text:
var config    = require("../config/config")
  , Sequelize = require("../../index")
  , sequelize = new Sequelize(config.mysql.database, config.mysql.username, config.mysql.password, { logging: false })
  , Helpers   = new (require("../config/helpers"))(sequelize)

describe('HasMany', function() {
  beforeEach(function() { Helpers.sync() })
  afterEach(function() { Helpers.drop() })

  //prevent periods from occurring in the table name since they are used to delimit (table.column)
  var User  = sequelize.define('User' + Math.ceil(Math.random()*10000000), { name: Sequelize.STRING })
    , Task  = sequelize.define('Task' + Math.ceil(Math.random()*10000000), { name: Sequelize.STRING })
    , users = null
    , tasks = null

  User.hasMany(Task, {as:'Tasks'})
  Task.hasMany(User, {as:'Users'})

  beforeEach(function() {
    Helpers.async(function(_done) {
      Helpers.Factories.DAO(User.name, {name: 'User' + Math.random()}, function(_users) {
        users = _users; _done()
      }, 5)
    })
    Helpers.async(function(_done) {
      Helpers.Factories.DAO(Task.name, {name: 'Task' + Math.random()}, function(_tasks) {
        tasks = _tasks; _done()
      }, 2)
    })
  })

  describe('addDAO / getDAO', function() {
    var user = null
      , task = null

    beforeEach(function() {
      Helpers.async(function(done) {
        User.all().on('success', function(_users) {
          Task.all().on('success', function(_tasks) {
            user = _users[0]
            task = _tasks[0]

            done()
          })
        })
      })
    })

    it('should correctly add an association to the dao', function() {
      Helpers.async(function(done) {
        user.getTasks().on('success', function(_tasks) {
          expect(_tasks.length).toEqual(0)
          user.addTask(task).on('success', function() {
            user.getTasks().on('success', function(_tasks) {
              expect(_tasks.length).toEqual(1)
              done()
            })
          })
        })
      })
    })
  })

  describe('removeDAO', function() {
    var user  = null
      , tasks = null

    beforeEach(function() {
      Helpers.async(function(done) {
        User.all().on('success', function(users) {
          Task.all().on('success', function(_tasks) {
            user = users[0]
            tasks = _tasks

            done()
          })
        })
      })
    })

    it("should correctly remove associated objects", function() {
      Helpers.async(function(done) {
        user.getTasks().on('success', function(__tasks) {
          expect(__tasks.length).toEqual(0)
          user.setTasks(tasks).on('success', function() {
            user.getTasks().on('success', function(_tasks) {
              expect(_tasks.length).toEqual(tasks.length)
              user.removeTask(tasks[0]).on('success', function() {
                user.getTasks().on('success', function(_tasks) {
                  expect(_tasks.length).toEqual(tasks.length - 1)
                  done()
                })
              })
            })
          })
        })
      })
    })
  })
})

redpajama_set_name: RedPajamaGithub


text:
package tondeuse.fr.application.fichiers;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import tondeuse.fr.application.exceptions.IllegalPositionException;
import tondeuse.fr.application.exceptions.ParsingException;
import tondeuse.fr.application.intelligence.PassageTondeuses;
import tondeuse.fr.application.model.Plateau;
import tondeuse.fr.application.model.Position;
import tondeuse.fr.application.model.Tondeuse;

/**
 *
 * Classe permettant de transferer en objet memoire un fichier
 *
 */
public class GestionFichier {

	static final Logger LOGGER = LoggerFactory.getLogger(GestionFichier.class);

	private String path;
	/**
	 *
	 * @param path le chemin du fichier
	 */
	private GestionFichier(String path) {
		this.path = path;
	}

	public static Plateau chargerFichier(String path) throws ParsingException {

		GestionFichier gestionFichier = new GestionFichier(path);
		String[] lignes = gestionFichier.readFile(path);
		LOGGER.info("lecture du fichier");
		Plateau plateau = null;
		if (lignes.length == 0) {
			throw new ParsingException("fichier vide");
		}
		// recuperation du coin superieur du plateau
		try {
			Position coinSuperieur = LoadElements.loadCoordonnees(lignes[0].split(" "));
			plateau = new Plateau(coinSuperieur);

			plateau = new Plateau(LoadElements.loadCoordonnees(lignes[0].split(" ")));
			//recuperation des tondeuses
			for (int i = 1; i < lignes.length; i++) {
				Tondeuse tondeuse = LoadElements.loadTondeuseCoordonneesEtOrientation(lignes[i]);
				i++;
				tondeuse.addActions(LoadElements.loadActions(lignes[i], coinSuperieur));
				plateau.addTondeuse(tondeuse);
			}
		} catch (IllegalPositionException e) {

			throw new ParsingException("Fichier formatee de facon incorrecte");
		}
		return plateau;
	}

	/**
	 * Lit le fichier en entree et retour un tableau de String, un élément pour
	 * chaque ligne
	 *
	 * @param path
	 *            le chemin vers le fichier
	 * @return le tableau de String
	 * @throws ParsingException
	 *             Si un probleme est rencontre
	 */
	private String[] readFile(String path) throws ParsingException {
		LOGGER.info("chargement du fichier");
		FileReader fileReader = null;
		List<String> lignes = new ArrayList<String>();
		try {
			fileReader = new FileReader(path);
		} catch (FileNotFoundException e) {
			throw new ParsingException("Fichier non present");
		}
		// initialisation du bufffer
		BufferedReader bufferedReader = null;
		try {
			bufferedReader = new BufferedReader(fileReader);
			// parcours des lignes
			String ligne = null;
			while ((ligne = bufferedReader.readLine()) != null) {
				lignes.add(ligne);
			}
		} catch (IOException e) {
			throw new ParsingException("Erreur en parsant le fichier");
		} finally {
			// fermeture du buffer
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			} catch (IOException e) {
				throw new ParsingException("Impossible de fermer le buffer");
			}
		}
		// conertit la liste en tableau
		return lignes.toArray(new String[lignes.size()]);
	}

}


text:
This is the second version of the gallery app. This repo is however only a part of the whole. This is the frontend of the app. There is no data to be displayed here but this app makes API calls to get data. Both backend and frontend are meant to be run on separate servers.

##What does it currently do?
Currently, you can use this to explore images that are sent through explore api from the server.

##Implementation
This is implemented in [AngularJS](https://www.angularjs.org/), HTML5, CSS3. Using extra angular libraries such as [Angular Material](https://material.angularjs.org/latest/), [Angular Messages](https://docs.angularjs.org/api/ngMessages/directive/ngMessages), etc. I am also trying to use [Ben Nadel's Preload Factory](https://www.bennadel.com/blog/2597-preloading-images-in-angularjs-with-promises.htm) (currently a work in progress)

##How to make it work?
Just git clone this repo into a document root of a apache server, go inside the directory and do a `bower install`


text:
package ec.util;
import java.io.*;
import java.util.Vector;
import java.util.Enumeration;

/*
 * Output.java
 * Created: Sat Aug  7 15:30:54 1999
 *
 */

/**
 *
Outputs and logs system messages, errors, and other various
 * items printed as a result of a run.
 *
 *
 Output maintains zero or more logs, which contain Writers which
 * write out stuff.  Each log has an associated verbosity; if request
 * is made to write text to a log, and the text's maximal verbosity
 * is lower than the verbosity of the log, the log will not write it.
 * Each Output instance also has an instance-level global verbosity;
 * incoming requests to write text are additionally subject to this
 * verbosity test.  Lastly, the Output class itself has a global
 * verbosity as well.  This last verbosity is useful for shutting
 * down writing to all logs in the entire system in a simple way.
 *
 *
When the system fails for some reason and must be started back
 * up from a checkpoint, Output's log files may be overwritten.  Output
 * offers three approaches here.  First, Output can clear the log file
 * and overwrite it.  Second, Output can append to the existing log file;
 * because checkpoints are only done occasionally, this may result in
 * duplicate outputs to a file, so keep this in mind.  Third, Output can
 * keep certain written text, typically announcements, in memory;
 * this text gets written out into the checkpoint file, and so it is sound.
 *
 *
There are several kinds of announcements, in different levels
 * of importance.
 *
 *

 *
 FATAL ERRORs.  These errors cause the system to exit(1) immediately.
 *
 Simple ERRORs.  These errors set the "errors" flag to true; at
 * the end of a stream of simple errors, the system in general is expected
 * to exit with a fatal error due to the flag being set.  That's the
 * protocol anyway.  On restart from a checkpoint, if there were any
 * simple errors, the system ends with a fatal error automatically.
 *
 WARNINGs.  These errors do not cause the system to exit under any
 * circumstances.
 *
 MESSAGEs.  Useful facts printed out for the benefit of the user.
 *
 SYSTEM MESSAGEs.  Useful system-level facts printed out for the
 * benefit of the user.
 *

 *
 *
The default verbosity values for different kinds of announcements are
 * given below:
 *

0	V_VERBOSE	(totally verbose)

1000	V_NO_MESSAGES	(don't print messages or system messages)

2000	V_NO_WARNINGS	(don't print warnings, messages, or system messages)

3000	V_NO_GENERAL	(don't print warnings, messages, system messages, or other "general info" stuff that might come along (like statistics maybe))

4000	V_NO_ERRORS	(don't even print errors)

5000	V_TOTALLY_SILENT	(be totally silent)

 *
 *
Output by default will automatically flush any log which prints an announcement
 * (or anything printed with Output.println(...).  You can change this behavior with
 * the setFlush() method.
 *
 *
Output will also store all announcements in memory by default so as to reproduce
 * them if it's restarted from a checkpoint.  You can change this behavior also by
 *
 * @author Sean Luke
 * @version 1.0
 */

public class Output implements Serializable
    {
    boolean errors;
    Vector logs = new Vector();
    Vector announcements = new Vector();
    int verbosity;
    boolean flush = true;
    boolean store = true;
    String filePrefix = "";

    public static final int ALL_LOGS = -1;

    /** Total verbosity */
    public static final int V_VERBOSE = 0;
    /** Don't print messages */
    public static final int V_NO_MESSAGES = 1000;
    /** Don't print warnings or messages */
    public static final int V_NO_WARNINGS = 2000;
    /** The standard verbosity to use if you don't want common reporting (like statistics) */
    public static final int V_NO_GENERAL = 3000;
    /** Don't print warnings, messages, or simple errors  */
    public static final int V_NO_ERRORS = 4000;
    /** No verbosity at all, not even system messages or fatal errors*/
    public static final int V_TOTALLY_SILENT = 5000;

    public void setFilePrefix(String filePrefix) {
        this.filePrefix = filePrefix;
        }

    protected void finalize() throws Throwable
        {
        // flush the logs
        close();

        // do super.finalize, just for good style
        super.finalize();
        }

    private void exitWithError()
        {
        // flush logs first
        close();

        // exit
        System.exit(1);
        }

    /** Closes the logs -- ONLY call this if you are preparing to quit */
    public synchronized void close()
        {
        // just in case
        flush();

        Enumeration e = logs.elements();
        while(e.hasMoreElements())
            {
            Log log = (Log)e.nextElement();
            if (!log.isLoggingToSystemOut)
                log.writer.close();
            }
        }

    /** Flushes the logs */
    public synchronized void flush()
        {
        Enumeration e = logs.elements();
        while(e.hasMoreElements())
            {
            Log log = (Log)e.nextElement();
            log.writer.flush();
            }
        // just in case...
        System.out.flush();
        System.err.flush();
        }

    /** Creates a new, verbose, empty Output object. */
    public Output(boolean storeAnnouncementsInMemory, int _verbosity)
        {
        errors = false;
        store = storeAnnouncementsInMemory;
        verbosity = _verbosity;
        }

    /** Sets whether the Output flushes its announcements.*/
    public synchronized void setFlush(boolean v)
        {
        flush = v;
        }

    /* Returns the Output's flushing behavior. */
    public synchronized boolean getFlush()
        {
        return flush;
        }

    /** Sets whether the Output stores its announcements.*/
    public synchronized void setStore(boolean v)
        {
        store = v;
        }

    /* Returns the Output's storing behavior. */
    public synchronized boolean getStore()
        {
        return store;
        }

    /** Sets the Output object's general verbosity to v. */
    public synchronized void setVerbosity(int v)
        {
        verbosity = v;
        }

    /** Returns the Output object's general verbosity*/
    public synchronized int getVerbosity()
        {
        return verbosity;
        }

    /** Creates a new log of minimal verbosity verbosity and adds it
        to Output.  This log will write to the file filename, and may
        or may not post announcements to the log. If the log must be
        reset upon restarting from a checkpoint, it will append to the file
        or erase the file and start over depending on appendOnRestart.
        If appendOnRestart is false and postAnnouncements is
        true, then this log will repost all the announcements on restarting
        from a checkpoint. Returns the position of the log in Output's
        collection of logs -- you should use this to access the log always;
        never store the log itself, which may go away upon a system restart.
        The log can be compressed with gzip, but you cannot appendOnRestart
        and compress at the same time.*/

    public synchronized int addLog(File filename,
        int _verbosity,
        boolean postAnnouncements,
        boolean appendOnRestart,
        boolean gzip) throws IOException
        {
        if (filePrefix != null && filePrefix.length()>0)
            filename = new File(filename.getParent(),filePrefix+filename.getName());
        logs.addElement(new Log(filename,_verbosity,postAnnouncements,appendOnRestart,gzip));
        return logs.size()-1;
        }

    /** Creates a new log of minimal verbosity verbosity and adds it
        to Output.  This log will write to the file filename, and may
        or may not post announcements to the log. If the log must be
        reset upon restarting from a checkpoint, it will append to the file
        or erase the file and start over depending on appendOnRestart.
        If appendOnRestart is false and postAnnouncements is
        true, then this log will repost all the announcements on restarting
        from a checkpoint. Returns the position of the log in Output's
        collection of logs -- you should use this to access the log always;
        never store the log itself, which may go away upon a system restart. */

    public synchronized int addLog(File filename,
        int _verbosity,
        boolean postAnnouncements,
        boolean appendOnRestart) throws IOException
        {
        if (filePrefix != null && filePrefix.length()>0)
            filename = new File(filename.getParent(),filePrefix+filename.getName());
        logs.addElement(new Log(filename,_verbosity,postAnnouncements,appendOnRestart));
        return logs.size()-1;
        }

    /** Creates a new log of minimal verbosity verbosity and adds it
        to Output.  This log will write to stdout (descriptor == Log.D_STDOUT)
        or stderr (descriptor == Log.D_STDERR), and may or may not
        post announcements to the log. Returns the position of the
        log in Output's
        collection of logs -- you should use this to access the log always;
        never store the log itself, which may go away upon a system restart. */

    public synchronized int addLog(int descriptor,
        int _verbosity,
        boolean postAnnouncements)
        {
        logs.addElement(new Log(descriptor,_verbosity,postAnnouncements));
        return logs.size()-1;
        }

    /** Creates a new log of minimal verbosity verbosity and adds it
        to Output.  This log may or may not post announcements to
        the log, and if it does, it additionally may or may not repost
        all of its announcements to the log upon a restart.  The log
        writes to writer, which is reset upon system restart by
        restarter. Returns the position of the log in Output's
        collection of logs -- you should use this to access the log always;
        never store the log itself, which may go away upon a system restart. */

    public synchronized int addLog(Writer writer,
        LogRestarter restarter,
        int _verbosity,
        boolean postAnnouncements,
        boolean repostAnnouncements)
        {
        logs.addElement(new Log(writer,restarter,_verbosity,postAnnouncements,repostAnnouncements));
        return logs.size()-1;
        }

    /** Adds the given log to Output.  In general you shouldn't use this
        method unless you really really need something custom.
        Returns the position of the log in Output's
        collection of logs -- you should use this to access the log always;
        never store the log itself, which may go away upon a system restart. */

    public synchronized int addLog(Log l)
        {
        logs.addElement(l);
        return logs.size()-1;
        }

    /** Returns the number of logs currently posted. */
    public synchronized int numLogs()
        {
        return logs.size();
        }

    /** Returns the given log. */
    public synchronized Log log(int x)
        {
        return (Log)logs.elementAt(x);
        }

    /** Removes the given log. */
    public synchronized Log removeLog(int x)
        {
        Log l = log(x);
        logs.removeElementAt(x);
        return l;
        }

    /** Prints an initial error to System.err.  This is only to
        be used by ec.Evolve in starting up the system. */
    public static void initialError(String s)
        {
        System.err.println("STARTUP ERROR:\n" + s);

        // just in case...
        System.out.flush();
        System.err.flush();
        System.exit(1);
        }

    /** Prints an initial error to System.err.  This is only to
        be used by ec.Evolve in starting up the system. */
    public static void initialError(String s, Parameter p1)
        {
        System.err.println("STARTUP ERROR:\n" + s);
        if (p1!=null) System.err.println("PARAMETER: " + p1);

        // just in case...
        System.out.flush();
        System.err.flush();
        System.exit(1);
        }

    /** Prints an initial error to System.err.  This is only to
        be used by ec.Evolve in starting up the system. */
    public static void initialError(String s, Parameter p1, Parameter p2)
        {
        System.err.println("STARTUP ERROR:\n" + s);
        if (p1!=null) System.err.println("PARAMETER: " + p1);
        if (p2!=null && p1!=null) System.err.println("     ALSO: " + p2);

        // just in case...
        System.out.flush();
        System.err.flush();
        System.exit(1);
        }

    /** Prints an initial message to System.err.  This is only to
        be used by ec.Evolve in starting up the system.  These messages are not logged. */
    public static void initialMessage(String s)
        {
        System.err.println(s);
        System.err.flush();
        }

    /** Posts a system message. */
    public synchronized void systemMessage(String s)
        {
        println(s, V_NO_MESSAGES ,ALL_LOGS, true);
        }

    /** Posts a fatal error.  This causes the system to exit. */
    public synchronized void fatal(String s)
        {
        println("FATAL ERROR:\n"+s, V_TOTALLY_SILENT, ALL_LOGS, true);
        exitWithError();
        }

    /** Posts a fatal error.  This causes the system to exit. */
    public synchronized void fatal(String s, Parameter p1)
        {
        println("FATAL ERROR:\n"+s, V_TOTALLY_SILENT, ALL_LOGS, true);
        if (p1!=null) println("PARAMETER: " + p1, V_TOTALLY_SILENT, ALL_LOGS, true);
        exitWithError();
        }

    /** Posts a fatal error.  This causes the system to exit. */
    public synchronized void fatal(String s, Parameter p1, Parameter p2)
        {
        println("FATAL ERROR:\n"+s, V_TOTALLY_SILENT, ALL_LOGS, true);
        if (p1!=null) println("PARAMETER: " + p1, V_TOTALLY_SILENT, ALL_LOGS, true);
        if (p2!=null && p1!=null) println("     ALSO: " + p2, V_TOTALLY_SILENT, ALL_LOGS, true);
        else println("PARAMETER: " + p2, V_TOTALLY_SILENT, ALL_LOGS, true);
        exitWithError();
        }

    /** Posts a simple error. This causes the error flag to be raised as well. */
    public synchronized void error(String s)
        {
        println("ERROR:\n"+s, V_NO_ERRORS, ALL_LOGS, true);
        errors = true;
        }

    /** Posts a simple error. This causes the error flag to be raised as well. */
    public synchronized void error(String s, Parameter p1)
        {
        println("ERROR:\n"+s, V_TOTALLY_SILENT, ALL_LOGS, true);
        if (p1!=null) println("PARAMETER: " + p1, V_TOTALLY_SILENT, ALL_LOGS, true);
        errors = true;
        }

    /** Posts a simple error. This causes the error flag to be raised as well. */
    public synchronized void error(String s, Parameter p1, Parameter p2)
        {
        println("ERROR:\n"+s, V_TOTALLY_SILENT, ALL_LOGS, true);
        if (p1!=null) println("PARAMETER: " + p1, V_TOTALLY_SILENT, ALL_LOGS, true);
        if (p2!=null && p1!=null) println("     ALSO: " + p2, V_TOTALLY_SILENT, ALL_LOGS, true);
        else println("PARAMETER: " + p2, V_TOTALLY_SILENT, ALL_LOGS, true);
        errors = true;
        }

    /** Posts a warning. */
    public synchronized void warning(String s, Parameter p1, Parameter p2)
        {
        println("WARNING:\n"+s, V_NO_WARNINGS, ALL_LOGS, true);
        if (p1!=null) println("PARAMETER: " + p1, V_TOTALLY_SILENT, ALL_LOGS, true);
        if (p2!=null && p1!=null) println("     ALSO: " + p2, V_TOTALLY_SILENT, ALL_LOGS, true);
        else println("PARAMETER: " + p2, V_TOTALLY_SILENT, ALL_LOGS, true);
        }

    /** Posts a warning. */
    public synchronized void warning(String s, Parameter p1)
        {
        println("WARNING:\n"+s, V_NO_WARNINGS, ALL_LOGS, true);
        if (p1!=null) println("PARAMETER: " + p1, V_TOTALLY_SILENT, ALL_LOGS, true);
        }

    /** Posts a warning. */
    public synchronized void warning(String s)
        {
        println("WARNING:\n"+s, V_NO_WARNINGS, ALL_LOGS, true);
        }

    java.util.HashSet oneTimeWarnings = new java.util.HashSet();
    /** Posts a warning one time only. */
    public synchronized void warnOnce(String s)
        {
        if (!oneTimeWarnings.contains(s))
            {
            oneTimeWarnings.add(s);
            println("ONCE-ONLY WARNING:\n"+s, V_NO_WARNINGS, ALL_LOGS, true);
            }
        }

    public synchronized void warnOnce(String s, Parameter p1)
        {
        if (!oneTimeWarnings.contains(s))
            {
            oneTimeWarnings.add(s);
            println("ONCE-ONLY WARNING:\n"+s, V_NO_WARNINGS, ALL_LOGS, true);
            if (p1!=null) println("PARAMETER: " + p1, V_TOTALLY_SILENT, ALL_LOGS, true);
            }
        }

    public synchronized void warnOnce(String s, Parameter p1, Parameter p2)
        {
        if (!oneTimeWarnings.contains(s))
            {
            oneTimeWarnings.add(s);
            println("ONCE-ONLY WARNING:\n"+s, V_NO_WARNINGS, ALL_LOGS, true);
            if (p1!=null) println("PARAMETER: " + p1, V_TOTALLY_SILENT, ALL_LOGS, true);
            if (p2!=null && p1!=null) println("     ALSO: " + p2, V_TOTALLY_SILENT, ALL_LOGS, true);
            else println("PARAMETER: " + p2, V_TOTALLY_SILENT, ALL_LOGS, true);
            }
        }

    /** Posts a message. */
    public synchronized void message(String s)
        {
        println(s, V_NO_MESSAGES, ALL_LOGS, true);
        }

    /** Forces a file-based log to reopen, erasing its previous contents.
        non-file logs ignore this. */

    public synchronized void reopen(int _log) throws IOException
        {
        Log oldlog = (Log)logs.elementAt(_log);
        logs.setElementAt(oldlog.reopen(),_log);
        }

    /** Forces one or more file-based logs to reopen, erasing
        their previous contents.  non-file logs ignore this. */

    public synchronized void reopen(int[] _logs) throws IOException
        {
        for(int x=0;x<_logs.length;x++)
            {
            Log oldlog = (Log)logs.elementAt(_logs[x]);
            logs.setElementAt(oldlog.reopen(),_logs[x]);
            }
        }

    /** Prints a message to a given log, with a certain verbosity.
        _announcement indicates that the message is an announcement. */

    protected synchronized void println(String s,
        int _verbosity,
        Log log,
        boolean _announcement,
        boolean _reposting) throws OutputException
        {
        if (log.writer==null) throw new OutputException("Log with a null writer: " + log);
        if (!log.postAnnouncements && _announcement) return;  // don't write it
        if (log.verbosity >= _verbosity) return;  // don't write it
        if (verbosity >= _verbosity) return;  // don't write it
        // now write it
        log.writer.println(s);
        if (flush) log.writer.flush();
        //...and stash it in memory maybe
        if (store && _announcement && !_reposting)
            announcements.addElement(new Announcement(s,_verbosity));
        }

    /** Prints a message to a given log,
        with a certain verbosity.  If log==ALL_LOGS, posted to all logs. */
    public synchronized void println(String s,
        int _verbosity,
        int log,
        boolean _announcement) throws OutputException
        {
        if (log==ALL_LOGS) for (int x = 0; x<logs.size();x++)
                               {
                               Log l = (Log) logs.elementAt(x);
                               if (l==null) throw new OutputException("Unknown log number" + l);
                               println(s,_verbosity,l,_announcement,false);
                               }
        else
            {
            Log l = (Log) logs.elementAt(log);
            if (l==null) throw new OutputException("Unknown log number" + l);
            println(s,_verbosity,l,_announcement,false);
            }
        }

    /** Prints a non-announcement message to the given logs,
        with a certain verbosity. */
    public synchronized void println(String s,
        int _verbosity,
        int[] _logs) throws OutputException
        {
        for(int x=0;x<_logs.length;x++)
            println(s,_verbosity,(Log)(logs.elementAt(_logs[x])),false,false);
        }

    /** Prints a non-announcement message to the given logs,
        with a certain verbosity. */
    public synchronized void println(String s,
        int _verbosity,
        int log) throws OutputException
        {
        println(s,_verbosity,(Log)(logs.elementAt(log)),false,false);
        }

    /** Prints a non-announcement message to a given log, with a
        certain verbosity. No '\n' is printed.  */
    protected synchronized void print(String s,
        int _verbosity,
        Log log) throws OutputException
        {
        if (log.writer==null) throw new OutputException("Log with a null writer: " + log);
        if (log.verbosity >= _verbosity) return;  // don't write it
        if (verbosity >= _verbosity) return;  // don't write it
        // now write it
        log.writer.print(s);
        //if (flush) log.writer.flush();
        }

    /** Prints a non-announcement message to a given log, with a
        certain verbosity. If log==ALL_LOGS, posted to all logs.
        No '\n' is printed.  */
    public synchronized void print(String s,
        int _verbosity,
        int log) throws OutputException
        {
        if (log==ALL_LOGS) for (int x = 0; x<logs.size();x++)
                               {
                               Log l = (Log) logs.elementAt(x);
                               if (l==null) throw new OutputException("Unknown log number" + l);
                               print(s,_verbosity,l);
                               }
        else
            {
            Log l = (Log) logs.elementAt(log);
            if (l==null) throw new OutputException("Unknown log number" + l);
            print(s,_verbosity,l);
            }
        }

    /** Prints a non-announcement message to the given logs,
        with a certain verbosity. No '\n' is printed.  */
    public synchronized void print(String s,
        int _verbosity,
        int[] _logs) throws OutputException
        {
        for(int x=0;x<_logs.length;x++)
            print(s,_verbosity,_logs[x]);
        }

    /** Exits with a fatal error if the error flag has been raised. */
    public synchronized void exitIfErrors()
        {
        if (errors)
            {
            println("SYSTEM EXITING FROM ERRORS\n", V_TOTALLY_SILENT,ALL_LOGS, true);
            exitWithError();
            }
        }

    /** Clears the error flag. */
    public synchronized void clearErrors()
        {
        errors = false;
        }

    /** Clears out announcements.  Note that this will cause these
        announcements to be unavailable for reposting after a restart! */
    public synchronized void clearAnnouncements()
        {
        if (announcements!=null)
            announcements = new Vector();
        }

    public synchronized void restart() throws IOException
        {
        // restart logs, then repost announcements to them
        int ls = logs.size();
        for(int x=0;x<ls;x++)
            {
            Log l = (Log)(logs.elementAt(x));
            logs.setElementAt(l = l.restarter.restart(l),x);
            if (l.repostAnnouncementsOnRestart && store)
                {
                int as = announcements.size();
                for (int y=0;y<as;y++)
                    {
                    Announcement a = (Announcement)(announcements.elementAt(y));
                    println(a.text,a.verbosity,l,true,true);
                    }
                }
            }

        // exit with a fatal error if the errors flag is set.
        exitIfErrors();
        }

    /** Returns a compressing input stream using JZLib (http://www.jcraft.com/jzlib/).  If JZLib is not available on your system, this method will return null. */
    public static InputStream makeCompressingInputStream(InputStream in)
        {
        // to do this, we're going to use reflection.  But here's the equivalent code:
        /*
          return new com.jcraft.jzlib.ZInputStream(in);
        */
        try
            {
            return (InputStream)(Class.forName("com.jcraft.jzlib.ZInputStream").getConstructor(new Class[] { InputStream.class } ).newInstance(new Object[] { in }));
            }
        catch (Exception e) { return null; }  // failed, probably doesn't have JZLib on the system
        }

    /** Returns a compressing output stream using JZLib (http://www.jcraft.com/jzlib/).  If JZLib is not available on your system, this method will return null. */
    public static OutputStream makeCompressingOutputStream(OutputStream out)
        {
        // to do this, we're going to use reflection.  But here's the equivalent code:
        /*
          com.jcraft.jzlib.ZOutputStream stream = new com.jcraft.jzlib.ZOutputStream(out, com.jcraft.jzlib.JZlib.Z_BEST_SPEED);
          stream.setFlushMode(com.jcraft.jzlib.JZlib.Z_SYNC_FLUSH);
          return stream;
        */
        try
            {
            Class outz = Class.forName("com.jcraft.jzlib.JZlib");
            int Z_BEST_SPEED = outz.getField("Z_BEST_SPEED").getInt(null);
            int Z_SYNC_FLUSH = outz.getField("Z_SYNC_FLUSH").getInt(null);

            Class outc = Class.forName("com.jcraft.jzlib.ZOutputStream");
            Object outi = outc.getConstructor(new Class[] { OutputStream.class, Integer.TYPE }).newInstance(new Object[] { out, new Integer(Z_BEST_SPEED) });
            outc.getMethod("setFlushMode", new Class[] { Integer.TYPE }).invoke(outi, new Object[] { new Integer(Z_SYNC_FLUSH) });
            return (OutputStream) outi;
            }
        catch (Exception e) { return null; } // failed, probably doesn't have JZLib on the system
        }

    }


text:
import os
import sys
import time

import pytest
from daethon import Daemon

class TDaemon(Daemon):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        with open('testing_daemon', 'w') as f:
            f.write('inited')

    def run(self):
        time.sleep(1)
        with open('testing_daemon', 'w') as f:
            f.write('finished')

def file_contains(path, s):
    with open(path) as f:
        return f.read() == s

def control_daemon(action):
    os.system(' '.join((sys.executable, __file__, action)))

@pytest.fixture
def context():
    control_daemon('start')
    time.sleep(0.5)
    yield
    if os.path.exists('testing_daemon.pid'):
        control_daemon('stop')
    time.sleep(0.5)
    os.system('rm testing_daemon*')  # clean up files if necessary

def test_daemon_can_start(context):
    assert os.path.exists('testing_daemon.pid')
    assert file_contains('testing_daemon', 'inited')

def test_daemon_can_stop(context):
    control_daemon('stop')
    time.sleep(0.5)
    assert not os.path.exists('testing_daemon.pid')
    assert file_contains('testing_daemon', 'inited')

def test_daemon_can_finish(context):
    time.sleep(1)
    assert not os.path.exists('testing_daemon.pid')
    assert file_contains('testing_daemon', 'finished')

def test_daemon_can_restart(context):
    with open('testing_daemon.pid') as f:
        pid1 = f.read()
    time.sleep(0.5)
    control_daemon('restart')
    time.sleep(0.5)
    with open('testing_daemon.pid') as f:
        pid2 = f.read()
    assert pid1 != pid2

if __name__ == '__main__':
    if len(sys.argv) == 2:
        arg = sys.argv[1]
        if arg in ('start', 'stop', 'restart'):
            d = TDaemon('testing_daemon.pid', verbose=0)
            getattr(d, arg)()
    else:
        pytest.main()


text:
@interface MarvellBroadcast_SSID_Password()<NSNetServiceBrowserDelegate>

{
    //marvell
    NSTimer *timer;
    NSTimer *timerMdns;
    int TimerCount;
    char ssid[33];
    int Mode;
    unsigned char bssid[6];
    unsigned char preamble[6];
    char passphrase[64];
    int passLen;
    int passLength;
    unsigned int ssidLength;
    int invalidKey;
    int invalidPassphrase;
    unsigned long passCRC;
    unsigned long ssidCRC;
    NSInteger _state;
    NSInteger _substate;

    Byte customData[16];
    int customDataLen;
    unsigned long customDataCRC;
    int encryptedCustomDataLen;
    Byte encryptedCustomData[16];
    int timerCount;
    int flag;
    //marvell

}

@property(nonatomic,strong)NSString *currentssid;//ssid
@property(strong,nonatomic)NSString  *wifiPassword;//wifi密码

@end
@implementation MarvellBroadcast_SSID_Password

- (void)startBroadcast_SSID:(NSString *)currentssid
                   Password:(NSString *)password
{
    flag=1;
    self.wifiPassword=password;
    self.currentssid=currentssid;
    [self xmitterTaskv2];
}

-(void)stopBroadcast
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(xmitterTaskv2) object:nil];
    if ([timer isValid]) {
        [timer invalidate];
        timer = nil;
    }
    if ([timerMdns isValid]) {
        [timerMdns invalidate];
        timerMdns = nil;
    }

}
-(void) mdnsFound
{
    timerCount--;
    if (!timerCount) {
        [timerMdns invalidate];
        timerMdns = nil;
        [self performSelector:@selector(xmitterTaskv2) withObject:nil afterDelay:2];

    }
}
-(void)xmitterTaskv2
{
    [self currentWifiSSID];
    const char *temp = [self.wifiPassword UTF8String];
    strcpy(passphrase, temp);
    passLength = (int)self.wifiPassword.length;
    passLen = passLength;
    unsigned char *str = (unsigned char *)temp;
    unsigned char *str1 = (unsigned char *)ssid;
    int i;

    passCRC = crc32(0, str, passLen);
    ssidCRC = crc32(0, str1, ssidLength);

    passCRC = passCRC & 0xffffffff;
    ssidCRC = ssidCRC & 0xffffffff;

    NSString *customDataString =nil;
    for (i = 0; i < sizeof(customData); i++)
        customData[i] = 0x00;
    if ([customDataString length] % 2) {
        customDataLen = 0;
        customDataCRC = 0;
    } else {
        customDataLen = (int)[customDataString length] / 2;
        for (int i = 0; i < [customDataString length]; i += 2) {
            NSString *word = [customDataString substringWithRange:NSMakeRange(i, 2)];
            unsigned int c;
            [[NSScanner scannerWithString:word] scanHexInt:&c];
            customData[i/2] = c;
        }
        if (customDataLen % 16 == 0) {
            encryptedCustomDataLen = customDataLen;
        } else {
            encryptedCustomDataLen = ((customDataLen / 16) + 1) * 16;
        }

        customDataCRC = crc32(0, customData, encryptedCustomDataLen);
        customDataCRC = customDataCRC & 0xffffffff;
    }
    timer=  [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(statemachinev2) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];

}
-(void)statemachinev2
{
    NSString *temp;
    if (_state == 0 && _substate == 0) {
        TimerCount++;
    }
    if (TimerCount >= 300) {
        [self queryMdnsService];
        NSLog(@"Browsing services");
        timerCount = 15;
        timerMdns =  [NSTimer scheduledTimerWithTimeInterval:1 target:self selector: @selector(mdnsFound) userInfo:nil repeats:YES];

        if ([timer isValid] && [timer isKindOfClass:[NSTimer class]]) {
            [timer invalidate];
            timer = nil;
        }
        _state = 0;
        _substate = 0;
        TimerCount = 0;
        flag = 1;
    }

    switch(_state) {
        case 0:
            if (_substate == 3) {
                _state = 1;
                _substate = 0;
            } else {
                [self xmitState0v2:_substate];
                _substate++;
            }
            break;
        case 1:

            [self xmitState1v2:_substate LengthSSID:2];
            _substate++;
            if (ssidLength % 2 == 1) {
                if (_substate * 2 == ssidLength + 5) {
                    [self xmitState1v2:_substate LengthSSID: 1];
                    _state = 2;
                    _substate = 0;
                }
            } else {
                if ((_substate - 1) * 2 == (ssidLength + 4)) {
                    _state = 2;
                    _substate = 0;
                }
            }
            break;
        case 2:
            [self xmitState2v2:_substate LengthPassphrase:2];

            _substate++;
            if (passLen % 2 == 1) {
                if (_substate * 2 == passLen + 5) {
                    [self xmitState2v2:_substate LengthPassphrase: 1];
                    _state = 3;
                    _substate = 0;
                }
            } else {
                if ((_substate - 1) * 2 == (passLen + 4)) {
                    _state = 3;
                    _substate = 0;
                }
            }
            break;
        case 3:
            [self xmitState3v2:_substate LengthCustomData:2];

            _substate++;
            if (encryptedCustomDataLen % 2 == 1) {
                if (_substate * 2 == encryptedCustomDataLen + 5) {
                    [self xmitState3v2:_substate LengthCustomData: 1];
                    _state = 0;
                    _substate = 0;
                }
            } else {
                if ((_substate - 1) * 2 == (encryptedCustomDataLen + 4)) {
                    _state = 0;
                    _substate = 0;
                }
            }
            break;

        default:
            NSLog(@"MRVL: I should not be here!");
    }
}

-(void)xmitState0v2:(int)substate
{
    int i, j, k;

    k = preamble[2  * substate];
    j = preamble[2 * substate + 1];
    i = substate | 0x78;
    [self xmitRawv2:i data: j substate: k];
}

-(void)xmitState1v2:(int)substate LengthSSID:(int)len
{
    if (substate == 0) {
        int u = 0x40;
        [self xmitRawv2:u data:ssidLength substate: ssidLength];
    } else if (substate == 1 || substate == 2) {
        int k = (int) (ssidCRC >> ((2 * (substate - 1) + 0) * 8)) & 0xff;
        int j = (int) (ssidCRC >> ((2 * (substate - 1) + 1) * 8)) & 0xff;
        int i = substate | 0x40;
        [self xmitRawv2:i data: j substate: k];
    } else {
        int u = 0x40 | substate;
        int l = (0xff & ssid[(2 * (substate - 3))]);
        int m;
        if (len == 2)
            m = (0xff & ssid[(2 * (substate - 3) + 1)]);
        else
            m = 0;
        [self xmitRawv2:u data:m substate:l];
    }
}

-(void)xmitState2v2: (int)substate LengthPassphrase:(int)len
{
    if (substate == 0) {
        int u = 0x00;
        [self xmitRawv2:u data:passLen substate: passLen];
    } else if (substate == 1 || substate == 2) {
        int k = (int) (passCRC >> ((2 * (substate - 1) + 0) * 8)) & 0xff;
        int j = (int) (passCRC >> ((2 * (substate - 1) + 1) * 8)) & 0xff;
        int i = substate;
        [self xmitRawv2:i data: j substate: k];
    } else {
        int u = substate;
        int l = (0xff & passphrase[(2 * (substate - 3))]);
        int m;
        if (len == 2)
            m = (0xff & passphrase[(2 * (substate - 3)) + 1]);
        else
            m = 0;
        [self xmitRawv2:u data:m substate:l];
    }
}

-(void)xmitState3v2:(int)substate LengthCustomData: (int)len
{
    if (substate == 0) {
        int i = 0x60;
        [self xmitRawv2:i data:customDataLen substate: customDataLen];
    } else if (substate == 1 || substate == 2) {
        int k = (int) (customDataCRC >> ((2 * (substate - 1) + 0) * 8)) & 0xff;
        int j = (int) (customDataCRC >> ((2 * (substate - 1) + 1) * 8)) & 0xff;
        int i = substate | 0x60;
        [self xmitRawv2:i data: j substate: k];
    } else {
        int u = substate | 0x60;
        int l = (0xff & encryptedCustomData[(2 * (substate - 3))]);
        int m;
        if (len == 2)
            m = (0xff & encryptedCustomData[(2 * (substate - 3)) + 1]);
        else
            m = 0;
        [self xmitRawv2:u data:m substate:l];
    }
}
-(void) xmitRawv2:(int) u data:(int) m substate:(int) l
{
    int sock;
    struct sockaddr_in addr;
    char buf = 'a';

    NSMutableString* getnamebyaddr = [NSMutableString stringWithFormat:@"239.%d.%d.%d", u, m, l];
    const char * d_addr = [getnamebyaddr UTF8String];

    if ((sock = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
        NSLog(@"ERROR: broadcastMessage - socket() failed");
        return;
    }

    bzero((char *)&addr, sizeof(struct sockaddr_in));

    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(d_addr);
    addr.sin_port        = htons(10000);

    if ((sendto(sock, &buf, sizeof(buf), 0, (struct sockaddr *) &addr, sizeof(addr))) != 1) {
        NSLog(@"Errno %d", errno);
        NSLog(@"ERROR: broadcastMessage - sendto() sent incorrect number of bytes");
        close(sock);
        return;
    }

    close(sock);
}
-(void)queryMdnsService
{
    NSNetServiceBrowser *serviceBrowser;

    serviceBrowser = [[NSNetServiceBrowser alloc] init];
    [serviceBrowser setDelegate:self];
    [serviceBrowser searchForServicesOfType:@"_ezconnect-prov._tcp" inDomain:@"local"];
}

- (void)netServiceBrowser:(NSNetServiceBrowser *)browser
           didFindService:(NSNetService *)aNetService
               moreComing:(BOOL)moreComing
{

    NSLog(@"More coming");

}

-(NSString *)currentWifiSSID
{
    // Does not work on the simulator.
    NSString *ssid_str = nil;

    NSString *bssid_str = nil;
    NSArray *testArray = [[NSArray alloc] init];
    NSArray *ifs = (id)CFBridgingRelease(CNCopySupportedInterfaces());
    NSString *temp;
    for (NSString *ifnam in ifs) {
        NSDictionary *info = (id)CFBridgingRelease(CNCopyCurrentNetworkInfo((CFStringRef)ifnam));
        NSLog(@"String %@", info);
        if (info[@"SSID"]) {
            ssid_str = info[@"SSID"];
            NSLog(@"ssid %@", ssid_str);
            for(int i = 0 ;i < [ssid_str length]; i++) {
                ssid[i] = [ssid_str characterAtIndex:i];
            }
            ssidLength = ssid_str.length;
            bssid_str = info[@"BSSID"];
            NSLog(@"bssid %@", bssid_str);
            testArray = [bssid_str componentsSeparatedByString:@":"];
            NSScanner *aScanner;
            unsigned int te;
            for (int i = 0; i < 6; i++) {
                temp = [testArray objectAtIndex:i];
                aScanner = [NSScanner scannerWithString:temp];
                [aScanner scanHexInt: &te];
                bssid[i] = te;
            }

            preamble[0] = 0x45;
            preamble[1] = 0x5a;
            preamble[2] = 0x50;
            preamble[3] = 0x52;
            preamble[4] = 0x32;
            preamble[5] = 0x32;
        }
    }
    return ssid_str;
}

@end


text:
package org.eclipse.jdt.internal.ui.refactoring;

import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;

import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;

import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceDescription;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;

import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.window.Window;

import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.GlobalBuildAction;
import org.eclipse.ui.dialogs.ListDialog;

import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;

/**
 * DO NOT REMOVE, used in a product.
 * @deprecated As of 3.5, replaced by {@link org.eclipse.jdt.ui.refactoring.RefactoringSaveHelper}
 */
public class RefactoringSaveHelper {

	private boolean fFilesSaved;
	private final int fSaveMode;

	/**
	 * Save mode to save all dirty editors (always ask).
	 */
	public static final int SAVE_ALL_ALWAYS_ASK= 1;

	/**
	 * Save mode to save all dirty editors.
	 */
	public static final int SAVE_ALL= 2;

	/**
	 * Save mode to save all unknown editors, i.e. those that don't work on
	 * resources, don't use file buffers, or are otherwise suspect.
	 *
	 * Used for refactorings with participants or qualified name updating.
	 */
	public static final int SAVE_NON_JAVA_UPDATES= 3;

	/**
	 * Save mode to save only dirty editors on compilation units that are not in
	 * working copy mode.
	 *
	 * Used for refactorings without participants or qualified name updating.
	 */
	public static final int SAVE_JAVA_ONLY_UPDATES= 4;

	/**
	 * Save mode to not save save any editors.
	 */
	public static final int SAVE_NOTHING= 5;

	/**
	 * @param saveMode one of the SAVE_* constants
	 */
	public RefactoringSaveHelper(int saveMode) {
		Assert.isTrue(saveMode == SAVE_ALL_ALWAYS_ASK
				|| saveMode == SAVE_ALL
				|| saveMode == SAVE_NON_JAVA_UPDATES
				|| saveMode == SAVE_JAVA_ONLY_UPDATES
				|| saveMode == SAVE_NOTHING);
		fSaveMode= saveMode;
	}

	/**
	 * @param shell
	 * @return true if save was successful and refactoring can proceed;
	 * 		false if the refactoring must be cancelled
	 */
	public boolean saveEditors(Shell shell) {
		final IEditorPart[] dirtyEditors;
		switch (fSaveMode) {
			case SAVE_ALL_ALWAYS_ASK:
			case SAVE_ALL:
				dirtyEditors= EditorUtility.getDirtyEditors(true);
				break;

			case SAVE_NON_JAVA_UPDATES:
				dirtyEditors= EditorUtility.getDirtyEditorsToSave(false); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=175495
				break;

			case SAVE_JAVA_ONLY_UPDATES:
				dirtyEditors= EditorUtility.getDirtyEditorsToSave(false);
				break;

			case SAVE_NOTHING:
				return true;

			default:
				throw new IllegalStateException(Integer.toString(fSaveMode));
		}
		if (dirtyEditors.length == 0)
			return true;
		if (! askSaveAllDirtyEditors(shell, dirtyEditors))
			return false;
		try {
			// Save isn't cancelable.
			IWorkspace workspace= ResourcesPlugin.getWorkspace();
			IWorkspaceDescription description= workspace.getDescription();
			boolean autoBuild= description.isAutoBuilding();
			description.setAutoBuilding(false);
			workspace.setDescription(description);
			try {
				if (fSaveMode == SAVE_ALL_ALWAYS_ASK || fSaveMode == SAVE_ALL
						|| RefactoringSavePreferences.getSaveAllEditors()) {
					if (!JavaPlugin.getActiveWorkbenchWindow().getWorkbench().saveAllEditors(false))
						return false;
				} else {
					IRunnableWithProgress runnable= new IRunnableWithProgress() {
						public void run(IProgressMonitor pm) throws InterruptedException {
							int count= dirtyEditors.length;
							pm.beginTask("", count); //$NON-NLS-1$
							for (int i= 0; i < count; i++) {
								IEditorPart editor= dirtyEditors[i];
								editor.doSave(new SubProgressMonitor(pm, 1));
								if (pm.isCanceled())
									throw new InterruptedException();
							}
							pm.done();
						}
					};
					try {
						PlatformUI.getWorkbench().getProgressService().runInUI(JavaPlugin.getActiveWorkbenchWindow(), runnable, null);
					} catch (InterruptedException e) {
						return false;
					} catch (InvocationTargetException e) {
						ExceptionHandler.handle(e, shell,
								RefactoringMessages.RefactoringStarter_saving, RefactoringMessages.RefactoringStarter_unexpected_exception);
						return false;
					}
				}
				fFilesSaved= true;
			} finally {
				description.setAutoBuilding(autoBuild);
				workspace.setDescription(description);
			}
			return true;
		} catch (CoreException e) {
			ExceptionHandler.handle(e, shell,
				RefactoringMessages.RefactoringStarter_saving, RefactoringMessages.RefactoringStarter_unexpected_exception);
			return false;
		}
	}

	public void triggerBuild() {
		if (fFilesSaved && ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding()) {
			new GlobalBuildAction(JavaPlugin.getActiveWorkbenchWindow(), IncrementalProjectBuilder.INCREMENTAL_BUILD).run();
		}
	}

	private boolean askSaveAllDirtyEditors(Shell shell, IEditorPart[] dirtyEditors) {
		final boolean canSaveAutomatically= fSaveMode != SAVE_ALL_ALWAYS_ASK;
		if (canSaveAutomatically && RefactoringSavePreferences.getSaveAllEditors()) //must save everything
			return true;
		ListDialog dialog= new ListDialog(shell) {
			{
				setShellStyle(getShellStyle() | SWT.APPLICATION_MODAL);
			}
			@Override
			protected Control createDialogArea(Composite parent) {
				Composite result= (Composite) super.createDialogArea(parent);
				if (canSaveAutomatically) {
					final Button check= new Button(result, SWT.CHECK);
					check.setText(RefactoringMessages.RefactoringStarter_always_save);
					check.setSelection(RefactoringSavePreferences.getSaveAllEditors());
					check.addSelectionListener(new SelectionAdapter() {
						@Override
						public void widgetSelected(SelectionEvent e) {
							RefactoringSavePreferences.setSaveAllEditors(check.getSelection());
						}
					});
					applyDialogFont(result);
				}
				return result;
			}
		};
		dialog.setTitle(RefactoringMessages.RefactoringStarter_save_all_resources);
		dialog.setAddCancelButton(true);
		dialog.setLabelProvider(createDialogLabelProvider());
		dialog.setMessage(RefactoringMessages.RefactoringStarter_must_save);
		dialog.setContentProvider(new ArrayContentProvider());
		dialog.setInput(Arrays.asList(dirtyEditors));
		return dialog.open() == Window.OK;
	}

	public boolean hasFilesSaved() {
		return fFilesSaved;
	}

	private ILabelProvider createDialogLabelProvider() {
		return new LabelProvider() {
			@Override
			public Image getImage(Object element) {
				return ((IEditorPart) element).getTitleImage();
			}
			@Override
			public String getText(Object element) {
				return ((IEditorPart) element).getTitle();
			}
		};
	}
}


text:
const fs = require('fs');
const path = require('path');
const { createApolloFetch } = require('apollo-fetch');
const env = require('dotenv-extended').load({
  assignToProcessEnv: false,
});

const introspect = uri => {
  const fetch = createApolloFetch({ uri });
  const query = `{
    __schema {
      types {
        kind
        name
        possibleTypes {
          name
        }
      }
    }
  }`;

  return fetch({ query }).then(result => result.data);
};

introspect(env.API).then(introspection => {
  fs.writeFileSync(
    path.resolve(process.cwd(), 'introspection.json'),
    JSON.stringify(introspection)
  );
});


text:
.. kullback_leiber_divergence.rst
.. py:module:: dit.divergences.kullback_leibler_divergence

***************************
Kullback-Leibler Divergence
***************************

The Kullback-Leibler divergence, sometimes also called the *relative entropy*,
of a distribution :math:`p` from a distribution :math:`q` is defined as:

.. math::

   \DKL[p || q] = \sum_{x \in \mathcal{X}} p(x) \log_2 \frac{p(x)}{q(x)}

The Kullback-Leibler divergence quantifies the average number of *extra* bits
required to represent a distribution :math:`p` when using an arbitrary
distribution :math:`q`. This can be seen through the following identity:

.. math::

   \DKL[p || q] = \xH[p || q] - \H[p]

Where the :doc:`cross_entropy` quantifies the total cost of encoding :math:`p`
using :math:`q`, and the :doc:`../multivariate/entropy` quantifies the true,
minimum cost of encoding :math:`p`. For example, let's consider the cost of
representing a biased coin by a fair one:

.. ipython::

   In [1]: from dit.divergences import kullback_leibler_divergence

   In [2]: p = dit.Distribution(['0', '1'], [3/4, 1/4])

   In [3]: q = dit.Distribution(['0', '1'], [1/2, 1/2])

   @doctest float
   In [4]: kullback_leibler_divergence(p, q)
   Out[4]: 0.18872187554086717

That is, it costs us :math:`0.1887` bits of wasted overhead by using a
mismatched distribution.

Not a Metric
============

Although the Kullback-Leibler divergence is often used to see how "different"
two distributions are, it is not a  metric. Importantly, it is neither symmetric
nor does it obey the triangle inequality. It does, however, have the following
property:

.. math::

   \DKL[p || q] \ge 0

with equality if and only if :math:`p = q`. This makes it a `premetric
<http://en.wikipedia.org/wiki/Metric_(mathematics)#Premetrics>`_.

API
===

.. autofunction:: kullback_leibler_divergence


text:
const Command = require('../BaseCmd')
const tumblr = new (require('../../util/TumblrTools'))()

const blogUrl = 'lady-zenora.tumblr.com'

class Yaoi extends Command {
  constructor (client) {
    super(client, {
      name: 'yaoi',
      group: 'nsfw',
      memberName: 'yaoi',
      throttling: { usages: 1, duration: 10 },
      description: 'Returns a random yaoi image or gif.',
      examples: ['+yaoi'],
      nsfw: true
    })
  }

  async run (msg, args) {
    tumblr.getRandomPhoto(blogUrl).then(photo => {
      msg.channel.send(photo)
    })
  }
}

module.exports = Yaoi


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <script>var QUnit = parent.QUnit</script>
    <script src="testinit.js"></script>
    <script src="../../dist/sizzle.js"></script>
</head>
<body>
<script>
    var doc = parent.document,
            unframed = [ doc.getElementById("qunit-fixture"), doc.body, doc.documentElement ],
            framed = Sizzle("*");

    window.parent.iframeCallback(
            Sizzle.uniqueSort(unframed.concat(framed)),
            framed.concat(unframed.reverse()),
            "Mixed array was sorted correctly"
    );
</script>
</body>
</html>


text:
/*
 */
/* #define _POSIX_SOURCE /* defined when source is waited tobe POSIX-compliant */
/* #define _SYSV_SOURCE /* defined when source is System V */
/* #ifdef __STDC__ /* used to determine if using an ANSI compiler */

#ifndef INCaparserh
#define INCaparserh

#include <wdLib.h>
#include <semLib.h>
#include "lc.h"

/* ------------- Make C header file C++ compliant ------------------- */
#ifdef __cplusplus
extern "C" {
#endif

/* Table Header Structure */
/* The entry element the first in a list. There are four for 	*/
/* longword alignment.						*/

extern Acqparams acqReferenceData;
extern autodata *autoDP;

typedef struct {
	int	num_entries;
	int	size_entry;
	int	mod_factor;
	char	entry[4];
} TBL_OBJ;

typedef TBL_OBJ *TBL_ID;

#define EXP_BASE_NAME_SIZE  32

typedef struct {
        int parser_cmd;
	unsigned long NumAcodes;
	unsigned long NumTables;
	unsigned long startFID;
        int      spare1;
	char AcqBaseBufName[EXP_BASE_NAME_SIZE];
	} PARSER_MSG;

/* Experiment Data Structure */
/* The table_ptr is the first entry in a list. */

typedef struct {
   	char		id[EXP_BASE_NAME_SIZE];
	int		interactive_flag;
	int		num_acode_sets;
	int		cur_acode_set;
	unsigned int	*cur_acode_base;
	unsigned int	*cur_jump_base;
	int		cur_acode_size;
        Acqparams       *pLcStruct;
        autodata        *pAutodataStruct;
	unsigned int	*cur_rtvar_base;
	int		cur_rtvar_size;
	unsigned long 	cur_scan_data_adr;
	unsigned long 	prev_scan_data_adr;
	long		initial_scan_num;
	long		tag2snd;
	int		num_tables;
        int		dspSrcBuf;
        int		dspDstBuf;
#ifdef VXWORKS
	TBL_ID		*table_ptr;
	SEM_ID		pAcodeControl;     /* Mutex Semaphore for Acode/Table updt */
	SEM_ID		pSemParseUpdt;     /* Binary Semaphore  for Acode/Table updt */
	SEM_ID		pSemParseSuspend;  /* 4 Sync Ops needing fifo (AUTOLOCK & AUTOSHIM) */
	WDOG_ID 	wdFifoStart;
#endif
} ACODE_OBJ;

typedef ACODE_OBJ *ACODE_ID;

/* defines for interactive_flag in ACODE_OBJ  */
#define ACQI_INTERACTIVE 1
#define ACQ_AUTOGAIN	 2

/* ---   Parse Ahead Constants --- */
#define PARSE_AHEAD_COUNT 64  /* 32 increased to 64 to help EPI exp on DDR */
#define PARSE_AHEAD_ITR_LOCATION 48  /* (PARSE_AHEAD_COUNT/2) */
#define PARSE_AHEAD_ITR_INTERVAL 4  /*  Interval to add interrupts */

/*

/* --------- ANSI/C++ compliant function prototypes --------------- */

#if defined(__STDC__) || defined(__cplusplus)

ACODE_OBJ *acodeCreate(char *expname);

unsigned int *getAcodeSet(char *expname, int acode_index, unsigned int *size, int timeVal);
int getPattern(int pat_index,int* *patternList,int *patternSize);
int *TableElementPntrGet(int table_index, int element, int *errorcode, char *emssg);
/* int sendCntrlFifoList(int* list, int size, int ntimes , int rem, int startfifo); */
int sendCntrlFifoList(int* list, int size, int ntimes);
int writeCntrlFifoWord(int word);
int writeCntrlFifoBuf(int *list, int size);
int flushCntrlFifoRemainingWords();
int startCntrlFifo();
void wait4CntrlFifoStop();
int rmAcodeSet(char *expname, int cur_acode_set);
int markAcodeSetDone(char *expname, int cur_acode_set);

void acodeDelete(ACODE_ID pAcodeId);
void acodeStartFifoWD(ACODE_ID pAcodeId);
void acodeCancelFifoWD(ACODE_ID pAcodeId);
unsigned short *getWFSet(char *expname);

#else
/* --------- NON-ANSI/C++ prototypes ------------  */

ACODE_OBJ *acodeCreate();
void acodeDelete();
void acodeStartFifoWD();
void acodeCancelFifoWD();
unsigned short *getWFSet();

#endif

#ifdef __cplusplus
}
#endif

#endif


text:
package com.google.cloud.tools.managedcloudsdk.command;

import com.google.cloud.tools.managedcloudsdk.process.AsyncStreamHandler;
import java.util.concurrent.Future;

/** An {@link AsyncStreamHandler} that saves the output. */
interface AsyncStreamSaver extends AsyncStreamHandler {

  /** Returns a future to a fully saved process inputStream. */
  Future<String> getResult();
}


text:
module TrophyHelper
 def display_trophy_link(user, noid)
   trophyclass = "trophy-off"
   trophytitle= "Highlight File on Profile"
   if user.trophies.map(&:generic_file_id).include? noid
     trophyclass = "trophy-on"
   end

   return link_to raw("<i class='#{trophyclass} icon-trophy'></i> #{trophytitle}"),"", :class=> 'trophy-class', :title => trophytitle, :id => noid,  :remote=>true # link to trophy
 end
end


text:
'use strict';

const Backbone = require('backbone');
const _ = require('underscore');

const chai = require('chai');
const expect = chai.expect;

const ParentModel = require('../../src/ParentModel');

describe('ParentModel', function() {

    context('when using as extended Backbone.Model', function() {
        beforeEach(function() {
            this.model = new ParentModel();
        });

        it('should contain additional ParentModel functions', function() {
            const prototype = this.model.__proto__;
            expect(prototype.createChildModel).to.exist;
            expect(prototype.createChildCollection).to.exist;
            expect(prototype.getChild).to.exist;
            expect(prototype.setChild).to.exist;
            expect(prototype.getAttributes).to.exist;
        });
    });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-parent</artifactId>
        <version>2.8-SNAPSHOT</version>
        <relativePath>../../parent</relativePath>
    </parent>

  <groupId>org.apache.camel</groupId>
  <artifactId>camel-servlet</artifactId>
  <packaging>bundle</packaging>
  <name>Camel :: Servlet</name>
  <description>Camel servlet transport support</description>

  <properties>
      <camel.osgi.export.pkg>org.apache.camel.component.servlet.*</camel.osgi.export.pkg>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.apache.felix</groupId>
      <artifactId>org.osgi.compendium</artifactId>
      <version>1.2.0</version>
      <scope>provided</scope>
      <exclusions>
        <exclusion>
          <groupId>org.apache.felix</groupId>
          <artifactId>javax.servlet</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.apache.felix</groupId>
          <artifactId>org.osgi.foundation</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-http</artifactId>
      <exclusions>
         <exclusion>
      	   <groupId>org.apache.geronimo.specs</groupId>
           <artifactId>geronimo-servlet_2.4_spec</artifactId>
         </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>org.apache.geronimo.specs</groupId>
      <artifactId>geronimo-servlet_2.4_spec</artifactId>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>httpunit</groupId>
      <artifactId>httpunit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
          <forkMode>pertest</forkMode>
          <childDelegation>false</childDelegation>
          <useFile>true</useFile>
          <includes>
            <include>**/*Test.*</include>
          </includes>
        </configuration>
      </plugin>
     </plugins>
   </build>

</project>


text:
package org.ensime.core.debug

import java.io.File

import akka.actor._
import akka.event.LoggingReceive
import com.sun.jdi._
import com.sun.jdi.event._
import com.sun.jdi.request.StepRequest
import org.ensime.api._

import scala.collection.mutable

case class DMClassPrepareEvent(prepareEvent: ClassPrepareEvent, eventSet: EventSet)

object DebugManager {
  def apply(
    broadcaster: ActorRef
  )(
    implicit
    config: EnsimeConfig
  ): Props = Props(new DebugManager(broadcaster, config))
}

class DebugManager(
    broadcaster: ActorRef,
    config: EnsimeConfig
) extends Actor with ActorLogging {

  // TODO this is built once on startup - probably makes sense for it to be done each time a debug vm is created
  private var sourceMap = new SourceMap(config)

  private var activeBreakpoints = Set[Breakpoint]()

  // These vals should be vars to make it more obvious that we are managing state
  // Map unqualified file names to sets of fully qualified paths.
  private val pendingBreaksBySourceName =
    new mutable.HashMap[String, mutable.HashSet[Breakpoint]].withDefault { _ => new mutable.HashSet }
  private var maybeVM: Option[VM] = None

  def tryPendingBreaksForSourcename(sourceName: String): Unit = {
    for (breaks <- pendingBreaksBySourceName.get(sourceName)) {
      val toTry = mutable.HashSet() ++ breaks
      for (bp <- toTry) {
        setBreakpoint(bp.file, bp.line)
      }
    }
  }

  def setBreakpoint(file: File, line: Int): Boolean = {
    val applied = maybeVM.exists { vm => vm.setBreakpoint(file, line) }
    if (applied) {
      activeBreakpoints += Breakpoint(file, line)
      true
    } else {
      addPendingBreakpoint(Breakpoint(file, line))
      false
    }
  }

  def clearBreakpoint(file: File, line: Int): Unit = {
    val clearBp = Breakpoint(file, line)
    for (bps <- pendingBreaksBySourceName.get(file.getName)) {
      bps.retain { _ != clearBp }
    }
    val toRemove = activeBreakpoints.filter { _ == clearBp }
    for (vm <- maybeVM) {
      vm.clearBreakpoints(toRemove)
    }
    activeBreakpoints --= toRemove
  }

  def clearAllBreakpoints(): Unit = {
    pendingBreaksBySourceName.clear()
    activeBreakpoints = Set.empty
    for (vm <- maybeVM) {
      vm.clearAllBreakpoints()
    }
  }

  def moveActiveBreaksToPending(): Unit = {
    activeBreakpoints.foreach(addPendingBreakpoint)
    activeBreakpoints = Set.empty
  }

  def addPendingBreakpoint(bp: Breakpoint): Unit = {
    val file = bp.file
    val breaks = pendingBreaksBySourceName.getOrElse(file.getName, mutable.HashSet())
    breaks.add(bp)
    pendingBreaksBySourceName(file.getName) = breaks
  }

  def pendingBreakpoints: List[Breakpoint] = {
    pendingBreaksBySourceName.values.flatten.toList
  }

  def disconnectDebugVM(): Unit = {
    withVM { vm =>
      vm.dispose()
    }
    moveActiveBreaksToPending()
    maybeVM = None
    broadcaster ! DebugVMDisconnectEvent
  }

  def vmOptions(): List[String] = List(
    "-classpath",
    config.runtimeClasspath.mkString("\"", File.pathSeparator, "\"")
  ) ++ config.debugVMArgs

  def withVM[T](action: (VM => T)): Option[T] = {
    maybeVM.synchronized {
      try {
        for (vm <- maybeVM) yield {
          action(vm)
        }
      } catch {
        case e: VMDisconnectedException =>
          log.error(e, "Attempted interaction with disconnected VM:")
          disconnectDebugVM()
          None
        case e: Throwable =>
          log.error(e, "Exception thrown whilst handling vm action")
          None
      }
    }
  }

  private def handleRPCWithVM()(action: (VM => RpcResponse)): RpcResponse = {
    withVM { vm =>
      action(vm)
    }.getOrElse {
      log.warning("Could not access debug VM.")
      FalseResponse
    }
  }

  private def handleRPCWithVMAndThread(threadId: DebugThreadId)(action: ((VM, ThreadReference) => RpcResponse)): RpcResponse = {
    withVM { vm =>
      (for (thread <- vm.threadById(threadId)) yield {
        action(vm, thread)
      }).getOrElse {
        log.warning(s"Could not find thread: $threadId")
        FalseResponse
      }
    }.getOrElse {
      log.warning("Could not access debug VM")
      FalseResponse
    }
  }

  def bgMessage(msg: String): Unit = {
    broadcaster ! SendBackgroundMessageEvent(msg)
  }

  // the JVM should have its own actor
  def receive: Receive = LoggingReceive { fromJvm orElse fromUser }

  def fromJvm: Receive = {
    case DebuggerShutdownEvent =>
      withVM { vm =>
        vm.dispose()
      }
      context.stop(self)

    case DMClassPrepareEvent(prepareEvent, eventSet) =>
      withVM { vm =>
        val refType = prepareEvent.referenceType()
        vm.typeAdded(refType)
        tryPendingBreaksForSourcename(refType.sourceName())
      }
      eventSet.resume()

    case e: VMStartEvent =>
      withVM { vm =>
        vm.initLocationMap()
        // by default we will attempt to start in suspended mode so we can attach breakpoints etc
        vm.resume()
      }
      broadcaster ! DebugVMStartEvent
    case e: VMDisconnectedException =>
      disconnectDebugVM()
    case e: VMDeathEvent =>
      disconnectDebugVM()
    case e: VMDisconnectEvent =>
      disconnectDebugVM()
    case e: StepEvent =>
      (for (pos <- sourceMap.locToPos(e.location())) yield {
        broadcaster ! DebugStepEvent(DebugThreadId(e.thread().uniqueID()), e.thread().name, pos.file, pos.line)
      }) getOrElse {
        val loc = e.location()
        log.warning(s"Step position not found: ${loc.sourceName()} : ${loc.lineNumber()}")
      }
    case e: BreakpointEvent =>
      (for (pos <- sourceMap.locToPos(e.location())) yield {
        broadcaster ! DebugBreakEvent(DebugThreadId(e.thread().uniqueID()), e.thread().name, pos.file, pos.line)
      }) getOrElse {
        val loc = e.location()
        log.warning(s"Break position not found: ${loc.sourceName()} : ${loc.lineNumber()}")
      }
    case e: ExceptionEvent =>
      withVM { vm => vm.remember(e.exception) }

      val pos = if (e.catchLocation() != null) sourceMap.locToPos(e.catchLocation()) else None
      broadcaster ! DebugExceptionEvent(
        e.exception.uniqueID(),
        DebugThreadId(e.thread().uniqueID()),
        e.thread().name,
        pos.map(_.file),
        pos.map(_.line)
      )
    case e: ThreadDeathEvent =>
      broadcaster ! DebugThreadDeathEvent(DebugThreadId(e.thread().uniqueID()))
    case e: ThreadStartEvent =>
      broadcaster ! DebugThreadStartEvent(DebugThreadId(e.thread().uniqueID()))
    case e: AccessWatchpointEvent =>
    case e: ClassPrepareEvent =>
      withVM { vm =>
        log.info(s"ClassPrepareEvent: ${e.referenceType().name()}")
      }
    case e: ClassUnloadEvent =>
    case e: MethodEntryEvent =>
    case e: MethodExitEvent =>
  }

  def disposeCurrentVM(): Unit = {
    withVM { vm =>
      vm.dispose()
    }
  }
  def handleStartupFailure(e: Exception): RpcResponse = {
    maybeVM = None
    log.error(e, "Failure during VM startup")
    val message = e.toString
    DebugVmError(1, message)
  }

  def handleDebugStartReq(commandLine: String): RpcResponse = {
    disposeCurrentVM()
    try {
      val vm = new VM(VmStart(commandLine), vmOptions(), self, broadcaster, sourceMap)
      maybeVM = Some(vm)
      vm.start()
      DebugVmSuccess()
    } catch {
      case e: Exception =>
        log.error(e, "Could not start VM")
        handleStartupFailure(e)
    }
  }

  def handleDebugAttachReq(hostname: String, port: String): RpcResponse = {
    disposeCurrentVM()
    try {
      val vm = new VM(VmAttach(hostname, port), vmOptions(), self, broadcaster, sourceMap)
      maybeVM = Some(vm)
      vm.start()
      DebugVmSuccess()
    } catch {
      case e: Exception =>
        log.error(e, "Could not attach VM")
        handleStartupFailure(e)
    }
  }

  def fromUser: Receive = {
    case DebugStartReq(commandLine: String) =>
      sender ! handleDebugStartReq(commandLine)
    case DebugAttachReq(hostname, port) ⇒
      sender ! handleDebugAttachReq(hostname, port)
    case DebugActiveVmReq =>
      sender ! handleRPCWithVM() { vm =>
        TrueResponse
      }
    case DebugStopReq =>
      sender ! handleRPCWithVM() { vm =>
        if (vm.mode.shouldExit) {
          vm.exit(0)
        }
        vm.dispose()
        TrueResponse
      }
    case DebugRunReq =>
      sender ! handleRPCWithVM() { vm =>
        vm.resume()
        TrueResponse
      }
    case DebugContinueReq(threadId) =>
      sender ! handleRPCWithVMAndThread(threadId) {
        (vm, thread) =>
          vm.resume()
          TrueResponse
      }
    case DebugSetBreakReq(file, line: Int) =>
      if (!setBreakpoint(file, line)) {
        bgMessage("Location not loaded. Set pending breakpoint.")
      }
      sender ! TrueResponse
    case DebugClearBreakReq(file, line: Int) =>
      clearBreakpoint(file, line)
      sender ! TrueResponse

    case DebugClearAllBreaksReq =>
      clearAllBreakpoints()
      sender ! TrueResponse

    case DebugListBreakpointsReq =>
      val breaks = BreakpointList(activeBreakpoints.toList, pendingBreakpoints)
      sender ! breaks

    case DebugNextReq(threadId: DebugThreadId) =>
      sender ! handleRPCWithVMAndThread(threadId) {
        (vm, thread) =>
          vm.newStepRequest(
            thread,
            StepRequest.STEP_LINE,
            StepRequest.STEP_OVER
          )
          TrueResponse
      }

    case DebugStepReq(threadId: DebugThreadId) =>
      sender ! handleRPCWithVMAndThread(threadId) {
        (vm, thread) =>
          vm.newStepRequest(
            thread,
            StepRequest.STEP_LINE,
            StepRequest.STEP_INTO
          )
          TrueResponse
      }

    case DebugStepOutReq(threadId: DebugThreadId) =>
      sender ! handleRPCWithVMAndThread(threadId) {
        (vm, thread) =>
          vm.newStepRequest(
            thread,
            StepRequest.STEP_LINE,
            StepRequest.STEP_OUT
          )
          TrueResponse
      }

    case DebugLocateNameReq(threadId: DebugThreadId, name: String) =>
      sender ! handleRPCWithVMAndThread(threadId) {
        (vm, thread) =>
          vm.locationForName(thread, name).getOrElse(FalseResponse)
      }
    case DebugBacktraceReq(threadId: DebugThreadId, index: Int, count: Int) =>
      sender ! handleRPCWithVMAndThread(threadId) { (vm, thread) =>
        vm.backtrace(thread, index, count)
      }
    case DebugValueReq(location) =>
      sender ! handleRPCWithVM() { vm =>
        vm.debugValueAtLocation(location).getOrElse(FalseResponse)
      }
    case DebugToStringReq(threadId, location) =>
      sender ! handleRPCWithVM() { vm =>
        vm.debugValueAtLocationToString(threadId, location) match {
          case Some(strValue) => StringResponse(strValue)
          case None => FalseResponse
        }
      }

    case DebugSetValueReq(location, newValue) =>
      sender ! handleRPCWithVM() { vm =>
        location match {
          case DebugStackSlot(threadId, frame, offset) => vm.threadById(threadId) match {
            case Some(thread) =>
              val status = vm.setStackVar(thread, frame, offset, newValue)
              status match {
                case true =>
                  TrueResponse
                case false =>
                  FalseResponse
              }
            case _ =>
              log.error(s"Unknown thread $threadId for debug-set-value")
              FalseResponse
          }
          case unknown =>
            log.error(s"Unsupported location type for debug-set-value.: $unknown")
            FalseResponse
        }
      }
  }
}


text:
import {Component} from '@angular/core';
import {ArticleService} from './article.service';

@Component({
  selector: 'default-view',
  template: `

Default view

    <ng-content></ng-content>
  `,
  providers: [ArticleService]
})
export class DefaultViewComponent {}


text:
test-collection
===============

performance and integration tests


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InvokeIR.PowerForensics.NTFS
{
    #region EAInformationClass

    class EAInformation : Attr
    {
        internal struct ATTR_EA_INFORMATION
        {
            internal AttrHeader.ATTR_HEADER_RESIDENT header;
            internal ushort PackedSize;
            internal ushort EACount;
            internal uint UnpackedSize;

            internal ATTR_EA_INFORMATION(byte[] bytes)
            {
                header = new AttrHeader.ATTR_HEADER_RESIDENT(bytes.Take(24).ToArray());
                PackedSize = BitConverter.ToUInt16(bytes, 24);
                EACount = BitConverter.ToUInt16(bytes, 26);
                UnpackedSize = BitConverter.ToUInt32(bytes, 28);
            }
        }

        #region Properties

        public readonly ushort PackedSize;
        public readonly ushort EACount;
        public readonly uint UnpackedSize;

        #endregion Properties

        #region Constructors

        internal EAInformation(byte[] bytes, string attrName)
        {
            ATTR_EA_INFORMATION ea = new ATTR_EA_INFORMATION(bytes);

            Name = Enum.GetName(typeof(ATTR_TYPE), ea.header.commonHeader.ATTRType);
            NameString = attrName;
            NonResident = ea.header.commonHeader.NonResident;
            AttributeId = ea.header.commonHeader.Id;
            PackedSize = ea.PackedSize;
            EACount = ea.EACount;
            UnpackedSize = ea.UnpackedSize;
        }

        #endregion Constructors
    }

    #endregion EAInformationClass
}


text:
package com.lipingxin.app.coolweather.activity;

import com.lipingxin.app.coolweather.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

/*
 * @author: pingxinli
 * @email: pingxinli@hengtiansoft.com
 * @version: 2015年8月6日 下午3:24:50
 * @description:
*/
public class AboutUsActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.about_us);
	}

}


text:
package com.webcohesion.enunciate.examples.jaxwsrijersey.genealogy.data;

import java.net.URI;
import java.util.List;

/**
 * Extension for name.
 *
 * @author Ryan Heaton
 */
public class NameExt extends Name {

  private List<URI> links;

  public List<URI> getLinks() {
    return links;
  }

  public void setLinks(List<URI> links) {
    this.links = links;
  }
}


text:
module TwentyfourSevenOffice
  module Services
    class ApiOperation::ResultTransformer
      extend TwentyfourSevenOffice::Utils

      def self.transform_result(result)
        return result unless result.is_a?(Hash)

        data_type_name = result.keys.first
        output_data_type = resolve_output_data_type(data_type_name)

        if output_data_type
          data = result[data_type_name]

          if data.is_a?(Array)
            data.map do |d|
              output_data_type.new(rewrite_values_for_array_attributes(output_data_type, d))
            end
          else
            output_data_type.new(rewrite_values_for_array_attributes(output_data_type, data))
          end
        else
          result
        end
      end

      private

      def self.resolve_output_data_type(name_sym)
        TwentyfourSevenOffice::DataTypes.const_get(camelcase(name_sym))
      end

      # Rewrites the contents of the given hash to be compatible with
      # Virtus array attribute coercion. Example:
      #
      # {
      #   ...
      #   :maps => {
      #     :company_map => {:map_type => 1, :external_id => 5, :company_id => 10}
      #   }
      #   ...
      # }
      #
      # becomes
      #
      # {
      #   ...
      #   :maps => [{:map_type => 1, :external_id => 5, :company_id => 10}]
      #   ...
      # }
      #
      # Rewriting only happens for hash values where the matching
      # output data type attribute primitive is an Array (e.g. Company#maps).
      # Elements that are the only child of a parent element will be converted
      # to a hash by Savon. This method will however always wrap values in an Array.
      #
      # Bit of a hack, to be honest.
      def self.rewrite_values_for_array_attributes(output_data_type, data)
        return data unless output_data_type < TwentyfourSevenOffice::DataTypes::DataType

        output_data_type.attribute_set.each do |attr|
          # Should rewrite hash?
          if attr.primitive == Array && data[attr.name]
            # Get value to rewrite. For the 24SevenOffice API, there will
            # never be more than 1 key/value pair.
            values = data[attr.name].values.first
            # Wrap value in array if necessary
            values = values.is_a?(Array) ? values : [values]
            # Write the new hash value. The hash key that corresponds to
            # the type name has now been removed (:company_map in the example).
            data[attr.name] = values
          end
        end

        data
      end
    end
  end
end


text:
'use strict';

const common = require('../common');
const ArrayStream = require('../common/arraystream');
const repl = require('repl');
const DEFAULT_MAX_LISTENERS = require('events').defaultMaxListeners;

ArrayStream.prototype.write = () => {};

const putIn = new ArrayStream();
const testMe = repl.start('', putIn);

// https://github.com/nodejs/node/issues/18284
// Tab-completion should not repeatedly add the
// `Runtime.executionContextCreated` listener
process.on('warning', common.mustNotCall());

putIn.run(['async function test() {']);
for (let i = 0; i < DEFAULT_MAX_LISTENERS; i++) {
  testMe.complete('await Promise.resolve()', () => {});
}


text:
layout:     post
title:      "iOS 7 sound recording"
date:       2014-02-07 12:09:00
author:     "Daniel Vela"
header-img: "img/post-bg-01.jpg"
locale:       en
lang-ref:   grabacion-audio-ios7
---

To record sound with iOS 7 use **AVAudioRecorder** class.

Before stert the recording with the **record** method call the **prepareToRecord** method. Both methods return a boolean like return value.
It's important to check that returns **YES**. In order case show an error because the recording won't start.

## Creation and configuration of AVAudioRecorder

The object **AVAudioRecorder** requires for its initialization an object of type **NSDictionary** with the following values:

{% highlight objc %}
@{AVFormatIDKey:@(kAudioFormatMPEG4AAC),
  AVSampleRateKey:@44100.0,
  AVNumberOfChannelsKey:@2,
  AVEncoderAudioQualityKey:@(AVAudioQualityMin),
  AVEncoderBitRateKey:@16,
};
{% endhighlight %}

Also create this object **NSDictionary** is needed to make the previous step: create an **AVAudioSesion** object.

Since iOS 7 is needed to create an *AVAudioSession** object before the creation of **AVAudioRecorder*8. In other case recording won't start.

![Audio recording session]({{ site.url }}/assets/tumblr_inline_n0mhtxb2Q31qjhbuu.png)

{% highlight objc %}
Code sample

//
//  ViewController.m
//  NoiseAlertPrototype
//
//  Created by Daniel Vela on 30/01/14.
//  Copyright (c) 2014 veladan. All rights reserved.
//

#import "ViewController.h"

const float min_level = 20.0f;
const float max_level = 160.0f;

@interface ViewController ()

@end

@implementation ViewController

-(AVAudioRecorder*)recorder {
    if (_recorder == nil) {
        NSURL* url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
                                                             inDomains:NSUserDomainMask]
                      lastObject];
        url = [url URLByAppendingPathComponent:@"record.aac"];
        NSDictionary* settings = @{AVFormatIDKey:@(kAudioFormatMPEG4AAC),
                                   AVSampleRateKey:@44100.0,
                                   AVNumberOfChannelsKey:@2,
                                   AVEncoderAudioQualityKey:@(AVAudioQualityMin),
                                   AVEncoderBitRateKey:@16,

                                   };
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        [audioSession setCategory:AVAudioSessionCategoryRecord
                            error:nil];
        NSError* error;
        _recorder = [[AVAudioRecorder alloc] initWithURL:url
                                                    settings:settings
                                                       error:&error];
        if (error) {
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Error creating audio recorder"
                                                            message:[error description]
                                                           delegate:nil
                                                  cancelButtonTitle:@"cancel"
                                                  otherButtonTitles:nil];
            [alert show];
        }
        _recorder.meteringEnabled = YES;

    }
    return _recorder;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self setStop];
    [self startTakingNoiseSamples];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

float adjustNoiseLevel(float value) {
    if (value > 0) value = 0;
    value = max_level + value;
    value = value / max_level;
    return value;
}

- (void)setAverageLevelValue:(float)value {
    value = adjustNoiseLevel(value);
    [self.averageLevel setProgress:value];
}

- (void)setPeakLevelValue:(float)value  {
    value = adjustNoiseLevel(value);
    [self.peakLevel setProgress:value];
}

- (void)startTakingNoiseSamples {

    if ([self.recorder isRecording] == YES) {
        [self.recorder updateMeters];
        float averagePower = [self.recorder averagePowerForChannel:0];
        float peakPower = [self.recorder peakPowerForChannel:0];
        [self setAverageLevelValue:averagePower];
        [self setPeakLevelValue:peakPower];
    }

    [self performSelector:@selector(startTakingNoiseSamples)
               withObject:nil
               afterDelay:0.05f];
}

- (void)startRecording {
    [self setStart];
    BOOL prepared = [self.recorder prepareToRecord];
    if (prepared == NO) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Error creating audio recorder"
                                                        message:@"no preparado"
                                                       delegate:nil
                                              cancelButtonTitle:@"cancel"
                                              otherButtonTitles:nil];
        [alert show];

    }
    BOOL started = [self.recorder record];
    if (started == NO) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Error starting recording"
                                                        message:@"no preparado"
                                                       delegate:nil
                                              cancelButtonTitle:@"cancel"
                                              otherButtonTitles:nil];
        [alert show];

    }

}

- (void)stopRecording {
    [self setStop];
    [self.recorder stop];
}

- (void)setStop {
    [self.startStopButton setTitle:@"Start" forState:UIControlStateNormal];
    [self.startStopButton addTarget:self
                          action:@selector(startRecording)
                forControlEvents:UIControlEventTouchUpInside];
}

- (void)setStart {
    [self.startStopButton setTitle:@"Stop" forState:UIControlStateNormal];
    [self.startStopButton addTarget:self
                          action:@selector(stopRecording)
                forControlEvents:UIControlEventTouchUpInside];
}

@end
{% endhighlight %}


text:
<?php

namespace OpenConext\EngineBlockBundle\Exception;

use LogicException as CoreLogicException;

final class LogicException extends CoreLogicException
{
}


text:
<?php

namespace Silex\Provider;

use Silex\Application;
use Silex\ServiceProviderInterface;
use Silex\Translator;
use Symfony\Component\Translation\MessageSelector;
use Symfony\Component\Translation\Loader\ArrayLoader;
use Symfony\Component\Translation\Loader\XliffFileLoader;

/**
 * Symfony Translation component Provider.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class TranslationServiceProvider implements ServiceProviderInterface
{
    public function register(Application $app)
    {
        $app['translator'] = $app->share(function ($app) {
            $translator = new Translator($app, $app['translator.message_selector'], $app['translator.cache_dir'], $app['debug']);

            // Handle deprecated 'locale_fallback'
            if (isset($app['locale_fallback'])) {
                $app['locale_fallbacks'] = (array) $app['locale_fallback'];
            }

            $translator->setFallbackLocales($app['locale_fallbacks']);

            $translator->addLoader('array', new ArrayLoader());
            $translator->addLoader('xliff', new XliffFileLoader());

            // Register default resources
            foreach ($app['translator.resources'] as $resource) {
                $translator->addResource($resource[0], $resource[1], $resource[2], $resource[3]);
            }

            foreach ($app['translator.domains'] as $domain => $data) {
                foreach ($data as $locale => $messages) {
                    $translator->addResource('array', $messages, $locale, $domain);
                }
            }

            return $translator;
        });

        $app['translator.resources'] = function ($app) {
            return array();
        };

        $app['translator.message_selector'] = $app->share(function () {
            return new MessageSelector();
        });

        $app['translator.domains'] = array();
        $app['locale_fallbacks'] = array('en');
        $app['translator.cache_dir'] = null;
    }

    public function boot(Application $app)
    {
    }
}


text:
using System;
using System.Data;
using Restful.Data.Dapper;

namespace System.Data
{
    public static class IDataReaderExtensions
    {
        /// <summary>
        /// 获取 DeserializerState 对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="reader"></param>
        /// <returns></returns>
        public static SqlMapper.DeserializerState GetDeserializerState<T>( this IDataReader reader )
        {
            int hash = SqlMapper.GetColumnHash( reader );

            return new SqlMapper.DeserializerState( hash, SqlMapper.GetDeserializer( typeof( T ), reader, 0, -1, false ) );
        }
    }
}


text:
// Copyright (c) 2016-2020 Alexander Ong
// See LICENSE in project root for license information.

using UnityEngine;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.IO;
using MoonscraperChartEditor.Song;

// Purposefully generating as much garbage as possible, purely to test potential memory issues.
public class StringCorruptionTest : MonoBehaviour {
    ChartEditor editor;
    float startTime;
    Clipboard clipboard = new Clipboard();

    // Use this for initialization
    void Start () {
        editor = ChartEditor.Instance;
    }

    void StartTest()
    {
        Debug.Log("Starting null internal string test");
        enabled = true;
        startTime = Time.realtimeSinceStartup;
        Random.InitState(0);
    }

    void EndTest()
    {
        Debug.Log("Ending null internal string test. Total time: " + (Time.realtimeSinceStartup - startTime));
        enabled = false;
    }

    public void StartStopTest()
    {
        if (enabled)
            EndTest();
        else
            StartTest();
    }

    private void OnEnable()
    {
        StartTest();
    }

    private void OnDisable()
    {
        EndTest();
    }

    // Update is called once per frame
    void Update () {
        Song song = editor.currentSong;
        float songLength = editor.currentSongLength;

        ReadClipboardFromFile();

        if (ValidateSectionsAndGetStopTest(song, 0))
        {
            EndTest();
            return;
        }

        ClearAllSections(song);
        AddRandomSections(song, songLength);

        if (ValidateSectionsAndGetStopTest(song, 1))
        {
            EndTest();
            return;
        }

        FillClipboard(song);
        WriteClipboardToFile(clipboard);
    }

    void ClearAllSections(Song song)
    {
        for(int i = song.sections.Count - 1; i >= 0; --i)
        {
            song.Remove(song.sections[i]);
        }
    }

    bool ValidateSectionsAndGetStopTest(Song song, int id)
    {
        bool stopTest = false;

        foreach (Section section in song.sections)
        {
            bool nullReferenceExceptionFound = false;
            string exceptionMessage;
            if (!ValidateString(section.title, ref nullReferenceExceptionFound, out exceptionMessage))
            {
                if (nullReferenceExceptionFound)
                {
                    Debug.LogError("Validation " + id + ". Null reference string failed validation. \nString was " + section.title + ". \n Message was " + exceptionMessage);
                    stopTest = true;
                    break;
                }
                else
                {
                    Debug.LogWarning("Validation " + id + ". String failed validation. String was " + section.title + ". \n Message was " + exceptionMessage);
                }
            }
        }

        return stopTest;
    }

    void AddRandomSections(Song song, float songLength)
    {
        uint maxTickPosition = song.TimeToTick(songLength, song.resolution);
        const int maxSections = 100;
        int numberOfSections = Random.Range(0, maxSections);

        for (int i = 0; i < numberOfSections; ++i)
        {
            string sectionName = GenerateRandomSectionName();
            uint tickPosition = (uint)Random.Range(0, (int)maxTickPosition);
            Section section = new Section(sectionName, tickPosition);
            song.Add(section);
        }
    }

    string GenerateRandomSectionName()
    {
        const int maxLength = 150;
        int stringLength = Random.Range(0, maxLength);
        string str = string.Empty;

        for (int i = 0; i < stringLength; ++i)
        {
            int charInt;
            do
            {
                charInt = Random.Range(char.MinValue, char.MaxValue);
            }
            while (charInt >= 0xD800 && charInt <= 0xDFFF);

            char character = (char)charInt;
            str += character;
        }

        return str;
    }

    bool ValidateString(string str, ref bool isNullReferenceException, out string exceptionMessage)
    {
        isNullReferenceException = false;
        exceptionMessage = string.Empty;

        try
        {
            UTF8Encoding.UTF8.GetByteCount(str);
        }
        catch (System.NullReferenceException e)
        {
            isNullReferenceException = true;
            exceptionMessage = e.Message;
            return false;
        }
        catch (System.Exception e)
        {
            exceptionMessage = e.Message;
            return false;
        }

        return true;
    }

    void FillClipboard(Song song)
    {
        Clipboard.SelectionArea area = new Clipboard.SelectionArea();
        clipboard = new Clipboard();

        clipboard.data = song.sections.ToArray();
        clipboard.resolution = song.resolution;
        clipboard.instrument = MenuBar.currentInstrument;
        clipboard.SetCollisionArea(area, song);
    }

    void WriteClipboardToFile(Clipboard clipboard)
    {
        try
        {
            FileStream fs = null;

            try
            {
                fs = new FileStream(ClipboardObjectController.CLIPBOARD_FILE_LOCATION, FileMode.Create, FileAccess.ReadWrite);
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(fs, clipboard);
            }
            catch (SerializationException e)
            {
                Logger.LogException(e, "Failed to serialize");
            }
            catch (System.Exception e)
            {
                Logger.LogException(e, "Failed to serialize in general");
            }
            finally
            {
                if (fs != null)
                    fs.Close();
                else
                    Debug.LogError("Filestream when writing clipboard data failed to initialise");
            }
        }
        catch (System.Exception e)
        {
            Logger.LogException(e, "Failed to copy data");
        }
    }

    void ReadClipboardFromFile()
    {
        FileStream fs = null;
        clipboard = null;

        try
        {
            // Read clipboard data from a file instead of the actual clipboard because the actual clipboard doesn't work for whatever reason
            fs = new FileStream(ClipboardObjectController.CLIPBOARD_FILE_LOCATION, FileMode.Open);
            BinaryFormatter formatter = new BinaryFormatter();

            clipboard = (Clipboard)formatter.Deserialize(fs);
        }
        catch (System.Exception e)
        {
            Logger.LogException(e, "Failed to read from clipboard file");
            clipboard = null;
        }
        finally
        {
            if (fs != null)
                fs.Close();
            else
                Debug.LogError("Filestream when reading clipboard data failed to initialise");
        }

        if (clipboard != null)
        {
            foreach (SongObject clipboardSongObject in clipboard.data)
            {
                PlaceSongObject.AddObjectToCurrentEditor(clipboardSongObject.Clone(), editor, false);
            }
        }
    }
}