text:
'use strict';

/**
 * @class
 * Initializes a new instance of the PasswordCredentialListResult class.
 * @constructor
 * PasswordCredential list operation result.
 *
 */
class PasswordCredentialListResult extends Array {
  constructor() {
    super();
  }

  /**
   * Defines the metadata of PasswordCredentialListResult
   *
   * @returns {object} metadata of PasswordCredentialListResult
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'PasswordCredentialListResult',
      type: {
        name: 'Composite',
        className: 'PasswordCredentialListResult',
        modelProperties: {
          value: {
            required: false,
            serializedName: '',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'PasswordCredentialElementType',
                  type: {
                    name: 'Composite',
                    className: 'PasswordCredential'
                  }
              }
            }
          }
        }
      }
    };
  }
}

module.exports = PasswordCredentialListResult;


text:
import os
import unittest

try:
    from subprocess import check_output
except ImportError:
    from subprocess import Popen, PIPE, CalledProcessError

    def check_output(*popenargs, **kwargs):
        """Lifted from python 2.7 stdlib."""
        if 'stdout' in kwargs:
            raise ValueError('stdout argument not allowed, it will be '
                             'overridden.')
        process = Popen(stdout=PIPE, *popenargs, **kwargs)
        output, unused_err = process.communicate()
        retcode = process.poll()
        if retcode:
            cmd = kwargs.get("args")
            if cmd is None:
                cmd = popenargs[0]
            raise CalledProcessError(retcode, cmd, output=output)
        return output

os.environ['LC_ALL'] = 'eo'
os.environ['SWIFT_LOCALEDIR'] = os.path.dirname(__file__)
from swift import gettext_ as _

class TestTranslations(unittest.TestCase):

    def test_translations(self):
        translated_message = check_output(['python', __file__])
        self.assertEquals(translated_message, 'testo mesaĝon\n')

if __name__ == "__main__":
    print _('test message')

redpajama_set_name: RedPajamaGithub


text:
package org.hisp.dhis.dxf2.metadata.feedback;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.google.common.base.MoreObjects;
import org.hisp.dhis.common.DxfNamespaces;
import org.hisp.dhis.feedback.Status;
import org.hisp.dhis.dxf2.metadata.MetadataImportParams;
import org.hisp.dhis.feedback.ErrorReport;
import org.hisp.dhis.feedback.Stats;
import org.hisp.dhis.feedback.TypeReport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Morten Olav Hansen <mortenoh@gmail.com>
 */
@JacksonXmlRootElement( localName = "importReport", namespace = DxfNamespaces.DXF_2_0 )
public class ImportReport
{
    private MetadataImportParams importParams;

    private Status status = Status.OK;

    private Map<Class<?>, TypeReport> typeReportMap = new HashMap<>();

    public ImportReport()
    {
    }

    //-----------------------------------------------------------------------------------
    // Utility Methods
    //-----------------------------------------------------------------------------------

    public TypeReport addTypeReport( TypeReport typeReport )
    {
        if ( !typeReportMap.containsKey( typeReport.getKlass() ) ) typeReportMap.put( typeReport.getKlass(), new TypeReport( typeReport.getKlass() ) );
        typeReportMap.get( typeReport.getKlass() ).merge( typeReport );

        return typeReport;
    }

    public void addTypeReports( List<TypeReport> typeReports )
    {
        typeReports.forEach( this::addTypeReport );
    }

    public void addTypeReports( Map<Class<?>, TypeReport> typeReportMap )
    {
        typeReportMap.values().forEach( this::addTypeReport );
    }

    public List<ErrorReport> getErrorReports()
    {
        List<ErrorReport> errorReports = new ArrayList<>();
        typeReportMap.values().forEach( typeReport -> errorReports.addAll( typeReport.getErrorReports() ) );

        return errorReports;
    }

    //-----------------------------------------------------------------------------------
    // Getters and Setters
    //-----------------------------------------------------------------------------------

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public MetadataImportParams getImportParams()
    {
        return importParams;
    }

    public void setImportParams( MetadataImportParams importParams )
    {
        this.importParams = importParams;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public Status getStatus()
    {
        return status;
    }

    public void setStatus( Status status )
    {
        this.status = status;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public Stats getStats()
    {
        Stats stats = new Stats();
        typeReportMap.values().forEach( typeReport -> stats.merge( typeReport.getStats() ) );

        return stats;
    }

    @JsonProperty
    @JacksonXmlElementWrapper( localName = "typeReports", namespace = DxfNamespaces.DXF_2_0 )
    @JacksonXmlProperty( localName = "typeReport", namespace = DxfNamespaces.DXF_2_0 )
    public List<TypeReport> getTypeReports()
    {
        return new ArrayList<>( typeReportMap.values() );
    }

    public Map<Class<?>, TypeReport> getTypeReportMap()
    {
        return typeReportMap;
    }

    @Override
    public String toString()
    {
        return MoreObjects.toStringHelper( this )
            .add( "stats", getStats() )
            .add( "typeReports", getTypeReports() )
            .toString();
    }
}


text:
com.wordpress.javaenterprise7
=============================

Various example applications featuring functionality in Java EE 7


text:
package org.camunda.bpm.extension.reactor.projectreactor.io.codec;

import org.camunda.bpm.extension.reactor.projectreactor.io.buffer.Buffer;

/**
 * A selection of standard codecs.
 *
 * @author Jon Brisbin
 */
public abstract class StandardCodecs {

  private StandardCodecs() {
  }

  public static final Codec<Buffer, Buffer, Buffer> PASS_THROUGH_CODEC = new PassThroughCodec<Buffer>();

  /**
   * A {@link ByteArrayCodec}.
   */
  public static final ByteArrayCodec BYTE_ARRAY_CODEC = new ByteArrayCodec();

  /**
   * A {@link StringCodec}.
   */
  public static final StringCodec STRING_CODEC = new StringCodec();

  /**
   * A {@link StringCodec}.
   */
  public static final StringCodec DELIMITED_STRING_CODEC = new StringCodec(Codec.DEFAULT_DELIMITER);

  /**
   * A {@link DelimitedCodec} that works with {@code String} data delimited by a line-feed ({@code '\n'}) character
   */
  public static final DelimitedCodec<String, String> LINE_FEED_CODEC = new DelimitedCodec<String,
    String>(STRING_CODEC);

}


text:
<?php
/** Menu block **/

if(!class_exists('header_breaking')) {
	class header_breaking extends header_builder {

		//set and create block
		function __construct() {
			$block_options = array(
				'image' => 'breaking.png',
				'class' => 'hbSprite-breakingNews icon-newspaper',
				'name' => 'Breaking News',
				'imagedesc' => '',
				'desc' => 'This is an alert Block to show any warning, alert or confirmation message to the user'
			);
			//create the block
			parent::__construct('header_breaking', $block_options);
		}

		function form($instance,$header_name) {
			$defaults = array(
				'title' => '',
				'type' => '',
				'text' => '',
				'categories' => -1,
				'posts_number' => 5
			);
			$options_categories = array();
			$options_categories_obj = get_categories();
			foreach ($options_categories_obj as $category) {
				$options_categories[$category->cat_ID] = $category->cat_name;
			}
			$instance = wp_parse_args($instance, $defaults);
			extract($instance);
			?>

						Title

				<?php echo creiden_hb_input($header_name,$id_base,$order, 'title', $title); ?>

						What to Show

					Select the content of the Breaking Area

				<?php echo creiden_hb_select($header_name,$id_base,$order,array('Latest Posts','Custom News'),'type',$type); ?>

						Number Of Posts

				<?php echo creiden_hb_input($header_name,$id_base,$order, 'posts_number', $posts_number); ?>

						Breaking Area Selected Categories

					Select the categories you want

				<?php echo creiden_hb_select_multiple($header_name,$id_base,$order,$options_categories,'categories',$categories,'multiple'); ?>

						Custom Text

					Put the sentences you want to show in the Breaking Area here separated by commas ","

				<?php echo creiden_hb_input($header_name,$id_base,$order, 'text', $text); ?>

		<?php
		}

		function block($instance) {
			extract($instance);
			if($type) {
				$custom_breaking = explode(',', $text);
				?>

<?php echo esc_html($title) ?>

							<?php foreach ($custom_breaking as $key => $value) {
								?>

<?php echo esc_html($value); ?>

					    	<?php } ?>

			<?php
			} else {
				$breakNumPosts = $posts_number ? $posts_number : 5;
				$cat_ids = $categories ? implode(',', $categories) : -1 ;
				$args = array(
					'showposts'  => $breakNumPosts,
					'category' => $cat_ids,
					'order'      => 'DESC',
					'suppress_filters' => false
				);
				$ticker_posts = get_posts( $args );
				if ($ticker_posts) {
			?>

<?php echo esc_html($title) ?>

						<?php foreach ($ticker_posts as $key => $value) {
							?>

<a href="<?php echo esc_url($value->guid) ?>">
<?php echo esc_html($value->post_title); ?>

				    	<?php } ?>

		<?php
			}

			}
		}

	}
}


text:
'use strict';

// Setting up route
angular.module('core').config(['$stateProvider', '$urlRouterProvider',
  function($stateProvider, $urlRouterProvider) {
    // Redirect to 404 when route not found
    $urlRouterProvider.otherwise(function($injector, $location) {
      $injector.get('$state').transitionTo('not-found', null, {
        location: false
      });
    });
    // Home state routing
    $stateProvider
      .state('home', {
        url: '/',
        templateUrl: 'modules/core/client/views/home.client.view.html'
      })
      .state('quiz', {
        url: '/{courseName:.+}/quiz',
        templateUrl: 'modules/quiz/client/views/quizTemplate.client.view.html'
      })
      .state('quiz.results', {
        url: '/results',
        templateUrl: 'modules/quiz/client/views/quizResults.client.view.html',
        params: {
          correctScore: null,
          numQuestion: null,
          category: null,
        }
      })
      .state('resources', {
        url: '/{courseName:.+}/resources',
        templateUrl: 'modules/core/client/views/resources.client.view.html'
      })
      .state('question_upload', {
        url: '/question_upload',
        templateUrl: 'modules/quiz/client/views/quizUpload.client.view.html'
      })
      .state('studentprofile', {
        url: '/student/{userName:.+}',
        templateUrl: 'modules/core/client/views/profile.client.view.html'
      })
      .state('teacherprofile', {
        url: '/teacher/{userName:.+}',
        templateUrl: 'modules/core/client/views/teacherprofile.client.view.html'
      })
      .state('userData', {
        url: '/data/users',
        templateUrl: 'modules/core/client/views/data.users.client.view.html'
      })
      .state('questionData', {
        url: '/data/questions',
        templateUrl: 'modules/core/client/views/data.questions.client.view.html'
      })
      .state('about', {
        url: '/about',
        templateUrl: 'modules/core/client/views/about.client.view.html'
      })
      .state('contact', {
        url: '/contact',
        templateUrl: 'modules/core/client/views/contact.client.view.html'
      })
      .state('bad-request', {
        url: '/bad-request',
        templateUrl: 'modules/core/client/views/400.client.view.html',
        data: {
          ignoreState: true
        }
      })
      .state('not-found', {
        url: '/not-found',
        templateUrl: 'modules/core/client/views/404.client.view.html',
        data: {
          ignoreState: true
        }
      })
      .state('forbidden', {
        url: '/forbidden',
        templateUrl: 'modules/core/client/views/403.client.view.html',
        data: {
          ignoreState: true
        }
      });
  }
]);


text:
require 'bundler/setup'
require 'serverspec'
require 'docker'

describe 'Dockerfile' do
  image = Docker::Image.build_from_dir('.')

  set :os, family: :debian
  set :backend, :docker
  set :docker_image, image.id

  it 'installs Ubuntu 14.04' do
    expect(os_version).to include('Ubuntu 14.04')
  end

  %w(ruby2.3 ruby2.3-dev nodejs).each do |package|
    describe package(package) do
      it { should be_installed }
    end
  end

  def os_version
    command('lsb_release -a').stdout
  end
end


text:
/* global jest, describe, it, expect, beforeEach, jasmine */

jest.mock('../ImageLoadActionHandler', () => jest.fn());

import ImageLoadActionHandler from '../ImageLoadActionHandler';
import IMAGE_STATUS from '../ImageLoadStatus';
import IMAGE_LOAD from '../ImageLoadActionTypes';
import { loadImage } from '../ImageLoadActions';

describe('loadImage', () => {
  let dispatch = null;
  let getState = null;
  const options = { minRetry: 2, maxRetry: 4 };

  beforeEach(() => {
    dispatch = jest.fn();
    getState = jest.fn(() => ({
      assetAdmin: {
        imageLoad: {
          files: [{
            url: 'http://www.mysite.com/file.jpg',
            state: IMAGE_STATUS.FAILED,
          }],
        },
      },
    }));
  });

  it('should skip missing images', () => {
    const result = loadImage('', {})(dispatch, getState);
    expect(result).toBe(null);
    expect(dispatch).not.toBeCalled();
    expect(getState).toHaveBeenCalledTimes(0);
  });

  it('should skip processed files', () => {
    const result = loadImage('http://www.mysite.com/file.jpg', options)(dispatch, getState);
    expect(result).toBe(null);
    expect(dispatch).not.toBeCalled();
    expect(getState).toHaveBeenCalledTimes(1);
  });

  it('should process new files', () => {
    class MockHandler {
      constructor(opts) {
        expect(opts.minRetry).toBe(2);
        expect(opts.maxRetry).toBe(4);
        this.opts = opts;
      }
      loadImage(url) {
        expect(url).toBe('http://www.mysite.com/another.jpg');
        return Promise.resolve(this.opts);
      }
    }

    ImageLoadActionHandler.mockImplementation((opts) => new MockHandler(opts));

    const url = 'http://www.mysite.com/another.jpg';
    const result = loadImage(url, options)(dispatch, getState);
    expect(result).toBeInstanceOf(Promise);

    // Assert result of calls after promise is resolved
    return result.then((opts) => {
      expect(dispatch).not.toBeCalled();

      opts.onReset(url);
      expect(dispatch.mock.calls[0][0]).toEqual({
        type: IMAGE_LOAD.RESET,
        payload: { url },
      });

      const status = 'MY_MOCK_STATUS';
      opts.onStatusChange(url, status);
      expect(dispatch.mock.calls[1][0]).toEqual({
        type: IMAGE_LOAD.SET_STATUS,
        payload: { status, url },
      });

      expect(getState).toHaveBeenCalledTimes(1);
    });
  });
});


text:
package dlp.snippets;

// [START dlp_deidentify_table_row_suppress]

import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.ContentItem;
import com.google.privacy.dlp.v2.DeidentifyConfig;
import com.google.privacy.dlp.v2.DeidentifyContentRequest;
import com.google.privacy.dlp.v2.DeidentifyContentResponse;
import com.google.privacy.dlp.v2.FieldId;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.RecordCondition;
import com.google.privacy.dlp.v2.RecordCondition.Condition;
import com.google.privacy.dlp.v2.RecordCondition.Conditions;
import com.google.privacy.dlp.v2.RecordCondition.Expressions;
import com.google.privacy.dlp.v2.RecordSuppression;
import com.google.privacy.dlp.v2.RecordTransformations;
import com.google.privacy.dlp.v2.RelationalOperator;
import com.google.privacy.dlp.v2.Table;
import com.google.privacy.dlp.v2.Table.Row;
import com.google.privacy.dlp.v2.Value;
import java.io.IOException;

public class DeIdentifyTableRowSuppress {

  public static void deIdentifyTableRowSuppress() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    Table tableToDeIdentify =
        Table.newBuilder()
            .addHeaders(FieldId.newBuilder().setName("AGE").build())
            .addHeaders(FieldId.newBuilder().setName("PATIENT").build())
            .addHeaders(FieldId.newBuilder().setName("HAPPINESS SCORE").build())
            .addRows(
                Row.newBuilder()
                    .addValues(Value.newBuilder().setStringValue("101").build())
                    .addValues(Value.newBuilder().setStringValue("Charles Dickens").build())
                    .addValues(Value.newBuilder().setStringValue("95").build())
                    .build())
            .addRows(
                Row.newBuilder()
                    .addValues(Value.newBuilder().setStringValue("22").build())
                    .addValues(Value.newBuilder().setStringValue("Jane Austen").build())
                    .addValues(Value.newBuilder().setStringValue("21").build())
                    .build())
            .addRows(
                Row.newBuilder()
                    .addValues(Value.newBuilder().setStringValue("55").build())
                    .addValues(Value.newBuilder().setStringValue("Mark Twain").build())
                    .addValues(Value.newBuilder().setStringValue("75").build())
                    .build())
            .build();

    deIdentifyTableRowSuppress(projectId, tableToDeIdentify);
  }

  public static Table deIdentifyTableRowSuppress(String projectId, Table tableToDeIdentify)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlp = DlpServiceClient.create()) {
      // Specify what content you want the service to de-identify.
      ContentItem contentItem = ContentItem.newBuilder().setTable(tableToDeIdentify).build();

      // Specify when the content should be de-identified.
      Condition condition =
          Condition.newBuilder()
              .setField(FieldId.newBuilder().setName("AGE").build())
              .setOperator(RelationalOperator.GREATER_THAN)
              .setValue(Value.newBuilder().setIntegerValue(89).build())
              .build();
      // Apply the condition to record suppression.
      RecordSuppression recordSuppressions =
          RecordSuppression.newBuilder()
              .setCondition(
                  RecordCondition.newBuilder()
                      .setExpressions(
                          Expressions.newBuilder()
                              .setConditions(
                                  Conditions.newBuilder().addConditions(condition).build())
                              .build())
                      .build())
              .build();
      // Use record suppression as the only transformation
      RecordTransformations transformations =
          RecordTransformations.newBuilder().addRecordSuppressions(recordSuppressions).build();

      DeidentifyConfig deidentifyConfig =
          DeidentifyConfig.newBuilder().setRecordTransformations(transformations).build();

      // Combine configurations into a request for the service.
      DeidentifyContentRequest request =
          DeidentifyContentRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setItem(contentItem)
              .setDeidentifyConfig(deidentifyConfig)
              .build();

      // Send the request and receive response from the service.
      DeidentifyContentResponse response = dlp.deidentifyContent(request);

      // Print the results.
      System.out.println("Table after de-identification: " + response.getItem().getTable());

      return response.getItem().getTable();
    }
  }
}
// [END dlp_deidentify_table_row_suppress]


text:
"""Tests for `tf.data.experimental.SqlDataset`."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.python.data.experimental.kernel_tests import sql_dataset_test_base
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.platform import test

class SqlDatasetTest(sql_dataset_test_base.SqlDatasetTestBase):

  # Test that SqlDataset can read from a database table.
  def testReadResultSet(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.string,
                                                dtypes.string), 2)
    with self.cached_session() as sess:
      for _ in range(2):  # Run twice to verify statelessness of db operations.
        sess.run(
            init_op,
            feed_dict={
                self.query: "SELECT first_name, last_name, motto FROM students "
                            "ORDER BY first_name DESC"
            })
        for _ in range(2):  # Dataset is repeated. See setUp.
          self.assertEqual((b"John", b"Doe", b"Hi!"), sess.run(get_next))
          self.assertEqual((b"Jane", b"Moe", b"Hi again!"), sess.run(get_next))
        with self.assertRaises(errors.OutOfRangeError):
          sess.run(get_next)

  # Test that SqlDataset works on a join query.
  def testReadResultSetJoinQuery(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.string,
                                                dtypes.string))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query:
                  "SELECT students.first_name, state, motto FROM students "
                  "INNER JOIN people "
                  "ON students.first_name = people.first_name "
                  "AND students.last_name = people.last_name"
          })
      self.assertEqual((b"John", b"California", b"Hi!"), sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  # Test that SqlDataset can read a database entry with a null-terminator
  # in the middle of the text and place the entry in a `string` tensor.
  def testReadResultSetNullTerminator(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.string,
                                                dtypes.string))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query:
                  "SELECT first_name, last_name, favorite_nonsense_word "
                  "FROM students ORDER BY first_name DESC"
          })
      self.assertEqual((b"John", b"Doe", b"n\0nsense"), sess.run(get_next))
      self.assertEqual((b"Jane", b"Moe", b"nonsense\0"), sess.run(get_next))
    with self.assertRaises(errors.OutOfRangeError):
      sess.run(get_next)

  # Test that SqlDataset works when used on two different queries.
  # Because the output types of the dataset must be determined at graph-creation
  # time, the two queries must have the same number and types of columns.
  def testReadResultSetReuseSqlDataset(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.string,
                                                dtypes.string))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query: "SELECT first_name, last_name, motto FROM students "
                          "ORDER BY first_name DESC"
          })
      self.assertEqual((b"John", b"Doe", b"Hi!"), sess.run(get_next))
      self.assertEqual((b"Jane", b"Moe", b"Hi again!"), sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)
      sess.run(
          init_op,
          feed_dict={
              self.query: "SELECT first_name, last_name, state FROM people "
                          "ORDER BY first_name DESC"
          })
      self.assertEqual((b"John", b"Doe", b"California"), sess.run(get_next))
      self.assertEqual((b"Benjamin", b"Franklin", b"Pennsylvania"),
                       sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  # Test that an `OutOfRangeError` is raised on the first call to
  # `get_next_str_only` if result set is empty.
  def testReadEmptyResultSet(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.string,
                                                dtypes.string))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query: "SELECT first_name, last_name, motto FROM students "
                          "WHERE first_name = 'Nonexistent'"
          })
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  # Test that an error is raised when `driver_name` is invalid.
  def testReadResultSetWithInvalidDriverName(self):
    init_op = self._createSqlDataset((dtypes.string, dtypes.string,
                                      dtypes.string))[0]
    with self.cached_session() as sess:
      with self.assertRaises(errors.InvalidArgumentError):
        sess.run(
            init_op,
            feed_dict={
                self.driver_name: "sqlfake",
                self.query: "SELECT first_name, last_name, motto FROM students "
                            "ORDER BY first_name DESC"
            })

  # Test that an error is raised when a column name in `query` is nonexistent
  def testReadResultSetWithInvalidColumnName(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.string,
                                                dtypes.string))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query:
                  "SELECT first_name, last_name, fake_column FROM students "
                  "ORDER BY first_name DESC"
          })
      with self.assertRaises(errors.UnknownError):
        sess.run(get_next)

  # Test that an error is raised when there is a syntax error in `query`.
  def testReadResultSetOfQueryWithSyntaxError(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.string,
                                                dtypes.string))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query:
                  "SELEmispellECT first_name, last_name, motto FROM students "
                  "ORDER BY first_name DESC"
          })
      with self.assertRaises(errors.UnknownError):
        sess.run(get_next)

  # Test that an error is raised when the number of columns in `query`
  # does not match the length of `output_types`.
  def testReadResultSetWithMismatchBetweenColumnsAndOutputTypes(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.string,
                                                dtypes.string))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query: "SELECT first_name, last_name FROM students "
                          "ORDER BY first_name DESC"
          })
      with self.assertRaises(errors.InvalidArgumentError):
        sess.run(get_next)

  # Test that no results are returned when `query` is an insert query rather
  # than a select query. In particular, the error refers to the number of
  # output types passed to the op not matching the number of columns in the
  # result set of the query (namely, 0 for an insert statement.)
  def testReadResultSetOfInsertQuery(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.string,
                                                dtypes.string))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query:
                  "INSERT INTO students (first_name, last_name, motto) "
                  "VALUES ('Foo', 'Bar', 'Baz'), ('Fizz', 'Buzz', 'Fizzbuzz')"
          })
      with self.assertRaises(errors.InvalidArgumentError):
        sess.run(get_next)

  # Test that `SqlDataset` can read an integer from a SQLite database table and
  # place it in an `int8` tensor.
  def testReadResultSetInt8(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.int8))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query: "SELECT first_name, desk_number FROM students "
                          "ORDER BY first_name DESC"
          })
      self.assertEqual((b"John", 9), sess.run(get_next))
      self.assertEqual((b"Jane", 127), sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  # Test that `SqlDataset` can read a negative or 0-valued integer from a
  # SQLite database table and place it in an `int8` tensor.
  def testReadResultSetInt8NegativeAndZero(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.int8,
                                                dtypes.int8))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query: "SELECT first_name, income, favorite_negative_number "
                          "FROM students "
                          "WHERE first_name = 'John' ORDER BY first_name DESC"
          })
      self.assertEqual((b"John", 0, -2), sess.run(get_next))
    with self.assertRaises(errors.OutOfRangeError):
      sess.run(get_next)

  # Test that `SqlDataset` can read a large (positive or negative) integer from
  # a SQLite database table and place it in an `int8` tensor.
  def testReadResultSetInt8MaxValues(self):
    init_op, get_next = self._createSqlDataset((dtypes.int8, dtypes.int8))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query:
                  "SELECT desk_number, favorite_negative_number FROM students "
                  "ORDER BY first_name DESC"
          })
      self.assertEqual((9, -2), sess.run(get_next))
      # Max and min values of int8
      self.assertEqual((127, -128), sess.run(get_next))
    with self.assertRaises(errors.OutOfRangeError):
      sess.run(get_next)

  # Test that `SqlDataset` can read an integer from a SQLite database table and
  # place it in an `int16` tensor.
  def testReadResultSetInt16(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.int16))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query: "SELECT first_name, desk_number FROM students "
                          "ORDER BY first_name DESC"
          })
      self.assertEqual((b"John", 9), sess.run(get_next))
      self.assertEqual((b"Jane", 127), sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  # Test that `SqlDataset` can read a negative or 0-valued integer from a
  # SQLite database table and place it in an `int16` tensor.
  def testReadResultSetInt16NegativeAndZero(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.int16,
                                                dtypes.int16))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query: "SELECT first_name, income, favorite_negative_number "
                          "FROM students "
                          "WHERE first_name = 'John' ORDER BY first_name DESC"
          })
      self.assertEqual((b"John", 0, -2), sess.run(get_next))
    with self.assertRaises(errors.OutOfRangeError):
      sess.run(get_next)

  # Test that `SqlDataset` can read a large (positive or negative) integer from
  # a SQLite database table and place it in an `int16` tensor.
  def testReadResultSetInt16MaxValues(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.int16))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query: "SELECT first_name, favorite_medium_sized_number "
                          "FROM students ORDER BY first_name DESC"
          })
      # Max value of int16
      self.assertEqual((b"John", 32767), sess.run(get_next))
      # Min value of int16
      self.assertEqual((b"Jane", -32768), sess.run(get_next))
    with self.assertRaises(errors.OutOfRangeError):
      sess.run(get_next)

  # Test that `SqlDataset` can read an integer from a SQLite database table and
  # place it in an `int32` tensor.
  def testReadResultSetInt32(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.int32))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query: "SELECT first_name, desk_number FROM students "
                          "ORDER BY first_name DESC"
          })
      self.assertEqual((b"John", 9), sess.run(get_next))
      self.assertEqual((b"Jane", 127), sess.run(get_next))

  # Test that `SqlDataset` can read a negative or 0-valued integer from a
  # SQLite database table and place it in an `int32` tensor.
  def testReadResultSetInt32NegativeAndZero(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.int32))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query: "SELECT first_name, income FROM students "
                          "ORDER BY first_name DESC"
          })
      self.assertEqual((b"John", 0), sess.run(get_next))
      self.assertEqual((b"Jane", -20000), sess.run(get_next))
    with self.assertRaises(errors.OutOfRangeError):
      sess.run(get_next)

  # Test that `SqlDataset` can read a large (positive or negative) integer from
  # a SQLite database table and place it in an `int32` tensor.
  def testReadResultSetInt32MaxValues(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.int32))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query: "SELECT first_name, favorite_number FROM students "
                          "ORDER BY first_name DESC"
          })
      # Max value of int32
      self.assertEqual((b"John", 2147483647), sess.run(get_next))
      # Min value of int32
      self.assertEqual((b"Jane", -2147483648), sess.run(get_next))
    with self.assertRaises(errors.OutOfRangeError):
      sess.run(get_next)

  # Test that `SqlDataset` can read a numeric `varchar` from a SQLite database
  # table and place it in an `int32` tensor.
  def testReadResultSetInt32VarCharColumnAsInt(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.int32))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query: "SELECT first_name, school_id FROM students "
                          "ORDER BY first_name DESC"
          })
      self.assertEqual((b"John", 123), sess.run(get_next))
      self.assertEqual((b"Jane", 1000), sess.run(get_next))
    with self.assertRaises(errors.OutOfRangeError):
      sess.run(get_next)

  # Test that `SqlDataset` can read an integer from a SQLite database table
  # and place it in an `int64` tensor.
  def testReadResultSetInt64(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.int64))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query: "SELECT first_name, desk_number FROM students "
                          "ORDER BY first_name DESC"
          })
      self.assertEqual((b"John", 9), sess.run(get_next))
      self.assertEqual((b"Jane", 127), sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  # Test that `SqlDataset` can read a negative or 0-valued integer from a
  # SQLite database table and place it in an `int64` tensor.
  def testReadResultSetInt64NegativeAndZero(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.int64))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query: "SELECT first_name, income FROM students "
                          "ORDER BY first_name DESC"
          })
      self.assertEqual((b"John", 0), sess.run(get_next))
      self.assertEqual((b"Jane", -20000), sess.run(get_next))
    with self.assertRaises(errors.OutOfRangeError):
      sess.run(get_next)

  # Test that `SqlDataset` can read a large (positive or negative) integer from
  # a SQLite database table and place it in an `int64` tensor.
  def testReadResultSetInt64MaxValues(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.int64))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query:
                  "SELECT first_name, favorite_big_number FROM students "
                  "ORDER BY first_name DESC"
          })
      # Max value of int64
      self.assertEqual((b"John", 9223372036854775807), sess.run(get_next))
      # Min value of int64
      self.assertEqual((b"Jane", -9223372036854775808), sess.run(get_next))
    with self.assertRaises(errors.OutOfRangeError):
      sess.run(get_next)

  # Test that `SqlDataset` can read an integer from a SQLite database table and
  # place it in a `uint8` tensor.
  def testReadResultSetUInt8(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.uint8))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query: "SELECT first_name, desk_number FROM students "
                          "ORDER BY first_name DESC"
          })
      self.assertEqual((b"John", 9), sess.run(get_next))
      self.assertEqual((b"Jane", 127), sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  # Test that `SqlDataset` can read the minimum and maximum uint8 values from a
  # SQLite database table and place them in `uint8` tensors.
  def testReadResultSetUInt8MinAndMaxValues(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.uint8))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query: "SELECT first_name, brownie_points FROM students "
                          "ORDER BY first_name DESC"
          })
      # Min value of uint8
      self.assertEqual((b"John", 0), sess.run(get_next))
      # Max value of uint8
      self.assertEqual((b"Jane", 255), sess.run(get_next))
    with self.assertRaises(errors.OutOfRangeError):
      sess.run(get_next)

  # Test that `SqlDataset` can read an integer from a SQLite database table
  # and place it in a `uint16` tensor.
  def testReadResultSetUInt16(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.uint16))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query: "SELECT first_name, desk_number FROM students "
                          "ORDER BY first_name DESC"
          })
      self.assertEqual((b"John", 9), sess.run(get_next))
      self.assertEqual((b"Jane", 127), sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  # Test that `SqlDataset` can read the minimum and maximum uint16 values from a
  # SQLite database table and place them in `uint16` tensors.
  def testReadResultSetUInt16MinAndMaxValues(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.uint16))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query: "SELECT first_name, account_balance FROM students "
                          "ORDER BY first_name DESC"
          })
      # Min value of uint16
      self.assertEqual((b"John", 0), sess.run(get_next))
      # Max value of uint16
      self.assertEqual((b"Jane", 65535), sess.run(get_next))
    with self.assertRaises(errors.OutOfRangeError):
      sess.run(get_next)

  # Test that `SqlDataset` can read a 0-valued and 1-valued integer from a
  # SQLite database table and place them as `True` and `False` respectively
  # in `bool` tensors.
  def testReadResultSetBool(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.bool))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query:
                  "SELECT first_name, registration_complete FROM students "
                  "ORDER BY first_name DESC"
          })
      self.assertEqual((b"John", True), sess.run(get_next))
      self.assertEqual((b"Jane", False), sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  # Test that `SqlDataset` can read an integer that is not 0-valued or 1-valued
  # from a SQLite database table and place it as `True` in a `bool` tensor.
  def testReadResultSetBoolNotZeroOrOne(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.bool))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query: "SELECT first_name, favorite_medium_sized_number "
                          "FROM students ORDER BY first_name DESC"
          })
      self.assertEqual((b"John", True), sess.run(get_next))
      self.assertEqual((b"Jane", True), sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  # Test that `SqlDataset` can read a float from a SQLite database table
  # and place it in a `float64` tensor.
  def testReadResultSetFloat64(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.string,
                                                dtypes.float64))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query:
                  "SELECT first_name, last_name, victories FROM townspeople "
                  "ORDER BY first_name"
          })
      self.assertEqual((b"George", b"Washington", 20.0), sess.run(get_next))
      self.assertEqual((b"John", b"Adams", -19.95), sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  # Test that `SqlDataset` can read a float from a SQLite database table beyond
  # the precision of 64-bit IEEE, without throwing an error. Test that
  # `SqlDataset` identifies such a value as equal to itself.
  def testReadResultSetFloat64OverlyPrecise(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.string,
                                                dtypes.float64))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query:
                  "SELECT first_name, last_name, accolades FROM townspeople "
                  "ORDER BY first_name"
          })
      self.assertEqual(
          (b"George", b"Washington",
           1331241.321342132321324589798264627463827647382647382643874),
          sess.run(get_next))
      self.assertEqual(
          (b"John", b"Adams",
           1331241321342132321324589798264627463827647382647382643874.0),
          sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

  # Test that `SqlDataset` can read a float from a SQLite database table,
  # representing the largest integer representable as a 64-bit IEEE float
  # such that the previous integer is also representable as a 64-bit IEEE float.
  # Test that `SqlDataset` can distinguish these two numbers.
  def testReadResultSetFloat64LargestConsecutiveWholeNumbersNotEqual(self):
    init_op, get_next = self._createSqlDataset((dtypes.string, dtypes.string,
                                                dtypes.float64))
    with self.cached_session() as sess:
      sess.run(
          init_op,
          feed_dict={
              self.query:
                  "SELECT first_name, last_name, triumphs FROM townspeople "
                  "ORDER BY first_name"
          })
      self.assertNotEqual((b"George", b"Washington", 9007199254740992.0),
                          sess.run(get_next))
      self.assertNotEqual((b"John", b"Adams", 9007199254740991.0),
                          sess.run(get_next))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(get_next)

if __name__ == "__main__":
  test.main()


text:
const nonWhitespace = /\S/;
const newlines = /\r\n?|\n/;

// Trims the whitespace off the lines.
function lineFilter(lines, line, i, { length }) {
  if (i > 0) { line = line.trimLeft(); }
  if (i + 1 < length) { line = line.trimRight(); }
  if (line) { lines.push(line); }

  return lines;
}

// Cleans the whitespace from a text node.
function cleanText(node) {
  if (!nonWhitespace.test(node.value)) {
    return "";
  }

  let lines = node.value.split(newlines);
  lines = lines.reduce(lineFilter, []);

  return lines.join(" ");
}

// Helper to transform an expression into an expression statement.
function toStatement(t, expression) {
  if (!t.isStatement(expression)) {
    return t.expressionStatement(expression);
  }
  return expression;
}

// Helper to create a function call statement in AST.
function toFunctionCallStatement(t, functionName, args) {
  return t.expressionStatement(toFunctionCall(t, functionName, args));
}

// Helper to create a function call in AST.
export function toFunctionCall(t, functionName, args) {
  return t.callExpression(t.identifier(functionName), args);
}

// Helper to transform a JSX identifier into a normal reference.
export function toReference(t, node, identifier) {
  if (t.isIdentifier(node)) {
    return node;
  }
  if (t.isJSXIdentifier(node)) {
    return identifier ? t.identifier(node.name) : t.literal(node.name);
  }
  return t.memberExpression(
    toReference(t, node.object, true),
    toReference(t, node.property, true)
  );
}

// Extracts attributes into the appropriate
// attribute array. Static attributes and the key
// are placed into static attributes, and expressions
// are placed into the variadic attributes.
export function extractOpenArguments(t, attributes) {
  let key = null;
  let statics = [];
  let attrs = [];
  let hasSpread = false;

  for (let attribute of attributes) {
    if (t.isJSXSpreadAttribute(attribute)) {
      hasSpread = true;
      attrs.push(attribute);
      continue;
    }

    let name = attribute.name.name;
    let attr = t.literal(name);
    let value = attribute.value;

    if (!value) {
      value = t.literal(true);
    } else if (t.isJSXExpressionContainer(value)) {
      value = value.expression;
    }

    if (name === "key") {
      key = value;
    }

    if (name === "key" || t.isLiteral(value)) {
      statics.push(attr, value);
    } else {
      attrs.push([ attr, value ]);
    }
  }

  if (!statics.length) { statics = null; }
  if (!attrs.length) { attrs = null; }

  return { key, statics, attrs, hasSpread };
}

// Transforms an attribute array into sequential attr calls.
export function attrsToAttrCalls(t, scope, attrs) {
  return attrs.map((attr) => {
    if (t.isJSXSpreadAttribute(attr)) {
      let iterator = scope.generateUidIdentifier("attr");

      return t.forInStatement(
        t.variableDeclaration("var", [iterator]),
        attr.argument,
        toFunctionCallStatement(t, "attr", [
          iterator,
          t.memberExpression(attr.argument, iterator, true)
        ])
      );
    }

    return toFunctionCall(t, "attr", attr);
  });
}

// Filters out empty children, and transform JSX expressions
// into normal expressions.
export function buildChildren(t, children) {
  return children.reduce((children, child) => {
    if (t.isJSXExpressionContainer(child)) {
      child = child.expression;
    }

    if (t.isLiteral(child) && typeof child.value === "string") {
      let text = cleanText(child);
      if (!text) { return children; }

      child = toFunctionCall(t, "text", [t.literal(text)]);
    }

    if (t.isJSXEmptyExpression(child)) {
      return children;
    } else if (t.isArrayExpression(child)) {
      child = t.sequenceExpression(buildChildren(t, child.elements));
    } else if (t.isIdentifier(child) || t.isMemberExpression(child)) {
      child = toReference(t, child);
    }

    children.push(child);
    return children;
  }, []);
}

// Helper to flatten out sequence expressions into a top level
// expression statements.
export function flattenExpressions(t, expressions) {
  return expressions.reduce((nodes, node) => {
    if (t.isSequenceExpression(node)) {
      let expressions = flattenExpressions(t, node.expressions);
      nodes.push(...expressions);
    } else {
      nodes.push(toStatement(t, node));
    }
    return nodes;
  }, []);
}


text:
package com.fortify.processrunner.context;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.fortify.util.spring.expression.helper.DefaultExpressionHelper;

/**
 *
This class defines the process runner context. It is basically a
 * {@link HashMap} that can contain arbitrary String keys together with
 * arbitrary Object values.

 *
 *
To allow type-safe access to this {@link Map}, callers can call the
 * {@link #as(Class)} method to 'cast' the {@link Map} to an arbitrary
 * interface. This will generate a Java proxy that provides access to
 * the {@link Map} via regular bean methods like getX() and setX(value).

 *
 *
Note that interfaces used with the {@link #as(Class)} method should
 * use unique method names (for example based on the interface name) to avoid
 * naming conflicts in the map between different types of functionality.

 *
 *
Currently the following method declarations are supported in interfaces
 * passed to the {@link #as(Class)} method:

 *

 *
get[SomeProperty]()Get the value for the [SomeProperty] key from the context

 *
set[SomeProperty](value)Set the value for the [SomeProperty] key on the context

 *

 */
@SuppressWarnings({"unchecked","rawtypes"})
public class Context extends HashMap<String, Object> {
	private static final long serialVersionUID = 1L;
	private final Map<Class, Object> proxies = new HashMap<Class, Object>();

	/**
	 * Constructor for new, empty context
	 */
	public Context() {}

	/**
	 * Constructor for copying an existing {@link Context} instance
	 * @param context
	 */
	public Context(Context context) {
		super(context);
	}

	/**
	 * Convenience method for chaining put operations
	 */
	public Context chainedPut(String key, Object value) {
		put(key, value); return this;
	}

	public <T> T get(String key, Class<T> returnType) {
		return DefaultExpressionHelper.get().evaluateSimpleExpression(this, key, returnType);
	}

	/**
	 * Indicate whether this {@link Context} contains a value for the given key.
	 * If the {@link Context} contains the given key, but it is a blank string,
	 * this method will also return 'false'
	 * @param key
	 * @return
	 */
	public final boolean hasValueForKey(String key) {
		Object value = get(key);
		return value!=null && !(value instanceof String && StringUtils.isBlank((String)value));
	}

	public final boolean hasValueForAnyKey(String... keys) {
		for ( String key : keys ) {
			if ( hasValueForKey(key) ) { return true; }
		}
		return false;
	}

	public final boolean hasValueForAllKeys(String... keys) {
		for ( String key : keys ) {
			if ( !hasValueForKey(key) ) { return false; }
		}
		return true;
	}

	/**
	 * Make the contents of this {@link Context} instance available through the
	 * given interface, allowing for type-safe access.
	 * @param iface
	 * @return
	 */
	public final <T> T as(Class<T> iface) {
		T result = (T)proxies.get(iface);
		if ( result == null ) {
			result = (T) Proxy.newProxyInstance(this.getClass().getClassLoader(),
                new Class[]{iface},
                new MapBasedInvocationHandler(this));
		}
		return result;
	}

	/**
	 * This {@link InvocationHandler} implementation can be used to provide
	 * method implementations based on a backing map, for example to get and
	 * set specific properties in the backing map.
	 */
	private static final class MapBasedInvocationHandler implements InvocationHandler {
		private final Map<String, Object> map;
		private final List<MethodHandler> methodHandlers = Arrays.asList(new MethodHandler[]{
			new GetMethodHandler(), new SetMethodHandler()
		});
		public MapBasedInvocationHandler(Map<String, Object> map) {
			this.map = map;
		}
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			for ( MethodHandler mh : methodHandlers ) {
		    	if ( mh.canHandleMethod(map, method, args) ) {
		    		return mh.handleMethod(map, method, args);
		    	}
		    }
		    throw new RuntimeException("No handler found for method "+method);
		}

		private static interface MethodHandler {
			public Object handleMethod(Map<String, Object> map, Method method, Object[] args);
			public boolean canHandleMethod(Map<String, Object> map, Method method, Object[] args);
		}

		private static abstract class AbstractMethodHandler implements MethodHandler{
			protected abstract String getSupportedPrefix();
			protected abstract boolean canHandleArgs(Object[] args);
			protected abstract Object handleKey(Map<String, Object> map, String key, Object[] args);

			public boolean canHandleMethod(Map<String, Object> map, Method method, Object[] args) {
				return method.getName().startsWith(getSupportedPrefix());
			}

			public final Object handleMethod(Map<String, Object> map, Method method, Object[] args) {
				return handleKey(map, method.getName().substring(getSupportedPrefix().length()), args);
			}
		}

		/**
		 * Given an interface method named get[SomeProperty](), this
		 * {@link AbstractMethodHandler} implementation will get the
		 * value for the [SomeProperty] key from the backing map.
		 */
		private static final class GetMethodHandler extends AbstractMethodHandler {
			@Override
			protected String getSupportedPrefix() {
				return "get";
			}
			@Override
			protected boolean canHandleArgs(Object[] args) {
				return args.length==0;
			}
			@Override
			protected Object handleKey(Map<String, Object> map, String key, Object[] args) {
				return map.get(key);
			}
		}

		/**
		 * Given an interface method named set[SomeProperty](), this
		 * {@link AbstractMethodHandler} implementation will set the
		 * value for the [SomeProperty] key on the backing map.
		 */
		private static final class SetMethodHandler extends AbstractMethodHandler {
			@Override
			protected String getSupportedPrefix() {
				return "set";
			}
			@Override
			protected boolean canHandleArgs(Object[] args) {
				return args.length==1;
			}
			@Override
			protected Object handleKey(Map<String, Object> map, String key, Object[] args) {
				return map.put(key, args[0]);
			}
		}
	}
}


text:
namespace InWorldz.PrimExporter.ExpLib.ImportExport.BabylonFlatBuffers
{

using System;
using FlatBuffers;

public struct BabylonFileFlatbuffer : IFlatbufferObject
{
  private Table __p;
  public ByteBuffer ByteBuffer { get { return __p.bb; } }
  public static BabylonFileFlatbuffer GetRootAsBabylonFileFlatbuffer(ByteBuffer _bb) { return GetRootAsBabylonFileFlatbuffer(_bb, new BabylonFileFlatbuffer()); }
  public static BabylonFileFlatbuffer GetRootAsBabylonFileFlatbuffer(ByteBuffer _bb, BabylonFileFlatbuffer obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
  public void __init(int _i, ByteBuffer _bb) { __p.bb_pos = _i; __p.bb = _bb; }
  public BabylonFileFlatbuffer __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }

  public InWorldz.PrimExporter.ExpLib.ImportExport.BabylonFlatBuffers.Material? Materials(int j) { int o = __p.__offset(4); return o != 0 ? (InWorldz.PrimExporter.ExpLib.ImportExport.BabylonFlatBuffers.Material?)(new InWorldz.PrimExporter.ExpLib.ImportExport.BabylonFlatBuffers.Material()).__assign(__p.__indirect(__p.__vector(o) + j * 4), __p.bb) : null; }
  public int MaterialsLength { get { int o = __p.__offset(4); return o != 0 ? __p.__vector_len(o) : 0; } }
  public InWorldz.PrimExporter.ExpLib.ImportExport.BabylonFlatBuffers.MultiMaterial? MultiMaterials(int j) { int o = __p.__offset(6); return o != 0 ? (InWorldz.PrimExporter.ExpLib.ImportExport.BabylonFlatBuffers.MultiMaterial?)(new InWorldz.PrimExporter.ExpLib.ImportExport.BabylonFlatBuffers.MultiMaterial()).__assign(__p.__indirect(__p.__vector(o) + j * 4), __p.bb) : null; }
  public int MultiMaterialsLength { get { int o = __p.__offset(6); return o != 0 ? __p.__vector_len(o) : 0; } }
  public InWorldz.PrimExporter.ExpLib.ImportExport.BabylonFlatBuffers.Mesh? Meshes(int j) { int o = __p.__offset(8); return o != 0 ? (InWorldz.PrimExporter.ExpLib.ImportExport.BabylonFlatBuffers.Mesh?)(new InWorldz.PrimExporter.ExpLib.ImportExport.BabylonFlatBuffers.Mesh()).__assign(__p.__indirect(__p.__vector(o) + j * 4), __p.bb) : null; }
  public int MeshesLength { get { int o = __p.__offset(8); return o != 0 ? __p.__vector_len(o) : 0; } }

  public static Offset<BabylonFileFlatbuffer> CreateBabylonFileFlatbuffer(FlatBufferBuilder builder,
      VectorOffset materialsOffset = default(VectorOffset),
      VectorOffset multiMaterialsOffset = default(VectorOffset),
      VectorOffset meshesOffset = default(VectorOffset)) {
    builder.StartObject(3);
    BabylonFileFlatbuffer.AddMeshes(builder, meshesOffset);
    BabylonFileFlatbuffer.AddMultiMaterials(builder, multiMaterialsOffset);
    BabylonFileFlatbuffer.AddMaterials(builder, materialsOffset);
    return BabylonFileFlatbuffer.EndBabylonFileFlatbuffer(builder);
  }

  public static void StartBabylonFileFlatbuffer(FlatBufferBuilder builder) { builder.StartObject(3); }
  public static void AddMaterials(FlatBufferBuilder builder, VectorOffset materialsOffset) { builder.AddOffset(0, materialsOffset.Value, 0); }
  public static VectorOffset CreateMaterialsVector(FlatBufferBuilder builder, Offset<InWorldz.PrimExporter.ExpLib.ImportExport.BabylonFlatBuffers.Material>[] data) { builder.StartVector(4, data.Length, 4); for (int i = data.Length - 1; i >= 0; i--) builder.AddOffset(data[i].Value); return builder.EndVector(); }
  public static void StartMaterialsVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); }
  public static void AddMultiMaterials(FlatBufferBuilder builder, VectorOffset multiMaterialsOffset) { builder.AddOffset(1, multiMaterialsOffset.Value, 0); }
  public static VectorOffset CreateMultiMaterialsVector(FlatBufferBuilder builder, Offset<InWorldz.PrimExporter.ExpLib.ImportExport.BabylonFlatBuffers.MultiMaterial>[] data) { builder.StartVector(4, data.Length, 4); for (int i = data.Length - 1; i >= 0; i--) builder.AddOffset(data[i].Value); return builder.EndVector(); }
  public static void StartMultiMaterialsVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); }
  public static void AddMeshes(FlatBufferBuilder builder, VectorOffset meshesOffset) { builder.AddOffset(2, meshesOffset.Value, 0); }
  public static VectorOffset CreateMeshesVector(FlatBufferBuilder builder, Offset<InWorldz.PrimExporter.ExpLib.ImportExport.BabylonFlatBuffers.Mesh>[] data) { builder.StartVector(4, data.Length, 4); for (int i = data.Length - 1; i >= 0; i--) builder.AddOffset(data[i].Value); return builder.EndVector(); }
  public static void StartMeshesVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); }
  public static Offset<BabylonFileFlatbuffer> EndBabylonFileFlatbuffer(FlatBufferBuilder builder) {
    int o = builder.EndObject();
    return new Offset<BabylonFileFlatbuffer>(o);
  }
  public static void FinishBabylonFileFlatbufferBuffer(FlatBufferBuilder builder, Offset<BabylonFileFlatbuffer> offset) { builder.Finish(offset.Value); }
};

}


text:
enum PhysicsServerOptions
{
	PHYSICS_SERVER_ENABLE_COMMAND_LOGGING = 1,
	PHYSICS_SERVER_REPLAY_FROM_COMMAND_LOG = 2,
	PHYSICS_SERVER_USE_RTC_CLOCK = 4,
};

///Don't use PhysicsServerCreateFuncInternal directly
///Use PhysicsServerCreateFuncBullet2 instead, or initialize options.m_commandProcessor
class CommonExampleInterface* PhysicsServerCreateFuncInternal(struct CommonExampleOptions& options);

#endif  //PHYSICS_SERVER_EXAMPLE_H


text:
@interface hRDViewController : UIViewController <NSURLConnectionDelegate, NSURLConnectionDataDelegate>
@property (copy, nonatomic)NSString* userId;
@property (copy, nonatomic)NSString* latitude;
@property (copy, nonatomic)NSString* longitude;
@property (copy, nonatomic)NSString* radius;
@property (copy, nonatomic)NSDictionary* dictDetails;
@property (strong, nonatomic)NSURL* url;
@property  (strong, nonatomic)NSMutableURLRequest* request;
@property (strong, nonatomic)NSURLConnection *connection;
@property(strong, nonatomic)NSMutableData *data;
@property (strong, nonatomic) IBOutlet UILabel *childZoneStatusLabel;
@property (strong, nonatomic) IBOutlet UILabel *parentUserIdLabel;

@end


text:
A Photoshop script to automatically generate properly sized app icons for iOS devices from a single PSD image.

##Device support:
- iPad (incl. retina)
- iPhone/iPod (incl. retina)
- iTunes (incl. retina)

##Usage

1. Open the PSD for your app icon. The PSD should be as large as the largest icon you want to generate (usually iTunes @ 1024px×1024px)
2. Go to File > Scripts > Browse and select `icon.js`.
3. The script will generate your app icons as web optimized PNG's, and save them to the same folder as your PSD.

##To do:

- Support for Android
- Support for Windows Mobile
- Support for Blackberry


text:
set -e

sys_has() {
    type "$1" > /dev/null 2>&1
    return $?
}

if [ -z "$ARTIFACT_MANAGER_DIR" ]; then
    ARTIFACT_MANAGER_DIR="$HOME/artifactmgr"
fi

NVM_DIR="$ARTIFACT_MANAGER_DIR/.nvm"

if sys_has "apt-get"; then
    sudo apt-get -y update
    sudo apt-get -y install curl git python-software-properties python g++ make
elif sys_has "yum"; then
    sudo yum -y install curl git-core
fi

if ! sys_has "curl"; then
    echo "FAIL: curl is not installed"
    exit 1
fi

if ! sys_has "git"; then
    echo "FAIL: git is not installed"
    exit 1
fi

rm -rf $ARTIFACT_MANAGER_DIR
git clone https://github.com/jojow/artifactmgr.git $ARTIFACT_MANAGER_DIR

rm -rf $NVM_DIR
git clone https://github.com/creationix/nvm.git $NVM_DIR
cd $NVM_DIR
git checkout tags/v0.24.0

source $NVM_DIR/nvm.sh

nvm install 0.10
nvm use 0.10
nvm alias default 0.10

npm install -g forever

cd $ARTIFACT_MANAGER_DIR

npm install

chmod a+x run.sh

echo "INFO: run artifact manager by invoking $ARTIFACT_MANAGER_DIR/run.sh"

#
# Run artifact manager:
#  $ARTIFACT_MANAGER_DIR/run.sh
#


text:
package com.blazeloader.api.client.gui;

import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;

/**
 * API functions for GUI-related tasks.
 */
public class ApiGuiClient {

    /**
     * Opens a GUI, triggering an eventDisplayGui in the process.
     *
     * @param gui The GUI to display.
     */
    public static void openGUI(GuiScreen gui) {
        Minecraft.getMinecraft().displayGuiScreen(gui);
    }

    /**
     * Closes the currently open GUI, returning to the bottom layer.
     * <p>Usually either the main menu or the main game interface.
     */
    public static void closeCurrentGUI() {
        Minecraft.getMinecraft().displayGuiScreen(null);
    }

    /**
     * Returns the currently open GUI. May be null.
     *
     * @return Returns the currently open GUI.
     */
    public static GuiScreen getOpenGUI() {
        return Minecraft.getMinecraft().currentScreen;
    }
}


text:
Durum Bildir

{{ animal.name }}
(5 Gönüllü)

+ Gönüllü Ol

   <router-outlet></router-outlet>


text:
"""File-system datastore."""
from __future__ import with_statement

import os
import re

from cloud_browser.app_settings import settings
from cloud_browser.cloud import errors, base
from cloud_browser.common import SEP

###############################################################################
# Helpers / Constants
###############################################################################
NO_DOT_RE = re.compile("^[^.]+")

def not_dot(path):
    """Check if non-dot."""
    return NO_DOT_RE.match(os.path.basename(path))

def is_dir(path):
    """Check if non-dot and directory."""
    return not_dot(path) and os.path.isdir(path)

###############################################################################
# Classes
###############################################################################
class FilesystemContainerWrapper(errors.CloudExceptionWrapper):
    """Exception translator."""
    translations = {
        OSError: errors.NoContainerException,
    }
wrap_fs_cont_errors = FilesystemContainerWrapper()  # pylint: disable=C0103

class FilesystemObjectWrapper(errors.CloudExceptionWrapper):
    """Exception translator."""
    translations = {
        OSError: errors.NoObjectException,
    }
wrap_fs_obj_errors = FilesystemObjectWrapper()  # pylint: disable=C0103

class FilesystemObject(base.CloudObject):
    """Filesystem object wrapper."""

    def _get_object(self):
        """Return native storage object."""
        return object()

    def _read(self):
        """Return contents of object."""
        with open(self.base_path, 'rb') as file_obj:
            return file_obj.read()

    @property
    def base_path(self):
        """Base absolute path of container."""
        return os.path.join(self.container.base_path, self.name)

    @classmethod
    def from_path(cls, container, path):
        """Create object from path."""
        from datetime import datetime

        path = path.strip(SEP)
        full_path = os.path.join(container.base_path, path)
        last_modified = datetime.fromtimestamp(os.path.getmtime(full_path))
        obj_type = cls.type_cls.SUBDIR if is_dir(full_path)\
            else cls.type_cls.FILE

        return cls(container,
                   name=path,
                   size=os.path.getsize(full_path),
                   content_type=None,
                   last_modified=last_modified,
                   obj_type=obj_type)

class FilesystemContainer(base.CloudContainer):
    """Filesystem container wrapper."""
    #: Storage object child class.
    obj_cls = FilesystemObject

    def _get_container(self):
        """Return native container object."""
        return object()

    @wrap_fs_obj_errors
    def get_objects(self, path, marker=None,
                    limit=settings.CLOUD_BROWSER_DEFAULT_LIST_LIMIT):
        """Get objects."""
        def _filter(name):
            """Filter."""
            return (not_dot(name) and
                    (marker is None or
                     os.path.join(path, name).strip(SEP) > marker.strip(SEP)))

        search_path = os.path.join(self.base_path, path)
        objs = [self.obj_cls.from_path(self, os.path.join(path, o))
                for o in os.listdir(search_path) if _filter(o)]
        objs = sorted(objs, key=lambda x: x.base_path)
        return objs[:limit]

    @wrap_fs_obj_errors
    def get_object(self, path):
        """Get single object."""
        return self.obj_cls.from_path(self, path)

    @property
    def base_path(self):
        """Base absolute path of container."""
        return os.path.join(self.conn.abs_root, self.name)

    @classmethod
    def from_path(cls, conn, path):
        """Create container from path."""
        path = path.strip(SEP)
        full_path = os.path.join(conn.abs_root, path)
        return cls(conn, path, 0, os.path.getsize(full_path))

class FilesystemConnection(base.CloudConnection):
    """Filesystem connection wrapper."""
    #: Container child class.
    cont_cls = FilesystemContainer

    def __init__(self, root):
        """Initializer."""
        super(FilesystemConnection, self).__init__(None, None)
        self.root = root
        self.abs_root = os.path.abspath(root)

    def _get_connection(self):
        """Return native connection object."""
        return object()

    @wrap_fs_cont_errors
    def _get_containers(self):
        """Return available containers."""
        full_fn = lambda p: os.path.join(self.abs_root, p)
        return [self.cont_cls.from_path(self, d)
                for d in os.listdir(self.abs_root) if is_dir(full_fn(d))]

    @wrap_fs_cont_errors
    def _get_container(self, path):
        """Return single container."""
        path = path.strip(SEP)
        if SEP in path:
            raise errors.InvalidNameException(
                "Path contains %s - %s" % (SEP, path))
        return self.cont_cls.from_path(self, path)


text:
package org.fedoraproject.xmvn.tools.subst;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.fedoraproject.xmvn.artifact.Artifact;
import org.fedoraproject.xmvn.artifact.DefaultArtifact;
import org.fedoraproject.xmvn.metadata.ArtifactMetadata;
import org.fedoraproject.xmvn.metadata.MetadataResult;

/**
 * @author Mikolaj Izdebski
 */
public class ArtifactVisitor
    implements FileVisitor<Path>
{
    private boolean debug;

    private final Set<String> types = new LinkedHashSet<>();

    private final List<MetadataResult> metadata;

    private boolean followSymlinks;

    private boolean dryRun;

    private int failureCount;

    public ArtifactVisitor( boolean debug, List<MetadataResult> metadata )
    {
        this.debug = debug;
        this.metadata = metadata;
    }

    public void setTypes( Collection<String> types )
    {
        this.types.addAll( types );
    }

    public void setFollowSymlinks( boolean followSymlinks )
    {
        this.followSymlinks = followSymlinks;
    }

    public void setDryRun( boolean dryRun )
    {
        this.dryRun = dryRun;
    }

    public int getFailureCount()
    {
        return failureCount;
    }

    @Override
    public FileVisitResult postVisitDirectory( Path path, IOException e )
        throws IOException
    {
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult preVisitDirectory( Path path, BasicFileAttributes attrs )
        throws IOException
    {
        if ( Files.isSymbolicLink( path ) && !followSymlinks )
        {
            if ( debug )
                System.err.printf( "Skipping symlink to directory: %s%n", path );
            return FileVisitResult.SKIP_SUBTREE;
        }

        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile( Path path, BasicFileAttributes attrs )
        throws IOException
    {
        if ( !Files.isRegularFile( path ) )
        {
            if ( debug )
                System.err.printf( "Skipping %s: not a regular file%n", path );
            return FileVisitResult.CONTINUE;
        }

        String fileName = path.getFileName().toString();

        for ( String type : types )
        {
            if ( fileName.endsWith( "." + type ) )
            {
                substituteArtifact( path, type );
            }
        }

        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed( Path path, IOException e )
        throws IOException
    {
        System.err.printf( "WARNING: Failed to access file %s%n", path );
        return FileVisitResult.CONTINUE;
    }

    private Artifact getArtifactFromManifest( Path path )
        throws IOException
    {
        try ( JarFile jarFile = new JarFile( path.toFile() ) )
        {
            Manifest mf = jarFile.getManifest();
            if ( mf == null )
                return null;

            String groupId = mf.getMainAttributes().getValue( Artifact.MF_KEY_GROUPID );
            String artifactId = mf.getMainAttributes().getValue( Artifact.MF_KEY_ARTIFACTID );
            String extension = mf.getMainAttributes().getValue( Artifact.MF_KEY_EXTENSION );
            String classifier = mf.getMainAttributes().getValue( Artifact.MF_KEY_CLASSIFIER );
            String version = mf.getMainAttributes().getValue( Artifact.MF_KEY_VERSION );

            if ( groupId == null || artifactId == null )
                return null;

            return new DefaultArtifact( groupId, artifactId, extension, classifier, version );
        }
    }

    private Artifact getArtifactFromPomProperties( Path path, String extension )
        throws IOException
    {
        try ( ZipInputStream zis = new ZipInputStream( Files.newInputStream( path ) ) )
        {
            ZipEntry entry;
            while ( ( entry = zis.getNextEntry() ) != null )
            {
                String name = entry.getName();
                if ( name.startsWith( "META-INF/maven/" ) && name.endsWith( "/pom.properties" ) )
                {
                    Properties properties = new Properties();
                    properties.load( zis );

                    String groupId = properties.getProperty( "groupId" );
                    String artifactId = properties.getProperty( "artifactId" );
                    String version = properties.getProperty( "version" );
                    return new DefaultArtifact( groupId, artifactId, extension, version );
                }
            }

            return null;
        }
    }

    private Artifact readArtifactDefinition( Path path, String extension )
    {
        try
        {
            Artifact artifact = getArtifactFromManifest( path );
            if ( artifact != null )
                return artifact;

            artifact = getArtifactFromPomProperties( path, extension );
            if ( artifact != null )
                return artifact;

            return null;
        }
        catch ( IOException e )
        {
            System.err.printf( "ERROR: Failed to get artifact definition from file %s%n", path );
            e.printStackTrace();
            return null;
        }
    }

    private void substituteArtifact( Path path, String type )
        throws IOException
    {
        Artifact artifact = readArtifactDefinition( path, type );
        if ( artifact == null )
        {
            System.err.printf( "Skipping file %s: No artifact definition found%n", path );
            failureCount++;
            return;
        }

        ArtifactMetadata metadata = resolveMetadata( artifact );
        if ( metadata == null )
        {
            System.err.printf( "WARNING: Skipping file %s: Artifact %s not found in repository%n", path, artifact );
            failureCount++;
            return;
        }

        Path artifactPath = Paths.get( metadata.getPath() );

        if ( !dryRun )
        {
            Files.delete( path );
            Files.createSymbolicLink( path, artifactPath );
        }

        System.err.printf( "Linked %s to %s%n", path, artifactPath );
    }

    private ArtifactMetadata resolveMetadata( Artifact artifact )
    {
        List<Artifact> versionedArtifacts = Arrays.asList( artifact, artifact.setVersion( null ) );

        for ( MetadataResult metadataResult : metadata )
        {
            for ( Artifact versionedArtifact : versionedArtifacts )
            {
                ArtifactMetadata metadata = metadataResult.getMetadataFor( versionedArtifact );
                if ( metadata != null )
                    return metadata;
            }
        }

        return null;
    }
}


text:
'use strict';

var Registry = require('../../registry');
var Axes = require('../../plots/cartesian/axes');
var Fx = require('../../components/fx');

var createPlot2D = require('gl-plot2d');
var createSpikes = require('gl-spikes2d');
var createSelectBox = require('gl-select-box');
var getContext = require('webgl-context');

var createOptions = require('./convert');
var createCamera = require('./camera');
var showNoWebGlMsg = require('../../lib/show_no_webgl_msg');
var axisConstraints = require('../cartesian/constraints');
var enforceAxisConstraints = axisConstraints.enforce;
var cleanAxisConstraints = axisConstraints.clean;
var doAutoRange = require('../cartesian/autorange').doAutoRange;

var dragHelpers = require('../../components/dragelement/helpers');
var drawMode = dragHelpers.drawMode;
var selectMode = dragHelpers.selectMode;

var AXES = ['xaxis', 'yaxis'];
var STATIC_CANVAS, STATIC_CONTEXT;

var SUBPLOT_PATTERN = require('../cartesian/constants').SUBPLOT_PATTERN;

function Scene2D(options, fullLayout) {
    this.container = options.container;
    this.graphDiv = options.graphDiv;
    this.pixelRatio = options.plotGlPixelRatio || window.devicePixelRatio;
    this.id = options.id;
    this.staticPlot = !!options.staticPlot;
    this.scrollZoom = this.graphDiv._context._scrollZoom.cartesian;

    this.fullData = null;
    this.updateRefs(fullLayout);

    this.makeFramework();
    if(this.stopped) return;

    // update options
    this.glplotOptions = createOptions(this);
    this.glplotOptions.merge(fullLayout);

    // create the plot
    this.glplot = createPlot2D(this.glplotOptions);

    // create camera
    this.camera = createCamera(this);

    // trace set
    this.traces = {};

    // create axes spikes
    this.spikes = createSpikes(this.glplot);

    this.selectBox = createSelectBox(this.glplot, {
        innerFill: false,
        outerFill: true
    });

    // last button state
    this.lastButtonState = 0;

    // last pick result
    this.pickResult = null;

    // is the mouse over the plot?
    // it's OK if this says true when it's not, so long as
    // when we get a mouseout we set it to false before handling
    this.isMouseOver = true;

    // flag to stop render loop
    this.stopped = false;

    // redraw the plot
    this.redraw = this.draw.bind(this);
    this.redraw();
}

module.exports = Scene2D;

var proto = Scene2D.prototype;

proto.makeFramework = function() {
    // create canvas and gl context
    if(this.staticPlot) {
        if(!STATIC_CONTEXT) {
            STATIC_CANVAS = document.createElement('canvas');

            STATIC_CONTEXT = getContext({
                canvas: STATIC_CANVAS,
                preserveDrawingBuffer: false,
                premultipliedAlpha: true,
                antialias: true
            });

            if(!STATIC_CONTEXT) {
                throw new Error('Error creating static canvas/context for image server');
            }
        }

        this.canvas = STATIC_CANVAS;
        this.gl = STATIC_CONTEXT;
    } else {
        var liveCanvas = this.container.querySelector('.gl-canvas-focus');

        var gl = getContext({
            canvas: liveCanvas,
            preserveDrawingBuffer: true,
            premultipliedAlpha: true
        });

        if(!gl) {
            showNoWebGlMsg(this);
            this.stopped = true;
            return;
        }

        this.canvas = liveCanvas;
        this.gl = gl;
    }

    // position the canvas
    var canvas = this.canvas;

    canvas.style.width = '100%';
    canvas.style.height = '100%';
    canvas.style.position = 'absolute';
    canvas.style.top = '0px';
    canvas.style.left = '0px';
    canvas.style['pointer-events'] = 'none';

    this.updateSize(canvas);

    // create SVG container for hover text
    var svgContainer = this.svgContainer = document.createElementNS(
        'http://www.w3.org/2000/svg',
        'svg');
    svgContainer.style.position = 'absolute';
    svgContainer.style.top = svgContainer.style.left = '0px';
    svgContainer.style.width = svgContainer.style.height = '100%';
    svgContainer.style['z-index'] = 20;
    svgContainer.style['pointer-events'] = 'none';

    // create div to catch the mouse event
    var mouseContainer = this.mouseContainer = document.createElement('div');
    mouseContainer.style.position = 'absolute';
    mouseContainer.style['pointer-events'] = 'auto';

    this.pickCanvas = this.container.querySelector('.gl-canvas-pick');

    // append canvas, hover svg and mouse div to container
    var container = this.container;
    container.appendChild(svgContainer);
    container.appendChild(mouseContainer);

    var self = this;
    mouseContainer.addEventListener('mouseout', function() {
        self.isMouseOver = false;
        self.unhover();
    });
    mouseContainer.addEventListener('mouseover', function() {
        self.isMouseOver = true;
    });
};

proto.toImage = function(format) {
    if(!format) format = 'png';

    this.stopped = true;

    if(this.staticPlot) this.container.appendChild(STATIC_CANVAS);

    // update canvas size
    this.updateSize(this.canvas);

    // grab context and yank out pixels
    var gl = this.glplot.gl;
    var w = gl.drawingBufferWidth;
    var h = gl.drawingBufferHeight;

    // force redraw
    gl.clearColor(1, 1, 1, 0);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    this.glplot.setDirty();
    this.glplot.draw();

    gl.bindFramebuffer(gl.FRAMEBUFFER, null);

    var pixels = new Uint8Array(w * h * 4);
    gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, pixels);

    // flip pixels
    for(var j = 0, k = h - 1; j < k; ++j, --k) {
        for(var i = 0; i < w; ++i) {
            for(var l = 0; l < 4; ++l) {
                var tmp = pixels[4 * (w * j + i) + l];
                pixels[4 * (w * j + i) + l] = pixels[4 * (w * k + i) + l];
                pixels[4 * (w * k + i) + l] = tmp;
            }
        }
    }

    var canvas = document.createElement('canvas');
    canvas.width = w;
    canvas.height = h;

    var context = canvas.getContext('2d');
    var imageData = context.createImageData(w, h);
    imageData.data.set(pixels);
    context.putImageData(imageData, 0, 0);

    var dataURL;

    switch(format) {
        case 'jpeg':
            dataURL = canvas.toDataURL('image/jpeg');
            break;
        case 'webp':
            dataURL = canvas.toDataURL('image/webp');
            break;
        default:
            dataURL = canvas.toDataURL('image/png');
    }

    if(this.staticPlot) this.container.removeChild(STATIC_CANVAS);

    return dataURL;
};

proto.updateSize = function(canvas) {
    if(!canvas) canvas = this.canvas;

    var pixelRatio = this.pixelRatio;
    var fullLayout = this.fullLayout;

    var width = fullLayout.width;
    var height = fullLayout.height;
    var pixelWidth = Math.ceil(pixelRatio * width) |0;
    var pixelHeight = Math.ceil(pixelRatio * height) |0;

    // check for resize
    if(canvas.width !== pixelWidth || canvas.height !== pixelHeight) {
        canvas.width = pixelWidth;
        canvas.height = pixelHeight;
    }

    return canvas;
};

proto.computeTickMarks = function() {
    this.xaxis.setScale();
    this.yaxis.setScale();

    var nextTicks = [
        Axes.calcTicks(this.xaxis),
        Axes.calcTicks(this.yaxis)
    ];

    for(var j = 0; j < 2; ++j) {
        for(var i = 0; i < nextTicks[j].length; ++i) {
            // coercing tick value (may not be a string) to a string
            nextTicks[j][i].text = nextTicks[j][i].text + '';
        }
    }

    return nextTicks;
};

function compareTicks(a, b) {
    for(var i = 0; i < 2; ++i) {
        var aticks = a[i];
        var bticks = b[i];

        if(aticks.length !== bticks.length) return true;

        for(var j = 0; j < aticks.length; ++j) {
            if(aticks[j].x !== bticks[j].x) return true;
        }
    }

    return false;
}

proto.updateRefs = function(newFullLayout) {
    this.fullLayout = newFullLayout;

    var spmatch = this.id.match(SUBPLOT_PATTERN);
    var xaxisName = 'xaxis' + spmatch[1];
    var yaxisName = 'yaxis' + spmatch[2];

    this.xaxis = this.fullLayout[xaxisName];
    this.yaxis = this.fullLayout[yaxisName];
};

proto.relayoutCallback = function() {
    var graphDiv = this.graphDiv;
    var xaxis = this.xaxis;
    var yaxis = this.yaxis;
    var layout = graphDiv.layout;

    // make a meaningful value to be passed on to possible 'plotly_relayout' subscriber(s)
    var update = {};
    var xrange = update[xaxis._name + '.range'] = xaxis.range.slice();
    var yrange = update[yaxis._name + '.range'] = yaxis.range.slice();
    update[xaxis._name + '.autorange'] = xaxis.autorange;
    update[yaxis._name + '.autorange'] = yaxis.autorange;

    Registry.call('_storeDirectGUIEdit', graphDiv.layout, graphDiv._fullLayout._preGUI, update);

    // update the input layout
    var xaIn = layout[xaxis._name];
    xaIn.range = xrange;
    xaIn.autorange = xaxis.autorange;

    var yaIn = layout[yaxis._name];
    yaIn.range = yrange;
    yaIn.autorange = yaxis.autorange;

    // lastInputTime helps determine which one is the latest input (if async)
    update.lastInputTime = this.camera.lastInputTime;
    graphDiv.emit('plotly_relayout', update);
};

proto.cameraChanged = function() {
    var camera = this.camera;

    this.glplot.setDataBox(this.calcDataBox());

    var nextTicks = this.computeTickMarks();
    var curTicks = this.glplotOptions.ticks;

    if(compareTicks(nextTicks, curTicks)) {
        this.glplotOptions.ticks = nextTicks;
        this.glplotOptions.dataBox = camera.dataBox;
        this.glplot.update(this.glplotOptions);
        this.handleAnnotations();
    }
};

proto.handleAnnotations = function() {
    var gd = this.graphDiv;
    var annotations = this.fullLayout.annotations;

    for(var i = 0; i < annotations.length; i++) {
        var ann = annotations[i];

        if(ann.xref === this.xaxis._id && ann.yref === this.yaxis._id) {
            Registry.getComponentMethod('annotations', 'drawOne')(gd, i);
        }
    }
};

proto.destroy = function() {
    if(!this.glplot) return;

    var traces = this.traces;

    if(traces) {
        Object.keys(traces).map(function(key) {
            traces[key].dispose();
            delete traces[key];
        });
    }

    this.glplot.dispose();

    this.container.removeChild(this.svgContainer);
    this.container.removeChild(this.mouseContainer);

    this.fullData = null;
    this.glplot = null;
    this.stopped = true;
    this.camera.mouseListener.enabled = false;
    this.mouseContainer.removeEventListener('wheel', this.camera.wheelListener);
    this.camera = null;
};

proto.plot = function(fullData, calcData, fullLayout) {
    var glplot = this.glplot;

    this.updateRefs(fullLayout);
    this.xaxis.clearCalc();
    this.yaxis.clearCalc();
    this.updateTraces(fullData, calcData);
    this.updateFx(fullLayout.dragmode);

    var width = fullLayout.width;
    var height = fullLayout.height;

    this.updateSize(this.canvas);

    var options = this.glplotOptions;
    options.merge(fullLayout);
    options.screenBox = [0, 0, width, height];

    var mockGraphDiv = {_fullLayout: {
        _axisConstraintGroups: fullLayout._axisConstraintGroups,
        xaxis: this.xaxis,
        yaxis: this.yaxis,
        _size: fullLayout._size
    }};

    cleanAxisConstraints(mockGraphDiv, this.xaxis);
    cleanAxisConstraints(mockGraphDiv, this.yaxis);

    var size = fullLayout._size;
    var domainX = this.xaxis.domain;
    var domainY = this.yaxis.domain;

    options.viewBox = [
        size.l + domainX[0] * size.w,
        size.b + domainY[0] * size.h,
        (width - size.r) - (1 - domainX[1]) * size.w,
        (height - size.t) - (1 - domainY[1]) * size.h
    ];

    this.mouseContainer.style.width = size.w * (domainX[1] - domainX[0]) + 'px';
    this.mouseContainer.style.height = size.h * (domainY[1] - domainY[0]) + 'px';
    this.mouseContainer.height = size.h * (domainY[1] - domainY[0]);
    this.mouseContainer.style.left = size.l + domainX[0] * size.w + 'px';
    this.mouseContainer.style.top = size.t + (1 - domainY[1]) * size.h + 'px';

    var ax, i;

    for(i = 0; i < 2; ++i) {
        ax = this[AXES[i]];
        ax._length = options.viewBox[i + 2] - options.viewBox[i];

        doAutoRange(this.graphDiv, ax);
        ax.setScale();
    }

    enforceAxisConstraints(mockGraphDiv);

    options.ticks = this.computeTickMarks();

    options.dataBox = this.calcDataBox();

    options.merge(fullLayout);
    glplot.update(options);

    // force redraw so that promise is returned when rendering is completed
    this.glplot.draw();
};

proto.calcDataBox = function() {
    var xaxis = this.xaxis;
    var yaxis = this.yaxis;
    var xrange = xaxis.range;
    var yrange = yaxis.range;
    var xr2l = xaxis.r2l;
    var yr2l = yaxis.r2l;

    return [xr2l(xrange[0]), yr2l(yrange[0]), xr2l(xrange[1]), yr2l(yrange[1])];
};

proto.setRanges = function(dataBox) {
    var xaxis = this.xaxis;
    var yaxis = this.yaxis;
    var xl2r = xaxis.l2r;
    var yl2r = yaxis.l2r;

    xaxis.range = [xl2r(dataBox[0]), xl2r(dataBox[2])];
    yaxis.range = [yl2r(dataBox[1]), yl2r(dataBox[3])];
};

proto.updateTraces = function(fullData, calcData) {
    var traceIds = Object.keys(this.traces);
    var i, j, fullTrace;

    this.fullData = fullData;

    // remove empty traces
    traceIdLoop:
    for(i = 0; i < traceIds.length; i++) {
        var oldUid = traceIds[i];
        var oldTrace = this.traces[oldUid];

        for(j = 0; j < fullData.length; j++) {
            fullTrace = fullData[j];

            if(fullTrace.uid === oldUid && fullTrace.type === oldTrace.type) {
                continue traceIdLoop;
            }
        }

        oldTrace.dispose();
        delete this.traces[oldUid];
    }

    // update / create trace objects
    for(i = 0; i < fullData.length; i++) {
        fullTrace = fullData[i];
        var calcTrace = calcData[i];
        var traceObj = this.traces[fullTrace.uid];

        if(traceObj) traceObj.update(fullTrace, calcTrace);
        else {
            traceObj = fullTrace._module.plot(this, fullTrace, calcTrace);
            this.traces[fullTrace.uid] = traceObj;
        }
    }

    // order object per traces
    this.glplot.objects.sort(function(a, b) {
        return a._trace.index - b._trace.index;
    });
};

proto.updateFx = function(dragmode) {
    // switch to svg interactions in lasso/select mode & shape drawing
    if(selectMode(dragmode) || drawMode(dragmode)) {
        this.pickCanvas.style['pointer-events'] = 'none';
        this.mouseContainer.style['pointer-events'] = 'none';
    } else {
        this.pickCanvas.style['pointer-events'] = 'auto';
        this.mouseContainer.style['pointer-events'] = 'auto';
    }

    // set proper cursor
    if(dragmode === 'pan') {
        this.mouseContainer.style.cursor = 'move';
    } else if(dragmode === 'zoom') {
        this.mouseContainer.style.cursor = 'crosshair';
    } else {
        this.mouseContainer.style.cursor = null;
    }
};

proto.emitPointAction = function(nextSelection, eventType) {
    var uid = nextSelection.trace.uid;
    var ptNumber = nextSelection.pointIndex;
    var trace;

    for(var i = 0; i < this.fullData.length; i++) {
        if(this.fullData[i].uid === uid) {
            trace = this.fullData[i];
        }
    }

    var pointData = {
        x: nextSelection.traceCoord[0],
        y: nextSelection.traceCoord[1],
        curveNumber: trace.index,
        pointNumber: ptNumber,
        data: trace._input,
        fullData: this.fullData,
        xaxis: this.xaxis,
        yaxis: this.yaxis
    };

    Fx.appendArrayPointValue(pointData, trace, ptNumber);

    this.graphDiv.emit(eventType, {points: [pointData]});
};

proto.draw = function() {
    if(this.stopped) return;

    requestAnimationFrame(this.redraw);

    var glplot = this.glplot;
    var camera = this.camera;
    var mouseListener = camera.mouseListener;
    var mouseUp = this.lastButtonState === 1 && mouseListener.buttons === 0;
    var fullLayout = this.fullLayout;

    this.lastButtonState = mouseListener.buttons;

    this.cameraChanged();

    var x = mouseListener.x * glplot.pixelRatio;
    var y = this.canvas.height - glplot.pixelRatio * mouseListener.y;

    var result;

    if(camera.boxEnabled && fullLayout.dragmode === 'zoom') {
        this.selectBox.enabled = true;

        var selectBox = this.selectBox.selectBox = [
            Math.min(camera.boxStart[0], camera.boxEnd[0]),
            Math.min(camera.boxStart[1], camera.boxEnd[1]),
            Math.max(camera.boxStart[0], camera.boxEnd[0]),
            Math.max(camera.boxStart[1], camera.boxEnd[1])
        ];

        // 1D zoom
        for(var i = 0; i < 2; i++) {
            if(camera.boxStart[i] === camera.boxEnd[i]) {
                selectBox[i] = glplot.dataBox[i];
                selectBox[i + 2] = glplot.dataBox[i + 2];
            }
        }

        glplot.setDirty();
    } else if(!camera.panning && this.isMouseOver) {
        this.selectBox.enabled = false;

        var size = fullLayout._size;
        var domainX = this.xaxis.domain;
        var domainY = this.yaxis.domain;

        result = glplot.pick(
            (x / glplot.pixelRatio) + size.l + domainX[0] * size.w,
            (y / glplot.pixelRatio) - (size.t + (1 - domainY[1]) * size.h)
        );

        var nextSelection = result && result.object._trace.handlePick(result);

        if(nextSelection && mouseUp) {
            this.emitPointAction(nextSelection, 'plotly_click');
        }

        if(result && result.object._trace.hoverinfo !== 'skip' && fullLayout.hovermode) {
            if(nextSelection && (
                !this.lastPickResult ||
                this.lastPickResult.traceUid !== nextSelection.trace.uid ||
                this.lastPickResult.dataCoord[0] !== nextSelection.dataCoord[0] ||
                this.lastPickResult.dataCoord[1] !== nextSelection.dataCoord[1])
            ) {
                var selection = nextSelection;

                this.lastPickResult = {
                    traceUid: nextSelection.trace ? nextSelection.trace.uid : null,
                    dataCoord: nextSelection.dataCoord.slice()
                };
                this.spikes.update({ center: result.dataCoord });

                selection.screenCoord = [
                    ((glplot.viewBox[2] - glplot.viewBox[0]) *
                    (result.dataCoord[0] - glplot.dataBox[0]) /
                        (glplot.dataBox[2] - glplot.dataBox[0]) + glplot.viewBox[0]) /
                            glplot.pixelRatio,
                    (this.canvas.height - (glplot.viewBox[3] - glplot.viewBox[1]) *
                    (result.dataCoord[1] - glplot.dataBox[1]) /
                        (glplot.dataBox[3] - glplot.dataBox[1]) - glplot.viewBox[1]) /
                            glplot.pixelRatio
                ];

                // this needs to happen before the next block that deletes traceCoord data
                // also it's important to copy, otherwise data is lost by the time event data is read
                this.emitPointAction(nextSelection, 'plotly_hover');

                var trace = this.fullData[selection.trace.index] || {};
                var ptNumber = selection.pointIndex;
                var hoverinfo = Fx.castHoverinfo(trace, fullLayout, ptNumber);

                if(hoverinfo && hoverinfo !== 'all') {
                    var parts = hoverinfo.split('+');
                    if(parts.indexOf('x') === -1) selection.traceCoord[0] = undefined;
                    if(parts.indexOf('y') === -1) selection.traceCoord[1] = undefined;
                    if(parts.indexOf('z') === -1) selection.traceCoord[2] = undefined;
                    if(parts.indexOf('text') === -1) selection.textLabel = undefined;
                    if(parts.indexOf('name') === -1) selection.name = undefined;
                }

                Fx.loneHover({
                    x: selection.screenCoord[0],
                    y: selection.screenCoord[1],
                    xLabel: this.hoverFormatter('xaxis', selection.traceCoord[0]),
                    yLabel: this.hoverFormatter('yaxis', selection.traceCoord[1]),
                    zLabel: selection.traceCoord[2],
                    text: selection.textLabel,
                    name: selection.name,
                    color: Fx.castHoverOption(trace, ptNumber, 'bgcolor') || selection.color,
                    borderColor: Fx.castHoverOption(trace, ptNumber, 'bordercolor'),
                    fontFamily: Fx.castHoverOption(trace, ptNumber, 'font.family'),
                    fontSize: Fx.castHoverOption(trace, ptNumber, 'font.size'),
                    fontColor: Fx.castHoverOption(trace, ptNumber, 'font.color'),
                    nameLength: Fx.castHoverOption(trace, ptNumber, 'namelength'),
                    textAlign: Fx.castHoverOption(trace, ptNumber, 'align')
                }, {
                    container: this.svgContainer,
                    gd: this.graphDiv
                });
            }
        }
    }

    // Remove hover effects if we're not over a point OR
    // if we're zooming or panning (in which case result is not set)
    if(!result) {
        this.unhover();
    }

    glplot.draw();
};

proto.unhover = function() {
    if(this.lastPickResult) {
        this.spikes.update({});
        this.lastPickResult = null;
        this.graphDiv.emit('plotly_unhover');
        Fx.loneUnhover(this.svgContainer);
    }
};

proto.hoverFormatter = function(axisName, val) {
    if(val === undefined) return undefined;

    var axis = this[axisName];
    return Axes.tickText(axis, axis.c2l(val), 'hover').text;
};