text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:background="#fff"
        android:minHeight="?attr/actionBarSize">

        <ImageView
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:id="@+id/back"
            android:src="@drawable/backicon"/>

        <com.github.omadahealth.typefaceview.TypefaceTextView
            android:id="@+id/toolbar_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="left"
            android:layout_marginLeft="40dp"
            android:text="ENTER PIN"
            android:textColor="@android:color/black"
            android:textSize="20sp"
            android:visibility="visible" />

    </android.support.v7.widget.Toolbar>

</RelativeLayout>


text:
layout: default
title: Home
---

    {% for post in paginator.posts %}

            <time class="post_detail post_date" datetime="{{ post.date | date_to_xmlschema }}">{{ post.date | date_to_string }}</time>

{{ post.title }}

        {{ post.content }}

    {% endfor %}

                {% if paginator.previous_page %}

                    Previous page

                {% endif %}

                {% if paginator.next_page %}

                    Next page

                {% endif %}

redpajama_set_name: RedPajamaGithub


text:
using System.Diagnostics;

using Xamarin.Forms.CustomAttributes;
using Xamarin.Forms.Internals;

namespace Xamarin.Forms.Controls
{
	[Preserve (AllMembers=true)]
	[Issue (IssueTracker.Github, 2333, "TimePicker not shown when .Focus() is called", PlatformAffected.WinPhone)]
	public class Issue2333 : ContentPage
	{
		public Issue2333 ()
		{
			var timePicker = new TimePicker ();
			var timePickerBtn = new Button {
				Text = "Click me to call .Focus on TimePicker"
			};

			timePickerBtn.Clicked += (sender, args) => {
				timePicker.Focus ();
			};

			var timePickerBtn2 = new Button {
				Text = "Click me to call .Unfocus on TimePicker"
			};

			timePickerBtn2.Clicked += (sender, args) => {
				timePicker.Unfocus ();
			};

			Content = new StackLayout {
				Children = {
					timePickerBtn,
					timePickerBtn2,
					timePicker,
				}
			};
		}
	}
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/** @module hooks */ /** for typedoc */
var common_1 = require("../common/common");
var coreservices_1 = require("../common/coreservices");
/**
 * A [[TransitionHookFn]] which waits for the views to load
 *
 * Registered using `transitionService.onStart({}, loadEnteringViews);`
 *
 * Allows the views to do async work in [[ViewConfig.load]] before the transition continues.
 * In angular 1, this includes loading the templates.
 */
var loadEnteringViews = function (transition) {
    var $q = coreservices_1.services.$q;
    var enteringViews = transition.views('entering');
    if (!enteringViews.length)
        return;
    return $q.all(enteringViews.map(function (view) { return $q.when(view.load()); })).then(common_1.noop);
};
exports.registerLoadEnteringViews = function (transitionService) {
    return transitionService.onFinish({}, loadEnteringViews);
};
/**
 * A [[TransitionHookFn]] which activates the new views when a transition is successful.
 *
 * Registered using `transitionService.onSuccess({}, activateViews);`
 *
 * After a transition is complete, this hook deactivates the old views from the previous state,
 * and activates the new views from the destination state.
 *
 * See [[ViewService]]
 */
var activateViews = function (transition) {
    var enteringViews = transition.views('entering');
    var exitingViews = transition.views('exiting');
    if (!enteringViews.length && !exitingViews.length)
        return;
    var $view = transition.router.viewService;
    exitingViews.forEach(function (vc) { return $view.deactivateViewConfig(vc); });
    enteringViews.forEach(function (vc) { return $view.activateViewConfig(vc); });
    $view.sync();
};
exports.registerActivateViews = function (transitionService) {
    return transitionService.onSuccess({}, activateViews);
};
//# sourceMappingURL=views.js.map


text:
import os
import subprocess
import sys

def main():
  # Read the environment block from the file. This is stored in the format used
  # by CreateProcess. Drop last 2 NULs, one for list terminator, one for
  # trailing vs. separator.
  env_pairs = open(sys.argv[1]).read()[:-2].split('\0')
  env_dict = dict([item.split('=', 1) for item in env_pairs])

  # mc writes to stderr, so this explicitly redirects to stdout and eats it.
  try:
    # This needs shell=True to search the path in env_dict for the mc
    # executable.
    rest = sys.argv[2:]
    subprocess.check_output(['mc.exe'] + rest,
                            env=env_dict,
                            stderr=subprocess.STDOUT,
                            shell=True)
    # We require all source code (in particular, the header generated here) to
    # be UTF-8. jinja can output the intermediate .mc file in UTF-8 or UTF-16LE.
    # However, mc.exe only supports Unicode via the -u flag, and it assumes when
    # that is specified that the input is UTF-16LE (and errors out on UTF-8
    # files, assuming they're ANSI). Even with -u specified and UTF16-LE input,
    # it generates an ANSI header, and includes broken versions of the message
    # text in the comment before the value. To work around this, for any invalid
    # // comment lines, we simply drop the line in the header after building it.
    header_dir = None
    input_file = None
    for i, arg in enumerate(rest):
      if arg == '-h' and len(rest) > i + 1:
        assert header_dir == None
        header_dir = rest[i + 1]
      elif arg.endswith('.mc') or arg.endswith('.man'):
        assert input_file == None
        input_file = arg
    if header_dir:
      header_file = os.path.join(
          header_dir, os.path.splitext(os.path.basename(input_file))[0] + '.h')
      header_contents = []
      with open(header_file, 'rb') as f:
        for line in f.readlines():
          if line.startswith('//') and '?' in line:
            continue
          header_contents.append(line)
      with open(header_file, 'wb') as f:
        f.write(''.join(header_contents))
  except subprocess.CalledProcessError as e:
    print e.output
    sys.exit(e.returncode)

if __name__ == '__main__':
  main()


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Post = mongoose.model('Post'),
	_ = require('lodash');

/**
 * Create a Post
 */
exports.create = function(req, res) {
	var post = new Post(req.body);
	post.user = req.user;

	post.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(post);
		}
	});
};

/**
 * Show the current Post
 */
exports.read = function(req, res) {
	res.jsonp(req.post);
};

/**
 * Update a Post
 */
exports.update = function(req, res) {
	var post = req.post ;

	post = _.extend(post , req.body);

	post.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(post);
		}
	});
};

/**
 * Delete an Post
 */
exports.delete = function(req, res) {
	var post = req.post ;

	post.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(post);
		}
	});
};

/**
 * List of Posts
 */
exports.list = function(req, res) {
	Post.find().sort('-created').populate('user', 'displayName').exec(function(err, posts) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(posts);
		}
	});
};

/**
 * Post middleware
 */
exports.postByID = function(req, res, next, id) {
	Post.findById(id).populate('user', 'displayName').exec(function(err, post) {
		if (err) return next(err);
		if (! post) return next(new Error('Failed to load Post ' + id));
		req.post = post ;
		next();
	});
};

/**
 * Post authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.post.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};


text:
package io.vertx.ext.web.handler.sockjs;

import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpMethod;
import io.vertx.ext.web.WebTestBase;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.CorsHandler;
import org.junit.Test;

public class SockJSCORSTest extends WebTestBase {

  @Test
  public void testSockJSInternalCORSHandling() {
    router
      .route()
      .handler(BodyHandler.create());
    SockJSProtocolTest.installTestApplications(router, vertx);
    client.request(HttpMethod.GET, "/echo/info?t=21321")
      .compose(req -> req
        .putHeader(HttpHeaders.ORIGIN, "http://example.com")
        .send())
      .onComplete(onSuccess(resp -> {
        assertEquals(200, resp.statusCode());
        assertEquals("http://example.com", resp.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
        assertEquals("true", resp.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
        complete();
    }));
    await();
  }

  @Test
  public void testNoConflictsSockJSAndCORSHandler() {
    router
      .route()
      .handler(CorsHandler.create("*").allowCredentials(false))
      .handler(BodyHandler.create());
    SockJSProtocolTest.installTestApplications(router, vertx);
    client.request(HttpMethod.GET, "/echo/info?t=21321")
      .compose(req -> req
        .putHeader(HttpHeaders.ORIGIN, "http://example.com")
        .send())
      .onComplete(onSuccess(resp -> {
        assertEquals(200, resp.statusCode());
        assertEquals("*", resp.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
        assertFalse(resp.headers().contains(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
        //If the SockJS handles the CORS stuff, it would reply with allow credentials true and allow origin example.com
        complete();
      }));
    await();
  }

}


text:
<?php
session_start();

if (isset($_GET['session_id'])) {
	$session_id = $_GET['session_id'];
	$check_session_id = file_get_contents('http://' . $_SERVER['HTTP_HOST'] . "/api/rest/session/validate/$session_id");

	if ($check_session_id != 'true') {
		echo "Invalid patient id $session_id.
";
	} else {
		//$check_completion = file_get_content("http://vs.ocirs.com/rest/survey/completed/$session_id");
		$_SESSION['session_id'] = $session_id;
	}
}

if (!isset($_SESSION['session_id'])):
?>
	<form method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
		Patient Id

		<input type="text" name="session_id" />
		<input type="submit" name='submit' />
	</form>
<?php
else:
?>

<?php endif; ?>


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="Task">
    <insert id="SAVE" parameterType="task">
    	insert into wf_task (id,order_Id,task_Name,display_Name,task_Type,perform_Type,operator,create_Time,finish_Time,expire_Time,action_Url,parent_Task_Id,variable,version)
    	values (#{id, jdbcType=VARCHAR},#{orderId, jdbcType=VARCHAR},#{taskName, jdbcType=VARCHAR},
    	#{displayName, jdbcType=VARCHAR},#{taskType, jdbcType=NUMERIC},
    	#{performType, jdbcType=NUMERIC},#{operator, jdbcType=VARCHAR},
    	#{createTime, jdbcType=VARCHAR},#{finishTime, jdbcType=VARCHAR},
    	#{expireTime, jdbcType=VARCHAR},#{actionUrl, jdbcType=VARCHAR},
    	#{parentTaskId, jdbcType=VARCHAR},#{variable, jdbcType=VARCHAR},0)
    </insert>
    <update id="UPDATE" parameterType="task">
    	update wf_task set finish_Time=#{finishTime, jdbcType=VARCHAR}, operator=#{operator, jdbcType=VARCHAR}, version = version + 1
    	where id=#{id, jdbcType=VARCHAR} and version=#{version, jdbcType=NUMERIC}
    </update>
    <delete id="DELETE" parameterType="string">
    	delete from wf_task where id = #{id, jdbcType=VARCHAR}
    </delete>
    <select id="SELECTONE" parameterType="string" resultType="task">
        select
            id,
            order_Id as orderId,
            task_Name as taskName,
            display_Name as displayName,
            task_Type as taskType,
            perform_Type as performType,
            operator,
            create_Time as createTime,
            finish_Time as finishTime,
            expire_Time as expireTime,
            action_Url as actionUrl,
            parent_Task_Id as parentTaskId,
            variable,
            version
        from wf_task
    	where id = #{id, jdbcType=VARCHAR}
    </select>
    <select id="SELECTBYPARENT" parameterType="string" resultType="task">
        select
            id,
            order_Id as orderId,
            task_Name as taskName,
            display_Name as displayName,
            task_Type as taskType,
            perform_Type as performType,
            operator,
            create_Time as createTime,
            finish_Time as finishTime,
            expire_Time as expireTime,
            action_Url as actionUrl,
            parent_Task_Id as parentTaskId,
            variable,
            version
        from wf_task
    	where parent_Task_Id = #{id, jdbcType=VARCHAR}
    </select>
    <select id="SELECTLIST" resultType="task">
        select
            id,
            order_Id as orderId,
            task_Name as taskName,
            display_Name as displayName,
            task_Type as taskType,
            perform_Type as performType,
            operator,
            create_Time as createTime,
            finish_Time as finishTime,
            expire_Time as expireTime,
            action_Url as actionUrl,
            parent_Task_Id as parentTaskId,
            variable,
            version
        from wf_task
    </select>
</mapper>


text:
<?php

namespace Symfony\Component\Security\Authentication\Provider;

use Symfony\Component\Security\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Exception\BadCredentialsException;
use Symfony\Component\Security\Authentication\Token\AnonymousToken;

/*
 * This file is part of the Symfony framework.
 *
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * AnonymousAuthenticationProvider validates AnonymousToken instances.
 *
 * @author Fabien Potencier <fabien.potencier@symfony-project.com>
 */
class AnonymousAuthenticationProvider implements AuthenticationProviderInterface
{
    protected $key;

    /**
     * Constructor.
     *
     * @param string $key The key shared with the authentication token
     */
    public function __construct($key)
    {
        $this->key = $key;
    }

    /**
     * {@inheritdoc}
     */
    public function authenticate(TokenInterface $token)
    {
        if (!$this->supports($token)) {
            return null;
        }

        if ($this->key != $token->getKey()) {
            throw new BadCredentialsException('The Token does not contain the expected key.');
        }

        return $token;
    }

    /**
     * {@inheritdoc}
     */
    public function supports(TokenInterface $token)
    {
        return $token instanceof AnonymousToken;
    }
}


text:
package eu.ydp.empiria.player.client.controller.item;

import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.NodeList;
import com.google.inject.Inject;
import eu.ydp.empiria.player.client.gin.scopes.page.PageScoped;
import eu.ydp.empiria.player.client.util.file.xml.XmlData;

import javax.annotation.PostConstruct;

public class ItemXMLWrapper {

    @Inject
    @PageScoped
    private XmlData xmlData;

    private Document document;

    @PostConstruct
    public void postConstruct() {
        document = xmlData.getDocument();
    }

    public NodeList getStyleDeclaration() {
        return getElementsByTagName("styleDeclaration");
    }

    public NodeList getAssessmentItems() {
        return getElementsByTagName("assessmentItem");
    }

    public Element getItemBody() {
        return (Element) getElementsByTagName("itemBody").item(0);
    }

    public NodeList getResponseDeclarations() {
        return getElementsByTagName("responseDeclaration");
    }

    public NodeList getExpressions() {
        return getElementsByTagName("expressions");
    }

    public String getBaseURL() {
        return xmlData.getBaseURL();
    }

    private NodeList getElementsByTagName(String nodeName) {
        return document.getElementsByTagName(nodeName);
    }

}


text:
package org.openengsb.core.api.l10n;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Properties;

import org.apache.commons.lang.LocaleUtils;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;

/**
 * Localization helper to lookup string resources from the bundle's localization entries.
 */
@SuppressWarnings("serial")
public class BundleStrings implements StringLocalizer {

    private HashMap<String, Properties> entries;

    public BundleStrings() {
    }

    public BundleStrings(Bundle bundle) {
        setBundle(bundle);
    }

    @Override
    public LocalizableString getString(final String key, final String... parameters) {
        return new LocalizableString() {
            @Override
            public String getString(Locale locale) {
                return BundleStrings.this.getString(key, locale, parameters);
            }

            @Override
            public String getKey() {
                return key;
            }
        };
    }

    @Override
    public String getString(String key, Locale locale, String... parameters) {
        @SuppressWarnings("unchecked")
        List<Locale> locales = LocaleUtils.localeLookupList(locale, new Locale(""));
        for (Locale l : locales) {
            Properties p = entries.get(buildEntryFilename(l));
            if (p == null) {
                continue;
            }
            if (p.containsKey(key)) {
                String property = p.getProperty(key);
                String format = MessageFormat.format(property, (Object[]) parameters);
                return format;
            }
        }
        return null;
    }

    private String buildEntryFilename(Locale locale) {
        String name = "";
        if (!locale.getLanguage().isEmpty()) {
            name += '_' + locale.getLanguage();
            if (!locale.getCountry().isEmpty()) {
                name += '_' + locale.getCountry();
                if (!locale.getVariant().isEmpty()) {
                    name += '_' + locale.getVariant();
                }
            }
        }
        return name;
    }

    public void setBundle(Bundle bundle) {
        String path = (String) bundle.getHeaders().get(Constants.BUNDLE_LOCALIZATION);
        if (path == null) {
            path = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME;
        }
        path = path.trim();
        int idx = path.lastIndexOf('/');
        if (idx == -1) {
            buildEntriesMap(bundle, "/", path);
        } else if (idx == 0) {
            buildEntriesMap(bundle, "/", path.substring(1));
        } else {
            buildEntriesMap(bundle, path.substring(0, idx), path.substring(idx + 1));
        }
    }

    private void buildEntriesMap(Bundle bundle, String directory, String basename) {
        @SuppressWarnings("unchecked")
        Enumeration<URL> resources = bundle.findEntries(directory, basename + "*.properties", false);
        entries = new HashMap<String, Properties>();
        while (resources != null && resources.hasMoreElements()) {
            URL url = resources.nextElement();
            String name = new File(url.toString()).getName().substring(basename.length());
            name = name.substring(0, name.length() - ".properties".length());
            Properties p = loadProperties(url);
            if (p != null) {
                entries.put(name, p);
            }
        }
    }

    private Properties loadProperties(URL url) {
        InputStream in = null;
        try {
            in = url.openStream();
            Properties p = new Properties();
            p.load(in);
            return p;
        } catch (IOException e) {
            return null;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // nop
                }
            }
        }
    }
}


text:
package com.networknt.light.rule.user;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.networknt.light.rule.AbstractRule;
import com.networknt.light.rule.Rule;
import com.networknt.light.server.DbService;
import com.networknt.light.util.HashUtil;
import com.networknt.light.util.JwtUtil;
import com.networknt.light.util.ServiceLocator;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.OJSONWriter;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by steve on 9/23/2014.
 */
public abstract class AbstractUserRule extends AbstractRule implements Rule {
    static final org.slf4j.Logger logger = LoggerFactory.getLogger(AbstractUserRule.class);

    public static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
        + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    Pattern pattern = Pattern.compile(EMAIL_PATTERN);

    public abstract boolean execute (Object ...objects) throws Exception;
    ObjectMapper mapper = ServiceLocator.getInstance().getMapper();

    protected boolean isUserInDbByEmail(String email) {
        boolean userInDb = false;
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            Vertex user = graph.getVertexByKey("User.email", email);
            if(user != null) {
                userInDb = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            graph.shutdown();
        }
        return userInDb;
    }

    protected boolean isUserInDbByUserId(String userId) {
        boolean userInDb = false;
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            Vertex user = graph.getVertexByKey("User.userId", userId);
            if(user != null) {
                userInDb = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            graph.shutdown();
        }
        return userInDb;
    }

    protected Vertex getUserByUserId(OrientGraph graph, String userId) throws Exception {
        return graph.getVertexByKey("User.userId", userId);
    }

    protected Vertex getUserByEmail(OrientGraph graph, String email) throws Exception {
        return graph.getVertexByKey("User.email", email);
    }

    protected Vertex getCredential(OrientGraph graph, Vertex user) throws Exception {
        return graph.getVertex(user.getProperty("credential"));
    }

    protected Vertex addUser(Map<String, Object> data) throws Exception {
        Vertex user = null;
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            graph.begin();
            String password = (String)data.remove("password");
            OrientVertex credential = graph.addVertex("class:Credential", "password", password);
            data.put("credential", credential);
            user = graph.addVertex("class:User", data);
            graph.commit();
        } catch (Exception e) {
            logger.error("Exception:", e);
            graph.rollback();
            throw e;
        } finally {
            graph.shutdown();
        }
        return user;
    }

    protected Vertex addActivation(String userId) throws Exception {
        Vertex activation = null;
        String code = HashUtil.generateUUID();
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            graph.begin();
            activation = graph.addVertex("class:Activation", "userId", userId, "code", code, "createDate", new Date());
            graph.commit();
        } catch (Exception e) {
            logger.error("Exception:", e);
            graph.rollback();
            throw e;
        } finally {
            graph.shutdown();
        }
        return activation;
    }

    protected void delActivation(String userId, String code) throws Exception {
        Vertex activation = null;
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            graph.begin();
            activation = graph.getVertexByKey("Activation.userId", userId);
            if(activation != null && code != null && code.equals(activation.getProperty("code"))) {
                activation.remove();
            }

            graph.commit();
        } catch (Exception e) {
            logger.error("Exception:", e);
            graph.rollback();
            throw e;
        } finally {
            graph.shutdown();
        }
    }

    protected void delUser(Map<String, Object> data) throws Exception {
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            graph.begin();
            Vertex user = graph.getVertexByKey("User.userId", data.get("userId"));
            if(user != null) {
                graph.removeVertex(user.getProperty("credential"));
                graph.removeVertex(user);
            }
        } catch (Exception e) {
            logger.error("Exception:", e);
            graph.rollback();
            throw e;
        } finally {
            graph.shutdown();
        }
    }

    protected void updPassword(Map<String, Object> data) throws Exception {
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            graph.begin();
            Vertex user = graph.getVertexByKey("User.userId", data.get("userId"));
            user.setProperty("updateDate", data.get("updateDate"));
            Vertex credential = user.getProperty("credential");
            if (credential != null) {
                credential.setProperty("password", data.get("password"));
            }
            graph.commit();
        } catch (Exception e) {
            logger.error("Exception:", e);
            graph.rollback();
            throw e;
        } finally {
            graph.shutdown();
        }
    }

    protected void updRole(Map<String, Object> data) throws Exception {
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            graph.begin();
            Vertex user = graph.getVertexByKey("User.userId", data.get("userId"));
            if(user != null) {
                user.setProperty("roles", data.get("roles"));
                user.setProperty("updateDate", data.get("updateDate"));
                Vertex updateUser = graph.getVertexByKey("User.userId", data.get("updateUserId"));
                updateUser.addEdge("Update", user);
            }
            graph.commit();
        } catch (Exception e) {
            logger.error("Exception:", e);
            graph.rollback();
            throw e;
        } finally {
            graph.shutdown();
        }
    }

    protected void updLockByUserId(Map<String, Object> data) throws Exception {
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            graph.begin();
            Vertex user = graph.getVertexByKey("User.userId", data.get("userId"));
            if(user != null) {
                user.setProperty("locked", data.get("locked"));
                user.setProperty("updateDate", data.get("updateDate"));
                Vertex updateUser = graph.getVertexByKey("User.userId", data.get("updateUserId"));
                updateUser.addEdge("Update", user);
            }
            graph.commit();
        } catch (Exception e) {
            logger.error("Exception:", e);
            graph.rollback();
            throw e;
        } finally {
            graph.shutdown();
        }
    }

    protected void updUser(Map<String, Object> data) throws Exception {
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            graph.begin();
            Vertex user =  graph.getVertexByKey("User.userId", data.get("userId"));
            if(user != null) {
                String firstName = (String)data.get("firstName");
                if(firstName != null && !firstName.equals(user.getProperty("firstName"))) {
                    user.setProperty("firstName", firstName);
                }
                String lastName = (String)data.get("lastName");
                if(lastName != null && !lastName.equals(user.getProperty("lastName"))) {
                    user.setProperty("lastName", lastName);
                }
                user.setProperty("updateDate", data.get("updateDate"));
            }
            graph.commit();
        } catch (Exception e) {
            logger.error("Exception:", e);
            graph.rollback();
            throw e;
        } finally {
            graph.shutdown();
        }
    }

    // TODO need to know which clientId to remove only for that client or all?
    protected void revokeRefreshToken(Map<String, Object> data) throws Exception {
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            graph.begin();
            Vertex user = graph.getVertexByKey("User.userId", data.get("userId"));
            if(user != null) {
                Vertex credential = user.getProperty("credential");
                if(credential != null) {
                    credential.removeProperty("clientRefreshTokens");
                }
            }
            graph.commit();
        } catch (Exception e) {
            logger.error("Exception:", e);
            graph.rollback();
            throw e;
        } finally {
            graph.shutdown();
        }
    }

    protected void signIn(Map<String, Object> data) throws Exception {
        String hashedRefreshToken = (String)data.get("hashedRefreshToken");
        if(hashedRefreshToken != null) {
            OrientGraph graph = ServiceLocator.getInstance().getGraph();
            try {
                graph.begin();
                Vertex user = graph.getVertexByKey("User.userId", data.get("userId"));
                if(user != null) {
                    Vertex credential = user.getProperty("credential");
                    if(credential != null) {
                        String clientId = (String)data.get("clientId");
                        // get hostRefreshTokens map here.
                        Map clientRefreshTokens = credential.getProperty("clientRefreshTokens");
                        if(clientRefreshTokens != null) {
                            // logged in before, check if logged in from the host.
                            List<String> refreshTokens = (List)clientRefreshTokens.get(clientId);
                            if(refreshTokens != null) {
                                // max refresh tokens for user is 10. max 10 devices.
                                if(refreshTokens.size() >= 10) {
                                    refreshTokens.remove(0);
                                }
                                refreshTokens.add(hashedRefreshToken);
                            } else {
                                refreshTokens = new ArrayList<String>();
                                refreshTokens.add(hashedRefreshToken);
                                clientRefreshTokens.put(clientId, refreshTokens);
                            }
                            credential.setProperty("clientRefreshTokens", clientRefreshTokens);
                        } else {
                            // never logged in, create the map.
                            clientRefreshTokens = new HashMap<String, List<String>>();
                            List<String> refreshTokens = new ArrayList<String>();
                            refreshTokens.add(hashedRefreshToken);
                            clientRefreshTokens.put(clientId, refreshTokens);
                            credential.setProperty("clientRefreshTokens", clientRefreshTokens);
                        }
                    }
                }
                graph.commit();
            } catch (Exception e) {
                logger.error("Exception:", e);
                graph.rollback();
                throw e;
            } finally {
                graph.shutdown();
            }
        } else {
            logger.debug("There is no hashedRefreshToken as user didn't select remember me. Do nothing");
        }
    }

    protected void logOut(Map<String, Object> data) throws Exception {
        String refreshToken = (String)data.get("refreshToken");
        if(refreshToken != null) {
            OrientGraph graph = ServiceLocator.getInstance().getGraph();
            try {
                graph.begin();
                Vertex user = graph.getVertexByKey("User.userId", data.get("userId"));
                if(user != null) {
                    Vertex credential = user.getProperty("credential");
                    if(credential != null) {
                        // now remove the refresh token
                        String clientId = (String)data.get("clientId");
                        logger.debug("logOut to remove refreshToken {} from clientId {}" , refreshToken, clientId);
                        Map clientRefreshTokens = credential.getProperty("clientRefreshTokens");
                        if(clientRefreshTokens != null) {
                            // logged in before, check if logged in from the host.
                            List<String> refreshTokens = (List)clientRefreshTokens.get(clientId);
                            if(refreshTokens != null) {
                                String hashedRefreshToken = HashUtil.md5(refreshToken);
                                refreshTokens.remove(hashedRefreshToken);
                            }
                        } else {
                            logger.error("There is no refresh tokens");
                        }
                    }
                }
                graph.commit();
            } catch (Exception e) {
                logger.error("Exception:", e);
                graph.rollback();
                throw e;
            } finally {
                graph.shutdown();
            }
        } else {
            logger.debug("There is no hashedRefreshToken as user didn't pass in refresh token when logging out. Do nothing");
        }
    }

    boolean checkRefreshToken(Vertex credential, String clientId, String refreshToken) throws Exception {
        boolean result = false;
        if(credential != null && refreshToken != null) {
            Map clientRefreshTokens = credential.getProperty("clientRefreshTokens");
            if(clientRefreshTokens != null) {
                List<String> refreshTokens = (List)clientRefreshTokens.get(clientId);
                if(refreshTokens != null) {
                    String hashedRefreshToken = HashUtil.md5(refreshToken);
                    for(String token: refreshTokens) {
                        if(hashedRefreshToken.equals(token)) {
                            result = true;
                            break;
                        }
                    }
                }
            } else {
                logger.error("There is no refresh tokens");
            }
        }
        return result;
    }

    protected void upVoteUser(Map<String, Object> data) {
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            graph.begin();
            OrientVertex user = (OrientVertex)graph.getVertexByKey("User.userId", data.get("userId"));
            OrientVertex voteUser = (OrientVertex)graph.getVertexByKey("User.userId", data.get("voteUserId"));
            if(user != null && voteUser != null) {
                for (Edge edge : voteUser.getEdges(user, Direction.OUT, "DownVote")) {
                    if(edge.getVertex(Direction.IN).equals(user)) graph.removeEdge(edge);
                }
                voteUser.addEdge("UpVote", user);
            }
            graph.commit();
        } catch (Exception e) {
            logger.error("Exception:", e);
            graph.rollback();
            throw e;
        } finally {
            graph.shutdown();
        }
    }

    protected void downVoteUser(Map<String, Object> data) {
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            graph.begin();
            OrientVertex user = (OrientVertex)graph.getVertexByKey("User.userId", data.get("userId"));
            OrientVertex voteUser = (OrientVertex)graph.getVertexByKey("User.userId", data.get("voteUserId"));
            if(user != null && voteUser != null) {
                for (Edge edge : voteUser.getEdges(user, Direction.OUT, "UpVote")) {
                    if(edge.getVertex(Direction.IN).equals(user)) graph.removeEdge(edge);
                }
                voteUser.addEdge("DownVote", user);
            }
            graph.commit();
        } catch (Exception e) {
            logger.error("Exception:", e);
            graph.rollback();
            throw e;
        } finally {
            graph.shutdown();
        }
    }

    // TODO refactor it to be generic. table name as part of the criteria? or a parameter?
    protected long getTotalNumberUserFromDb(OrientGraph graph, Map<String, Object> criteria) throws Exception {
        StringBuilder sql = new StringBuilder("SELECT COUNT(*) as count FROM User");
        String whereClause = DbService.getWhereClause(criteria);
        if(whereClause != null && whereClause.length() > 0) {
            sql.append(whereClause);
        }
        logger.debug("sql=" + sql);
        OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>(sql.toString());
        List<ODocument> list = graph.getRawGraph().command(query).execute();
        return list.get(0).field("count");
    }

    protected String getUserFromDb(OrientGraph graph, Map<String, Object> criteria) throws Exception {
        String json = null;
        StringBuilder sql = new StringBuilder("SELECT FROM User ");
        String whereClause = DbService.getWhereClause(criteria);
        if(whereClause != null && whereClause.length() > 0) {
            sql.append(whereClause);
        }

        String sortedBy = (String)criteria.get("sortedBy");
        String sortDir = (String)criteria.get("sortDir");
        if(sortedBy != null) {
            sql.append(" ORDER BY ").append(sortedBy);
            if(sortDir != null) {
                sql.append(" ").append(sortDir);
            }
        }
        Integer pageSize = (Integer)criteria.get("pageSize");
        Integer pageNo = (Integer)criteria.get("pageNo");
        if(pageNo != null && pageSize != null) {
            sql.append(" SKIP ").append((pageNo - 1) * pageSize);
            sql.append(" LIMIT ").append(pageSize);
        }
        logger.debug("sql=" + sql);
        OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>(sql.toString());
        List<ODocument> list = graph.getRawGraph().command(query).execute();
        if(list.size() > 0) {
            json = OJSONWriter.listToJSON(list, null);
        }
        return json;
    }

    boolean isEmail(String userIdEmail) {
        Matcher matcher = pattern.matcher(userIdEmail);
        return matcher.matches();
    }

    String generateToken(Vertex user, String clientId) throws Exception {
        Map<String, Object> jwtMap = new LinkedHashMap<String, Object>();
        jwtMap.put("@rid", user.getId().toString());
        jwtMap.put("userId", user.getProperty("userId"));
        jwtMap.put("clientId", clientId);
        jwtMap.put("roles", user.getProperty("roles"));
        return JwtUtil.getJwt(jwtMap);
    }

    boolean checkPassword(OrientGraph graph, Vertex user, String inputPassword) throws Exception {
        Vertex credential = user.getProperty("credential");
        //Vertex credential = getCredential(graph, user);
        String storedPassword = (String) credential.getProperty("password");
        return HashUtil.validatePassword(inputPassword, storedPassword);
    }

}


text:
import {HtmlAst} from '@angular/compiler/src/html_ast';
import {Message, id} from '@angular/compiler/src/i18n/message';
import {deserializeXmb, serializeXmb} from '@angular/compiler/src/i18n/xmb_serializer';
import {ParseError, ParseSourceSpan} from '@angular/compiler/src/parse_util';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';

export function main() {
  describe('Xmb', () => {
    describe('Xmb Serialization', () => {
      it('should return an empty message bundle for an empty list of messages',
         () => { expect(serializeXmb([])).toEqual('<message-bundle></message-bundle>'); });

      it('should serializeXmb messages without desc', () => {
        let m = new Message('content', 'meaning', null);
        let expected = `<message-bundle><msg id='${id(m)}'>content</msg></message-bundle>`;
        expect(serializeXmb([m])).toEqual(expected);
      });

      it('should serializeXmb messages with desc', () => {
        let m = new Message('content', 'meaning', 'description');
        let expected =
            `<message-bundle><msg id='${id(m)}' desc='description'>content</msg></message-bundle>`;
        expect(serializeXmb([m])).toEqual(expected);
      });
    });

    describe('Xmb Deserialization', () => {
      it('should parse an empty bundle', () => {
        let mb = '<message-bundle></message-bundle>';
        expect(deserializeXmb(mb, 'url').messages).toEqual({});
      });

      it('should parse an non-empty bundle', () => {
        let mb = `
          <message-bundle>
            <msg id="id1" desc="description1">content1</msg>
            <msg id="id2">content2</msg>
          </message-bundle>
        `;

        let parsed = deserializeXmb(mb, 'url').messages;
        expect(_serialize(parsed['id1'])).toEqual('content1');
        expect(_serialize(parsed['id2'])).toEqual('content2');
      });

      it('should error when cannot parse the content', () => {
        let mb = `
          <message-bundle>
            <msg id="id1" desc="description1">content
          </message-bundle>
        `;

        let res = deserializeXmb(mb, 'url');
        expect(_serializeErrors(res.errors)).toEqual(['Unexpected closing tag "message-bundle"']);
      });

      it('should error when cannot find the id attribute', () => {
        let mb = `
          <message-bundle>
            <msg>content</msg>
          </message-bundle>
        `;

        let res = deserializeXmb(mb, 'url');
        expect(_serializeErrors(res.errors)).toEqual(['"id" attribute is missing']);
      });

      it('should error on empty content', () => {
        let mb = ``;
        let res = deserializeXmb(mb, 'url');
        expect(_serializeErrors(res.errors)).toEqual(['Missing element "message-bundle"']);
      });

      it('should error on an invalid element', () => {
        let mb = `
          <message-bundle>
            <invalid>content</invalid>
          </message-bundle>
        `;

        let res = deserializeXmb(mb, 'url');
        expect(_serializeErrors(res.errors)).toEqual(['Unexpected element "invalid"']);
      });

      it('should expand \'ph\' elements', () => {
        let mb = `
          <message-bundle>
            <msg id="id1">a<ph name="i0"/></msg>
          </message-bundle>
        `;

        let res = deserializeXmb(mb, 'url').messages['id1'];
        expect((<any>res[1]).name).toEqual('ph');
      });
    });
  });
}

function _serialize(nodes: HtmlAst[]): string {
  return (<any>nodes[0]).value;
}

function _serializeErrors(errors: ParseError[]): string[] {
  return errors.map(e => e.msg);
}


text: return require("lockbox.init")


text:
'use strict';

import lodash from 'lodash';

export default (function(window, _) {

  var My = window.My || {};

  // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
  // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and
  // set a `X-Http-Method-Override` header.
  My.emulateHTTP = false;

  // Turn on `emulateJSON` to support legacy servers that can't deal with direct
  // `application/json` requests ... this will encode the body as
  // `application/x-www-form-urlencoded` instead and will send the model in a
  // form param named `model`.
  My.emulateJSON = false;

  var Model = My.Model = function(attributes, options) {
    var attrs = attributes || {};
    options || (options = {});
    this.cid = _.uniqueId(this.cidPrefix);
    this.attributes = {};

    if (options.collection) this.collection = options.collection;
    if (options.parse) attrs = this.parse(attrs, options) || {};

    var defaults = _.result(this, 'defaults');
    attrs = _.defaults(_.extend({}, defaults, attrs), defaults);
    this.set(attrs, options);
    this.changed = {};
    this.initialize.apply(this, arguments);
  };

  _.extend(Model.prototype, {

    // A hash of attributes whose current and previous value differ.
    changed: null,

    // The value returned during the last failed validation.
    validationError: null,

    // The default name for the JSON `id` attribute is `"id"`. MongoDB and
    // CouchDB users may want to set this to `"_id"`.
    idAttribute: 'id',

    // The prefix is used to create the client id which is used to identify models locally.
    // You may want to override this if you're experiencing name clashes with model ids.
    cidPrefix: 'c',

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize: function() {},

    // Return a copy of the model's `attributes` object.
    toJSON: function(options) {
      return _.clone(this.attributes);
    },

    // Proxy `My.sync` by default -- but override this if you need
    // custom syncing semantics for *this* particular model.
    sync: function() {
      return My.sync.apply(this, arguments);
    },

    // Get the value of an attribute.
    get: function(attr) {
      return this.attributes[attr];
    },

    // Get the HTML-escaped value of an attribute.
    escape: function(attr) {
      return _.escape(this.get(attr));
    },

    // Returns `true` if the attribute contains a value that is not null
    // or undefined.
    has: function(attr) {
      return this.get(attr) != null;
    },

    // Special-cased proxy to underscore's `_.matches` method.
    matches: function(attrs) {
      return !!_.iteratee(attrs, this)(this.attributes);
    },

    // Set a hash of model attributes on the object, firing `"change"`. This is
    // the core primitive operation of a model, updating the data and notifying
    // anyone who needs to know about the change in state. The heart of the beast.
    set: function(key, val, options) {
      if (key == null) return this;

      // Handle both `"key", value` and `{key: value}` -style arguments.
      var attrs;
      if (typeof key === 'object') {
        attrs = key;
        options = val;
      } else {
        (attrs = {})[key] = val;
      }

      options || (options = {});

      // Run validation.
      if (!this._validate(attrs, options)) return false;

      // Extract attributes and options.
      var unset = options.unset;
      var silent = options.silent;
      var changes = [];
      var changing = this._changing;
      this._changing = true;

      if (!changing) {
        this._previousAttributes = _.clone(this.attributes);
        this.changed = {};
      }

      var current = this.attributes;
      var changed = this.changed;
      var prev = this._previousAttributes;

      // For each `set` attribute, update or delete the current value.
      for (var attr in attrs) {
        val = attrs[attr];
        if (!_.isEqual(current[attr], val)) changes.push(attr);
        if (!_.isEqual(prev[attr], val)) {
          changed[attr] = val;
        } else {
          delete changed[attr];
        }
        unset ? delete current[attr] : current[attr] = val;
      }

      // Update the `id`.
      if (this.idAttribute in attrs) this.id = this.get(this.idAttribute);

      // Trigger all relevant attribute changes.
      if (!silent) {
        if (changes.length) this._pending = options;
        for (var i = 0; i < changes.length; i++) {
          this.trigger('change:' + changes[i], this, current[changes[i]], options);
        }
      }

      // You might be wondering why there's a `while` loop here. Changes can
      // be recursively nested within `"change"` events.
      if (changing) return this;
      if (!silent) {
        while (this._pending) {
          options = this._pending;
          this._pending = false;
          this.trigger('change', this, options);
        }
      }
      this._pending = false;
      this._changing = false;
      return this;
    },

    // Remove an attribute from the model, firing `"change"`. `unset` is a noop
    // if the attribute doesn't exist.
    unset: function(attr, options) {
      return this.set(attr, void 0, _.extend({}, options, {
        unset: true
      }));
    },

    // Clear all attributes on the model, firing `"change"`.
    clear: function(options) {
      var attrs = {};
      for (var key in this.attributes) attrs[key] = void 0;
      return this.set(attrs, _.extend({}, options, {
        unset: true
      }));
    },

    // Determine if the model has changed since the last `"change"` event.
    // If you specify an attribute name, determine if that attribute has changed.
    hasChanged: function(attr) {
      if (attr == null) return !_.isEmpty(this.changed);
      return _.has(this.changed, attr);
    },

    // Return an object containing all the attributes that have changed, or
    // false if there are no changed attributes. Useful for determining what
    // parts of a view need to be updated and/or what attributes need to be
    // persisted to the server. Unset attributes will be set to undefined.
    // You can also pass an attributes object to diff against the model,
    // determining if there *would be* a change.
    changedAttributes: function(diff) {
      if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
      var old = this._changing ? this._previousAttributes : this.attributes;
      var changed = {};
      for (var attr in diff) {
        var val = diff[attr];
        if (_.isEqual(old[attr], val)) continue;
        changed[attr] = val;
      }
      return _.size(changed) ? changed : false;
    },

    // Get the previous value of an attribute, recorded at the time the last
    // `"change"` event was fired.
    previous: function(attr) {
      if (attr == null || !this._previousAttributes) return null;
      return this._previousAttributes[attr];
    },

    // Get all of the attributes of the model at the time of the previous
    // `"change"` event.
    previousAttributes: function() {
      return _.clone(this._previousAttributes);
    },

    // Fetch the model from the server, merging the response with the model's
    // local attributes. Any changed attributes will trigger a "change" event.
    fetch: function(options) {
      options = _.extend({
        parse: true
      }, options);
      var model = this;
      var success = options.success;
      options.success = function(resp) {
        var serverAttrs = options.parse ? model.parse(resp, options) : resp;
        if (!model.set(serverAttrs, options)) return false;
        if (success) success.call(options.context, model, resp, options);
        model.trigger('sync', model, resp, options);
      };
      wrapError(this, options);
      return this.sync('read', this, options);
    },

    // Set a hash of model attributes, and sync the model to the server.
    // If the server returns an attributes hash that differs, the model's
    // state will be `set` again.
    save: function(key, val, options) {
      // Handle both `"key", value` and `{key: value}` -style arguments.
      var attrs;
      if (key == null || typeof key === 'object') {
        attrs = key;
        options = val;
      } else {
        (attrs = {})[key] = val;
      }

      options = _.extend({
        validate: true,
        parse: true
      }, options);
      var wait = options.wait;

      // If we're not waiting and attributes exist, save acts as
      // `set(attr).save(null, opts)` with validation. Otherwise, check if
      // the model will be valid when the attributes, if any, are set.
      if (attrs && !wait) {
        if (!this.set(attrs, options)) return false;
      } else if (!this._validate(attrs, options)) {
        return false;
      }

      // After a successful server-side save, the client is (optionally)
      // updated with the server-side state.
      var model = this;
      var success = options.success;
      var attributes = this.attributes;
      options.success = function(resp) {
        // Ensure attributes are restored during synchronous saves.
        model.attributes = attributes;
        var serverAttrs = options.parse ? model.parse(resp, options) : resp;
        if (wait) serverAttrs = _.extend({}, attrs, serverAttrs);
        if (serverAttrs && !model.set(serverAttrs, options)) return false;
        if (success) success.call(options.context, model, resp, options);
        model.trigger('sync', model, resp, options);
      };
      wrapError(this, options);

      // Set temporary attributes if `{wait: true}` to properly find new ids.
      if (attrs && wait) this.attributes = _.extend({}, attributes, attrs);

      var method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
      if (method === 'patch' && !options.attrs) options.attrs = attrs;
      var xhr = this.sync(method, this, options);

      // Restore attributes.
      this.attributes = attributes;

      return xhr;
    },

    // Destroy this model on the server if it was already persisted.
    // Optimistically removes the model from its collection, if it has one.
    // If `wait: true` is passed, waits for the server to respond before removal.
    destroy: function(options) {
      options = options ? _.clone(options) : {};
      var model = this;
      var success = options.success;
      var wait = options.wait;

      var destroy = function() {
        model.stopListening();
        model.trigger('destroy', model, model.collection, options);
      };

      options.success = function(resp) {
        if (wait) destroy();
        if (success) success.call(options.context, model, resp, options);
        if (!model.isNew()) model.trigger('sync', model, resp, options);
      };

      var xhr = false;
      if (this.isNew()) {
        _.defer(options.success);
      } else {
        wrapError(this, options);
        xhr = this.sync('delete', this, options);
      }
      if (!wait) destroy();
      return xhr;
    },

    // Default URL for the model's representation on the server -- if you're
    // using My's restful methods, override this to change the endpoint
    // that will be called.
    url: function() {
      var base =
        _.result(this, 'urlRoot') ||
        _.result(this.collection, 'url') ||
        urlError();
      if (this.isNew()) return base;
      var id = this.get(this.idAttribute);
      return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id);
    },

    // **parse** converts a response into the hash of attributes to be `set` on
    // the model. The default implementation is just to pass the response along.
    parse: function(resp, options) {
      return resp;
    },

    // Create a new model with identical attributes to this one.
    clone: function() {
      return new this.constructor(this.attributes);
    },

    // A model is new if it has never been saved to the server, and lacks an id.
    isNew: function() {
      return !this.has(this.idAttribute);
    },

    // Check if the model is currently in a valid state.
    isValid: function(options) {
      return this._validate({}, _.extend({}, options, {
        validate: true
      }));
    },

    // Run validation against the next complete set of model attributes,
    // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
    _validate: function(attrs, options) {
      if (!options.validate || !this.validate) return true;
      attrs = _.extend({}, this.attributes, attrs);
      var error = this.validationError = this.validate(attrs, options) || null;
      if (!error) return true;
      this.trigger('invalid', this, error, _.extend(options, {
        validationError: error
      }));
      return false;
    }
  });

  // Override this function to change the manner in which My persists
  // models to the server. You will be passed the type of request, and the
  // model in question. By default, makes a RESTful Ajax request
  // to the model's `url()`. Some possible customizations could be:
  //
  // * Use `setTimeout` to batch rapid-fire updates into a single request.
  // * Send up the models as XML instead of JSON.
  // * Persist models via WebSockets instead of Ajax.
  //
  // Turn on `My.emulateHTTP` in order to send `PUT` and `DELETE` requests
  // as `POST`, with a `_method` parameter containing the true HTTP method,
  // as well as all requests with the body as `application/x-www-form-urlencoded`
  // instead of `application/json` with the model in a param named `model`.
  // Useful when interfacing with server-side languages like **PHP** that make
  // it difficult to read the body of `PUT` requests.
  My.sync = function(method, model, options) {
    var type = methodMap[method];

    // Default options, unless specified.
    _.defaults(options || (options = {}), {
      emulateHTTP: My.emulateHTTP,
      emulateJSON: My.emulateJSON
    });

    // Default JSON-request options.
    var params = {type: type, dataType: 'json'};

    // Ensure that we have a URL.
    if (!options.url) {
      params.url = _.result(model, 'url') || urlError();
    }

    // Ensure that we have the appropriate request data.
    if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
      params.contentType = 'application/json';
      params.data = JSON.stringify(options.attrs || model.toJSON(options));
    }

    // For older servers, emulate JSON by encoding the request into an HTML-form.
    if (options.emulateJSON) {
      params.contentType = 'application/x-www-form-urlencoded';
      params.data = params.data ? {model: params.data} : {};
    }

    // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
    // And an `X-HTTP-Method-Override` header.
    if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
      params.type = 'POST';
      if (options.emulateJSON) params.data._method = type;
      var beforeSend = options.beforeSend;
      options.beforeSend = function(xhr) {
        xhr.setRequestHeader('X-HTTP-Method-Override', type);
        if (beforeSend) return beforeSend.apply(this, arguments);
      };
    }

    // Don't process data on a non-GET request.
    if (params.type !== 'GET' && !options.emulateJSON) {
      params.processData = false;
    }

    // Pass along `textStatus` and `errorThrown` from jQuery.
    var error = options.error;
    options.error = function(xhr, textStatus, errorThrown) {
      options.textStatus = textStatus;
      options.errorThrown = errorThrown;
      if (error) error.call(options.context, xhr, textStatus, errorThrown);
    };

    // Make the request, allowing the user to override any Ajax options.
    var xhr = options.xhr = My.ajax(_.extend(params, options));
    model.trigger('request', model, xhr, options);
    return xhr;
  };

  // Map from CRUD to HTTP for our default `My.sync` implementation.
  var methodMap = {
    'create': 'POST',
    'update': 'PUT',
    'patch': 'PATCH',
    'delete': 'DELETE',
    'read': 'GET'
  };

  // Set the default implementation of `My.ajax` to proxy through to `$`.
  // Override this if you'd like to use a different library.
  My.ajax = function() {
    // return My.$.ajax.apply(My.$, arguments);
    // TODO ajax implementation
    // TODO fetch API & polyfill
  };

  Model.extend = function(protoProps, staticProps) {
    var parent = this;
    var child;

    // The constructor function for the new subclass is either defined by you
    // (the "constructor" property in your `extend` definition), or defaulted
    // by us to simply call the parent constructor.
    if (protoProps && _.has(protoProps, 'constructor')) {
      child = protoProps.constructor;
    } else {
      child = function() {
        return parent.apply(this, arguments);
      };
    }

    // Add static properties to the constructor function, if supplied.
    _.assign(child, parent, staticProps);

    // Set the prototype chain to inherit from `parent`, without calling
    // `parent`'s constructor function and add the prototype properties.
    child.prototype = _.create(parent.prototype, protoProps);
    child.prototype.constructor = child;

    // Set a convenience property in case the parent's prototype is needed
    // later.
    child.__super__ = parent.prototype;

    return child;
  }

  // Wrap an optional error callback with a fallback error event.
  var wrapError = function(model, options) {
    var error = options.error;
    options.error = function(resp) {
      if (error) error.call(options.context, model, resp, options);
      model.trigger('error', model, resp, options);
    };
  };

  return My;
})(window, lodash);


text:
#include "config.h"
#include "DOMObjectCache.h"

#include "Document.h"
#include "Node.h"
#include <glib-object.h>
#include <wtf/HashMap.h>

namespace WebKit {

typedef struct {
    GObject* object;
    WebCore::Frame* frame;
    guint timesReturned;
} DOMObjectCacheData;

typedef HashMap<void*, DOMObjectCacheData*> DOMObjectMap;

static DOMObjectMap& domObjects()
{
    static DOMObjectMap staticDOMObjects;
    return staticDOMObjects;
}

static WebCore::Frame* getFrameFromHandle(void* objectHandle)
{
    WebCore::Node* node = static_cast<WebCore::Node*>(objectHandle);
    if (!node->inDocument())
        return 0;
    return node->document().frame();
}

void DOMObjectCache::forget(void* objectHandle)
{
    DOMObjectCacheData* cacheData = domObjects().get(objectHandle);
    ASSERT(cacheData);
    g_slice_free(DOMObjectCacheData, cacheData);
    domObjects().take(objectHandle);
}

static void weakRefNotify(gpointer data, GObject* zombie)
{
    gboolean* objectDead = static_cast<gboolean*>(data);
    *objectDead = TRUE;
}

void DOMObjectCache::clearByFrame(WebCore::Frame* frame)
{
    Vector<DOMObjectCacheData*> toUnref;

    // Unreffing the objects removes them from the cache in their
    // finalize method, so just save them to do that while we are not
    // iterating the cache itself.
    DOMObjectMap::iterator end = domObjects().end();
    for (DOMObjectMap::iterator iter = domObjects().begin(); iter != end; ++iter) {
        DOMObjectCacheData* data = iter->value;
        ASSERT(data);
        if ((!frame || data->frame == frame) && data->timesReturned)
            toUnref.append(data);
    }

    Vector<DOMObjectCacheData*>::iterator last = toUnref.end();
    for (Vector<DOMObjectCacheData*>::iterator it = toUnref.begin(); it != last; ++it) {
        DOMObjectCacheData* data = *it;
        // We can't really know what the user has done with the DOM
        // objects, so in case any of the external references to them
        // were unreffed (but not all, otherwise the object would be
        // dead and out of the cache) we'll add a weak ref before we
        // start to get rid of the cache's own references; if the
        // object dies in the middle of the process, we'll just stop.
        gboolean objectDead = FALSE;
        g_object_weak_ref(data->object, weakRefNotify, &objectDead);
        // We need to check objectDead first, otherwise the cache data
        // might be garbage already.
        while (!objectDead && data->timesReturned > 0) {
            // If this is the last unref we are going to do,
            // disconnect the weak ref. We cannot do it afterwards
            // because the object might be dead at that point.
            if (data->timesReturned == 1) {
                g_object_weak_unref(data->object, weakRefNotify, &objectDead);
                // At this point, the next time the DOMObject is
                // unref'ed it will be finalized,
                // DOMObject::finalize() will call
                // DOMObjectCache::forget(), which will free 'data'.
                // Toggling 'objectDead' here will ensure we don't
                // dereference an invalid pointer in the next
                // iteration.
                objectDead = TRUE;
            }
            data->timesReturned--;
            g_object_unref(data->object);
        }
    }
}

DOMObjectCache::~DOMObjectCache()
{
    clearByFrame();
}

void* DOMObjectCache::get(void* objectHandle)
{
    DOMObjectCacheData* data = domObjects().get(objectHandle);
    if (!data)
        return 0;

    // We want to add one ref each time a wrapper is returned, so that
    // the user can manually unref them if he chooses to.
    ASSERT(data->object);
    data->timesReturned++;
    return g_object_ref(data->object);
}

void* DOMObjectCache::put(void* objectHandle, void* wrapper)
{
    if (domObjects().get(objectHandle))
        return wrapper;

    DOMObjectCacheData* data = g_slice_new(DOMObjectCacheData);
    data->object = static_cast<GObject*>(wrapper);
    data->frame = 0;
    data->timesReturned = 1;

    domObjects().set(objectHandle, data);
    return wrapper;
}

void* DOMObjectCache::put(WebCore::Node* objectHandle, void* wrapper)
{
    // call the ::put version that takes void* to do the basic cache
    // insertion work
    put(static_cast<void*>(objectHandle), wrapper);

    DOMObjectCacheData* data = domObjects().get(objectHandle);
    ASSERT(data);

    data->frame = getFrameFromHandle(objectHandle);

    return wrapper;
}

}


text:
require 'rails_helper'

RSpec.describe BatchesController, type: :controller do

    describe "as admin" do

        before do
            @user = FactoryGirl.create :admin
            login_with @user
        end

        describe "GET #index" do
            it "assigns all batches as @batches" do
                batches = FactoryGirl.create_list :batch, 5
                get :index
                expect(assigns(:batches).to_a).to eq(batches.to_a)
            end

            it "responds with http success" do
                expect(response).to have_http_status(:ok)
            end
        end

        describe "GET #show" do
            before do
                @batch = FactoryGirl.create :batch
            end

            it "assigns the requested batch as @batch" do
                get :show, params: {:id => @batch.id}
                expect(assigns(:batch)).to eq(@batch)
            end

            it "responds with http success" do
                expect(response).to have_http_status(:ok)
            end

        end # SHOW

        describe "GET #new" do
            it "assigns a new batch as @batch" do
                get :new
                expect(assigns(:batch)).to be_a_new(Batch)
            end

            it "responds with http success" do
                expect(response).to have_http_status(:ok)
            end
        end

        describe "POST #create" do

            let(:create_batch){ post :create, {:params => {:qty => {:n => 1}}} }
            context "with valid params" do
                it "creates a new Batch" do
                    expect{
                        create_batch.to change(Batch, :count).by(1)
                    }
                end

                it "creates n bottles" do
                    expect{
                        create_batch.to change(Bottle, :count).by(1)
                    }
                end

                it "assigns a newly created batch as @batch" do
                    create_batch
                    expect(assigns(:batch)).to be_a(Batch)
                    expect(assigns(:batch)).to be_persisted
                end

                it "redirects to the created batch" do
                    create_batch
                    expect(response).to redirect_to(batch_path(assigns(:batch).id))
                end

            end

        end

        describe "DELETE #destroy" do
            it "destroys the requested batch" do
                batch = FactoryGirl.create :batch
                expect {
                    delete :destroy, params: {id: batch.id}
                }.to change(Batch, :count).by(-1)
            end

            it "destroys the related bottles" do
                batch = FactoryGirl.create :batch
                expect {
                    delete :destroy, params: {id: batch.id}
                }.to change(Bottle, :count).by(-1)
            end

            it "redirects to the batches list" do
                batch = FactoryGirl.create :batch
                delete :destroy, params: {id: batch.to_param}
                expect(response).to redirect_to(batches_url)
            end
        end
    end

    describe "as reg_user" do

        before do
            @user = FactoryGirl.create :reg_user
            login_with @user
            @batch = FactoryGirl.create :batch
        end

        let(:expect_access_denied){expect(response).to redirect_to("/")}
        describe "denies access to everything" do
            it "denies index" do
                get :index
                expect_access_denied
            end

            it "denies show" do
                get :show, params: {id: @batch.id}
                expect_access_denied
            end

            it "denies new" do
                get :new
                expect_access_denied
            end

            it "denies create" do
                get :create, params: {}
                expect_access_denied
            end

            it "denies delete" do
                get :show, params: {id: @batch.id}
                expect_access_denied
            end
        end
    end

    describe "as anonymous user" do
        before do
            @batch = FactoryGirl.create :batch
        end
        let(:expect_login_redirect){expect(response).to redirect_to("/users/sign_in")}
        it "denies index" do
            get :index
            expect_login_redirect
        end

        it "denies show" do
            get :show, params: {id: @batch.id}
            expect_login_redirect
        end

        it "denies new" do
            get :new
            expect_login_redirect
        end

        it "denies create" do
            get :create, params: @batch.attributes
            expect_login_redirect
        end

        it "denies delete" do
            get :show, params: {id: @batch.id}
            expect_login_redirect
        end

    end

end


text:
<?php

namespace common\models;

/**
 * This is the ActiveQuery class for [[SiteConfig]].
 *
 * @see SiteConfig
 */
class SiteConfigQuery extends \yii\db\ActiveQuery
{
    /*public function active()
    {
        return $this->andWhere('[[status]]=1');
    }*/

    /**
     * @inheritdoc
     * @return SiteConfig[]|array
     */
    public function all($db = null)
    {
        return parent::all($db);
    }

    /**
     * @inheritdoc
     * @return SiteConfig|array|null
     */
    public function one($db = null)
    {
        return parent::one($db);
    }
}


text:
package quickfix.field;
import quickfix.StringField;

public class MiscFeeCurr extends StringField
{
  static final long serialVersionUID = 20050617;

  public static final int FIELD = 138;

  public MiscFeeCurr()
  {
    super(138);
  }

  public MiscFeeCurr(String data)
  {
     super(138, data);
  }

}


text:
//  Copyright (c) 2013, Facebook, Inc.  All rights reserved.
//  This source code is licensed under the BSD-style license found in the
//  LICENSE file in the root directory of this source tree. An additional grant
//  of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include "db/builder.h"

#include "db/dbformat.h"
#include "db/filename.h"
#include "db/merge_helper.h"
#include "db/table_cache.h"
#include "db/version_edit.h"
#include "rocksdb/db.h"
#include "rocksdb/env.h"
#include "rocksdb/iterator.h"
#include "rocksdb/options.h"
#include "rocksdb/table.h"
#include "table/block_based_table_builder.h"
#include "util/stop_watch.h"

namespace rocksdb {

class TableFactory;

TableBuilder* NewTableBuilder(const Options& options,
                              const InternalKeyComparator& internal_comparator,
                              WritableFile* file,
                              CompressionType compression_type) {
  return options.table_factory->NewTableBuilder(options, internal_comparator,
                                                file, compression_type);
}

Status BuildTable(const std::string& dbname, Env* env, const Options& options,
                  const EnvOptions& soptions, TableCache* table_cache,
                  Iterator* iter, FileMetaData* meta,
                  const InternalKeyComparator& internal_comparator,
                  const SequenceNumber newest_snapshot,
                  const SequenceNumber earliest_seqno_in_memtable,
                  const CompressionType compression) {
  Status s;
  meta->file_size = 0;
  meta->smallest_seqno = meta->largest_seqno = 0;
  iter->SeekToFirst();

  // If the sequence number of the smallest entry in the memtable is
  // smaller than the most recent snapshot, then we do not trigger
  // removal of duplicate/deleted keys as part of this builder.
  bool purge = options.purge_redundant_kvs_while_flush;
  if (earliest_seqno_in_memtable <= newest_snapshot) {
    purge = false;
  }

  std::string fname = TableFileName(dbname, meta->number);
  if (iter->Valid()) {
    unique_ptr<WritableFile> file;
    s = env->NewWritableFile(fname, &file, soptions);
    if (!s.ok()) {
      return s;
    }

    TableBuilder* builder =
        NewTableBuilder(options, internal_comparator, file.get(), compression);

    // the first key is the smallest key
    Slice key = iter->key();
    meta->smallest.DecodeFrom(key);
    meta->smallest_seqno = GetInternalKeySeqno(key);
    meta->largest_seqno = meta->smallest_seqno;

    MergeHelper merge(internal_comparator.user_comparator(),
                      options.merge_operator.get(), options.info_log.get(),
                      options.min_partial_merge_operands,
                      true /* internal key corruption is not ok */);

    if (purge) {
      // Ugly walkaround to avoid compiler error for release build
      bool ok __attribute__((unused)) = true;

      // Will write to builder if current key != prev key
      ParsedInternalKey prev_ikey;
      std::string prev_key;
      bool is_first_key = true;    // Also write if this is the very first key

      while (iter->Valid()) {
        bool iterator_at_next = false;

        // Get current key
        ParsedInternalKey this_ikey;
        Slice key = iter->key();
        Slice value = iter->value();

        // In-memory key corruption is not ok;
        // TODO: find a clean way to treat in memory key corruption
        ok = ParseInternalKey(key, &this_ikey);
        assert(ok);
        assert(this_ikey.sequence >= earliest_seqno_in_memtable);

        // If the key is the same as the previous key (and it is not the
        // first key), then we skip it, since it is an older version.
        // Otherwise we output the key and mark it as the "new" previous key.
        if (!is_first_key && !internal_comparator.user_comparator()->Compare(
                                  prev_ikey.user_key, this_ikey.user_key)) {
          // seqno within the same key are in decreasing order
          assert(this_ikey.sequence < prev_ikey.sequence);
        } else {
          is_first_key = false;

          if (this_ikey.type == kTypeMerge) {
            // Handle merge-type keys using the MergeHelper
            // TODO: pass statistics to MergeUntil
            merge.MergeUntil(iter, 0 /* don't worry about snapshot */);
            iterator_at_next = true;
            if (merge.IsSuccess()) {
              // Merge completed correctly.
              // Add the resulting merge key/value and continue to next
              builder->Add(merge.key(), merge.value());
              prev_key.assign(merge.key().data(), merge.key().size());
              ok = ParseInternalKey(Slice(prev_key), &prev_ikey);
              assert(ok);
            } else {
              // Merge did not find a Put/Delete.
              // Can not compact these merges into a kValueType.
              // Write them out one-by-one. (Proceed back() to front())
              const std::deque<std::string>& keys = merge.keys();
              const std::deque<std::string>& values = merge.values();
              assert(keys.size() == values.size() && keys.size() >= 1);
              std::deque<std::string>::const_reverse_iterator key_iter;
              std::deque<std::string>::const_reverse_iterator value_iter;
              for (key_iter=keys.rbegin(), value_iter = values.rbegin();
                   key_iter != keys.rend() && value_iter != values.rend();
                   ++key_iter, ++value_iter) {

                builder->Add(Slice(*key_iter), Slice(*value_iter));
              }

              // Sanity check. Both iterators should end at the same time
              assert(key_iter == keys.rend() && value_iter == values.rend());

              prev_key.assign(keys.front());
              ok = ParseInternalKey(Slice(prev_key), &prev_ikey);
              assert(ok);
            }
          } else {
            // Handle Put/Delete-type keys by simply writing them
            builder->Add(key, value);
            prev_key.assign(key.data(), key.size());
            ok = ParseInternalKey(Slice(prev_key), &prev_ikey);
            assert(ok);
          }
        }

        if (!iterator_at_next) iter->Next();
      }

      // The last key is the largest key
      meta->largest.DecodeFrom(Slice(prev_key));
      SequenceNumber seqno = GetInternalKeySeqno(Slice(prev_key));
      meta->smallest_seqno = std::min(meta->smallest_seqno, seqno);
      meta->largest_seqno = std::max(meta->largest_seqno, seqno);

    } else {
      for (; iter->Valid(); iter->Next()) {
        Slice key = iter->key();
        meta->largest.DecodeFrom(key);
        builder->Add(key, iter->value());
        SequenceNumber seqno = GetInternalKeySeqno(key);
        meta->smallest_seqno = std::min(meta->smallest_seqno, seqno);
        meta->largest_seqno = std::max(meta->largest_seqno, seqno);
      }
    }

    // Finish and check for builder errors
    if (s.ok()) {
      s = builder->Finish();
      if (s.ok()) {
        meta->file_size = builder->FileSize();
        assert(meta->file_size > 0);
      }
    } else {
      builder->Abandon();
    }
    delete builder;

    // Finish and check for file errors
    if (s.ok() && !options.disableDataSync) {
      if (options.use_fsync) {
        StopWatch sw(env, options.statistics.get(), TABLE_SYNC_MICROS);
        s = file->Fsync();
      } else {
        StopWatch sw(env, options.statistics.get(), TABLE_SYNC_MICROS);
        s = file->Sync();
      }
    }
    if (s.ok()) {
      s = file->Close();
    }

    if (s.ok()) {
      // Verify that the table is usable
      Iterator* it = table_cache->NewIterator(ReadOptions(), soptions,
                                              internal_comparator, *meta);
      s = it->status();
      delete it;
    }
  }

  // Check for input iterator errors
  if (!iter->status().ok()) {
    s = iter->status();
  }

  if (s.ok() && meta->file_size > 0) {
    // Keep it
  } else {
    env->DeleteFile(fname);
  }
  return s;
}

}  // namespace rocksdb


text:
<?php

$params = array_merge(
        require(__DIR__ . '/../../common/config/params.php'), require(__DIR__ . '/../../common/config/params-local.php'), require(__DIR__ . '/params.php'), require(__DIR__ . '/params-local.php')
);

return [
    'id' => 'app-frontend',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'controllerNamespace' => 'frontend\controllers',
    'modules' => require(__DIR__ . '/modules.php'),
    'components' => [
        'urlManager' => [
            'showScriptName' => false,
            'enablePrettyUrl' => true
        ],
        // here you can set theme used for your backend application
// (template comes with 'default' and 'cool')
        'view' => [
            'theme' => [
                'pathMap' => ['@app/views' => '@webroot/themes/cool/views'],
                'baseUrl' => '@web/themes/cool',
            ],
        ],
        'user' => [
            'identityClass' => 'common\models\User',
            'enableAutoLogin' => true,
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
    ],
    'params' => $params,
];


text:
package org.usfirst.frc.team166.robot.commands.Autonomous;

import edu.wpi.first.wpilibj.Preferences;
import edu.wpi.first.wpilibj.command.CommandGroup;
import edu.wpi.first.wpilibj.command.WaitCommand;

import org.usfirst.frc.team166.robot.RobotMap;
import org.usfirst.frc.team166.robot.commands.DriveDistance;
import org.usfirst.frc.team166.robot.commands.DriveStraightAuto;
import org.usfirst.frc.team166.robot.commands.GearManipulator.OpenManipulator;

/**
 *
 */
public class CenterGearAutonomous extends CommandGroup {

	public CenterGearAutonomous() {

		double centerGearAutoSpeed = Preferences.getInstance().getDouble(RobotMap.centerGearAutoSpeed, 0.0);
		double centerGearAutoDistance = Preferences.getInstance().getDouble(RobotMap.centerGearAutoDistance, 0.0);
		double autoWaitTime = Preferences.getInstance().getDouble(RobotMap.autoWaitTime, 0.0);

		addSequential(new DriveStraightAuto(centerGearAutoDistance, centerGearAutoSpeed));
		addSequential(new WaitCommand(autoWaitTime));
		addSequential(new OpenManipulator());

		double autoWaitTime2 = Preferences.getInstance().getDouble(RobotMap.autoWaitTime2, 0.0);
		addSequential(new WaitCommand(autoWaitTime2));
		double centerGearAutoDistanceBackwards = Preferences.getInstance()
				.getDouble(RobotMap.centerGearAutoDistanceBackwards, 0.0);
		addSequential(new DriveDistance(centerGearAutoDistanceBackwards, -0.25));
	}
}


text:
function OTF = opticsDefocusedMTF(s, alpha)
% Diffraction-limited MTF without aberrations but with defocus
%
% Syntax:
%   OTF = opticsDefocusedMTF(s, alpha)
%
% Description:
%    The diffraction-limited MTF of a lens with a circular aperture,
%    without aberrations when (a) focused (alpha = 0) and (b) defocused
%    (alpha ~= 0).
%
%    The vector s is the reduced spatial frequency, which ranges from 0 to
%    2. In the routine dlCore this is called normalizedFreq and in that
%    routine it ranges from 0 to 1. Here it ranges from 0 to 2 but
%    otherwise appears to be the same.
%
%    The parameter alpha is the defocus parameter; it is related to the
%    defocus w20 of Hopkins. The vector alpha varies with spatial
%    frequency. The formula is defined in the Marimont and Wandell paper.
%
%    This function is used when calculating
%      * the effects of human chromatic aberration,
%      * understanding defocus and depth-of-field (opticsDepthDefocus).
%
%    This routine is called from defocusMTF via opticsDefocusCore.
%
% Inputs:
%    s     - Vector. The reduced spatial frequency [Range: 0-2]
%    alpha - Vector. The defocus parameter. varies with spatial frequency.
%
% Outputs:
%    OTF   - Matrix. The resulting MTF
%
% Optional key/value pairs:
%    None.
%
% References:
%    * See paper by Marimont and Wandell for definitions and functions.
%       Particularly the material in  Appendix A. These calculations come
%       from the optics literature and particularly Hopkins.
%
%    * Other useful references are:
%      = "On the depth  information in the point spread function of a
%        defocused optical system (Subbarao, 1999)"
%        [Note: XXX - The Subbarao paper claims there is an error in the
%        formula, but I don't think he is right. He complains about the
%        external scale factor. We do have a problem. But I am not sure his
%        solution is right.]
%
%      = Levi and Austing, Tables of the Modulation Transfer ... (1968)
%        [Note: XXX - We should compare tables therein with this some day.]
%
% See Also:
%   humanCore, opticsDefocusParameters (NYI), opticsDepthDefocus,
%   Examples at: s_opticsDefocus
%

% History:
%    xx/xx/05       Copyright ImagEval Consultants, LLC, 2005.
%    03/12/18  jnm  Formatting
%    06/27/19  JNM  Documentation update

if notDefined('s'), error('Reduced spatial frequency required'); end
if notDefined('alpha'), error('Alpha required'); end

% Normalized spatial frequency from reduced SF
% We always have a problem
nf = abs(s) / 2;
beta = sqrt(1 - nf .^ 2);

% Allocate size.
OTF = zeros(size(nf));

% Calculate perfect spatial frequencies of OTF (alpha = 0)
ii = alpha == 0;
% if sum(ii) > 0, warning('alpha zero case detected'); end
OTF(ii) = (2 / pi) * (acos(nf(ii)) - nf(ii) .* beta(ii));

% Calculate defocused spatial frequencies of OTF (alpha ~= 0)
ii = alpha ~= 0;
H1 = beta(ii) .* besselj(1, alpha(ii)) + 1 / 2 * sin(2 * beta(ii)) .* ...
    (besselj(1, alpha(ii)) - besselj(3, alpha(ii))) - ...
    1 / 4 * sin(4 * beta(ii)) .* ...
    (besselj(3, alpha(ii)) - besselj(5, alpha(ii)));

H2 = sin(beta(ii)) .* (besselj(0, alpha(ii)) - besselj(2, alpha(ii))) + ...
    1 / 3 * sin(3 * beta(ii)) .* ...
    (besselj(2, alpha(ii)) - besselj(4, alpha(ii))) - ...
    1 / 5 * sin(5 * beta(ii)) .* ...
    (besselj(4, alpha(ii)) - besselj(6, alpha(ii)));

OTF(ii) = (4 ./ (pi * alpha(ii))) .* cos(alpha(ii) .* nf(ii)) .* H1 - ...
    (4 ./ (pi * alpha(ii))) .* sin(alpha(ii) .* nf(ii)) .* H2;

% Normalize? Assuming the first entry is basically DC?
OTF = OTF / OTF(1);

end


text:
package com.alibaba.cobar.config.loader;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

import com.alibaba.cobar.CobarServer;
import com.alibaba.cobar.config.QuarantineConfig;
import com.alibaba.cobar.config.SchemaConfig;
import com.alibaba.cobar.config.UserConfig;
import com.alibaba.cobar.server.util.StringUtil;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.taobao.tddl.common.exception.TddlException;
import com.taobao.tddl.common.exception.TddlNestableRuntimeException;
import com.taobao.tddl.common.model.lifecycle.AbstractLifecycle;
import com.taobao.tddl.common.model.lifecycle.Lifecycle;
import com.taobao.tddl.common.properties.ConnectionProperties;
import com.taobao.tddl.config.ConfigDataHandler;
import com.taobao.tddl.config.ConfigDataHandlerFactory;
import com.taobao.tddl.config.ConfigDataListener;
import com.taobao.tddl.config.impl.ConfigDataHandlerCity;
import com.taobao.tddl.matrix.jdbc.TDataSource;

import com.taobao.tddl.common.utils.logger.Logger;
import com.taobao.tddl.common.utils.logger.LoggerFactory;

/**
 * 加载一个appname对应的资源,比如用户密码/tddl数据源等
 *
 * @author jianghang 2014-5-28 下午5:09:41
 * @since 5.1.0
 */
public final class AppLoader extends AbstractLifecycle implements Lifecycle {

    private static final Logger              logger            = LoggerFactory.getLogger(AppLoader.class);
    private static final String              DATAID_PREFIX     = "com.taobao.corona.";
    private static final String              DATAID_SUFFIX     = ".passwd";
    private static final String              QUARANTINE_SURFIX = ".quarantine";
    private ConfigDataHandlerFactory         cdhf              = ConfigDataHandlerCity.getFactory(null, null);
    private Cache<String, ConfigDataHandler> cdhs              = CacheBuilder.newBuilder().build();
    private String                           cluster;
    private Map<String/* app */, UserConfig> users;
    private Map<String, SchemaConfig>        schemas;
    private QuarantineConfig                 quarantine;

    public AppLoader(String cluster){
        this.cluster = cluster;
    }

    @Override
    protected void doInit() throws TddlException {
        this.users = new HashMap<String, UserConfig>();
        this.schemas = new HashMap<String, SchemaConfig>();
        this.quarantine = QuarantineConfig.getInstance();
    }

    /**
     * 装载app
     */
    public void loadApp(final String app) {
        try {
            logger.info("start loading app:" + app);
            this.loadUser(app);
            this.loadSchema(app);
            this.loadQuarantine(app);
            logger.info("finish loading app:" + app);
        } catch (Throwable e) {
            throw new TddlNestableRuntimeException(e);
        }
    }

    /**
     * Do not add cluster to keep compatible with old tddl
     *
     * @param app
     * @throws ExecutionException
     * @throws TddlException
     */
    private void loadQuarantine(String app) throws ExecutionException, TddlException {
        String dataId = DATAID_PREFIX + app + QUARANTINE_SURFIX;
        ConfigDataHandler cdh = getQuarantineDataHandler(app, dataId);
        String config = cdh.getData();
        this.parseQuarantineConfig(dataId, app, config);
    }

    /**
     * 卸载app
     */
    public void unLoadApp(final String app) {
        try {
            logger.info("start unLoading app:" + app);
            this.unLoadUser(app);
            this.unLoadSchema(app);
            logger.info("finish unLoading app:" + app);
        } catch (Throwable e) {
            throw new TddlNestableRuntimeException(e);
        }
    }

    private synchronized void loadUser(final String app) throws ExecutionException, TddlException {
        String dataId = DATAID_PREFIX + this.cluster + "." + app + DATAID_SUFFIX;
        ConfigDataHandler cdh = getConfigDataHandler(app, dataId);
        String config = cdh.getData();
        if (StringUtil.isEmpty(config)) {
            cdhs.invalidate(dataId);
            cdh.destroy();

            // 重新拿一下新的dataId
            String newDataId = DATAID_PREFIX + app + DATAID_SUFFIX;
            cdh = getConfigDataHandler(app, newDataId);
            config = cdh.getData();
        }

        this.parseConfig(dataId, app, config);
    }

    private synchronized void unLoadUser(final String app) throws TddlException {
        String dataId = DATAID_PREFIX + this.cluster + "." + app + DATAID_SUFFIX;
        ConfigDataHandler cdh = cdhs.getIfPresent(dataId);
        if (cdh != null) {
            cdh.destroy();
            cdhs.invalidate(dataId);
        }

        String newDataId = DATAID_PREFIX + app + DATAID_SUFFIX;
        cdh = cdhs.getIfPresent(newDataId);
        if (cdh != null) {
            cdh.destroy();
            cdhs.invalidate(dataId);
        }

        users.remove(app);
    }

    private synchronized void loadSchema(final String app) {
        SchemaConfig schema = schemas.get(app);
        if (schema != null) {
            return;
        }

        // MDC.put("app", app);
        TDataSource ds = new TDataSource();
        ds.putConnectionProperties(ConnectionProperties.CHOOSE_STREAMING, true);
        ds.putConnectionProperties(ConnectionProperties.PROCESS_AUTO_INCREMENT_BY_SEQUENCE, true);
        ds.putConnectionProperties(ConnectionProperties.INIT_CONCURRENT_POOL_EVERY_CONNECTION, false);
        // 共享一个链接池
        ds.setGlobalExecutorService(CobarServer.getInstance().getServerExectuor());
        // ds.putConnectionProperties(ConnectionProperties.MERGE_CONCURRENT,
        // true);
        // ds.putConnectionProperties(ConnectionProperties.CONCURRENT_THREAD_SIZE,
        // CobarServer.getInstance()
        // .getConfig()
        // .getSystem()
        // .getServerExecutor());
        ds.setSharding(false);// 允许非sharding启动
        ds.setAppName(app);
        // try {
        // ds.init();
        // } catch (TddlException e) {
        // // 启动时出错不往上抛
        // logger.error(e);
        // } finally {
        // MDC.remove("app");
        // }
        schema = new SchemaConfig(app);
        schema.setDataSource(ds);
        schemas.put(app, schema);
    }

    private synchronized void unLoadSchema(final String app) throws TddlException {
        SchemaConfig schema = schemas.remove(app);
        if (schema != null) {
            TDataSource dataSource = schema.getDataSource();
            if (dataSource != null) {
                dataSource.destroy();
            }
        }
    }

    private ConfigDataHandler getQuarantineDataHandler(final String app, final String dataId) throws ExecutionException {
        return cdhs.get(dataId, new Callable<ConfigDataHandler>() {

            @Override
            public ConfigDataHandler call() throws Exception {
                return cdhf.getConfigDataHandler(dataId, new ConfigDataListener() {

                    @Override
                    public void onDataRecieved(String dataId, String data) {
                        parseQuarantineConfig(dataId, app, data);
                    }
                });
            }
        });
    }

    private ConfigDataHandler getConfigDataHandler(final String app, final String dataId) throws ExecutionException {
        return cdhs.get(dataId, new Callable<ConfigDataHandler>() {

            @Override
            public ConfigDataHandler call() throws Exception {
                return cdhf.getConfigDataHandler(dataId, new ConfigDataListener() {

                    @Override
                    public void onDataRecieved(String dataId, String data) {
                        parseConfig(dataId, app, data);
                    }
                });
            }
        });
    }

    private synchronized void parseConfig(String dataId, String app, String config) {
        if (StringUtil.isEmpty(config)) {
            logger.info("password data is empty, so use default passwd, dataId:" + dataId);
            config = app;
        }

        UserConfig user = this.users.get(app);
        if (user == null) {
            user = new UserConfig();
            this.users.put(app, user);
        }
        user.setName(app);
        user.setPassword(config);
        user.setSchemas(this.buildSchema(app));
    }

    private void parseQuarantineConfig(String dataId, String app, String config) {
        /* Must clear existing whitelist first always */
        cleanHostByApp(app);
        if (StringUtil.isEmpty(config)) {
            return;
        }

        parseQuarantine(app, dataId, config);
    }

    synchronized private void parseQuarantine(String app, String dataId, String config) {
        quarantine.resetHosts(app, config);
    }

    private void cleanHostByApp(String app) {
        quarantine.cleanHostByApp(app);
    }

    private Set<String> buildSchema(String app) {
        Set<String> result = new HashSet<String>();
        result.add(app);
        return result;
    }

    public Map<String, SchemaConfig> getSchemas() {
        return schemas;
    }

    public Map<String, UserConfig> getUsers() {
        return users;
    }

    @Override
    protected void doDestroy() throws TddlException {
        for (ConfigDataHandler cdh : cdhs.asMap().values()) {
            try {
                cdh.destroy();
            } catch (Exception e) {
                // ignore
            }
        }

        for (SchemaConfig schema : schemas.values()) {
            TDataSource dataSource = schema.getDataSource();
            try {
                if (dataSource != null) {
                    dataSource.destroy();
                }
            } catch (Exception e) {
                // ignore
            }
        }
    }

    public QuarantineConfig getQuarantine() {
        return quarantine;
    }

}


text:
'use strict';

var Reflux = require('reflux');
var store = require('store');
var actions = require('../actions/actions');
var auth = require('../mixins/auth');

module.exports = Reflux.createStore({
  user: {},
  init: function() {
    this.user = {
      auth: auth.authenticated(),
      id: store.get('osmid'),
      username: store.get('username'),
      avatar: store.get('avatar')
    };
    this.listenTo(actions.userLogin, this.login);
    this.listenTo(actions.userLogout, this.logout);
  },

  getInitialState: function() {
    return this.user;
  },

  login: function() {
    var _this = this;
    auth.authenticate(function(err) {
      if (err) return console.error(err);
      auth.xhr({
        method: 'GET',
        path: '/api/0.6/user/details'
      }, function(err, details) {
        if (err) return console.error(err);
        details = details.getElementsByTagName('user')[0];
        var id = store.set('osmid', details.getAttribute('id')),
          username = store.set('username', details.getAttribute('display_name')),
          avatar = store.set('avatar', details.getElementsByTagName('img')[0].getAttribute('href'));

        _this.user = {
          auth: auth.authenticated(),
          id: store.get('osmid'),
          username: store.get('username'),
          avatar: store.get('avatar')
        };
        _this.trigger(_this.user);
      });
    });
  },

  logout: function() {
    auth.logout();
    this.user = {};
    this.trigger(this.user);
  }
});