text:
/**
 * Implementation of server component.
 * Init and start server instance.
 */
var logger = require('pomelo-logger').getLogger('pomelo', __filename);
var fs = require('fs');
var path = require('path');
var pathUtil = require('../util/pathUtil');
var Loader = require('pomelo-loader');
var utils = require('../util/utils');
var schedule = require('pomelo-scheduler');
var events = require('../util/events');
var Constants = require('../util/constants');
var FilterService = require('../common/service/filterService');
var HandlerService = require('../common/service/handlerService');

var ST_INITED = 0;    // server inited
var ST_STARTED = 1;   // server started
var ST_STOPED = 2;    // server stoped

/**
 * Server factory function.
 *
 * @param {Object} app  current application context
 * @return {Object} erver instance
 */
module.exports.create = function(app, opts) {
  return new Server(app, opts);
};

var Server = function (app, opts) {
  this.opts = opts || {};
  this.app = app;
  this.globalFilterService = null;
  this.filterService = null;
  this.handlerService = null;
  this.crons = [];
  this.jobs = {};
  this.state = ST_INITED;

  app.event.on(events.ADD_CRONS, this.addCrons.bind(this));
  app.event.on(events.REMOVE_CRONS, this.removeCrons.bind(this));
};

var pro = Server.prototype;

/**
 * Server lifecycle callback
 */
pro.start = function() {
  if(this.state > ST_INITED) {
    return;
  }

  this.globalFilterService = initFilter(true, this.app);
  this.filterService = initFilter(false, this.app);
  this.handlerService = initHandler(this.app, this.opts);
  this.cronHandlers = loadCronHandlers(this.app);
  loadCrons(this, this.app);
  this.state = ST_STARTED;
};

pro.afterStart = function() {
  scheduleCrons(this, this.crons);
};

/**
 * Stop server
 */
pro.stop = function() {
  this.state = ST_STOPED;
};

/**
 * Global handler.
 *
 * @param  {Object} msg request message
 * @param  {Object} session session object
 * @param  {Callback} callback function
 */
pro.globalHandle = function(msg, session, cb) {
  if(this.state !== ST_STARTED) {
    utils.invokeCallback(cb, new Error('server not started'));
    return;
  }

  var routeRecord = parseRoute(msg.route);
  if(!routeRecord) {
    utils.invokeCallback(cb, new Error('meet unknown route message %j', msg.route));
    return;
  }

  var self = this;
  var dispatch = function(err, resp, opts) {
    if(err) {
      handleError(true, self, err, msg, session, resp, opts, function(err, resp, opts) {
        response(true, self, err, msg, session, resp, opts, cb);
      });
      return;
    }

    if(self.app.getServerType() !== routeRecord.serverType) {
      doForward(self.app, msg, session, routeRecord, function(err, resp, opts) {
        response(true, self, err, msg, session, resp, opts, cb);
      });
    } else {
      doHandle(self, msg, session, routeRecord, function(err, resp, opts) {
        response(true, self, err, msg, session, resp, opts, cb);
      });
    }
  };
  beforeFilter(true, self, msg, session, dispatch);
};

/**
 * Handle request
 */
pro.handle = function(msg, session, cb) {
   if(this.state !== ST_STARTED) {
    cb(new Error('server not started'));
    return;
  }

  var routeRecord = parseRoute(msg.route);
  doHandle(this, msg, session, routeRecord, cb);
};

/**
 * Add crons at runtime.
 *
 * @param {Array} crons would be added in application
 */
pro.addCrons = function(crons) {
  this.cronHandlers = loadCronHandlers(this.app);
  for(var i=0, l=crons.length; i<l; i++) {
    var cron = crons[i];
    checkAndAdd(cron, this.crons, this);
  }
  scheduleCrons(this, crons);
};

/**
 * Remove crons at runtime.
 *
 * @param {Array} crons would be removed in application
 */
pro.removeCrons = function(crons) {
  for(var i=0, l=crons.length; i<l; i++) {
    var cron = crons[i];
    var id = parseInt(cron.id);
    if(!!this.jobs[id]) {
      schedule.cancelJob(this.jobs[id]);
    } else {
      logger.warn('cron is not in application: %j', cron);
    }
  }
};

var initFilter = function(isGlobal, app) {
  var service = new FilterService();
  var befores, afters;

  if(isGlobal) {
    befores = app.get(Constants.KEYWORDS.GLOBAL_BEFORE_FILTER);
    afters = app.get(Constants.KEYWORDS.GLOBAL_AFTER_FILTER);
  } else {
    befores = app.get(Constants.KEYWORDS.BEFORE_FILTER);
    afters = app.get(Constants.KEYWORDS.AFTER_FILTER);
  }

  var i, l;
  if(befores) {
    for(i=0, l=befores.length; i<l; i++) {
      service.before(befores[i]);
    }
  }

  if(afters) {
    for(i=0, l=afters.length; i<l; i++) {
      service.after(afters[i]);
    }
  }

  return service;
};

var initHandler = function(app, opts) {
  return new HandlerService(app, opts);
};

/**
 * Load cron handlers from current application
 */
var loadCronHandlers = function(app) {
  var p = pathUtil.getCronPath(app.getBase(), app.getServerType());
  if(p) {
    return Loader.load(p, app);
  }
};

/**
 * Load crons from configure file
 */
var loadCrons = function(server, app) {
  var env = app.get(Constants.RESERVED.ENV);
  var p = path.join(app.getBase(), Constants.FILEPATH.CRON);
  if(!fs.existsSync(p)) {
    p = path.join(app.getBase(), Constants.FILEPATH.CONFIG_DIR, env, path.basename(Constants.FILEPATH.CRON));
    if (!fs.existsSync(p)) {
      return;
    }
  }
  app.loadConfigBaseApp(Constants.RESERVED.CRONS, Constants.FILEPATH.CRON);
  var crons = app.get(Constants.RESERVED.CRONS);
  for(var serverType in crons) {
    if(app.serverType === serverType) {
      var list = crons[serverType];
      for(var i = 0; i<list.length; i++) {
        if(!list[i].serverId) {
          checkAndAdd(list[i], server.crons, server);
        } else {
          if(app.serverId === list[i].serverId) {
            checkAndAdd(list[i], server.crons, server);
          }
        }
      }
    }
  }
};

/**
 * Fire before filter chain if any
 */
var beforeFilter = function(isGlobal, server, msg, session, cb) {
  var fm;
  if(isGlobal) {
    fm = server.globalFilterService;
  } else {
    fm = server.filterService;
  }
  if(fm) {
    fm.beforeFilter(msg, session, cb);
  } else {
    utils.invokeCallback(cb);
  }
};

/**
 * Fire after filter chain if have
 */
var afterFilter = function(isGlobal, server, err, msg, session, resp, opts, cb) {
  var fm;
  if(isGlobal) {
    fm = server.globalFilterService;
  } else {
    fm = server.filterService;
  }
  if(fm) {
    if(isGlobal) {
      fm.afterFilter(err, msg, session, resp, function() {
        // do nothing
      });
    } else {
      fm.afterFilter(err, msg, session, resp, function(err) {
        cb(err, resp, opts);
      });
    }
  }
};

/**
 * pass err to the global error handler if specified
 */
var handleError = function(isGlobal, server, err, msg, session, resp, opts, cb) {
  var handler;
  if(isGlobal) {
    handler = server.app.get(Constants.RESERVED.GLOBAL_ERROR_HANDLER);
  } else {
    handler = server.app.get(Constants.RESERVED.ERROR_HANDLER);
  }
  if(!handler) {
    logger.debug('no default error handler to resolve unknown exception. ' + err.stack);
    utils.invokeCallback(cb, err, resp, opts);
  } else {
    if(handler.length === 5) {
      handler(err, msg, resp, session, cb);
    } else {
       handler(err, msg, resp, session, opts, cb);
    }
  }
};

/**
 * Send response to client and fire after filter chain if any.
 */

var response = function(isGlobal, server, err, msg, session, resp, opts, cb) {
  if(isGlobal) {
    cb(err, resp, opts);
    // after filter should not interfere response
    afterFilter(isGlobal, server, err, msg, session, resp, opts, cb);
  } else {
    afterFilter(isGlobal, server, err, msg, session, resp, opts, cb);
  }
};

/**
 * Parse route string.
 *
 * @param  {String} route route string, such as: serverName.handlerName.methodName
 * @return {Object}       parse result object or null for illeagle route string
 */
var parseRoute = function(route) {
  if(!route) {
    return null;
  }
  var ts = route.split('.');
  if(ts.length !== 3) {
    return null;
  }

  return {
    route: route,
    serverType: ts[0],
    handler: ts[1],
    method: ts[2]
  };
};

var doForward = function(app, msg, session, routeRecord, cb) {
  var finished = false;
  //should route to other servers
  try {
    app.sysrpc[routeRecord.serverType].msgRemote.forwardMessage(
    // app.sysrpc[routeRecord.serverType].msgRemote.forwardMessage2(
      session,
      msg,
      // msg.oldRoute || msg.route,
      // msg.body,
      // msg.aesPassword,
      // msg.compressGzip,
      session.export(),
      function(err, resp, opts) {
        if(err) {
          logger.error('fail to process remote message:' + err.stack);
        }
        finished = true;
        utils.invokeCallback(cb, err, resp, opts);
      }
    );
  } catch(err) {
    if(!finished) {
      logger.error('fail to forward message:' + err.stack);
      utils.invokeCallback(cb, err);
    }
  }
};

var doHandle = function(server, msg, session, routeRecord, cb) {
  var originMsg = msg;
  msg = msg.body || {};
  msg.__route__ = originMsg.route;

  var self = server;

  var handle = function(err, resp, opts) {
    if(err) {
      // error from before filter
      handleError(false, self, err, msg, session, resp, opts, function(err, resp, opts) {
        response(false, self, err, msg, session, resp, opts, cb);
      });
      return;
    }

    self.handlerService.handle(routeRecord, msg, session, function(err, resp, opts) {
      if(err) {
        //error from handler
        handleError(false, self, err, msg, session, resp, opts, function(err, resp, opts) {
          response(false, self, err, msg, session, resp, opts, cb);
        });
        return;
      }

      response(false, self, err, msg, session, resp, opts, cb);
    });
  };  //end of handle

  beforeFilter(false, server, msg, session, handle);
};

/**
 * Schedule crons
 */
var scheduleCrons = function(server, crons) {
  var handlers = server.cronHandlers;
  for(var i = 0; i<crons.length; i++) {
    var cronInfo = crons[i];
    var time = cronInfo.time;
    var action = cronInfo.action;
    var jobId = cronInfo.id;

    if(!time || !action || !jobId) {
      logger.error('cron miss necessary parameters: %j', cronInfo);
      continue;
    }

    if(action.indexOf('.') < 0) {
      logger.error('cron action is error format: %j', cronInfo);
      continue;
    }

    var cron = action.split('.')[0];
    var job = action.split('.')[1];
    var handler = handlers[cron];

    if(!handler) {
      logger.error('could not find cron: %j', cronInfo);
      continue;
    }

    if(typeof handler[job] !== 'function') {
      logger.error('could not find cron job: %j, %s', cronInfo, job);
      continue;
    }

    var id = schedule.scheduleJob(time, handler[job].bind(handler));
    server.jobs[jobId] = id;
  }
};

/**
 * If cron is not in crons then put it in the array.
 */
var checkAndAdd = function(cron, crons, server) {
  if(!containCron(cron.id, crons)) {
    server.crons.push(cron);
  } else {
    logger.warn('cron is duplicated: %j', cron);
  }
};

/**
 * Check if cron is in crons.
 */
var containCron = function(id, crons) {
  for(var i=0, l=crons.length; i<l; i++) {
    if(id === crons[i].id) {
      return true;
    }
  }
  return false;
};


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package scalaExec.gui;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.JEditorPane;
import javax.swing.JOptionPane;

import scalaExec.Interpreter.GlobalValues;
import scalaExec.scalaLab.StreamGobbler;

public class CompileExecutePaneActionJava extends AbstractAction {
    int rv = 0;  // the return value of the compilation phase

    static boolean processUserSelection = false;
    String tempFileName = "";

    File tempFile = null;

    public CompileExecutePaneActionJava() {
        super("Compile and Execute Java text in editor");
        setEnabled(true);
    }

    public void executeTextExternalJava() {
        int rv = 0;  // the return value of the compilation phase

        String className = "";
        // execute now the compiled code
        String programText = GlobalValues.editorPane.getText();  // get the program's text in order to search for the class's name
        int clPos = programText.indexOf("class");
        if (clPos != -1) { // "class" exists
            int afterClassPos = clPos + 6;
            // after the word "object an identifier and a "{" must exist
            programText = programText.substring(afterClassPos);
            StringTokenizer stTok = new StringTokenizer(programText, " ");
            className = stTok.nextToken();
            tempFileName = className + ".java";   // public classes and Java files should have the same name
        } else
            return;

        String jarFileName = GlobalValues.jarFilePath;
        // get the user's home path
        String homePath = GlobalValues.fullJarFilePath;
        char JavaPathChar = '/';
        homePath = homePath.substring(0, homePath.lastIndexOf(JavaPathChar));
        try {
            // take the program's text and save it to a temporary file
            tempFile = new File(homePath + File.separatorChar + tempFileName);
            FileWriter fw = new FileWriter(tempFile);
            GlobalValues.editorPane.write(fw);
        } catch (IOException ioe) {
            System.out.println("Exception trying to write to " + tempFileName);
            return;
        }
        // compile the temporary file

        String selectedValue = tempFileName;
        String[] command = new String[6];
        command[0] = "javac";
        command[1] = "-cp";
        command[2] = GlobalValues.jarFilePath + File.pathSeparator +
                scalalab.JavaGlobals.ejmlFile + File.pathSeparator +
                scalalab.JavaGlobals.jsciFile + File.pathSeparator +
                scalalab.JavaGlobals.javacppFile + File.pathSeparator +
                scalalab.JavaGlobals.gslFile + File.pathSeparator +
                scalalab.JavaGlobals.mtjColtSGTFile + File.pathSeparator +
                scalalab.JavaGlobals.ApacheCommonsFile + File.pathSeparator +
                scalalab.JavaGlobals.jfreechartFile + File.pathSeparator +
                scalalab.JavaGlobals.numalFile + File.pathSeparator
                + scalalab.JavaGlobals.LAPACKFile + File.pathSeparator
                + scalalab.JavaGlobals.ARPACKFile + File.pathSeparator
                + scalalab.JavaGlobals.JASFile + homePath;
        command[3] = "-d";   // where to place output class files
        command[4] = homePath;   //  the path to save the compiled class files
        try {
            command[5] = tempFile.getCanonicalPath();  // full filename to compile
        } catch (IOException ex) {
            System.out.println("Exception in tempFile.getCanonicalPath()");
            return;
        }

        String compileCommandString = command[0] + "  " + command[1] + "  " + command[2] + " " + command[3] + " " + command[4] + " " + command[5];

        System.out.println("compileCommand Java= " + compileCommandString);

        try {
            Runtime rt = Runtime.getRuntime();
            Process javaProcess = rt.exec(command);
            // an error message?
            StreamGobbler errorGobbler = new StreamGobbler(javaProcess.getErrorStream(), "ERROR");

            // any output?
            StreamGobbler outputGobbler = new StreamGobbler(javaProcess.getInputStream(), "OUTPUT");

            // kick them off
            errorGobbler.start();
            outputGobbler.start();

            // any error???
            javaProcess.waitFor();
            rv = javaProcess.exitValue();
            String commandString = command[0] + "  " + command[1] + "  " + command[2];
            if (rv == 0)
                System.out.println("Process:  " + commandString + "  exited successfully ");
            else
                System.out.println("Process:  " + commandString + "  exited with error, error value = " + rv);

        } catch (IOException exio) {
            System.out.println("IOException trying to executing " + command);
            exio.printStackTrace();

        } catch (InterruptedException ie) {
            System.out.println("Interrupted Exception  trying to executing " + command);
            ie.printStackTrace();
        }

        tempFile.delete(); // delete the temporary source file

        if (processUserSelection == false) {

            if (rv == 0) {  // compilation success: proceed to run
                command = new String[4];   // the run command
                command[0] = "java";
                command[1] = "-cp";
                command[2] = "." + File.pathSeparator + GlobalValues.jarFilePath + File.pathSeparator +
                        scalalab.JavaGlobals.ejmlFile + File.pathSeparator +
                        scalalab.JavaGlobals.jsciFile + File.pathSeparator +
                        scalalab.JavaGlobals.javacppFile + File.pathSeparator +
                        scalalab.JavaGlobals.gslFile + File.pathSeparator +
                        scalalab.JavaGlobals.mtjColtSGTFile + File.pathSeparator +
                        scalalab.JavaGlobals.ApacheCommonsFile + File.pathSeparator +
                        scalalab.JavaGlobals.jfreechartFile + File.pathSeparator +
                        scalalab.JavaGlobals.numalFile + File.pathSeparator +
                        scalalab.JavaGlobals.LAPACKFile + File.pathSeparator +
                        scalalab.JavaGlobals.ARPACKFile + File.pathSeparator +
                        scalalab.JavaGlobals.JASFile + File.pathSeparator + homePath;
                command[3] = className;    // the name of the Scala compiler class

                try {
                    Runtime rt = Runtime.getRuntime();
                    Process javaProcess = rt.exec(command);
                    // an error message?
                    StreamGobbler errorGobbler = new StreamGobbler(javaProcess.getErrorStream(), "ERROR");

                    // any output?
                    StreamGobbler outputGobbler = new StreamGobbler(javaProcess.getInputStream(), "OUTPUT");

                    // kick them off
                    errorGobbler.start();
                    outputGobbler.start();

                    // any error???
                    javaProcess.waitFor();
                    rv = javaProcess.exitValue();
                    String commandString = command[0] + "  " + command[1] + "  " + command[2] + " " + command[3];
                    if (rv == 0)
                        System.out.println("Process:  " + commandString + "  exited successfully ");
                    else
                        System.out.println("Process:  " + commandString + "  exited with error, error value = " + rv);

                } catch (IOException ex) {
                    System.out.println("IOException trying to executing " + command);
                    ex.printStackTrace();

                } catch (InterruptedException ie) {
                    System.out.println("Interrupted Exception  trying to executing " + command);
                    ie.printStackTrace();
                }
            }
        }

    }

    public void executeTextJava() {
        String className = "";
        // execute now the compiled code
        String programText = GlobalValues.editorPane.getSelectedText();
        String programOutput;
        if (programText != null) { // selected text
            // put selected code in comments
            GlobalValues.editorPane.replaceSelection("/* \n " + programText + " \n */");
            className = JOptionPane.showInputDialog("Select a name for the Java class", "userClassesStaticJava");
            programOutput = " class " + className + "  \n { \n " +
                    "\n static " + programText + "\n}";
            tempFileName = className + ".java";   // public classes and Java files should have the same name
//           System.out.println("program text = "+programOutput);

            processUserSelection = true;
            programText = programOutput;
        } else { // use the whole program text

            programText = GlobalValues.editorPane.getText();  // get the program's text in order to search for the class's name
            processUserSelection = false;
        }
        processCode(programText);
    }

    public void executeTextJava(JEditorPane editorPane) {
        String programText = editorPane.getText();  // get the program's text in order to search for the class's name
        processCode(programText);
    }
        /*public void executeTextJava() {
               String programText = GlobalValues.editorPane.getText();  // get the program's text in order to search for the class's name
               processCode(programText);
        }*/

    public void executeTextJavaEmbedded(JEditorPane editorPane) {
        String programText = editorPane.getText();  // get the program's text in order to search for the class's name
        processCodeEmbedded(programText);
    }

    public void executeTextJavaEmbedded() {
        String programText = GlobalValues.editorPane.getText();  // get the program's text in order to search for the class's name
        processCodeEmbedded(programText);
    }

    public void processCode(String programText) {
        String canonicalClassName = "";
        String pathOfCanonicalClassName = "";

        String className = "";
        // execute now the compiled code
        int clPos = programText.indexOf("class");
        if (clPos != -1) { // "class" exists
            int afterClassPos = clPos + 6;
            // after the word "class an identifier and a "{" must exist
            String afterProgramText = programText.substring(afterClassPos, afterClassPos + 50);
            StringTokenizer stTok = new StringTokenizer(afterProgramText, " {\n");
            className = stTok.nextToken();
            tempFileName = className + ".java";   // public classes and Java files should have the same name
        } else
            return;

        String jarFileName = GlobalValues.jarFilePath;

        String homePath = ".";
        String wholePathName = tempFileName; // homePath+File.separatorChar+tempFileName;
        try {
            // take the program's text and save it to a temporary file
            tempFile = new File(wholePathName);
            FileWriter fw = new FileWriter(tempFile);
            GlobalValues.editorPane.write(fw);
        } catch (IOException ioe) {
            System.out.println("Exception trying to write to " + wholePathName);
            System.out.println("Probably you tried to execute scalalab with direct double-click on the .jar file");
            System.out.println("Correct this problem by making a shortcut to the desktop");
            System.out.println("or with the command:   java -jar scalalab.jar ");
            JOptionPane.showMessageDialog(null, "Please Start scalalab from a terminal with: java -jar scalalab.jar,  for the external compilation to work properly", "Start from terminal", JOptionPane.WARNING_MESSAGE);
            return;
        }
        String selectedValue = tempFileName;
        System.out.println("selectedValue = " + tempFileName);
        String[] command = new String[11];
        String toolboxes = "";
        for (int k = 0; k < GlobalValues.ScalaSciClassPathComponents.size(); k++)
            if (toolboxes != "")
                toolboxes = toolboxes + File.pathSeparator + GlobalValues.ScalaSciClassPathComponents.elementAt(k);
            else
                toolboxes = GlobalValues.ScalaSciClassPathComponents.elementAt(k);
        System.out.println("current ScalaSciPath = " + toolboxes);   // Sterg-Sterg-Sterg

        command[0] = "java";
        command[1] = "-classpath";
        command[2] = "." + File.pathSeparator +
                GlobalValues.jarFilePath + File.pathSeparator
                + GlobalValues.scalalabLibPath + File.pathSeparator
                + scalalab.JavaGlobals.javacFile + File.pathSeparator
                + scalalab.JavaGlobals.ejmlFile + File.pathSeparator
                + scalalab.JavaGlobals.jsciFile + File.pathSeparator
                + scalalab.JavaGlobals.javacppFile + File.pathSeparator
                + scalalab.JavaGlobals.gslFile + File.pathSeparator
                + scalalab.JavaGlobals.mtjColtSGTFile + File.pathSeparator
                + scalalab.JavaGlobals.ApacheCommonsFile + File.pathSeparator
                + scalalab.JavaGlobals.jfreechartFile + File.pathSeparator
                + scalalab.JavaGlobals.numalFile + File.pathSeparator
                + scalalab.JavaGlobals.LAPACKFile + File.pathSeparator
                + scalalab.JavaGlobals.ARPACKFile + File.pathSeparator
                + scalalab.JavaGlobals.JASFile
                + File.pathSeparator + toolboxes;

        command[3] = "com.sun.tools.javac.Main";    // the name of the Java  compiler class
        command[4] = "-classpath";
        command[5] = command[2];
        command[6] = "-sourcepath";
        command[7] = command[2];
        try {
            command[10] = tempFile.getCanonicalPath();
            canonicalClassName = command[10];
            pathOfCanonicalClassName = canonicalClassName.substring(0, canonicalClassName.lastIndexOf(File.separatorChar));

        } catch (IOException ex) {
            Logger.getLogger(CompileExecutePaneActionJava.class.getName()).log(Level.SEVERE, null, ex);
        }
        command[8] = "-d";
        command[9] = pathOfCanonicalClassName;

        String compileCommandString = command[0] + "  " + command[1] + "  " + command[2] + " " + command[3] + " " + command[4] + " " + command[5] + " " + command[6] + " " + command[7] + " " + command[8] + " " + command[9] + " " + command[10];

        System.out.println("compileCommand Java= " + compileCommandString);

        try {
            Runtime rt = Runtime.getRuntime();
            Process javaProcess = rt.exec(command);
            // an error message?
            StreamGobbler errorGobbler = new StreamGobbler(javaProcess.getErrorStream(), "ERROR");

            // any output?
            StreamGobbler outputGobbler = new StreamGobbler(javaProcess.getInputStream(), "OUTPUT");

            // kick them off
            errorGobbler.start();
            outputGobbler.start();

            // any error???
            javaProcess.waitFor();
            int rv = javaProcess.exitValue();
            String commandString = command[0] + "  " + command[1] + "  " + command[2];
            if (rv == 0)
                System.out.println("Process:  " + commandString + "  exited successfully ");
            else
                System.out.println("Process:  " + commandString + "  exited with error, error value = " + rv);

        } catch (IOException exio) {
            System.out.println("IOException trying to executing " + command);
            exio.printStackTrace();

        } catch (InterruptedException ie) {
            System.out.println("Interrupted Exception  trying to executing " + command);
            ie.printStackTrace();
        }

        tempFile.delete(); // delete the temporary source file

        if (processUserSelection == false) {
            if (rv == 0) {  // compilation success: proceed to run
                command = new String[4];   // the run command
                command[0] = "java";
                command[1] = "-cp";
                command[2] = "." + File.pathSeparator + pathOfCanonicalClassName + File.pathSeparator +
                        GlobalValues.jarFilePath + File.pathSeparator +
                        scalalab.JavaGlobals.jfreechartFile + File.pathSeparator +
                        scalalab.JavaGlobals.jsciFile + File.pathSeparator +
                        scalalab.JavaGlobals.javacppFile + File.pathSeparator +
                        scalalab.JavaGlobals.gslFile + File.pathSeparator +
                        scalalab.JavaGlobals.numalFile + File.pathSeparator +
                        scalalab.JavaGlobals.mtjColtSGTFile + File.pathSeparator +
                        scalalab.JavaGlobals.ApacheCommonsFile + File.pathSeparator +
                        scalalab.JavaGlobals.ejmlFile + File.pathSeparator +
                        scalalab.JavaGlobals.LAPACKFile + File.pathSeparator +
                        scalalab.JavaGlobals.ARPACKFile + File.pathSeparator +
                        scalalab.JavaGlobals.JASFile +
                        File.pathSeparator + homePath + File.separator + toolboxes;
                command[3] = className;    // the name of the Scala compiler class

                try {
                    Runtime rt = Runtime.getRuntime();
                    Process javaProcess = rt.exec(command);
                    // an error message?
                    StreamGobbler errorGobbler = new StreamGobbler(javaProcess.getErrorStream(), "ERROR");

                    // any output?
                    StreamGobbler outputGobbler = new StreamGobbler(javaProcess.getInputStream(), "OUTPUT");

                    // kick them off
                    errorGobbler.start();
                    outputGobbler.start();

                    // any error???
                    javaProcess.waitFor();
                    rv = javaProcess.exitValue();
                    String commandString = command[0] + "  " + command[1] + "  " + command[2] + " " + command[3];
                    if (rv == 0)
                        System.out.println("Process:  " + commandString + "  exited successfully ");
                    else
                        System.out.println("Process:  " + commandString + "  exited with error, error value = " + rv);

                } catch (IOException ex) {
                    System.out.println("IOException trying to executing " + command);
                    ex.printStackTrace();

                } catch (InterruptedException ie) {
                    System.out.println("Interrupted Exception  trying to executing " + command);
                    ie.printStackTrace();
                }
            } // rv==0
        }
    }

    public void processCodeEmbedded(String programText) {
        String canonicalClassName = "";
        String pathOfCanonicalClassName = "";

        String className = "";
        // execute now the compiled code
        int clPos = programText.indexOf("class");
        if (clPos != -1) { // "class" exists
            int afterClassPos = clPos + 6;
            // after the word "class an identifier and a "{" must exist
            String afterProgramText = programText.substring(afterClassPos, afterClassPos + 50);
            StringTokenizer stTok = new StringTokenizer(afterProgramText, " {\n");
            className = stTok.nextToken();
            tempFileName = className + ".java";   // public classes and Java files should have the same name
        } else
            return;

        String homePath = ".";
        String wholePathName = tempFileName; // homePath+File.separatorChar+tempFileName;
        try {
            // take the program's text and save it to a temporary file
            tempFile = new File(wholePathName);
            FileWriter fw = new FileWriter(tempFile);
            GlobalValues.editorPane.write(fw);
        } catch (IOException ioe) {
            System.out.println("Exception trying to write to " + wholePathName);
            System.out.println("Probably you tried to execute scalalab with direct double-click on the .jar file");
            System.out.println("Correct this problem by making a shortcut to the desktop");
            System.out.println("or with the command:   java -jar scalalab.jar ");
            JOptionPane.showMessageDialog(null, "Please Start scalalab from a terminal with: java -jar scalalab.jar,  for the external compilation to work properly", "Start from terminal", JOptionPane.WARNING_MESSAGE);
            return;
        }
        String selectedValue = tempFileName;
        System.out.println("selectedValue = " + tempFileName);
        String[] command = new String[11];
        String toolboxes = "";
        for (int k = 0; k < GlobalValues.ScalaSciClassPathComponents.size(); k++)
            toolboxes = toolboxes + File.pathSeparator + GlobalValues.ScalaSciClassPathComponents.elementAt(k);
        System.out.println("current ScalaSciPath = " + toolboxes);   // Sterg-Sterg-Sterg

        command[0] = "java";
        command[1] = "-classpath";
        command[2] = "." + File.pathSeparator
                + scalalab.JavaGlobals.javacFile + File.pathSeparator
                + scalalab.JavaGlobals.ejmlFile + File.pathSeparator
                + scalalab.JavaGlobals.jsciFile + File.pathSeparator
                + scalalab.JavaGlobals.javacppFile + File.pathSeparator
                + scalalab.JavaGlobals.gslFile + File.pathSeparator
                + scalalab.JavaGlobals.mtjColtSGTFile + File.pathSeparator
                + scalalab.JavaGlobals.ApacheCommonsFile + File.pathSeparator
                + scalalab.JavaGlobals.numalFile + File.pathSeparator
                + scalalab.JavaGlobals.LAPACKFile + File.pathSeparator
                + scalalab.JavaGlobals.ARPACKFile + File.pathSeparator;
        command[3] = "com.sun.tools.javac.Main";    // the name of the Java  compiler class
        command[4] = "-classpath";
        command[5] = command[2];
        command[6] = "-sourcepath";
        command[7] = command[2];
        try {
            command[10] = tempFile.getCanonicalPath();
            canonicalClassName = command[10];
            pathOfCanonicalClassName = canonicalClassName.substring(0, canonicalClassName.lastIndexOf(File.separatorChar));

        } catch (IOException ex) {
            Logger.getLogger(CompileExecutePaneActionJava.class.getName()).log(Level.SEVERE, null, ex);
        }
        command[8] = "-d";
        command[9] = pathOfCanonicalClassName;

        String compileCommandString = command[0] + "  " + command[1] + "  " + command[2] + " " + command[3] + " " + command[4] + " " + command[5] + " " + command[6] + " " + command[7] + " " + command[8] + " " + command[9] + " " + command[10];

        System.out.println("compileCommand JavaEmbedded = " + compileCommandString);

        try {
            Runtime rt = Runtime.getRuntime();
            Process javaProcess = rt.exec(command);
            // an error message?
            StreamGobbler errorGobbler = new StreamGobbler(javaProcess.getErrorStream(), "ERROR");

            // any output?
            StreamGobbler outputGobbler = new StreamGobbler(javaProcess.getInputStream(), "OUTPUT");

            // kick them off
            errorGobbler.start();
            outputGobbler.start();

            // any error???
            javaProcess.waitFor();
            int rv = javaProcess.exitValue();
            String commandString = command[0] + "  " + command[1] + "  " + command[2];
            if (rv == 0)
                System.out.println("Process:  " + commandString + "  exited successfully ");
            else
                System.out.println("Process:  " + commandString + "  exited with error, error value = " + rv);

        } catch (IOException exio) {
            System.out.println("IOException trying to executing " + command);
            exio.printStackTrace();

        } catch (InterruptedException ie) {
            System.out.println("Interrupted Exception  trying to executing " + command);
            ie.printStackTrace();
        }

        tempFile.delete(); // delete the temporary source file

        if (processUserSelection == false) {

            if (rv == 0) {  // compilation success: proceed to run
                command = new String[4];   // the run command
                command[0] = "java";
                command[1] = "-cp";
                command[2] = "." + File.pathSeparator + pathOfCanonicalClassName + File.pathSeparator
                        + scalalab.JavaGlobals.ejmlFile + File.pathSeparator
                        + scalalab.JavaGlobals.jsciFile + File.pathSeparator
                        + scalalab.JavaGlobals.javacppFile + File.pathSeparator
                        + scalalab.JavaGlobals.gslFile + File.pathSeparator
                        + scalalab.JavaGlobals.mtjColtSGTFile + File.pathSeparator
                        + scalalab.JavaGlobals.ApacheCommonsFile + File.pathSeparator
                        + scalalab.JavaGlobals.numalFile + File.pathSeparator
                        + scalalab.JavaGlobals.LAPACKFile + File.pathSeparator
                        + scalalab.JavaGlobals.ARPACKFile + File.pathSeparator;
                command[3] = className;    // the name of the Scala compiler class

                try {
                    Runtime rt = Runtime.getRuntime();
                    Process javaProcess = rt.exec(command);
                    // an error message?
                    StreamGobbler errorGobbler = new StreamGobbler(javaProcess.getErrorStream(), "ERROR");

                    // any output?
                    StreamGobbler outputGobbler = new StreamGobbler(javaProcess.getInputStream(), "OUTPUT");

                    // kick them off
                    errorGobbler.start();
                    outputGobbler.start();

                    // any error???
                    javaProcess.waitFor();
                    rv = javaProcess.exitValue();
                    String commandString = command[0] + "  " + command[1] + "  " + command[2] + " " + command[3];
                    if (rv == 0)
                        System.out.println("Process:  " + commandString + "  exited successfully ");
                    else
                        System.out.println("Process:  " + commandString + "  exited with error, error value = " + rv);

                } catch (IOException ex) {
                    System.out.println("IOException trying to executing " + command);
                    ex.printStackTrace();

                } catch (InterruptedException ie) {
                    System.out.println("Interrupted Exception  trying to executing " + command);
                    ie.printStackTrace();
                }
            } // rv==0
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        executeTextJava();
    }

}

redpajama_set_name: RedPajamaGithub


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 2.0.1
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

public enum aiPrimitiveType {
  aiPrimitiveType_POINT = 0x1,
  aiPrimitiveType_LINE = 0x2,
  aiPrimitiveType_TRIANGLE = 0x4,
  aiPrimitiveType_POLYGON = 0x8
}


text:
#include "Python.h"

#include <stdio.h>
#include <locale.h>
#include <string.h>
#include <ctype.h>

#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif

#ifdef HAVE_LANGINFO_H
#include <langinfo.h>
#endif

#ifdef HAVE_LIBINTL_H
#include <libintl.h>
#endif

#ifdef HAVE_WCHAR_H
#include <wchar.h>
#endif

#if defined(__APPLE__)
#include <CoreFoundation/CoreFoundation.h>
#endif

#if defined(MS_WINDOWS)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif

#ifdef RISCOS
char *strdup(const char *);
#endif

PyDoc_STRVAR(locale__doc__, "Support for POSIX locales.");

static PyObject *Error;

/* support functions for formatting floating point numbers */

PyDoc_STRVAR(setlocale__doc__,
"(integer,string=None) -> string. Activates/queries locale processing.");

/* the grouping is terminated by either 0 or CHAR_MAX */
static PyObject*
copy_grouping(char* s)
{
    int i;
    PyObject *result, *val = NULL;

    if (s[0] == '\0')
        /* empty string: no grouping at all */
        return PyList_New(0);

    for (i = 0; s[i] != '\0' && s[i] != CHAR_MAX; i++)
        ; /* nothing */

    result = PyList_New(i+1);
    if (!result)
        return NULL;

    i = -1;
    do {
        i++;
        val = PyInt_FromLong(s[i]);
        if (!val)
            break;
        if (PyList_SetItem(result, i, val)) {
            Py_DECREF(val);
            val = NULL;
            break;
        }
    } while (s[i] != '\0' && s[i] != CHAR_MAX);

    if (!val) {
        Py_DECREF(result);
        return NULL;
    }

    return result;
}

static void
fixup_ulcase(void)
{
    PyObject *mods, *strop, *string, *ulo;
    unsigned char ul[256];
    int n, c;

    /* find the string and strop modules */
    mods = PyImport_GetModuleDict();
    if (!mods)
        return;
    string = PyDict_GetItemString(mods, "string");
    if (string)
        string = PyModule_GetDict(string);
    strop=PyDict_GetItemString(mods, "strop");
    if (strop)
        strop = PyModule_GetDict(strop);
    if (!string && !strop)
        return;

    /* create uppercase map string */
    n = 0;
    for (c = 0; c < 256; c++) {
        if (isupper(c))
            ul[n++] = c;
    }
    ulo = PyString_FromStringAndSize((const char *)ul, n);
    if (!ulo)
        return;
    if (string)
        PyDict_SetItemString(string, "uppercase", ulo);
    if (strop)
        PyDict_SetItemString(strop, "uppercase", ulo);
    Py_DECREF(ulo);

    /* create lowercase string */
    n = 0;
    for (c = 0; c < 256; c++) {
        if (islower(c))
            ul[n++] = c;
    }
    ulo = PyString_FromStringAndSize((const char *)ul, n);
    if (!ulo)
        return;
    if (string)
        PyDict_SetItemString(string, "lowercase", ulo);
    if (strop)
        PyDict_SetItemString(strop, "lowercase", ulo);
    Py_DECREF(ulo);

    /* create letters string */
    n = 0;
    for (c = 0; c < 256; c++) {
        if (isalpha(c))
            ul[n++] = c;
    }
    ulo = PyString_FromStringAndSize((const char *)ul, n);
    if (!ulo)
        return;
    if (string)
        PyDict_SetItemString(string, "letters", ulo);
    Py_DECREF(ulo);
}

static PyObject*
PyLocale_setlocale(PyObject* self, PyObject* args)
{
    int category;
    char *locale = NULL, *result;
    PyObject *result_object;

    if (!PyArg_ParseTuple(args, "i|z:setlocale", &category, &locale))
        return NULL;

    if (locale) {
        /* set locale */
        result = setlocale(category, locale);
        if (!result) {
            /* operation failed, no setting was changed */
            PyErr_SetString(Error, "unsupported locale setting");
            return NULL;
        }
        result_object = PyString_FromString(result);
        if (!result_object)
            return NULL;
        /* record changes to LC_CTYPE */
        if (category == LC_CTYPE || category == LC_ALL)
            fixup_ulcase();
        /* things that got wrong up to here are ignored */
        PyErr_Clear();
    } else {
        /* get locale */
        result = setlocale(category, NULL);
        if (!result) {
            PyErr_SetString(Error, "locale query failed");
            return NULL;
        }
        result_object = PyString_FromString(result);
    }
    return result_object;
}

PyDoc_STRVAR(localeconv__doc__,
"() -> dict. Returns numeric and monetary locale-specific parameters.");

static PyObject*
PyLocale_localeconv(PyObject* self)
{
    PyObject* result;
    struct lconv *l;
    PyObject *x;

    result = PyDict_New();
    if (!result)
        return NULL;

    /* if LC_NUMERIC is different in the C library, use saved value */
    l = localeconv();

    /* hopefully, the localeconv result survives the C library calls
       involved herein */

#define RESULT_STRING(s)\
    x = PyString_FromString(l->s);\
    if (!x) goto failed;\
    PyDict_SetItemString(result, #s, x);\
    Py_XDECREF(x)

#define RESULT_INT(i)\
    x = PyInt_FromLong(l->i);\
    if (!x) goto failed;\
    PyDict_SetItemString(result, #i, x);\
    Py_XDECREF(x)

    /* Numeric information */
    RESULT_STRING(decimal_point);
    RESULT_STRING(thousands_sep);
    x = copy_grouping(l->grouping);
    if (!x)
        goto failed;
    PyDict_SetItemString(result, "grouping", x);
    Py_XDECREF(x);

    /* Monetary information */
    RESULT_STRING(int_curr_symbol);
    RESULT_STRING(currency_symbol);
    RESULT_STRING(mon_decimal_point);
    RESULT_STRING(mon_thousands_sep);
    x = copy_grouping(l->mon_grouping);
    if (!x)
        goto failed;
    PyDict_SetItemString(result, "mon_grouping", x);
    Py_XDECREF(x);
    RESULT_STRING(positive_sign);
    RESULT_STRING(negative_sign);
    RESULT_INT(int_frac_digits);
    RESULT_INT(frac_digits);
    RESULT_INT(p_cs_precedes);
    RESULT_INT(p_sep_by_space);
    RESULT_INT(n_cs_precedes);
    RESULT_INT(n_sep_by_space);
    RESULT_INT(p_sign_posn);
    RESULT_INT(n_sign_posn);
    return result;

  failed:
    Py_XDECREF(result);
    Py_XDECREF(x);
    return NULL;
}

PyDoc_STRVAR(strcoll__doc__,
"string,string -> int. Compares two strings according to the locale.");

static PyObject*
PyLocale_strcoll(PyObject* self, PyObject* args)
{
#if !defined(HAVE_WCSCOLL) || !defined(Py_USING_UNICODE)
    char *s1,*s2;

    if (!PyArg_ParseTuple(args, "ss:strcoll", &s1, &s2))
        return NULL;
    return PyInt_FromLong(strcoll(s1, s2));
#else
    PyObject *os1, *os2, *result = NULL;
    wchar_t *ws1 = NULL, *ws2 = NULL;
    int rel1 = 0, rel2 = 0, len1, len2;

    if (!PyArg_UnpackTuple(args, "strcoll", 2, 2, &os1, &os2))
        return NULL;
    /* If both arguments are byte strings, use strcoll.  */
    if (PyString_Check(os1) && PyString_Check(os2))
        return PyInt_FromLong(strcoll(PyString_AS_STRING(os1),
                                      PyString_AS_STRING(os2)));
    /* If neither argument is unicode, it's an error.  */
    if (!PyUnicode_Check(os1) && !PyUnicode_Check(os2)) {
        PyErr_SetString(PyExc_ValueError, "strcoll arguments must be strings");
    }
    /* Convert the non-unicode argument to unicode. */
    if (!PyUnicode_Check(os1)) {
        os1 = PyUnicode_FromObject(os1);
        if (!os1)
            return NULL;
        rel1 = 1;
    }
    if (!PyUnicode_Check(os2)) {
        os2 = PyUnicode_FromObject(os2);
        if (!os2) {
            Py_DECREF(os1);
            return NULL;
        }
        rel2 = 1;
    }
    /* Convert the unicode strings to wchar[]. */
    len1 = PyUnicode_GET_SIZE(os1) + 1;
    ws1 = PyMem_MALLOC(len1 * sizeof(wchar_t));
    if (!ws1) {
        PyErr_NoMemory();
        goto done;
    }
    if (PyUnicode_AsWideChar((PyUnicodeObject*)os1, ws1, len1) == -1)
        goto done;
    ws1[len1 - 1] = 0;
    len2 = PyUnicode_GET_SIZE(os2) + 1;
    ws2 = PyMem_MALLOC(len2 * sizeof(wchar_t));
    if (!ws2) {
        PyErr_NoMemory();
        goto done;
    }
    if (PyUnicode_AsWideChar((PyUnicodeObject*)os2, ws2, len2) == -1)
        goto done;
    ws2[len2 - 1] = 0;
    /* Collate the strings. */
    result = PyInt_FromLong(wcscoll(ws1, ws2));
  done:
    /* Deallocate everything. */
    if (ws1) PyMem_FREE(ws1);
    if (ws2) PyMem_FREE(ws2);
    if (rel1) {
        Py_DECREF(os1);
    }
    if (rel2) {
        Py_DECREF(os2);
    }
    return result;
#endif
}

PyDoc_STRVAR(strxfrm__doc__,
"string -> string. Returns a string that behaves for cmp locale-aware.");

static PyObject*
PyLocale_strxfrm(PyObject* self, PyObject* args)
{
    char *s, *buf;
    size_t n1, n2;
    PyObject *result;

    if (!PyArg_ParseTuple(args, "s:strxfrm", &s))
        return NULL;

    /* assume no change in size, first */
    n1 = strlen(s) + 1;
    buf = PyMem_Malloc(n1);
    if (!buf)
        return PyErr_NoMemory();
    n2 = strxfrm(buf, s, n1) + 1;
    if (n2 > n1) {
        /* more space needed */
        buf = PyMem_Realloc(buf, n2);
        if (!buf)
            return PyErr_NoMemory();
        strxfrm(buf, s, n2);
    }
    result = PyString_FromString(buf);
    PyMem_Free(buf);
    return result;
}

#if defined(MS_WINDOWS)
static PyObject*
PyLocale_getdefaultlocale(PyObject* self)
{
    char encoding[100];
    char locale[100];

    PyOS_snprintf(encoding, sizeof(encoding), "cp%d", GetACP());

    if (GetLocaleInfo(LOCALE_USER_DEFAULT,
                      LOCALE_SISO639LANGNAME,
                      locale, sizeof(locale))) {
        Py_ssize_t i = strlen(locale);
        locale[i++] = '_';
        if (GetLocaleInfo(LOCALE_USER_DEFAULT,
                          LOCALE_SISO3166CTRYNAME,
                          locale+i, (int)(sizeof(locale)-i)))
            return Py_BuildValue("ss", locale, encoding);
    }

    /* If we end up here, this windows version didn't know about
       ISO639/ISO3166 names (it's probably Windows 95).  Return the
       Windows language identifier instead (a hexadecimal number) */

    locale[0] = '0';
    locale[1] = 'x';
    if (GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IDEFAULTLANGUAGE,
                      locale+2, sizeof(locale)-2)) {
        return Py_BuildValue("ss", locale, encoding);
    }

    /* cannot determine the language code (very unlikely) */
    Py_INCREF(Py_None);
    return Py_BuildValue("Os", Py_None, encoding);
}
#endif

#if defined(__APPLE__)
/*
** Find out what the current script is.
** Donated by Fredrik Lundh.
*/
static char *mac_getscript(void)
{
    CFStringEncoding enc = CFStringGetSystemEncoding();
    static CFStringRef name = NULL;
    /* Return the code name for the encodings for which we have codecs. */
    switch(enc) {
    case kCFStringEncodingMacRoman: return "mac-roman";
    case kCFStringEncodingMacGreek: return "mac-greek";
    case kCFStringEncodingMacCyrillic: return "mac-cyrillic";
    case kCFStringEncodingMacTurkish: return "mac-turkish";
    case kCFStringEncodingMacIcelandic: return "mac-icelandic";
    /* XXX which one is mac-latin2? */
    }
    if (!name) {
        /* This leaks an object. */
        name = CFStringConvertEncodingToIANACharSetName(enc);
    }
    return (char *)CFStringGetCStringPtr(name, 0);
}

static PyObject*
PyLocale_getdefaultlocale(PyObject* self)
{
    return Py_BuildValue("Os", Py_None, mac_getscript());
}
#endif

#ifdef HAVE_LANGINFO_H
#define LANGINFO(X) {#X, X}
struct langinfo_constant{
	char* name;
	int value;
} langinfo_constants[] =
{
    /* These constants should exist on any langinfo implementation */
    LANGINFO(DAY_1),
    LANGINFO(DAY_2),
    LANGINFO(DAY_3),
    LANGINFO(DAY_4),
    LANGINFO(DAY_5),
    LANGINFO(DAY_6),
    LANGINFO(DAY_7),

    LANGINFO(ABDAY_1),
    LANGINFO(ABDAY_2),
    LANGINFO(ABDAY_3),
    LANGINFO(ABDAY_4),
    LANGINFO(ABDAY_5),
    LANGINFO(ABDAY_6),
    LANGINFO(ABDAY_7),

    LANGINFO(MON_1),
    LANGINFO(MON_2),
    LANGINFO(MON_3),
    LANGINFO(MON_4),
    LANGINFO(MON_5),
    LANGINFO(MON_6),
    LANGINFO(MON_7),
    LANGINFO(MON_8),
    LANGINFO(MON_9),
    LANGINFO(MON_10),
    LANGINFO(MON_11),
    LANGINFO(MON_12),

    LANGINFO(ABMON_1),
    LANGINFO(ABMON_2),
    LANGINFO(ABMON_3),
    LANGINFO(ABMON_4),
    LANGINFO(ABMON_5),
    LANGINFO(ABMON_6),
    LANGINFO(ABMON_7),
    LANGINFO(ABMON_8),
    LANGINFO(ABMON_9),
    LANGINFO(ABMON_10),
    LANGINFO(ABMON_11),
    LANGINFO(ABMON_12),

#ifdef RADIXCHAR
    /* The following are not available with glibc 2.0 */
    LANGINFO(RADIXCHAR),
    LANGINFO(THOUSEP),
    /* YESSTR and NOSTR are deprecated in glibc, since they are
       a special case of message translation, which should be rather
       done using gettext. So we don't expose it to Python in the
       first place.
    LANGINFO(YESSTR),
    LANGINFO(NOSTR),
    */
    LANGINFO(CRNCYSTR),
#endif

    LANGINFO(D_T_FMT),
    LANGINFO(D_FMT),
    LANGINFO(T_FMT),
    LANGINFO(AM_STR),
    LANGINFO(PM_STR),

    /* The following constants are available only with XPG4, but...
       AIX 3.2. only has CODESET.
       OpenBSD doesn't have CODESET but has T_FMT_AMPM, and doesn't have
       a few of the others.
       Solution: ifdef-test them all. */
#ifdef CODESET
    LANGINFO(CODESET),
#endif
#ifdef T_FMT_AMPM
    LANGINFO(T_FMT_AMPM),
#endif
#ifdef ERA
    LANGINFO(ERA),
#endif
#ifdef ERA_D_FMT
    LANGINFO(ERA_D_FMT),
#endif
#ifdef ERA_D_T_FMT
    LANGINFO(ERA_D_T_FMT),
#endif
#ifdef ERA_T_FMT
    LANGINFO(ERA_T_FMT),
#endif
#ifdef ALT_DIGITS
    LANGINFO(ALT_DIGITS),
#endif
#ifdef YESEXPR
    LANGINFO(YESEXPR),
#endif
#ifdef NOEXPR
    LANGINFO(NOEXPR),
#endif
#ifdef _DATE_FMT
    /* This is not available in all glibc versions that have CODESET. */
    LANGINFO(_DATE_FMT),
#endif
    {0, 0}
};

PyDoc_STRVAR(nl_langinfo__doc__,
"nl_langinfo(key) -> string\n"
"Return the value for the locale information associated with key.");

static PyObject*
PyLocale_nl_langinfo(PyObject* self, PyObject* args)
{
    int item, i;
    if (!PyArg_ParseTuple(args, "i:nl_langinfo", &item))
        return NULL;
    /* Check whether this is a supported constant. GNU libc sometimes
       returns numeric values in the char* return value, which would
       crash PyString_FromString.  */
    for (i = 0; langinfo_constants[i].name; i++)
        if (langinfo_constants[i].value == item) {
            /* Check NULL as a workaround for GNU libc's returning NULL
               instead of an empty string for nl_langinfo(ERA).  */
            const char *result = nl_langinfo(item);
            return PyString_FromString(result != NULL ? result : "");
        }
    PyErr_SetString(PyExc_ValueError, "unsupported langinfo constant");
    return NULL;
}
#endif /* HAVE_LANGINFO_H */

#ifdef HAVE_LIBINTL_H

PyDoc_STRVAR(gettext__doc__,
"gettext(msg) -> string\n"
"Return translation of msg.");

static PyObject*
PyIntl_gettext(PyObject* self, PyObject *args)
{
	char *in;
	if (!PyArg_ParseTuple(args, "z", &in))
		return 0;
	return PyString_FromString(gettext(in));
}

PyDoc_STRVAR(dgettext__doc__,
"dgettext(domain, msg) -> string\n"
"Return translation of msg in domain.");

static PyObject*
PyIntl_dgettext(PyObject* self, PyObject *args)
{
	char *domain, *in;
	if (!PyArg_ParseTuple(args, "zz", &domain, &in))
		return 0;
	return PyString_FromString(dgettext(domain, in));
}

PyDoc_STRVAR(dcgettext__doc__,
"dcgettext(domain, msg, category) -> string\n"
"Return translation of msg in domain and category.");

static PyObject*
PyIntl_dcgettext(PyObject *self, PyObject *args)
{
	char *domain, *msgid;
	int category;
	if (!PyArg_ParseTuple(args, "zzi", &domain, &msgid, &category))
		return 0;
	return PyString_FromString(dcgettext(domain,msgid,category));
}

PyDoc_STRVAR(textdomain__doc__,
"textdomain(domain) -> string\n"
"Set the C library's textdmain to domain, returning the new domain.");

static PyObject*
PyIntl_textdomain(PyObject* self, PyObject* args)
{
	char *domain;
	if (!PyArg_ParseTuple(args, "z", &domain))
		return 0;
	domain = textdomain(domain);
	if (!domain) {
		PyErr_SetFromErrno(PyExc_OSError);
		return NULL;
	}
	return PyString_FromString(domain);
}

PyDoc_STRVAR(bindtextdomain__doc__,
"bindtextdomain(domain, dir) -> string\n"
"Bind the C library's domain to dir.");

static PyObject*
PyIntl_bindtextdomain(PyObject* self,PyObject*args)
{
	char *domain,*dirname;
	if (!PyArg_ParseTuple(args, "zz", &domain, &dirname))
		return 0;
	dirname = bindtextdomain(domain, dirname);
	if (!dirname) {
		PyErr_SetFromErrno(PyExc_OSError);
		return NULL;
	}
	return PyString_FromString(dirname);
}

#ifdef HAVE_BIND_TEXTDOMAIN_CODESET
PyDoc_STRVAR(bind_textdomain_codeset__doc__,
"bind_textdomain_codeset(domain, codeset) -> string\n"
"Bind the C library's domain to codeset.");

static PyObject*
PyIntl_bind_textdomain_codeset(PyObject* self,PyObject*args)
{
	char *domain,*codeset;
	if (!PyArg_ParseTuple(args, "sz", &domain, &codeset))
		return NULL;
	codeset = bind_textdomain_codeset(domain, codeset);
	if (codeset)
		return PyString_FromString(codeset);
	Py_RETURN_NONE;
}
#endif

#endif

static struct PyMethodDef PyLocale_Methods[] = {
  {"setlocale", (PyCFunction) PyLocale_setlocale,
   METH_VARARGS, setlocale__doc__},
  {"localeconv", (PyCFunction) PyLocale_localeconv,
   METH_NOARGS, localeconv__doc__},
  {"strcoll", (PyCFunction) PyLocale_strcoll,
   METH_VARARGS, strcoll__doc__},
  {"strxfrm", (PyCFunction) PyLocale_strxfrm,
   METH_VARARGS, strxfrm__doc__},
#if defined(MS_WINDOWS) || defined(__APPLE__)
  {"_getdefaultlocale", (PyCFunction) PyLocale_getdefaultlocale, METH_NOARGS},
#endif
#ifdef HAVE_LANGINFO_H
  {"nl_langinfo", (PyCFunction) PyLocale_nl_langinfo,
   METH_VARARGS, nl_langinfo__doc__},
#endif
#ifdef HAVE_LIBINTL_H
  {"gettext",(PyCFunction)PyIntl_gettext,METH_VARARGS,
    gettext__doc__},
  {"dgettext",(PyCFunction)PyIntl_dgettext,METH_VARARGS,
   dgettext__doc__},
  {"dcgettext",(PyCFunction)PyIntl_dcgettext,METH_VARARGS,
    dcgettext__doc__},
  {"textdomain",(PyCFunction)PyIntl_textdomain,METH_VARARGS,
   textdomain__doc__},
  {"bindtextdomain",(PyCFunction)PyIntl_bindtextdomain,METH_VARARGS,
   bindtextdomain__doc__},
#ifdef HAVE_BIND_TEXTDOMAIN_CODESET
  {"bind_textdomain_codeset",(PyCFunction)PyIntl_bind_textdomain_codeset,
   METH_VARARGS, bind_textdomain_codeset__doc__},
#endif
#endif
  {NULL, NULL}
};

PyMODINIT_FUNC
init_locale(void)
{
    PyObject *m, *d, *x;
#ifdef HAVE_LANGINFO_H
    int i;
#endif

    m = Py_InitModule("_locale", PyLocale_Methods);
    if (m == NULL)
    	return;

    d = PyModule_GetDict(m);

    x = PyInt_FromLong(LC_CTYPE);
    PyDict_SetItemString(d, "LC_CTYPE", x);
    Py_XDECREF(x);

    x = PyInt_FromLong(LC_TIME);
    PyDict_SetItemString(d, "LC_TIME", x);
    Py_XDECREF(x);

    x = PyInt_FromLong(LC_COLLATE);
    PyDict_SetItemString(d, "LC_COLLATE", x);
    Py_XDECREF(x);

    x = PyInt_FromLong(LC_MONETARY);
    PyDict_SetItemString(d, "LC_MONETARY", x);
    Py_XDECREF(x);

#ifdef LC_MESSAGES
    x = PyInt_FromLong(LC_MESSAGES);
    PyDict_SetItemString(d, "LC_MESSAGES", x);
    Py_XDECREF(x);
#endif /* LC_MESSAGES */

    x = PyInt_FromLong(LC_NUMERIC);
    PyDict_SetItemString(d, "LC_NUMERIC", x);
    Py_XDECREF(x);

    x = PyInt_FromLong(LC_ALL);
    PyDict_SetItemString(d, "LC_ALL", x);
    Py_XDECREF(x);

    x = PyInt_FromLong(CHAR_MAX);
    PyDict_SetItemString(d, "CHAR_MAX", x);
    Py_XDECREF(x);

    Error = PyErr_NewException("locale.Error", NULL, NULL);
    PyDict_SetItemString(d, "Error", Error);

    x = PyString_FromString(locale__doc__);
    PyDict_SetItemString(d, "__doc__", x);
    Py_XDECREF(x);

#ifdef HAVE_LANGINFO_H
    for (i = 0; langinfo_constants[i].name; i++) {
	    PyModule_AddIntConstant(m, langinfo_constants[i].name,
				    langinfo_constants[i].value);
    }
#endif
}

/*
Local variables:
c-basic-offset: 4
indent-tabs-mode: nil
End:
*/


text:
<?php

namespace zikmont\TransporteBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Table(name="tpt_despachos")
 * @ORM\Entity(repositoryClass="zikmont\TransporteBundle\Repository\TptDespachosRepository")
 */
class TptDespachos
{
    /**
     * @ORM\Id
     * @ORM\Column(name="codigo_despacho_pk", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $codigoDespachoPk;

    /**
     * @ORM\Column(name="fecha", type="datetime", nullable="true")
     */
    private $fecha;

    /**
     * @ORM\Column(name="codigo_usuario_fk", type="string", length=20, nullable="true")
     */
    private $codigoUsuarioFk;

    /**
     * @ORM\Column(name="comentarios", type="string", length=200, nullable="true")
     */
    private $comentarios;

    /**
     * Get codigoDespachoPk
     *
     * @return integer
     */
    public function getCodigoDespachoPk()
    {
        return $this->codigoDespachoPk;
    }

    /**
     * Set fecha
     *
     * @param datetime $fecha
     */
    public function setFecha($fecha)
    {
        $this->fecha = $fecha;
    }

    /**
     * Get fecha
     *
     * @return datetime
     */
    public function getFecha()
    {
        return $this->fecha;
    }

    /**
     * Set codigoUsuarioFk
     *
     * @param string $codigoUsuarioFk
     */
    public function setCodigoUsuarioFk($codigoUsuarioFk)
    {
        $this->codigoUsuarioFk = $codigoUsuarioFk;
    }

    /**
     * Get codigoUsuarioFk
     *
     * @return string
     */
    public function getCodigoUsuarioFk()
    {
        return $this->codigoUsuarioFk;
    }

    /**
     * Set comentarios
     *
     * @param string $comentarios
     */
    public function setComentarios($comentarios)
    {
        $this->comentarios = $comentarios;
    }

    /**
     * Get comentarios
     *
     * @return string
     */
    public function getComentarios()
    {
        return $this->comentarios;
    }
}


text:
package com.sirius.upns.server.node.service.impl;

import com.myctu.platform.gateway.agent.pubsub.AbstractEventListener;
import com.sirius.upns.protocol.business.msg.Custom;
import com.sirius.upns.protocol.business.msg.Private;
import com.sirius.upns.server.node.domain.Subscriber;
import com.sirius.upns.server.node.service.SubscriberManager;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by pippo on 14-4-1.
 */
public class PrivateChannelListener extends AbstractEventListener {

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

	protected static ExecutorService executor = Executors.newFixedThreadPool(
			Runtime.getRuntime().availableProcessors() * 4);

	protected SubscriberManager subscriberManager;

	public PrivateChannelListener(SubscriberManager subscriberManager) {
		this.subscriberManager = subscriberManager;
	}

	@Override
	public void onEvent(String channel, final Map<String, Object> event) {
		logger.debug("received event:[{}] on channel:[{}]", event, channel);
		/*异步发送避免消费的太慢*/
		executor.execute(new Runnable() {

			@Override
			public void run() {
				sendToClient(event);
			}

		});
	}

	private void sendToClient(Map<String, Object> event) {
		try {
			/*其实类型是个private,直接获取userId,避免不需要的反序列化*/
			String userId = (String) event.get(Private.USER_ID);
			Set<Subscriber> _subscribers = subscriberManager.getByUserId(userId);
			if (_subscribers.isEmpty()) {
				logger.debug("can not find subscriber with userId:[{}]", userId);
				return;
			}

			Custom custom = new Custom();
			custom.fromMap(event);
			for (Subscriber subscriber : _subscribers) {
				logger.debug("publish message:[{}] to subscriber:[{}]", custom, subscriber);
				subscriber.publish(custom);
			}
		} catch (Exception e) {
			logger.error("send message:[{}] to client due to error:[{}]", event, ExceptionUtils.getStackTrace(e));
		}
	}
}


text:
/*
 * Translated default messages for bootstrap-select.
 * Locale: EU (Basque)
 * Region:
 */
(function ($) {
  $.fn.selectpicker.defaults = {
    noneSelectedText: 'Hautapenik ez',
    noneResultsText: 'Emaitzarik ez {0}',
    countSelectedText: '{1}(e)tik {0} hautatuta',
    maxOptionsText: ['Mugara iritsita ({n} {var} gehienez)', 'Taldearen mugara iritsita ({n} {var} gehienez)', ['elementu', 'elementu']],
    multipleSeparator: ', '
  };
})(jQuery);


text:
The Pachyderm S3 gateway supports the following operations:

* [Create bucket](#create-bucket): Creates a repo and branch.
* [Delete bucket](#delete-bucket): Deletes a branch or a repo with all branches.
* [List buckets](#list-buckets): Lists all branches on all repos as S3 buckets.
* [List objects](#list-objects): Lists the files in the HEAD of a branch.
* [Write object](#write-object) (Upload): Atomically writes a file on a branch of a repo.
* [Get object](#get-object) (Download): Gets file contents on a branch of a repo.
* [Remove object](#remove-object): Atomically removes a file on a branch.

!!! Info

      When using the AWS S3 CLI, simply append `--profile <name-your-profile>` at the end of your command to reference a given profile. If none, the session token will be retrieved from the default profile. More info in the [**Configure your S3 client**](../configure-s3client/#configure-your-s3-client) page.

      For example, in the **Create Bucket** section below, the command would become:
      ```shell
      aws --endpoint-url http://localhost:30600/ s3 mb s3://master.test --profile <name-your-profile>
      ```

## Create Bucket
Call the *create an S3 bucket* command on your S3 client to create a branch in a Pachyderm repository.
For example, let's create the `master` branch of the repo `test`.

1. In MinIO,
    - this would look like:
      ```shell
      $ mc mb local/master.test
      ```
      **System Response:**
      ```
      Bucket created successfully `local/master.test`.
      ```
    - verify that the S3 bucket has been successfully created:
      ```shell
      $ mc ls local
      ```
      **System Response:**
      ```
      [2021-04-26 22:46:08]   0B master.test/
      ```
1. If you are using AWS S3 CLI,
    - this would look like:
      ```shell
      $ aws --endpoint-url http://localhost:30600/ s3 mb s3://master.test
      ```
      **System Response:**
      ```
      make_bucket: master.test
      ```
    - verify that the S3 bucket has been successfully created:
      ```shell
      $ aws --endpoint-url http://localhost:30600/ s3 ls
      ```
      **System Response:**
      ```
      2021-04-26 22:46:08 master.test
      ```
    !!! Note
        Alternatively, You can also use the `pachctl list repo` command to view the
        list of repositories. You should see the newly created repository in this list.

## Delete Bucket
Call the *delete an empty S3 bucket* command on your S3 client to delete a Pachyderm repository.

!!! Warning
    The repo must be completely empty.

1. In MinIO,
    ```shell
    $ mc rb local/master.test
    ```
    **System Response:**
    ```
    Removed `local/master.test` successfully.
    ```
1. If you are using AWS S3 CLI,
    ```shell
    $ aws --endpoint-url http://localhost:30600/ s3 rb s3://master.test
    ```
    **System Response:**
    ```
    remove_bucket: master.test
    ```

## List Buckets
You can check the list of filesystem objects in your Pachyderm
repository by running an S3 client `ls` command.

1. In MinIO,
     ```shell
     $ mc ls local
     ```
     **System Response:**
     ```
     [2021-04-26 15:09:50 PDT]      0B master.train/
     [2021-04-26 14:58:50 PDT]      0B master.pre_process/
     [2021-04-26 14:58:09 PDT]      0B master.split/
     [2021-04-26 14:58:09 PDT]      0B stats.split/
     ```

1. If you are using AWS S3 CLI,

     ```shell
     $ aws --endpoint-url http://localhost:30600 s3 ls
     ```
     **System Response:**
     ```
     2021-04-26 15:09:50 master.train
     2021-04-26 14:58:50 master.pre_process
     2021-04-26 14:58:09 master.split
     2021-04-26 14:58:09 stats.split
     ```

## List Objects
For example, list the contents of the repository raw_data.

1. In MinIO,
     ```shell
     $ mc ls local/master.raw_data
     ```
     **System Response:**
     ```
     [2021-04-26 12:11:37 PDT]  2.6MiB github_issues_medium.csv
     ```

1. If you are using AWS S3 CLI,
     ```shell
     $ aws --endpoint-url http://localhost:30600/ s3 ls s3://master.raw_data
     ```
     **System Response:**
     ```
     2021-04-26  11:22:23    2685061 github_issues_medium.csv
     ```

## Write Object
For example, add the `test.csv` file to the `master` branch in
the `raw_data` repository. `raw_data` being an input repository.

!!! Note
    Not all the repositories that you see in the results of the `ls` command are
    repositories that can be written to.
    Some of them might be read-only.
    Note that you should have writting access to the input repo
    in order to be able to add files to it.

1. In MinIO,
    - this would look like:
        ```shell
        $ mc cp test.csv local/master.raw_data/test.csv
        ```
        **System Response:**
        ```
        test.csv:                  62 B / 62 B  ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓  100.00% 206 B/s 0s
        ```
    - Check that the file was added:
        ```shell
        $ mc ls local/master.raw_data
        ```
        **System Response:**

        ```
        [2021-04-26 12:11:37 PDT]  2.6MiB github_issues_medium.csv
        [2021-04-26 12:11:37 PDT]     62B test.csv
        ```

1. If you are using AWS S3 CLI,
    - this would look like:
      ```shell
      $ aws --endpoint-url http://localhost:30600/ s3 cp test.csv s3://master.raw_data
      ```
      **System Response:**
      ```
      upload: ./test.csv to s3://master.raw_data/test.csv
      ```
    - Check that the file was added:
      ```shell
      $ aws --endpoint-url http://localhost:30600/ s3 ls s3://master.raw_data/
      ```
      **System Response:**
      ```
      2021-04-26 12:11:37  2685061 github_issues_medium.csv
      2021-04-26 12:11:37       62 test.csv
      ```

## Get Object
For example, download the file `github_issues_medium.csv` from the `master` branch of the repo `raw_data`.

1. In MinIO,
     ```shell
     $ mc cp local/master.raw_data/github_issues_medium.csv .
     ```
     **System Response:**
     ```
     github_issues_medium.csv:  2.56 MiB / 2.56 MiB  ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 100.00% 1.26 MiB/s 2s
     ```

1. If you are using AWS S3 CLI,
     ```shell
     $ aws --endpoint-url http://localhost:30600/ s3 cp s3://master.raw_data/test.csv .
     ```
     **System Response:**
     ```
     download: s3://master.raw_data/test.csv to ./test.csv
     ```

## Remove Object
For example, delete the file `test.csv` in the `HEAD` of the `master` branch of the `raw_data` repo.

1. In MinIO,
     ```shell
     $ mc rm local/master.raw_data/test.csv
     ```
     **System Response:**
     ```
     Removing `local/master.raw_data/test.csv`.
     ```

1. If you are using AWS S3 CLI,

     ```shell
     $ aws --endpoint-url http://localhost:30600/ s3 rm s3://master.raw_data/test.csv
     ```
     **System Response:**
     ```
     delete: s3://master.raw_data/test.csv
     ```
!!! note "See Also:"
    - [Complete S3 Gateway API reference](../../../../reference/s3gateway_api/)


text:
@class NSMPlayerRestoration;

@protocol NSMVideoPlayerProtocol <NSMPlayerProtocol>

- (void)restorePlayerWithRestoration:(NSMPlayerRestoration *)restoration;
- (NSMPlayerRestoration *)savePlayerState;

@end


text:
/*
 * Executes the build process for Orchard themes.
 */

var fs = require('fs');
var path = require('path');
var async = require('async');
var mv = require('mv');

'use strict';

module.exports = function(grunt) {

    var helpers = {
        /**
         * Deletes a directory and everything inside.
         */
        deleteDirectory: function (path) {
            if (!fs.existsSync(path)) {
                return;
            }

            fs.readdirSync(path).forEach(function(file,index){
                var curPath = path + "/" + file;
                if(fs.lstatSync(curPath).isDirectory()) { // recurse
                    helpers.deleteDirectory(curPath);
                } else { // delete file
                    fs.unlinkSync(curPath);
                }
            });

            fs.rmdirSync(path);
        },

        /**
         * Returns directories inside the directory associated to the provided path.
         */
        getDirectories: function (srcpath) {
            return fs.readdirSync(srcpath).filter(function(file) {
                return fs.statSync(path.join(srcpath, file)).isDirectory();
            });
        }
    };

    grunt.registerTask('buildThemes', 'Builds custom themes.', function () {
        /**
         * Retrieves defined options.
         */
        var options = this.options();
        grunt.verbose.writeflags(options, 'Options');

        if (!options.dest) {
            grunt.fail.fatal('Unable to build themes if no `dest` option is provided.');
        }

        // check if /Themes has been included in destination path.
        if (options.dest.indexOf('/Themes') < 0) {
            options.dest = path.join(options.dest, 'Themes');
        }

        options.themes = options.themes || './themes';
        options.task = options.task || 'dist';

        // grunt task should be marked as async.
        var done = this.async(),
            themes = helpers.getDirectories(options.themes),
            count = -1;

        /**
         * Builds the next theme (dictated by `count`) in the list of `themes`.
         */
        var buildNextTheme = function () {
            count++;

            // all themes have been built.
            if (count === themes.length) {
                // slight delay to ensure future tasks can interact with theme files.
                setTimeout(done, 500);
                return;
            }

            var child = grunt.util.spawn({
                cmd: 'npm',
                args: ['run', options.task],
                opts: {
                    cwd: path.join(options.themes, themes[count])
                }
            }, function(error, result, code) {
                if (error) {
                    grunt.fail.fatal('Failed to build theme ' + themes[count] + '.');
                    return;
                }

                helpers.deleteDirectory(path.join(options.dest, themes[count]));
                copyTheme();
            });

            child.stdout.on('data', function(buf) {
                grunt.log.writeln(String(buf));
            });

            child.stderr.on('data', function(buf) {
                grunt.log.writeln(String(buf));
            });
        };

        /**
         * Deletes the existing theme and copies the distributable ready theme
         * into position.
         */
        var copyTheme = function () {
            var dest = path.join(options.dest, themes[count]);

            // deletes theme is already exists.
            if (fs.exists(dest)) {
                fs.rmdir(dest);
            }

            mv(path.join(options.themes, themes[count], 'dist'), dest, {mkdirp: true}, function() {
                buildNextTheme();
            });
        };

        buildNextTheme();
    });
};


text:
package org.apache.camel.component.irc;

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

import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.RuntimeCamelException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.schwering.irc.lib.IRCConnection;
import org.schwering.irc.lib.IRCEventAdapter;

import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class IrcProducerTest {

    private IrcComponent component;
    private IRCConnection connection;
    private IrcEndpoint endpoint;
    private IrcConfiguration configuration;
    private IrcProducer producer;
    private IRCEventAdapter listener;
    private Exchange exchange;
    private Message message;

    @BeforeEach
    public void doSetup() {
        component = mock(IrcComponent.class);
        connection = mock(IRCConnection.class);
        endpoint = mock(IrcEndpoint.class);
        configuration = mock(IrcConfiguration.class);
        listener = mock(IRCEventAdapter.class);
        exchange = mock(Exchange.class);
        message = mock(Message.class);

        List<IrcChannel> channels = new ArrayList<>();
        channels.add(new IrcChannel("#chan1", null));
        channels.add(new IrcChannel("#chan2", "chan2key"));

        when(configuration.getChannelList()).thenReturn(channels);
        when(endpoint.getConfiguration()).thenReturn(configuration);
        when(endpoint.getComponent()).thenReturn(component);
        when(component.getIRCConnection(configuration)).thenReturn(connection);

        producer = new IrcProducer(endpoint);
        producer.setListener(listener);
        producer.start();
    }

    @Test
    public void doStopTest() throws Exception {
        producer.stop();
        verify(connection).doPart("#chan1");
        verify(connection).doPart("#chan2");
        verify(connection).removeIRCEventListener(listener);
    }

    @Test
    public void doStartTest() throws Exception {
        producer.start();

        verify(connection).addIRCEventListener(listener);
        verify(endpoint).joinChannels();
    }

    @Test
    public void processTest() throws Exception {

        when(connection.isConnected()).thenReturn(true);
        when(exchange.getIn()).thenReturn(message);
        when(message.getBody(String.class)).thenReturn("PART foo");
        when(message.getHeader(IrcConstants.IRC_SEND_TO, String.class)).thenReturn("bottest");

        producer.process(exchange);
        verify(connection).send("PART foo");

        when(message.getBody(String.class)).thenReturn("foo");

        producer.process(exchange);
        verify(connection).doPrivmsg("bottest", "foo");

        when(message.getHeader(IrcConstants.IRC_SEND_TO, String.class)).thenReturn(null);

        producer.process(exchange);
        verify(connection).doPrivmsg("#chan1", "foo");
        verify(connection).doPrivmsg("#chan2", "foo");
    }

    @Test
    public void processTestException() throws Exception {

        when(exchange.getIn()).thenReturn(message);
        when(message.getBody(String.class)).thenReturn("PART foo");
        when(message.getHeader(IrcConstants.IRC_TARGET, String.class)).thenReturn("bottest");

        when(connection.isConnected()).thenReturn(false);

        assertThrows(RuntimeCamelException.class,
                () -> producer.process(exchange));
    }
}


text:
package timetakers.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import timetakers.security.CustomUserDetailsService;

import static timetakers.TimeTakerApplication.DISABLE_FRAME_OPTIONS;

/**
 * @author David Liebl
 */

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        if (DISABLE_FRAME_OPTIONS) {
            http.headers()
                    .frameOptions()
                    .disable();
        }

        http.authorizeRequests()
            .antMatchers("/css/**", "/js/**", "/img/**", "/signup*", "/logout*", "/login*", "/error").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin().loginPage("/login").defaultSuccessUrl("/", true).loginProcessingUrl("/securitycheck").failureUrl("/login?error").permitAll()
            .and()
            .logout().logoutUrl("/logout").logoutSuccessUrl("/login?logout").invalidateHttpSession(true).permitAll()
            .and()
            .exceptionHandling().accessDeniedPage("/error");
    }

    @Bean(name = "passwordEncoder")
    protected PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}


text:
builds the [vimeo/graphite-api-influxdb](https://registry.hub.docker.com/u/vimeo/graphite-api-influxdb/) docker image, with graphite-api and graphite-influxdb
using [baseimage-docker](http://phusion.github.io/baseimage-docker/)
which means you effectively get a full working linux system with an init system, logging,
etc.  So you can login if anything goes wrong.

# building

* install docker on your system
* make a new directory and put your own Dockerfile in it, it looks like so:

```
FROM vimeo/graphite-api-influxdb
```

* put a customized graphite-api.yaml in this directory, you can base yourself off [the graphite-api.yaml in this repository](https://github.com/vimeo/graphite-api-influxdb-docker/blob/master/graphite-api.yaml)

* build!

```
docker build .
```

* run !

```
docker run -p 8000:8000 <image-id>
```

If you want, you can build with a name and run the container with this name:
```
docker build . -t <name>
docker run -p 8000:8000 <name>
```

# logging in to the container

See [container admininstration](https://github.com/phusion/baseimage-docker/blob/master/README.md#container_administration)

# http 500 errors

on /render calls, you might get http 500 responses.
unfortunately we can't simply log yet what happend (i.e. which exception)
or display the errors in the http response.
see https://github.com/brutasse/graphite-api/issues/16
but you can make a free account on getsentry.com and use that, it works nicely.
You can also try this patch for graphite-api https://github.com/brutasse/graphite-api/pull/73#issuecomment-74080310
It works for some people (including yours truly)

# Gunicorn not starting?
This shouldn't happen to you as an end user,
but may happen if you're tweaking this image.
Try running in debug/standalone mode by running this script:
https://github.com/brutasse/graphite-api/blob/master/bin/graphite


text:
package org.apache.harmony.unpack200.bytecode;

import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * A compressor-defined class file attribute.
 */
public class NewAttribute extends BCIRenumberedAttribute {

    private final List lengths = new ArrayList(); // List of Integers
    private final List body = new ArrayList();
    private ClassConstantPool pool;
    private final int layoutIndex;

    public NewAttribute(CPUTF8 attributeName, int layoutIndex) {
        super(attributeName);
        this.layoutIndex = layoutIndex;
    }

    public int getLayoutIndex() {
        return layoutIndex;
    }

    /*
     * (non-Javadoc)
     *
     * @see org.apache.harmony.unpack200.bytecode.Attribute#getLength()
     */
    protected int getLength() {
        int length = 0;
        for(int iter = 0; iter < lengths.size(); iter++) {
            length += ((Integer)lengths.get(iter)).intValue();
        }
        return length;
    }

    /*
     * (non-Javadoc)
     *
     * @see org.apache.harmony.unpack200.bytecode.Attribute#writeBody(java.io.DataOutputStream)
     */
    protected void writeBody(DataOutputStream dos) throws IOException {
        for (int i = 0; i < lengths.size(); i++) {
            int length = ((Integer) lengths.get(i)).intValue();
            Object obj = body.get(i);
            long value = 0;
            if (obj instanceof Long) {
                value = ((Long) obj).longValue();
            } else if (obj instanceof ClassFileEntry) {
                value = pool.indexOf(((ClassFileEntry) obj));
            } else if (obj instanceof BCValue) {
                value = ((BCValue) obj).actualValue;
            }
            // Write
            if (length == 1) {
                dos.writeByte((int) value);
            } else if (length == 2) {
                dos.writeShort((int) value);
            } else if (length == 4) {
                dos.writeInt((int) value);
            } else if (length == 8) {
                dos.writeLong(value);
            }
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see org.apache.harmony.unpack200.bytecode.ClassFileEntry#toString()
     */
    public String toString() {
        return attributeName.underlyingString();
    }

    public void addInteger(int length, long value) {
        lengths.add(new Integer(length));
        body.add(new Long(value));
    }

    public void addBCOffset(int length, int value) {
        lengths.add(new Integer(length));
        body.add(new BCOffset(value));
    }

    public void addBCIndex(int length, int value) {
        lengths.add(new Integer(length));
        body.add(new BCIndex(value));
    }

    public void addBCLength(int length, int value) {
        lengths.add(new Integer(length));
        body.add(new BCLength(value));
    }

    public void addToBody(int length, Object value) {
        lengths.add(new Integer(length));
        body.add(value);
    }

    protected void resolve(ClassConstantPool pool) {
        super.resolve(pool);
        for(int iter = 0; iter < body.size(); iter++) {
            Object element = body.get(iter);
            if (element instanceof ClassFileEntry) {
                ((ClassFileEntry) element).resolve(pool);
            }
        }
        this.pool = pool;
    }

    protected ClassFileEntry[] getNestedClassFileEntries() {
    	int total = 1;
    	for(int iter = 0; iter < body.size(); iter++) {
            Object element = body.get(iter);
            if (element instanceof ClassFileEntry) {
                total++;
            }
        }
    	ClassFileEntry[] nested = new ClassFileEntry[total];
    	nested[0] = getAttributeName();
    	int i = 1;
    	for(int iter = 0; iter < body.size(); iter++) {
            Object element = body.get(iter);
            if (element instanceof ClassFileEntry) {
            	nested[i] = (ClassFileEntry) element;
                i++;
            }
        }
    	return nested;
    }

    private static class BCOffset extends BCValue {

        private final int offset;
        private int index;

        public BCOffset(int offset) {
            this.offset = offset;
        }

        public void setIndex(int index) {
            this.index = index;
        }

    }

    private static class BCIndex extends BCValue {

        private final int index;

        public BCIndex(int index) {
            this.index = index;
        }
    }

    private static class BCLength extends BCValue {

        private final int length;

        public BCLength(int length) {
            this.length = length;
        }
    }

    // Bytecode-related value (either a bytecode index or a length)
    private static abstract class BCValue {

        int actualValue;

        public void setActualValue(int value) {
            this.actualValue = value;
        }

    }

    protected int[] getStartPCs() {
        // Don't need to return anything here as we've overridden renumber
        return null;
    }

    public void renumber(List byteCodeOffsets) {
        if (!renumbered) {
            Object previous = null;
            for (Iterator iter = body.iterator(); iter.hasNext();) {
                Object obj = iter.next();
                if (obj instanceof BCIndex) {
                    BCIndex bcIndex = (BCIndex) obj;
                    bcIndex.setActualValue(((Integer) byteCodeOffsets
                            .get(bcIndex.index)).intValue());
                } else if (obj instanceof BCOffset) {
                    BCOffset bcOffset = (BCOffset) obj;
                    if (previous instanceof BCIndex) {
                        int index = ((BCIndex) previous).index
                                + bcOffset.offset;
                        bcOffset.setIndex(index);
                        bcOffset.setActualValue(((Integer) byteCodeOffsets
                                .get(index)).intValue());
                    } else if (previous instanceof BCOffset) {
                        int index = ((BCOffset) previous).index
                                + bcOffset.offset;
                        bcOffset.setIndex(index);
                        bcOffset.setActualValue(((Integer) byteCodeOffsets
                                .get(index)).intValue());
                    } else {
                        // Not sure if this should be able to happen
                        bcOffset.setActualValue(((Integer) byteCodeOffsets
                                .get(bcOffset.offset)).intValue());
                    }
                } else if (obj instanceof BCLength) {
                    // previous must be a BCIndex
                    BCLength bcLength = (BCLength) obj;
                    BCIndex prevIndex = (BCIndex) previous;
                    int index = prevIndex.index + bcLength.length;
                    int actualLength = ((Integer) byteCodeOffsets.get(index))
                            .intValue()
                            - prevIndex.actualValue;
                    bcLength.setActualValue(actualLength);
                }
                previous = obj;
            }
            renumbered = true;
        }
    }

}


text:
require 'spec_helper'

RSpec.describe ROM::Relation::Curried do
  include_context 'users and tasks'

  let(:users) { rom.relations.users }

  before do
    setup.relation(:users) do
      def by_name(name)
        restrict(name: name)
      end

      def find(criteria)
        restrict(criteria)
      end
    end
  end

  describe '#call' do
    let(:relation) { users.by_name.('Jane') }

    it 'materializes a relation' do
      expect(relation).to match_array([
        name: 'Jane', email: 'jane@doe.org'
      ])
    end

    it 'returns a loaded relation' do
      expect(relation.source).to eql(users.by_name('Jane'))
    end
  end

  describe '#respond_to?' do
    it 'returns true if wrapped relation responds to a method' do
      expect(users.by_name).to respond_to(:dataset)
    end

    it 'returns false if wrapped relation does not respond to a method' do
      expect(users.by_name).not_to respond_to(:not_here)
    end
  end

  describe '#method_missing' do
    it 'forwards to the relation' do
      expect(users.by_name.dataset).to eql(users.dataset)
    end

    it 'does not forward to the relation when method is auto-curried' do
      expect { users.by_name.find }.to raise_error(NoMethodError, /find/)
    end
  end
end


text:
#include <string>
#include "third_party/googletest/src/googletest/include/gtest/gtest.h"
#include "./aom_config.h"
#include "./aom_version.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/util.h"
#include "test/y4m_video_source.h"
#include "aom_ports/aom_timer.h"

namespace {

const int kMaxPsnr = 100;
const double kUsecsInSec = 1000000.0;

struct EncodePerfTestVideo {
  EncodePerfTestVideo(const char *name_, uint32_t width_, uint32_t height_,
                      uint32_t bitrate_, int frames_)
      : name(name_), width(width_), height(height_), bitrate(bitrate_),
        frames(frames_) {}
  const char *name;
  uint32_t width;
  uint32_t height;
  uint32_t bitrate;
  int frames;
};

const EncodePerfTestVideo kAV1EncodePerfTestVectors[] = {
  EncodePerfTestVideo("desktop_640_360_30.yuv", 640, 360, 200, 2484),
  EncodePerfTestVideo("kirland_640_480_30.yuv", 640, 480, 200, 300),
  EncodePerfTestVideo("macmarcomoving_640_480_30.yuv", 640, 480, 200, 987),
  EncodePerfTestVideo("macmarcostationary_640_480_30.yuv", 640, 480, 200, 718),
  EncodePerfTestVideo("niklas_640_480_30.yuv", 640, 480, 200, 471),
  EncodePerfTestVideo("tacomanarrows_640_480_30.yuv", 640, 480, 200, 300),
  EncodePerfTestVideo("tacomasmallcameramovement_640_480_30.yuv", 640, 480, 200,
                      300),
  EncodePerfTestVideo("thaloundeskmtg_640_480_30.yuv", 640, 480, 200, 300),
  EncodePerfTestVideo("niklas_1280_720_30.yuv", 1280, 720, 600, 470),
};

const int kEncodePerfTestSpeeds[] = { 5, 6, 7, 8 };
const int kEncodePerfTestThreads[] = { 1, 2, 4 };

#define NELEMENTS(x) (sizeof((x)) / sizeof((x)[0]))

class AV1EncodePerfTest
    : public ::libaom_test::EncoderTest,
      public ::libaom_test::CodecTestWithParam<libaom_test::TestMode> {
 protected:
  AV1EncodePerfTest()
      : EncoderTest(GET_PARAM(0)), min_psnr_(kMaxPsnr), nframes_(0),
        encoding_mode_(GET_PARAM(1)), speed_(0), threads_(1) {}

  virtual ~AV1EncodePerfTest() {}

  virtual void SetUp() {
    InitializeConfig();
    SetMode(encoding_mode_);

    cfg_.g_lag_in_frames = 0;
    cfg_.rc_min_quantizer = 2;
    cfg_.rc_max_quantizer = 56;
    cfg_.rc_dropframe_thresh = 0;
    cfg_.rc_undershoot_pct = 50;
    cfg_.rc_overshoot_pct = 50;
    cfg_.rc_buf_sz = 1000;
    cfg_.rc_buf_initial_sz = 500;
    cfg_.rc_buf_optimal_sz = 600;
    cfg_.rc_resize_allowed = 0;
    cfg_.rc_end_usage = AOM_CBR;
    cfg_.g_error_resilient = 1;
    cfg_.g_threads = threads_;
  }

  virtual void PreEncodeFrameHook(::libaom_test::VideoSource *video,
                                  ::libaom_test::Encoder *encoder) {
    if (video->frame() == 0) {
      const int log2_tile_columns = 3;
      encoder->Control(AOME_SET_CPUUSED, speed_);
      encoder->Control(AV1E_SET_TILE_COLUMNS, log2_tile_columns);
      encoder->Control(AV1E_SET_FRAME_PARALLEL_DECODING, 1);
      encoder->Control(AOME_SET_ENABLEAUTOALTREF, 0);
    }
  }

  virtual void BeginPassHook(unsigned int /*pass*/) {
    min_psnr_ = kMaxPsnr;
    nframes_ = 0;
  }

  virtual void PSNRPktHook(const aom_codec_cx_pkt_t *pkt) {
    if (pkt->data.psnr.psnr[0] < min_psnr_) {
      min_psnr_ = pkt->data.psnr.psnr[0];
    }
  }

  // for performance reasons don't decode
  virtual bool DoDecode() { return 0; }

  double min_psnr() const { return min_psnr_; }

  void set_speed(unsigned int speed) { speed_ = speed; }

  void set_threads(unsigned int threads) { threads_ = threads; }

 private:
  double min_psnr_;
  unsigned int nframes_;
  libaom_test::TestMode encoding_mode_;
  unsigned speed_;
  unsigned int threads_;
};

TEST_P(AV1EncodePerfTest, PerfTest) {
  for (size_t i = 0; i < NELEMENTS(kAV1EncodePerfTestVectors); ++i) {
    for (size_t j = 0; j < NELEMENTS(kEncodePerfTestSpeeds); ++j) {
      for (size_t k = 0; k < NELEMENTS(kEncodePerfTestThreads); ++k) {
        if (kAV1EncodePerfTestVectors[i].width < 512 &&
            kEncodePerfTestThreads[k] > 1)
          continue;
        else if (kAV1EncodePerfTestVectors[i].width < 1024 &&
                 kEncodePerfTestThreads[k] > 2)
          continue;

        set_threads(kEncodePerfTestThreads[k]);
        SetUp();

        const aom_rational timebase = { 33333333, 1000000000 };
        cfg_.g_timebase = timebase;
        cfg_.rc_target_bitrate = kAV1EncodePerfTestVectors[i].bitrate;

        init_flags_ = AOM_CODEC_USE_PSNR;

        const unsigned frames = kAV1EncodePerfTestVectors[i].frames;
        const char *video_name = kAV1EncodePerfTestVectors[i].name;
        libaom_test::I420VideoSource video(
            video_name, kAV1EncodePerfTestVectors[i].width,
            kAV1EncodePerfTestVectors[i].height, timebase.den, timebase.num, 0,
            kAV1EncodePerfTestVectors[i].frames);
        set_speed(kEncodePerfTestSpeeds[j]);

        aom_usec_timer t;
        aom_usec_timer_start(&t);

        ASSERT_NO_FATAL_FAILURE(RunLoop(&video));

        aom_usec_timer_mark(&t);
        const double elapsed_secs = aom_usec_timer_elapsed(&t) / kUsecsInSec;
        const double fps = frames / elapsed_secs;
        const double minimum_psnr = min_psnr();
        std::string display_name(video_name);
        if (kEncodePerfTestThreads[k] > 1) {
          char thread_count[32];
          snprintf(thread_count, sizeof(thread_count), "_t-%d",
                   kEncodePerfTestThreads[k]);
          display_name += thread_count;
        }

        printf("{\n");
        printf("\t\"type\" : \"encode_perf_test\",\n");
        printf("\t\"version\" : \"%s\",\n", VERSION_STRING_NOSP);
        printf("\t\"videoName\" : \"%s\",\n", display_name.c_str());
        printf("\t\"encodeTimeSecs\" : %f,\n", elapsed_secs);
        printf("\t\"totalFrames\" : %u,\n", frames);
        printf("\t\"framesPerSecond\" : %f,\n", fps);
        printf("\t\"minPsnr\" : %f,\n", minimum_psnr);
        printf("\t\"speed\" : %d,\n", kEncodePerfTestSpeeds[j]);
        printf("\t\"threads\" : %d\n", kEncodePerfTestThreads[k]);
        printf("}\n");
      }
    }
  }
}

AV1_INSTANTIATE_TEST_CASE(AV1EncodePerfTest,
                          ::testing::Values(::libaom_test::kRealTime));
}  // namespace


text:
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../../Gemfile', __FILE__)

require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
$:.unshift File.expand_path('../../../../../lib', __FILE__)
$:.unshift File.expand_path('../../lib/chili/social_feature/lib', __FILE__)
$:.unshift File.expand_path('../../lib/chili/invites_feature/lib', __FILE__)


text:
/**
 * 2009-8-20
 */
package org.zlex.chapter05_3;

import org.apache.commons.codec.binary.Base64;

/**
 * Base64组件
 *
 * @author 梁栋
 * @version 1.0
 * @since 1.0
 */
public abstract class Base64Coder {

	/**
	 * 字符编码
	 */
	public final static String ENCODING = "UTF-8";

	/**
	 * Base64编码
	 *
	 * @param data 待编码数据
	 * @return String 编码数据
	 * @throws Exception
	 */
	public static String encode(String data) throws Exception {

		// 执行编码
		byte[] b = Base64.encodeBase64(data.getBytes(ENCODING));

		return new String(b, ENCODING);
	}

	/**
	 * Base64安全编码<br>
	 * 遵循RFC 2045实现
	 *
	 * @param data
	 *            待编码数据
	 * @return String 编码数据
	 *
	 * @throws Exception
	 */
	public static String encodeSafe(String data) throws Exception {

		// 执行编码
		byte[] b = Base64.encodeBase64(data.getBytes(ENCODING), true);

		return new String(b, ENCODING);
	}

	/**
	 * Base64解码
	 *
	 * @param data 待解码数据
	 * @return String 解码数据
	 * @throws Exception
	 */
	public static String decode(String data) throws Exception {

		// 执行解码
		byte[] b = Base64.decodeBase64(data.getBytes(ENCODING));

		return new String(b, ENCODING);
	}

}