text:
'use strict';

app.controller('profileController', profileController);

profileController.$inject = ['$rootScope', '$stateParams', '$scope', 'userService', 'loginService', 'authProvider', 'constantFactory', '$location', 'commonService', 'masterService'];

function profileController($rootScope, $stateParams, $scope, userService, loginService, authProvider, constantFactory, $location, commonService, masterService)
{
    //write activate function
    function activate() {
        //alert("Here");

        $scope.action = $stateParams.action;

        masterService.getAllStates(onStates, errorCallback);

        getProfile();
    }

    function onStates(data) {
        $scope.states = [];
        $scope.officeStates = [];
        $.each(data.data, function (i, obj) {
            var item = new masterModel();
            item.update(obj.key, obj.value);
            $scope.states.push(item);
            $scope.officeStates.push(item);
        });
    }

    function getProfile()
    {
        console.log('entering getProfile() controller');

        userService.getProfile(profileloadSuccessCallBack, profileLoadErrorCallBack);
    }

    $scope.updateProfile = function()
    {
        //put this to the http data object;;;
        console.log($scope.profile);
        userService.updateProfile($scope.profile);
        console.log('Update Profile Executed.....');
    }

    function profileloadSuccessCallBack(d) {
        //console.log(d.data.profileTypeId);
        var profile = new profileModel();

        console.log("d.data");
        console.log(d.data);
        profile.update(d.data);

        $scope.profile = profile;

        console.log("after update");
        console.log($scope.profile);
        //showHideField();
        //getProfileImage(d.data.imageId);

        //console.log('-----' + data.Email);
    }

    function getProfileImage(imageId) {
        if (imageId != null && imageId !== "") {
            userService.getImageData(imageId, function (d) {
                $scope.base64BgImagePath = "data:image/png;base64," + d.data;
            }, profileLoadErrorCallBack);
        }
        else {
            if (d != null && d.data != null) {
                $scope.base64BgImagePath = d.data.photo != null
                    ? "data:image/png;base64," + d.data.photo
                    : $scope.defaultProfilePic;
            } else {
                $scope.base64BgImagePath = $scope.defaultProfilePic;
            }
        }
    }

    function profileLoadErrorCallBack(d) {
        $rootScope.alerts.push({
            'type': 'danger',
            'msg': "Unable to load Profile detail"
        });
        clearProfileData();
    }

    function errorCallback(d) {
        $scope.alerts.push({
            'type': 'danger',
            'msg': "Unable to process"
        });
    }

    function clearProfileData() {
        var data = new profileModel();
        //$scope.profile = data;
        data.ProfileId = 0;
        showHideField();
    }

    activate();
}


text:
require 'formula'

class BulkExtractor < Formula
  homepage 'https://github.com/simsong/bulk_extractor/wiki'
  url 'http://digitalcorpora.org/downloads/bulk_extractor/bulk_extractor-1.4.4.tar.gz'
  sha1 'e95ed6db74d9998842089b53eb4322dd0a730a82'

  depends_on :autoconf
  depends_on :automake

  depends_on 'afflib' => :optional
  depends_on 'exiv2' => :optional
  depends_on 'libewf' => :optional

  # Error in exec install hooks; installing java GUI manually. Reported in
  # https://groups.google.com/group/bulk_extractor-users/browse_thread/thread/ff7cc11e8e6d8e8d
  patch do
    url "https://gist.github.com/raw/3785687/3a61d57539c2b9ecde44121b370db85ff9d4f86e/makefile.in.patch"
    sha1 "0b597214c15505d84602a28b74fc01ce5aa0c902"
  end

  def install
    system "./configure", "--disable-dependency-tracking",
                          "--prefix=#{prefix}"
    system "make"
    system "make install"

    # Install documentation
    (share/'bulk_extractor/doc').install Dir['doc/*.{html,txt,pdf}']

    (lib/'python2.7/site-packages').install Dir['python/*.py']

    # Install the GUI the Homebrew way
    libexec.install 'java_gui/BEViewer.jar'
    bin.write_jar_script libexec/"BEViewer.jar", "BEViewer", "-Xmx1g"
  end

  test do
    input_file = testpath/"data.txt"
    input_file.write "http://brew.sh\n(201)555-1212\n"

    output_dir = testpath/"output"
    system "#{bin}/bulk_extractor", "-o", output_dir, input_file

    assert (output_dir/"url.txt").read.include?("http://brew.sh")
    assert (output_dir/"telephone.txt").read.include?("(201)555-1212")
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.elasticsearch.rest.action.get;

import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.support.RestActions;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;

import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.NOT_FOUND;
import static org.elasticsearch.rest.RestStatus.OK;

/**
 *
 */
public class RestGetAction extends BaseRestHandler {

    @Inject
    public RestGetAction(Settings settings, RestController controller) {
        super(settings);
        controller.registerHandler(GET, "/{index}/{type}/{id}", this);
    }

    @Override
    public void handleRequest(final RestRequest request, final RestChannel channel, final NodeClient client) {
        final GetRequest getRequest = new GetRequest(request.param("index"), request.param("type"), request.param("id"));
        getRequest.operationThreaded(true);
        getRequest.refresh(request.paramAsBoolean("refresh", getRequest.refresh()));
        getRequest.routing(request.param("routing"));  // order is important, set it after routing, so it will set the routing
        getRequest.parent(request.param("parent"));
        getRequest.preference(request.param("preference"));
        getRequest.realtime(request.paramAsBoolean("realtime", getRequest.realtime()));
        getRequest.ignoreErrorsOnGeneratedFields(request.paramAsBoolean("ignore_errors_on_generated_fields", false));

        String sField = request.param("fields");
        if (sField != null) {
            String[] sFields = Strings.splitStringByCommaToArray(sField);
            if (sFields != null) {
                getRequest.fields(sFields);
            }
        }

        getRequest.version(RestActions.parseVersion(request));
        getRequest.versionType(VersionType.fromString(request.param("version_type"), getRequest.versionType()));

        getRequest.fetchSourceContext(FetchSourceContext.parseFromRestRequest(request));

        client.get(getRequest, new RestBuilderListener<GetResponse>(channel) {
            @Override
            public RestResponse buildResponse(GetResponse response, XContentBuilder builder) throws Exception {
                builder.startObject();
                response.toXContent(builder, request);
                builder.endObject();
                if (!response.isExists()) {
                    return new BytesRestResponse(NOT_FOUND, builder);
                } else {
                    return new BytesRestResponse(OK, builder);
                }
            }
        });
    }
}


text:
/*!
 * \file tvm/arith/int_set.h
 * \brief Integer set
 */
#ifndef TVM_ARITH_INT_SET_H_
#define TVM_ARITH_INT_SET_H_

#include <tvm/ir/expr.h>
#include <tvm/tir/expr.h>

#include <unordered_map>

namespace tvm {
namespace arith {

using tir::IterVar;
using tir::Var;
using tir::VarNode;

//-----------------------------------------------
// Integer set data structure.
//
// This is a API build on top of the base
// integer analysis API to provide set analysis.
//------------------------------------------------
/*!
 * \brief Sign type of an integer expression.
 */
enum SignType { kPositive, kNegative, kZero, kUnknown };

/*!
 * \brief Base class of all Integer set containers.
 *        represent a set of integers in one dimension.
 * \sa IntSet
 */
class IntSetNode : public Object {
 public:
  static constexpr const char* _type_key = "IntSet";
  static constexpr bool _type_has_method_sequal_reduce = false;
  TVM_DECLARE_BASE_OBJECT_INFO(IntSetNode, Object);
};

/*!
 * \brief Managed reference to IntSetNode.
 * \sa IntSetNode
 */
class IntSet : public ObjectRef {
 public:
  /*!
   * \brief Find a range that covers the region.
   * \param max_range The range to be covered.
   * \return The covering range.
   */
  Range CoverRange(Range max_range) const;
  /*! \return Lower bound of the set */
  PrimExpr min() const;
  /*! \return upper bound of the set */
  PrimExpr max() const;
  /*! \return The sign of the elements in the integer set */
  SignType GetSignType() const;
  /*! \return Whether the set represent nothing  */
  bool IsNothing() const;
  /*! \return Whether the set represent everything  */
  bool IsEverything() const;
  /*! \return Whether the set is a single point */
  bool IsSinglePoint() const;
  /*! \return Whether the set is proved to be bigger than 0 */
  bool CanProvePositive() const;
  /*! \return Whether the set is proved to be smaller than 0 */
  bool CanProveNegative() const;
  /*! \return Whether the set is proved to be smaller than or equal to 0 */
  bool CanProveNonPositive() const;
  /*! \return Whether the set is proved to be larger than or equal to 0 */
  bool CanProveNonNegative() const;
  /*!
   * \brief The single point value, call only if IsSinglePoint is true
   * \return The point value.
   */
  PrimExpr PointValue() const;
  /*!
   * \brief Try to match IntSet with range r.
   *
   * \note It is guanrateed that IntSet::FromRange(r).MatchRange(r) == true
   * \return true if we can prove they are the same.
   */
  bool MatchRange(const tvm::Range& r) const;
  /*! \return The set contains nothing */
  static IntSet Nothing();
  /*! \return The set contains everything */
  static IntSet Everything();
  /*!
   * \brief construct a point set.
   * \param point The point in the set.
   * \return construct a single point set
   */
  static IntSet SinglePoint(PrimExpr point);
  /*!
   * \brief construct a integer set from vector expression.
   * \param vec The vector expression, can also be single point.
   * \return The result set containing the indices in the vector.
   */
  static IntSet Vector(PrimExpr vec);
  /*!
   * \brief Construct a set representing a range.
   * \param r The range
   * \return constructed set.
   */
  static IntSet FromRange(tvm::Range r);
  /*!
   * \brief Construct a set representing a interval.
   * \param min The minimum value of the interval.
   * \param max The maximum value of the interval.
   * \return constructed set.
   */
  static IntSet Interval(PrimExpr min, PrimExpr max);

  TVM_DEFINE_OBJECT_REF_METHODS(IntSet, ObjectRef, IntSetNode);
};

//-----------------------------------------------
// Integer set legacy API.
//------------------------------------------------
/*!
 * \brief Convert std::unordered_map<const VarNode*, IntSet> to Map<Var, IntSet>
 *
 * \param dom_map The domain map to convert.
 * \return The converted map.
 */
Map<Var, IntSet> ConvertDomMap(const std::unordered_map<const VarNode*, IntSet>& dom_map);
/*!
 * \brief Find an symbolic integer set that contains all possible values of
 *  e given the domain of each iteration variables.
 *
 * \param e The expression to be evaluated.
 * \param dom_map The domain of each variable.
 * \return An integer set that can cover all the possible values of e.
 */
IntSet EvalSet(PrimExpr e, const Map<IterVar, IntSet>& dom_map);
/*!
 * \brief Same as EvalSet, but takes unordered_map
 *
 * \param e The expression to be evaluated.
 * \param dom_map The domain of each variable.
 * \return An integer set that can cover all the possible values of e.
 */
IntSet EvalSet(PrimExpr e, const std::unordered_map<const tir::VarNode*, IntSet>& dom_map);
/*!
 * \brief Find an symbolic integer set that contains is union over
 *  all the possible conditional values in dom_map.
 *
 * \param r The initial range.
 * \param dom_map The domain of each variable.
 * \return An integer set that can cover all the possible values.
 */
IntSet EvalSet(Range r, const Map<IterVar, IntSet>& dom_map);

/*!
 * \brief Find an symbolic integer set that contains is union over
 *  all the possible conditional values in dom_map.
 *
 * \param s The initial set.
 * \param dom_map The domain of each variable.
 * \return An integer set that can cover all the possible values.
 */
IntSet EvalSet(IntSet s, const std::unordered_map<const VarNode*, IntSet>& dom_map);
/*!
 * \brief Same as EvalSet, but takes unordered_map
 *
 * \param r The range to be evaluated.
 * \param dom_map The domain of each variable.
 * \return An integer set that can cover all the possible values of e.
 */
IntSet EvalSet(Range r, const std::unordered_map<const VarNode*, IntSet>& dom_map);
/*! \brief Map from Expr to IntSet */
using ExprIntSetMap = std::unordered_map<PrimExpr, IntSet, ObjectPtrHash, ObjectPtrEqual>;
/*!
 * \brief Find the integer set of every sub-expression, given the
 *  domain of each iteration variables.
 *
 * \param e The expression to be evaluated.
 * \param dom_map The domain of each variable.
 * \return the map from the expression to its possible value.
 */
ExprIntSetMap EvalSetForEachSubExpr(PrimExpr e,
                                    const std::unordered_map<const VarNode*, IntSet>& dom_map);

/*!
 * \brief Create an union set of all sets
 * \param sets The sets to be unioned
 * \return the set after union
 */
IntSet Union(const Array<IntSet>& sets);

/*!
 * \brief Create an union set of all sets
 * \param sets The sets to be intersected
 * \return the set after intersected
 */
IntSet Intersect(const Array<IntSet>& sets);

}  // namespace arith
}  // namespace tvm
#endif  // TVM_ARITH_INT_SET_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true">

        <shape>
            <corners android:radius="50dp" />
            <gradient android:angle="45" android:centerX="35%" android:endColor="#7b84ec" android:startColor="#49c5d7" android:type="linear" />
            <padding android:bottom="0dp" android:left="0dp" android:right="0dp" android:top="0dp" />
            <size android:width="270dp" android:height="60dp" />
            <stroke android:width="5dp" android:color="#eaecfb" />
        </shape>

    </item>

    <item>

        <shape>
            <corners android:radius="50dp" />
            <gradient android:angle="45" android:centerX="35%" android:endColor="#49c5d7" android:startColor="#7b84ec" android:type="linear" />
            <padding android:bottom="0dp" android:left="0dp" android:right="0dp" android:top="0dp" />
            <size android:width="270dp" android:height="60dp" />
            <stroke android:width="5dp" android:color="#eaecfb" />
        </shape>

    </item>

</selector>


text:
import '@testing-library/jest-dom';

if (global.Range) {
  global.Range.prototype.getClientRects = jest.fn().mockReturnValue({ length: 0 });
  global.Range.prototype.getBoundingClientRect = jest.fn().mockReturnValue({});
}


text:
package com.google.api.ads.dfp.jaxws.v201502;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for ActivityError.Reason.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="ActivityError.Reason">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="ACTIVITIES_FEATURE_REQUIRED"/>
 *     <enumeration value="UNKNOWN"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "ActivityError.Reason")
@XmlEnum
public enum ActivityErrorReason {

    /**
     *
     *                 The 'activities' feature is required but not enabled.
     *
     *
     */
    ACTIVITIES_FEATURE_REQUIRED,

    /**
     *
     *                 The value returned if the actual value is not exposed by the requested API version.
     *
     *
     */
    UNKNOWN;

    public String value() {
        return name();
    }

    public static ActivityErrorReason fromValue(String v) {
        return valueOf(v);
    }

}


text:
class Main_Application : public QQmlApplicationEngine {
    Q_OBJECT
    public:
        Main_Application();
        // this method is used to setup all the ros functionality we need
        // before the application starts runnings
        void run();

    // this defines a slot that will be called when the application is idle
    public slots:
        void main_loop();
        void handle(QString str);

    private:
        ros::NodeHandle nh;
};

#endif // MAIN_APPLICATION_H


text:
package org.apache.jmeter.samplers;

import org.apache.jmeter.util.JMeterUtils;

/**
 * Base class for SampleSender implementations
 */
public abstract class AbstractSampleSender implements SampleSender {

    // Note: this is an instance field (and is not transient), so is created by the JMeter client
    // and propagated to the server instance by RMI.
    // [a static field would be recreated on the server, and would pick up the server properties]
    private final boolean isClientConfigured = JMeterUtils.getPropDefault("sample_sender_client_configured", true); // $NON-NLS-1$

    /**
     * @return boolean indicates how SampleSender configuration is done, {@code true}
     *         means use client properties and send to servers, {@code false} means use
     *         server configurations
     */
    public boolean isClientConfigured() {
        return isClientConfigured;
    }

    /**
     *
     */
    protected AbstractSampleSender() {
        super();
    }

    @Override
    public void testEnded() {
        // Not used
    }

}


text:
package com.bylak.android.normalize;

/**
 * Created with IntelliJ IDEA.
 * User: Artur.Bylak
 * Date: 18.02.14
 * Time: 12:32
 * To change this template use File | Settings | File Templates.
 */
public interface DataSizeChanger {
    double[] changeSize(double[] dataToProcess, int expectedOutputCount);
}


text:
/*
 * Aakash Apoorv
 */
using System;
using System.Threading;
using Sce.PlayStation.Core;
using Sce.PlayStation.Core.Graphics;
using Sce.PlayStation.Core.Environment;
using Sce.PlayStation.Core.Input;
using Sce.PlayStation.Core.Audio;
using Sce.PlayStation.HighLevel.GameEngine2D;
using Sce.PlayStation.HighLevel.GameEngine2D.Base;
using LuaInterface;

namespace Sample
{

/**
 * LuaSample
 */
public class LuaSample
{
    static GraphicsContext graphics;
    static bool loop = true;

    static Lua lua;
	static GamePadData gamePadData;

	static string titleString;
	static int TitleStringX;

	static string buttonName;

    public static void Main(string[] args)
    {
        Init();
        while (loop) {
            SystemEvents.CheckEvents();
            Update();
            Render();
        }
        Term();
    }

    public static void Init()
    {
        graphics = new GraphicsContext();
        SampleDraw.Init(graphics);

        // Set up LuaInterface
        lua = new Lua();

        // Register C# function
        lua.RegisterFunction("FillCircle", null, typeof(LuaSample).GetMethod("FillCircle"));
		lua.RegisterFunction("MoveText", null, typeof(LuaSample).GetMethod("MoveText"));
		lua.RegisterFunction("btnText", null, typeof(LuaSample).GetMethod("btnText"));
        // Read Lua file
        lua.DoFile("/Application/touch.lua");

		titleString = Convert.ToString(lua["TitleString"]);
		TitleStringX = Convert.ToInt32(lua["TitleStringX"]);

<<<<<<< HEAD
			buttonName= "nil";

=======
		buttonName= "nil";
>>>>>>> 27ba49d2a274c352ed94cfdb8a630b52f57fad44

    }

    public static void Term()
    {
        // Close LuaInterface
        lua.Dispose();

        SampleDraw.Term();
        graphics.Dispose();
    }
		PSLua.mainController mc = new PSLua.mainController();

    public static void Update()

    {
<<<<<<< HEAD
			PSLua.mainController mc = new PSLua.mainController();
			string mys = mc.GameKey();
			bool myb = mc.GameKeyBool();

			if(myb)
			{
				//Console.WriteLine(mys);
            }

			bool isBtnDown = myb;
			var btnLua = mys;
			lua.GetFunction("OnPress").Call(btnLua, isBtnDown);
=======
		gamePadData = GamePad.GetData(0);
		if((gamePadData.Buttons & GamePadButtons.Left) != 0)
		{
			Console.WriteLine(gamePadData.Buttons);

            	}

		if((gamePadData.Buttons) != 0)
		{
			Console.WriteLine(gamePadData.Buttons);

            	}

		bool isBtnDown = true;
		if ((gamePadData.Buttons) != 0)
		{
			isBtnDown = true;
		}
		else
		{
			isBtnDown = false;
		}
		var btnLua = Convert.ToString(gamePadData.Buttons);
		lua.GetFunction("OnPress").Call(btnLua, isBtnDown);
>>>>>>> 27ba49d2a274c352ed94cfdb8a630b52f57fad44

        	SampleDraw.Update();

    }

    public static void Render()
    {
        graphics.SetClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        graphics.Clear();

        foreach (var touchData in Touch.GetData(0)) {
            if (touchData.Status == TouchStatus.Down ||
                touchData.Status == TouchStatus.Move) {

                // Call Lua function
                int pointX = (int)((touchData.X + 0.5f) * SampleDraw.Width);
                int pointY = (int)((touchData.Y + 0.5f) * SampleDraw.Height);
                bool isDown = touchData.Status == TouchStatus.Down;
                lua.GetFunction("OnTouch").Call(pointX, pointY, isDown);

            }
        }

        // Get Lua variables

        var colorIndex = Convert.ToInt32(lua["ColorIndex"]);
        var message = string.Format("Color {0}", colorIndex);

        SampleDraw.DrawText(message, 0xffffffff, 0, graphics.Screen.Height - 24);

				SampleDraw.DrawText(buttonName, 0xffffffff, 0, 0);

        graphics.SwapBuffers();
    }

    public static void FillCircle(uint argb, int pointX, int pointY, int radius)
    {
        SampleDraw.FillCircle(argb, pointX, pointY, radius);

    }

	public static void MoveText (int arg)
		{
			//buttonName = Convert.ToString(gamePadData.Buttons);
		}
	public static void btnText(string arg)
		{
			buttonName = arg;
		}

	public static void btnCircle ()
		{
			SampleDraw.DrawText("Circle Pressed", 0xffffffff, 200, 200);
		}
}

} // Sample


text:
"""
Temporary(?) resting place for the WordNet based stemmer.
"""

from nltk.stemmer import StemmerI
from nltk.token import Token
from nltk_contrib.pywordnet import *
from nltk_contrib.pywordnet.tools import morphy

##//////////////////////////////////////////////////////
##  WordNet Stemmer
##//////////////////////////////////////////////////////

class WordNetStemmer(StemmerI):
    """
    A class for stemming strings using the pywordnet package. The C{morphy}
    function is used which reduces the given word form into a word which
    exists in the WordNet database, if possible. Note that morphological
    affixes often remain after stemming, as WordNet contains quite a number of
    entries for inflectional forms. This stemmer is not as powerful as the one
    contained in the C{wnb} binary distributed with WordNet 1.7 - there are
    plans to improve this in the near future.
    """

    def stem(self, token):
        # inherit docs from StemmerI
        # TODO - when the new token comes out, use it to get the
        # part-of-speech, thus narrowing the search (and getting eg.
        # fly/verb for the query flies, rather than the plural noun).
        # This will only match the first POS from the list below...
        for pos in [NOUN, VERB, ADJECTIVE, ADVERB]:
            stemmed = morphy(token.type().lower(), pos)
            if stemmed:
                # restore the case
                new_string = ''
                for index in range(min(len(token.type()), len(stemmed))):
                    if token.type()[index].isupper():
                        new_string += stemmed[index].upper()
                    else:
                        new_string += stemmed[index]
                return Token(new_string, token.loc())

        return token


text:
Spegi's Open source Game Engine

A wrapper for easier game development with C++.

Libraries used:
- Ogre3D for 3D acceleration and rendering
- Bullet with btogre for physics
- SDL2 Mixer for audio
- ENet for UDP networking (does not work, will be fixed by 0.3)
- OIS for user input (keyboard, mouse, joystick)

## Downloads
The latest release version is 0.2.1-alpha. It's recommended to use that.

You can download the source code and vs14 and MinGW x86 debug binaries from Releases.

## Installation

Please note, that the libraries used are not included, compiled or linked with the engine (yet). You need to link them to your application yourself.

Libraries required for linkage:
- SOGE.lib (Obviously)
- OgreMain_d.lib
- SDL2.lib
- SDL2main.lib
- SDL2_mixer.lib
- OIS_d.lib
- enet.lib
- Ws2_32.lib
- Winmm.lib
- BtOgre.lib

## Documentation
API documentation is included with the download in the folder doc/.

## Changes
See [Changelog](CHANGELOG.md)

## Authors and contributors
See [Contributors](CONTRIBUTORS.md)

## License
SOGE is licensed under the Apache License (version 2.0).
For more information, see LICENSE or visit <http://www.apache.org/licenses/LICENSE-2.0>.


text:
package msglnk.rest

import javax.ws.rs._
import javax.ws.rs.core.Context
import javax.servlet.http.HttpServletRequest
import java.security.Principal
import msglnk.dto.SessionDataDto

@Path("/keep-alive")
class KeepAlive {

    @GET
    def ping(@Context request: HttpServletRequest): SessionDataDto = {
        val session = request.getSession
        val dto = new SessionDataDto()
        dto.setSessionId(session.getId)
        request.getUserPrincipal match {
            case principal: Principal => {
                dto.setUserName(principal.getName)
                dto.setLogged(true)
            }
            case null => {
                dto.setUserName("guest")
                dto.setLogged(false)
            }
        }
        dto
    }

}


text:
package org.checkerframework.afu.scenelib.tools;

import static java.nio.charset.StandardCharsets.UTF_8;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.checkerframework.afu.scenelib.el.AScene;
import org.checkerframework.afu.scenelib.el.DefException;
import org.checkerframework.afu.scenelib.io.IndexFileParser;
import org.checkerframework.afu.scenelib.io.IndexFileWriter;
import org.checkerframework.afu.scenelib.io.JavapParser;
import org.checkerframework.afu.scenelib.io.classfile.ClassFileReader;
import org.checkerframework.afu.scenelib.io.classfile.ClassFileWriter;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.plumelib.util.FileIOException;

/** Concatenates multiple descriptions of annotations into a single one. */
public class Anncat {
  private static void usage() {
    System.err.print(
        "anncat, part of the Annotation File Utilities\n"
            + "(https://checkerframework.org/annotation-file-utilities/)\n"
            + "usage: anncat <inspec>* [ --out <outspec> ], where:\n"
            + "    <inspec> ::=\n"
            + "        ( --javap <in.javap> )\n"
            + "        | ( --index <in.jaif> )\n"
            + "        | ( --class <in.class> )\n"
            + "    <outspec> ::=\n"
            + "        ( --index <out.jaif> )\n"
            + "        | ( --class [ --overwrite ] <orig.class> [ --to <out.class> ] )\n"
            + "If outspec is omitted, default is index file to stdout.\n");
  }

  private static void usageAssert(boolean b) {
    if (!b) {
      System.err.println("*** Usage error ***");
      usage();
      System.exit(3);
    }
  }

  public static void main(String[] args) {
    usageAssert(0 < args.length);
    if (args[0].equals("--help")) {
      usage();
      System.exit(0);
    }

    try {

      int idx = 0;

      @NonNull AScene theScene = new AScene();

      // Read the scene
      while (idx < args.length && !args[idx].equals("--out")) {
        if (args[idx].equals("--javap")) {
          idx++;
          usageAssert(idx < args.length);
          String infile = args[idx++];
          System.out.println("Reading javap file " + infile + "...");
          JavapParser.parse(infile, theScene);
          System.out.println("Finished.");
        } else if (args[idx].equals("--index")) {
          idx++;
          usageAssert(idx < args.length);
          String infile = args[idx++];
          System.err.println("Reading index file " + infile + "...");
          IndexFileParser.parseFile(infile, theScene);
          System.err.println("Finished.");
        } else if (args[idx].equals("--class")) {
          idx++;
          usageAssert(idx < args.length);
          String infile = args[idx++];
          System.err.println("Reading class file " + infile + "...");
          ClassFileReader.read(theScene, infile);
          System.err.println("Finished.");
        } else {
          usageAssert(false);
        }
      }

      // Write the scene
      if (idx == args.length) {
        System.err.println("Writing index file to standard output...");
        IndexFileWriter.write(theScene, new OutputStreamWriter(System.out, UTF_8));
        System.err.println("Finished.");
      } else {
        idx++;
        usageAssert(idx < args.length);
        if (args[idx].equals("--index")) {
          idx++;
          usageAssert(idx < args.length);
          String outfile = args[idx];
          idx++;
          usageAssert(idx == args.length);
          System.err.println("Writing index file to " + outfile + "...");
          // In Java 11, use: new FileWriter(outfile, UTF_8)
          IndexFileWriter.write(theScene, Files.newBufferedWriter(Paths.get(outfile), UTF_8));
          System.err.println("Finished.");
        } else if (args[idx].equals("--class")) {
          idx++;
          usageAssert(idx < args.length);
          boolean overwrite;
          if (args[idx].equals("--overwrite")) {
            System.err.println("Overwrite mode enabled.");
            overwrite = true;
            idx++;
            usageAssert(idx < args.length);
          } else {
            overwrite = false;
          }
          String origfile = args[idx];
          idx++;
          if (idx < args.length) {
            usageAssert(args[idx].equals("--to"));
            idx++;
            usageAssert(idx < args.length);
            String outfile = args[idx];
            idx++;
            usageAssert(idx == args.length);
            System.err.println("Reading original class file " + origfile);
            System.err.println("and writing annotated version to " + outfile + "...");
            ClassFileWriter.insert(
                theScene, new FileInputStream(origfile), new FileOutputStream(outfile), overwrite);
            System.err.println("Finished.");
          } else {
            System.err.println("Rewriting class file " + origfile + " with annotations...");
            ClassFileWriter.insert(theScene, null, origfile, overwrite);
            System.err.println("Finished.");
          }
        } else {
          usageAssert(false);
        }
      }

    } catch (FileIOException e) {
      e.printStackTrace(System.err);
      System.exit(1);
    } catch (IOException e) {
      e.printStackTrace(System.err);
      System.exit(2);
    } catch (DefException e) {
      e.printStackTrace(System.err);
      System.exit(1);
    }
    System.exit(0);
  }
}


text:
package net.savantly.sprout.domain.permissions;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.transaction.Transactional;

import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.zalando.problem.Problem;
import org.zalando.problem.Status;

import net.savantly.sprout.core.domain.privilege.PrivilegeEntity;
import net.savantly.sprout.core.domain.privilege.PrivilegeRepository;
import net.savantly.sprout.core.domain.role.RoleEntity;
import net.savantly.sprout.core.domain.role.RoleRepository;
import net.savantly.sprout.core.tenancy.TenantContext;

@RequestMapping("/api/permissions")
@RestController
@Transactional
public class PermissionsApi {

	private final RoleRepository roleRepo;
	private final PrivilegeRepository privilegeRepo;

	public PermissionsApi(RoleRepository roleRepo, PrivilegeRepository privilegeRepo) {
		this.roleRepo = roleRepo;
		this.privilegeRepo = privilegeRepo;
	}

	@GetMapping("/role")
	public ResponseEntity<List<RoleEntity>> getRoles() {
		return ResponseEntity.ok(roleRepo.findAll());
	}

	@PutMapping("/role")
	@PreAuthorize("hasAuthority('ADMIN')")
	public ResponseEntity<RoleEntity> updateRole(@RequestBody PermissionUpdateDto dto) {
		RoleEntity role = roleOrThrow(dto.getRole());
		Set<PrivilegeEntity> privileges = dto.getPrivileges().stream().map(s -> privilegeOrThrow(s)).collect(Collectors.toSet());
		role.setPrivileges(privileges);
		return ResponseEntity.ok(roleRepo.save(role));
	}

	@GetMapping("/privilege")
	public ResponseEntity<Iterable<PrivilegeEntity>> getPrivileges() {
		return ResponseEntity.ok(privilegeRepo.findAll());
	}

	@PostMapping("/role/{name}")
	@PreAuthorize("hasAuthority('ADMIN')")
	public ResponseEntity<RoleEntity> createRole(@PathVariable("name") String name) {
		return ResponseEntity.ok(roleRepo.save(new RoleEntity().setName(name)));
	}

	@DeleteMapping("/role/{name}")
	@PreAuthorize("hasAuthority('ADMIN')")
	public ResponseEntity<Void> deleteRole(@PathVariable("name") String name) {
		RoleEntity role = roleOrThrow(name);
		roleRepo.delete(role);
		return ResponseEntity.ok().build();
	}

	@PostMapping("/role/{name}/{privilege}")
	@PreAuthorize("hasAuthority('ADMIN')")
	public ResponseEntity<RoleEntity> addPrivilegeToRole(@PathVariable("name") String name,
			@PathVariable("privilege") String privilege) {
		RoleEntity role = roleOrThrow(name);
		PrivilegeEntity privilegeEntity = privilegeOrThrow(privilege);
		role.getPrivileges().add(privilegeEntity);
		return ResponseEntity.ok(role);
	}

	@DeleteMapping("/role/{name}/{privilege}")
	@PreAuthorize("hasAuthority('ADMIN')")
	public ResponseEntity<RoleEntity> removePrivilegeFromRole(@PathVariable("name") String name,
			@PathVariable("privilege") String privilege) {
		RoleEntity role = roleOrThrow(name);
		PrivilegeEntity privilegeEntity = privilegeOrThrow(privilege);
		role.getPrivileges().remove(privilegeEntity);
		return ResponseEntity.ok(role);
	}

	private RoleEntity roleOrThrow(String name) {
		return roleRepo.findByName(name).stream().findFirst().orElseThrow(
				() -> Problem.builder().withDetail("role not found").withStatus(Status.BAD_REQUEST).build());
	}

	private PrivilegeEntity privilegeOrThrow(String name) {
		return privilegeRepo.findByNameAndTenantId(name, TenantContext.getCurrentTenant()).stream().findFirst().orElseThrow(
				() -> Problem.builder().withDetail("privilege not found").withStatus(Status.BAD_REQUEST).build());
	}

}


text:
package org.knowm.xchange.service.trade.params.orders;

import java.util.Collection;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.instrument.Instrument;

public interface OpenOrdersParamMultiInstrument extends OpenOrdersParams {
  @Override
  default boolean accept(LimitOrder order) {
    return order != null
        && getInstruments() != null
        && getInstruments().contains(order.getCurrencyPair());
  }

  Collection<Instrument> getInstruments();

  void setInstruments(Collection<Instrument> instruments);
}


text:
package org.sakaiproject.authz.tool;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Collection;
import java.util.List;
import java.util.Vector;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;

import org.sakaiproject.authz.api.AuthzGroup;
import org.sakaiproject.authz.api.AuthzGroupService;
import org.sakaiproject.authz.api.AuthzPermissionException;
import org.sakaiproject.authz.api.AuthzRealmLockException;
import org.sakaiproject.authz.api.FunctionManager;
import org.sakaiproject.authz.api.GroupAlreadyDefinedException;
import org.sakaiproject.authz.api.GroupIdInvalidException;
import org.sakaiproject.authz.api.GroupNotDefinedException;
import org.sakaiproject.authz.api.GroupProvider;
import org.sakaiproject.authz.api.Member;
import org.sakaiproject.authz.api.Role;
import org.sakaiproject.authz.api.RoleAlreadyDefinedException;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.PagedResourceActionII;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.cheftool.api.Menu;
import org.sakaiproject.cheftool.api.MenuItem;
import org.sakaiproject.cheftool.menu.MenuEntry;
import org.sakaiproject.cheftool.menu.MenuImpl;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.javax.PagingPosition;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserNotDefinedException;
import org.sakaiproject.user.api.UserDirectoryService;
import org.sakaiproject.userauditservice.api.UserAuditRegistration;
import org.sakaiproject.userauditservice.api.UserAuditService;
import org.sakaiproject.util.ResourceLoader;

/**
 * <p>
 * RealmsAction is the Sakai Admin realms editor.
 * </p>
 */
@Slf4j
public class RealmsAction extends PagedResourceActionII
{

	private static final long serialVersionUID = 1L;

	/** Resource bundle using current language locale */
	private static ResourceLoader rb = new ResourceLoader("authz-tool");

	private AuthzGroupService authzGroupService;
	private FunctionManager functionManager;
	private GroupProvider groupProvider;
	private SecurityService securityService;
	private SessionManager sessionManager;
	private ToolManager toolManager;
	private UserDirectoryService userDirectoryService;
	private UserAuditRegistration userAuditRegistration;
	private UserAuditService userAuditService;

	public RealmsAction()
	{
		authzGroupService = ComponentManager.get(AuthzGroupService.class);
		functionManager = ComponentManager.get(FunctionManager.class);
		groupProvider = ComponentManager.get(GroupProvider.class);
		securityService = ComponentManager.get(SecurityService.class);
		sessionManager = ComponentManager.get(SessionManager.class);
		toolManager = ComponentManager.get(ToolManager.class);
		userDirectoryService = ComponentManager.get(UserDirectoryService.class);
		userAuditRegistration = ComponentManager.get(UserAuditRegistration.class);
		userAuditService = ComponentManager.get(UserAuditService.class);
	}

	/**
	 * {@inheritDoc}
	 */
	protected List readResourcesPage(SessionState state, int first, int last)
	{
		// search?
		String search = StringUtils.trimToNull((String) state.getAttribute(STATE_SEARCH));

		return authzGroupService.getAuthzGroups(search, new PagingPosition(first, last));
	}

	/**
	 * {@inheritDoc}
	 */
	protected int sizeResources(SessionState state)
	{
		// search?
		String search = StringUtils.trimToNull((String) state.getAttribute(STATE_SEARCH));

		return authzGroupService.countAuthzGroups(search);
	}

	/**
	 * Populate the state object, if needed.
	 */
	protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData rundata)
	{
		super.initState(state, portlet, rundata);

		// // setup the observer to notify our main panel
		// if (state.getAttribute(STATE_OBSERVER) == null)
		// {
		// // the delivery location for this tool
		// String deliveryId = clientWindowId(state, portlet.getID());
		//
		// // the html element to update on delivery
		// String elementId = mainPanelUpdateId(portlet.getID());
		//
		// // the event resource reference pattern to watch for
		// String pattern = authzGroupService.realmReference("");
		//
		// state.setAttribute(STATE_OBSERVER, new EventObservingCourier(deliveryId, elementId, pattern));
		// }

	} // initState

	/**
	 * build the context
	 */
	public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
	{
		context.put("tlang", rb);

		// if not allowed, we won't do anything
		if (!isAccessAllowed())
		{
			return (String) getContext(rundata).get("template") + "_noaccess";
		}

		String template = null;

		// check mode and dispatch
		String mode = (String) state.getAttribute("mode");
		if (mode == null)
		{
			template = buildListContext(state, context);
		}
		else if ("new".equals(mode))
		{
			template = buildNewContext(state, context);
		}
		else if ("edit".equals(mode))
		{
			template = buildEditContext(state, context);
		}
		else if ("confirm".equals(mode))
		{
			template = buildConfirmRemoveContext(state, context);
		}
		else if ("saveas".equals(mode))
		{
			template = buildSaveasContext(state, context);
		}

		else if ("newRole".equals(mode))
		{
			template = buildNewRoleContext(state, context);
		}
		else if ("editRole".equals(mode))
		{
			template = buildEditRoleContext(state, context);
		}
		else if ("saveasRole".equals(mode))
		{
			template = buildSaveasRoleContext(state, context);
		}

		else if ("newUser".equals(mode))
		{
			template = buildNewUserContext(state, context);
		}
		else if ("editUser".equals(mode))
		{
			template = buildEditUserContext(state, context);
		}
		else if ("view".equals(mode))
		{
			template = buildViewContext(state, context);
		}
		else if ("viewRole".equals(mode))
		{
			template = buildViewRoleContext(state, context);
		}

		else
		{
		 	log.warn("mode: {}", mode);
			template = buildListContext(state, context);
		}

		String prefix = (String) getContext(rundata).get("template");
		return prefix + template;

	} // buildMainPanelContext

	/**
	 * Build the context for the main list mode.
	 */
	private String buildListContext(SessionState state, Context context)
	{
		// prepare the paging of realms
		List realms = prepPage(state);

		// put the service in the context (used for allow update calls on each realm)
		context.put("service", authzGroupService);

		// put all realms into the context
		context.put("realms", realms);

		pagingInfoToContext(state, context);

		// build the menu
		Menu bar = new MenuImpl();
		if (authzGroupService.allowAdd(""))
		{
			bar.add(new MenuEntry(rb.getString("realm.new"), "doNew"));
		}

		// add the paging commands
		//addListPagingMenus(bar, state);

		// add the search commands
		addSearchMenus(bar, state, rb.getString("realm.list.search.acc"));

		// add the refresh commands
		addRefreshMenus(bar, state);

		if (bar.size() > 0)
		{
			context.put(Menu.CONTEXT_MENU, bar);
		}

		context.put("viewAllowed", isAccessAllowed());

		// inform the observing courier that we just updated the page...
		// if there are pending requests to do so they can be cleared
		justDelivered(state);

		return "_list";

	} // buildListContext

	/**
	 * Build the context for the new realm mode.
	 */
	private String buildNewContext(SessionState state, Context context)
	{
		// name the html form for user edit fields
		context.put("form-name", "realm-form");

		return "_edit";

	} // buildNewContext

	/**
	 * Build the context for the edit realm mode.
	 */
	private String buildEditContext(SessionState state, Context context)
	{
		// get the realm to edit
		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");
		context.put("realm", realm);

		// get the roles defined in the realm
		List roles = new Vector();
		roles.addAll(realm.getRoles());
		Collections.sort(roles);
		context.put("roles", roles);

		// get a list of the users who have individual grants in the realm
		List grants = new Vector();
		grants.addAll(realm.getMembers());
		Collections.sort(grants);
		context.put("grants", grants);

		// name the html form for user edit fields
		context.put("form-name", "realm-form");

		// build the menu
		// we need the form fields for the remove...
		Menu bar = new MenuImpl();
		if (realm != null && authzGroupService.allowRemove(realm.getId()))
		{
			bar.add(new MenuEntry(rb.getString("realm.remove"), null, true, MenuItem.CHECKED_NA, "doRemove", "realm-form"));
		}

		bar.add(new MenuEntry(rb.getString("realm.add"), null, true, MenuItem.CHECKED_NA, "doNew_role", "realm-form"));
		bar.add(new MenuEntry(rb.getString("realm.grant"), null, true, MenuItem.CHECKED_NA, "doNew_user", "realm-form"));

		bar.add(new MenuEntry(rb.getString("realm.save"), null, true, MenuItem.CHECKED_NA, "doSaveas_request", "realm-form"));

		context.put(Menu.CONTEXT_MENU, bar);

		return "_edit";

	} // buildEditContext

	/**
	 * Build the context for the view realm mode.
	 */
	private String buildViewContext(SessionState state, Context context)
	{
		// get the realm to edit
		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");
		context.put("realm", realm);

		// get the roles defined in the realm
		List roles = new Vector();
		roles.addAll(realm.getRoles());
		Collections.sort(roles);
		context.put("roles", roles);

		// get a list of the users who have individual grants in the realm
		List grants = new Vector();
		grants.addAll(realm.getMembers());
		Collections.sort(grants);
		context.put("grants", grants);

		return "_view";

	} // buildEditContext

	/**
	 * Build the context for the new realm mode.
	 */
	private String buildConfirmRemoveContext(SessionState state, Context context)
	{
		// get the realm to edit
		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");
		context.put("realm", realm);

		return "_confirm_remove";

	} // buildConfirmRemoveContext

	/**
	 * Build the context for the role save as
	 */
	private String buildSaveasRoleContext(SessionState state, Context context)
	{
		// get the realm to edit
		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");
		context.put("realm", realm);

		// get the role
		Role role = (Role) state.getAttribute("role");
		context.put("role", role);

		return "_saveas_role";

	} // buildSaveasRoleContext

	/**
	 * Build the context for the new role mode.
	 */
	private String buildNewRoleContext(SessionState state, Context context)
	{
		// name the html form for user edit fields
		context.put("form-name", "role-form");

		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");
		context.put("realm", realm);

		// get all functions
		List allFunctions = functionManager.getRegisteredFunctions();
		Collections.sort(allFunctions);
		context.put("allLocks", allFunctions);

		// get all roles
		List allRoles = new Vector();
		if (realm != null)
			allRoles.addAll(realm.getRoles());
		Collections.sort(allRoles);
		context.put("allRoles", allRoles);

		return "_edit_role";

	} // buildNewRoleContext

	/**
	 * Build the context for the edit role mode.
	 */
	private String buildEditRoleContext(SessionState state, Context context)
	{
		// name the html form for user edit fields
		context.put("form-name", "role-form");

		// get the realm
		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");
		context.put("realm", realm);

		// get the role
		Role role = (Role) state.getAttribute("role");
		context.put("role", role);

		// get all functions
		List allFunctions = functionManager.getRegisteredFunctions();
		Collections.sort(allFunctions);
		context.put("allLocks", allFunctions);

		// get all roles
		List allRoles = new Vector();
		if (realm != null)
			allRoles.addAll(realm.getRoles());
		Collections.sort(allRoles);
		context.put("allRoles", allRoles);

		// build the menu
		Menu bar = new MenuImpl();
		bar.add(new MenuEntry(rb.getString("realm.removerol"), null, true, MenuItem.CHECKED_NA, "doRemove_role"));
		bar.add(new MenuEntry(rb.getString("realm.copyrol"), null, true, MenuItem.CHECKED_NA, "doSaveas_role"));
		context.put(Menu.CONTEXT_MENU, bar);

		return "_edit_role";

	} // buildEditRoleContext

	/**
	 * Build the context for the view role mode.
	 */
	private String buildViewRoleContext(SessionState state, Context context)
	{

		// get the realm
		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");
		context.put("realm", realm);

		// get the role
		Role role = (Role) state.getAttribute("role");
		context.put("role", role);

		// get all functions
		List allFunctions = functionManager.getRegisteredFunctions();
		Collections.sort(allFunctions);
		context.put("allLocks", allFunctions);

		// get all roles
		List allRoles = new Vector();
		if (realm != null)
			allRoles.addAll(realm.getRoles());
		Collections.sort(allRoles);
		context.put("allRoles", allRoles);

		return "_view_role";

	} // buildViewRoleContext

	/**
	 * Build the context for the new user grant mode.
	 */
	private String buildNewUserContext(SessionState state, Context context)
	{
		// name the html form for user edit fields
		context.put("form-name", "user-form");

		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");

		context.put("realm", realm);

		// get all roles
		List allRoles = new Vector();
		if (realm != null)
			allRoles.addAll(realm.getRoles());
		Collections.sort(allRoles);
		context.put("allRoles", allRoles);

		return "_edit_user";

	} // buildNewUserContext

	/**
	 * Build the context for the edit user grant mode.
	 */
	private String buildEditUserContext(SessionState state, Context context)
	{
		// name the html form for user edit fields
		context.put("form-name", "user-form");

		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");
		User user = (User) state.getAttribute("user");

		context.put("realm", realm);
		context.put("user", user);

		// get this user's role - only if not provided
		if (realm != null)
		{
			Member grant = realm.getMember(user.getId());
			context.put("grant", grant);
			if ((grant != null) && (!grant.isProvided()) && (grant.getRole() != null))
			{
				context.put("roles", grant.getRole());
			}
		}

		// get all roles
		List allRoles = new Vector();
		if (realm != null)
			allRoles.addAll(realm.getRoles());
		Collections.sort(allRoles);
		context.put("allRoles", allRoles);

		// build the menu
		Menu bar = new MenuImpl();
		bar.add(new MenuEntry(rb.getString("realm.removeall"), null, true, MenuItem.CHECKED_NA, "doRemove_user"));
		context.put(Menu.CONTEXT_MENU, bar);

		return "_edit_user";

	} // buildEditUserContext

	/**
	 * Build the context for the save-as mode.
	 */
	private String buildSaveasContext(SessionState state, Context context)
	{
		// get the realm being edited
		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");
		context.put("realm", realm);

		return "_saveas";

	} // buildSaveasContext

	/**
	 * Handle a request to save-as the realm as a new realm.
	 */
	public void doSaveas(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		if (!"POST".equals(data.getRequest().getMethod())) {
			return;
		}

		// read the form
		String id = data.getParameters().getString("id");

		// get the realm to copy from
		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");

		try
		{
			// make a new site with this id and as a structural copy of site
			AuthzGroup newRealm = authzGroupService.addAuthzGroup(id, realm, userDirectoryService.getCurrentUser().getId());
		}
		catch (GroupAlreadyDefinedException e)
		{
			addAlert(state, rb.getString("realm.iduse"));
			return;
		}
		catch (GroupIdInvalidException e)
		{
			addAlert(state, rb.getString("realm.idinvalid"));
			return;
		}
		catch (AuthzPermissionException e)
		{
			addAlert(state, rb.getString("realm.notpermis"));
			return;
		}

		doCancel(data, context);

		// TODO: hard coding this frame id is fragile, portal dependent, and needs to be fixed -ggolden
		schedulePeerFrameRefresh("sitenav");

	} // doSaveas

	/**
	 * cancel the saveas request, return to edit
	 */
	public void doCancel_saveas(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		if (!"POST".equals(data.getRequest().getMethod())) {
			return;
		}

		// return to main mode
		state.setAttribute("mode", "edit");

	} // doCancel_saveas

	/**
	 * Go into saveas mode
	 */
	public void doSaveas_request(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		// read the form - if rejected, leave things as they are
		if (!readRealmForm(data, state)) return;

		// go to saveas mode
		state.setAttribute("mode", "saveas");

	} // doSaveas_request

	/**
	 * Handle a request for a new realm.
	 */
	public void doNew(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
		state.setAttribute("mode", "new");

		// mark the realm as new, so on cancel it can be deleted
		state.setAttribute("new", "true");

		// disable auto-updates while in view mode
		disableObservers(state);

	} // doNew

	/**
	 * Handle a request to edit a realm.
	 */
	public void doEdit(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		String id = data.getParameters().getString("id");

		// get the realm
		try
		{
			AuthzGroup realm = authzGroupService.getAuthzGroup(id);
			state.setAttribute("realm", realm);

			state.setAttribute("mode", "edit");

			// disable auto-updates while in view mode
			disableObservers(state);
		}
		catch (GroupNotDefinedException e)
		{
		 	log.warn("realm not found: {}", id);

			addAlert(state, rb.getFormattedMessage("realm.notfound", new Object[]{id}));
			state.removeAttribute("mode");

			// make sure auto-updates are enabled
			enableObserver(state);
		}
		// catch (AuthzPermissionException e)
		// {
		// addAlert(state, rb.getString("realm.notpermis1") + " " + id);
		// state.removeAttribute("mode");
		//
		// // make sure auto-updates are enabled
		// enableObserver(state);
		// }

	} // doEdit

	/**
	 * Handle a request to save the realm edit (from the realm edit form).
	 */
	public void doSave(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		if (!"POST".equals(data.getRequest().getMethod())) {
			return;
		}

		// read the form - if rejected, leave things as they are
		if (!readRealmForm(data, state)) return;

		doSave_edit(data, context);

	} // doSave

	/**
	 * Handle a request to save the edit from either page or tools list mode - no form to read in.
	 */
	public void doSave_edit(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		if (!"POST".equals(data.getRequest().getMethod())) {
			return;
		}

		// commit the change
		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");
		if (realm != null)
		{
			try
			{
				authzGroupService.save(realm);
				// Grab the list from session state and save it, if appropriate
				List<String[]> userAuditList = (List<String[]>) state.getAttribute("userAuditList");
				if (userAuditList!=null && !userAuditList.isEmpty())
				{
					userAuditRegistration.addToUserAuditing(userAuditList);
					state.removeAttribute("userAuditList");
				}
			}
			catch (GroupNotDefinedException e)
			{
				// TODO: GroupNotDefinedException
			}
			catch (AuthzPermissionException e)
			{
				// TODO: AuthzPermissionException
			}
			catch (Exception e)
			{
			 	log.warn("realmId = {} {}", realm.getId(), e.getMessage());
			}
		}

		// cleanup
		cleanState(state);

		// return to main mode
		state.removeAttribute("mode");

		// make sure auto-updates are enabled
		enableObserver(state);

		// TODO: hard coding this frame id is fragile, portal dependent, and needs to be fixed -ggolden
		schedulePeerFrameRefresh("sitenav");

	} // doSave_edit

	/**
	 * doCancel called when "eventSubmit_doCancel" is in the request parameters to cancel realm edits
	 */
	public void doCancel(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		if (!"POST".equals(data.getRequest().getMethod())) {
			return;
		}

		// get the realm
		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");
		if (realm != null)
		{
			// if this was a new, delete the realm
			if ("true".equals(state.getAttribute("new")))
			{
				// remove the realm
				try
				{
					authzGroupService.removeAuthzGroup(realm);
				}
				catch (AuthzPermissionException e)
				{
					addAlert(state, rb.getFormattedMessage("realm.notpermis2", new Object[]{realm.getId()}));
				}
				catch (AuthzRealmLockException arle)
				{
					log.warn("GROUP LOCK REGRESSION: {}", arle.getMessage(), arle);
				}
			}
		}

		// cleanup
		cleanState(state);

		// return to main mode
		state.removeAttribute("mode");

		// make sure auto-updates are enabled
		enableObserver(state);

	} // doCancel

	/**
	 * doRemove called when "eventSubmit_doRemove" is in the request parameters to confirm removal of the realm
	 */
	public void doRemove(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		// read the form - if rejected, leave things as they are
		if (!readRealmForm(data, state)) return;

		// go to remove confirm mode
		state.setAttribute("mode", "confirm");

		// disable auto-updates while in view mode
		disableObservers(state);

	} // doRemove

	/**
	 * doRemove_confirmed called when "eventSubmit_doRemove_confirmed" is in the request parameters to remove the realm
	 */
	public void doRemove_confirmed(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		if (!"POST".equals(data.getRequest().getMethod())) {
			return;
		}

		// get the realm
		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");
		if (realm != null)
		{
			// remove the realm
			try
			{
				authzGroupService.removeAuthzGroup(realm);
			}
			catch (AuthzPermissionException e)
			{
				addAlert(state, rb.getFormattedMessage("realm.notpermis2", new Object[]{realm.getId()}));
			}
			catch (AuthzRealmLockException arle)
			{
				log.warn("GROUP LOCK REGRESSION: {}", arle.getMessage(), arle);
			}

			// cleanup
			cleanState(state);

			// go to main mode
			state.removeAttribute("mode");

			// make sure auto-updates are enabled
			enableObserver(state);
		}

	} // doRemove_confirmed

	/**
	 * doCancel_remove called when "eventSubmit_doCancel_remove" is in the request parameters to cancel realm removal
	 */
	public void doCancel_remove(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		if (!"POST".equals(data.getRequest().getMethod())) {
			return;
		}

		// return to edit mode
		state.setAttribute("mode", "edit");

	} // doCancel_remove

	/**
	 * Handle a request to view a realm.
	 */
	public void doView(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		String id = data.getParameters().getString("id");

		// get the realm
		try
		{
			AuthzGroup realm = authzGroupService.getAuthzGroup(id);
			state.setAttribute("realm", realm);

			state.setAttribute("mode", "view");

			// disable auto-updates while in view mode
			disableObservers(state);
		}
		catch (GroupNotDefinedException e)
		{
		 	log.warn("realm not found: {}", id);

			addAlert(state, rb.getFormattedMessage("realm.notfound", new Object[]{id}));
			state.removeAttribute("mode");

			// make sure auto-updates are enabled
			enableObserver(state);
		}

	} // doView

	/**
	 * View a role.
	 */
	public void doView_role(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		// read the form - if rejected, leave things as they are
		if (!readRealmForm(data, state)) return;

		state.setAttribute("mode", "viewRole");

		String id = data.getParameters().getString("target");

		// get the role
		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");
		if (realm != null)
		{
			Role role = realm.getRole(id);
			state.setAttribute("role", role);
		}

	} // doView_role

	/**
	 * Read the realm form and update the realm in state.
	 *
	 * @return true if the form is accepted, false if there's a validation error (an alertMessage will be set)
	 */
	private boolean readRealmForm(RunData data, SessionState state)
	{
		// read the form
		String id = data.getParameters().getString("id");
		String provider = data.getParameters().getString("provider");
		String maintain = data.getParameters().getString("maintain");

		// verify provider information
		if (StringUtils.trimToNull(provider) != null)
		{
			String[] providers = groupProvider.unpackId(provider);
			for (int i = 0; i<providers.length; i++)
			{
				// no Exception is defined to be thrown from GroupProvider's getuserRolesForGroup(String) call
				// we will check for the null or empty returned value as an indicator for invalid provider id.
				//Map<String, String> userRoles = groupProvider.getUserRolesForGroup(providers[i]);
			    if (!groupProvider.groupExists(providers[i]))
				{
					// if provider id isn't found or is null then an empty collection should be returned.
					// is it proper to issue the following alert?
					addAlert(state, rb.getFormattedMessage("realm.noProviderIdFound", new Object[]{providers[i]}));
				}
			}

			if (state.getAttribute(STATE_MESSAGE) != null)
			{
				return false;
			}
		}

		// get the realm
		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");

		// add if needed
		if (realm == null)
		{
			try
			{
				realm = authzGroupService.addAuthzGroup(id);

				// put the realm in the state
				state.setAttribute("realm", realm);
			}
			catch (GroupAlreadyDefinedException e)
			{
				addAlert(state, rb.getString("realm.iduse"));
				return false;
			}
			catch (GroupIdInvalidException e)
			{
				addAlert(state, rb.getString("realm.idinvalid"));
				return false;
			}
			catch (AuthzPermissionException e)
			{
				addAlert(state, rb.getString("realm.notpermis3"));
				return false;
			}
		}

		// update
		if (realm != null)
		{
			realm.setProviderGroupId(provider);
			realm.setMaintainRole(maintain);
		}

		return true;

	} // readRealmForm

	/**
	 * Handle a request to create a new role in the realm edit.
	 */
	public void doNew_role(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
		state.setAttribute("mode", "newRole");

		// read the form - if rejected, leave things as they are
		if (!readRealmForm(data, state)) return;

		// mark the realm as new, so on cancel it can be deleted
		state.setAttribute("newRole", "true");

	} // doNew_role

	/**
	 * Edit an existing page.
	 */
	public void doEdit_role(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		// read the form - if rejected, leave things as they are
		if (!readRealmForm(data, state)) return;

		state.setAttribute("mode", "editRole");

		String id = data.getParameters().getString("target");

		// get the role
		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");
		if (realm != null)
		{
			Role role = realm.getRole(id);
			state.setAttribute("role", role);
		}

	} // doEdit_role

	/**
	 * Handle a request to remove the role being edited.
	 */
	public void doRemove_role(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");
		Role role = (Role) state.getAttribute("role");
		if (realm != null && role != null)
		{
			// remove the role (no confirm)
			realm.removeRole(role.getId());

			// done with the role
			state.removeAttribute("role");

			// return to edit mode
			state.setAttribute("mode", "edit");
		}

	} // doRemove_role

	/**
	 * Handle a request to remove the role being edited.
	 */
	public void doSaveas_role(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		// read the form - if rejected, leave things as they are
		if (!readRoleForm(data, state)) return;

		// go to saveas_role mode
		state.setAttribute("mode", "saveasRole");

	} // doSaveas_role

	/**
	 * Handle a request to saveas with this name.
	 */
	public void doSave_role_as(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		// read the form
		if (!readRoleSaveAsForm(data, state)) return;

		// cleanup
		state.removeAttribute("role");

		// go back to edit mode
		state.setAttribute("mode", "edit");

	} // doSave_role_as

	/**
	 * Handle a request to cancel role saveas.
	 */
	public void doCancel_role_saveas(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		// cleanup
		state.removeAttribute("role");

		// go back to edit mode
		state.setAttribute("mode", "edit");

	} // doCancel_role_saveas

	/**
	 * Handle a request to save the realm edit (from the role edit form).
	 */
	public void doSave_role(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		// read the form - if rejected, leave things as they are
		if (!readRoleForm(data, state)) return;

		doSave_edit(data, context);

	} // doSave_role

	/**
	 * Handle a request to be done role editing - return to the edit mode.
	 */
	public void doDone_role(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		// read the form - if rejected, leave things as they are
		if (!readRoleForm(data, state)) return;

		// cleanup
		state.removeAttribute("role");

		// go back to edit mode
		state.setAttribute("mode", "edit");

	} // doDone_role

	/**
	 * Read the user form and update the realm in state.
	 *
	 * @return true if the form is accepted, false if there's a validation error (an alertMessage will be set)
	 */
	private boolean readRoleForm(RunData data, SessionState state)
	{
		// get the realm
		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");

		// get the locks
		String[] locks = data.getParameters().getStrings("locks");

		// we are setting for either a new role or this role
		Role role = (Role) state.getAttribute("role");

		//Read the locks if they're null and the role is not null to avoid passing them around
		if (locks == null && role != null) {
			Collection realms = new ArrayList<String>(Arrays.asList(realm.getId()));
			List <String> newlocks = new ArrayList(authzGroupService.getAllowedFunctions(role.getId(), realms));
			locks = newlocks.toArray(new String[0]);
		}

		if (realm != null && role == null)
		{
			// read the form
			String id = StringUtils.trimToNull(data.getParameters().getString("id"));

			// if the field is missing, and there are no locks, just be done with no change
			if ((id == null) && (locks == null)) return true;

			if (id == null)
			{
				addAlert(state, rb.getString("realm.please"));
				return false;
				// TODO: would be nice to read the locks, and restore them when the form returns -ggolden
			}

			// create the role
			try
			{
				role = realm.addRole(id);
			}
			catch (RoleAlreadyDefinedException e)
			{
				addAlert(state, rb.getFormattedMessage("realm.defined", new Object[]{id}) );
				return false;
				// TODO: would be nice to read the locks, and restore them when the form returns -ggolden
			}
		}

		// clear out the role
		role.disallowAll();

		String descriptionString = StringUtils.trimToNull(data.getParameters().getString("description"));
		String providerOnlyString = StringUtils.trimToNull(data.getParameters().getString("providerOnly"));

		//Role can't be null at this point
		if (descriptionString == null) {
			descriptionString = role.getDescription();
		}

		if (providerOnlyString == null) {
			providerOnlyString = String.valueOf(role.isProviderOnly());
		}

		// description
		role.setDescription(StringUtils.trimToNull(descriptionString));

		// providerOnly
		role.setProviderOnly("true".equals(providerOnlyString));

		// for each lock set, give it to the role
		if (locks != null)
		{
			for (int i = 0; i < locks.length; i++)
			{
				role.allowFunction(locks[i]);
			}
		}

		return true;

	} // readRoleForm

	/**
	 * Read the role save as form and make the new role in the realm in edit.
	 *
	 * @return true if the form is accepted, false if there's a validation error (an alertMessage will be set)
	 */
	private boolean readRoleSaveAsForm(RunData data, SessionState state)
	{
		// get the realm
		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");

		// we will copy this role
		Role role = (Role) state.getAttribute("role");

		// read the form
		String id = StringUtils.trimToNull(data.getParameters().getString("id"));

		if (id == null)
		{
			addAlert(state, rb.getString("realm.please"));
			return false;
		}

		if (realm != null)
		{
			// create the role
			try
			{
				realm.addRole(id, role);
			}
			catch (RoleAlreadyDefinedException e)
			{
				addAlert(state, rb.getFormattedMessage("realm.defined", new Object[]{id}) );
				return false;
			}
		}

		return true;

	} // readRoleSaveAsForm

	/**
	 * create a new user ability grant in the realm edit.
	 */
	public void doNew_user(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		// read the form - if rejected, leave things as they are
		if (!readRealmForm(data, state)) return;

		state.setAttribute("mode", "newUser");

		// mark the realm as new, so on cancel it can be deleted
		state.setAttribute("newUser", "true");

	} // doNew_user

	/**
	 * Edit an existing user ability grant.
	 */
	public void doEdit_user(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		// read the form - if rejected, leave things as they are
		if (!readRealmForm(data, state)) return;

		String id = data.getParameters().getString("target");
		try
		{
			User user = userDirectoryService.getUser(id);
			state.setAttribute("user", user);
			state.setAttribute("mode", "editUser");
		}
		catch (UserNotDefinedException e)
		{
		 	log.warn("user not found: {}", id);
			addAlert(state, rb.getString("realm.user.notfound"));
		}

	} // doEdit_user

	/**
	 * Handle a request to remove all grants to the user.
	 */
	public void doRemove_user(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		// the user we are editing
		User user = (User) state.getAttribute("user");

		// get the realm
		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");

		if (realm != null && user != null)
		{
			// Need to grab the role before removing the user from the realm
			// Need to grab the role before removing the user from the realm
			Role role = realm.getUserRole(user.getId());
			String roleId = "";
			if (role != null) {
				roleId = role.getId();
			}

			// clear out this user's settings
			realm.removeMember(user.getId());

			// user auditing
			addToAuditLogList(state, realm, user.getEid(), roleId);

			// done with the user
			state.removeAttribute("user");

			// return to edit mode
			state.setAttribute("mode", "edit");
		}

	} // doRemove_user

	/**
	 * Handle a request to save the realm edit (from the user edit form).
	 */
	public void doSave_user(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		// read the form - if rejected, leave things as they are
		if (!readUserForm(data, state)) return;

		doSave_edit(data, context);

	} // doSave_user

	/**
	 * Handle a request to be done user editing - return to the edit mode.
	 */
	public void doDone_user(RunData data, Context context)
	{
		SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

		// read the form - if rejected, leave things as they are
		if (!readUserForm(data, state)) return;

		// cleanup
		state.removeAttribute("user");

		// go back to edit mode
		state.setAttribute("mode", "edit");

	} // doDone_user

	/**
	 * Read the user form and update the realm in state.
	 *
	 * @return true if the form is accepted, false if there's a validation error (an alertMessage will be set)
	 */
	private boolean readUserForm(RunData data, SessionState state)
	{
		// get the role
		String roles = StringUtils.trimToNull(data.getParameters().getString("roles"));

		//get status
		Boolean status=true;
		String checkForStatus=data.getParameters().get("status");
		if (!(checkForStatus==null)){
		status=data.getParameters().getBoolean("status");
		}

		// we are setting for either a new user or this user
		User user = (User) state.getAttribute("user");
		if (user == null)
		{
			// read the form
			String eid = StringUtils.trimToNull(data.getParameters().getString("eid"));

			// if the field is missing, and there are no roles, just be done with no change
			if ((eid == null) && (roles == null)) return true;

			try
			{
				user = userDirectoryService.getUserByEid(eid);
			}
			catch (UserNotDefinedException e)
			{
				addAlert(state, rb.getString("realm.user"));
				return false;
				// TODO: would be nice to read the roles, and restore them when the form returns -ggolden
			}
		}

		// get the realm
		AuthzGroup realm = (AuthzGroup) state.getAttribute("realm");
		if (realm != null)
		{
			// if the user is set to have the same role the user already has, do nothing
			Member grant = realm.getMember(user.getId());

			// if no change, change nothing
			if (roles == null && (grant == null && (checkForStatus == null) ) ) {
			    // removing this since it would cause a null pointer exception if the code got here so we think the code does not ever get here -AZ
			    //) || (grant.isProvided())))) return true;
			    return true;
			}
			if ((roles != null) && (grant != null) && (grant.getRole().getId().equals(roles) && (grant.isActive()==status)) && !grant.isProvided()) return true;

			// clear out this user's settings
			realm.removeMember(user.getId());

			// if there's a role, give it
			if (roles != null)
			{
				// TODO: active, provided
				realm.addMember(user.getId(), roles, status, false);

				// user auditing
				addToAuditLogList(state, realm, user.getEid(), roles);
			}
		}

		return true;

	} // readUserForm

	/**
	 * Clean up all possible state value when done an edit.
	 */
	private void cleanState(SessionState state)
	{
		state.removeAttribute("realm");
		state.removeAttribute("role");
		state.removeAttribute("user");
		state.removeAttribute("new");
		state.removeAttribute("newRole");
		state.removeAttribute("newUser");
		state.removeAttribute("allRoles");
		state.removeAttribute("allLocks");
		state.removeAttribute("roles");
		state.removeAttribute("locks");
		state.removeAttribute("userAuditList");

	} // cleanState

	/**
	 * Check if the current user is allowed to access the tool
	 *
	 * Super users are allowed, as well as people with the AuthzGroupService.SECURE_VIEW_ALL_AUTHZ_GROUPS permission.
	 */
	private boolean isAccessAllowed() {
		if(securityService.isSuperUser()) {
			return true;
		}
		String siteId = toolManager.getCurrentPlacement().getContext();
		String siteRef = siteId;
		if(siteId != null && !siteId.startsWith(SiteService.REFERENCE_ROOT)) {
			siteRef = SiteService.REFERENCE_ROOT + Entity.SEPARATOR + siteId;
		}

		String userId = sessionManager.getCurrentSessionUserId();

		if(securityService.unlock(userId, AuthzGroupService.SECURE_VIEW_ALL_AUTHZ_GROUPS, siteRef)) {
			log.debug("Granting view access to Realms tool for userId: {}", userId);
			return true;
		}

		return false;
	}

	private List<String[]> retrieveAuditLogList(SessionState state)
	{
		// user auditing
		List<String[]> userAuditList = (List<String[]>) state.getAttribute("userAuditList");
		if (userAuditList!=null && !userAuditList.isEmpty())
		{
			state.removeAttribute("userAuditList");
		}
		else
		{
			userAuditList = new ArrayList<String[]>();
		}

		return userAuditList;
	}

	private void addToAuditLogList(SessionState state, AuthzGroup realm, String userEid, String userRole)
	{
		List<String[]> userAuditList = retrieveAuditLogList(state);

		String realmId = realm.getId();
		String siteId = "";
		String fullReferenceRoot = SiteService.REFERENCE_ROOT + Entity.SEPARATOR;
		if (realmId.startsWith(fullReferenceRoot))
		{
			siteId = realmId.substring(fullReferenceRoot.length());
		}
		else
		{
			// this will likely never happen, but adding it in as a backup
			siteId = realmId;
		}
		String newOrExistingUser = (String) state.getAttribute("newUser");
		String userAuditAction = userAuditService.USER_AUDIT_ACTION_UPDATE;

		// if this using the Grant As functionality, it will be a new user being added
		if (newOrExistingUser!=null && "true".equals(newOrExistingUser))
		{
			userAuditAction = userAuditService.USER_AUDIT_ACTION_ADD;
		}
		String[] userAuditString = {siteId,userEid,userRole,userAuditAction,userAuditRegistration.getDatabaseSourceKey(),userDirectoryService.getCurrentUser().getEid()};
		userAuditList.add(userAuditString);

		state.setAttribute("userAuditList", userAuditList);
	}

} // RealmsAction


text:
import { Reducer } from 'redux-testkit';
import loadedMessagesReducer from '../../reducers/loadedMessagesReducer';
import { loadedMessagesReducerMock as mock } from '../mockData';

describe('loadedMessagesReducer', () => {
  it('should have an initial state', () => {
    expect(loadedMessagesReducer(undefined, {
      type: 'UNREGISTERED'
    })).toEqual(mock.initialState);
  });
  it('should not affect state', () => {
    Reducer(loadedMessagesReducer).expect({ type: 'NOT_EXISTING' })
      .toReturnState(mock.initialState);
  });
  it('should load messages into the store', () => {
    Reducer(loadedMessagesReducer).expect(mock.actionLoadMessages)
      .toReturnState(mock.messagesLoaded);
  });
  it('should set store with id of created group after a group is created', () => {
    Reducer(loadedMessagesReducer).expect(mock.actionCreateGroup)
      .toReturnState(mock.groupCreated);
  });
  it('should reset state after group is deleted', () => {
    Reducer(loadedMessagesReducer).expect(mock.actionDeleteGroup)
      .toReturnState(mock.initialState);
  });
  it('should reset state after a user leaves a group', () => {
    Reducer(loadedMessagesReducer).expect(mock.actionLeaveGroup)
      .toReturnState(mock.initialState);
  });
  it('should reset state after a user signs out', () => {
    Reducer(loadedMessagesReducer).expect(mock.actionSignOut)
      .toReturnState(mock.initialState);
  });
});


text:
Simplified parallelism in the browser.

[![Build Status](https://travis-ci.org/dkushner/ergjs.svg?branch=master)](https://travis-ci.org/dkushner/ergjs)
[![Build Status](https://saucelabs.com/buildstatus/dkushner)](https://saucelabs.com/beta/builds/7d308342ce924c00bec33bf4c8850866)

[![Sauce Test Status](https://saucelabs.com/browser-matrix/dkushner.svg)](https://saucelabs.com/u/dkushner)

### What's it for?
In modern web applications, computationally expensive operations can tie up the main script evaluation thread and lead to degraded user experiences. `ergjs` provides an easy way to offload these operations into independent, general purpose "threads" called [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers).

Web Workers are a phenomenal tool for performing heavy computing tasks in the browser but are too heavy for traditional "fire-and-forget" approaches to concurrency supported by native OS threads. Furthermore, the behaviour of Web Workers can vary dramatically between browsers and the Web Worker API may make integrating them into your project seem like more hassle than they're worth. `ergjs` solves this by managing long-lived Web Workers and distributing user-defined tasks among them.


text:
<?php
namespace www\db_definition;

/**
 * User: Lite Scaffold
 */
use Lite\DB\Model as Model;
use Lite\DB\Query as Query;

/**
 * Class TableSingleSample

 * @property-read int $id
 * @property int $sample_id 样品ID
 * @property double $length 长
 * @property double $width 宽
 * @property double $height 高
 * @property double $volume 容积
 * @property double $weight 重量
 * @property mixed $technic_flow_id_list 工艺流程(模具,成型,素烧,釉下工艺,釉烧,釉上工艺,烘烤,包装)
 * @method static TableSingleSample|Query meta()
 * @method boolean onBeforeSave()
 * @method boolean onBeforeUpdate()
 * @method boolean onBeforeInsert()
 * @method static string getDbTablePrefix($type = TableSingleSample::DB_READ)
 * @method static TableSingleSample|Query setQuery($query = null, $db_config = array())
 * @method Query getQuery()
 * @method static \Exception transaction($handler)
 * @method \PDOStatement execute()
 * @method static TableSingleSample|Query find($statement = '', $var = null, ...$var2)
 * @method static TableSingleSample|Query order($statement='')
 * @method static TableSingleSample|Query|bool create($data)
 * @method static TableSingleSample|Query|array findOneByPk($val, $as_array = false)
 * @method static TableSingleSample|Query|array findByPks(array $pks, $as_array = false)
 * @method static bool delByPk($val)
 * @method static bool updateByPk($val, $data)
 * @method static bool updateWhere(array $data, $limit = 1, $statement, ...$var2)
 * @method static bool deleteWhere($limit = 1, $statement, ...$var2)
 * @method array all($as_array = false)
 * @method TableSingleSample|Query|array|null one($as_array = false)
 * @method mixed|null ceil($key)
 * @method bool chunk($size = 1, $handler)
 * @method int count()
 * @method array|null paginate($page = null, $as_array = false)
 * @method number update()
 * @method string|bool insert()
 * @method static array|bool insertMany($data_list, $break_on_fail = true)
 * @method bool delete()
 * @method bool save()
 * @method setPropertiesDefine(array $defines)
 * @method array getPropertiesDefine($key=null)
 * @method array getEntityPropertiesDefine($key=null)
 * @method array getAllPropertiesKey()
 * @method string getPrimaryKey()
 */
abstract class TableSingleSample extends Model {
	public function __construct($data=array()){
		$this->setPropertiesDefine(array(
			'id' => array(
				'alias' => 'id',
				'type' => 'int',
				'length' => 11,
				'primary' => true,
				'required' => true,
				'readonly' => true,
				'entity' => true
			),
			'sample_id' => array(
				'alias' => '样品ID',
				'type' => 'int',
				'length' => 10,
				'required' => true,
				'min' => 0,
				'entity' => true
			),
			'length' => array(
				'alias' => '长',
				'type' => 'double',
				'length' => 10,
				'precision' => 2,
				'min' => 0,
				'default' => 0.00,
				'entity' => true
			),
			'width' => array(
				'alias' => '宽',
				'type' => 'double',
				'length' => 10,
				'precision' => 2,
				'min' => 0,
				'default' => 0.00,
				'entity' => true
			),
			'height' => array(
				'alias' => '高',
				'type' => 'double',
				'length' => 10,
				'precision' => 2,
				'min' => 0,
				'default' => 0.00,
				'entity' => true
			),
			'volume' => array(
				'alias' => '容积',
				'type' => 'double',
				'length' => 10,
				'precision' => 2,
				'min' => 0,
				'default' => 0.00,
				'entity' => true
			),
			'weight' => array(
				'alias' => '重量',
				'type' => 'double',
				'length' => 10,
				'precision' => 2,
				'min' => 0,
				'default' => 0.00,
				'entity' => true
			),
			'technic_flow_id_list' => array(
				'alias' => '工艺流程',
				'type' => 'set',
				'default' => null,
				'options' => array('1'=>'模具', '2'=>'成型', '3'=>'素烧', '4'=>'釉下工艺', '5'=>'釉烧', '6'=>'釉上工艺', '7'=>'烘烤', '8'=>'包装'),
				'entity' => true
			),
		));
		parent::__construct($data);
	}

	/**
	 * current model table name
	 * @return string
	 */
	public function getTableName() {
		return 'single_sample';
	}

	/**
	* get database config
	* @return array
	*/
	protected function getDbConfig(){
		return include dirname(__DIR__).'/db.inc.php';
	}

	/**
	* 获取模块名称
	* @return string
	*/
	public function getModelDesc(){
		return '单件';
	}
}


text:
import Vue from 'vue'
import VueRouter from 'vue-router'

/**
 * Apply Vue plugins
 */
Vue.use(VueRouter)

/**
 * Initial router
 */
import routes from './routes'
const router = new VueRouter()
router.map(routes)

/**
 * Start client
 */
import app from './app'
router.start(app, '#app')


text:
Collection can be run together as a series of requests with different Environment. You can write test cases in Test Script, pass data between requests by using `setEnvVariable` or `File`, and sort requests as your actual use case of APIs.

Hitchhiker support to add a Schedule to your Collection to do automate API testing and response data comparison.

Follow these step to run a schedule:

1. [Create a Schedule](Create_Schedule.md)

2. [Run Schedule](Run.md)


text:
package nested_dir

import (
	"fmt"
	"os"
	"path/filepath"
)

type t struct {
	myString string
}

func Something() string {
	someString := T("hello")
	var anotherString string = T("world")
	println(someString, anotherString)

	yetAnotherString := []string{T("tricky tests")}
	var moreStrings []string
	moreStrings = []string{T("are"), T("tricky")}
	println(yetAnotherString, moreStrings)

	mappyMap := map[string]string{T("hello"): T("world")}
	println(mappyMap)

	myT := t{myString: T("my string")}
	println(myT)

	trickyT := t{T("this is a tricky case")}
	println(trickyT)

	fmt.Printf(T("HAI"))
	if os.Getenv(T("SOMETHING")) {
		fmt.Printf(filepath.Clean(os.Getenv(T("something"))))
	}

	return T("enqueuedequeueenqueuebananapants")
}


text:
// Start Quick Search

function addSearchResult(name, id) {
  searchResultsNameStorage.push(name);
  name = escape(name);
  $("#searchResults").append("

" + name + "

");
}

function loadSearchResult(element) {
  let iteration = $(".searchResult").index(element);
  let id = quickSearchVideos[iteration];
  console.log("i:" + iteration + ",id:" + id);

  //getVideoData function equivalent without reloading video names
  let videoId = id;
  let videoTime = 0;
  let videoName = searchResultsNameStorage[iteration];
  addVideo(videoName, videoTime, videoId);

  if (searchClose) {
    toggleMenu("searchResults");
  }
}

// * This function loads the video for the Quick Search functionality

function quickSearch(query) {
  //console.log("debug: quickSearch(\"" + query + "\")");

  if (!inBoxSearch && quickSearchVideosIteration + 1 < quickSearchVideos.length) {
    $("#inputBox").val("").attr("placeholder", loadingPlaceholder);
  }
  if (query !== "") {
    $("#searchProgress").css("display", "flex");

    quickSearchQuery = query;
    let searchDataFrame = document.createElement("iframe");
    searchDataFrame.setAttribute("id", "searchDataFrame");
    searchDataFrame.setAttribute("src", "");
    document.getElementById("dataFramesContainer").appendChild(searchDataFrame);
    searchDataPlayer = new YT.Player('searchDataFrame', {
      events: {
        'onReady': onSearchDataPlayerReady,
        'onStateChange': onSearchDataPlayerStateChange
      }
    });
    searchDataFrame.setAttribute("src", "https://www.youtube.com/embed/?enablejsapi=1");
  }
  else if (quickSearchVideosIteration + 1 < quickSearchVideos.length) {
    quickSearchVideosIteration++;
    getVideoData(quickSearchVideos[quickSearchVideosIteration]);
  }
}

// * This function cues the search results for use in the next function

let searchDataPlayerErrors = 0;
function onSearchDataPlayerReady() {
  try {
    searchDataPlayer.cuePlaylist({listType: "search", list: quickSearchQuery});
  }
  catch(e) {
    searchDataPlayerErrors++;
    console.log(e);
    if (searchDataPlayerErrors <= 5) {
      try {
        searchDataPlayer.destroy();
      } catch(e) {};
      quickSearch(quickSearchQuery);
    }
  }
}

// * This function uses the search results to add the next video

function onSearchDataPlayerStateChange(event) {
  if (event.data === 5) {
    if (!inBoxSearch) {
      $("#inputBox").val("").attr("placeholder", placeholder).blur().focus();
    }
    quickSearchVideosIteration = 0;
    quickSearchVideos = searchDataPlayer.getPlaylist();
    let data = searchDataPlayer.getVideoUrl();

    let id = urlValidate(data);
    if (id) {
      if (id[0] === "playlist") {
        id = id[1][0];
      }
      else if (id[0] === "youtube") {
        id = id[1];
      }
    }

    searchDataPlayer.destroy();
    if (inBoxSearch) {
      $(".searchResult").remove();
      searchResultsIteration = 0;
      searchResultsNameStorage = [];
      //as long as not open already (trying to search twice will close on second)
      if ($("#searchResultsWindow").css("display") !== "block") {
        toggleMenu("searchResults");
      }
    }
    getVideoData(id);

    $("#searchProgress").css("display", "none");
  }
}

// End Quick Search


text:
<?php
/**
 * the last known user to change this file in the repository  <$LastChangedBy: suqian $>
 * @author lei wei <leiwei@pipi.cn>
 * @version $Id: templates.xml 894 2013-07-25 07:55:25Z leiwei $
 * @package
 */
class PhoneService extends PipiService {

	/**
	 * 获取手机端验证码
	 * @param string $id  随机键值
	 * @return string
	 */
	public function getPhoneCode($id){
		if(empty($id)){
			return $this->setError(Yii::t('common','Parameter is empty'),0);
		}
		$otherRedisModel=new OtherRedisModel();
		return $otherRedisModel->getPhoneCode($id);
	}

	/**
	 * 存储手机端验证码
	 * @param string $id  随机键值
	 * @param string $value  验证码值
	 * @param int $expirTime 失效时间
	 * @return boolean
	 */
	public function savePhoneCode($id,$value,$expirTime=60){
		if(empty($id)){
			return $this->setError(Yii::t('common','Parameter is empty'),0);
		}
		$otherRedisModel=new OtherRedisModel();
		return $otherRedisModel->savePhoneCode($id,$value,$expirTime);
	}

}

?>