text:
package org.powlab.jeye.decode

import org.powlab.jeye.core._
import org.powlab.jeye.core.Types._
import org.powlab.jeye.core.Descriptors._
import org.powlab.jeye.core.parsing.DescriptorParser._
import org.powlab.jeye.decode.expra.ExpressionHelpers._
import org.powlab.jeye.decode.processor.stack.StackInformator._
import org.powlab.jeye.decode.processor.conversion._
import org.powlab.jeye.decode.expression._
import org.powlab.jeye.utils.ConstantPoolUtils
import org.powlab.jeye.utils.AttributeUtils
import scala.collection.mutable.Map
import scala.collection.mutable.ArrayBuffer
import org.powlab.jeye.decode.expression.ConversionExpression

/**
 * Работа с локальными переменными
 */
object LocalVariableTrace {

  def apply(): LocalVariableTrace = {
    new LocalVariableTrace()
  }

}

private class Trace(val variable: LocalVariable, val descriptor: ParameterDescriptor)

class LocalVariableTrace() {
  private var completed: Boolean = false
  private val traces = new ArrayBuffer[Trace]
  private val descriptors = Map[Int, ParameterDescriptor]()

  def add(variable: LocalVariable) {
    add(variable, variable.descriptor)
  }

  def add(variable: LocalVariable, descriptor: ParameterDescriptor) {
    traces += new Trace(variable, descriptor)
  }

  def complete() {
    completed = true
    traces.filter(! _.variable.isSynthetic).foreach(trace => {
      val descriptor = trace.descriptor
      val variable = trace.variable
      if (!descriptors.contains(variable.index)) {
        descriptors.put(variable.index, descriptor)
      } else {
        val keepedDescriptor = descriptors(variable.index)
        // работа с примитивами
        if (isSubInt(descriptor.baseType)) {
          descriptors.put(variable.index, descriptor)
        }
      }
    })
  }

  def analyze(index: Int, variable: ITypedExpression): ITypedExpression = {
    if (! descriptors.contains(index)) {
      return variable
    }
    val descriptor = descriptors(index)
    if (! isIntable(descriptor.baseType)) {
      return variable
    }
    return convertLiteral(variable, descriptor.baseType)
  }

  def checkcast(variable: ITypedExpression, descriptor: ParameterDescriptor): ITypedExpression = {
    if (descriptor == TYPE_INT_DESCRIPTOR && isSubIntDesc(variable.descriptor)) {
        return ConversionExpression(descriptor.baseType, variable)
    }
    variable
  }

}


text:
(function () {
  'use strict';

  /**
   * @ngdoc controller
   * @name LaunchInstanceSourceController
   * @description
   * The `LaunchInstanceSourceController` controller provides functions for
   * configuring the source step of the Launch Instance Wizard.
   *
   */
  var push = [].push;

  angular
    .module('hz.dashboard.launch-instance')
    .controller('LaunchInstanceSourceController', LaunchInstanceSourceController);

  LaunchInstanceSourceController.$inject = [
    '$scope',
    'hz.dashboard.launch-instance.boot-source-types',
    'bytesFilter',
    'horizon.framework.widgets.charts.donutChartSettings',
    'dateFilter',
    'decodeFilter',
    'diskFormatFilter',
    'gbFilter',
    'horizon.framework.widgets.charts.quotaChartDefaults',
    'dashboardBasePath'
  ];

  function LaunchInstanceSourceController($scope,
    bootSourceTypes,
    bytesFilter,
    donutChartSettings,
    dateFilter,
    decodeFilter,
    diskFormatFilter,
    gbFilter,
    quotaChartDefaults,
    basePath) {

    var ctrl = this;
    ctrl.label = {
      title: gettext('Instance Details'),
      /*eslint-disable max-len */
      subtitle: gettext('Please provide the initial host name for the instance, the availability zone where it will be deployed, and the instance count. Increase the Count to create multiple instances with the same settings.'),
      /*eslint-enable max-len */
      instanceName: gettext('Instance Name'),
      availabilityZone: gettext('Availability Zone'),
      instance_count: gettext('Count'),
      instanceSourceTitle: gettext('Instance Source'),
      /*eslint-disable max-len */
      instanceSourceSubTitle: gettext('Instance source is the template used to create an instance. You can use a snapshot of an existing instance, an image, or a volume (if enabled). You can also choose to use persistent storage by creating a new volume.'),
      /*eslint-enable max-len */
      bootSource: gettext('Select Boot Source'),
      volumeSize: gettext('Size (GB)'),
      volumeCreate: gettext('Create New Volume'),
      volumeDeviceName: gettext('Device Name'),
      deleteVolumeOnTerminate: gettext('Delete Volume on Terminate'),
      id: gettext('ID'),
      min_ram: gettext('Min Ram'),
      min_disk: gettext('Min Disk')
    };

    // Error text for invalid fields
    /*eslint-disable max-len */
    ctrl.bootSourceTypeError = gettext('Volumes can only be attached to 1 active instance at a time. Please either set your instance count to 1 or select a different source type.');
    /*eslint-enable max-len */
    ctrl.instanceNameError = gettext('A name is required for your instance.');
    ctrl.instanceCountError = gettext(
      'Instance count is required and must be an integer of at least 1'
    );
    ctrl.volumeSizeError = gettext('Volume size is required and must be an integer');

    // toggle button label/value defaults
    ctrl.toggleButtonOptions = [
      { label: gettext('Yes'), value: true },
      { label: gettext('No'), value: false }
    ];

    /*
     * Boot Sources
     */
    ctrl.bootSourcesOptions = [
      { type: bootSourceTypes.IMAGE, label: gettext('Image') },
      { type: bootSourceTypes.INSTANCE_SNAPSHOT, label: gettext('Instance Snapshot') },
      { type: bootSourceTypes.VOLUME, label: gettext('Volume') },
      { type: bootSourceTypes.VOLUME_SNAPSHOT, label: gettext('Volume Snapshot') }
    ];

    ctrl.updateBootSourceSelection = updateBootSourceSelection;

    /*
     * Transfer table
     */
    ctrl.tableHeadCells = [];
    ctrl.tableBodyCells = [];
    ctrl.tableData = {};
    ctrl.helpText = {};
    ctrl.maxInstanceCount = 1;
    ctrl.sourceDetails = basePath + 'launch-instance/source/source-details.html';

    var selection = ctrl.selection = $scope.model.newInstanceSpec.source;

    var bootSources = {
      image: {
        available: $scope.model.images,
        allocated: selection,
        displayedAvailable: $scope.model.images,
        displayedAllocated: selection
      },
      snapshot: {
        available: $scope.model.imageSnapshots,
        allocated: selection,
        displayedAvailable: [],
        displayedAllocated: selection
      },
      volume: {
        available: $scope.model.volumes,
        allocated: selection,
        displayedAvailable: [],
        displayedAllocated: selection
      },
      volume_snapshot: {
        available: $scope.model.volumeSnapshots,
        allocated: selection,
        displayedAvailable: [],
        displayedAllocated: selection
      }
    };

    // Mapping for dynamic table headers
    var tableHeadCellsMap = {
      image: [
        { text: gettext('Name'), style: { width: '30%' }, sortable: true, sortDefault: true },
        { text: gettext('Updated'), style: { width: '15%' }, sortable: true },
        { text: gettext('Size'), style: { width: '15%' }, classList: ['number'], sortable: true },
        { text: gettext('Type'), sortable: true },
        { text: gettext('Visibility'), sortable: true }
      ],
      snapshot: [
        { text: gettext('Name'), style: { width: '30%' }, sortable: true, sortDefault: true },
        { text: gettext('Updated'), style: { width: '15%' }, sortable: true },
        { text: gettext('Size'), style: { width: '15%' }, classList: ['number'], sortable: true },
        { text: gettext('Type'), sortable: true },
        { text: gettext('Visibility'), sortable: true }
      ],
      volume: [
        { text: gettext('Name'), style: { width: '25%' }, sortable: true, sortDefault: true },
        { text: gettext('Description'), style: { width: '20%' }, sortable: true },
        { text: gettext('Size'), style: { width: '15%' }, classList: ['number'], sortable: true },
        { text: gettext('Type'), style: { width: '20%' }, sortable: true },
        { text: gettext('Availability Zone'), style: { width: '20%' }, sortable: true }
      ],
      volume_snapshot: [
        { text: gettext('Name'), style: { width: '25%' }, sortable: true, sortDefault: true },
        { text: gettext('Description'), style: { width: '20%' }, sortable: true },
        { text: gettext('Size'), style: { width: '15%' }, classList: ['number'], sortable: true },
        { text: gettext('Created'), style: { width: '15%' }, sortable: true },
        { text: gettext('Status'), style: { width: '20%' }, sortable: true }
      ]
    };

    // Map Visibility data so we can decode true/false to Public/Private
    var _visibilitymap = { true: gettext('Public'), false: gettext('Private') };

    // Mapping for dynamic table data
    var tableBodyCellsMap = {
      image: [
        { key: 'name', classList: ['hi-light'] },
        { key: 'updated_at', filter: dateFilter, filterArg: 'short' },
        { key: 'size', filter: bytesFilter, classList: ['number'] },
        { key: 'disk_format', style: { 'text-transform': 'uppercase' } },
        { key: 'is_public', filter: decodeFilter, filterArg: _visibilitymap,
          style: { 'text-transform': 'capitalize' } }
      ],
      snapshot: [
        { key: 'name', classList: ['hi-light'] },
        { key: 'updated_at', filter: dateFilter, filterArg: 'short' },
        { key: 'size', filter: bytesFilter, classList: ['number'] },
        { key: 'disk_format', style: { 'text-transform': 'uppercase' } },
        { key: 'is_public', filter: decodeFilter, filterArg: _visibilitymap,
          style: { 'text-transform': 'capitalize' } }
      ],
      volume: [
        { key: 'name', classList: ['hi-light'] },
        { key: 'description' },
        { key: 'size', filter: gbFilter, classList: ['number'] },
        { key: 'volume_image_metadata', filter: diskFormatFilter,
          style: { 'text-transform': 'uppercase' } },
        { key: 'availability_zone' }
      ],
      volume_snapshot: [
        { key: 'name', classList: ['hi-light'] },
        { key: 'description' },
        { key: 'size', filter: gbFilter, classList: ['number'] },
        { key: 'created_at', filter: dateFilter, filterArg: 'short' },
        { key: 'status', style: { 'text-transform': 'capitalize' } }
      ]
    };

    /*
     * Donut chart
     */
    ctrl.chartSettings = donutChartSettings;
    var maxTotalInstances = 1; // Must have default value > 0
    var totalInstancesUsed = 0;

    if ($scope.model.novaLimits && $scope.model.novaLimits.maxTotalInstances) {
      maxTotalInstances = $scope.model.novaLimits.maxTotalInstances;
    }

    if ($scope.model.novaLimits && $scope.model.novaLimits.totalInstancesUsed) {
      totalInstancesUsed = $scope.model.novaLimits.totalInstancesUsed;
    }

    ctrl.instanceStats = {
      title: gettext('Total Instances'),
      maxLimit: maxTotalInstances,
      label: '100%',
      data: [
        {
          label: quotaChartDefaults.usageLabel,
          value: 1,
          colorClass: quotaChartDefaults.usageColorClass
        },
        {
          label: quotaChartDefaults.addedLabel,
          value: 1,
          colorClass: quotaChartDefaults.addedColorClass
        },
        {
          label: quotaChartDefaults.remainingLabel,
          value: 1,
          colorClass: quotaChartDefaults.remainingColorClass
        }
      ]
    };

    var newSpecWatcher = $scope.$watch(
      function () {
        return $scope.model.newInstanceSpec.instance_count;
      },
      function (newValue, oldValue) {
        if (newValue !== oldValue) {
          updateChart();
          validateBootSourceType();
        }
      }
    );

    var maxInstancesWatcher = $scope.$watch(
      function () {
        return $scope.model.novaLimits.maxTotalInstances;
      },
      function (newValue, oldValue) {
        if (newValue !== oldValue) {
          maxTotalInstances = Math.max(1, newValue);
          updateChart();
          updateMaxInstanceCount();
        }
      }
    );

    var instancesUsedWatcher = $scope.$watch(
      function () {
        return $scope.model.novaLimits.totalInstancesUsed;
      },
      function (newValue, oldValue) {
        if (newValue !== oldValue) {
          totalInstancesUsed = newValue;
          updateChart();
          updateMaxInstanceCount();
        }
      }
    );

    var allocatedWatcher = $scope.$watch(
      function () {
        return ctrl.tableData.allocated.length;
      },
      function (newValue, oldValue) {
        if (newValue !== oldValue) {
          updateChart();
        }
        checkVolumeForImage(newValue);
      }
    );

    var imagesWatcher = $scope.$watchCollection(
      function () {
        return $scope.model.images;
      },
      function () {
        $scope.initPromise.then(function () {
          $scope.$applyAsync(function () {
            if ($scope.launchContext.imageId) {
              setSourceImageWithId($scope.launchContext.imageId);
            }
          });
        });
      }
    );

    // Explicitly remove watchers on desruction of this controller
    $scope.$on('$destroy', function() {
      newSpecWatcher();
      maxInstancesWatcher();
      instancesUsedWatcher();
      allocatedWatcher();
      imagesWatcher();
    });

    // Initialize
    changeBootSource(ctrl.bootSourcesOptions[0].type);

    if (!$scope.model.newInstanceSpec.source_type) {
      $scope.model.newInstanceSpec.source_type = ctrl.bootSourcesOptions[0];
      ctrl.currentBootSource = ctrl.bootSourcesOptions[0].type;
    }

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

    function updateBootSourceSelection(selectedSource) {
      ctrl.currentBootSource = selectedSource;
      $scope.model.newInstanceSpec.vol_create = false;
      $scope.model.newInstanceSpec.vol_delete_on_terminate = false;
      changeBootSource(selectedSource);
      validateBootSourceType();
    }

    // Dynamically update page based on boot source selection
    function changeBootSource(key, preSelection) {
      updateDataSource(key, preSelection);
      updateHelpText(key);
      updateTableHeadCells(key);
      updateTableBodyCells(key);
      updateChart();
      updateMaxInstanceCount();
    }

    function updateDataSource(key, preSelection) {
      selection.length = 0;
      if (preSelection) {
        push.apply(selection, preSelection);
      }
      angular.extend(ctrl.tableData, bootSources[key]);
    }

    function updateHelpText() {
      angular.extend(ctrl.helpText, {
        noneAllocText: gettext('Select a source from those listed below.'),
        availHelpText: gettext('Select one'),
        /*eslint-disable max-len */
        volumeAZHelpText: gettext('When selecting volume as boot source, please ensure the instance\'s availability zone is compatible with your volume\'s availability zone.')
        /*eslint-enable max-len */
      });
    }

    function updateTableHeadCells(key) {
      refillArray(ctrl.tableHeadCells,  tableHeadCellsMap[key]);
    }

    function updateTableBodyCells(key) {
      refillArray(ctrl.tableBodyCells, tableBodyCellsMap[key]);
    }

    function refillArray(arrayToRefill, contentArray) {
      arrayToRefill.length = 0;
      Array.prototype.push.apply(arrayToRefill, contentArray);
    }

    function updateChart() {
      // Initialize instance_count to 1
      if ($scope.model.newInstanceSpec.instance_count <= 0) {
        $scope.model.newInstanceSpec.instance_count = 1;
      }

      var data = ctrl.instanceStats.data;
      var added = $scope.model.newInstanceSpec.instance_count || 1;
      var remaining = Math.max(0, maxTotalInstances - totalInstancesUsed - added);

      ctrl.instanceStats.maxLimit = maxTotalInstances;
      data[0].value = totalInstancesUsed;
      data[1].value = added;
      data[2].value = remaining;
      var quotaCalc = Math.round((totalInstancesUsed + added) / maxTotalInstances * 100);
      ctrl.instanceStats.overMax = quotaCalc > 100 ? true : false;
      ctrl.instanceStats.label = quotaCalc + '%';
      ctrl.instanceStats = angular.extend({}, ctrl.instanceStats);
    }

    /*
     * Validation
     */

    /*
     * If boot source type is 'image' and 'Create New Volume' is checked, set the minimum volume
     * size for validating vol_size field
     */
    function checkVolumeForImage() {
      var source = selection ? selection[0] : undefined;

      if (source && ctrl.currentBootSource === bootSourceTypes.IMAGE) {
        var imageGb = source.size * 1e-9;
        var imageDisk = source.min_disk;
        ctrl.minVolumeSize = Math.ceil(Math.max(imageGb, imageDisk));

        var volumeSizeText = gettext('The volume size must be at least %(minVolumeSize)s GB');
        var volumeSizeObj = { minVolumeSize: ctrl.minVolumeSize };
        ctrl.minVolumeSizeError = interpolate(volumeSizeText, volumeSizeObj, true);
      } else {
        ctrl.minVolumeSize = undefined;
      }
    }

    // Update the maximum instance count based on nova limits
    function updateMaxInstanceCount() {
      ctrl.maxInstanceCount = maxTotalInstances - totalInstancesUsed;

      var instanceCountText = gettext(
        'The instance count must not exceed your quota available of %(maxInstanceCount)s instances'
      );
      var instanceCountObj = { maxInstanceCount: ctrl.maxInstanceCount };
      ctrl.instanceCountMaxError = interpolate(instanceCountText, instanceCountObj, true);
    }

    // Validator for boot source type. Instance count must to be 1 if volume selected
    function validateBootSourceType() {
      var bootSourceType = ctrl.currentBootSource;
      var instanceCount = $scope.model.newInstanceSpec.instance_count;

      /*
       * Field is valid if boot source type is not volume, instance count is blank/undefined
       * (this is an error with instance count) or instance count is 1
       */
      var isValid = bootSourceType !== bootSourceTypes.VOLUME ||
                    !instanceCount ||
                    instanceCount === 1;

      $scope.launchInstanceSourceForm['boot-source-type']
            .$setValidity('bootSourceType', isValid);
    }

    function findSourceById(sources, id) {
      var len = sources.length;
      var source;
      for (var i = 0; i < len; i++) {
        source = sources[i];
        if (source.id === id) {
          return source;
        }
      }
    }

    function setSourceImageWithId(id) {
      var pre = findSourceById($scope.model.images, id);
      if (pre) {
        changeBootSource(bootSourceTypes.IMAGE, [pre]);
        $scope.model.newInstanceSpec.source_type = ctrl.bootSourcesOptions[0];
        ctrl.currentBootSource = ctrl.bootSourcesOptions[0].type;
      }
    }
  }
})();

redpajama_set_name: RedPajamaGithub


text:
module ParserTest
(runTests
) where
import Parser
import Structure

assertFileParsesTo :: String -> Script -> IO Bool
assertFileParsesTo fileName expectedResult =
  do parseResult <- parseFile fileName
     return $ parseResult == expectedResult

assertSimpleArith =
  assertFileParsesTo
    "../test/parse/simple-arith.dom"
    (Script [
      ArithmeticExp (
        ArithmeticOperation
          Subtract
          (ArithmeticOperation Add (IntLiteral 5) (ArithmeticOperation Multiply (IntLiteral 4) (IntLiteral 9)))
          (IntLiteral 3))])

assertSimpleBool =
  assertFileParsesTo
    "../test/parse/simple-bool.dom"
    (Script [
      BooleanExp (
        BooleanOperation
          And
          (BooleanOperation
            And
            IsTrue
            (BooleanOperation
              Or
              (RelationalOperation
                Greater
                  (IntLiteral 4)
                  (IntLiteral 2))
              IsFalse))
          (Negate
            (RelationalOperation
              Equal
              (IntLiteral 3)
              (IntLiteral 3))))])

assertSimpleBinding =
  assertFileParsesTo
  "../test/parse/simple-binding.dom"
  (Script [
    Declare (
      BindValue
        "myval"
        (ArithmeticExp
          (IntLiteral 8))),
    Declare(
      BindValue
      "myval"
      (ArithmeticExp
        (Variable
          (Value "varname"))))])

assertSimpleFunction =
  assertFileParsesTo
  "../test/parse/simple-function.dom"
  (Script [
    FunctionExp (
      Function
        "twoTimesThree"
        (ArithmeticExp (
          ArithmeticOperation
            Multiply
            (IntLiteral 2)
            (IntLiteral 3)))),
    FunctionExp (
      FunctionWithParams
        "timesTwo"
        ["num"]
        (ArithmeticExp (
          ArithmeticOperation
            Multiply
            (Variable (Value "num"))
            (IntLiteral 2))))])

assertSimpleApplication =
  assertFileParsesTo
  "../test/parse/simple-application.dom"
  (Script [
    FunctionEval (
      FunctionCall
        (ValueOf (Value "timeTwo"))
        (ArithmeticExp (IntLiteral 4))),
    FunctionEval (
      FunctionCall
        (ValueOf (Value "timesTwo"))
        (ArithmeticExp (
          ArithmeticOperation
            Multiply
            (IntLiteral 2)
            (Variable (Value "myvar")))))])

testAssertions :: [(String, IO Bool)] -> [IO String]
testAssertions = map statusStrings
  where statusStrings (name, iores) = do
          result <- iores
          return $ if result then "passed" else "failed: " ++ name

printTests :: [IO String] -> IO ()
printTests ioResults = do
  results <- sequence ioResults
  print results

runTests = printTests $
  testAssertions [
    ("simple-arith.dom", assertSimpleArith),
    ("simple-bool.dom", assertSimpleBool),
    ("simple-binding.dom", assertSimpleBinding),
    ("simple-function.dom", assertSimpleFunction),
    ("simple-application.dom", assertSimpleApplication)]


text:
"""Tests for filesystem elements, including Foxhound and related objects.

"""

import datreant as dtr
import pytest
import os
import py.path

class TestFoxhound:
    """Test Foxhound functionality"""

    @pytest.fixture
    def treant(self, tmpdir):
        with tmpdir.as_cwd():
            t = dtr.treants.Container('testtreant')
        return t

    @pytest.fixture
    def group(self, tmpdir):
        with tmpdir.as_cwd():
            g = dtr.Group('testgroup')
        return g


text:
class TestError < StandardError

end


text:
package no.plasmid.blopp.migration.example;

import no.plasmid.blopp.domain.domainobject.BlogEntry;
import no.plasmid.blopp.domain.domainobject.Category;
import no.plasmid.blopp.domain.domainobject.NavigationPage;
import no.plasmid.blopp.domain.domainobject.TextContent;
import no.plasmid.blopp.domain.domainrelation.ParentChild;
import no.plasmid.blopp.orientdb.OrientDBTransactionFactory;
import no.plasmid.blopp.orientdb.OrientDBTransactionWrapper;

public class Migration_20160602_2120_Blog_entries extends ExampleDataMigration {

	public Migration_20160602_2120_Blog_entries(OrientDBTransactionFactory transactionFactory) {
		super(transactionFactory);
	}

	@Override
	public String getDescription() {
		return "Create some blog entries";
	}

	@Override
	public void upgrade() {
		OrientDBTransactionWrapper transaction = transactionFactory.getTransaction();

		Category projectsCategory = NavigationPage.getFrontPage().findChild("projects");
		Category bloppCategory = new Category("Blopp");
		new ParentChild(projectsCategory, bloppCategory, "blopp");
		Category anotherCategory = new Category("Another");
		new ParentChild(projectsCategory, anotherCategory, "another");

		BlogEntry testEntry = new BlogEntry("Testing blopp");
		new ParentChild(bloppCategory, testEntry, "testing-blopp");

		TextContent leadText = testEntry.getLeadTextContent();
		String lead1 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent dapibus tincidunt massa, vel varius lorem suscipit a. "
				+ "Cras et est tempus, faucibus orci non, tincidunt eros. Pellentesque in elit congue, vulputate mi euismod, elementum tortor. "
				+ "Nulla tortor magna, ullamcorper sit amet luctus eu, suscipit ut ligula. Nullam sed elit enim. "
				+ "Pellentesque rutrum lacus ligula, sit amet ullamcorper leo dignissim et. Vestibulum nec magna eu dolor pellentesque interdum. "
				+ "Praesent pharetra libero lobortis lacinia accumsan. Fusce pretium urna elit, non ornare sapien cursus sit amet. "
				+ "Praesent auctor at sapien eget molestie. Aenean consectetur aliquet venenatis. Phasellus non mi ac felis porttitor imperdiet.";
		leadText.setContent(lead1.substring(0, 400));

		TextContent bodyText = testEntry.getBodyTextContent();
		bodyText.setContent("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent dapibus tincidunt massa, vel varius lorem suscipit a. "
				+ "Cras et est tempus, faucibus orci non, tincidunt eros. Pellentesque in elit congue, vulputate mi euismod, elementum tortor. "
				+ "Nulla tortor magna, ullamcorper sit amet luctus eu, suscipit ut ligula. Nullam sed elit enim. "
				+ "Pellentesque rutrum lacus ligula, sit amet ullamcorper leo dignissim et. Vestibulum nec magna eu dolor pellentesque interdum. "
				+ "Praesent pharetra libero lobortis lacinia accumsan. Fusce pretium urna elit, non ornare sapien cursus sit amet. "
				+ "Praesent auctor at sapien eget molestie. Aenean consectetur aliquet venenatis. Phasellus non mi ac felis porttitor imperdiet.");

		BlogEntry testEntry2 = new BlogEntry("Another article");
		new ParentChild(bloppCategory, testEntry2, "testing-blopp");

		TextContent leadText2 = testEntry2.getLeadTextContent();
		String lead2 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent dapibus tincidunt massa, vel varius lorem suscipit a. "
				+ "Cras et est tempus, faucibus orci non, tincidunt eros. Pellentesque in elit congue, vulputate mi euismod, elementum tortor. "
				+ "Nulla tortor magna, ullamcorper sit amet luctus eu, suscipit ut ligula. Nullam sed elit enim. "
				+ "Pellentesque rutrum lacus ligula, sit amet ullamcorper leo dignissim et. Vestibulum nec magna eu dolor pellentesque interdum. "
				+ "Praesent pharetra libero lobortis lacinia accumsan. Fusce pretium urna elit, non ornare sapien cursus sit amet. "
				+ "Praesent auctor at sapien eget molestie. Aenean consectetur aliquet venenatis. Phasellus non mi ac felis porttitor imperdiet.";
		leadText2.setContent(lead2.substring(0, 400));

		TextContent bodyText2 = testEntry2.getBodyTextContent();
		bodyText2.setContent("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent dapibus tincidunt massa, vel varius lorem suscipit a. "
				+ "Cras et est tempus, faucibus orci non, tincidunt eros. Pellentesque in elit congue, vulputate mi euismod, elementum tortor. "
				+ "Nulla tortor magna, ullamcorper sit amet luctus eu, suscipit ut ligula. Nullam sed elit enim. "
				+ "Pellentesque rutrum lacus ligula, sit amet ullamcorper leo dignissim et. Vestibulum nec magna eu dolor pellentesque interdum. "
				+ "Praesent pharetra libero lobortis lacinia accumsan. Fusce pretium urna elit, non ornare sapien cursus sit amet. "
				+ "Praesent auctor at sapien eget molestie. Aenean consectetur aliquet venenatis. Phasellus non mi ac felis porttitor imperdiet.");
		transaction.finish();
	}

}


text:
<?php
  // src/Ddnet/BillingBundle/Form/Type/ClientType.php

namespace Ddnet\BillingBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\CallbackValidator;
use Symfony\Component\Form\FormValidatorInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ClientType extends AbstractType {
  public function buildFormInterface(FormBuilder $builder, array $options) {
    parent::buildForm($builder, $options);

  }
  public function getName() { return 'client'; }
  public function getDefaultOptions() {
    return array('data_class' => "Ddnet\BillingBundle\Entity\Client");

  }
}


text:
The BaseClass
=============

.. currentmodule:: iperflexer.baseclass

A module for base classes that have common methods to inherit.

Just logging for now.

.. ifconfig:: repository != 'rtfd'

   .. uml::

      BaseClass o-- logging.Logger
      BaseClass : Logger

.. autosummary::
   :toctree: api

   BaseClass

Example Use::

   class TestClass(BaseClass):
       def __init__(self):
           super(TestClass, self).__init__()

   t = TestClass()
   t.logger.info("This message will get sent to the logger as INFO")


text:
package com.lithium.mineraloil.selenium.elements;

import java.util.List;

public interface SelectList {
    void select(String optionText);

    void select(String optionText, boolean closeSelectListAfterClick);

    void selectIfContains(String optionText);

    boolean isDisplayed();

    String getSelectedOption();

    List<String> getAvailableOptions();
}


text:
import os
import commands

perl = "/usr/bin/perl"
LLVM = "./LLVM-IR/"
temp_filename = "temp"
XFAIL_text = "; XFAIL: *\n"

arch_file_list = dict()
arch_file_list['lin_32e'] = ['test_omp_task_final.ll', 'test_omp_task_untied.ll']

arch_script = "../runtime/tools/check-openmp-test.pl"
arch_cmd = perl + " " + arch_script
arch = commands.getoutput(arch_cmd)
arch = arch[:len(arch)-1]

print "Adding XFAILS ..."

for f in arch_file_list[arch]:
	filename = LLVM + arch + "/" + f
	lines = open(filename).readlines()
	lines.insert(1, XFAIL_text)
	f2 = open(temp_filename, "w")
	for l in lines:
		f2.write(l)
	f2.close()

	os.system("mv " + temp_filename + " " + filename)


text:
@echo off
set REPORT_DIR=data\iris\reports_cv%3\%2
mkdir %REPORT_DIR%
Recognizer.exe --step=all --data_file=data\iris\iris.csv --class_name_column=4 --description_dir=data\iris\descriptions --reports_dir=%REPORT_DIR% --fold_count=%3 --classifier_type=%1_%2


text:
module Main where

import           Logic.Pheasant

main :: IO ()
main = return ()


text:
#ifndef QUAZIP_STATIC
    #define QUAZIP_STATIC
#endif

#include "QThread"
#include "QJsonArray"
#include "QJsonDocument"
#include "QStringList"
#include "QDir"
#include "QFile"
#include "QCryptographicHash"
#include "QTextStream"
#include "QEventLoop"

#include "quazip.h"
#include "util.h"
#include "updater.h"
#include "registry.h"
#include "mpq.h"
#include "logger.h"

/* Types
 * 0 = client
 * 1 = diff w3 patch
 * 2 = full w3 upate
 * 3 = beta
 * 4 = map
 */
Updater::Updater(Config * c, int t, QString w) {
    config=c;
    type=t;
    jsonKey=w;
    mirrorno=0;
    restartNeeded=false;
    downloader=nullptr;
    zippath = config->APPDATA+"\\patch.zip";
}

Updater::~Updater() {

}

void Updater::startUpdate() {
    /*
     * XPAM CLIENT UPDATE PROCEDURE - DOCUMENTATION
     * 1. Access 3 different update.json mirrors. 2 out of 3 must be the same for the procedure to continue
     * 2. First object is latest stable patch, second object is beta patch. Each patch has current patch version,
     *    4 mirrors to the update zip archive and sha1 hash of the archive. Patches are full, not incremental.
     *    See Other Files->update.json
     * 3. Mirrors are Google Drive, SkyDrive, Ubuntu ONE and files.eurobattle.net in that order
     * 4. If JSON patch version is bigger than your current in registry, download the archive.
     * 5. If you fail to download from the first mirror, fallback to the second etc
     * 6. When the archive is downloaded, compare the hash
     * 7. Download and extract the archive to %appdata%/Eurobattle.net
     * 8. Open instructions.txt and execute the commands
     * 9. COMMANDS
     *    MOVE <from> <to EUROPATH | W3PATH | W3PATH_126 | MAPPATH | MAPPATH_126> //always overwrite
     *    DELETE <filename> <location EUROPATH | W3PATH | MAPPATH>                //deletes a file
     *
     * 10. Cleanup %appdata$ after update
     * 11. If instructions.txt included a file called newxpam.exe then start update.bat and exit app.
     *     Update.bat removes xpam.exe and renames newxpam.exe (if it exists). Then starts xpam.exe
     *
     *
     * UPLOAD INSTRUCTIONS
     * -Google Drive: make sure you mark as public
     */
    QTime now = QTime::currentTime();
    qsrand(now.msec());

    if (downloader!=nullptr) {
        emit sendLine("FORBIDDEN RESTART");
        emit updateFinished(restartNeeded, false, false, false, type);
        return;
    }

    QByteArray j1=simpleDl(config->json1);
    QByteArray j2=simpleDl(config->json2);
    QByteArray j3=simpleDl(config->json3);

    if ((j1.isEmpty() && j2.isEmpty()) || (j1.isEmpty() && j3.isEmpty()) || (j2.isEmpty() && j3.isEmpty())) {
        emit sendLine("Update info is empty. Update servers are down or there might be a problem with your internet connection");
        emit updateFinished(restartNeeded, false, false, false, type);
        return;
    }

    QCryptographicHash h1(QCryptographicHash::Sha1);
    h1.addData(j1);
    QString sh1(h1.result().toHex());
    emit sendLine("Hash 1 is: "+sh1);
    h1.reset();
    h1.addData(j2);
    QString sh2(h1.result().toHex());
    emit sendLine("Hash 2 is: "+sh2);
    h1.reset();
    h1.addData(j3);
    QString sh3(h1.result().toHex());
    emit sendLine("Hash 3 is: "+sh3);

    if (j1==j2){
        jsonba=j1;
    }
    else if (j1==j3){
        jsonba=j1;
    }
    else if (j2==j3){
        jsonba=j2;
    }
    else {
        emit sendLine("Update info mismatch.");
        emit updateFinished(restartNeeded, false, false, false, type);
        return;
    }

    int setResult = setCurrentPlusOneJson();
    if (setResult==0){
        //Up to date client
        Logger::log("Client is up to date", config);
        emit updateFinished(restartNeeded, true, true, false, type);
        return;
    }
    else if (setResult==2){
        //No W3 patch found
        Logger::log("No W3 patch found to dl", config);
        emit updateFinished(restartNeeded, false, false, false, type);
        return;
    }

    latestVersion = qRound(real.value("version").toDouble());
    if (type==0 || type==3) {
        emit sendLine("Local version: "+QString::number(config->PATCH)+" Incremental version: "+QString::number(latestVersion));
    }

    //Tell splash screen to hide, only taken into account if it is a startup update
    //This means that we have an update so it'd be nice to see the progress
    if (type==3) emit hideSplashScreen();

    mirrors << real.value("mirror1").toString();
    mirrors << real.value("mirror2").toString();
    mirrors << real.value("mirror3").toString();
    mirrors << real.value("mirror4").toString();

    QString mirrorUrl = mirrors[mirrorno];
    if (type==2) {
        int mn = getRandomMirror();
        mirrorUrl = mirrors.at(mn);
        emit sendLine("Downloading from random: mirror "+(QString::number(mn))+" ("+mirrorUrl+")");
    }
    else {
        emit sendLine("Downloading from: mirror "+(QString::number(mirrorno))+" ("+mirrorUrl+")");
    }

    QUrl url(mirrorUrl);

    downloader=new Downloader(url, config);
    dlthread = new QThread();
    downloader->moveToThread(dlthread);

    QObject::connect(dlthread, SIGNAL(started()), downloader, SLOT(startDl()));
    QObject::connect(downloader, SIGNAL(progress(qint64,qint64)), this, SLOT(receiveProgress(qint64,qint64)));
    QObject::connect(downloader, SIGNAL(sendInfo(QString)), this, SIGNAL(sendLine(QString)));
    QObject::connect(downloader, SIGNAL(finisheddl()), this, SLOT(receiveFinishdl()));

    QObject::connect(downloader, SIGNAL(finisheddl()), dlthread, SLOT(quit()));
    QObject::connect(downloader, SIGNAL(finisheddl()), downloader, SLOT(deleteLater()));
    QObject::connect(dlthread, SIGNAL(finished()), dlthread, SLOT(deleteLater()));

    progressTime = QTime().currentTime();
    progressTime.start();

    dlthread->start();
}

/*
 * Extracts patch.zip
 */
bool Updater::extractZip() {

    Logger::log("1", config);
    emit sendLine("...");
    QuaZip zip(zippath);
    zip.open(QuaZip::mdUnzip);

    if (zip.isOpen()) {
        for( bool f = zip.goToFirstFile(); f; f = zip.goToNextFile() ) {

            QString filePath = zip.getCurrentFileName();
            QuaZipFile zFile( zip.getZipName(), filePath );

            zFile.open(QIODevice::ReadOnly);
            qint64 size=zFile.size();
            char * buffer = (char *)malloc(size);
            qint64 ret = zFile.read(buffer, size);
            zFile.close();

            emit sendLine("Extracting "+filePath+" ("+QString::number(size)+") read "+QString::number(ret)+"-"+QString::number(sizeof(buffer)));

            if (QFile::exists(config->APPDATA+"\\"+filePath)) QFile::remove(config->APPDATA+"\\"+filePath);

            QFile dstFile(config->APPDATA+"\\"+filePath);

            dstFile.open(QIODevice::WriteOnly);
            if (dstFile.isOpen()){
                dstFile.write(buffer, size);
                dstFile.close();
            }
            else {
                emit sendLine("Could not extract file "+filePath+" "+dstFile.errorString());
                return false;
            }
            delete buffer;
        }
    }
    else {
        emit sendLine("Could not open the zip file");
        return false;
    }
    zip.close();

    //cleanup
    QFile::remove(zippath);

    emit sendLine("...");
    return true;
}

bool Updater::instructions() {
    //read instructions.txt and execute
    /*
     * MOVE, DELETE or ICONS
     * Filename
     * EUROPATH, SOUNDPATH, W3PATH, W3PATH_126, MAPPATH, MAPPATH_126
    */
    QFile inst(config->APPDATA+"\\instructions.txt");
    if (inst.open(QIODevice::ReadOnly)) {
        QTextStream in(&inst);
        while (!in.atEnd()) {
            QString line = in.readLine();
            QStringList l = line.split(" ");
            QString midParam=Util::getMiddleParam(l);

            //emit sendLine("Instruction: <"+l.first()+"> <"+midParam+"> <"+l.last()+">");

            QString dstPath;
            if      (l.last()=="EUROPATH") dstPath=config->EUROPATH;
            else if (l.last()=="W3PATH") dstPath=config->W3PATH_LATEST;
            else if (l.last()=="W3PATH_126") dstPath=config->W3PATH_126;
            else if (l.last()=="MAPPATH") dstPath=config->DOCMAPPATHDL;
            else if (l.last()=="MAPPATH_126") dstPath=config->MAPPATH_126DL;
            else if (l.last()=="SOUNDPATH") dstPath=config->SOUNDPATH;
            else if (l.last()=="APPDATA_BNET_CACHE") dstPath=config->APPDATA_BNET_CACHE;
            else if (l.last()=="APPDATA_BNET_DOWNLOADS") dstPath=config->APPDATA_BNET_DOWNLOADS;

            if (l[0]=="MOVE") {

                //Skip cdkey files if they exist in destination
                if (midParam=="roc.w3k" || midParam=="tft.w3k") {
                    QFile cdkey(dstPath+"/"+midParam);
                    if (cdkey.exists()) {
                        continue;
                    }
                }

                QFile from(config->APPDATA+"\\"+midParam);
                if (QFile::exists(dstPath+"\\"+midParam)) QFile::remove(dstPath+"\\"+midParam);

                //check if download folder exists
                if(l.last()=="MAPPATH" || l.last()=="MAPPATH_126")
                {
                    if (!QDir().exists(dstPath))
                        QDir().mkdir(dstPath);
                }

                emit sendLine("Moving to "+dstPath+"\\"+midParam);
                if (!from.rename(dstPath+"\\"+midParam)) {
                    emit sendLine("Could not move file "+from.fileName()+" to "+dstPath+"\\"+midParam+" -- "+from.errorString());
                    return false;
                }
                if (midParam=="newxpam.exe") restartNeeded=true;
            }
            else if (l[0]=="DELETE") {
                emit sendLine("Deleting "+midParam);

                QFile::remove(dstPath+"\\"+midParam);
            }
            else if (l[0]=="ICONS") {
                if (!updateMPQ(dstPath)) {
                    emit sendLine("Failed to update icons. Please contact Technical Support");
                    return false;
                }
                QFile::remove(config->APPDATA+"\\icons.txt");
            }
        }
    }
    else {
        emit sendLine("Could not open instructions file");
        return false;
    }
    inst.close();

    //cleanup appdata
    QFile::remove(config->APPDATA+"\\instructions.txt");

    emit sendLine("...");
    return true;
}

bool Updater::updateMPQ(QString w3path)
{
    emit sendLine("Updating MPQ with custom icons");
    //O = open
    //d = delete file
    //f = flush
    //a = add from to
    //C = close
    //exit
    Mpq mpq;
    QFile inputFile(config->APPDATA+"\\icons.txt");
    if (inputFile.open(QIODevice::ReadOnly)) {
        QTextStream in(&inputFile);
        while (!in.atEnd()) {
            QString line = in.readLine();
            QStringList l = line.split(" ");

            if (l[0]=="O") {
                if (mpq.open(w3path+"\\"+l[1])==false) {
                    emit sendLine(Util::getLastErrorMsg()+config->W3PATH_LATEST+"\\"+l[1]);
                    return false;
                }
            }
            else if(l[0]=="d") {
                mpq.removeFile(l[1]);
            }
            else if(l[0]=="f") {

            }
            else if(l[0]=="a") {
                QFile f(config->APPDATA+"\\"+l[1]);
                f.open(QIODevice::ReadOnly);
                QByteArray ba;
                ba = f.readAll();
                DWORD size=ba.size();
                emit sendLine(l[2]+" ("+QString::number(size)+")");

                if (size==0) return false;
                if (mpq.createFile(l[2], size)==false) {
                    emit sendLine(Util::getLastErrorMsg());
                    return false;
                }
                if (mpq.writeFile(ba)==false) {
                    emit sendLine(Util::getLastErrorMsg());
                    return false;
                }
                if (mpq.finishWriteFile()==false) {
                    emit sendLine(Util::getLastErrorMsg());
                    return false;
                }
                f.close();
                QFile::remove(config->APPDATA+"\\"+l[1]);
            }
            else if(l[0]=="c") {
                emit sendLine("Closing mpq");
                mpq.close();
            }
            else if(l[0]=="exit") {
                emit sendLine("End of icons.txt instruction file");
                inputFile.close();
                return true;
            }
        }
    }
    else {
        emit sendLine("Could not open file icons.txt");
        return false;
    }
    emit sendLine("Something went terribly wrong...");
    return false;
}

// Receives download progress from downloader
// We use a timer so we don't waste cycles
void Updater::receiveProgress(qint64 bytesReceived, qint64 bytesTotal) {
    //emit sendLine("Slot activated "+QString::number(bytesReceived));
    if (progressTime.elapsed() > 200 && bytesTotal != -1) {
        int percents = qRound((((float)bytesReceived/(float)bytesTotal)*100.0));
        emit modifyLastLine("("+QString::number(bytesReceived)+" Bytes / "+QString::number(bytesTotal)+" Bytes) -- "+QString::number(percents)+"%");

        progressTime.restart();
    }
}

void Updater::receiveFinishdl() {

    //Check hash
    Logger::log("Checking file hash...", config);
    emit sendLine("Checking file hash...");

    bool hashok=false;
    QString sha1="unknown";

    QFile fz(zippath);
    if (fz.exists() && fz.size()!=0) {

        QCryptographicHash crypto(QCryptographicHash::Sha1);
        fz.open(QFile::ReadOnly);
        while(!fz.atEnd()){
          crypto.addData(fz.read(8192));
        }
        QByteArray hash = crypto.result();
        sha1 = QString(hash.toHex());
        if (sha1==real.value("sha1").toString()) {
            hashok=true;
        }
        fz.close();
    }
    else {
        emit sendLine("Error with download, could not open result file.");
        Logger::log("Error with download, could not open result file.", config);
    }

    //Data is empty or hash mismatch
    if (!hashok) {
        if (mirrorno==3) {
            emit sendLine("All mirrors failed. Aborting the update");
            emit updateFinished(restartNeeded, false, false, false, type);
            return;
        }
        emit sendLine("Remote checksum: "+real.value("sha1").toString()+"; Local checksum: "+sha1);
        emit sendLine("There was an error downloading the update files. Trying another mirror");
        mirrorno++;

        QString mirrorUrl = mirrors[mirrorno];
        if (type==2) {
            int mn = getRandomMirror();
            mirrorUrl = mirrors.at(mn);
            emit sendLine("Downloading from random: mirror "+(QString::number(mn))+" ("+mirrorUrl+")");
        }
        else {
            emit sendLine("Downloading from: mirror "+(QString::number(mirrorno))+" ("+mirrorUrl+")");
        }

        QUrl url(mirrorUrl);

        downloader=new Downloader(url, config);
        dlthread = new QThread();
        downloader->moveToThread(dlthread);

        QObject::connect(dlthread, SIGNAL(started()), downloader, SLOT(startDl()));
        QObject::connect(downloader, SIGNAL(progress(qint64,qint64)), this, SLOT(receiveProgress(qint64,qint64)));
        QObject::connect(downloader, SIGNAL(sendInfo(QString)), this, SIGNAL(sendLine(QString)));
        QObject::connect(downloader, SIGNAL(finisheddl()), this, SLOT(receiveFinishdl()));

        QObject::connect(downloader, SIGNAL(finisheddl(QByteArray)), dlthread, SLOT(quit()));
        QObject::connect(downloader, SIGNAL(finisheddl(QByteArray)), downloader, SLOT(deleteLater()));
        QObject::connect(dlthread, SIGNAL(finished()), dlthread, SLOT(deleteLater()));

        dlthread->start();
    }
    else {
        //Download was OK
        Logger::log("Extracting zip", config);
        emit sendLine("File hash OK. Extracting update ZIP...");

        if (!extractZip()){
            emit sendLine("Extraction process failed. Aborting update");
            return;
        }
        if (!instructions()){
            emit sendLine("Instruction process failed. Aborting update");
            return;
        }
        //Change registry version
        if (type==0 || type==3) {
            if (!Registry::setPatchVersion(latestVersion)){
                emit sendLine("Error changing current version in registry. Aborting update");
                return;
            }
            //Change config
            config->PATCH=Registry::getPatchVersion();

            QFile f(config->EUROPATH+"\\changelog.txt");
            f.open(QFile::ReadOnly);
            if (f.isOpen()) {
                QString changelog(f.readAll());
                emit sendLine(changelog);
                f.close();
            }

            emit sendLine("...");

            //Check if an even newer (incremental) update exists
            emit sendLine("Checking if there is an even newer patch...");
            if (setCurrentPlusOneJson()==1) { //if next patch exists
                restartNeeded=true; //client will restart and then do the next incremental update
            }
        }

        //Successful update
        emit updateFinished(restartNeeded, true, false, false, type);
    }
}

int Updater::setCurrentPlusOneJson() {
    QJsonDocument json = QJsonDocument::fromJson(jsonba);
    QJsonObject obj=json.object();
    QJsonValue value;

    if (type==3) {
        emit sendLine("Requested patch: beta");
        QString key = "beta";
        QStringList keys = obj.keys();

        if (!keys.contains(key)) {
            emit sendLine("No beta patch exists. Xpam is up to date");
            return 0;
        }
        value=obj.value("beta");
        real=value.toObject();
        if (qRound(real.value("version").toDouble()) <= config->PATCH) {
            emit sendLine("Beta patch is current. Xpam is up to date");
            return 0;
        }
    }
    else if (type==1 || type==2) {
        //Full or partial W3 update
        emit sendLine("Requested patch: full or quick W3 update");
        QString key = jsonKey;
        QStringList keys = obj.keys();

        if (!keys.contains(key)) {
            emit sendLine("No W3 patch exists.");
            return 2;
        }
        value=obj.value(jsonKey);
        real=value.toObject();
    }
    else if (type==4) {
        //Map download
        emit sendLine("Requested patch: map download: "+jsonKey);

        //Key here means map name in maps array!
        QString key = jsonKey;

        QJsonValue value = obj.value("maps");
        QJsonArray maps = value.toArray();

        bool found = false;
        foreach (const QJsonValue & v, maps) {
            QJsonObject obj = v.toObject();
            if (obj.value("name").toString()==key) {
                found = true;
                real=v.toObject();
            }
        }

        if (!found) {
            emit sendLine("No map exists on download server.");
            return 2;
        }
    }
    else {
        emit sendLine("Requested patch: stable");
        int incremental=config->PATCH+1;
        QString key = QString::number(incremental);
        QStringList keys = obj.keys();

        if (!keys.contains(key)) {
            emit sendLine("No newer patch exists. Xpam is up to date");
            return 0;
        }
        value=obj.value(key);
        real=value.toObject();
    }
    return 1;
}

QByteArray Updater::simpleDl(QUrl url) {
    QNetworkAccessManager nam;
    QNetworkRequest request(url);
    request.setTransferTimeout(10000);
    request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
    QNetworkReply * reply = nam.get(request);

    QEventLoop loop;
    connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();

    if (reply->error() == QNetworkReply::NoError) {
        QByteArray ba(reply->readAll());
        reply->deleteLater();
        return ba;
    }
    else {
        QByteArray ba;
        reply->deleteLater();
        return ba;
    }
}

QByteArray Updater::getUpdateJson(Config * config) {

    QByteArray jsonba;

    QByteArray j1=simpleDl(config->json1);
    QByteArray j2=simpleDl(config->json2);
    QByteArray j3=simpleDl(config->json3);

    if ((j1.isEmpty() && j2.isEmpty()) || (j1.isEmpty() && j3.isEmpty()) || (j2.isEmpty() && j3.isEmpty())) {
        return QByteArray();
    }

    if (j1==j2){
        jsonba=j1;
    }
    else if (j1==j3){
        jsonba=j1;
    }
    else if (j2==j3){
        jsonba=j2;
    }
    else {
        return QByteArray();
    }

    return jsonba;
}

QString Updater::moveToDocuments(Config *config) {

    QStringList folders;
    folders << "Ai Scripts";
    folders << "Campaigns";
    folders << "Errors";
    folders << "Maps";
    folders << "Replay";
    folders << "ScreenShots";
    folders << "Scripts";
    folders << "Strings";
    folders << "Logs";

    QString log="";

    QDir w3doc(config->DOCPATH);
    if (!w3doc.exists()) {
        w3doc.mkpath(".");
    }

    QDir dir;

    for (int i = 0; i < folders.size(); ++i) {
        boolean moved = dir.rename(config->W3PATH_LATEST+"\\"+folders.at(i), config->DOCPATH+"/"+folders.at(i));

        log+="<br />"+config->W3PATH_LATEST+"\\"+folders.at(i)+" -> "+config->DOCPATH+"/"+folders.at(i);
        if (moved) {
            log+=" (MOVED)";
        }
        else {
            log+=" (FAILED)";
            QDir newdir(config->DOCPATH+"//"+folders.at(i));
            if (!newdir.exists()) {
                newdir.mkpath(".");
                log+=" (created new empty folder)";
            }
        }
    }
    return log;
}

void Updater::replaceCDKeys(Config *config) {
       QFile roc(config->W3PATH_LATEST+"\\roc.w3k");
       if (!roc.exists()) {
           QFile rocNew(config->W3PATH_LATEST+"\\roc.w3k.new");
           if (rocNew.exists()) {
               rocNew.rename(config->W3PATH_LATEST+"\\roc.w3k");
           }
       }

       QFile tft(config->W3PATH_LATEST+"\\tft.w3k");
       if (!tft.exists()) {
           QFile tftnew(config->W3PATH_LATEST+"\\tft.w3k.new");
           if (tftnew.exists()) {
               tftnew.rename(config->W3PATH_LATEST+"\\tft.w3k");
           }
       }
}

void Updater::renamePatchMpqForLatestW3(Config *config) {
    QFile modMpq(config->W3PATH_LATEST+"\\War3Mod.mpq");
    if (!modMpq.exists()) {
        QFile patchMpq(config->W3PATH_LATEST+"\\War3Patch.mpq");
        if (patchMpq.exists()) {
            patchMpq.copy(config->W3PATH_LATEST+"\\War3Mod.mpq");
        }
    }
}

void Updater::cancelUpdate() {
    this->downloader->reply->abort();
    this->downloader->deleteLater();
    emit sendLine("Update ABORTED BY USER");
    emit updateFinished(false, true, true, true, type);
}

int Updater::getRandomMirror() {

    QString mirrorsTried="";
    for (int i=0; i<this->usedMirrors.size(); i++) {
        mirrorsTried+=QString::number(this->usedMirrors.at(i))+"..";
    }
    if (mirrorsTried=="") {
        emit sendLine("Mirrors tried so far: none");
    }
    else {
        emit sendLine("Mirrors tried so far: "+mirrorsTried);
    }

    int high=3;
    int low=0;
    int mirrorNo = qrand() % ((high + 1) - low) + low;
    while (this->usedMirrors.contains(mirrorNo)) {
        mirrorNo = qrand() % ((high + 1) - low) + low;
    }
    //Does not contain
    this->usedMirrors.append(mirrorNo);

    emit sendLine("Picked random mirror: "+QString::number(mirrorNo));
    return mirrorNo;
}


text:
package com.zimbra.kabuki.tools.tz;

import java.io.*;
import java.text.MessageFormat;

import org.apache.tools.ant.*;
import org.apache.tools.ant.types.*;

public class GenerateDataTask extends Task {

	//
	// Data
	//

	private File srcFile;
	private File destFile;

	//
	// Public methods
	//

	public void setSrc(File file) {
		this.srcFile = file;
	}

	public void setDest(File file) {
		this.destFile = file;
	}

	//
	// Task methods
	//

	public void execute() throws BuildException {

		antAssert(this.srcFile == null, "missing src attribute");
		antAssert(this.destFile == null, "missing dest attribute");

		antAssert(!this.srcFile.exists(), "file doesn't exist: ", this.srcFile);

		try {
			String[] args = {
				"-i", this.srcFile.getAbsolutePath(),
				"-o", this.destFile.getAbsolutePath()
			};

			System.out.print("GenerateData");
			for (String arg : args) {
				System.out.print(' ');
				System.out.print(arg);
			}
			System.out.println();

			GenerateData.main(args);
		}
		catch (Exception e) {
			throw new BuildException(e);
		}
	}

	//
	// Private static functions
	//

	private static void antAssert(boolean condition, String message, Object... args)
	throws BuildException {
		if (condition) {
			if (args.length > 0) {
				message = MessageFormat.format(message, args);
			}
			throw new BuildException(message);
		}
	}

} // class GenerateDataTask


text:
<?php

namespace Tacit\Controller\Exception;

class RequestTimeoutException extends RestfulException
{
    protected $status = 408;
    protected $message = "Request Timeout";
    protected $description = "Request has timed out.";
}


text:
"""
The UNIX Rule of Transparency.

See http://www.catb.org/esr/writings/taoup/html/ch01s06.html for more.
"""
# -*- coding: utf-8 -*-

__author__ = """Chris Tabor (dxdstudio@gmail.com)"""

if __name__ == '__main__':
    from os import getcwd
    from os import sys
    sys.path.append(getcwd())

from random import choice
import pdb
import sys

DEBUG = True if __name__ == '__main__' else False
# Allow debugging from command line.
DEBUG_PDB = '--debug' in sys.argv

# Not transparent - BAD
def gnrt_rndm_nms(cnt):
    f = ['Jane', 'Hans', 'Ella', 'Lois', 'Bernardo', 'Yolanda']
    l = ['McKinley', 'Adams', 'Salvatore', 'Geoffries', 'Fritzmann', 'Smith']
    return ['{} {}'.format(choice(f), choice(l)) for val in range(cnt)]

# Transparent - GOOD
# It has the following transparent properties:
#   1. Docstrings, for reader and for introspection
#   2. Arguments/returns values
#   3. Default value, with a sensible default, keyword argument based.
#   4. Type checking.
#   5. Easy to understand varaible names and method name.
def get_random_names(count=3):
    """Get a list of random first and last names, up to `count`.

    Args:
        count (int, optional): The number of names to generate. Default is 3.
    Returns:
        names (list): The list of generated names.
    """
    if not isinstance(count, int):
        raise ValueError('Need a number!')
    first_names = ['Jane', 'Hans', 'Ella', 'Lois', 'Bernardo', 'Yolanda']
    last_names = [
        'McKinley', 'Adams', 'Salvatore', 'Geoffries', 'Fritzmann', 'Smith']
    return ['{} {}'.format(
        choice(first_names), choice(last_names)) for _ in range(count)]

if DEBUG_PDB:
    pdb.set_trace()
    print(get_random_names(count=3))


text:
package com.dell.doradus.logservice.store;

import com.dell.doradus.olap.collections.MemoryStream;

public class TimestampBuilder {
	private long[] m_timestamps;

	public TimestampBuilder(int size) {
	    m_timestamps = new long[size];
	}

    public void add(int doc, long timestamp) {
        m_timestamps[doc] = timestamp;
    }

	public void flush(MemoryStream output, Temp temp) {
	    long last = 0;
	    MemoryStream s_st = temp.getStream(0);
        for(int i = 0; i < m_timestamps.length; i++) {
            long next = m_timestamps[i];
            s_st.writeVLong(next - last);
            last = next;
        }
        Temp.writeCompressed(output, s_st);
	}

    public int getSize() { return m_timestamps.length; }

	public long getMinTimestamp() {
	    long timestamp = m_timestamps[0];
	    for(int i = 1; i < m_timestamps.length; i++) {
	        if(m_timestamps[i] < timestamp) timestamp = m_timestamps[i];
	    }
	    return timestamp;
	}

    public long getMaxTimestamp() {
        long timestamp = m_timestamps[0];
        for(int i = 1; i < m_timestamps.length; i++) {
            if(m_timestamps[i] > timestamp) timestamp = m_timestamps[i];
        }
        return timestamp;
    }

}


text:
<?php

namespace DanielBadura\Redmine\Api\Struct;

/**
 * @author Marco Giesen <marco.giesen93@gmail.com>
 */
class Membership
{
    public $project;

    public $roles;
}


text:
Danube Cloud :: Factory :: Appliances
#####################################

Danube Cloud appliances (VM images), which are part of the Danube Cloud first compute node USB image:

    * `base-64-es`_ (OS zone)
    * `esdc-cfgdb`_ (OS zone)
    * `esdc-dns`_ (OS zone)
    * `esdc-img`_ (OS zone)
    * `esdc-mgmt`_ (KVM)
    * `esdc-mon`_ (KVM)

`Additional VM appliances <contrib>`_ are available for download at the public Danube Cloud image repository - https://images.danubecloud.org.

------------------------------------------------------------

base-64-es
==========

* **root_authorized_keys**: content for ``/root/.ssh/authorized_keys``.
* **org.erigones:zabbix_ip**: ``Server`` and ``ServerActive`` parameters in zabbix_agentd.conf.

Changelog
---------

4.2
~~~~~

- Version bump.

4.1
~~~~~

- Version bump.

4.0
~~~~~

- Built from new `base-64-es`_ with 2018Q4 pkgsrc - `#126 <https://github.com/erigones/esdc-factory/pull/126>`__

3.0.0
~~~~~

- Updated Zabbix agent to 3.0.14 - `#110 <https://github.com/erigones/esdc-factory/issues/110>`__
- Updated pkgsrc in /opt/local to 2017Q4 - `#111 <https://github.com/erigones/esdc-factory/issues/111>`__
- Fixed sm-prepare-image - commit `7e3d694 <https://github.com/erigones/esdc-factory/commit/7e3d694321a836839e8eadbfdd2c8bdaffe9eae9>`__

2.6.7
~~~~~

- Version bump.

2.6.6
~~~~~

- Version bump.

2.6.5
~~~~~

- Version bump.

2.6.4
~~~~~

- Version bump.

2.6.3
~~~~~

- Version bump.

2.6.2
~~~~~

- Version bump.

2.6.1
~~~~~

- Updated zabbix agent to 3.0.10 - commit `9211f83 <https://github.com/erigones/esdc-factory/commit/9211f8360003d6268ff1643b556b5e1420845ffe>`__

2.6.0
~~~~~

- Updated pkgsrc in /opt/local to 2016Q4 - `#36 <https://github.com/erigones/esdc-factory/issues/36>`__
- Updated zabbix agent to 3.0.9 - `#36 <https://github.com/erigones/esdc-factory/issues/36>`__

2.5.3
~~~~~

- Version bump.

2.5.2
~~~~~

- Switched to zabbix-agent package from pkgsrc.erigones.com - commit `ab681c3 <https://github.com/erigones/esdc-factory/commit/ab681c3929598796d99fdfadfed0e1aede46926c>`__ and commit `d9386cd <https://github.com/erigones/esdc-factory/commit/d9386cddcfa26273d816d7de62d6b5ff13bc078f>`__
- Updated zabbix agent to 3.0.8 - commit `07194fa <https://github.com/erigones/esdc-factory/commit/07194fa5637893b25a0fcc539c4c0c62fef4b836>`__

2.5.1
~~~~~

- Version bump.

2.5.0
~~~~~

- Version bump.

2.4.0
~~~~~

- Version bump.

2.3.3
~~~~~

- Updated zabbix agent to 3.0.7 - commit `6f338b2 <https://github.com/erigones/esdc-factory/commit/6f338b22c71c3c022063bdd093a60a8afefa2342>`__

2.3.2
~~~~~

- Version bump.

2.3.1
~~~~~

- Updated zabbix agent to 3.0.5 - `#7 <https://github.com/erigones/esdc-factory/issues/7>`__

2.3.0
~~~~~

- Initial release.

------------------------------------------------------------

esdc-cfgdb
==========

The *esdc-cfgdb* appliance is an OS zone based on the `base-64-es`_ image.
The image supports following metadata (in addition to `base-64-es`_ image metadata):

* **org.erigones:cfgdb_node**: Znode path, which will be created during image deploy (default: ``/esdc``).
* **org.erigones:cfgdb_data**: data for the *org.erigones:cfgdb_node* (default: ``DanubeCloud``).
* **org.erigones:cfgdb_username**: protects the *org.erigones:cfgdb_node* with a username and password (requires *org.erigones:cfgdb_password* to be set, default: ``esdc``).
* **org.erigones:cfgdb_password**: protects the *org.erigones:cfgdb_node* with a username and password (requires *org.erigones:cfgdb_username* to be set).
* **org.erigones:cfgdb_zk_rest_ssl_cert**: SSL certificate for the ZK REST service (optional).
* **org.erigones:cfgdb_zk_rest_ssl_key**: SSL private key for the ZK REST service. The ZK REST service is enabled only if the key and the certificate are both provided (optional).

Changelog
---------

4.2
~~~~~

- Version bump.

4.1
~~~~~

- Version bump.

4.0
~~~~~

- Built from new `base-64-es`_ with 2018Q4 pkgsrc - `#126 <https://github.com/erigones/esdc-factory/pull/126>`__

3.0.0
~~~~~

- Built from new `base-64-es`_ with 2017Q4 pkgsrc - `#111 <https://github.com/erigones/esdc-factory/issues/111>`__
- Added ZooKeeper REST service - `#108 <https://github.com/erigones/esdc-factory/issues/108>`__
- Added ``cfgdb_zk_rest_ssl_{cert,key}`` metadata and updated related post-deploy configuration script - `#102 <https://github.com/erigones/esdc-factory/issues/102>`__

2.6.7
~~~~~

- Version bump.

2.6.6
~~~~~

- Version bump.

2.6.5
~~~~~

- Version bump.

2.6.4
~~~~~

- Version bump.

2.6.3
~~~~~

- Version bump.

2.6.2
~~~~~

- Version bump.

2.6.1
~~~~~

- Added discovery service for purposes of the compute node installer - `#64 <https://github.com/erigones/esdc-factory/issues/64>`__

2.6.0
~~~~~

- Built from new `base-64-es`_ with 2016Q4 pkgsrc - `#36 <https://github.com/erigones/esdc-factory/issues/36>`__
- Added binaries: zookeepercli, query_cfgdb - `#50 <https://github.com/erigones/esdc-factory/issues/50>`__

2.5.3
~~~~~

- Add support for appending additional SSH authorized_keys into the service VMs - `#43 <https://github.com/erigones/esdc-factory/issues/43>`__

2.5.2
~~~~~

- Version bump.

2.5.1
~~~~~

- Version bump.

2.5.0
~~~~~

- Version bump.

2.4.0
~~~~~

- Version bump.

2.3.3
~~~~~

- Version bump.

2.3.2
~~~~~

- Version bump.

2.3.1
~~~~~

- Version bump.

2.3.0
~~~~~

- Initial release.

------------------------------------------------------------

esdc-dns
========

The *esdc-dns* appliance is an OS zone based on the `base-64-es`_ image.
The image supports following metadata (in addition to `base-64-es`_ image metadata):

* **org.erigones:pgsql_host**: ``gpgsql-host`` parameter in pdns.conf.
* **org.erigones:pgsql_port**: ``gpgsql-port`` parameter in pdns.conf.
* **org.erigones:pgsql_user**: ``gpgsql-user`` parameter in pdns.conf.
* **org.erigones:pgsql_password**: ``gpgsql-password`` parameter in pdns.conf.
* **org.erigones:pgsql_dbname**: ``gpgsql-dbname`` parameter in pdns.conf.
* **org.erigones:recursor_forwarders**: sets the ``forward-zones-recurse=.=<metadata-value>`` parameter in recursor.conf.

Changelog
---------

4.2
~~~~~

- Version bump.

4.1
~~~~~

- Version bump.

4.0
~~~~~

- Version bump.

3.0.0
~~~~~

- Built from new `base-64-es`_ with 2017Q4 pkgsrc - `#111 <https://github.com/erigones/esdc-factory/issues/111>`__
- Changed PowerDNS packages to our powerdns40* - `#113 <https://github.com/erigones/esdc-factory/issues/113>`__

2.6.7
~~~~~

- Version bump.

2.6.6
~~~~~

- Version bump.

2.6.5
~~~~~

- Version bump.

2.6.4
~~~~~

- Version bump.

2.6.3
~~~~~

- Version bump.

2.6.2
~~~~~

- Version bump.

2.6.1
~~~~~

- Version bump.

2.6.0
~~~~~

- Built from new `base-64-es`_ with 2016Q4 pkgsrc - `#36 <https://github.com/erigones/esdc-factory/issues/36>`__
- Fixed problem where the pdns service goes to maintenance state when DB is not reachable - `#48 <https://github.com/erigones/esdc-factory/issues/48>`__
- Added new metadata parameter: `org.erigones:recursor_forwarders` - `#60 <https://github.com/erigones/esdc-factory/issues/60>`__

2.5.3
~~~~~

- Changed default PowerDNS server settings to be preconfigured as a master name server - `#41 <https://github.com/erigones/esdc-factory/issues/41>`__
- Add support for appending additional SSH authorized_keys into the service VMs - `#43 <https://github.com/erigones/esdc-factory/issues/43>`__

2.5.2
~~~~~

- Version bump.

2.5.1
~~~~~

- Version bump.

2.5.0
~~~~~

- Version bump.

2.4.0
~~~~~

- Version bump.

2.3.3
~~~~~

- Version bump.

2.3.2
~~~~~

- Version bump.

2.3.1
~~~~~

- Version bump.

2.3.0
~~~~~

- Initial release.

------------------------------------------------------------

esdc-img
========

The *esdc-img* appliance is an OS zone based on the `base-64-es`_ image.

Changelog
---------

4.2
~~~~~

- Version bump.

4.1
~~~~~

- Version bump.

4.0
~~~~~

- Built from new `base-64-es`_ with 2018Q4 pkgsrc - `#126 <https://github.com/erigones/esdc-factory/pull/126>`__

3.0.0
~~~~~

- Built from new `base-64-es`_ with 2017Q4 pkgsrc - `#111 <https://github.com/erigones/esdc-factory/issues/111>`__

2.6.7
~~~~~

- Version bump.

2.6.6
~~~~~

- Version bump.

2.6.5
~~~~~

- Version bump.

2.6.4
~~~~~

- Version bump.

2.6.3
~~~~~

- Version bump.

2.6.2
~~~~~

- Version bump.

2.6.1
~~~~~

- Version bump.

2.6.0
~~~~~

- Built from new `base-64-es`_ with 2016Q4 pkgsrc - `#36 <https://github.com/erigones/esdc-factory/issues/36>`__

2.5.3
~~~~~

- Add support for appending additional SSH authorized_keys into the service VMs - `#43 <https://github.com/erigones/esdc-factory/issues/43>`__

2.5.2
~~~~~

- Version bump.

2.5.1
~~~~~

- Version bump.

2.5.0
~~~~~

-  Updated versions of the packages in requirements file - commit `503c087 <https://github.com/erigones/esdc-shipment/commit/503c087d353055de48e4c8f056f56f4bc6853974>`__

2.4.0
~~~~~

- Version bump.

2.3.3
~~~~~

- Version bump.

2.3.2
~~~~~

- Version bump.

2.3.1
~~~~~

- Version bump.

2.3.0
~~~~~

- Initial release.

------------------------------------------------------------

esdc-mgmt
=========

The *esdc-mgmt* appliance is a `CentOS 7 <contrib/centos-7.rst>`_ virtual machine with the Danube Cloud application stack.
The image supports following metadata:

* **root_authorized_keys**: content for ``/root/.ssh/authorized_keys``.
* **org.erigones:zabbix_ip**: ``Server`` and ``ServerActive`` parameters in zabbix_agentd.conf.
* **org.erigones:rabbitmq_password**: esDC RabbitMQ password.
* **org.erigones:redis_password**: esDC Redis password.
* **org.erigones:pgsql_esdc_password**: esDC PostgreSQL password.
* **org.erigones:pgsql_pdns_password**: esDC PostgreSQL password for PowerDNS.
* **org.erigones:pgsql_mgmt_mon_password**: esDC PostgreSQL password for Zabbix agent (optional).
* **org.erigones:zabbix_server**: MON_ZABBIX_SERVER in esDC. If not set, monitoring support will be disabled.
* **org.erigones:zabbix_esdc_username**: MON_ZABBIX_USERNAME in esDC.
* **org.erigones:zabbix_esdc_password**: MON_ZABBIX_PASSWORD in esDC.
* **org.erigones:esdc_admin_email**: change email of admin user.
* **org.erigones:cfgdb_ip**: IP address of cfgdb01.local server that will be configured in port forwarding in local HAProxy (optional, default: ``127.0.0.1``).
* **org.erigones:erigonesd_ssl_cert**: SSL certificate to be used by internal Danube Cloud services (optional, no default).
* **org.erigones:erigonesd_ssl_key**: SSL key to be used by internal Danube Cloud services (optional, no default).
* **hostname**: Full hostname to be configured by `cloud-init <https://cloudinit.readthedocs.io/>`__ at first boot.

Changelog
---------

4.2
~~~~~

- Add python3 to CentOS appliances - `#459 <https://github.com/erigones/esdc-ce/issues/459>`__

4.1
~~~~~

- Version bump.

4.0
~~~~~

- Enable `vmadm console` support - `#130 <https://github.com/erigones/esdc-factory/issues/130>`__
- Added 04-mtu-set.sh to override incorrectly set non-default MTU in KVM - `#430 <https://github.com/erigones/esdc-ce/issues/430>`__

3.0.0
~~~~~

- Fixed /etc/rc.d/rc.local permissions - `#109 <https://github.com/erigones/esdc-factory/issues/109>`__
- Added ``cfgdb_ip`` and ``erigonesd_ssl_{cert,key}`` metadata and updated related post-deploy configuration script - `#102 <https://github.com/erigones/esdc-factory/issues/102>`__
- Enabled TCP keepalive in RabbitMQ - `esdc-ce#350 <https://github.com/erigones/esdc-ce/issues/350>`__
- Switched pgbouncer pool_mode to session -  `#113 <https://github.com/erigones/esdc-factory/issues/113>`__

2.6.7
~~~~~

- Version bump.

2.6.6
~~~~~

- Version bump.

2.6.5
~~~~~

- Disabled cloud-init network configuration - `#80 <https://github.com/erigones/esdc-factory/issues/80>`__

2.6.4
~~~~~

- Added `org.erigones:pgsql_mgmt_mon_password` metadata parameter - `#72 <https://github.com/erigones/esdc-factory/issues/72>`__
- Added bash-completion package - commit `420d304 <https://github.com/erigones/esdc-factory/commit/420d3042044db9b5557051ad21d66cf6ea66f882>`__
- Modified rabbitmq-server.service to be restarted upon failure - `#71 <https://github.com/erigones/esdc-factory/issues/71>`__

2.6.3
~~~~~

- Version bump.

2.6.2
~~~~~

- Version bump.

2.6.1
~~~~~

- Version bump.

2.6.0
~~~~~

- Version bump.

2.5.3
~~~~~

- Added bash completion for *es* - commit `ac851d0 <https://github.com/erigones/esdc-factory/commit/ac851d015da0347afa2bf4f4ee6120b83eab12ef>`__
- Add support for appending additional SSH authorized_keys into the service VMs - `#43 <https://github.com/erigones/esdc-factory/issues/43>`__

2.5.2
~~~~~

- Version bump.

2.5.1
~~~~~

- Version bump.

2.5.0
~~~~~

- Added HTTP connection rate limit for the mgmt web portal - commit `398ce29 <https://github.com/erigones/esdc-factory/commit/398ce29b33e0e4f98794f021342dea44b4eba03b>`

2.4.0
~~~~~

- Removed hardcoded hostname and pre-installed RabbitMQ data dir - `#22 <https://github.com/erigones/esdc-factory/issues/22>`__
- Removed hardcoded hostname in /etc/hosts - commit `54415d0 <https://github.com/erigones/esdc-factory/commit/54415d0a0bdb944c4a159c04304a21fbe395909d>`__
- Disabled monitoring support by default - commit `dd1b671 <https://github.com/erigones/esdc-factory/commit/dd1b6715cbc5494d1d92281613a518486235d120>`__

2.3.3
~~~~~

- Version bump.

2.3.2
~~~~~

- Fixed logrotate in /opt/erigones/var/log - `#20 <https://github.com/erigones/esdc-factory/issues/20>`__

2.3.1
~~~~~

- Added Ansible - `#17 <https://github.com/erigones/esdc-factory/issues/17>`__

2.3.0
~~~~~

- Initial release.

------------------------------------------------------------

esdc-mon
========

The *esdc-mon* appliance is a `CentOS 7 <contrib/centos-7.rst>`_ virtual machine with Zabbix server pre-installed.
The image supports following metadata:

* **root_authorized_keys**: content for ``/root/.ssh/authorized_keys``.
* **org.erigones:zabbix_ip**: ``Server`` and ``ServerActive`` parameters in zabbix_agentd.conf.
* **org.erigones:zabbix_esdc_password**: *provisioner* zabbix user password.
* **org.erigones:zabbix_admin_password**: *Admin* zabbix user password.
* **org.erigones:zabbix_admin_email**: create *E-mail* media type with this email for user *Admin*.
* **org.erigones:zabbix_smtp_email**: configure outgoing e-mail address in the *E-mail* media type.
* **hostname**: Full hostname to be configured by `cloud-init <https://cloudinit.readthedocs.io/>`__ at first boot.

.. note:: Zabbix is a registered trademark of `Zabbix LLC <http://www.zabbix.com>`_.

Changelog
---------

4.2
~~~~~

- Add python3 to CentOS appliances - `#459 <https://github.com/erigones/esdc-ce/issues/459>`__

4.1
~~~~~

- Version bump.

4.0
~~~~~

- Enable `vmadm console` support - `#130 <https://github.com/erigones/esdc-factory/issues/130>`__
- Added 04-mtu-set.sh to override incorrectly set non-default MTU in KVM - `#430 <https://github.com/erigones/esdc-ce/issues/430>`__

3.0.0
~~~~~

- Fixed monitoring items of erigonesd mgmt worker - `#98 <https://github.com/erigones/esdc-factory/issues/98>`__
- Fixed timezone of the Zabbix frontend - `#106 <https://github.com/erigones/esdc-factory/issues/106>`__
- Fixed /etc/rc.d/rc.local permissions - `#109 <https://github.com/erigones/esdc-factory/issues/109>`__

2.6.7
~~~~~

- Version bump.

2.6.6
~~~~~

- Version bump.

2.6.5
~~~~~

- Added t_svc-db-ha template for monitoring HA status of the PostgreSQL cluster - `#79 <https://github.com/erigones/esdc-factory/issues/79>`__
- Disabled cloud-init network configuration - `#80 <https://github.com/erigones/esdc-factory/issues/80>`__

2.6.4
~~~~~

- Added bash-completion package - commit `420d304 <https://github.com/erigones/esdc-factory/commit/420d3042044db9b5557051ad21d66cf6ea66f882>`__

2.6.3
~~~~~

- Version bump.

2.6.2
~~~~~

- Version bump.

2.6.1
~~~~~

- Added SQL functions and a helper script for managing Zabbix database partitions - `#44 <https://github.com/erigones/esdc-factory/issues/44>`__

2.6.0
~~~~~

- Updated several templates - switched from ZONEID to UUID_SHORT macro - `#49 <https://github.com/erigones/esdc-factory/issues/49>`__

2.5.3
~~~~~

- Decreased severity of *Too many SCSI errors on disk...* alert and increased DISK_ERRORS_THRESHOLD - `#40 <https://github.com/erigones/esdc-factory/issues/40>`__
- Add support for appending additional SSH authorized_keys into the service VMs - `#43 <https://github.com/erigones/esdc-factory/issues/43>`__

2.5.2
~~~~~

- Fixed trigger value to be in line with trigger description in t_erigones-zone - `#28 <https://github.com/erigones/esdc-factory/issues/28>`__
- Updated Ludolph systemd service to start after postgres, pgbouncer and httpd services - commit `0c6ee4a <https://github.com/erigones/esdc-factory/commit/0c6ee4ac00eede5388af215cdb8556b1d4c7f7ca>`__ and commit `a5afec0 <https://github.com/erigones/esdc-factory/commit/a5afec029c5a605d9fc3394ced90b0cb3aec8c7f>`__
- Added externalscripts and alertscripts symlinks in /etc/zabbix - commit `40e99f6 <https://github.com/erigones/esdc-factory/commit/40e99f6cdaf699e87b0edf75c666e35861d1c1cd>`__
- Added sample SMS escalation action - commit `7c4f488 <https://github.com/erigones/esdc-factory/commit/7c4f4886d74750d35a988a74988abafefcb4e8ec>`__
- Added sample Zabbix alert scripts - commit `d4a1c4c <https://github.com/erigones/esdc-factory/commit/d4a1c4c6659c702f22bff92456527e8adcd99b8a>`__
- Added network interface monitoring into t_erigones-zone + small fixes - commit `bc37060 <https://github.com/erigones/esdc-factory/commit/bc37060b5ac77740cb0a3ae034f1cc339acd5b0d>`__
- Disabled cache hit ratio trigger in t_svc-db - commit `3ad5f55 <https://github.com/erigones/esdc-factory/commit/3ad5f5578e7897072fff223e080f0caae415560c>`__
- Fixed exec parameters of default media types - `#29 <https://github.com/erigones/esdc-factory/issues/29>`__
- Fixed FS discovery in t_linux and t_erigonos templates - `#30 <https://github.com/erigones/esdc-factory/issues/30>`__
- Fixed node hard disk discovery and added trigger on SCSI errors into t_solaris_disk - commit `273ad34 <https://github.com/erigones/esdc-factory/commit/273ad34e0c24ab7cb5f2de2f4478534bfa13230e>`__
- Fixed invalid graph description for network monitoring in t_erigonos - `#34 <https://github.com/erigones/esdc-factory/issues/34>`__ - `#112 <https://github.com/erigones/esdc-ce/issues/112>`__

2.5.1
~~~~~

- Version bump.

2.5.0
~~~~~

- Version bump.

2.4.0
~~~~~

- Added used swap metric into compute node monitoring template (t_erigonos) - `#21 <https://github.com/erigones/esdc-factory/issues/21>`__
- Removed hardcoded hostname in /etc/hosts - commit `54415d0 <https://github.com/erigones/esdc-factory/commit/54415d0a0bdb944c4a159c04304a21fbe395909d>`__

2.3.3
~~~~~

- Version bump.

2.3.2
~~~~~

- Version bump.

2.3.1
~~~~~

- Disabled trigger "Cache hit ratio of database zabbix is below ??%" - `#8 <https://github.com/erigones/esdc-factory/issues/8>`__
- Disabled trigger "Free swap space is below ??M" on mgmt and mon VMs - `#16 <https://github.com/erigones/esdc-factory/issues/16>`__

2.3.0
~~~~~

- Initial release.

------------------------------------------------------------

centos-6
========

Moved to `contrib/centos-6.rst <contrib/centos-6.rst>`_.

------------------------------------------------------------

centos-7
========

Moved to `contrib/centos-7.rst <contrib/centos-7.rst>`_.


text:
class GFXD3D11Shader;

enum CONST_CLASS
{
	D3DPC_SCALAR,
	D3DPC_VECTOR,
	D3DPC_MATRIX_ROWS,
	D3DPC_MATRIX_COLUMNS,
	D3DPC_OBJECT,
	D3DPC_STRUCT
};

enum CONST_TYPE
{
   D3DPT_VOID,
   D3DPT_BOOL,
   D3DPT_INT,
   D3DPT_FLOAT,
   D3DPT_STRING,
   D3DPT_TEXTURE,
   D3DPT_TEXTURE1D,
   D3DPT_TEXTURE2D,
   D3DPT_TEXTURE3D,
   D3DPT_TEXTURECUBE,
   D3DPT_SAMPLER,
   D3DPT_SAMPLER1D,
   D3DPT_SAMPLER2D,
   D3DPT_SAMPLER3D,
   D3DPT_SAMPLERCUBE,
   D3DPT_PIXELSHADER,
   D3DPT_VERTEXSHADER,
   D3DPT_PIXELFRAGMENT,
   D3DPT_VERTEXFRAGMENT
};

enum REGISTER_TYPE
{
	D3DRS_BOOL,
	D3DRS_INT4,
	D3DRS_FLOAT4,
	D3DRS_SAMPLER
};

struct ConstantDesc
{
   String Name = String::EmptyString;
   S32 RegisterIndex = 0;
   S32 RegisterCount = 0;
   S32 Rows = 0;
   S32 Columns = 0;
   S32 Elements = 0;
   S32 StructMembers = 0;
   REGISTER_TYPE RegisterSet = D3DRS_FLOAT4;
   CONST_CLASS Class = D3DPC_SCALAR;
   CONST_TYPE Type = D3DPT_FLOAT;
   U32 Bytes = 0;
};

class ConstantTable
{
public:
   bool Create(const void* data);

   U32 GetConstantCount() const { return m_constants.size(); }
   const String& GetCreator() const { return m_creator; }

   const ConstantDesc* GetConstantByIndex(U32 i) const { return &m_constants[i]; }
   const ConstantDesc* GetConstantByName(const String& name) const;

   void ClearConstants() { m_constants.clear(); }

private:
   Vector<ConstantDesc> m_constants;
   String m_creator;
};

// Structs
struct CTHeader
{
   U32 Size;
   U32 Creator;
   U32 Version;
   U32 Constants;
   U32 ConstantInfo;
   U32 Flags;
   U32 Target;
};

struct CTInfo
{
   U32 Name;
   U16 RegisterSet;
   U16 RegisterIndex;
   U16 RegisterCount;
   U16 Reserved;
   U32 TypeInfo;
   U32 DefaultValue;
};

struct CTType
{
   U16 Class;
   U16 Type;
   U16 Rows;
   U16 Columns;
   U16 Elements;
   U16 StructMembers;
   U32 StructMemberInfo;
};

// Shader instruction opcodes
const U32 SIO_COMMENT = 0x0000FFFE;
const U32 SIO_END = 0x0000FFFF;
const U32 SI_OPCODE_MASK = 0x0000FFFF;
const U32 SI_COMMENTSIZE_MASK = 0x7FFF0000;
const U32 CTAB_CONSTANT = 0x42415443;

// Member functions
inline bool ConstantTable::Create(const void* data)
{
   const U32* ptr = static_cast<const U32*>(data);
   while(*++ptr != SIO_END)
   {
      if((*ptr & SI_OPCODE_MASK) == SIO_COMMENT)
      {
         // Check for CTAB comment
         U32 comment_size = (*ptr & SI_COMMENTSIZE_MASK) >> 16;
         if(*(ptr+1) != CTAB_CONSTANT)
         {
            ptr += comment_size;
            continue;
         }

         // Read header
         const char* ctab = reinterpret_cast<const char*>(ptr+2);
         size_t ctab_size = (comment_size-1)*4;

         const CTHeader* header = reinterpret_cast<const CTHeader*>(ctab);
         if(ctab_size < sizeof(*header) || header->Size != sizeof(*header))
            return false;
         m_creator = ctab + header->Creator;

         // Read constants
         m_constants.reserve(header->Constants);
         const CTInfo* info = reinterpret_cast<const CTInfo*>(ctab + header->ConstantInfo);
         for(U32 i = 0; i < header->Constants; ++i)
         {
            const CTType* type = reinterpret_cast<const CTType*>(ctab + info[i].TypeInfo);

            // Fill struct
            ConstantDesc desc;
            desc.Name = ctab + info[i].Name;
            desc.RegisterSet = static_cast<REGISTER_TYPE>(info[i].RegisterSet);
            desc.RegisterIndex = info[i].RegisterIndex;
            desc.RegisterCount = info[i].RegisterCount;
            desc.Rows = type->Rows;
            desc.Class = static_cast<CONST_CLASS>(type->Class);
            desc.Type = static_cast<CONST_TYPE>(type->Type);
            desc.Columns = type->Columns;
            desc.Elements = type->Elements;
            desc.StructMembers = type->StructMembers;
            desc.Bytes = 4 * desc.Elements * desc.Rows * desc.Columns;
            m_constants.push_back(desc);
         }

         return true;
      }
   }
   return false;
}

inline const ConstantDesc* ConstantTable::GetConstantByName(const String& name) const
{
   Vector<ConstantDesc>::const_iterator it;
   for(it = m_constants.begin(); it != m_constants.end(); ++it)
   {
      if(it->Name == name)
         return &(*it);
   }
   return NULL;
}

/////////////////// Constant Buffers /////////////////////////////

// Maximum number of CBuffers ($Globals & $Params)
const U32 CBUFFER_MAX = 2;

struct ConstSubBufferDesc
{
   U32 start;
   U32 size;

   ConstSubBufferDesc() : start(0), size(0){}
};

class GFXD3D11ConstBufferLayout : public GenericConstBufferLayout
{
public:
   GFXD3D11ConstBufferLayout();
   /// Get our constant sub buffer data
   Vector<ConstSubBufferDesc> &getSubBufferDesc(){ return mSubBuffers; }

   /// We need to manually set the size due to D3D11 alignment
   void setSize(U32 size){ mBufferSize = size;}

   /// Set a parameter, given a base pointer
   virtual bool set(const ParamDesc& pd, const GFXShaderConstType constType, const U32 size, const void* data, U8* basePointer);

protected:
   /// Set a matrix, given a base pointer
   virtual bool setMatrix(const ParamDesc& pd, const GFXShaderConstType constType, const U32 size, const void* data, U8* basePointer);

   Vector<ConstSubBufferDesc> mSubBuffers;
};

class GFXD3D11ShaderConstHandle : public GFXShaderConstHandle
{
public:

   // GFXShaderConstHandle
   const String& getName() const;
   GFXShaderConstType getType() const;
   U32 getArraySize() const;

   WeakRefPtr<GFXD3D11Shader> mShader;

   bool mVertexConstant;
   GenericConstBufferLayout::ParamDesc mVertexHandle;
   bool mPixelConstant;
   GenericConstBufferLayout::ParamDesc mPixelHandle;

   /// Is true if this constant is for hardware mesh instancing.
   ///
   /// Note: We currently store its settings in mPixelHandle.
   ///
   bool mInstancingConstant;

   void setValid( bool valid ) { mValid = valid; }
   S32 getSamplerRegister() const;

   // Returns true if this is a handle to a sampler register.
   bool isSampler() const
   {
      return ( mPixelConstant && mPixelHandle.constType >= GFXSCT_Sampler ) || ( mVertexConstant && mVertexHandle.constType >= GFXSCT_Sampler );
   }

   /// Restore to uninitialized state.
   void clear()
   {
      mShader = NULL;
      mVertexConstant = false;
      mPixelConstant = false;
      mInstancingConstant = false;
      mVertexHandle.clear();
      mPixelHandle.clear();
      mValid = false;
   }

   GFXD3D11ShaderConstHandle();
};

/// The D3D11 implementation of a shader constant buffer.
class GFXD3D11ShaderConstBuffer : public GFXShaderConstBuffer
{
   friend class GFXD3D11Shader;
   // Cache device context
   ID3D11DeviceContext* mDeviceContext;

public:

   GFXD3D11ShaderConstBuffer(GFXD3D11Shader* shader,
      GFXD3D11ConstBufferLayout* vertexLayout,
      GFXD3D11ConstBufferLayout* pixelLayout);

   virtual ~GFXD3D11ShaderConstBuffer();

   /// Called by GFXD3D11Device to activate this buffer.
   /// @param mPrevShaderBuffer The previously active buffer
   void activate(GFXD3D11ShaderConstBuffer *prevShaderBuffer);

   /// Used internally by GXD3D11ShaderConstBuffer to determine if it's dirty.
   bool isDirty();

   /// Called from GFXD3D11Shader when constants have changed and need
   /// to be the shader this buffer references is reloaded.
   void onShaderReload(GFXD3D11Shader *shader);

   // GFXShaderConstBuffer
   virtual GFXShader* getShader();
   virtual void set(GFXShaderConstHandle* handle, const F32 fv);
   virtual void set(GFXShaderConstHandle* handle, const Point2F& fv);
   virtual void set(GFXShaderConstHandle* handle, const Point3F& fv);
   virtual void set(GFXShaderConstHandle* handle, const Point4F& fv);
   virtual void set(GFXShaderConstHandle* handle, const PlaneF& fv);
   virtual void set(GFXShaderConstHandle* handle, const LinearColorF& fv);
   virtual void set(GFXShaderConstHandle* handle, const S32 f);
   virtual void set(GFXShaderConstHandle* handle, const Point2I& fv);
   virtual void set(GFXShaderConstHandle* handle, const Point3I& fv);
   virtual void set(GFXShaderConstHandle* handle, const Point4I& fv);
   virtual void set(GFXShaderConstHandle* handle, const AlignedArray<F32>& fv);
   virtual void set(GFXShaderConstHandle* handle, const AlignedArray<Point2F>& fv);
   virtual void set(GFXShaderConstHandle* handle, const AlignedArray<Point3F>& fv);
   virtual void set(GFXShaderConstHandle* handle, const AlignedArray<Point4F>& fv);
   virtual void set(GFXShaderConstHandle* handle, const AlignedArray<S32>& fv);
   virtual void set(GFXShaderConstHandle* handle, const AlignedArray<Point2I>& fv);
   virtual void set(GFXShaderConstHandle* handle, const AlignedArray<Point3I>& fv);
   virtual void set(GFXShaderConstHandle* handle, const AlignedArray<Point4I>& fv);
   virtual void set(GFXShaderConstHandle* handle, const MatrixF& mat, const GFXShaderConstType matType = GFXSCT_Float4x4);
   virtual void set(GFXShaderConstHandle* handle, const MatrixF* mat, const U32 arraySize, const GFXShaderConstType matrixType = GFXSCT_Float4x4);

   // GFXResource
   virtual const String describeSelf() const;
   virtual void zombify();
   virtual void resurrect();

protected:

   void _createBuffers();

   template<class T>
   inline void SET_CONSTANT(GFXShaderConstHandle* handle,
      const T& fv,
      GenericConstBuffer *vBuffer,
      GenericConstBuffer *pBuffer);

   // Constant buffers, VSSetConstantBuffers1 has issues on win 7. So unfortunately for now we have multiple constant buffers
   ID3D11Buffer* mConstantBuffersV[CBUFFER_MAX];
   ID3D11Buffer* mConstantBuffersP[CBUFFER_MAX];

   /// We keep a weak reference to the shader
   /// because it will often be deleted.
   WeakRefPtr<GFXD3D11Shader> mShader;

   //vertex
   GFXD3D11ConstBufferLayout* mVertexConstBufferLayout;
   GenericConstBuffer* mVertexConstBuffer;
   //pixel
   GFXD3D11ConstBufferLayout* mPixelConstBufferLayout;
   GenericConstBuffer* mPixelConstBuffer;
};

class gfxD3D11Include;
typedef StrongRefPtr<gfxD3D11Include> gfxD3DIncludeRef;

/////////////////// GFXShader implementation /////////////////////////////

class GFXD3D11Shader : public GFXShader
{
   friend class GFXD3D11Device;
   friend class GFXD3D11ShaderConstBuffer;

public:
   typedef Map<String, GFXD3D11ShaderConstHandle*> HandleMap;

   GFXD3D11Shader();
   virtual ~GFXD3D11Shader();

   // GFXShader
   virtual GFXShaderConstBufferRef allocConstBuffer();
   virtual const Vector<GFXShaderConstDesc>& getShaderConstDesc() const;
   virtual GFXShaderConstHandle* getShaderConstHandle(const String& name);
   virtual GFXShaderConstHandle* findShaderConstHandle(const String& name);
   virtual U32 getAlignmentValue(const GFXShaderConstType constType) const;
   virtual bool getDisassembly( String &outStr ) const;

   // GFXResource
   virtual void zombify();
   virtual void resurrect();

protected:

   virtual bool _init();

   static const U32 smCompiledShaderTag;

   ConstantTable table;

   ID3D11VertexShader *mVertShader;
   ID3D11PixelShader *mPixShader;

   GFXD3D11ConstBufferLayout* mVertexConstBufferLayout;
   GFXD3D11ConstBufferLayout* mPixelConstBufferLayout;

   static gfxD3DIncludeRef smD3DInclude;

   HandleMap mHandles;

   /// The shader disassembly from DX when this shader is compiled.
   /// We only store this data in non-release builds.
   String mDissasembly;

   /// Vector of sampler type descriptions consolidated from _compileShader.
   Vector<GFXShaderConstDesc> mSamplerDescriptions;

   /// Vector of descriptions (consolidated for the getShaderConstDesc call)
   Vector<GFXShaderConstDesc> mShaderConsts;

   // These two functions are used when compiling shaders from hlsl
   virtual bool _compileShader( const Torque::Path &filePath,
                                const String &target,
                                const D3D_SHADER_MACRO *defines,
                                GenericConstBufferLayout *bufferLayout,
                                Vector<GFXShaderConstDesc> &samplerDescriptions );

   void _getShaderConstants( ID3D11ShaderReflection* refTable,
	                         GenericConstBufferLayout *bufferLayout,
                             Vector<GFXShaderConstDesc> &samplerDescriptions );

   bool _convertShaderVariable(const D3D11_SHADER_TYPE_DESC &typeDesc, GFXShaderConstDesc &desc);

   bool _saveCompiledOutput( const Torque::Path &filePath,
                             ID3DBlob *buffer,
                             GenericConstBufferLayout *bufferLayout,
                             Vector<GFXShaderConstDesc> &samplerDescriptions );

   // Loads precompiled shaders
   bool _loadCompiledOutput( const Torque::Path &filePath,
                             const String &target,
                             GenericConstBufferLayout *bufferLayoutF,
                             Vector<GFXShaderConstDesc> &samplerDescriptions );

   // This is used in both cases
   virtual void _buildShaderConstantHandles(GenericConstBufferLayout *layout, bool vertexConst);

   virtual void _buildSamplerShaderConstantHandles( Vector<GFXShaderConstDesc> &samplerDescriptions );

   /// Used to build the instancing shader constants from
   /// the instancing vertex format.
   void _buildInstancingShaderConstantHandles();
};

inline bool GFXD3D11Shader::getDisassembly(String &outStr) const
{
   outStr = mDissasembly;
   return (outStr.isNotEmpty());
}

#endif


text:
namespace movable_square {
    const std::string module_name("movable_square");

    struct vec2 {
        float x;
        float y;
    };

    const char *vertex_shader_source = R"glsl(
#version 100

attribute vec4 position;
attribute vec4 color;

varying vec4 fragment_color;

uniform vec2 offset;

void main() {
    fragment_color = color;
    gl_Position = position + vec4(offset.xy, 0.0, 0.0);
}
)glsl";

    const char *fragment_shader_source = R"glsl(
#version 100

precision mediump float;

varying vec4 fragment_color;

void main() {
   gl_FragColor = fragment_color;
}
)glsl";

    const int vertex_depth = 4;
    const float square_units_per_msec = 0.001f;
    const float square_unit_offset = 0.025f;

    bool left_pressed = 0;
    bool right_pressed = 0;
    bool up_pressed = 0;
    bool down_pressed = 0;

    int run(int argc, char **argv) {
        engine e;
        window main_window;

        std::list<shader> shaders;
        shaders.emplace_back(GL_VERTEX_SHADER, vertex_shader_source);
        shaders.emplace_back(GL_FRAGMENT_SHADER, fragment_shader_source);
        shader_program main_program(shaders);

        std::vector<float> square_vertex_vector {
            0.1f, 0.1f, 0.0f, 1.0f,
            -0.1f, 0.1f, 0.0f, 1.0f,
            -0.1f, -0.1f, 0.0f, 1.0f,
            0.1f, -0.1f, 0.0f, 1.0f,
            0.0f, 1.0f, 0.0f, 1.0f,
            0.0f, 1.0f, 0.0f, 1.0f,
            0.0f, 1.0f, 0.0f, 1.0f,
            0.0f, 1.0f, 0.0f, 1.0f
        };
        const int vertex_count = square_vertex_vector.size() / vertex_depth / 2;
        vertex_buffer square_vertices(square_vertex_vector);

        main_program.use();
        square_vertices.bind();
        uint32_t position_attrib = main_program.get_attrib_location("position");
        glEnableVertexAttribArray(position_attrib);
        glVertexAttribPointer(position_attrib, vertex_depth, GL_FLOAT, GL_FALSE, 0, 0);
        uint32_t color_attrib = main_program.get_attrib_location("color");
        glEnableVertexAttribArray(color_attrib);
        glVertexAttribPointer(
                color_attrib,
                vertex_depth,
                GL_FLOAT,
                GL_FALSE,
                0,
                (GLvoid*) (sizeof(float) * vertex_depth * vertex_count));

        uint32_t offset_uniform = main_program.get_uniform_location("offset");
        vec2 offsets;

        SDL_Event event;
        bool done = false;
        while (!done) {
            while (SDL_PollEvent(&event)) {
                switch (event.type) {
                    case SDL_QUIT:
                        done = true;
                        break;
                    case SDL_KEYDOWN:
                        switch (event.key.keysym.sym) {
                            case SDLK_LEFT:  left_pressed = 1; break;
                            case SDLK_RIGHT: right_pressed = 1; break;
                            case SDLK_UP:    up_pressed = 1; break;
                            case SDLK_DOWN:  down_pressed = 1; break;
                        }
                        break;
                    case SDL_KEYUP:
                        switch (event.key.keysym.sym) {
                            case SDLK_LEFT:  left_pressed = 0; break;
                            case SDLK_RIGHT: right_pressed = 0; break;
                            case SDLK_UP:    up_pressed = 0; break;
                            case SDLK_DOWN:  down_pressed = 0; break;
                        }
                        break;
                }
            }

            if (left_pressed) {
                offsets.x -= square_unit_offset;
            }
            if (right_pressed) {
                offsets.x += square_unit_offset;
            }
            if (up_pressed) {
                offsets.y += square_unit_offset;
            }
            if (down_pressed) {
                offsets.y -= square_unit_offset;
            }

            glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
            glClear(GL_COLOR_BUFFER_BIT);

            glUniform2f(offset_uniform, offsets.x, offsets.y);

            glDrawArrays(GL_TRIANGLE_FAN, 0, vertex_count);

            main_window.swap();
        }

        return 0;
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Sign in · Storm Demo</title>
  <link href="assets/lib/bootstrap/css/bootstrap.css" rel="stylesheet">
  <link href="assets/common/login.css" rel="stylesheet">

      Invalid username/password.

    <form class="form-signin" method="post" action="login.html">

Please sign in

      <input type="text" class="input-block-level" placeholder="User name" name="username" value="gvetticaden">
      <input type="password" class="input-block-level" placeholder="Password" name="password" value="gvetticaden">
      <button class="btn btn-primary" type="submit">Sign in</button>

        Log in as gvetticaden/gvetticaden

    </form>


text:
.favMenu {
	BACKGROUND-IMAGE: url(../images/candan_di.gif); FONT: menu; CURSOR: hand; COLOR: windowtext
}
.favMenu DIV {
	WIDTH: 100%
}
.favMenu A {
	COLOR: windowtext; TEXT-DECORATION: none
}
.favMenu A:hover {
	COLOR: windowtext; TEXT-DECORATION: underline
}
.topFolder {
	BORDER-RIGHT: #f2f5f8 1px solid; PADDING-RIGHT: 2px; PADDING-LEFT: 1px; FONT-SIZE: 10pt; BACKGROUND-IMAGE: url(../images/candan_1di.gif); PADDING-BOTTOM: 0px; VERTICAL-ALIGN: middle; BORDER-LEFT: #f2f5f8 1px solid; PADDING-TOP: 0px; HEIGHT: 22px; BACKGROUND-COLOR: #f2f5f8
}
.topItem {
	BORDER-RIGHT: buttonface 1px solid; PADDING-RIGHT: 2px; BORDER-TOP: buttonface 1px solid; PADDING-LEFT: 2px; PADDING-BOTTOM: 2px; VERTICAL-ALIGN: middle; BORDER-LEFT: buttonface 1px solid; PADDING-TOP: 2px; BORDER-BOTTOM: buttonface 1px solid
}
.subFolder {
	PADDING-RIGHT: 3px; PADDING-LEFT: 3px; PADDING-BOTTOM: 3px; VERTICAL-ALIGN: middle; PADDING-TOP: 3px; HEIGHT: 25px
}
.subItem {
	PADDING-RIGHT: 3px; PADDING-LEFT: 3px; PADDING-BOTTOM: 4px; VERTICAL-ALIGN: middle; PADDING-TOP: 3px
}
.sub {
	BORDER-TOP-WIDTH: 0px; DISPLAY: none; FONT-SIZE: 9pt; BACKGROUND-IMAGE: url(../images/candan_di.gif); VERTICAL-ALIGN: middle; BORDER-LEFT: 0px; BORDER-BOTTOM: 0px
}
.sub .sub {
	BORDER-RIGHT: 0px; BORDER-TOP: 0px; BORDER-LEFT: 0px; BORDER-BOTTOM: 0px
}
.icon {
	VERTICAL-ALIGN: top; MARGIN-RIGHT: 5px
}
.outer {
	BORDER-RIGHT: buttonhighlight 1px solid; PADDING-RIGHT: 0px; BORDER-TOP: buttonshadow 1px solid; PADDING-LEFT: 0px; BACKGROUND: buttonface; PADDING-BOTTOM: 0px; BORDER-LEFT: buttonshadow 1px solid; PADDING-TOP: 0px; BORDER-BOTTOM: buttonhighlight 1px solid
}
.inner {
	BORDER-RIGHT: buttonshadow 1px solid; PADDING-RIGHT: 0px; BORDER-TOP: buttonhighlight 1px solid; PADDING-LEFT: 0px; PADDING-BOTTOM: 0px; OVERFLOW: hidden; BORDER-LEFT: buttonhighlight 1px solid; PADDING-TOP: 0px; BORDER-BOTTOM: buttonshadow 1px solid
}
.scrollButton {
	BORDER-RIGHT: buttonface 1px solid; BORDER-TOP: buttonface 1px solid; DISPLAY: none; FONT-SIZE: 10px; BACKGROUND: buttonface; OVERFLOW: hidden; BORDER-LEFT: buttonface 1px solid; WIDTH: 50px; CURSOR: default; COLOR: buttontext; BORDER-BOTTOM: buttonface 1px solid; FONT-FAMILY: webdings; POSITION: absolute; HEIGHT: 16px; TEXT-ALIGN: center
}
.flat {
	BORDER-RIGHT: buttonface 1px solid; PADDING-RIGHT: 0px; BORDER-TOP: buttonface 1px solid; PADDING-LEFT: 0px; PADDING-BOTTOM: 0px; BORDER-LEFT: buttonface 1px solid; PADDING-TOP: 0px; BORDER-BOTTOM: buttonface 1px solid
}