text:
package org.apache.hive.service.cli.session;

import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.QueryDisplay;
import org.apache.hadoop.hive.ql.QueryInfo;
import org.apache.hadoop.hive.ql.log.PerfLogger;
import org.apache.hadoop.hive.ql.plan.api.StageType;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hive.service.cli.OperationHandle;
import org.apache.hive.service.cli.SessionHandle;
import org.apache.hive.service.rpc.thrift.TProtocolVersion;
import org.apache.hive.tmpl.QueryProfileTmpl;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;

/**
 * Test QueryDisplay and its consumers like WebUI.
 */
public class TestQueryDisplay {
  private HiveConf conf;
  private SessionManager sessionManager;

  @Before
  public void setup() {
    conf = new HiveConf();
    conf.set("hive.support.concurrency", "false");

    sessionManager = new SessionManager(null, true);
    sessionManager.init(conf);
  }

  /**
   * Test if query display captures information on current/historic SQL operations.
   */
  @Test
  public void testQueryDisplay() throws Exception {
    HiveSession session = sessionManager
        .createSession(new SessionHandle(TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V8),
            TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V8, "testuser", "", "",
            new HashMap<String, String>(), false, "");
    session.getSessionState().setIsHiveServerQuery(false);
    SessionState.start(conf);
    OperationHandle opHandle1 = session.executeStatement("show databases", null);
    SessionState.start(conf);
    OperationHandle opHandle2 = session.executeStatement("show tables", null);

    List<QueryInfo> liveSqlOperations, historicSqlOperations;
    liveSqlOperations = sessionManager.getOperationManager().getLiveQueryInfos();
    historicSqlOperations = sessionManager.getOperationManager().getHistoricalQueryInfos();
    Assert.assertEquals(liveSqlOperations.size(), 2);
    Assert.assertEquals(historicSqlOperations.size(), 0);
    verifyDDL(liveSqlOperations.get(0), "show databases", opHandle1.getHandleIdentifier().toString(), false);
    verifyDDL(liveSqlOperations.get(1), "show tables", opHandle2.getHandleIdentifier().toString(), false);

    session.closeOperation(opHandle1);
    liveSqlOperations = sessionManager.getOperationManager().getLiveQueryInfos();
    historicSqlOperations = sessionManager.getOperationManager().getHistoricalQueryInfos();
    Assert.assertEquals(liveSqlOperations.size(), 1);
    Assert.assertEquals(historicSqlOperations.size(), 1);
    verifyDDL(historicSqlOperations.get(0), "show databases", opHandle1.getHandleIdentifier().toString(), true);
    verifyDDL(liveSqlOperations.get(0), "show tables", opHandle2.getHandleIdentifier().toString(), false);

    session.closeOperation(opHandle2);
    liveSqlOperations = sessionManager.getOperationManager().getLiveQueryInfos();
    historicSqlOperations = sessionManager.getOperationManager().getHistoricalQueryInfos();
    Assert.assertEquals(liveSqlOperations.size(), 0);
    Assert.assertEquals(historicSqlOperations.size(), 2);
    verifyDDL(historicSqlOperations.get(1), "show databases", opHandle1.getHandleIdentifier().toString(), true);
    verifyDDL(historicSqlOperations.get(0), "show tables", opHandle2.getHandleIdentifier().toString(), true);

    session.close();
  }

  /**
   * Test if webui captures information on current/historic SQL operations.
   */
  @Test
  public void testWebUI() throws Exception {
    HiveSession session = sessionManager
        .createSession(new SessionHandle(TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V8),
            TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V8, "testuser", "", "",
            new HashMap<String, String>(), false, "");

    SessionState.start(conf);
    OperationHandle opHandle1 = session.executeStatement("show databases", null);
    SessionState.start(conf);
    OperationHandle opHandle2 = session.executeStatement("show tables", null);

    verifyDDLHtml("show databases", opHandle1.getHandleIdentifier().toString());
    verifyDDLHtml("show tables", opHandle2.getHandleIdentifier().toString());

    session.closeOperation(opHandle1);
    session.closeOperation(opHandle2);

    verifyDDLHtml("show databases", opHandle1.getHandleIdentifier().toString());
    verifyDDLHtml("show tables", opHandle2.getHandleIdentifier().toString());

    session.close();
  }

  /**
   * Test for the HiveConf option HIVE_SERVER2_WEBUI_EXPLAIN_OUTPUT.
   */
  @Test
  public void checkWebuiExplainOutput() throws Exception {

    //check cases when HIVE_SERVER2_WEBUI_EXPLAIN_OUTPUT is set and not set
    boolean[] webuiExplainConfValues = new boolean[]{true, false};

    for (boolean confValue : webuiExplainConfValues) {
      conf.setBoolVar(HiveConf.ConfVars.HIVE_SERVER2_WEBUI_EXPLAIN_OUTPUT, confValue);
      HiveSession session = sessionManager
          .createSession(new SessionHandle(TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V8),
              TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V8, "testuser", "", "",
              new HashMap<String, String>(), false, "");
      SessionState.start(conf);

      OperationHandle opHandle = session.executeStatement("show tables", null);
      session.closeOperation(opHandle);
      //STAGE PLANS is something which will be shown as part of EXPLAIN query
      verifyDDLHtml("STAGE PLANS", opHandle.getHandleIdentifier().toString(), confValue);
      //Check that the following message is not shown when this option is set
      verifyDDLHtml(
          "Set configuration hive.server2.webui.explain.output to true to view future query plans",
          opHandle.getHandleIdentifier().toString(), !confValue);
      session.close();
    }
  }

  /**
   * Test for the HiveConf options HIVE_SERVER2_WEBUI_SHOW_GRAPH,
   * HIVE_SERVER2_WEBUI_MAX_GRAPH_SIZE.
   */
  @Test
  public void checkWebuiShowGraph() throws Exception {
    // WebUI-related boolean confs must be set before build, since the implementation of
    // QueryProfileTmpl.jamon depends on them.
    // They depend on HIVE_SERVER2_WEBUI_EXPLAIN_OUTPUT being set to true.
    conf.setBoolVar(HiveConf.ConfVars.HIVE_SERVER2_WEBUI_EXPLAIN_OUTPUT, true);
    conf.setBoolVar(HiveConf.ConfVars.HIVE_SERVER2_WEBUI_SHOW_GRAPH, true);

    HiveSession session = sessionManager
        .createSession(new SessionHandle(TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V8),
            TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V8, "testuser", "", "",
            new HashMap<String, String>(), false, "");
    SessionState.start(conf);

    session.getSessionConf()
        .setIntVar(HiveConf.ConfVars.HIVE_SERVER2_WEBUI_MAX_GRAPH_SIZE, 0);
    testGraphDDL(session, true);
    session.getSessionConf()
        .setIntVar(HiveConf.ConfVars.HIVE_SERVER2_WEBUI_MAX_GRAPH_SIZE, 40);
    testGraphDDL(session, false);

    session.close();
    resetConfToDefaults();
  }

  private void testGraphDDL(HiveSession session, boolean exceedMaxGraphSize) throws Exception {
    OperationHandle opHandleGraph = session.executeStatement("show tables", null);
    session.closeOperation(opHandleGraph);

    // Check for a query plan. If the graph size exceeds the max allowed, none should appear.
    verifyDDLHtml("Query information not available.",
        opHandleGraph.getHandleIdentifier().toString(), exceedMaxGraphSize);
    verifyDDLHtml("STAGE DEPENDENCIES",
        opHandleGraph.getHandleIdentifier().toString(), !exceedMaxGraphSize);
    // Check that if plan Json is there, it is not empty
    verifyDDLHtml("jsonPlan = {}", opHandleGraph.getHandleIdentifier().toString(), false);
  }

  /**
   * Test for the HiveConf option HIVE_SERVER2_WEBUI_SHOW_STATS, which is available for MapReduce
   * jobs only.
   */
  @Test
  public void checkWebUIShowStats() throws Exception {
    // WebUI-related boolean confs must be set before build. HIVE_SERVER2_WEBUI_SHOW_STATS depends
    // on HIVE_SERVER2_WEBUI_EXPLAIN_OUTPUT and HIVE_SERVER2_WEBUI_SHOW_GRAPH being set to true.
    conf.setVar(HiveConf.ConfVars.HIVE_EXECUTION_ENGINE, "mr");
    conf.setBoolVar(HiveConf.ConfVars.HIVE_SERVER2_WEBUI_EXPLAIN_OUTPUT, true);
    conf.setBoolVar(HiveConf.ConfVars.HIVE_SERVER2_WEBUI_SHOW_GRAPH, true);
    conf.setIntVar(HiveConf.ConfVars.HIVE_SERVER2_WEBUI_MAX_GRAPH_SIZE, 40);
    conf.setBoolVar(HiveConf.ConfVars.HIVE_SERVER2_WEBUI_SHOW_STATS, true);

    HiveSession session = sessionManager
        .createSession(new SessionHandle(TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V8),
            TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V8, "testuser", "", "",
            new HashMap<String, String>(), false, "");
    SessionState.start(conf);

    OperationHandle opHandleSetup =
        session.executeStatement("CREATE TABLE statsTable (i int)", null);
    session.closeOperation(opHandleSetup);
    OperationHandle opHandleMrQuery =
        session.executeStatement("INSERT INTO statsTable VALUES (0)", null);
    session.closeOperation(opHandleMrQuery);

    // INSERT queries include  a MapReduce task.
    verifyDDLHtml("Counters", opHandleMrQuery.getHandleIdentifier().toString(), true);

    session.close();
    resetConfToDefaults();
  }

  private void resetConfToDefaults() {
    conf.setBoolVar(HiveConf.ConfVars.HIVE_SERVER2_WEBUI_EXPLAIN_OUTPUT, false);
    conf.setBoolVar(HiveConf.ConfVars.HIVE_SERVER2_WEBUI_SHOW_GRAPH, false);
    conf.setBoolVar(HiveConf.ConfVars.HIVE_SERVER2_WEBUI_SHOW_STATS, false);
    conf.setIntVar(HiveConf.ConfVars.HIVE_SERVER2_WEBUI_MAX_GRAPH_SIZE, 25);
  }

  private void verifyDDL(QueryInfo queryInfo, String stmt, String handle, boolean finished) {

    Assert.assertEquals(queryInfo.getUserName(), "testuser");
    Assert.assertEquals(queryInfo.getExecutionEngine(), "mr");
    Assert.assertEquals(queryInfo.getOperationId(), handle);
    Assert.assertTrue(queryInfo.getBeginTime() > 0 && queryInfo.getBeginTime() <= System.currentTimeMillis());

    if (finished) {
      Assert.assertTrue(
          queryInfo.getEndTime() > 0 && queryInfo.getEndTime() >= queryInfo.getBeginTime()
              && queryInfo.getEndTime() <= System.currentTimeMillis());
      Assert.assertTrue(queryInfo.getRuntime() > 0);
    } else {
      Assert.assertNull(queryInfo.getEndTime());
      //For runtime, query may have finished.
    }

    QueryDisplay qDisplay1 = queryInfo.getQueryDisplay();
    Assert.assertNotNull(qDisplay1);
    Assert.assertEquals(qDisplay1.getQueryString(), stmt);
    Assert.assertNotNull(qDisplay1.getExplainPlan());
    Assert.assertNull(qDisplay1.getErrorMessage());

    Assert.assertTrue(qDisplay1.getHmsTimings(QueryDisplay.Phase.COMPILATION).size() > 0);
    Assert.assertTrue(qDisplay1.getHmsTimings(QueryDisplay.Phase.EXECUTION).size() > 0);

    Assert.assertTrue(qDisplay1.getPerfLogStarts(QueryDisplay.Phase.COMPILATION).size() > 0);
    Assert.assertTrue(qDisplay1.getPerfLogEnds(QueryDisplay.Phase.COMPILATION).size() > 0);

    Assert.assertTrue(qDisplay1.getPerfLogStarts(QueryDisplay.Phase.COMPILATION).size() > 0);
    Assert.assertTrue(qDisplay1.getPerfLogEnds(QueryDisplay.Phase.COMPILATION).size() > 0);

    Assert.assertTrue(qDisplay1.getPerfLogStarts(QueryDisplay.Phase.COMPILATION).containsKey(PerfLogger.COMPILE));
    Assert.assertFalse(qDisplay1.getPerfLogStarts(QueryDisplay.Phase.EXECUTION).containsKey(PerfLogger.COMPILE));
    Assert.assertTrue(qDisplay1.getPerfLogStarts(QueryDisplay.Phase.EXECUTION).containsKey(PerfLogger.DRIVER_EXECUTE));
    Assert.assertFalse(qDisplay1.getPerfLogStarts(QueryDisplay.Phase.COMPILATION)
        .containsKey(PerfLogger.DRIVER_EXECUTE));

    Assert.assertEquals(qDisplay1.getTaskDisplays().size(), 1);
    QueryDisplay.TaskDisplay tInfo1 = qDisplay1.getTaskDisplays().get(0);
    Assert.assertEquals(tInfo1.getTaskId(), "Stage-0");
    Assert.assertEquals(tInfo1.getTaskType(), StageType.DDL);
    Assert.assertTrue(tInfo1.getBeginTime() > 0 && tInfo1.getBeginTime() <= System.currentTimeMillis());
    Assert.assertTrue(tInfo1.getEndTime() > 0 && tInfo1.getEndTime() >= tInfo1.getBeginTime()
        && tInfo1.getEndTime() <= System.currentTimeMillis());
    Assert.assertEquals(tInfo1.getStatus(), "Success, ReturnVal 0");
  }

  /**
   * Sanity check if basic information is delivered in this html.  Let's not go too crazy and
   * assert each element, to make it easier to add UI improvements.
   */
  private void verifyDDLHtml(String stmt, String opHandle) throws Exception {
    verifyDDLHtml(stmt, opHandle, true);
  }

  private void verifyDDLHtml(String stmt, String opHandle, boolean assertCondition) throws Exception {
    StringWriter sw = new StringWriter();
    QueryInfo queryInfo = sessionManager.getOperationManager().getQueryInfo(opHandle);
    HiveConf hiveConf = sessionManager.getOperationManager().getHiveConf();
    new QueryProfileTmpl().render(sw, queryInfo, hiveConf);
    String html = sw.toString();
    Assert.assertEquals(assertCondition, html.contains(stmt));

    Assert.assertTrue(html.contains("testuser"));
  }

}


text:
package com.rockagen.gnext.service.spring.security.extension;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.context.ApplicationContextException;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.Assert;

/**
 * An extension for spring security {@link org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl}
 * @author RA
 * @see org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl
 */
public class BasicJdbcDaoImpl extends JdbcDaoSupport implements
		UserDetailsService {

	// ~ Instance fields ==================================================

	/**
     *
     */
	public static final String DEF_USERS_BY_USERNAME_QUERY = "select username,password,enabled "
			+ "from users " + "where username = ?";
	public static final String DEF_AUTHORITIES_BY_USERNAME_QUERY = "select username,authority "
			+ "from authorities " + "where username = ?";
	public static final String DEF_GROUP_AUTHORITIES_BY_USERNAME_QUERY = "select g.id, g.group_name, ga.authority "
			+ "from groups g, group_members gm, group_authorities ga "
			+ "where gm.username = ? "
			+ "and g.id = ga.group_id "
			+ "and g.id = gm.group_id";

	protected MessageSourceAccessor messages = SpringSecurityMessageSource
			.getAccessor();

	private String authoritiesByUsernameQuery;
	private String groupAuthoritiesByUsernameQuery;
	private String usersByUsernameQuery;
	private String rolePrefix = "";
	private boolean usernameBasedPrimaryKey = true;
	private boolean enableAuthorities = true;
	private boolean enableGroups;

	// ~ Constructors
	// ===================================================================================================

	public BasicJdbcDaoImpl() {
		usersByUsernameQuery = DEF_USERS_BY_USERNAME_QUERY;
		authoritiesByUsernameQuery = DEF_AUTHORITIES_BY_USERNAME_QUERY;
		groupAuthoritiesByUsernameQuery = DEF_GROUP_AUTHORITIES_BY_USERNAME_QUERY;
	}

	// ~ Methods
	// ========================================================================================================

	/**
	 * Allows subclasses to add their own granted authorities to the list to be
	 * returned in the <tt>UserDetails</tt>.
	 *
	 * @param username
	 *            the username, for use by finder methods
	 * @param authorities
	 *            the current granted authorities, as populated from the
	 *            authoritiesByUsername mapping
	 */
	protected void addCustomAuthorities(String username,
			List<GrantedAuthority> authorities) {
	}

	public String getUsersByUsernameQuery() {
		return usersByUsernameQuery;
	}

	protected void initDao() throws ApplicationContextException {
		Assert.isTrue(enableAuthorities || enableGroups,
				"Use of either authorities or groups must be enabled");
	}

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		// extend
		List<BasicSecurityUser> users = loadUsersByUsername(username);

		if (users.size() == 0) {
			logger.debug("Query returned no results for user '" + username
					+ "'");
			throw new UsernameNotFoundException(messages.getMessage(
					"JdbcDaoImpl.notFound", new Object[] { username }));
		}

		BasicSecurityUser user = users.get(0); // contains no GrantedAuthority[]

		Set<GrantedAuthority> dbAuthsSet = new HashSet<GrantedAuthority>();

		if (enableAuthorities) {
			dbAuthsSet.addAll(loadUserAuthorities(user.getUsername()));
		}

		if (enableGroups) {
			dbAuthsSet.addAll(loadGroupAuthorities(user.getUsername()));
		}

		List<GrantedAuthority> dbAuths = new ArrayList<GrantedAuthority>(
				dbAuthsSet);

		addCustomAuthorities(user.getUsername(), dbAuths);

		if (dbAuths.size() == 0) {
			logger.debug("User '" + username
					+ "' has no authorities and will be treated as 'not found'");
			throw new UsernameNotFoundException(messages.getMessage(
					"JdbcDaoImpl.noAuthority", new Object[] { username },
					"User {0} has no GrantedAuthority"));
		}

		return createUserDetails(username, user, dbAuths);
	}

	/**
	 * Executes the SQL <tt>usersByUsernameQuery</tt> and returns a list of
	 * UserDetails objects. There should normally only be one matching user.
	 */
	protected List<BasicSecurityUser> loadUsersByUsername(String username) {
		return getJdbcTemplate().query(usersByUsernameQuery,
				new String[] { username }, new RowMapper<BasicSecurityUser>() {
					public BasicSecurityUser mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						String username = rs.getString(1);
						String password = rs.getString(2);
						boolean enabled = rs.getBoolean(3);
						String mername = rs.getString(4);
						String email = rs.getString(5);
						String latestIp=rs.getString(6);
						return new BasicSecurityUser(username, password,
								enabled, true, true, true,
								AuthorityUtils.NO_AUTHORITIES, mername, email,latestIp);
					}

				});
	}

	/**
	 * Loads authorities by executing the SQL from
	 * <tt>authoritiesByUsernameQuery</tt>.
	 *
	 * @return a list of GrantedAuthority objects for the user
	 */
	protected List<GrantedAuthority> loadUserAuthorities(String username) {
		return getJdbcTemplate().query(authoritiesByUsernameQuery,
				new String[] { username }, new RowMapper<GrantedAuthority>() {
					public GrantedAuthority mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						String roleName = rolePrefix + rs.getString(2);
						SimpleGrantedAuthority authority = new SimpleGrantedAuthority(
								roleName);
						return authority;
					}
				});
	}

	/**
	 * Loads authorities by executing the SQL from
	 * <tt>groupAuthoritiesByUsernameQuery</tt>.
	 *
	 * @return a list of GrantedAuthority objects for the user
	 */
	protected List<GrantedAuthority> loadGroupAuthorities(String username) {
		return getJdbcTemplate().query(groupAuthoritiesByUsernameQuery,
				new String[] { username }, new RowMapper<GrantedAuthority>() {
					public GrantedAuthority mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						String roleName = getRolePrefix() + rs.getString(3);
						SimpleGrantedAuthority authority = new SimpleGrantedAuthority(
								roleName);

						return authority;
					}
				});
	}

	/**
	 * Can be overridden to customize the creation of the final
	 * UserDetailsObject which is returned by the <tt>loadUserByUsername</tt>
	 * method.
	 *

	 * NOTE: extend
	 *

	 *
	 * @param username
	 *            the name originally passed to loadUserByUsername
	 * @param userFromUserQuery
	 *            the object returned from the execution of the
	 * @param combinedAuthorities
	 *            the combined array of authorities from all the authority
	 *            loading queries.
	 * @return the final UserDetails which should be used in the system.
	 */
	protected UserDetails createUserDetails(String username,
			BasicSecurityUser userFromUserQuery,
			List<GrantedAuthority> combinedAuthorities) {
		String returnUsername = userFromUserQuery.getUsername();

		if (!usernameBasedPrimaryKey) {
			returnUsername = username;
		}

		return new BasicSecurityUser(returnUsername,
				userFromUserQuery.getPassword(), userFromUserQuery.isEnabled(),
				true, true, true, combinedAuthorities,
				userFromUserQuery.getNickname(), userFromUserQuery.getEmail(),userFromUserQuery.getLatestIp());
	}

	/**
	 * Allows the default query string used to retrieve authorities based on
	 * username to be overridden, if default table or column names need to be
	 * changed. The default query is {@link #DEF_AUTHORITIES_BY_USERNAME_QUERY};
	 * when modifying this query, ensure that all returned columns are mapped
	 * back to the same column names as in the default query.
	 *
	 * @param queryString
	 *            The SQL query string to set
	 */
	public void setAuthoritiesByUsernameQuery(String queryString) {
		authoritiesByUsernameQuery = queryString;
	}

	protected String getAuthoritiesByUsernameQuery() {
		return authoritiesByUsernameQuery;
	}

	/**
	 * Allows the default query string used to retrieve group authorities based
	 * on username to be overridden, if default table or column names need to be
	 * changed. The default query is
	 * {@link #DEF_GROUP_AUTHORITIES_BY_USERNAME_QUERY}; when modifying this
	 * query, ensure that all returned columns are mapped back to the same
	 * column names as in the default query.
	 *
	 * @param queryString
	 *            The SQL query string to set
	 */
	public void setGroupAuthoritiesByUsernameQuery(String queryString) {
		groupAuthoritiesByUsernameQuery = queryString;
	}

	/**
	 * Allows a default role prefix to be specified. If this is set to a
	 * non-empty value, then it is automatically prepended to any roles read in
	 * from the db. This may for example be used to add the <tt>ROLE_</tt>
	 * prefix expected to exist in role names (by default) by some other Spring
	 * Security classes, in the case that the prefix is not already present in
	 * the db.
	 *
	 * @param rolePrefix
	 *            the new prefix
	 */
	public void setRolePrefix(String rolePrefix) {
		this.rolePrefix = rolePrefix;
	}

	protected String getRolePrefix() {
		return rolePrefix;
	}

	/**
	 * If true (the default), indicates the
	 * {@link #getUsersByUsernameQuery()} returns a username in response to a
	 * query. If false, indicates that a primary key is used
	 * instead. If set to true, the class will use the
	 * database-derived username in the returned UserDetails. If
	 * false, the class will use the
	 * {@link #loadUserByUsername(String)} derived username in the returned
	 * UserDetails.
	 *
	 * @param usernameBasedPrimaryKey
	 *            true if the mapping queries return the username
	 *            String, or false if the mapping
	 *            returns a database primary key.
	 */
	public void setUsernameBasedPrimaryKey(boolean usernameBasedPrimaryKey) {
		this.usernameBasedPrimaryKey = usernameBasedPrimaryKey;
	}

	protected boolean isUsernameBasedPrimaryKey() {
		return usernameBasedPrimaryKey;
	}

	/**
	 * Allows the default query string used to retrieve users based on username
	 * to be overridden, if default table or column names need to be changed.
	 * The default query is {@link #DEF_USERS_BY_USERNAME_QUERY}; when modifying
	 * this query, ensure that all returned columns are mapped back to the same
	 * column names as in the default query. If the 'enabled' column does not
	 * exist in the source database, a permanent true value for this column may
	 * be returned by using a query similar to
	 *
	 *

	 * "select username,password,'true' as enabled from users where username = ?"
	 *

	 *
	 * @param usersByUsernameQueryString
	 *            The query string to set
	 */
	public void setUsersByUsernameQuery(String usersByUsernameQueryString) {
		this.usersByUsernameQuery = usersByUsernameQueryString;
	}

	protected boolean getEnableAuthorities() {
		return enableAuthorities;
	}

	/**
	 * Enables loading of authorities (roles) from the authorities table.
	 * Defaults to true
	 */
	public void setEnableAuthorities(boolean enableAuthorities) {
		this.enableAuthorities = enableAuthorities;
	}

	protected boolean getEnableGroups() {
		return enableGroups;
	}

	/**
	 * Enables support for group authorities. Defaults to false
	 *
	 * @param enableGroups
	 */
	public void setEnableGroups(boolean enableGroups) {
		this.enableGroups = enableGroups;
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace matacms\rbac\models;

use matacms\rbac\components\DbManager;
use matacms\rbac\validators\RbacValidator;
use Yii;
use yii\base\InvalidConfigException;
use yii\base\Model;
use yii\helpers\ArrayHelper;

class Assignment extends Model
{
	/** @var array */
    public $items = [];

	/** @var integer */
    public $user_id;

    /** @var boolean */
    public $updated = false;

	/** @var DbManager */
    protected $manager;

    /** @inheritdoc */
    public function init()
    {
        parent::init();
        $this->manager = Yii::$app->authManager;
        if ($this->user_id !== null) {
            $this->items = array_keys($this->manager->getItemsByUser($this->user_id));
        }
    }

    /** @inheritdoc */
    public function rules()
    {
        return [
            ['items', RbacValidator::className()],
            ['user_id', 'integer']
        ];
    }

    /**
     * Updates auth assignments for user.
     * @return boolean
     */
    public function updateAssignments()
    {
        if ($this->user_id === null) {
            return false;
        }

        if (!$this->validate()) {
            return false;
        }

        if (!is_array($this->items)) {
            $this->items = [];
        }

        $assignedItems = $this->manager->getItemsByUser($this->user_id);
        $assignedItemsNames = array_keys($assignedItems);

        foreach (array_diff($assignedItemsNames, $this->items) as $item) {
            $this->manager->revoke($assignedItems[$item], $this->user_id);
        }

        foreach (array_diff($this->items, $assignedItemsNames) as $item) {
            $this->manager->assign($this->manager->getItem($item), $this->user_id);
        }

        $this->updated = true;

        return true;
    }

    /**
     * Returns all available auth items to be attached to user.
     * @return array
     */
    public function getAvailableItems()
    {
        return ArrayHelper::map($this->manager->getItems(), 'name', function ($item) {
            return empty($item->description)
                ? $item->name
                : $item->name . ' (' . $item->description . ')';
        });
    }
}


text:
#include "stdafx.h"
#include "moose.h"
#include <template_data.h>
#include <fstream>

#define THRESHOLD 30

/// Create filter shell
ADTF_FILTER_PLUGIN("Moose Filter", OID_ADTF_MOOSE_FILTER, MooseFilter);

MooseFilter::MooseFilter(const tChar* __info):cFilter(__info)
{
    LOG_INFO("Constructed");
}

MooseFilter::~MooseFilter()
{

}

tResult MooseFilter::Init(tInitStage eStage, __exception)
{
    LOG_INFO("Init yo");
    // never miss calling the parent implementation!!
    RETURN_IF_FAILED(cFilter::Init(eStage, __exception_ptr))

    // Copy-pasted code from Carvisualization.cpp that processes sensor data. --------------------------------------------------------------------------
    cObjectPtr<IMediaDescriptionManager> pDescManager;
    RETURN_IF_FAILED(_runtime->GetObject(OID_ADTF_MEDIA_DESCRIPTION_MANAGER,IID_ADTF_MEDIA_DESCRIPTION_MANAGER,(tVoid**)&pDescManager,__exception_ptr));

    //input descriptor
    tChar const * strDescSignalValue = pDescManager->GetMediaDescription("tSignalValue");
    RETURN_IF_POINTER_NULL(strDescSignalValue);
    cObjectPtr<IMediaType> pTypeSignalValue = new cMediaType(0, 0, 0, "tSignalValue", strDescSignalValue,IMediaDescription::MDF_DDL_DEFAULT_VERSION);
    RETURN_IF_FAILED(pTypeSignalValue->GetInterface(IID_ADTF_MEDIA_TYPE_DESCRIPTION, (tVoid**)&m_pCoderDescSignalInput));

    // End of copypasta ---------------------------------------------------------------------------------------------------------------------------------

    // in StageFirst you can create and register your static pins.
    if (eStage == StageFirst)
    {
        // ----- Input pins

        // get a media type for the input pin
        cObjectPtr<IMediaType> pInputType;
        RETURN_IF_FAILED(AllocMediaType(&pInputType, MEDIA_TYPE_TEMPLATE, MEDIA_SUBTYPE_TEMPLATE, __exception_ptr));

        // create and register the input pin
        // front-left US-sensor
        RETURN_IF_FAILED(input_uss_front_left_.Create("input_uss_front_left", new cMediaType(0, 0, 0, "tSignalValue"), static_cast<IPinEventSink*>(this)));
        RETURN_IF_FAILED(RegisterPin(&input_uss_front_left_));
        // front-right US-sensor
        RETURN_IF_FAILED(input_uss_front_right_.Create("input_uss_front_right", new cMediaType(0, 0, 0, "tSignalValue"), static_cast<IPinEventSink*>(this)));
        RETURN_IF_FAILED(RegisterPin(&input_uss_front_right_));

        // -----
        // Output pins
        // -----
        tChar const * strDescBoolSignalValue = pDescManager->GetMediaDescription("tBoolSignalValue");
        RETURN_IF_POINTER_NULL(strDescBoolSignalValue);
        cObjectPtr<IMediaType> pTypeBoolSignalValueOutput = new cMediaType(0, 0, 0, "tBoolSignalValue", strDescBoolSignalValue,IMediaDescription::MDF_DDL_DEFAULT_VERSION);
		RETURN_IF_FAILED(pTypeBoolSignalValueOutput->GetInterface(IID_ADTF_MEDIA_TYPE_DESCRIPTION, (tVoid**)&m_pCoderDescBoolSignalOutput));

        tChar const * strDescSignalValueOutput = pDescManager->GetMediaDescription("tSignalValue");
        RETURN_IF_POINTER_NULL(strDescSignalValueOutput);
        cObjectPtr<IMediaType> pTypeSignalValueOutput = new cMediaType(0, 0, 0, "tSignalValue", strDescSignalValueOutput,IMediaDescription::MDF_DDL_DEFAULT_VERSION);
        RETURN_IF_FAILED(pTypeSignalValueOutput->GetInterface(IID_ADTF_MEDIA_TYPE_DESCRIPTION, (tVoid**)&m_pCoderDescSignalOutput));

        // Headlight Output
		RETURN_IF_FAILED(output_head_lights_.Create("output_head_lights", pTypeBoolSignalValueOutput, NULL));
		RETURN_IF_FAILED(RegisterPin(&output_head_lights_));

        // Turn Signal Left
        RETURN_IF_FAILED(output_turn_signal_left_.Create("output_turn_signal_left", pTypeBoolSignalValueOutput, NULL));
		RETURN_IF_FAILED(RegisterPin(&output_turn_signal_left_));

        // Turn Signal Right
        RETURN_IF_FAILED(output_turn_signal_right_.Create("output_turn_signal_right", pTypeBoolSignalValueOutput, NULL));
		RETURN_IF_FAILED(RegisterPin(&output_turn_signal_right_));

        // Breaklight Output
        RETURN_IF_FAILED(output_break_lights_.Create("output_break_lights", pTypeBoolSignalValueOutput, NULL));
		RETURN_IF_FAILED(RegisterPin(&output_break_lights_));

        // Motor Output
        RETURN_IF_FAILED(output_motors_.Create("output_motors", pTypeSignalValueOutput, NULL));
		RETURN_IF_FAILED(RegisterPin(&output_motors_));

        // Steer Angle Output
		RETURN_IF_FAILED(output_steering_angle_.Create("output_steering_angle", pTypeSignalValueOutput, NULL));
        RETURN_IF_FAILED(RegisterPin(&output_steering_angle_));
    }
    else if (eStage == StageNormal)
    {
        // In this stage you would do further initialisation and/or create your dynamic pins.
        // Please take a look at the demo_dynamicpin example for further reference.
    }
    else if (eStage == StageGraphReady)
    {
        // All pin connections have been established in this stage so you can query your pins
        // about their media types and additional meta data.
        // Please take a look at the demo_imageproc example for further reference.
    }

    // Initialize default values.
    uss_front_left_value_ = uss_front_right_value_ = motor_speed_ = steering_angle_ = 0.0;
    head_lights_value_ = break_lights_value_ = left_signal_value_ = right_signal_value_ = false;
    cycle_ = 0;
    RETURN_NOERROR;
}

tResult MooseFilter::Shutdown(tInitStage eStage, __exception)
{
    LOG_INFO("Shutdown");
    // In each stage clean up everything that you initiaized in the corresponding stage during Init.
    // Pins are an exception:
    // - The base class takes care of static pins that are members of this class.
    // - Dynamic pins have to be cleaned up in the ReleasePins method, please see the demo_dynamicpin
    //   example for further reference.

    if (eStage == StageGraphReady)
    {
    }
    else if (eStage == StageNormal)
    {
    }
    else if (eStage == StageFirst)
    {
    }

    // call the base class implementation
    return cFilter::Shutdown(eStage, __exception_ptr);
}

tResult MooseFilter::OnPinEvent(IPin* pSource,
                                           tInt nEventCode,
                                           tInt nParam1,
                                           tInt nParam2,
                                           IMediaSample* pMediaSample)
{
    //LOG_INFO(adtf_util::cString::Format("### PIN EVENT ###"));
    // first check what kind of event it is
    // Annotation by lohmannm: when using the filter, it appeared that only every second
    // pin event is actually a media sample. That is why there will always be two lines
    // of "### PIN EVENT ###" between two sets of data.
    if (nEventCode == IPinEventSink::PE_MediaSampleReceived)
    {
        tFloat32 signalValue = 0;
        tUInt32 timeStamp = 0;
        // so we received a media sample, so this pointer better be valid.
        RETURN_IF_POINTER_NULL(pMediaSample);
        if (pMediaSample != NULL && m_pCoderDescSignalInput != NULL)
                {
                // read-out the incoming Media Sample
                cObjectPtr<IMediaCoder> pCoderInput;
                RETURN_IF_FAILED(m_pCoderDescSignalInput->Lock(pMediaSample, &pCoderInput));

                //get values from media sample
                pCoderInput->Get("f32Value", (tVoid*)&signalValue);
                pCoderInput->Get("ui32ArduinoTimestamp", (tVoid*)&timeStamp);
                m_pCoderDescSignalInput->Unlock(pCoderInput);
                //LOG_INFO(adtf_util::cString::Format("Signal: %f", signalValue));
                //LOG_INFO(adtf_util::cString::Format("TimeStamp: %d", timeStamp));
                }
            else
			    RETURN_ERROR(ERR_FAILED);

        if (pSource == &input_uss_front_left_) {
            uss_front_left_value_ = signalValue;
        }
        else if (pSource == &input_uss_front_right_) {
            uss_front_right_value_ = signalValue;
        }

        // Obstacle in front. STOP.
        if (uss_front_left_value_ < THRESHOLD && uss_front_right_value_ < THRESHOLD) {
            SetLightConfig(cycle_, false, true, false, false);
            MotorSpeed(0);
            SteeringAngle(0);
        }
        // Obstacle left. Turn right.
        else if (uss_front_left_value_ < THRESHOLD && uss_front_right_value_ >= THRESHOLD) {
            SetLightConfig(cycle_, true, false, false, true);
            MotorSpeed(15);
            SteeringAngle(60);
        }
        // Obstacle right. Turn left.
        else if (uss_front_left_value_ >= THRESHOLD && uss_front_right_value_ < THRESHOLD) {
            SetLightConfig(cycle_, true, false, true, false);
            MotorSpeed(15);
            SteeringAngle(-60);
        }
        // No obstacle. Drive.
        else if (uss_front_left_value_ >= THRESHOLD && uss_front_right_value_ >= THRESHOLD) {
            SetLightConfig(cycle_, true, false, false, false);
            MotorSpeed(20);
            SteeringAngle(0);
        }
        cycle_++;
        LOG_INFO(cString::Format("%d. cycle", cycle_));
        if (cycle_ == 4) cycle_ = 0;
    }
    RETURN_NOERROR;
}

tResult MooseFilter::TransmitLight(unsigned int lightIndex, tBool state)
{
    //write values with zero
    tUInt32 timeStamp = 0;

    //create new media sample
    cObjectPtr<IMediaSample> pMediaSample;
    AllocMediaSample((tVoid**)&pMediaSample);

    //allocate memory with the size given by the descriptor
    cObjectPtr<IMediaSerializer> pSerializer;
    m_pCoderDescBoolSignalOutput->GetMediaSampleSerializer(&pSerializer);
    tInt nSize = pSerializer->GetDeserializedSize();
    pMediaSample->AllocBuffer(nSize);

    //write date to the media sample with the coder of the descriptor
    cObjectPtr<IMediaCoder> pCoderOutput;
    m_pCoderDescBoolSignalOutput->WriteLock(pMediaSample, &pCoderOutput);

    pCoderOutput->Set("bValue", (tVoid*)&(state));
    pCoderOutput->Set("ui32ArduinoTimestamp", (tVoid*)&timeStamp);
    m_pCoderDescBoolSignalOutput->Unlock(pCoderOutput);

    //transmit media sample over output pin
    pMediaSample->SetTime(_clock->GetStreamTime());

    switch(lightIndex)
    {
        case 0:
            output_head_lights_.Transmit(pMediaSample);
            head_lights_value_ = state;
            break;
        case 1:
            output_break_lights_.Transmit(pMediaSample);
            break_lights_value_ = state;
            break;
        case 2:
            output_turn_signal_left_.Transmit(pMediaSample);
            left_signal_value_ = state;
            break;
        case 3:
            output_turn_signal_right_.Transmit(pMediaSample);
            right_signal_value_ = state;
            break;
    }

    LOG_INFO(cString::Format("Setting light %d", lightIndex));

	RETURN_NOERROR;
}

tResult MooseFilter::SetLightConfig(int cycle, tBool head, tBool breaklight, tBool left, tBool right)
{
    LOG_INFO(cString::Format("%d. cycle in method", cycle));
    if (cycle == 0/* && head != head_lights_value_*/) TransmitLight(0, head);
    if (cycle == 1/*breaklight != break_lights_value_*/) TransmitLight(1, breaklight);
    if (cycle == 2/*left != left_signal_value_*/) TransmitLight(2, left);
    if (cycle == 3/*right != right_signal_value_*/) TransmitLight(3, right);

    RETURN_NOERROR;
}

void MooseFilter::MotorSpeed(int val)
{
    //if (val == motor_speed_) return;
    //motor_speed_ = val;
	tFloat32 flValue= (tFloat32)(val);
	tUInt32 timeStamp = 0;

    //create new media sample
    cObjectPtr<IMediaSample> pMediaSample;
    AllocMediaSample((tVoid**)&pMediaSample);

    //allocate memory with the size given by the descriptor
    cObjectPtr<IMediaSerializer> pSerializer;
    m_pCoderDescSignalOutput->GetMediaSampleSerializer(&pSerializer);
    tInt nSize = pSerializer->GetDeserializedSize();
    pMediaSample->AllocBuffer(nSize);

    //write date to the media sample with the coder of the descriptor
    cObjectPtr<IMediaCoder> pCoder;
    m_pCoderDescSignalOutput->WriteLock(pMediaSample, &pCoder);

	pCoder->Set("f32Value", (tVoid*)&(flValue));
    pCoder->Set("ui32ArduinoTimestamp", (tVoid*)&timeStamp);
    m_pCoderDescSignalOutput->Unlock(pCoder);

    //transmit media sample over output pin
    pMediaSample->SetTime(_clock->GetStreamTime());
    output_motors_.Transmit(pMediaSample);

    LOG_INFO(cString::Format("Setting motor speed to %d", val));
}

void MooseFilter::SteeringAngle(int val)
{
    //if (val == steering_angle_) return;
    //steering_angle_ = val;

    tFloat32 flValue= ((tFloat32)val)*35.f/((tFloat32)100);
	tUInt32 timeStamp = 0;

	//LOG_INFO(cString::Format("slot speed: %f",flValue));

    //create new media sample
    cObjectPtr<IMediaSample> pMediaSample;
    AllocMediaSample((tVoid**)&pMediaSample);

    //allocate memory with the size given by the descriptor
    cObjectPtr<IMediaSerializer> pSerializer;
    m_pCoderDescSignalOutput->GetMediaSampleSerializer(&pSerializer);
    tInt nSize = pSerializer->GetDeserializedSize();
    pMediaSample->AllocBuffer(nSize);

    //write date to the media sample with the coder of the descriptor
    cObjectPtr<IMediaCoder> pCoder;
    m_pCoderDescSignalOutput->WriteLock(pMediaSample, &pCoder);

	pCoder->Set("f32Value", (tVoid*)&(flValue));
    pCoder->Set("ui32ArduinoTimestamp", (tVoid*)&timeStamp);
    m_pCoderDescSignalOutput->Unlock(pCoder);

    //transmit media sample over output pin
    pMediaSample->SetTime(_clock->GetStreamTime());
    output_steering_angle_.Transmit(pMediaSample);

    LOG_INFO(cString::Format("Setting steering angle to %d", val));
}


text:
package graphql.java.generator;

public class SimpleObject {
    public String objName = "name";
    public int objIndex = 0;
    public Boolean simple = true;
    public boolean littleBBoolean = true;
    public String getObjName() {
        return objName;
    }
    public int getObjIndex() {
        return objIndex;
    }
    public Boolean isSimple() {
        return simple;
    }
    public boolean isLittleBBoolean() {
        return littleBBoolean;
    }
}


text:
<core:FragmentDefinition
		xmlns="sap.m"
		xmlns:core="sap.ui.core">
	<Avatar />
</core:FragmentDefinition>


text:
$(document).ready(function() {

          //Enable swiping...
          $(".carousel-inner").swipe( {
            //Generic swipe handler for all directions
            swipeLeft:function(event, direction, distance, duration, fingerCount) {
              $(this).parent().carousel('next');
            },
            swipeRight: function() {
              $(this).parent().carousel('prev');
            },
            //Default is 75px, set to 0 for demo so any distance triggers swipe
            threshold:0
          });
        });


text:
from __future__ import unicode_literals

from django.db import migrations, models
import republisher.models

class Migration(migrations.Migration):

    dependencies = [
        ('newsroom', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Republisher',
            fields=[
                ('id', models.AutoField(primary_key=True, verbose_name='ID', serialize=False, auto_created=True)),
                ('name', models.CharField(max_length=200, unique=True)),
                ('email_addresses', models.CharField(max_length=250, validators=[republisher.models.validate_email_list])),
                ('message', models.TextField(blank=True)),
            ],
            options={
                'ordering': ['name'],
            },
        ),
        migrations.CreateModel(
            name='RepublisherArticle',
            fields=[
                ('id', models.AutoField(primary_key=True, verbose_name='ID', serialize=False, auto_created=True)),
                ('wait_time', models.PositiveIntegerField(help_text='Minimum number of minutes after publication till sent.', default=0)),
                ('note', models.TextField(blank=True, help_text='A note for the republisher specific to this article.')),
                ('status', models.CharField(max_length=20, default='scheduled', choices=[('scheduled', 'Scheduled'), ('sent', 'Sent'), ('failed', 'Failed'), ('paused', 'Paused')])),
                ('article', models.ForeignKey(to='newsroom.Article')),
                ('republisher', models.ForeignKey(to='republisher.Republisher')),
            ],
            options={
                'ordering': ['article__published', 'republisher'],
            },
        ),
        migrations.AlterUniqueTogether(
            name='republisherarticle',
            unique_together=set([('article', 'republisher')]),
        ),
    ]


text:
/events/:slug/staff/program/sessions

As a staff member (program team or organizer only) viewing the Program sub nav 'Sessions' tab
I want to see a sub nav with links to pages for all aspects of the current event program
So that I may view or manage/edit these areas.
I also want the sub nav to inform me how many sessions are accepted and waitlisted
both in total and also filtered by specific tracks.

I want to see an event info bar with all pertinent CFP information
Followed by a dynamic 'Sessions' table that can be sorted by one or multiple columns
And that includes all event sessions with the talk title and speaker names
As links so that I can view/edit/interact with any of them.

I want the table to include a 'Scheduled' column so that I know if the session has been scheduled
As well as a 'Track' and 'Status' column.

Below that I want to see a dynamic 'Waitlist' table that can be sorted by one or multiple columns.

If I am an organizer
I want to see a 'New Session' button so that I may bypass the proposal process
And add a new session to the program.

I also want to see a 'Copy Speaker Emails' button so that I can copy all
Speaker Emails directly to my clipboard.

Finally I want to see a 'Download as JSON' button so that I can download a
File with all program session information in order to transfer the data elsewhere.


text:
<!--
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.
-->
### Reading from text file

You use one of the Beam-provided I/O adapters to read from an external source. The adapters vary in their exact usage, but all of them read from some external data source and return a `PCollection` whose elements represent the data records in that source.

Each data source adapter has a Read transform; to read, you must apply that transform to the Pipeline object itself.

`TextIO.Read` , for example, reads from an external text file and returns a `PCollection` whose elements are of type String. Each String represents one line from the text file. Here's how you would apply `TextIO.Read` to your Pipeline to create a `PCollection`:

```
public static void main(String[] args) {
    // First create the pipeline
    PipelineOptions options = PipelineOptionsFactory.fromArgs(args).create();
    Pipeline pipeline = Pipeline.create(options);

    // Now create the PCollection by reading text files. Separate elements will be added for each line in the input file
    PCollection<String> lines =
        pipeline.apply("King Lear",TextIO.read().from("gs://apache-beam-samples/shakespeare/kinglear.txt")
);

}
```

### Playground exercise

In the playground window, you can find an example that reads a king lear poem from the text file stored in the Google Storage bucket and fills PCollection with individual lines and then with individual words. Try it out and see what the output is.

One of the differences you will see is that the output is much shorter than the input file itself. This is because the number of elements in the output `PCollection` is limited with the `Sample.fixedSizeGlobally` transform. Use Sample.fixedSizeGlobally transform of is another technique you can use to troubleshoot and limit the output sent to the console for debugging purposes in case of large input datasets.

Overview [file](https://storage.googleapis.com/apache-beam-samples/shakespeare/kinglear.txt)


text:
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Caching.Events;
using Alachisoft.NCache.Caching;
using Alachisoft.NCache.Serialization.Formatters;
using Alachisoft.NCache.Runtime.Events;
using System.Collections.Generic;
using System.Collections;

namespace Alachisoft.NCache.SocketServer.CallbackTasks
{
    internal sealed class PollRequestCallback : ICallbackTask
    {
        private int _callbackId;
        private string _clientId;
        private readonly EventTypeInternal _eventType;

        internal PollRequestCallback(string clientId, int callbackId, EventTypeInternal eventType)
        {
            _clientId = clientId;
            _callbackId = callbackId;
            _eventType = eventType;
        }

        public void Process()
        {
            ClientManager clientManager = null;
            lock (ConnectionManager.ConnectionTable) clientManager = (ClientManager)ConnectionManager.ConnectionTable[_clientId];
            if (clientManager != null)
            {
                Common.Protobuf.Response response = new Common.Protobuf.Response();
                response.pollNotifyEventResponse = new Common.Protobuf.PollNotifyEventResponse();
                response.pollNotifyEventResponse.callbackId = _callbackId;
                response.pollNotifyEventResponse.eventType = (int)_eventType;
                response.responseType = Common.Protobuf.Response.Type.POLL_NOTIFY_CALLBACK;
                IList serializedResponse = Common.Util.ResponseHelper.SerializeResponse(response,Common.Protobuf.Response.Type.POLL_NOTIFY_CALLBACK);
                ConnectionManager.AssureSend(clientManager, serializedResponse, false);
            }
        }
    }
}


text:
<?php
class Kwf_Exception_Unauthorized extends Kwf_Exception_Abstract
{
    private $_passwordToMask;

    public function __construct($message = "Unauthorized")
    {
        parent::__construct($message, 401);
    }

    public function getHeader()
    {
        return 'HTTP/1.1 401 Unauthorized';
    }

    public function getTemplate()
    {
        return 'Error401';
    }

    public function log()
    {
        if (!self::isLogEnabled()) {
            return false;
        }

        $body = '';
        $body .= $this->_format('REQUEST_URI', isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '(none)');
        $body .= $this->_format('HTTP_REFERER', isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '(none)');
        $body .= $this->_format('Time', date('H:i:s'));
        $body .= $this->_format('_GET', print_r($_GET, true));
        $body .= $this->_format('_POST', print_r($_POST, true));

        Kwf_Exception_Logger_Abstract::getInstance()->log($this, 'accessdenied', $body);
    }

    public function setPasswordToMask($password)
    {
        $this->_passwordToMask = $password;
    }

    public function getPasswordToMask()
    {
        return $this->_passwordToMask;
    }
}


text:
package org.paukov.graph;

/**
 * Created by dpaukov on 5/3/18.
 */
public enum EdgeClass {
  UNKNOWN, TREE, BACK, FORWARD, CROSS
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _03.Megapixels
{
    class Megapixels
    {
        static void Main(string[] args)
        {
            int width = int.Parse(Console.ReadLine());
            int height = int.Parse(Console.ReadLine());

            decimal mpixels = Math.Round((width * height) / 1000000m, 1);
            Console.WriteLine($"{width}x{height} => {mpixels}MP");
        }
    }
}


text:
package com.datumbox.framework.machinelearning.classification;

import com.datumbox.common.dataobjects.AssociativeArray;
import com.datumbox.common.dataobjects.Dataset;
import com.datumbox.common.dataobjects.Record;
import com.datumbox.common.persistentstorage.interfaces.DatabaseConnector;
import com.datumbox.framework.machinelearning.common.bases.mlmodels.BaseMLclassifier;
import com.datumbox.common.persistentstorage.interfaces.BigMap;
import com.datumbox.common.persistentstorage.interfaces.DatabaseConfiguration;
import com.datumbox.common.dataobjects.TypeInference;
import com.datumbox.framework.machinelearning.common.validation.SoftMaxRegressionValidation;
import com.datumbox.framework.statistics.descriptivestatistics.Descriptives;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * The SoftMaxRegression implements the Multinomial Logistic Regression classifier.
 *
 * References:
 * http://blog.datumbox.com/machine-learning-tutorial-the-multinomial-logistic-regression-softmax-regression/
 * http://blog.datumbox.com/tuning-the-learning-rate-in-gradient-descent/
 * http://www.cs.cmu.edu/afs/cs/user/aberger/www/html/tutorial/node3.html
 * http://acl.ldc.upenn.edu/P/P02/P02-1002.pdf
 *
 * @author Vasilis Vryniotis <bbriniotis@datumbox.com>
 */
public class SoftMaxRegression extends BaseMLclassifier<SoftMaxRegression.ModelParameters, SoftMaxRegression.TrainingParameters, SoftMaxRegression.ValidationMetrics> {

    /**
     * The ModelParameters class stores the coefficients that were learned during
     * the training of the algorithm.
     */
    public static class ModelParameters extends BaseMLclassifier.ModelParameters {

        @BigMap
        private Map<List<Object>, Double> thitas; //the thita parameters of the model

        /**
         * Protected constructor which accepts as argument the DatabaseConnector.
         *
         * @param dbc
         */
        protected ModelParameters(DatabaseConnector dbc) {
            super(dbc);
        }

        /**
         * Getter for the Thita coefficients of the model.
         *
         * @return
         */
        public Map<List<Object>, Double> getThitas() {
            return thitas;
        }

        /**
         * Setter for the Thita coefficients of the model.
         *
         * @param thitas
         */
        protected void setThitas(Map<List<Object>, Double> thitas) {
            this.thitas = thitas;
        }
    }

    /**
     * The TrainingParameters class stores the parameters that can be changed
     * before training the algorithm.
     */
    public static class TrainingParameters extends BaseMLclassifier.TrainingParameters {
        private int totalIterations=100;
        private double learningRate=0.1;

        /**
         * Getter for the total iterations of the training process.
         *
         * @return
         */
        public int getTotalIterations() {
            return totalIterations;
        }

        /**
         * Setter for the total iterations of the training process.
         *
         * @param totalIterations
         */
        public void setTotalIterations(int totalIterations) {
            this.totalIterations = totalIterations;
        }

        /**
         * Getter for the initial value of the Learning Rate.
         *
         * @return
         */
        public double getLearningRate() {
            return learningRate;
        }

        /**
         * Setter for the initial value of the Learning Rate. This value will be
         * adapted during the iterations.
         *
         * @param learningRate
         */
        public void setLearningRate(double learningRate) {
            this.learningRate = learningRate;
        }

    }

    /**
     * The ValidationMetrics class stores information about the performance of the
     * algorithm.
     */
    public static class ValidationMetrics extends BaseMLclassifier.ValidationMetrics {
        private double SSE = 0.0;
        private double CountRSquare = 0.0; // http://www.ats.ucla.edu/stat/mult_pkg/faq/general/Psuedo_RSquareds.htm

        /**
         * Getter for the SSE metric.
         *
         * @return
         */
        public double getSSE() {
            return SSE;
        }

        /**
         * Setter for the SSE metric.
         *
         * @param SSE
         */
        public void setSSE(double SSE) {
            this.SSE = SSE;
        }

        /**
         * Getter for the Count R^2 metric.
         *
         * @return
         */
        public double getCountRSquare() {
            return CountRSquare;
        }

        /**
         * Setter for the Count R^2 metric.
         *
         * @param CountRSquare
         */
        public void setCountRSquare(double CountRSquare) {
            this.CountRSquare = CountRSquare;
        }

    }

    /**
     * Public constructor of the algorithm.
     *
     * @param dbName
     * @param dbConf
     */
    public SoftMaxRegression(String dbName, DatabaseConfiguration dbConf) {
        super(dbName, dbConf, SoftMaxRegression.ModelParameters.class, SoftMaxRegression.TrainingParameters.class, SoftMaxRegression.ValidationMetrics.class, new SoftMaxRegressionValidation());
    }

    @Override
    protected void predictDataset(Dataset newData) {
        ModelParameters modelParameters = knowledgeBase.getModelParameters();

        Set<Object> classesSet = modelParameters.getClasses();
        Map<List<Object>, Double> thitas = modelParameters.getThitas();

        for(Integer rId : newData) {
            Record r = newData.get(rId);
            AssociativeArray predictionScores = new AssociativeArray();
            for(Object theClass : classesSet) {
                predictionScores.put(theClass, calculateClassScore(r.getX(), theClass, thitas));
            }

            Object theClass=getSelectedClassFromClassScores(predictionScores);

            Descriptives.normalizeExp(predictionScores);

            newData.set(rId, new Record(r.getX(), r.getY(), theClass, predictionScores));
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    protected void _fit(Dataset trainingData) {
        ModelParameters modelParameters = knowledgeBase.getModelParameters();
        TrainingParameters trainingParameters = knowledgeBase.getTrainingParameters();

        Map<List<Object>, Double> thitas = modelParameters.getThitas();
        Set<Object> classesSet = modelParameters.getClasses();

        //first we need to find all the classes
        for(Integer rId : trainingData) {
            Record r = trainingData.get(rId);
            Object theClass=r.getY();

            classesSet.add(theClass);
        }

        //we initialize the thitas to zero for all features and all classes compinations
        for(Object theClass : classesSet) {
            thitas.put(Arrays.<Object>asList(Dataset.constantColumnName, theClass), 0.0);

            for(Integer rId : trainingData) {
                Record r = trainingData.get(rId);
                for(Object feature : r.getX().keySet()) {
                    thitas.put(Arrays.<Object>asList(feature, theClass), 0.0);
                }
            }
        }

        double minError = Double.POSITIVE_INFINITY;

        double learningRate = trainingParameters.getLearningRate();
        int totalIterations = trainingParameters.getTotalIterations();
        DatabaseConnector dbc = knowledgeBase.getDbc();
        for(int iteration=0;iteration<totalIterations;++iteration) {

            logger.debug("Iteration {}", iteration);

            Map<List<Object>, Double> tmp_newThitas = dbc.getBigMap("tmp_newThitas", true);

            tmp_newThitas.putAll(thitas);
            batchGradientDescent(trainingData, tmp_newThitas, learningRate);

            double newError = calculateError(trainingData,tmp_newThitas);

            //bold driver
            if(newError>minError) {
                learningRate/=2.0;
            }
            else {
                learningRate*=1.05;
                minError=newError;

                //keep the new thitas
                thitas.clear();
                thitas.putAll(tmp_newThitas);
            }

            //Drop the temporary Collection
            dbc.dropBigMap("tmp_newThitas", tmp_newThitas);
        }
    }

    @Override
    protected SoftMaxRegression.ValidationMetrics validateModel(Dataset validationData) {
        SoftMaxRegression.ValidationMetrics validationMetrics = super.validateModel(validationData);

        validationMetrics.setCountRSquare(validationMetrics.getAccuracy()); //CountRSquare is equal to Accuracy

        double SSE = calculateError(validationData,knowledgeBase.getModelParameters().getThitas());
        validationMetrics.setSSE(SSE);

        return validationMetrics;
    }

    private void batchGradientDescent(Dataset trainingData, Map<List<Object>, Double> newThitas, double learningRate) {
        //NOTE! This is not the stochastic gradient descent. It is the batch gradient descent optimized for speed (despite it looks more than the stochastic).
        //Despite the fact that the loops are inverse, the function still changes the values of Thitas at the end of the function. We use the previous thitas
        //to estimate the costs and only at the end we update the new thitas.
        ModelParameters modelParameters = knowledgeBase.getModelParameters();

        double multiplier = learningRate/modelParameters.getN();
        Map<List<Object>, Double> thitas = modelParameters.getThitas();
        Set<Object> classesSet = modelParameters.getClasses();

        for(Integer rId : trainingData) {
            Record r = trainingData.get(rId);
            //mind the fact that we use the previous thitas to estimate the new ones! this is because the thitas must be updated simultaniously
            AssociativeArray classProbabilities = hypothesisFunction(r.getX(), thitas);
            for(Object theClass : classesSet) {

                double error;
                double score = classProbabilities.getDouble(theClass);
                if(r.getY().equals(theClass)) {
                    error = 1 - score;
                }
                else {
                    error = - score;
                }

                double errorMultiplier = multiplier*error;

                //update the weight of constant
                List<Object> featureClassTuple = Arrays.<Object>asList(Dataset.constantColumnName, theClass);
                newThitas.put(featureClassTuple, newThitas.get(featureClassTuple)+errorMultiplier);

                //update the rest of the weights

                for(Map.Entry<Object, Object> entry : r.getX().entrySet()) {
                    Double value = TypeInference.toDouble(entry.getValue());

                    Object feature = entry.getKey();
                    featureClassTuple = Arrays.<Object>asList(feature, theClass);

                    Double thitaWeight = newThitas.get(featureClassTuple);
                    if(thitaWeight!=null) {//ensure that the feature is in the dictionary
                        newThitas.put(featureClassTuple, thitaWeight+errorMultiplier*value);
                    }
                }
            }
        }

    }

    private Double calculateClassScore(AssociativeArray x, Object theClass, Map<List<Object>, Double> thitas) {
        double score = thitas.get(Arrays.<Object>asList(Dataset.constantColumnName, theClass));

        for(Map.Entry<Object, Object> entry : x.entrySet()) {
            Double value = TypeInference.toDouble(entry.getValue());

            Object feature = entry.getKey();
            List<Object> featureClassTuple = Arrays.<Object>asList(feature, theClass);

            Double thitaWeight = thitas.get(featureClassTuple);
            if(thitaWeight!=null) {//ensure that the feature is in the dictionary
                score+=thitaWeight*value;
            }
        }

        return score;
    }

    private double calculateError(Dataset trainingData, Map<List<Object>, Double> thitas) {
        //The cost function as described on http://ufldl.stanford.edu/wiki/index.php/Softmax_Regression
        //It is optimized for speed to reduce the amount of loops
        double error=0.0;

        for(Integer rId : trainingData) {
            Record r = trainingData.get(rId);
            AssociativeArray classProbabilities = hypothesisFunction(r.getX(), thitas);
            Double score = classProbabilities.getDouble(r.getY());
            error+=Math.log(score); //no need to loop through the categories. Just grab the one that we are interested in
        }

        return -error/knowledgeBase.getModelParameters().getN();
    }

    private AssociativeArray hypothesisFunction(AssociativeArray x, Map<List<Object>, Double> thitas) {
        Set<Object> classesSet = knowledgeBase.getModelParameters().getClasses();
        AssociativeArray predictionProbabilities = new AssociativeArray();

        for(Object theClass : classesSet) {
            double score=calculateClassScore(x, theClass, thitas);
            if(score<=0) {
                score=1e-8;
            }
            predictionProbabilities.put(theClass, score);
        }

        Descriptives.normalize(predictionProbabilities);

        return predictionProbabilities;
    }

}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>ssl::context</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../reference.html" title="Reference">
<link rel="prev" href="spawn/overload4.html" title="spawn (4 of 4 overloads)">
<link rel="next" href="ssl__context/add_certificate_authority.html" title="ssl::context::add_certificate_authority">

Home
Libraries
People
FAQ
More

ssl::context

class context :
  public ssl::context_base,
  noncopyable

        Types

<colgroup>
<col>
<col>
</colgroup>

                  Name

                  Description

                  file_format

                  File format types.

                  impl_type

                  (Deprecated: Use native_handle_type.) The native type of the SSL
                  context.

                  method

                  Different methods supported by a context.

                  native_handle_type

                  The native handle type of the SSL context.

                  options

                  Bitmask type for SSL options.

                  password_purpose

                  Purpose of PEM password.

        Member
        Functions

<colgroup>
<col>
<col>
</colgroup>

                  Name

                  Description

                  add_certificate_authority

                  Add certification authority for performing verification.

                  add_verify_path

                  Add a directory containing certificate authority files to be used
                  for performing verification.

                  clear_options

                  Clear options on the context.

                  context

                  Constructor.

                  Deprecated constructor taking a reference to an io_service object.

                  Move-construct a context from another.

                  impl

                  (Deprecated: Use native_handle().) Get the underlying implementation
                  in the native type.

                  load_verify_file

                  Load a certification authority file for performing verification.

                  native_handle

                  Get the underlying implementation in the native type.

                  operator=

                  Move-assign a context from another.

                  set_default_verify_paths

                  Configures the context to use the default directories for finding
                  certification authority certificates.

                  set_options

                  Set options on the context.

                  set_password_callback

                  Set the password callback.

                  set_verify_callback

                  Set the callback used to verify peer certificates.

                  set_verify_depth

                  Set the peer verification depth.

                  set_verify_mode

                  Set the peer verification mode.

                  use_certificate

                  Use a certificate from a memory buffer.

                  use_certificate_chain

                  Use a certificate chain from a memory buffer.

                  use_certificate_chain_file

                  Use a certificate chain from a file.

                  use_certificate_file

                  Use a certificate from a file.

                  use_private_key

                  Use a private key from a memory buffer.

                  use_private_key_file

                  Use a private key from a file.

                  use_rsa_private_key

                  Use an RSA private key from a memory buffer.

                  use_rsa_private_key_file

                  Use an RSA private key from a file.

                  use_tmp_dh

                  Use the specified memory buffer to obtain the temporary Diffie-Hellman
                  parameters.

                  use_tmp_dh_file

                  Use the specified file to obtain the temporary Diffie-Hellman parameters.

                  ~context

                  Destructor.

        Data
        Members

<colgroup>
<col>
<col>
</colgroup>

                  Name

                  Description

                  default_workarounds

                  Implement various bug workarounds.

                  no_compression

                  Disable compression. Compression is disabled by default.

                  no_sslv2

                  Disable SSL v2.

                  no_sslv3

                  Disable SSL v3.

                  no_tlsv1

                  Disable TLS v1.

                  no_tlsv1_1

                  Disable TLS v1.1.

                  no_tlsv1_2

                  Disable TLS v1.2.

                  single_dh_use

                  Always create a new key when using tmp_dh parameters.

        Requirements

        Header: boost/asio/ssl/context.hpp

        Convenience header: boost/asio/ssl.hpp

Copyright © 2003-2015 Christopher M.
      Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
TAB = "\t"

@look = ""

def init
  @expression = gets.chomp
  @expression = @expression.split(//)
  @number = 0
  get_char
  skip_white
end

# Read New Character From Input Stream
#
def get_char
  @look = @expression[@number]
  @number +=1
end

# Report an Error
#
def error(text)
  puts "\nError: " + text
end

# Report What Was Expected
#
def expected(text)
  abort(text + " Expected")
end

# Match a Specific Input Character
#
def match(input)
  if @look == input
    get_char
    skip_white
  else
    expected("'" + input.to_s + "'")
  end
end

# Recognize a Decimal Digit
#
def is_digit?(input)
    !!Float(input) rescue false
end

# Recognize an Alphanumeric
#
def is_al_num(input)
  is_alpha?(input) || is_digit?(input)
end

# Recognize an Alpha Character
#
def is_alpha?(input)
  !is_digit?(input)
end

# Recognize White Space
#
def is_white(input)
  [' ', TAB].any? { |op| @look == op }
end

# Skip over leading white Space
#
def skip_white
  while is_white(@look)
    get_char
  end
end

# Get an Identifier
#
def get_name
  expected("Name") unless is_alpha?(@look)
  token = ""
  while is_al_num(@look)
    token = token + @look.upcase
    get_char
  end
  skip_white
  return token
end

# Get a Number
#
def get_num
  expected("Integer") unless is_digit?(@look)
  value = ""
  while is_digit?(@look)
    value = value + @look
    get_char
  end
  skip_white
  return value
end

# Output a string with tab
#
def emit(input)
  print "\t" + input
end

# Output a string with tab and CRLF
#
def emit_ln(input)
  emit(input)
  print "\n"
end

# Parse and translate a match term
def term
  factor
  operations = ['*', '/']
  while (operations.any? { |op| @look == op })
    emit_ln 'MOVE D0, -(SP)'
    case @look
    when '*': multiply
    when '/': divide
    else expected('Mulop')
    end
  end
end

# Parse and Translate an Expression
#
def expression
  if is_addop @look
    emit_ln 'CLR D0'
  else
    term
  end
  while is_addop @look
    emit_ln 'MOVE D0, -(SP)'
    case @look
    when '+': add
    when '-': subtract
    else expected('Addop')
    end
  end
end

# Recognize an Addop
#
def is_addop(input)
  ['+', '-'].any? { |op| @look == op }
end

# Recognize and Translate an Add
#
def add
  match '+'
  term
  emit_ln 'ADD (SP)+, D1'
end

# Recognize and Translate a Subtract
#
def subtract
  match '-'
  term
  emit_ln 'SUB (SP)+, D0'
  emit_ln 'NEG D0'
end

# Parse and Translate a Math Factor
#
def factor
  if @look == '('
    match '('
    expression
    match ')'
  elsif is_alpha?@look
    ident
  else
    emit_ln "MOVE ##{get_num},D0"
  end
end

# Parse and Translate an Identifier
#
def ident
  name = get_name
  if @look == '('
    match '('
    match ')'
    emit_ln "BSR #{name}"
  else
    emit_ln "MOVE #{name} (PC),D0"
  end
end

# Recognize and Translate a Multiply
#
def multiply
  match '*'
  factor
  emit_ln 'MULS (SP)+,D0'
end

# Recognize and Translate a Divide
#
def divide
  match '/'
  factor
  emit_ln 'MOVE (SP)+,D1'
  emit_ln 'DIVS D1,D0'
end

# Parse and translate an assignment statement
#
def assignment
  @name = get_name
  match '='
  expression
  emit_ln "LEA #{@name} (PC),A0"
  emit_ln 'MOVE D0,(A0)'
end


text:
<?php

/**
 * @category   Zend
 * @package    Zend_CodeGenerator
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_CodeGenerator_Php_Member_Container extends ArrayObject
{

    /**#@+
     * @param const string
     */
    const TYPE_PROPERTY = 'property';
    const TYPE_METHOD   = 'method';
    /**#@-*/

    /**
     * @var const|string
     */
    protected $_type = self::TYPE_PROPERTY;

    /**
     * __construct()
     *
     * @param const|string $type
     */
    public function __construct($type = self::TYPE_PROPERTY)
    {
        $this->_type = $type;
        parent::__construct(array(), self::ARRAY_AS_PROPS);
    }

}


text:
def extractLazyNanaseruTranslation(item):
	"""
	Parser for 'Lazy Nanaseru Translation'
	"""
	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or 'preview' in item['title'].lower():
		return None
	if 'WATTT' in item['tags']:
		return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag, postfix=postfix)
	return False


text:
import unittest
import os
from skrf.media.rectangularWaveguide import RectangularWaveguide
from skrf.network import Network
from skrf.constants import mil

class MediaTestCase(unittest.TestCase):
    """

    """
    def setUp(self):
        """

        """
        self.files_dir = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            'qucs_prj'
            )
        self.pwd = os.path.join(
            os.path.dirname(os.path.abspath(__file__)))

    @unittest.skip
    def test_line(self):
        """
        """
        fname = os.path.join(self.files_dir,\
                'rectangularWaveguideWR10,200mil.s2p')

        qucs_ntwk = Network(fname)
        wg = RectangularWaveguide(
            frequency = qucs_ntwk.frequency,
            a = 100*mil
            )
        skrf_ntwk = wg.thru(Z0=50)**wg.line(200*mil,'m')**wg.thru(Z0=50)
        self.assertEqual(qucs_ntwk, skrf_ntwk)

    def test_conductor_loss(self):
        """
        This only compares the magnitude of the generated line, because
        the loss approximation doesnt account for reactance of field on
        sidewalls.
        """
        ntwk = Network(os.path.join(self.pwd, 'wr1p5_1in_swg_Al_0rough.s2p'))
        wg = RectangularWaveguide(
            frequency = ntwk.frequency,
            a=15*mil,
            z0=50,
            rho = 1/(3.8e7),
            )
        self.assertTrue(
            max(abs(wg.line(1,'in').s_mag[:,1,0] - ntwk.s_mag[:,1,0]))<1e-3 )

    def test_roughness(self):
        """
        This only compares the magnitude of the generated line, because
        the loss approximation doesnt account for reactance of field on
        sidewalls.
        """
        ntwk = Network(os.path.join(self.pwd, 'wr1p5_1in_swg_Al_100nm_rough.s2p'))
        wg = RectangularWaveguide(
            ntwk.frequency,
            a=15*mil,
            z0=50,
            rho = 1/(3.8e7),
            roughness = 100e-9,
            )
        self.assertTrue(
            max(abs(wg.line(1,'in').s_mag[:,1,0] - ntwk.s_mag[:,1,0]))<1e-3 )


text:
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <wlr/backend/libinput.h>
#include <wlr/types/wlr_tablet_v2.h>
#include "log.h"
#include "sway/input/cursor.h"
#include "sway/input/seat.h"
#include "sway/input/tablet.h"

static void handle_pad_tablet_destroy(struct wl_listener *listener, void *data) {
	struct sway_tablet_pad *pad =
		wl_container_of(listener, pad, tablet_destroy);

	pad->tablet = NULL;

	wl_list_remove(&pad->tablet_destroy.link);
	wl_list_init(&pad->tablet_destroy.link);
}

static void attach_tablet_pad(struct sway_tablet_pad *tablet_pad,
		struct sway_tablet *tablet) {
	sway_log(SWAY_DEBUG, "Attaching tablet pad \"%s\" to tablet tool \"%s\"",
		tablet_pad->seat_device->input_device->wlr_device->name,
		tablet->seat_device->input_device->wlr_device->name);

	tablet_pad->tablet = tablet;

	wl_list_remove(&tablet_pad->tablet_destroy.link);
	tablet_pad->tablet_destroy.notify = handle_pad_tablet_destroy;
	wl_signal_add(&tablet->seat_device->input_device->wlr_device->events.destroy,
		&tablet_pad->tablet_destroy);
}

struct sway_tablet *sway_tablet_create(struct sway_seat *seat,
		struct sway_seat_device *device) {
	struct sway_tablet *tablet =
		calloc(1, sizeof(struct sway_tablet));
	if (!sway_assert(tablet, "could not allocate sway tablet for seat")) {
		return NULL;
	}

	wl_list_insert(&seat->cursor->tablets, &tablet->link);

	device->tablet = tablet;
	tablet->seat_device = device;

	return tablet;
}

void sway_configure_tablet(struct sway_tablet *tablet) {
	struct wlr_input_device *device =
		tablet->seat_device->input_device->wlr_device;
	struct sway_seat *seat = tablet->seat_device->sway_seat;

	if ((seat->wlr_seat->capabilities & WL_SEAT_CAPABILITY_POINTER) == 0) {
		seat_configure_xcursor(seat);
	}

	tablet->tablet_v2 =
		wlr_tablet_create(server.tablet_v2, seat->wlr_seat, device);

	/* Search for a sibling tablet pad */
	if (!wlr_input_device_is_libinput(device)) {
		/* We can only do this on libinput devices */
		return;
	}

	struct libinput_device_group *group =
		libinput_device_get_device_group(wlr_libinput_get_device_handle(device));
	struct sway_tablet_pad *tablet_pad;
	wl_list_for_each(tablet_pad, &seat->cursor->tablet_pads, link) {
		struct wlr_input_device *pad_device =
			tablet_pad->seat_device->input_device->wlr_device;
		if (!wlr_input_device_is_libinput(pad_device)) {
			continue;
		}

		struct libinput_device_group *pad_group =
			libinput_device_get_device_group(wlr_libinput_get_device_handle(pad_device));

		if (pad_group == group) {
			attach_tablet_pad(tablet_pad, tablet);
			break;
		}
	}
}

void sway_tablet_destroy(struct sway_tablet *tablet) {
	if (!tablet) {
		return;
	}
	wl_list_remove(&tablet->link);
	free(tablet);
}

static void handle_tablet_tool_set_cursor(struct wl_listener *listener, void *data) {
	struct sway_tablet_tool *tool =
		wl_container_of(listener, tool, set_cursor);
	struct wlr_tablet_v2_event_cursor *event = data;

	struct sway_cursor *cursor = tool->seat->cursor;
	if (!seatop_allows_set_cursor(cursor->seat)) {
		return;
	}

	struct wl_client *focused_client = NULL;
	struct wlr_surface *focused_surface =
		cursor->seat->wlr_seat->pointer_state.focused_surface;
	if (focused_surface != NULL) {
		focused_client = wl_resource_get_client(focused_surface->resource);
	}

	// TODO: check cursor mode
	if (focused_client == NULL ||
			event->seat_client->client != focused_client) {
		sway_log(SWAY_DEBUG, "denying request to set cursor from unfocused client");
		return;
	}

	cursor_set_image_surface(cursor, event->surface, event->hotspot_x,
			event->hotspot_y, focused_client);
}

static void handle_tablet_tool_destroy(struct wl_listener *listener, void *data) {
	struct sway_tablet_tool *tool =
		wl_container_of(listener, tool, tool_destroy);

	wl_list_remove(&tool->tool_destroy.link);
	wl_list_remove(&tool->set_cursor.link);

	free(tool);
}

void sway_tablet_tool_configure(struct sway_tablet *tablet,
		struct wlr_tablet_tool *wlr_tool) {
	struct sway_tablet_tool *tool =
		calloc(1, sizeof(struct sway_tablet_tool));
	if (!sway_assert(tool, "could not allocate sway tablet tool for tablet")) {
		return;
	}

	tool->seat = tablet->seat_device->sway_seat;
	tool->tablet = tablet;
	tool->tablet_v2_tool =
		wlr_tablet_tool_create(server.tablet_v2,
			tablet->seat_device->sway_seat->wlr_seat, wlr_tool);

	tool->tool_destroy.notify = handle_tablet_tool_destroy;
	wl_signal_add(&wlr_tool->events.destroy, &tool->tool_destroy);

	tool->set_cursor.notify = handle_tablet_tool_set_cursor;
	wl_signal_add(&tool->tablet_v2_tool->events.set_cursor,
		&tool->set_cursor);

	wlr_tool->data = tool;
}

static void handle_tablet_pad_attach(struct wl_listener *listener,
		void *data) {
	struct sway_tablet_pad *pad = wl_container_of(listener, pad, attach);
	struct wlr_tablet_tool *wlr_tool = data;
	struct sway_tablet_tool *tool = wlr_tool->data;

	if (!tool) {
		return;
	}

	attach_tablet_pad(pad, tool->tablet);
}

static void handle_tablet_pad_ring(struct wl_listener *listener, void *data) {
	struct sway_tablet_pad *pad = wl_container_of(listener, pad, ring);
	struct wlr_event_tablet_pad_ring *event = data;

	if (!pad->current_surface) {
		return;
	}

	wlr_tablet_v2_tablet_pad_notify_ring(pad->tablet_v2_pad,
		event->ring, event->position,
		event->source == WLR_TABLET_PAD_RING_SOURCE_FINGER,
		event->time_msec);
}

static void handle_tablet_pad_strip(struct wl_listener *listener, void *data) {
	struct sway_tablet_pad *pad = wl_container_of(listener, pad, strip);
	struct wlr_event_tablet_pad_strip *event = data;

	if (!pad->current_surface) {
		return;
	}

	wlr_tablet_v2_tablet_pad_notify_strip(pad->tablet_v2_pad,
		event->strip, event->position,
		event->source == WLR_TABLET_PAD_STRIP_SOURCE_FINGER,
		event->time_msec);
}

static void handle_tablet_pad_button(struct wl_listener *listener, void *data) {
	struct sway_tablet_pad *pad = wl_container_of(listener, pad, button);
	struct wlr_event_tablet_pad_button *event = data;

	if (!pad->current_surface) {
		return;
	}

	wlr_tablet_v2_tablet_pad_notify_mode(pad->tablet_v2_pad,
		event->group, event->mode, event->time_msec);

	wlr_tablet_v2_tablet_pad_notify_button(pad->tablet_v2_pad,
		event->button, event->time_msec,
		(enum zwp_tablet_pad_v2_button_state)event->state);
}

struct sway_tablet_pad *sway_tablet_pad_create(struct sway_seat *seat,
		struct sway_seat_device *device) {
	struct sway_tablet_pad *tablet_pad =
		calloc(1, sizeof(struct sway_tablet_pad));
	if (!sway_assert(tablet_pad, "could not allocate sway tablet")) {
		return NULL;
	}

	tablet_pad->seat_device = device;
	wl_list_init(&tablet_pad->attach.link);
	wl_list_init(&tablet_pad->button.link);
	wl_list_init(&tablet_pad->strip.link);
	wl_list_init(&tablet_pad->ring.link);
	wl_list_init(&tablet_pad->surface_destroy.link);
	wl_list_init(&tablet_pad->tablet_destroy.link);

	wl_list_insert(&seat->cursor->tablet_pads, &tablet_pad->link);

	return tablet_pad;
}

void sway_configure_tablet_pad(struct sway_tablet_pad *tablet_pad) {
	struct wlr_input_device *device =
		tablet_pad->seat_device->input_device->wlr_device;
	struct sway_seat *seat = tablet_pad->seat_device->sway_seat;

	tablet_pad->tablet_v2_pad =
		wlr_tablet_pad_create(server.tablet_v2, seat->wlr_seat, device);

	wl_list_remove(&tablet_pad->attach.link);
	tablet_pad->attach.notify = handle_tablet_pad_attach;
	wl_signal_add(&device->tablet_pad->events.attach_tablet,
		&tablet_pad->attach);

	wl_list_remove(&tablet_pad->button.link);
	tablet_pad->button.notify = handle_tablet_pad_button;
	wl_signal_add(&device->tablet_pad->events.button, &tablet_pad->button);

	wl_list_remove(&tablet_pad->strip.link);
	tablet_pad->strip.notify = handle_tablet_pad_strip;
	wl_signal_add(&device->tablet_pad->events.strip, &tablet_pad->strip);

	wl_list_remove(&tablet_pad->ring.link);
	tablet_pad->ring.notify = handle_tablet_pad_ring;
	wl_signal_add(&device->tablet_pad->events.ring, &tablet_pad->ring);

	/* Search for a sibling tablet */
	if (!wlr_input_device_is_libinput(device)) {
		/* We can only do this on libinput devices */
		return;
	}

	struct libinput_device_group *group =
		libinput_device_get_device_group(wlr_libinput_get_device_handle(device));
	struct sway_tablet *tool;
	wl_list_for_each(tool, &seat->cursor->tablets, link) {
		struct wlr_input_device *tablet =
			tool->seat_device->input_device->wlr_device;
		if (!wlr_input_device_is_libinput(tablet)) {
			continue;
		}

		struct libinput_device_group *tablet_group =
			libinput_device_get_device_group(wlr_libinput_get_device_handle(tablet));

		if (tablet_group == group) {
			attach_tablet_pad(tablet_pad, tool);
			break;
		}
	}
}

void sway_tablet_pad_destroy(struct sway_tablet_pad *tablet_pad) {
	if (!tablet_pad) {
		return;
	}

	wl_list_remove(&tablet_pad->link);
	wl_list_remove(&tablet_pad->attach.link);
	wl_list_remove(&tablet_pad->button.link);
	wl_list_remove(&tablet_pad->strip.link);
	wl_list_remove(&tablet_pad->ring.link);
	wl_list_remove(&tablet_pad->surface_destroy.link);
	wl_list_remove(&tablet_pad->tablet_destroy.link);

	free(tablet_pad);
}

static void handle_pad_tablet_surface_destroy(struct wl_listener *listener,
		void *data) {
	struct sway_tablet_pad *tablet_pad =
		wl_container_of(listener, tablet_pad, surface_destroy);

	wlr_tablet_v2_tablet_pad_notify_leave(tablet_pad->tablet_v2_pad,
		tablet_pad->current_surface);
	wl_list_remove(&tablet_pad->surface_destroy.link);
	wl_list_init(&tablet_pad->surface_destroy.link);
	tablet_pad->current_surface = NULL;
}

void sway_tablet_pad_notify_enter(struct sway_tablet_pad *tablet_pad,
		struct wlr_surface *surface) {
	if (!tablet_pad || !tablet_pad->tablet) {
		return;
	}

	if (surface == tablet_pad->current_surface) {
		return;
	}

	/* Leave current surface */
	if (tablet_pad->current_surface) {
		wlr_tablet_v2_tablet_pad_notify_leave(tablet_pad->tablet_v2_pad,
			tablet_pad->current_surface);
		wl_list_remove(&tablet_pad->surface_destroy.link);
		wl_list_init(&tablet_pad->surface_destroy.link);
		tablet_pad->current_surface = NULL;
	}

	if (!wlr_surface_accepts_tablet_v2(tablet_pad->tablet->tablet_v2, surface)) {
		return;
	}

	wlr_tablet_v2_tablet_pad_notify_enter(tablet_pad->tablet_v2_pad,
		tablet_pad->tablet->tablet_v2, surface);

	tablet_pad->current_surface = surface;
	wl_list_remove(&tablet_pad->surface_destroy.link);
	tablet_pad->surface_destroy.notify = handle_pad_tablet_surface_destroy;
	wl_signal_add(&surface->events.destroy, &tablet_pad->surface_destroy);
}


text:
package jp.canetrash.vicuna.dao;

import jp.canetrash.vicuna.entity.DamagePortalEntity;
import jp.canetrash.vicuna.entity.DamagePortalEntity.DamagePortalKey;

/**
 * @author tfunato
 *
 */
public interface DamagePortalDao extends
		Dao<DamagePortalEntity, DamagePortalKey> {
}


text:
package org.apache.ignite.tests.p2p.cache;

import java.io.Serializable;
import org.apache.ignite.cache.query.annotations.QuerySqlField;

/**
 * Wraps Person class.
 */
public class PersonWrapper {
    /** */
    public static class Person implements Serializable {
        /** */
        @QuerySqlField
        private String name;

        /** */
        @QuerySqlField(index = true)
        private int id;

        /** */
        @QuerySqlField
        private String lastName;

        /** */
        @QuerySqlField
        private double salary;

        /**
         *
         */
        public Person() {
            // No-op.
        }

        /**
         * @param name Name.
         */
        public Person(String name) {
            this.name = name;
        }

        /**
         * @return Name.
         */
        public String name() {
            return name;
        }

        /**
         * @return Name.
         */
        public String getName() {
            return name;
        }

        /**
         * @param name Name.
         */
        public void setName(String name) {
            this.name = name;
        }

        /**
         * @return ID.
         */
        public int getId() {
            return id;
        }

        /**
         * @param id ID.
         */
        public void setId(int id) {
            this.id = id;
        }

        /**
         * @return Last name.
         */
        public String getLastName() {
            return lastName;
        }

        /**
         * @param lastName Last name.
         */
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        /**
         * @return Salary.
         */
        public double getSalary() {
            return salary;
        }

        /**
         * @param salary Salary.
         */
        public void setSalary(double salary) {
            this.salary = salary;
        }
    }
}


text:
import numpy as np
from mpmath import *
from sympy import *
from sympy.matrices.dense import *
import functools
import util

print("Working...")

# Symbols
Theta = Symbol('Theta')
Phi = Symbol('Phi')
theta = Symbol('theta')
phi = Symbol('phi')
n0 = Symbol('n0')
n1 = Symbol('n1')
phi_pol = Symbol('phi_pol')
alpha = Symbol('alpha')

# Set up integral
mu = Matrix([sin(Theta)*cos(Phi), sin(Theta)*sin(Phi), cos(Theta)]) # Dipole
r = Matrix([sin(theta)*cos(phi), sin(theta)*sin(phi), cos(theta)]) # Position
R = rot_axis3(-phi)*rot_axis2(theta)*rot_axis3(phi) # Rotation matrix
apod = 1 # sqrt(n1)/(sqrt(n0*cos(theta))) # Energy conservation
P = Matrix([cos(phi_pol), sin(phi_pol), 0]) # Polarizer
J = sin(theta) # Jacobian
integrand = J*(P.dot(apod*R*r.cross(mu).cross(r))**2) # Integrand
tot_integrand = J*(r.cross(mu).cross(r)).dot((r.cross(mu).cross(r)))

# Calculate I integral
int1 = integrate(expand(integrand), (phi, 0, 2*pi)) # phi integral
I = integrate(expand(int1), (theta, 0, alpha)) # theta integral

# Calculate I_tot integral
int1 = integrate(expand(tot_integrand), (phi, 0, 2*pi)) # phi integral
I_tot = integrate(expand(int1), (theta, 0, pi)) # theta integral

# Calculate fraction of total power detected
I_frac = I/I_tot

# Print expressions for each polarization in Fourkas' form
pols = [0, pi/4, pi/2, 3*pi/4]
for pol in pols:
    I_pol = trigsimp(I_frac.subs([(phi_pol, pol)]))
    B_term = sin(Theta)**2
    if pol == 0 or pol == pi/2:
        sub_in = sin(Phi)**2
        sub_out = (1 - cos(2*Phi))/2
        C_term = sin(Theta)**2*cos(2*Phi)
    else:
        sub_in = sin(Phi)*cos(Phi)
        sub_out = sin(2*Phi)/2
        C_term = sin(Theta)**2*sin(2*Phi)
    if pol == 0 or pol == pi/4:
        C_sign = 1
    else:
        C_sign = -1

    I_pol_sin2cos = collect(I_pol, sub_in).subs([(sub_in, sub_out)])
    I_pol_collect_C_term = collect(expand(I_pol_sin2cos), C_sign*C_term)
    C_sin = C_sign*I_pol_collect_C_term.args[-1].args[1] # Extract C coefficient
    C = simplify(C_sin.subs([(sin(alpha)**2, 1 - cos(alpha)**2)])) # Write in cos
    A_and_B_terms = collect(Add(*I_pol_collect_C_term.args[0:-1]), B_term)
    B = A_and_B_terms.args[-1].args[1] # Extract B coefficient
    A = Add(*A_and_B_terms.args[0:-1]) # Extract A coefficient

    # Express coefficients in of powers of cos(alpha)
    coeffs = [expand_trig(x.subs([(sin(alpha)**2, 1 - cos(alpha)**2)])) for x in [A, B, C]]

    my_I_pol = coeffs[0] + coeffs[1]*B_term + coeffs[2]*C_sign*C_term

    # Ensure that simplification didn't change the expression
    assert(simplify(expand(my_I_pol) - expand(I_pol)) == 0)

    # Print the expression in plain text
    # print(my_I_pol)

    # Print the expression in latex
    init_printing(order='rev-lex')
    names = ['A', 'B', 'C']
    int_string = 'I_{'+str(int(np.rad2deg(float(pol))))+'}(\\Theta, \\Phi, \\alpha) =& I_{\\text{tot}}(t, t+\\tau)(A + B' + latex(B_term) + ' + C(' + latex(C_sign*C_term) + '))\\\\'
    print(int_string.replace('\\left (', '').replace(' \\right )', ''))
    coeff_strings = [name + ' =& ' + latex(coeff).replace('\\\\', '\\') + '\\\\' for name, coeff in zip(names, coeffs)]
    for s in coeff_strings:
        print(s.replace('\\left (', '').replace('\\right )', ''))
    print('\n')


text:
package com.reactnativenavigation.screens;

import android.support.v7.app.AppCompatActivity;

import com.reactnativenavigation.params.ScreenParams;
import com.reactnativenavigation.views.LeftButtonOnClickListener;

class ScreenFactory {
    static Screen create(AppCompatActivity activity,
                         ScreenParams screenParams,
                         LeftButtonOnClickListener leftButtonOnClickListener) {
        if (screenParams.isFragmentScreen()) {
            return new FragmentScreen(activity, screenParams, leftButtonOnClickListener);
        } else if (screenParams.hasTopTabs()) {
            if (screenParams.hasCollapsingTopBar()) {
                return new CollapsingViewPagerScreen(activity, screenParams, leftButtonOnClickListener);
            } else {
                return new ViewPagerScreen(activity, screenParams, leftButtonOnClickListener);
            }
        } else if (screenParams.hasCollapsingTopBar()) {
            return new CollapsingSingleScreen(activity, screenParams, leftButtonOnClickListener);
        } else {
            return new SingleScreen(activity, screenParams, leftButtonOnClickListener);
        }
    }
}


text:
/* eslint-env mocha */
import chai, { expect } from 'chai';
import chaiHttp from 'chai-http';
import { createServer } from '../server';

chai.use(chaiHttp);

import fakeDB from '../server/fakeDB';

const server = createServer({
  nodeEnv: 'test',
  webConcurrency: process.env.WEB_CONCURRENCY || 1,
  port: process.env.PORT || 5000,
});

describe('API', () => {
  it('should list ALL posts on api/v0/posts GET', (done) => {
    chai.request(server)
      .get('/api/v0/posts')
      .end((err, res) => {
        expect(res.status).to.equal(200);
        expect(res).to.be.json;
        expect(res.text).to.be.an('string');
        expect(res.text).to.equal(JSON.stringify(fakeDB));
        done();
      });
  });

  it('should list ONE post on api/v0/posts/:slug GET', (done) => {
    const post = {
      id: '128sd04d',
      tags: ['Design', 'Front end', 'Back end', 'UX'],
      title: 'Save for something.',
      slug: 'sparebank1-savings-calculator',
      subtitle: 'Savings calculator developed for Sparebank1 in Norway',
      picture: '/media/sparebank1-sparkalkulator.jpg',
      client: 'Sparebank1',
      description: '',
    };

    chai.request(server)
      .get(`/api/v0/posts/${post.slug}`)
      .end((err, res) => {
        expect(res.status).to.equal(200);
        expect(res).to.be.json;
        expect(res.text).to.be.an('string');
        expect(res.text).to.equal(JSON.stringify(post));
        done();
      });
  });
});


text:
<?php

namespace Zimbra\Admin\Tests\Request;

use Zimbra\Admin\Tests\ZimbraAdminApiTestCase;
use Zimbra\Admin\Request\CheckPasswordStrength;

/**
 * Testcase class for CheckPasswordStrength.
 */
class CheckPasswordStrengthTest extends ZimbraAdminApiTestCase
{
    public function testCheckPasswordStrengthRequest()
    {
        $id = $this->faker->word;
        $password = $this->faker->word;
        $req = new CheckPasswordStrength($id, $password);
        $this->assertInstanceOf('Zimbra\Admin\Request\Base', $req);
        $this->assertSame($id, $req->getId());
        $this->assertSame($password, $req->getPassword());

        $req->setId($id)
            ->setPassword($password);
        $this->assertSame($id, $req->getId());
        $this->assertSame($password, $req->getPassword());

        $xml = '<?xml version="1.0"?>' . "\n"
            . '<CheckPasswordStrengthRequest id="' . $id .'" password="' . $password . '" />';
        $this->assertXmlStringEqualsXmlString($xml, (string) $req);

        $array = [
            'CheckPasswordStrengthRequest' => [
                '_jsns' => 'urn:zimbraAdmin',
                'id' => $id,
                'password' => $password,
            ],
        ];
        $this->assertEquals($array, $req->toArray());
    }

    public function testCheckPasswordStrengthApi()
    {
        $id = $this->faker->word;
        $password = $this->faker->word;
        $this->api->checkPasswordStrength(
            $id, $password
        );

        $client = $this->api->getClient();
        $req = $client->lastRequest();
        $xml = '<?xml version="1.0"?>' . "\n"
            . '<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:urn="urn:zimbra" xmlns:urn1="urn:zimbraAdmin">'
                . '<env:Body>'
                    . '<urn1:CheckPasswordStrengthRequest '
                        . 'id="' . $id . '" password="' . $password . '" />'
                . '</env:Body>'
            . '</env:Envelope>';
        $this->assertXmlStringEqualsXmlString($xml, (string) $req);
    }
}