text:
"""Reports doit execution status/results"""

import sys
import time
import datetime
import json
from io import StringIO

class ConsoleReporter(object):
    """Default reporter. print results on console/terminal (stdout/stderr)

    @ivar failure_verbosity: (int) include captured stdout/stderr on failure
                             report even if already shown.
    """
    # short description, used by the help system
    desc = 'console output'

    def __init__(self, outstream, options):
        # save non-successful result information (include task errors)
        self.failures = []
        self.runtime_errors = []
        self.failure_verbosity = options.get('failure_verbosity', 0)
        self.outstream = outstream

    def write(self, text):
        self.outstream.write(text)

    def initialize(self, tasks, selected_tasks):
        """called just after tasks have been loaded before execution starts"""
        pass

    def get_status(self, task):
        """called when task is selected (check if up-to-date)"""
        pass

    def execute_task(self, task):
        """called when execution starts"""
        # ignore tasks that do not define actions
        # ignore private/hidden tasks (tasks that start with an underscore)
        if task.actions and (task.name[0] != '_'):
            self.write('.  %s\n' % task.title())

    def add_failure(self, task, exception):
        """called when execution finishes with a failure"""
        result = {'task': task, 'exception':exception}
        self.failures.append(result)
        self._write_failure(result)

    def add_success(self, task):
        """called when execution finishes successfully"""
        pass

    def skip_uptodate(self, task):
        """skipped up-to-date task"""
        if task.name[0] != '_':
            self.write("-- %s\n" % task.title())

    def skip_ignore(self, task):
        """skipped ignored task"""
        self.write("!! %s\n" % task.title())

    def cleanup_error(self, exception):
        """error during cleanup"""
        sys.stderr.write(exception.get_msg())

    def runtime_error(self, msg):
        """error from doit (not from a task execution)"""
        # saved so they are displayed after task failures messages
        self.runtime_errors.append(msg)

    def teardown_task(self, task):
        """called when starts the execution of teardown action"""
        pass

    def _write_failure(self, result, write_exception=True):
        msg = '%s - taskid:%s\n' % (result['exception'].get_name(),
                                    result['task'].name)
        self.write(msg)
        if write_exception:
            self.write(result['exception'].get_msg())
            self.write("\n")

    def complete_run(self):
        """called when finished running all tasks"""
        # if test fails print output from failed task
        for result in self.failures:
            task = result['task']
            # makes no sense to print output if task was not executed
            if not task.executed:
                continue
            show_err = task.verbosity < 1 or self.failure_verbosity > 0
            show_out = task.verbosity < 2 or self.failure_verbosity == 2
            if show_err or show_out:
                self.write("#"*40 + "\n")
            if show_err:
                self._write_failure(result,
                                    write_exception=self.failure_verbosity)
                err = "".join([a.err for a in task.actions if a.err])
                self.write("{} <stderr>:\n{}\n".format(task.name, err))
            if show_out:
                out = "".join([a.out for a in task.actions if a.out])
                self.write("{} <stdout>:\n{}\n".format(task.name, out))

        if self.runtime_errors:
            self.write("#"*40 + "\n")
            self.write("Execution aborted.\n")
            self.write("\n".join(self.runtime_errors))
            self.write("\n")

class ExecutedOnlyReporter(ConsoleReporter):
    """No output for skipped (up-to-date) and group tasks

    Produces zero output unless a task is executed
    """
    desc = 'console, no output for skipped (up-to-date) and group tasks'

    def skip_uptodate(self, task):
        """skipped up-to-date task"""
        pass

    def skip_ignore(self, task):
        """skipped ignored task"""
        pass

class ZeroReporter(ConsoleReporter):
    """Report only internal errors from doit"""
    desc = 'report only internal errors from doit'

    def _just_pass(self, *args):
        """over-write base to do nothing"""
        pass

    get_status = execute_task = add_failure = add_success \
        = skip_uptodate = skip_ignore = teardown_task = complete_run \
        = _just_pass

    def runtime_error(self, msg):
        sys.stderr.write(msg)

class TaskResult(object):
    """result object used by JsonReporter"""
    # FIXME what about returned value from python-actions ?
    def __init__(self, task):
        self.task = task
        self.result = None # fail, success, up-to-date, ignore
        self.out = None # stdout from task
        self.err = None # stderr from task
        self.error = None # error from doit (exception traceback)
        self.started = None # datetime when task execution started
        self.elapsed = None # time (in secs) taken to execute task
        self._started_on = None # timestamp
        self._finished_on = None # timestamp

    def start(self):
        """called when task starts its execution"""
        self._started_on = time.time()

    def set_result(self, result, error=None):
        """called when task finishes its execution"""
        self._finished_on = time.time()
        self.result = result
        line_sep = "\n<------------------------------------------------>\n"
        self.out = line_sep.join([a.out for a in self.task.actions if a.out])
        self.err = line_sep.join([a.err for a in self.task.actions if a.err])
        self.error = error

    def to_dict(self):
        """convert result data to dictionary"""
        if self._started_on is not None:
            started = datetime.datetime.utcfromtimestamp(self._started_on)
            self.started = str(started)
            self.elapsed = self._finished_on - self._started_on
        return {'name': self.task.name,
                'result': self.result,
                'out': self.out,
                'err': self.err,
                'error': self.error,
                'started': self.started,
                'elapsed': self.elapsed}

class JsonReporter(object):
    """output results in JSON format

    - out (str)
    - err (str)
    - tasks (list - dict):
         - name (str)
         - result (str)
         - out (str)
         - err (str)
         - error (str)
         - started (str)
         - elapsed (float)
    """

    desc = 'output in JSON format'

    def __init__(self, outstream, options=None): #pylint: disable=W0613
        # options parameter is not used
        # json result is sent to stdout when doit finishes running
        self.t_results = {}
        # when using json reporter output can not contain any other output
        # than the json data. so anything that is sent to stdout/err needs to
        # be captured.
        self._old_out = sys.stdout
        sys.stdout = StringIO()
        self._old_err = sys.stderr
        sys.stderr = StringIO()
        self.outstream = outstream
        # runtime and cleanup errors
        self.errors = []

    def get_status(self, task):
        """called when task is selected (check if up-to-date)"""
        self.t_results[task.name] = TaskResult(task)

    def execute_task(self, task):
        """called when execution starts"""
        self.t_results[task.name].start()

    def add_failure(self, task, exception):
        """called when execution finishes with a failure"""
        self.t_results[task.name].set_result('fail', exception.get_msg())

    def add_success(self, task):
        """called when execution finishes successfully"""
        self.t_results[task.name].set_result('success')

    def skip_uptodate(self, task):
        """skipped up-to-date task"""
        self.t_results[task.name].set_result('up-to-date')

    def skip_ignore(self, task):
        """skipped ignored task"""
        self.t_results[task.name].set_result('ignore')

    def cleanup_error(self, exception):
        """error during cleanup"""
        self.errors.append(exception.get_msg())

    def runtime_error(self, msg):
        """error from doit (not from a task execution)"""
        self.errors.append(msg)

    def teardown_task(self, task):
        """called when starts the execution of teardown action"""
        pass

    def complete_run(self):
        """called when finished running all tasks"""
        # restore stdout
        log_out = sys.stdout.getvalue()
        sys.stdout = self._old_out
        log_err = sys.stderr.getvalue()
        sys.stderr = self._old_err

        # add errors together with stderr output
        if self.errors:
            log_err += "\n".join(self.errors)

        task_result_list = [
            tr.to_dict() for tr in self.t_results.values()]
        json_data = {'tasks': task_result_list,
                     'out': log_out,
                     'err': log_err}
        # indent not available on simplejson 1.3 (debian etch)
        # json.dump(json_data, sys.stdout, indent=4)
        json.dump(json_data, self.outstream)


text:
angular.module('PGSQLApp')
    .controller('connectionDialogCtrl', function ($log, $mdDialog, $mdToast, $scope, connectionManager, toastManager) {
        $scope.formData = {
            name: null,
            host: 'localhost',
            port: '5432',
            username: 'postgres',
            password: 'root',
            savePassword: false,
            database: 'afApp'
        }

        $scope.hide = function () {
            $mdDialog.hide();
        };

        $scope.cancel = function () {
            $mdDialog.cancel();
        };

        $scope.test = function () {
            let connectionInfo = createConnectionInfo()
            console.log(connectionInfo)
            connectionManager.testConnection(connectionInfo)
                .then(() => {
                    toastManager.showSuccessToast(`Connection successful.`)
                })
                .catch((err) => {
                    let cd = err.data && err.data.code ? err.data.code : null
                    switch(cd){
                        case "28P01":
                            toastManager.showErrorToast(`[${cd}] Authentication failed.`)
                            break;
                        case "3D000":
                            toastManager.showErrorToast(`[${cd}] Authentication failed. Bad database?`)
                            break;
                        case 'ENOTFOUND':
                            toastManager.showErrorToast(`[${cd}] Unable to connect. Bad host?`)
                            break;
                        default:
                            toastManager.showErrorToast(`[${cd}] Connection error.`)
                    }
                })
        }

        $scope.answer = function (answer) {
            let connectionInfo = createConnectionInfo()
            connectionManager.addConnection(connectionInfo)
                .then(()=>{
                    $mdDialog.hide();
                })
                .catch((err)=>{
                    toastManager.showErrorToast(`Failed to add connection.`)
                })
        };

        function createConnectionInfo() {
            return new ConnectionInfo($scope.formData)
        }
    })

redpajama_set_name: RedPajamaGithub


text:
package mya.greenlog.com.moveyourass;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import myaddd.greenlog.com.shared.MYAService;
import myaddd.greenlog.com.shared.State;

public class MYAServiceWear extends MYAService {
    private static final String TAG = MYAServiceWear.class.getSimpleName();

    private NotificationManager mNotificationManager;
    private static final long[] VIBRATION_PATTERN_NEED_REST = {0, 150, 500, 150, 500, 150};
    private static final long[] VIBRATION_PATTERN_REST_COMPLETED = {0, 300};
    private static final long NOTIFICATION_REST_COMPLETED_TIMEOUT_MS = 1000 * 15;

    private Timer mDelayedNotifyCancelTimer;

    @Override
    public void onCreate() {
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onInactivityExpired() {
        showNotificationNeedRest();
    }

    @Override
    protected void onRestCompleted() {
        showNotificationRestCompleted();
    }

    @Override
    protected void onStepDetected(final State.SuspendState suspendState, final long lastStepDetectedAgo, final long restStepsNeed, final long minimumRestSteps) {
        showNotificationStepDetected(restStepsNeed, minimumRestSteps);
    }

    @Override
    protected void onSuspendStateChanged(final State.SuspendState suspendState, final long lastStepDetectedAgo, final long restStepsNeed) {
        if (suspendState != State.SuspendState.NotSuspended) {
            mNotificationManager.cancelAll();
        }
    }

    @Override
    public int onStartCommand(final Intent intent, final int flags, final int startId) {
        if (intent != null) {
            if (intent.getAction() != null) {
                switch (intent.getAction()) {
                    case COMMAND_SET_SUSPEND:
                        // cancel all notifications
                        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancelAll();
                        break;
                }
            }
        }

        return super.onStartCommand(intent, flags, startId);
    }

    private void showNotificationNeedRest() {
        mNotificationManager.cancelAll();
//
//        final Intent intentStartApp = new Intent(this, MainActivity.class);
//        final TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
//        stackBuilder.addParentStack(MainActivity.class);
//        stackBuilder.addNextIntent(intentStartApp);
//        final PendingIntent pendingIntentStartApp = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
//
//        int lastSnoozeId = mSettingsManager.readSnoozeModeLastId();
//        String lastSnoozeText = getResources().getStringArray(R.array.snooze_modes_values)[lastSnoozeId];
//
//        final Intent intentDefaultSnooze = new Intent(this, MYAServiceMobile.class);
//        intentDefaultSnooze.setAction(MYAService.COMMAND_SET_SUSPEND);
//        intentDefaultSnooze.putExtra(MYAService.COMMAND_SET_SUSPEND_STATE,
//                SnoozeModes.getSuspendState(lastSnoozeId).ordinal());
//        intentDefaultSnooze.putExtra(MYAService.COMMAND_SET_SUSPEND_TIMEOUT,
//                SnoozeModes.getSuspendTimeoutSeconds(lastSnoozeId));
//        final PendingIntent pendingIntentDefaultSnooze = PendingIntent.getService(this, 0, intentDefaultSnooze, PendingIntent.FLAG_UPDATE_CURRENT);
//
//        final Intent intentSnoozeSelect = new Intent(this, SnoozePickerActivity.class);
//        final PendingIntent pendingSnoozeSelect = PendingIntent.getActivity(this, 0, intentSnoozeSelect, PendingIntent.FLAG_UPDATE_CURRENT);

        final Notification notification = (new NotificationCompat.Builder(this))
                .setContentTitle(getString(R.string.need_rest_title))
                .setContentText(getString(R.string.need_rest_content))
                .setWhen((new Date()).getTime())
//                .setContentIntent(pendingIntentStartApp)
//                .addAction(R.drawable.ic_snooze_white_24dp, lastSnoozeText, pendingIntentDefaultSnooze)
//                .addAction(R.drawable.ic_list_white_24dp, getString(R.string.need_rest_action_snooze_select), pendingSnoozeSelect)
//                .setDeleteIntent(pendingIntentDefaultSnooze)
                .setAutoCancel(true)
                .setLocalOnly(true)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setLights(0xff3f51b5, 500, 500)
                .setVibrate(VIBRATION_PATTERN_NEED_REST)
                .build();
        mNotificationManager.notify(1, notification);
    }

    private void showNotificationRestCompleted() {
        mNotificationManager.cancelAll();

//        final Intent intentStartApp = new Intent(this, MainActivity.class);
//        final TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
//        stackBuilder.addParentStack(MainActivity.class);
//        stackBuilder.addNextIntent(intentStartApp);
//        final PendingIntent pendingIntentStartApp = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        final Notification notification = (new NotificationCompat.Builder(this))
                .setContentTitle(getString(R.string.rest_completed_title))
                .setContentText(getString(R.string.rest_completed_content))
                .setWhen((new Date()).getTime())
//                .setContentIntent(pendingIntentStartApp)
                .setAutoCancel(true)
                .setLocalOnly(true)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setVibrate(VIBRATION_PATTERN_REST_COMPLETED)
                .build();
        mNotificationManager.notify(1, notification);

        if (mDelayedNotifyCancelTimer != null) {
            mDelayedNotifyCancelTimer.cancel();
            mDelayedNotifyCancelTimer.purge();
        }
        mDelayedNotifyCancelTimer = new Timer();
        mDelayedNotifyCancelTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mNotificationManager.cancelAll();
                mDelayedNotifyCancelTimer = null;
            }
        }, NOTIFICATION_REST_COMPLETED_TIMEOUT_MS);
    }

    private void showNotificationStepDetected(final long restStepsNeed, final long minimumRestSteps) {
        mNotificationManager.cancel(1);

//        final Intent intentStartApp = new Intent(this, MainActivity.class);
//        final TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
//        stackBuilder.addParentStack(MainActivity.class);
//        stackBuilder.addNextIntent(intentStartApp);
//        final PendingIntent pendingIntentStartApp = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        final Notification notification = (new NotificationCompat.Builder(this))
                .setContentTitle(getString(R.string.keep_going))
                .setContentText(getString(R.string.steps_to_complete_rest, restStepsNeed))
                .setWhen((new Date()).getTime())
//                .setContentIntent(pendingIntentStartApp)
                .setAutoCancel(true)
                .setLocalOnly(true)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setProgress((int) minimumRestSteps, (int) (minimumRestSteps - restStepsNeed), false)
                .build();
        mNotificationManager.notify(2, notification);
    }
}


text:
package net.floodlightcontroller.packet;

/**
*
* @author David Erickson (daviderickson@cs.stanford.edu)
*/
public interface IPacket {
    /**
     *
     * @return
     */
    public IPacket getPayload();

    /**
     *
     * @param packet
     * @return
     */
    public IPacket setPayload(IPacket packet);

    /**
     *
     * @return
     */
    public IPacket getParent();

    /**
     *
     * @param packet
     * @return
     */
    public IPacket setParent(IPacket packet);

    /**
     * Reset any checksums as needed, and call resetChecksum on all parents
     */
    public void resetChecksum();

    /**
     * Sets all payloads parent packet if applicable, then serializes this
     * packet and all payloads
     * @return a byte[] containing this packet and payloads
     */
    public byte[] serialize();

    /**
     * Deserializes this packet layer and all possible payloads
     * @param data
     * @param offset offset to start deserializing from
     * @param length length of the data to deserialize
     * @return the deserialized data
     */
    public IPacket deserialize(byte[] data, int offset, int length);

    /** Clone this packet and its payload packet but not its parent.
     *
     * @return
     */
    public Object clone();
}


text:
package jace.config;

import jace.Emulator;
import jace.EmulatorUILogic;
import jace.core.Computer;
import jace.core.Keyboard;
import jace.core.Utility;
import javafx.collections.ObservableList;
import javafx.scene.control.TreeItem;
import javafx.scene.image.ImageView;

import java.io.*;
import java.lang.reflect.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;

/**
 * Manages the configuration state of the emulator components.
 *
 * @author Brendan Robert (BLuRry) brendan.robert@gmail.com
 */
public class Configuration implements Reconfigurable {

    private static Method findAnyMethodByName(Class<? extends Reconfigurable> aClass, String m) {
        for (Method method : aClass.getMethods()) {
            if (method.getName().equals(m)) {
                return method;
            }
        }
        return null;
    }

    static ConfigurableField getConfigurableFieldInfo(Reconfigurable subject, String settingName) {
        Field f;
        try {
            f = subject.getClass().getField(settingName);
        } catch (NoSuchFieldException | SecurityException ex) {
            return null;
        }
        ConfigurableField annotation = f.getAnnotation(ConfigurableField.class);
        return annotation;
    }

    public static String getShortName(ConfigurableField f, String longName) {
        return (f != null && !f.shortName().equals("")) ? f.shortName() : longName;
    }

    public static InvokableAction getInvokableActionInfo(Reconfigurable subject, String actionName) {
        for (Method m : subject.getClass().getMethods()) {
            if (m.getName().equals(actionName) && m.isAnnotationPresent(InvokableAction.class)) {
                return m.getAnnotation(InvokableAction.class);
            }
        }
        return null;
    }

    public static Optional<ImageView> getChangedIcon() {
        return Utility.loadIcon("icon_exclaim.gif").map(ImageView::new);
    }

    @Override
    public String getName() {
        return "Configuration";
    }

    @Override
    public String getShortName() {
        return "cfg";
    }

    @Override
    public void reconfigure() {
    }

    /**
     * Represents a serializable configuration node as part of a tree. The root
     * node should be a single instance (e.g. Computer) The child nodes should
     * be all object instances that stem from each object The overall goal of
     * this class is two-fold: 1) Provide a navigable manner to inspect
     * configuration 2) Provide a simple persistence mechanism to load/store
     * configuration
     */
    public static class ConfigNode extends TreeItem implements Serializable {

        public transient ConfigNode root;
        public transient ConfigNode parent;
        private transient final ObservableList<ConfigNode> children;
        public transient Reconfigurable subject;
        private transient boolean changed = true;

        public Map<String, Serializable> settings = new TreeMap<>();
        public Map<String, String[]> hotkeys = new TreeMap<>();
        public String name;
        private String id;

        private void writeObject(java.io.ObjectOutputStream out)
                throws IOException {
            out.writeObject(id);
            out.writeObject(name);
            out.writeObject(settings);
            out.writeObject(hotkeys);
            out.writeObject(children.toArray());
        }

        private void readObject(java.io.ObjectInputStream in)
                throws IOException, ClassNotFoundException {
            children.setAll(super.getChildren());
            id = (String) in.readObject();
            name = (String) in.readObject();
            settings = (Map) in.readObject();
            hotkeys = (Map) in.readObject();
            Object[] nodeArray = (Object[]) in.readObject();
            synchronized (children) {
                for (Object child : nodeArray) {
                    children.add((ConfigNode) child);
                }
            }
        }

        private void readObjectNoData()
                throws ObjectStreamException {
            name = "Bad read";
        }

        @Override
        public String toString() {
            return name;
        }

        public ConfigNode(Reconfigurable subject) {
            this(null, subject);
            this.root = null;
            this.setExpanded(true);
        }

        public ConfigNode(ConfigNode parent, Reconfigurable subject) {
            this(parent, subject, subject.getName());
        }

        public ConfigNode(ConfigNode parent, Reconfigurable subject, String id) {
            super();
            this.id = id;
            this.name = subject.getName();
            this.subject = subject;
            this.children = getChildren();
            this.parent = parent;
            if (this.parent != null) {
                this.root = this.parent.root != null ? this.parent.root : this.parent;
            }
            setValue(toString());
        }

        public void setFieldValue(String field, Serializable value) {
            setChanged(true);
            if (value != null) {
                if (value.equals(getFieldValue(field))) {
                    return;
                }
            } else {
                if (getFieldValue(field) == null) {
                    return;
                }
            }
            setRawFieldValue(field, value);
        }

        public void setRawFieldValue(String field, Serializable value) {
            settings.put(field, value);
        }

        public Serializable getFieldValue(String field) {
            return settings.get(field);
        }

        public Set<String> getAllSettingNames() {
            return settings.keySet();
        }

        @Override
        final public ObservableList<ConfigNode> getChildren() {
            return super.getChildren();
        }

        private boolean removeChild(String childName) {
            ConfigNode child = findChild(childName);
            synchronized (children) {
                return children.remove(child);
            }
        }

        private ConfigNode findChild(String id) {
            synchronized (children) {
                for (ConfigNode node : children) {
                    if (id.equalsIgnoreCase(node.id)) {
                        return node;
                    }
                }
            }
            return null;
        }

        private void putChild(String id, ConfigNode newChild) {
            removeChild(id);
            int index = 0;
            for (ConfigNode node : children) {
                int compare = node.toString().compareToIgnoreCase(id);
                if (compare >= 0) {
                    break;
                } else {
                    index++;
                }
            }
            synchronized (children) {
                children.add(index, newChild);
            }
        }

        private void setChanged(boolean b) {
            changed = b;
            if (!changed) {
                setGraphic(null);
            } else {
                getChangedIcon().ifPresent(this::setGraphic);
            }
        }

        public Stream<ConfigNode> getTreeAsStream() {
            synchronized (children) {
                return Stream.concat(
                        Stream.of(this),
                        children.stream().flatMap(ConfigNode::getTreeAsStream));
            }
        }
    }
    public static ConfigNode BASE;
    public static EmulatorUILogic ui = Emulator.logic;
    public static Computer emulator = Emulator.getComputer();
    @ConfigurableField(name = "Autosave Changes", description = "If unchecked, changes are only saved when the Save button is pressed.")
    public static boolean saveAutomatically = false;

    public static void buildTree() {
        BASE = new ConfigNode(new Configuration());
        buildTree(BASE, new LinkedHashSet());
    }

    private static void buildTree(ConfigNode node, Set visited) {
        if (node.subject == null) {
            return;
        }

        for (Method m : node.subject.getClass().getMethods()) {
            if (!m.isAnnotationPresent(InvokableAction.class)) {
                continue;
            }
            InvokableAction action = m.getDeclaredAnnotation(InvokableAction.class);
            node.hotkeys.put(m.getName(), action.defaultKeyMapping());
        }

        for (Field f : node.subject.getClass().getFields()) {
//            System.out.println("Evaluating field " + f.getName());
            try {
                Object o = f.get(node.subject);
                if (o == null || !f.getType().isPrimitive() && f.getType() != String.class && visited.contains(o)) {
                    continue;
                }
                visited.add(o);
//                System.out.println(o.getClass().getName());
                // If the object in question is not reconfigurable,
                // skip over it and investigate its fields instead
//                if (o.getClass().isAssignableFrom(Reconfigurable.class)) {
//                if (Reconfigurable.class.isAssignableFrom(o.getClass())) {
                if (f.isAnnotationPresent(ConfigurableField.class)) {
                    if (ISelection.class.isAssignableFrom(o.getClass())) {
                        ISelection selection = (ISelection) o;
                        node.setRawFieldValue(f.getName(), (Serializable) selection.getSelections().get(selection.getValue()));
                    } else {
                        node.setRawFieldValue(f.getName(), (Serializable) o);
                    }
                    continue;
                }

                if (o instanceof Reconfigurable) {
                    Reconfigurable r = (Reconfigurable) o;
                    ConfigNode child = node.findChild(r.getName());
                    if (child == null || !child.subject.equals(o)) {
                        child = new ConfigNode(node, r);
                        node.putChild(f.getName(), child);
                    }
                    buildTree(child, visited);
                } else if (o.getClass().isArray()) {
                    String fieldName = f.getName();
                    Class type = o.getClass().getComponentType();
//                    System.out.println("Evaluating " + node.subject.getShortName() + "." + fieldName + "; type is " + type.toGenericString());
                    List<Reconfigurable> children = new ArrayList<>();
                    if (!Reconfigurable.class.isAssignableFrom(type)) {
//                        System.out.println("Looking at type " + type.getName() + " to see if optional");
                        if (Optional.class.isAssignableFrom(type)) {
                            Type genericTypes = f.getGenericType();
//                            System.out.println("Looking at generic parmeters " + genericTypes.getTypeName() + " for reconfigurable class, type " + genericTypes.getClass().getName());
                            if (genericTypes instanceof GenericArrayType) {
                                GenericArrayType aType = (GenericArrayType) genericTypes;
                                ParameterizedType pType = (ParameterizedType) aType.getGenericComponentType();
                                if (pType.getActualTypeArguments().length != 1) {
                                    continue;
                                }
                                Type genericType = pType.getActualTypeArguments()[0];
//                                System.out.println("Looking at type " + genericType.getTypeName() + " to see if reconfigurable");
                                if (!Reconfigurable.class.isAssignableFrom((Class) genericType)) {
                                    continue;
                                }
                            } else {
                                continue;
                            }

                            synchronized (children) {
                                for (Optional<Reconfigurable> child : (Optional<Reconfigurable>[]) o) {
                                    if (child.isPresent()) {
                                        children.add(child.get());
                                    } else {
                                        children.add(null);
                                    }
                                }
                            }
                        }
                    } else {
                        children = Arrays.asList((Reconfigurable[]) o);
                    }
                    for (int i = 0; i < children.size(); i++) {
                        Reconfigurable child = children.get(i);
                        String childId = fieldName + i;
                        if (child == null) {
                            node.removeChild(childId);
                            continue;
                        }
                        ConfigNode grandchild = node.findChild(childId);
                        if (grandchild == null || !grandchild.subject.equals(child)) {
                            grandchild = new ConfigNode(node, child, childId);
                            node.putChild(childId, grandchild);
                        }
                        buildTree(grandchild, visited);
                    }
                }
            } catch (IllegalArgumentException | IllegalAccessException ex) {
                Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @InvokableAction(
            name = "Save settings",
            description = "Save all configuration settings as defaults",
            category = "general",
            alternatives = "save preferences;save defaults",
            defaultKeyMapping = "meta+ctrl+s"
    )
    public static void saveSettings() {
        {
            ObjectOutputStream oos = null;
            try {
                applySettings(BASE);
                oos = new ObjectOutputStream(new FileOutputStream(getSettingsFile()));
                oos.writeObject(BASE);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    if (oos != null) {
                        oos.close();
                    }
                } catch (IOException ex) {
                    Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    @InvokableAction(
            name = "Load settings",
            description = "Load all configuration settings previously saved",
            category = "general",
            alternatives = "load preferences;revert settings;revert preferences",
            defaultKeyMapping = "meta+ctrl+r"
    )
    public static void loadSettings() {
        boolean successful = false;
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream(getSettingsFile()));
            ConfigNode newRoot = (ConfigNode) ois.readObject();
            applyConfigTree(newRoot, BASE);
            successful = true;
        } catch (FileNotFoundException ex) {
            // This just means there are no settings to be saved -- just ignore it.
        } catch (InvalidClassException ex) {
            Logger.getLogger(Configuration.class.getName()).log(Level.WARNING, "Unable to load settings, Jace version is newer and incompatible with old settings.");
        } catch (ClassNotFoundException | IOException ex) {
            Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (ois != null) {
                    ois.close();
                }
                if (!successful) {
                    applySettings(BASE);
                }
            } catch (IOException ex) {
                Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void resetToDefaults() {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public static File getSettingsFile() {
        return new File(System.getProperty("user.dir"), ".jace.conf");
    }

    /**
     * Apply settings from node tree to the object model This also calls
     * "reconfigure" on objects in sequence
     *
     * @param node
     * @return True if any settings have changed in the node or any of its
     * descendants
     */
    public static boolean applySettings(ConfigNode node) {
        boolean resume = false;
        if (node == BASE) {
            resume = Emulator.getComputer().pause();
        }
        boolean hasChanged = false;
        if (node.changed) {
            doApply(node);
            hasChanged = true;
        }

        // Now that the object structure reflects the current configuration,
        // process reconfiguration from the children, etc.
        for (ConfigNode child : node.getChildren()) {
            hasChanged |= applySettings(child);
        }

        if (node.equals(BASE) && hasChanged) {
            buildTree();
        }

        if (resume) {
            Emulator.getComputer().resume();
        }

        return hasChanged;
    }

    private static void applyConfigTree(ConfigNode newRoot, ConfigNode oldRoot) {
        if (oldRoot == null || newRoot == null) {
            return;
        }
        oldRoot.settings = newRoot.settings;
        oldRoot.hotkeys = newRoot.hotkeys;
        if (oldRoot.subject != null) {
            doApply(oldRoot);
            buildTree(oldRoot, new HashSet());
        }
        newRoot.getChildren().stream().forEach((child) -> {
            String childName = child.toString();
            ConfigNode oldChild = oldRoot.findChild(childName);
            if (oldChild == null) {
                oldChild = oldRoot.findChild(child.id);
            }
            //            System.out.println("Applying settings for " + childName);
            applyConfigTree(child, oldChild);
        });
    }

    private static void doApply(ConfigNode node) {
        List<String> removeList = new ArrayList<>();
        Keyboard.unregisterAllHandlers(node.subject);
        node.hotkeys.keySet().stream().forEach((m) -> {
            Method method = findAnyMethodByName(node.subject.getClass(), m);
            if (method != null) {
                InvokableAction action = method.getAnnotation(InvokableAction.class);
                for (String code : node.hotkeys.get(m)) {
                    Keyboard.registerInvokableAction(action, node.subject, method, code);
                }
            }
        });

        for (String f : node.settings.keySet()) {
            try {
                Field ff = node.subject.getClass().getField(f);
//                System.out.println("Setting " + f + " to " + node.settings.get(f));
                Object val = node.settings.get(f);
                Class valType = (val != null ? val.getClass() : null);
                Class fieldType = ff.getType();
                if (ISelection.class.isAssignableFrom(fieldType)) {
                    ISelection selection = (ISelection) ff.get(node.subject);
                    try {
                        selection.setValue(val);
                    } catch (ClassCastException c) {
                        selection.setValueByMatch(String.valueOf(val));
                    }
                    continue;
                }
                if (val == null || valType.equals(fieldType)) {
                    ff.set(node.subject, val);
                    continue;
                }
//                System.out.println(fieldType);
                val = Utility.deserializeString(String.valueOf(val), fieldType, false);
//                System.out.println("Setting "+node.subject.getName()+" property "+ff.getName()+" with value "+String.valueOf(val));
                ff.set(node.subject, val);
            } catch (NoSuchFieldException ex) {
                System.out.println("Setting " + f + " no longer exists, skipping.");
                removeList.add(f);
            } catch (SecurityException | IllegalArgumentException | IllegalAccessException ex) {
                Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        removeList.stream().forEach((f) -> {
            node.settings.remove(f);
        });

        try {
            // When settings are applied, this could very well change the object structure
            // For example, if cards or other pieces of emulation are changed around
//            System.out.println("Reconfiguring "+node.subject.getName());
            node.subject.reconfigure();
        } catch (Exception ex) {
            Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex);
        }

        node.setChanged(false);
    }

    public static void applySettings(Map<String, String> settings) {
        for (Map.Entry<String, String> setting : settings.entrySet()) {
            Map<String, ConfigNode> shortNames = new HashMap<>();
            buildNodeMap(BASE, shortNames);

            String settingName = setting.getKey();
            String value = setting.getValue();
            String[] parts = settingName.split("\\.");
            if (parts.length != 2) {
                System.err.println("Unable to parse settting, should be in the form of DEVICE.PROPERTYNAME " + settingName);
                continue;
            }
            String deviceName = parts[0];
            String fieldName = parts[1];
            ConfigNode n = shortNames.get(deviceName.toLowerCase());
            if (n == null) {
                System.err.println("Unable to find device named " + deviceName + ", try one of these: " + Utility.join(shortNames.keySet(), ", "));
                continue;
            }

            boolean found = false;
            List<String> shortFieldNames = new ArrayList<>();
            for (String longName : n.getAllSettingNames()) {
                ConfigurableField f = getConfigurableFieldInfo(n.subject, longName);
                String shortName = getShortName(f, longName);
                shortFieldNames.add(shortName);

                if (fieldName.equalsIgnoreCase(longName) || fieldName.equalsIgnoreCase(shortName)) {
                    found = true;
                    n.setFieldValue(longName, value);
                    applySettings(n);
//                    n.subject.reconfigure();
                    buildTree();
                    System.out.println("Set property " + n.subject.getName() + "." + longName + " to " + value);
                    break;
                }
            }
            if (!found) {
                System.err.println("Unable to find property " + fieldName + " for device " + deviceName + ".  Try one of these: " + Utility.join(shortFieldNames, ", "));
            }
        }
    }

    private static void buildNodeMap(ConfigNode n, Map<String, ConfigNode> shortNames) {
//        System.out.println("Encountered " + n.subject.getShortName().toLowerCase());
        shortNames.put(n.subject.getShortName().toLowerCase(), n);
        synchronized (n.getChildren()) {
            n.getChildren().stream().forEach((c) -> {
                buildNodeMap(c, shortNames);
            });
        }
    }

    private static void printTree(ConfigNode n, String prefix, int i) {
        n.getAllSettingNames().stream().forEach((setting) -> {
            for (int j = 0; j < i; j++) {
                System.out.print(" ");
            }
            ConfigurableField f = null;
            try {
                f = n.subject.getClass().getField(setting).getAnnotation(ConfigurableField.class);
            } catch (NoSuchFieldException | SecurityException ex) {
                Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex);
            }
            String sn = (f != null && !f.shortName().equals("")) ? f.shortName() : setting;
            System.out.println(prefix + ">>" + setting + " (" + n.subject.getShortName() + "." + sn + ")");
        });
        n.getChildren().stream().forEach((c) -> {
            printTree(c, prefix + "." + c, i + 1);
        });
    }
}


text:
// EnemyElectricField.cpp: implementation of the EnemyElectricField class.
//
//////////////////////////////////////////////////////////////////////

#include "EnemyElectricField.h"

using namespace CR::Sound;

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

EnemyElectricField::EnemyElectricField(Level *curLevel, float tDelay, bool bOrientation, bool sDirection)
{
	SetRenderHealthBar(false);
	ipFlags.S_NO_GRAVITY = true;
	level_class = curLevel;

	this->tDelay = tDelay;
	this->bOrientation = bOrientation;

	dTimer = tDelay;

	this->sDirection = sDirection;

	SetWeaponDamage(10);
	ipFlags.S_VISIBLE = false;

	m_soundFX = ISound::Instance().CreateSoundFX(CR::AssetList::sounds::shock::ID);
}

EnemyElectricField::~EnemyElectricField()
{

}

HPTRect &EnemyElectricField::GetWeaponWorldLoc()
{
	if(bOrientation)
		SetRectangle(rectWeaponWorldLoc, 16, 96, -8, -48);
	else
		SetRectangle(rectWeaponWorldLoc, 96, 16, -48, -8);

	return rectWeaponWorldLoc;
}
//HPTRect &EnemyElectricField::GetWorldLoc()
//{
	/* Center (0,0), offset by Render Offset */
//	if(bOrientation)
//		SetRectangle(rectWorldLoc, 16, 96, -8, -48);
//	else
//		SetRectangle(rectWorldLoc, 96, 16, -48, -8);

//	return rectWorldLoc;
//}

void EnemyElectricField::processUpdate()
{
	ipFlags.S_DIRECTION = sDirection;

	if(!player_spr->IsAnimating())
	{
		ipFlags.S_VISIBLE = false;
		ipFlags.S_ATTACK = false;
	}

	dTimer -= time;

	if(dTimer < 0)
	{
		ipFlags.S_ATTACK = true;
		dTimer = tDelay;
		ipFlags.S_VISIBLE = true;
		SetAnimation(ENEMY_ELECTRIC_FIELD, 0, true, true, 10, true);
		if (ipFlags.S_ACTIVE) m_soundFX->Play();
	}

	/* Center (0,0), offset by Render Offset */
	if(bOrientation)
	{
		rectDX = 16;
		rectDY = 96;
		rectXOffset = -8;
		rectYOffset = -48;

	//	SetRectangle(rectWorldLoc, 16, 96, -8, -48);
	}
	else
	{
		rectDX = 96;
		rectDY = 12;
		rectXOffset = -48;
		rectYOffset = -6;

	//	SetRectangle(rectWorldLoc, 96, 16, -48, -8);
	}
}


text:
// Private reference to toString function.
var toString = Object.prototype.toString;

/**
 * Tests whether or not an object is an array.
 *
 * @private
 * @category Internal
 * @param {*} val The object to test.
 * @return {boolean} `true` if `val` is an array, `false` otherwise.
 * @example
 *
 *      isArray([]); //=> true
 *      isArray(true); //=> false
 *      isArray({}); //=> false
 */
export default Array.isArray || function _isArray(val) {
    return val && val.length >= 0 && toString.call(val) === '[object Array]';
};


text:
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true"
    android:interpolator="@android:anim/decelerate_interpolator" >

    <translate
        android:duration="@integer/config_slide_time"
        android:fromXDelta="100%p"
        android:toXDelta="0" />

    <alpha
        android:duration="@integer/config_slide_time"
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />
</set>
<!-- Copyright (C) 2013 Ahmed Nammari -->

<!-- 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. -->


text:
module Testbasics(tests) where
import Test.HUnit
import Database.HDBC
import TestUtils
import System.IO
import Control.Exception

openClosedb = sqlTestCase $
    do dbh <- connectDB
       disconnect dbh

multiFinish = dbTestCase (\dbh ->
    do sth <- prepare dbh "SELECT 1 + 1"
       r <- execute sth []
       assertEqual "basic count" 0 r
       finish sth
       finish sth
       finish sth
                          )

basicQueries = dbTestCase (\dbh ->
    do sth <- prepare dbh "SELECT 1 + 1"
       execute sth [] >>= (0 @=?)
       r <- fetchAllRows sth
       assertEqual "converted from" [["2"]] (map (map fromSql) r)
       assertEqual "int32 compare" [[SqlInt32 2]] r
       assertEqual "iToSql compare" [[iToSql 2]] r
       assertEqual "num compare" [[toSql (2::Int)]] r
       assertEqual "nToSql compare" [[nToSql (2::Int)]] r
       assertEqual "string compare" [[SqlString "2"]] r
                          )

createTable = dbTestCase (\dbh ->
    do run dbh "CREATE TABLE hdbctest1 (testname VARCHAR(20), testid INTEGER, testint INTEGER, testtext TEXT)" []
       commit dbh
                         )

dropTable = dbTestCase (\dbh ->
    do run dbh "DROP TABLE hdbctest1" []
       commit dbh
                       )

runReplace = dbTestCase (\dbh ->
    do r <- run dbh "INSERT INTO hdbctest1 VALUES (?, ?, ?, ?)" r1
       assertEqual "insert retval" 1 r
       run dbh "INSERT INTO hdbctest1 VALUES (?, ?, ?, ?)" r2
       commit dbh
       sth <- prepare dbh "SELECT * FROM hdbctest1 WHERE testname = 'runReplace' ORDER BY testid"
       rv2 <- execute sth []
       assertEqual "select retval" 0 rv2
       r <- fetchAllRows sth
       assertEqual "" [r1, r2] r
                       )
    where r1 = [toSql "runReplace", iToSql 1, iToSql 1234, SqlString "testdata"]
          r2 = [toSql "runReplace", iToSql 2, iToSql 2, SqlNull]

executeReplace = dbTestCase (\dbh ->
    do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('executeReplace',?,?,?)"
       execute sth [iToSql 1, iToSql 1234, toSql "Foo"]
       execute sth [SqlInt32 2, SqlNull, toSql "Bar"]
       commit dbh
       sth <- prepare dbh "SELECT * FROM hdbctest1 WHERE testname = ? ORDER BY testid"
       execute sth [SqlString "executeReplace"]
       r <- fetchAllRows sth
       assertEqual "result"
                   [[toSql "executeReplace", iToSql 1, toSql "1234",
                     toSql "Foo"],
                    [toSql "executeReplace", iToSql 2, SqlNull,
                     toSql "Bar"]]
                   r
                            )

testExecuteMany = dbTestCase (\dbh ->
    do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('multi',?,?,?)"
       executeMany sth rows
       commit dbh
       sth <- prepare dbh "SELECT testid, testint, testtext FROM hdbctest1 WHERE testname = 'multi'"
       execute sth []
       r <- fetchAllRows sth
       assertEqual "" rows r
                          )
    where rows = [map toSql ["1", "1234", "foo"],
                  map toSql ["2", "1341", "bar"],
                  [toSql "3", SqlNull, SqlNull]]

testFetchAllRows = dbTestCase (\dbh ->
    do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('sFetchAllRows', ?, NULL, NULL)"
       executeMany sth rows
       commit dbh
       sth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'sFetchAllRows' ORDER BY testid"
       execute sth []
       results <- fetchAllRows sth
       assertEqual "" rows results
                               )
    where rows = map (\x -> [iToSql x]) [1..9]

testFetchAllRows' = dbTestCase (\dbh ->
    do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('sFetchAllRows2', ?, NULL, NULL)"
       executeMany sth rows
       commit dbh
       sth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'sFetchAllRows2' ORDER BY testid"
       execute sth []
       results <- fetchAllRows' sth
       assertEqual "" rows results
                               )
    where rows = map (\x -> [iToSql x]) [1..9]

basicTransactions = dbTestCase (\dbh ->
    do assertBool "Connected database does not support transactions; skipping transaction test" (dbTransactionSupport dbh)
       sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('basicTransactions', ?, NULL, NULL)"
       execute sth [iToSql 0]
       commit dbh
       qrysth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'basicTransactions' ORDER BY testid"
       execute qrysth []
       fetchAllRows qrysth >>= (assertEqual "initial commit" [[toSql "0"]])

       -- Now try a rollback
       executeMany sth rows
       rollback dbh
       execute qrysth []
       fetchAllRows qrysth >>= (assertEqual "rollback" [[toSql "0"]])

       -- Now try another commit
       executeMany sth rows
       commit dbh
       execute qrysth []
       fetchAllRows qrysth >>= (assertEqual "final commit" ([SqlString "0"]:rows))
                               )
    where rows = map (\x -> [iToSql $ x]) [1..9]

testWithTransaction = dbTestCase (\dbh ->
    do assertBool "Connected database does not support transactions; skipping transaction test" (dbTransactionSupport dbh)
       sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('withTransaction', ?, NULL, NULL)"
       execute sth [toSql "0"]
       commit dbh
       qrysth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'withTransaction' ORDER BY testid"
       execute qrysth []
       fetchAllRows qrysth >>= (assertEqual "initial commit" [[toSql "0"]])

       -- Let's try a rollback.
       catch (withTransaction dbh (\_ -> do executeMany sth rows
                                            fail "Foo"))
             (\SomeException{} -> return ())
       execute qrysth []
       fetchAllRows qrysth >>= (assertEqual "rollback" [[SqlString "0"]])

       -- And now a commit.
       withTransaction dbh (\_ -> executeMany sth rows)
       execute qrysth []
       fetchAllRows qrysth >>= (assertEqual "final commit" ([iToSql 0]:rows))
                               )
    where rows = map (\x -> [iToSql x]) [1..9]

tests = TestList
        [
         TestLabel "openClosedb" openClosedb,
         TestLabel "multiFinish" multiFinish,
         TestLabel "basicQueries" basicQueries,
         TestLabel "createTable" createTable,
         TestLabel "runReplace" runReplace,
         TestLabel "executeReplace" executeReplace,
         TestLabel "executeMany" testExecuteMany,
         TestLabel "fetchAllRows" testFetchAllRows,
         TestLabel "fetchAllRows'" testFetchAllRows',
         TestLabel "basicTransactions" basicTransactions,
         TestLabel "withTransaction" testWithTransaction,
         TestLabel "dropTable" dropTable
         ]


text:
require 'sinatra/base'
require 'openid/store/filesystem'
require './lib/models/user'
require './lib/config'
require './lib/referer_saver'
require 'hoptoad_notifier'

HoptoadNotifier.configure do |config|
  config.api_key = CONFIG[:hoptoad][:api_key]
end

Mongomatic.db = Mongo::Connection.new.db(CONFIG[:database])

ONE_TIME_TOKEN_COOKIE = CONFIG[:cookies][:one_time]
TOKEN_COOKIE = CONFIG[:cookies][:token]

class WomptAuth < Sinatra::Base
  use Rack::Session::Pool,
    :path => '/auth',
    :expire_after => 60, # In seconds
    :secret => 'C6xyESB0FdkabrhtBxOlPikZTS0jKnQRq1vMfluX'

  use HoptoadNotifier::Rack if CONFIG[:hoptoad] && CONFIG[:hoptoad][:report_errors]
  use RefererSaver

  use OmniAuth::Builder do
    if settings.environment == :production
      provider :github , '39af35ac1c5189438931' , 'eff1d530e71b571ca58f787a95c62900fa5623c6', :scope => nil
    else
      provider :github , '60ae284d5c81eceaebe1' , '2bac1bc17e414ad15eee27403c6cd900623ae9b4', :scope => nil
    end
    provider :facebook , '181725458505189' , '5afa28d747aabd3d1a6ce71d26933c14', :scope => 'email'
    provider :twitter , 'P5TqY6I9EmvxNLQVjNZJGw' , 'msMp5fnQ5QvbfzRcAdVOvDyAYiROnm9C9g8grR0doQQ'
    provider :open_id, nil, :name => 'google', :identifier => 'https://www.google.com/accounts/o8/id', :scope => 'email'
  end

  def self.get_or_post(path, opts={}, &block)
    get(path, opts, &block)
    post(path, opts, &block)
  end

  get_or_post '/auth/:name/callback' do |name|
    auth = request.env['omniauth.auth']
    host = request.env['HTTP_HOST'].split(':')[0]
    user = find_or_create_user(auth)
    return haml :error, :locals => {:message => user} if user.is_a? String

    response.set_cookie(ONE_TIME_TOKEN_COOKIE, :value => user['one_time_token'], :path => '/')
    back_to = session && session.delete('back_to') || '/'
    haml :redirect, :locals => {:to => back_to}
  end

	get_or_post '/auth/failure' do
		haml :error, :locals => {:message => params[:message]}
	end

  def find_or_create_user auth
    info = auth['user_info']
    create_session = true
    user = User.find_one('authentications.provider' => auth['provider'], 'authentications.uid' => auth['uid'])
    if(token_user = get_user_from_token)
      puts "Found a signed in user: #{token_user}"
      if(token_user && user)
        return "The #{auth['provider']} account is already associated with another Wompt account, please sign out and try again"
      end
      user = token_user
      user.add_authentication_from_authinfo(auth)
      # User is already logged in, no need for new sessions
      create_session = false
    end

    if !user
      if (email = info['email']) && (email.length > 3) && (user = User.find_one('email' => email))
        user.add_authentication_from_authinfo(auth)
      else
        user = User.new('authentications' => [{'provider' => auth['provider'], 'uid' => auth['uid'], 'info' => convert_unserializable_objects(auth)}])
        user['email'] = info['email'] if info['email']
        if(name = (info['name'] || info['nickname']))
          user['name'] = name
        end
      end
    end

    user['one_time_token'] = generate_token if create_session

    if(auth_doc = user.get_authentication(auth['provider'], auth['uid']))
      auth_doc['info'] = convert_unserializable_objects(auth)
    end
    user.save!
    return user
  end

  def get_user_from_token()
    user = (token = request.cookies[TOKEN_COOKIE]) &&
    !token.blank? &&
    User.find_one('sessions.token' => token)
    if(token && !user) # a token that doesn't belong to a user should be deleted
      response.delete_cookie TOKEN_COOKIE
    end
    user
  end

  def convert_unserializable_objects obj
    return obj if obj.nil?

    if(obj.is_a? Array)
      obj.map do |item|
        convert_unserializable_objects(item)
      end
    elsif obj.is_a? Hash
      obj.inject({}) do |memo, pair|
        memo[pair[0]] = convert_unserializable_objects(pair[1])
        memo
      end
    elsif obj.is_a? Numeric
      obj
    else
      obj.to_s
    end
  end

  get "/ok" do
    'OK'
  end

  def generate_token
    ActiveSupport::SecureRandom.base64(20)
  end
end


text:
package org.apache.hyracks.algebricks.runtime.operators.base;

import org.apache.hyracks.api.dataflow.value.RecordDescriptor;

public abstract class AbstractOneInputOneOutputPushRuntime extends AbstractOneInputPushRuntime {

    protected RecordDescriptor inputRecordDesc;

    @Override
    public void setInputRecordDescriptor(int index, RecordDescriptor recordDescriptor) {
        this.inputRecordDesc = recordDescriptor;
    }

}


text:
package uk.ac.ox.it.ords.api.database.structure.services;

import java.util.ServiceLoader;

import uk.ac.ox.it.ords.api.database.structure.services.impl.DatabaseStructureAuditServiceImpl;

public interface DatabaseStructureAuditService {

    /**
     * Create audit message that the user is not authorised to perform a specific action
     * @param request the action that is not authorised
     */
    public abstract void createNotAuthRecord(String request);

    public abstract void createNotAuthRecord(String request, int logicalDatabaseId);

	public abstract void createDatabase(int databaseId);

	public abstract void createODBCRole(int databaseId, String role);

	public abstract void removeODBCRole(int databaseId, String role);

	public abstract void removeODBCRoles(int databaseId);

	public abstract void deleteDatabase(int databaseId);

	/**
	 * Factory for obtaining implementations
	 */
    public static class Factory {
		private static DatabaseStructureAuditService provider;
	    public static DatabaseStructureAuditService getInstance() {
	    	//
	    	// Use the service loader to load an implementation if one is available
	    	// Place a file called uk.ac.ox.oucs.ords.utilities.csv in src/main/resources/META-INF/services
	    	// containing the classname to load as the CsvService implementation.
	    	// By default we load the Hibernate implementation.
	    	//
	    	if (provider == null){
	    		ServiceLoader<DatabaseStructureAuditService> ldr = ServiceLoader.load(DatabaseStructureAuditService.class);
	    		for (DatabaseStructureAuditService service : ldr) {
	    			// We are only expecting one
	    			provider = service;
	    		}
	    	}
	    	//
	    	// If no service provider is found, use the default
	    	//
	    	if (provider == null){
	    		provider = new DatabaseStructureAuditServiceImpl();
	    	}

	    	return provider;
	    }
	}

}


text:
package com.lqg.base;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.lqg.model.PageModel;
import com.lqg.util.GenericsUtils;
/**
 * Dao鐨勫疄鐜�
 * @author Li Qiuguo
 * @param <T>
 */
@Transactional
@SuppressWarnings("unchecked")
public class DaoSupportImpl<T>  implements DaoSupport<T>{
	// 鑾峰彇娉涘瀷鐨勫弬鏁扮殑绫
	protected Class<T> entityClass = GenericsUtils.getGenericType(this.getClass());
	// HibernateTemplate鐨勬敞鍏
	@Autowired
	protected HibernateTemplate hibernateTemplate;

	public HibernateTemplate getTemplate() {
		return hibernateTemplate;
	}
	@Override
	public void delete(Serializable ... ids) {
		for (Serializable id : ids) {
			T t = (T) getTemplate().load(this.entityClass, id);
			getTemplate().delete(t);
		}
	}
	//浜嬪姟鐨勪紶杈撴帶鍒�
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public T get(Serializable entityId) {
		return (T) getTemplate().get(this.entityClass, entityId);
	}
	//浜嬪姟鐨勪紶杈撴帶鍒�
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public T load(Serializable entityId) {
		return (T) getTemplate().load(this.entityClass, entityId);
	}
	//浜嬪姟鐨勪紶杈撴帶鍒�
	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Object uniqueResult(final String hql,final Object[] queryParams) {
		return getTemplate().execute(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {
				//session鏌ヨhql璇彞
				Query query = session.createQuery(hql);
				//璁剧疆鍙傛暟
				setQueryParams(query, queryParams);
				//杩斿洖涓嶉噸澶嶇殑缁撴灉
				return query.uniqueResult();
			}
		});
	}
	//浜嬪姟鐨勪紶杈撴帶鍒�
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public long getCount() {
		String hql = "select count(*) from " + GenericsUtils.getGenericName(this.entityClass);
		return (Long)uniqueResult(hql,null);
	}
	//浜嬪姟鐨勪紶杈撴帶鍒�
	@Override
	public void save(Object obj) {
		getTemplate().save(obj);
		getTemplate().flush();
	}
	@Override
	public void saveOrUpdate(Object obj) {
		getTemplate().saveOrUpdate(obj);
		getTemplate().flush();
	}
	//浜嬪姟鐨勪紶杈撴帶鍒�
	@Override
	public void update(Object obj) {
		getTemplate().update(obj);
		getTemplate().flush();
	}
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public PageModel<T> find(final int pageNo, int maxResult) {
		return find(null, null, null, pageNo, maxResult);
	}
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public PageModel<T> find(int pageNo, int maxResult,
			Map<String, String> orderby) {
		return find(null, null, orderby, pageNo, maxResult);
	}
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public PageModel<T> find(int pageNo, int maxResult, String where,
			Object[] queryParams) {
		return find(where, queryParams, null, pageNo, maxResult);
	}
	/**
	 * 鎬荤殑鍙傛暟鏌ヨ鏂规硶
	 * @param where sql鐨勭鍚堟潯浠�
	 * @param queryParams hql鐨勫弬鏁�
	 *  @param orderby 鎺掑垪鐨勯『搴�	 * @param pageNo 绗嚑椤�
	 * @param maxResult 姣忛〉鐨勫ぇ灏�	 * return PageModel
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public PageModel<T> find(final String where, final Object[] queryParams,
			final Map<String, String> orderby, final int pageNo,
			final int maxResult) {
		//璁剧疆pageModel灏佽
		final PageModel<T> pageModel = new PageModel<T>();
		//璁剧疆绗嚑椤
		pageModel.setPageNo(pageNo);
		//姣忛〉鐨勫ぇ灏
		pageModel.setPageSize(maxResult);
		getTemplate().execute(new HibernateCallback<Object>() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				String hql = new StringBuffer().append("from ")
								.append(GenericsUtils.getGenericName(entityClass))//绫诲埆
								.append(" ")//绌烘牸
								.append(where == null ? "" : where)//鏉′欢
								.append(createOrderBy(orderby))//鎺掑簭
								.toString();//杞负string
				Query query = session.createQuery(hql);//鏌ヨ
				setQueryParams(query,queryParams);//璁剧疆鍙傛暟
				List<T> list = null;
				if(maxResult < 0 && pageNo < 0){
					list = query.list();//
				}else{
					list = query.setFirstResult(getFirstResult(pageNo, maxResult))//璁剧疆寮�ご椤�
								.setMaxResults(maxResult)//璁剧疆鍙栨牱鏁扮洰
								.list();//缁撴灉
					//
					hql = new StringBuffer().append("select count(*) from ")//sql璇彞
									.append(GenericsUtils.getGenericName(entityClass))//瀹炰綋
									.append(" ")//绌烘牸
									.append(where == null ? "" : where)//鏉′欢
									.toString();//杞负string
					query = session.createQuery(hql);//鏌ヨ
					setQueryParams(query,queryParams);//璁剧疆鍙傛暟
					int totalRecords = ((Long) query.uniqueResult()).intValue();//鎬荤殑鏁扮洰
					pageModel.setTotalRecords(totalRecords);//璁剧疆totoalRecords
				}
				pageModel.setList(list);//pageModel灏佽
				return null;
			}
		});
		return pageModel;
		}
	/**
	 * 鑾峰彇绗嚑椤�	 * @param pageNo 绗嚑椤�
	 * @param maxResult 姣忛〉澶у皬
	 * @return 寮�ご鏁扮洰
	 */
	protected int getFirstResult(int pageNo,int maxResult){
		int firstResult = (pageNo-1) * maxResult;
		return firstResult < 0 ? 0 : firstResult;
	}
	/**
	 * query 璁剧疆鎬時ams
	 * @param query
	 * @param queryParams
	 */
	protected void setQueryParams(Query query, Object[] queryParams){
		if(queryParams!=null && queryParams.length>0){
			for(int i=0; i<queryParams.length; i++){
				query.setParameter(i, queryParams[i]);
			}
		}
	}
	/**
	 * orderby鎺掑簭
	 * @param orderby
	 * @return 鎬荤殑sql濡備綍*/
	protected String createOrderBy(Map<String, String> orderby){
		StringBuffer sb = new StringBuffer("");
		if(orderby != null && orderby.size() > 0){
			sb.append(" order by ");
			for(String key : orderby.keySet()){
				sb.append(key).append(" ").append(orderby.get(key)).append(",");
			}
			sb.deleteCharAt(sb.length() - 1);
		}
		return sb.toString();
	}
	/**
	 * 鑾峰彇session
	 * @return
	 */
	protected Session getSession(){
		return (!this.hibernateTemplate.isAllowCreate() ?
		    SessionFactoryUtils.getSession(this.hibernateTemplate.getSessionFactory(), false) :
				SessionFactoryUtils.getSession(
						this.hibernateTemplate.getSessionFactory(),
						this.hibernateTemplate.getEntityInterceptor(),
						this.hibernateTemplate.getJdbcExceptionTranslator()));
	}
}