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

  var push = [].push;

  /**
   * @ngdoc overview
   * @name hz.dashboard.launch-instance
   * @description
   *
   * # hz.dashboard.launch-instance
   *
   * The `hz.dashboard.launch-instance` module allows a user
   * to launch an instance via the multi-step wizard framework
   *
   */
  var module = angular.module('hz.dashboard.launch-instance');

  /**
   * @name bootSourceTypes
   * @description Boot source types
   */
  module.constant('bootSourceTypes', {
    IMAGE: 'image',
    INSTANCE_SNAPSHOT: 'snapshot',
    VOLUME: 'volume',
    VOLUME_SNAPSHOT: 'volume_snapshot'
  });

  /**
   * @ngdoc filter
   * @name diskFormat
   * @description
   * Expects object and returns disk_format property value.
   * Returns empty string if input is null or not an object.
   * Uniquely required for the source step implementation of transfer tables
   */
  module.filter('diskFormat', function() {
    return function(input) {
      if (input === null || !angular.isObject(input) ||
        !angular.isDefined(input.disk_format) || input.disk_format === null) {
        return '';
      } else {
        return input.disk_format.toUpperCase();
      }
    };
  });

  /**
   * @ngdoc controller
   * @name LaunchInstanceSourceCtrl
   * @description
   * The `LaunchInstanceSourceCtrl` controller provides functions for
   * configuring the source step of the Launch Instance Wizard.
   *
   */
  module.controller('LaunchInstanceSourceCtrl', [
    '$scope',
    'bootSourceTypes',
    'bytesFilter',
    'horizon.framework.widgets.charts.donutChartSettings',
    'dateFilter',
    'decodeFilter',
    'diskFormatFilter',
    'gbFilter',
    'horizon.framework.widgets.charts.quotaChartDefaults',
    LaunchInstanceSourceCtrl
  ]);

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

    $scope.label = {
      title: gettext('Instance Details'),
      // jscs:disable maximumLineLength
      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.'),
      // jscs:enable maximumLineLength
      instanceName: gettext('Instance Name'),
      availabilityZone: gettext('Availability Zone'),
      instance_count: gettext('Count'),
      instanceSourceTitle: gettext('Instance Source'),
      // jscs:disable maximumLineLength
      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.'),
      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
    // jscs:disable maximumLineLength
    $scope.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.');
    // jscs:enable maximumLineLength
    $scope.instanceNameError = gettext('A name is required for your instance.');
    $scope.instanceCountError = gettext(
      'Instance count is required and must be an integer of at least 1'
    );
    $scope.volumeSizeError = gettext('Volume size is required and must be an integer');

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

    /*
     * Boot Sources
     */

    $scope.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') }
    ];

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

    /*
     * Transfer table
     */

    $scope.tableHeadCells = [];
    $scope.tableBodyCells = [];
    $scope.tableData = {};
    $scope.helpText = {};
    $scope.maxInstanceCount = 1;
    $scope.sourceDetails =
        '/static/dashboard/launch-instance/source/source-details.html';

    var selection = $scope.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' } }
      ]
    };

    // 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($scope.tableData, bootSources[key]);
    }

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

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

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

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

    /*
     * Donut chart
     */

    $scope.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;
    }

    $scope.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
        }
      ]
    };

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

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

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

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

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

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

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

    //
    // Validations
    //

    /*
     * 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 && $scope.currentBootSource === bootSourceTypes.IMAGE) {
        var imageGb = source.size * 1e-9;
        var imageDisk = source.min_disk;
        $scope.minVolumeSize = Math.ceil(Math.max(imageGb, imageDisk));

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

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

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

    // Validator for boot source type. Instance count must to be 1 if volume selected
    function validateBootSourceType() {
      var bootSourceType = $scope.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 = $scope.bootSourcesOptions[0];
        $scope.currentBootSource = $scope.bootSourcesOptions[0].type;
      }
    }

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

    // Initialize

    changeBootSource($scope.bootSourcesOptions[0].type);

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

  /**
   * @ngdoc controller
   * @name LaunchInstanceSourceHelpCtrl
   * @description
   * The `LaunchInstanceSourceHelpCtrl` controller provides functions for
   * configuring the help text used within the source step of the
   * Launch Instance Wizard.
   */
  module.controller('LaunchInstanceSourceHelpCtrl', [
    LaunchInstanceSourceHelpCtrl
  ]);

  function LaunchInstanceSourceHelpCtrl() {
    var ctrl = this;

    ctrl.title = gettext('Select Source Help');

    ctrl.instanceDetailsTitle = gettext('Instance Details');
    ctrl.instanceDetailsParagraphs = [
      // jscs:disable maximumLineLength
      gettext('An instance name is required and used to help you uniquely identify your instance in the dashboard.'),
      gettext('If you select an availability zone and plan to use the boot from volume option, make sure that the availability zone you select for the instance is the same availability zone where your bootable volume resides.')
      // jscs:enable maximumLineLength
    ];

    ctrl.instanceSourceTitle = gettext('Instance Source');
    ctrl.instanceSourceParagraphs = [
      // jscs:disable maximumLineLength
      gettext('If you want to create an instance that uses ephemeral storage, meaning the instance data is lost when the instance is deleted, then choose one of the following boot sources:'),
      gettext('
Image: This option uses an image to boot the instance.
'),
      gettext('
Instance Snapshot: This option uses an instance snapshot to boot the instance.
'),
      gettext('If you want to create an instance that uses persistent storage, meaning the instance data is saved when the instance is deleted, then select one of the following boot options:'),
      gettext('
Image (with Create New Volume checked): This options uses an image to boot the instance, and creates a new volume to persist instance data. You can specify volume size and whether to delete the volume on termination of the instance.
'),
      gettext('
Volume: This option uses a volume that already exists. It does not create a new volume. You can choose to delete the volume on termination of the instance. Note: when selecting Volume, you can only launch one instance.
'),
      gettext('
Volume Snapshot: This option uses a volume snapshot to boot the instance, and creates a new volume to persist instance data. You can choose to delete the volume on termination of the instance.
')
      // jscs:enable maximumLineLength
    ];
  }

})();


text:
$(document).ready(function() {
  var notes = $("em:contains('NOTE:')");
  notes.addClass("note");
  $.each(notes, function(index, note) {
    var noteText = note.innerHTML;
    note.innerHTML = noteText.replace("NOTE:", "NOTE:");
  });

  $(":header:contains('Ubuntu/Debian')").addClass("ubuntu").prepend("");
  $(":header:contains('CentOS/RHEL')").addClass("centos").prepend("");

  var dts = $("#documentation > dl > dt");
  $.each(dts, function(index, dt) {
    $("
").insertBefore(dt);
  });

  $(".hamburger-button").click(function() {
    $(this).toggleClass("collapsed");
    $(".toc-collapse").slideToggle();
  });
});

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DomainModel;
using DomainModel.Projections;
using DomainServices;

namespace AccoBooking.ViewModels.Acco
{
  [Export, PartCreationPolicy(CreationPolicy.NonShared)]
  public class AccoReminderSearchViewModel : BaseSearchViewModel<AccoReminder, AccoReminderListItem>
  {
    [ImportingConstructor]
    public AccoReminderSearchViewModel(IUnitOfWorkManager<IAccoBookingUnitOfWork> unitOfWorkManager)
      : base(unitOfWorkManager)
    {

    }

    protected async override Task<IEnumerable<AccoReminderListItem>> ExecuteQuery()
    {
      var items = await UnitOfWork.AccoReminderSearchService.FindAccoRemindersAsync(_parentid, CancellationToken.None);
      return items.OrderBy(x => x.DisplaySequence);

    }

  }

}


text:
{% load i18n %}

{% block content %}
	{% block title %}
{% trans "Copy options" %}
{% endblock %}
	{% block header %}
{% blocktrans %}Choose copy options{% endblocktrans %}
{% endblock %}

	{% block form %}
	{% if form %}
	<form action="." method="post">
		{% csrf_token %}
		{{ form.as_p }}
	</form>
	{% endif %}
	{% endblock %}

	{% block submit_row %}

		<input type="submit" value="{% trans 'Save' %}" class="default submit" />
		<input type="submit" value="{% trans 'Close' %}" class="cancel" />

	{% endblock %}
{% endblock %}

{% block script %}

{% endblock %}


text:
package io.scribeapp.classifier.meta;

import java.io.IOException;

import io.scribeapp.R;
import io.scribeapp.classifier.Classifier;
import io.scribeapp.classifier.ann.Network;
import io.scribeapp.classifier.ann.NetworkImpl;
import io.scribeapp.classifier.model.ClassificationResult;
import io.scribeapp.classifier.model.LabelClassificationResult;
import io.scribeapp.classifier.model.LabelClassificationResult.Label;
import io.scribeapp.classifier.gesture.GestureLibraryClassifier;
import io.scribeapp.classifier.utils.PCA;
import io.scribeapp.classifier.utils.Utils;

import android.content.Context;
import android.gesture.Gesture;
import android.graphics.Bitmap;
import android.util.Log;

import javax.inject.Inject;

public class MetaClassifier implements Classifier {
	private static final String TAG = "MetaClassifier";

	private Network small_net;
	private Network capital_net;
	private Network digit_net;

	private GestureLibraryClassifier small_library;
	private GestureLibraryClassifier capital_library;
	private GestureLibraryClassifier number_library;
	private PCA pca;

    @Inject
	public MetaClassifier(Context context) {
		try {
			pca = new PCA(context);

			small_net = NetworkImpl.createFromInputStream(context.getAssets().open("pl_small_net"), SMALL_ALPHA);
			capital_net = NetworkImpl.createFromInputStream(context.getAssets().open("pl_capital_net"), CAPITAL_ALPHA);
			digit_net = NetworkImpl.createFromInputStream(context.getAssets().open("digit_net"), DIGIT);

			small_library = new GestureLibraryClassifier(context, GestureLibraryClassifier.USER_SMALL_FILENAME);
			if (!small_library.isValid()) {
				Log.d(TAG, "Default small lib");
				small_library = new GestureLibraryClassifier(context, R.raw.default_small_lib);
			}

			capital_library = new GestureLibraryClassifier(context, GestureLibraryClassifier.USER_CAPITAL_FILENAME);
			if (!capital_library.isValid()) {
				capital_library = new GestureLibraryClassifier(context, R.raw.default_capital_lib);
				Log.d(TAG, "Default capital lib");
			}

			number_library = new GestureLibraryClassifier(context, GestureLibraryClassifier.USER_DIGIT_FILENAME);
			if (!number_library.isValid()) {
				number_library = new GestureLibraryClassifier(context, R.raw.default_digit_lib);
				Log.d(TAG, "Default number lib");
			}

		}
		catch (IOException e) {
			e.printStackTrace();
		}

		Log.i(TAG, "Classifier loaded");
	}

	public ClassificationResult classify(Gesture gesture, int type) {
		float[] sample = prepare(gesture);
		if (sample == null) return null;
		LabelClassificationResult result = null;

		float threshold = 0.0000001f;

		if (type == SMALL_ALPHA) {
			LabelClassificationResult small_net_result = (LabelClassificationResult) small_net.classify(sample);
			LabelClassificationResult small_lib_result = small_library.classify(gesture, SMALL_ALPHA);

			LabelClassificationResult pairs = small_net_result.pairsWith(small_lib_result);

			if (pairs.result.size() > 0)  {
				result = pairs;
			}
			else {
				result = small_net_result.filter(threshold);
			}
		}
		else if (type == CAPITAL_ALPHA) {
			LabelClassificationResult capital_net_result = (LabelClassificationResult) capital_net.classify(sample);
			LabelClassificationResult capital_lib_result = capital_library.classify(gesture, CAPITAL_ALPHA);

			LabelClassificationResult pairs = capital_net_result.pairsWith(capital_lib_result);
			if (pairs.result.size() > 0) {
				result = pairs;
			}
			else {
				result = capital_net_result.filter(threshold);
				Label[] labelsWithBelief = result.getLabelsWithBelief();
				if (labelsWithBelief.length > 0)
				Log.d(TAG, "Best from net: "+labelsWithBelief[0].belief+ " "+labelsWithBelief[0].label);
			}
		}
		else if (type == DIGIT) {
			LabelClassificationResult digit_net_result = (LabelClassificationResult) digit_net.classify(sample);
			LabelClassificationResult digit_lib_result = number_library.classify(gesture, DIGIT);

			result = digit_net_result.combine(digit_lib_result).filter(threshold);
		}

		if (result.isEmpty()) result = null;

//		if (result != null) {
//			for (Label l : result.result)
//				Log.i(TAG, "RESULT: " + l.label + " " + l.belief);
//
//			Character c = result.getLabels()[0];
//			try {
//				Utils.saveBitmap(bitmap, "P-" + System.currentTimeMillis() + "-" + c);
//			}
//			catch (IOException e) {
//				e.printStackTrace();
//			}
//		}

		return result;
	}

    @Override
    public ClassificationResult classify(Gesture gesture) {
        return null;
    }

    /**
	 * Konwertuje podany gest na wektor zapisany w tablicy wartości float.
	 * Wektor ten jest tworzony zgodnie z formatem MNIST, a podlega analizie głównych składowych (PCA).
	 * @param gesture
	 * @return
	 */
	private float[] prepare(Gesture gesture) {
		Bitmap in = Utils.getBitmapFromGesture(gesture);
		if (in == null) return null;
		if (in.getWidth() > in.getHeight()) {
			in = Bitmap.createScaledBitmap(in, 20, Math.max(20 * in.getHeight() / in.getWidth(), 1), true);
		}
		else {
			in = Bitmap.createScaledBitmap(in, Math.max(20 * in.getWidth() / in.getHeight(), 1), 20, true);
		}

		float[] sample = Utils.getVectorFromBitmap(in);

		return pca.applyPCA(sample);
	}

	/**
	 * Nieużywane, zawsze zwraca null
	 * @see Classifier#classify(float[])
	 */
	@Override
	public LabelClassificationResult classify(float[] sample) {
		return null;
	}

	/**
	 * Nieużywane, zawsze zwraca null
	 * @see Classifier#classifyRaw(float[])
	 */
	@Override
	public float[] classifyRaw(float[] sample) {
		return null;
	}
}


text:
<#
.Synopsis
   Get the configured port range set on a policy for discovery.
.DESCRIPTION
   Get the configured port range set on a policy for discovery.
.EXAMPLE
   Get-NessusPolicyPortRange -SessionId 0 -PolicyId 112 | fl

    PolicyId  : 112
    PortRange : default
#>
function Get-NessusPolicyPortRange
{
    [CmdletBinding()]
    [OutputType([int])]
    Param
    (
        # Nessus session Id
        [Parameter(Mandatory=$true,
                   Position=0,
                   ValueFromPipelineByPropertyName=$true)]
        [Alias('Index')]
        [int32]
        $SessionId,

        [Parameter(Mandatory=$true,
                   Position=1,
                   ValueFromPipelineByPropertyName=$true)]
        [int32[]]
        $PolicyId
    )

    Begin
    {
        $sessions = Get-NessusSession | Select-Object -ExpandProperty sessionid
        if ($SessionId -notin $sessions)
        {
            throw "SessionId $($SessionId) is not present in the current sessions."
        }
        $Session = Get-NessusSession -SessionId $SessionId
    }
    Process
    {
        foreach ($PolicyToChange in $PolicyId)
        {
            try
            {
                $Policy = Get-NessusPolicyDetail -SessionId $Session.SessionId -PolicyId $PolicyToChange
                $UpdateProps = [ordered]@{
                    'PolicyId' = $PolicyToChange
                    'PortRange' = $Policy.settings.portscan_range
                }
                $PolSettingsObj = [PSCustomObject]$UpdateProps
                $PolSettingsObj.pstypenames.insert(0,'Nessus.PolicySetting')
                $PolSettingsObj
            }
            catch
            {
                throw $_
            }

        }
    }
    End
    {
    }
}

<#
.Synopsis
   Set port range set on a Policy for discovery.
.DESCRIPTION
   Set port range set on a Policy for discovery.
.EXAMPLE
   Set-NessusPolicyPortRange -SessionId 0 -PolicyId 112 -Port 22,23,25,80,400-1000 | fl

    PolicyId  : 112
    PortRange : 22,23,25,80,400-1000
#>
function Set-NessusPolicyPortRange
{
    [CmdletBinding()]
    [OutputType([int])]
    Param
    (
        # Nessus session Id
        [Parameter(Mandatory=$true,
                   Position=0,
                   ValueFromPipelineByPropertyName=$true)]
        [Alias('Index')]
        [int32]
        $SessionId,

        [Parameter(Mandatory=$true,
                   Position=1,
                   ValueFromPipelineByPropertyName=$true)]
        [int32[]]
        $PolicyId,

        [Parameter(Mandatory=$true,
                   Position=2,
                   ValueFromPipelineByPropertyName=$true)]
        [string[]]
        $Port
    )

    Begin
    {
        $sessions = Get-NessusSession | Select-Object -ExpandProperty sessionid
        if ($SessionId -notin $sessions)
        {
            throw "SessionId $($SessionId) is not present in the current sessions."
        }
        $Session = Get-NessusSession -SessionId $SessionId
    }
    Process
    {
        foreach ($PolicyToChange in $PolicyId)
        {
            $RequestParams = @{
                'SessionObject' = $Session
                'Path' = "/policies/$($PolicyToChange)"
                'Method' = 'PUT'
                'ContentType' = 'application/json'
                'Parameter'= "{`"settings`": {`"portscan_range`": `"$($Port -join ",")`"}}"
            }

            InvokeNessusRestRequest @RequestParams | Out-Null
            Get-NessusPolicyPortRange -SessionId $SessionId -PolicyId $PolicyToChange

        }
    }
    End
    {
    }
}

<#
.Synopsis
   Adds to the currently configured configured port range set on a policy for discovery.
.DESCRIPTION
   Adds to the currently configured configured port range set on a policy for discovery.
.EXAMPLE
   Add-NessusPolicyPortRange -SessionId 0 -PolicyId 112 -Port 3389 | fl

    PolicyId  : 112
    PortRange : 22,23,25,80,400-1000,3389
#>
function Add-NessusPolicyPortRange
{
    [CmdletBinding()]
    [OutputType([int])]
    Param
    (
        # Nessus session Id
        [Parameter(Mandatory=$true,
                   Position=0,
                   ValueFromPipelineByPropertyName=$true)]
        [Alias('Index')]
        [int32]
        $SessionId = @(),

        [Parameter(Mandatory=$true,
                   Position=1,
                   ValueFromPipelineByPropertyName=$true)]
        [int32[]]
        $PolicyId,

        [Parameter(Mandatory=$true,
                   Position=2,
                   ValueFromPipelineByPropertyName=$true)]
        [string[]]
        $Port
    )

    Begin
    {
        $sessions = Get-NessusSession | Select-Object -ExpandProperty sessionid
        if ($SessionId -notin $sessions)
        {
            throw "SessionId $($SessionId) is not present in the current sessions."
        }
        $Session = Get-NessusSession -SessionId $SessionId
    }
    Process
    {
        foreach ($PolicyToChange in $PolicyId)
        {
            try{
                $Policy = Get-NessusPolicyDetail -SessionId $Session.SessionId -PolicyId $PolicyToChange
                $Ports = "$($Policy.settings.portscan_range),$($Port -join ",")"
                $RequestParams = @{
                    'SessionObject' = $Session
                    'Path' = "/policies/$($PolicyToChange)"
                    'Method' = 'PUT'
                    'ContentType' = 'application/json'
                    'Parameter'= "{`"settings`": {`"portscan_range`": `"$($Ports)`"}}"
                }

                InvokeNessusRestRequest @RequestParams | Out-Null
                Get-NessusPolicyPortRange -SessionId $SessionId -PolicyId $PolicyToChange
             }
             catch
             {
               throw $_
             }
        }
    }
    End
    {
    }
}

<#
.Synopsis
   Get the configuration state of the port scanner in a policy.
.DESCRIPTION
   Get the configuration state of the port scanner in a policy.
.EXAMPLE
   Get-NessusPolicyPortScanner -SessionId 0 -PolicyId 111 | fl

    PolicyId   : 111
    SYNScanner : yes
    UDPScanner : no
    TCPScanner : yes
#>
function Get-NessusPolicyPortScanner
{
    [CmdletBinding()]
    [OutputType([int])]
    Param
    (
        # Nessus session Id
        [Parameter(Mandatory=$true,
                   Position=0,
                   ValueFromPipelineByPropertyName=$true)]
        [Alias('Index')]
        [int32]
        $SessionId,

        [Parameter(Mandatory=$true,
                   Position=1,
                   ValueFromPipelineByPropertyName=$true)]
        [int32[]]
        $PolicyId
    )

    Begin
    {
        $sessions = Get-NessusSession | Select-Object -ExpandProperty sessionid
        if ($SessionId -notin $sessions)
        {
            throw "SessionId $($SessionId) is not present in the current sessions."
        }
        $Session = Get-NessusSession -SessionId $SessionId
    }
    Process
    {
        foreach ($PolicyToChange in $PolicyId)
        {
            try
            {
                $Policy = Get-NessusPolicyDetail -SessionId $Session.SessionId -PolicyId $PolicyToChange
                $UpdateProps = [ordered]@{
                    'PolicyId' = $PolicyToChange
                    'SYNScanner' = $Policy.settings.syn_scanner
                    'UDPScanner' = $Policy.settings.udp_scanner
                    'TCPScanner' = $Policy.settings.tcp_scanner
                }
                $PolSettingsObj = [PSCustomObject]$UpdateProps
                $PolSettingsObj.pstypenames.insert(0,'Nessus.PolicySetting')
                $PolSettingsObj
            }
            catch
            {
                throw $_
            }

        }
    }
    End
    {
    }
}

<#
.Synopsis
   Enable one or more port scanners on a policy.
.DESCRIPTION
   Enable one or more port scanners on a policy.
.EXAMPLE
   Enable-NessusPolicyPortScanner -SessionId 0 -PolicyId 111 -ScanMethods SYN,TCP | fl

    PolicyId   : 111
    SYNScanner : yes
    UDPScanner : no
    TCPScanner : yes
#>
function Enable-NessusPolicyPortScanner
{
    [CmdletBinding()]
    [OutputType([int])]
    Param
    (
        # Nessus session Id
        [Parameter(Mandatory = $true,
                   Position = 0,
                   ValueFromPipelineByPropertyName = $true)]
        [Alias('Index')]
        [int32]
        $SessionId,

        [Parameter(Mandatory = $true,
                   Position = 1,
                   ValueFromPipelineByPropertyName = $true)]
        [int32[]]
        $PolicyId,

        [Parameter(Mandatory = $true,
                   Position = 2,
                   ValueFromPipelineByPropertyName = $true)]
        [ValidateSet('TCP', 'SYN', 'UDP')]
        [string[]]
        $ScanMethods
    )

    Begin
    {
        $sessions = Get-NessusSession | Select-Object -ExpandProperty sessionid
        if ($SessionId -notin $sessions)
        {
            throw "SessionId $($SessionId) is not present in the current sessions."
        }
        $Session = Get-NessusSession -SessionId $SessionId

        $Scanners = @{}
        foreach ($Scanner in $ScanMethods)
        {
            if($Scanner -eq 'TCP')
            {$Scanners['tcp_scanner'] = 'yes'}

            if($Scanner -eq 'UDP')
            {$Scanners['udp_scanner'] = 'yes'}

            if($Scanner -eq 'SYN')
            {$Scanners['syn_scanner'] = 'yes'}
        }

        $Settings = @{'settings' = $Scanners}
        $SettingsJson = ConvertTo-Json -InputObject $Settings -Compress
    }
    Process
    {
        foreach ($PolicyToChange in $PolicyId)
        {
            $RequestParams = @{
                'SessionObject' = $Session
                'Path' = "/policies/$($PolicyToChange)"
                'Method' = 'PUT'
                'ContentType' = 'application/json'
                'Parameter'= $SettingsJson
            }

            InvokeNessusRestRequest @RequestParams | Out-Null
            Get-NessusPolicyPortScanner -SessionId $SessionId -PolicyId $PolicyToChange

        }
    }
    End
    {
    }
}

<#
.Synopsis
   Disable one or more port scanners on a policy.
.DESCRIPTION
   Disable one or more port scanners on a policy.
.EXAMPLE
   Disable-NessusPolicyPortScanner -SessionId 0 -PolicyId 111 -ScanMethods UDP | fl

    PolicyId   : 111
    SYNScanner : yes
    UDPScanner : no
    TCPScanner : yes
#>
function Disable-NessusPolicyPortScanner
{
    [CmdletBinding()]
    [OutputType([int])]
    Param
    (
        # Nessus session Id
        [Parameter(Mandatory = $true,
                   Position = 0,
                   ValueFromPipelineByPropertyName = $true)]
        [Alias('Index')]
        [int32]
        $SessionId,

        [Parameter(Mandatory = $true,
                   Position = 1,
                   ValueFromPipelineByPropertyName = $true)]
        [int32[]]
        $PolicyId,

        [Parameter(Mandatory = $true,
                   Position = 2,
                   ValueFromPipelineByPropertyName = $true)]
        [ValidateSet('TCP', 'SYN', 'UDP')]
        [string[]]
        $ScanMethods
    )

    Begin
    {
        $sessions = Get-NessusSession | Select-Object -ExpandProperty sessionid
        if ($SessionId -notin $sessions)
        {
            throw "SessionId $($SessionId) is not present in the current sessions."
        }
        $Session = Get-NessusSession -SessionId $SessionId

        $Scanners = @{}
        foreach ($Scanner in $ScanMethods)
        {
            if($Scanner -eq 'TCP')
            {$Scanners['tcp_scanner'] = 'no'}

            if($Scanner -eq 'UDP')
            {$Scanners['udp_scanner'] = 'no'}

            if($Scanner -eq 'SYN')
            {$Scanners['syn_scanner'] = 'no'}
        }

        $Settings = @{'settings' = $Scanners}
        $SettingsJson = ConvertTo-Json -InputObject $Settings -Compress
    }
    Process
    {
        foreach ($PolicyToChange in $PolicyId)
        {
            $RequestParams = @{
                'SessionObject' = $Session
                'Path' = "/policies/$($PolicyToChange)"
                'Method' = 'PUT'
                'ContentType' = 'application/json'
                'Parameter'= $SettingsJson
            }

            InvokeNessusRestRequest @RequestParams | Out-Null
            Get-NessusPolicyPortScanner -SessionId $SessionId -PolicyId $PolicyToChange

        }
    }
    End
    {
    }
}

<#
.Synopsis
   Get the local port enumeration settings for a policy.
.DESCRIPTION
   Get the local port enumeration settings for a policy. On Windows system Nessus uses
   WMI to run and parse netstat information, on Linux and Unix host it uses SSH to run
   and parse the netstat information. SNMP Can also be used to query the open port MIBs
   for the different operating systems to avoid scanning the host.
.EXAMPLE
   Get-NessusPolicyLocalPortEnumeration -SessionId 0 -PolicyId 111

    PolicyId             : 111
    WMINetstat           : yes
    SSHNetstat           : yes
    SNMPScanner          : no
    VerifyOpenPorts      : yes
    ScanOnlyIfLocalFails : no
#>
function Get-NessusPolicyLocalPortEnumeration
{
    [CmdletBinding()]
    [OutputType([int])]
    Param
    (
        # Nessus session Id
        [Parameter(Mandatory=$true,
                   Position=0,
                   ValueFromPipelineByPropertyName=$true)]
        [Alias('Index')]
        [int32]
        $SessionId,

        [Parameter(Mandatory=$true,
                   Position=1,
                   ValueFromPipelineByPropertyName=$true)]
        [int32[]]
        $PolicyId
    )

    Begin
    {
        $sessions = Get-NessusSession | Select-Object -ExpandProperty sessionid
        if ($SessionId -notin $sessions)
        {
            throw "SessionId $($SessionId) is not present in the current sessions."
        }
        $Session = Get-NessusSession -SessionId $SessionId
    }
    Process
    {
        foreach ($PolicyToChange in $PolicyId)
        {
            try
            {
                $Policy = Get-NessusPolicyDetail -SessionId $Session.SessionId -PolicyId $PolicyToChange
                $UpdateProps = [ordered]@{
                    'PolicyId' = $PolicyToChange
                    'WMINetstat' = $Policy.settings.wmi_netstat_scanner
                    'SSHNetstat' = $Policy.settings.ssh_netstat_scanner
                    'SNMPScanner' = $Policy.settings.snmp_scanner
                    'VerifyOpenPorts' = $Policy.settings.verify_open_ports
                    'ScanOnlyIfLocalFails' = $Policy.settings.only_portscan_if_enum_failed
                }
                $PolSettingsObj = [PSCustomObject]$UpdateProps
                $PolSettingsObj.pstypenames.insert(0,'Nessus.PolicySetting')
                $PolSettingsObj
            }
            catch
            {
                throw $_
            }

        }
    }
    End
    {
    }
}

<#
.Synopsis
   Enable the local port enumeration settings for a policy.
.DESCRIPTION
   Enable local port enumeration settings for a policy. On Windows system Nessus uses
   WMI to run and parse netstat information, on Linux and Unix host it uses SSH to run
   and parse the netstat information. SNMP Can also be used to query the open port MIBs
   for the different operating systems to avoid scanning the host.
.EXAMPLE
   Enable-NessusPolicyLocalPortEnumeration -SessionId 0 -PolicyId 111 -ScanMethods WMINetstat,SNMPScanner,SSHNetstat -VerifyOpenPorts -ScanOnlyIfLocalFails

    PolicyId             : 111
    WMINetstat           : yes
    SSHNetstat           : yes
    SNMPScanner          : yes
    VerifyOpenPorts      : yes
    ScanOnlyIfLocalFails : yes
#>
function Enable-NessusPolicyLocalPortEnumeration
{
    [CmdletBinding()]
    [OutputType([int])]
    Param
    (
        # Nessus session Id
        [Parameter(Mandatory = $true,
                   Position = 0,
                   ValueFromPipelineByPropertyName = $true)]
        [Alias('Index')]
        [int32]
        $SessionId,

        [Parameter(Mandatory = $true,
                   Position = 1,
                   ValueFromPipelineByPropertyName = $true)]
        [int32[]]
        $PolicyId,

        [Parameter(Mandatory = $true,
                   Position = 2,
                   ValueFromPipelineByPropertyName = $true)]
        [ValidateSet('WMINetstat', 'SSHNetstat', 'SNMPScanner')]
        [string[]]
        $ScanMethods,

        [Parameter(Mandatory = $false,
                   ValueFromPipelineByPropertyName = $true)]
        [switch]
        $VerifyOpenPorts,

        [Parameter(Mandatory = $false,
                   ValueFromPipelineByPropertyName = $true)]
        [switch]
        $ScanOnlyIfLocalFails
    )

    Begin
    {
        $sessions = Get-NessusSession | Select-Object -ExpandProperty sessionid
        if ($SessionId -notin $sessions)
        {
            throw "SessionId $($SessionId) is not present in the current sessions."
        }
        $Session = Get-NessusSession -SessionId $SessionId

        $Scanners = @{}
        foreach ($Scanner in $ScanMethods)
        {
            if($Scanner -eq 'WMINetstat')
            {$Scanners['wmi_netstat_scanner'] = 'yes'}

            if($Scanner -eq 'SSHNetstat')
            {$Scanners['ssh_netstat_scanner'] = 'yes'}

            if($Scanner -eq 'SNMPScanner')
            {$Scanners['snmp_scanner'] = 'yes'}
        }

        if($VerifyOpenPorts)
        {$Scanners['verify_open_ports'] = 'yes'}

        if($ScanOnlyIfLocalFails)
        {$Scanners['only_portscan_if_enum_failed'] = 'yes'}

        $Settings = @{'settings' = $Scanners}
        $SettingsJson = ConvertTo-Json -InputObject $Settings -Compress
    }
    Process
    {
        foreach ($PolicyToChange in $PolicyId)
        {
            $RequestParams = @{
                'SessionObject' = $Session
                'Path' = "/policies/$($PolicyToChange)"
                'Method' = 'PUT'
                'ContentType' = 'application/json'
                'Parameter'= $SettingsJson
            }

            InvokeNessusRestRequest @RequestParams | Out-Null
            Get-NessusPolicyLocalPortEnumeration -SessionId $SessionId -PolicyId $PolicyToChange

        }
    }
    End
    {
    }
}

<#
.Synopsis
   Disable the local port enumeration settings for a policy.
.DESCRIPTION
   Disable local port enumeration settings for a policy. On Windows system Nessus uses
   WMI to run and parse netstat information, on Linux and Unix host it uses SSH to run
   and parse the netstat information. SNMP Can also be used to query the open port MIBs
   for the different operating systems to avoid scanning the host.
.EXAMPLE
   Disable-NessusPolicyLocalPortEnumeration -SessionId 0 -PolicyId 111 -ScanMethods SNMPScanner -ScanOnlyIfLocalFails

    PolicyId             : 111
    WMINetstat           : yes
    SSHNetstat           : yes
    SNMPScanner          : no
    VerifyOpenPorts      : yes
    ScanOnlyIfLocalFails : no
#>
function Disable-NessusPolicyLocalPortEnumeration
{
    [CmdletBinding()]
    [OutputType([int])]
    Param
    (
        # Nessus session Id
        [Parameter(Mandatory = $true,
                   Position = 0,
                   ValueFromPipelineByPropertyName = $true)]
        [Alias('Index')]
        [int32]
        $SessionId,

        [Parameter(Mandatory = $true,
                   Position = 1,
                   ValueFromPipelineByPropertyName = $true)]
        [int32[]]
        $PolicyId,

        [Parameter(Mandatory = $true,
                   Position = 2,
                   ValueFromPipelineByPropertyName = $true)]
        [ValidateSet('WMINetstat', 'SSHNetstat', 'SNMPScanner')]
        [string[]]
        $ScanMethods,

        [Parameter(Mandatory = $false,
                   ValueFromPipelineByPropertyName = $true)]
        [switch]
        $VerifyOpenPorts,

        [Parameter(Mandatory = $false,
                   ValueFromPipelineByPropertyName = $true)]
        [switch]
        $ScanOnlyIfLocalFails
    )

    Begin
    {
        $sessions = Get-NessusSession | Select-Object -ExpandProperty sessionid
        if ($SessionId -notin $sessions)
        {
            throw "SessionId $($SessionId) is not present in the current sessions."
        }
        $Session = Get-NessusSession -SessionId $SessionId

        $Scanners = @{}
        foreach ($Scanner in $ScanMethods)
        {
            if($Scanner -eq 'WMINetstat')
            {$Scanners['wmi_netstat_scanner'] = 'no'}

            if($Scanner -eq 'SSHNetstat')
            {$Scanners['ssh_netstat_scanner'] = 'no'}

            if($Scanner -eq 'SNMPScanner')
            {$Scanners['snmp_scanner'] = 'no'}
        }

        if($VerifyOpenPorts)
        {$Scanners['verify_open_ports'] = 'no'}

        if($ScanOnlyIfLocalFails)
        {$Scanners['only_portscan_if_enum_failed'] = 'no'}

        $Settings = @{'settings' = $Scanners}
        $SettingsJson = ConvertTo-Json -InputObject $Settings -Compress
    }
    Process
    {
        foreach ($PolicyToChange in $PolicyId)
        {
            $RequestParams = @{
                'SessionObject' = $Session
                'Path' = "/policies/$($PolicyToChange)"
                'Method' = 'PUT'
                'ContentType' = 'application/json'
                'Parameter'= $SettingsJson
            }

            InvokeNessusRestRequest @RequestParams | Out-Null
            Get-NessusPolicyLocalPortEnumeration -SessionId $SessionId -PolicyId $PolicyToChange

        }
    }
    End
    {
    }
}


text:
package edu.umass.cs.ciir.waltz.sys.tmp;

import ciir.jfoley.chai.io.Directory;
import ciir.jfoley.chai.io.IO;
import ciir.jfoley.chai.jvm.MemoryNotifier;
import edu.umass.cs.ciir.waltz.coders.sorter.GeometricItemMerger;
import edu.umass.cs.ciir.waltz.sys.PostingIndexWriter;
import edu.umass.cs.ciir.waltz.sys.PostingsConfig;

import java.io.Closeable;
import java.io.File;
import java.io.Flushable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * @author jfoley
 */
public final class TmpStreamPostingIndexWriter<K, V> implements Flushable, Closeable {
  private final Directory tmpDir;
  PostingsConfig<K, V> cfg;
  public MemoryPostingIndex<K,V> tmpIndex;
  private int totalDocuments;
  private int flushSize = 200000;
  GeometricItemMerger merger;

  public TmpStreamPostingIndexWriter(Directory outputDir, String baseName, PostingsConfig<K, V> cfg) {
    this.tmpDir = outputDir.childDir(baseName + ".tmp");
    this.cfg = cfg;
    tmpIndex = new MemoryPostingIndex<>(cfg);
    this.totalDocuments = 0;
    this.merger = new GeometricItemMerger(8, new MergeIntermediate());
    MemoryNotifier.register(this);
  }

  public synchronized int addDocument() {
    // local doc number
    this.tmpIndex.totalDocuments++;
    // global doc number
    return totalDocuments++;
  }

  public synchronized void add(MemoryPostingIndex<K,V> memIndex) {
    int currentId = merger.allocate();
    File output = getOutput(currentId);

    // flush to disk asynchronously
    merger.doAsync(() -> {
      try (TmpPostingWriter<K, V> writer = new TmpPostingWriter<>(cfg, output)) {
        memIndex.write(writer);
      } catch (IOException e) {
        e.printStackTrace();
      }
      merger.addNewItem(currentId);
    });
  }

  public synchronized void add(K key, int document, V payload) {
    tmpIndex.add(key, document, payload);

    if (tmpIndex.size() > flushSize) {
      try {
        flush();
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  }

  public TmpPostingMerger<K, V> getMerger(List<Integer> ids) throws IOException {
    List<TmpPostingReader<K,V>> inputs = new ArrayList<>();
    for (Integer id : ids) {
      File input = getOutput(id);
      TmpPostingReader<K,V> x = new TmpPostingReader<>(cfg, IO.openInputStream(input));
      inputs.add(x);
    }
    return new TmpPostingMerger<>(cfg, inputs);
  }

  public File getOutput(int id) {
    return tmpDir.child(Integer.toString(id) + ".lzf");
  }

  @Override
  public void flush() throws IOException {
    synchronized (this) {
      if (tmpIndex.isEmpty()) {
        return;
      }

      MemoryPostingIndex<K, V> prev = tmpIndex;
      tmpIndex = new MemoryPostingIndex<>(cfg);
      int currentId = merger.allocate();
      File output = getOutput(currentId);

      // flush to disk asynchronously
      merger.doAsync(() -> {
        try (TmpPostingWriter<K, V> writer = new TmpPostingWriter<>(cfg, output)) {
          prev.write(writer);
        } catch (IOException e) {
          e.printStackTrace();
        }
        merger.addNewItem(currentId);
      });
    }

    merger.checkIfWeCanMergeItems();
  }

  public void close() throws IOException {
    MemoryNotifier.unregister(this);
    flush();
  }

  public final class MergeIntermediate implements GeometricItemMerger.MergeFn {
    @Override
    public void apply(List<Integer> inputs, int output) throws IOException {
      TmpPostingMerger<K, V> merger = getMerger(inputs);
      try (TmpPostingWriter<K,V> writer = new TmpPostingWriter<>(cfg, getOutput(output))) {
        merger.write(writer);
      }
      for (int input : inputs) {
        if(!getOutput(input).delete()) {
          Logger.getAnonymousLogger().warning("Couldn't delete temporary indexing file: "+getOutput(input).getAbsolutePath());
        }
      }
    }
  }

  public void mergeTo(PostingIndexWriter<K, V> finalWriter) throws IOException {
    flush();
    TmpPostingMerger<K, V> postingMerger = this.getMerger(merger.getFinalItems());
    postingMerger.write(finalWriter);
  }
}


text:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 4                                                        |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2002 The PHP Group                                |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license,       |
// | that is bundled with this package in the file LICENSE, and is        |
// | available at through the world-wide-web at                           |
// | http://www.php.net/license/3_0.txt.                                  |
// | If you did not receive a copy of the PHP license and are unable to   |
// | obtain it through the world-wide-web, please send a note to          |
// | license@php.net so we can mail you a copy immediately.               |
// +----------------------------------------------------------------------+
// | Authors: Ian Eure <ieure@php.net>                                    |
// +----------------------------------------------------------------------+
//
// $Id: Parameter.php,v 1.1 2007/03/25 10:10:21 cweiske Exp $

/**
 * Class for working with MIME type parameters
 *
 * @version 1.2.0
 * @package MIME_Type
 * @author Ian Eure <ieure@php.net>
 */
class MIME_Type_Parameter {
    /**
     * Parameter name
     *
     * @var string
     */
    var $name;

    /**
     * Parameter value
     *
     * @var string
     */
    var $value;

    /**
     * Parameter comment
     *
     * @var string
     */
    var $comment;

    /**
     * Constructor.
     *
     * @param  string $param MIME parameter to parse, if set.
     * @return void
     */
    function MIME_Type_Parameter($param = false)
    {
        if ($param) {
            $this->parse($param);
        }
    }

    /**
     * Parse a MIME type parameter and set object fields
     *
     * @param  string $param MIME type parameter to parse
     * @return void
     */
    function parse($param)
    {
        $comment = '';
        $param   = MIME_Type::stripComments($param, $comment);
        $this->name    = $this->getAttribute($param);
        $this->value   = $this->getValue($param);
        $this->comment = $comment;
    }

    /**
     * Get a parameter attribute (e.g. name)
     *
     * @param  string MIME type parameter
     * @return string Attribute name
     * @static
     */
    function getAttribute($param)
    {
        $tmp = explode('=', $param);
        return trim($tmp[0]);
    }

    /**
     * Get a parameter value
     *
     * @param  string $param MIME type parameter
     * @return string Value
     * @static
     */
    function getValue($param)
    {
        $tmp = explode('=', $param, 2);
        $value = $tmp[1];
        $value = trim($value);
        if ($value[0] == '"' && $value[strlen($value)-1] == '"') {
            $value = substr($value, 1, -1);
        }
        $value = str_replace('\\"', '"', $value);
        return $value;
    }

    /**
     * Get a parameter comment
     *
     * @param  string $param MIME type parameter
     * @return string Parameter comment
     * @see getComment()
     * @static
     */
    function getComment($param)
    {
        $cs = strpos($param, '(');
        $comment = substr($param, $cs);
        return trim($comment, '() ');
    }

    /**
     * Does this parameter have a comment?
     *
     * @param  string  $param MIME type parameter
     * @return boolean true if $param has a comment, false otherwise
     * @static
     */
    function hasComment($param)
    {
        if (strstr($param, '(')) {
            return true;
        }
        return false;
    }

    /**
     * Get a string representation of this parameter
     *
     * This function performs the oppsite of parse()
     *
     * @return string String representation of parameter
     */
    function get()
    {
        $val = $this->name . '="' . str_replace('"', '\\"', $this->value) . '"';
        if ($this->comment) {
            $val .= ' (' . $this->comment . ')';
        }
        return $val;
    }
}
?>


text:
//  Copyright 2004 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package org.apache.tapestry.link;

import java.util.List;

import org.apache.tapestry.IActionListener;
import org.apache.tapestry.IBinding;
import org.apache.tapestry.IDirect;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.Tapestry;
import org.apache.tapestry.engine.ILink;

/**
 *  A component for creating a link using the direct service; used for actions that
 *  are not dependant on dynamic page state.
 *
 *  [Component Reference]
 *
 * @author Howard Lewis Ship
 * @version $Id$
 *
 **/

public abstract class DirectLink extends AbstractLinkComponent implements IDirect
{

    public abstract IBinding getStatefulBinding();
    public abstract IActionListener getListener();

    /**
     *  Returns true if the stateful parameter is bound to
     *  a true value.  If stateful is not bound, also returns
     *  the default, true.  May be invoked when not renderring.
     *
     **/

    public boolean isStateful()
    {
        IBinding statefulBinding = getStatefulBinding();

        if (statefulBinding == null)
            return true;

        return statefulBinding.getBoolean();
    }

    public ILink getLink(IRequestCycle cycle)
    {
        return getLink(cycle, Tapestry.DIRECT_SERVICE, constructServiceParameters(getParameters()));
    }

    /**
     *  Converts a service parameters value to an array
     *  of objects.
     *  This is used by the {@link DirectLink}, {@link ServiceLink}
     *  and {@link ExternalLink}
     *  components.
     *
     *  @param parameterValue the input value which may be
     *

     *
null  (returns null)
     *
An array of Object (returns the array)
     *
A {@link List} (returns an array of the values in the List})
     *
A single object (returns the object as a single-element array)
     *

     *
     *  @return An array representation of the input object.
     *
     *  @since 2.2
     **/

    public static Object[] constructServiceParameters(Object parameterValue)
    {
        if (parameterValue == null)
            return null;

        if (parameterValue instanceof Object[])
            return (Object[]) parameterValue;

        if (parameterValue instanceof List)
        {
            List list = (List) parameterValue;

            return list.toArray();
        }

        return new Object[] { parameterValue };
    }

    /**
     *  Invoked by the direct service to trigger the application-specific
     *  action by notifying the {@link IActionListener listener}.
     *
     *  @throws org.apache.tapestry.StaleSessionException if the component is stateful, and
     *  the session is new.
     *
     **/

    public void trigger(IRequestCycle cycle)
    {
        IActionListener listener = getListener();

        if (listener == null)
        	throw Tapestry.createRequiredParameterException(this, "listener");

        listener.actionTriggered(this, cycle);
    }

    /** @since 2.2 **/

    public abstract Object getParameters();
}


text:
import React, { Component } from 'react';
import PackagesContainer from '../../containers/PackagesContainer';
import styles from './App.scss';

/**
 * Main App component
 */
class App extends Component {
  render() {
    return (
      <div className={styles.app}>
        <PackagesContainer />
      </div>
    );
  }
}

export default App;


text:
/* app/components/input-spark/styles.css */

.input {
  background-color: red;
}


text:
<?php

namespace Wingu\OctopusCore\CodeGenerator\Tests\Unit\PHP\OOP;

use Wingu\OctopusCore\CodeGenerator\PHP\OOP\Modifiers;
use Wingu\OctopusCore\CodeGenerator\Tests\Unit\Expected\PHP\OOP\ModifiersVisibilityMock;
use Wingu\OctopusCore\CodeGenerator\Tests\Unit\TestCase;

class ModifiersVisibilityTraitTest extends TestCase
{

    /**
     * Data provider.
     *
     * @return array
     */
    public function getDataVisibility()
    {
        return array(
            [Modifiers::VISIBILITY_PRIVATE],
            [Modifiers::VISIBILITY_PROTECTED],
            [Modifiers::VISIBILITY_PUBLIC],
        );
    }

    /**
     * @dataProvider getDataVisibility
     */
    public function testSetGetVisibility($visibility)
    {
        $mock = new ModifiersVisibilityMock();
        $mock->setVisibility($visibility);
        $this->assertSame($visibility, $mock->getVisibility());
    }

    /**
     * @expectedException \Wingu\OctopusCore\CodeGenerator\Exceptions\InvalidArgumentException
     */
    public function testSetVisibilityFail()
    {
        $mock = new ModifiersVisibilityMock();
        $mock->setVisibility('dummy');
    }
}


text:
package com.doubleleft.hook;

import java.util.Vector;

import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.AsyncHttpResponseHandler;

import android.annotation.SuppressLint;

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

/**
 * Created by glaet on 2/28/14.
 */

@SuppressLint("DefaultLocale")
public class Collection {
	protected Client client;
	protected String name;
	protected String segments;

	protected CollectionOptions _options;
	protected Vector<CollectionWhere> _wheres;
	protected Vector<CollectionOrdering> _ordering;
	protected Vector<String> _group;
	protected Integer _limit;
	protected Integer _offset;

	public Collection(Client client, String name) {
		if (!name.matches("^[a-z_//0-9]+$")) {
			throw new Error("Invalid name" + name);
		}

		this.client = client;
		this.name = name;
		this.segments = "collection/" + this.name;
		this.reset();
	}

	public RequestHandle create(JSONObject data, AsyncHttpResponseHandler responseHandler) {
		return client.post(this.segments, data, responseHandler);
	}

	public RequestHandle get(AsyncHttpResponseHandler responseHandler) {
		return client.get(this.segments, this.buildQuery(), responseHandler);
	}

	public RequestHandle first(AsyncHttpResponseHandler responseHandler) {
		_options.first = true;
		return this.get(responseHandler);
	}

	public RequestHandle firstOrCreate(JSONObject data, AsyncHttpResponseHandler responseHandler) {
		_options.first = true;
        _options.data = data;
        return this.client.post(this.segments, this.buildQuery(), responseHandler);
	}

	public RequestHandle count(AsyncHttpResponseHandler responseHandler) {
		_options.aggregation = new CollectionOptionItem("count", null, null);
		return this.get(responseHandler);
	}

	public RequestHandle max(String field, AsyncHttpResponseHandler responseHandler) {
		_options.aggregation = new CollectionOptionItem("max", field, null);
		return this.get(responseHandler);
	}

	public RequestHandle min(String field, AsyncHttpResponseHandler responseHandler) {
		_options.aggregation = new CollectionOptionItem("min", field, null);
		return this.get(responseHandler);
	}

	public RequestHandle avg(String field, AsyncHttpResponseHandler responseHandler) {
		_options.aggregation = new CollectionOptionItem("avg", field, null);
		return this.get(responseHandler);
	}

	public RequestHandle sum(String field, AsyncHttpResponseHandler responseHandler) {
		_options.aggregation = new CollectionOptionItem("sum", field, null);
		return this.get(responseHandler);
	}

	public RequestHandle update(int id, JSONObject data, AsyncHttpResponseHandler responseHandler) {
		return client.post(this.segments + "/" + id, data, responseHandler);
	}

	public RequestHandle updateAll(JSONObject data, AsyncHttpResponseHandler responseHandler) {
		_options.data = data;
		return client.put(this.segments, this.buildQuery(), responseHandler);
	}

	public RequestHandle increment(String field, Object value, AsyncHttpResponseHandler responseHandler) {
		_options.operation = new CollectionOptionItem("increment", field, value);
		return client.put(this.segments, this.buildQuery(), responseHandler);
	}

	public RequestHandle decrement(String field, Object value, AsyncHttpResponseHandler responseHandler) {
		_options.operation = new CollectionOptionItem("decrement", field, value);
		return client.put(this.segments, this.buildQuery(), responseHandler);
	}

	public RequestHandle remove(int id, AsyncHttpResponseHandler responseHandler) {
		return client.remove(this.segments + "/" + id, responseHandler);
	}

	public RequestHandle drop(AsyncHttpResponseHandler responseHandler) {
		return client.remove(this.segments, responseHandler);
	}

	public Collection where(String field, Object value) {
		return this.where(field, "=", value);
	}

	public Collection where(String field, String operation, Object value) {
		_wheres.add(new CollectionWhere(field, operation, value, "and"));
		return this;
	}

    public Collection orWhere(String field, String operation, Object value) {
        _wheres.add(new CollectionWhere(field, operation, value, "or"));
        return this;
    }

	public Collection group(String field) {
		_group.add(field);
		return this;
	}

	public Collection group(String[] fields) {
		for (int i = 0; i < fields.length; i++) {
			_group.add(fields[i]);
		}
		return this;
	}

	public Collection sort(String field, Integer direction) {
		return this.sort(field, direction == -1 ? "desc" : "asc");
	}

	public Collection sort(String field, String direction) {
		_ordering.add(new CollectionOrdering(field, direction));
		return this;
	}

	public Collection limit(Integer num) {
		_limit = num;
		return this;
	}

	public Collection offset(Integer num) {
		_offset = num;
		return this;
	}

	protected JSONObject buildQuery() {
        JSONObject query = new JSONObject();

        try {
            if (_limit != null) {
                query.put("limit", _limit);
            }

            if (_offset != null) {
                query.put("offset", _offset);
            }

            if (_wheres != null && _wheres.size() > 0) {
                JSONArray whereArray = new JSONArray();
                for (int i = 0; i < _wheres.size(); i++) {
                    whereArray.put(_wheres.get(i).toJSON());
                }
                query.put("q", whereArray);
            }

            if (_ordering != null && _ordering.size() > 0) {
                JSONArray orderingArray = new JSONArray();
                for (int i = 0; i < _ordering.size(); i++) {
                    orderingArray.put(_ordering.get(i).toJSON());
                }
                query.put("s", orderingArray);
            }

            if (_group != null && _group.size() > 0) {
                JSONArray groupArray = new JSONArray();
                for (int i = 0; i < _group.size(); i++) {
                    groupArray.put(_group.get(i));
                }
                query.put("g", groupArray);
            }

            if (_options != null) {
                if (_options.data != null) {
                    query.put("data", _options.data);
                }

                if (_options.first) {
                    query.put("f", 1);
                }

                if (_options.aggregation != null) {
                    query.put("aggr", _options.aggregation.toJSON());
                }

                if (_options.operation != null) {
                    query.put("op", _options.operation.toJSON());
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

		this.reset(); // clear for future calls
		return query;
	}

	protected void reset() {
		this._options = new CollectionOptions();
		this._wheres = new Vector<CollectionWhere>();
		this._ordering = new Vector<CollectionOrdering>();
		this._group = new Vector<String>();
		this._limit = null;
		this._offset = null;
	}

	class CollectionOptions {
		public boolean first;
		public JSONObject data;
		public CollectionOptionItem aggregation;
		public CollectionOptionItem operation;

		public CollectionOptions() {
			first = false;
			data = null;
			aggregation = null;
			operation = null;
		}
	}

	class CollectionOptionItem {
		public String method;
		public String field;
		public Object value;

		public CollectionOptionItem(String method, String field, Object value) {
			this.method = method;
			this.field = field;
			this.value = value;
		}

		public JSONObject toJSON() {
            JSONObject json = new JSONObject();

            try {
                json.put("method", method);
                json.put("field", field);
                json.put("value", value);
            } catch (JSONException e) {
                e.printStackTrace();
            }

			return json;
		}

	}

	class CollectionWhere {
		public String field;
		public String operation;
		public Object value;
        public String bool;

        public CollectionWhere(String field, String operation, Object value, String bool) {
            this.field = field;
            this.operation = operation.toLowerCase();
            this.value = value;
            this.bool = bool;
        }

		public JSONArray toJSON() {
			JSONArray json = new JSONArray();
			json.put(field);
			json.put(operation);
			json.put(value);
            json.put(bool);
			return json;
		}

	}

	class CollectionOrdering {
		public String field;
		public String direction;

		public CollectionOrdering(String field, String direction) {
			this.field = field;
			this.direction = direction;
		}

		public JSONArray toJSON() {
            JSONArray json = new JSONArray();
            json.put(field);
            json.put(direction);
			return json;
		}

	}
}


text:
    #pragma hdrstop
#endif

#if wxUSE_XRC && wxUSE_FONTPICKERCTRL

#include "wx/xrc/xh_fontpicker.h"
#include "wx/fontpicker.h"

IMPLEMENT_DYNAMIC_CLASS(wxFontPickerCtrlXmlHandler, wxXmlResourceHandler)

wxFontPickerCtrlXmlHandler::wxFontPickerCtrlXmlHandler() : wxXmlResourceHandler()
{
    XRC_ADD_STYLE(wxFNTP_USE_TEXTCTRL);
    XRC_ADD_STYLE(wxFNTP_FONTDESC_AS_LABEL);
    XRC_ADD_STYLE(wxFNTP_USEFONT_FOR_LABEL);
    XRC_ADD_STYLE(wxFNTP_DEFAULT_STYLE);
    AddWindowStyles();
}

wxObject *wxFontPickerCtrlXmlHandler::DoCreateResource()
{
   XRC_MAKE_INSTANCE(picker, wxFontPickerCtrl)

    wxFont f = *wxNORMAL_FONT;
    if (HasParam(wxT("value")))
        f = GetFont(wxT("value"));

   picker->Create(m_parentAsWindow,
                  GetID(),
                  f,
                  GetPosition(), GetSize(),
                  GetStyle(wxT("style"), wxFNTP_DEFAULT_STYLE),
                  wxDefaultValidator,
                  GetName());

    SetupWindow(picker);

    return picker;
}

bool wxFontPickerCtrlXmlHandler::CanHandle(wxXmlNode *node)
{
    return IsOfClass(node, wxT("wxFontPickerCtrl"));
}

#endif // wxUSE_XRC && wxUSE_FONTPICKERCTRL


text:
package jenkins.model;

import hudson.model.FreeStyleProject;
import hudson.model.ParametersDefinitionProperty;
import hudson.model.Queue;
import hudson.model.StringParameterDefinition;
import javax.servlet.http.HttpServletResponse;

import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;

/**
 * Tests of {@link ParameterizedJobMixIn}.
 * @author Oleg Nenashev
 */
public class ParameterizedJobMixInTest {

    @Rule
    public JenkinsRule j = new JenkinsRule();

    @Test
    public void doBuild_shouldFailWhenInvokingDisabledProject() throws Exception {
        final FreeStyleProject project = j.createFreeStyleProject();
        project.doDisable();

        final JenkinsRule.WebClient webClient = j.createWebClient();
        webClient.assertFails(project.getUrl() + "build", HttpServletResponse.SC_CONFLICT);
    }

    @Test
    @Issue("JENKINS-36193")
    public void doBuildWithParameters_shouldFailWhenInvokingDisabledProject() throws Exception {
        final FreeStyleProject project = j.createFreeStyleProject();
        project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("FOO", "BAR")));
        project.doDisable();

        final JenkinsRule.WebClient webClient = j.createWebClient();
        webClient.assertFails(project.getUrl() + "buildWithParameters", HttpServletResponse.SC_CONFLICT);
    }

    @Test
    @Issue("JENKINS-48770")
    public void doBuildQuietPeriodInSeconds() throws Exception {
        final int projectQuietPeriodInSeconds = 50;

        final FreeStyleProject project = j.createFreeStyleProject();
        project.setQuietPeriod(projectQuietPeriodInSeconds);

        final JenkinsRule.WebClient webClient = j.createWebClient();
        webClient.goTo(project.getUrl() + "build", "");
        long triggerTime = System.currentTimeMillis();

        Queue.Item item = Jenkins.get().getQueue().getItem(1);
        Assert.assertTrue(item instanceof Queue.WaitingItem);
        Assert.assertTrue(item.task instanceof FreeStyleProject);

        Queue.WaitingItem waitingItem = (Queue.WaitingItem) item;
        Assert.assertTrue((waitingItem.timestamp.getTimeInMillis() - triggerTime) > 45000);

        Jenkins.get().getQueue().doCancelItem(1);
    }
}


text:
using System;
using System.Collections.Generic;

namespace Util.Impresion.Web.ReverseEngenieer
{
    public partial class GuiasDet
    {
        public long GuiaDetId { get; set; }
        public long GuiaId { get; set; }
        public int? ImagenId { get; set; }
        public int? ClienteId { get; set; }

        public virtual ProveeClientes Cliente { get; set; }
        public virtual Guias Guia { get; set; }
        public virtual Imagenes Imagen { get; set; }
    }
}


text:
/**
* ABElectronics Servo Pi demo
* Version 1.0 Created 29/07/2016
*
* Requires rpio to be installed, install with: npm install rpio
* run with: sudo node pwm.js
*
* This demo shows how to set a 1KHz output frequency and change the pulse width between the minimum and maximum values
*/

// link to the servopi library
var servopi = require('../../lib/servopi/servopi');

// create an pwm object
var pwm = new PWM(0x40);

// Set PWM frequency to 1 Khz and enable the output
pwm.setPWMFrequency(1000);
pwm.outputEnable();

var x = 0;

// Update the pulse width on channel 1, incrementing it up to 4059 and back down to 0
while (1) {
    for (x = 0; x < 4095; x++){
        pwm.setPWM(1, 0, x);
    }
    for (x = 4095; x > 0; x--) {
        pwm.setPWM(1, 0, x);
    }
}


text:
'use strict';

/* jasmine specs for services go here */

// write tests for updates to putSeriesData

describe('service', function() {

	beforeEach(module('myApp.services'));

  	describe('metadataService', function(){

		describe('at start', function(){
			var metadataService;

			beforeEach(inject(function(_metadataService_) {
				metadataService = _metadataService_;
			}));

			it('.houseId should be false', function(){
				expect( metadataService.data.houseId ).toBe(false);
			});
			it('.chartDate should be false', function(){
				expect( metadataService.data.chartDate ).toBe(false);
			});
			it('.asofDate should be false', function(){
				expect( metadataService.data.asofDate ).toBe(false);
			});

			it('.view should be undefined', function(){
				expect( metadataService.current.view ).toBe( undefined );
			});
			it('.year should be undefined', function(){
				expect( metadataService.current.year ).toBe( undefined );
			});

		});

		describe('validate() for summary', function(){
			var metadataService;

			beforeEach ( inject ( function ( _metadataService_) {
				metadataService = _metadataService_;
				var params = { house: '0', date: '2013-12-30', view: 'summary', path: 'months' };
				metadataService.validate( params );
			}));

			it('data.houseId should be 0', function() {
				expect( metadataService.data.houseId ).toEqual('0');
			});
			it('data.chartDate should be 2013-12-30', function() {
				expect( metadataService.data.chartDate ).toEqual('2013-12-30');
			});
			it('current.view should be summary', function() {
				expect( metadataService.current.view ).toEqual('summary');
			});
			it('current.year should be 2013', function() {
				expect( metadataService.current.year ).toEqual('2013');
			});
			it('data.asofDate should still be false', function() {
				expect( metadataService.data.asofDate ).toBe( false );
			});

		});

		describe('validate() missing house and date', function(){
			var metadataService;

			beforeEach(inject(function(_metadataService_) {
				metadataService = _metadataService_;
				var params = { view: 'summary', path: 'monthly' };
				metadataService.validate( params );
			}));

			it('data.houseId should be 0', function() {
				expect( metadataService.data.houseId ).toEqual('0');
			});
			// need a mockdate object in Jasmine to do this. Or try the Angular mockdate object...
			xit('data.chartDate should be 2013-12-31', function() {
				expect( metadataService.data.chartDate ).toEqual('2013-12-31');
			});
			// need a mockdate object in Jasmine to do this. Or try the Angular mockdate object...
			xit('current.year should be 2013', function() {
				expect( metadataService.current.year ).toEqual('2013');
			});
			it('current.view should be summary', function() {
				expect( metadataService.current.view ).toEqual('summary');
			});
			it('data.asofDate should still be false', function() {
				expect( metadataService.data.asofDate ).toBe( false );
			});

		});

		describe('setParamYear()', function(){
			var metadataService;

			beforeEach(inject(function(_metadataService_) {
				metadataService = _metadataService_;
				var params = { house: '0', date: '2013-12-30', view: 'summary', path: 'monthly' };
				metadataService.validate( params );
				metadataService.setParamYear('2012');
			}));

			it('current.year should be 2013', function() {
				expect( metadataService.current.year ).toEqual('2012');
			});
			it('data.chartDate should be 2012-12-30', function() {
				expect( metadataService.data.chartDate ).toEqual('2012-12-30');
			});
			it('current.view should remain summary', function() {
				expect( metadataService.current.view ).toEqual('summary');
			});
			it('data.asofDate should still be false', function() {
				expect( metadataService.data.asofDate ).toBe( false );
			});

		});

		describe('before setMetadata()', function(){
			var metadataService;

			beforeEach(inject(function(_metadataService_) {
				metadataService = _metadataService_;
				//metadataService.setMetadata({"years":["2012","2013"],"asof":"2013-12-31","house":"Up Hill House"});
			}));

			it('data.chartDate should be false', function() {
				expect( metadataService.data.chartDate ).toBe( false );
			});

		});

		describe('setMetadata()', function(){
			var metadataService;

			beforeEach(inject(function(_metadataService_) {
				metadataService = _metadataService_;
				metadataService.setMetadata({"years":["2012","2013"],"asof":"2013-12-31","house": { "name": "Up Hill House"}});
			}));

			it('data.asofDate should be 2013-12-31', function() {
				expect( metadataService.data.asofDate ).toEqual('2013-12-31');
			});
			it('data.years.length should be 3 including all', function() {
				expect( metadataService.data.years.length ).toBe(3);
			});
			it('data.houseName should be Up Hill House', function() {
				expect( metadataService.data.houseName ).toEqual('Up Hill House');
			});
			it('data.chartDate should = data.asofDate if chartDate is not set yet', function() {
				expect( metadataService.data.chartDate ).toEqual('2013-12-31');
			});

		});

		describe('getDaysYTD()', function(){
			var metadataService;

			beforeEach(inject(function(_metadataService_) {
				metadataService = _metadataService_;
				metadataService.setMetadata({"years":["2012","2013"],"asof":"2013-12-31","house":"Up Hill House"});
				var params = { house: '0', date: '2013-12-30' };
				metadataService.validate( 'summary', params );
			}));

			it('chart year 2014 > asof year 2013, should return false', function() {
				metadataService.setParamYear('2014');
				metadataService.data.asofDate = '2013-02-28';
				expect( metadataService.getDaysYTD() ).toBe( false ); // don't have data past asof year
			});
			it('chart year 2013 = asof year 2013. 02-28 should return 59', function() {
				metadataService.data.asofDate = '2013-02-28';
				expect( metadataService.getDaysYTD() ).toEqual(59); // 31 + 28
			});
			it('chart year 2013, asof 2013-12-30 should return 365', function() {
				expect( metadataService.getDaysYTD() ).toEqual(365);
			});
			it('chart year 2012, asof 2013-12-30 should return 366', function() {
				metadataService.setParamYear('2012');
				expect( metadataService.getDaysYTD() ).toEqual(366);
			});

			it('chart year 2011 < asof 2013-12-30, should be false', function() {
				metadataService.setParamYear('2011');
				expect( metadataService.getDaysYTD() ).toBe( false );
			});

		});

	});

});


text:
class CreateStops < ActiveRecord::Migration
  def change
    create_table :stops do |t|
      t.float :lat
      t.float :long
      t.string :route
    end
  end
end


text:
NSString * const kOnlyNum          = @"0123456789";
NSString * const kOnlyLetter       = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
NSString * const kOnlyLetterAndNum = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";


text:
"""
script to list hosts
"""
import sys
import logging
from UniDomain import Classes
from optparse import OptionParser

if __name__ == "__main__":
    parser = OptionParser(usage="usage: %prog [options] [domain]", description="""
list hosts.
Specify a domain implies --author
if neither --authen nor --author are specified we list from authentication and database """)
    parser.add_option("-j", action="store_true", dest="janitor", help="use janitor account", default=False)
    parser.add_option("--authen", action="store_true", dest="authen", help="list from authen backend (kerberos)", default=False)
    parser.add_option("--author", action="store_true", dest="author", help="list from database backend (ldap)", default=False)
    parser.add_option("-v", action="store_true", dest="debug", help="be verbose", default=False)
    (options, args) = parser.parse_args()
    if len(args) > 1:
        parser.print_help()
        sys.exit(2)
    if options.debug:
        logging.basicConfig(level=logging.DEBUG)

    if options.janitor:
        config = Classes.Config(krb5keytab="/root/janitor/janitor.keytab",plugin_author='ldapdbadmin')
    else:
        config = Classes.Config(plugin_authen="krb5_login", plugin_author='ldapdbadmin')
    if not (options.author or options.authen):
        options.authen = True
        options.author = True
    authen = Classes.Authen(config)
    if not authen:
        sys.exit(3)
    userid = authen.authenticate()
    if not userid:
        sys.exit(4)
    authen.kadmin()
    author = Classes.Author(config)
    if not author:
        sys.exit(3)
    db = author.authorize(userid.split('@')[0])
    if not db:
        sys.exit(4)

    if options.authen:
        sys.stdout.write("\nHosts in the authen backend. : \n")
        print('\n'.join(['\t%s' % host for host in authen.list_hosts()]) + '\n')
    if options.author:
        if len(args) == 0:
            domainID = db.domainID
        else:
            domainID = db.get_itemID(args[0])
            if not domainID:
                sys.exit(5)
        sys.stdout.write("\nHosts in the db backend : \n")
        print('\n'.join(['\t%s\t%s; %s; %s; %s' % vals for vals in db.list_hosts(domain=domainID)]) + '\n')


text:
/**
 */
package org.jivesoftware.spark.ui.history;

import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @author Vyacheslav Durin (nixspirit@gmail.com)
 *
 *         Apr 10, 2013
 * @version 0.1
 */
public abstract class AbstractHistoryFile {

	protected static final int SIZE_MULTIPLICATOR = 1024; // 1024-KB, 2048-MB
	protected static final MessageFormat SIZE_FORMAT = new MessageFormat(
			"{0,number,#.##} Kb");
	protected static final DateFormat DAY_NAME_FORMAT = DateFormat
			.getDateInstance(DateFormat.MEDIUM);
	protected static final SimpleDateFormat MONTH_NAME_FORMAT = new SimpleDateFormat(
			"MMMM yyyy");
	private static final MessageFormat replacementFormat = new MessageFormat(
			"{0}");

	protected List<HistoryEntry> entries;

	protected abstract long getSize();

	protected abstract List<HistoryEntry> createEntries();

	public String getFormatSize() {
		return SIZE_FORMAT.format(new Object[] { getSize() });
	}

	public Collection<HistoryEntry> getHistoryEntries() {
		if (entries == null)
			entries = createEntries();
		return entries;
	}

	public List<HistoryEntry> search(String occurrence) {
		return search(entries, occurrence);
	}

	// ############# UTILS ##############

	private List<HistoryEntry> search(List<HistoryEntry> entries,
			String occurrence) {

		List<HistoryEntry> result = new ArrayList<>();
		for (HistoryEntry historyEntry : entries) {

			if (!historyEntry.hasRecords()) {

				if (hasOccurrence(historyEntry, occurrence)) {
					HistoryEntry copy = new HistoryEntry(historyEntry);
					highlihght(copy, occurrence);
					result.add(copy);
				}

			} else {
				result.addAll(search(historyEntry.getEntries(), occurrence));
			}
		}
		return result;
	}

	private boolean hasOccurrence(HistoryEntry historyEntry, String occurrence) {
		if (historyEntry.isEmpty())
			return false;

		for (HistoryMessage msg : historyEntry.getMessages()) {
			String body = msg.getBody();
			if (body.contains(occurrence)) {
				return true;
			}
		}
		return false;
	}

	private void highlihght(HistoryEntry historyEntry, String occurrence) {
		// TODO: now replaced always with the occurrence in lowercase.
		String replacement = replacementFormat
				.format(new String[] { occurrence });
		String insentiveCase = "(?i)";

		for (HistoryMessage msg : historyEntry.getMessages()) {
			String body = msg.getBody();
			msg.setBody(body
					.replaceAll(insentiveCase + occurrence, replacement));
		}
	}

	protected List<HistoryEntry> toList(Map<Date, HistoryEntry> months) {
		List<HistoryEntry> entries = new ArrayList<>();
		for (Entry<Date, HistoryEntry> historyEntry : months.entrySet()) {
			entries.add(historyEntry.getValue());
		}

		Collections.sort(entries, ( o1, o2 ) -> o2.getDate().compareTo(o1.getDate()) );

		return entries;
	}
}


text:
import random
import sys

import numpy as np
import tensorflow as tf

def test_seed_set_before_each_test():
    """Test that the tests are deterministic, locally and in the CI."""
    assert random.random() == 0.8444218515250481
    assert np.random.uniform() == 0.5488135039273248

    random_tf_value = tf.random.uniform([1], dtype=tf.dtypes.float64)[0].numpy()
    if sys.version_info >= (3, 0):
        assert random_tf_value == 0.3358018290373803
    else:
        assert random_tf_value == 0.3759982263246542


text:
var fs = require("fs"),
  path = require("path"),
  Sequelize = require("sequelize");

module.exports = function(config, options) {
  options = options || {}
  if(typeof config === 'string' || config instanceof String) {
    var sequelize = new Sequelize(config, options);
  } else if(!config && options) {
    var sequelize = new Sequelize(options);
  } else if(config.database) {
    var sequelize = new Sequelize(config.database, config.username, config.password, options);
  } else {
    console.log(typeof config);
    console.log(config instanceof String);
    var err = Error('invalid database config');
    throw err;
  }

  var db = {};

  fs.readdirSync(__dirname)
    .filter(function(file) {
      return (file.indexOf(".") > 0) && (file !== "index.js");
    })
    .forEach(function(file) {
      var model = sequelize.import(path.join(__dirname, file));
      db[model.name] = model;
    });

  Object.keys(db).forEach(function(modelName) {
    if ("associate" in db[modelName]) {
      db[modelName].associate(db);
    }
  });

  db.sequelize = sequelize;
  db.Sequelize = Sequelize;

  return db;
}


text:
Potion provides several modules for construction visualizations: `@potion/element@next`, `@potion/layout@next`, `@potion/extra@next` and `@potion/util@next`.

This enables you to install only the modules you need. However, if you would like to install all modules you can do so by running:

```bash
npm install @potion/main@next
```

# Hello World

A basic example to get you up and running.

```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import { Svg, Circle } from '@potion/element';

ReactDOM.render(
  <Svg width={400} height={400}>
    <Circle cx={200} cy={200} r={40} fill='black' />
  </Svg>
, 'body');
```