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

namespace Opserver.Data.SQL
{
    public partial class SQLNode
    {
        /// <summary>
        /// http://msdn.microsoft.com/en-us/library/ff877972.aspx
        /// </summary>
        public class AGDatabaseReplica : ISQLVersioned, IMonitorStatus
        {
            Version IMinVersioned.MinVersion => SQLServerVersions.SQL2012.RTM;
            SQLServerEditions ISQLVersioned.SupportedEditions => SQLServerEditions.All;

            public int DatabaseId { get; internal set; }
            public Guid GroupId { get; internal set; }
            public Guid ReplicaId { get; internal set; }
            public Guid GroupDatabaseId { get; internal set; }
            public bool? IsLocal { get; internal set; }
            public SynchronizationStates? SynchronizationState { get; internal set; }
            public bool? IsCommitParticipant { get; internal set; }
            public SynchronizationHealths? SynchronizationHealth { get; internal set; }
            public DatabaseStates? DatabaseState { get; internal set; }
            public bool? IsSuspended { get; internal set; }
            public SuspendReasons? SuspendReason { get; internal set; }
            public decimal? RecoveryLSN { get; internal set; }
            public decimal? TruncationLSN { get; internal set; }
            public decimal? LastSentLSN { get; internal set; }
            public DateTime? LastSentTime { get; internal set; }
            public decimal? LastReceivedLSN { get; internal set; }
            public DateTime? LastReceivedTime { get; internal set; }
            public decimal? LastHardenedLSN { get; internal set; }
            public decimal? LastRedoneLSN { get; internal set; }
            public DateTime? LastRedoneTime { get; internal set; }
            public decimal? LastCommitLSN { get; internal set; }
            public DateTime? LastCommitTime { get; internal set; }
            public decimal? EndOfLogLSN { get; internal set; }
            public long? LogSendQueueSize { get; internal set; }
            public long? LogSendRate { get; internal set; }
            public long? RedoQueueSize { get; internal set; }
            public long? RedoRate { get; internal set; }
            public long? FileStreamSendRate { get; internal set; }
            public long? LowWatermarkForGhosts { get; internal set; }
            public string DatabaseName { get; internal set; }
            public long? LogKBytesUsed { get; internal set; }
            public long? LogKBytesTotal { get; internal set; }

            public DateTime? LogSendETA
            {
                get
                {
                    if (LogSendRate.GetValueOrDefault() <= 0 || LogSendQueueSize.GetValueOrDefault() <= 0) return null;
                    var secs = (double)(LogSendQueueSize / LogSendRate);
                    return DateTime.UtcNow.AddSeconds(secs);
                }
            }

            /// <summary>
            /// Returns the *real* log send rate, if there's nothing to send SQL still reports the last high rate,
            /// when it's actually sending noting.  This will return null as it should in that case.
            /// </summary>
            public long? LogSendRateReal => LogSendQueueSize > 0 ? LogSendRate : null;

            public double? LogPercentUsed
            {
                get
                {
                    if (LogKBytesUsed.GetValueOrDefault() <= 0 || LogKBytesTotal.GetValueOrDefault() <= 0) return null;
                    return (double)(LogKBytesUsed / LogKBytesTotal);
                }
            }

            public MonitorStatus MonitorStatus
            {
                get
                {
                    switch (SynchronizationHealth)
                    {
                        case SynchronizationHealths.NotHealthy:
                        case SynchronizationHealths.PartiallyHealthy:
                            if (IsSuspended.GetValueOrDefault() && SuspendReason == SuspendReasons.UserAction) return MonitorStatus.Warning;
                            return MonitorStatus.Critical;
                    }
                    return MonitorStatus.Good;
                }
            }

            public string MonitorStatusReason
            {
                get
                {
                    switch (SynchronizationHealth)
                    {
                        case SynchronizationHealths.NotHealthy:
                            return DatabaseName + " - not syncing";
                        case SynchronizationHealths.PartiallyHealthy:
                            if (IsSuspended.GetValueOrDefault() && SuspendReason == SuspendReasons.UserAction) return DatabaseName + " - user suspended replication";
                            return DatabaseName + " - partially syncing";
                    }
                    return null;
                }
            }

            public string DatabaseStateDescription => DatabaseState.HasValue
                ? DatabaseState.Value.AsString(EnumFormat.Description) + (IsSuspended.GetValueOrDefault() ? " (Suspended)" : "")
                : string.Empty;

            public string SuspendReasonDescription => SuspendReason.HasValue ? "Suspended by " + SuspendReason.Value.AsString(EnumFormat.Description) : string.Empty;

            public string GetFetchSQL(in SQLServerEngine e) => @"
Select dbrs.database_id DatabaseId,
       dbrs.group_id GroupId,
       dbrs.replica_id ReplicaId,
       dbrs.group_database_id GroupDatabaseId,
       dbrs.is_local IsLocal,
       dbrs.synchronization_state SynchronizationState,
       dbrs.is_commit_participant IsCommitParticipant,
       dbrs.synchronization_health SynchronizationHealth,
       dbrs.database_state DatabaseState,
       dbrs.is_suspended IsSuspended,
       dbrs.suspend_reason SuspendReason,
       dbrs.recovery_lsn RecoveryLSN,
       dbrs.truncation_lsn TruncationLSN,
       dbrs.last_sent_lsn LastSentLSN,
       dbrs.last_sent_time LastSentTime,
       dbrs.last_received_lsn LastReceivedLSN,
       dbrs.last_received_time LastReceivedTime,
       dbrs.last_hardened_lsn LastHardenedLSN,
       dbrs.last_redone_lsn LastRedoneLSN,
       dbrs.last_redone_time LastRedoneTime,
       dbrs.last_commit_lsn LastCommitLSN,
       dbrs.last_commit_time LastCommitTime,
       dbrs.end_of_log_lsn EndOfLogLSN,
       dbrs.log_send_queue_size LogSendQueueSize,
       dbrs.log_send_rate LogSendRate,
       dbrs.redo_queue_size RedoQueueSize,
       dbrs.redo_rate RedoRate,
       dbrs.filestream_send_rate FileStreamSendRate,
       dbrs.low_water_mark_for_ghosts LowWatermarkForGhosts,
       DB_NAME(database_id) DatabaseName,
       lfu.cntr_value LogKBytesUsed,
	   lft.cntr_value LogKBytesTotal
  From sys.dm_hadr_database_replica_states dbrs
	   Left Join sys.dm_os_performance_counters lfu
	     On DB_NAME(database_id) = lfu.instance_name
	     And lfu.counter_name = 'Log File(s) Used Size (KB)'
	     And dbrs.is_local = 1
       Left Join sys.dm_os_performance_counters lft
	     On lfu.instance_name = lft.instance_name
	     And lft.counter_name = 'Log File(s) Size (KB)'";
        }
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Oidium fusisporioides f. lapsanae Desm.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
<?php
session_start();
function check_user_validation(){
	if (isset($_SESSION['login']) && $_SESSION['login'] == true){
		return "sd";
	}
	else{
		header("location: index.php");
	}
}
function is_user_admin(){
	if ($_SESSION['admin'] ==1){
		return true;
	}
	else{
		return false;
	}
}

?>


text:
To view a full working demo, go here <http://pargo.gomedia.co.za/>

## Version

This module has only been tested for Magento CE 1.9x
It will probably work on older versions of Magento too.

## Installation

To install this module place the contents of the app directory into your project's app directory.

Test this first!

## Support

This module is provided for free (as is) and is licensed under the Apache 2 software license.
If you require support or help setting up the module please contact Stock2Shop.
<http://www.stock2shop.com/contact-us/>

Support is charged by the hour.


text:
import $ from 'jquery';
import 'vendor/jquery.endless-scroll';
import MockAdapter from 'axios-mock-adapter';
import axios from '~/lib/utils/axios_utils';
import CommitsList from '~/commits';
import Pager from '~/pager';

describe('Commits List', () => {
  let commitsList;

  beforeEach(() => {
    setFixtures(`
      <form class="commits-search-form" action="/h5bp/html5-boilerplate/commits/master">
        <input id="commits-search">
      </form>

      `);
    jest.spyOn(Pager, 'init').mockImplementation(() => {});
    commitsList = new CommitsList(25);
  });

  it('should be defined', () => {
    expect(CommitsList).toBeDefined();
  });

  describe('processCommits', () => {
    it('should join commit headers', () => {
      commitsList.$contentList = $(`

            20 Sep, 2016
            1 commit

      `);

      const data = `

          20 Sep, 2016
          1 commit

      `;

      // The last commit header should be removed
      // since the previous one has the same data-day value.
      expect(commitsList.processCommits(data).find('li.commit-header').length).toBe(0);
    });
  });

  describe('on entering input', () => {
    let ajaxSpy;
    let mock;

    beforeEach(() => {
      commitsList.searchField.val('');

      jest.spyOn(window.history, 'replaceState').mockImplementation(() => {});
      mock = new MockAdapter(axios);

      mock.onGet('/h5bp/html5-boilerplate/commits/master').reply(200, {
        html: '
Result
',
      });

      ajaxSpy = jest.spyOn(axios, 'get');
    });

    afterEach(() => {
      mock.restore();
    });

    it('should save the last search string', done => {
      commitsList.searchField.val('GitLab');
      commitsList
        .filterResults()
        .then(() => {
          expect(ajaxSpy).toHaveBeenCalled();
          expect(commitsList.lastSearch).toEqual('GitLab');

          done();
        })
        .catch(done.fail);
    });

    it('should not make ajax call if the input does not change', done => {
      commitsList
        .filterResults()
        .then(() => {
          expect(ajaxSpy).not.toHaveBeenCalled();
          expect(commitsList.lastSearch).toEqual('');

          done();
        })
        .catch(done.fail);
    });
  });
});


text:
simple-open-helper
==================

An easy to use Android open helper


text: package 'python'


text:
package com.spedge.jenkins.jru.params;

import hudson.model.ParameterValue;
import hudson.model.StringParameterValue;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.kohsuke.stapler.StaplerRequest;

/**
 * We use this class to parse the StaplerRequest
 * and retrieve the parameters we want from it.
 *
 * @author Stuart Davidson
 *
 */
public class ExecuteParams
{
    private static final String DELAY_NAME = "delay";
    private static final String ATTEMPTS_NAME = "attempts";
    private static final String FORMAT_NAME = "format";
    private static final String UUID_NAME = "uuid";

    private static final int DELAY_DEFAULT = 1000;
    private static final int ATTEMPTS_DEFAULT = 3;
    private static final String FORMAT_DEFAULT = "json";

    private int attempts = 0;
    private int delay = 0;
    private String format;
    private UUID uuid = null;

    public ExecuteParams(StaplerRequest req)
    {
        this.delay = NumberUtils.toInt(req.getParameter(DELAY_NAME), DELAY_DEFAULT);
        this.attempts = NumberUtils.toInt(req.getParameter(ATTEMPTS_NAME), ATTEMPTS_DEFAULT);
        this.format = StringUtils.defaultIfEmpty(req.getParameter(FORMAT_NAME), FORMAT_DEFAULT);

        try
        {
            this.uuid = UUID.fromString(req.getParameter(UUID_NAME));
        }
        catch(NullPointerException npe) { uuid = null; }
        catch(IllegalArgumentException iae) { }
    }

    public int getAttempts()
    {
        return attempts;
    }

    public int getDelay()
    {
        return delay;
    }

    public String getFormat()
    {
        return format;
    }

    public UUID getUUID()
    {
        return uuid;
    }

    public List<ParameterValue> getParameters()
    {
        List<ParameterValue> values = new ArrayList<ParameterValue>();
        values.add(new StringParameterValue(DELAY_NAME, "" + delay));
        values.add(new StringParameterValue(ATTEMPTS_NAME, "" + attempts));
        values.add(new StringParameterValue(FORMAT_NAME, "" + format));
        values.add(new StringParameterValue(UUID_NAME, "" + uuid));
        return values;
    }

    @Override
    public String toString()
    {
        return "Delay : " + delay + ", Attempts : " + attempts + ", Format : " + format + ", UUID : " + uuid.toString();
    }
}


text:
{% extends "base/layout.html" %}
{% load general_extras %}
{% block head_title %}Woops!{% endblock head_title %}

{% block content %}

Oops, something went wrong! We are on it.

{% endblock content %}


text:
var buildings = require("../../public/buildings/buildings");

function EmscriptenBuildingsApi(emscriptenApiPointer, cwrap, emscriptenModule, emscriptenMemory) {

    var _emscriptenApiPointer = emscriptenApiPointer;
    var _emscriptenMemory = emscriptenMemory;
    var _buildingsApi_SetBuildingHighlightChangedCallback = cwrap("buildingsApi_SetBuildingHighlightChangedCallback", null, ["number", "number"]);
    var _buildingsApi_CreateHighlightAtLocation = cwrap("buildingsApi_CreateHighlightAtLocation", null, ["number", "number", "number", "number", "number", "number", "number", "number"]);
    var _buildingsApi_CreateHighlightAtScreenPoint = cwrap("buildingsApi_CreateHighlightAtScreenPoint", null, ["number", "number", "number", "number", "number", "number", "number", "number"]);
    var _buildingsApi_DestroyHighlight = cwrap("buildingsApi_DestroyHighlight", null, ["number", "number"]);
    var _buildingsApi_SetHighlightColor = cwrap("buildingsApi_SetHighlightColor", null, ["number", "number", "number", "number", "number", "number"]);
    var _buildingsApi_TryGetBuildingInformationBufferSizes = cwrap("buildingsApi_TryGetBuildingInformationBufferSizes", "number", ["number", "number", "number", "number"]);
    var _buildingsApi_TryGetBuildingInformation = cwrap("buildingsApi_TryGetBuildingInformation", "number", ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
    var _buildingsApi_TryFindIntersectionWithBuilding = cwrap("buildingsApi_TryFindIntersectionWithBuilding", "number", ["number", "number", "number"]);

    this.registerBuildingInformationReceivedCallback = function(callback) {
        _buildingsApi_SetBuildingHighlightChangedCallback(_emscriptenApiPointer, emscriptenModule.addFunction(callback));
    };

    this.createBuildingHighlight = function(buildingHighlight) {
        var buildingHighlightId = 0;
        var options = buildingHighlight.getOptions();
        var color = buildingHighlight.getColor();

        var shouldCreateView = options.getIsInformationOnly() ? 0 : 1;

        if (options.getSelectionMode() === buildings.BuildingHighlightSelectionType.SELECT_AT_LOCATION) {
            var latLng = options.getSelectionLocation();
            buildingHighlightId = _buildingsApi_CreateHighlightAtLocation(
                _emscriptenApiPointer,
                latLng.lat,
                latLng.lng,
                color.x/255,
                color.y/255,
                color.z/255,
                color.w/255,
                shouldCreateView
            );
        }
        else {
            var point = options.getSelectionScreenPoint();
            buildingHighlightId = _buildingsApi_CreateHighlightAtScreenPoint(
                _emscriptenApiPointer,
                point.x,
                point.y,
                color.x/255,
                color.y/255,
                color.z/255,
                color.w/255,
                shouldCreateView
            );
        }

        return buildingHighlightId;
    };

    this.destroyBuildingHighlight = function(buildingHighlightId) {
        _buildingsApi_DestroyHighlight(_emscriptenApiPointer, buildingHighlightId);
    };

    this.setHighlightColor = function(buildingHighlightId, color) {
        _buildingsApi_SetHighlightColor(_emscriptenApiPointer, buildingHighlightId, color.x/255, color.y/255, color.z/255, color.w/255);
    };

    this.tryGetBuildingInformation = function(buildingHighlightId) {
        var buildingIdSizeBuf = _emscriptenMemory.createInt32Buffer(1);
        var contourPointsSizeBuf = _emscriptenMemory.createInt32Buffer(1);
        var buildingContoursSizeBuf = _emscriptenMemory.createInt32Buffer(1);

        var success = _buildingsApi_TryGetBuildingInformationBufferSizes(_emscriptenApiPointer, buildingHighlightId, buildingIdSizeBuf.ptr, contourPointsSizeBuf.ptr, buildingContoursSizeBuf.ptr);

        var buildingIdSize = _emscriptenMemory.consumeBufferToArray(buildingIdSizeBuf)[0];
        var contourPointsSize = _emscriptenMemory.consumeBufferToArray(contourPointsSizeBuf)[0];
        var buildingContoursSize = _emscriptenMemory.consumeBufferToArray(buildingContoursSizeBuf)[0];

        if (!success)
        {
            return null;
        }

        var buildingIdBuf = _emscriptenMemory.createInt8Buffer(buildingIdSize);
        var baseAltitudeBuf = _emscriptenMemory.createDoubleBuffer(1);
        var topAltitudeBuf = _emscriptenMemory.createDoubleBuffer(1);
        var centroidBuf = _emscriptenMemory.createBufferFromArray([0.0, 0.0], _emscriptenMemory.createDoubleBuffer);

        // building contours fetched as struct of arrays
        var contourPointsLatLngDoublesBuf = _emscriptenMemory.createDoubleBuffer(contourPointsSize * 2);
        var contourPointCountsBuf = _emscriptenMemory.createInt32Buffer(buildingContoursSize);
        var contourBottomAltitudeBuf = _emscriptenMemory.createDoubleBuffer(buildingContoursSize);
        var contourTopAltitudeBuf = _emscriptenMemory.createDoubleBuffer(buildingContoursSize);

        success = _buildingsApi_TryGetBuildingInformation(
            _emscriptenApiPointer,
            buildingHighlightId,
            buildingIdBuf.ptr,
            buildingIdSize,
            baseAltitudeBuf.ptr,
            topAltitudeBuf.ptr,
            centroidBuf.ptr,
            contourPointsLatLngDoublesBuf.ptr,
            contourPointsLatLngDoublesBuf.element_count,
            contourPointCountsBuf.ptr,
            contourPointCountsBuf.element_count,
            contourBottomAltitudeBuf.ptr,
            contourBottomAltitudeBuf.element_count,
            contourTopAltitudeBuf.ptr,
            contourTopAltitudeBuf.element_count
            );

        var buildingId = _emscriptenMemory.consumeUtf8BufferToString(buildingIdBuf);
        var baseAltitude = _emscriptenMemory.consumeBufferToArray(baseAltitudeBuf);
        var topAltitude = _emscriptenMemory.consumeBufferToArray(topAltitudeBuf);
        var centroid = L.latLng(_emscriptenMemory.consumeBufferToArray(centroidBuf));

        var buildingDimensions = new buildings.BuildingDimensions(baseAltitude, topAltitude, centroid);

        var contourPointsLatLngDoubles = _emscriptenMemory.consumeBufferToArray(contourPointsLatLngDoublesBuf);
        var contourPointCounts = _emscriptenMemory.consumeBufferToArray(contourPointCountsBuf);
        var contourBottomAltitudes = _emscriptenMemory.consumeBufferToArray(contourBottomAltitudeBuf);
        var contourTopAltitudes = _emscriptenMemory.consumeBufferToArray(contourTopAltitudeBuf);

        var buildingContours = [];
        var pointBufferIndex = 0;
        for (var contourIndex = 0; contourIndex < contourPointCountsBuf.element_count; ++contourIndex) {
            var pointCount = contourPointCounts[contourIndex];
            var points = [];
            for (var i = 0; i < pointCount; ++i) {
                var lat = contourPointsLatLngDoubles[pointBufferIndex++];
                var lng = contourPointsLatLngDoubles[pointBufferIndex++];
                points.push(L.latLng(lat, lng));
            }
            var contour = new buildings.BuildingContour(
                contourBottomAltitudes[contourIndex],
                contourTopAltitudes[contourIndex],
                points);
            buildingContours.push(contour);
        }

        if (!success) {
            return null;
        }

        return new buildings.BuildingInformation(buildingId, buildingDimensions, buildingContours);
    };

    this.findIntersectionWithBuilding = function(ray) {
        var rayElements = [ray.origin.x, ray.origin.y, ray.origin.z, ray.direction.x, ray.direction.y, ray.direction.z];

        var rayBuffer = _emscriptenMemory.createBufferFromArray(rayElements, _emscriptenMemory.createDoubleBuffer);

        var intersectionLatLngAltBuffer = _emscriptenMemory.createDoubleBuffer(3);

        var didIntersect = _buildingsApi_TryFindIntersectionWithBuilding(_emscriptenApiPointer, rayBuffer.ptr, intersectionLatLngAltBuffer.ptr);

        _emscriptenMemory.freeBuffer(rayBuffer);

        var resultArray = _emscriptenMemory.consumeBufferToArray(intersectionLatLngAltBuffer);

        return {
            found : didIntersect,
            point : L.latLng(resultArray)
        };
    };

}

module.exports = EmscriptenBuildingsApi;


text:
var process = require("../lib/process");
var assert = require("assert");

describe("process function", function () {

  it("should not does nothing when template is single quoted string", function () {
    var source = "template: '

'";
    var actual = process(source, null).source;
    assert.equal(actual, source);
  });

  it("should not does nothing when template is double quoted string", function () {
    var source = 'template: "

"';
    var actual = process(source, null).source;
    assert.equal(actual, source);
  });

  it("should not does nothing with tagged template function", function () {
    var source = 'template: myFn`<div></div>`';
    var actual = process(source, null).source;
    assert.equal(actual, source);
  });

  it("should pass through template when htmlmin config is null", function () {
    var source = 'template: ` \n'
               + '
\n'
               + '
\n'
               + '`';
    var actual = process(source, null).source;
    assert.equal(actual, source);
  });

  it("should pass through template when htmlmin config is an empty object", function () {
    var source = 'template: ` \n'
               + '
\n'
               + '
\n'
               + '`';
    var actual = process(source, {}).source;
    assert.equal(actual, source);
  });

  it("should process html template with specified htmlmin config", function () {
    var source = 'template: ` \n'
               + '
\n'
               + '
\n'
               + '`';
    var actual = process(source, {collapseWhitespace: true}).source;
    var expected = 'template: `<div></div>`';
    assert.equal(actual, expected);
  });

  it("should process multiple html templates with specified htmlmin config", function () {
    var source = 'template: ` \n'
               + '
\n'
               + '   \n'
               + '
\n'
               + '`,\n'
               + 'template: ` \n'
               + '
\n'
               + '
\n'
               + '`,\n'
               + 'styleUrls: []'
    var actual = process(source, {collapseWhitespace: true}).source;
    var expected = 'template: `<p><span></span></p>`,\n'
                 + 'template: `<div></div>`,\n'
                 + 'styleUrls: []';
    assert.equal(actual, expected);
  });

  it("should preserve camelized attribute names", function () {
    var source = 'template:

';
    var actual = process(source, {collapseWhitespace: true}).source;
    assert.equal(actual, source);
  });

});


text:
package org.inaetics.ails.api.common.model;

import com.google.common.base.Preconditions;

/**
 * Representation of an access point measurement. This describes the measurement of access points by
 * a single device.
 *
 * @author L. Buit, N. Korthout, J. Naus
 * @version 0.1.1
 * @since 22-10-2015
 */
public class AccessPointMeasurement {

    private AccessPoint accessPoint;
    private int measurementValue;

    public AccessPointMeasurement() {
        // Empty constructor for Jackson
    }

    /**
     * Constructor for AccessPointMeasurement.
     *
     * @param accessPoint @NotNull The access point on which the measurement was performed.
     */
    public AccessPointMeasurement(AccessPoint accessPoint, int measurementValue) {
        super();
        this.accessPoint = Preconditions.checkNotNull(accessPoint, "accesspoint is not set");
        this.measurementValue = Preconditions.checkNotNull(measurementValue, "measurementValue is not set");
    }

    /**
     * Retrieve the access point on which the measurement was performed.
     *
     * @return the accessPoint
     */
    public AccessPoint getAccessPoint() {
        return accessPoint;
    }

    /**
     * Retrieve the measurement value on which the measurement was performed.
     *
     * @return the measurement value
     */
    public int getMeasurementValue() {
        return measurementValue;
    }

    // Below setters only exist for Jackson

    public void setAccessPoint(AccessPoint accessPoint) {
        this.accessPoint = accessPoint;
    }

    public void setMeasurementValue(int measurementValue) {
        this.measurementValue = measurementValue;
    }

    public String toString() {
        return "AccessPointMeasurement{access_point: " + this.accessPoint + ", measurement_value: " + this.measurementValue +  "}";
    }
}


text:
package fr.ourten.teabeans.property;

import fr.ourten.teabeans.listener.ValueInvalidationListener;
import fr.ourten.teabeans.value.Observable;
import org.junit.jupiter.api.Test;

import java.util.concurrent.atomic.AtomicInteger;

import static java.util.stream.Collectors.joining;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

public class ReducePropertyTest
{
    @Test
    void computeValue_givenSimpleMultiplication_thenShouldReduce()
    {
        Property<Integer> two = new Property<>(2);
        Property<Integer> four = new Property<>(4);

        ReduceProperty<Integer, Integer> multiplied = ReduceProperty.reduce((first, second) -> first * second);
        multiplied.bind(two, four);

        assertThat(multiplied.getValue()).isEqualTo(8);

        four.setValue(8);

        assertThat(multiplied.isValid()).isFalse();
        assertThat(multiplied.getValue()).isEqualTo(16);
    }

    @Test
    void computeValue_givenSimpleJoin_thenShouldReduce()
    {
        Property<Integer> two = new Property<>(2);
        Property<Integer> four = new Property<>(4);

        ReduceProperty<Integer, String> concatenated = ReduceProperty.reduce(values -> values.map(String::valueOf).collect(joining(",")), two, four);

        assertThat(concatenated.getValue()).isEqualTo("2,4");

        four.setValue(8);

        assertThat(concatenated.isValid()).isFalse();
        assertThat(concatenated.getValue()).isEqualTo("2,8");
    }

    @Test
    void bind_givenInvalidObservable_thenShouldThrow()
    {
        Property<Integer> two = new Property<>(2);
        Observable observable = new TestObservable();

        ReduceProperty<Integer, String> concatenated = ReduceProperty.reduce(values -> values.map(String::valueOf).collect(joining(",")));
        assertThatThrownBy(() -> concatenated.bind(two, observable)).isInstanceOf(UnsupportedOperationException.class).hasMessageContaining("ObservableValue");
    }

    @Test
    void setValue_givenManualSet_thenShouldStopBinding()
    {
        Property<Integer> two = new Property<>(2);
        Property<Integer> four = new Property<>(4);

        ReduceProperty<Integer, String> concatenated = ReduceProperty.reduce(values -> values.map(String::valueOf).collect(joining(",")), two, four);

        assertThat(concatenated.getValue()).isEqualTo("2,4");

        concatenated.setValue("ABC");
        assertThat(concatenated.getValue()).isEqualTo("ABC");

        four.setValue(8);
        assertThat(concatenated.getValue()).isEqualTo("ABC");
    }

    @Test
    void setValue_givenPropertyBind_thenShouldStopBinding()
    {
        Property<Integer> two = new Property<>(2);
        Property<Integer> four = new Property<>(4);

        Property<String> result = new Property<>("ABC");

        ReduceProperty<Integer, String> concatenated = ReduceProperty.reduce(values -> values.map(String::valueOf).collect(joining(",")), two, four);

        assertThat(concatenated.getValue()).isEqualTo("2,4");

        concatenated.bindProperty(result);
        assertThat(concatenated.getValue()).isEqualTo(result.getValue());

        four.setValue(8);
        assertThat(concatenated.getValue()).isEqualTo(result.getValue());
    }

    @Test
    void setValue_givenPropertyBind_thenShouldPropagateChange()
    {
        Property<Integer> two = new Property<>(2);
        Property<Integer> four = new Property<>(4);

        Property<String> result = new Property<>("ABC");

        AtomicInteger invalidated = new AtomicInteger();
        AtomicInteger changed = new AtomicInteger();

        ReduceProperty<Integer, String> concatenated = ReduceProperty.reduce(values -> values.map(String::valueOf).collect(joining(",")), two, four);
        concatenated.addListener(obs -> invalidated.getAndIncrement());

        assertThat(concatenated.getValue()).isEqualTo("2,4");

        concatenated.addChangeListener((obs, oldValue, newValue) ->
        {
            changed.getAndIncrement();
            assertThat(oldValue).isEqualTo("2,4");
            assertThat(newValue).isEqualTo(result.getValue());
        });

        concatenated.bindProperty(result);

        assertThat(invalidated.get()).isEqualTo(1);
        assertThat(changed.get()).isEqualTo(1);
    }

    @Test
    void actAsBinding_givenPropertyBehaviorThenBinding_thenShouldRestoreBindingDependencies()
    {
        Property<Integer> two = new Property<>(2);
        Property<Integer> four = new Property<>(4);

        Property<String> result = new Property<>("ABC");

        ReduceProperty<Integer, String> concatenated = ReduceProperty.reduce(values -> values.map(String::valueOf).collect(joining(",")), two, four);
        concatenated.bindProperty(result);

        assertThat(concatenated.getValue()).isEqualTo(result.getValue());

        concatenated.actAsBinding();

        assertThat(concatenated.getValue()).isEqualTo("2,4");
        four.setValue(8);
        assertThat(concatenated.getValue()).isEqualTo("2,8");
    }

    private static class TestObservable implements Observable
    {
        @Override
        public void addListener(ValueInvalidationListener listener)
        {

        }

        @Override
        public void removeListener(ValueInvalidationListener listener)
        {

        }

        @Override
        public void addChangeListener(ValueInvalidationListener listener)
        {

        }

        @Override
        public void removeChangeListener(ValueInvalidationListener listener)
        {

        }

        @Override
        public void mute()
        {

        }

        @Override
        public void unmute()
        {

        }

        @Override
        public boolean isMuted()
        {
            return false;
        }
    }
}


text:
require 'rails_helper'

module DiabeticToolbox
  RSpec.describe Reading, type: :model do
    #region Definitions
    let(:reading) { build(:reading) }
    let(:member)  { build(:member)  }
    #endregion

    #region Stories
    describe 'a member' do
      context 'recording a new reading' do
        #region Success
        DiabeticToolbox.from :readings, require: %w(create_member_reading)
        it 'should save with appropriate parameters' do
          member.save

          params = {
            glucometer_value: reading.glucometer_value,
            test_time: reading.test_time,
            meal: reading.meal,
            intake: reading.intake
          }

          result = CreateMemberReading.new( member, params ).call
          member.reload

          expect(result.success?).to eq true
          expect(result.flash).to eq 'Your reading was successfully recorded'
          expect(member.readings.size).to eq 1
        end
        #endregion

        #region Failure
        it 'should not save without required parameters' do
          member.save

          params = {}

          result = CreateMemberReading.new( member, params ).call
          member.reload

          expect(result.success?).to eq false
          expect(result.flash).to eq 'Sorry, your reading could not be recorded'
          expect(member.readings.size).to eq 0
        end
        #endregion
      end
    end
    #endregion
  end
end


text:
/**
 * @file NeuroEvoMember.cpp
 * @brief Single set of params for NeuroEvolution
 * @date August 2013
 * @author Atil Iscen
 * $Id$
 */

#include "NeuroEvoMember.h"
#include "neuralNet/Neural Network v2/neuralNetwork.h"
#include <fstream>
#include <iostream>
#include <assert.h>
#include <stdexcept>

using namespace std;

NeuroEvoMember::NeuroEvoMember(configuration config)
{
	this->numInputs=config.getintvalue("numberOfStates");
    this->numOutputs=config.getintvalue("numberOfActions");
	int numHidden = config.getintvalue("numberHidden");
    assert(numOutputs > 0);
	cout<<"creating NN"<<endl;
	if(numInputs>0)
		nn = new neuralNetwork(numInputs, numHidden,numOutputs);
	else
	{
		statelessParameters.resize(numOutputs);
		for(int i=0;i<numOutputs;i++)
			statelessParameters[i]=rand()*1.0/RAND_MAX;
	}
	maxScore=-1000;
}

NeuroEvoMember::~NeuroEvoMember()
{
	delete nn;
}

void NeuroEvoMember::mutate(std::tr1::ranlux64_base_01 *eng){
	std::tr1::uniform_real<double> unif(0, 1);
	if(unif(*eng)  > 0.5)
	{
		return;
	}
	//TODO: for each weight of the NN with 0.5 probability mutate it

	if(numInputs>0)
		this->nn->mutate(eng);
	else
	{
		double dev = 3.0 / 100.0;   // 10 percent of interval 0-1
		std::tr1::normal_distribution<double> normal(0, dev);
		for(std::size_t i=0;i<statelessParameters.size();i++)
		{
			if(unif(*eng)  > 0.5)
			{
				continue;
			}
			double mutAmount = normal(*eng);
//			cout<<"param: "<<i<<" dev: "<<dev<<" rand: "<<mutAmount<<endl;
			double newParam= statelessParameters[i] + mutAmount;
			if(newParam < 0.0)
				statelessParameters[i] = 0.0;
			else if(newParam > 1.0)
				statelessParameters[i] = 1.0;
			else
				statelessParameters[i] =newParam;
		}

	}
}

void NeuroEvoMember::copyFrom(NeuroEvoMember* otherMember)
{
	if(numInputs>0)
	{
		this->nn->copyWeightFrom(otherMember->getNn());
		this->maxScore=-10000;
		this->pastScores.clear();
	}
	else
	{
		this->statelessParameters=otherMember->statelessParameters;
	}
}

void NeuroEvoMember::copyFrom(NeuroEvoMember *otherMember1, NeuroEvoMember *otherMember2, std::tr1::ranlux64_base_01 *eng)
{
    if(numInputs>0)
    {
        this->nn->combineWeights(otherMember1->getNn(), otherMember2->getNn(), eng);
        this->maxScore=-10000;
        this->pastScores.clear();
    }
    else
    {
        std::tr1::uniform_real<double> unif(0, 1);
        for (int i = 0; i < numOutputs; i++)
        {
            if (unif(*eng) > 0.5)
            {
                this->statelessParameters[i] = otherMember1->statelessParameters[i];
            }
            else
            {
                this->statelessParameters[i] = otherMember2->statelessParameters[i];
            }
        }
    }
}

void NeuroEvoMember::saveToFile(const char * outputFilename)
{
	if(numInputs > 0 )
		this->getNn()->saveWeights(outputFilename);
	else
	{
		ofstream ss(outputFilename);
		for(std::size_t i=0;i<statelessParameters.size();i++)
		{
			ss<<statelessParameters[i];
			if(i!=statelessParameters.size()-1)
				ss<<",";
		}
		ss.close();
	}
}

void NeuroEvoMember::loadFromFile(const char * outputFilename)
{
	if(numInputs > 0 )
		this->getNn()->loadWeights(outputFilename);
	else
	{
		//cout<<"loading parameters from file "<<outputFilename<<endl;
		ifstream ss(outputFilename);
		int i=0;
		string value;
#if (0)
		// Disable definition of unused variable to suppress compiler warning
		double valueDbl;
#endif
		if(ss.is_open())
		{
			while(!ss.eof())
			{
				//cout<<"success opening file"<<endl;
				if(getline ( ss, value, ',' )>0)
				{
					//cout<<"value read as string: "<<value<<endl;
					statelessParameters[i++]=atof(value.c_str());
					//cout<<statelessParameters[i-1]<<",";
				}
			}
			//cout<<"reading complete"<<endl;
			cout<<endl;
			ss.close();
		}
		else
		{
			cout << "File of name " << outputFilename << " does not exist" << std::endl;
			cout << "Try turning learning on in config.ini to generate parameters" << std::endl;
			throw std::invalid_argument("Parameter file does not exist");
		}
		//cout<<"reading complete"<<endl;
		//cout<<endl;
		ss.close();
	}

}


text:
module Aerogel::Mailer
class Definition

  include Aerogel::Render::Scope

  attr_accessor :name, :blk, :params

  DEFAULT_LAYOUT = "mailer"

  def initialize( name, blk )
    self.name = name.to_sym
    self.params = {}
    self.blk = blk

    self.class.register_mailer( self )
  end

  def from( str )
    params[:from] = str
  end

  def to( str )
    params[:to] = str
  end

  def subject( str )
    params[:subject] = str
  end

  # Sets layout name for text/plain and text/html layouts
  # or disables layout for message body templates.
  #
  # Example
  #   layout false # disables layout for text and html message templates
  #   layout 'mailer-admin' # sets layouts to 'views/layouts/mailer-admin.text.erb'
  #                        # and 'views/layouts/mailer-admin.html.erb'
  #
  def layout( name )
    params[:layout] = name
  end

  # Sets message body. Multiple calls to #body are allowed,
  # e.g. for setting  plain text part and html part separately.
  #
  # If message body is set via call to #body, existing mailer templates
  # and layout will be ignored.
  #
  # +args+ can be a String, which sets the text/plain message body
  # or a Hash.
  #
  # Example:
  #   body "This is a plain text message"
  #   body html: "This is a HTML only message"
  #   body text: "This is a plain text", html: "and <b>HTML</b> message"
  #
  def body( args )
    params[:body] ||= {}
    if args.is_a? String
      params[:body][:text] = args
    elsif args.is_a? Hash
      params[:body][:html] = args[:html] if args.include? :html
      params[:body][:text] = args[:text] if args.include? :text
    else
      raise ArgumentError.new "Invalid argument #{args.class} to #body"
    end
  end

  # Sets local variables to be passed to template. Multiple calls to #locals
  # are allowed, variables passed this way will be merged into one set before
  # passing to a template.
  #
  # Example:
  #   locals user: current_user, url: url
  #   locals order: order
  #
  def locals( args )
    params[:locals] ||= {}
    params[:locals].merge! args
  end

  def compile( context, *args )
    unless args.size == blk.arity
      raise Aerogel::Mailer::Error.new("wrong number of arguments for mailer '#{name}': #{args.size} for #{blk.arity}")
    end
    # @self_before_instance_eval = eval "self", blk.binding
    @self_before_instance_eval = context
    params.clear
    instance_exec( *args, &blk )
    params[:from] ||= config.mailer.default_from!
    if params[:from].nil?
      raise Aerogel::Mailer::Error.new("'from' address is not set for mailer '#{name}'")
    end
    render_body
    params
  end

  def method_missing( method, *args, &block )
    @self_before_instance_eval.send method, *args, &block
  end

  def self.register_mailer( mailer )
    @mailers ||= {}
    @mailers[mailer.name] = mailer
  end

  def self.mailers
    @mailers || {}
  end

private

  class TemplateNameCache
    # Returns template file name, use cached file name if possible.
    #
    def self.fetch( filename )
      @cache ||= {} # reset if reload templates is used
      return @cache[filename] unless @cache[filename].nil?
      if Aerogel.get_resource( :views, filename+".erb" )
        @cache[filename] = filename.to_sym
      else
        @cache[filename] = false # template not found
      end
      @cache[filename]
    end

    def self.clear
      @cache = {}
    end
  end # class TemplateNameCache

  # Renders message body using filled params.
  # Stores rendered body (text and html parts) into params[:body] hash.
  #
  def render_body
    if Aerogel.config.aerogel.reloader?
      TemplateNameCache.clear
      template_cache.clear
    end
    params[:body] ||= {}
    return unless params[:body].blank? # body set in the mailer definition block
    if params[:layout] == false
      layout_text = false
      layout_html = false
    else
      layout_name = params[:layout] || DEFAULT_LAYOUT
      layout_text = TemplateNameCache.fetch( "layouts/#{layout_name}.text" )
      layout_html = TemplateNameCache.fetch( "layouts/#{layout_name}.html" )
    end
    body_text = TemplateNameCache.fetch( "mailers/#{name}.text" )
    body_html = TemplateNameCache.fetch( "mailers/#{name}.html" )
    if !body_text && !body_html
      raise Aerogel::Mailer::Error.new "No body templates found for mailer '#{name}'"
    end
    if body_text
      params[:body][:text] = erb body_text, layout: layout_text, locals: params[:locals]
    end
    if body_html
      params[:body][:html] = erb body_html, layout: layout_html, locals: params[:locals]
    end
    true
  end

end # class Definition
end # module Aerogel::Mailer


text:
import React, {Component, PropTypes} from 'react';

function getStyles(props, context) {
  const {cardMedia} = context.muiTheme;

  return {
    root: {
      position: 'relative',
    },
    overlayContainer: {
      position: 'absolute',
      top: 0,
      bottom: 0,
      right: 0,
      left: 0,
    },
    overlay: {
      height: '100%',
      position: 'relative',
    },
    overlayContent: {
      position: 'absolute',
      bottom: 0,
      right: 0,
      left: 0,
      paddingTop: 8,
      background: cardMedia.overlayContentBackground,
    },
    media: {},
    mediaChild: {
      verticalAlign: 'top',
      maxWidth: '100%',
      minWidth: '100%',
      width: '100%',
    },
  };
}

class CardMedia extends Component {
  static propTypes = {
    /**
     * If true, a click on this card component expands the card.
     */
    actAsExpander: PropTypes.bool,
    /**
     * Can be used to render elements inside the Card Media.
     */
    children: PropTypes.node,
    /**
     * If true, this card component is expandable.
     */
    expandable: PropTypes.bool,
    /**
     * Override the inline-styles of the Card Media.
     */
    mediaStyle: PropTypes.object,
    /**
     * Can be used to render overlay element in Card Media.
     */
    overlay: PropTypes.node,
    /**
     * Override the inline-styles of the overlay container.
     */
    overlayContainerStyle: PropTypes.object,
    /**
     * Override the inline-styles of the overlay content.
     */
    overlayContentStyle: PropTypes.object,
    /**
     * Override the inline-styles of the overlay element.
     */
    overlayStyle: PropTypes.object,
    /**
     * Override the inline-styles of the root element.
     */
    style: PropTypes.object,
  };

  static contextTypes = {
    muiTheme: PropTypes.object.isRequired,
  };

  render() {
    const {
      actAsExpander, // eslint-disable-line no-unused-vars
      children,
      expandable, // eslint-disable-line no-unused-vars
      mediaStyle,
      overlay,
      overlayContainerStyle,
      overlayContentStyle,
      overlayStyle,
      style,
      ...other
    } = this.props;

    const {prepareStyles} = this.context.muiTheme;
    const styles = getStyles(this.props, this.context);
    const rootStyle = Object.assign(styles.root, style);
    const extendedMediaStyle = Object.assign(styles.media, mediaStyle);
    const extendedOverlayContainerStyle = Object.assign(styles.overlayContainer, overlayContainerStyle);
    const extendedOverlayContentStyle = Object.assign(styles.overlayContent, overlayContentStyle);
    const extendedOverlayStyle = Object.assign(styles.overlay, overlayStyle);
    const titleColor = this.context.muiTheme.cardMedia.titleColor;
    const subtitleColor = this.context.muiTheme.cardMedia.subtitleColor;
    const color = this.context.muiTheme.cardMedia.color;

    const styledChildren = React.Children.map(children, (child) => {
      return React.cloneElement(child, {
        style: prepareStyles(Object.assign({}, styles.mediaChild, child.props.style)),
      });
    });

    const overlayChildren = React.Children.map(overlay, (child) => {
      if (child.type.muiName === 'CardHeader' || child.type.muiName === 'CardTitle') {
        return React.cloneElement(child, {
          titleColor: titleColor,
          subtitleColor: subtitleColor,
        });
      } else if (child.type.muiName === 'CardText') {
        return React.cloneElement(child, {
          color: color,
        });
      } else {
        return child;
      }
    });

    return (

          {styledChildren}

        {overlay ?

                {overlayChildren}

 : ''}

    );
  }
}

export default CardMedia;


text:
from __future__ import absolute_import

from .mock import _all_auth_mock_
from .mock import public_incursion
from .mock import public_incursion_no_expires
from .mock import public_incursion_no_expires_second
from .mock import public_incursion_warning
from .mock import public_incursion_server_error
from esipy import App
from esipy import EsiClient
from esipy import EsiSecurity
from esipy.cache import BaseCache
from esipy.cache import DictCache
from esipy.cache import DummyCache

from requests.adapters import HTTPAdapter

import httmock
import mock
import time
import six
import unittest
import warnings

import logging
# set pyswagger logger to error, as it displays too much thing for test needs
pyswagger_logger = logging.getLogger('pyswagger')
pyswagger_logger.setLevel(logging.ERROR)

class TestEsiPy(unittest.TestCase):
    CALLBACK_URI = "https://foo.bar/baz/callback"
    LOGIN_EVE = "https://login.eveonline.com"
    OAUTH_VERIFY = "%s/oauth/verify" % LOGIN_EVE
    OAUTH_TOKEN = "%s/oauth/token" % LOGIN_EVE
    CLIENT_ID = 'foo'
    SECRET_KEY = 'bar'
    BASIC_TOKEN = six.u('Zm9vOmJhcg==')
    SECURITY_NAME = 'evesso'

    @mock.patch('six.moves.urllib.request.urlopen')
    def setUp(self, urlopen_mock):
        # I hate those mock... thx urlopen instead of requests...
        urlopen_mock.return_value = open('test/resources/swagger.json')

        self.app = App.create(
            'https://esi.tech.ccp.is/latest/swagger.json'
        )

        self.security = EsiSecurity(
            self.app,
            TestEsiPy.CALLBACK_URI,
            TestEsiPy.CLIENT_ID,
            TestEsiPy.SECRET_KEY
        )

        self.cache = DictCache()
        self.client = EsiClient(self.security, cache=self.cache)
        self.client_no_auth = EsiClient(cache=self.cache, retry_requests=True)

    def tearDown(self):
        """ clear the cache so we don't have residual data """
        self.cache._dict = {}

    def test_esipy_client_no_args(self):
        client_no_args = EsiClient()
        self.assertIsNone(client_no_args.security)
        self.assertTrue(isinstance(client_no_args.cache, DictCache))
        self.assertEqual(
            client_no_args._session.headers['User-Agent'],
            'EsiPy/Client - https://github.com/Kyria/EsiPy'
        )
        self.assertEqual(client_no_args.raw_body_only, False)

    def test_esipy_client_with_headers(self):
        client_with_headers = EsiClient(headers={'User-Agent': 'foobar'})
        self.assertEqual(
            client_with_headers._session.headers['User-Agent'],
            'foobar'
        )

    def test_esipy_client_with_adapter(self):
        transport_adapter = HTTPAdapter()
        client_with_adapters = EsiClient(
            transport_adapter=transport_adapter
        )
        self.assertEqual(
            client_with_adapters._session.get_adapter('http://'),
            transport_adapter
        )
        self.assertEqual(
            client_with_adapters._session.get_adapter('https://'),
            transport_adapter
        )

    def test_esipy_client_without_cache(self):
        client_without_cache = EsiClient(cache=None)
        self.assertTrue(isinstance(client_without_cache.cache, DummyCache))

    def test_esipy_client_with_cache(self):
        cache = DictCache()
        client_with_cache = EsiClient(cache=cache)
        self.assertTrue(isinstance(client_with_cache.cache, BaseCache))
        self.assertEqual(client_with_cache.cache, cache)

    def test_esipy_client_wrong_cache(self):
        with self.assertRaises(ValueError):
            EsiClient(cache=DictCache)

    def test_esipy_request_public(self):
        with httmock.HTTMock(public_incursion):
            incursions = self.client_no_auth.request(
                self.app.op['get_incursions']()
            )
            self.assertEqual(incursions.data[0].type, 'Incursion')
            self.assertEqual(incursions.data[0].faction_id, 500019)

    def test_esipy_request_authed(self):
        with httmock.HTTMock(*_all_auth_mock_):
            self.security.auth('let it bee')
            char_location = self.client.request(
                self.app.op['get_characters_character_id_location'](
                    character_id=123456789
                )
            )
            self.assertEqual(char_location.data.station_id, 60004756)

            # force expire
            self.security.token_expiry = 0
            char_location_with_refresh = self.client.request(
                self.app.op['get_characters_character_id_location'](
                    character_id=123456789
                )
            )
            self.assertEqual(
                char_location_with_refresh.data.station_id,
                60004756
            )

    def test_client_cache_request(self):
        @httmock.all_requests
        def fail_if_request(url, request):
            self.fail('Cached data is not supposed to do requests')

        incursion_operation = self.app.op['get_incursions']

        with httmock.HTTMock(public_incursion_no_expires):
            incursions = self.client_no_auth.request(incursion_operation())
            self.assertEqual(incursions.data[0].state, 'mobilizing')

        with httmock.HTTMock(public_incursion_no_expires_second):
            incursions = self.client_no_auth.request(incursion_operation())
            self.assertEqual(incursions.data[0].state, 'established')

        with httmock.HTTMock(public_incursion):
            incursions = self.client_no_auth.request(incursion_operation())
            self.assertEqual(incursions.data[0].state, 'mobilizing')

        with httmock.HTTMock(fail_if_request):
            incursions = self.client_no_auth.request(incursion_operation())
            self.assertEqual(incursions.data[0].state, 'mobilizing')

    def test_client_warning_header(self):
        with httmock.HTTMock(public_incursion_warning):
            warnings.simplefilter('error')
            incursion_operation = self.app.op['get_incursions']

            with self.assertRaises(UserWarning):
                self.client_no_auth.request(incursion_operation())

    def test_client_raw_body_only(self):
        client = EsiClient(raw_body_only=True)
        self.assertEqual(client.raw_body_only, True)

        with httmock.HTTMock(public_incursion):
            incursions = client.request(self.app.op['get_incursions']())
            self.assertIsNone(incursions.data)
            self.assertTrue(len(incursions.raw) > 0)

            incursions = client.request(
                self.app.op['get_incursions'](),
                raw_body_only=False
            )
            self.assertIsNotNone(incursions.data)

    def test_esipy_reuse_operation(self):
        operation = self.app.op['get_incursions']()
        with httmock.HTTMock(public_incursion):
            incursions = self.client_no_auth.request(operation)
            self.assertEqual(incursions.data[0].faction_id, 500019)

            # this shouldn't create any errors
            incursions = self.client_no_auth.request(operation)
            self.assertEqual(incursions.data[0].faction_id, 500019)

    def test_esipy_multi_request(self):
        operation = self.app.op['get_incursions']()

        with httmock.HTTMock(public_incursion):
            count = 0
            for req, incursions in self.client_no_auth.multi_request(
                    [operation, operation, operation], threads=2):
                self.assertEqual(incursions.data[0].faction_id, 500019)
                count += 1

            # Check we made 3 requests
            self.assertEqual(count, 3)

    def test_esipy_backoff(self):
        operation = self.app.op['get_incursions']()

        start_calls = time.time()

        with httmock.HTTMock(public_incursion_server_error):
            incursions = self.client_no_auth.request(operation)
            self.assertEqual(incursions.data.error, 'broke')

        end_calls = time.time()

        # Check we retried 5 times
        self.assertEqual(incursions.data.count, 5)

        # Check that backoff slept for a sum > 2 seconds
        self.assertTrue(end_calls - start_calls > 2)


text:
import { Coordinate } from '../coordinate';
import { FeatureLike } from '../Feature';
import Geometry from '../geom/Geometry';
import GeometryType from '../geom/GeometryType';
import { State } from '../render';
import RenderFeature from '../render/Feature';
import Fill from './Fill';
import ImageStyle from './Image';
import Stroke from './Stroke';
import Text from './Text';

export type GeometryFunction = (p0: FeatureLike) => Geometry | RenderFeature | undefined;
export interface Options {
    geometry?: string | Geometry | GeometryFunction | undefined;
    fill?: Fill | undefined;
    image?: ImageStyle | undefined;
    renderer?: RenderFunction | undefined;
    stroke?: Stroke | undefined;
    text?: Text | undefined;
    zIndex?: number | undefined;
}
export type RenderFunction = (p0: Coordinate | Coordinate[] | Coordinate[][], p1: State) => void;
export type StyleFunction = (p0: FeatureLike, p1: number) => Style | Style[];
export type StyleLike = Style | Style[] | StyleFunction;
export default class Style {
    constructor(opt_options?: Options);
    clone(): Style;
    getFill(): Fill;
    getGeometry(): string | Geometry | GeometryFunction;
    getGeometryFunction(): GeometryFunction;
    getImage(): ImageStyle;
    getRenderer(): RenderFunction | null;
    getStroke(): Stroke;
    getText(): Text;
    getZIndex(): number | undefined;
    setFill(fill: Fill): void;
    setGeometry(geometry: string | Geometry | GeometryFunction): void;
    setImage(image: ImageStyle): void;
    setRenderer(renderer: RenderFunction | null): void;
    setStroke(stroke: Stroke): void;
    setText(text: Text): void;
    setZIndex(zIndex: number | undefined): void;
}
export function createDefaultStyle(feature: FeatureLike, resolution: number): Style[];
export function createEditingStyle(): { [key in GeometryType]: Style[] };
export function toFunction(obj: StyleFunction | Style[] | Style): StyleFunction;


text:
// A structure which holds the detail of a record
struct record
{
	int recordID;
	char name[100];
}RecordArray[1000];

void (*bubbleSort)(void *arr, int productsCount, int (*comp)(void *, int , int ), void (*swap)(void *, int , int ));

// Swap the records in the list.
void swapRecords(void *arr, int index1, int index2)
{
	struct record *elem1 = ((struct record *)(arr) + index1);
	struct record *elem2 = ((struct record *)(arr) + index2);

	struct record temp = *((struct record *)(arr) + index1);
	*((struct record *)(arr) + index1) = *((struct record *)(arr) + index2);
	*((struct record *)(arr) + index2) = temp;
	return;
}

// A comparator function to compare by ID.
int compareByID(void *arr, int index1, int index2)
{
	struct record *elem1 = ((struct record *)(arr) + index1);
	struct record *elem2 = ((struct record *)(arr) + index2);

	if ( elem1->recordID < elem2->recordID)
		return -1;
	else if (elem1->recordID > elem2->recordID)
		return 1;
	else
		return 0;
}

// A comparator function to compare by name.
int compareByName(void *arr, int index1, int index2)
{
	struct record *elem1 = ((struct record *)(arr) + index1);
	struct record *elem2 = ((struct record *)(arr) + index2);
	return strcmp(elem1->name, elem2->name);
}

// Function which calls the "actual" bubble sort function in the library.
void bubbleSortRecords(int choice, int productsCount)
{
	// i, j are the iterating variables.
	int i, j;
	switch(choice)
	{
		case 1 :
		{
			bubbleSort(RecordArray, productsCount, &compareByID, &swapRecords);
			break;
		}

		case 2 :
		{
			bubbleSort(RecordArray, productsCount, &compareByName, &swapRecords);
			break;
		}
	}
	return;
}

// A helper function to print all the record
void printProducts(int productsCount)
{
	printf("\nPrinting the record...\n\n");
	int i;
	for(i=0; i<productsCount; i++)
	{
		printf("Product #%d-\t", i+1);
		printf("[ID = %d, Name = %s]\n", RecordArray[i].recordID, RecordArray[i].name);
	}
	return;
}

int main(int argc, char *argv[])
{
	if(argc == 2)
	{
		void* lib = dlopen("./libLIBRARY.so", RTLD_LAZY);
		bubbleSort = dlsym(lib,"bubbleSort");

		int recordCount;	// The number of records.

		printf("Enter the number of records - ");
		scanf("%d", &recordCount);

		int i;
		for(i=0; i<recordCount; i++)
		{
			printf("\nEnter the details\n\nRecord #%d-\n", i+1);

			printf("Enter the Unique Record ID of the record  ");
			scanf("%d", &RecordArray[i].recordID);

			printf("Enter the Record name of the record  ");
			getchar();
			scanf("%[^\n]s", RecordArray[i].name);
		}
		bubbleSortRecords((strcmp(argv[1], "1") == 0) ? 1 : 2, recordCount);
		printf("\nBubble Sort-\n");
		printProducts(recordCount);
	}
	return 0;
}


text:
exports.testRunInSandbox = function (test) {
  var sandbox = require('../sandbox')
  var whitelist = [
    'console',
    './node_modules/http',
    'a',
    'b'
  ]
  var context = {require: require}

  var aBarInASandbox = function () {
    sandbox.runInSandbox(
      function () { require('a').bar() },
      context,
      whitelist
    )
  }

  test.doesNotThrow(function () {
    sandbox.runInSandbox(
      function () { require('console') },
      context,
      whitelist
    )
  })

  test.throws(
    function () {
      sandbox.runInSandbox(
        function () { require('http') },
        context,
        whitelist
      )
    },
    function (err) {
      if (err instanceof Error && err.message === "'http' is not whitelisted") {
        return true
      } else {
        return false
      }
    }
  )

  test.throws(
    function () {
      sandbox.runInSandbox(
        function () { require('http') },
        context,
        []
      )
    },
    function (err) {
      if (err instanceof Error && err.message === "'http' is not whitelisted") {
        return true
      } else {
        return false
      }
    }
  )

  test.equal(
    'function',
    sandbox.runInSandbox(
      function () { return typeof require },
      context
    )
  )

  test.throws(
    function () {
      sandbox.runInSandbox(
        function () { require('http') },
        context
      )
    },
    function (err) {
      if (err instanceof Error && err.message === "'http' is not whitelisted") {
        return true
      } else {
        return false
      }
    }
  )

  test.equal(
    42,
    sandbox.runInSandbox(function () { return 42 })
  )

  test.throws(
    function () {
      sandbox.runInSandbox(function () { return require('http') })
    },
    function (err) {
      if (err.message === 'require is not defined') {
        return true
      } else {
        return false
      }
    }
  )

  test.equal(
    42,
    sandbox.runInSandbox(
      function () { return require('./node_modules/http').getTheAnswer() },
      context,
      whitelist
    )
  )

  test.equal(
    42,
    sandbox.runInSandbox(
      function () { return require('a').foo() },
      context,
      whitelist
    )
  )

  test.throws(
    aBarInASandbox,
    function (err) {
      if (err instanceof Error && err.message === "'c' is not whitelisted") {
        return true
      } else {
        return false
      }
    }
  )

  whitelist.push('c')

  test.throws(
    aBarInASandbox,
    function (err) {
      if (err instanceof Error && err.message === 'boooooyaaaaah!') {
        return true
      } else {
        return false
      }
    }
  )

  whitelist.pop()

  test.throws(
    aBarInASandbox,
    function (err) {
      if (err instanceof Error && err.message === "'c' is not whitelisted") {
        return true
      } else {
        return false
      }
    }
  )

  test.throws(
    function () {
      sandbox.runInSandbox(function () {
        return process.env // could be any of http://nodejs.org/api/globals.html
      })
    },
    function (err) {
      if (err.message === 'process is not defined') {
        return true
      } else {
        return false
      }
    }
  )

  // assert that we are in strict mode
  test.throws(
    function () {
      sandbox.runInSandbox(function () {
        foo = 42 // eslint-disable-line
      })
    },
    function (err) {
      if (err.message === 'foo is not defined') {
        return true
      } else {
        return false
      }
    }
  )

  test.done()
}


text:
namespace Lucene
{
    PersianNormalizationFilter::PersianNormalizationFilter(TokenStreamPtr input) : TokenFilter(input)
    {
        normalizer = newLucene<PersianNormalizer>();
        termAtt = addAttribute<TermAttribute>();
    }

    PersianNormalizationFilter::~PersianNormalizationFilter()
    {
    }

    bool PersianNormalizationFilter::incrementToken()
    {
        if (input->incrementToken())
        {
            int32_t newlen = normalizer->normalize(termAtt->termBuffer().get(), termAtt->termLength());
            termAtt->setTermLength(newlen);
            return true;
        }
        else
            return false;
    }
}


text:
define( [], function() {
    var view = Marionette.View.extend( {
        template: '#tmpl-nf-apps'
    } );
    return view;
} );


text:
package org.apache.ignite.internal.processors.cache;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteDataStreamer;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.CacheMetrics;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cache.CacheRebalanceMode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.events.CacheRebalancingEvent;
import org.apache.ignite.events.Event;
import org.apache.ignite.events.EventType;
import org.apache.ignite.internal.util.lang.GridAbsPredicate;
import org.apache.ignite.internal.util.typedef.PA;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgnitePredicate;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;

import static org.apache.ignite.IgniteSystemProperties.IGNITE_REBALANCE_STATISTICS_TIME_INTERVAL;
import static org.apache.ignite.testframework.GridTestUtils.runAsync;
import static org.apache.ignite.testframework.GridTestUtils.waitForCondition;

/**
 *
 */
public class CacheGroupsMetricsRebalanceTest extends GridCommonAbstractTest {
    /** */
    private static final TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true);

    /** */
    private static final String CACHE1 = "cache1";

    /** */
    private static final String CACHE2 = "cache2";

    /** */
    private static final String CACHE3 = "cache3";

    /** */
    private static final long REBALANCE_DELAY = 5_000;

    /** */
    private static final String GROUP = "group1";

    /** {@inheritDoc} */
    @Override protected void afterTest() throws Exception {
        super.afterTest();

        stopAllGrids();
    }

    /** {@inheritDoc} */
    @Override protected long getTestTimeout() {
        return 10 * 60 * 1000;
    }

    /** {@inheritDoc} */
    @SuppressWarnings("unchecked")
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);

        ((TcpDiscoverySpi)cfg.getDiscoverySpi()).setIpFinder(ipFinder);

        CacheConfiguration cfg1 = new CacheConfiguration()
            .setName(CACHE1)
            .setGroupName(GROUP)
            .setCacheMode(CacheMode.PARTITIONED)
            .setAtomicityMode(CacheAtomicityMode.ATOMIC)
            .setRebalanceMode(CacheRebalanceMode.ASYNC)
            .setRebalanceBatchSize(100)
            .setStatisticsEnabled(true);

        CacheConfiguration cfg2 = new CacheConfiguration(cfg1)
            .setName(CACHE2);

        CacheConfiguration cfg3 = new CacheConfiguration()
            .setName(CACHE3)
            .setCacheMode(CacheMode.PARTITIONED)
            .setAtomicityMode(CacheAtomicityMode.ATOMIC)
            .setRebalanceMode(CacheRebalanceMode.ASYNC)
            .setRebalanceBatchSize(100)
            .setStatisticsEnabled(true)
            .setRebalanceDelay(REBALANCE_DELAY);

        cfg.setCacheConfiguration(cfg1, cfg2, cfg3);

        return cfg;
    }

    /**
     * @throws Exception If failed.
     */
    public void testRebalance() throws Exception {
        Ignite ignite = startGrids(4);

        IgniteCache<Object, Object> cache1 = ignite.cache(CACHE1);
        IgniteCache<Object, Object> cache2 = ignite.cache(CACHE2);

        for (int i = 0; i < 10000; i++) {
            cache1.put(i, CACHE1 + "-" + i);

            if (i % 2 == 0)
                cache2.put(i, CACHE2 + "-" + i);
        }

        final CountDownLatch l1 = new CountDownLatch(1);
        final CountDownLatch l2 = new CountDownLatch(1);

        startGrid(4).events().localListen(new IgnitePredicate<Event>() {
            @Override public boolean apply(Event evt) {
                l1.countDown();

                try {
                    assertTrue(l2.await(5, TimeUnit.SECONDS));
                }
                catch (InterruptedException e) {
                    throw new AssertionError();
                }

                return false;
            }
        }, EventType.EVT_CACHE_REBALANCE_STOPPED);

        assertTrue(l1.await(5, TimeUnit.SECONDS));

        ignite = ignite(4);

        CacheMetrics metrics1 = ignite.cache(CACHE1).localMetrics();
        CacheMetrics metrics2 = ignite.cache(CACHE2).localMetrics();

        l2.countDown();

        long rate1 = metrics1.getRebalancingKeysRate();
        long rate2 = metrics2.getRebalancingKeysRate();

        assertTrue(rate1 > 0);
        assertTrue(rate2 > 0);

        // rate1 has to be roughly the same as rate2
        double ratio = ((double)rate2 / rate1);

        log.info("Ratio: " + ratio);

        assertTrue(ratio > 0.9 && ratio < 1.1);
    }

    /**
     * @throws Exception If failed.
     */
    public void testRebalanceEstimateFinishTime() throws Exception {
        System.setProperty(IGNITE_REBALANCE_STATISTICS_TIME_INTERVAL, String.valueOf(1000));

        Ignite ig1 = startGrid(1);

        final int KEYS = 4_000_000;

        try (IgniteDataStreamer<Integer, String> st = ig1.dataStreamer(CACHE1)) {
            for (int i = 0; i < KEYS; i++)
                st.addData(i, CACHE1 + "-" + i);
        }

        final CountDownLatch finishRebalanceLatch = new CountDownLatch(1);

        final Ignite ig2 = startGrid(2);

        ig2.events().localListen(new IgnitePredicate<Event>() {
            @Override public boolean apply(Event evt) {
                CacheRebalancingEvent rebEvent = (CacheRebalancingEvent)evt;

                if (rebEvent.cacheName().equals(CACHE1)) {
                    log.info("CountDown rebalance stop latch: " + rebEvent.cacheName());

                    finishRebalanceLatch.countDown();
                }

                return false;
            }
        }, EventType.EVT_CACHE_REBALANCE_STOPPED);

        waitForCondition(new PA() {
            @Override public boolean apply() {
                return ig2.cache(CACHE1).localMetrics().getRebalancingStartTime() != -1L;
            }
        }, 5_000);

        CacheMetrics metrics = ig2.cache(CACHE1).localMetrics();

        long startTime = metrics.getRebalancingStartTime();
        long currTime = U.currentTimeMillis();

        assertTrue("Invalid start time [startTime=" + startTime + ", currTime=" + currTime + ']',
            startTime > 0L && (currTime - startTime) >= 0L && (currTime - startTime) <= 5000L);

        final CountDownLatch latch = new CountDownLatch(1);

        runAsync(new Runnable() {
            @Override public void run() {
                // Waiting 25% keys will be rebalanced.
                int partKeys = KEYS / 2;

                final long keysLine = partKeys * 3L / 4L;

                log.info("Wait until keys left will be less than: " + keysLine);

                while (true) {
                    CacheMetrics m = ig2.cache(CACHE1).localMetrics();

                    long keyLeft = m.getKeysToRebalanceLeft();

                    if (keyLeft > 0 && keyLeft < keysLine) {
                        latch.countDown();

                        break;
                    }

                    log.info("Keys left: " + m.getKeysToRebalanceLeft());

                    try {
                        Thread.sleep(1_000);
                    }
                    catch (InterruptedException e) {
                        log.warning("Interrupt thread", e);

                        Thread.currentThread().interrupt();
                    }
                }
            }
        });

        assertTrue(latch.await(getTestTimeout(), TimeUnit.MILLISECONDS));

        waitForCondition(new PA() {
            @Override public boolean apply() {
                return ig2.cache(CACHE1).localMetrics().getEstimatedRebalancingFinishTime() != -1L;
            }
        }, 5_000L);

        long finishTime = ig2.cache(CACHE1).localMetrics().getEstimatedRebalancingFinishTime();

        assertTrue("Not a positive estimation of rebalancing finish time: " + finishTime,
            finishTime > 0L);

        currTime = U.currentTimeMillis();

        long timePassed = currTime - startTime;
        long timeLeft = finishTime - currTime;

        // TODO: finishRebalanceLatch gets countdown much earlier because of ForceRebalanceExchangeTask triggered by cache with delay
//        assertTrue("Got timeout while waiting for rebalancing. Estimated left time: " + timeLeft,
//            finishRebalanceLatch.await(timeLeft + 10_000L, TimeUnit.MILLISECONDS));

        waitForCondition(new GridAbsPredicate() {
            @Override public boolean apply() {
                return ig2.cache(CACHE1).localMetrics().getKeysToRebalanceLeft() == 0;
            }
        }, timeLeft + 10_000L);

        log.info("[timePassed=" + timePassed + ", timeLeft=" + timeLeft +
                ", Time to rebalance=" + (finishTime - startTime) +
                ", startTime=" + startTime + ", finishTime=" + finishTime + ']'
        );

        System.clearProperty(IGNITE_REBALANCE_STATISTICS_TIME_INTERVAL);

        currTime = U.currentTimeMillis();

        log.info("Rebalance time: " + (currTime - startTime));

        long diff = finishTime - currTime;

        assertTrue("Expected less than 10000, but actual: " + diff, Math.abs(diff) < 10_000L);
    }

    /**
     * @throws Exception If failed.
     */
    public void testRebalanceDelay() throws Exception {
        Ignite ig1 = startGrid(1);

        final IgniteCache<Object, Object> cache = ig1.cache(CACHE3);

        for (int i = 0; i < 10000; i++)
            cache.put(i, CACHE3 + "-" + i);

        long beforeStartTime = U.currentTimeMillis();

        startGrid(2);
        startGrid(3);

        waitForCondition(new PA() {
            @Override public boolean apply() {
                return cache.localMetrics().getRebalancingStartTime() != -1L;
            }
        }, 5_000);

        assert(cache.localMetrics().getRebalancingStartTime() < U.currentTimeMillis() + REBALANCE_DELAY);
        assert(cache.localMetrics().getRebalancingStartTime() > beforeStartTime + REBALANCE_DELAY);
    }
}


text:
import { Component, OnInit }   from '@angular/core';
import { Router, ActivatedRoute, NavigationStart, NavigationEnd } from '@angular/router';
import { Hero, HeroService }   from './hero.service';
import { Subscription }       from 'rxjs/Subscription';
import { SpinnerService } from '../core/spinner/spinner.service';

@Component({
  template: `

HEROES

      Hero name: <input #heroName />
      <button (click)="add(heroName.value); heroName.value=''">
        Add
     </button>

        {{hero.id}} {{hero.name}}
        <button class="delete"
      (click)="delete(hero); $event.stopPropagation()">x</button>

    {{selectedHero.name | uppercase}} is my hero

  <button (click)="gotoDetail()">View Details</button>

  `
})
export class HeroListComponent implements OnInit {

  private selectedId: number;
  private sub: Subscription;
  selectedHero: Hero;

  heroes: Hero[];
  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private service: HeroService) { }

  ngOnInit() {
    this.sub = this.route
      .params
      .subscribe(params => {
        this.selectedId = +params['id'];
        this.service.getHeroes()
          .then(heroes => this.heroes = heroes);
      });

  }

  isSelected(hero: Hero) { return hero.id === this.selectedId; }

  onSelect(hero: Hero) {
    this.router.navigate(['/hero', hero.id]);
  }

   ngOnDestroy() {
    this.sub.unsubscribe();
  }

  add(name: string): void {
    name = name.trim();
    if (!name) { return; }
    this.service.create(name)
      .then(hero => {
        this.heroes.push(hero);
        this.selectedHero = null;
      });
  }
  delete(hero: Hero): void {
    this.service
        .delete(hero.id)
        .then(() => {
          this.heroes = this.heroes.filter(h => h !== hero);
          if (this.selectedHero === hero) { this.selectedHero = null; }
        });
  }

  gotoDetail(): void {
    this.router.navigate(['/detail', this.selectedHero.id]);
  }
}


text:
package com.yameguun.sample;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

	private int count = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		Button button = (Button) this.findViewById(R.id.countbutton);
		button.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {

				count += 1;

				Intent intent=new Intent();
				intent.setAction("org.adw.launcher.counter.SEND");
				intent.putExtra("PNAME", "com.yameguun.sample");
				intent.putExtra("COUNT", count);
				sendBroadcast(intent);
			}
		});
	}
}


text:
PDT19
=====

Training 'Programming for testers, group 19'


text:
FROM python:2.7.12-alpine
MAINTAINER Gaston Severina <gseverina@gmail.com>

RUN apk update

# install ansible
RUN apk add ansible