text:
package com.ogove.hr.Adapter;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatImageView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.ogove.hr.Core.ActivityProvider;
import com.ogove.hr.Core.Broadcast;
import com.ogove.hr.Core.Config;
import com.ogove.hr.Core.LocalData;
import com.ogove.hr.Core.LocalStorage;
import com.ogove.hr.Core.Nav;
import com.ogove.hr.Core.Utils;
import com.ogove.hr.Entities.Company;
import com.ogove.hr.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

import cz.msebera.android.httpclient.Header;

public class CompanyAdapter extends ArrayAdapter<Company>
    implements View.OnClickListener{
    private Activity context = null;
    private ArrayList<Company> datas = null;
    private int layoutId;

    public CompanyAdapter(Activity context, int layoutId, ArrayList<Company> datas){
        super(context, layoutId, datas);
        this.context = context;
        this.layoutId = layoutId;
        this.datas = datas;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        if ((context != null) && (position >= 0) && (position < datas.size()))
        {
            LayoutInflater inflater = context.getLayoutInflater();
            convertView = inflater.inflate(layoutId, null);

            Company obj = datas.get(position);

            TextView name = (TextView) convertView.findViewById(R.id.itName);
            name.setText(obj.getName());

            LinearLayout itManager = (LinearLayout) convertView.findViewById(R.id.itManager);
            if (obj.getManager()) {
                AppCompatImageView itUpdate = (AppCompatImageView) convertView.findViewById(R.id.itUpdate);
                itUpdate.setTag(obj.getId());
                itUpdate.setOnClickListener(this);

                AppCompatImageView itDelete = (AppCompatImageView) convertView.findViewById(R.id.itDelete);
                itDelete.setTag(obj.getId());
                itDelete.setOnClickListener(this);
            }
            else itManager.setVisibility(View.GONE);
        }
        return convertView;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.itUpdate:
            {
                AppCompatImageView itUpdate = (AppCompatImageView) v;
                String Id = (String) itUpdate.getTag();
                Nav.openCompanySettings(context, Id);
                break;
            }
            case R.id.itDelete:
            {
                AppCompatImageView itDelete = (AppCompatImageView) v;
                String Id = (String) itDelete.getTag();
                delete(Id);
                break;
            }
        }
    }

    private void delete(String id)
    {
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = Utils.UserParams();
        Company obj = LocalData.getCompany(id);
        params.put("companyid", obj.getId());
        client.delete(Config.BaseURL +"/company", params, new JsonHttpResponseHandler() {
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {
                    if (response.getBoolean("Success"))
                    {
                        JSONObject result = response.getJSONObject("Result");
                        LocalData.removeCompany(result.getString("Id"));
                        Broadcast.reloadCompanies();
                    }
                    else Utils.messageShort(context, response.getString("Message"));
                } catch (Exception E) {}
            }
        });
    }
}


text:
<?php

namespace Luthor\Parser\Extensions;

use Luthor\Parser\Extensions\Adapters\BlockAdapter;

/**
 * This is a token defintion for Codeblocks
 */
class Codeblock extends BlockAdapter
{
    /** inline {@inheritdoc} */
    public $priority = 40;

    /** inline {@inheritdoc} */
    public function getIndentation()
    {
        return 1;
    }

    /** inline {@inheritdoc} */
    public function getRegex()
    {
        return '~ {' . abs($this->config['tab_to_spaces']) . '}~A';
    }

    /** inline {@inheritdoc} */
    public function getContext()
    {
        $context = array(
            'indent' => $this->indent,
            'line' => $this->line,
            'type' => $this->getType(),
            'close_on' => array('LINE'),
            'close_html' => "
",
            'create_html' => "
\n" . str_repeat(' ', abs($this->config['tab_to_spaces'])),
            'to_raw' => array('*'),
        );

        return new Context($context);
    }
}

?>

redpajama_set_name: RedPajamaGithub


text:
angular.module('app')
  .controller('AddBusinessController', AddBusinessController);

AddBusinessController.$inject = ['user',
  '$scope',
  '$mdDialog',
  'DatabaseService',
  'BusinessService',
  'US_STATES',
  'BUSINESS_CATEGORIES'];

function AddBusinessController(user, $scope, $mdDialog, DatabaseService,
                               BusinessService, US_STATES,
                               BUSINESS_CATEGORIES) {
  $scope.$onInit = $onInit();
  $scope.states = US_STATES;
  $scope.cancel = cancel;
  $scope.submit = submit;
  $scope.categories = BUSINESS_CATEGORIES;
  $scope.facebookUrl = 'http://www.facebook.com/';
  $scope.url = 'http://www.';

  function $onInit() {
  }

  function cancel() {
    $mdDialog.hide();
    BusinessService.setBusiness(null);
  }

  function submit() {
    var businessUid = DatabaseService.createBusiness($scope.business, user);
    $scope.business.uid = businessUid;
    BusinessService.setBusiness($scope.business);
    $mdDialog.hide();
    showUploadPhotoDialog($scope.business, businessUid, 'business');
  }

  function showUploadPhotoDialog(data, uid, collection) {
    $mdDialog.show({
      controller: UploadPhotoController,
      templateUrl: 'components/upload-photo/upload-photo.html',
      parent: angular.element(document.body),
      clickOutsideToClose: true,
      locals: {
        data: data,
        uid: uid,
        collection: collection
      }
    });
  }
}


text:
package org.sakaiproject.scorm.dao.hibernate;

import org.adl.datamodels.DMErrorCodes;
import org.adl.datamodels.DMFactory;
import org.adl.datamodels.DMProcessingInfo;
import org.adl.datamodels.DMRequest;
import org.adl.datamodels.SCODataManager;
import org.adl.datamodels.ieee.ValidatorFactory;
import org.sakaiproject.scorm.dao.api.DataManagerDao;

public class DataManagerDaoImplTest extends AbstractServiceTest {
	DataManagerDao dataManagerDao;

	@Override
	protected void onSetUpBeforeTransaction() throws Exception {
		super.onSetUpBeforeTransaction();
		dataManagerDao = (DataManagerDao) getApplicationContext().getBean("org.sakaiproject.scorm.dao.api.DataManagerDao");
	}

	public void testSimple() {

		SCODataManager dataManager = new SCODataManager();
		ValidatorFactory validatorFactory = new ValidatorFactory();
		dataManager.addDM(DMFactory.DM_SCORM_2004, validatorFactory);
		dataManager.addDM(DMFactory.DM_SCORM_NAV, validatorFactory);
		dataManager.addDM(DMFactory.DM_SSP, validatorFactory);
		dataManager.setScoId("sco01");
		dataManagerDao.save(dataManager);
		dataManager.setValue(new DMRequest("cmi.interactions.0.id", "1"), validatorFactory);

		dataManagerDao.update(dataManager);

		assertEquals(0, dataManager.getValue(new DMRequest("cmi.interactions.0.id"), new DMProcessingInfo()));
		assertEquals(DMErrorCodes.OUT_OF_RANGE, dataManager.getValue(new DMRequest("cmi.interactions.1.id"), new DMProcessingInfo()));
	}

}


text:
package org.apache.commons.dbcp2.cpdsadapter;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.time.Duration;
import java.util.Properties;

import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import javax.sql.DataSource;

import org.apache.commons.dbcp2.Constants;
import org.apache.commons.dbcp2.datasources.SharedPoolDataSource;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

/**
 * Tests for DriverAdapterCPDS
 */
public class TestDriverAdapterCPDS {

    private static class ThreadDbcp367 extends Thread {

        private final DataSource ds;

        private volatile boolean failed;

        public ThreadDbcp367(final DataSource ds) {
            this.ds = ds;
        }

        public boolean isFailed() {
            return failed;
        }

        @Override
        public void run() {
            Connection c = null;
            try {
                for (int j=0; j < 5000; j++) {
                    c = ds.getConnection();
                    c.close();
                }
            } catch (final SQLException sqle) {
                failed = true;
                sqle.printStackTrace();
            }
        }
    }

    private DriverAdapterCPDS pcds;

    @BeforeEach
    public void setUp() throws Exception {
        pcds = new DriverAdapterCPDS();
        pcds.setDriver("org.apache.commons.dbcp2.TesterDriver");
        pcds.setUrl("jdbc:apache:commons:testdriver");
        pcds.setUser("foo");
        pcds.setPassword("bar");
        pcds.setPoolPreparedStatements(false);
    }

    @Test
    public void testClosingWithUserName()
        throws Exception {
        final Connection[] c = new Connection[10];
        for (int i=0; i<c.length; i++) {
            c[i] = pcds.getPooledConnection("u1", "p1").getConnection();
        }

        // close one of the connections
        c[0].close();
        assertTrue(c[0].isClosed());
        // get a new connection
        c[0] = pcds.getPooledConnection("u1", "p1").getConnection();

        for (final Connection element : c) {
            element.close();
        }

        // open all the connections
        for (int i=0; i<c.length; i++) {
            c[i] = pcds.getPooledConnection("u1", "p1").getConnection();
        }
        for (final Connection element : c) {
            element.close();
        }
    }

    // https://issues.apache.org/jira/browse/DBCP-376
    @Test
    public void testDbcp367() throws Exception {
        final ThreadDbcp367[] threads = new ThreadDbcp367[200];

        pcds.setPoolPreparedStatements(true);
        pcds.setMaxPreparedStatements(-1);
        pcds.setAccessToUnderlyingConnectionAllowed(true);

        try (final SharedPoolDataSource spds = new SharedPoolDataSource()) {
            spds.setConnectionPoolDataSource(pcds);
            spds.setMaxTotal(threads.length + 10);
            spds.setDefaultMaxWait(Duration.ofMillis(-1));
            spds.setDefaultMaxIdle(10);
            spds.setDefaultAutoCommit(Boolean.FALSE);

            spds.setValidationQuery("SELECT 1");
            spds.setDefaultDurationBetweenEvictionRuns(Duration.ofSeconds(10));
            spds.setDefaultNumTestsPerEvictionRun(-1);
            spds.setDefaultTestWhileIdle(true);
            spds.setDefaultTestOnBorrow(true);
            spds.setDefaultTestOnReturn(false);

            for (int i = 0; i < threads.length; i++) {
                threads[i] = new ThreadDbcp367(spds);
                threads[i].start();
            }

            for (int i = 0; i < threads.length; i++) {
                threads[i].join();
                Assertions.assertFalse(threads[i].isFailed(), "Thread " + i + " has failed");
            }
        }
    }

    @SuppressWarnings("deprecation")
    @Test
    public void testDeprecatedAccessors() {
        int i = 0;
        //
        i++;
        pcds.setMinEvictableIdleTimeMillis(i);
        assertEquals(i, pcds.getMinEvictableIdleTimeMillis());
        assertEquals(Duration.ofMillis(i), pcds.getMinEvictableIdleDuration());
        //
        i++;
        pcds.setTimeBetweenEvictionRunsMillis(i);
        assertEquals(i, pcds.getTimeBetweenEvictionRunsMillis());
        assertEquals(Duration.ofMillis(i), pcds.getDurationBetweenEvictionRuns());
    }

    @Test
    public void testGetObjectInstance() throws Exception {
        final Reference ref = pcds.getReference();
        final Object o = pcds.getObjectInstance(ref, null, null, null);
        assertEquals(pcds.getDriver(), ((DriverAdapterCPDS) o).getDriver());
    }

    @Test
    public void testGetObjectInstanceChangeDescription() throws Exception {
        final Reference ref = pcds.getReference();
        for (int i = 0; i < ref.size(); i++) {
            if (ref.get(i).getType().equals("description")) {
                ref.remove(i);
                break;
            }
        }
        ref.add(new StringRefAddr("description", "anything"));
        final Object o = pcds.getObjectInstance(ref, null, null, null);
        assertEquals(pcds.getDescription(), ((DriverAdapterCPDS) o).getDescription());
    }

    @Test
    public void testGetObjectInstanceNull() throws Exception {
        final Object o = pcds.getObjectInstance(null, null, null, null);
        assertNull(o);
    }

    @Test
    public void testGetParentLogger() {
        assertThrows(SQLFeatureNotSupportedException.class, pcds::getParentLogger);
    }

    @Test
    public void testGetReference() throws NamingException {
        final Reference ref = pcds.getReference();
        assertEquals(pcds.getDriver(), ref.get("driver").getContent());
        assertEquals(pcds.getDescription(), ref.get("description").getContent());
    }

    @Test
    public void testGettersAndSetters() {
        pcds.setUser("foo");
        assertEquals("foo", pcds.getUser());
        pcds.setPassword("bar");
        assertEquals("bar", pcds.getPassword());
        pcds.setPassword(new char[] {'a', 'b'});
        assertArrayEquals(new char[] {'a', 'b'}, pcds.getPasswordCharArray());
        final PrintWriter pw = new PrintWriter(System.err);
        pcds.setLogWriter(pw);
        @SuppressWarnings("resource")
        final PrintWriter logWriter = pcds.getLogWriter();
        assertEquals(pw, logWriter);
        pcds.setLoginTimeout(10);
        assertEquals(10, pcds.getLoginTimeout());
        pcds.setMaxIdle(100);
        assertEquals(100, pcds.getMaxIdle());
        pcds.setDurationBetweenEvictionRuns(Duration.ofMillis(100));
        assertEquals(100, pcds.getDurationBetweenEvictionRuns().toMillis());
        pcds.setNumTestsPerEvictionRun(1);
        assertEquals(1, pcds.getNumTestsPerEvictionRun());
        pcds.setMinEvictableIdleDuration(Duration.ofMillis(11));
        assertEquals(Duration.ofMillis(11), pcds.getMinEvictableIdleDuration());
        pcds.setDescription("jo");
        assertEquals("jo", pcds.getDescription());
    }

    /**
     * JIRA: DBCP-245
     */
    @Test
    public void testIncorrectPassword() throws Exception
    {
        pcds.getPooledConnection("u2", "p2").close();
        try {
            // Use bad password
            pcds.getPooledConnection("u1", "zlsafjk");
            fail("Able to retrieve connection with incorrect password");
        } catch (final SQLException e1) {
            // should fail

        }

        // Use good password
        pcds.getPooledConnection("u1", "p1").close();
        try {
            pcds.getPooledConnection("u1", "x");
            fail("Able to retrieve connection with incorrect password");
        }
        catch (final SQLException e) {
            if (!e.getMessage().startsWith("x is not the correct password")) {
                throw e;
            }
            // else the exception was expected
        }

        // Make sure we can still use our good password.
        pcds.getPooledConnection("u1", "p1").close();
    }

    /**
     * JIRA: DBCP-442
     */
    @Test
    public void testNullValidationQuery() throws Exception {
        try (final SharedPoolDataSource spds = new SharedPoolDataSource()) {
            spds.setConnectionPoolDataSource(pcds);
            spds.setDefaultTestOnBorrow(true);
            try (final Connection c = spds.getConnection()) {
                // close right away
            }
        }
    }

    @Test
    public void testSetConnectionProperties() throws Exception {
        // Set user property to bad value
        pcds.setUser("bad");
        // Supply correct value in connection properties
        // This will overwrite field value
        final Properties properties = new Properties();
        properties.put(Constants.KEY_USER, "foo");
        properties.put(Constants.KEY_PASSWORD, pcds.getPassword());
        pcds.setConnectionProperties(properties);
        pcds.getPooledConnection().close();
        assertEquals("foo", pcds.getUser());
        // Put bad password into properties
        properties.put("password", "bad");
        // This does not change local field
        assertEquals("bar", pcds.getPassword());
        // Supply correct password in getPooledConnection
        // Call will succeed and overwrite property
        pcds.getPooledConnection("foo", "bar").close();
        assertEquals("bar", pcds.getConnectionProperties().getProperty("password"));
    }

    @Test
    public void testSetConnectionPropertiesConnectionCalled() throws Exception {
        final Properties properties = new Properties();
        // call to the connection
        pcds.getPooledConnection().close();
        assertThrows(IllegalStateException.class, () -> pcds.setConnectionProperties(properties));
    }

    @Test
    public void testSetConnectionPropertiesNull() throws Exception {
        pcds.setConnectionProperties(null);
    }

    @Test
    public void testSetPasswordNull() throws Exception {
        pcds.setPassword("Secret");
        assertEquals("Secret", pcds.getPassword());
        pcds.setPassword((char[]) null);
        assertNull(pcds.getPassword());
    }

    @Test
    public void testSetPasswordNullWithConnectionProperties() throws Exception {
        pcds.setConnectionProperties(new Properties());
        pcds.setPassword("Secret");
        assertEquals("Secret", pcds.getPassword());
        pcds.setPassword((char[]) null);
        assertNull(pcds.getPassword());
    }

    @Test
    public void testSetPasswordThenModCharArray() {
        final char[] pwd = {'a'};
        pcds.setPassword(pwd);
        assertEquals("a", pcds.getPassword());
        pwd[0] = 'b';
        assertEquals("a", pcds.getPassword());
    }

    @Test
    public void testSetUserNull() throws Exception {
        pcds.setUser("Alice");
        assertEquals("Alice", pcds.getUser());
        pcds.setUser(null);
        assertNull(pcds.getUser());
    }

    @Test
    public void testSetUserNullWithConnectionProperties() throws Exception {
        pcds.setConnectionProperties(new Properties());
        pcds.setUser("Alice");
        assertEquals("Alice", pcds.getUser());
        pcds.setUser(null);
        assertNull(pcds.getUser());
    }

    @Test
    public void testSimple() throws Exception {
        try (final Connection conn = pcds.getPooledConnection().getConnection()) {
            assertNotNull(conn);
            try (final PreparedStatement stmt = conn.prepareStatement("select * from dual")) {
                assertNotNull(stmt);
                try (final ResultSet rset = stmt.executeQuery()) {
                    assertNotNull(rset);
                    assertTrue(rset.next());
                }
            }
        }
    }

    @Test
    public void testSimpleWithUsername() throws Exception {
        try (final Connection conn = pcds.getPooledConnection("u1", "p1").getConnection()) {
            assertNotNull(conn);
            try (final PreparedStatement stmt = conn.prepareStatement("select * from dual")) {
                assertNotNull(stmt);
                try (final ResultSet rset = stmt.executeQuery()) {
                    assertNotNull(rset);
                    assertTrue(rset.next());
                }
            }
        }
    }

    @Test
    public void testToStringWithoutConnectionProperties() throws ClassNotFoundException
    {
        final DriverAdapterCPDS cleanCpds = new DriverAdapterCPDS();
        cleanCpds.setDriver( "org.apache.commons.dbcp2.TesterDriver" );
        cleanCpds.setUrl( "jdbc:apache:commons:testdriver" );
        cleanCpds.setUser( "foo" );
        cleanCpds.setPassword( "bar" );

        cleanCpds.toString();
    }
}


text:
$(document).ready(function() {
	/// here...
});


text:
package com.amazonaws.services.elasticache.model;

import java.io.Serializable;
import com.amazonaws.AmazonWebServiceRequest;

/**
 *

 * Represents the input of a DescribeReplicationGroups action.
 *

 */
public class DescribeReplicationGroupsRequest extends AmazonWebServiceRequest
        implements Serializable, Cloneable {

    /**
     *

     * The identifier for the replication group to be described. This parameter
     * is not case sensitive.
     *

     *

     * If you do not specify this parameter, information about all replication
     * groups is returned.
     *

     */
    private String replicationGroupId;
    /**
     *

     * The maximum number of records to include in the response. If more records
     * exist than the specified MaxRecords value, a marker is
     * included in the response so that the remaining results can be retrieved.
     *

     *

     * Default: 100
     *

     *

     * Constraints: minimum 20; maximum 100.
     *

     */
    private Integer maxRecords;
    /**
     *

     * An optional marker returned from a prior request. Use this marker for
     * pagination of results from this action. If this parameter is specified,
     * the response includes only records beyond the marker, up to the value
     * specified by MaxRecords.
     *

     */
    private String marker;

    /**
     *

     * The identifier for the replication group to be described. This parameter
     * is not case sensitive.
     *

     *

     * If you do not specify this parameter, information about all replication
     * groups is returned.
     *

     *
     * @param replicationGroupId
     *        The identifier for the replication group to be described. This
     *        parameter is not case sensitive.

     *

     *        If you do not specify this parameter, information about all
     *        replication groups is returned.
     */

    public void setReplicationGroupId(String replicationGroupId) {
        this.replicationGroupId = replicationGroupId;
    }

    /**
     *

     * The identifier for the replication group to be described. This parameter
     * is not case sensitive.
     *

     *

     * If you do not specify this parameter, information about all replication
     * groups is returned.
     *

     *
     * @return The identifier for the replication group to be described. This
     *         parameter is not case sensitive.

     *

     *         If you do not specify this parameter, information about all
     *         replication groups is returned.
     */

    public String getReplicationGroupId() {
        return this.replicationGroupId;
    }

    /**
     *

     * The identifier for the replication group to be described. This parameter
     * is not case sensitive.
     *

     *

     * If you do not specify this parameter, information about all replication
     * groups is returned.
     *

     *
     * @param replicationGroupId
     *        The identifier for the replication group to be described. This
     *        parameter is not case sensitive.

     *

     *        If you do not specify this parameter, information about all
     *        replication groups is returned.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public DescribeReplicationGroupsRequest withReplicationGroupId(
            String replicationGroupId) {
        setReplicationGroupId(replicationGroupId);
        return this;
    }

    /**
     *

     * The maximum number of records to include in the response. If more records
     * exist than the specified MaxRecords value, a marker is
     * included in the response so that the remaining results can be retrieved.
     *

     *

     * Default: 100
     *

     *

     * Constraints: minimum 20; maximum 100.
     *

     *
     * @param maxRecords
     *        The maximum number of records to include in the response. If more
     *        records exist than the specified MaxRecords value, a
     *        marker is included in the response so that the remaining results
     *        can be retrieved.

     *

     *        Default: 100
     *

     *

     *        Constraints: minimum 20; maximum 100.
     */

    public void setMaxRecords(Integer maxRecords) {
        this.maxRecords = maxRecords;
    }

    /**
     *

     * The maximum number of records to include in the response. If more records
     * exist than the specified MaxRecords value, a marker is
     * included in the response so that the remaining results can be retrieved.
     *

     *

     * Default: 100
     *

     *

     * Constraints: minimum 20; maximum 100.
     *

     *
     * @return The maximum number of records to include in the response. If more
     *         records exist than the specified MaxRecords value, a
     *         marker is included in the response so that the remaining results
     *         can be retrieved.

     *

     *         Default: 100
     *

     *

     *         Constraints: minimum 20; maximum 100.
     */

    public Integer getMaxRecords() {
        return this.maxRecords;
    }

    /**
     *

     * The maximum number of records to include in the response. If more records
     * exist than the specified MaxRecords value, a marker is
     * included in the response so that the remaining results can be retrieved.
     *

     *

     * Default: 100
     *

     *

     * Constraints: minimum 20; maximum 100.
     *

     *
     * @param maxRecords
     *        The maximum number of records to include in the response. If more
     *        records exist than the specified MaxRecords value, a
     *        marker is included in the response so that the remaining results
     *        can be retrieved.

     *

     *        Default: 100
     *

     *

     *        Constraints: minimum 20; maximum 100.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public DescribeReplicationGroupsRequest withMaxRecords(Integer maxRecords) {
        setMaxRecords(maxRecords);
        return this;
    }

    /**
     *

     * An optional marker returned from a prior request. Use this marker for
     * pagination of results from this action. If this parameter is specified,
     * the response includes only records beyond the marker, up to the value
     * specified by MaxRecords.
     *

     *
     * @param marker
     *        An optional marker returned from a prior request. Use this marker
     *        for pagination of results from this action. If this parameter is
     *        specified, the response includes only records beyond the marker,
     *        up to the value specified by MaxRecords.
     */

    public void setMarker(String marker) {
        this.marker = marker;
    }

    /**
     *

     * An optional marker returned from a prior request. Use this marker for
     * pagination of results from this action. If this parameter is specified,
     * the response includes only records beyond the marker, up to the value
     * specified by MaxRecords.
     *

     *
     * @return An optional marker returned from a prior request. Use this marker
     *         for pagination of results from this action. If this parameter is
     *         specified, the response includes only records beyond the marker,
     *         up to the value specified by MaxRecords.
     */

    public String getMarker() {
        return this.marker;
    }

    /**
     *

     * An optional marker returned from a prior request. Use this marker for
     * pagination of results from this action. If this parameter is specified,
     * the response includes only records beyond the marker, up to the value
     * specified by MaxRecords.
     *

     *
     * @param marker
     *        An optional marker returned from a prior request. Use this marker
     *        for pagination of results from this action. If this parameter is
     *        specified, the response includes only records beyond the marker,
     *        up to the value specified by MaxRecords.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public DescribeReplicationGroupsRequest withMarker(String marker) {
        setMarker(marker);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getReplicationGroupId() != null)
            sb.append("ReplicationGroupId: " + getReplicationGroupId() + ",");
        if (getMaxRecords() != null)
            sb.append("MaxRecords: " + getMaxRecords() + ",");
        if (getMarker() != null)
            sb.append("Marker: " + getMarker());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeReplicationGroupsRequest == false)
            return false;
        DescribeReplicationGroupsRequest other = (DescribeReplicationGroupsRequest) obj;
        if (other.getReplicationGroupId() == null
                ^ this.getReplicationGroupId() == null)
            return false;
        if (other.getReplicationGroupId() != null
                && other.getReplicationGroupId().equals(
                        this.getReplicationGroupId()) == false)
            return false;
        if (other.getMaxRecords() == null ^ this.getMaxRecords() == null)
            return false;
        if (other.getMaxRecords() != null
                && other.getMaxRecords().equals(this.getMaxRecords()) == false)
            return false;
        if (other.getMarker() == null ^ this.getMarker() == null)
            return false;
        if (other.getMarker() != null
                && other.getMarker().equals(this.getMarker()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime
                * hashCode
                + ((getReplicationGroupId() == null) ? 0
                        : getReplicationGroupId().hashCode());
        hashCode = prime * hashCode
                + ((getMaxRecords() == null) ? 0 : getMaxRecords().hashCode());
        hashCode = prime * hashCode
                + ((getMarker() == null) ? 0 : getMarker().hashCode());
        return hashCode;
    }

    @Override
    public DescribeReplicationGroupsRequest clone() {
        return (DescribeReplicationGroupsRequest) super.clone();
    }
}


text:
#include <stdexcept>

#ifndef HOOLANG_NOTIMPLEMENTEDEXCEPTION_HH
#define HOOLANG_NOTIMPLEMENTEDEXCEPTION_HH

namespace hoo
{
    namespace common
    {
        class NotImplementedException : public std::runtime_error
        {
        public:
            NotImplementedException();
            explicit NotImplementedException(const std::string &arg);
        };
    } // namespace common
} // namespace hoo

#endif //HOOLANG_NOTIMPLEMENTEDEXCEPTION_HH


text:
package de.theit.jenkins.crowd;

import java.util.ArrayList;
import java.util.Collection;

import org.jvnet.localizer.ResourceBundleHolder;

/**
 * This class delivers localized error messages.
 *
 * @author Thorsten Heit (theit@gmx.de)
 * @since 06.09.2011
 * @version $Id$
 */
public class ErrorMessages {
	/** Contains the localized messages. */
	private final static ResourceBundleHolder holder = ResourceBundleHolder.get(ErrorMessages.class);

	/**
	 * Returns the localized error message when no URL is specified.
	 *
	 * @return The localized error message for a missing Crowd URL.
	 */
	public static String specifyCrowdUrl() {
		return holder.format("pleaseSpecifyCrowdUrl");
	}

	/**
	 * Returns the localized error message when no application name is given.
	 *
	 * @return The localized error message for a missing application name.
	 */
	public static String specifyApplicationName() {
		return holder.format("specifyApplicationName");
	}

	/**
	 * Returns the localized error message when no application password is
	 * given.
	 *
	 * @return The localized error message for a missing application password.
	 */
	public static String specifyApplicationPassword() {
		return holder.format("specifyApplicationPassword");
	}

	/**
	 * Returns the localized error message when no group name is given.
	 *
	 * @return The localized error message for a missing group name.
	 */
	public static String specifyGroup() {
		return holder.format("specifyGroup");
	}

	/**
	 * Returns the localized error message when no session validation interval
	 * time is given.
	 *
	 * @return The localized error message for a missing session validation
	 *         interval time.
	 */
	public static String specifySessionValidationInterval() {
		return holder.format("specifySessionValidationInterval");
	}

	/**
	 * Returns the localized error message when the connection check failed.
	 *
	 * @return The localized error message for a failed connection check.
	 */
	public static String operationFailed() {
		return holder.format("operationFailed");
	}

	/**
	 * Returns the localized error message when the configuration file
	 * crowd.properties cannot be loaded.
	 *
	 * @return The localized error message when the configuration file
	 *         crowd.properties cannot be loaded.
	 */
	public static String cannotLoadCrowdProperties() {
		return holder.format("cannotLoadCrowdProperties");
	}

	/**
	 * Returns the localized error message text when the application name and
	 * password are not valid.
	 *
	 * @return The localized error message for invalid application name and
	 *         password.
	 */
	public static String invalidAuthentication() {
		return holder.format("invalidAuthentication");
	}

	/**
	 * Returns the localized error message when the application has no
	 * permission to perform a connection check to the Crowd server.
	 *
	 * @return The localized error message for missing permission to perform a
	 *         connection check to the Crowd server.
	 */
	public static String applicationPermission() {
		return holder.format("applicationPermission");
	}

	/**
	 * Returns the localized error message when the user was not found on the
	 * remote Crowd server.
	 *
	 * @param username
	 *            The user name. May not be null.
	 *
	 * @return The localized error message when the user was not found on the
	 *         remote Crowd server.
	 */
	public static String userNotFound(String username) {
		return holder.format("userNotFound", username);
	}

	/**
	 * Returns the localized error message when the group was not found on the
	 * remote Crowd server.
	 *
	 * @param groupname
	 *            The name of the group. May not be null.
	 *
	 * @return The localized error message when the group was not found on the
	 *         remote Crowd server.
	 */
	public static String groupNotFound(String groupname) {
		return holder.format("groupNotFound", groupname);
	}

	/**
	 * Returns the localized error message when the user password has expired
	 * and must be changed.
	 *
	 * @param username
	 *            The user name. May not be null.
	 *
	 * @return The localized error message when the user password has expired.
	 */
	public static String expiredCredentials(String username) {
		return holder.format("expiredCredentials", username);
	}

	/**
	 * Returns the localized error message when the account is inactive.
	 *
	 * @param username
	 *            The user name. May not be null.
	 *
	 * @return The localized error message when the account is inactive.
	 */
	public static String accountExpired(String username) {
		return holder.format("accountExpired", username);
	}

	/**
	 * Returns the localized error message when a user does not have access to
	 * authenticate against an application.
	 *
	 * @param username
	 *            The user name. May not be null.
	 *
	 * @return The localized error message for denied application access.
	 */
	public static String applicationAccessDenied(String username) {
		return holder.format("applicationAccessDenied", username);
	}

	/**
	 * Returns the localized error message when a user does not have the
	 * permission to login.
	 *
	 * @param username
	 *            The user name. May not be null.
	 * @param groupNames
	 *            The names of the groups allowed to login. May not be
	 *            null.
	 *
	 * @return The localized error message when a user does not have the
	 *         permission to login.
	 */
	public static String userNotValid(String username, ArrayList<String> groupNames) {
		return holder.format("userNotValid", username, groupNames.toString());
	}
}


text:
/**
 * Libs
 */
var React = require('react');
var TupiqTools = require('../utils/TupiqTools');
var Analytics = require('../utils/Analytics');

/**
 * Stores
 */
var TupiqStore = require('../stores/TupiqStore');

/**
 * Actions
 */
var TupiqActions = require('../actions/TupiqActions');

/**
 * Pure component
 */
var Tupiq = require('./Tupiq.react');

/**
 * Private
 */
var padding = 10;

function getStateFromStores() {
  return {
    isDragging: TupiqStore.getDragging(),
    isMinimised: TupiqStore.getMinimised(),
    coordinates: TupiqStore.getCoordinates(),
    dragOriginData: TupiqStore.getDragOriginData()
  }
}

/**
 * TupiqContainer
 */
var TupiqContainer = React.createClass({
  getInitialState: function() {
    return getStateFromStores();
  },

  componentDidMount: function() {
    TupiqStore.addChangeListener(this._onChange);

    // Listen to window resize so we can reposition if necessary
    window.addEventListener('resize', this.onWindowResize);

    // Handcrafted DOM resize handler
    // http://www.backalleycoder.com/2013/03/18/cross-browser-event-based-element-resize-detection/
    var object = document.createElement('object');
    object.setAttribute('style', 'display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; pointer-events: none; z-index: -1;');
    object.onload = function() {
    	object.contentDocument.defaultView.addEventListener('resize', this.onDomNodeResize);
    }.bind(this);
    object.type = 'text/html';
    object.data = 'about:blank';

    var domNode = this.getDOMNode();
    domNode.appendChild(object);

    // This will be fired from the context menu background script.
    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  		if ('minimisePanel' in request) {
				TupiqActions.minimise();

				Analytics.trackEvent('Button', 'Click', 'Minimise Panel');
  		}
  	}.bind(this));
  },

  componentWillUnmount: function() {
    TupiqStore.removeChangeListener(this._onChange);

    window.removeEventListener('resize', this.onWindowResize);
  },

  _onChange: function() {
    this.setState(getStateFromStores());
  },

  onDomNodeResize: function(event) {
  	this.onWindowResize();
  },

  onWindowResize: function(event) {
  	// If we're minimised, or it's the initial x position of 50%
    if (this.state.isMinimised === true) {
    	return;
    }

    // We could call forceUpdate here, but nested Tupiq component is "pure"
    // and will ignore a forceUpdate. Better yet set window dimensions
    // into state?
    TupiqActions.reposition({
      x: this.state.coordinates.x,
      y: this.state.coordinates.y
    });
  },

  onMouseDown: function(event) {
    // Dodgy as.
    if (this.state.isMinimised === true || event.target.className === 'tupiq__header__logo-container' || event.target.className === 'tupiq__header__logo-container__tupiq-logo') {
    	event.preventDefault();

    	return;
    }

    if (event.button === 0) {
      event.stopPropagation();

      this.addEvents();

      var pageOffset = this.getDOMNode().getBoundingClientRect();

      TupiqActions.startDrag({
        scrollOriginX: event.pageX,
        scrollOriginY: event.pageY,
        elementOriginX: pageOffset.left,
        elementOriginY: pageOffset.top
      });

      Analytics.trackEvent('Tupiq', 'Drag');
    }
  },

  onMouseMove: function(event) {
  	var element = this.getDOMNode(),
  			elementWidth = element.offsetWidth,
				elementHeight = element.offsetHeight,
    		elementWidthCenter = elementWidth / 2,
				elementHeightCenter = elementHeight / 2,
				windowWidthCenter = window.innerWidth / 2,
				windowHeightCenter = window.innerHeight / 2,
				deltaX = event.pageX - this.state.dragOriginData.scrollOriginX,
				deltaY = event.pageY - this.state.dragOriginData.scrollOriginY,
				targetX = this.state.dragOriginData.elementOriginX + deltaX + elementWidthCenter,
				targetY = this.state.dragOriginData.elementOriginY + deltaY + elementHeightCenter,
				snapBuffer = 15;

    if (this.state.isDragging) {
      var targetXRel = (targetX - elementWidthCenter - padding) / (window.innerWidth - elementWidth - (padding * 2));
      var targetYRel = (targetY - elementHeightCenter - padding) / (window.innerHeight - elementHeight - (padding * 2));

      targetXRel = Math.max(targetXRel, 0);
      targetXRel = Math.min(targetXRel, 1);

      targetYRel = Math.max(targetYRel, 0);
      targetYRel = Math.min(targetYRel, 1);

      if (TupiqTools.isNumberBetween(targetX, windowWidthCenter - snapBuffer, windowWidthCenter + snapBuffer) && TupiqTools.isNumberBetween(targetY, windowHeightCenter - snapBuffer, windowHeightCenter + snapBuffer)) {
      	targetXRel = .5;
      	targetYRel = .5;
      }

      TupiqActions.reposition({
        x: targetXRel,
        y: targetYRel
      });
    }
  },

  onMouseUp: function(event) {
    this.removeEvents();

    TupiqActions.stopDrag();
  },

  addEvents: function() {
    document.addEventListener('mousemove', this.onMouseMove);
    document.addEventListener('mouseup', this.onMouseUp);
  },

  removeEvents: function() {
    document.removeEventListener('mousemove', this.onMouseMove);
    document.removeEventListener('mouseup', this.onMouseUp);
  },

  render: function(){
    return (
      <Tupiq
      	isMinimised={this.state.isMinimised}
        isDragging={this.state.isDragging}
        coordinates={this.state.coordinates}
        onMouseDown={this.onMouseDown} />
    )
  }
});

module.exports = TupiqContainer;


text:
using namespace std;

int main (){

	//number of bins`
	int num;
	//capacity of bin
	int size;
	ifstream infile;
	infile.open("inputFile.txt");
	infile >> num;
	infile >> size;
	int* objectSize = new int[num];
	int x;
	for(int j = 0; j < num; j++)
	{
		infile >> x;
		objectSize[j] = x;
	}

	BinPacking* b = new BinPacking(num);

	//call firstfit
	cout<< "Using First Fit Packing .... " <<endl<<endl;

	b->firstFitPack(objectSize, num, size);

	b->printBinSequence();

	cout<< endl << "Using Best Fit Packing .... " <<endl<<endl;

	////call bestfit
	b->bestFitPack(objectSize, num, size);

	b->printBinSequence();

}


text:
package com.salesforce.dva.argus.ws.dto;

import com.salesforce.dva.argus.ws.annotation.Description;
import com.salesforce.dva.argus.ws.resources.AbstractResource;
import javax.ws.rs.Path;

/**
 * Endpoint help DTO.
 *
 * @author  Tom Valine (tvaline@salesforce.com)
 */
public class EndpointHelpDto {

    //~ Instance fields ******************************************************************************************************************************

    String endpoint;
    String description;

    //~ Methods **************************************************************************************************************************************

    /**
     * Creates an endpoint help DTO from a resource class.
     *
     * @param   resourceClass  The resource class.
     *
     * @return  The endpoint help DTO.
     */
    public static EndpointHelpDto fromResourceClass(Class<? extends AbstractResource> resourceClass) {
        Path path = resourceClass.getAnnotation(Path.class);
        Description description = resourceClass.getAnnotation(Description.class);

        if (path != null && description != null) {
            EndpointHelpDto result = new EndpointHelpDto();

            result.setDescription(description.value());
            result.setEndpoint(path.value());
            return result;
        } else {
            return null;
        }
    }

    //~ Methods **************************************************************************************************************************************

    /**
     * Returns the endpoint.
     *
     * @return  The endpoint.
     */
    public String getEndpoint() {
        return endpoint;
    }

    /**
     * Specifies the endpoint.
     *
     * @param  endpoint  The endpoint.
     */
    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }

    /**
     * Returns the description.
     *
     * @return  The description.
     */
    public String getDescription() {
        return description;
    }

    /**
     * Specifies the description.
     *
     * @param  description  The description.
     */
    public void setDescription(String description) {
        this.description = description;
    }
}
/* Copyright (c) 2016, Salesforce.com, Inc.  All rights reserved. */


text:
package hy222ap_assign1;

import java.util.Scanner;

public class Convert {

	public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

		System.out.print("Give a temperature in Fahrenheit: ");

		double F =scan.nextDouble();

		double C =(F-32)*5/9;

		System.out.print("\nThe temperature in Celsius is: "+Math.round(C*10)/10.0);

		scan.close();
	}

}


text:
- Date: 25 Oct 2016
- Attendees: Jon, Andy, Ben, Celia, Dillon, James, Jerry, Max, Paul, Aaron.
- Start Time: 7:42P
- End Time: 8:52P

## Agenda:
1. Financial status update
2. 501c3 application status update
3. Board Meeting Schedule for 2017
4. Board and officer election
5. Conflict of interest forms
6. Other Business

## Minutes:

### 1. Financial status update
Jon listed all the financial transactions from Oct 2015 - Sept 2016.

### 2. 501c3 application status update
IRS says "they have no record of it", even though we have the FedEx receipt. Plan is to re-submit in January, as we'll have another
Hour of Code event by then, so emphasize our educational & community focus.

We want to find a non-profit accountant: Max may know someone.

### 3. Board Meeting Schedule for 2017

Andy proposes that for the 2016-2017 board year, we meet quarterly, the first month of each quarter: October, January, April and July.
We can always cancel if there is nothing on the agenda.
He also proposes that we set an exact date no later than the 15th of the previous month. The board vote was unanimous: 5 in favor.

### 4. Board and officer election

Board & existing officer seats are set at the annual meeting.
Notes that committees, chairs and new officer positions can be created at any time (no by-law change required)
Terms for officers are until the next annual board meeting.

#### Officer positions

We have four officer positions:
- Secretary: keeps records, and ensures that everything is filed
- President: presides board meetings and general running of the board
- Treasurer: keeps records of funds
- General council: reviews all legal contracts, ensures board acts in accordances with the law

The vote was unanimous (5 in favor) for all officerships:
- Secretary: Celia
- President: Andy
- Treasurer: Jon
- General council: Ben

#### Board seats

The board sets financial policy, and has the ability to create committees/chairs/officerships.

James proposes that we expand the board by 2 seats, from 5 to 7 seats. This was not approved: 4 against, 1 in favor.

There were 5 nominations for the 5 board seats. Since the number of persons nominated was the same as number of open board seats, we did not count votes. The board members for the October 2016 - October 2017 will be:
- Jerry,
- Jon,
- Andy,
- Ben,
- Celia

### 5. Conflict of interest forms

Conflict of interest form needs to be completed by all board members, officers and chairs. These were completed, signed by
Jerry, Jon, Andy, Ben, Celia.

### 6. Other Business

#### How to spend more money
We have a surplus in the bank, and because we are a non-profit we cannot make a profit, so we need to figure out how to spend
this money. One idea was to award more scholarships. The board plans to brainstorm in more detail at January's meeting.

#### PyGotham videos
Sync issue: We still don't have videos from PyGotham published because there's a slight audio-sync issue with some videos.
We've told Carl to publish all of them, and of people complain about individual videos we will fix.

Missing videos issue: We have a handful of missing videos. UN has all videos from OpenCamps, of which we were one of several events, so for us to do through this will wait a lot of time. Our solution for this is to post and ask the UN for specific videos, as the speakers and video viewers help us discover which ones are missing.

#### Being a community sponsor for PyCon 2017

We've been a community sponsor for PyCon for the last 2 years, which cost nothing and required no work on our part.
But this year PyCon is requiring all community sponsors to have a booth, and to be present at the expo booth during all
session breaks/meals. They have a limit of 11 community sponsors/booths.

We need to decide if we want to be a community sponsor this year. Benefits include free conference admission
(but not transportation/lodging). This requires from us:
- 2-3 reps, to cover shift rotations during breaks/meals
- Booth stuff: table cloth, banner, stickets, etc. This will cost some money, but is within our budget.

Potential Reps Jon is 80% going. Andy is a strong maybe. Reps do not have to be a board member/officer.

#### Hour of Code (Sat, Dec 10)

90% sure we have the space at NYU. Our biggest need is getting volunteers/mentors, and getting the word out to the public.
We need 3 sponsors: we have 1 confirmed so far.

#### PyGotham

PyGotham 2016 was a part of the first annual OpenCamps at the UN. OpenCamps' 2016 goal was 5,000 attendees.
For 2017 it's 10,000: the idea for 2017 is to run for 3 weekends, with a tentpoll event each weekend.

Venue update: We will find out Thursday about OpenCamps (eg if/that it's happening again): the logisitical complication is that OpenCamps is
run by the UN's IT department, but they must have a delegate to sponsor and boom the room on their behalf. After Thursday,
we will need to take action either way: if OpenCamps is happening, then we can move forward with planning PyGotham at the UN;
if OpenCamps is not happening, then we will need to find a venue for PyGotham 2017 ASAP.

We should start meeting monthly, ideally starting early November, to start prepping for PyGotham. Sounds like Tuesdays during the
meetups is a good time for this.

Based on last year's PyGotham event at OpenCamps, we want to ensure the following for next year's planning:
- That we also book set up time
- That volunteers come day before

#### BAP website

We should have by-laws & spending & minutes on our site


text:
package eu.sarunas.atf.meta.sut.basictypes;

import eu.sarunas.projects.atf.metadata.generic.Type;

public class DateType extends Type
{
	public DateType()
    {
	    super("date", null);
	    setReferenceType(true);
    };

	public DateType(String nativeType)
    {
		this();

		this.nativeType = nativeType;
    };

    public String getNativeType()
    {
    	return this.nativeType;
    };

    private String nativeType = "";
};


text:
SrPresenter_DDraw::SrPresenter_DDraw():m_dd(NULL),
	m_frontSurface(NULL),
	m_drawSurface(NULL)
{

}

SrPresenter_DDraw::~SrPresenter_DDraw(void)
{
}

bool SrPresenter_DDraw::InitPresenter( HWND hWnd, uint32 width, uint32 height, uint32 bpp )
{
	// ´´½¨ddraw¶ÔÏó
	if (FAILED(DirectDrawCreateEx(NULL, (void **)&m_dd, IID_IDirectDraw7, NULL)))
		return 0;

	// ´°¿Úģʽ£¨ÉèÖÃЭ×÷¼¶±ð£©
	m_dd->SetCooperativeLevel(hWnd, DDSCL_NORMAL);

	//m_dd->SetDisplayMode( width, height, bpp, 0, 0 );

	DDSURFACEDESC2 ddDesc;
	memset( &ddDesc, 0, sizeof(ddDesc) );

	ddDesc.dwSize = sizeof(ddDesc);
	ddDesc.dwFlags = DDSD_CAPS;
	ddDesc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
	ddDesc.dwBackBufferCount = 1;

	if ( FAILED( m_dd->CreateSurface( &ddDesc, &m_frontSurface, NULL ) ) )
	{
		return 0;
	}

	ddDesc.dwFlags = DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT| DDSD_CAPS;
	ddDesc.dwWidth = width;
	ddDesc.dwHeight = height;
	ddDesc.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
	ddDesc.ddpfPixelFormat.dwFlags = DDPF_RGB;
	ddDesc.ddpfPixelFormat.dwRGBBitCount = 32;
	ddDesc.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;

	if ( FAILED( m_dd->CreateSurface( &ddDesc, &m_drawSurface, NULL ) ) )
	{
		return 0;
	}

	return true;
}

bool SrPresenter_DDraw::ShutdownPresenter()
{
	SAFE_RELEASE( m_drawSurface );
	SAFE_RELEASE( m_dd );

	return true;
}

void SrPresenter_DDraw::Swap()
{
	if (m_frontSurface)
	{
		m_frontSurface->Flip( NULL, 0 );
	}
}

uint8* SrPresenter_DDraw::Lock()
{
	DDSURFACEDESC2 ddDesc2;
	memset(&ddDesc2, 0, sizeof(ddDesc2));
	m_drawSurface->Lock(NULL, &ddDesc2, DDLOCK_WRITEONLY, NULL);

	return (uint8*)ddDesc2.lpSurface;
}

void SrPresenter_DDraw::UnLock()
{
	m_drawSurface->Unlock(NULL);
}


text: <button class="button alert" ng-click="handleDeleteAccountButtonClick()">Delete account</button>


text:
var webpack = require('webpack');
var PACKAGE = require('./package.json');
var banner = PACKAGE.name + ' - ' + PACKAGE.version + ' | ' +
  '(c) 2015, ' + new Date().getFullYear() + '  ' + PACKAGE.author + ' | ' +
  PACKAGE.license + ' | ' +
  PACKAGE.homepage;

module.exports = {
  entry: {
    'react-rating': './src/react-rating.js'
  },
  output: {
    // Output the bundled file.
    path: './lib',
    // Use the name specified in the entry key as name for the bundle file.
    filename: '[name].js',
    // Export as a Universal Module Definition library.
    library: 'ReactRating',
    libraryTarget: 'umd',
    // The modified bundle is served from memory at the relative path
    // specified in publicPath.
    // I use the same as the output path to use the same index.html either
    // served by webpack-dev-server or as a static file loaded in the browser.
    publicPath: '/lib'
  },
  module: {
    loaders: [
      {
        // Test for js or jsx files.
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loaders: [
          "babel-loader",
          "eslint-loader"
        ]
      }
    ]
  },
  externals: {
    // Don't bundle the 'react' npm package with the component.
    'react': {
      root: 'React',
      commonjs2: 'react',
      commonjs: 'react',
      amd: 'react'
    }
  },
  resolve: {
    // Include empty string '' to resolve files by their explicit extension
    // (e.g. require('./somefile.ext')).
    // Include '.js', '.jsx' to resolve files by these implicit extensions
    // (e.g. require('underscore')).
    extensions: ['', '.js', '.jsx']
  },
  plugins: [
    new webpack.DefinePlugin({
      // If BUILD_DEV is in process environment, return true. Otherwise,
      // return (void 0). BUILD_DEV=1 before webpack command will do the job.
      __DEV__: process.env.BUILD_DEV && 'true'
    }),
    new webpack.BannerPlugin(banner)
  ]
};


text:
""" This module provides the tools necessary to load filter definitions from
    plaintext files. For a description of the definition language, refer to
    README.md.
"""

__all__ = ["Tokenizer", "Parser", "Instantiator", "LoadFilter"]

from string import ascii_letters, digits
import filter

ALPHANUM = ascii_letters + digits
NUMERIC  = digits + "."

class Tokenizer (object):
    """ Splits a string into a list of tokens accepted by the language. The
        tokens are basically just literals (strings and floats) and symbols
        (parens, brackets, braces, comma, equal sign).
    """

    def tokenize(self, string):
        """ Returns the tokenized string
        """

        tokens  = []
        current = (None, [])

        for c in string:

            if c in NUMERIC and (current[0] != "identifier"):
                t = "numeric"
            elif c in ALPHANUM and (current[0] != "numeric"):
                t = "identifier"
            elif c in "[](){},=":
                t = c
            else:
                t = None

            if current[0] != t:
                if current[0] != None:
                    tokens.append((current[0], "".join(current[1])))
                current = (t, [])
            current[1].append(c)

        if current[0] != None:
            tokens.append((current[0], "".join(current[1])))

        return tokens

class Parser (object):
    """ Accepts tokens and parses them into a tree structure composed of Python
        objects (lists, dicts, and primitives).
    """

    class Chain (list):
        """ Represents a FilterChain
        """
        pass

    class Stack (list):
        """ Represents a FilterStack
        """
        pass

    class Object (dict):
        """ Represents a configuration object for a filter
        """
        pass

    class Filter (object):
        """ Represents a basic filter object, optionally with configuration
        """
        def __init__(self, name):
            self.name = name
            self.args = None

    def parseContainer(self, t, root):
        """ Parses a container type, i.e. a Chain or a Stack. The parameter 't'
            must be the corresponding type. The param 'root' is the root of the
            pre-processed tree.
        """

        c = t()

        funcs = {
            "chain": self.parseChain,
            "stack": self.parseStack,
            "object": self.parseObject
        }

        pending = None

        for node in root:
            if type(node) == tuple:
                if node[0] in funcs:
                    if node[0] == "object":
                        if pending is None or type(pending) != Parser.Filter:
                            raise RuntimeError("unexpected config object in container")
                        else:
                            pending.args = self.parseObject(node[2])
                    else:
                        if pending is None:
                            pending = funcs[node[0]](node[2])
                        else:
                            raise RuntimeError("missing expected ',' in container")
                else:
                    raise RuntimeError("unexpected %s found in container" % node[0])
            elif node  == ",":
                if pending is None:
                    raise RuntimeError("found unexpected ',' in container")
                else:
                    c.append(pending)
                    pending = None
            elif type(node) == str:
                pending = self.parseFilter(node)
            else:
                print("found unexpected item in container: %s" % str(node))

        if pending is not None:
            c.append(pending)

        return c

    def parseChain(self, root):
        """ Parses a Chain object using parseContainer
        """
        return self.parseContainer(Parser.Chain, root)

    def parseStack(self, root):
        """ Parses a Stack object using parseContainer
        """
        return self.parseContainer(Parser.Stack, root)

    def parseLiteral(self, root):
        """ Parses a literal -- if it can be converted to a float, it will be;
            otherwise it will be kept as a string
        """
        res = None
        try:
            res = float(root)
        except ValueError:
            res = root
        return res

    def parseList(self, root):
        """ Parses a list of literals
        """
        c = []

        pending = None

        for node in root:
            if node == ",":
                if pending is None:
                    raise RuntimeError("found unexpected ',' in container")
                else:
                    c.append(pending)
                    pending = None
            elif type(node) == str:
                if pending is None:
                    pending = self.parseLiteral(node)
                else:
                    raise RuntimeError("missing expected ',' in container")
            else:
                print("found unexpected item in container: %s" % str(node))

        if pending is not None:
            c.append(pending)

        return c

    def parseObject(self, root):
        """ Parses a configuration object
        """
        p = Parser.Object()

        key = None
        equ = False
        val = None

        for node in root:
            if type(node) == tuple:
                if node[0] == "stack":
                    if equ is False or val is not None:
                        raise RuntimeError("illegal placement of list value inside config object")
                    else:
                        val = self.parseList(node[2])
                else:
                    raise RuntimeError("found illegal container inside config object")
            elif node == "=":
                if key is None or equ is True or val is not None:
                    raise RuntimeError("illegal placement of '=' inside config object")
                else:
                    equ = True
            elif node == ",":
                if val is None:
                    raise RuntimeError("illegal placement of ',' inside config object")
                p[key] = val
                key, equ, val = None, False, None
            elif type(node) == str:
                if val is None:
                    if key is None:
                        key = node
                    elif equ is True and val is None:
                        val = self.parseLiteral(node)
                    else:
                        raise RuntimeError("illegal placement of key inside config object")
                else:
                    raise RuntimeError("illegal placement of key inside config object")
            else:
                raise RuntimeError("found unknown item %s of %s" % (str(node), type(node)))

        if val is not None:
            p[key] = val
        elif key is not None:
            raise RuntimeError("unfinished key in config object")

        return p

    def parseFilter(self, name):
        """ Parses a Filter object
        """
        return Parser.Filter(name)

    def parse(self, tokens):
        """ Parses a token stream. First, the stream is converted into an
            intermediate representation of nested lists of tuples. The other
            parse* methods above handle the conversion of this intermediate
            representation into the actual parsed tree.
        """

        root = (None, None, [])
        cur = root

        parens = {
            "(" : ("chain",  True),
            ")" : ("chain",  False),
            "[" : ("stack",  True),
            "]" : ("stack",  False),
            "{" : ("object", True),
            "}" : ("object", False)
        }

        funcs = {
            "chain": self.parseChain,
            "stack": self.parseStack,
            "identifier": self.parseFilter
        }

        for t, content in tokens:

            if t in parens:
                ptype, mode = parens[t]
                if mode:
                    next = (ptype, cur, [])
                    cur[2].append(next)
                    cur = next
                elif ptype == cur[0]:
                    cur = cur[1]
                else:
                    raise RuntimeError("mismatched brackets - %s and %s" % (ptype, cur[0]))
            else:
                cur[2].append(content)

        if cur is not root:
            raise RuntimeError("unclosed %s bracket somewhere" % (cur[0]))

        return self.parseChain(root[2])

class Instantiator (object):
    """ Instantiates an actual filter object based on the contents of a parse
        tree.
    """

    def instantiate(self, root):
        """ Recursively converts the parse tree (root) into an actual object
            from ppg.filter.
        """

        if isinstance(root, Parser.Chain):
            for i,v in enumerate(root):
                root[i] = self.instantiate(v)
            return filter.FilterChain(*root)

        elif isinstance(root, Parser.Stack):
            for i,v in enumerate(root):
                root[i] = self.instantiate(v)
            return filter.FilterStack(*root)

        elif isinstance(root, Parser.Object):
            for k, v in root.items():
                root[k] = self.instantiate(v)
            return root

        elif isinstance(root, Parser.Filter):
            if not root.name in filter.__all__:
                raise RuntimeError("unknown filter %s" % root.name)
            kwargs = root.args or {}
            return filter.__getattribute__(root.name)(**kwargs)

        else:
            return root

def LoadFilter(filterString):
    """ Convenience method for converting a string directly into a real, usable
        Filter object.
    """
    return Instantiator().instantiate(Parser().parse(Tokenizer().tokenize(filterString)))


text:
namespace {
const char kTestUMAClientName[] = "Test";
}  // namespace

class LeveldbScopedDatabaseUnitTest : public testing::Test {
 public:
  LeveldbScopedDatabaseUnitTest() {}
  ~LeveldbScopedDatabaseUnitTest() override {}

 protected:
  void SetUp() override {
    ASSERT_TRUE(database_dir_.CreateUniqueTempDir());
    db_ = new LeveldbScopedDatabase(kTestUMAClientName, database_dir_.path());
  }

  void TearDown() override {
    db_ = nullptr;
    base::DeleteFile(database_dir_.path(), true);
  }

  ValueStore::Status ReadAllValues(
      std::map<std::string, std::string>* values) const {
    values->clear();
    leveldb::ReadOptions read_options;
    read_options.verify_checksums = true;
    scoped_ptr<leveldb::Iterator> iterator;
    ValueStore::Status status = db_->CreateIterator(read_options, &iterator);
    if (!status.ok())
      return status;
    iterator->SeekToFirst();
    while (iterator->Valid()) {
      // The LeveldbProfileDatabase writes all values as JSON strings.
      // This method returns the encoded strings.
      (*values)[iterator->key().ToString()] = iterator->value().ToString();
      iterator->Next();
    }
    return db_->ToValueStoreError(iterator->status());
  }

  content::TestBrowserThreadBundle thread_bundle_;
  base::ScopedTempDir database_dir_;
  scoped_refptr<LeveldbScopedDatabase> db_;
};

TEST_F(LeveldbScopedDatabaseUnitTest, TestSplitKey) {
  std::string scope;
  std::string key;
  EXPECT_TRUE(LeveldbScopedDatabase::SplitKey("s:k", &scope, &key));
  EXPECT_EQ(scope, "s");
  EXPECT_EQ(key, "k");
  EXPECT_TRUE(LeveldbScopedDatabase::SplitKey("s:", &scope, &key));
  EXPECT_EQ(scope, "s");
  EXPECT_EQ(key, "");
  EXPECT_TRUE(LeveldbScopedDatabase::SplitKey("s:k:o", &scope, &key));
  EXPECT_EQ(scope, "s");
  EXPECT_EQ(key, "k:o");
  EXPECT_FALSE(LeveldbScopedDatabase::SplitKey("s-k", &scope, &key));
  EXPECT_FALSE(LeveldbScopedDatabase::SplitKey("", &scope, &key));
  EXPECT_FALSE(LeveldbScopedDatabase::SplitKey(":k", &scope, &key));
}

TEST_F(LeveldbScopedDatabaseUnitTest, TestCreateKey) {
  std::string scoped_key;

  EXPECT_TRUE(LeveldbScopedDatabase::CreateKey("scope", "key", &scoped_key));
  EXPECT_EQ("scope:key", scoped_key);
  EXPECT_TRUE(LeveldbScopedDatabase::CreateKey("scope", "", &scoped_key));
  EXPECT_EQ("scope:", scoped_key);
  EXPECT_TRUE(LeveldbScopedDatabase::CreateKey("scope", "key:o", &scoped_key));
  EXPECT_EQ("scope:key:o", scoped_key);

  EXPECT_FALSE(LeveldbScopedDatabase::CreateKey("", "key", &scoped_key));
  EXPECT_FALSE(
      LeveldbScopedDatabase::CreateKey("scope:withdelim", "key", &scoped_key));
}

TEST_F(LeveldbScopedDatabaseUnitTest, TestWrite) {
  std::map<std::string, std::string> db_values;
  EXPECT_TRUE(ReadAllValues(&db_values).ok());
  EXPECT_EQ(0u, db_values.size());

  base::DictionaryValue scope1_values;
  scope1_values.SetString("s1_key1", "s1_value1");
  scope1_values.SetString("s1_key2", "s1_value2");
  EXPECT_FALSE(db_->Write("", scope1_values).ok());
  EXPECT_TRUE(db_->Write("scope1", scope1_values).ok());

  base::DictionaryValue scope2_values;
  scope2_values.SetString("s2_key1", "s2_value1");
  scope2_values.SetString("s2_key2", "s2_value2");
  EXPECT_TRUE(db_->Write("scope2", scope2_values).ok());

  // Read all values using raw leveldb. Values are JSON strings.
  EXPECT_TRUE(ReadAllValues(&db_values).ok());
  EXPECT_EQ(4u, db_values.size());
  EXPECT_EQ("\"s1_value1\"", db_values["scope1:s1_key1"]);
  EXPECT_EQ("\"s1_value2\"", db_values["scope1:s1_key2"]);
  EXPECT_EQ("\"s2_value1\"", db_values["scope2:s2_key1"]);
  EXPECT_EQ("\"s2_value2\"", db_values["scope2:s2_key2"]);

  // Intentionally overwrite value (with a new value).
  base::DictionaryValue changed_scope2_values;
  changed_scope2_values.SetString("s2_key1", "s2_value1");
  changed_scope2_values.SetString("s2_key2", "s2_value3");
  EXPECT_TRUE(db_->Write("scope2", changed_scope2_values).ok());

  EXPECT_TRUE(ReadAllValues(&db_values).ok());
  EXPECT_EQ(4u, db_values.size());
  EXPECT_EQ("\"s1_value1\"", db_values["scope1:s1_key1"]);
  EXPECT_EQ("\"s1_value2\"", db_values["scope1:s1_key2"]);
  EXPECT_EQ("\"s2_value1\"", db_values["scope2:s2_key1"]);
  EXPECT_EQ("\"s2_value3\"", db_values["scope2:s2_key2"]);
}

TEST_F(LeveldbScopedDatabaseUnitTest, TestRead) {
  base::DictionaryValue scope1_values;
  scope1_values.SetString("s1_key1", "s1_value1");
  scope1_values.SetString("s1_key2", "s1_value2");
  EXPECT_TRUE(db_->Write("scope1", scope1_values).ok());

  base::DictionaryValue scope2_values;
  scope2_values.SetString("s2_key1", "s2_value1");
  scope2_values.SetString("s2_key2", "s2_value2");
  EXPECT_TRUE(db_->Write("scope2", scope2_values).ok());

  // And test an empty scope.
  EXPECT_FALSE(db_->Write("", scope2_values).ok());

  base::DictionaryValue read_s1_vals;
  EXPECT_FALSE(db_->Read("", &read_s1_vals).ok());
  EXPECT_TRUE(db_->Read("scope1", &read_s1_vals).ok());
  EXPECT_TRUE(scope1_values.Equals(&read_s1_vals));

  base::DictionaryValue read_s2_vals;
  EXPECT_TRUE(db_->Read("scope2", &read_s2_vals).ok());
  EXPECT_TRUE(scope2_values.Equals(&read_s2_vals));
}

TEST_F(LeveldbScopedDatabaseUnitTest, TestEmptyValue) {
  base::DictionaryValue values;
  values.SetString("s1_key1", "");
  EXPECT_TRUE(db_->Write("scope1", values).ok());

  scoped_ptr<base::Value> value;
  ASSERT_TRUE(db_->Read("scope1", "s1_key1", &value).ok());
  std::string str;
  EXPECT_TRUE(value->GetAsString(&str));
  EXPECT_EQ(str, "");
}

TEST_F(LeveldbScopedDatabaseUnitTest, TestValueContainingDelimiter) {
  base::DictionaryValue values;
  values.SetString("s1_key1", "with:delimiter");
  EXPECT_TRUE(db_->Write("scope1", values).ok());

  scoped_ptr<base::Value> value;
  ASSERT_TRUE(db_->Read("scope1", "s1_key1", &value).ok());
  std::string str;
  EXPECT_TRUE(value->GetAsString(&str));
  EXPECT_EQ(str, "with:delimiter");
}

TEST_F(LeveldbScopedDatabaseUnitTest, TestDeleteValues) {
  base::DictionaryValue scope1_values;
  scope1_values.SetString("s1_key1", "s1_value1");
  scope1_values.SetString("s1_key2", "s1_value2");
  EXPECT_TRUE(db_->Write("scope1", scope1_values).ok());

  base::DictionaryValue scope2_values;
  scope2_values.SetString("s2_key1", "s2_value1");
  scope2_values.SetString("s2_key2", "s2_value2");
  EXPECT_TRUE(db_->Write("scope2", scope2_values).ok());

  std::vector<std::string> keys;
  keys.push_back("s2_key1");
  keys.push_back("s2_key2");
  keys.push_back("s1_key1");
  EXPECT_TRUE(db_->DeleteValues("scope2", keys).ok());

  base::DictionaryValue read_s1_vals;
  EXPECT_TRUE(db_->Read("scope1", &read_s1_vals).ok());
  EXPECT_TRUE(scope1_values.Equals(&read_s1_vals));

  base::DictionaryValue read_s2_vals;
  EXPECT_TRUE(db_->Read("scope2", &read_s2_vals).ok());
  EXPECT_TRUE(read_s2_vals.empty());
}


text:
@implementation SamuraiCSSObject(NumberAutomatic)

- (BOOL)isAutomatic
{
	return NO;
}

@end

#pragma mark -

@implementation SamuraiCSSNumberAutomatic

+ (instancetype)parseValue:(KatanaValue *)value
{
	if ( NULL == value )
		return nil;

	SamuraiCSSNumberAutomatic * result = nil;

	if ( KATANA_VALUE_NUMBER == value->unit )
	{
		if ( INVALID_VALUE == value->fValue )
		{
			result = [[SamuraiCSSNumberAutomatic alloc] init];
		}
	}
	else if ( KATANA_VALUE_STRING == value->unit || KATANA_VALUE_IDENT == value->unit )
	{
		if ( 0 == strcasecmp( value->string, "auto" ) )
		{
			result = [[SamuraiCSSNumberAutomatic alloc] init];
		}
	}

	return result;
}

#pragma mark -

+ (instancetype)automatic
{
	return [[SamuraiCSSNumberAutomatic alloc] init];
}

#pragma mark -

- (id)init
{
	self = [super init];
	if ( self )
	{
		self.value = INVALID_VALUE;
		self.unit = nil;
	}
	return self;
}

- (void)dealloc
{
}

#pragma mark -

- (NSString *)description
{
	return @"Automatic()";
}

- (BOOL)isAutomatic
{
	return YES;
}

- (BOOL)isAbsolute
{
	return NO;
}

- (CGFloat)computeValue:(CGFloat)value
{
	return INVALID_VALUE;
}

@end

// ----------------------------------
// Unit test
// ----------------------------------

#pragma mark -

#if __SAMURAI_TESTING__

TEST_CASE( WebCore, CSSNumberAutomatic )

DESCRIBE( before )
{
}

DESCRIBE( after )
{
}

TEST_CASE_END

#endif	// #if __SAMURAI_TESTING__

#endif	// #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)

#import "_pragma_pop.h"


text:
import sys
import vtk

rgb = [[50, 1.0, 0.0, 0.0],
      [150, 0.0, 0.0, 1.0]]
opacity = [[0, 0.0],
           [150, 0.2]]

volume = vtk.vtkVolume()
volumeProperty = vtk.vtkVolumeProperty()

def keyPressed(caller, eventId):
  code = caller.GetKeyCode()
  delta = 1
  opdelta = 0.1
  if code == 'o': # o,p control first color value
    rgb[0][0] -= delta
    opacity[0][0] = rgb[0][0]
    print 'rgb[0]',rgb[0][0]
  elif code == 'p':
    rgb[0][0] += delta
    opacity[0][0] = rgb[0][0]
    print 'rgb[0]',rgb[0][0]
  elif code == 'a': # a,s control second color value
    rgb[1][0] -= delta
    opacity[1][0] = rgb[1][0]
    print 'rgb[1]',rgb[1][0]
  elif code == 's':
    rgb[1][0] += delta
    opacity[1][0] = rgb[1][0]
    print 'rgb[1]',rgb[1][0]
  elif code == 'r': # r,t control first opacity value
    opacity[0][1] -= opdelta
    print 'op[0]',opacity[0][1]
  elif code == 't':
    opacity[0][1] += opdelta
    print 'op[0]',opacity[0][1]
  elif code == 'f': # f,g control second opacity value
    opacity[1][1] -= opdelta
    print 'op[1]',opacity[1][1]
  elif code == 'g':
    opacity[1][1] += opdelta
    print 'op[1]',opacity[1][1]
  updateColorOpacity()

def updateColorOpacity():
  opacityFunction = vtk.vtkPiecewiseFunction()
  for op in opacity:
    opacityFunction.AddPoint(op[0], op[1])
  colorFunction = vtk.vtkColorTransferFunction()
  for c in rgb:
    colorFunction.AddRGBPoint(c[0], c[1], c[2], c[3])
  global volumeProperty
  volumeProperty.SetColor(colorFunction)
  volumeProperty.SetScalarOpacity(opacityFunction)
  global volume
  volume.Update()

def main(argv):
  if len(argv) < 2:
    print "usage:",argv[0]," data.nrrd data.cmap"
    exit(1)
  data_fn = argv[1]
  cmap_fn = argv[2]
  reader = vtk.vtkPNrrdReader()
  reader.SetFileName(data_fn)
  reader.Update()
  data = reader.GetOutput()
  # opacity function
  opacityFunction = vtk.vtkPiecewiseFunction()
  # color function
  colorFunction = vtk.vtkColorTransferFunction()
  cmap = open(cmap_fn, 'r')
  for line in cmap.readlines():
    parts = line.split()
    value = float(parts[0])
    r = float(parts[1])
    g = float(parts[2])
    b = float(parts[3])
    a = float(parts[4])
    opacityFunction.AddPoint(value, a)
    colorFunction.AddRGBPoint(value, r, g, b)
  # volume setup:
  #volumeProperty = vtk.vtkVolumeProperty()
  global volumeProperty
  volumeProperty.SetColor(colorFunction)
  volumeProperty.SetScalarOpacity(opacityFunction)
  # composite function (using ray tracing)
  compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
  volumeMapper = vtk.vtkVolumeRayCastMapper()
  volumeMapper.SetVolumeRayCastFunction(compositeFunction)
  volumeMapper.SetInput(data)
  # make the volume
  #volume = vtk.vtkVolume()
  global volume
  volume.SetMapper(volumeMapper)
  volume.SetProperty(volumeProperty)
  # renderer
  renderer = vtk.vtkRenderer()
  renderWin = vtk.vtkRenderWindow()
  renderWin.AddRenderer(renderer)
  renderInteractor = vtk.vtkRenderWindowInteractor()
  renderInteractor.SetRenderWindow(renderWin)
  renderInteractor.AddObserver( vtk.vtkCommand.KeyPressEvent, keyPressed )
  renderer.AddVolume(volume)
  renderer.SetBackground(0,0,0)
  renderWin.SetSize(400, 400)
  renderInteractor.Initialize()
  renderWin.Render()
  renderInteractor.Start()

if __name__ == '__main__':
  main(sys.argv)


text:
package com.seongil.mvplife.sample.ui.detailview.fragment;

import android.support.annotation.NonNull;

import com.seongil.mvplife.sample.domain.ClipDomain;
import com.seongil.mvplife.sample.ui.base.BaseView;

/**
 * @author seong-il, kim
 * @since 2017. 4. 30.
 */
public interface DetailClipItemView extends BaseView {

    void renderClipDomain(@NonNull ClipDomain domain);

    void notifyRemovedItem(@NonNull String itemKey);

    void notifyUpdatedFavoriteState(boolean isFavouritesItem);

    void notifyUpdatedClipItem(@NonNull final ClipDomain domain);

    void renderError(@NonNull Throwable t);

    void onBackPressed();

    void notifyInsertionSuccess(@NonNull ClipDomain domain);
}


text:
#include "stdafx.h"

#define new DEBUG_NEW

/////////////////////////////////////////////////////////////////////////////
// more User interface for COleClientItem

/////////////////////////////////////////////////////////////////////////////
// OLE Object Verb Menu helpers

// simple wrapper for OleUIAddVerbMenu API

void AFXAPI AfxOleSetEditMenu(COleClientItem* pItem, CMenu* pMenu,
	UINT iMenuItem, UINT nIDVerbMin, UINT nIDVerbMax, UINT nIDConvert)
{
	ASSERT_VALID(pMenu);
	if (pItem != NULL)
		ASSERT_VALID(pItem);

	HMENU hmenuDummy;
	if (!::OleUIAddVerbMenu(pItem != NULL ? pItem->m_lpObject : NULL,
		NULL, pMenu->GetSafeHmenu(), iMenuItem,
		nIDVerbMin, nIDVerbMax, nIDConvert != 0, nIDConvert, &hmenuDummy))
	{
		// turn gray popup into gray disabled normal menu item
		TCHAR szBuffer[256];
		pMenu->GetMenuString(iMenuItem, szBuffer, _countof(szBuffer), MF_BYPOSITION);
		pMenu->DeleteMenu(iMenuItem, MF_BYPOSITION);
		pMenu->InsertMenu(
			iMenuItem, MF_BYPOSITION|MF_STRING|MF_GRAYED|MF_DISABLED,
			nIDVerbMin, szBuffer);
	}
}

/////////////////////////////////////////////////////////////////////////////
// UI message handlers

void COleDocument::OnUpdatePasteMenu(CCmdUI* pCmdUI)
{
	pCmdUI->Enable(COleClientItem::CanPaste());
}

void COleDocument::OnUpdatePasteLinkMenu(CCmdUI* pCmdUI)
{
	pCmdUI->Enable(COleClientItem::CanPasteLink());
}

void COleDocument::OnUpdateEditLinksMenu(CCmdUI* pCmdUI)
{
	POSITION pos = GetStartPosition();
	COleClientItem* pItem;
	while ((pItem = GetNextClientItem(pos)) != NULL)
	{
		if (pItem->GetType() == OT_LINK)
		{
			// we found a link!
			pCmdUI->Enable(TRUE);
			return;
		}
	}
	pCmdUI->Enable(FALSE);      // no links today
}

void COleDocument::OnEditLinks()
{
	ASSERT_VALID(this);

	COleLinksDialog dlg(this, GetRoutingView_());
	dlg.DoModal();
}

void COleDocument::OnEditConvert()
{
	ASSERT_VALID(this);

	// get selected item
	COleClientItem* pItem = GetPrimarySelectedItem(GetRoutingView_());
	if (pItem == NULL)
		return;

	// do conversion dialog & convert for that item
	COleConvertDialog dlg(pItem);
	if (dlg.DoModal() == IDOK)
		dlg.DoConvert(pItem);
}

void COleDocument::OnUpdateEditChangeIcon(CCmdUI* pCmdUI)
{
	ASSERT_VALID(this);

	pCmdUI->Enable(GetPrimarySelectedItem(GetRoutingView_()) != NULL);
}

void COleDocument::OnEditChangeIcon()
{
	ASSERT_VALID(this);

	// get selected item
	COleClientItem* pItem = GetPrimarySelectedItem(GetRoutingView_());
	if (pItem == NULL)
		return;

	// do conversion dialog & convert for that item
	COleChangeIconDialog dlg(pItem);
	if (dlg.DoModal() == IDOK)
		dlg.DoChangeIcon(pItem);
}

void COleDocument::OnUpdateObjectVerbMenu(CCmdUI* pCmdUI)
{
	if (pCmdUI->m_pMenu == NULL || pCmdUI->m_pParentMenu == NULL)
	{
		// not a menu or is on sub-menu (don't recurse)
		pCmdUI->ContinueRouting();
		return;
	}

	// check for single selection
	COleClientItem* pItem = GetPrimarySelectedItem(GetRoutingView_());
	if (pItem == NULL || pItem->GetType() == OT_STATIC)
	{
		// no selection, or is 'static' item
		pCmdUI->Enable(FALSE);
	}

	// only include Convert... if there is a handler for ID_OLE_EDIT_CONVERT
	UINT nConvertID = ID_OLE_EDIT_CONVERT;
	AFX_CMDHANDLERINFO info;
	if (!OnCmdMsg(ID_OLE_EDIT_CONVERT, CN_COMMAND, NULL, &info))
		nConvertID = 0;

	// update the menu
	AfxOleSetEditMenu(GetPrimarySelectedItem(GetRoutingView_()),
		pCmdUI->m_pMenu, pCmdUI->m_nIndex,
		ID_OLE_VERB_FIRST, ID_OLE_VERB_LAST, nConvertID);
}

/////////////////////////////////////////////////////////////////////////////


text:
package mpphpapc

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"regexp"
	"strconv"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestGetPhpApcStatus_1(t *testing.T) {
	stub := `memory_segments:1
segment_size:134217592
total_memory:134217592
cached_files_count:392
cached_files_size:54266016
cache_hits:606130
cache_misses:392
cache_full_count:0
user_cache_vars_count:770
user_cache_vars_size:45835056
user_cache_hits:8334
user_cache_misses:10997
user_cache_full_count:0`

	stat := make(map[string]float64)

	err := parsePhpApcStatus(stub, &stat)
	assert.Nil(t, err)
	assert.EqualValues(t, stat["memory_segments"], 1)
	assert.EqualValues(t, stat["segment_size"], 134217592)
	assert.EqualValues(t, stat["total_memory"], 134217592)
	assert.EqualValues(t, stat["cached_files_count"], 392)
	assert.EqualValues(t, stat["cached_files_size"], 54266016)
	assert.EqualValues(t, stat["cache_hits"], 606130)
	assert.EqualValues(t, stat["cache_misses"], 392)
	assert.EqualValues(t, stat["cache_full_count"], 0)
	assert.EqualValues(t, stat["user_cache_vars_count"], 770)
	assert.EqualValues(t, stat["user_cache_vars_size"], 45835056)
	assert.EqualValues(t, stat["user_cache_hits"], 8334)
	assert.EqualValues(t, stat["user_cache_misses"], 10997)
	assert.EqualValues(t, stat["user_cache_full_count"], 0)
}

func TestGetPhpApcMetrics_1(t *testing.T) {
	stub := `memory_segments:1
segment_size:134217592
total_memory:134217592
cached_files_count:392
cached_files_size:54266016
cache_hits:606130
cache_misses:392
cache_full_count:0
user_cache_vars_count:770
user_cache_vars_size:45835056
user_cache_hits:8334
user_cache_misses:10997
user_cache_full_count:0`

	ts := httptest.NewServer(
		http.HandlerFunc(
			func(w http.ResponseWriter, r *http.Request) {
				fmt.Fprintln(w, stub)
			}))
	defer ts.Close()
	re, _ := regexp.Compile("([a-z]+)://([A-Za-z0-9.]+):([0-9]+)(.*)")
	found := re.FindStringSubmatch(ts.URL)
	assert.EqualValues(t, len(found), 5, fmt.Sprintf("Test stub uri format is changed. %s", ts.URL))

	host := found[2]
	port, _ := strconv.Atoi(found[3])
	path := found[4]

	ret, err := getPhpApcMetrics(host, uint16(port), path)
	assert.Nil(t, err)
	assert.NotNil(t, ret)
	assert.NotEmpty(t, ret)
	assert.Contains(t, ret, "memory_segments")
	assert.Contains(t, ret, "segment_size")
	assert.Contains(t, ret, "total_memory")
	assert.Contains(t, ret, "cached_files_count")
	assert.Contains(t, ret, "cached_files_size")
	assert.Contains(t, ret, "cache_hits")
	assert.Contains(t, ret, "cache_misses")
	assert.Contains(t, ret, "cache_full_count")
	assert.Contains(t, ret, "user_cache_vars_count")
	assert.Contains(t, ret, "user_cache_vars_size")
	assert.Contains(t, ret, "user_cache_hits")
	assert.Contains(t, ret, "user_cache_misses")
	assert.Contains(t, ret, "user_cache_full_count")
}


text:
Title: Installation sur Android

Nous recommandons l'utilisation de l'application
[*OpenVPN for Android* de Arne Schwabe][openvpn_android],

D'abord, téléchargez le fichier .ovpn dans [votre compte](/account/)
et enregistrez-le.

Ensuite, ouvrez *OpenVPN for Android* et importez le fichier téléchargé.
Vous pouvez éditer la configuration dans l'application pour définir votre
nom de compte et votre mot de passe, pour qu'ils ne vous soient pas demandé
à la connexion.

Vous pouvez maintenant vous connecter au VPN.

Si vous avez une question, n'hésitez pas à [nous contacter](/page/help).

[openvpn_android]: https://play.google.com/store/apps/details?id=de.blinkt.openvpn


text:
<?php

namespace DealNews\API\Client\Exception;

class InvalidOption extends \Exception {

}


text:
.edit-bar {
  padding-top: 10px;
  padding-bottom: 10px;
}

.dashboardHeader {
  text-align: center;
  height: 45px;
  padding-top: 10px;
  background-color: white;
}


text:
<?php

namespace Everon\Module\Auth\Interfaces;

interface FactoryWorker
{
    function buildAuthSession();
}


text:
"""
Created on Tue Jun 20 01:56:57 2017

@author: Muhammad Salek Ali
"""

# 1- Importing libraries for twitter and NLP
#--------------------------------------------
import numpy as np
import tweepy
from textblob import TextBlob

# 2- Authentication
#-------------------
consumerKey= 'enter_yours_here'
consumerSecret= 'enter_yours_here'

accessToken='enter_yours_here'
accessTokenSecret='enter_yours_here'

auth = tweepy.OAuthHandler(consumerKey, consumerSecret)
auth.set_access_token(accessToken, accessTokenSecret)

api = tweepy.API(auth)

# 3- Prepare query features
#---------------------------

teams = ['India', 'Pakistan']
hashtag = "PAKvsIND"

#Tweets to be collected:
fromDate = "2017-06-17"

# 4- Analysis Result Labels
#----------------------------
def senti(analysis, threshold = 0):
    if analysis.sentiment[0]>threshold:
        return 'Positive'
    elif analysis.sentiment[0]==threshold:
        return 'Neutral'
    else:
        return 'Negative'

# 5- Retrieve Tweets and Save Them
#----------------------------------

meanPolarities = dict()

for team in teams:
    teamPolarities = []

    #Save the tweets in csv
    with open('%s_tweets.csv' % team, 'w') as teamFile:
        teamFile.write('tweet,label,sentiment\n')
        maxQuery=5000
        for tweet in tweepy.Cursor(api.search,
                                   q=[hashtag,team],
                                   include_entities=True
                                   ).items():
            text = TextBlob(tweet.text)
            #Get the label corresponding to the sentiment analysis
            teamPolarities.append(text.sentiment[0])
            print (len(teamPolarities))
            print (senti(text))
            teamFile.write('%s,%s,%s\n' % (tweet.text.encode('utf8'), senti(text),str(text.sentiment[0])))
            if (len(teamPolarities)>=maxQuery):
                break
    #Save the mean for final results
    meanPolarities[team] = np.mean(teamPolarities)

# 6- Output a Result
#--------------------

print ('Mean Sentiment Polarities:')
print(meanPolarities)


text:
package com.outerspacecat.memcache;

import com.google.common.base.Preconditions;
import java.util.regex.Pattern;

/**
 * Defines utility methods for working with Memcache.
 *
 * @author Caleb Richardson
 */
public final class Memcache
{
  private final static Pattern KEY_PATTERN =
      Pattern.compile("[\\x21-\\x7E]{1,250}");

  private Memcache ()
  {
  }

  /**
   * Returns whether or not {@code key} is a valid Memcache key.
   * <p>
   * Memcache keys must be between 1 and 250 characters in length (inclusive),
   * and must contain only non-control, non-whitespace ASCII characters, which
   * corresponds to the range U+0021-U+007E (inclusive).
   *
   * @param key the key to check for validity. Must be non {@code null}.
   * @return whether or not {@code key} is a valid Memcache key
   */
  public static boolean isValidKey ( final CharSequence key )
  {
    Preconditions.checkNotNull(key, "key required");

    return KEY_PATTERN.matcher(key).matches();
  }
}


text:
/* eslint-disable func-names, space-before-function-paren, no-var, quotes, consistent-return, prefer-arrow-callback, comma-dangle, object-shorthand, no-new, max-len, no-multi-spaces, import/newline-after-import */
/* global bp */
/* global Cookies */
/* global Flash */
/* global ConfirmDangerModal */
/* global AwardsHandler */
/* global Aside */

function requireAll(context) { return context.keys().map(context); }

window.$ = window.jQuery = require('jquery');
require('jquery-ui/ui/autocomplete');
require('jquery-ui/ui/draggable');
require('jquery-ui/ui/effect-highlight');
require('jquery-ui/ui/sortable');
require('jquery-ujs');
require('vendor/jquery.endless-scroll');
require('vendor/jquery.highlight');
require('vendor/jquery.waitforimages');
require('vendor/jquery.caret');
require('vendor/jquery.atwho');
require('vendor/jquery.scrollTo');
window.Cookies = require('vendor/js.cookie');
require('./autosave');
require('bootstrap/js/affix');
require('bootstrap/js/alert');
require('bootstrap/js/button');
require('bootstrap/js/collapse');
require('bootstrap/js/dropdown');
require('bootstrap/js/modal');
require('bootstrap/js/scrollspy');
require('bootstrap/js/tab');
require('bootstrap/js/transition');
require('bootstrap/js/tooltip');
require('bootstrap/js/popover');
require('select2/select2.js');
window.Pikaday = require('pikaday');
window._ = require('underscore');
window.Dropzone = require('dropzone');
window.Sortable = require('vendor/Sortable');
require('mousetrap');
require('mousetrap/plugins/pause/mousetrap-pause');
require('./shortcuts');
require('./shortcuts_navigation');
require('./shortcuts_dashboard_navigation');
require('./shortcuts_issuable');
require('./shortcuts_network');
require('vendor/jquery.nicescroll');
requireAll(require.context('./behaviors',  false, /^\.\/.*\.(js|es6)$/));
requireAll(require.context('./blob',       false, /^\.\/.*\.(js|es6)$/));
requireAll(require.context('./templates',  false, /^\.\/.*\.(js|es6)$/));
requireAll(require.context('./commit',     false, /^\.\/.*\.(js|es6)$/));
requireAll(require.context('./extensions', false, /^\.\/.*\.(js|es6)$/));
requireAll(require.context('./lib/utils',  false, /^\.\/.*\.(js|es6)$/));
requireAll(require.context('./u2f',        false, /^\.\/.*\.(js|es6)$/));
requireAll(require.context('./droplab',    false, /^\.\/.*\.(js|es6)$/));
requireAll(require.context('.',            false, /^\.\/(?!application\.js).*\.(js|es6)$/));
require('vendor/fuzzaldrin-plus');
window.ES6Promise = require('vendor/es6-promise.auto');
window.ES6Promise.polyfill();

(function () {
  document.addEventListener('beforeunload', function () {
    // Unbind scroll events
    $(document).off('scroll');
    // Close any open tooltips
    $('.has-tooltip, [data-toggle="tooltip"]').tooltip('destroy');
  });

  window.addEventListener('hashchange', gl.utils.handleLocationHash);
  window.addEventListener('load', function onLoad() {
    window.removeEventListener('load', onLoad, false);
    gl.utils.handleLocationHash();
  }, false);

  $(function () {
    var $body = $('body');
    var $document = $(document);
    var $window = $(window);
    var $sidebarGutterToggle = $('.js-sidebar-toggle');
    var $flash = $('.flash-container');
    var bootstrapBreakpoint = bp.getBreakpointSize();
    var fitSidebarForSize;

    // Set the default path for all cookies to GitLab's root directory
    Cookies.defaults.path = gon.relative_url_root || '/';

    // `hashchange` is not triggered when link target is already in window.location
    $body.on('click', 'a[href^="#"]', function() {
      var href = this.getAttribute('href');
      if (href.substr(1) === gl.utils.getLocationHash()) {
        setTimeout(gl.utils.handleLocationHash, 1);
      }
    });

    // prevent default action for disabled buttons
    $('.btn').click(function(e) {
      if ($(this).hasClass('disabled')) {
        e.preventDefault();
        e.stopImmediatePropagation();
        return false;
      }
    });

    $('.nav-sidebar').niceScroll({
      cursoropacitymax: '0.4',
      cursorcolor: '#FFF',
      cursorborder: '1px solid #FFF'
    });
    $('.js-select-on-focus').on('focusin', function () {
      return $(this).select().one('mouseup', function (e) {
        return e.preventDefault();
      });
    // Click a .js-select-on-focus field, select the contents
    // Prevent a mouseup event from deselecting the input
    });
    $('.remove-row').bind('ajax:success', function () {
      $(this).tooltip('destroy')
        .closest('li')
        .fadeOut();
    });
    $('.js-remove-tr').bind('ajax:before', function () {
      return $(this).hide();
    });
    $('.js-remove-tr').bind('ajax:success', function () {
      return $(this).closest('tr').fadeOut();
    });
    $('select.select2').select2({
      width: 'resolve',
      // Initialize select2 selects
      dropdownAutoWidth: true
    });
    $('.js-select2').bind('select2-close', function () {
      return setTimeout((function () {
        $('.select2-container-active').removeClass('select2-container-active');
        return $(':focus').blur();
      }), 1);
    // Close select2 on escape
    });
    // Initialize tooltips
    $.fn.tooltip.Constructor.DEFAULTS.trigger = 'hover';
    $body.tooltip({
      selector: '.has-tooltip, [data-toggle="tooltip"]',
      placement: function (_, el) {
        return $(el).data('placement') || 'bottom';
      }
    });
    $('.trigger-submit').on('change', function () {
      return $(this).parents('form').submit();
    // Form submitter
    });
    gl.utils.localTimeAgo($('abbr.timeago, .js-timeago'), true);
    // Flash
    if ($flash.length > 0) {
      $flash.click(function () {
        return $(this).fadeOut();
      });
      $flash.show();
    }
    // Disable form buttons while a form is submitting
    $body.on('ajax:complete, ajax:beforeSend, submit', 'form', function (e) {
      var buttons;
      buttons = $('[type="submit"]', this);
      switch (e.type) {
        case 'ajax:beforeSend':
        case 'submit':
          return buttons.disable();
        default:
          return buttons.enable();
      }
    });
    $(document).ajaxError(function (e, xhrObj) {
      var ref = xhrObj.status;
      if (xhrObj.status === 401) {
        return new Flash('You need to be logged in.', 'alert');
      } else if (ref === 404 || ref === 500) {
        return new Flash('Something went wrong on our end.', 'alert');
      }
    });
    $('.account-box').hover(function () {
      // Show/Hide the profile menu when hovering the account box
      return $(this).toggleClass('hover');
    });
    $document.on('click', '.diff-content .js-show-suppressed-diff', function () {
      var $container;
      $container = $(this).parent();
      $container.next('table').show();
      return $container.remove();
    // Commit show suppressed diff
    });
    $('.navbar-toggle').on('click', function () {
      $('.header-content .title').toggle();
      $('.header-content .header-logo').toggle();
      $('.header-content .navbar-collapse').toggle();
      return $('.navbar-toggle').toggleClass('active');
    });
    // Show/hide comments on diff
    $body.on('click', '.js-toggle-diff-comments', function (e) {
      var $this = $(this);
      var notesHolders = $this.closest('.diff-file').find('.notes_holder');
      $this.toggleClass('active');
      if ($this.hasClass('active')) {
        notesHolders.show().find('.hide').show();
      } else {
        notesHolders.hide();
      }
      $this.trigger('blur');
      return e.preventDefault();
    });
    $document.off('click', '.js-confirm-danger');
    $document.on('click', '.js-confirm-danger', function (e) {
      var btn = $(e.target);
      var form = btn.closest('form');
      var text = btn.data('confirm-danger-message');
      e.preventDefault();
      return new ConfirmDangerModal(form, text);
    });
    $('input[type="search"]').each(function () {
      var $this = $(this);
      $this.attr('value', $this.val());
    });
    $document.off('keyup', 'input[type="search"]').on('keyup', 'input[type="search"]', function () {
      var $this;
      $this = $(this);
      return $this.attr('value', $this.val());
    });
    $document.off('breakpoint:change').on('breakpoint:change', function (e, breakpoint) {
      var $gutterIcon;
      if (breakpoint === 'sm' || breakpoint === 'xs') {
        $gutterIcon = $sidebarGutterToggle.find('i');
        if ($gutterIcon.hasClass('fa-angle-double-right')) {
          return $sidebarGutterToggle.trigger('click');
        }
      }
    });
    fitSidebarForSize = function () {
      var oldBootstrapBreakpoint;
      oldBootstrapBreakpoint = bootstrapBreakpoint;
      bootstrapBreakpoint = bp.getBreakpointSize();
      if (bootstrapBreakpoint !== oldBootstrapBreakpoint) {
        return $document.trigger('breakpoint:change', [bootstrapBreakpoint]);
      }
    };
    $window.off('resize.app').on('resize.app', function () {
      return fitSidebarForSize();
    });
    gl.awardsHandler = new AwardsHandler();
    new Aside();
    // bind sidebar events
    new gl.Sidebar();

    gl.utils.initTimeagoTimeout();
  });
}).call(this);