text:
package org.springframework.boot.jdbc;

import org.junit.jupiter.api.Test;

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

/**
 * Tests for {@link DatabaseDriver}.
 *
 * @author Phillip Webb
 * @author Maciej Walkowiak
 * @author Stephane Nicoll
 */
class DatabaseDriverTests {

	@Test
	void classNameForKnownDatabase() {
		String driverClassName = DatabaseDriver.fromJdbcUrl("jdbc:postgresql://hostname/dbname").getDriverClassName();
		assertThat(driverClassName).isEqualTo("org.postgresql.Driver");
	}

	@Test
	void nullClassNameForUnknownDatabase() {
		String driverClassName = DatabaseDriver.fromJdbcUrl("jdbc:unknowndb://hostname/dbname").getDriverClassName();
		assertThat(driverClassName).isNull();
	}

	@Test
	void unknownOnNullJdbcUrl() {
		DatabaseDriver actual = DatabaseDriver.fromJdbcUrl(null);
		assertThat(actual).isEqualTo(DatabaseDriver.UNKNOWN);
	}

	@Test
	void failureOnMalformedJdbcUrl() {
		assertThatIllegalArgumentException().isThrownBy(() -> DatabaseDriver.fromJdbcUrl("malformed:url"))
				.withMessageContaining("URL must start with");
	}

	@Test
	void unknownOnNullProductName() {
		DatabaseDriver actual = DatabaseDriver.fromProductName(null);
		assertThat(actual).isEqualTo(DatabaseDriver.UNKNOWN);
	}

	@Test
	void databaseProductNameLookups() {
		assertThat(DatabaseDriver.fromProductName("newone")).isEqualTo(DatabaseDriver.UNKNOWN);
		assertThat(DatabaseDriver.fromProductName("Apache Derby")).isEqualTo(DatabaseDriver.DERBY);
		assertThat(DatabaseDriver.fromProductName("H2")).isEqualTo(DatabaseDriver.H2);
		assertThat(DatabaseDriver.fromProductName("HDB")).isEqualTo(DatabaseDriver.HANA);
		assertThat(DatabaseDriver.fromProductName("HSQL Database Engine")).isEqualTo(DatabaseDriver.HSQLDB);
		assertThat(DatabaseDriver.fromProductName("SQLite")).isEqualTo(DatabaseDriver.SQLITE);
		assertThat(DatabaseDriver.fromProductName("MySQL")).isEqualTo(DatabaseDriver.MYSQL);
		assertThat(DatabaseDriver.fromProductName("Oracle")).isEqualTo(DatabaseDriver.ORACLE);
		assertThat(DatabaseDriver.fromProductName("PostgreSQL")).isEqualTo(DatabaseDriver.POSTGRESQL);
		assertThat(DatabaseDriver.fromProductName("Amazon Redshift")).isEqualTo(DatabaseDriver.REDSHIFT);
		assertThat(DatabaseDriver.fromProductName("Microsoft SQL Server")).isEqualTo(DatabaseDriver.SQLSERVER);
		assertThat(DatabaseDriver.fromProductName("SQL SERVER")).isEqualTo(DatabaseDriver.SQLSERVER);
		assertThat(DatabaseDriver.fromProductName("DB2")).isEqualTo(DatabaseDriver.DB2);
		assertThat(DatabaseDriver.fromProductName("Firebird 2.5.WI")).isEqualTo(DatabaseDriver.FIREBIRD);
		assertThat(DatabaseDriver.fromProductName("Firebird 2.1.LI")).isEqualTo(DatabaseDriver.FIREBIRD);
		assertThat(DatabaseDriver.fromProductName("DB2/LINUXX8664")).isEqualTo(DatabaseDriver.DB2);
		assertThat(DatabaseDriver.fromProductName("DB2 UDB for AS/400")).isEqualTo(DatabaseDriver.DB2_AS400);
		assertThat(DatabaseDriver.fromProductName("DB3 XDB for AS/400")).isEqualTo(DatabaseDriver.DB2_AS400);
		assertThat(DatabaseDriver.fromProductName("Teradata")).isEqualTo(DatabaseDriver.TERADATA);
		assertThat(DatabaseDriver.fromProductName("Informix Dynamic Server")).isEqualTo(DatabaseDriver.INFORMIX);
	}

	@Test
	void databaseJdbcUrlLookups() {
		assertThat(DatabaseDriver.fromJdbcUrl("jdbc:newone://localhost")).isEqualTo(DatabaseDriver.UNKNOWN);
		assertThat(DatabaseDriver.fromJdbcUrl("jdbc:derby:sample")).isEqualTo(DatabaseDriver.DERBY);
		assertThat(DatabaseDriver.fromJdbcUrl("jdbc:h2:~/sample")).isEqualTo(DatabaseDriver.H2);
		assertThat(DatabaseDriver.fromJdbcUrl("jdbc:hsqldb:hsql://localhost")).isEqualTo(DatabaseDriver.HSQLDB);
		assertThat(DatabaseDriver.fromJdbcUrl("jdbc:sqlite:sample.db")).isEqualTo(DatabaseDriver.SQLITE);
		assertThat(DatabaseDriver.fromJdbcUrl("jdbc:mysql://localhost:3306/sample")).isEqualTo(DatabaseDriver.MYSQL);
		assertThat(DatabaseDriver.fromJdbcUrl("jdbc:oracle:thin:@localhost:1521:orcl"))
				.isEqualTo(DatabaseDriver.ORACLE);
		assertThat(DatabaseDriver.fromJdbcUrl("jdbc:postgresql://127.0.0.1:5432/sample"))
				.isEqualTo(DatabaseDriver.POSTGRESQL);
		assertThat(DatabaseDriver.fromJdbcUrl(
				"jdbc:redshift://examplecluster.abc123xyz789.us-west-2.redshift.amazonaws.com:5439/sample"))
						.isEqualTo(DatabaseDriver.REDSHIFT);
		assertThat(DatabaseDriver.fromJdbcUrl("jdbc:jtds:sqlserver://127.0.0.1:1433/sample"))
				.isEqualTo(DatabaseDriver.JTDS);
		assertThat(DatabaseDriver.fromJdbcUrl("jdbc:sap:localhost")).isEqualTo(DatabaseDriver.HANA);
		assertThat(DatabaseDriver.fromJdbcUrl("jdbc:sqlserver://127.0.0.1:1433")).isEqualTo(DatabaseDriver.SQLSERVER);
		assertThat(DatabaseDriver.fromJdbcUrl("jdbc:firebirdsql://localhost/sample"))
				.isEqualTo(DatabaseDriver.FIREBIRD);
		assertThat(DatabaseDriver.fromJdbcUrl("jdbc:firebird://localhost/sample")).isEqualTo(DatabaseDriver.FIREBIRD);
		assertThat(DatabaseDriver.fromJdbcUrl("jdbc:db2://localhost:50000/sample ")).isEqualTo(DatabaseDriver.DB2);
		assertThat(DatabaseDriver.fromJdbcUrl("jdbc:as400://localhost")).isEqualTo(DatabaseDriver.DB2_AS400);
		assertThat(DatabaseDriver.fromJdbcUrl("jdbc:teradata://localhost/SAMPLE")).isEqualTo(DatabaseDriver.TERADATA);
		assertThat(DatabaseDriver.fromJdbcUrl("jdbc:informix-sqli://localhost:1533/sample"))
				.isEqualTo(DatabaseDriver.INFORMIX);
		assertThat(DatabaseDriver.fromJdbcUrl("jdbc:informix-direct://sample")).isEqualTo(DatabaseDriver.INFORMIX);
	}

}


text:
{% extends "content_base.html" %}

{% load bootstrap_tags %}
{% load i18n %}

{% block head_title %}About Sponsorship{% endblock %}

{% block one_column %}

{% trans "About Sponsorship" %}

{% trans "ABOUT_SPONSORSHIP" %}

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
require 'chef/knife/vault_base'

class Chef
  class Knife
    class VaultRotateAllKeys < Knife

      include Chef::Knife::VaultBase

      banner "knife vault rotate all keys"

      def run
        set_mode(config[:vault_mode])
        rotate_all_keys
      end

      private

      def rotate_all_keys
        vaults = Chef::DataBag.list.keys
        vaults.each { |vault| rotate_vault_keys(vault) }
      end

      def rotate_vault_keys(vault)
        vault_items(vault).each do |item|
          rotate_vault_item_keys(vault, item)
        end
      end

      def vault_items(vault)
        Chef::DataBag.load(vault).keys.inject([]) do |array, key|
          array << key.sub('_keys', '') if key.match(/.+_keys$/)
          array
        end
      end

      def rotate_vault_item_keys(vault, item)
        puts "Rotating keys for: #{vault} #{item}"
        ChefVault::Item.load(vault, item).rotate_keys!
      end
    end
  end
end


text:
// Copyright 2020 Google LLC

package com.google.gcp_variant_transforms.library;

import com.google.common.collect.ImmutableList;
import htsjdk.variant.vcf.VCFCodec;
import java.io.Serializable;

import htsjdk.tribble.readers.LineIterator;

/**
 * Custom Iterator for {@link VCFCodec}.
 */
public class HeaderIterator implements LineIterator, Serializable {
  private static final long serialVersionUID = 60231493676096593L;
  private final ImmutableList<String> headerLines;
  private int currentIndex;

  public HeaderIterator(ImmutableList<String> headerLines) {
    this.headerLines = headerLines;
    this.currentIndex = 0;
  }

  @Override
  public boolean hasNext() {
    return currentIndex < headerLines.size();
  }

  @Override
  public String next() {
    return headerLines.get(currentIndex++);
  }

  @Override
  public String peek() {
    return headerLines.get(currentIndex);
  }
}


text:
package automl_test

import (
	"context"

	automl "cloud.google.com/go/automl/apiv1beta1"
	automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1"
)

func ExampleNewPredictionClient() {
	ctx := context.Background()
	c, err := automl.NewPredictionClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use client.
	_ = c
}

func ExamplePredictionClient_Predict() {
	ctx := context.Background()
	c, err := automl.NewPredictionClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}

	req := &automlpb.PredictRequest{
		// TODO: Fill request struct fields.
	}
	resp, err := c.Predict(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

func ExamplePredictionClient_BatchPredict() {
	ctx := context.Background()
	c, err := automl.NewPredictionClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}

	req := &automlpb.BatchPredictRequest{
		// TODO: Fill request struct fields.
	}
	op, err := c.BatchPredict(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}

	resp, err := op.Wait(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}


text:
package net.glowstone.block.blocktype;

import java.util.Arrays;
import java.util.Collection;
import net.glowstone.block.GlowBlock;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;

public class BlockDirt extends BlockType {

    @Override
    public Collection<ItemStack> getDrops(GlowBlock block, ItemStack tool) {
        //TODO switch to MaterialData instead of using magic values
        if (block.getData() == 1) {
            //Coarse dirt
            return Arrays.asList(new ItemStack(Material.DIRT, 1, (short) 1));
        } else {
            //normal dirt and podzol drop normal dirt
            return Arrays.asList(new ItemStack(Material.DIRT));
        }
    }
}


text:
template<typename T> void f(T t) {
  auto a = t.x;
  decltype(auto) b = t.x;
  auto c = (t.x);
  decltype(auto) d = (t.x);
}

#else

struct Z {
  int x : 5; // expected-note {{bit-field}}
};

// expected-error@12 {{non-const reference cannot bind to bit-field 'x'}}
template void f(Z); // expected-note {{in instantiation of}}

#endif


text: Spring Rest Endpoints Documentation Generator


text:
import { RouterModule } from '@angular/router';
import { DefaultComponent } from './components/default.component';
var routes = [
    { path: 'default', component: DefaultComponent }
];
export var DefaultRoutes = RouterModule.forChild(routes);
//# sourceMappingURL=default.routes.js.map


text:
ActiveRecord::Base.transaction do
  MailTemplate.create!(
    subject: 'Welcome [[User - Name]]!',
    body: %Q(
      Welcome [[User - Name]] to our platform!

      Click here if you don't wish to receive emails.
    ),
    mailer_name: 'sample_mailer',
    method_name: 'welcome_mail',
    locale: :en
  )

  MailTemplate.create!(
    subject: 'Bem vindo [[Usuário - Nome]]!',
    body: %Q(
      Bem vindo [[Usuário - Nome]]!

      Clique aqui para cancelar o recebimento de emails.
    ),
    mailer_name: 'sample_mailer',
    method_name: 'welcome_mail',
    locale: :'pt-br'
  )
end


text:
dbsync
======

PHP Mysql Database Syncing Class

This class allows you to be able to set php files to establish what database changes need to happen to your local database copy.
Primary use is for groups of people who use version control systems(like git) to maintain projects,
but want keep a local database copy for testing.

Installation and Setup

Settings

Open up dbsync.php file:

Set database variable to desired database

Set other class variables if you need to change them from current value - recommended to leave as is

Files Structure

Unless changed all database files are in dbtables folder

_tables.php is your primary table for setting all the database tables you need.

In the _tables.php file is a $tables assoc array that contains table(key) and a value(array)

							Example:

							$_tables = array(

							    'table1' => array('notes' => 'Here are some notes about this table'),

							    'table2' => array(),

							    'table3' => array()

							);

    				Each table may have a notes variable in array if desired to set notes for that table

    				Ex: 'table' => array('notes' => 'Here are some notes about this table')

			Dbsync runs through each key in $_tables array and looks for the correspoding ${key}.php file.

			Ex: If key = 'table1' dbsync will look for table1.php files for that tables columns.

			In each tables file there should be a ${table}_columns array

			Ex: Inside the table1.php file should be a $table1_columns array

Column Settings

In each table file the main array will consist of the key(column name) and value(list of possible column attributes)

Ex:

			'{columnname}' => array(

			    'type' => 'INT', // Type of column - NOT case sensative anymore

			    'constraint' => 11, // Optional - Constraint for type - Ex: INT(11) or DECIMAL(10,2)

			    'default' => '{defaultvalue}', // Optional - Default value if inset is null or non existant

			    'primary' => false, // Optional - Default is false - Indicates whether or not column is a primary

			    'index' => false, // Optional - Default is false - Indicates whether or not column is indexed

			    'unique' => false, // Optional - Default is false - Indicates whether or not column is a unique index

			    'auto_increment' => false, // Optional - Default is false - Indicates whether or not column is auto_incremented to next number

			    'null' => false // Optional - Default is false - Indicates whether or not column can be null

			    'on_update_time' => false // Optional - Default is false - Whether or not to update on row modification

			    'extra' => {attribute value} // Optional - BINARY, UNSIGNED or UNSIGNED ZEROFILL

			)


text:
<?php
App::uses('Component', 'Controller');
App::uses('Program', 'Model');
App::uses('ProgramSetting', 'Model');
App::uses('ProgramSpecificMongoModel', 'Model');

class StatsComponent extends Component
{

    public $Controller = null;

    var $components          = array('Redis');
    var $localizedValueLabel = array();

    public function __construct(ComponentCollection $collection, $settings = array())
    {
        $this->localizedValueLabel = array(
            'scheduled' => __('scheduled'),
            'sent' => __('sent'),
            'received' => __('received'),
            'message(s)' => __('message(s)'),
            'participant(s)' => __('participant(s)'),
            'Participant(s) Optin/Total' => __('Participant(s) Optin/Total'),
            'Message(s)-Total(Current-Month)' => __('Message(s) Total(Current Month)'),
            'Received Total(Current Month)' => __('Received Total(Current Month)'),
            'Sent Total(Current Month)' => __('Sent Total(Current Month)'),
            'Schedule Total(Today)' => __('Schedule Total(Today)'),
            'total message(s)' => __('total message(s)'),
            'sent message(s)' => __('sent message(s)'),
            'schedule(s)' => __('schedule(s)'),
            'Optin/Total participant(s)' => __('Optin/Total participant(s)'),
            'Total(total current month) message(s)' => __('Total(total current month) message(s)'),
            'Total(current month) received' => __('Total(current month) received'),
            'Total(current month) sent' => __('Total(current month) sent'),
            'Total(today) schedule(s)' => __('Total(today) schedule(s)'),
            'Stats Not Available' => __('Stats Not Available'),
            );
        //$this->Controller = $collection->getController();
        parent::__construct($collection, $settings);
    }

    public function startup(Controller $controller)
    {
        parent::startup($controller);
        $this->Controller = $controller;
        $this->cacheStatsExpire = Configure::read('vusion.cacheStatsExpire');
        if ($this->cacheStatsExpire == null) {
            //A default value for all
            $this->cacheStatsExpire = array(
                '1000' => '120');
        }

        /*if(isset($this->Controller->redis)){
            $this->redis = $this->Controller->redis;
        }else{
            $this->redis = new Redis();
            $this->redis->connect('127.0.0.1');
        }

        if(isset($this->Controller->redisProgramPrefix)){
            $this->redisProgramPrefix = $this->Controller->redisProgramPrefix;
        }else{
            $this->redisProgramPrefix = 'vusion:programs';
        }*/

        $this->Controller->set('statsLabels', $this->localizedValueLabel);
    }

    public function getProgramStat($model, $conditions=array())
    {
        try {
            return $model->count($conditions);
        } catch (Exception $e) {
            return 'N/A';
        }
    }

    protected function _getProgramStats($database)
    {
        $programStats = array(
            'active-participant-count' => 'N/A',
            'participant-count' => 'N/A',
            'all-received-messages-count'=> 'N/A',
            'current-month-received-messages-count' => 'N/A',
            'all-sent-messages-count' => 'N/A',
            'current-month-sent-messages-count' => 'N/A',
            'total-current-month-messages-count' => 'N/A',
            'history-count' => 'N/A',
            'today-schedule-count' => 'N/A',
            'schedule-count' => 'N/A',
            'object-type' => 'program-stats',
            'model-version'=> '1');

        $tempProgramSetting = ProgramSpecificMongoModel::init('ProgramSetting', $database);
        $programTimeNow = $tempProgramSetting->getProgramTimeNow();
        if(empty($programTimeNow)){
            return $programStats;
        }
        $tempParticipant = ProgramSpecificMongoModel::init('Participant', $database);
        $programStats['active-participant-count'] = $this->getProgramStat(
            $tempParticipant,
            array('session-id' => array('$ne' => null)));

        $programStats['participant-count'] = $this->getProgramStat($tempParticipant);

        $tempSchedule = ProgramSpecificMongoModel::init('Schedule', $database);
        $programTimeToday = $programTimeNow->modify('+1 day');
        $programStats['today-schedule-count'] = $this->getProgramStat(
            $tempSchedule,
            array('date-time' => array('$lt' => $programTimeToday->format(DateTime::ISO8601))));

        $programStats['schedule-count'] = $this->getProgramStat($tempSchedule);

        $tempHistory = ProgramSpecificMongoModel::init('History', $database);
        $programTimeForMonth = $programTimeNow->format("Y-m-d\TH:i:s");
        $first_second = date('Y-m-01\TH:i:s', strtotime($programTimeForMonth));
        $last_second = date('Y-m-t\TH:i:s', strtotime($programTimeForMonth));
        $programStats['all-received-messages-count'] = $this->getProgramStat(
            $tempHistory,
            array('message-direction' => 'incoming'));

        $programStats['current-month-received-messages-count'] = $this->getProgramStat(
            $tempHistory,
            array(
                'timestamp' => array(
                    '$gt' => $first_second,
                    '$lt' => $last_second),
                'message-direction' => 'incoming'));

        $programStats['current-month-sent-messages-count'] = $this->getProgramStat(
            $tempHistory,
            array(
                'timestamp' => array(
                    '$gt' => $first_second,
                    '$lt' => $last_second
                    ),
                'message-direction' => 'outgoing'));

        if($programStats['current-month-sent-messages-count'] === 'N/A' || $programStats['current-month-received-messages-count'] === 'N/A' ){
            $totalCurrentMonthMessagesCount = 'N/A';
        } else {
            $totalCurrentMonthMessagesCount =  $programStats['current-month-sent-messages-count'] + $programStats['current-month-received-messages-count'];
        }
        $programStats['total-current-month-messages-count'] = $totalCurrentMonthMessagesCount;

        $programStats['all-sent-messages-count'] = $this->getProgramStat(
            $tempHistory,
            array('message-direction' => 'outgoing'));

        $programStats['history-count'] = $this->getProgramStat(
            $tempHistory,
            array(
                '$or' => array(
                    array('object-type' => array('$in' => $tempHistory->messageType)),
                    array('object-type' => array('$exists' => false ))
                    )));

        unset($tempProgramSetting);
        unset($tempParticipant);
        unset($tempHistory);
        unset($tempSchedule);
        return $programStats;
    }

    protected function _getStatsKey($database)
    {
        $redisProgramPrefix = $this->Redis->getProgramPrefix();
        return $redisProgramPrefix.':'.$database.':stats';
    }

    public function getProgramStats($database, $onlyCached=false)
    {
        $redis = $this->Redis->redisConnect();
        $statsKey = $this->_getStatsKey($database);
        $stats = $redis->get($statsKey);

        if ($stats != null) {
            return (array)json_decode($stats);
        }

        if ($onlyCached) {
            return  null;
        }

        $start = time();
        $programStats = $this->_getProgramStats($database);
        $end = time();
        $duration = $end - $start;
        $expiring = $this->_getTimeToCacheStatsExpire($duration);
        $redis->setex($statsKey, $expiring, json_encode($programStats));
        return $programStats;
    }

    public function _getTimeToCacheStatsExpire($duration)
    {
        foreach ($this->cacheStatsExpire as $computationDuration => $cacheDuration) {
            if ($duration <= $computationDuration) {
                return $cacheDuration;
            }
        }
        return end($this->cacheStatsExpire);
    }

    public function _getTimeframeCondition($database, $past=true)
    {
        $tmpProgramSetting = ProgramSpecificMongoModel::init('ProgramSetting', $database, true);
        $time = $tmpProgramSetting->getProgramTimeNow();
        $timeframe = 'week';
        if (isset($this->Controller->params['url']['for'])) {
            $timeframe = $this->Controller->params['url']['for'];
            if ($timeframe == 'ever') {
                return null;
            }
            if (in_array($timeframe, array('week', 'month', 'year'))) {
                $timeframe = $this->Controller->params['url']['for'];
            }
        }
        if ($past) {
            return $time->modify("-1 $timeframe")->format("Y-m-d");
        }
        return $time->modify("+1 $timeframe")->format("Y-m-d");
    }

    public function getStatsType()
    {
        if (isset($this->Controller->params['url']['stats_type'])) {
            $statsType = $this->Controller->params['url']['stats_type'];
            if (in_array($statsType, array('participants', 'history', 'schedules', 'top_dialogues_requests', 'summary'))) {
                return $statsType;
            }
        }
        return null;
    }

    public function getStats($database, $statsType)
    {
        switch ($statsType) {
            case 'summary':
                $stats = $this->getProgramStats($database);
                break;
            case 'participants':
                $date = $this->_getTimeframeCondition($database);
                $conditions = array();
                if ($date != null) {
                    $conditions = array('conditions' => array('_id' => array('$gte' => $date)));
                }
                $tmpParticipantStats = ProgramSpecificMongoModel::init('ParticipantStats', $database);
                $stats = $tmpParticipantStats->find('all', $conditions);
                break;
            case 'history':
                $date = $this->_getTimeframeCondition($database);
                $conditions = array();
                if ($date != null) {
                    $conditions = array('conditions' => array('_id' => array('$gte' => $date)));
                }
                $tmpHistoryStats = ProgramSpecificMongoModel::init('HistoryStats', $database);
                $stats = $tmpHistoryStats->find('all', $conditions);
                break;
            case 'schedules':
                $date = $this->_getTimeframeCondition($database, false);
                $tmpSchedule = ProgramSpecificMongoModel::init('Schedule', $database);
                $stats = $tmpSchedule->aggregateStats($date);
                break;
            case 'top_dialogues_requests':
                $date = $this->_getTimeframeCondition($database);
                $tmpHistory = ProgramSpecificMongoModel::init('History', $database);
                $tmpDialogue = ProgramSpecificMongoModel::init('Dialogue', $database);
                $tmpRequest = ProgramSpecificMongoModel::init('Request', $database);
                $dialogueActivities = $tmpHistory->getMostActive($date, 'dialogue-id', 'dialogue-id', 'count');
                $dialogueActivities = $tmpDialogue->fromDialogueIdsToNames($dialogueActivities);
                $requestActivities = $tmpHistory->getMostActive($date, 'request-id', 'request-id', 'count');
                $requestActivities = $tmpRequest->fromRequestIdsToKeywords($requestActivities);
                $stats = array(
                    array(
                        'key' => 'dialogue',
                        'values' => $dialogueActivities),
                    array(
                        'key' => 'request',
                        'values' => $requestActivities));
                break;
            default:
                $stats = array();
        }
        return $stats;
    }

}


text:
import pychrono as chrono
import pychrono.vehicle as veh
import pychrono.irrlicht as irr
import math as m

# =============================================================================

def main():
    #print("Copyright (c) 2017 projectchrono.org\nChrono version: ", CHRONO_VERSION , "\n\n")

    #  Create the HMMWV vehicle, set parameters, and initialize
    my_hmmwv = veh.HMMWV_Full()
    my_hmmwv.SetContactMethod(contact_method)
    my_hmmwv.SetChassisFixed(False)
    my_hmmwv.SetInitPosition(chrono.ChCoordsysD(initLoc, chrono.ChQuaternionD(1, 0, 0, 0)))
    my_hmmwv.SetPowertrainType(powertrain_model)
    my_hmmwv.SetDriveType(drive_type)
    my_hmmwv.SetSteeringType(steering_type)
    my_hmmwv.SetTireType(tire_model)
    my_hmmwv.SetTireStepSize(tire_step_size)
    my_hmmwv.Initialize()

    my_hmmwv.SetChassisVisualizationType(chassis_vis_type)
    my_hmmwv.SetSuspensionVisualizationType(suspension_vis_type)
    my_hmmwv.SetSteeringVisualizationType(steering_vis_type)
    my_hmmwv.SetWheelVisualizationType(wheel_vis_type)
    my_hmmwv.SetTireVisualizationType(tire_vis_type)

    # Create the terrain

    terrain = veh.RigidTerrain(my_hmmwv.GetSystem())
    if (contact_method == chrono.ChContactMethod_NSC):
        patch_mat = chrono.ChMaterialSurfaceNSC()
        patch_mat.SetFriction(0.9)
        patch_mat.SetRestitution(0.01)
    elif (contact_method == chrono.ChContactMethod_SMC):
        patch_mat = chrono.ChMaterialSurfaceSMC()
        patch_mat.SetFriction(0.9)
        patch_mat.SetRestitution(0.01)
        patch_mat.SetYoungModulus(2e7)
    patch = terrain.AddPatch(patch_mat,
                             chrono.CSYSNORM,
                             300, 50)
    patch.SetTexture(veh.GetDataFile("terrain/textures/tile4.jpg"), 200, 200)
    patch.SetColor(chrono.ChColor(0.8, 0.8, 0.5))
    terrain.Initialize()

    # Create the path-follower, cruise-control driver
    # Use a parameterized ISO double lane change (to left)
    path = veh.DoubleLaneChangePath(initLoc, 13.5, 4.0, 11.0, 50.0, True)
    driver = veh.ChPathFollowerDriver(my_hmmwv.GetVehicle(), path, "my_path", target_speed)
    driver.GetSteeringController().SetLookAheadDistance(5)
    driver.GetSteeringController().SetGains(0.8, 0, 0)
    driver.GetSpeedController().SetGains(0.4, 0, 0)
    driver.Initialize()

    # Create the vehicle Irrlicht interface
    vis = veh.ChWheeledVehicleVisualSystemIrrlicht()
    my_hmmwv.GetVehicle().SetVisualSystem(vis)
    vis.SetWindowTitle('HMMWV steering controller')
    vis.SetWindowSize(1280, 1024)
    vis.SetChaseCamera(chrono.ChVectorD(0.0, 0.0, 1.75), 6.0, 0.5)
    vis.Initialize()
    vis.AddLogo(chrono.GetChronoDataFile('logo_pychrono_alpha.png'))
    vis.AddTypicalLights()
    vis.AddSkyBox()

   	# Visualization of controller points (sentinel & target)
    ballS = vis.GetSceneManager().addSphereSceneNode(0.1);
    ballT = vis.GetSceneManager().addSphereSceneNode(0.1);
    ballS.getMaterial(0).EmissiveColor = irr.SColor(0, 255, 0, 0);
    ballT.getMaterial(0).EmissiveColor = irr.SColor(0, 0, 255, 0);

    # Simulation loop
    my_hmmwv.GetVehicle().EnableRealtime(True)

    while vis.Run() :
        time = my_hmmwv.GetSystem().GetChTime()

        # End simulation
        if (time >= t_end):
            break

        # Update sentinel and target location markers for the path-follower controller.
        pS = driver.GetSteeringController().GetSentinelLocation()
        pT = driver.GetSteeringController().GetTargetLocation()
        ballS.setPosition(irr.vector3df(pS.x, pS.y, pS.z))
        ballT.setPosition(irr.vector3df(pT.x, pT.y, pT.z))

        # Draw scene
        vis.BeginScene()
        vis.DrawAll()
        vis.EndScene()

        # Get driver inputs
        driver_inputs = driver.GetInputs()

        # Update modules (process inputs from other modules)
        driver.Synchronize(time)
        terrain.Synchronize(time)
        my_hmmwv.Synchronize(time, driver_inputs, terrain)
        vis.Synchronize("", driver_inputs)

        # Advance simulation for one timestep for all modules
        driver.Advance(step_size)
        terrain.Advance(step_size)
        my_hmmwv.Advance(step_size)
        vis.Advance(step_size)

    return 0

# The path to the Chrono data directory containing various assets (meshes, textures, data files)
# is automatically set, relative to the default location of this demo.
# If running from a different directory, you must change the path to the data directory with:
#chrono.SetChronoDataPath('path/to/data')
veh.SetDataPath(chrono.GetChronoDataPath() + 'vehicle/')

# Initial vehicle location
initLoc = chrono.ChVectorD(-50, 0, 0.7)

# Vehicle target speed (cruise-control)
target_speed = 12

# Visualization type for vehicle parts (PRIMITIVES, MESH, or NONE)
chassis_vis_type = veh.VisualizationType_NONE
suspension_vis_type =  veh.VisualizationType_PRIMITIVES
steering_vis_type = veh.VisualizationType_PRIMITIVES
wheel_vis_type = veh.VisualizationType_MESH
tire_vis_type = veh.VisualizationType_MESH

# Type of powertrain model (SHAFTS, SIMPLE)
powertrain_model = veh.PowertrainModelType_SHAFTS

# Drive type (FWD, RWD, or AWD)
drive_type = veh.DrivelineTypeWV_AWD

# Steering type (PITMAN_ARM or PITMAN_ARM_SHAFTS)
steering_type = veh.SteeringTypeWV_PITMAN_ARM

# Type of tire model (RIGID, RIGID_MESH, PACEJKA, LUGRE, FIALA, PAC89)
tire_model = veh.TireModelType_TMEASY

# Contact method
contact_method = chrono.ChContactMethod_SMC

# Simulation step sizes
step_size = 2e-3;
tire_step_size = 1e-3;

# Simulation end time
t_end = 100;

main()


text:
Clazz.declarePackage ("J.adapter.smarter");
Clazz.load (["JU.P3"], "J.adapter.smarter.XtalSymmetry", ["java.lang.Boolean", "$.Float", "java.util.Hashtable", "JU.BS", "$.Lst", "$.M3", "$.M4", "$.P3i", "$.PT", "$.SB", "$.V3", "J.adapter.smarter.Atom", "JS.Symmetry", "$.SymmetryOperation", "JU.BSUtil", "$.Logger"], function () {
c$ = Clazz.decorateAsClass (function () {
this.asc = null;
this.acr = null;
this.symmetry = null;
this.unitCellParams = null;
this.baseUnitCell = null;
this.symmetryRange = 0;
this.doCentroidUnitCell = false;
this.centroidPacked = false;
this.packingError = 0;
this.filterSymop = null;
this.applySymmetryToBonds = false;
this.latticeCells = null;
this.ptSupercell = null;
this.matSupercell = null;
this.trajectoryUnitCells = null;
this.doNormalize = true;
this.doPackUnitCell = false;
this.baseSymmetry = null;
this.sym2 = null;
this.rminx = 0;
this.rminy = 0;
this.rminz = 0;
this.rmaxx = 0;
this.rmaxy = 0;
this.rmaxz = 0;
this.ptOffset = null;
this.minXYZ = null;
this.maxXYZ = null;
this.minXYZ0 = null;
this.maxXYZ0 = null;
this.checkAll = false;
this.bondCount0 = 0;
this.dtype = 3;
this.unitCellTranslations = null;
this.latticeOp = 0;
this.latticeOnly = false;
this.noSymmetryCount = 0;
this.firstSymmetryAtom = 0;
this.ptTemp = null;
this.mTemp = null;
this.nVib = 0;
Clazz.instantialize (this, arguments);
}, J.adapter.smarter, "XtalSymmetry");
Clazz.prepareFields (c$, function () {
this.unitCellParams =  Clazz.newFloatArray (6, 0);
this.ptOffset =  new JU.P3 ();
});
Clazz.makeConstructor (c$,
function () {
});
Clazz.defineMethod (c$, "set",
function (reader) {
this.acr = reader;
this.asc = reader.asc;
this.getSymmetry ();
return this;
}, "J.adapter.smarter.AtomSetCollectionReader");
Clazz.defineMethod (c$, "getSymmetry",
function () {
return (this.symmetry == null ? (this.symmetry = this.acr.getInterface ("JS.Symmetry")) : this.symmetry);
});
Clazz.defineMethod (c$, "setSymmetry",
function (symmetry) {
return (this.symmetry = symmetry);
}, "J.api.SymmetryInterface");
Clazz.defineMethod (c$, "setSymmetryRange",
 function (factor) {
this.symmetryRange = factor;
this.asc.setInfo ("symmetryRange", Float.$valueOf (factor));
}, "~N");
Clazz.defineMethod (c$, "setLatticeCells",
 function () {
this.latticeCells = this.acr.latticeCells;
var isLatticeRange = (this.latticeCells[0] <= 555 && this.latticeCells[1] >= 555 && (this.latticeCells[2] == 0 || this.latticeCells[2] == 1 || this.latticeCells[2] == -1));
this.doNormalize = this.latticeCells[0] != 0 && (!isLatticeRange || this.latticeCells[2] == 1);
this.applySymmetryToBonds = this.acr.applySymmetryToBonds;
this.doPackUnitCell = this.acr.doPackUnitCell;
this.doCentroidUnitCell = this.acr.doCentroidUnitCell;
this.centroidPacked = this.acr.centroidPacked;
this.filterSymop = this.acr.filterSymop;
if (this.acr.strSupercell == null) this.setSupercellFromPoint (this.acr.ptSupercell);
});
Clazz.defineMethod (c$, "setSupercellFromPoint",
function (pt) {
this.ptSupercell = pt;
if (pt == null) {
this.matSupercell = null;
return;
}this.matSupercell =  new JU.M4 ();
this.matSupercell.m00 = pt.x;
this.matSupercell.m11 = pt.y;
this.matSupercell.m22 = pt.z;
this.matSupercell.m33 = 1;
JU.Logger.info ("Using supercell \n" + this.matSupercell);
}, "JU.P3");
Clazz.defineMethod (c$, "setUnitCell",
 function (info, matUnitCellOrientation, unitCellOffset) {
this.unitCellParams =  Clazz.newFloatArray (info.length, 0);
for (var i = 0; i < info.length; i++) this.unitCellParams[i] = info[i];

this.asc.haveUnitCell = true;
this.asc.setCurrentModelInfo ("unitCellParams", this.unitCellParams);
if (this.asc.isTrajectory) {
if (this.trajectoryUnitCells == null) {
this.trajectoryUnitCells =  new JU.Lst ();
this.asc.setInfo ("unitCells", this.trajectoryUnitCells);
}this.trajectoryUnitCells.addLast (this.unitCellParams);
}this.asc.setGlobalBoolean (2);
this.getSymmetry ().setUnitCell (this.unitCellParams, false);
if (unitCellOffset != null) {
this.symmetry.setOffsetPt (unitCellOffset);
this.asc.setCurrentModelInfo ("unitCellOffset", unitCellOffset);
}if (matUnitCellOrientation != null) {
this.symmetry.initializeOrientation (matUnitCellOrientation);
this.asc.setCurrentModelInfo ("matUnitCellOrientation", matUnitCellOrientation);
}}, "~A,JU.M3,JU.P3");
Clazz.defineMethod (c$, "addSpaceGroupOperation",
function (xyz, andSetLattice) {
if (andSetLattice) this.setLatticeCells ();
this.symmetry.setSpaceGroup (this.doNormalize);
return this.symmetry.addSpaceGroupOperation (xyz, 0);
}, "~S,~B");
Clazz.defineMethod (c$, "setLatticeParameter",
function (latt) {
this.symmetry.setSpaceGroup (this.doNormalize);
this.symmetry.setLattice (latt);
}, "~N");
Clazz.defineMethod (c$, "applySymmetryFromReader",
function (readerSymmetry) {
this.asc.setCoordinatesAreFractional (this.acr.iHaveFractionalCoordinates);
this.setUnitCell (this.acr.unitCellParams, this.acr.matUnitCellOrientation, this.acr.unitCellOffset);
this.setAtomSetSpaceGroupName (this.acr.sgName);
this.setSymmetryRange (this.acr.symmetryRange);
if (this.acr.doConvertToFractional || this.acr.fileCoordinatesAreFractional) {
this.setLatticeCells ();
var doApplySymmetry = true;
if (this.acr.ignoreFileSpaceGroupName || !this.acr.iHaveSymmetryOperators) {
if (!this.acr.merging || readerSymmetry == null) readerSymmetry = this.acr.getNewSymmetry ();
doApplySymmetry = readerSymmetry.createSpaceGroup (this.acr.desiredSpaceGroupIndex, (this.acr.sgName.indexOf ("!") >= 0 ? "P1" : this.acr.sgName), this.acr.unitCellParams);
} else {
this.acr.doPreSymmetry ();
readerSymmetry = null;
}this.packingError = this.acr.packingError;
if (doApplySymmetry) {
if (readerSymmetry != null) this.setSpaceGroupFrom (readerSymmetry);
this.applySymmetryLattice ();
if (readerSymmetry != null && this.filterSymop == null) this.setAtomSetSpaceGroupName (readerSymmetry.getSpaceGroupName ());
}}if (this.acr.iHaveFractionalCoordinates && this.acr.merging && readerSymmetry != null) {
var atoms = this.asc.atoms;
for (var i = this.asc.getLastAtomSetAtomIndex (), n = this.asc.ac; i < n; i++) readerSymmetry.toCartesian (atoms[i], true);

this.asc.setCoordinatesAreFractional (false);
this.acr.addVibrations = false;
}return this.symmetry;
}, "J.api.SymmetryInterface");
Clazz.defineMethod (c$, "setSpaceGroupFrom",
function (readerSymmetry) {
this.getSymmetry ().setSpaceGroupFrom (readerSymmetry);
}, "J.api.SymmetryInterface");
Clazz.defineMethod (c$, "setAtomSetSpaceGroupName",
 function (spaceGroupName) {
this.asc.setCurrentModelInfo ("spaceGroup", spaceGroupName + "");
}, "~S");
Clazz.defineMethod (c$, "applySymmetryLattice",
 function () {
if (!this.asc.coordinatesAreFractional || this.symmetry.getSpaceGroup () == null) return;
this.sym2 = null;
var maxX = this.latticeCells[0];
var maxY = this.latticeCells[1];
var maxZ = Math.abs (this.latticeCells[2]);
this.firstSymmetryAtom = this.asc.getLastAtomSetAtomIndex ();
var bsAtoms = this.asc.bsAtoms;
if (bsAtoms != null) this.firstSymmetryAtom = bsAtoms.nextSetBit (this.firstSymmetryAtom);
this.rminx = this.rminy = this.rminz = 3.4028235E38;
this.rmaxx = this.rmaxy = this.rmaxz = -3.4028235E38;
var pt0 = null;
if (this.acr.fillRange != null) {
if (bsAtoms == null) this.asc.bsAtoms = bsAtoms =  new JU.BS ();
bsAtoms.setBits (this.firstSymmetryAtom, this.asc.ac);
this.doPackUnitCell = false;
this.minXYZ =  new JU.P3i ();
this.maxXYZ = JU.P3i.new3 (1, 1, 1);
var oabc =  new Array (4);
for (var i = 0; i < 4; i++) oabc[i] = JU.P3.newP (this.acr.fillRange[i]);

this.adjustRangeMinMax (oabc);
if (this.sym2 == null) {
this.sym2 =  new JS.Symmetry ();
this.sym2.getUnitCell (this.acr.fillRange, false, null);
}this.applyAllSymmetry (this.acr.ms, bsAtoms);
pt0 =  new JU.P3 ();
var atoms = this.asc.atoms;
for (var i = this.asc.ac; --i >= this.firstSymmetryAtom; ) {
pt0.setT (atoms[i]);
this.symmetry.toCartesian (pt0, false);
this.sym2.toFractional (pt0, false);
if (this.acr.fixJavaFloat) JU.PT.fixPtFloats (pt0, 100000.0);
if (!this.isWithinCell (this.dtype, pt0, 0, 1, 0, 1, 0, 1, this.packingError)) bsAtoms.clear (i);
}
return;
}var offset = null;
this.nVib = 0;
var va = null;
var vb = null;
var vc = null;
this.baseSymmetry = this.symmetry;
var supercell = this.acr.strSupercell;
var oabc = null;
var isSuper = (supercell != null && supercell.indexOf (",") >= 0);
if (isSuper) {
oabc = this.symmetry.getV0abc (supercell);
if (oabc != null) {
this.minXYZ =  new JU.P3i ();
this.maxXYZ = JU.P3i.new3 (maxX, maxY, maxZ);
this.symmetry.setMinMaxLatticeParameters (this.minXYZ, this.maxXYZ);
pt0 = JU.P3.newP (oabc[0]);
va = JU.P3.newP (oabc[1]);
vb = JU.P3.newP (oabc[2]);
vc = JU.P3.newP (oabc[3]);
this.adjustRangeMinMax (oabc);
}}var iAtomFirst = this.asc.getLastAtomSetAtomIndex ();
if (bsAtoms != null) iAtomFirst = bsAtoms.nextSetBit (iAtomFirst);
if (this.rminx == 3.4028235E38) {
this.matSupercell = null;
supercell = null;
oabc = null;
} else {
var doPack0 = this.doPackUnitCell;
this.doPackUnitCell = doPack0;
if (this.asc.bsAtoms == null) this.asc.bsAtoms = JU.BSUtil.newBitSet2 (0, this.asc.ac);
bsAtoms = this.asc.bsAtoms;
this.applyAllSymmetry (this.acr.ms, null);
this.doPackUnitCell = doPack0;
var atoms = this.asc.atoms;
var atomCount = this.asc.ac;
for (var i = iAtomFirst; i < atomCount; i++) {
this.symmetry.toCartesian (atoms[i], true);
bsAtoms.set (i);
}
this.symmetry = null;
this.symmetry = this.getSymmetry ();
this.setUnitCell ( Clazz.newFloatArray (-1, [0, 0, 0, 0, 0, 0, va.x, va.y, va.z, vb.x, vb.y, vb.z, vc.x, vc.y, vc.z]), null, offset);
this.setAtomSetSpaceGroupName (oabc == null || supercell == null ? "P1" : "cell=" + supercell);
this.symmetry.setSpaceGroup (this.doNormalize);
this.symmetry.addSpaceGroupOperation ("x,y,z", 0);
if (pt0 != null) this.symmetry.toFractional (pt0, true);
for (var i = iAtomFirst; i < atomCount; i++) {
this.symmetry.toFractional (atoms[i], true);
if (pt0 != null) atoms[i].sub (pt0);
}
this.asc.haveAnisou = false;
this.asc.setCurrentModelInfo ("matUnitCellOrientation", null);
}this.minXYZ =  new JU.P3i ();
this.maxXYZ = JU.P3i.new3 (maxX, maxY, maxZ);
this.symmetry.setMinMaxLatticeParameters (this.minXYZ, this.maxXYZ);
if (oabc == null) {
this.applyAllSymmetry (this.acr.ms, bsAtoms);
return;
}if (this.acr.forcePacked || this.doPackUnitCell) {
var bs = this.asc.bsAtoms;
var atoms = this.asc.atoms;
if (bs == null) bs = this.asc.bsAtoms = JU.BSUtil.newBitSet2 (0, this.asc.ac);
for (var i = bs.nextSetBit (iAtomFirst); i >= 0; i = bs.nextSetBit (i + 1)) {
if (!this.isWithinCell (this.dtype, atoms[i], this.minXYZ.x, this.maxXYZ.x, this.minXYZ.y, this.maxXYZ.y, this.minXYZ.z, this.maxXYZ.z, this.packingError)) bs.clear (i);
}
}});
Clazz.defineMethod (c$, "adjustRangeMinMax",
 function (oabc) {
var pa =  new JU.P3 ();
var pb =  new JU.P3 ();
var pc =  new JU.P3 ();
if (this.acr.forcePacked) {
pa.setT (oabc[1]);
pb.setT (oabc[2]);
pc.setT (oabc[3]);
pa.scale (this.packingError);
pb.scale (this.packingError);
pc.scale (this.packingError);
}oabc[0].scaleAdd2 (this.minXYZ.x, oabc[1], oabc[0]);
oabc[0].scaleAdd2 (this.minXYZ.y, oabc[2], oabc[0]);
oabc[0].scaleAdd2 (this.minXYZ.z, oabc[3], oabc[0]);
oabc[0].sub (pa);
oabc[0].sub (pb);
oabc[0].sub (pc);
var pt = JU.P3.newP (oabc[0]);
this.symmetry.toFractional (pt, true);
this.setSymmetryMinMax (pt);
oabc[1].scale (this.maxXYZ.x - this.minXYZ.x);
oabc[2].scale (this.maxXYZ.y - this.minXYZ.y);
oabc[3].scale (this.maxXYZ.z - this.minXYZ.z);
oabc[1].scaleAdd2 (2, pa, oabc[1]);
oabc[2].scaleAdd2 (2, pb, oabc[2]);
oabc[3].scaleAdd2 (2, pc, oabc[3]);
for (var i = 0; i < 3; i++) {
for (var j = i + 1; j < 4; j++) {
pt.add2 (oabc[i], oabc[j]);
if (i != 0) pt.add (oabc[0]);
this.symmetry.toFractional (pt, false);
this.setSymmetryMinMax (pt);
}
}
this.symmetry.toCartesian (pt, false);
pt.add (oabc[1]);
this.symmetry.toFractional (pt, false);
this.setSymmetryMinMax (pt);
this.minXYZ = JU.P3i.new3 (Clazz.doubleToInt (Math.min (0, Math.floor (this.rminx + 0.001))), Clazz.doubleToInt (Math.min (0, Math.floor (this.rminy + 0.001))), Clazz.doubleToInt (Math.min (0, Math.floor (this.rminz + 0.001))));
this.maxXYZ = JU.P3i.new3 (Clazz.doubleToInt (Math.max (1, Math.ceil (this.rmaxx - 0.001))), Clazz.doubleToInt (Math.max (1, Math.ceil (this.rmaxy - 0.001))), Clazz.doubleToInt (Math.max (1, Math.ceil (this.rmaxz - 0.001))));
}, "~A");
Clazz.defineMethod (c$, "setSymmetryMinMax",
 function (c) {
if (this.rminx > c.x) this.rminx = c.x;
if (this.rminy > c.y) this.rminy = c.y;
if (this.rminz > c.z) this.rminz = c.z;
if (this.rmaxx < c.x) this.rmaxx = c.x;
if (this.rmaxy < c.y) this.rmaxy = c.y;
if (this.rmaxz < c.z) this.rmaxz = c.z;
}, "JU.P3");
Clazz.defineMethod (c$, "isWithinCell",
function (dtype, pt, minX, maxX, minY, maxY, minZ, maxZ, slop) {
return (pt.x > minX - slop && pt.x < maxX + slop && (dtype < 2 || pt.y > minY - slop && pt.y < maxY + slop) && (dtype < 3 || pt.z > minZ - slop && pt.z < maxZ + slop));
}, "~N,JU.P3,~N,~N,~N,~N,~N,~N,~N");
Clazz.defineMethod (c$, "applyAllSymmetry",
 function (ms, bsAtoms) {
if (this.asc.ac == 0 || bsAtoms != null && bsAtoms.isEmpty ()) return;
var n = this.noSymmetryCount = this.asc.baseSymmetryAtomCount > 0 ? n = this.asc.baseSymmetryAtomCount : bsAtoms == null ? this.asc.getLastAtomSetAtomCount () : this.asc.ac - bsAtoms.nextSetBit (this.asc.getLastAtomSetAtomIndex ());
this.asc.setTensors ();
this.bondCount0 = this.asc.bondCount;
this.finalizeSymmetry (this.symmetry);
var operationCount = this.symmetry.getSpaceGroupOperationCount ();
var excludedOps = (this.acr.thisBiomolecule == null ? null :  new JU.BS ());
if (excludedOps != null) this.asc.checkSpecial = true;
this.dtype = Clazz.floatToInt (this.symmetry.getUnitCellInfoType (6));
this.symmetry.setMinMaxLatticeParameters (this.minXYZ, this.maxXYZ);
if (this.doCentroidUnitCell) this.asc.setInfo ("centroidMinMax",  Clazz.newIntArray (-1, [this.minXYZ.x, this.minXYZ.y, this.minXYZ.z, this.maxXYZ.x, this.maxXYZ.y, this.maxXYZ.z, (this.centroidPacked ? 1 : 0)]));
if (this.ptSupercell != null) {
this.asc.setCurrentModelInfo ("supercell", this.ptSupercell);
switch (this.dtype) {
case 3:
this.minXYZ.z *= Clazz.floatToInt (Math.abs (this.ptSupercell.z));
this.maxXYZ.z *= Clazz.floatToInt (Math.abs (this.ptSupercell.z));
case 2:
this.minXYZ.y *= Clazz.floatToInt (Math.abs (this.ptSupercell.y));
this.maxXYZ.y *= Clazz.floatToInt (Math.abs (this.ptSupercell.y));
case 1:
this.minXYZ.x *= Clazz.floatToInt (Math.abs (this.ptSupercell.x));
this.maxXYZ.x *= Clazz.floatToInt (Math.abs (this.ptSupercell.x));
}
}if (this.doCentroidUnitCell || this.doPackUnitCell || this.symmetryRange != 0 && this.maxXYZ.x - this.minXYZ.x == 1 && this.maxXYZ.y - this.minXYZ.y == 1 && this.maxXYZ.z - this.minXYZ.z == 1) {
this.minXYZ0 = JU.P3.new3 (this.minXYZ.x, this.minXYZ.y, this.minXYZ.z);
this.maxXYZ0 = JU.P3.new3 (this.maxXYZ.x, this.maxXYZ.y, this.maxXYZ.z);
if (ms != null) {
ms.setMinMax0 (this.minXYZ0, this.maxXYZ0);
this.minXYZ.set (Clazz.floatToInt (this.minXYZ0.x), Clazz.floatToInt (this.minXYZ0.y), Clazz.floatToInt (this.minXYZ0.z));
this.maxXYZ.set (Clazz.floatToInt (this.maxXYZ0.x), Clazz.floatToInt (this.maxXYZ0.y), Clazz.floatToInt (this.maxXYZ0.z));
}switch (this.dtype) {
case 3:
this.minXYZ.z--;
this.maxXYZ.z++;
case 2:
this.minXYZ.y--;
this.maxXYZ.y++;
case 1:
this.minXYZ.x--;
this.maxXYZ.x++;
}
}var nCells = (this.maxXYZ.x - this.minXYZ.x) * (this.maxXYZ.y - this.minXYZ.y) * (this.maxXYZ.z - this.minXYZ.z);
var cartesianCount = (this.asc.checkSpecial || this.acr.thisBiomolecule != null ? n * operationCount * nCells : this.symmetryRange > 0 ? n * operationCount : 1);
var cartesians =  new Array (cartesianCount);
var atoms = this.asc.atoms;
for (var i = 0; i < n; i++) atoms[i + this.firstSymmetryAtom].bsSymmetry = JU.BS.newN (operationCount * (nCells + 1));

var pt = 0;
var unitCells =  Clazz.newIntArray (nCells, 0);
this.unitCellTranslations =  new Array (nCells);
var iCell = 0;
var cell555Count = 0;
var absRange = Math.abs (this.symmetryRange);
var checkCartesianRange = (this.symmetryRange != 0);
var checkRangeNoSymmetry = (this.symmetryRange < 0);
var checkRange111 = (this.symmetryRange > 0);
if (checkCartesianRange) {
this.rminx = this.rminy = this.rminz = 3.4028235E38;
this.rmaxx = this.rmaxy = this.rmaxz = -3.4028235E38;
}var symmetry = this.symmetry;
var lastSymmetry = symmetry;
this.latticeOp = symmetry.getLatticeOp ();
this.checkAll = (this.asc.atomSetCount == 1 && this.asc.checkSpecial && this.latticeOp >= 0);
this.latticeOnly = (this.asc.checkLatticeOnly && this.latticeOp >= 0);
var pttemp = null;
var op = symmetry.getSpaceGroupOperation (0);
if (this.doPackUnitCell) {
pttemp =  new JU.P3 ();
this.ptOffset.set (0, 0, 0);
}var atomMap = (this.bondCount0 > this.asc.bondIndex0 && this.applySymmetryToBonds ?  Clazz.newIntArray (n, 0) : null);
var lstNCS = this.acr.lstNCS;
if (lstNCS != null && lstNCS.get (0).m33 == 0) {
var nOp = symmetry.getSpaceGroupOperationCount ();
var nn = lstNCS.size ();
for (var i = nn; --i >= 0; ) {
var m = lstNCS.get (i);
m.m33 = 1;
symmetry.toFractionalM (m);
}
for (var i = 1; i < nOp; i++) {
var m1 = symmetry.getSpaceGroupOperation (i);
for (var j = 0; j < nn; j++) {
var m = JU.M4.newM4 (lstNCS.get (j));
m.mul2 (m1, m);
if (this.doNormalize) JS.SymmetryOperation.setOffset (m, atoms, this.firstSymmetryAtom, this.noSymmetryCount);
lstNCS.addLast (m);
}
}
}for (var tx = this.minXYZ.x; tx < this.maxXYZ.x; tx++) for (var ty = this.minXYZ.y; ty < this.maxXYZ.y; ty++) for (var tz = this.minXYZ.z; tz < this.maxXYZ.z; tz++) {
this.unitCellTranslations[iCell] = JU.V3.new3 (tx, ty, tz);
unitCells[iCell++] = 555 + tx * 100 + ty * 10 + tz;
if (tx != 0 || ty != 0 || tz != 0 || cartesians.length == 0) continue;
for (pt = 0; pt < n; pt++) {
var atom = atoms[this.firstSymmetryAtom + pt];
if (ms != null) {
symmetry = ms.getAtomSymmetry (atom, this.symmetry);
if (symmetry !== lastSymmetry) {
if (symmetry.getSpaceGroupOperationCount () == 0) this.finalizeSymmetry (lastSymmetry = symmetry);
op = symmetry.getSpaceGroupOperation (0);
}}var c = JU.P3.newP (atom);
op.rotTrans (c);
symmetry.toCartesian (c, false);
if (this.doPackUnitCell) {
symmetry.toUnitCell (c, this.ptOffset);
pttemp.setT (c);
symmetry.toFractional (pttemp, false);
if (this.acr.fixJavaFloat) JU.PT.fixPtFloats (pttemp, 100000.0);
if (bsAtoms == null) atom.setT (pttemp);
 else if (atom.distance (pttemp) < 0.0001) bsAtoms.set (atom.index);
 else {
bsAtoms.clear (atom.index);
continue;
}}if (bsAtoms != null) atom.bsSymmetry.clearAll ();
atom.bsSymmetry.set (iCell * operationCount);
atom.bsSymmetry.set (0);
if (checkCartesianRange) this.setSymmetryMinMax (c);
if (pt < cartesianCount) cartesians[pt] = c;
}
if (checkRangeNoSymmetry) {
this.rminx -= absRange;
this.rminy -= absRange;
this.rminz -= absRange;
this.rmaxx += absRange;
this.rmaxy += absRange;
this.rmaxz += absRange;
}cell555Count = pt = this.symmetryAddAtoms (0, 0, 0, 0, pt, iCell * operationCount, cartesians, ms, excludedOps, atomMap);
}

if (checkRange111) {
this.rminx -= absRange;
this.rminy -= absRange;
this.rminz -= absRange;
this.rmaxx += absRange;
this.rmaxy += absRange;
this.rmaxz += absRange;
}iCell = 0;
for (var tx = this.minXYZ.x; tx < this.maxXYZ.x; tx++) for (var ty = this.minXYZ.y; ty < this.maxXYZ.y; ty++) for (var tz = this.minXYZ.z; tz < this.maxXYZ.z; tz++) {
iCell++;
if (tx != 0 || ty != 0 || tz != 0) pt = this.symmetryAddAtoms (tx, ty, tz, cell555Count, pt, iCell * operationCount, cartesians, ms, excludedOps, atomMap);
}

if (iCell * n == this.asc.ac - this.firstSymmetryAtom) this.duplicateAtomProperties (iCell);
this.setSymmetryOps ();
this.asc.setCurrentModelInfo ("presymmetryAtomIndex", Integer.$valueOf (this.firstSymmetryAtom));
this.asc.setCurrentModelInfo ("presymmetryAtomCount", Integer.$valueOf (n));
this.asc.setCurrentModelInfo ("latticeDesignation", symmetry.getLatticeDesignation ());
this.asc.setCurrentModelInfo ("unitCellRange", unitCells);
this.asc.setCurrentModelInfo ("unitCellTranslations", this.unitCellTranslations);
this.baseUnitCell = this.unitCellParams;
this.unitCellParams =  Clazz.newFloatArray (6, 0);
this.reset ();
}, "J.adapter.smarter.MSInterface,JU.BS");
Clazz.defineMethod (c$, "symmetryAddAtoms",
 function (transX, transY, transZ, baseCount, pt, iCellOpPt, cartesians, ms, excludedOps, atomMap) {
var isBaseCell = (baseCount == 0);
var addBonds = (atomMap != null);
if (this.doPackUnitCell) this.ptOffset.set (transX, transY, transZ);
var range2 = this.symmetryRange * this.symmetryRange;
var checkRangeNoSymmetry = (this.symmetryRange < 0);
var checkRange111 = (this.symmetryRange > 0);
var checkSymmetryMinMax = (isBaseCell && checkRange111);
checkRange111 = new Boolean (checkRange111 & !isBaseCell).valueOf ();
var nOp = this.symmetry.getSpaceGroupOperationCount ();
var lstNCS = this.acr.lstNCS;
var nNCS = (lstNCS == null ? 0 : lstNCS.size ());
var nOperations = nOp + nNCS;
nNCS = Clazz.doubleToInt (nNCS / nOp);
var checkSpecial = (nOperations == 1 && !this.doPackUnitCell ? false : this.asc.checkSpecial);
var checkSymmetryRange = (checkRangeNoSymmetry || checkRange111);
var checkDistances = (checkSpecial || checkSymmetryRange);
var checkOps = (excludedOps != null);
var addCartesian = (checkSpecial || checkSymmetryMinMax);
var bsAtoms = (this.acr.isMolecular ? null : this.asc.bsAtoms);
var symmetry = this.symmetry;
if (checkRangeNoSymmetry) baseCount = this.noSymmetryCount;
var atomMax = this.firstSymmetryAtom + this.noSymmetryCount;
var ptAtom =  new JU.P3 ();
var code = null;
var d0 = (checkOps ? 0.01 : 0.0001);
var subSystemId = '\u0000';
var j00 = (bsAtoms == null ? this.firstSymmetryAtom : bsAtoms.nextSetBit (0));
out : for (var iSym = 0; iSym < nOperations; iSym++) {
if (isBaseCell && iSym == 0 || this.latticeOnly && iSym > 0 && iSym != this.latticeOp || excludedOps != null && excludedOps.get (iSym)) continue;
var pt0 = (checkSpecial || excludedOps != null ? pt : checkRange111 ? baseCount : 0);
var spinOp = (iSym >= nOp ? 0 : this.asc.vibScale == 0 ? symmetry.getSpinOp (iSym) : this.asc.vibScale);
var i0 = Math.max (this.firstSymmetryAtom, (bsAtoms == null ? 0 : bsAtoms.nextSetBit (0)));
var checkDistance = checkDistances;
var spt = (iSym >= nOp ? Clazz.doubleToInt ((iSym - nOp) / nNCS) : iSym);
var cpt = spt + iCellOpPt;
for (var i = i0; i < atomMax; i++) {
var a = this.asc.atoms[i];
if (a.ignoreSymmetry || bsAtoms != null && !bsAtoms.get (i)) continue;
if (ms == null) {
symmetry.newSpaceGroupPoint (iSym, a, ptAtom, transX, transY, transZ, (iSym >= nOp ? lstNCS.get (iSym - nOp) : null));
} else {
symmetry = ms.getAtomSymmetry (a, this.symmetry);
symmetry.newSpaceGroupPoint (iSym, a, ptAtom, transX, transY, transZ, null);
code = symmetry.getSpaceGroupOperationCode (iSym);
if (code != null) {
subSystemId = code.charAt (0);
symmetry = ms.getSymmetryFromCode (code);
if (symmetry.getSpaceGroupOperationCount () == 0) this.finalizeSymmetry (symmetry);
}}if (this.acr.fixJavaFloat) JU.PT.fixPtFloats (ptAtom, 100000.0);
var c = JU.P3.newP (ptAtom);
symmetry.toCartesian (c, false);
if (this.doPackUnitCell) {
symmetry.toUnitCell (c, this.ptOffset);
ptAtom.setT (c);
symmetry.toFractional (ptAtom, false);
if (this.acr.fixJavaFloat) JU.PT.fixPtFloats (ptAtom, 100000.0);
if (!this.isWithinCell (this.dtype, ptAtom, this.minXYZ0.x, this.maxXYZ0.x, this.minXYZ0.y, this.maxXYZ0.y, this.minXYZ0.z, this.maxXYZ0.z, this.packingError)) continue;
}if (checkSymmetryMinMax) this.setSymmetryMinMax (c);
var special = null;
if (checkDistance) {
if (checkSymmetryRange && (c.x < this.rminx || c.y < this.rminy || c.z < this.rminz || c.x > this.rmaxx || c.y > this.rmaxy || c.z > this.rmaxz)) continue;
var minDist2 = 3.4028235E38;
var j0 = (this.checkAll ? this.asc.ac : pt0);
var name = a.atomName;
var id = (code == null ? a.altLoc : subSystemId);
for (var j = j00; j < j0; j++) {
if (bsAtoms != null && !bsAtoms.get (j)) continue;
var pc = cartesians[j];
if (pc == null) continue;
var d2 = c.distanceSquared (pc);
if (checkSpecial && d2 < d0) {
if (checkOps) {
excludedOps.set (iSym);
continue out;
}special = this.asc.atoms[this.firstSymmetryAtom + j];
if ((special.atomName == null || special.atomName.equals (name)) && special.altLoc == id) break;
special = null;
}if (checkRange111 && j < baseCount && d2 < minDist2) minDist2 = d2;
}
if (checkRange111 && minDist2 > range2) continue;
}if (checkOps) {
checkDistance = false;
}var atomSite = a.atomSite;
if (special != null) {
if (addBonds) atomMap[atomSite] = special.index;
special.bsSymmetry.set (cpt);
special.bsSymmetry.set (spt);
} else {
if (addBonds) atomMap[atomSite] = this.asc.ac;
var atom1 = this.asc.newCloneAtom (a);
if (this.asc.bsAtoms != null) this.asc.bsAtoms.set (atom1.index);
atom1.setT (ptAtom);
if (spinOp != 0 && atom1.vib != null) {
symmetry.getSpaceGroupOperation (iSym).rotate (atom1.vib);
atom1.vib.scale (spinOp);
}atom1.atomSite = atomSite;
if (code != null) atom1.altLoc = subSystemId;
atom1.bsSymmetry = JU.BSUtil.newAndSetBit (cpt);
atom1.bsSymmetry.set (spt);
if (addCartesian) cartesians[pt++] = c;
var tensors = a.tensors;
if (tensors != null) {
atom1.tensors = null;
for (var j = tensors.size (); --j >= 0; ) {
var t = tensors.get (j);
if (t == null) continue;
if (nOp == 1) atom1.addTensor (t.copyTensor (), null, false);
 else this.addRotatedTensor (atom1, t, iSym, false, symmetry);
}
}}}
if (addBonds) {
var bonds = this.asc.bonds;
var atoms = this.asc.atoms;
for (var bondNum = this.asc.bondIndex0; bondNum < this.bondCount0; bondNum++) {
var bond = bonds[bondNum];
var atom1 = atoms[bond.atomIndex1];
var atom2 = atoms[bond.atomIndex2];
if (atom1 == null || atom2 == null) continue;
var iAtom1 = atomMap[atom1.atomSite];
var iAtom2 = atomMap[atom2.atomSite];
if (iAtom1 >= atomMax || iAtom2 >= atomMax) this.asc.addNewBondWithOrder (iAtom1, iAtom2, bond.order);
}
}}
return pt;
}, "~N,~N,~N,~N,~N,~N,~A,J.adapter.smarter.MSInterface,JU.BS,~A");
Clazz.defineMethod (c$, "duplicateAtomProperties",
 function (nTimes) {
var p = this.asc.getAtomSetAuxiliaryInfoValue (-1, "atomProperties");
if (p != null) for (var entry, $entry = p.entrySet ().iterator (); $entry.hasNext () && ((entry = $entry.next ()) || true);) {
var key = entry.getKey ();
var val = entry.getValue ();
if (Clazz.instanceOf (val, String)) {
var data = val;
var s =  new JU.SB ();
for (var i = nTimes; --i >= 0; ) s.append (data);

p.put (key, s.toString ());
} else {
var f = val;
var fnew =  Clazz.newFloatArray (f.length * nTimes, 0);
for (var i = nTimes; --i >= 0; ) System.arraycopy (f, 0, fnew, i * f.length, f.length);

}}
}, "~N");
Clazz.defineMethod (c$, "finalizeSymmetry",
 function (symmetry) {
var name = this.asc.getAtomSetAuxiliaryInfoValue (-1, "spaceGroup");
symmetry.setFinalOperations (name, this.asc.atoms, this.firstSymmetryAtom, this.noSymmetryCount, this.doNormalize, this.filterSymop);
if (this.filterSymop != null || name == null || name.equals ("unspecified!")) this.setAtomSetSpaceGroupName (symmetry.getSpaceGroupName ());
}, "J.api.SymmetryInterface");
Clazz.defineMethod (c$, "setSymmetryOps",
 function () {
var operationCount = this.symmetry.getSpaceGroupOperationCount ();
if (operationCount > 0) {
var symmetryList =  new Array (operationCount);
for (var i = 0; i < operationCount; i++) symmetryList[i] = "" + this.symmetry.getSpaceGroupXyz (i, this.doNormalize);

this.asc.setCurrentModelInfo ("symmetryOperations", symmetryList);
this.asc.setCurrentModelInfo ("symmetryOps", this.symmetry.getSymmetryOperations ());
}this.asc.setCurrentModelInfo ("symmetryCount", Integer.$valueOf (operationCount));
this.asc.setCurrentModelInfo ("latticeType", this.symmetry.getLatticeType ());
this.asc.setCurrentModelInfo ("intlTableNo", this.symmetry.getIntTableNumber ());
if (this.acr.sgName == null || this.acr.sgName.indexOf ("?") >= 0 || this.acr.sgName.indexOf ("!") >= 0) this.setAtomSetSpaceGroupName (this.acr.sgName = this.symmetry.getSpaceGroupName ());
});
Clazz.defineMethod (c$, "getOverallSpan",
function () {
return (this.maxXYZ0 == null ? JU.V3.new3 (this.maxXYZ.x - this.minXYZ.x, this.maxXYZ.y - this.minXYZ.y, this.maxXYZ.z - this.minXYZ.z) : JU.V3.newVsub (this.maxXYZ0, this.minXYZ0));
});
Clazz.defineMethod (c$, "applySymmetryBio",
function (thisBiomolecule, applySymmetryToBonds, filter) {
var biomts = thisBiomolecule.get ("biomts");
if (biomts.size () < 2) return;
this.acr.lstNCS = null;
this.setLatticeCells ();
var lc = (this.latticeCells != null && this.latticeCells[0] != 0 ?  Clazz.newIntArray (3, 0) : null);
if (lc != null) for (var i = 0; i < 3; i++) lc[i] = this.latticeCells[i];

this.latticeCells = null;
var particleMode = (filter.indexOf ("BYCHAIN") >= 0 ? 1 : filter.indexOf ("BYSYMOP") >= 0 ? 2 : 0);
this.doNormalize = false;
var biomtchains = thisBiomolecule.get ("chains");
if (biomtchains.get (0).equals (biomtchains.get (1))) biomtchains = null;
this.symmetry = null;
this.getSymmetry ().setSpaceGroup (this.doNormalize);
this.addSpaceGroupOperation ("x,y,z", false);
var name = thisBiomolecule.get ("name");
this.setAtomSetSpaceGroupName (this.acr.sgName = name);
var len = biomts.size ();
this.applySymmetryToBonds = applySymmetryToBonds;
this.bondCount0 = this.asc.bondCount;
this.firstSymmetryAtom = this.asc.getLastAtomSetAtomIndex ();
var atomMax = this.asc.ac;
var ht =  new java.util.Hashtable ();
var nChain = 0;
var atoms = this.asc.atoms;
var addBonds = (this.bondCount0 > this.asc.bondIndex0 && applySymmetryToBonds);
switch (particleMode) {
case 1:
for (var i = atomMax; --i >= this.firstSymmetryAtom; ) {
var id = Integer.$valueOf (atoms[i].chainID);
var bs = ht.get (id);
if (bs == null) {
nChain++;
ht.put (id, bs =  new JU.BS ());
}bs.set (i);
}
this.asc.bsAtoms =  new JU.BS ();
for (var i = 0; i < nChain; i++) {
this.asc.bsAtoms.set (atomMax + i);
var a =  new J.adapter.smarter.Atom ();
a.set (0, 0, 0);
a.radius = 16;
this.asc.addAtom (a);
}
var ichain = 0;
for (var e, $e = ht.entrySet ().iterator (); $e.hasNext () && ((e = $e.next ()) || true);) {
var a = atoms[atomMax + ichain++];
var bs = e.getValue ();
for (var i = bs.nextSetBit (0); i >= 0; i = bs.nextSetBit (i + 1)) a.add (atoms[i]);

a.scale (1 / bs.cardinality ());
a.atomName = "Pt" + ichain;
a.chainID = e.getKey ().intValue ();
}
this.firstSymmetryAtom = atomMax;
atomMax += nChain;
addBonds = false;
break;
case 2:
this.asc.bsAtoms =  new JU.BS ();
this.asc.bsAtoms.set (atomMax);
var a = atoms[atomMax] =  new J.adapter.smarter.Atom ();
a.set (0, 0, 0);
for (var i = atomMax; --i >= this.firstSymmetryAtom; ) a.add (atoms[i]);

a.scale (1 / (atomMax - this.firstSymmetryAtom));
a.atomName = "Pt";
a.radius = 16;
this.asc.addAtom (a);
this.firstSymmetryAtom = atomMax++;
addBonds = false;
break;
}
var assemblyIdAtoms = thisBiomolecule.get ("asemblyIdAtoms");
if (filter.indexOf ("#<") >= 0) {
len = Math.min (len, JU.PT.parseInt (filter.substring (filter.indexOf ("#<") + 2)) - 1);
filter = JU.PT.rep (filter, "#<", "_<");
}for (var iAtom = this.firstSymmetryAtom; iAtom < atomMax; iAtom++) atoms[iAtom].bsSymmetry = JU.BSUtil.newAndSetBit (0);

var bsAtoms = this.asc.bsAtoms;
var atomMap = (addBonds ?  Clazz.newIntArray (this.asc.ac, 0) : null);
for (var i = (biomtchains == null ? 1 : 0); i < len; i++) {
if (filter.indexOf ("!#") >= 0) {
if (filter.indexOf ("!#" + (i + 1) + ";") >= 0) continue;
} else if (filter.indexOf ("#") >= 0 && filter.indexOf ("#" + (i + 1) + ";") < 0) {
continue;
}var mat = biomts.get (i);
var chains = (biomtchains == null ? null : biomtchains.get (i));
if (chains != null && assemblyIdAtoms != null) {
bsAtoms =  new JU.BS ();
for (var e, $e = assemblyIdAtoms.entrySet ().iterator (); $e.hasNext () && ((e = $e.next ()) || true);) if (chains.indexOf (":" + e.getKey () + ";") >= 0) bsAtoms.or (e.getValue ());

if (this.asc.bsAtoms != null) bsAtoms.and (this.asc.bsAtoms);
chains = null;
}for (var iAtom = this.firstSymmetryAtom; iAtom < atomMax; iAtom++) {
if (bsAtoms != null && !bsAtoms.get (iAtom) || chains != null && chains.indexOf (":" + this.acr.vwr.getChainIDStr (atoms[iAtom].chainID) + ";") < 0) continue;
try {
var atomSite = atoms[iAtom].atomSite;
var atom1;
if (addBonds) atomMap[atomSite] = this.asc.ac;
atom1 = this.asc.newCloneAtom (atoms[iAtom]);
if (this.asc.bsAtoms != null) this.asc.bsAtoms.set (atom1.index);
atom1.atomSite = atomSite;
mat.rotTrans (atom1);
atom1.bsSymmetry = JU.BSUtil.newAndSetBit (i);
} catch (e) {
if (Clazz.exceptionOf (e, Exception)) {
this.asc.errorMessage = "appendAtomCollection error: " + e;
} else {
throw e;
}
}
}
if (i > 0) {
this.symmetry.addBioMoleculeOperation (mat, false);
if (addBonds) {
for (var bondNum = this.asc.bondIndex0; bondNum < this.bondCount0; bondNum++) {
var bond = this.asc.bonds[bondNum];
var iAtom1 = atomMap[atoms[bond.atomIndex1].atomSite];
var iAtom2 = atomMap[atoms[bond.atomIndex2].atomSite];
this.asc.addNewBondWithOrder (iAtom1, iAtom2, bond.order);
}
}}}
if (biomtchains != null) {
if (this.asc.bsAtoms == null) this.asc.bsAtoms = JU.BSUtil.newBitSet2 (0, this.asc.ac);
this.asc.bsAtoms.clearBits (this.firstSymmetryAtom, atomMax);
}this.noSymmetryCount = atomMax - this.firstSymmetryAtom;
this.asc.setCurrentModelInfo ("presymmetryAtomIndex", Integer.$valueOf (this.firstSymmetryAtom));
this.asc.setCurrentModelInfo ("presymmetryAtomCount", Integer.$valueOf (this.noSymmetryCount));
this.asc.setCurrentModelInfo ("biosymmetryCount", Integer.$valueOf (len));
this.asc.setCurrentModelInfo ("biosymmetry", this.symmetry);
this.finalizeSymmetry (this.symmetry);
this.setSymmetryOps ();
this.reset ();
}, "java.util.Map,~B,~S");
Clazz.defineMethod (c$, "reset",
 function () {
this.asc.coordinatesAreFractional = false;
this.asc.setCurrentModelInfo ("hasSymmetry", Boolean.TRUE);
this.asc.setGlobalBoolean (1);
});
Clazz.defineMethod (c$, "addRotatedTensor",
function (a, t, iSym, reset, symmetry) {
if (this.ptTemp == null) {
this.ptTemp =  new JU.P3 ();
this.mTemp =  new JU.M3 ();
}return a.addTensor ((this.acr.getInterface ("JU.Tensor")).setFromEigenVectors (symmetry.rotateAxes (iSym, t.eigenVectors, this.ptTemp, this.mTemp), t.eigenValues, t.isIsotropic ? "iso" : t.type, t.id, t), null, reset);
}, "J.adapter.smarter.Atom,JU.Tensor,~N,~B,J.api.SymmetryInterface");
Clazz.defineMethod (c$, "setTensors",
function () {
var n = this.asc.ac;
for (var i = this.asc.getLastAtomSetAtomIndex (); i < n; i++) {
var a = this.asc.atoms[i];
if (a.anisoBorU == null) continue;
a.addTensor (this.symmetry.getTensor (this.acr.vwr, a.anisoBorU), null, false);
if (Float.isNaN (a.bfactor)) a.bfactor = a.anisoBorU[7] * 100;
a.anisoBorU = null;
}
});
Clazz.defineMethod (c$, "setTimeReversal",
function (op, timeRev) {
this.symmetry.setTimeReversal (op, timeRev);
}, "~N,~N");
Clazz.defineMethod (c$, "rotateToSuperCell",
function (t) {
if (this.matSupercell != null) this.matSupercell.rotTrans (t);
}, "JU.V3");
Clazz.defineMethod (c$, "setSpinVectors",
function () {
if (this.nVib > 0 || this.asc.iSet < 0 || !this.acr.vibsFractional) return this.nVib;
var i0 = this.asc.getAtomSetAtomIndex (this.asc.iSet);
var sym = this.getBaseSymmetry ();
for (var i = this.asc.ac; --i >= i0; ) {
var v = this.asc.atoms[i].vib;
if (v != null) {
if (v.modDim > 0) {
(v).setMoment ();
} else {
v = v.clone ();
sym.toCartesian (v, true);
this.asc.atoms[i].vib = v;
}this.nVib++;
}}
return this.nVib;
});
Clazz.defineMethod (c$, "scaleFractionalVibs",
function () {
var params = this.getBaseSymmetry ().getUnitCellParams ();
var ptScale = JU.P3.new3 (1 / params[0], 1 / params[1], 1 / params[2]);
var i0 = this.asc.getAtomSetAtomIndex (this.asc.iSet);
for (var i = this.asc.ac; --i >= i0; ) {
var v = this.asc.atoms[i].vib;
if (v != null) {
v.scaleT (ptScale);
}}
});
Clazz.defineMethod (c$, "getBaseSymmetry",
function () {
return (this.baseSymmetry == null ? this.symmetry : this.baseSymmetry);
});
Clazz.defineMethod (c$, "finalizeUnitCell",
function (ptSupercell) {
if (ptSupercell != null && this.baseUnitCell != null) {
this.baseUnitCell[22] = Math.max (1, Clazz.floatToInt (ptSupercell.x));
this.baseUnitCell[23] = Math.max (1, Clazz.floatToInt (ptSupercell.y));
this.baseUnitCell[24] = Math.max (1, Clazz.floatToInt (ptSupercell.z));
}}, "JU.P3");
Clazz.defineStatics (c$,
"PARTICLE_NONE", 0,
"PARTICLE_CHAIN", 1,
"PARTICLE_SYMOP", 2);
});


text:
set -ex

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
ENV="test-environment-${TRAVIS_PYTHON_VERSION}"

# ~~~ New install ~~~ #
if [ ! -d "$HOME/conda/bin" ]; then
  if [ -d "$HOME/conda" ]; then
    rm -rf $HOME/conda
  fi
  echo "Creating new conda installation."
  wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh;
  bash miniconda.sh -b -p $HOME/conda
  export PATH="$HOME/conda/bin:$PATH"
  hash -r
  conda config --set always_yes yes --set changeps1 no
  conda install pyyaml
  conda update -q conda
  conda info -a
  conda env create \
    --name $ENV \
    python=$TRAVIS_PYTHON_VERSION \
    --file $DIR/requirements-py3.yml
  source activate $ENV
# ~~~ cached install ~~~ #
else
  echo "Using cached conda installation."
  export PATH="$HOME/conda/bin:$PATH"
  hash -r
  conda config --set always_yes yes --set changeps1 no
  conda update -q conda
  source activate $ENV
  conda update -q \
    --all \
    python=$TRAVIS_PYTHON_VERSION
  conda env update \
    --file $DIR/requirements-py3.yml \
    python=$TRAVIS_PYTHON_VERSION
  pip install -U codeclimate-test-reporter codacy-coverage
  pip uninstall --yes quimb
fi


text:
import json

from django.contrib import messages
from django.utils.six import text_type

class AjaxMessagesMiddleware(object):
    """
    Middleware to handle messages for AJAX requests.

    If the AJAX response is already JSON, add a "messages" key to it (or
    append to an existing "messages" key) a list of messages (each
    message is an object with "level", "message", and "tags" keys).

    If the AJAX response is currently html, turn it into JSON and stuff
    the HTML content into the "html" key, adding a "messages" key as
    well.

    If the AJAX response is neither json nor html, return it as-is (with
    no messages attached, and without iterating over messages).

    If the AJAX response has a status code other than 200, or has an attribute
    ``no_messages`` that is ``True``, it will not be modified (and messages
    will not be read).

    """
    def process_response(self, request, response):
        handle_response = (
            request.is_ajax() and
            response.status_code == 200 and
            not getattr(response, 'no_messages', False)
            )
        if handle_response:
            content_type = response.get('content-type', 'None').split(";")[0]

            content = response.content.decode('utf-8')

            if content_type == "application/json":
                data = json.loads(content)
            elif content_type == "text/html":
                data = {"html": content}
            else:
                return response

            messagelist = data.setdefault("messages", [])

            for message in messages.get_messages(request):
                messagelist.append({
                    "level": message.level,
                    "message": text_type(message.message),
                    "tags": message.tags,
                })

            response.content = json.dumps(data)
            response["content-type"] = "application/json"
            response["content-length"] = len(response.content)
        return response


text:
<?php

namespace Panda\Ui\Html\Helpers;

use DOMElement;
use Panda\Ui\Html\Factories\HTMLFactoryInterface;

/**
 * Class SelectHelper
 * @package Panda\Ui\Html\Helpers
 */
class SelectHelper
{
    /**
     * Sets the given array as options in select.
     *
     * For example:
     * If we are given an array the keys of the array will be the options values
     * and the key values will be the options titles.
     *
     * @param HTMLFactoryInterface $factory
     * @param DOMElement           $select
     * @param array                $options
     * @param mixed|array          $checkedValue
     *
     * @throws \InvalidArgumentException
     * @throws \Exception
     *
     * @deprecated Use \Panda\Ui\Html\Renders\SelectRender::render() instead
     */
    public static function setOptions(HTMLFactoryInterface $factory, DOMElement $select, $options = [], $checkedValue = null)
    {
        foreach ($options as $value => $title) {
            // Build option
            $option = $factory->buildHtmlElement('option', $title);
            $option->attr('value', $value);

            // Append option to container
            $factory->getHTMLHandler()->append($select, $option);
        }

        // Set checked values
        $checkedValues = is_array($checkedValue) ? $checkedValue : [$checkedValue];
        foreach ($checkedValues as $value) {
            // Skip empty values
            if (empty($value)) {
                continue;
            }

            // Select option
            $option = $factory->getHTMLHandler()->select($select->ownerDocument, sprintf('option[value=%s]', $value), $select)->item(0);
            if ($option) {
                $factory->getHTMLHandler()->attr($option, 'selected', 'selected');
            }
        }
    }

    /**
     * Sets the given array as groups in select.
     *
     * Get label and options from each group and apply accordingly.
     *
     * @param HTMLFactoryInterface $factory
     * @param DOMElement           $select
     * @param array                $groups
     * @param mixed|array          $checkedValue
     *
     * @throws \InvalidArgumentException
     * @throws \Exception
     *
     * @deprecated Use \Panda\Ui\Html\Renders\SelectRender::render() instead
     */
    public static function setGroups(HTMLFactoryInterface $factory, DOMElement $select, $groups = [], $checkedValue = null)
    {
        foreach ($groups as $data) {
            $label = $data['label'];
            $options = $data['options'];

            // Build group
            $group = $factory->buildHtmlElement('optgroup', '', '', '', [
                'label' => $label,
            ]);

            // Add options to group
            self::setOptions($factory, $group, $options, $checkedValue);

            // Append group to container
            $factory->getHTMLHandler()->append($select, $group);
        }
    }
}


text:
function ellipseXIntercept(yi, rx, ry)
{
    return rx * Math.sqrt(1 - (yi * yi) / (ry * ry));
}

function scanConvertRoundedRectangleOutside(r, height, lineHeight, corner)
{
    var intervals = [];
    var upperCorner = true;
    var lowerCorner = true;

    if (corner == "upper")
        lowerCorner = false;
    else if (corner == "lower")
        upperCorner = false;

    for (var y = 0; y < height; y += lineHeight) {
        if (y + lineHeight <= r.y || y >= r.y + r.height)
            continue;

        if (upperCorner && (y + lineHeight < r.y + r.ry)) {
            // within the upper rounded corner part of the rectangle
            var dx = ellipseXIntercept(y + lineHeight - r.y - r.ry, r.rx, r.ry);
            intervals.push( { y: y, left: r.x + r.rx - dx, right: r.x + r.width - r.rx + dx} );
        }
        else if (lowerCorner && (y > r.y + r.height - r.ry)) {
            // within the lower rounded corner part of the rectangle
            var dx = ellipseXIntercept(y - (r.y + r.height - r.ry), r.rx, r.ry);
            intervals.push( { y: y, left: r.x + r.rx - dx, right: r.x + r.width - r.rx + dx} );
        }
        else // within the rectangle's vertical edges
            intervals.push( {y: y, left: r.x, right: r.x + r.width} );
    }

    return intervals;
}

function genLeftRoundedRectFloatShapeOutsideRefTest(args)
{
    var leftRoundedRect = args.roundedRect;
    var leftRoundedRectIntervals = scanConvertRoundedRectangleOutside(leftRoundedRect, args.containerHeight, args.lineHeight, args.corner);
    var leftFloatDivs = leftRoundedRectIntervals.map(function(interval) {
        var width = SubPixelLayout.snapToLayoutUnit(interval.right);
        var cls = "left-" + args.floatElementClassSuffix;
        return '

';
    });
    document.getElementById("left-" + args.insertElementIdSuffix).insertAdjacentHTML('afterend', leftFloatDivs.join("\n"));
    return leftFloatDivs;
}

function getRoundedRectLeftEdge(args)
{
    var leftRoundedRect = args.roundedRect;
    var leftRoundedRectIntervals = scanConvertRoundedRectangleOutside(leftRoundedRect, args.containerHeight, args.lineHeight, args.corner);
    var leftSidePoints = leftRoundedRectIntervals.map(function(interval) {
        var width = SubPixelLayout.snapToLayoutUnit(interval.right);
        return width;
    });
    return leftSidePoints;
}

function genRightRoundedRectFloatShapeOutsideRefTest(args)
{
    var rightRoundedRect = Object.create(args.roundedRect);
    rightRoundedRect.x = args.containerWidth - args.roundedRect.width;
    var rightRoundedRectIntervals = scanConvertRoundedRectangleOutside(rightRoundedRect, args.containerHeight, args.lineHeight, args.corner);
    var rightFloatDivs = rightRoundedRectIntervals.map(function(interval) {
        var width = args.containerWidth - SubPixelLayout.snapToLayoutUnit(interval.left);
        var cls = "right-" + args.floatElementClassSuffix;
        return '

';
    });
    document.getElementById("right-" + args.insertElementIdSuffix).insertAdjacentHTML('afterend', rightFloatDivs.join("\n"));
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WordSearchBackground
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            // This event handler is called when the background thread finishes.
            // This method runs on the main thread.
            if (e.Error != null)
            {
                MessageBox.Show("Error: " + e.Error.Message);
            }
            else if (e.Cancelled)
            {
                MessageBox.Show("Word counting cancelled.");
            }
            else
            {
                MessageBox.Show("Finished counting words");
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            // This method runs on the main thread.
            Words.CurrentState state = (Words.CurrentState)e.UserState;
            this.txtLinesCounted.Text = state.LinesCounted.ToString();
            this.txtWrodsCounted.Text = state.WordsCounted.ToString();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            // The event handler is where the actual work is done.
            // This method runs on the background thread.

            // Get the BackgroundWorker object that raised this event.
            BackgroundWorker worker = (BackgroundWorker)sender;

            // Get the Words object and call the main method.
            Words words = (Words)e.Argument;
            words.CountWords(worker, e);
        }

        private void StartThread()
        {
            // This method runs on the main thread.
            this.txtWrodsCounted.Text = "0";

            // Initialize the object that the background worker calls.
            Words words = new Words();
            words.CompareString = this.txtCompareString.Text;
            words.SourceFile = this.txtSourceFile.Text;

            // Start the asynchronous operation.
            backgroundWorker1.RunWorkerAsync(words);
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            StartThread();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            // Cancel the asynchronous operation.
            this.backgroundWorker1.CancelAsync();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}


text:
require "vagrant"
require_relative "communicator"

module VagrantPlugins
  module F5
    class Plugin < Vagrant.plugin("2")
      name "f5 communicator"
      description <<-DESC
      This plugin allows Vagrant to communicate with remote machines using
      SSH as the underlying protocol for F5 BIG-IP machines,
      powered internally by Ruby's net-ssh library.
      DESC

      communicator("f5") do
        Communicator
      end

      config(:f5, :provisioner) do
        require File.expand_path("../config", __FILE__)
        Config
      end

      provisioner(:f5) do
        require File.expand_path("../provisioner", __FILE__)
        Provisioner
      end
    end
  end
end


text:
/*
 *  @author  Anthony Chan
 */

package logformat.clog;

import java.io.*;

// Extend java.io.DataInputStream to include a readString() method
public class MixedDataInputStream extends DataInputStream
{
    public MixedDataInputStream( InputStream in )
    {
        super( in );
    }

    // Return a trimed String from reading the Stream with a temporary buffer
    public String readString( int bytesize ) throws IOException
    {
        byte[] bytebuf = new byte[ bytesize ];
        super.readFully( bytebuf );
        return ( new String( bytebuf ) ).trim();
    }
}


text:
require 'test/unit'
require 'rexml/document'
require '_loadpath'
require 'openwsman'
require '_client'

class WsmanTest < Test::Unit::TestCase
  def test_client
    client = Client.open
    assert client
    options = Openwsman::ClientOptions.new
    assert options
#    options.set_dump_request
    uri = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_OperatingSystem"
#    uri = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_HostedService"
#    uri = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_CommMechanismForManager"
#    uri = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ManagedElement"
    result = client.enumerate( options, nil, uri )
    assert result
#    puts result

    count = 0
    context = result.context
    while (context)
	count += 1
	result = client.pull( options, nil, uri, context )
	puts "Response ##{count}"
#	puts "### #{result}"
	result.body["PullResponse"]["Items"].child.each { |child|
	    puts "\t#{child.name} = #{child.text}"
	}
	context = result.context
    end
    client.release( options, uri, context ) if context
    puts "Got #{count} responses"
  end
end


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>http::serializer::is_header_done</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../index.html" title="Chapter 1. Boost.Beast">
<link rel="up" href="../boost__beast__http__serializer.html" title="http::serializer">
<link rel="prev" href="is_done.html" title="http::serializer::is_done">
<link rel="next" href="limit.html" title="http::serializer::limit">

Home
Libraries
People
FAQ
More

http::serializer::is_header_done

Return true
          if serialization of the header is complete.

          Synopsis

bool
is_header_done();

          Description

          This function indicates whether or not all buffers containing serialized
          header octets have been retrieved.

Copyright © 2016, 2017 Vinnie Falco

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


text:
require 'base64'
require 'cgi'
require 'stringio'

require 'plist/generator'
require 'plist/parser'

module Plist
  VERSION = '3.1.0'
end


text:
import six
from six.moves.urllib import parse

import rally
from rally.common import db
from rally.common import objects
from rally import consts
from rally.deployment import engine

@engine.configure(name="MultihostEngine")
class MultihostEngine(engine.Engine):
    """Deploy multihost cloud with existing engines.

    Sample configuration:

        {
            "type": "MultihostEngine",
            "controller": {
                "type": "DevstackEngine",
                "provider": {
                    "type": "DummyProvider"
                }
            },
            "nodes": [
                {"type": "Engine1", "config": "Config1"},
                {"type": "Engine2", "config": "Config2"},
                {"type": "Engine3", "config": "Config3"},
            ]
        }

    If {controller_ip} is specified in configuration values, it will be
    replaced with controller address taken from endpoint returned by
    controller engine:

        ...
        "nodes": [
            {
                "type": "DevstackEngine",
                "localrc": {
                    "GLANCE_HOSTPORT": "{controller_ip}:9292",
        ...
    """

    def __init__(self, *args, **kwargs):
        super(MultihostEngine, self).__init__(*args, **kwargs)
        self.config = self.deployment["config"]
        self.nodes = []

    def _deploy_node(self, config):
        deployment = objects.Deployment(config=config,
                                        parent_uuid=self.deployment["uuid"])
        deployer = engine.Engine.get_engine(config["type"], deployment)
        with deployer:
            endpoints = deployer.make_deploy()
        return deployer, endpoints

    def _update_controller_ip(self, obj):
        if isinstance(obj, dict):
            keyval = six.iteritems(obj)
        elif isinstance(obj, list):
            keyval = enumerate(obj)

        for key, value in keyval:
            if isinstance(value, six.string_types):
                obj[key] = value.format(controller_ip=self.controller_ip)
            elif type(value) in (dict, list):
                self._update_controller_ip(value)

    def deploy(self):
        self.deployment.update_status(consts._DeployStatus.DEPLOY_SUBDEPLOY)
        self.controller, self.endpoints = self._deploy_node(
            self.config["controller"])
        endpoint = self.endpoints[0]
        self.controller_ip = parse.urlparse(endpoint.auth_url).hostname

        for node_config in self.config["nodes"]:
            self._update_controller_ip(node_config)
            self.nodes.append(self._deploy_node(node_config)[0])
        return self.endpoints

    def cleanup(self):
        subdeploys = db.deployment_list(parent_uuid=self.deployment["uuid"])
        for subdeploy in subdeploys:
            rally.api.Deployment.destroy(subdeploy["uuid"])


text:
// --------------------------------------------------------------------------
// Tethys.Framework
// ==========================================================================
//
// This library contains common code for WPF, Silverlight, Windows Phone and
// Windows 8 projects.
//
// ===========================================================================
//
// <copyright file="SimpleDiff.cs" company="Tethys">
// Copyright  1998-2020 by Thomas Graf
//            All rights reserved.
//            Licensed under the Apache License, Version 2.0.
//            Unless required by applicable law or agreed to in writing,
//            software distributed under the License is distributed on an
//            "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
//            either express or implied.
// </copyright>
//
// System ... netstandard2.0
// Tools .... Microsoft Visual Studio 2019
//
// ---------------------------------------------------------------------------

namespace Tethys.Text
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;

    ///
    /// SimpleDiff implements as simple LCS algorithm.
    /// LCS = Longest common subsequence, see this
    /// link.
    /// for details.
    ///
    /// <remarks>
    /// Parts of this code are based on code of <c>Nish Sivakumar</c>.
    /// The original article can be found here
    ///
    /// link and the original code is licensed by the Code Project Open
    /// License (CPOL).
    /// </remarks>
    public class SimpleDiff
    {
        #region PRIVATE PROPERTIES
        ///
        /// Left side.
        ///
        private readonly string[] left;

        ///
        /// Right side.
        ///
        private readonly string[] right;

        ///
        /// The matrix.
        ///
        [SuppressMessage(
            "Microsoft.Performance",
            "CA1814:PreferJaggedArraysOverMultidimensional",
            MessageId = "Member",
            Justification = "Best solution here.")]
        private int[,] matrix;

        ///
        /// Matrix creation flag.
        ///
        private bool matrixCreated;

        ///
        /// Pre skip value.
        ///
        private int preSkip;

        ///
        /// Post skip value.
        ///
        private int postSkip;
        #endregion // PRIVATE PROPERTIES

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

        #region PUBLIC PROPERTIES
        ///
        /// Line update event.
        ///
        public event EventHandler<DiffEventArgs> LineUpdate;
        #endregion // PUBLIC PROPERTIES

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

        #region CONSTRUCTION
        ///
        /// Initializes a new instance of the <see cref="SimpleDiff"/> class.
        ///
        /// <param name="left">The left.</param>
        /// <param name="right">The right.</param>
        public SimpleDiff(string[] left, string[] right)
        {
            this.left = left;
            this.right = right;
        } // SimpleDiff()
        #endregion // CONSTRUCTION

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

        #region PUBLIC METHODS
        ///
        /// This is the sole public method and it initializes
        /// the LCS matrix the first time it's called, and
        /// proceeds to fire a series of LineUpdate event.
        ///
        public void RunDiff()
        {
            if (!this.matrixCreated)
            {
                this.CalculatePreSkip();
                this.CalculatePostSkip();
                this.CreateLcsMatrix();
            } // if

            for (var i = 0; i < this.preSkip; i++)
            {
                this.FireLineUpdate(DiffType.None, this.left[i], i);
            } // for

            var totalSkip = this.preSkip + this.postSkip;
            this.ShowDiff(
                this.left.Length - totalSkip,
                this.right.Length - totalSkip);

            var leftLen = this.left.Length;
            for (var i = this.postSkip; i > 0; i--)
            {
                this.FireLineUpdate(
                    DiffType.None,
                    this.left[leftLen - i],
                    leftLen - i);
            } // for
        } // RunDiff()
        #endregion // PUBLIC METHODS

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

        #region PRIVATE METHODS
        ///
        /// This comparison is specifically
        /// for strings, and was nearly thrice as
        /// fast as the default comparison operation.
        ///
        /// <param name="left">The left.</param>
        /// <param name="right">The right.</param>
        /// <returns>A value indicating whether both string are the same.</returns>
        private static bool StringCompare(string left, string right)
        {
            return Equals(left, right);
        } // StringCompare()

        ///
        /// This method is an optimization that
        /// skips matching elements at the end of the
        /// two arrays being compared.
        /// Care's taken so that this will never
        /// overlap with the pre-skip.
        ///
        private void CalculatePostSkip()
        {
            var leftLen = this.left.Length;
            var rightLen = this.right.Length;
            while (this.postSkip < leftLen && this.postSkip < rightLen &&
                this.postSkip < (leftLen - this.preSkip) &&
                StringCompare(
                    this.left[leftLen - this.postSkip - 1],
                    this.right[rightLen - this.postSkip - 1]))
            {
                this.postSkip++;
            } // while
        } // CalculatePostSkip()

        ///
        /// This method is an optimization that
        /// skips matching elements at the start of
        /// the arrays being compared.
        ///
        private void CalculatePreSkip()
        {
            var leftLen = this.left.Length;
            var rightLen = this.right.Length;
            while (this.preSkip < leftLen && this.preSkip < rightLen &&
                StringCompare(this.left[this.preSkip], this.right[this.preSkip]))
            {
                this.preSkip++;
            } // while
        } // CalculatePreSkip()

#if true
        ///
        /// This traverses the elements using the LCS matrix
        /// and fires appropriate events for added, subtracted,
        /// and unchanged lines.
        /// It's recursively called till we run out of items.
        ///
        /// <param name="leftIndex">Index of the left.</param>
        /// <param name="rightIndex">Index of the right.</param>
        /// <remarks>
        /// Note: This is the improved non-recursive version.
        /// </remarks>
        private void ShowDiff(int leftIndex, int rightIndex)
        {
            var updates = new List<DiffEventArgs>();

            while (leftIndex > 0 || rightIndex > 0)
            {
                if (leftIndex > 0 && rightIndex > 0 &&
                    StringCompare(
                        this.left[this.preSkip + leftIndex - 1],
                        this.right[this.preSkip + rightIndex - 1]))
                {
                    updates.Add(new DiffEventArgs(
                        DiffType.None,
                        this.left[this.preSkip + leftIndex - 1],
                        this.preSkip + leftIndex - 1));
                    leftIndex--;
                    rightIndex--;
                }
                else
                {
                    if (rightIndex > 0 &&
                        (leftIndex == 0 ||
                        this.matrix[leftIndex, rightIndex - 1]
                        >= this.matrix[leftIndex - 1, rightIndex]))
                    {
                        updates.Add(new DiffEventArgs(
                            DiffType.Add,
                            this.right[this.preSkip + rightIndex - 1],
                            this.preSkip + rightIndex - 1));
                        rightIndex--;
                    }
                    else if (leftIndex > 0 &&
                      (rightIndex == 0 ||
                      this.matrix[leftIndex, rightIndex - 1]
                        < this.matrix[leftIndex - 1, rightIndex]))
                    {
                        updates.Add(new DiffEventArgs(
                            DiffType.Subtract,
                            this.left[this.preSkip + leftIndex - 1],
                            this.preSkip + leftIndex - 1));
                        leftIndex--;
                    }
                }
            }

            for (var i = updates.Count - 1; i >= 0; i--)
            {
                var update = updates[i];
                this.FireLineUpdate(update.DiffType, update.LineValue, update.LineIndex);
            } // for
        } // ShowDiff()
#else
        ///
        /// This traverses the elements using the LCS matrix
        /// and fires appropriate events for added, subtracted,
        /// and unchanged lines.
        /// It's recursively called till we run out of items.
        ///
        /// <param name="leftIndex">Index of the left.</param>
        /// <param name="rightIndex">Index of the right.</param>
        /// <remarks>
        /// Note: This is the original - RECURSIVE - version.
        /// </remarks>
        private void ShowDiff(int leftIndex, int rightIndex)
        {
            if (leftIndex > 0 && rightIndex > 0 &&
                StringCompare(this.left[this.preSkip + leftIndex - 1],
                this.right[this.preSkip + rightIndex - 1]))
            {
                this.ShowDiff(leftIndex - 1, rightIndex - 1);
                this.FireLineUpdate(DiffType.None,
                  this.left[this.preSkip + leftIndex - 1],
                  this.preSkip + leftIndex - 1);
            }
            else
            {
                if (rightIndex > 0 &&
                    (leftIndex == 0 ||
                     this.matrix[leftIndex, rightIndex - 1] >=
                     this.matrix[leftIndex - 1, rightIndex]))
                {
                    this.ShowDiff(leftIndex, rightIndex - 1);
                    this.FireLineUpdate(DiffType.Add,
                      this.right[this.preSkip + rightIndex - 1],
                      this.preSkip + rightIndex - 1);
                }
                else if (leftIndex > 0 && (rightIndex == 0 ||
                      this.matrix[leftIndex, rightIndex - 1] <
                      this.matrix[leftIndex - 1, rightIndex]))
                {
                    this.ShowDiff(leftIndex - 1, rightIndex);
                    this.FireLineUpdate(DiffType.Subtract,
                      this.left[this.preSkip + leftIndex - 1],
                      this.preSkip + leftIndex - 1);
                } // if
            } // if
        } // ShowDiff()
#endif

        ///
        /// This is the core method in the entire class,
        /// and uses the standard LCS calculation algorithm.
        ///
        [SuppressMessage(
            "Microsoft.Performance",
            "CA1814:PreferJaggedArraysOverMultidimensional",
            MessageId = "Body",
            Justification = "Best solution here.")]
        private void CreateLcsMatrix()
        {
            var totalSkip = this.preSkip + this.postSkip;
            if (totalSkip >= this.left.Length || totalSkip >= this.right.Length)
            {
                return;
            } // if

            // We only create a matrix large enough for the
            // unskipped contents of the diff'ed arrays
            this.matrix = new int[
                this.left.Length - totalSkip + 1,
                this.right.Length - totalSkip + 1];

            for (var i = 1; i <= this.left.Length - totalSkip; i++)
            {
                // Simple optimization to avoid this calculation
                // inside the outer loop (may have got JIT optimized
                // but my tests showed a minor improvement in speed)
                var leftIndex = this.preSkip + i - 1;

                // Again, instead of calculating the adjusted index inside
                // the loop, I initialize it under the assumption that
                // incrementing will be a faster operation on most CPUs
                // compared to addition. Again, this may have got JIT
                // optimized but my tests showed a minor speed difference.
                for (int j = 1, rightIndex = this.preSkip + 1;
                    j <= this.right.Length - totalSkip; j++, rightIndex++)
                {
                    this.matrix[i, j] = StringCompare(
                        this.left[leftIndex],
                        this.right[rightIndex - 1]) ?
                        this.matrix[i - 1, j - 1] + 1 :
                        Math.Max(this.matrix[i, j - 1], this.matrix[i - 1, j]);
                } // for
            } // for

            this.matrixCreated = true;
        } // CreateLCSMatrix()

        ///
        /// Fires the line update.
        ///
        /// <param name="diffType">Type of the diff.</param>
        /// <param name="lineValue">The line value.</param>
        /// <param name="index">The index.</param>
        private void FireLineUpdate(DiffType diffType, string lineValue, int index)
        {
            var local = this.LineUpdate;

            local?.Invoke(this, new DiffEventArgs(diffType, lineValue, index));
        } // FireLineUpdate()
        #endregion // PRIVATE METHODS
    } // SimpleDiff
} // Tethys.Text.Diff

// ====================
// End of SimpleDiff.cs
// ====================