text:
using System;
using System.Data;
using System.Collections;
using System.IO;

namespace TestFu.Data.Populators
{
	/// <summary>
	/// A <see cref="IUniqueValidator"/> querying the databse.
	/// </summary>
	/// <include
	///		file='Data/TestFu.Data.Doc.xml'
	///		path='//example[contains(descendant-or-self::*,"DbCommandUniqueValidator")]'
	///		/>
	public abstract class DbCommandUniqueValidatorBase : UniqueValidatorBase
	{
        private Random rnd = new Random((int)DateTime.Now.Ticks);
        private IDbFactory dbFactory;
        private string connectionString;

        public DbCommandUniqueValidatorBase(
            ITablePopulator table,
            UniqueConstraint unique,
            IDbFactory dbFactory,
            string connectionString
            )
		:base(table,unique)
		{
            if (dbFactory == null)
                throw new ArgumentNullException("factory");
            if (connectionString == null)
                throw new ArgumentNullException("connectionString");
            this.dbFactory = dbFactory;
            this.connectionString = connectionString;
        }

        public abstract string GetSelectKeyQuery();
        public abstract string GetSelectCountByKeyQuery(DataRow row);

        protected virtual IDataReader SelectKeys()
        {
            IDbConnection connection = null;
            try
            {
                connection = this.DbFactory.CreateConnection(this.connectionString);
                string selectQuery = this.GetSelectKeyQuery();
                connection.Open();
                using (IDbCommand command = this.DbFactory.CreateCommand(selectQuery, connection))
                {
                    return command.ExecuteReader(CommandBehavior.CloseConnection);
                }
            }
            catch (Exception ex)
            {
                if (connection != null)
                    connection.Dispose();

                throw new ApplicationException("Error while selecting keys", ex);
            }
        }

        public override bool Contains(DataRow row)
        {
            if (row == null)
                throw new ArgumentNullException("row");

            string selectCountByKeyQuery = this.GetSelectCountByKeyQuery(row);
            using (IDbConnection connection = this.DbFactory.CreateConnection(this.ConnectionString))
            {
                connection.Open();
                using (IDbCommand command = this.DbFactory.CreateCommand(selectCountByKeyQuery, connection))
                {
                    int count = (int)command.ExecuteScalar();
                    return count != 0;
                }
            }
        }

        protected virtual int SelectKeyCount()
		{
            return this.DbFactory.SelectCount(this.Table.Table,this.ConnectionString);
		}

        public IDbFactory DbFactory
        {
            get
            {
                return this.dbFactory;
            }
        }

        public string ConnectionString
        {
            get
            {
                return this.connectionString;
            }
        }

        public IEnumerable Keys
		{
			get
			{
				return new KeyCollection(this.Table.Table, this.SelectKeys());
			}
		}

		public override bool IsEmpty
		{
			get
			{
				return this.SelectKeyCount()==0;
			}
		}

		public override DataRow GetKey()
		{
			int index = this.rnd.Next(this.SelectKeyCount());

			int i=0;
			using (IDataReader dr = this.SelectKeys())
			{
				while(dr.Read())
				{
					// if i == index, we get the row
					if (i==index)
					{
						// fill a datarow with the data
						DataRow row = this.Table.Table.NewRow();
						for(int j=0;j<dr.FieldCount;++j)
							row[j]=dr[j];
						return row;
					}
					// increment i
					i++;
				}
			}
			throw new Exception("Error while looking for a key");
		}

		public override void AddKey(DataRow row)
		{
			if (row==null)
				throw new ArgumentNullException("row");
		}

		public override void RemoveKey(DataRow row)
		{
			if (row==null)
				throw new ArgumentNullException("row");
		}

		internal class KeyCollection : IEnumerable
		{
			private DataTable table;
			private IDataReader dr;

			public KeyCollection(DataTable table,IDataReader dr)
			{
				this.table=table;
				this.dr=dr;
			}

			public KeyEnumerator GetEnumerator()
			{
				return new KeyEnumerator(this.table,this.dr);
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return this.GetEnumerator();
			}

			#region KeyEnumerator
			internal class KeyEnumerator : IEnumerator, IDisposable
			{
				private DataTable table;
				private IDataReader dr;
				private DataRow row=null;
				public KeyEnumerator(DataTable table, IDataReader dr)
				{
					this.table = table;
					this.dr=dr;
				}

				#region IEnumerator
				public void Reset()
				{
					throw new NotSupportedException();
				}

				public bool MoveNext()
				{
					if (dr==null)
						throw new InvalidOperationException("DataReader out of range");
					if (!dr.Read())
					{
						this.Dispose();
						return false;
					}

					this.row=table.NewRow();
					for(int j=0;j<this.dr.FieldCount;++j)
						this.row[j]=dr[j];
					return true;
				}

				public DataRow Current
				{
					get
					{
						return this.row;
					}
				}

				Object IEnumerator.Current
				{
					get
					{
						return this.Current;
					}
				}
				#endregion

				#region IDisposable
				public void Dispose()
				{
					if (this.dr!=null)
					{
						this.dr.Close();
						this.dr=null;
					}
				}
				#endregion
			}
			#endregion
		}
	}
}


text:
package sbql4j8.com.sun.tools.doclint;

import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import javax.tools.Diagnostic;

import sbql4j8.com.sun.source.doctree.DocTree;
import sbql4j8.com.sun.source.tree.Tree;
import sbql4j8.com.sun.tools.doclint.Env.AccessKind;

/**
 * Message reporting for DocLint.
 *
 * Options are used to filter out messages based on group and access level.
 * Support can be enabled for accumulating statistics of different kinds of
 * messages.
 *
 *
This is NOT part of any supported API.
 * If you write code that depends on this, you do so at your own
 * risk.  This code and its internal interfaces are subject to change
 * or deletion without notice.

 */
public class Messages {
    /**
     * Groups used to categorize messages, so that messages in each group
     * can be enabled or disabled via options.
     */
    public enum Group {
        ACCESSIBILITY,
        HTML,
        MISSING,
        SYNTAX,
        REFERENCE;

        String optName() { return name().toLowerCase(); }
        String notOptName() { return "-" + optName(); }

        static boolean accepts(String opt) {
            for (Group g: values())
                if (opt.equals(g.optName())) return true;
            return false;
        }
    };

    private final Options options;
    private final Stats stats;

    ResourceBundle bundle;
    Env env;

    Messages(Env env) {
        this.env = env;
        String name = getClass().getPackage().getName() + ".resources.doclint";
        bundle = ResourceBundle.getBundle(name, Locale.ENGLISH);

        stats = new Stats(bundle);
        options = new Options(stats);
    }

    void error(Group group, DocTree tree, String code, Object... args) {
        report(group, Diagnostic.Kind.ERROR, tree, code, args);
    }

    void warning(Group group, DocTree tree, String code, Object... args) {
        report(group, Diagnostic.Kind.WARNING, tree, code, args);
    }

    void setOptions(String opts) {
        options.setOptions(opts);
    }

    void setStatsEnabled(boolean b) {
        stats.setEnabled(b);
    }

    void reportStats(PrintWriter out) {
        stats.report(out);
    }

    protected void report(Group group, Diagnostic.Kind dkind, DocTree tree, String code, Object... args) {
        if (options.isEnabled(group, env.currAccess)) {
            String msg = (code == null) ? (String) args[0] : localize(code, args);
            env.trees.printMessage(dkind, msg, tree,
                    env.currDocComment, env.currPath.getCompilationUnit());

            stats.record(group, dkind, code);
        }
    }

    protected void report(Group group, Diagnostic.Kind dkind, Tree tree, String code, Object... args) {
        if (options.isEnabled(group, env.currAccess)) {
            String msg = localize(code, args);
            env.trees.printMessage(dkind, msg, tree, env.currPath.getCompilationUnit());

            stats.record(group, dkind, code);
        }
    }

    String localize(String code, Object... args) {
        String msg = bundle.getString(code);
        if (msg == null) {
            StringBuilder sb = new StringBuilder();
            sb.append("message file broken: code=").append(code);
            if (args.length > 0) {
                sb.append(" arguments={0}");
                for (int i = 1; i < args.length; i++) {
                    sb.append(", {").append(i).append("}");
                }
            }
            msg = sb.toString();
        }
        return MessageFormat.format(msg, args);
    }

    // <editor-fold defaultstate="collapsed" desc="Options">

    /**
     * Handler for (sub)options specific to message handling.
     */
    static class Options {
        Map<String, Env.AccessKind> map = new HashMap<String, Env.AccessKind>();
        private final Stats stats;

        static boolean isValidOptions(String opts) {
            for (String opt: opts.split(",")) {
                if (!isValidOption(opt.trim().toLowerCase()))
                    return false;
            }
            return true;
        }

        private static boolean isValidOption(String opt) {
            if (opt.equals("none") || opt.equals(Stats.OPT))
                return true;

            int begin = opt.startsWith("-") ? 1 : 0;
            int sep = opt.indexOf("/");
            String grp = opt.substring(begin, (sep != -1) ? sep : opt.length());
            return ((begin == 0 && grp.equals("all")) || Group.accepts(grp))
                    && ((sep == -1) || AccessKind.accepts(opt.substring(sep + 1)));
        }

        Options(Stats stats) {
            this.stats = stats;
        }

        /** Determine if a message group is enabled for a particular access level. */
        boolean isEnabled(Group g, Env.AccessKind access) {
            if (map.isEmpty())
                map.put("all", Env.AccessKind.PROTECTED);

            Env.AccessKind ak = map.get(g.optName());
            if (ak != null && access.compareTo(ak) >= 0)
                return true;

            ak = map.get(ALL);
            if (ak != null && access.compareTo(ak) >= 0) {
                ak = map.get(g.notOptName());
                if (ak == null || access.compareTo(ak) > 0) // note >, not >=
                    return true;
            }

            return false;
        }

        void setOptions(String opts) {
            if (opts == null)
                setOption(ALL, Env.AccessKind.PRIVATE);
            else {
                for (String opt: opts.split(","))
                    setOption(opt.trim().toLowerCase());
            }
        }

        private void setOption(String arg) throws IllegalArgumentException {
            if (arg.equals(Stats.OPT)) {
                stats.setEnabled(true);
                return;
            }

            int sep = arg.indexOf("/");
            if (sep > 0) {
                Env.AccessKind ak = Env.AccessKind.valueOf(arg.substring(sep + 1).toUpperCase());
                setOption(arg.substring(0, sep), ak);
            } else {
                setOption(arg, null);
            }
        }

        private void setOption(String opt, Env.AccessKind ak) {
            map.put(opt, (ak != null) ? ak
                    : opt.startsWith("-") ? Env.AccessKind.PUBLIC : Env.AccessKind.PRIVATE);
        }

        private static final String ALL = "all";
    }

    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Statistics">

    /**
     * Optionally record statistics of different kinds of message.
     */
    static class Stats {
        public static final String OPT = "stats";
        public static final String NO_CODE = "";
        final ResourceBundle bundle;

        // tables only initialized if enabled
        int[] groupCounts;
        int[] dkindCounts;
        Map<String, Integer> codeCounts;

        Stats(ResourceBundle bundle) {
            this.bundle = bundle;
        }

        void setEnabled(boolean b) {
            if (b) {
                groupCounts = new int[Messages.Group.values().length];
                dkindCounts = new int[Diagnostic.Kind.values().length];
                codeCounts = new HashMap<String, Integer>();
            } else {
                groupCounts = null;
                dkindCounts = null;
                codeCounts = null;
            }
        }

        void record(Messages.Group g, Diagnostic.Kind dkind, String code) {
            if (codeCounts == null) {
                return;
            }
            groupCounts[g.ordinal()]++;
            dkindCounts[dkind.ordinal()]++;
            if (code == null) {
                code = NO_CODE;
            }
            Integer i = codeCounts.get(code);
            codeCounts.put(code, (i == null) ? 1 : i + 1);
        }

        void report(PrintWriter out) {
            if (codeCounts == null) {
                return;
            }
            out.println("By group...");
            Table groupTable = new Table();
            for (Messages.Group g : Messages.Group.values()) {
                groupTable.put(g.optName(), groupCounts[g.ordinal()]);
            }
            groupTable.print(out);
            out.println();
            out.println("By diagnostic kind...");
            Table dkindTable = new Table();
            for (Diagnostic.Kind k : Diagnostic.Kind.values()) {
                dkindTable.put(k.toString().toLowerCase(), dkindCounts[k.ordinal()]);
            }
            dkindTable.print(out);
            out.println();
            out.println("By message kind...");
            Table codeTable = new Table();
            for (Map.Entry<String, Integer> e : codeCounts.entrySet()) {
                String code = e.getKey();
                String msg;
                try {
                    msg = code.equals(NO_CODE) ? "OTHER" : bundle.getString(code);
                } catch (MissingResourceException ex) {
                    msg = code;
                }
                codeTable.put(msg, e.getValue());
            }
            codeTable.print(out);
        }

        /**
         * A table of (int, String) sorted by decreasing int.
         */
        private static class Table {

            private static final Comparator<Integer> DECREASING = new Comparator<Integer>() {

                public int compare(Integer o1, Integer o2) {
                    return o2.compareTo(o1);
                }
            };
            private final TreeMap<Integer, Set<String>> map = new TreeMap<Integer, Set<String>>(DECREASING);

            void put(String label, int n) {
                if (n == 0) {
                    return;
                }
                Set<String> labels = map.get(n);
                if (labels == null) {
                    map.put(n, labels = new TreeSet<String>());
                }
                labels.add(label);
            }

            void print(PrintWriter out) {
                for (Map.Entry<Integer, Set<String>> e : map.entrySet()) {
                    int count = e.getKey();
                    Set<String> labels = e.getValue();
                    for (String label : labels) {
                        out.println(String.format("%6d: %s", count, label));
                    }
                }
            }
        }
    }
    // </editor-fold>
}

redpajama_set_name: RedPajamaGithub


text:
package io.github.andreybgm.gigreminder.screen.locations;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.github.andreybgm.gigreminder.R;
import io.github.andreybgm.gigreminder.data.Location;
import io.github.andreybgm.gigreminder.screen.locations.uievent.DeleteLocationEvent;

public class ListViewHolder extends RecyclerView.ViewHolder {
    @BindView(R.id.text_name)
    TextView nameView;

    @BindView(R.id.button_delete)
    ImageButton deleteButton;

    private final LocationsPresenter presenter;

    public ListViewHolder(View itemView, LocationsPresenter presenter) {
        super(itemView);

        ButterKnife.bind(this, itemView);

        this.presenter = presenter;
    }

    public void bind(Location location, int position, LocationsUiModel uiModel) {
        nameView.setText(location.getName());
        deleteButton.setOnClickListener(v -> presenter.sendUiEvent(
                DeleteLocationEvent.create(position, uiModel)
        ));
    }
}


text:
package com.graphhopper.routing.weighting;

import com.graphhopper.routing.util.FlagEncoder;
import com.graphhopper.routing.util.HintsMap;
import com.graphhopper.util.EdgeIteratorState;

/**
 * The AdjustedWeighting wraps another Weighting.
 *
 * @author Robin Boldt
 */
public abstract class AbstractAdjustedWeighting implements Weighting {
    protected final Weighting superWeighting;

    public AbstractAdjustedWeighting(Weighting superWeighting) {
        if (superWeighting == null)
            throw new IllegalArgumentException("No super weighting set");
        this.superWeighting = superWeighting;
    }

    @Override
    public long calcMillis(EdgeIteratorState edgeState, boolean reverse, int prevOrNextEdgeId) {
        return superWeighting.calcMillis(edgeState, reverse, prevOrNextEdgeId);
    }

    /**
     * Returns the flagEncoder of the superWeighting. Usually we do not have a Flagencoder here.
     */
    @Override
    public FlagEncoder getFlagEncoder() {
        return superWeighting.getFlagEncoder();
    }

    @Override
    public boolean matches(HintsMap reqMap) {
        return getName().equals(reqMap.getWeighting())
                && superWeighting.getFlagEncoder().toString().equals(reqMap.getVehicle());
    }

    @Override
    public String toString() {
        return getName() + "|" + superWeighting.toString();
    }
}


text:
/*!
 * Module dependencies
 */

var MPromise = require('mpromise');
var util = require('util');

/**
 * Promise constructor.
 *
 * Promises are returned from executed queries. Example:
 *
 *     var query = Candy.find({ bar: true });
 *     var promise = query.exec();
 *
 * @param {Function} fn a function which will be called when the promise is resolved that accepts `fn(err, ...){}` as signature
 * @inherits mpromise https://github.com/aheckmann/mpromise
 * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
 * @event `err`: Emits when the promise is rejected
 * @event `complete`: Emits when the promise is fulfilled
 * @api public
 */

function Promise (fn) {
  MPromise.call(this, fn);
}

/*!
 * Inherit from mpromise
 */

Promise.prototype = Object.create(MPromise.prototype, {
    constructor: {
        value: Promise
      , enumerable: false
      , writable: true
      , configurable: true
    }
});

/*!
 * Override event names for backward compatibility.
 */

Promise.SUCCESS = 'complete';
Promise.FAILURE = 'err';

/**
 * Adds `listener` to the `event`.
 *
 * If `event` is either the success or failure event and the event has already been emitted, the`listener` is called immediately and passed the results of the original emitted event.
 *
 * @see mpromise#on https://github.com/aheckmann/mpromise#on
 * @method on
 * @memberOf Promise
 * @param {String} event
 * @param {Function} listener
 * @return {Promise} this
 * @api public
 */

/**
 * Rejects this promise with `reason`.
 *
 * If the promise has already been fulfilled or rejected, not action is taken.
 *
 * @see mpromise#reject https://github.com/aheckmann/mpromise#reject
 * @method reject
 * @memberOf Promise
 * @param {Object|String|Error} reason
 * @return {Promise} this
 * @api public
 */

/**
 * Rejects this promise with `err`.
 *
 * If the promise has already been fulfilled or rejected, not action is taken.
 *
 * Differs from [#reject](#promise_Promise-reject) by first casting `err` to an `Error` if it is not `instanceof Error`.
 *
 * @api public
 * @param {Error|String} err
 * @return {Promise} this
 */

Promise.prototype.error = function (err) {
  if (!(err instanceof Error)) {
    if (err instanceof Object) {
      err = util.inspect(err);
    }
    err = new Error(err);
  }
  return this.reject(err);
}

/**
 * Resolves this promise to a rejected state if `err` is passed or a fulfilled state if no `err` is passed.
 *
 * If the promise has already been fulfilled or rejected, not action is taken.
 *
 * `err` will be cast to an Error if not already instanceof Error.
 *
 * _NOTE: overrides [mpromise#resolve](https://github.com/aheckmann/mpromise#resolve) to provide error casting._
 *
 * @param {Error} [err] error or null
 * @param {Object} [val] value to fulfill the promise with
 * @api public
 */

Promise.prototype.resolve = function (err) {
  if (err) return this.error(err);
  return this.fulfill.apply(this, Array.prototype.slice.call(arguments, 1));
};

/**
 * Adds a single function as a listener to both err and complete.
 *
 * It will be executed with traditional node.js argument position when the promise is resolved.
 *
 *     promise.addBack(function (err, args...) {
 *       if (err) return handleError(err);
 *       console.log('success');
 *     })
 *
 * Alias of [mpromise#onResolve](https://github.com/aheckmann/mpromise#onresolve).
 *
 * _Deprecated. Use `onResolve` instead._
 *
 * @method addBack
 * @param {Function} listener
 * @return {Promise} this
 * @deprecated
 */

Promise.prototype.addBack = Promise.prototype.onResolve;

/**
 * Fulfills this promise with passed arguments.
 *
 * @method fulfill
 * @see https://github.com/aheckmann/mpromise#fulfill
 * @param {any} args
 * @api public
 */

/**
 * Fulfills this promise with passed arguments.
 *
 * Alias of [mpromise#fulfill](https://github.com/aheckmann/mpromise#fulfill).
 *
 * _Deprecated. Use `fulfill` instead._
 *
 * @method complete
 * @param {any} args
 * @api public
 * @deprecated
 */

Promise.prototype.complete = MPromise.prototype.fulfill;

/**
 * Adds a listener to the `complete` (success) event.
 *
 * Alias of [mpromise#onFulfill](https://github.com/aheckmann/mpromise#onfulfill).
 *
 * _Deprecated. Use `onFulfill` instead._
 *
 * @method addCallback
 * @param {Function} listener
 * @return {Promise} this
 * @api public
 * @deprecated
 */

Promise.prototype.addCallback = Promise.prototype.onFulfill;

/**
 * Adds a listener to the `err` (rejected) event.
 *
 * Alias of [mpromise#onReject](https://github.com/aheckmann/mpromise#onreject).
 *
 * _Deprecated. Use `onReject` instead._
 *
 * @method addErrback
 * @param {Function} listener
 * @return {Promise} this
 * @api public
 * @deprecated
 */

Promise.prototype.addErrback = Promise.prototype.onReject;

/**
 * Creates a new promise and returns it. If `onFulfill` or `onReject` are passed, they are added as SUCCESS/ERROR callbacks to this promise after the nextTick.
 *
 * Conforms to [promises/A+](https://github.com/promises-aplus/promises-spec) specification.
 *
 * ####Example:
 *
 *     var promise = Meetups.find({ tags: 'javascript' }).select('_id').exec();
 *     promise.then(function (meetups) {
 *       var ids = meetups.map(function (m) {
 *         return m._id;
 *       });
 *       return People.find({ meetups: { $in: ids }).exec();
 *     }).then(function (people) {
 *       if (people.length < 10000) {
 *         throw new Error('Too few people!!!');
 *       } else {
 *         throw new Error('Still need more people!!!');
 *       }
 *     }).then(null, function (err) {
 *       assert.ok(err instanceof Error);
 *     });
 *
 * @see promises-A+ https://github.com/promises-aplus/promises-spec
 * @see mpromise#then https://github.com/aheckmann/mpromise#then
 * @method then
 * @memberOf Promise
 * @param {Function} onFulFill
 * @param {Function} onReject
 * @return {Promise} newPromise
 */

/**
 * Signifies that this promise was the last in a chain of `then()s`: if a handler passed to the call to `then` which produced this promise throws, the exception will go uncaught.
 *
 * ####Example:
 *
 *     var p = new Promise;
 *     p.then(function(){ throw new Error('shucks') });
 *     setTimeout(function () {
 *       p.fulfill();
 *       // error was caught and swallowed by the promise returned from
 *       // p.then(). we either have to always register handlers on
 *       // the returned promises or we can do the following...
 *     }, 10);
 *
 *     // this time we use .end() which prevents catching thrown errors
 *     var p = new Promise;
 *     var p2 = p.then(function(){ throw new Error('shucks') }).end(); // <--
 *     setTimeout(function () {
 *       p.fulfill(); // throws "shucks"
 *     }, 10);
 *
 * @api public
 * @see mpromise#end https://github.com/aheckmann/mpromise#end
 * @method end
 * @memberOf Promise
 */

/*!
 * expose
 */

module.exports = Promise;


text:
;(function(Agent){

  Agent.LazyWorker = Marionette.Object.extend({

    // time to wait until starting work
    deferTime: 200,

    // time to work and potentially freeze the screen
    workTime: 80,

    jobId: 0,

    initialize: function() {
      this.initTime = new Date();
      this.queue = [];
      this.startWork = _.debounce(this.startWork, this.deferTime);
      // this.logSize();
    },

    push: function(job) {
      // console.log('** callee', Agent.stackFrame(8));
      // console.log('push called', this.queue.length, new Date() - this.initTime);

      job.jobId = this.jobId++;
      this.queue.push(job);
      this.triggerMethod('push');
      this.startWork();
    },

    startWork: function() {
      if (this.isWorking) {
        return;
      }

      this.triggerMethod('work:start');
      // window.setTimeout(this.stopWork.bind(this), this.workTime);
      this.isWorking = true;
      this.startTime = new Date();
      var job;

      while (this.isWorking) {
        //console.log('working loop called', this.queue.length, new Date() - this.initTime);

        job = this.queue.shift();
        if (!job) {
          //console.log('queue is empty', new Date() - this.startTime)
          this.stopWork();
          this.triggerMethod('queue:empty');
          return;
        }

        job.callback.apply(job.context, job.args);

        if (new Date() - this.startTime > this.workTime) {
          //console.log('time has elapsed', new Date() - this.startTime)
          this.stopWork();
          this.startWork();
          return;
        }
      }
    },

    stopWork: function() {
      if (!this.isWorking) {
        return;
      }

      //console.log('stop work called', new Date() - this.startTime);
      this.triggerMethod('work:stop')
      this.isWorking = false;
    },

    logSize: function() {
      window.setInterval(function() {
        console.log('!!! queue size', Agent.lazyWorker.queue.length)
      }, 1000);
    }

  });

}(Agent));


text:
(function() {
  var UpdatePackageDependencies, WorkspaceView;

  WorkspaceView = require('atom').WorkspaceView;

  UpdatePackageDependencies = require('../lib/update-package-dependencies');

  describe("Update Package Dependencies", function() {
    var mainModule;
    mainModule = null;
    beforeEach(function() {
      atom.workspaceView = new WorkspaceView;
      return waitsForPromise(function() {
        return atom.packages.activatePackage('update-package-dependencies').then(function(pack) {
          return mainModule = pack.mainModule;
        });
      });
    });
    return it("updates package dependencies", function() {
      spyOn(mainModule, 'update');
      atom.workspaceView.trigger("update-package-dependencies:update");
      return expect(mainModule.update).toHaveBeenCalled();
    });
  });

}).call(this);


text:
Please provide the voter ID and password you received by email.

<form method="post" action="{% url "helios.views.password_voter_login" election.uuid %}" onsubmit="show_waiting()">
<input type="hidden" name="csrf_token" value="{{csrf_token}}" />
<input type="hidden" name="return_url" value="{{return_url}}" />
<input type="hidden" name="cast_ballot" value="{{cast_ballot}}" />

    {{password_login_form.as_table}}

{% if bad_voter_login %}

bad voter ID or password, please try again.

{% endif %}
{% if cast_ballot == "1" %}

You may cast as many ballots as you wish:
only the last one counts.

<input type="submit" class="button" value="cast ballot" />
{% else %}
<input type="submit" class="button" value="log in" />
{% endif %}
</form>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive;
using System.Reflection;
using Octokit.Tests.Helpers;
using Xunit;

namespace Octokit.Tests.Conventions
{
    public class SyncObservableClients
    {
        [Theory]
        [MemberData("GetClientInterfaces")]
        public void CheckObservableClients(Type clientInterface)
        {
            var observableClient = clientInterface.GetObservableClientInterface();
            var mainMethods = clientInterface.GetMethodsOrdered();
            var observableMethods = observableClient.GetMethodsOrdered();
            var mainNames = Array.ConvertAll(mainMethods, m => m.Name);
            var observableNames = Array.ConvertAll(observableMethods, m => m.Name);

            var methodsMissingOnReactiveClient = mainNames.Except(observableNames).ToList();
            if (methodsMissingOnReactiveClient.Any())
            {
                throw new InterfaceMissingMethodsException(observableClient, methodsMissingOnReactiveClient);
            }

            var additionalMethodsOnReactiveClient = observableNames.Except(mainNames).ToList();
            if (additionalMethodsOnReactiveClient.Any())
            {
                throw new InterfaceHasAdditionalMethodsException(observableClient, additionalMethodsOnReactiveClient);
            }

            if (mainNames.Count() != observableNames.Count())
            {
                throw new InterfaceMethodsMismatchException(observableClient, clientInterface);
            }

            int index = 0;
            foreach(var mainMethod in mainMethods)
            {
                var observableMethod = observableMethods[index];
                AssertEx.WithMessage(() => CheckMethod(mainMethod, observableMethod), "Invalid signature for " + observableMethod);
                index++;
            }
        }

        private static void CheckMethod(MethodInfo mainMethod, MethodInfo observableMethod)
        {
            Assert.Equal(mainMethod.MemberType, observableMethod.MemberType);
            Assert.Equal(mainMethod.Name, observableMethod.Name);
            CheckParameters(mainMethod, observableMethod);
            CheckReturnValue(mainMethod, observableMethod);
        }

        private static void CheckReturnValue(MethodInfo mainMethod, MethodInfo observableMethod)
        {
            var mainReturnType = mainMethod.ReturnType;
            var observableReturnType = observableMethod.ReturnType;
            var expectedType = GetObservableExpectedType(mainReturnType);

            if (expectedType != observableReturnType)
            {
                throw new ReturnValueMismatchException(observableMethod, expectedType, observableReturnType);
            }
        }

        private static Type GetObservableExpectedType(Type mainType)
        {
            var typeInfo = mainType.GetTypeInfo();
            switch(typeInfo.TypeCategory)
            {
                case TypeCategory.ClientInterface:
                    // client interface - IClient => IObservableClient
                    return mainType.GetObservableClientInterface();
                case TypeCategory.Task:
                    // void - Task => IObservable<Unit>
                    return typeof(IObservable<Unit>);
                case TypeCategory.GenericTask:
                    // single item - Task<TResult> => IObservable<TResult>
                case TypeCategory.ReadOnlyList:
                    // list - Task<IReadOnlyList<TResult>> => IObservable<TResult>
                    return typeof(IObservable<>).MakeGenericType(typeInfo.Type);
                case TypeCategory.Other:
                    return mainType;
                default:
                    throw new Exception("Unknown type category " + typeInfo.TypeCategory);
            }
        }

        private static void CheckParameters(MethodInfo mainMethod, MethodInfo observableMethod)
        {
            var mainParameters = mainMethod.GetParametersOrdered();
            var observableParameters = observableMethod.GetParametersOrdered();

            if (mainParameters.Length != observableParameters.Length)
            {
                throw new ParameterCountMismatchException(observableMethod, mainParameters, observableParameters);
            }

            int index = 0;
            foreach(var mainParameter in mainParameters)
            {
                var observableParameter = observableParameters[index];
                if (mainParameter.Name != observableParameter.Name)
                {
                    throw new ParameterMismatchException(observableMethod, index, mainParameter, observableParameter);
                }

                var mainType = mainParameter.ParameterType;
                var expectedType = GetObservableExpectedType(mainType);
                if (expectedType != observableParameter.ParameterType)
                {
                    throw new ParameterMismatchException(observableMethod, index, mainParameter, observableParameter);
                }
                index++;
            }
        }

        public static IEnumerable<object[]> GetClientInterfaces()
        {
            return typeof(IEventsClient)
                .Assembly
                .ExportedTypes
                .Where(TypeExtensions.IsClientInterface)
                .Where(t => t != typeof(IStatisticsClient)) // This convention doesn't apply to this one type.
                .Select(type => new[] { type });
        }
    }
}


text:
<!--
 Copyright 2016 Google Inc.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportHeight="24.0"
    android:viewportWidth="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M4,15.5C4,17.43 5.57,19 7.5,19L6,20.5v0.5h12v-0.5L16.5,19c1.93,0 3.5,-1.57 3.5,-3.5L20,5c0,-3.5 -3.58,-4 -8,-4s-8,0.5 -8,4v10.5zM12,17c-1.1,0 -2,-0.9 -2,-2s0.9,-2 2,-2 2,0.9 2,2 -0.9,2 -2,2zM18,10L6,10L6,5h12v5z" />
</vector>


text: A web based 3D racing game


text:
using iMotto.Adapter.Readers.Requests;
using iMotto.Cache;
using iMotto.Data;
using iMotto.Data.Entities;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace iMotto.Adapter.Readers.Handlers
{
    class ReadAwardHandler : BaseHandler<ReadAwardsRequest>
    {
        private readonly ICacheManager _cacheManager;
        private readonly IGiftRepo _giftRepo;

        public ReadAwardHandler(ICacheManager cacheManager, IGiftRepo giftRepo)
        {
            _cacheManager = cacheManager;
            _giftRepo = giftRepo;
        }

        protected override async Task<HandleResult> HandleCoreAsync(ReadAwardsRequest reqObj)
        {
            string uid = null;
            var tuple = _cacheManager.GetCache<IOnlineUserCache>().GetOnlineUserViaSignature(reqObj.Sign);

            if (tuple != null)
            {
                uid = tuple.Item1;
            }

            List<Award> result = await _giftRepo.GetAwardsAsync(uid, reqObj.PIndex, reqObj.PSize);

            return new HandleResult<List<Award>>
            {
                State = HandleStates.Success,
                Msg = string.Empty,
                Data = result
            };
        }
    }
}


text:
package vos;

import org.codehaus.jackson.annotate.JsonProperty;

public class IngredientesPlato {

	@JsonProperty(value="ID_PLATO")
	private int idPlato;

	@JsonProperty(value="NOM_INGR")
	private String nombreIngrdiente;

	public IngredientesPlato(@JsonProperty(value="ID_PLATO")int idPlato, @JsonProperty(value="NOM_INGR")String nombreIngrdiente) {
		super();
		this.idPlato = idPlato;
		this.nombreIngrdiente = nombreIngrdiente;
	}

	public int getIdPlato() {
		return idPlato;
	}

	public void setIdPlato(int idPlato) {
		this.idPlato = idPlato;
	}

	public String getNombreIngrdiente() {
		return nombreIngrdiente;
	}

	public void setNombreIngrdiente(String nombreIngrdiente) {
		this.nombreIngrdiente = nombreIngrdiente;
	}

}


text:
<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>Rectangle Testing</title>
	<link rel="stylesheet" href="../css/style.css">
	<script type="text/javascript" src="../../lib/paper.js"></script>
	<script type="text/paperscript" canvas="canvas">
		var point1 = new Point(10, 10);
		var size1 = new Size(50, 50);
		var rectangle1 = new Rectangle(point1, size1);
		var path1 = new Path.Rectangle(rectangle1);
		path1.strokeColor = 'black';
		path1.fillColor = 'red';
		path1.id = "square1";
		path1.strokeCap = "square";
		path1.opacity = ".1";
		path1.dashArray = [5, 2];
		path1.dashOffset = "0";

		var point2 = new Point(75, 75);
		var point22 = new Point(100, 100);
		var path2 = new Path.Rectangle(point2, point22);
		path2.strokeColor = 'red';
		path2.strokeWidth = '4';
		path2.fillColor = 'blue';
		path2.id = "square2";
		path2.strokeCap = "butt";
		path2.opacity = "1";

		var point3 = new Point(150, 150);
		var size3 = new Size(50, 50);
		var rectangle3 = new Rectangle(point3, size3);
		var path3 = new Path.Rectangle(rectangle3);
		path3.strokeColor = 'blue';

		var point4 = new Point(200, 200);
		var size4 = new Size(100, 100);
		var rectangle4 = new Rectangle(point4, size4);
		var cornerSize4 = new Size(30, 30);
		var path4 = new Path.Rectangle(rectangle4, cornerSize4);
		path4.strokeColor= 'yellow';
		path4.fillColor='purple';

		document.getElementById('svg').appendChild(project.exportSVG());
	</script>
</head>
<body>
	<canvas id="canvas" width="500" height="500"></canvas>
	<svg id="svg" width="500" height="500"></svg>
</body>
</html>


text:
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link rel="stylesheet" href="http://www.petercorke.com/RVC/common/toolboxhelp.css">
    <title>M-File Help: lambda2xy</title>

      M-File Help: lambda2xy
      View code for lambda2xy

lambda2xy

= LAMBDA2XY(LAMBDA) is the xy-chromaticity coordinate (1x2) for

illumination at the specific wavelength LAMBDA [metres]. If LAMBDA is a
vector (Nx1), then P (Nx2) is a vector whose elements are the luminosity
at the corresponding elements of LAMBDA.

xy = lambda2xy(lambda, E) is the rg-chromaticity coordinate (1x2) for an
illumination spectrum E (Nx1) defined at corresponding wavelengths
lambda (Nx1).

References

Robotics, Vision & Control, Section 10.2,
P. Corke, Springer 2011.

See also

cmfxyz, lambda2rg

© 1990-2014 Peter Corke.


text:
CONNECTALDIR?=../..
S2H_INTERFACES = StrstrRequest:Strstr.request
H2S_INTERFACES = Strstr\#\(64,64\):StrstrIndication
MEM_INTERFACES = "append(lStrstr.config_read_client,lStrstr.haystack_read_client),nil"

BSVFILES = $(CONNECTALDIR)/lib/strstr/bsv/Strstr.bsv
CPPFILES=teststrstr.cpp
CONNECTALFLAGS += -D DEGPAR=2
CONNECTALFLAGS += -I $(CONNECTALDIR)/lib/strstr/cpp

include $(CONNECTALDIR)/Makefile.connectal


text:
package org.apache.pig.piggybank.evaluation.math;

import java.io.IOException;

import org.apache.pig.EvalFunc;
import org.apache.pig.data.DataAtom;
import org.apache.pig.data.Datum;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.logicalLayer.schema.AtomSchema;
import org.apache.pig.impl.logicalLayer.schema.Schema;
/**
 * math.CEIL implements a binding to the Java function
* {@link java.lang.Math#ceil(double) Math.ceil(double)}. Given a single
* data atom it  Returns the smallest (closest to negative infinity)
* double value that is greater than or equal  to the argument and is equal
* to a mathematical integer.
*
*

*
Parameters:

*
value - DataAtom [double].

*
*
Return Value:

*
DataAtom [double]

*
*
Return Schema:

*
ceil_inputSchema

*
*
Example:

*

* register math.jar;

* A = load 'mydata' using PigStorage() as ( float1 );

* B = foreach A generate float1, math.ceil(float1);
*

*

*
* @see Math#ceil(double)
* @see
* @author ajay garg
*
*/
public class CEIL extends EvalFunc<DataAtom>{
	/**
	 * java level API
	 * @param input expects a single numeric DataAtom value
	 * @param output returns a single numeric DataAtom value, ceil value of the argument
	 */
	@Override
	public void exec(Tuple input, DataAtom output) throws IOException {
		output.setValue(ceil(input));
	}

	protected double ceil(Tuple input) throws IOException{
		Datum temp = input.getField(0);
		double retVal;
		if(!(temp instanceof DataAtom)){
			throw new IOException("invalid input format. ");
		}
		else{
			try{
				retVal=((DataAtom)temp).numval();
			}
			catch(RuntimeException e){
				throw new IOException((DataAtom)temp+" is not a valid number");
			}
		}
		return Math.ceil(retVal);

	}

	@Override
	public Schema outputSchema(Schema input) {
		return new AtomSchema("ceil_"+input.toString());
	}

}


text:
package org.apache.camel.dataformat.beanio;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import org.apache.camel.CamelContext;
import org.apache.camel.CamelContextAware;
import org.apache.camel.Exchange;
import org.apache.camel.spi.DataFormat;
import org.apache.camel.spi.DataFormatName;
import org.apache.camel.support.ServiceSupport;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.ResourceHelper;
import org.beanio.BeanReader;
import org.beanio.BeanReaderErrorHandler;
import org.beanio.BeanWriter;
import org.beanio.StreamFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A data format (
 * {@link DataFormat}) for beanio data.
 */
public class BeanIODataFormat extends ServiceSupport implements DataFormat, DataFormatName, CamelContextAware {

    private static final Logger LOG = LoggerFactory.getLogger(BeanIODataFormat.class);

    private transient CamelContext camelContext;
    private transient StreamFactory factory;
    private BeanIOConfiguration configuration = new BeanIOConfiguration();

    public BeanIODataFormat() {
    }

    public BeanIODataFormat(String mapping, String streamName) {
        setMapping(mapping);
        setStreamName(streamName);
    }

    @Override
    public String getDataFormatName() {
        return "beanio";
    }

    @Override
    protected void doStart() throws Exception {
        ObjectHelper.notNull(getStreamName(), "Stream name not configured.");
        if (factory == null) {
            // Create the stream factory that will be used to read/write objects.
            factory = StreamFactory.newInstance();

            // Load the mapping file using the resource helper to ensure it can be loaded in OSGi and other environments
            InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(getCamelContext(), getMapping());
            try {
                if (getProperties() != null) {
                    factory.load(is, getProperties());
                } else {
                    factory.load(is);
                }
            } finally {
                IOHelper.close(is);
            }
        }
    }

    @Override
    protected void doStop() throws Exception {
        factory = null;
    }

    public CamelContext getCamelContext() {
        return camelContext;
    }

    public void setCamelContext(CamelContext camelContext) {
        this.camelContext = camelContext;
    }

    StreamFactory getFactory() {
        return factory;
    }

    public void marshal(Exchange exchange, Object body, OutputStream stream) throws Exception {
        List<Object> models = getModels(exchange, body);
        writeModels(stream, models);
    }

    public Object unmarshal(Exchange exchange, InputStream stream) throws Exception {
        return readModels(exchange, stream);
    }

    @SuppressWarnings("unchecked")
    private List<Object> getModels(Exchange exchange, Object body) {
        List<Object> models;
        if ((models = exchange.getContext().getTypeConverter().convertTo(List.class, body)) == null) {
            models = new ArrayList<Object>();
            Iterator<Object> it = ObjectHelper.createIterator(body);
            while (it.hasNext()) {
                models.add(it.next());
            }
        }
        return models;
    }

    private void writeModels(OutputStream stream, List<Object> models) {
        BufferedWriter streamWriter = IOHelper.buffered(new OutputStreamWriter(stream, getEncoding()));
        BeanWriter out = factory.createWriter(getStreamName(), streamWriter);

        for (Object obj : models) {
            out.write(obj);
        }

        out.flush();
        out.close();
    }

    private List<Object> readModels(Exchange exchange, InputStream stream) {
        List<Object> results = new ArrayList<Object>();
        BufferedReader streamReader = IOHelper.buffered(new InputStreamReader(stream, getEncoding()));

        BeanReader in = factory.createReader(getStreamName(), streamReader);

        try {
            if (ObjectHelper.isNotEmpty(configuration.getBeanReaderErrorHandler())) {
                in.setErrorHandler(configuration.getBeanReaderErrorHandler());
            } else {
                in.setErrorHandler(new BeanIOErrorHandler(configuration));
            }

            Object readObject;
            while ((readObject = in.read()) != null) {
                if (readObject instanceof BeanIOHeader) {
                    exchange.getOut().getHeaders().putAll(((BeanIOHeader) readObject).getHeaders());
                }
                results.add(readObject);
            }
        } finally {
            in.close();
        }

        return results;
    }

    public String getMapping() {
        return configuration.getMapping();
    }

    public void setIgnoreUnexpectedRecords(boolean ignoreUnexpectedRecords) {
        configuration.setIgnoreUnexpectedRecords(ignoreUnexpectedRecords);
    }

    public void setProperties(Properties properties) {
        configuration.setProperties(properties);
    }

    public void setStreamName(String streamName) {
        configuration.setStreamName(streamName);
    }

    public boolean isIgnoreUnidentifiedRecords() {
        return configuration.isIgnoreUnidentifiedRecords();
    }

    public boolean isIgnoreInvalidRecords() {
        return configuration.isIgnoreInvalidRecords();
    }

    public void setIgnoreInvalidRecords(boolean ignoreInvalidRecords) {
        configuration.setIgnoreInvalidRecords(ignoreInvalidRecords);
    }

    public void setEncoding(Charset encoding) {
        configuration.setEncoding(encoding);
    }

    public boolean isIgnoreUnexpectedRecords() {
        return configuration.isIgnoreUnexpectedRecords();
    }

    public Properties getProperties() {
        return configuration.getProperties();
    }

    public String getStreamName() {
        return configuration.getStreamName();
    }

    public void setMapping(String mapping) {
        configuration.setMapping(mapping);
    }

    public void setIgnoreUnidentifiedRecords(boolean ignoreUnidentifiedRecords) {
        configuration.setIgnoreUnidentifiedRecords(ignoreUnidentifiedRecords);
    }

    public Charset getEncoding() {
        return configuration.getEncoding();
    }

    public BeanReaderErrorHandler getBeanReaderErrorHandler() {
        return configuration.getBeanReaderErrorHandler();
    }

    public void setBeanReaderErrorHandler(BeanReaderErrorHandler beanReaderErrorHandler) {
        configuration.setBeanReaderErrorHandler(beanReaderErrorHandler);
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>pygame — Pygame v1.9.2 documentation</title>
    <link rel="stylesheet" href="../_static/pygame.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/pygame.ico"/>
    <link rel="top" title="Pygame v1.9.2 documentation" href="../index.html" />
    <link rel="next" title="pygame.Rect" href="rect.html" />
    <link rel="prev" title="pygame.pixelcopy" href="pixelcopy.html" />

pygame documentation

	    ||
	    Pygame Home ||
	    Help Contents ||
	    Reference Index ||

	    camera ||
	    cdrom ||
	    Color ||
	    cursors ||
	    display ||
	    draw ||
	    event ||
	    examples ||
	    font ||
	    freetype ||
	    gfxdraw ||
	    image ||
	    joystick ||
	    key ||
	    locals ||
	    mask ||
	    math ||
	    midi ||
	    mixer ||
	    mouse ||
	    movie ||
	    music ||
	    Overlay ||
	    PixelArray ||
	    pixelcopy ||
	    pygame ||
	    Rect ||
	    scrap ||
	    sndarray ||
	    sprite ||
	    Surface ||
	    surfarray ||
	    tests ||
	    time ||
	    transform ||
	    version

<tt class="docutils literal">pygame</tt>

the top level pygame package

<colgroup>
<col width="29%" />
<col width="1%" />
<col width="70%" />
</colgroup>

pygame.init
—
initialize all imported pygame modules

pygame.quit
—
uninitialize all pygame modules

pygame.error
—
standard pygame exception

pygame.get_error
—
get the current error message

pygame.set_error
—
set the current error message

pygame.get_sdl_version
—
get the version number of SDL

pygame.get_sdl_byteorder
—
get the byte order of SDL

pygame.register_quit
—
register a function to be called when pygame quits

pygame.encode_string
—
Encode a unicode or bytes object

pygame.encode_file_path
—
Encode a unicode or bytes object as a file system path

The pygame package represents the top-level package for others to use. Pygame
itself is broken into many submodules, but this does not affect programs that
use Pygame.

As a convenience, most of the top-level variables in pygame have been placed
inside a module named ‘pygame.locals’. This is meant to be used with ‘from
<tt class="xref py py-mod docutils literal">pygame.locals</tt>pygame constants import *’, in addition to ‘import pygame’.

When you ‘import pygame’ all available pygame submodules are automatically
imported. Be aware that some of the pygame modules are considered “optional”,
and may not be available. In that case, Pygame will provide a placeholder
object instead of the module, which can be used to test for availability.

<tt class="descclassname">pygame.</tt><tt class="descname">init</tt><big>(</big><big>)</big>¶

initialize all imported pygame modules

init() -> (numpass, numfail)

Initialize all imported Pygame modules. No exceptions will be raised if a
module fails, but the total number if successful and failed inits will be
returned as a tuple. You can always initialize individual modules manually,
but <tt class="xref py py-func docutils literal">pygame.init()</tt>initialize all imported pygame modules is a convenient way to get everything started. The
<tt class="docutils literal">init()</tt> functions for individual modules will raise exceptions when they
fail.

You may want to initalise the different modules seperately to speed up your
program or to not use things your game does not.

It is safe to call this <tt class="docutils literal">init()</tt> more than once: repeated calls will have
no effect. This is true even if you have <tt class="docutils literal">pygame.quit()</tt> all the modules.

<tt class="descclassname">pygame.</tt><tt class="descname">quit</tt><big>(</big><big>)</big>¶

uninitialize all pygame modules

quit() -> None

Uninitialize all pygame modules that have previously been initialized. When
the Python interpreter shuts down, this method is called regardless, so your
program should not need it, except when it wants to terminate its pygame
resources and continue. It is safe to call this function more than once:
repeated calls have no effect.

Note, that <tt class="xref py py-func docutils literal">pygame.quit()</tt>uninitialize all pygame modules will not exit your program. Consider letting
your program end in the same way a normal python program will end.

exception <tt class="descclassname">pygame.</tt><tt class="descname">error</tt>¶

standard pygame exception

raise pygame.error(message)

This exception is raised whenever a pygame or <tt class="docutils literal">SDL</tt> operation fails. You
can catch any anticipated problems and deal with the error. The exception is
always raised with a descriptive message about the problem.

Derived from the RuntimeError exception, which can also be used to catch
these raised errors.

<tt class="descclassname">pygame.</tt><tt class="descname">get_error</tt><big>(</big><big>)</big>¶

get the current error message

get_error() -> errorstr

<tt class="docutils literal">SDL</tt> maintains an internal error message. This message will usually be
given to you when <tt class="xref py py-func docutils literal">pygame.error()</tt>standard pygame exception is raised. You will rarely need to
call this function.

<tt class="descclassname">pygame.</tt><tt class="descname">set_error</tt><big>(</big><big>)</big>¶

set the current error message

set_error(error_msg) -> None

<tt class="docutils literal">SDL</tt> maintains an internal error message. This message will usually be
given to you when <tt class="xref py py-func docutils literal">pygame.error()</tt>standard pygame exception is raised. You will rarely need to
call this function.

<tt class="descclassname">pygame.</tt><tt class="descname">get_sdl_version</tt><big>(</big><big>)</big>¶

get the version number of SDL

get_sdl_version() -> major, minor, patch

Returns the three version numbers of the <tt class="docutils literal">SDL</tt> library. This version is
built at compile time. It can be used to detect which features may not be
available through Pygame.

get_sdl_version is new in pygame 1.7.0

<tt class="descclassname">pygame.</tt><tt class="descname">get_sdl_byteorder</tt><big>(</big><big>)</big>¶

get the byte order of SDL

get_sdl_byteorder() -> int

Returns the byte order of the <tt class="docutils literal">SDL</tt> library. It returns <tt class="docutils literal">LIL_ENDIAN</tt> for
little endian byte order and <tt class="docutils literal">BIG_ENDIAN</tt> for big endian byte order.

get_sdl_byteorder is new in pygame 1.8

<tt class="descclassname">pygame.</tt><tt class="descname">register_quit</tt><big>(</big><big>)</big>¶

register a function to be called when pygame quits

register_quit(callable) -> None

When <tt class="xref py py-func docutils literal">pygame.quit()</tt>uninitialize all pygame modules is called, all registered quit functions are
called. Pygame modules do this automatically when they are initializing.
This function is not be needed for regular pygame users.

<tt class="descclassname">pygame.</tt><tt class="descname">encode_string</tt><big>(</big><big>)</big>¶

Encode a unicode or bytes object

encode_string([obj [, encoding [, errors [, etype]]]]) -> bytes or None

obj: If unicode, encode; if bytes, return unaltered; if anything else,
return None; if not given, raise SyntaxError.

encoding (string): If present, encoding to use. The default is
‘unicode_escape’.

errors (string): If given, how to handle unencodable characters. The default
is ‘backslashreplace’.

etype (exception type): If given, the exception type to raise for an
encoding error. The default is UnicodeEncodeError, as returned by
<tt class="docutils literal">PyUnicode_AsEncodedString()</tt>. For the default encoding and errors values
there should be no encoding errors.

This function is used in encoding file paths. Keyword arguments are
supported.

Added in Pygame 1.9.2 (primarily for use in unit tests)

<tt class="descclassname">pygame.</tt><tt class="descname">encode_file_path</tt><big>(</big><big>)</big>¶

Encode a unicode or bytes object as a file system path

encode_file_path([obj [, etype]]) -> bytes or None

obj: If unicode, encode; if bytes, return unaltered; if anything else,
return None; if not given, raise SyntaxError.

etype (exception type): If given, the exception type to raise for an
encoding error. The default is UnicodeEncodeError, as returned by
<tt class="docutils literal">PyUnicode_AsEncodedString()</tt>.

This function is used to encode file paths in Pygame. Encoding is to the
codec as returned by <tt class="docutils literal">sys.getfilesystemencoding()</tt>. Keyword arguments are
supported.

Added in Pygame 1.9.2 (primarily for use in unit tests)

<tt class="docutils literal">pygame.version</tt>

small module containing version information

<colgroup>
<col width="36%" />
<col width="2%" />
<col width="63%" />
</colgroup>

pygame.version.ver
—
version number as a string

pygame.version.vernum
—
tupled integers of the version

This module is automatically imported into the pygame package and offers a few
variables to check with version of pygame has been imported.

<tt class="descclassname">pygame.version.</tt><tt class="descname">ver</tt>¶

version number as a string

ver = ‘1.2’

This is the version represented as a string. It can contain a micro release
number as well, <tt class="docutils literal">e.g.</tt>, ‘1.5.2’

<tt class="descclassname">pygame.version.</tt><tt class="descname">vernum</tt>¶

tupled integers of the version

vernum = (1, 5, 3)

This variable for the version can easily be compared with other version
numbers of the same format. An example of checking Pygame version numbers
would look like this:

if pygame.version.vernum < (1, 5):
    print 'Warning, older version of Pygame (%s)' %  pygame.version.ver
    disable_advanced_features = True

Navigation

          index

          next |

          previous |

Pygame v1.9.2 documentation »

        © Copyright 2011, Pygame Developers.


text:
'use strict';

angular.module('mean.system').controller('IndexController', ['$scope', 'Global', '$http', '$q', 'MeanUser',
  function($scope, Global, $http, $q, MeanUser) {
    $scope.global = Global;
    $scope.user = MeanUser;

    $scope.demoLogin = function() {
      MeanUser.login({
        email: 'demo@traction.com',
        password: 'demo1234',
        redirect: false
      });
    };

    // just log in
    MeanUser.login({
      email: 'demo@traction.com',
      password: 'demo1234',
      redirect: false
    });
  }
]);