text:
#ifndef __HISTORY_SCENE_H__
#define __HISTORY_SCENE_H__

#include "../BaseScene.h"
#include "../cocos-wheels/CWTableView.h"

struct Record;

struct RecordTexts {
    const Record *source;
    const char *title;
    std::string time;
    std::string players[4];
    int seats[4];
};

struct FilterIndex {
    size_t real_index;
    uint8_t player_flag;
};

class RecordHistoryScene : public BaseScene, cw::TableViewDelegate {
public:
    typedef std::function<void (Record *)> ViewCallback;

    CREATE_FUNC_WITH_PARAM_1(RecordHistoryScene, ViewCallback &&, viewCallback);
    bool init(ViewCallback &&viewCallback);

    static void modifyRecord(const Record *record);

    virtual void onEnter() override;

private:
    std::vector<RecordTexts> _recordTexts;

    struct FilterCriteria {
        time_t start_time;
        time_t finish_time;
        bool ignore_case;
        bool whole_word;
        bool regular_enabled;
        char name[64];
        char title[128];
    };
    FilterCriteria _filterCriteria;
    std::vector<FilterIndex> _filterIndices;

    void filter();
    void refresh();
    void updateRecordTexts();

    virtual ssize_t numberOfCellsInTableView(cw::TableView *table) override;
    virtual float tableCellSizeForIndex(cw::TableView *table, ssize_t idx) override;
    virtual cw::TableViewCell *tableCellAtIndex(cw::TableView *table, ssize_t idx) override;

    void onMoreButton(cocos2d::Ref *sender);
    void showFilterAlert();
    void switchToSummary();
    void switchToBatchDelete();
    void showTransmissionAlert();

    void showSendAlert(std::vector<bool> selectFlags);
    void showRecvAlert();

    void onDeleteButton(cocos2d::Ref *sender);
    void onCellClicked(cocos2d::Ref *sender);

    void saveRecordsAndRefresh();

    cocos2d::Label *_emptyLabel = nullptr;
    cw::TableView *_tableView = nullptr;
    ViewCallback _viewCallback;
};

#endif


text:
require 'spec_helper'

describe MerchantESolutions::DetailRecord do
  let(:csv_header) { ["Merchant Id","DBA Name","Term Num","Batch Num","Batch Date","Tran Date","Card Type","Card Number","Reference","Purchase Id","Auth Code","Entry Mode","Tran Amount","Trident Tran Id","Client Ref Num"] }

  describe "#initialize" do
    subject { MerchantESolutions::DetailRecord.new(csv_row) }

    # "Merchant Id","DBA Name","Term Num","Batch Num","Batch Date","Tran Date","Card Type","Card Number","Reference","Purchase Id","Auth Code","Entry Mode","Tran Amount","Trident Tran Id","Client Ref Num"

    let(:csv_row) { CSV::Row.new(csv_header, [42, "Hamazon", 1, 220, "10/07/2013", "10/06/2013", "AM", "000000xxxxxx1234", "'0000213", "AAAAAAAAAAA0", "100000", "KEYED", 7.09, "T.T.ID", "clientRefNumber"]) }

    its(:organization_id) { should == 42 }
    its(:organization_name) { should == "Hamazon" }
    its(:term_number) { should == 1 }
    its(:batch_number) { should == 220 }
    it "parses out the transaction date" do
      subject.batch_date.day.should == 7
      subject.batch_date.month.should == 10
      subject.batch_date.year.should == 2013
    end
    it "parses out the transaction date" do
      subject.transaction_date.day.should == 6
      subject.transaction_date.month.should == 10
      subject.transaction_date.year.should == 2013
    end
    its("transaction_date.month") { should == 10 }
    its(:card_code) { should == "AM" }
    its(:card_number) { should == "000000xxxxxx1234" }
    its(:reference_number) { should == "0000213"}
    its(:purchase_id) { should == "AAAAAAAAAAA0" }
    its(:auth_code) { should == "100000" }
    its(:entry_mode) { should == "KEYED" }
    its(:transaction_amount) { should == 7.09 }
    its(:trident_transaction_id) { should == "T.T.ID" }
    its(:client_reference_number) { should == "clientRefNumber" }
  end

  describe "#reference_number" do
    let(:reference_number) { "'0000213" }
    let(:csv_row) { CSV::Row.new(csv_header, [nil, nil, nil, nil, nil, nil, nil, nil, reference_number]) }
    let(:record) { MerchantESolutions::DetailRecord.new(csv_row)}

    context "when no arguments are given" do
      it "removes the pre-pended apostrophe from the reference number" do
        record.reference_number.should == "0000213"
      end
    end

    context "when the :unchanged option is set to true" do
      it "returns the reference number verbatim, the pre-pended apostrophe intact" do
        record.reference_number(:unchanged => true).should == "'0000213"
      end
    end

    context "when the reference number doesn't contain an apostrophe" do
      let (:reference_number) { "0000213" }

      it "returns the reference number verbatim, regardless of the :unchanged argument" do
        record.reference_number.should == "0000213"
        record.reference_number(:unchanged => true).should == "0000213"
      end
    end
  end

  describe "#purchase_id" do
    let(:purchase_id) { " AAA0    " }
    let(:csv_row) { CSV::Row.new(csv_header, [nil, nil, nil, nil, nil, nil, nil, nil, nil, purchase_id]) }
    let(:record) { MerchantESolutions::DetailRecord.new(csv_row)}

    context "when no arguments are given" do
      it "strips whitespace from the purchase id" do
        record.purchase_id.should == "AAA0"
      end
    end

    context "when the :unchanged options is set to true" do
      it "returns the purchase id verbatim, whitespace intact" do
        record.purchase_id(:unchanged => true).should == purchase_id
      end
    end

    context "when the purchase id doesn't contains any spaces" do
      let(:purchase_id) { "AAA0" }

      it "returns the purchase id verbatim, regardless of the :unchanged argument" do
        record.purchase_id.should == "AAA0"
        record.purchase_id(:unchanged => true).should == "AAA0"
      end
    end
  end

  describe "credit cards" do
    let(:csv_row) { CSV::Row.new(csv_header, [nil, nil, nil, nil, nil, nil, card_code]) }
    subject { MerchantESolutions::DetailRecord.new(csv_row) }

    context "when the code is AM" do
      let(:card_code) { "AM" }
      its(:credit_company) { should == "American Express" }
    end
    context "when the code is DS" do
      let(:card_code) { "DS" }
      its(:credit_company) { should == "Discover" }
      its(:credit_type) { should == "Credit" }
    end
    context "when the code is MB" do
      let(:card_code) { "MB" }
      its(:credit_company) { should == "MasterCard" }
      its(:credit_type) { should == "Business" }
    end
    context "when the code is MC" do
      let(:card_code) { "MC" }
      its(:credit_company) { should == "MasterCard" }
      its(:credit_type) { should == "Credit" }
    end
    context "when the code is MD" do
      let(:card_code) { "MD" }
      its(:credit_company) { should == "MasterCard" }
      its(:credit_type) { should == "Debit" }
    end
    context "when the code is VB" do
      let(:card_code) { "VB" }
      its(:credit_company) { should == "Visa" }
      its(:credit_type) { should == "Business" }
    end
    context "when the code is VD" do
      let(:card_code) { "VD" }
      its(:credit_company) { should == "Visa" }
      its(:credit_type) { should == "Debit" }
    end
    context "when the code is VS" do
      let(:card_code) { "VS" }
      its(:credit_company) { should == "Visa" }
      its(:credit_type) { should == "Credit" }
    end
    context "when the code is unknown" do
      let(:card_code) { "something you've never seen" }
      its(:credit_company) { should == card_code }
      its(:credit_type) { should be_nil }
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
`attest-tool` is a simple utility to exercise attestation-related operations on your system.

## Building attest-tool

If your system has git and a [Go 1.15+ compiler](https://golang.org/dl/) installed, you can
install `attest-tool` from source by running the following commands:

```shell
git clone 'https://github.com/google/go-attestation' && cd go-attestation/attest/attest-tool
go build -o attest-tool ./ # compiled to ./attest-tool
```

## Testing attestation readiness

The main use-case of `attest-tool` is testing whether attestation works on the local system.

Once `attest-tool` has been built, you can run it in self-test mode like this:

```shell
./attest-tool self-test
```

After a few seconds, it should print out a 'PASS' message, or a 'FAIL' message with a
description of what went wrong.

On Linux, `attest-tool` either needs to be run as root, or granted access to the TPM (`/dev/tpmrm0`) device
& event log (`/sys/kernel/security/tpm0/binary_bios_measurements`)


text:
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".")

function Stop-Pester()
{
	[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
	PARAM
	(
		$message = "EMERGENCY: Script cannot continue."
	)

	$msg = $message;
	$e = New-CustomErrorRecord -msg $msg -cat OperationStopped -o $msg;
	$PSCmdlet.ThrowTerminatingError($e);
}

Describe "ExternalNode.Tests" -Tags "ExternalNode.Tests" {
	. "$here\$sut"

	$entityPrefix = "TestItem-";
	$usedEntitySets = @("Nodes", "ExternalNodes", "ExternalNodeBags");
	$nodeEntityKindId = [biz.dfch.CS.Appclusive.Public.Constants+EntityKindId]::Node.value__;

	Context "#CLOUDTCL-2199-ExternalNodeTests" {

		BeforeEach {
			$moduleName = 'biz.dfch.PS.Appclusive.Client';
			Remove-Module $moduleName -ErrorAction:SilentlyContinue;
			Import-Module $moduleName;

			$svc = Enter-Appclusive;

			$currentTenant = Get-ApcTenant -Current -Svc $Svc;
			$nodeParentId = $currentTenant.NodeId;
		}

		AfterEach {
            $svc = Enter-Appclusive;
            $entityFilter = "startswith(Name, '{0}')" -f $entityPrefix;

            foreach ($entitySet in $usedEntitySets)
            {
                $entities = $svc.Core.$entitySet.AddQueryOption('$filter', $entityFilter) | Select;

                foreach ($entity in $entities)
                {
                    Remove-ApcEntity -svc $svc -Id $entity.Id -EntitySetName $entitySet -Confirm:$false;
                }
            }
        }

        It "Create-Get-Delete-ExternalNode" -Test {
			#ARRANGE
            $nodeName = $entityPrefix + "node";
			$extName = $entityPrefix + "externalnode";
			$extType = "ArbitraryType";

			#ACT create node
			$newNode = New-ApcNode -Name $nodeName -ParentId $nodeParentId -EntityKindId $nodeEntityKindId -svc $svc;

			#get Id of the node
			$nodeId = $newNode.Id;

			#create external node
			$extNode = New-ApcExternalNode -name $extName -NodeId $nodeId -ExternalId $nodeId -ExternalType $extType -svc $svc | select;

			#get id of external node
			$extNodeId = $extNode.Id;

			#ASSERT external Node
			$extNode | Should Not Be $null;
            $extNode | Should BeOfType [biz.dfch.CS.Appclusive.Api.Core.ExternalNode];
            $extNode.NodeId | Should Be $nodeId;
            $extNode.ExternalId | Should Be $nodeId;
            $extNode.ExternalType | Should Be $extType;
            $extNode.Name | Should Be $extName;

			#ACT Get the external-node using Get-ApcExternalNode
			$loadedextNode = Get-ApcExternalNode -Id $extNodeId -svc $svc;

			#ASSERT the node we get is the same
			$loadedextNode | Should Not Be $null;
            $loadedextNode | Should BeOfType [biz.dfch.CS.Appclusive.Api.Core.ExternalNode];
            $loadedextNode.NodeId | Should Be $nodeId;
            $loadedextNode.ExternalId | Should Be $nodeId;
            $loadedextNode.ExternalType | Should Be $extType;
            $loadedextNode.Name | Should Be $extName;

			#ACT delete external node
			$svc.Core.DeleteObject($loadedextNode);
			$result = $svc.Core.SaveChanges();

			#ASSERT external node is deleted
			$result.StatusCode | Should Be 204;
			$query = "Id eq {0}" -f $extNodeId;
			$deletedExtNode = $svc.Core.ExternalNodes.AddQueryOption('$filter', $query) | select;
			$deletedExtNode | Should Be $null;

			#CLEANUP delete node
			Remove-ApcNode -svc $svc -Id $nodeId -Confirm:$false;
        }

        It "Create-Get-ExternalNodeBags" -Test {
			#ARRANGE
            $nodeName = $entityPrefix + "node";
			$extName = $entityPrefix + "externalnode";
			$extType = "ArbitraryType";

			#ACT create node
			$newNode = New-ApcNode -Name $nodeName -ParentId $nodeParentId -EntityKindId $nodeEntityKindId -svc $svc;

			#get Id of the node
			$nodeId = $newNode.Id;
			$nodeEntityKindId = $newNode.EntityKindId;

			#create external node
			$extNode = New-ApcExternalNode -name $extName -NodeId $nodeId -ExternalId $nodeId -ExternalType $extType -svc $svc | select;

			#get id of external node
			$extNodeId = $extNode.Id;

			#ASSERT external Node
			$extNode | Should Not Be $null;
            $extNode | Should BeOfType [biz.dfch.CS.Appclusive.Api.Core.ExternalNode];
            $extNode.NodeId | Should Be $nodeId;
            $extNode.ExternalId | Should Be $nodeId;
            $extNode.ExternalType | Should Be $extType;
            $extNode.Name | Should Be $extName;

            $countOfBags = 10;

            for($i = 1; $i -le $countOfBags; $i++)
            {
                $nodeBagName = ("{0}-Name-{1}" -f $nodeName,$i);
                $nodeBagValue = ("{0}-Value-{1}" -f $nodeName,$i);

                $null = Create-ExternalNodeBag -Name $nodeBagName -ExternalNodeId $extNodeId -Value $nodeBagValue -Svc $svc;
            }

			#get the external node bags with specific id
            $nodeBagsFilter = "ExternaldNodeId eq {0}" -f $extNodeId;
            $createdNodeBags = $svc.Core.ExternalNodeBags.AddQueryOption('$filter', $nodeBagsFilter) | Select;

			#ASSERT  count of external node bags
            $createdNodeBags.Count | Should Be $countOfBags;
        }

        It "Update-ExternalNode" -Test {
			#ARRANGE
            $nodeName = $entityPrefix + "node";
			$extName = $entityPrefix + "externalnode";
			$extType = "ArbitraryType";

			#ACT create node
			$newNode = New-ApcNode -Name $nodeName -ParentId $nodeParentId -EntityKindId $nodeEntityKindId -svc $svc;

			#get Id of the node
			$nodeId = $newNode.Id;

			#create external node
			$extNode = New-ApcExternalNode -name $extName -NodeId $nodeId -ExternalId $nodeId -ExternalType $extType -svc $svc | select;

			#get id of external node
			$extNodeId = $extNode.Id;

			#ASSERT external Node
			$extNode | Should Not Be $null;
            $extNode | Should BeOfType [biz.dfch.CS.Appclusive.Api.Core.ExternalNode];
            $extNode.NodeId | Should Be $nodeId;
            $extNode.ExternalId | Should Be $nodeId;
            $extNode.ExternalType | Should Be $extType;
            $extNode.Name | Should Be $extName;

			#ACT Update external Node
			$newExtName = $extName + " Updated";
			$newExtDescription = "Description Updated";
			$newExtType = "Arbitrary-Type-Updated";
			$newExtId = ("Arbitrary-Id-{0}-Updated" -f $nodeId);

			$updatedExternalNode = Update-ExternalNode -Svc $svc -externalNodeId $extNodeId -UpdatedName $newExtName -UpdatedDescription $newExtDescription -UpdatedExternalType $newExtType -UpdatedExternalId $newExtId;

			#CLEANUP delete Node - external node is deleted automatically
			Remove-ApcNode -svc $svc -Id $nodeId -Confirm:$false;
        }

        It "Update-ExternalNodeBag" -Test {
			#ARRANGE
            $nodeName = $entityPrefix + "node";
			$extName = $entityPrefix + "externalnode";
			$extType = "ArbitraryType";
			$extBagName = $entityPrefix + "ExternalNodeBag";
            $extBagValue = ("{0}-Value" -f $nodeName);

			#ACT create node
			$newNode = New-ApcNode -Name $nodeName -ParentId $nodeParentId -EntityKindId $nodeEntityKindId -svc $svc;

			#get Id of the node
			$nodeId = $newNode.Id;
			$nodeEntityKindId = $newNode.EntityKindId;

			#create external node
			$extNode = New-ApcExternalNode -name $extName -NodeId $nodeId -ExternalId $nodeId -ExternalType $extType -svc $svc | select;

			#get id of external node
			$extNodeId = $extNode.Id;

			#ASSERT external Node
			$extNode | Should Not Be $null;
            $extNode | Should BeOfType [biz.dfch.CS.Appclusive.Api.Core.ExternalNode];
            $extNode.NodeId | Should Be $nodeId;
            $extNode.ExternalId | Should Be $nodeId;
            $extNode.ExternalType | Should Be $extType;
            $extNode.Name | Should Be $extName;

			#ACT create external node bag
            $extNodeBag = Create-ExternalNodeBag -Name $extBagName -ExternalNodeId $extNodeId -Value $extBagValue -Svc $svc;

			#get id of external node bag
			$extNodeBagId = $extNodeBag.Id;

			#ACT Update external Node
			$newName = $extBagName + " Updated";
			$newDescription = "Description Updated";
			$newValue = $extBagValue + " Updated";

			$updatedExternalNode = Update-ExternalNodeBag -Svc $svc -ExternalNodeBagId $extNodeBagId -UpdatedName $newName -UpdatedDescription $newDescription -UpdatedValue $newValue;

			#CLEANUP delete Node - external node and external node bags are deleted automatically
			Remove-ApcNode -svc $svc -Id $nodeId -Confirm:$false;
        }

        It "Delete-ExternalNode-Deletes-ExtNodeBag" -Test {
			#ARRANGE
            $nodeName = $entityPrefix + "node";
			$extName = $entityPrefix + "externalnode";
			$extType = "ArbitraryType";
			$extBagName = $entityPrefix + "ExternalNodeBag";
            $extBagValue = ("{0}-Value" -f $nodeName);

			#ACT create node
			$newNode = New-ApcNode -Name $nodeName -ParentId $nodeParentId -EntityKindId $nodeEntityKindId -svc $svc;

			#get Id of the node
			$nodeId = $newNode.Id;
			$nodeEntityKindId = $newNode.EntityKindId;

			#create external node
			$extNode = New-ApcExternalNode -name $extName -NodeId $nodeId -ExternalId $nodeId -ExternalType $extType -svc $svc | select;

			#get id of external node
			$extNodeId = $extNode.Id;

			#ASSERT external Node
			$extNode | Should Not Be $null;
            $extNode | Should BeOfType [biz.dfch.CS.Appclusive.Api.Core.ExternalNode];
            $extNode.NodeId | Should Be $nodeId;
            $extNode.ExternalId | Should Be $nodeId;
            $extNode.ExternalType | Should Be $extType;
            $extNode.Name | Should Be $extName;

			#ACT create external node bag
            $extNodeBag = Create-ExternalNodeBag -Name $extBagName -ExternalNodeId $extNodeId -Value $extBagValue -Svc $svc;

			#get id of external node bag
			$extNodeBagId = $extNodeBag.Id;

			#ACT delete external node
			$svc.Core.DeleteObject($extNode);
			$result = $svc.Core.SaveChanges();

			#ASSERT that external node bag is deleted too
			$query = "Id eq {0}" -f $extNodeBagId;
			$loadedExtNodeBag = $svc.Core.ExternalNodeBags.AddQueryOption('$filter', $query) | select;
			$loadedExtNodeBag | Should Be $null;
			$loadedExtNodeBag.Id | Should Be $null;
		}
    }
}

#
# Copyright 2016 d-fens GmbH
#
# 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.
#


text:
using System;

namespace EasyNetQ;

/// <summary>
///     Represents a consumed message
/// </summary>
public readonly struct ConsumedMessage
{
    /// <summary>
    ///     Creates ConsumedMessage
    /// </summary>
    /// <param name="receivedInfo">The received info</param>
    /// <param name="properties">The properties</param>
    /// <param name="body">The body</param>
    public ConsumedMessage(MessageReceivedInfo receivedInfo, MessageProperties properties, in ReadOnlyMemory<byte> body)
    {
        ReceivedInfo = receivedInfo;
        Properties = properties;
        Body = body;
    }

    /// <summary>
    ///     A received info associated with the message
    /// </summary>
    public MessageReceivedInfo ReceivedInfo { get; }

    /// <summary>
    ///     Various message properties
    /// </summary>
    public MessageProperties Properties { get; }

    /// <summary>
    ///     The message body
    /// </summary>
    public ReadOnlyMemory<byte> Body { get; }
}


text:
function GAMIT_Net_Retro_Pro_Interaction(targetTime,nTrials,lowCognitiveLoad,highCognitiveLoad,showGraphics,exportRawData,wt1,wt2)
%
% Demonstrate how the retrospective and prospective time estimates are
% calculated in the GAMIT model.

if nargin < 1
    targetTime = 650;
end
if nargin<2
    nTrials = 20;
end
if nargin<3
    lowCognitiveLoad = 0.95;
    highCognitiveLoad = 1.05;
end
if nargin<5
    showGraphics = true;
end
if nargin<6
    exportRawData = true;
end
relativeEstimates = true; % divide through by targetTime
params = GAMIT_Params();
if nargin <8
    %step 1: Get default params & generate a reference curve
    nCurves = 100;
    nSamples = 500;
    [wt1, wt2] = GAMIT_Learning(params,nCurves,nSamples);
else
    %already generated weights;
end

testTimes = targetTime * ones(1,nTrials);

%%% RETROSPECTIVE %%%
retrospectiveLow = GAMIT_Net(testTimes,lowCognitiveLoad,false,false,params,wt1, wt2);
retrospectiveHigh = GAMIT_Net(testTimes,highCognitiveLoad,false,false,params,wt1, wt2);

%%% PROSPECTIVE %%%
prospectiveLow = GAMIT_Net(testTimes,lowCognitiveLoad,true,false,params,wt1, wt2);
prospectiveHigh = GAMIT_Net(testTimes,highCognitiveLoad,true,false,params,wt1, wt2);

if exportRawData
%     t = table(retrospectiveLow,retrospectiveHigh,prospectiveLow,prospectiveHigh);
%     writetable(t,'GAMIT_Retro_Pro_Interaction.csv','Delimiter',',');
    tdata=[retrospectiveLow,retrospectiveHigh,prospectiveLow,prospectiveHigh];
    csvwrite('GAMIT_Retro_Pro_Interaction.csv',tdata );
    save('GAMIT_Retro_Pro_Params.mat','params');
end

if showGraphics
    %Graphics code shows interaction plot like Block, Hancock & Zakay 2010
    figure(1);
    clf(1);
    %load coordinates
    xC = [lowCognitiveLoad, highCognitiveLoad];
    %get retrospective 'coordinates'
    yR = [mean(retrospectiveLow),mean(retrospectiveHigh)];
    yeR = [std(retrospectiveLow),std(retrospectiveHigh)];
    yeR = yeR /sqrt(length(retrospectiveLow));
    %get retrospective 'coordinates'
    yP = [mean(prospectiveLow),mean(prospectiveHigh)];
    yeP = [std(prospectiveLow),std(prospectiveHigh)];
    yeP = yeP /sqrt(length(prospectiveLow));
    if relativeEstimates
        yR = yR/targetTime;
        yeR = yeR/targetTime;
        yP = yP/targetTime;
        yeP = yeP/targetTime;
    end

    hold on;
    %plot lines
    %offset second set of xcoords slightly for ease of view
    xCprime = xC+diff(xC)*.02;
%     line(xC, yR,'Color','k','LineStyle','--','Marker','o');
%     line(xCprime, yP,  'Color','k','Marker','o');
    %plot error bars
    errorbar(xC,yR,yeR,'Color','k','LineStyle','--','Marker','o');
    errorbar(xCprime,yP,yeP,'Color','k','Marker','o');
    legend('Retrospective','Prospective','Location','best');

    hold off;
    xlabel('Relative Cognitve Load (Normal load = 1.0)');
    if relativeEstimates
        ylabel('Mean Duration Judgement Ratio');
    else
        ylabel('Mean Time Estimates');
    end
%     title('Interaction of retrospective & prospective time estimates with cognitive load');
    figureHandle = gcf;
    %# make all text in the figure to size 14 and bold
    set(findall(figureHandle,'type','text'),'fontSize',14,'fontWeight','bold')
end


text:
Authors
=======

Code
----

 - Grokzen (https://github.com/Grokzen)
 - Markbaas (https://github.com/markbaas)
 - Gonditeniz (https://github.com/gonditeniz)
 - Comagnaw (https://github.com/comagnaw)
 - Cogwirrel (https://github.com/cogwirrel)

Testing
-------

 - Glenn Schmottlach (https://github.com/gschmottlach-xse)

Documentation
-------------

 - Grokzen (https://github.com/Grokzen)
 - Scott Lowe (https://github.com/scottclowe)


text:
#include <uecho/frame/server.h>

/****************************************
* uecho_server_new
****************************************/

uEchoServer* uecho_server_new(void)
{
  uEchoServer* server;

  server = (uEchoServer*)malloc(sizeof(uEchoServer));

  if (!server)
    return NULL;

  server->udp_servers = uecho_udp_serverlist_new();
  server->mcast_servers = uecho_mcast_serverlist_new();
  server->msg_mgr = uecho_message_observer_manager_new();

  uecho_server_setoption(server, uEchoOptionNone);

  return server;
}

/****************************************
* uecho_server_delete
****************************************/

bool uecho_server_delete(uEchoServer* server)
{
  if (!server)
    return false;

  uecho_udp_serverlist_delete(server->udp_servers);
  uecho_mcast_serverlist_delete(server->mcast_servers);
  uecho_message_observer_manager_delete(server->msg_mgr);

  free(server);

  return true;
}

/****************************************
 * uecho_server_isboundaddress
 ****************************************/

bool uecho_server_isboundaddress(uEchoServer* server, const char* addr)
{
  if (!server)
    return false;

  if (uecho_udp_serverlist_isboundaddress(server->udp_servers, addr))
    return true;

  if (uecho_mcast_serverlist_isboundaddress(server->mcast_servers, addr))
    return true;

  return false;
}

/****************************************
 * uecho_server_start
 ****************************************/

bool uecho_server_start(uEchoServer* server)
{
  bool all_actions_succeeded = true;
  uEchoMessageObserver* observer;
  uEchoMessageHandler handler;
  void* obj;
  uEchoUdpServer* udp_server;
  uEchoMcastServer* mcast_server;

  if (!server)
    return false;

  uecho_server_stop(server);

  all_actions_succeeded &= uecho_mcast_serverlist_open(server->mcast_servers);
  if (uecho_server_isudpserverenabled(server)) {
    all_actions_succeeded &= uecho_udp_serverlist_open(server->udp_servers);
  }

  // Add message observers
  for (observer = uecho_message_observer_manager_getobservers(server->msg_mgr); observer; observer = uecho_message_observer_next(observer)) {
    handler = uecho_message_observer_gethandler(observer);
    obj = uecho_message_observer_getobjcet(observer);
    if (!handler || !obj) {
      all_actions_succeeded = false;
      continue;
    }
    for (udp_server = uecho_udp_serverlist_gets(server->udp_servers); udp_server; udp_server = uecho_udp_server_next(udp_server)) {
      all_actions_succeeded &= uecho_udp_server_addobserver(udp_server, obj, handler);
    }
    for (mcast_server = uecho_mcast_serverlist_gets(server->mcast_servers); mcast_server; mcast_server = uecho_mcast_server_next(mcast_server)) {
      all_actions_succeeded &= uecho_mcast_server_addobserver(mcast_server, obj, handler);
    }
  }

  all_actions_succeeded &= uecho_mcast_serverlist_start(server->mcast_servers);
  if (uecho_server_isudpserverenabled(server)) {
    all_actions_succeeded &= uecho_udp_serverlist_start(server->udp_servers);
  }

  if (!all_actions_succeeded) {
    uecho_server_stop(server);
  }

  return all_actions_succeeded;
}

/****************************************
 * uecho_server_stop
 ****************************************/

bool uecho_server_stop(uEchoServer* server)
{
  bool all_actions_succeeded;

  if (!server)
    return false;

  all_actions_succeeded = true;

  all_actions_succeeded &= uecho_mcast_serverlist_close(server->mcast_servers);
  all_actions_succeeded &= uecho_mcast_serverlist_stop(server->mcast_servers);
  uecho_udp_serverlist_clear(server->mcast_servers);

  all_actions_succeeded &= uecho_udp_serverlist_close(server->udp_servers);
  all_actions_succeeded &= uecho_udp_serverlist_stop(server->udp_servers);
  uecho_udp_serverlist_clear(server->udp_servers);

  return all_actions_succeeded;
}

/****************************************
 * uecho_server_isrunning
 ****************************************/

bool uecho_server_isrunning(uEchoServer* server)
{
  bool all_actions_succeeded;

  if (!server)
    return false;

  all_actions_succeeded = true;
  all_actions_succeeded &= uecho_mcast_serverlist_isrunning(server->mcast_servers);

  if (uecho_server_isudpserverenabled(server)) {
    all_actions_succeeded &= uecho_udp_serverlist_isrunning(server->udp_servers);
  }

  return all_actions_succeeded;
}

/****************************************
 * uecho_server_postannounce
 ****************************************/

const char* uecho_server_getaddress(uEchoServer* server)
{
  uEchoMcastServer* mcast_server;

  for (mcast_server = uecho_mcast_serverlist_gets(server->mcast_servers); mcast_server; mcast_server = uecho_mcast_server_next(mcast_server)) {
    return uecho_mcast_server_getaddress(mcast_server);
  }

  return "";
}

/****************************************
 * uecho_server_sendto
 ****************************************/

bool uecho_server_sendto(uEchoServer* server, const char* addr, int port, byte* msg, size_t msg_len)
{
  uEchoSocket* sock;
  size_t sent_byte_cnt;

  sock = uecho_socket_dgram_new();
  if (!sock)
    return false;

  sent_byte_cnt = uecho_socket_sendto(sock, addr, port, msg, msg_len);
  uecho_socket_delete(sock);
  return (msg_len == sent_byte_cnt) ? true : false;
}

/****************************************
 * uecho_server_postannounce
 ****************************************/

bool uecho_server_postannounce(uEchoServer* server, byte* msg, size_t msg_len)
{
  if (!server)
    return false;

  if (uecho_mcast_serverlist_post(server->mcast_servers, msg, msg_len))
    return true;

  return uecho_server_sendto(server, uEchoMulticastAddr, uEchoUdpPort, msg, msg_len);
}

/****************************************
 * uecho_server_postresponse
 ****************************************/

bool uecho_server_postresponse(uEchoServer* server, const char* addr, byte* msg, size_t msg_len)
{
  if (!server)
    return false;

  if (uecho_udp_serverlist_sendto(server->udp_servers, addr, msg, msg_len))
    return true;

  return uecho_server_sendto(server, addr, uEchoUdpPort, msg, msg_len);
}

/****************************************
 * uecho_server_addobserver
 ****************************************/

bool uecho_server_addobserver(uEchoServer* server, void* obj, uEchoMessageHandler handler)
{
  return uecho_message_observer_manager_addobserver(server->msg_mgr, obj, handler);
}


text:
fcViews.resourceDay = ResourceDayView;

function ResourceDayView(element, calendar) {
	var t = this;

	// exports
	t.render = render;

	// imports
	ResourceView.call(t, element, calendar, 'resourceDay');
	var opt = t.opt;
	var renderAgenda = t.renderAgenda;
	var skipHiddenDays = t.skipHiddenDays;
	var getCellsPerWeek = t.getCellsPerWeek;
	var formatDates = calendar.formatDates;

	function render(date, delta) {
		if (delta) {
			addDays(date, delta);
		}
		skipHiddenDays(date, delta < 0 ? -1 : 1);

		var start = cloneDate(date, true);
		var end = addDays(cloneDate(start), 1);

		t.title = formatDate(date, opt('titleFormat'));

		t.start = t.visStart = start;
		t.end = t.visEnd = end;

		var colCnt = opt('resources').length;
		renderAgenda(colCnt);
	}

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: danny
 * Date: 20/11/14
 * Time: 06:48 PM
 */
?>

Colecciones

                        <?php foreach($collections as $key) {?>

                                <a class="filteroascollection" href="<?=base_url()?>main/oas_objects_per_collection/<?=$key["idcollection"]?>"><?php echo $key["name"]; ?> (<?=$numoas_collection[$key["idcollection"].$key["name"]]?>)

                                    <?php foreach($subcollections as $key2){
                                        if($key2["idcollection"]==$key["idcollection"]){ ?>

<a href="<?=base_url()?>main/oas_objects_per_subcollection/<?=$key["idcollection"]?>/<?=$key2["idsubcollection"]?>"><?php echo $key2["name"]; ?>(<?=$numoas_subcollections[$key2["idsubcollection"].$key2["name"]]?>)

                                        <?php } ?>

                                    <?php } ?>

                        <?php } ?>


text:
<?php

namespace Migrate;

use Arbor\Core\Container;
use Common\MigrateHelper;

/**
 * @package Migrate
 * @author Michal Tomczak (m.tomczak@coderdojo.org.pl)
 */
class Version20150911182900 extends MigrateHelper
{

    /**
     * {@inheritdoc}
     */
    public function update(Container $container)
    {

        $this->beginTransaction();
        $schema = $this->createSchema();
        $devices=$schema->getTable('devices');
        $devices->addColumn('hire_expiration_date','datetime',array('notnull' => false));

        $deviceLogs=$schema->getTable('device_logs');
        $deviceLogs->addColumn('hire_expiration_date','datetime',array('notnull' => false));

        $this->updateSchema($schema);

        $this->executeQuery("INSERT INTO functionalities(id,name,description) VALUES(:id,:name,:description)",array(
            'id'=>15
            ,'name'=>'Hire date prolongation'
            ,'description'=>''
        ));

        $this->executeQuery("INSERT INTO log_actions(id,name) VALUES(:id,:name)", array(
            'id' => 20,
            'name' => 'Prolongation hire date for device'
        ));

        $this->commitTransaction();

    }

    /**
     * {@inheritdoc}
     */
    public function downgrade(Container $container)
    {
        $this->beginTransaction();
        $schema = $this->createSchema();
        $devices=$schema->getTable('devices');
        $devices->dropColumn('hire_expiration_date');

        $deviceLogs=$schema->getTable('device_logs');
        $deviceLogs->dropColumn('hire_expiration_date');

        $this->updateSchema($schema);

        $this->commitTransaction();

        $this->executeQuery("DELETE FROM roles_functionalities WHERE functionality_id=:id",array(
            'id'=>15
        ));

        $this->executeQuery("DELETE FROM functionalities WHERE id=:id",array(
            'id'=>15
        ));

        $this->executeQuery("DELETE FROM device_logs WHERE log_left_id in (select id from logs where log_action_id=:id) or log_right_id in (select id from logs where log_action_id=:id)", array(
            'id' => 20
        ));

        $this->executeQuery("DELETE FROM logs WHERE log_action_id in (:id)", array(
            'id' => 20
        ));

        $this->executeQuery("DELETE FROM log_actions WHERE id in (:id)", array(
            'id' => 20
        ));

    }

}


text:
#pragma once

namespace folly {
namespace observer {

template <typename Observable, typename Traits>
class ObserverCreator<Observable, Traits>::Context {
 public:
  template <typename... Args>
  Context(Args&&... args) : observable_(std::forward<Args>(args)...) {
    updateValue();
  }

  ~Context() {
    if (value_.copy()) {
      Traits::unsubscribe(observable_);
    }
  }

  void setCore(observer_detail::Core::WeakPtr coreWeak) {
    coreWeak_ = std::move(coreWeak);
  }

  std::shared_ptr<const T> get() {
    updateRequested_ = false;
    return value_.copy();
  }

  void update() {
    // This mutex ensures there's no race condition between initial update()
    // call and update() calls from the subsciption callback.
    //
    // Additionally it helps avoid races between two different subscription
    // callbacks (getting new value from observable and storing it into value_
    // is not atomic).
    std::lock_guard<std::mutex> lg(updateMutex_);
    if (!updateValue()) {
      // Value didn't change, so we can skip the version update.
      return;
    }

    bool expected = false;
    if (updateRequested_.compare_exchange_strong(expected, true)) {
      observer_detail::ObserverManager::scheduleRefreshNewVersion(coreWeak_);
    }
  }

  template <typename F>
  void subscribe(F&& callback) {
    Traits::subscribe(observable_, std::forward<F>(callback));
  }

 private:
  bool updateValue() {
    auto newValue = Traits::get(observable_);
    auto newValuePtr = newValue.get();
    if (!newValue) {
      throw std::logic_error("Observable returned nullptr.");
    }
    value_.swap(newValue);
    return newValuePtr != newValue.get();
  }

  folly::Synchronized<std::shared_ptr<const T>> value_;
  std::atomic<bool> updateRequested_{false};

  observer_detail::Core::WeakPtr coreWeak_;

  Observable observable_;

  std::mutex updateMutex_;
};

template <typename Observable, typename Traits>
template <typename... Args>
ObserverCreator<Observable, Traits>::ObserverCreator(Args&&... args)
    : context_(std::make_shared<Context>(std::forward<Args>(args)...)) {}

template <typename Observable, typename Traits>
Observer<typename ObserverCreator<Observable, Traits>::T>
ObserverCreator<Observable, Traits>::getObserver()&& {
  // This master shared_ptr allows grabbing derived weak_ptrs, pointing to the
  // the same Context object, but using a separate reference count. Master
  // shared_ptr destructor then blocks until all shared_ptrs obtained from
  // derived weak_ptrs are released.
  class ContextMasterPointer {
   public:
    explicit ContextMasterPointer(std::shared_ptr<Context> context)
        : contextMaster_(std::move(context)),
          context_(
              contextMaster_.get(),
              [destroyBaton = destroyBaton_](Context*) {
                destroyBaton->post();
              }) {}
    ~ContextMasterPointer() {
      if (context_) {
        context_.reset();
        destroyBaton_->wait();
      }
    }
    ContextMasterPointer(const ContextMasterPointer&) = delete;
    ContextMasterPointer(ContextMasterPointer&&) = default;
    ContextMasterPointer& operator=(const ContextMasterPointer&) = delete;
    ContextMasterPointer& operator=(ContextMasterPointer&&) = default;

    Context* operator->() const {
      return contextMaster_.get();
    }

    std::weak_ptr<Context> get_weak() {
      return context_;
    }

   private:
    std::shared_ptr<folly::Baton<>> destroyBaton_{
        std::make_shared<folly::Baton<>>()};
    std::shared_ptr<Context> contextMaster_;
    std::shared_ptr<Context> context_;
  };
  // We want to make sure that Context can only be destroyed when Core is
  // destroyed. So we have to avoid the situation when subscribe callback is
  // locking Context shared_ptr and remains the last to release it.
  // We solve this by having Core hold the master shared_ptr and subscription
  // callback gets derived weak_ptr.
  ContextMasterPointer contextMaster(context_);
  auto contextWeak = contextMaster.get_weak();
  auto observer = makeObserver([context = std::move(contextMaster)]() {
    return context->get();
  });

  context_->setCore(observer.core_);
  context_->subscribe([contextWeak = std::move(contextWeak)] {
    if (auto context = contextWeak.lock()) {
      context->update();
    }
  });

  // Do an extra update in case observable was updated between observer creation
  // and setting updates callback.
  context_->update();
  context_.reset();

  return observer;
}
} // namespace observer
} // namespace folly


text:
define('ts/common/DeleteLparTest', [
    'ts/widgets/TSWidget',
    'ts/widgets/TSFormTest',
    'dojo/text!ts/common/DeleteLparTest.html',
	'dojo/css!ts/common/DeleteLpar.css',
	'dojo/nls!ts/common/dataCenter.json'
], function(TSWidget, TSFormTest, html, css, json){
	'use strict';

    var i18n = TSWidget.prototype.i18n.createBranch(json);
	function DeleteLparTest(opts){
        //CommonWidget.call(this, {html: html, css: css, json: json});
		TSFormTest.call(this);
        i18n = this.i18n;
        this.opts = null;
        this.container = null;
        this.initialize.apply(this, arguments);
	}

    var methods = {
        initialize: function(opts){
            var that = this,
                $container = this.container = $(this.rootElement),
                $listItems = null;

            this.opts = $.extend({}, opts);

            var submit = this.roles.get('submit');

            $(submit).on('click', function() {
            	if(!that.isValid()) {
            		return;
            	}

            	var originData = that.opts.data;

            	var currData = $.extend(originData, that.getFormData4EncryptPassword());

                //currData.password = $.jCryption.encryptKey(currData.password);

                $.post(that.opts.url, currData, function(data){
                    if(data.flag){
                        if(data.flag === '1'){
                            var grid = that.opts.gridWidget;
                            var lparList = that.opts.lparListWidget;
                            // grid.removeData();
                            // Dialog.alert(i18n.getMsg('delSucc'));
                            Dialog.close();
                            originData = [originData];
                            originData.forEach(function(item){
                                item.runningStatus = lparList.runningStatusMapInversion.deleting;
                            });
                            grid.updateData(originData, 'lparPcid');
                            lparList.setActionsStatus(grid, lparList.runningStatusMapInversion.deleting);
                            lparList.setActionsStatusByMaster(grid, originData);
                        }
                    }
                });
            });

            var cancel = this.roles.get('cancel');

            $(cancel).on('click', function() {
            	Dialog.close();
            });

            /*
            this.addEventListener("DOMNodeInserted",function(){
                that.createCompleteCallback();

            });
            */

        },
        loadData: function(data){
            // if(data.platformType){
            //     this.vm.platformType(data.platformType);
            //     this.vm.platformTypeEnable(false);
            // }
        },
        getData: function(keysObj){
        	return {};
            return JSON.parse(ko.toJSON(this.vm, keysObj));
        },
        createCompleteCallback: function(){

        	/*
        	var that = this;
            var originData = this.opts.data;

            ko.applyBindings(this.vm, this.container[0]);

            var formField = new CommonFormField();
            this.formField = formField;
            this.formField.placeAt(this.container, 'append');

            formField.loadData([{
                    _type: 'password',
                    _name: 'password',
                    _text: i18n.getMsg('hostPassword'),
                    _valid: {
                        required: {
                            message: i18n.getMsg('please enter the host password'),
                            params: true
                        }
                    }
                }, {
                    _isSubmitGroup: true,
                    _type: 'button',
                    _name: 'save',
                    _text: i18n.getMsg('submit'),
                    _clickCB: function(){
                        if(!this.validate()){
                            return ;
                        }
                        var currData = formField.getData(originData);
                        //currData.password = $.jCryption.encryptKey(currData.password);
                        $.post(that.opts.url, currData, function(data){
                            if(data.flag){
                                if(data.flag === '1'){
                                    var grid = that.opts.gridWidget;
                                    var lparList = that.opts.lparListWidget;
                                    // grid.removeData();
                                    // Dialog.alert(i18n.getMsg('delSucc'));
                                    Dialog.close();
                                    originData = [originData];
                                    originData.forEach(function(item){
                                        item.runningStatus = lparList.runningStatusMapInversion.deleting;
                                    });
                                    grid.updateData(originData, 'lparPcid');
                                    lparList.setActionsStatus(grid, lparList.runningStatusMapInversion.deleting);
                                    lparList.setActionsStatusByMaster(grid, originData);
                                }
                            }
                        });
                    }
                }
            ]);
            */

        },

        /*
        validate: function(){

            if (this.formField.vm.errors().length == 0) {
                //可以提交数据了.
                return true;
            } else {
                this.formField.vm.errors.showAllMessages();
                return false;
            }
        },
        req: function(data){
            var jsonData = {data: data};
            var dataInterface = {
                real: rootPath + 'xcat/XCATPlatformAction.do?method=registePlatform',
                simulate: 'xcat/host/DeleteLparSucc.json'
            };

            $.post(GUtil.getInterface(dataInterface), jsonData, function(data){
                if(data.flag == 1){
                    Dialog.close();
                }else{
                    Dialog.alert('注册失败!');
                }

            }, 'json');
        }
        */
    }

    function obj2Arr(obj){
        var arr = [];
        for(var key in obj){
            arr.push(key);
            arr.push(obj[key]);
        }
        return arr;
    }

    ExtendClass(DeleteLparTest, TSFormTest);
    InstallFunctions(DeleteLparTest.prototype, DONT_ENUM, obj2Arr(methods));

    SetProperties(DeleteLparTest.prototype,DONT_ENUM,[
        "i18n",i18n,
        "template",html
    ]);

	return DeleteLparTest;
});


text:
using EPiServer;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.Filters;
using EPiServer.Security;
using EPiServer.Shell.Security;
using System.Collections.Generic;
using System.Web.Mvc;

namespace AlloyDemo.Features.RegisterPersonas
{
    public class RegisterPersonasController : Controller
    {
        // shared password and email domain for all created users
        private const string password = "Pa$$w0rd";
        private const string email = "@alloy.com";

        // stored roles (groups) that are mapped
        private const string accessToAdminView = "AccessToAdminView"; // mapped to CmsAdmins
        private const string accessToEditView = "AccessToEditView"; // mapped to CmsEditors
        private const string personalizersRole = "Personalizers"; // mapped to VisitorGroupAdmins
        private const string developersRole = "Developers"; // mapped to EPiBetaUsers

        // virtual roles that are assigned access rights
        private const string adminsRole = "CmsAdmins"; // full access rights to Root
        private const string editorsRole = "CmsEditors"; // no access rights to Root

        // stored roles that are assigned access rights
        private const string contentCreatorsRole = "ContentCreators"; // Read, Create, Edit, Delete access rights to Root
        private const string newsEditorsRole = "NewsEditors"; // full access to News & Events
        private const string marketersRole = "Marketers"; // Create access rights to ProductPage
        private const string cLevelExecsRole = "CLevelExecs"; // approve strategic content e.g. Edit access rights for Press Releases
        private const string lawyersRole = "Lawyers"; // approve legal content e.g. Edit access rights for Press Releases

        private static string[] rolesToCreate = new[]
            { accessToAdminView, accessToEditView, newsEditorsRole, contentCreatorsRole,
            marketersRole, personalizersRole, developersRole, cLevelExecsRole, lawyersRole };

        public class UserAndRoles
        {
            public string UserName;
            public string[] Roles;
        }

        public static UserAndRoles[] Users = new[]
        {
            new UserAndRoles
            {
                UserName = "Alice", // a CMS Admin
                Roles = new[] { accessToAdminView }
            },
            new UserAndRoles
            {
                UserName = "Dana", // a Developer
                Roles = new[] { accessToAdminView, developersRole }
            },
            new UserAndRoles
            {
                UserName = "Eve", // a CMS Editor
                Roles = new[] { accessToEditView, contentCreatorsRole }
            },            new UserAndRoles
            {
                UserName = "Emily", // a CMS Editor
                Roles = new[] { accessToEditView, contentCreatorsRole }
            },
            new UserAndRoles
            {
                UserName = "Emil", // a CMS Editor
                Roles = new[] { accessToEditView, contentCreatorsRole }
            },
            new UserAndRoles
            {
                UserName = "Nick", // a News Editor
                Roles = new[] { accessToEditView, newsEditorsRole }
            },
            new UserAndRoles
            {
                UserName = "Nancy", // a News Editor
                Roles = new[] { accessToEditView, newsEditorsRole }
            },
            new UserAndRoles
            {
                UserName = "Michelle", // a Marketer
                Roles = new[] { accessToEditView, marketersRole, personalizersRole }
            },
            new UserAndRoles
            {
                UserName = "Carlos", // the CEO
                Roles = new[] { accessToEditView, cLevelExecsRole }
            },
            new UserAndRoles
            {
                UserName = "Catherine", // the CFO
                Roles = new[] { accessToEditView, cLevelExecsRole }
            },
            new UserAndRoles
            {
                UserName = "Larry", // a Lawyer
                Roles = new[] { accessToEditView, lawyersRole }
            },
            new UserAndRoles
            {
                UserName = "Laura", // a Lawyer
                Roles = new[] { accessToEditView, lawyersRole }
            },
            new UserAndRoles
            {
                UserName = "Lori", // a Lawyer
                Roles = new[] { accessToEditView, lawyersRole }
            }
        };

        private readonly IContentSecurityRepository securityRepository;
        private readonly IPageCriteriaQueryService pageFinder;
        private readonly UIUserProvider users;
        private readonly UIRoleProvider roles;

        public RegisterPersonasController(IContentSecurityRepository securityRepository,
            IPageCriteriaQueryService pageFinder,
            UIUserProvider users, UIRoleProvider roles)
        {
            this.securityRepository = securityRepository;
            this.pageFinder = pageFinder;
            this.users = users;
            this.roles = roles;
        }

        //
        // GET: /RegisterPersonas
        public ActionResult Index()
        {
            return View("~/Features/RegisterPersonas/RegisterPersonas.cshtml");
        }

        //
        // POST: /RegisterPersonas
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Index(string submit)
        {
            int countOfRolesCreated = 0;
            int countOfUsersCreated = 0;

            #region Use EPiServer classes to create roles and users

            UIUserCreateStatus status;
            IEnumerable<string> errors = new List<string>();

            foreach (string role in rolesToCreate)
            {
                if (!roles.RoleExists(role))
                {
                    roles.CreateRole(role);
                    countOfRolesCreated++;
                }
            }

            foreach (var item in Users)
            {
                if (users.GetUser(item.UserName) == null)
                {
                    var newUser = users.CreateUser(item.UserName, password,
                        email: $"{item.UserName.ToLower()}{email}",
                        passwordQuestion: null, passwordAnswer: null,
                        isApproved: true,
                        status: out status, errors: out errors);

                    if (status == UIUserCreateStatus.Success)
                    {
                        countOfUsersCreated++;
                        roles.AddUserToRoles(item.UserName, item.Roles);
                    }
                }
            }

            #endregion

            #region Use EPiServer classes to give access rights to Root, Recycle Bin, and News & Events

            SetSecurity(ContentReference.RootPage, adminsRole, AccessLevel.FullAccess);
            SetSecurity(ContentReference.RootPage, "WebAdmins", AccessLevel.NoAccess);
            SetSecurity(ContentReference.RootPage, "Administrators", AccessLevel.NoAccess);
            SetSecurity(ContentReference.RootPage, contentCreatorsRole, AccessLevel.Read | AccessLevel.Create | AccessLevel.Edit | AccessLevel.Delete);
            SetSecurity(ContentReference.RootPage, marketersRole, AccessLevel.Create | AccessLevel.Publish);

            SetSecurity(ContentReference.WasteBasket, adminsRole, AccessLevel.FullAccess);
            SetSecurity(ContentReference.WasteBasket, "Administrators", AccessLevel.NoAccess);

            // find the News & Events page
            var criteria = new PropertyCriteriaCollection
            {
                new PropertyCriteria
                {
                    Name = "PageName",
                    Type = PropertyDataType.LongString,
                    Condition = CompareCondition.Equal,
                    Value = "News & Events"
                }
            };

            var pages = pageFinder.FindPagesWithCriteria(ContentReference.StartPage, criteria);

            if (pages.Count == 1)
            {
                // give News Editors full access and remove all access for others
                var news = pages[0].ContentLink;
                SetSecurity(news, newsEditorsRole, AccessLevel.FullAccess, overrideInherited: true);
                SetSecurity(news, contentCreatorsRole, AccessLevel.NoAccess, overrideInherited: true);
                SetSecurity(news, marketersRole, AccessLevel.NoAccess, overrideInherited: true);
            }

            // find the Press Releases page
            criteria = new PropertyCriteriaCollection
            {
                new PropertyCriteria
                {
                    Name = "PageName",
                    Type = PropertyDataType.LongString,
                    Condition = CompareCondition.Equal,
                    Value = "Press Releases"
                }
            };

            pages = pageFinder.FindPagesWithCriteria(ContentReference.StartPage, criteria);

            if (pages.Count == 1)
            {
                // allow Lawyers and C-Level Execs to edit Press Releases
                // so they can approve/decline changes
                var pressReleases = pages[0].ContentLink;
                SetSecurity(pressReleases, lawyersRole, AccessLevel.Edit, overrideInherited: true);
                SetSecurity(pressReleases, cLevelExecsRole, AccessLevel.Edit, overrideInherited: true);
            }

            #endregion

            RegisterPersonas.IsEnabled = false;

            ViewData["message"] = $"Register personas completed successfully. {countOfRolesCreated} roles created. {countOfUsersCreated} users created and added to roles.";

            return View("~/Features/RegisterPersonas/RegisterPersonas.cshtml");
        }

        private void SetSecurity(ContentReference reference, string role, AccessLevel level, bool overrideInherited = false)
        {
            IContentSecurityDescriptor permissions = securityRepository.Get(reference).CreateWritableClone() as IContentSecurityDescriptor;
            if (overrideInherited)
            {
                if (permissions.IsInherited) permissions.ToLocal();
            }
            permissions.AddEntry(new AccessControlEntry(role, level));
            securityRepository.Save(reference, permissions, SecuritySaveType.Replace);
        }

        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (!RegisterPersonas.IsEnabled)
            {
                filterContext.Result = new HttpNotFoundResult();
                return;
            }
            base.OnAuthorization(filterContext);
        }
    }
}


text:
<?php

namespace Illuminate\Pagination;

use Illuminate\Contracts\Support\Arrayable;
use UnexpectedValueException;

class Cursor implements Arrayable
{
    /**
     * The parameters associated with the cursor.
     *
     * @var array
     */
    protected $parameters;

    /**
     * Determine whether the cursor points to the next or previous set of items.
     *
     * @var bool
     */
    protected $pointsToNextItems;

    /**
     * Create a new cursor instance.
     *
     * @param  array  $parameters
     * @param  bool  $pointsToNextItems
     */
    public function __construct(array $parameters, $pointsToNextItems = true)
    {
        $this->parameters = $parameters;
        $this->pointsToNextItems = $pointsToNextItems;
    }

    /**
     * Get the given parameter from the cursor.
     *
     * @param  string  $parameterName
     * @return string|null
     *
     * @throws \UnexpectedValueException
     */
    public function parameter(string $parameterName)
    {
        if (! array_key_exists($parameterName, $this->parameters)) {
            throw new UnexpectedValueException("Unable to find parameter [{$parameterName}] in pagination item.");
        }

        return $this->parameters[$parameterName];
    }

    /**
     * Get the given parameters from the cursor.
     *
     * @param  array  $parameterNames
     * @return array
     */
    public function parameters(array $parameterNames)
    {
        return collect($parameterNames)->map(function ($parameterName) {
            return $this->parameter($parameterName);
        })->toArray();
    }

    /**
     * Determine whether the cursor points to the next set of items.
     *
     * @return bool
     */
    public function pointsToNextItems()
    {
        return $this->pointsToNextItems;
    }

    /**
     * Determine whether the cursor points to the previous set of items.
     *
     * @return bool
     */
    public function pointsToPreviousItems()
    {
        return ! $this->pointsToNextItems;
    }

    /**
     * Get the array representation of the cursor.
     *
     * @return array
     */
    public function toArray()
    {
        return array_merge($this->parameters, [
            '_pointsToNextItems' => $this->pointsToNextItems,
        ]);
    }

    /**
     * Get the encoded string representation of the cursor to construct a URL.
     *
     * @return string
     */
    public function encode()
    {
        return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode(json_encode($this->toArray())));
    }

    /**
     * Get a cursor instance from the encoded string representation.
     *
     * @param  string|null  $encodedString
     * @return static|null
     */
    public static function fromEncoded($encodedString)
    {
        if (is_null($encodedString) || ! is_string($encodedString)) {
            return null;
        }

        $parameters = json_decode(base64_decode(str_replace(['-', '_'], ['+', '/'], $encodedString)), true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            return null;
        }

        $pointsToNextItems = $parameters['_pointsToNextItems'];

        unset($parameters['_pointsToNextItems']);

        return new static($parameters, $pointsToNextItems);
    }
}


text:
#include "radeon_variable.h"

#include "memory_pool.h"
#include "radeon_compiler_util.h"
#include "radeon_dataflow.h"
#include "radeon_list.h"
#include "radeon_opcodes.h"
#include "radeon_program.h"

/**
 * Rewrite the index and writemask for the destination register of var
 * and its friends to new_index and new_writemask.  This function also takes
 * care of rewriting the swizzles for the sources of var.
 */
void rc_variable_change_dst(
	struct rc_variable * var,
	unsigned int new_index,
	unsigned int new_writemask)
{
	struct rc_variable * var_ptr;
	struct rc_list * readers;
	unsigned int old_mask = rc_variable_writemask_sum(var);
	unsigned int conversion_swizzle =
			rc_make_conversion_swizzle(old_mask, new_writemask);

	for (var_ptr = var; var_ptr; var_ptr = var_ptr->Friend) {
		if (var_ptr->Inst->Type == RC_INSTRUCTION_NORMAL) {
			rc_normal_rewrite_writemask(var_ptr->Inst,
							conversion_swizzle);
			var_ptr->Inst->U.I.DstReg.Index = new_index;
		} else {
			struct rc_pair_sub_instruction * sub;
			if (var_ptr->Dst.WriteMask == RC_MASK_W) {
				assert(new_writemask & RC_MASK_W);
				sub = &var_ptr->Inst->U.P.Alpha;
			} else {
				sub = &var_ptr->Inst->U.P.RGB;
				rc_pair_rewrite_writemask(sub,
							conversion_swizzle);
			}
			sub->DestIndex = new_index;
		}
	}

	readers = rc_variable_readers_union(var);

	for ( ; readers; readers = readers->Next) {
		struct rc_reader * reader = readers->Item;
		if (reader->Inst->Type == RC_INSTRUCTION_NORMAL) {
			reader->U.I.Src->Index = new_index;
			reader->U.I.Src->Swizzle = rc_rewrite_swizzle(
				reader->U.I.Src->Swizzle, conversion_swizzle);
		} else {
			struct rc_pair_instruction * pair_inst =
							&reader->Inst->U.P;
			unsigned int src_type = rc_source_type_swz(
							reader->U.P.Arg->Swizzle);

			int src_index = reader->U.P.Arg->Source;
			if (src_index == RC_PAIR_PRESUB_SRC) {
				src_index = rc_pair_get_src_index(
						pair_inst, reader->U.P.Src);
			}
			/* Try to delete the old src, it is OK if this fails,
			 * because rc_pair_alloc_source might be able to
			 * find a source the ca be reused.
			 */
			if (rc_pair_remove_src(reader->Inst, src_type,
							src_index, old_mask)) {
				/* Reuse the source index of the source that
				 * was just deleted and set its register
				 * index.  We can't use rc_pair_alloc_source
				 * for this becuase it might return a source
				 * index that is already being used. */
				if (src_type & RC_SOURCE_RGB) {
					pair_inst->RGB.Src[src_index]
						.Used =	1;
					pair_inst->RGB.Src[src_index]
						.Index = new_index;
					pair_inst->RGB.Src[src_index]
						.File = RC_FILE_TEMPORARY;
				}
				if (src_type & RC_SOURCE_ALPHA) {
					pair_inst->Alpha.Src[src_index]
						.Used = 1;
					pair_inst->Alpha.Src[src_index]
						.Index = new_index;
					pair_inst->Alpha.Src[src_index]
						.File = RC_FILE_TEMPORARY;
				}
			} else {
				src_index = rc_pair_alloc_source(
						&reader->Inst->U.P,
						src_type & RC_SOURCE_RGB,
						src_type & RC_SOURCE_ALPHA,
						RC_FILE_TEMPORARY,
						new_index);
				if (src_index < 0) {
					rc_error(var->C, "Rewrite of inst %u failed "
						"Can't allocate source for "
						"Inst %u src_type=%x "
						"new_index=%u new_mask=%u\n",
						var->Inst->IP, reader->Inst->IP, src_type, new_index, new_writemask);
						continue;
				}
			}
			reader->U.P.Arg->Swizzle = rc_rewrite_swizzle(
				reader->U.P.Arg->Swizzle, conversion_swizzle);
			if (reader->U.P.Arg->Source != RC_PAIR_PRESUB_SRC) {
				reader->U.P.Arg->Source = src_index;
			}
		}
	}
}

/**
 * Compute the live intervals for var and its friends.
 */
void rc_variable_compute_live_intervals(struct rc_variable * var)
{
	while(var) {
		unsigned int i;
		unsigned int start = var->Inst->IP;

		for (i = 0; i < var->ReaderCount; i++) {
			unsigned int chan;
			unsigned int chan_start = start;
			unsigned int chan_end = var->Readers[i].Inst->IP;
			unsigned int mask = var->Readers[i].WriteMask;
			struct rc_instruction * inst;

			/* Extend the live interval of T0 to the start of the
			 * loop for sequences like:
			 * BGNLOOP
			 * read T0
			 * ...
			 * write T0
			 * ENDLOOP
			 */
			if (var->Readers[i].Inst->IP < start) {
				struct rc_instruction * bgnloop =
					rc_match_endloop(var->Readers[i].Inst);
				chan_start = bgnloop->IP;
			}

			/* Extend the live interval of T0 to the start of the
			 * loop in case there is a BRK instruction in the loop
			 * (we don't actually check for a BRK instruction we
			 * assume there is one somewhere in the loop, which
			 * there usually is) for sequences like:
			 * BGNLOOP
			 * ...
			 * conditional BRK
			 * ...
			 * write T0
			 * ENDLOOP
			 * read T0
			 ***************************************************
			 * Extend the live interval of T0 to the end of the
			 * loop for sequences like:
			 * write T0
			 * BGNLOOP
			 * ...
			 * read T0
			 * ENDLOOP
			 */
			for (inst = var->Inst; inst != var->Readers[i].Inst;
							inst = inst->Next) {
				rc_opcode op = rc_get_flow_control_inst(inst);
				if (op == RC_OPCODE_ENDLOOP) {
					struct rc_instruction * bgnloop =
						rc_match_endloop(inst);
					if (bgnloop->IP < chan_start) {
						chan_start = bgnloop->IP;
					}
				} else if (op == RC_OPCODE_BGNLOOP) {
					struct rc_instruction * endloop =
						rc_match_bgnloop(inst);
					if (endloop->IP > chan_end) {
						chan_end = endloop->IP;
					}
				}
			}

			for (chan = 0; chan < 4; chan++) {
				if ((mask >> chan) & 0x1) {
					if (!var->Live[chan].Used
					|| chan_start < var->Live[chan].Start) {
						var->Live[chan].Start =
								chan_start;
					}
					if (!var->Live[chan].Used
					|| chan_end > var->Live[chan].End) {
						var->Live[chan].End = chan_end;
					}
					var->Live[chan].Used = 1;
				}
			}
		}
		var = var->Friend;
	}
}

/**
 * @return 1 if a and b share a reader
 * @return 0 if they do not
 */
static unsigned int readers_intersect(
	struct rc_variable * a,
	struct rc_variable * b)
{
	unsigned int a_index, b_index;
	for (a_index = 0; a_index < a->ReaderCount; a_index++) {
		struct rc_reader reader_a = a->Readers[a_index];
		for (b_index = 0; b_index < b->ReaderCount; b_index++) {
			struct rc_reader reader_b = b->Readers[b_index];
			if (reader_a.Inst->Type == RC_INSTRUCTION_NORMAL
				&& reader_b.Inst->Type == RC_INSTRUCTION_NORMAL
				&& reader_a.U.I.Src == reader_b.U.I.Src) {

				return 1;
			}
			if (reader_a.Inst->Type == RC_INSTRUCTION_PAIR
				&& reader_b.Inst->Type == RC_INSTRUCTION_PAIR
				&& reader_a.U.P.Src == reader_b.U.P.Src) {

				return 1;
			}
		}
	}
	return 0;
}

void rc_variable_add_friend(
	struct rc_variable * var,
	struct rc_variable * friend)
{
	assert(var->Dst.Index == friend->Dst.Index);
	while(var->Friend) {
		var = var->Friend;
	}
	var->Friend = friend;
}

struct rc_variable * rc_variable(
	struct radeon_compiler * c,
	unsigned int DstFile,
	unsigned int DstIndex,
	unsigned int DstWriteMask,
	struct rc_reader_data * reader_data)
{
	struct rc_variable * new =
			memory_pool_malloc(&c->Pool, sizeof(struct rc_variable));
	memset(new, 0, sizeof(struct rc_variable));
	new->C = c;
	new->Dst.File = DstFile;
	new->Dst.Index = DstIndex;
	new->Dst.WriteMask = DstWriteMask;
	if (reader_data) {
		new->Inst = reader_data->Writer;
		new->ReaderCount = reader_data->ReaderCount;
		new->Readers = reader_data->Readers;
	}
	return new;
}

static void get_variable_helper(
	struct rc_list ** variable_list,
	struct rc_variable * variable)
{
	struct rc_list * list_ptr;
	for (list_ptr = *variable_list; list_ptr; list_ptr = list_ptr->Next) {
		struct rc_variable * var;
		for (var = list_ptr->Item; var; var = var->Friend) {
			if (readers_intersect(var, variable)) {
				rc_variable_add_friend(var, variable);
				return;
			}
		}
	}
	rc_list_add(variable_list, rc_list(&variable->C->Pool, variable));
}

static void get_variable_pair_helper(
	struct rc_list ** variable_list,
	struct radeon_compiler * c,
	struct rc_instruction * inst,
	struct rc_pair_sub_instruction * sub_inst)
{
	struct rc_reader_data reader_data;
	struct rc_variable * new_var;
	rc_register_file file;
	unsigned int writemask;

	if (sub_inst->Opcode == RC_OPCODE_NOP) {
		return;
	}
	memset(&reader_data, 0, sizeof(struct rc_reader_data));
	rc_get_readers_sub(c, inst, sub_inst, &reader_data, NULL, NULL, NULL);

	if (reader_data.ReaderCount == 0) {
		return;
	}

	if (sub_inst->WriteMask) {
		file = RC_FILE_TEMPORARY;
		writemask = sub_inst->WriteMask;
	} else if (sub_inst->OutputWriteMask) {
		file = RC_FILE_OUTPUT;
		writemask = sub_inst->OutputWriteMask;
	} else {
		writemask = 0;
		file = RC_FILE_NONE;
	}
	new_var = rc_variable(c, file, sub_inst->DestIndex, writemask,
								&reader_data);
	get_variable_helper(variable_list, new_var);
}

/**
 * Generate a list of variables used by the shader program.  Each instruction
 * that writes to a register is considered a variable.  The struct rc_variable
 * data structure includes a list of readers and is essentially a
 * definition-use chain.  Any two variables that share a reader are considered
 * "friends" and they are linked together via the Friend attribute.
 */
struct rc_list * rc_get_variables(struct radeon_compiler * c)
{
	struct rc_instruction * inst;
	struct rc_list * variable_list = NULL;

	for (inst = c->Program.Instructions.Next;
					inst != &c->Program.Instructions;
					inst = inst->Next) {
		struct rc_reader_data reader_data;
		struct rc_variable * new_var;
		memset(&reader_data, 0, sizeof(reader_data));

		if (inst->Type == RC_INSTRUCTION_NORMAL) {
			rc_get_readers(c, inst, &reader_data, NULL, NULL, NULL);
			if (reader_data.ReaderCount == 0) {
				continue;
			}
			new_var = rc_variable(c, inst->U.I.DstReg.File,
				inst->U.I.DstReg.Index,
				inst->U.I.DstReg.WriteMask, &reader_data);
			get_variable_helper(&variable_list, new_var);
		} else {
			get_variable_pair_helper(&variable_list, c, inst,
							&inst->U.P.RGB);
			get_variable_pair_helper(&variable_list, c, inst,
							&inst->U.P.Alpha);
		}
	}

	return variable_list;
}

/**
 * @return The bitwise or of the writemasks of a variable and all of its
 * friends.
 */
unsigned int rc_variable_writemask_sum(struct rc_variable * var)
{
	unsigned int writemask = 0;
	while(var) {
		writemask |= var->Dst.WriteMask;
		var = var->Friend;
	}
	return writemask;
}

/*
 * @return A list of readers for a variable and its friends.  Readers
 * that read from two different variable friends are only included once in
 * this list.
 */
struct rc_list * rc_variable_readers_union(struct rc_variable * var)
{
	struct rc_list * list = NULL;
	while (var) {
		unsigned int i;
		for (i = 0; i < var->ReaderCount; i++) {
			struct rc_list * temp;
			struct rc_reader * a = &var->Readers[i];
			unsigned int match = 0;
			for (temp = list; temp; temp = temp->Next) {
				struct rc_reader * b = temp->Item;
				if (a->Inst->Type != b->Inst->Type) {
					continue;
				}
				if (a->Inst->Type == RC_INSTRUCTION_NORMAL) {
					if (a->U.I.Src == b->U.I.Src) {
						match = 1;
						break;
					}
				}
				if (a->Inst->Type == RC_INSTRUCTION_PAIR) {
					if (a->U.P.Arg == b->U.P.Arg
					    && a->U.P.Src == b->U.P.Src) {
						match = 1;
						break;
					}
				}
			}
			if (match) {
				continue;
			}
			rc_list_add(&list, rc_list(&var->C->Pool, a));
		}
		var = var->Friend;
	}
	return list;
}

static unsigned int reader_equals_src(
	struct rc_reader reader,
	unsigned int src_type,
	void * src)
{
	if (reader.Inst->Type != src_type) {
		return 0;
	}
	if (src_type == RC_INSTRUCTION_NORMAL) {
		return reader.U.I.Src == src;
	} else {
		return reader.U.P.Src == src;
	}
}

static unsigned int variable_writes_src(
	struct rc_variable * var,
	unsigned int src_type,
	void * src)
{
	unsigned int i;
	for (i = 0; i < var->ReaderCount; i++) {
		if (reader_equals_src(var->Readers[i], src_type, src)) {
			return 1;
		}
	}
	return 0;
}

struct rc_list * rc_variable_list_get_writers(
	struct rc_list * var_list,
	unsigned int src_type,
	void * src)
{
	struct rc_list * list_ptr;
	struct rc_list * writer_list = NULL;
	for (list_ptr = var_list; list_ptr; list_ptr = list_ptr->Next) {
		struct rc_variable * var = list_ptr->Item;
		if (variable_writes_src(var, src_type, src)) {
			struct rc_variable * friend;
			rc_list_add(&writer_list, rc_list(&var->C->Pool, var));
			for (friend = var->Friend; friend;
						friend = friend->Friend) {
				if (variable_writes_src(friend, src_type, src)) {
					rc_list_add(&writer_list,
						rc_list(&var->C->Pool, friend));
				}
			}
			/* Once we have indentifed the variable and its
			 * friends that write this source, we can stop
			 * stop searching, because we know know of the
			 * other variables in the list will write this source.
			 * If they did they would be friends of var.
			 */
			break;
		}
	}
	return writer_list;
}

void rc_variable_print(struct rc_variable * var)
{
	unsigned int i;
	while (var) {
		fprintf(stderr, "%u: TEMP[%u].%u: ",
			var->Inst->IP, var->Dst.Index, var->Dst.WriteMask);
		for (i = 0; i < 4; i++) {
			fprintf(stderr, "chan %u: start=%u end=%u ", i,
					var->Live[i].Start, var->Live[i].End);
		}
		fprintf(stderr, "%u readers\n", var->ReaderCount);
		if (var->Friend) {
			fprintf(stderr, "Friend: \n\t");
		}
		var = var->Friend;
	}
}


text:
package com.ayoview.sample.deepmind.xfermode;

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

import com.cowthan.sample.BaseActivity;
import com.cowthan.sample.R;

import org.ayo.Display;
import org.ayo.app.AyoViewLib;

/**
 *
 */
public class DemoXfermodePorterDuffActivity extends BaseActivity {

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

		final LinearLayout ll_root = findViewById(R.id.ll_root);

		findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {

			}
		});

		View view_1 = findViewById(R.id.view_1);
		AyoViewLib.setViewSize(view_1, Display.screenWidth, Display.screenHeight);

		View view_2 = findViewById(R.id.view_2);
		AyoViewLib.setViewSize(view_2, Display.screenWidth, Display.screenHeight);

		View view_3 = findViewById(R.id.view_3);
		AyoViewLib.setViewSize(view_3, Display.screenWidth, Display.screenHeight);

		View view_4 = findViewById(R.id.view_4);
		AyoViewLib.setViewSize(view_4, Display.screenWidth, Display.screenHeight);

		View view_5 = findViewById(R.id.view_5);
		AyoViewLib.setViewSize(view_5, Display.screenWidth, Display.screenHeight);

		View view_6 = findViewById(R.id.view_6);
		AyoViewLib.setViewSize(view_6, Display.screenWidth, Display.screenHeight);
	}
}


text:
using System;
using System.ComponentModel;

namespace nMqtt.SampleApp
{
	public abstract class Model : IModel
	{
		public event PropertyChangedEventHandler PropertyChanged;

		protected void OnPropertyChanged (string propertyName)
		{
			if (PropertyChanged != null)
			{
				PropertyChanged (this, new PropertyChangedEventArgs (propertyName));
			}
		}
	}
}


text:
<?php

namespace Acme\FmpsBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Acme\FmpsBundle\Entity\Category;
use Acme\FmpsBundle\Form\CategoryType;
use Symfony\Component\HttpFoundation\Response;
use JMS\SecurityExtraBundle\Annotation\Secure;

/**
 * Category controller.
 *
 * @Route("/categories")
 */
class CategoryController extends Controller
{
    /**
     * Lists all Category entities.
     *
     * @Route("/", name="category")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getEntityManager();

        $dql = "SELECT c FROM AcmeFmpsBundle:Category c";
        $query = $em->createQuery($dql);

        $paginator = $this->get('knp_paginator');
        $entities = $paginator->paginate($query, $this->get('request')->query->get('page', 1),15);

        return $this->render('AcmeFmpsBundle:Category:index.html.twig', array( 'entities' => $entities ));
    }

    /**
     * Finds and displays a Category entity.
     *
     * @Route("/{id}/show", name="category_show")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('AcmeFmpsBundle:Category')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Category entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),        );
    }

    /**
     * Displays a form to create a new Category entity.
     *
     * @Route("/new", name="category_new")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Category();
        $form   = $this->createForm(new CategoryType(), $entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView()
        );
    }

    /**
     * Creates a new Category entity.
     *
     * @Route("/create", name="category_create")
     * @Method("post")
     * @Template("AcmeFmpsBundle:Category:new.html.twig")
     */
    public function createAction()
    {
        $entity  = new Category();
        $request = $this->getRequest();
        $form    = $this->createForm(new CategoryType(), $entity);
        $form->bindRequest($request);

        if ($form->isValid()) {
           $em = $this->getDoctrine()->getEntityManager();
           $em->persist($entity);
           $em->flush();

		       $this->get('session')->setFlash('notice', 'Catégorie a été créée avec succès');

					 return $this->redirect($this->generateUrl('category_show', array('id' => $entity->getId())));
        }

				else {

						return array(
	            'entity' => $entity,
	            'form'   => $form->createView()
	          );
				}

    }

    /**
     * Displays a form to edit an existing Category entity.
     *
     * @Route("/{id}/edit", name="category_edit")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('AcmeFmpsBundle:Category')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Category entity.');
        }

        $editForm = $this->createForm(new CategoryType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing Category entity.
     *
     * @Route("/{id}/update", name="category_update")
     * @Method("post")
     * @Template("AcmeFmpsBundle:Category:edit.html.twig")
     */
    public function updateAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('AcmeFmpsBundle:Category')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Category entity.');
        }

        $editForm   = $this->createForm(new CategoryType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        $request = $this->getRequest();

        $editForm->bindRequest($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            $this->get('session')->setFlash('notice', 'Catégorie a été mise à jour avec succès');

            return $this->redirect($this->generateUrl('category_show', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Deletes a Category entity.
     *
     * @Route("/{id}/delete", name="category_delete")
     * @Method("post")
     */
    public function deleteAction($id)
    {
        $form = $this->createDeleteForm($id);
        $request = $this->getRequest();

        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $entity = $em->getRepository('AcmeFmpsBundle:Category')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Category entity.');
            }

						if ( count($entity->getOffresServices()) > 0 ){
							$this->get('session')->setFlash('error', 'Impossible de supprimer cette catégorie');
							return $this->redirect($this->generateUrl('category'));
						}

					  $em->remove($entity);
	          $em->flush();

					  $this->get('session')->setFlash('notice', 'Catégorie a été supprimée avec succès');
        }

        return $this->redirect($this->generateUrl('category'));
    }

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }

}


text:
package org.apache.spark.ml.tuning

import org.apache.spark.SparkFunSuite
import org.apache.spark.ml.{Estimator, Model}
import org.apache.spark.ml.classification.{LogisticRegression, LogisticRegressionModel, OneVsRest}
import org.apache.spark.ml.classification.LogisticRegressionSuite.generateLogisticInput
import org.apache.spark.ml.evaluation.{BinaryClassificationEvaluator, Evaluator, RegressionEvaluator}
import org.apache.spark.ml.linalg.Vectors
import org.apache.spark.ml.param.{ParamMap}
import org.apache.spark.ml.param.shared.HasInputCol
import org.apache.spark.ml.regression.LinearRegression
import org.apache.spark.ml.util.{DefaultReadWriteTest, MLTestingUtils}
import org.apache.spark.mllib.util.{LinearDataGenerator, MLlibTestSparkContext}
import org.apache.spark.sql.Dataset
import org.apache.spark.sql.types.StructType

class TrainValidationSplitSuite
  extends SparkFunSuite with MLlibTestSparkContext with DefaultReadWriteTest {

  import testImplicits._

  test("train validation with logistic regression") {
    val dataset = sc.parallelize(generateLogisticInput(1.0, 1.0, 100, 42), 2).toDF()

    val lr = new LogisticRegression
    val lrParamMaps = new ParamGridBuilder()
      .addGrid(lr.regParam, Array(0.001, 1000.0))
      .addGrid(lr.maxIter, Array(0, 10))
      .build()
    val eval = new BinaryClassificationEvaluator
    val tvs = new TrainValidationSplit()
      .setEstimator(lr)
      .setEstimatorParamMaps(lrParamMaps)
      .setEvaluator(eval)
      .setTrainRatio(0.5)
      .setSeed(42L)
    val tvsModel = tvs.fit(dataset)
    val parent = tvsModel.bestModel.parent.asInstanceOf[LogisticRegression]
    assert(tvs.getTrainRatio === 0.5)
    assert(parent.getRegParam === 0.001)
    assert(parent.getMaxIter === 10)
    assert(tvsModel.validationMetrics.length === lrParamMaps.length)
  }

  test("train validation with linear regression") {
    val dataset = sc.parallelize(
      LinearDataGenerator.generateLinearInput(
        6.3, Array(4.7, 7.2), Array(0.9, -1.3), Array(0.7, 1.2), 100, 42, 0.1), 2)
      .map(_.asML).toDF()

    val trainer = new LinearRegression().setSolver("l-bfgs")
    val lrParamMaps = new ParamGridBuilder()
      .addGrid(trainer.regParam, Array(1000.0, 0.001))
      .addGrid(trainer.maxIter, Array(0, 10))
      .build()
    val eval = new RegressionEvaluator()
    val tvs = new TrainValidationSplit()
      .setEstimator(trainer)
      .setEstimatorParamMaps(lrParamMaps)
      .setEvaluator(eval)
      .setTrainRatio(0.5)
      .setSeed(42L)
    val tvsModel = tvs.fit(dataset)

    MLTestingUtils.checkCopyAndUids(tvs, tvsModel)

    val parent = tvsModel.bestModel.parent.asInstanceOf[LinearRegression]
    assert(parent.getRegParam === 0.001)
    assert(parent.getMaxIter === 10)
    assert(tvsModel.validationMetrics.length === lrParamMaps.length)

      eval.setMetricName("r2")
    val tvsModel2 = tvs.fit(dataset)
    val parent2 = tvsModel2.bestModel.parent.asInstanceOf[LinearRegression]
    assert(parent2.getRegParam === 0.001)
    assert(parent2.getMaxIter === 10)
    assert(tvsModel2.validationMetrics.length === lrParamMaps.length)
  }

  test("transformSchema should check estimatorParamMaps") {
    import TrainValidationSplitSuite.{MyEstimator, MyEvaluator}

    val est = new MyEstimator("est")
    val eval = new MyEvaluator
    val paramMaps = new ParamGridBuilder()
      .addGrid(est.inputCol, Array("input1", "input2"))
      .build()

    val tvs = new TrainValidationSplit()
      .setEstimator(est)
      .setEstimatorParamMaps(paramMaps)
      .setEvaluator(eval)
      .setTrainRatio(0.5)
    tvs.transformSchema(new StructType()) // This should pass.

    val invalidParamMaps = paramMaps :+ ParamMap(est.inputCol -> "")
    tvs.setEstimatorParamMaps(invalidParamMaps)
    intercept[IllegalArgumentException] {
      tvs.transformSchema(new StructType())
    }
  }

  test("read/write: TrainValidationSplit") {
    val lr = new LogisticRegression().setMaxIter(3)
    val evaluator = new BinaryClassificationEvaluator()
    val paramMaps = new ParamGridBuilder()
        .addGrid(lr.regParam, Array(0.1, 0.2))
        .build()
    val tvs = new TrainValidationSplit()
      .setEstimator(lr)
      .setEvaluator(evaluator)
      .setTrainRatio(0.5)
      .setEstimatorParamMaps(paramMaps)
      .setSeed(42L)

    val tvs2 = testDefaultReadWrite(tvs, testParams = false)

    assert(tvs.getTrainRatio === tvs2.getTrainRatio)
    assert(tvs.getSeed === tvs2.getSeed)

    ValidatorParamsSuiteHelpers
      .compareParamMaps(tvs.getEstimatorParamMaps, tvs2.getEstimatorParamMaps)

    tvs2.getEstimator match {
      case lr2: LogisticRegression =>
        assert(lr.uid === lr2.uid)
        assert(lr.getMaxIter === lr2.getMaxIter)
      case other =>
        throw new AssertionError(s"Loaded TrainValidationSplit expected estimator of type" +
          s" LogisticRegression but found ${other.getClass.getName}")
    }
  }

  test("read/write: TrainValidationSplit with nested estimator") {
    val ova = new OneVsRest()
      .setClassifier(new LogisticRegression)
    val evaluator = new BinaryClassificationEvaluator()
      .setMetricName("areaUnderPR")  // not default metric
    val classifier1 = new LogisticRegression().setRegParam(2.0)
    val classifier2 = new LogisticRegression().setRegParam(3.0)
    val paramMaps = new ParamGridBuilder()
      .addGrid(ova.classifier, Array(classifier1, classifier2))
      .build()
    val tvs = new TrainValidationSplit()
      .setEstimator(ova)
      .setEvaluator(evaluator)
      .setTrainRatio(0.5)
      .setEstimatorParamMaps(paramMaps)
      .setSeed(42L)

    val tvs2 = testDefaultReadWrite(tvs, testParams = false)

    assert(tvs.getTrainRatio === tvs2.getTrainRatio)
    assert(tvs.getSeed === tvs2.getSeed)

    tvs2.getEstimator match {
      case ova2: OneVsRest =>
        assert(ova.uid === ova2.uid)
        val classifier = ova2.getClassifier
        classifier match {
          case lr: LogisticRegression =>
            assert(ova.getClassifier.asInstanceOf[LogisticRegression].getMaxIter
              === lr.getMaxIter)
          case _ =>
            throw new AssertionError(s"Loaded TrainValidationSplit expected estimator of type" +
              s" LogisticREgression but found ${classifier.getClass.getName}")
        }

      case other =>
        throw new AssertionError(s"Loaded TrainValidationSplit expected estimator of type" +
          s" OneVsRest but found ${other.getClass.getName}")
    }

    ValidatorParamsSuiteHelpers
      .compareParamMaps(tvs.getEstimatorParamMaps, tvs2.getEstimatorParamMaps)
  }

  test("read/write: Persistence of nested estimator works if parent directory changes") {
    val ova = new OneVsRest()
      .setClassifier(new LogisticRegression)
    val evaluator = new BinaryClassificationEvaluator()
      .setMetricName("areaUnderPR")  // not default metric
    val classifier1 = new LogisticRegression().setRegParam(2.0)
    val classifier2 = new LogisticRegression().setRegParam(3.0)
    val paramMaps = new ParamGridBuilder()
      .addGrid(ova.classifier, Array(classifier1, classifier2))
      .build()
    val tvs = new TrainValidationSplit()
      .setEstimator(ova)
      .setEvaluator(evaluator)
      .setTrainRatio(0.5)
      .setEstimatorParamMaps(paramMaps)
      .setSeed(42L)

    ValidatorParamsSuiteHelpers.testFileMove(tvs, tempDir)
  }

  test("read/write: TrainValidationSplitModel") {
    val lr = new LogisticRegression()
      .setThreshold(0.6)
    val lrModel = new LogisticRegressionModel(lr.uid, Vectors.dense(1.0, 2.0), 1.2)
      .setThreshold(0.6)
    val evaluator = new BinaryClassificationEvaluator()
    val paramMaps = new ParamGridBuilder()
        .addGrid(lr.regParam, Array(0.1, 0.2))
        .build()
    val tvs = new TrainValidationSplitModel("cvUid", lrModel, Array(0.3, 0.6))
    tvs.set(tvs.estimator, lr)
      .set(tvs.evaluator, evaluator)
      .set(tvs.trainRatio, 0.5)
      .set(tvs.estimatorParamMaps, paramMaps)
      .set(tvs.seed, 42L)

    val tvs2 = testDefaultReadWrite(tvs, testParams = false)

    assert(tvs.getTrainRatio === tvs2.getTrainRatio)
    assert(tvs.validationMetrics === tvs2.validationMetrics)
    assert(tvs.getSeed === tvs2.getSeed)
  }
}

object TrainValidationSplitSuite extends SparkFunSuite{

  abstract class MyModel extends Model[MyModel]

  class MyEstimator(override val uid: String) extends Estimator[MyModel] with HasInputCol {

    override def fit(dataset: Dataset[_]): MyModel = {
      throw new UnsupportedOperationException
    }

    override def transformSchema(schema: StructType): StructType = {
      require($(inputCol).nonEmpty)
      schema
    }

    override def copy(extra: ParamMap): MyEstimator = defaultCopy(extra)
  }

  class MyEvaluator extends Evaluator {

    override def evaluate(dataset: Dataset[_]): Double = {
      throw new UnsupportedOperationException
    }

    override def isLargerBetter: Boolean = true

    override val uid: String = "eval"

    override def copy(extra: ParamMap): MyEvaluator = defaultCopy(extra)
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="http://www.unidata.ucar.edu/namespaces/thredds/InvCatalog/v1.0" xmlns:xlink="http://www.w3.org/1999/xlink">
  <service name="myServer" serviceType="DODS" base="http://localhost:8080/thredds/dodsC/" />
  <dataset name="modelNotFlat">
    <metadata inherited="true">
      <serviceName>myServer</serviceName>
    </metadata>
    <catalogRef xlink:href="gfs_211/catalog.xml" xlink:title="gfs_211" />
    <catalogRef xlink:href="eta_211/catalog.xml" xlink:title="eta_211"/>
  </dataset>
</catalog>


text:
"""
Django settings for djangotest project.

Generated by 'django-admin startproject' using Django 1.8.6.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '2i3gth@h!5&eyuk!9x(18tj=zdw2r^*1mwt262o6-w1&kg0&+)'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'hedwig.django',
    'hedwig.rest_framework',
    'chidiya'
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'djangotest.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'djangotest.wsgi.application'

HEDWIG = {
    'VHOST': 'hedwig_server',
    'USERNAME': 'hedwig_test',
    'PASSWORD': 'hedwig_pass',
    'CONSUMER': {
        'QUEUES': {
            'djangotest_consumer': {
                'BINDINGS': ['#'],
                'CALLBACK': 'chidiya.callbacks.printer',
                'DURABLE': False,
                'AUTO_DELETE': True,
                'NO_ACK': True
            }
        }
    }
}
HEDWIG_DJANGO = {
    'MODEL_SIGNALS': True
}
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'


text:
package Print;

/**
 * this Interface has to be implemented by classes that should be printed.
 * @author isabel
 * @since 24.11.16
 */
public interface Printable {
    /**
     * formats the text, so it can be written in a latex file
     *
     * @param space the deepness of the text written
     */
    void printLatex(String space);

    /**
     * formats the code such that it can be written on the terminal
     */
    void printConsole();
}