text:
package io.alfredux.softbills.security.jwt;

import io.alfredux.softbills.security.AuthoritiesConstants;
import io.github.jhipster.config.JHipsterProperties;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.util.ReflectionTestUtils;

import java.util.Collections;

import static org.assertj.core.api.Assertions.assertThat;

public class JWTFilterTest {

    private TokenProvider tokenProvider;

    private JWTFilter jwtFilter;

    @Before
    public void setup() {
        JHipsterProperties jHipsterProperties = new JHipsterProperties();
        tokenProvider = new TokenProvider(jHipsterProperties);
        ReflectionTestUtils.setField(tokenProvider, "secretKey", "test secret");
        ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", 60000);
        jwtFilter = new JWTFilter(tokenProvider);
        SecurityContextHolder.getContext().setAuthentication(null);
    }

    @Test
    public void testJWTFilter() throws Exception {
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
            "test-user",
            "test-password",
            Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
        );
        String jwt = tokenProvider.createToken(authentication, false);
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
        request.setRequestURI("/api/test");
        MockHttpServletResponse response = new MockHttpServletResponse();
        MockFilterChain filterChain = new MockFilterChain();
        jwtFilter.doFilter(request, response, filterChain);
        assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
        assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user");
        assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt);
    }

    @Test
    public void testJWTFilterInvalidToken() throws Exception {
        String jwt = "wrong_jwt";
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
        request.setRequestURI("/api/test");
        MockHttpServletResponse response = new MockHttpServletResponse();
        MockFilterChain filterChain = new MockFilterChain();
        jwtFilter.doFilter(request, response, filterChain);
        assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
        assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
    }

    @Test
    public void testJWTFilterMissingAuthorization() throws Exception {
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.setRequestURI("/api/test");
        MockHttpServletResponse response = new MockHttpServletResponse();
        MockFilterChain filterChain = new MockFilterChain();
        jwtFilter.doFilter(request, response, filterChain);
        assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
        assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
    }

    @Test
    public void testJWTFilterMissingToken() throws Exception {
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer ");
        request.setRequestURI("/api/test");
        MockHttpServletResponse response = new MockHttpServletResponse();
        MockFilterChain filterChain = new MockFilterChain();
        jwtFilter.doFilter(request, response, filterChain);
        assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
        assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
    }

    @Test
    public void testJWTFilterWrongScheme() throws Exception {
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
            "test-user",
            "test-password",
            Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
        );
        String jwt = tokenProvider.createToken(authentication, false);
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Basic " + jwt);
        request.setRequestURI("/api/test");
    }

}


text:
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class member_login extends CI_Controller {

	function __construct()
	{
		# code...
		parent::__construct();

		/* if($this->nativesession->get( 'is_member_logged_in' ) == FALSE)
		{
			redirect(base_url( $this->nativesession->get( 'local_admin_login_map' ) .'/login' ));
		} */

		$this->load->model('country_model');
		$this->load->model('member_login_model');
		$this->load->helper(array('form', 'url'));
		$this->load->library('form_validation');
	}

	function index() {

		$this->nativesession->set( 'gan_member_login_map', $this->uri->segment( 1 ) );

		$data = array(
		 'title' => 'Member Login',
		 'menu' => '',
		 'content' => 'login',
		 'countries' => $this->country_model->get_country(),
		 'scripts' => ''
		);
		// $this->load->view('members/login', $data);

		 $this->template
			->set_partial('forgot_password', 'members/forgot_password')
			->set_partial('member_registration', 'members/member_registration')
			->set_layout('template_member_login')
			->build('members/login', $data);

	}

	function registration() {

		$this->nativesession->set( 'gan_member_login_map', $this->uri->segment( 1 ) );

		$data = array(
		 'title' => 'Member Login',
		 'menu' => '',
		 'content' => 'login',
		 'countries' => $this->country_model->get_country(),
		 'scripts' => ''
		);
		// $this->load->view('members/login', $data);

		 $this->template
			->set_partial('forgot_password', 'members/forgot_password')
			->set_layout('template_member_registration')
			->build('members/member_registration', $data);

	}

	function login_member()
	{

		$login_success = null;

		if ( isset( $_POST[ 'login' ] ) )
		{
			$login = $_POST[ 'login' ];

			$data = array('member_code' => $login[ 'member_code' ]);
			$potential_user = $this->member_login_model->get_user_existing_data($data);

			if ($potential_user)
			{

					$this->load->library( 'PBKDF2' );

					$member = $potential_user;

					$pbkdf2 = new PBKDF2();

					if ( $pbkdf2->validatePassword( $login[ 'password' ], $member['password'] ) )
					{
						if($member['status'] != 'deactivated' && $member['status'] != 'inactive'){

							$login_success = true;

							if ( isset( $login[ 'remember_me' ] ) )
							{
								// @TODO remember me mechanism
							}

							$this->nativesession->set( array(
								'is_logged_in' 	=> true,
								'is_member_logged_in' 	=> true,
								'member_id' 		=> $member['id'],
								'member_code' 		=> $member['member_code'],
								'ms_status' 		=> $member['status']
							) );

							// $country_code = function_exists( 'geoip_country_code_by_name' ) ? geoip_country_code_by_name( $_SERVER[ 'REMOTE_ADDR' ] ) : '';

							$member_id = (string)$member['id'];

							$member_data = array(
											'last_login_date' 	=> date( 'Y-m-d H:i:s' ),
											'last_login_ip' 	=> $_SERVER[ 'REMOTE_ADDR' ],
											'last_login_country' => function_exists( 'geoip_country_code_by_name' ) ? geoip_country_code_by_name( $_SERVER[ 'REMOTE_ADDR' ] ) : ''
											);

							$this->member_login_model->update_member($member_id, $member_data);

							redirect( base_url('members/home') );
						}
						else if($member['status'] == 'inactive')
						{
							$this->nativesession->set_flashdata( 'login_status', '
It seems that your account is inactive. please contact your administrator.
' );
							$login_success = false;
							redirect( base_url('login') );
						}
						else
						{
							$this->nativesession->set_flashdata( 'login_status', '
Your account is suspended, please contact administrator.
' );
							$login_success = false;
							redirect( base_url('login') );
						}

					}
					else
					{
						$this->nativesession->set_flashdata( 'login_status', '
Incorrect Member ID or Password.
' );
						$login_success = false;
						redirect( base_url('login') );
					}

			}
			else
			{
				$this->nativesession->set_flashdata( 'login_status', '
Incorrect Member ID or Password.
' );
				$login_success = false;
				redirect( base_url('login') );
			}

		}
	}

	function member_logout()
	{
		$this->nativesession->sess_destroy();
		redirect(base_url('members'));
	}
}
?>

redpajama_set_name: RedPajamaGithub


text:
--  testVTimePointsToRanges
update	test.sample_properties
set		STRING_VALUE	= 'test.date_time_points'
where	PROPERTY_NAME	= 'SourceView'
	and	WORKITEM_NAME	= 'testVTimePointsToRanges';

update	test.sample_properties
set		STRING_VALUE	= 'test.vw_timepoints_ranges'
where	PROPERTY_NAME	= 'ObjectView'
	and	WORKITEM_NAME	= 'testVTimePointsToRanges';

update	test.sample_properties
set		STRING_VALUE	= 'catalog_id, position_id'
where
		PROPERTY_NAME	= 'KeyColumns'
	and	WORKITEM_NAME	= 'testVTimePointsToRanges';

--  testVTimeRangesToSeries
update	test.sample_properties
set		STRING_VALUE	= 'test.vw_timepoints_ranges'
where	PROPERTY_NAME	= 'SourceView'
	and	WORKITEM_NAME	= 'testVTimeRangesToSeries';

update	test.sample_properties
set		STRING_VALUE	= 'test.vw_timeranges_series'
where	PROPERTY_NAME	= 'ObjectView'
	and	WORKITEM_NAME	= 'testVTimeRangesToSeries';

--	testVTimePointsToSeries
update	test.sample_properties
set		STRING_VALUE	= 'test.date_time_points'
where	PROPERTY_NAME	= 'SourceView'
	and	WORKITEM_NAME	= 'testVTimePointsToSeries';

update	test.sample_properties
set		STRING_VALUE	= 'test.vw_timepoints_series'
where	PROPERTY_NAME	= 'ObjectView'
	and	WORKITEM_NAME	= 'testVTimePointsToSeries';

update	test.sample_properties
set		STRING_VALUE	= 'catalog_id, position_id'
where
		PROPERTY_NAME	= 'KeyColumns'
	and	WORKITEM_NAME	= 'testVTimePointsToSeries';

--  testVTimeSeriesToRanges
update	test.sample_properties
set		STRING_VALUE	= 'test.vw_timepoints_series'
where	PROPERTY_NAME	= 'SourceView'
	and	WORKITEM_NAME	= 'testVTimeSeriesToRanges';

update	test.sample_properties
set		STRING_VALUE	= 'test.vw_timeseries_ranges'
where	PROPERTY_NAME	= 'ObjectView'
	and	WORKITEM_NAME	= 'testVTimeSeriesToRanges';

--  testVTimeRangesCheckSum
update	test.sample_properties
set		STRING_VALUE	= 'test.vw_timepoints_ranges'
where	PROPERTY_NAME	= 'SourceView'
	and	WORKITEM_NAME	= 'testVTimeRangesCheckSum';

update	test.sample_properties
set		STRING_VALUE	= 'test.vw_timeranges_chksum'
where	PROPERTY_NAME	= 'ObjectView'
	and	WORKITEM_NAME	= 'testVTimeRangesCheckSum';

update	test.sample_properties
set		STRING_VALUE	= 'catalog_id, position_id'
where
		PROPERTY_NAME	= 'KeyColumns'
	and	WORKITEM_NAME	= 'testVTimeRangesCheckSum';

--  testVPivot
update	test.sample_properties
set		STRING_VALUE	= 'test.pivot_discrete_attrib'
where	PROPERTY_NAME	= 'SourceView'
	and	WORKITEM_NAME	= 'testVPivot';

update	test.sample_properties
set		STRING_VALUE	= 'test.vw_pivot'
where	PROPERTY_NAME	= 'ObjectView'
	and	WORKITEM_NAME	= 'testVPivot';

update	test.sample_properties
set		STRING_VALUE	= 'product_id'
where
		PROPERTY_NAME	= 'NonPivotedColumns'
	and	WORKITEM_NAME	= 'testVPivot';

update	test.sample_properties
set		STRING_VALUE	= 'attrib_code'
where
		PROPERTY_NAME	= 'PivotColumn'
	and	WORKITEM_NAME	= 'testVPivot';

update	test.sample_properties
set		STRING_VALUE	= 'value_'
where
		PROPERTY_NAME	= 'ValueColumn'
	and	WORKITEM_NAME	= 'testVPivot';

update	test.sample_properties
set		STRING_VALUE	= '''FIELD_A'' AS V_A, ''FIELD_B'' AS V_B, ''FIELD_C'' AS V_C, ''FIELD_D'' as V_D, ''FIELD_E'' as V_E, ''FIELD_F'' as V_F, ''FIELD_G'' as V_G, ''FIELD_H'' as V_H'
where
		PROPERTY_NAME	= 'ValueList'
	and	WORKITEM_NAME	= 'testVPivot';

--  testVUnpivot
update	test.sample_properties
set		STRING_VALUE	= 'test.vw_pivot'
where	PROPERTY_NAME	= 'SourceView'
	and	WORKITEM_NAME	= 'testVUnpivot';

update	test.sample_properties
set		STRING_VALUE	= 'test.vw_unpivot'
where	PROPERTY_NAME	= 'ObjectView'
	and	WORKITEM_NAME	= 'testVUnpivot';

update	test.sample_properties
set		STRING_VALUE	= 'product_id'
where
		PROPERTY_NAME	= 'NonPivotedColumns'
	and	WORKITEM_NAME	= 'testVUnpivot';

update	test.sample_properties
set		STRING_VALUE	= 'attrib_code'
where	PROPERTY_NAME	= 'PivotColumn'
	and	WORKITEM_NAME	= 'testVUnpivot';

update	test.sample_properties
set		STRING_VALUE	= 'value_'
where	PROPERTY_NAME	= 'ValueColumn'
	and	WORKITEM_NAME	= 'testVUnpivot';

update	test.sample_properties
set		STRING_VALUE	= 'V_A as ''FIELD_A'', V_B as ''FIELD_B'', V_C as ''FIELD_C'', V_D, V_E, V_F, V_G, V_H'
where	PROPERTY_NAME	= 'UnpivotColumns'
	and	WORKITEM_NAME	= 'testVUnpivot';

--  testVGroupingSets
update	test.sample_properties
set		STRING_VALUE	= 'test.grouping_flat_values'
where	PROPERTY_NAME	= 'SourceView'
	and	WORKITEM_NAME	= 'testVGroupingSets';

update	test.sample_properties
set		STRING_VALUE	= 'test.vw_grouping_sets'
where	PROPERTY_NAME	= 'ObjectView'
	and	WORKITEM_NAME	= 'testVGroupingSets';

update	test.sample_properties
set		STRING_VALUE	= 'SUM(value1) AS SUM_V1, SUM(value2) AS SUM_V2, SUM(value3) AS SUM_V3, SUM(value4) AS SUM_V4'
where	PROPERTY_NAME	= 'AggregateExprs'
	and	WORKITEM_NAME	= 'testVGroupingSets';

update	test.sample_properties
set		STRING_VALUE	= 'simulation_id'
where	PROPERTY_NAME	= 'SimpleGroupByColumns'
	and	WORKITEM_NAME	= 'testVGroupingSets';

update	test.sample_properties
set		STRING_VALUE	= '() AS ''TOTAL_FUND'', (is_cash) AS ''AGG_CASH'', (is_cash, prod_code) AS ''AGG_PROD'', (grp1_type, grp2_code) as ''agg_grp12'', (grp2_code, grp3_class) as ''agg_grp23'''
where	PROPERTY_NAME	= 'GroupingSetsColumns'
	and	WORKITEM_NAME	= 'testVGroupingSets';

--	testVNaviForeignKey
update	test.sample_properties
set		STRING_VALUE	= 'test.vw_navi_grp_flat'
where	PROPERTY_NAME	= 'ObjectView'
	and	WORKITEM_NAME	= 'testVNaviForeignKey';

update	test.sample_properties
set		STRING_VALUE	= 'test.grouping_flat_values'
where	PROPERTY_NAME	= 'ForeignKeyBaseTable'
	and	WORKITEM_NAME	= 'testVNaviForeignKey';

--	testVFullPivot
update	test.sample_properties
set		STRING_VALUE	= 'test.vw_full_pivot'
where	PROPERTY_NAME	= 'ObjectView'
	and	WORKITEM_NAME	= 'testVFullPivot';

update	test.sample_properties
set		STRING_VALUE	= 'test.pivot_discrete_attrib'
where	PROPERTY_NAME	= 'SourceView'
	and	WORKITEM_NAME	= 'testVFullPivot';

update	test.sample_properties
set		STRING_VALUE	= 'product_id'
where	PROPERTY_NAME	= 'JunctionColumns'
	and	WORKITEM_NAME	= 'testVFullPivot';

update	test.sample_properties
set		STRING_VALUE	= 'attrib_code'
where	PROPERTY_NAME	= 'PivotColumn'
	and	WORKITEM_NAME	= 'testVFullPivot';

update	test.sample_properties
set		STRING_VALUE	= 'value_'
where	PROPERTY_NAME	= 'MeasureColumn'
	and	WORKITEM_NAME	= 'testVFullPivot';

update	test.sample_properties
set		STRING_VALUE	= '''FIELD_A'' AS V_A, ''FIELD_B'' AS V_B, ''FIELD_C'' AS V_C, ''FIELD_D'' as V_D, ''FIELD_E'' as V_E, ''FIELD_F'' as V_F, ''FIELD_G'' as V_G, ''FIELD_H'' as V_H'
where	PROPERTY_NAME	= 'ValueAliasList'
	and	WORKITEM_NAME	= 'testVFullPivot';


text:
require 'spec_helper'

describe "<%= constant_name %>" do
  it "fails" do
    fail "hey buddy, you should probably rename this file and start specing for real"
  end
end


text:
package org.scijava.display;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.scijava.display.event.DisplayActivatedEvent;
import org.scijava.display.event.DisplayCreatedEvent;
import org.scijava.display.event.DisplayDeletedEvent;
import org.scijava.display.event.window.WinActivatedEvent;
import org.scijava.display.event.window.WinClosedEvent;
import org.scijava.event.EventHandler;
import org.scijava.event.EventService;
import org.scijava.log.LogService;
import org.scijava.object.ObjectService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.plugin.PluginInfo;
import org.scijava.plugin.PluginService;
import org.scijava.service.AbstractService;
import org.scijava.service.Service;

/**
 * Default service for working with {@link Display}s.
 *
 * @author Barry DeZonia
 * @author Curtis Rueden
 * @author Grant Harris
 */
@Plugin(type = Service.class)
public final class DefaultDisplayService extends AbstractService implements
	DisplayService
{

	// -- Parameters --

	@Parameter
	private LogService log;

	@Parameter
	private EventService eventService;

	@Parameter
	private ObjectService objectService;

	@Parameter
	private PluginService pluginService;

	// -- instance variables --

	private final LinkedList<Display<?>> displayList =
		new LinkedList<>();

	// -- DisplayService methods --

	@Override
	public EventService eventService() {
		return eventService;
	}

	@Override
	public ObjectService objectService() {
		return objectService;
	}

	@Override
	public PluginService pluginService() {
		return pluginService;
	}

	// -- DisplayService methods - active displays --

	@Override
	public Display<?> getActiveDisplay() {
		if (displayList.size() == 0) return null;
		return displayList.get(0);
	}

	@Override
	@SuppressWarnings("unchecked")
	public <D extends Display<?>> D getActiveDisplay(final Class<D> displayClass)
	{
		for (final Display<?> disp : displayList) {
			if (displayClass.isAssignableFrom(disp.getClass())) return (D) disp;
		}
		return null;
	}

	@Override
	public void setActiveDisplay(final Display<?> display) {
		if (display != null) {
			displayList.remove(display);
			displayList.addFirst(display);
			eventService.publish(new DisplayActivatedEvent(display));
		}
	}

	// -- DisplayService methods - display plugin discovery --

	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<PluginInfo<Display<?>>> getDisplayPlugins() {
		return (List) pluginService.getPluginsOfType(Display.class);
	}

	@Override
	public <D extends Display<?>> PluginInfo<Display<?>> getDisplayPlugin(
		final Class<D> pluginClass)
	{
		@SuppressWarnings({ "rawtypes", "unchecked" })
		final PluginInfo<Display<?>> displayPlugin =
			(PluginInfo) pluginService.getPlugin(pluginClass, Display.class);
		return displayPlugin;
	}

	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public PluginInfo<Display<?>> getDisplayPlugin(final String className) {
		return (PluginInfo) pluginService.getPlugin(className);
	}

	@Override
	public <D extends Display<?>> List<PluginInfo<D>> getDisplayPluginsOfType(
		final Class<D> type)
	{
		return pluginService.getPluginsOfType(type);
	}

	// -- DisplayService methods - display discovery --

	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<Display<?>> getDisplays() {
		return (List) objectService.getObjects(Display.class);
	}

	@Override
	public <D extends Display<?>> List<D> getDisplaysOfType(final Class<D> type)
	{
		return objectService.getObjects(type);
	}

	@Override
	public Display<?> getDisplay(final String name) {
		for (final Display<?> display : getDisplays()) {
			if (name.equalsIgnoreCase(display.getName())) {
				return display;
			}
		}
		return null;
	}

	@Override
	public List<Display<?>> getDisplays(final Object o) {
		final ArrayList<Display<?>> displays = new ArrayList<>();
		for (final Display<?> display : getDisplays()) {
			if (display.isDisplaying(o)) displays.add(display);
		}
		return displays;
	}

	// -- DisplayService methods - display creation --

	@Override
	public boolean isUniqueName(final String name) {
		for (final Display<?> display : getDisplays()) {
			if (name.equalsIgnoreCase(display.getName())) {
				return false;
			}
		}
		return true;
	}

	@Override
	public Display<?> createDisplay(final Object o) {
		return createDisplay(null, o);
	}

	@Override
	public Display<?> createDisplay(final String name, final Object o) {
		final Display<?> display = createDisplayQuietly(o);
		if (display == null) return null;
		if (name != null) display.setName(name);
		eventService.publish(new DisplayCreatedEvent(display));
		return display;
	}

	@Override
	public Display<?> createDisplayQuietly(final Object o) {
		// get available display plugins from the plugin service
		final List<PluginInfo<Display<?>>> displayPlugins = getDisplayPlugins();

		for (final PluginInfo<Display<?>> info : displayPlugins) {
			final Display<?> display = pluginService.createInstance(info);
			if (display == null) continue;
			// display object using the first compatible Display
			// TODO: how to handle multiple matches? prompt user with dialog box?
			if (display.canDisplay(o)) {
				display.display(o);
				return display;
			}
		}
		return null;
	}

	// -- Event handlers --

	/** Deletes the display when display window is closed. */
	@EventHandler
	protected void onEvent(final WinClosedEvent event) {
		final Display<?> display = event.getDisplay();
		if (display != null) display.close();
	}

	/** Sets the display to active when its window is activated. */
	@EventHandler
	protected void onEvent(final WinActivatedEvent event) {
		final Display<?> display = event.getDisplay();
		if (display != null) setActiveDisplay(display);
	}

	/** Removes a display from the display list when it is deleted */
	@EventHandler
	protected void onEvent(final DisplayDeletedEvent evt) {
		displayList.remove(evt.getObject());
	}
}


text:
// ========================================================================
// $Id: Manager.java,v 1.6 2004/12/22 23:28:11 janb Exp $
// Copyright 2002-2004 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================

package org.cipango.j2ee.session;

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

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EventListener;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.cipango.jboss.JBossSipAppContext;
import org.mortbay.jetty.HttpOnlyCookie;
import org.mortbay.jetty.SessionIdManager;
import org.mortbay.jetty.SessionManager;
import org.mortbay.jetty.servlet.SessionHandler;
import org.mortbay.jetty.webapp.WebAppContext;
import org.mortbay.log.Log;

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

// TODO
//-----

// we need a SnapshotInterceptor
// we need to package this into JBoss and Mort Bay spaces
// Cluster/CMR & JDO Stores should be finished/done
// a DebugInterceptor could be fun....
// Jetty should be user:jetty, role:webcontainer in order to use the session EJBs - wil probably need a SecurityInterceptor
// can I optimise return of objects from set/removeAttribute?
// CMPState should use local not remote interfaces
// FAQ entry should be finished
// Throttle/BufferInterceptor - could be written very like MigrationInterceptor
// StateAdaptor needs a name change
// We need some predefined containers
// tighten up access priviledges
// javadoc
//----------------------------------------

// we need to rethink the strategies for flushing the local cache into
// the distributed cache - specifically how they can be aggregated
// (or-ed as opposed to and-ed).

// the spec does not say (?) whether session attribute events should
// be received in the order that the changes took place - we can
// control this by placing the SynchronizationInterceptor before or
// after the BindingInterceptor

// we could use a TransactionInterceptor to ensure that compound
// operations on e.g. a CMPState are atomic - or we could explicitly
// code the use of transactions where needed (we should be able to
// make all multiple calls collapse into one call to server - look
// into this). Since HttpSessions have no transactional semantics,
// there is no way for the user to inform us of any requirements...

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

public class Manager implements org.mortbay.jetty.SessionManager
{
    // ----------------------------------------
    protected WebAppContext _context;
    /**
     * Whether or not the session manager will use cookies
     * or URLs only.
     */
    protected boolean _usingCookies = true;

    public WebAppContext getContext()
    {
        return _context;
    }

    public void setContext(WebAppContext context)
    {
        _context = context;
    }

    // ----------------------------------------
    protected int _scavengerPeriod = 60; // every 1 min

    public void setScavengerPeriod(int period)
    {
        _scavengerPeriod = period;
    }

    public int getScavengerPeriod()
    {
        return _scavengerPeriod;
    }

    // ----------------------------------------
    protected StateInterceptor[] _interceptorStack = null;

    public StateInterceptor[] getInterceptorStack()
    {
        return _interceptorStack;
    }

    public void setInterceptorStack(StateInterceptor[] interceptorStack)
    {
        _interceptorStack = interceptorStack;
    }

    // ----------------------------------------
    protected IdGenerator _idGenerator = null;

    public IdGenerator getIdGenerator()
    {
        return _idGenerator;
    }

    public void setIdGenerator(IdGenerator idGenerator)
    {
        _idGenerator = idGenerator;
    }

    // ----------------------------------------
    protected int _maxInactiveInterval;

    public int getMaxInactiveInterval()
    {
        return _maxInactiveInterval;
    }

    public void setMaxInactiveInterval(int seconds)
    {
        _maxInactiveInterval = seconds;
    }

    // ----------------------------------------
    protected Store _store = null;

    private boolean _crossContextSessionIDs = false;

    public Store getStore()
    {
        return _store;
    }

    public void setStore(Store store)
    {
        _store = store;

        if (_store != null)
            _store.setManager(this);
    }

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

    public Object clone()
    {
        // Log.info("cloning Manager: "+this);
        Manager m = new Manager();

        // deep-copy Store attribute - each Manager gets it's own Store instance
        Store store = getStore();
        if (store != null)
            m.setStore((Store) store.clone());

        // deep-copy IdGenerator attribute - each Manager gets it's own
        // IdGenerator instance
        IdGenerator ig = getIdGenerator();
        if (ig != null)
            m.setIdGenerator((IdGenerator) ig.clone());

        // Container uses InterceptorStack as a prototype to clone a stack for
        // each new session...
        m.setInterceptorStack(getInterceptorStack());

        m.setMaxInactiveInterval(getMaxInactiveInterval());
        m.setScavengerPeriod(getScavengerPeriod());

        return m;
    }

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

    final Map _sessions = new HashMap();

    public String getContextPath()
    {
        return _context.getContextPath();
    }

    // ----------------------------------------
    // LifeCycle API
    // ----------------------------------------

    boolean _started = false;

    Object _startedLock = new Object();

    Timer _scavenger;

    class Scavenger extends TimerTask
    {
        public void run()
        {
            try
            {
                scavenge();
            }
            catch (Throwable e)
            {
                Log.warn("could not scavenge local sessions", e);
            }
        }
    }

    public void start()
    {
        Log.debug("starting...");
        synchronized (_startedLock)
        {
            if (_started)
            {
                Log.warn("already started");
                return;
            }

            if (_store == null)
            {
                Log.warn("No Store. Falling back to a local session implementation - NO HTTPSESSION DISTRIBUTION");
                setStore(new LocalStore());
            }

            if (_idGenerator == null)
                _idGenerator = new DistributableIdGenerator();

            try
            {
                _store.start();
            }
            catch (Exception e)
            {
                Log.warn("Faulty Store. Falling back to a local session implementation - NO HTTPSESSION DISTRIBUTION", e);
                setStore(new LocalStore());
                try
                {
                    _store.start();
                }
                catch (Exception e2)
                {
                    Log.warn("could not start Store", e2);
                }
            }

            if (Log.isDebugEnabled())
                Log.debug("starting local scavenger thread...(period: " + getScavengerPeriod() + " secs)");
            long delay = getScavengerPeriod() * 1000;
            boolean isDaemon = true;
            _scavenger = new Timer(isDaemon);
            _scavenger.scheduleAtFixedRate(new Scavenger(), delay, delay);
            Log.debug("...local scavenger thread started");
            _started = true;
        }

        Log.debug("...started");
    }

    public boolean isStarted()
    {
        synchronized (_startedLock)
        {
            return _started;
        }
    }

    public void stop()
    {
        Log.debug("stopping...");

        synchronized (_startedLock)
        {
            if (!_started)
            {
                Log.warn("already stopped/not yet started");
                return;
            }

            // I guess we will have to ask the store for a list of sessions
            // to migrate... - TODO

            synchronized (_sessions)
            {
                List copy = new ArrayList(_sessions.values());
                for (Iterator i = copy.iterator(); i.hasNext();)
                    ((StateAdaptor) i.next()).migrate();

                _sessions.clear();
            }

            Log.debug("stopping local scavenger thread...");
            _scavenger.cancel();
            _scavenger = null;
            Log.debug("...local scavenger thread stopped");
            scavenge();

            _store.stop();
            _store.destroy();
            setStore(null);
            _started = false;
        }

        Log.debug("...stopped");
    }

    // ----------------------------------------
    // SessionManager API
    // ----------------------------------------

    protected SessionHandler _handler;

    public void setSessionHandler(SessionHandler handler)
    {
        this._handler = handler;
    }

    // ----------------------------------------
    // SessionManager API
    // ----------------------------------------

    public HttpSession getHttpSession(String id)
    {
        return findSession(id, true);
    }

    public boolean sessionExists(String id)
    {
        return findSession(id, false) != null;
    }

    public HttpSession newHttpSession(HttpServletRequest request) // TODO
    {
        return newSession(request);
    }

    // ----------------------------------------
    // this does not need locking as it is an int and access should be atomic...

    // ----------------------------------------
    // Listeners

    // These lists are only modified at webapp [un]deployment time, by a
    // single thread, so although read by multiple threads whilst the
    // Manager is running, need no synchronization...

    final List _sessionListeners = new ArrayList();

    final List _sessionAttributeListeners = new ArrayList();

    public void addEventListener(EventListener listener) throws IllegalArgumentException, IllegalStateException
    {
        synchronized (_startedLock)
        {
            if (isStarted())
                throw new IllegalStateException("EventListeners must be added before a Session Manager starts");

            boolean known = false;
            if (listener instanceof HttpSessionAttributeListener)
            {
                // Log.info("adding HttpSessionAttributeListener: "+listener);
                _sessionAttributeListeners.add(listener);
                known = true;
            }
            if (listener instanceof HttpSessionListener)
            {
                // Log.info("adding HttpSessionListener: "+listener);
                _sessionListeners.add(listener);
                known = true;
            }

            if (!known)
                throw new IllegalArgumentException("Unknown EventListener type " + listener);
        }
    }

    public void clearEventListeners()
    {
        _sessionAttributeListeners.clear();
        _sessionListeners.clear();
    }

    public void removeEventListener(EventListener listener) throws IllegalStateException
    {
        synchronized (_startedLock)
        {
            if (isStarted())
                throw new IllegalStateException("EventListeners may not be removed while a Session Manager is running");

            if (listener instanceof HttpSessionAttributeListener)
                _sessionAttributeListeners.remove(listener);
            if (listener instanceof HttpSessionListener)
                _sessionListeners.remove(listener);
        }
    }

    // ----------------------------------------
    // Implementation...
    // ----------------------------------------

    public ServletContext getServletContext()
    {
        return _context.getServletHandler().getServletContext();
    }

    public HttpSessionContext getSessionContext()
    {
        return null;
    }

    // --------------------
    // session lifecycle
    // --------------------

    // I need to think more about where the list of extant sessions is
    // held...

    // is it held by the State Factory/Type (static), which best knows
    // how to find it ? The trouble is we are not asking for just the
    // State but the whole container...

    // if the State was an EJB, the Manager could hold a HashMap of
    // id:State and the State would just be an EJB handle...

    // How does the ThrottleInterceptor fit into this. If it is holding
    // a local cache in front of a DistributedState, do we check them
    // both and compare timestamps, or flush() all ThrottleInterceptors
    // in the WebApp before we do the lookup (could be expensive...)

    // when finding a distributed session assume we are on nodeB
    // receiving a request for a session immediately after it has just
    // been created on NodeA. If we can't find it straight away, we need
    // to take into account how long it's flushing and distribution may
    // take, wait that long and then look again. This may hold up the
    // request, but without the session the request is not much good.

    // overload this to change the construction of the Container....

    protected HttpSession newContainer(String id, State state)
    {
        // put together the make-believe container and HttpSession state

        return Container.newContainer(this, id, state, getMaxInactiveInterval(), currentSecond(), getInterceptorStack());
    }

    protected Session newSession(HttpServletRequest request)
    {
        String id = null;
        HttpSession session = null;
        try
        {
            id = _store.allocateId(request);
            State state = _store.newState(id, getMaxInactiveInterval());
            session = newContainer(id, state);
        }
        catch (Exception e)
        {
            Log.debug("could not create HttpSession", e);
            return null; // BAD - TODO
        }

        if (Log.isDebugEnabled())
            Log.debug("remembering session - " + id);

        synchronized (_sessions)
        {
            _sessions.put(id, session);
        }

        notifySessionCreated(session);

        return (Session) session;
    }

    protected State destroyContainer(HttpSession session)
    {
        return Container.destroyContainer(session, getInterceptorStack());
    }

    protected void destroySession(HttpSession container)
    {
        String id = container.getId();
        if (Log.isDebugEnabled())
            Log.debug("forgetting session - " + id);
        Object tmp;
        synchronized (_sessions)
        {
            tmp = _sessions.remove(id);
        }
        container = (HttpSession) tmp;
        if (Log.isDebugEnabled())
            Log.debug("forgetting session - " + container);

        if (container == null)
        {
            Log.warn("session - " + id + " has already been destroyed");
            return;
        }

        // TODO remove all the attributes - generating correct events
        // check ordering on unbind and destroy notifications - The
        // problem is that we want these calls to go all the way through
        // the container - but not to the store - because that would be
        // too expensive and we can predict the final state...

        // we don't need to do this if we know that none of the attributes
        // are BindingListers AND there are no AttributeListeners
        // registered... - TODO

        // This will do for the moment...

        // LATER - TODO

        try
        {
            State state = ((StateAdaptor) container).getState();

            // filthy hack...
            // stop InvalidInterceptors - otherwise we can't clean up session...
            // - TODO
            {
                State s = state;
                StateInterceptor si = null;
                while (s instanceof StateInterceptor)
                {
                    si = (StateInterceptor) s;
                    s = si.getState(); // next interceptor
                    if (si instanceof ValidatingInterceptor)
                        si.stop();
                }
            }

            String[] names = state.getAttributeNameStringArray();
            for (int i = 0; i < names.length; i++)
                state.removeAttribute(names[i], false);

            // should just do this for attributes which are BindingListeners
            // - then just clear() the rest... - TODO
        }
        catch (RemoteException e)
        {
            Log.debug("could not raise events on session destruction - problem in distribution layer", e);
        }

        if (Log.isDebugEnabled())
            Log.debug("notifying session - " + id);
        notifySessionDestroyed(container);

        if (Log.isDebugEnabled())
            Log.debug("destroying container - " + id);
        State state = destroyContainer(container);

        try
        {
            if (state != null) // an interceptor may preempt us, if
            // it does not want this state
            // removed...
            {
                if (Log.isDebugEnabled())
                    Log.debug("removing state - " + id);
                _store.removeState(state);
            }
        }
        catch (Exception e)
        {
            Log.debug("could not remove session state", e);
        }
    }

    protected HttpSession findSession(String id, boolean create)
    {
        HttpSession container = null;

        try
        {
            // find the state
            State state = _store.loadState(id);

            // is it valid ?
            state = ((state != null) && state.isValid()) ? state : null; // expensive
            // ?

            // if so
            if (state != null)
            {

                // this looks slow - but to be 100% safe we need to make sure
                // that no-one can enter another container for the same id,
                // whilst we are thinking about it...

                // is there a container already available ?
                synchronized (_sessions)
                {
                    // do we have an existing container ?
                    container = (HttpSession) _sessions.get(id);

                    // if not...
                    if (container == null && create)
                    {
                        // make a new one...
                        container = newContainer(id, state);// we could lower
                        // contention by
                        // preconstructing
                        // containers... -
                        // TODO
                        _sessions.put(id, container);
                    }
                }
            }
        }
        catch (Exception ignore)
        {
            if (Log.isDebugEnabled())
                Log.debug("did not find distributed session: " + id);
        }

        return container;
    }

    // --------------------
    // session events
    // --------------------

    // should this all be delegated to the event raising interceptor....

    public Object notifyAttributeAdded(HttpSession session, String name, Object value)
    {
        int n = _sessionAttributeListeners.size();
        if (n > 0)
        {
            HttpSessionBindingEvent event = new HttpSessionBindingEvent(session, name, value);

            for (int i = 0; i < n; i++)
                ((HttpSessionAttributeListener) _sessionAttributeListeners.get(i)).attributeAdded(event);

            event = null;
        }

        return value;
    }

    public Object notifyAttributeReplaced(HttpSession session, String name, Object value)
    {
        int n = _sessionAttributeListeners.size();
        if (n > 0)
        {
            HttpSessionBindingEvent event = new HttpSessionBindingEvent(session, name, value);

            for (int i = 0; i < n; i++)
                ((HttpSessionAttributeListener) _sessionAttributeListeners.get(i)).attributeReplaced(event);

            event = null;
        }

        return value;
    }

    public Object notifyAttributeRemoved(HttpSession session, String name, Object value)
    {
        int n = _sessionAttributeListeners.size();
        if (n > 0)
        {
            HttpSessionBindingEvent event = new HttpSessionBindingEvent(session, name, value);

            for (int i = 0; i < n; i++)
                ((HttpSessionAttributeListener) _sessionAttributeListeners.get(i)).attributeRemoved(event);

            event = null;
        }

        return value;
    }

    public void notifySessionCreated(HttpSession session)
    {
        int n = _sessionListeners.size();
        if (n > 0)
        {
            HttpSessionEvent event = new HttpSessionEvent(session);

            for (int i = 0; i < n; i++)
                ((HttpSessionListener) _sessionListeners.get(i)).sessionCreated(event);

            event = null;
        }
    }

    public void notifySessionDestroyed(HttpSession session)
    {
        int n = _sessionListeners.size();
        if (n > 0)
        {
            HttpSessionEvent event = new HttpSessionEvent(session);

            for (int i = 0; i < n; i++)
                ((HttpSessionListener) _sessionListeners.get(i)).sessionDestroyed(event);

            event = null;
        }
    }

    // this is to help sessions decide if they have timed out... It is
    // wrapped here so that if I decide that System.currentTimeMillis()
    // is too heavy, I can figure out a lighter way to return a rough
    // time to the sessions...

    public long currentSecond()
    {
        return System.currentTimeMillis();
    }

    // ensure that this code is run with the correct ContextClassLoader...
    protected void scavenge()
    {
        Log.debug("starting local scavenging...");
        try
        {
            // prevent session destruction (from scavenging)
            // from being replicated to other members in the cluster.
            // Let them scavenge locally instead.
            AbstractReplicatedStore.setReplicating(true);
            //
            // take a quick copy...
            Collection copy;
            synchronized (_sessions)
            {
                copy = new ArrayList(_sessions.values());
            }
            if (Log.isDebugEnabled())
                Log.debug(copy.size() + " local sessions");
            //
            // iterate over it at our leisure...
            int n = 0;
            for (Iterator i = copy.iterator(); i.hasNext();)
            {
                // all we have to do is check if a session isValid() to force it
                // to examine itself and invalidate() itself if necessary... -
                // because it has a local cache of the necessary details, it
                // will only go to the Stored State if it really thinks that it
                // is invalid...
                StateAdaptor sa = null;
                try
                {
                    sa = (StateAdaptor) i.next();
                    // the ValidationInterceptor should pick this up and throw an IllegalStateException
                    long lat = sa.getLastAccessedTime();
                }
                catch (IllegalStateException ignore)
                {
                    if (Log.isDebugEnabled())
                        Log.debug("scavenging local session " + sa.getId());
                    destroySession(sa);
                    i.remove();
                    ++n;
                }
            }
            if (Log.isDebugEnabled())
                Log.debug("scavenged " + n + " local sessions");
        }
        finally
        {
            AbstractReplicatedStore.setReplicating(false);
        }
        Log.debug("...finished local scavenging");
    }

    /**
     * @return True if cross context session IDs are first considered for new
     * session IDs
     */
    public boolean getCrossContextSessionIDs()
    {
        return _crossContextSessionIDs;
    }

    /* ------------------------------------------------------------ */
    /** Set Cross Context sessions IDs
     * This option activates a mode where a requested session ID can be used to create a
     * new session. This facilitates the sharing of session cookies when cross context
     * dispatches use sessions.
     *
     * @param useRequestedId True if cross context session ID are first considered for new
     * session IDs
     */
    public void setCrossContextSessionIDs(boolean useRequestedId)
    {
        _crossContextSessionIDs = useRequestedId;
    }

    public Cookie getSessionCookie(HttpSession session, String contextPath, boolean requestIsSecure)
    {
//        if (_handler.isUsingCookies())
//        { what's the jetty6 counterpart for isUsingCookies? - nik
            Cookie cookie = _handler.getSessionManager().getHttpOnly() ? new HttpOnlyCookie(SessionManager.__SessionCookieProperty, session.getId()) : new Cookie(
                SessionManager.__SessionCookieProperty, session.getId());
            String domain = getServletContext().getInitParameter(SessionManager.__SessionDomainProperty);
            String maxAge = getServletContext().getInitParameter(SessionManager.__MaxAgeProperty);
            String path = getServletContext().getInitParameter(SessionManager.__SessionPathProperty);
            if (path == null)
                path = getCrossContextSessionIDs() ? "/" : ((JBossSipAppContext)_context).getUniqueName();
            if (path == null || path.length() == 0)
                path = "/";

            if (domain != null)
                cookie.setDomain(domain);
            if (maxAge != null)
                cookie.setMaxAge(Integer.parseInt(maxAge));
            else
                cookie.setMaxAge(-1);

            cookie.setSecure(requestIsSecure && getSecureCookies());
            cookie.setPath(path);

            return cookie;
//        }
//        return null;
    }

    public boolean isStarting()
    {
        // TODO Auto-generated method stub
        return false;
    }

    public SessionIdManager getMetaManager()
    {
        // TODO Auto-generated method stub
        return null;
    }

    public boolean isFailed()
    {
        // TODO Auto-generated method stub
        return false;
    }

    public boolean isRunning()
    {
        // TODO Auto-generated method stub
        return false;
    }

    public boolean isStopped()
    {
        // TODO Auto-generated method stub
        return false;
    }

    public boolean isStopping()
    {
        // TODO Auto-generated method stub
        return false;
    }

    public String getSessionPath()
    {
        // TODO Auto-generated method stub
        return null;
    }

    public String getSessionCookie()
    {
        // TODO Auto-generated method stub
        return null;
    }

    public String getSessionURL()
    {
        // TODO Auto-generated method stub
        return null;
    }

    public Cookie access(HttpSession arg0,boolean secure)
    {
        // TODO Auto-generated method stub
        return null;
    }

    public void complete(HttpSession arg0)
    {
        // TODO Auto-generated method stub

    }

    public boolean getHttpOnly()
    {
        // TODO Auto-generated method stub
        return false;
    }

    public int getMaxCookieAge()
    {
        // TODO Auto-generated method stub
        return 0;
    }

    public boolean getSecureCookies()
    {
        // TODO Auto-generated method stub
        return false;
    }

    public String getSessionDomain()
    {
        // TODO Auto-generated method stub
        return null;
    }

    public String getSessionURLPrefix()
    {
        // TODO Auto-generated method stub
        return null;
    }

    public boolean isValid(HttpSession session)
    {
        // TODO Auto-generated method stub
        return ((Session)session).isValid();
    }

    public void setIdManager(SessionIdManager arg0)
    {
        // TODO Auto-generated method stub

    }

    public void setMaxCookieAge(int arg0)
    {
        // TODO Auto-generated method stub

    }

    public void setSessionCookie(String arg0)
    {
        // TODO Auto-generated method stub

    }

    public void setSessionDomain(String arg0)
    {
        // TODO Auto-generated method stub

    }

    public void setSessionPath(String arg0)
    {
        // TODO Auto-generated method stub

    }

    public void setSessionURL(String arg0)
    {
        // TODO Auto-generated method stub

    }

    public interface Session extends HttpSession
    {
        /* ------------------------------------------------------------ */
        public boolean isValid();

        /* ------------------------------------------------------------ */
        public void access();
    }

    /**
     * @see org.mortbay.jetty.SessionManager#getClusterId(javax.servlet.http.HttpSession)
     */
    public String getClusterId(HttpSession session)
    {
        // TODO check that this is correct. There does not
        // seem to be any difference between the id as the
        // node knows it and the id within the cluster, so
        // we presume that the id is unique within the cluster.
        return session.getId();
    }

    /**
     * @see org.mortbay.jetty.SessionManager#getIdManager()
     */
    public SessionIdManager getIdManager()
    {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @see org.mortbay.jetty.SessionManager#getNodeId(javax.servlet.http.HttpSession)
     */
    public String getNodeId(HttpSession session)
    {
        // TODO check that this is correct. There does not
        // seem to be any difference between the id as the
        // node knows it and the id within the cluster, so
        // we presume that the id is unique within the cluster.
        return session.getId();
    }

    /**
     * @see org.mortbay.jetty.SessionManager#isUsingCookies()
     */
    public boolean isUsingCookies()
    {
        return _usingCookies;
    }
}


text:
#ifndef _JNI_META_DATA_H_
#define _JNI_META_DATA_H_

#include <jni.h>

static const char* CLASS_WMI_SERVICE = "org/jkiss/wmi/service/WMIService";
static const char* CLASS_WMI_OBJECT = "org/jkiss/wmi/service/WMIObject";
static const char* CLASS_WMI_QUALIFIER = "org/jkiss/wmi/service/WMIQualifier";
static const char* CLASS_WMI_OBJECT_SINK = "org/jkiss/wmi/service/WMIObjectSink";
static const char* CLASS_WMI_OBJECT_SINK_STATUS = "org/jkiss/wmi/service/WMIObjectSinkStatus";
static const char* CLASS_WMI_OBJECT_ATTRIBUTE = "org/jkiss/wmi/service/WMIObjectAttribute";
static const char* CLASS_WMI_OBJECT_METHOD = "org/jkiss/wmi/service/WMIObjectMethod";

class JNIMetaData
{
public:
	JNIMetaData(JNIEnv* pEnv);
	~JNIMetaData();

	static JNIMetaData& GetMetaData(JNIEnv* pEnv);
	//static void Destroy();

	JNIEnv* pJavaEnv;

	jclass wmiServiceClass;
	jmethodID wmiServiceConstructor;
	jfieldID wmiServiceHandleField;

	jclass wmiObjectClass;
	jmethodID wmiObjectConstructor;
	jfieldID wmiObjectHandleField;

	jclass wmiQualifierClass;
	jmethodID wmiQualifierConstructor;

	jclass wmiObjectSinkClass;
	jmethodID wmiObjectSinkIndicateMethod;
	jmethodID wmiObjectSinkSetStatusMethod;
	jclass wmiObjectSinkStatusClass;
	jclass wmiObjectAttributeClass;
	jmethodID wmiObjectAttributeConstructor;
	jclass wmiObjectMethodClass;
	jmethodID wmiObjectMethodConstructor;

	jclass javaLangObjectClass;
	jclass javaLangByteClass;
	jclass javaLangCharClass;
	jclass javaLangBooleanClass;
	jclass javaLangShortClass;
	jclass javaLangIntegerClass;
	jclass javaLangLongClass;
	jclass javaLangFloatClass;
	jclass javaLangDoubleClass;
	jclass javaLangStringClass;
	jclass javaUtilDateClass;
	jclass javaUtilListClass;

	jmethodID javaLangByteConstructor;
	jmethodID javaLangCharConstructor;
	jmethodID javaLangBooleanConstructor;
	jmethodID javaLangShortConstructor;
	jmethodID javaLangIntegerConstructor;
	jmethodID javaLangLongConstructor;
	jmethodID javaLangFloatConstructor;
	jmethodID javaLangDoubleConstructor;
	jmethodID javaUtilDateConstructor;
	jmethodID javaUtilListAddMethod;
	jmethodID javaLangObjectEqualsMethod;

private:
	jclass FindJavaClass(const char* className);
	jmethodID FindJavaMethod(jclass clazz, const char* methodName, const char* methodSig);
	void DeleteClassRef(jclass& clazz);

	static JNIMetaData* instance;
};

#endif


text:
@import Foundation;

@interface PASOption : NSObject

@property (nonatomic, assign, getter=hasRequiredArgument, readonly) BOOL     requiredArgument;
@property (nonatomic, copy, readonly)                               NSString *shortFlag;
@property (nonatomic, copy, readonly)                               NSString *longFlag;
@property (nonatomic, copy, readonly)                               NSString *format;

@property (nonatomic, copy, readonly) void (^handler)(PASOption *option, id argument);

+ (instancetype)optionWithFormat:(NSString *)format handler:(void (^)(PASOption *option, id argument))handler;
- (void)invokeWithArgument:(id)argument;

@end


text:
package agent

import (
	"context"
	"testing"

	"github.com/docker/swarmkit/agent/exec"
	"github.com/docker/swarmkit/api"
	"github.com/docker/swarmkit/log"
	"github.com/sirupsen/logrus"
	"github.com/stretchr/testify/assert"
	bolt "go.etcd.io/bbolt"
)

type testPublisherProvider struct {
}

func (tpp *testPublisherProvider) Publisher(ctx context.Context, subscriptionID string) (exec.LogPublisher, func(), error) {
	return exec.LogPublisherFunc(func(ctx context.Context, message api.LogMessage) error {
			log.G(ctx).WithFields(logrus.Fields{
				"subscription": subscriptionID,
				"task.id":      message.Context.TaskID,
				"node.id":      message.Context.NodeID,
				"service.id":   message.Context.ServiceID,
			}).Info(message.Data)
			return nil
		}), func() {
		}, nil
}

func TestWorkerAssign(t *testing.T) {
	db, cleanup := storageTestEnv(t)
	defer cleanup()

	ctx := context.Background()
	executor := &mockExecutor{t: t, dependencies: NewDependencyManager()}
	worker := newWorker(db, executor, &testPublisherProvider{})
	reporter := statusReporterFunc(func(ctx context.Context, taskID string, status *api.TaskStatus) error {
		log.G(ctx).WithFields(logrus.Fields{"task.id": taskID, "status": status}).Info("status update received")
		return nil
	})

	worker.Listen(ctx, reporter)

	for _, testcase := range []struct {
		changeSet        []*api.AssignmentChange
		expectedTasks    []*api.Task
		expectedSecrets  []*api.Secret
		expectedConfigs  []*api.Config
		expectedAssigned []*api.Task
	}{
		{}, // handle nil case.
		{
			changeSet: []*api.AssignmentChange{
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Task{
							Task: &api.Task{ID: "task-1"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionUpdate,
				},
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Secret{
							Secret: &api.Secret{ID: "secret-1"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionUpdate,
				},
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Config{
							Config: &api.Config{ID: "config-1"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionUpdate,
				},
				// these should be ignored
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Secret{
							Secret: &api.Secret{ID: "secret-2"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionRemove,
				},
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Task{
							Task: &api.Task{ID: "task-2"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionRemove,
				},
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Config{
							Config: &api.Config{ID: "config-2"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionRemove,
				},
			},
			expectedTasks: []*api.Task{
				{ID: "task-1"},
			},
			expectedSecrets: []*api.Secret{
				{ID: "secret-1"},
			},
			expectedConfigs: []*api.Config{
				{ID: "config-1"},
			},
			expectedAssigned: []*api.Task{
				{ID: "task-1"},
			},
		},
		{ // completely replaces the existing tasks and secrets
			changeSet: []*api.AssignmentChange{
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Task{
							Task: &api.Task{ID: "task-2"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionUpdate,
				},
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Secret{
							Secret: &api.Secret{ID: "secret-2"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionUpdate,
				},
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Config{
							Config: &api.Config{ID: "config-2"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionUpdate,
				},
			},
			expectedTasks: []*api.Task{
				{ID: "task-1"},
				{ID: "task-2"},
			},
			expectedSecrets: []*api.Secret{
				{ID: "secret-2"},
			},
			expectedConfigs: []*api.Config{
				{ID: "config-2"},
			},
			expectedAssigned: []*api.Task{
				{ID: "task-2"},
			},
		},
		{
			// remove assigned tasks, secret and config no longer present
			expectedTasks: []*api.Task{
				{ID: "task-1"},
				{ID: "task-2"},
			},
		},

		// TODO(stevvooe): There are a few more states here we need to get
		// covered to ensure correct during code changes.
	} {
		assert.NoError(t, worker.Assign(ctx, testcase.changeSet))

		var (
			tasks    []*api.Task
			assigned []*api.Task
		)
		assert.NoError(t, worker.db.View(func(tx *bolt.Tx) error {
			return WalkTasks(tx, func(task *api.Task) error {
				tasks = append(tasks, task)
				if TaskAssigned(tx, task.ID) {
					assigned = append(assigned, task)
				}
				return nil
			})
		}))

		assert.Equal(t, testcase.expectedTasks, tasks)
		assert.Equal(t, testcase.expectedAssigned, assigned)
		for _, secret := range testcase.expectedSecrets {
			secret, err := executor.Secrets().Get(secret.ID)
			assert.NoError(t, err)
			assert.NotNil(t, secret)
		}
		for _, config := range testcase.expectedConfigs {
			config, err := executor.Configs().Get(config.ID)
			assert.NoError(t, err)
			assert.NotNil(t, config)
		}
	}
}

func TestWorkerWait(t *testing.T) {
	db, cleanup := storageTestEnv(t)
	defer cleanup()

	ctx := context.Background()
	executor := &mockExecutor{t: t, dependencies: NewDependencyManager()}
	worker := newWorker(db, executor, &testPublisherProvider{})
	reporter := statusReporterFunc(func(ctx context.Context, taskID string, status *api.TaskStatus) error {
		log.G(ctx).WithFields(logrus.Fields{"task.id": taskID, "status": status}).Info("status update received")
		return nil
	})

	worker.Listen(ctx, reporter)

	changeSet := []*api.AssignmentChange{
		{
			Assignment: &api.Assignment{
				Item: &api.Assignment_Task{
					Task: &api.Task{ID: "task-1"},
				},
			},
			Action: api.AssignmentChange_AssignmentActionUpdate,
		},
		{
			Assignment: &api.Assignment{
				Item: &api.Assignment_Task{
					Task: &api.Task{ID: "task-2"},
				},
			},
			Action: api.AssignmentChange_AssignmentActionUpdate,
		},
		{
			Assignment: &api.Assignment{
				Item: &api.Assignment_Secret{
					Secret: &api.Secret{ID: "secret-1"},
				},
			},
			Action: api.AssignmentChange_AssignmentActionUpdate,
		},
		{
			Assignment: &api.Assignment{
				Item: &api.Assignment_Config{
					Config: &api.Config{ID: "config-1"},
				},
			},
			Action: api.AssignmentChange_AssignmentActionUpdate,
		},
	}

	expectedTasks := []*api.Task{
		{ID: "task-1"},
		{ID: "task-2"},
	}

	expectedSecrets := []*api.Secret{
		{ID: "secret-1"},
	}

	expectedConfigs := []*api.Config{
		{ID: "config-1"},
	}

	expectedAssigned := []*api.Task{
		{ID: "task-1"},
		{ID: "task-2"},
	}

	var (
		tasks    []*api.Task
		assigned []*api.Task
	)
	assert.NoError(t, worker.Assign(ctx, changeSet))

	assert.NoError(t, worker.db.View(func(tx *bolt.Tx) error {
		return WalkTasks(tx, func(task *api.Task) error {
			tasks = append(tasks, task)
			if TaskAssigned(tx, task.ID) {
				assigned = append(assigned, task)
			}
			return nil
		})
	}))

	assert.Equal(t, expectedTasks, tasks)
	assert.Equal(t, expectedAssigned, assigned)
	for _, secret := range expectedSecrets {
		secret, err := executor.Secrets().Get(secret.ID)
		assert.NoError(t, err)
		assert.NotNil(t, secret)
	}
	for _, config := range expectedConfigs {
		config, err := executor.Configs().Get(config.ID)
		assert.NoError(t, err)
		assert.NotNil(t, config)
	}

	err := worker.Assign(ctx, nil)
	assert.Nil(t, err)

	err = worker.Wait(ctx)
	assert.Nil(t, err)

	assigned = assigned[:0]

	assert.NoError(t, worker.db.View(func(tx *bolt.Tx) error {
		return WalkTasks(tx, func(task *api.Task) error {
			if TaskAssigned(tx, task.ID) {
				assigned = append(assigned, task)
			}
			return nil
		})
	}))
	assert.Equal(t, len(assigned), 0)
}

func TestWorkerUpdate(t *testing.T) {
	db, cleanup := storageTestEnv(t)
	defer cleanup()

	ctx := context.Background()
	executor := &mockExecutor{t: t, dependencies: NewDependencyManager()}
	worker := newWorker(db, executor, &testPublisherProvider{})
	reporter := statusReporterFunc(func(ctx context.Context, taskID string, status *api.TaskStatus) error {
		log.G(ctx).WithFields(logrus.Fields{"task.id": taskID, "status": status}).Info("status update received")
		return nil
	})

	worker.Listen(ctx, reporter)

	// create existing task/secret/config
	assert.NoError(t, worker.Assign(ctx, []*api.AssignmentChange{
		{
			Assignment: &api.Assignment{
				Item: &api.Assignment_Task{
					Task: &api.Task{ID: "task-1"},
				},
			},
			Action: api.AssignmentChange_AssignmentActionUpdate,
		},
		{
			Assignment: &api.Assignment{
				Item: &api.Assignment_Secret{
					Secret: &api.Secret{ID: "secret-1"},
				},
			},
			Action: api.AssignmentChange_AssignmentActionUpdate,
		},
		{
			Assignment: &api.Assignment{
				Item: &api.Assignment_Config{
					Config: &api.Config{ID: "config-1"},
				},
			},
			Action: api.AssignmentChange_AssignmentActionUpdate,
		},
	}))

	for _, testcase := range []struct {
		changeSet        []*api.AssignmentChange
		expectedTasks    []*api.Task
		expectedSecrets  []*api.Secret
		expectedConfigs  []*api.Config
		expectedAssigned []*api.Task
	}{
		{ // handle nil changeSet case.
			expectedTasks: []*api.Task{
				{ID: "task-1"},
			},
			expectedSecrets: []*api.Secret{
				{ID: "secret-1"},
			},
			expectedConfigs: []*api.Config{
				{ID: "config-1"},
			},
			expectedAssigned: []*api.Task{
				{ID: "task-1"},
			},
		},
		{
			// no changes
			changeSet: []*api.AssignmentChange{
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Task{
							Task: &api.Task{ID: "task-1"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionUpdate,
				},
			},
			expectedTasks: []*api.Task{
				{ID: "task-1"},
			},
			expectedSecrets: []*api.Secret{
				{ID: "secret-1"},
			},
			expectedConfigs: []*api.Config{
				{ID: "config-1"},
			},
			expectedAssigned: []*api.Task{
				{ID: "task-1"},
			},
		},
		{
			// adding a secret and task
			changeSet: []*api.AssignmentChange{
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Task{
							Task: &api.Task{ID: "task-2"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionUpdate,
				},
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Secret{
							Secret: &api.Secret{ID: "secret-2"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionUpdate,
				},
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Config{
							Config: &api.Config{ID: "config-2"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionUpdate,
				},
			},
			expectedTasks: []*api.Task{
				{ID: "task-1"},
				{ID: "task-2"},
			},
			expectedSecrets: []*api.Secret{
				{ID: "secret-1"},
				{ID: "secret-2"},
			},
			expectedConfigs: []*api.Config{
				{ID: "config-1"},
				{ID: "config-2"},
			},
			expectedAssigned: []*api.Task{
				{ID: "task-1"},
				{ID: "task-2"},
			},
		},
		{
			// remove assigned task and secret, updating existing secret
			changeSet: []*api.AssignmentChange{
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Task{
							Task: &api.Task{ID: "task-1"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionRemove,
				},
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Secret{
							Secret: &api.Secret{ID: "secret-1"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionRemove,
				},
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Secret{
							Secret: &api.Secret{ID: "secret-2"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionUpdate,
				},
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Config{
							Config: &api.Config{ID: "config-1"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionRemove,
				},
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Config{
							Config: &api.Config{ID: "config-2"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionUpdate,
				},
			},
			expectedTasks: []*api.Task{
				{ID: "task-1"},
				{ID: "task-2"},
			},
			expectedSecrets: []*api.Secret{
				{ID: "secret-2"},
			},
			expectedConfigs: []*api.Config{
				{ID: "config-2"},
			},
			expectedAssigned: []*api.Task{
				{ID: "task-2"},
			},
		},
		{
			// removing nonexistent items doesn't fail
			changeSet: []*api.AssignmentChange{
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Task{
							Task: &api.Task{ID: "task-1"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionRemove,
				},
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Secret{
							Secret: &api.Secret{ID: "secret-1"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionRemove,
				},
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Task{
							Task: &api.Task{ID: "task-2"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionRemove,
				},
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Secret{
							Secret: &api.Secret{ID: "secret-2"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionRemove,
				},
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Config{
							Config: &api.Config{ID: "config-1"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionRemove,
				},
				{
					Assignment: &api.Assignment{
						Item: &api.Assignment_Config{
							Config: &api.Config{ID: "config-2"},
						},
					},
					Action: api.AssignmentChange_AssignmentActionRemove,
				},
			},
			expectedTasks: []*api.Task{
				{ID: "task-1"},
				{ID: "task-2"},
			},
		},
	} {
		assert.NoError(t, worker.Update(ctx, testcase.changeSet))

		var (
			tasks    []*api.Task
			assigned []*api.Task
		)
		assert.NoError(t, worker.db.View(func(tx *bolt.Tx) error {
			return WalkTasks(tx, func(task *api.Task) error {
				tasks = append(tasks, task)
				if TaskAssigned(tx, task.ID) {
					assigned = append(assigned, task)
				}
				return nil
			})
		}))

		assert.Equal(t, testcase.expectedTasks, tasks)
		assert.Equal(t, testcase.expectedAssigned, assigned)
		for _, secret := range testcase.expectedSecrets {
			secret, err := executor.Secrets().Get(secret.ID)
			assert.NoError(t, err)
			assert.NotNil(t, secret)
		}
		for _, config := range testcase.expectedConfigs {
			config, err := executor.Configs().Get(config.ID)
			assert.NoError(t, err)
			assert.NotNil(t, config)
		}
	}
}

type mockTaskController struct {
	t *testing.T
	exec.Controller
	task         *api.Task
	dependencies exec.DependencyGetter
}

func (mtc *mockTaskController) Remove(ctx context.Context) error {
	mtc.t.Log("(*mockTestController).Remove")
	return nil
}

func (mtc *mockTaskController) Close() error {
	mtc.t.Log("(*mockTestController).Close")
	return nil
}

type mockExecutor struct {
	t *testing.T
	exec.Executor
	dependencies exec.DependencyManager
}

func (m *mockExecutor) Controller(task *api.Task) (exec.Controller, error) {
	return &mockTaskController{t: m.t, task: task, dependencies: Restrict(m.dependencies, task)}, nil
}

func (m *mockExecutor) Secrets() exec.SecretsManager {
	return m.dependencies.Secrets()
}

func (m *mockExecutor) Configs() exec.ConfigsManager {
	return m.dependencies.Configs()
}


text: module.exports = require('./lib/datadriver');


text:
#include "Vdlkino.h"
#include "VdlkinoSerial.h"

/* VdlkinoSerial */

VdlkinoSerial::VdlkinoSerial(uint8_t digital, uint8_t analog, HardwareSerial *serial) : Vdlkino(digital, analog) {
  this->serial = serial;
}

VdlkinoBlock VdlkinoSerial::getBlock() {
  VdlkinoBlock block(this);
  char buffer[4];
  if (this->serial->readBytes(buffer, 4) == 4) {
    block.oper = buffer[0];
    block.pin = buffer[1];
    block.value = buffer[2] << 8 | buffer[3];
    block.valid = 1;
  }
  return block;
}

void VdlkinoSerial::replay(uint16_t value) {
  this->serial->write(value >> 8);
  this->serial->write(value & 0xff);
}

void VdlkinoSerial::run() {
  VdlkinoBlock block = this->getBlock();
  if (block.valid) {
    this->replay(block.run());
  }
}


text:
<resources>
    <string name="app_name">Stretch Renderer</string>
    <string name="location_permission_denied">Stretch Renderer could not open the raster because WRITE permission was denied.</string>
    <string name="chooseParam">Edit renderer</string>
    <string name="dialog_title">Stretch rendering parameters</string>
    <string name="data_sdcard_offline_dir">ArcGIS/samples/raster</string>
    <string name="raster_name">Shasta</string>
    <string name="max_value">Max value</string>
    <string name="min_value">Min value</string>
    <string name="stretch_type">Stretch type</string>
    <string name="standard_deviation">Std Dev</string>
</resources>


text:
class AddIndexToCiTriggerRequestsForCommitId < ActiveRecord::Migration
  include Gitlab::Database::MigrationHelpers

  DOWNTIME = false

  disable_ddl_transaction!

  def up
    add_concurrent_index :ci_trigger_requests, :commit_id
  end

  def down
    remove_index :ci_trigger_requests, :commit_id if index_exists? :ci_trigger_requests, :commit_id
  end
end


text:
package runtime

import (
	"os"
	"syscall"
)

func FDLimit() (uint64, error) {
	var rlimit syscall.Rlimit
	if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit); err != nil {
		return 0, err
	}
	return rlimit.Cur, nil
}

func FDUsage() (uint64, error) {
	return countFiles("/proc/self/fd")
}

// countFiles reads the directory named by dirname and returns the count.
// This is same as stdlib "io/ioutil.ReadDir" but without sorting.
func countFiles(dirname string) (uint64, error) {
	f, err := os.Open(dirname)
	if err != nil {
		return 0, err
	}
	list, err := f.Readdir(-1)
	f.Close()
	if err != nil {
		return 0, err
	}
	return uint64(len(list)), nil
}


text:
CREATE SEQUENCE IF NOT EXISTS alert_alert_id_seq
	AS integer
	START WITH 1
	INCREMENT BY 1
	NO MAXVALUE
	NO MINVALUE
	CACHE 1;

ALTER SEQUENCE sequence_10
	AS bigint;


text:
'''
roots around in Illumina App dirs for csv results and joins various samples (provided by SampleSheet) into table
'''
__author__ = "Sonia Timberlake"

import pandas as pd
import os
import sys

def parse_SampleSheet(SampleSheet_file):
    ''' rudimentary Miseq SampleSheet.csv --> df parser '''
    with open(SampleSheet_file,'r') as f: lines=f.readlines()
    start_line = [i for i in range(len(lines)) if 'Data' in lines[i] ]
    assert(len(start_line)==1)
    table = [line.strip().split(',') for line in lines[1+start_line[0]:]]
    df = pd.DataFrame( data=table[1:], columns = table[0])
    df.Sample_ID = df.Sample_ID.apply(lambda x: x.strip())
    return df

def __old():
    indir = '/shared/soniat/misc/basespace_FT/mount/Projects/MiSeq M02127 2016 Run206/AppResults/'
    dfs={}
    for samp_id, bcnum in dict(zip(['UC-23 B','UC-23 A','UC-22 C'], [73,85,97])).items():
        infile = '{}/{} (2)/Files/{}_S{}.summary.csv'.format(indir, samp_id, samp_id.replace(' ','-'), bcnum)
        dfs[samp_id] = pd.read_table(infile, sep=',')
        dfs[samp_id].set_index( list(dfs[samp_id].columns[:-2]) , inplace=True)
        dfs[samp_id].drop( "%_hits", axis=1, inplace=True)
    all = pd.concat(dfs, axis=1)
    return all

def join_sample_csvs(AppResults_dir,
                     samp_ids=['08-120','UC-23 B','UC-23 A','UC-22 C'],
                     samp_id_suffix=' (2)' ):
    ''' find and read csvs from basespace AppResults_dir dir '''
    dfs = {}
    for samp_id in samp_ids:
        sample_path = '{}/{}{}/Files/'.format(AppResults_dir, samp_id, samp_id_suffix)
        try:
            file_path = [sample_path + fn for fn in os.listdir(sample_path)
                          if fn.endswith('csv') ][0]
            # (fn.startswith(samp_id.replace(' ','-'))
            print('reading csv {} ...'.format(file_path), file=sys.stderr)
            dfs[samp_id] = pd.read_table(file_path, sep=',')
            dfs[samp_id].set_index( list(dfs[samp_id].columns[:-2]) , inplace=True)
            dfs[samp_id].drop( "%_hits", axis=1, inplace=True)
        except:
            print('WARNING: no csv for samp_id {} found in {}'.format(samp_id ,sample_path ), file=sys.stderr)
    try:
        all = pd.concat(dfs, axis=1)
        all.columns = all.columns.get_level_values(0)
    except:
        all = pd.DataFrame()
    return all


text:
namespace Dapper.Net.Patterns.Chainable.Syntax.Implements {

    public interface IHasNoLock<out TSyntax> where TSyntax : ISqlSyntax {
        bool NoLockRaw { get; }
        TSyntax NoLock();
    }

}