text:
package au.com.connectedteam.activity;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import au.com.connectedteam.R;
import au.com.connectedteam.application.ConnectedApp;
import au.com.connectedteam.util.StringUtils;

/**
 * Static library support version of the framework's {@link android.app.ListFragment}.
 * Used to write apps that run on platforms prior to Android 3.0.  When running
 * on Android 3.0 or above, this implementation is still used; it does not try
 * to switch to the framework's implementation.  See the framework SDK
 * documentation for a class overview.
 */
public abstract class ListOrExpandableListFragment extends BaseParseFragment {

	static final int INTERNAL_EXPANDABLE_LIST_ID = R.id.expandable_list;

	static final int INTERNAL_EMPTY_ID = R.id.internalEmpty;
	static final int INTERNAL_LOADING_TEXT_ID = R.id.internalLoading;
    static final int INTERNAL_PROGRESS_CONTAINER_ID = R.id.progressContainer;
    static final int INTERNAL_LIST_CONTAINER_ID = R.id.listContainer;
    static final int INTERNAL_LIST_ROOT_CONTAINER_ID = R.id.listRootContainer;
    /*
	static final int INTERNAL_EMPTY_ID = 0x00ff0001;
    static final int INTERNAL_PROGRESS_CONTAINER_ID = 0x00ff0002;
    static final int INTERNAL_LIST_CONTAINER_ID = 0x00ff0003;
    */
    /**
	 * The current activated item position. Only used on tablets.
	 */
	protected int mActivatedPosition = ListView.INVALID_POSITION;
	protected long mPendingActivatedItemId = 0;

	/**
	 * The serialization (saved instance state) Bundle key representing the
	 * activated item position. Only used on tablets.
	 */
	private static final String STATE_ACTIVATED_POSITION = "activated_position";

    public static final int TIME_UPDATE_INTERVAL = 1000;

    final private Handler mHandler = new Handler();

    final private Runnable mRequestFocus = new Runnable() {
        public void run() {
            mList.focusableViewAvailable(mList);
        }
    };

    final private AdapterView.OnItemClickListener mOnClickListener
            = new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        	if(isAdded() && getView()!=null)
    			onListItemClick((ListView)parent, v, position, id);
    		else{
    			String msg = "onListItemClick, added: "+isAdded()+" view: "+getView();
    			if(ConnectedApp.DEBUG) throw new IllegalStateException(msg);
    			else{
    				Log.e("ListOrExpandableListFragment", msg);
    			}
    		}
    	}
    };
    final private OnChildClickListener mOnChildClickListener
    = new OnChildClickListener() {
    	public boolean onChildClick(ExpandableListView parent, View v,
    			int groupPosition, int childPosition, long id) {
    		if(isAdded() && getView()!=null)
    			return onListChildClick(parent, v, groupPosition, childPosition, id);
    		else{
    			String msg = "OnChildClick, added: "+isAdded()+" view: "+getView();
    			if(ConnectedApp.DEBUG) throw new IllegalStateException(msg);
    			else Log.e("ListOrExpandableListFragment", msg);
    			return true;
    		}
    	}
    };
    final private OnGroupClickListener mOnGroupClickListener
    = new OnGroupClickListener() {
		public boolean onGroupClick(ExpandableListView parent, View v,
				int groupPosition, long id) {
			if(isAdded() && getView()!=null)
				return onListGroupClick(parent, v, groupPosition, id);
			else{
    			String msg = "onGroupClick, added: "+isAdded()+" view: "+getView();
    			if(ConnectedApp.DEBUG) throw new IllegalStateException(msg);
    			else Log.e("ListOrExpandableListFragment", msg);
    			return true;
    		}
		}

    };

    ListAdapter mAdapter;
    ExpandableListAdapter mExpandableListAdapter;
    ListView mList;
    View mEmptyView;
    TextView mStandardEmptyView;
    TextView mLoadingTextView;
    View mSpinnerProgressView;
    ImageView mErrorIconView;
    View mProgressContainer;
    View mListContainer;
    CharSequence mEmptyText;
    boolean mListShown;
    boolean listEnabled=true;
    boolean isExpandableListView=false;

    public ListOrExpandableListFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState){
    	super.onCreate(savedInstanceState);
    	Log.d("ListOrExpandableListFragment", "onCreate: "+savedInstanceState);
    	if(savedInstanceState!=null){
    		isExpandableListView = savedInstanceState.getBoolean("isExpandableListView");
    	/*	if(isExpandableListView && mExpandableListState==null){
    			mExpandableListState = ExpandableSavedState.readFromBundle(savedInstanceState);
    		}*/
    	}
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    View root= getActivity().getLayoutInflater().inflate(R.layout.list_or_expandable_list_layout, container, false);
    return root;
    }

    /**
     * Provide default implementation to return a simple list view.  Subclasses
     * can override to replace with their own layout.  If doing so, the
     * returned view hierarchy must have a ListView whose id
     * is {@link android.R.id#list android.R.id.list} and can optionally
     * have a sibling view id {@link android.R.id#empty android.R.id.empty}
     * that is to be shown when the list is empty.
     *
     *
If you are overriding this method with your own custom content,
     * consider including the standard layout {@link android.R.layout#list_content}
     * in your layout file, so that you continue to retain all of the standard
     * behavior of ListFragment.  In particular, this is currently the only
     * way to have the built-in indeterminant progress state be shown.
     *
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        final Context context = getActivity();

        FrameLayout root = new FrameLayout(context);

        // ------------------------------------------------------------------

        LinearLayout pframe = new LinearLayout(context);
        pframe.setId(INTERNAL_PROGRESS_CONTAINER_ID);
        pframe.setOrientation(LinearLayout.VERTICAL);
        pframe.setVisibility(View.GONE);
        pframe.setGravity(Gravity.CENTER);

        ProgressBar progress = new ProgressBar(context, null,
                android.R.attr.progressBarStyleLarge);
        pframe.addView(progress, new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        root.addView(pframe, new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));

        // ------------------------------------------------------------------

        FrameLayout lframe = new FrameLayout(context);
        lframe.setId(INTERNAL_LIST_CONTAINER_ID);

        TextView tv = new TextView(getActivity());
        tv.setId(INTERNAL_EMPTY_ID);
        tv.setGravity(Gravity.CENTER);
        lframe.addView(tv, new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));

        ListView lv = new ListView(getActivity());
        lv.setId(android.R.id.list);
        lv.setDrawSelectorOnTop(false);
        lframe.addView(lv, new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));

        root.addView(lframe, new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));

        // ------------------------------------------------------------------

        root.setLayoutParams(new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));

        return root;
    }
*/
    /**
     * Attach to list view once the view hierarchy has been created.
     */
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ensureList();
        if(isExpandableListView){
        	/*if(mExpandableListAdapter!=null && mExpandableListState!=null){
        		mExpandableListState.restore(getExpandableListView());
        	}*/
        }
        if (savedInstanceState != null
				&& savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
			setActivatedPosition(savedInstanceState
					.getInt(STATE_ACTIVATED_POSITION));
		}
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
    	super.onSaveInstanceState(outState);
    	outState.putBoolean("isExpandableListView", isExpandableListView);
    	if(isExpandableListView && mList instanceof ExpandableListView){
    		/*if(!getRetainInstance() && mExpandableListState!=null){
    			//only need to save this if we aren't persisting state
    			mExpandableListState.writeToBundle(outState);
    		}*/
    	}
    	if (mActivatedPosition != ListView.INVALID_POSITION) {
    		// Serialize and persist the activated item position.
    		outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
    	}
    }

    /**
	 * Turns on activate-on-click mode. When this mode is on, list items will be
	 * given the 'activated' state when touched.
	 */
	public void setActivateOnItemClick(boolean activateOnItemClick) {
		// When setting CHOICE_MODE_SINGLE, ListView will automatically
		// give items the 'activated' state when touched.
		getListView().setChoiceMode(
				activateOnItemClick ? ListView.CHOICE_MODE_SINGLE
						: ListView.CHOICE_MODE_NONE);
	}

	public void setPendingActivatedItemId(long id) {
		mPendingActivatedItemId = id;

	}
	protected void setActivatedPosition(int position) {
		if (position == ListView.INVALID_POSITION) {
			getListView().setItemChecked(mActivatedPosition, false);
		} else {
			getListView().setItemChecked(position, true);
		}

		mActivatedPosition = position;
		mPendingActivatedItemId=0;
	}

	protected void setCardSeparatorAndBG(){

		getListView().setDivider(getResources().getDrawable(R.drawable.list_divider_card));
		if(isExpandableListView()){
			getExpandableListView().setChildDivider(getResources().getDrawable(R.drawable.list_divider_card));
		}
		getListView().setBackgroundResource(R.color.card_background);

	}
    /*
    protected Runnable timeUpdater = new Runnable(){

		@Override
		public void run() {
			uiHandler.removeCallbacks(timeUpdater);

				if (timeUpdateTick()) uiHandler.postDelayed(timeUpdater, TIME_UPDATE_INTERVAL);

		}

	};
	/**
	 * Base implementation updates ListView children.
	 * Subclasses can override to update other views on the same tick
	 * @return true to continue, false to stop the timeUpdater.
	 *
	protected boolean timeUpdateTick(){
		if (ListOrExpandableListFragment.this.isResumed() &&!isStalled && getListView()!=null){
			//skip over uservisiblehint
			if(!ListOrExpandableListFragment.this.getUserVisibleHint()) return true;

			int count = ListOrExpandableListFragment.this.getListView().getChildCount();
			int updated=0;
			//TODO modified so return value from CellTimeUpdater interface is ignored, becuase if there
			//is only one cell which is counting, and it is scrolled away, the counter will turn off.
			int areAllStatic=0;

			Date now = new Date();
			for (int i=0;i<count;i++){
				View child =ListOrExpandableListFragment.this.getListView().getChildAt(i);
				if (child instanceof CellTimeUpdater){
					areAllStatic=areAllStatic+((CellTimeUpdater)child).updateTimeLeft(now);
					updated++;
				}
			}

			return true;

		}
		return false;
	}

	@Override
	public void onPause(){
		super.onPause();
		uiHandler.removeCallbacks(timeUpdater);
		Log.d("ListOrExpandableListFragment", "onPause");

	}

	@Override
	public void onResume(){
		super.onResume();
		uiHandler.postDelayed(timeUpdater, TIME_UPDATE_INTERVAL);
	}
	*/

	protected final void changeListView(boolean expandable){
    	ViewGroup parent;
    	if (mList!=null){
    		parent = (FrameLayout) mList.getParent();
    		parent.removeView(mList);
    	}
    	else{
    		parent =  (ViewGroup) getView();
    	}

    	mList=null;
    	ListView lv;

    	if (expandable){
    		lv = new ExpandableListView(getActivity());
    		((ExpandableListView) lv).setGroupIndicator(null);
			((ExpandableListView) lv).setChildIndicator(null);
			//getExpandableListView().setIndicatorBounds(0, 0);
			lv.setId(INTERNAL_EXPANDABLE_LIST_ID);
			//lv.setSelector(R.drawable.list_selector_expandable);
    	}
    	else{
    		lv = new ListView(getActivity());
    		lv.setId(android.R.id.list);
    	}

    	lv.setDrawSelectorOnTop(false);
    	parent.addView(lv);

    	if (mProgressContainer == null) {
            throw new IllegalStateException("ExpandableListView can't be used with a custom content view");
        }
//    	try{
//    		//((FrameLayout)root.findViewById(INTERNAL_LIST_CONTAINER_ID)).addView(lv);
//    	}
//    	catch(NullPointerException e){
//    		throw new IllegalStateException("Could not find internal list container. " +
//    				"ExpandableListView can't be used with a custom content view");
//    	}
    	isExpandableListView=expandable;
    	ListAdapter lAdapter = mAdapter;
    	ExpandableListAdapter lExpandableAdapter = mExpandableListAdapter;
    	mAdapter=null;
    	mExpandableListAdapter=null;
    	ensureList();
    	mAdapter = lAdapter;
    	mExpandableListAdapter=lExpandableAdapter;

    }

    /**
     *
     * @return true if the attached list view is
     * an ExpandableListView
     */
    public boolean isExpandableListView(){
    	return mList instanceof ExpandableListView;
    }

    /**
     * Detach from list view.
     */
    @Override
    public void onDestroyView() {
        mHandler.removeCallbacks(mRequestFocus);
        if(mList!=null && !ConnectedApp.DEBUG){
       	 mList.setOnItemClickListener(null);
            if (mList instanceof ExpandableListView){
            	((ExpandableListView) mList).setOnChildClickListener(null);
            	((ExpandableListView) mList).setOnGroupClickListener(null);
            }
       }
        mList = null;
        mListShown = false;
        mEmptyView = mProgressContainer = mListContainer = null;
        mStandardEmptyView = null;
        super.onDestroyView();
    }
    protected CharSequence getLoadingText(){
        return getString(R.string.requesting);
    }

    //@Override
	protected void showRequestFailedView(String msg) {
    	if(!listEnabled) return;
    //	if(listEnabled) setEmptyText(msg);
    	if(StringUtils.isNullOrEmpty(msg)){
    		mLoadingTextView.setText(getLoadingText());
    		mErrorIconView.setVisibility(View.GONE);
    		mSpinnerProgressView.setVisibility(View.VISIBLE);
    	}
    	else{
    		mLoadingTextView.setText(msg);
    		mErrorIconView.setVisibility(View.VISIBLE);
    		mSpinnerProgressView.setVisibility(View.GONE);

    	}

	}
    //@Override
    protected boolean shouldDisplayRequestFailedView(){
		//return lastModel==null;
		return isListEnabled()&& !isListVisible() && mLoadingTextView!=null;
	}

    /**
     * This method will be called when an item in the list is selected.
     * Subclasses should override. Subclasses can call
     * getListView().getItemAtPosition(position) if they need to access the
     * data associated with the selected item.
     *
     * @param l The ListView where the click happened
     * @param v The view that was clicked within the ListView
     * @param position The position of the view in the list
     * @param id The row id of the item that was clicked
     */
    public void onListItemClick(ListView l, View v, int position, long id) {
    }

    /**
     * This method will be called when a group item in the ExpandableList is selected.
     * Subclasses should override.
     *
     *  @param parent The ExpandableListView where the click happened
     *	@param v The view within the expandable list/ListView that was clicked
     *	@param groupPosition The group position that contains the child that was clicked
     *	@param id The row id of the child that was clicked
     *	@return True if the click was handled
     */
    public boolean onListGroupClick(ExpandableListView parent, View v,
    		int groupPosition, long id) {
    	return false;
    }

    /**
     * This method will be called when a child item in the ExpandableList is selected.
     * Subclasses should override.
     *
     *  @param parent The ExpandableListView where the click happened
     *	@param v The view within the expandable list/ListView that was clicked
     *	@param groupPosition The group position that contains the child that was clicked
     *	@param childPosition The child position within the group
     *	@param id The row id of the child that was clicked
     *	@return True if the click was handled
     */
    public boolean onListChildClick(ExpandableListView parent, View v,
    		int groupPosition, int childPosition, long id) {
    	return false;
    }

    /**
     * Provide the cursor for the list view.
     */
    public void setListAdapter(ListAdapter adapter) {
    	mExpandableListAdapter = null;
        boolean hadAdapter = mAdapter != null;
        mAdapter = adapter;
        if(mList instanceof ExpandableListView){
        	changeListView(false);
        }
        if (mList != null) {
            mList.setAdapter(adapter);
            if (!mListShown && !hadAdapter) {
                // The list was hidden, and previously didn't have an
                // adapter.  It is now time to show it.
                setListShown(true, getView().getWindowToken() != null);
            }
            if(mList.getChoiceMode()==ListView.CHOICE_MODE_SINGLE && mPendingActivatedItemId!=0){
            	for(int i=0;i<adapter.getCount(); i++){
            		if(adapter.getItemId(i)==mPendingActivatedItemId){
            			setActivatedPosition(i);
            			break;
            		}
            	}

            }
        }
    }

    public int setListAdapterKeepScroll(ListAdapter adapter){
    	int firstPos = -1;
		int top=0;
		if(getListAdapter()!=null){
			firstPos = getListView().getFirstVisiblePosition();
			View v = getListView().getChildAt(0);
			top = (v == null) ? 0 : v.getTop();
		}
		setListAdapter(adapter);
		if(firstPos>=0 && firstPos<adapter.getCount()){
			getListView().setSelectionFromTop(firstPos, top);
		}
		return firstPos;
    }

    public void setExpandableListAdapter(ExpandableListAdapter adapter){
    	mAdapter=null;
    	boolean hadAdapter = mExpandableListAdapter != null;
    	mExpandableListAdapter = adapter;
    	if (mList!=null && !(mList instanceof ExpandableListView)){
    		changeListView(true);

    	}
    	if (mList instanceof ExpandableListView) {
            ((ExpandableListView)mList).setAdapter(adapter);
            if (!mListShown && !hadAdapter) {
                // The list was hidden, and previously didn't have an
                // adapter.  It is now time to show it.
                setListShown(true, getView().getWindowToken() != null);
            }
        }

    }

    public boolean isListVisible(){
    	if(!listEnabled){
    		return false;
    	}
    	return mListShown;
    }

    /**
     * Call this to permanently disable the list view components for this fragment.
     * Use this if eg you have overridden onCreateView and supplied a layout
     * which does not include a listview.
     * After calling this, listView methods such as setListAdapter etc will throw exceptions.
     */
    protected void enableListView(boolean enabled){
    	listEnabled=enabled;
    }

    protected boolean isListEnabled(){
    	return listEnabled;
    }

    /**
     * Set the currently selected list item to the specified
     * position with the adapter's data
     *
     * @param position
     */
    public void setSelection(int position) {
        ensureList();
        mList.setSelection(position);
    }

    /**
     * Get the position of the currently selected list item.
     */
    public int getSelectedItemPosition() {
        ensureList();
        return mList.getSelectedItemPosition();
    }

    /**
     * Get the cursor row ID of the currently selected list item.
     */
    public long getSelectedItemId() {
        ensureList();
        return mList.getSelectedItemId();
    }

    /**
     * Get the activity's list view widget.
     */
    public ListView getListView() {
        ensureList();
        return mList;
    }

    public ExpandableListView getExpandableListView() {
        ensureList();
        if (mList instanceof ExpandableListView){
        	return (ExpandableListView) mList;
        }
        return null;
    }

    /**
     * The default content for a ListFragment has a TextView that can
     * be shown when the list is empty.  If you would like to have it
     * shown, call this method to supply the text it should use.
     */
    public void setEmptyText(CharSequence text) {
        ensureList();
        if (mStandardEmptyView == null) {
            throw new IllegalStateException("Can't be used with a custom content view");
        }
        mStandardEmptyView.setText(text);
        if (mEmptyText == null && !StringUtils.isNullOrEmpty(text)) {
            mList.setEmptyView(mStandardEmptyView);
        }
        else if (StringUtils.isNullOrEmpty(text)){
        	mList.setEmptyView(null);
        }
        mEmptyText = text;
    }

    /**
     * Control whether the list is being displayed.  You can make it not
     * displayed if you are waiting for the initial data to show in it.  During
     * this time an indeterminant progress indicator will be shown instead.
     *
     *
Applications do not normally need to use this themselves.  The default
     * behavior of ListFragment is to start with the list not being shown, only
     * showing it once an adapter is given with {@link #setListAdapter(android.widget.ListAdapter)}.
     * If the list at that point had not been shown, when it does get shown
     * it will be do without the user ever seeing the hidden state.
     *
     * @param shown If true, the list view is shown; if false, the progress
     * indicator.  The initial value is true.
     */
    public void setListShown(boolean shown) {
        setListShown(shown, true);
    }

    /**
     * Like {@link #setListShown(boolean)}, but no animation is used when
     * transitioning from the previous state.
     */
    public void setListShownNoAnimation(boolean shown) {
        setListShown(shown, false);
    }

    /**
     * Control whether the list is being displayed.  You can make it not
     * displayed if you are waiting for the initial data to show in it.  During
     * this time an indeterminant progress indicator will be shown instead.
     *
     * @param shown If true, the list view is shown; if false, the progress
     * indicator.  The initial value is true.
     * @param animate If true, an animation will be used to transition to the
     * new state.
     */
    private void setListShown(boolean shown, boolean animate) {
        ensureList();
        if (mProgressContainer == null) {
            throw new IllegalStateException("Can't be used with a custom content view");
        }
        if (mListShown == shown) {
            return;
        }
        mListShown = shown;
        if (shown) {
            if (animate) {
                mProgressContainer.startAnimation(AnimationUtils.loadAnimation(
                        getActivity(), android.R.anim.fade_out));
                mListContainer.startAnimation(AnimationUtils.loadAnimation(
                        getActivity(), android.R.anim.fade_in));
            } else {
                mProgressContainer.clearAnimation();
                mListContainer.clearAnimation();
            }
            mProgressContainer.setVisibility(View.GONE);
            mListContainer.setVisibility(View.VISIBLE);
        } else {
            if (animate) {
                mProgressContainer.startAnimation(AnimationUtils.loadAnimation(
                        getActivity(), android.R.anim.fade_in));
                mListContainer.startAnimation(AnimationUtils.loadAnimation(
                        getActivity(), android.R.anim.fade_out));
            } else {
                mProgressContainer.clearAnimation();
                mListContainer.clearAnimation();
            }
            mProgressContainer.setVisibility(View.VISIBLE);
            mListContainer.setVisibility(View.GONE);
        }
    }

    /**
     * Get the ListAdapter associated with this activity's ListView.
     */
    public ListAdapter getListAdapter() {
        return mAdapter;
    }

    public ExpandableListAdapter getExpandableListAdapter(){
    	return mExpandableListAdapter;
    }

    private void ensureList() {
        if (mList != null || !listEnabled) {
            return;
        }
        View root = getView();
        if (root == null) {
            throw new IllegalStateException("Content view not yet created");
        }
        if (root instanceof ListView) {
            mList = (ListView)root;
        } else {
            mStandardEmptyView = (TextView)root.findViewById(INTERNAL_EMPTY_ID);
            if (mStandardEmptyView == null) {
                mEmptyView = root.findViewById(android.R.id.empty);
            } else {
                mStandardEmptyView.setVisibility(View.GONE);
            }
            mLoadingTextView = (TextView) root.findViewById(INTERNAL_LOADING_TEXT_ID);
            mProgressContainer = root.findViewById(INTERNAL_PROGRESS_CONTAINER_ID);
            mSpinnerProgressView = root.findViewById(R.id.progress_spinner);
            mErrorIconView = (ImageView) root.findViewById(R.id.progress_error_icon);
            mListContainer = root.findViewById(INTERNAL_LIST_CONTAINER_ID);
            View rawListView = root.findViewById(android.R.id.list);
            if(rawListView==null){
            	rawListView = root.findViewById(INTERNAL_EXPANDABLE_LIST_ID);
            }
            if (!(rawListView instanceof ListView)) {
                if (rawListView == null) {
                    throw new RuntimeException(
                            "Your content must have a ListView whose id attribute is " +
                            "'android.R.id.list'");
                }
                throw new RuntimeException(
                        "Content has view with id attribute 'android.R.id.list' "
                        + "that is not a ListView class");
            }
            mList = (ListView)rawListView;
            if (mEmptyView != null) {
                mList.setEmptyView(mEmptyView);
            } else if (mEmptyText != null) {
                mStandardEmptyView.setText(mEmptyText);
                mList.setEmptyView(mStandardEmptyView);
            }
        }
        mListShown = true;
        mList.setOnItemClickListener(mOnClickListener);
        if (mList instanceof ExpandableListView){
        	((ExpandableListView) mList).setOnChildClickListener(mOnChildClickListener);
        	((ExpandableListView) mList).setOnGroupClickListener(mOnGroupClickListener);
        }
        if (mAdapter != null && !isExpandableListView) {
            ListAdapter adapter = mAdapter;
            mAdapter = null;
            setListAdapter(adapter);
        }
        else if (mExpandableListAdapter != null && isExpandableListView) {
            ExpandableListAdapter adapter = mExpandableListAdapter;
            mExpandableListAdapter = null;
            setExpandableListAdapter(adapter);

        }
        else {
            // We are starting without an adapter, so assume we won't
            // have our data right away and start with the progress indicator.
            if (mProgressContainer != null) {
                setListShown(false, false);
            }
        }
        mHandler.post(mRequestFocus);
    }
}


text:
// This file was generated using Parlex's cpp_generator

#ifndef INCLUDED_FOR_COLLECTION_HPP
#define INCLUDED_FOR_COLLECTION_HPP

#include <optional>
#include <variant>
#include <vector>

#include "erased.hpp"

#include "parlex/detail/abstract_syntax_tree.hpp"
#include "parlex/detail/builtins.hpp"
#include "parlex/detail/document.hpp"

#include "plange_grammar.hpp"

namespace plc {

struct EXPRESSION;
struct IC;
struct IDENTIFIER;
struct IMPLICIT_TYPE_DEREFERENCE;
struct TYPE_DEREFERENCE;

struct FOR_COLLECTION {
	struct declaration {
		struct field_1_t_1_t {
			std::variant<
				erased<TYPE_DEREFERENCE>,
				erased<IMPLICIT_TYPE_DEREFERENCE>
			> field_1;

			std::vector<erased<IC>> field_2;

			explicit field_1_t_1_t(
				std::variant<
					erased<TYPE_DEREFERENCE>,
					erased<IMPLICIT_TYPE_DEREFERENCE>
				> && field_1, std::vector<erased<IC>> && field_2) : field_1(std::move(field_1)), field_2(std::move(field_2)) {}

			field_1_t_1_t(field_1_t_1_t const & other) = default;
			field_1_t_1_t(field_1_t_1_t && move) = default;

			static field_1_t_1_t build(parlex::detail::node const * b, parlex::detail::document::walk & w);
		};

		std::optional<field_1_t_1_t> field_1;

		erased<IDENTIFIER> field_2;

		explicit declaration(
			std::optional<field_1_t_1_t> && field_1, erased<IDENTIFIER> && field_2) : field_1(std::move(field_1)), field_2(std::move(field_2)) {}

		declaration(declaration const & other) = default;
		declaration(declaration && move) = default;

		static declaration build(parlex::detail::node const * b, parlex::detail::document::walk & w);
	};

	parlex::detail::document::text<literal_for_t> dontCare0;

	std::vector<erased<IC>> field_01;

	parlex::detail::document::text<literal_0x28_t> dontCare2;

	std::vector<erased<IC>> field_02;

	std::variant<
		declaration,
		erased<EXPRESSION>
	> field_03;

	std::vector<erased<IC>> field_04;

	std::variant<
		parlex::detail::document::text<literal_in_t>,
		parlex::detail::document::text<literal_0xE20x880x88_t>
	> field_05;

	std::vector<erased<IC>> field_06;

	erased<EXPRESSION> collection;

	std::vector<erased<IC>> field_07;

	parlex::detail::document::text<literal_0x29_t> dontCare10;

	std::vector<erased<IC>> field_08;

	erased<EXPRESSION> invoke;

	explicit FOR_COLLECTION(
		parlex::detail::document::text<literal_for_t> && dontCare0, std::vector<erased<IC>> && field_01, parlex::detail::document::text<literal_0x28_t> && dontCare2, std::vector<erased<IC>> && field_02, std::variant<
			declaration,
			erased<EXPRESSION>
		> && field_03, std::vector<erased<IC>> && field_04, std::variant<
			parlex::detail::document::text<literal_in_t>,
			parlex::detail::document::text<literal_0xE20x880x88_t>
		> && field_05, std::vector<erased<IC>> && field_06, erased<EXPRESSION> && collection, std::vector<erased<IC>> && field_07, parlex::detail::document::text<literal_0x29_t> && dontCare10, std::vector<erased<IC>> && field_08, erased<EXPRESSION> && invoke) : dontCare0(std::move(dontCare0)), field_01(std::move(field_01)), dontCare2(std::move(dontCare2)), field_02(std::move(field_02)), field_03(std::move(field_03)), field_04(std::move(field_04)), field_05(std::move(field_05)), field_06(std::move(field_06)), collection(std::move(collection)), field_07(std::move(field_07)), dontCare10(std::move(dontCare10)), field_08(std::move(field_08)), invoke(std::move(invoke)) {}

	FOR_COLLECTION(FOR_COLLECTION const & other) = default;
	FOR_COLLECTION(FOR_COLLECTION && move) = default;

	static FOR_COLLECTION build(parlex::detail::ast_node const & n);
	static parlex::detail::state_machine const & state_machine();

};

} // namespace plc

#endif //INCLUDED_FOR_COLLECTION_HPP

redpajama_set_name: RedPajamaGithub


text:
package ch.thn.gedcom.familytree;

import java.util.List;

import ch.thn.gedcom.creator.GedcomCreatorStructureStorage;
import ch.thn.gedcom.creator.GedcomEnums.Sex;
import ch.thn.gedcom.creator.structures.GedcomFamily;
import ch.thn.gedcom.creator.structures.GedcomIndividual;

/**
 *
 * @author Thomas Naeff (github.com/thnaeff)
 *
 */
public class GedcomToFamilyTree {

  private GedcomCreatorStructureStorage structureStorage = null;

  private FamilyTree familyTree = null;

  public GedcomToFamilyTree(GedcomCreatorStructureStorage structureStorage) {
    this.structureStorage = structureStorage;

  }

  /**
   *
   *
   * @return
   */
  public GedcomCreatorStructureStorage getStorage() {
    return structureStorage;
  }

  /**
   * Returns the family tree structure (the first node of the tree).
   *
   * @return
   */
  public FamilyTree getFamilyTree() {
    return familyTree;
  }

  /**
   * Build the family tree using the added individuals and families. The starting
   * individual of the tree will be the one which has the given individual ID
   *
   * @param individualId The ID to start with
   * @return
   * @throws GedcomToFamilytreeError If there is no individual with the given ID
   */
  public FamilyTree buildFamilyTree(String individualId) {
    return buildFamilyTree(individualId, null);
  }

  /**
   * Build the family tree using the added individuals and families. The starting
   * individual of the tree will be the one which has the given individual ID
   *
   * @param individualId The ID to start with
   * @param treeTitle
   * @return
   * @throws GedcomToFamilytreeError If there is no individual with the given ID
   */
  public FamilyTree buildFamilyTree(String individualId, String treeTitle) {

    if (!structureStorage.hasIndividual(individualId)) {
      throw new GedcomToFamilytreeError("Failed to build family tree. Individual with ID " +
          individualId + " does not exist.");
    }

    if (structureStorage.structuresModified()) {
      //Make sure the relations are built
      structureStorage.buildFamilyRelations();
    }

    FamilyTree familyTree = new FamilyTree(treeTitle);

    //Start building the tree by adding the first child
    addChild(familyTree, structureStorage.getIndividual(individualId));

    this.familyTree = familyTree;

    return familyTree;
  }

  /**
   * Add a child for building the family tree
   *
   * @param treeNode
   * @param child
   */
  private void addChild(FamilyTreeNode treeNode, GedcomIndividual child) {

    //Get all the links to this individuals families
    List<String> famsLinks = child.getSpouseFamilyLinks();

    //No family for this individual
    if (famsLinks == null || famsLinks.size() == 0) {
      addOneIndividualFamily(treeNode, child);
      return;
    }

    boolean familyAdded = false;

    //Process the family (or families) for this individual
    for (String famXRef : famsLinks) {
      if (famXRef == null || famXRef.length() == 0) {
        //An empty FAMS link
        continue;
      }

      if (!structureStorage.hasFamily(famXRef)) {
        //				throw new GedcomToFamilytreeError("Individual " + childId + " is linked to family " +
        //						famXRef + ", but such a family has not been found. Family skipped.");
        System.err.println("Individual " + child.getId() + " is linked to family " +
            famXRef + ", but such a family has not been found. Family skipped.");
        continue;
      }

      GedcomFamily family = structureStorage.getFamily(famXRef);

      String husbXRef = family.getHusbandLink();
      String wifeXRef = family.getWifeLink();
      List<String> childXRefs = family.getChildLinks();

      addFamily(treeNode, husbXRef, wifeXRef, child.getId(), childXRefs);

      familyAdded = true;
    }

    if (!familyAdded) {
      addOneIndividualFamily(treeNode, child);
    }
  }

  /**
   *
   *
   * @param treeNode
   * @param indi
   */
  private void addOneIndividualFamily(FamilyTreeNode treeNode, GedcomIndividual indi) {
    String husbXRef = null;
    String wifeXRef = null;

    Sex sex = indi.getSex();

    if (sex == Sex.FEMALE) {
      wifeXRef = indi.getId();
    } else {
      //Assume a male individual if set is not set and it is not a female
      husbXRef = indi.getId();
    }

    addFamily(treeNode, husbXRef, wifeXRef, indi.getId(), null);
  }

  /**
   * Add a family for building the family tree
   *
   * @param treeNode
   * @param husbXRef
   * @param wifeXRef
   * @param childOfParentsId The ID of the husband or wife which is the child
   * of the parents of this new family -> childOfParentsId matches either husbXRef
   * or wifeXRef
   * @param childXRefs
   */
  private void addFamily(FamilyTreeNode treeNode, String husbXRef, String wifeXRef,
      String childOfParentsId, List<String> childXRefs) {

    GedcomIndividual husband = null;
    GedcomIndividual wife = null;

    if (husbXRef != null) {
      if (!structureStorage.hasIndividual(husbXRef)) {
        System.out.println("Can not create family with husband " + husbXRef +
            ", wife " + wifeXRef + " and children " + childXRefs +
            ". ID of husband not found.");
        return;
      }

      husband = structureStorage.getIndividual(husbXRef);
    }

    if (wifeXRef != null) {
      if (!structureStorage.hasIndividual(wifeXRef)) {
        System.out.println("Can not create family with husband " + husbXRef +
            ", wife " + wifeXRef + " and children " + childXRefs +
            ". ID of wife not found.");
        return;
      }

      wife = structureStorage.getIndividual(wifeXRef);
    }

    FamilyTreeNode newNode = null;
    GedcomFamily family = structureStorage.getFamilyOfParents(husbXRef, wifeXRef);

    //
    if (childOfParentsId.equals(husbXRef)) {
      newNode = new FamilyTreeNode(husband, wife, family);
    } else {
      newNode = new FamilyTreeNode(wife, husband, family);
    }

    treeNode.addChildNode(newNode);

    if (childXRefs != null && childXRefs.size() > 0) {
      //Add all the children of this family
      for (String childXRef : childXRefs) {
        if (structureStorage.hasIndividual(childXRef)) {
          addChild(newNode, structureStorage.getIndividual(childXRef));
        }
      }
    }

  }

}


text:
---
uid: SolidEdgePart.PartDocument.QueryByProperty(SolidEdgePart.PropertyTableConstants,System.Object,System.Object,System.Object,System.Object,System.Object)
summary:
remarks:
syntax:
    parameters:
    - id: NumProps
      description: When the QueryType is seCustomPropertyQueryByNameAndValue, NumProps specifies the number of PropName-PropType-PropValue sets for which you are searching.
    - id: PropName
      description: When the QueryType is seCustomPropertyQueryByNameAndValue or seCustomPropertyQueryByTable, PropName specifies the array of AttachedProperty.Name strings for which you are searching.
    - id: PropType
      description: When the QueryType is seCustomPropertyQueryByNameAndValue or seCustomPropertyQueryByTable, PropType specifies the array of AttachedProperty.Type constants for which you are searching.
    - id: PropVal
      description: When the QueryType is seCustomPropertyQueryByNameAndValue, PropVal specifies the array of AttachedProperty.Value for which you are searching.
    - id: QueryType
      description: Specifies the type of query to perform. Valid values are members of the PropertyTableConstants constant set. With seCustomPropertyQueryAllProperties, TableName is ignored. With seCustomPropertyQueryByTable, the TableName and any custom property name/value pairs specified are searched for exact matches. With seCustomPropertyQueryByNameAndValue, only custom property name/value pairs are searched, and matches with all name/value pairs are returned.
    - id: TableName
      description: When the QueryType is seCustomPropertyQueryByTable, TableName specifies the AttachedPropertyTable.Name for which you are searching.
---


text:
export {
  SkyDefinitionListValueComponent
} from '@skyux/layout/modules/definition-list/definition-list-value.component';


text:
<?php

namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\ClassMetadataFactory;
use Doctrine\Persistence\Mapping\Driver\MappingDriver;
use PHPUnit\Framework\TestCase;

/**
 * @group DDC-2359
 */
class DDC2359Test extends TestCase
{

    /**
     * Verifies that {@see \Doctrine\ORM\Mapping\ClassMetadataFactory::wakeupReflection} is
     * not called twice when loading metadata from a driver
     */
    public function testIssue()
    {
        $mockDriver      = $this->createMock(MappingDriver::class);
        $mockMetadata    = $this->createMock(ClassMetadata::class);
        $entityManager   = $this->createMock(EntityManager::class);

        /* @var $metadataFactory \Doctrine\ORM\Mapping\ClassMetadataFactory|\PHPUnit_Framework_MockObject_MockObject */
        $metadataFactory = $this->getMockBuilder(ClassMetadataFactory::class)
                                ->setMethods(['newClassMetadataInstance', 'wakeupReflection'])
                                ->getMock();

        $configuration = $this->getMockBuilder(Configuration::class)
                              ->setMethods(['getMetadataDriverImpl'])
                              ->getMock();

        $connection = $this->createMock(Connection::class);

        $configuration
            ->expects($this->any())
            ->method('getMetadataDriverImpl')
            ->will($this->returnValue($mockDriver));

        $entityManager->expects($this->any())->method('getConfiguration')->will($this->returnValue($configuration));
        $entityManager->expects($this->any())->method('getConnection')->will($this->returnValue($connection));
        $entityManager
            ->expects($this->any())
            ->method('getEventManager')
            ->will($this->returnValue($this->createMock(EventManager::class)));

        $metadataFactory->expects($this->any())->method('newClassMetadataInstance')->will($this->returnValue($mockMetadata));
        $metadataFactory->expects($this->once())->method('wakeupReflection');

        $metadataFactory->setEntityManager($entityManager);

        $this->assertSame($mockMetadata, $metadataFactory->getMetadataFor(DDC2359Foo::class));
    }
}

/** @Entity */
class DDC2359Foo
{
    /** @Id @Column(type="integer") @GeneratedValue */
    public $id;
}


text:
require 'ansible/ruby/modules/base'

module Ansible
  module Ruby
    module Modules
      # Manages Homebrew casks.
      class Homebrew_cask < Base
        # @return [String] name of cask to install/remove
        attribute :name
        validates :name, presence: true, type: String

        # @return [String, nil] ':' separated list of paths to search for 'brew' executable.
        attribute :path
        validates :path, type: String

        # @return [:present, :absent, :upgraded, nil] state of the cask
        attribute :state
        validates :state, expression_inclusion: {:in=>[:present, :absent, :upgraded], :message=>"%{value} needs to be :present, :absent, :upgraded"}, allow_nil: true

        # @return [:yes, :no, nil] update homebrew itself first. Note that C(brew cask update) is a synonym for C(brew update).
        attribute :update_homebrew
        validates :update_homebrew, expression_inclusion: {:in=>[:yes, :no], :message=>"%{value} needs to be :yes, :no"}, allow_nil: true

        # @return [Array<String>, String, nil] options flags to install a package
        attribute :install_options
        validates :install_options, type: TypeGeneric.new(String)

        # @return [:yes, :no, nil] allow external apps
        attribute :accept_external_apps
        validates :accept_external_apps, expression_inclusion: {:in=>[:yes, :no], :message=>"%{value} needs to be :yes, :no"}, allow_nil: true

        # @return [:yes, :no, nil] upgrade all casks (mutually exclusive with `upgrade`)
        attribute :upgrade_all
        validates :upgrade_all, expression_inclusion: {:in=>[:yes, :no], :message=>"%{value} needs to be :yes, :no"}, allow_nil: true

        # @return [:yes, :no, nil] upgrade all casks (mutually exclusive with `upgrade_all`)
        attribute :upgrade
        validates :upgrade, expression_inclusion: {:in=>[:yes, :no], :message=>"%{value} needs to be :yes, :no"}, allow_nil: true

        # @return [:yes, :no, nil] upgrade casks that auto update; passes --greedy to brew cask outdated when checking if an installed cask has a newer version available
        attribute :greedy
        validates :greedy, expression_inclusion: {:in=>[:yes, :no], :message=>"%{value} needs to be :yes, :no"}, allow_nil: true
      end
    end
  end
end


text:
package common

import java.util.UUID

import akka.actor.ActorSystem

import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory

import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers

import scala.annotation.tailrec
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import scala.concurrent.duration._
import scala.language.postfixOps
import scala.util.{Failure, Success}

import common.FutureExtensions._

class FutureExtensionsTest extends AnyFunSuite with Matchers {
  val testConfig = ConfigFactory.load("test.conf")
  val futureExtensionsDispatcherPath = Option("akka.actor.future-extensions-dispatcher")

  test("future with timeout > success") {
    withTimeout(config = testConfig,
                dispatcherPath = futureExtensionsDispatcherPath,
                akkaTimeout = 3 seconds,
                futureSleep = 2 seconds).onComplete {
      case Success(result) => result shouldBe true
      case Failure(_) => fail("*** future with timeout > failed")
    }
  }

  test("future with timeout > failure") {
    withTimeout(config = testConfig,
                dispatcherPath = futureExtensionsDispatcherPath,
                akkaTimeout = 2 seconds,
                futureSleep = 3 seconds).onComplete {
      case Success(_) => fail("*** future with timeout > succeeded, when it should've failed!")
      case Failure(error) => error.getMessage.nonEmpty shouldBe true
    }
  }

  test("future factorial > success") {
    implicit val system = ActorSystem(UUID.randomUUID.toString, testConfig)
    implicit val dispatcher = futureExtensionsDispatcherPath match {
      case Some(path) => system.dispatchers.lookup(path)
      case None => system.dispatcher
    }
    implicit val timeout = 3 seconds

    Future {
      factorial(9)
    }.withTimeout(new TimeoutException("Future timed out!")).onComplete {
      case Success(result) => result shouldBe 362880
      case Failure(_) => fail("*** Future factorial test failed!")
    }
  }

  def withTimeout(config: Config,
                  dispatcherPath: Option[String],
                  akkaTimeout: FiniteDuration,
                  futureSleep: FiniteDuration): Future[Boolean] = {
    implicit val system = ActorSystem(UUID.randomUUID.toString, config)
    implicit val dispatcher = dispatcherPath match {
      case Some(path) => system.dispatchers.lookup(path)
      case None => system.dispatcher
    }
    implicit val timeout = akkaTimeout

    lazy val future = Future {
      Thread.sleep(futureSleep.toMillis)
      true
    }
    future.withTimeout(new TimeoutException("Future timed out!"))
  }

  @tailrec
  final def factorial(n: Long, acc: Long = 1): Long = n match {
    case i if i < 1 => acc
    case _ => factorial(n - 1, acc * n)
  }
}


text:
package com.bbn.nlp.corenlp;

import com.bbn.bue.common.strings.offsets.CharOffset;
import com.bbn.bue.common.strings.offsets.OffsetRange;
import com.bbn.bue.common.symbols.Symbol;
import com.bbn.nlp.ConstituentNode;
import com.bbn.nlp.parsing.HeadFinder;

import com.google.common.annotations.Beta;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;

import java.util.Iterator;
import java.util.List;
import java.util.Stack;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

/**
 * Represents a node and data from the StanfordParser, at least from basic XML output. The parent is
 * default Optional.absent() and for child Y of node X, can only be set by the builderForNonTerminal
 * of X.
 */
@Beta
public final class CoreNLPParseNode
        implements ConstituentNode<CoreNLPParseNode, CoreNLPParseNodeData> {

    private final Symbol tag;
    private final ImmutableList<CoreNLPParseNode> children;
    private Optional<CoreNLPParseNode> parent = Optional.absent();
    private final Optional<CoreNLPParseNode> head;
    private final Optional<CoreNLPParseNodeData> data = Optional.absent();
    private final Optional<OffsetRange<CharOffset>> span;
    private final Optional<CoreNLPToken> token;

    private CoreNLPParseNode(final Symbol tag, final List<CoreNLPParseNode> children,
                             final Optional<CoreNLPParseNode> head, final Optional<CoreNLPToken> token,
                             final Optional<OffsetRange<CharOffset>> span) {
        this.head = checkNotNull(head);
        this.token = checkNotNull(token);
        this.tag = checkNotNull(tag);
        this.children = ImmutableList.copyOf(children);
        this.span = span;
    }

    private static CoreNLPParseNode create(final Symbol tag, final List<CoreNLPParseNode> children,
                                          final Optional<CoreNLPParseNode> head, final Optional<CoreNLPToken> token,
                                          final Optional<OffsetRange<CharOffset>> span) {
        return new CoreNLPParseNode(tag, children, head, token, span);
    }

    public static CoreNLPParseNode create(final Symbol tag, final List<CoreNLPParseNode> children,
                                          final Optional<CoreNLPParseNode> head, final Optional<CoreNLPToken> token) {
        final Optional<OffsetRange<CharOffset>> span;
        if (children.isEmpty()) {
            checkState(children.isEmpty(), "if we have a data we must be a terminal node!");
            if (token.isPresent()) {
                span = Optional.of(token.get().offsets());
            } else {
                span = Optional.absent();
            }
        } else {
            // we have to have a span if we're a non-terminal node, and we're sticking to that.
            Optional<CharOffset> start = Optional.absent();
            for (final CoreNLPParseNode child : children) {
                if (child.span().isPresent()) {
                    start = Optional.of(child.span().get().startInclusive());
                    break;
                }
            }
            Optional<CharOffset> end = Optional.absent();
            for (final CoreNLPParseNode child : ImmutableList.copyOf(children).reverse()) {
                if (child.span.isPresent()) {
                    end = Optional.of(child.span().get().endInclusive());
                    break;
                }
            }
            if (start.isPresent()) {
                span = Optional.of(OffsetRange.charOffsetRange(start.get().asInt(), end.get().asInt()));
            } else {
                span = Optional.absent();
            }
        }
        checkArgument(!span.isPresent() || span.get().startInclusive().asInt() <= span.get().endInclusive().asInt(),
                "Span lengths inconsistent!");
        return create(tag, children, head, token, span);
    }

    @Override
    public Symbol tag() {
        return tag;
    }

    @Override
    public ImmutableList<CoreNLPParseNode> children() {
        return children;
    }

    @Override
    public Optional<CoreNLPParseNodeData> nodeData() {
        return data;
    }

    @Override
    public boolean terminal() {
        return children().isEmpty();
    }

    @Override
    public Optional<CoreNLPParseNode> parent() {
        return parent;
    }

    private void setParent(final CoreNLPParseNode parent) {
        checkState(!this.parent.isPresent(), "Parent node may not be set twice!");
        this.parent = Optional.of(parent);
    }

    @Override
    public Optional<CoreNLPParseNode> immediateHead() {
        if (terminal()) {
            return Optional.absent();
        }
        return head;
    }

    public Optional<CoreNLPToken> token() {
        return token;
    }

    /**
     * Resolves a head down to a terminal node. A terminal node is its own head here.
     */
    public Optional<CoreNLPParseNode> terminalHead() {
        if (terminal()) {
            return Optional.of(this);
        }
        if (immediateHead().isPresent()) {
            return immediateHead().get().terminalHead();
        }
        return Optional.absent();
    }

    @Override
    public String toString() {
        return "CoreNLPParseNode{" +
                "tag=" + tag +
                ", children=" + children +
                ", head=" + head +
                ", data=" + data +
                ", terminal=" + terminal() +
                '}';
    }

    /**
     * If terminal: span of the CoreNLPToken; else: span from the start of the first child to the
     * end of the last.
     */
    public Optional<OffsetRange<CharOffset>> span() {
        return span;
    }

    public static CoreNLPParseNodeBuilder buildForTerminal() {
        return new CoreNLPParseNodeBuilder(null);
    }

    public static CoreNLPParseNodeBuilder builderForNonTerminal(
            final HeadFinder<CoreNLPParseNode> headFinder) {
        return new CoreNLPParseNodeBuilder(headFinder);
    }

    public static class CoreNLPParseNodeBuilder {

        private final HeadFinder<CoreNLPParseNode> headFinder;

        private Symbol tag;
        private List<CoreNLPParseNode> children = Lists.newArrayList();
        private Optional<String> text = Optional.absent();
        private Optional<CoreNLPToken> token = Optional.absent();

        private CoreNLPParseNodeBuilder(final HeadFinder<CoreNLPParseNode> headFinder) {
            this.headFinder = headFinder;
        }

        public CoreNLPParseNodeBuilder withTag(Symbol tag) {
            this.tag = tag;
            return this;
        }

        public CoreNLPParseNodeBuilder addChildren(final List<CoreNLPParseNode> children) {
            this.children.addAll(checkNotNull(children));
            return this;
        }

        public CoreNLPParseNodeBuilder addChildren(final CoreNLPParseNode... children) {
            for (final CoreNLPParseNode child : children) {
                this.children.add(checkNotNull(child));
            }
            return this;
        }

        public CoreNLPParseNodeBuilder withText(Optional<String> text) {
            this.text = text;
            return this;
        }

        public CoreNLPParseNodeBuilder withToken(Optional<CoreNLPToken> token) {
            this.token = token;
            return this;
        }

        public CoreNLPParseNode build() {
            // we impose no requirement that text or token is present; verbs, noun phrases, etc., can all get dropped and parsers may find where they belonged.
            if (text.isPresent() && token.isPresent()) {
                checkState(text.get().equals(token.get().content()),
                        "if we have both text and a data they must be the same, but instead we have " + text
                                .get() + " and " + token.get().content());
            }
            final Optional<CoreNLPParseNode> head;
            if (children.isEmpty()) {
                head = Optional.absent();
            } else {
                head = headFinder.findHead(tag,
                        ImmutableList.copyOf(children));
            }
            final CoreNLPParseNode ret = create(tag, children, head, token);
            for (CoreNLPParseNode child : children) {
                child.setParent(ret);
            }
            return ret;
        }
    }

    public static Predicate<CoreNLPParseNode> isTerminal() {
        return new Predicate<CoreNLPParseNode>() {
            @Override
            public boolean apply(final CoreNLPParseNode input) {
                return input.terminal();
            }
        };
    }

    public Iterable<CoreNLPParseNode> preorderDFSTraversal() {
        return new Iterable<CoreNLPParseNode>() {
            @Override
            public Iterator<CoreNLPParseNode> iterator() {
                return new PreorderTraversal();
            }
        };
    }

    private class PreorderTraversal implements Iterator<CoreNLPParseNode> {

        private final Stack<CoreNLPParseNode> nodes = new Stack<>();

        public PreorderTraversal() {
            nodes.push(CoreNLPParseNode.this);
        }

        @Override
        public boolean hasNext() {
            return nodes.size() > 0;
        }

        @Override
        public CoreNLPParseNode next() {
            final CoreNLPParseNode n = nodes.pop();
            // reverse the nodes so we get everything in order; this is a stack after all
            for (final CoreNLPParseNode m : n.children().reverse()) {
                nodes.push(m);
            }
            return n;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException("Parses are immutable once created");
        }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.TestFramework;
using Azure.ResourceManager.CosmosDB.Models;
using NUnit.Framework;

namespace Azure.ResourceManager.CosmosDB.Tests
{
    public class SqlTriggerTests : CosmosDBManagementClientBase
    {
        private CosmosDBAccountResource _databaseAccount;
        private CosmosDBSqlDatabaseResource _sqlDatabase;
        private ResourceIdentifier _sqlContainerId;
        private CosmosDBSqlContainerResource _sqlContainer;
        private string _triggerName;

        public SqlTriggerTests(bool isAsync) : base(isAsync)
        {
        }

        protected CosmosDBSqlTriggerCollection SqlTriggerCollection => _sqlContainer.GetCosmosDBSqlTriggers();

        [OneTimeSetUp]
        public async Task GlobalSetup()
        {
            IgnoreTestInNonWindowsAgent();

            _resourceGroup = await GlobalClient.GetResourceGroupResource(_resourceGroupIdentifier).GetAsync();

            _databaseAccount = await CreateDatabaseAccount(SessionRecording.GenerateAssetName("dbaccount-"), CosmosDBAccountKind.GlobalDocumentDB);

            _sqlDatabase = await SqlDatabaseTests.CreateSqlDatabase(SessionRecording.GenerateAssetName("sql-db-"), null, _databaseAccount.GetCosmosDBSqlDatabases());

            _sqlContainerId = (await SqlContainerTests.CreateSqlContainer(SessionRecording.GenerateAssetName("sql-container-"), null, _sqlDatabase.GetCosmosDBSqlContainers())).Id;

            await StopSessionRecordingAsync();
        }

        [OneTimeTearDown]
        public void GlobalTeardown()
        {
            _sqlContainer.Delete(WaitUntil.Completed);
            _sqlDatabase.Delete(WaitUntil.Completed);
            _databaseAccount.Delete(WaitUntil.Completed);
        }

        [SetUp]
        public async Task SetUp()
        {
            _sqlContainer = await ArmClient.GetCosmosDBSqlContainerResource(_sqlContainerId).GetAsync();
        }

        [TearDown]
        public async Task TearDown()
        {
            if (await SqlTriggerCollection.ExistsAsync(_triggerName))
            {
                var id = SqlTriggerCollection.Id;
                id = CosmosDBSqlTriggerResource.CreateResourceIdentifier(id.SubscriptionId, id.ResourceGroupName, id.Parent.Parent.Name, id.Parent.Name, id.Name, _triggerName);
                CosmosDBSqlTriggerResource trigger = this.ArmClient.GetCosmosDBSqlTriggerResource(id);
                await trigger.DeleteAsync(WaitUntil.Completed);
            }
        }

        [Test]
        [RecordedTest]
        public async Task SqlTriggerCreateAndUpdate()
        {
            var trigger = await CreateSqlTrigger(null);
            Assert.AreEqual(_triggerName, trigger.Data.Resource.TriggerName);
            Assert.That(trigger.Data.Resource.Body, Contains.Substring("First Hello World"));
            Assert.AreEqual(trigger.Data.Resource.TriggerOperation, CosmosDBSqlTriggerOperation.All);
            Assert.AreEqual(trigger.Data.Resource.TriggerType, CosmosDBSqlTriggerType.Pre);

            // Seems bug in swagger definition
            //Assert.AreEqual(TestThroughput1, container.Data.Options.Throughput);

            bool ifExists = await SqlTriggerCollection.ExistsAsync(_triggerName);
            Assert.True(ifExists);

            CosmosDBSqlTriggerResource trigger2 = await SqlTriggerCollection.GetAsync(_triggerName);
            Assert.AreEqual(_triggerName, trigger2.Data.Resource.TriggerName);

            VerifySqlTriggers(trigger, trigger2);

            var updateOptions = new CosmosDBSqlTriggerCreateOrUpdateContent(AzureLocation.WestUS, new Models.CosmosDBSqlTriggerResourceInfo(_triggerName)
            {
                TriggerOperation = CosmosDBSqlTriggerOperation.Create,
                TriggerType = CosmosDBSqlTriggerType.Post,
                Body = @"function () { var updatetext = getContext();
    var response = context.getResponse();
    response.setBody('Second Hello World');
}"
            });

            trigger = (await SqlTriggerCollection.CreateOrUpdateAsync(WaitUntil.Completed, _triggerName, updateOptions)).Value;
            Assert.AreEqual(_triggerName, trigger.Data.Resource.TriggerName);
            Assert.That(trigger.Data.Resource.Body, Contains.Substring("Second Hello World"));
            Assert.AreEqual(trigger.Data.Resource.TriggerOperation, CosmosDBSqlTriggerOperation.Create);
            Assert.AreEqual(trigger.Data.Resource.TriggerType, CosmosDBSqlTriggerType.Post);

            trigger2 = await SqlTriggerCollection.GetAsync(_triggerName);
            VerifySqlTriggers(trigger, trigger2);
        }

        [Test]
        [RecordedTest]
        public async Task SqlTriggerList()
        {
            var trigger = await CreateSqlTrigger(null);

            var triggers = await SqlTriggerCollection.GetAllAsync().ToEnumerableAsync();
            Assert.That(triggers, Has.Count.EqualTo(1));
            Assert.AreEqual(trigger.Data.Name, triggers[0].Data.Name);

            VerifySqlTriggers(triggers[0], trigger);
        }

        [Test]
        [RecordedTest]
        public async Task SqlTriggerDelete()
        {
            var trigger = await CreateSqlTrigger(null);
            await trigger.DeleteAsync(WaitUntil.Completed);

            bool exists = await SqlTriggerCollection.ExistsAsync(_triggerName);
            Assert.IsFalse(exists);
        }

        internal async Task<CosmosDBSqlTriggerResource> CreateSqlTrigger(AutoscaleSettings autoscale)
        {
            _triggerName = Recording.GenerateAssetName("sql-trigger-");
            var sqlDatabaseCreateUpdateOptions = new CosmosDBSqlTriggerCreateOrUpdateContent(AzureLocation.WestUS,
                new Models.CosmosDBSqlTriggerResourceInfo(_triggerName)
                {
                    TriggerOperation = CosmosDBSqlTriggerOperation.All,
                    TriggerType = CosmosDBSqlTriggerType.Pre,
                    Body = @"function () {
    var updatetext = getContext();
    var response = context.getResponse();
    response.setBody('First Hello World');
}"
                })
            {
                Options = BuildDatabaseCreateUpdateOptions(TestThroughput1, autoscale),
            };
            var sqlContainerLro = await SqlTriggerCollection.CreateOrUpdateAsync(WaitUntil.Completed, _triggerName, sqlDatabaseCreateUpdateOptions);
            return sqlContainerLro.Value;
        }

        private void VerifySqlTriggers(CosmosDBSqlTriggerResource expectedValue, CosmosDBSqlTriggerResource actualValue)
        {
            Assert.AreEqual(expectedValue.Id, actualValue.Id);
            Assert.AreEqual(expectedValue.Data.Name, actualValue.Data.Name);
            Assert.AreEqual(expectedValue.Data.Resource.TriggerName, actualValue.Data.Resource.TriggerName);
            Assert.AreEqual(expectedValue.Data.Resource.Rid, actualValue.Data.Resource.Rid);
            Assert.AreEqual(expectedValue.Data.Resource.Timestamp, actualValue.Data.Resource.Timestamp);
            Assert.AreEqual(expectedValue.Data.Resource.ETag, actualValue.Data.Resource.ETag);
            Assert.AreEqual(expectedValue.Data.Resource.Body, actualValue.Data.Resource.Body);
            Assert.AreEqual(expectedValue.Data.Resource.TriggerType, actualValue.Data.Resource.TriggerType);
            Assert.AreEqual(expectedValue.Data.Resource.TriggerOperation, actualValue.Data.Resource.TriggerOperation);
        }
    }
}


text:
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/io/openni_camera/openni_driver.h>
#include <pcl/console/parse.h>
#include <pcl/common/time.h>
#include <pcl/surface/mls.h>

#include <mutex>

#define FPS_CALC(_WHAT_) \
do \
{ \
    static unsigned count = 0;\
    static double last = pcl::getTime ();\
    double now = pcl::getTime (); \
    ++count; \
    if (now - last >= 1.0) \
    { \
      std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" <<  std::endl; \
      count = 0; \
      last = now; \
      if (*stop_computing_) std::cout << "Press 's' to start computing!\n"; \
    } \
}while(false)

int default_polynomial_order = 0;
double default_search_radius = 0.0,
    default_sqr_gauss_param = 0.0;

template <typename PointType>
class OpenNISmoothing;

void keyboardEventOccurred (const pcl::visualization::KeyboardEvent &event,
                            void *stop_void)
{
  boost::shared_ptr<bool> stop = *static_cast<boost::shared_ptr<bool>*> (stop_void);
  if (event.getKeySym () == "s" && event.keyDown ())
  {
    *stop = ! *stop;
    if (*stop) std::cout << "Computing is now stopped!\n";
    else std::cout << "Computing commencing!\n";
  }
}

template <typename PointType>
class OpenNISmoothing
{
  public:
    using Cloud = pcl::PointCloud<PointType>;
    using CloudPtr = typename Cloud::Ptr;
    using CloudConstPtr = typename Cloud::ConstPtr;

    OpenNISmoothing (double search_radius, bool sqr_gauss_param_set, double sqr_gauss_param,
                     int polynomial_order, const std::string& device_id = "")
    : viewer ("PCL OpenNI MLS Smoothing")
    , device_id_(device_id)
    {
      // Start 4 threads
      smoother_.setSearchRadius (search_radius);
      if (sqr_gauss_param_set) smoother_.setSqrGaussParam (sqr_gauss_param);
      smoother_.setPolynomialOrder (polynomial_order);

      typename pcl::search::KdTree<PointType>::Ptr tree (new typename pcl::search::KdTree<PointType> ());
      smoother_.setSearchMethod (tree);

      viewer.createViewPort (0.0, 0.0, 0.5, 1.0, viewport_input_);
      viewer.setBackgroundColor (0, 0, 0, viewport_input_);
      viewer.createViewPort (0.5, 0.0, 1.0, 1.0, viewport_smoothed_);
      viewer.setBackgroundColor (0, 0, 0, viewport_smoothed_);

      stop_computing_.reset (new bool(true));
      cloud_.reset ();
      cloud_smoothed_.reset (new Cloud);
    }

    void
    cloud_cb_ (const CloudConstPtr& cloud)
    {
      FPS_CALC ("computation");

      mtx_.lock ();
      if (! *stop_computing_)
      {
        smoother_.setInputCloud (cloud);
        smoother_.process (*cloud_smoothed_);
      }
      cloud_ = cloud;
      mtx_.unlock ();
    }

    void
    run ()
    {
      pcl::Grabber* interface = new pcl::OpenNIGrabber (device_id_);

      std::function<void (const CloudConstPtr&)> f = [this] (const CloudConstPtr& cloud) { cloud_cb_ (cloud); };
      boost::signals2::connection c = interface->registerCallback (f);

      viewer.registerKeyboardCallback (keyboardEventOccurred, reinterpret_cast<void*> (&stop_computing_));

      interface->start ();

      while (!viewer.wasStopped ())
      {
        FPS_CALC ("visualization");
        viewer.spinOnce ();

        if (cloud_ && mtx_.try_lock ())
        {
          if (!viewer.updatePointCloud (cloud_, "input_cloud"))
            viewer.addPointCloud (cloud_, "input_cloud", viewport_input_);
          if (! *stop_computing_ && !viewer.updatePointCloud (cloud_smoothed_, "smoothed_cloud"))
            viewer.addPointCloud (cloud_smoothed_, "smoothed_cloud", viewport_smoothed_);
          mtx_.unlock ();
        }
      }

      interface->stop ();
    }

    pcl::MovingLeastSquares<PointType, PointType> smoother_;
    pcl::visualization::PCLVisualizer viewer;
    std::string device_id_;
    std::mutex mtx_;
    CloudConstPtr cloud_;
    CloudPtr cloud_smoothed_;
    int viewport_input_, viewport_smoothed_;
    boost::shared_ptr<bool> stop_computing_;
};

void
usage (char ** argv)
{
  std::cout << "usage: " << argv[0] << " <device_id> <options>\n\n"
            << "where options are:\n"
            << "                     -search_radius X = sphere radius to be used for finding the k-nearest neighbors used for fitting (default: " << default_search_radius << ")\n"
            << "                     -sqr_gauss_param X = parameter used for the distance based weighting of neighbors (recommended = search_radius^2) (default: " << default_sqr_gauss_param << ")\n"
            << "                     -polynomial_order X = order of the polynomial to be fit (0 means tangent estimation) (default: " << default_polynomial_order << ")\n";

  openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance ();
  if (driver.getNumberDevices () > 0)
  {
    for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx)
    {
      cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx)
              << ", connected: " << driver.getBus (deviceIdx) << " @ " << driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl;
      cout << "device_id may be #1, #2, ... for the first second etc device in the list or" << endl
           << "                 bus@address for the device connected to a specific usb-bus / address combination (works only in Linux) or" << endl
           << "                 <serial-number> (only in Linux and for devices which provide serial numbers)"  << endl;
    }
  }
  else
    cout << "No devices connected." << endl;
}

int
main (int argc, char ** argv)
{
  if (argc < 2)
  {
    usage (argv);
    return 1;
  }

  std::string arg (argv[1]);

  if (arg == "--help" || arg == "-h")
  {
    usage (argv);
    return 1;
  }

  // Command line parsing
  double search_radius = default_search_radius;
  double sqr_gauss_param = default_sqr_gauss_param;
  bool sqr_gauss_param_set = true;
  int polynomial_order = default_polynomial_order;

  pcl::console::parse_argument (argc, argv, "-search_radius", search_radius);
  if (pcl::console::parse_argument (argc, argv, "-sqr_gauss_param", sqr_gauss_param) == -1)
    sqr_gauss_param_set = false;
  pcl::console::parse_argument (argc, argv, "-polynomial_order", polynomial_order);

  pcl::OpenNIGrabber grabber (arg);
  if (grabber.providesCallback<pcl::OpenNIGrabber::sig_cb_openni_point_cloud_rgba> ())
  {
    OpenNISmoothing<pcl::PointXYZRGBA> v (search_radius, sqr_gauss_param_set, sqr_gauss_param,
                                          polynomial_order, arg);
    v.run ();
  }
  else
  {
    OpenNISmoothing<pcl::PointXYZ> v (search_radius, sqr_gauss_param_set, sqr_gauss_param,
                                      polynomial_order, arg);
    v.run ();
  }

  return (0);
}


text:
package com.fionapet.business.restclient;

import com.alibaba.fastjson.JSON;
import com.fionapet.business.entity.FosterRecordDetail;
import junit.framework.Assert;
import org.dubbo.x.consumer.Assertable;
import org.dubbo.x.consumer.RestClientTestCase;
import org.dubbo.x.entity.RestResultEnum;
import org.dubbo.x.facade.RestResult;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.ProcessingException;
import java.util.List;

/**
* Created by tom on 2016-07-25 09:32:31.
 */
public class FosterRecordDetailRestClient extends RestClientTestCase {
    private static final Logger LOGGER = LoggerFactory.getLogger(FosterRecordDetailRestClient.class);
    private static final String TOKEN = "fc5db3b3-4063-4a12-a511-880ba19e4b58";
    private static final String URL = "http://localhost:8818/api/v2/fosterrecorddetails";

    @Test(expected = ProcessingException.class)
    public void testList(){
         assertRequest(new Assertable() {
            @Override
            public void assertBlack(RestResult restResult) throws Exception {
                RestResult<List<FosterRecordDetail>> result = (RestResult<List<FosterRecordDetail>>)restResult;
                Assert.assertEquals(restResult.getCode(), RestResultEnum.OK.getCode());

                Assert.assertNotNull(result.getData());

                Assert.assertEquals(result.getData().size(), 0);

                LOGGER.info("FosterRecordDetail list:{}", JSON.toJSON(restResult));
            }
        }, URL, FosterRecordDetailRestClient.TOKEN);
    }

//    @Test(expected = ProcessingException.class)
//    public void testCreate(){
//        final FosterRecordDetail fosterRecordDetail = new FosterRecordDetail();
////        fosterRecordDetail.set*("*");
//
//        Response response = getBuilder(URL, fosterRecordDetailRestClient.TOKEN).post(Entity.entity(fosterRecordDetail, MediaType.APPLICATION_JSON));
//
//        assertRequest(new Assertable() {
//            @Override
//            public void assertBlack(RestResult restResult) throws Exception {
//                LOGGER.info("restResult:{}", restResult);
//                RestResult<HashMap> result = (RestResult<HashMap>)restResult;
//                Assert.assertEquals(restResult.getCode(), RestResultEnum.OK.getCode());
//
//                Assert.assertNotNull(result.getData());
//
//                LOGGER.info("result.getData():{}", result.getData().getClass());
//
//                Assert.assertNotNull(result.getData().get("id"));
//
//                LOGGER.info("list:{}", JSON.toJSON(restResult));
//            }
//        }, response);
//    }

}


text:
@interface WKTGeometryCollection : WKTGeometry {

    NSMutableArray *listGeometry;

}

- (id)init;

- (void)addGeometry:(WKTGeometry *)geometry;

- (void)removeGeometries;

- (NSArray *)getGeometries;

- (BOOL)isEqual:(WKTGeometryCollection *)otherGeometries;

- (void)copyTo:(WKTGeometryCollection *)otherGeometries;

- (NSString *)toWKT;

@end


text:
using System;
using System.IO;
using GroupDocs.Conversion.Options.Convert;

namespace GroupDocs.Conversion.Examples.CSharp.BasicUsage
{
    /// <summary>
    /// This example demonstrates how to convert DICOM file into PDF format.
    /// For more details about Digital Imaging and Communications in Medicine (.dicom) to Portable Document (.pdf) conversion please check this documentation article
    /// https://docs.groupdocs.com/conversion/net/convert-dicom-to-pdf
    /// </summary>
    internal static class ConvertDicomToPdf
    {
        public static void Run()
        {
            string outputFolder = Constants.GetOutputDirectoryPath();
            string outputFile = Path.Combine(outputFolder, "dicom-converted-to.pdf");

            // Load the source DICOM file
            using (Converter converter = new Converter(Constants.SAMPLE_DICOM))
            {
                PdfConvertOptions options = new PdfConvertOptions();
                // Save converted PDF file
                converter.Convert(outputFile, options);
            }

            Console.WriteLine("\nConversion to pdf completed successfully. \nCheck output in {0}", outputFolder);
        }
    }
}


text:
create table idm_system_owner
(
    id                   bytea        not null
        primary key,
    created              timestamp    not null,
    creator              varchar(255) not null,
    creator_id           bytea,
    modified             timestamp,
    modifier             varchar(255),
    modifier_id          bytea,
    original_creator     varchar(255),
    original_creator_id  bytea,
    original_modifier    varchar(255),
    original_modifier_id bytea,
    realm_id             bytea,
    transaction_id       bytea,
    external_id          varchar(255),
    owner_id             bytea        not null,
    system_id            bytea        not null
);

create index idx_idm_system_owner_system
    on idm_system_owner (system_id);

create index idx_idm_system_owner_gnt
    on idm_system_owner (owner_id);

create index idx_idm_system_owner_ext_id
    on idm_system_owner (external_id);

-- System owner audit
create table idm_system_owner_a
(
    id                     bytea  not null,
    rev                    bigint not null
        constraint fkdyjrou7sr2b75gbvdj1whr1uv
            references idm_audit,
    revtype                smallint,
    created                timestamp,
    created_m              boolean,
    creator                varchar(255),
    creator_m              boolean,
    creator_id             bytea,
    creator_id_m           boolean,
    modifier               varchar(255),
    modifier_m             boolean,
    modifier_id            bytea,
    modifier_id_m          boolean,
    original_creator       varchar(255),
    original_creator_m     boolean,
    original_creator_id    bytea,
    original_creator_id_m  boolean,
    original_modifier      varchar(255),
    original_modifier_m    boolean,
    original_modifier_id   bytea,
    original_modifier_id_m boolean,
    realm_id               bytea,
    realm_id_m             boolean,
    external_id            varchar(255),
    external_id_m          boolean,
    owner_id               bytea,
    owner_m                boolean,
    system_id              bytea,
    system_m               boolean,
    primary key (id, rev)
);

-- System owner by role
create table idm_system_owner_role
(
    id                   bytea        not null
        primary key,
    created              timestamp    not null,
    creator              varchar(255) not null,
    creator_id           bytea,
    modified             timestamp,
    modifier             varchar(255),
    modifier_id          bytea,
    original_creator     varchar(255),
    original_creator_id  bytea,
    original_modifier    varchar(255),
    original_modifier_id bytea,
    realm_id             bytea,
    transaction_id       bytea,
    external_id          varchar(255),
    owner_role_id        bytea        not null,
    system_id            bytea        not null
);

create index idx_idm_system_owner_role_system
    on idm_system_owner_role (system_id);

create index idx_idm_system_owner_role_role
    on idm_system_owner_role (owner_role_id);

create index idx_idm_system_owner_role_ext_id
    on idm_system_owner_role (external_id);

-- System owner by role audit
create table idm_system_owner_role_a
(
    id                     bytea  not null,
    rev                    bigint not null
        constraint fk7bhpd0tsh7ht7hflahrms4pjj
            references idm_audit,
    revtype                smallint,
    created                timestamp,
    created_m              boolean,
    creator                varchar(255),
    creator_m              boolean,
    creator_id             bytea,
    creator_id_m           boolean,
    modifier               varchar(255),
    modifier_m             boolean,
    modifier_id            bytea,
    modifier_id_m          boolean,
    original_creator       varchar(255),
    original_creator_m     boolean,
    original_creator_id    bytea,
    original_creator_id_m  boolean,
    original_modifier      varchar(255),
    original_modifier_m    boolean,
    original_modifier_id   bytea,
    original_modifier_id_m boolean,
    realm_id               bytea,
    realm_id_m             boolean,
    external_id            varchar(255),
    external_id_m          boolean,
    owner_role_id          bytea,
    owner_role_m           boolean,
    system_id              bytea,
    system_m               boolean,
    primary key (id, rev)
);


text:
const router = require('express').Router();

router.get('/', (req, res, next) => {
	res.render('app');
});

router.post('/', (req, res, next) => {
	/*
		TODO check forms and login, update session
	*/
});

module.exports = router;


text:
#ifndef __LZR_U901_BASE_NODE_HPP__
#define __LZR_U901_BASE_NODE_HPP__

#include <boost/foreach.hpp>
#define foreach BOOST_FOREACH

#include <sensor_msgs/LaserScan.h>

#include <pcl_ros/point_cloud.h>
#include <pcl/point_types.h>

#include <lzr_u901/range_to_point_converter.hpp>

class lzr_u901_base_node
{

	typedef lzr_u901_base_node self;
	typedef pcl::PointCloud<pcl::PointWithRange> PointCloud;

public:
	lzr_u901_base_node(ros::NodeHandle &nh,
					   const std::string &frame_id)
		: frame_id_(frame_id),
		  scan_pub_(nh.advertise<sensor_msgs::LaserScan>("scan", 1)),
		  point_cloud_pub_(nh.advertise<PointCloud>(nh.resolveName("point_cloud_u901"), 1))
	{}

protected:
	void publish_plane_as_laser_scan(const lzr_u901::scan &scan, const lzr_u901::scan::plane_t p)
	{
		using namespace lzr_u901;

		sensor_msgs::LaserScan scan_msg;
		scan_msg.header.stamp.fromNSec(1000*scan.time_received);
		scan_msg.header.frame_id = frame_id_;

		int num_ranges = scan::NUM_RANGES_PER_PLANE;

		scan_msg.angle_min = scan::angle_min();
		scan_msg.angle_max = scan::angle_max();
		scan_msg.angle_increment = scan::angle_increment();
		scan_msg.scan_time = 1/15.;
		scan_msg.time_increment = scan_msg.scan_time / (double)(num_ranges-1);
		scan_msg.range_min = 0;
		scan_msg.range_max = 15.;

		scan_msg.ranges.reserve(num_ranges);
		foreach (const scan::range &r, scan.plane(p))
		{
			scan_msg.ranges.push_back(scan::range_to_meters(r));
		}
		scan_pub_.publish(scan_msg);
	}

private:
	void append_to_point_cloud(pcl::PointCloud<pcl::PointWithRange> &cloud,
							   const float &x, const float &y, const float &z,
							   const float &r) const
	{
		pcl::PointWithRange p;
		p.x = x; p.y = y; p.z = z; p.range = r;

		cloud.push_back(p);
	}

protected:
	void publish_point_cloud(const lzr_u901::scan &scan)
	{
		using namespace lzr_u901;
		pcl::PointCloud<pcl::PointWithRange> cloud;
		cloud.header.frame_id = frame_id_;

		// populate cloud
		for (unsigned p = scan::PLANE_0; p < scan::NUM_PLANES; ++p)
		{
			point_converter_.convert(scan::plane_t(p), scan.plane(scan::plane_t(p)), boost::bind(&self::append_to_point_cloud, this, boost::ref(cloud), _1, _2, _3, _4));
		}

		point_cloud_pub_.publish(cloud);
	}

	void handle_scan(const lzr_u901::scan &scan)
	{
		using namespace lzr_u901;

		publish_plane_as_laser_scan(scan, scan::PLANE_0);
		publish_point_cloud(scan);
	}

private:
	std::string frame_id_;
	ros::Publisher scan_pub_;

	lzr_u901::range_to_point_converter point_converter_;
	ros::Publisher point_cloud_pub_;
};

#endif // __LZR_U901_BASE_NODE_HPP__


text:
namespace gtxilib {
namespace oopclasses {
namespace protos {

std::string StringListProto::values(int index) const {
  return values_[index];
}
const std::vector<std::string>& StringListProto::values() const {
  return values_;
}
bool StringListProto::has_values() const {
  return has_values_;
}
void StringListProto::clear_values() {
  values_.clear();
  has_values_ = false;
}
void StringListProto::set_values(int index, std::string new_values) {
  values_[index] = new_values;
  has_values_ = true;
}
std::string* StringListProto::mutable_values(int index) {
  has_values_ = true;
  return &values_[index];
}
void StringListProto::add_values(std::string new_values) {
  values_.push_back(new_values);
  has_values_ = true;
}
int StringListProto::values_size() const {
  return values_.size();
}

int32_t IntListProto::values(int index) const {
  return values_[index];
}
const std::vector<int32_t>& IntListProto::values() const {
  return values_;
}
bool IntListProto::has_values() const {
  return has_values_;
}
void IntListProto::clear_values() {
  values_.clear();
  has_values_ = false;
}
void IntListProto::set_values(int index, int32_t new_values) {
  values_[index] = new_values;
  has_values_ = true;
}
int32_t* IntListProto::mutable_values(int index) {
  has_values_ = true;
  return &values_[index];
}
void IntListProto::add_values(int32_t new_values) {
  values_.push_back(new_values);
  has_values_ = true;
}
int IntListProto::values_size() const {
  return values_.size();
}

void TypedValueProto::clear_value() {
  value_case_ = VALUE_NOT_SET;
  clear_boolean_value();
  clear_byte_value();
  clear_short_value();
  clear_char_value();
  clear_int_value();
  clear_float_value();
  clear_long_value();
  clear_double_value();
  clear_string_value();
  clear_string_list_value();
  clear_int_list_value();
}
TypedValueProto::ValueCase TypedValueProto::value_case() const {
  return value_case_;
}

TypedValueProto_TypeProto TypedValueProto::type() const {
  return type_;
}
bool TypedValueProto::has_type() const {
  return has_type_;
}
void TypedValueProto::clear_type() {
  type_ = TypedValueProto_TypeProto();
  has_type_ = false;
}
void TypedValueProto::set_type(TypedValueProto_TypeProto new_type) {
  type_ = new_type;
  has_type_ = true;
}
TypedValueProto_TypeProto* TypedValueProto::mutable_type() {
  has_type_ = true;
  return &type_;
}

bool TypedValueProto::boolean_value() const {
  return boolean_value_;
}
bool TypedValueProto::has_boolean_value() const {
  return has_boolean_value_;
}
void TypedValueProto::clear_boolean_value() {
  boolean_value_ = bool();
  has_boolean_value_ = false;
  if (value_case_ == kBooleanValue) {
    value_case_ = VALUE_NOT_SET;
  }
}
void TypedValueProto::set_boolean_value(bool new_boolean_value) {
  clear_value();
  value_case_ = kBooleanValue;
  boolean_value_ = new_boolean_value;
  has_boolean_value_ = true;
}
bool* TypedValueProto::mutable_boolean_value() {
  clear_value();
  value_case_ = kBooleanValue;
  has_boolean_value_ = true;
  return &boolean_value_;
}

std::string TypedValueProto::byte_value() const {
  return byte_value_;
}
bool TypedValueProto::has_byte_value() const {
  return has_byte_value_;
}
void TypedValueProto::clear_byte_value() {
  byte_value_ = std::string();
  has_byte_value_ = false;
  if (value_case_ == kByteValue) {
    value_case_ = VALUE_NOT_SET;
  }
}
void TypedValueProto::set_byte_value(std::string new_byte_value) {
  clear_value();
  value_case_ = kByteValue;
  byte_value_ = new_byte_value;
  has_byte_value_ = true;
}
std::string* TypedValueProto::mutable_byte_value() {
  clear_value();
  value_case_ = kByteValue;
  has_byte_value_ = true;
  return &byte_value_;
}

std::string TypedValueProto::short_value() const {
  return short_value_;
}
bool TypedValueProto::has_short_value() const {
  return has_short_value_;
}
void TypedValueProto::clear_short_value() {
  short_value_ = std::string();
  has_short_value_ = false;
  if (value_case_ == kShortValue) {
    value_case_ = VALUE_NOT_SET;
  }
}
void TypedValueProto::set_short_value(std::string new_short_value) {
  clear_value();
  value_case_ = kShortValue;
  short_value_ = new_short_value;
  has_short_value_ = true;
}
std::string* TypedValueProto::mutable_short_value() {
  clear_value();
  value_case_ = kShortValue;
  has_short_value_ = true;
  return &short_value_;
}

std::string TypedValueProto::char_value() const {
  return char_value_;
}
bool TypedValueProto::has_char_value() const {
  return has_char_value_;
}
void TypedValueProto::clear_char_value() {
  char_value_ = std::string();
  has_char_value_ = false;
  if (value_case_ == kCharValue) {
    value_case_ = VALUE_NOT_SET;
  }
}
void TypedValueProto::set_char_value(std::string new_char_value) {
  clear_value();
  value_case_ = kCharValue;
  char_value_ = new_char_value;
  has_char_value_ = true;
}
std::string* TypedValueProto::mutable_char_value() {
  clear_value();
  value_case_ = kCharValue;
  has_char_value_ = true;
  return &char_value_;
}

int32_t TypedValueProto::int_value() const {
  return int_value_;
}
bool TypedValueProto::has_int_value() const {
  return has_int_value_;
}
void TypedValueProto::clear_int_value() {
  int_value_ = int32_t();
  has_int_value_ = false;
  if (value_case_ == kIntValue) {
    value_case_ = VALUE_NOT_SET;
  }
}
void TypedValueProto::set_int_value(int32_t new_int_value) {
  clear_value();
  value_case_ = kIntValue;
  int_value_ = new_int_value;
  has_int_value_ = true;
}
int32_t* TypedValueProto::mutable_int_value() {
  clear_value();
  value_case_ = kIntValue;
  has_int_value_ = true;
  return &int_value_;
}

float TypedValueProto::float_value() const {
  return float_value_;
}
bool TypedValueProto::has_float_value() const {
  return has_float_value_;
}
void TypedValueProto::clear_float_value() {
  float_value_ = float();
  has_float_value_ = false;
  if (value_case_ == kFloatValue) {
    value_case_ = VALUE_NOT_SET;
  }
}
void TypedValueProto::set_float_value(float new_float_value) {
  clear_value();
  value_case_ = kFloatValue;
  float_value_ = new_float_value;
  has_float_value_ = true;
}
float* TypedValueProto::mutable_float_value() {
  clear_value();
  value_case_ = kFloatValue;
  has_float_value_ = true;
  return &float_value_;
}

int64_t TypedValueProto::long_value() const {
  return long_value_;
}
bool TypedValueProto::has_long_value() const {
  return has_long_value_;
}
void TypedValueProto::clear_long_value() {
  long_value_ = int64_t();
  has_long_value_ = false;
  if (value_case_ == kLongValue) {
    value_case_ = VALUE_NOT_SET;
  }
}
void TypedValueProto::set_long_value(int64_t new_long_value) {
  clear_value();
  value_case_ = kLongValue;
  long_value_ = new_long_value;
  has_long_value_ = true;
}
int64_t* TypedValueProto::mutable_long_value() {
  clear_value();
  value_case_ = kLongValue;
  has_long_value_ = true;
  return &long_value_;
}

double TypedValueProto::double_value() const {
  return double_value_;
}
bool TypedValueProto::has_double_value() const {
  return has_double_value_;
}
void TypedValueProto::clear_double_value() {
  double_value_ = double();
  has_double_value_ = false;
  if (value_case_ == kDoubleValue) {
    value_case_ = VALUE_NOT_SET;
  }
}
void TypedValueProto::set_double_value(double new_double_value) {
  clear_value();
  value_case_ = kDoubleValue;
  double_value_ = new_double_value;
  has_double_value_ = true;
}
double* TypedValueProto::mutable_double_value() {
  clear_value();
  value_case_ = kDoubleValue;
  has_double_value_ = true;
  return &double_value_;
}

std::string TypedValueProto::string_value() const {
  return string_value_;
}
bool TypedValueProto::has_string_value() const {
  return has_string_value_;
}
void TypedValueProto::clear_string_value() {
  string_value_ = std::string();
  has_string_value_ = false;
  if (value_case_ == kStringValue) {
    value_case_ = VALUE_NOT_SET;
  }
}
void TypedValueProto::set_string_value(std::string new_string_value) {
  clear_value();
  value_case_ = kStringValue;
  string_value_ = new_string_value;
  has_string_value_ = true;
}
std::string* TypedValueProto::mutable_string_value() {
  clear_value();
  value_case_ = kStringValue;
  has_string_value_ = true;
  return &string_value_;
}

const StringListProto& TypedValueProto::string_list_value() const {
  return string_list_value_;
}
bool TypedValueProto::has_string_list_value() const {
  return has_string_list_value_;
}
void TypedValueProto::clear_string_list_value() {
  string_list_value_ = StringListProto();
  has_string_list_value_ = false;
  if (value_case_ == kStringListValue) {
    value_case_ = VALUE_NOT_SET;
  }
}
void TypedValueProto::set_string_list_value(const StringListProto& new_string_list_value) {
  clear_value();
  value_case_ = kStringListValue;
  string_list_value_ = new_string_list_value;
  has_string_list_value_ = true;
}
StringListProto* TypedValueProto::mutable_string_list_value() {
  clear_value();
  value_case_ = kStringListValue;
  has_string_list_value_ = true;
  return &string_list_value_;
}

const IntListProto& TypedValueProto::int_list_value() const {
  return int_list_value_;
}
bool TypedValueProto::has_int_list_value() const {
  return has_int_list_value_;
}
void TypedValueProto::clear_int_list_value() {
  int_list_value_ = IntListProto();
  has_int_list_value_ = false;
  if (value_case_ == kIntListValue) {
    value_case_ = VALUE_NOT_SET;
  }
}
void TypedValueProto::set_int_list_value(const IntListProto& new_int_list_value) {
  clear_value();
  value_case_ = kIntListValue;
  int_list_value_ = new_int_list_value;
  has_int_list_value_ = true;
}
IntListProto* TypedValueProto::mutable_int_list_value() {
  clear_value();
  value_case_ = kIntListValue;
  has_int_list_value_ = true;
  return &int_list_value_;
}

std::string MetadataProto_MetadataMapEntry::key() const {
  return key_;
}
bool MetadataProto_MetadataMapEntry::has_key() const {
  return has_key_;
}
void MetadataProto_MetadataMapEntry::clear_key() {
  key_ = std::string();
  has_key_ = false;
}
void MetadataProto_MetadataMapEntry::set_key(std::string new_key) {
  key_ = new_key;
  has_key_ = true;
}
std::string* MetadataProto_MetadataMapEntry::mutable_key() {
  has_key_ = true;
  return &key_;
}

const TypedValueProto& MetadataProto_MetadataMapEntry::value() const {
  return value_;
}
bool MetadataProto_MetadataMapEntry::has_value() const {
  return has_value_;
}
void MetadataProto_MetadataMapEntry::clear_value() {
  value_ = TypedValueProto();
  has_value_ = false;
}
void MetadataProto_MetadataMapEntry::set_value(const TypedValueProto& new_value) {
  value_ = new_value;
  has_value_ = true;
}
TypedValueProto* MetadataProto_MetadataMapEntry::mutable_value() {
  has_value_ = true;
  return &value_;
}

const std::map<std::string, TypedValueProto>& MetadataProto::metadata_map() const {
  return metadata_map_;
}
bool MetadataProto::has_metadata_map() const {
  return has_metadata_map_;
}
void MetadataProto::clear_metadata_map() {
  metadata_map_ = std::map<std::string, TypedValueProto>();
  has_metadata_map_ = false;
}
void MetadataProto::set_metadata_map(const std::map<std::string, TypedValueProto>& new_metadata_map) {
  metadata_map_ = new_metadata_map;
  has_metadata_map_ = true;
}
std::map<std::string, TypedValueProto>* MetadataProto::mutable_metadata_map() {
  has_metadata_map_ = true;
  return &metadata_map_;
}

std::string CheckResultProto::source_check_class() const {
  return source_check_class_;
}
bool CheckResultProto::has_source_check_class() const {
  return has_source_check_class_;
}
void CheckResultProto::clear_source_check_class() {
  source_check_class_ = std::string();
  has_source_check_class_ = false;
}
void CheckResultProto::set_source_check_class(std::string new_source_check_class) {
  source_check_class_ = new_source_check_class;
  has_source_check_class_ = true;
}
std::string* CheckResultProto::mutable_source_check_class() {
  has_source_check_class_ = true;
  return &source_check_class_;
}

int32_t CheckResultProto::result_id() const {
  return result_id_;
}
bool CheckResultProto::has_result_id() const {
  return has_result_id_;
}
void CheckResultProto::clear_result_id() {
  result_id_ = int32_t();
  has_result_id_ = false;
}
void CheckResultProto::set_result_id(int32_t new_result_id) {
  result_id_ = new_result_id;
  has_result_id_ = true;
}
int32_t* CheckResultProto::mutable_result_id() {
  has_result_id_ = true;
  return &result_id_;
}

int64_t CheckResultProto::hierarchy_source_id() const {
  return hierarchy_source_id_;
}
bool CheckResultProto::has_hierarchy_source_id() const {
  return has_hierarchy_source_id_;
}
void CheckResultProto::clear_hierarchy_source_id() {
  hierarchy_source_id_ = int64_t();
  has_hierarchy_source_id_ = false;
}
void CheckResultProto::set_hierarchy_source_id(int64_t new_hierarchy_source_id) {
  hierarchy_source_id_ = new_hierarchy_source_id;
  has_hierarchy_source_id_ = true;
}
int64_t* CheckResultProto::mutable_hierarchy_source_id() {
  has_hierarchy_source_id_ = true;
  return &hierarchy_source_id_;
}

ResultType CheckResultProto::result_type() const {
  return result_type_;
}
bool CheckResultProto::has_result_type() const {
  return has_result_type_;
}
void CheckResultProto::clear_result_type() {
  result_type_ = ResultType();
  has_result_type_ = false;
}
void CheckResultProto::set_result_type(ResultType new_result_type) {
  result_type_ = new_result_type;
  has_result_type_ = true;
}
ResultType* CheckResultProto::mutable_result_type() {
  has_result_type_ = true;
  return &result_type_;
}

const MetadataProto& CheckResultProto::metadata() const {
  return metadata_;
}
bool CheckResultProto::has_metadata() const {
  return has_metadata_;
}
void CheckResultProto::clear_metadata() {
  metadata_ = MetadataProto();
  has_metadata_ = false;
}
void CheckResultProto::set_metadata(const MetadataProto& new_metadata) {
  metadata_ = new_metadata;
  has_metadata_ = true;
}
MetadataProto* CheckResultProto::mutable_metadata() {
  has_metadata_ = true;
  return &metadata_;
}

const AccessibilityHierarchy& AccessibilityEvaluation::hierarchy() const {
  return hierarchy_;
}
bool AccessibilityEvaluation::has_hierarchy() const {
  return has_hierarchy_;
}
void AccessibilityEvaluation::clear_hierarchy() {
  hierarchy_ = AccessibilityHierarchy();
  has_hierarchy_ = false;
}
void AccessibilityEvaluation::set_hierarchy(const AccessibilityHierarchy& new_hierarchy) {
  hierarchy_ = new_hierarchy;
  has_hierarchy_ = true;
}
AccessibilityHierarchy* AccessibilityEvaluation::mutable_hierarchy() {
  has_hierarchy_ = true;
  return &hierarchy_;
}

const CheckResultProto& AccessibilityEvaluation::results(int index) const {
  return results_[index];
}
const std::vector<CheckResultProto>& AccessibilityEvaluation::results() const {
  return results_;
}
bool AccessibilityEvaluation::has_results() const {
  return has_results_;
}
void AccessibilityEvaluation::clear_results() {
  results_.clear();
  has_results_ = false;
}
void AccessibilityEvaluation::set_results(int index, const CheckResultProto& new_results) {
  results_[index] = new_results;
  has_results_ = true;
}
CheckResultProto* AccessibilityEvaluation::mutable_results(int index) {
  has_results_ = true;
  return &results_[index];
}
CheckResultProto* AccessibilityEvaluation::add_results() {
  results_.emplace_back();
  has_results_ = true;
  return &results_.back();
}
int AccessibilityEvaluation::results_size() const {
  return results_.size();
}

}  // GTXiLib
}  // OOPClasses
}  // Protos