text:
function ft_realtime_oddball(cfg)

% FT_REALTIME_ODDBALL is an realtime application that computes an online
% average for a standard and deviant condition. The ERPs/ERFs are plotted,
% together with the difference as t-values. It should work both for EEG and
% MEG, as long as there are two triggers present
%
% Use as
%   ft_realtime_oddball(cfg)
% with the following configuration options
%   cfg.channel    = cell-array, see FT_CHANNELSELECTION (default = 'all')
%   cfg.trialfun   = string with the trial function
%
% The source of the data is configured as
%   cfg.dataset       = string
% or alternatively to obtain more low-level control as
%   cfg.datafile      = string
%   cfg.headerfile    = string
%   cfg.eventfile     = string
%   cfg.dataformat    = string, default is determined automatic
%   cfg.headerformat  = string, default is determined automatic
%   cfg.eventformat   = string, default is determined automatic
%
% To stop the realtime function, you have to press Ctrl-C

% Copyright (C) 2008-2012, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_realtime_oddball.m 7123 2012-12-06 21:21:38Z roboos $

% set the default configuration options
if ~isfield(cfg, 'dataformat'),     cfg.dataformat = [];      end % default is detected automatically
if ~isfield(cfg, 'headerformat'),   cfg.headerformat = [];    end % default is detected automatically
if ~isfield(cfg, 'eventformat'),    cfg.eventformat = [];     end % default is detected automatically
if ~isfield(cfg, 'channel'),        cfg.channel = 'all';      end
if ~isfield(cfg, 'bufferdata'),     cfg.bufferdata = 'last';  end % first or last
if ~isfield(cfg, 'jumptoeof'),      cfg.jumptoeof = 'no';     end % jump to end of file at initialization

% translate dataset into datafile+headerfile
cfg = ft_checkconfig(cfg, 'dataset2files', 'yes');
cfg = ft_checkconfig(cfg, 'required', {'datafile' 'headerfile'});

% these are used by the GUI callbacks
clear global chansel chanindx vaxis hdr
global chansel chanindx vaxis hdr

b1clicked = false;
b2clicked = false;
chansel = 1; % this is the subselection out of chanindx
vaxis = [
  -6 6
  -3 3
  ];

% ensure that the persistent variables related to caching are cleared
clear ft_read_header

% start by reading the header from the realtime buffer
hdr = ft_read_header(cfg.headerfile, 'cache', true);

% define a subset of channels for reading
cfg.channel = ft_channelselection(cfg.channel, hdr.label);
chanindx    = match_str(hdr.label, cfg.channel);
nchan       = length(chanindx);
if nchan==0
  error('no channels were selected');
end

if strcmp(cfg.jumptoeof, 'yes')
  prevSample = hdr.nSamples * hdr.nTrials;
else
  prevSample = 0;
end
count = 0;

f1 = nan;

% initialize the timelock cell-array, each cell will hold the average in one condition
timelock = {};

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this is the general BCI loop where realtime incoming data is handled
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while true

  % determine latest header and event information
  event     = ft_read_event(cfg.dataset, 'minsample', prevSample+1);  % only consider events that are later than the data processed sofar
  hdr       = ft_read_header(cfg.dataset, 'cache', true);             % the trialfun might want to use this, but it is not required
  cfg.event = event;                                               % store it in the configuration, so that it can be passed on to the trialfun
  cfg.hdr   = hdr;                                                 % store it in the configuration, so that it can be passed on to the trialfun

  % evaluate the trialfun, note that the trialfun should not re-read the events and header
  fprintf('evaluating ''%s'' based on %d events\n', cfg.trialfun, length(event));
  trl = feval(cfg.trialfun, cfg);

  % the code below assumes that the 4th column of the trl matrix contains the condition index
  % set the default condition to one if no condition index was given
  if size(trl,1)>0 && size(trl,2)<4
    trl(:,4) = 1;
  end

  fprintf('processing %d trials\n', size(trl,1));

  for trllop=1:size(trl,1)

    begsample = trl(trllop,1);
    endsample = trl(trllop,2);
    offset    = trl(trllop,3);
    condition = trl(trllop,4);  % it is important that the 4th column is returned with the condition number

    % remember up to where the data was read
    prevSample  = endsample;
    count       = count + 1;
    fprintf('processing segment %d from sample %d to %d, condition = %d\n', count, begsample, endsample, condition);

    while (hdr.nSamples*hdr.nTrials < endsample)
      % wait until all data up to the endsample has arrived
      hdr = ft_read_header(cfg.headerfile, 'cache', true);
    end

    % read the selected data segment from the buffer
    dat = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx, 'checkboundary', false);

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % from here onward it is specific to the processing of the data
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    % apply some preprocessing options
    dat = ft_preproc_lowpassfilter(dat, hdr.Fs, 45);
    dat = ft_preproc_baselinecorrect(dat, 1, -offset);

    % put the data in a fieldtrip-like raw structure
    data.trial{1} = dat;
    data.time{1}  = offset2time(offset, hdr.Fs, endsample-begsample+1);
    data.label    = hdr.label(chanindx);
    data.hdr      = hdr;
    data.fsample  = hdr.Fs;

    if length(timelock)<condition || isempty(timelock{condition})
      % this is the first occurence of this condition, initialize an empty timelock structure
      timelock{condition}.label   = data.label;
      timelock{condition}.time    = data.time{1};
      timelock{condition}.avg     = [];
      timelock{condition}.var     = [];
      timelock{condition}.dimord  = 'chan_time';
      nchans   = size(data.trial{1}, 1);
      nsamples = size(data.trial{1}, 2);
      % the following elements are for the cumulative computation
      timelock{condition}.n   = 0;                          % number of trials
      timelock{condition}.s   = zeros(nchans, nsamples);    % sum
      timelock{condition}.ss  = zeros(nchans, nsamples);    % sum of squares
    end

    % add the new data to the accumulated data
    timelock{condition}.n  = timelock{condition}.n  + 1;
    timelock{condition}.s  = timelock{condition}.s  + data.trial{1};
    timelock{condition}.ss = timelock{condition}.ss + data.trial{1}.^2;

    % compute the average and variance on the fly
    timelock{condition}.avg = timelock{condition}.s ./ timelock{condition}.n;
    timelock{condition}.var = (timelock{condition}.ss - (timelock{condition}.s.^2)./timelock{condition}.n) ./ (timelock{condition}.n-1);

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % from here onward the GUI is constructed
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    try

      if ~ishandle(f1)
        close all;
        f1 = figure;
        clear u1 u2
        clear p1 p2
        clear c1
        set(f1, 'resizeFcn', 'clear u1 u2 p1 p2 c1 b1 b2')
      end

      if ~exist('p1')
        p1 = subplot(2,1,1);
      end

      if ~exist('p2')
        p2 = subplot(2,1,2);
      end

      if ~exist('c1')
        pos = [0.75 0.93 0.1 0.05];
        c1 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_channel, 'BackgroundColor', 'white');
        set(c1, 'position', pos);
        set(c1, 'string', chanindx(chansel));
        set(c1, 'tag', 'c1');
      end

      if ~exist('u1')
        pos = get(p1, 'position'); % link the position to the subplot
        pos(1) = pos(1)-0.1;
        pos(2) = pos(2)-0.05;
        pos(3) = 0.1;
        pos(4) = 0.05;
        u1 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_axis, 'BackgroundColor', 'white');
        set(u1, 'position', pos);
        set(u1, 'string', num2str(vaxis(1,2)));
        set(u1, 'tag', 'u1');
      end

      if ~exist('u2')
        pos = get(p2, 'position'); % link the position to the subplot
        pos(1) = pos(1)-0.1;
        pos(2) = pos(2)-0.05;
        pos(3) = 0.1;
        pos(4) = 0.05;
        u2 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_axis, 'BackgroundColor', 'white');
        set(u2, 'position', pos);
        set(u2, 'string', num2str(vaxis(2,2)));
        set(u2, 'tag', 'u1');
      end

      if ~exist('b1')
        pos = [0.75 0.01 0.1 0.05];
        b1 = uicontrol('style', 'pushbutton', 'units', 'normalized', 'callback', 'evalin(''caller'', ''b1clicked = true'')');
        set(b1, 'position', pos);
        set(b1, 'string', 'reset');
        set(b1, 'tag', 'b1');
      end

      if ~exist('b2')
        pos = [0.88 0.01 0.1 0.05];
        b2 = uicontrol('style', 'pushbutton', 'units', 'normalized', 'callback', 'evalin(''caller'', ''b2clicked = true'')');
        set(b2, 'position', pos);
        set(b2, 'string', 'quit');
        set(b2, 'tag', 'b2');
      end

    end % try

    if b1clicked
      timelock = {};
      try, cla(p1); end
      try, cla(p2); end
      b1clicked = false;
    end

    if b2clicked
      return
      b2clicked = false;
    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % from here onward the data is plotted
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    try

      if length(timelock)>1
        sel = ~cellfun(@isempty, timelock);
        sel = find(sel, 2, 'first');
        if length(sel)~=2
          break
        end
        standard  = timelock{sel(1)};
        deviant   = timelock{sel(2)};
        tscore    = (deviant.avg - standard.avg) ./ sqrt(standard.var./standard.n + deviant.var./deviant.n);
        time      = standard.time; % deviant is the same

        if exist('p1')
          subplot(p1)
          cla
          hold on
          hs = plot(time, standard.avg(chansel,:), 'b-');
          hd = plot(time, deviant.avg(chansel,:), 'r-');
          set(hs, 'lineWidth', 1.5)
          set(hd, 'lineWidth', 1.5)
          grid on
          axis([time(1) time(end) vaxis(1,1) vaxis(1,2)])
          legend(sprintf('standard (n=%d)', standard.n), sprintf('deviant (n=%d)', deviant.n));
          xlabel('time (s)');
          ylabel('amplitude (uV)');
          title(sprintf('channel "%s"', hdr.label{chanindx(chansel)}));
        end

        if exist('p2')
          subplot(p2)
          cla
          hold on
          ht = plot(time, tscore(chansel,:), 'g-');
          set(ht, 'lineWidth', 1.5)
          grid on
          axis([time(1) time(end) vaxis(2,1) vaxis(2,2)])
          legend('difference');
          xlabel('time (s)');
          ylabel('t-score (a.u.)');
        end

      end % two conditions are available

    end % try

    % force matlab to redraw the figure
    drawnow

  end % looping over new trials
end % while true

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [time] = offset2time(offset, fsample, nsamples)
offset   = double(offset);
nsamples = double(nsamples);
time = (offset + (0:(nsamples-1)))/fsample;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function update_channel(h, varargin)
global chansel chanindx hdr
val = abs(str2num(get(h, 'string')));
val = max(1, min(val, length(chanindx)));
if ~isempty(val)
  switch get(h, 'tag')
    case 'c1'
      chansel = val;
      set(h, 'string', num2str(val));
      fprintf('switching to channel "%s"', hdr.label{chanindx(chansel)});
  end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function update_axis(h, varargin)
global vaxis
val = abs(str2num(get(h, 'string')));
if ~isempty(val)
  switch get(h, 'tag')
    case 'u1'
      vaxis(1,:) = [-val val];
    case 'u2'
      vaxis(2,:) = [-val val];
  end
end


text:
CTCI::ChapterOne = Module.new

require_relative 'chapter_one/one'
require_relative 'chapter_one/two'
require_relative 'chapter_one/three'
require_relative 'chapter_one/four'
require_relative 'chapter_one/five'
require_relative 'chapter_one/six'
require_relative 'chapter_one/seven'
require_relative 'chapter_one/eight'

redpajama_set_name: RedPajamaGithub


text:
/**
 * @file 编辑器支持的模式集合
 * @author mengke01(kekee000@gmail.com)
 */

import point from './point';
import range from './range';
import pan from './pan';
import bound from './bound';
import shapes from './shapes';
import addshapes from './addshapes';
import addpath from './addpath';
import split from './split';
import referenceline from './referenceline';

export default {
    point,
    range,
    pan,
    'default': bound,
    shapes,
    addshapes,
    addpath,
    split,
    referenceline
};


text:
<?php

return [
    'adminEmail' => 'smithsdmitry@gmail.com',
];


text:
for fastq in fastq/*.fastq; do
    sbatch $1 $fastq
done


text:
using System.Web.UI;
using System.Xml.Linq;
using Microsoft.Xrm.Sdk.Metadata;

namespace Microsoft.Xrm.Portal.Web.UI.CrmEntityFormView
{
	public class RowTemplateFactory
	{
		public RowTemplateFactory(int languageCode)
		{
			LanguageCode = languageCode;
		}

		public int LanguageCode { get; private set; }

		public virtual ITemplate CreateTemplate(XNode rowNode, EntityMetadata entityMetadata, ICellTemplateFactory cellTemplateFactory)
		{
			return new GridLayoutRowTemplate(rowNode, LanguageCode, entityMetadata, cellTemplateFactory);
		}
	}
}


text:
package core.adapt.iterator;

import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import core.adapt.HDFSPartition;
import core.adapt.Partition;
import core.adapt.Predicate;
import core.adapt.Query;
import core.common.globals.Globals;
import core.common.globals.TableInfo;
import core.utils.BinaryUtils;
import core.utils.ReflectionUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.ArrayUtils;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Iterator;

public class PartitionIterator implements Iterator<IteratorRecord> {

    protected static char newLine = '\n';

    protected IteratorRecord record;
    protected byte[] recordBytes;
    protected byte[] brokenRecordBytes;
    protected byte[] bytes;
    protected int bytesLength, offset, previous;
    protected Partition partition;
    protected Predicate[] predicates;
    protected Query query;

    public PartitionIterator() {

    }

    public PartitionIterator(Query q) {
        this.query = q;
    }

    public static String iteratorToString(PartitionIterator itr) {
        ByteArrayDataOutput dat = ByteStreams.newDataOutput();
        try {
            itr.write(dat);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to serialize the partitioner");
        }
        return itr.getClass().getName() + "@" + new String(dat.toByteArray());
    }

    public static PartitionIterator stringToIterator(String itrString) {
        String[] tokens = itrString.split("@", 2);
        return (PartitionIterator) ReflectionUtils.getInstance(tokens[0],
                new Class<?>[]{String.class}, new Object[]{tokens[1]});
    }

    public void setPartition(Partition partition) {
        this.partition = partition;
        if (Globals.getTableInfo(query.getTable()) == null) {
            String path = FilenameUtils.getPathNoEndSeparator(partition
                    .getPath());

            if (FilenameUtils.getBaseName(path).contains("partitions")
                    || FilenameUtils.getBaseName(path).contains("repartition")) { // hack
                path = FilenameUtils.getPathNoEndSeparator(FilenameUtils.getPath(path));
            }

            if (FilenameUtils.getBaseName(path).contains("data")) { // hack
                path = FilenameUtils.getPathNoEndSeparator(FilenameUtils.getPath(path));
            }

            // To remove table name.
            path = FilenameUtils.getPathNoEndSeparator(FilenameUtils.getPath(path));

            // Initialize Globals.
            Globals.loadTableInfo(query.getTable(), path, ((HDFSPartition) partition).getFS());
        }

        TableInfo tableInfo = Globals.getTableInfo(query.getTable());
        record = new IteratorRecord(tableInfo.delimiter);
        bytes = partition.getNextBytes();
        // bytesLength = partition.getSize();
        bytesLength = bytes == null ? 0 : bytes.length;
        offset = 0;
        previous = 0;
        brokenRecordBytes = null;
    }

    @Override
    public boolean hasNext() {
        for (; offset < bytesLength; offset++) {
            if (bytes[offset] == newLine) {
                // record.setBytes(bytes, previous, offset-previous);
                recordBytes = ArrayUtils.subarray(bytes, previous, offset);
                if (brokenRecordBytes != null) {
                    recordBytes = BinaryUtils.concatenate(brokenRecordBytes,
                            recordBytes);
                    brokenRecordBytes = null;
                }

                try {
                    record.setBytes(recordBytes);
                } catch (ArrayIndexOutOfBoundsException e) {
                    System.out.println("Index out of bounds while setting bytes: "
                            + (new String(recordBytes)));
                    throw e;
                }

                previous = ++offset;
                if (isRelevant(record)) {
                    // System.out.println("relevant record found ..");
                    return true;
                } else
                    continue;
            }
        }

        if (previous < bytesLength)
            brokenRecordBytes = BinaryUtils.getBytes(bytes, previous,
                    bytesLength - previous);
        else
            brokenRecordBytes = null;

        bytes = partition == null ? null : partition.getNextBytes();
        if (bytes != null) {
            bytesLength = bytes.length;
            offset = 0;
            previous = 0;
            return hasNext();
        } else
            return false;
    }

    protected boolean isRelevant(IteratorRecord record) {
        return true;
    }

    @Override
    public void remove() {
        next();
    }

    @Override
    public IteratorRecord next() {
        return record;
    }

    public void finish() {
    }

    public void write(DataOutput out) throws IOException {
    }

    // public static PartitionIterator read(DataInput in) throws IOException {
    // PartitionIterator it = new PartitionIterator();
    // it.readFields(in);
    // return it;
    // }

    public void readFields(DataInput in) throws IOException {
    }
}


text:
/**
* modal() plug-in
 *
 */
(function ($)
{
    var settings = {
        id : null,
        width : null,
        height : null,

        //base modal content providers
        content : null,
        selector : null,

        //effects
        open    : null,
        close   : null
    }

    var $currentModal = null;

    var methods = {
        init: function (options)
        {
            settings = $.extend(settings, options);

            //step 1 : create if needed
            if($currentModal === null)
                methods.create();

            //content is changing so show loader
            $currentModal.find(".content").html("");
            $currentModal.find(".loader").show();

            //Step 2 : populate
            if(settings.selector !== null)
            {
                //populate dialog this selector
                var content = $(settings.selector).clone().wrap('
').parent().html();
                methods.update(content);
            }
            else if(settings.content !== null)
            {
                //populate dialog with content
                methods.update(settings.content);
            }

            //step 3 : show
            methods.open();

            return $currentModal;

        },
        create : function()
        {
            //clean up any open dialogs
            methods.close();

            //append overlay
            $currentModal = $("
").appendTo("body").hide();

            if(settings.id !== null)
                $currentModal.attr("id", settings.id);

            //append background fill
            $("
").appendTo($currentModal).click(function() {
                methods.close();
            });

            //append dialog
            $dialog = $("
").appendTo($currentModal);

            //size and center
            if(settings.width !== null)
            {
                $dialog.css("width", settings.width);
                $dialog.css("margin-left", settings.width * -0.5);
            }

             if(settings.height !== null)
             {
                $dialog.css("height", settings.height);
                $dialog.css("margin-top", settings.height * -0.5);
             }

            //append dialog content
            $("
").appendTo($dialog);

            //append dialog close button
            $("×").appendTo($dialog).click(function(){
                methods.close();
            });

            //append dialog loader
            $("
loading
").appendTo($dialog);

            return $currentModal;
        },
        update : function(message)
        {
            if($currentModal != null)
            {
                $currentModal.find(".content").html(message);
                $currentModal.find(".loader").hide();
            }

            return $currentModal;
        },
        open : function()
        {
            if($currentModal != null)
            {
                if(settings.open != null)
                    settings.open.apply($currentModal);
                else
                    $currentModal.show();
            }

            return $currentModal;
        },
        close : function()
        {
            if($currentModal != null)
            {
                if(settings.close != null)
                    settings.close.apply($currentModal);
                else
                    $currentModal.remove();
            }
            $currentModal = null;
        }
    };

    /**
    * Constructor
    */
    $.modal = function (method)
    {
        // Method calling logic
        if (methods[method])
        {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        }
        else if (typeof method === 'object' || !method)
        {
            return methods.init.apply(this, arguments);
        }
        else
        {
            $.error('Method ' + method + ' does not exist on jQuery.modal');
        }
    }

    $.fn.modal = function (options)
    {
        //pass any options on with selector
        var opts = $.extend({
            selector : this
        }, options);

        //open dialog
        $.modal(opts);
    };

} (jQuery));


text:
random-word-bot
===============

twitter bot that tweets random words


text:
#ifndef _AccessManagerTest_H
#define _AccessManagerTest_H

#include "WDBaseTestPolicies.h"

class AccessManager;

//---- AccessManagerTest ----------------------------------------------------------
//! Test access managers with the default API.
/*!
This test can test any access manager that exports the default API.
It runs configured unit tests for the following API functions:
Validate, AuthenticateWeak, AuthenticateStrong, ChangePassword,
ResetPassword, IsAllowed and GetAllowed.
AccessManagers are defined and registered in the config of the coastd.
They have a config themselves, which in turn defines the backends
(i.e. AccessControllers) that they utilize to get access to user-
and token information.
*/
class AccessManagerTest : public testframework::TestCaseWithGlobalConfigDllAndModuleLoading
{
public:
	//--- constructors

	//! TestCase constructor
	//! \param name name of the test
	AccessManagerTest(TString tstrName)
    :TestCaseType(tstrName)
    {
}
    //! destroys the test case
	~AccessManagerTest()
    {
}
    //--- public api

	//! builds up a suite of testcases for this test
	static Test *suite ();

	//! sets the environment for this test
	void setUp ();

	//! deletes the environment for this test
	void tearDown ();

	TString getConfigFileName();

	// tests an access manager
	void doTestAccessManager(ROAnything config, AccessManager *am);

	// tests all regular access managers defined/registered in the config
	void RegularAccessManagersTest();
};

#endif


text:
<?php

namespace Zibios\WrikePhpJmsserializer\Model\Folder;

use JMS\Serializer\Annotation as SA;
use Zibios\WrikePhpJmsserializer\Model\AbstractModel;
use Zibios\WrikePhpJmsserializer\Model\Common\CustomFieldModel;
use Zibios\WrikePhpJmsserializer\Model\Common\MetadataModel;
use Zibios\WrikePhpJmsserializer\Model\Common\ProjectModel;
use Zibios\WrikePhpJmsserializer\Model\ResourceModelInterface;

/**
 * Folder Resource Model.
 *
 * @SuppressWarnings(PHPMD.TooManyFields)
 */
class FolderResourceModel extends AbstractModel implements ResourceModelInterface
{
    /**
     * Folder ID.
     *
     * Comment: Folder ID
     *
     * @SA\Type("string")
     * @SA\SerializedName("id")
     *
     * @var string|null
     */
    protected $id;

    /**
     * Account ID.
     *
     * Comment: Account ID
     *
     * @SA\Type("string")
     * @SA\SerializedName("accountId")
     *
     * @var string|null
     */
    protected $accountId;

    /**
     * Title.
     *
     * @SA\Type("string")
     * @SA\SerializedName("title")
     *
     * @var string|null
     */
    protected $title;

    /**
     * Created date.
     *
     * Format: yyyy-MM-dd'T'HH:mm:ss'Z'
     *
     * @SA\Type("string")
     * @SA\SerializedName("createdDate")
     *
     * @var string|null
     */
    protected $createdDate;

    /**
     * Updated date.
     *
     * Format: yyyy-MM-dd'T'HH:mm:ss'Z'
     *
     * @SA\Type("string")
     * @SA\SerializedName("updatedDate")
     *
     * @var string|null
     */
    protected $updatedDate;

    /**
     * Brief description.
     *
     * Comment: Optional
     *
     * @SA\Type("string")
     * @SA\SerializedName("briefDescription")
     *
     * @var string|null
     */
    protected $briefDescription;

    /**
     * Description.
     *
     * @SA\Type("string")
     * @SA\SerializedName("description")
     *
     * @var string|null
     */
    protected $description;

    /**
     * Color.
     *
     * Folder color, Enum
     * Comment: Optional
     *
     * @SA\Type("string")
     * @SA\SerializedName("color")
     *
     * @var string|null
     */
    protected $color;

    /**
     * List of user IDs, who share the folder.
     *
     * Comment: Contact ID list
     *
     * @SA\Type("array<string>")
     * @SA\SerializedName("sharedIds")
     *
     * @var array|string[]|null
     */
    protected $sharedIds;

    /**
     * List of parent folder IDs.
     *
     * Comment: Folder ID list
     *
     * @SA\Type("array<string>")
     * @SA\SerializedName("parentIds")
     *
     * @var array|string[]|null
     */
    protected $parentIds;

    /**
     * List of child folder IDs.
     *
     * Comment: Folder ID list
     *
     * @SA\Type("array<string>")
     * @SA\SerializedName("childIds")
     *
     * @var array|string[]|null
     */
    protected $childIds;

    /**
     * List of super parent folder IDs.
     *
     * Comment: Folder ID list
     *
     * @SA\Type("array<string>")
     * @SA\SerializedName("superParentIds")
     *
     * @var array|string[]|null
     */
    protected $superParentIds;

    /**
     * Folder scope.
     *
     * Folder scope, Enum
     *
     * @SA\Type("string")
     * @SA\SerializedName("scope")
     *
     * @var string|null
     */
    protected $scope;

    /**
     * True if folder has attachments.
     *
     * @SA\Type("boolean")
     * @SA\SerializedName("hasAttachments")
     *
     * @var string|null
     */
    protected $hasAttachments;

    /**
     * Total count of folder attachments.
     *
     * Comment: Optional
     *
     * @SA\Type("integer")
     * @SA\SerializedName("attachmentCount")
     *
     * @var string|null
     */
    protected $attachmentCount;

    /**
     * Link to open folder in web workspace, if user has appropriate access.
     *
     * @SA\Type("string")
     * @SA\SerializedName("permalink")
     *
     * @var string|null
     */
    protected $permalink;

    /**
     * Folder workflow ID.
     *
     * Comment: Workflow ID
     *
     * @SA\Type("string")
     * @SA\SerializedName("workflowId")
     *
     * @var string|null
     */
    protected $workflowId;

    /**
     * List of folder metadata entries.
     *
     * Metadata entry key-value pair
     * Metadata entries are isolated on per-client (application) basis
     * Comment: Optional
     *
     * @SA\Type("array<Zibios\WrikePhpJmsserializer\Model\Common\MetadataModel>")
     * @SA\SerializedName("metadata")
     *
     * @var array|MetadataModel[]|null
     */
    protected $metadata;

    /**
     * Custom fields.
     *
     * Comment: Optional
     *
     * @SA\Type("array<Zibios\WrikePhpJmsserializer\Model\Common\CustomFieldModel>")
     * @SA\SerializedName("customFields")
     *
     * @var array|CustomFieldModel[]|null
     */
    protected $customFields;

    /**
     * Custom column IDs.
     *
     * Comment: Optional
     * Comment: Custom Field ID
     *
     * @SA\Type("array<string>")
     * @SA\SerializedName("customColumnIds")
     *
     * @var array|string[]|null
     */
    protected $customColumnIds;

    /**
     * Project details, present only for project folders.
     *
     * Comment: Optional
     *
     * @SA\Type("Zibios\WrikePhpJmsserializer\Model\Common\ProjectModel")
     * @SA\SerializedName("project")
     *
     * @var ProjectModel|null
     */
    protected $project;

    /**
     * @return null|string
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param null|string $id
     *
     * @return $this
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getAccountId()
    {
        return $this->accountId;
    }

    /**
     * @param null|string $accountId
     *
     * @return $this
     */
    public function setAccountId($accountId)
    {
        $this->accountId = $accountId;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * @param null|string $title
     *
     * @return $this
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * @return string|null
     */
    public function getCreatedDate()
    {
        return $this->createdDate;
    }

    /**
     * @param string|null $createdDate
     *
     * @return $this
     */
    public function setCreatedDate($createdDate)
    {
        $this->createdDate = $createdDate;

        return $this;
    }

    /**
     * @return string|null
     */
    public function getUpdatedDate()
    {
        return $this->updatedDate;
    }

    /**
     * @param string|null $updatedDate
     *
     * @return $this
     */
    public function setUpdatedDate($updatedDate)
    {
        $this->updatedDate = $updatedDate;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getBriefDescription()
    {
        return $this->briefDescription;
    }

    /**
     * @param null|string $briefDescription
     *
     * @return $this
     */
    public function setBriefDescription($briefDescription)
    {
        $this->briefDescription = $briefDescription;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * @param null|string $description
     *
     * @return $this
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getColor()
    {
        return $this->color;
    }

    /**
     * @param null|string $color
     *
     * @return $this
     */
    public function setColor($color)
    {
        $this->color = $color;

        return $this;
    }

    /**
     * @return array|null|\string[]
     */
    public function getSharedIds()
    {
        return $this->sharedIds;
    }

    /**
     * @param array|null|\string[] $sharedIds
     *
     * @return $this
     */
    public function setSharedIds($sharedIds)
    {
        $this->sharedIds = $sharedIds;

        return $this;
    }

    /**
     * @return array|null|\string[]
     */
    public function getParentIds()
    {
        return $this->parentIds;
    }

    /**
     * @param array|null|\string[] $parentIds
     *
     * @return $this
     */
    public function setParentIds($parentIds)
    {
        $this->parentIds = $parentIds;

        return $this;
    }

    /**
     * @return array|null|\string[]
     */
    public function getChildIds()
    {
        return $this->childIds;
    }

    /**
     * @param array|null|\string[] $childIds
     *
     * @return $this
     */
    public function setChildIds($childIds)
    {
        $this->childIds = $childIds;

        return $this;
    }

    /**
     * @return array|null|\string[]
     */
    public function getSuperParentIds()
    {
        return $this->superParentIds;
    }

    /**
     * @param array|null|\string[] $superParentIds
     *
     * @return $this
     */
    public function setSuperParentIds($superParentIds)
    {
        $this->superParentIds = $superParentIds;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getScope()
    {
        return $this->scope;
    }

    /**
     * @param null|string $scope
     *
     * @return $this
     */
    public function setScope($scope)
    {
        $this->scope = $scope;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getHasAttachments()
    {
        return $this->hasAttachments;
    }

    /**
     * @param null|string $hasAttachments
     *
     * @return $this
     */
    public function setHasAttachments($hasAttachments)
    {
        $this->hasAttachments = $hasAttachments;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getAttachmentCount()
    {
        return $this->attachmentCount;
    }

    /**
     * @param null|string $attachmentCount
     *
     * @return $this
     */
    public function setAttachmentCount($attachmentCount)
    {
        $this->attachmentCount = $attachmentCount;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getPermalink()
    {
        return $this->permalink;
    }

    /**
     * @param null|string $permalink
     *
     * @return $this
     */
    public function setPermalink($permalink)
    {
        $this->permalink = $permalink;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getWorkflowId()
    {
        return $this->workflowId;
    }

    /**
     * @param null|string $workflowId
     *
     * @return $this
     */
    public function setWorkflowId($workflowId)
    {
        $this->workflowId = $workflowId;

        return $this;
    }

    /**
     * @return array|null|MetadataModel[]
     */
    public function getMetadata()
    {
        return $this->metadata;
    }

    /**
     * @param array|null|MetadataModel[] $metadata
     *
     * @return $this
     */
    public function setMetadata($metadata)
    {
        $this->metadata = $metadata;

        return $this;
    }

    /**
     * @return array|null|CustomFieldModel[]
     */
    public function getCustomFields()
    {
        return $this->customFields;
    }

    /**
     * @param array|null|CustomFieldModel[] $customFields
     *
     * @return $this
     */
    public function setCustomFields($customFields)
    {
        $this->customFields = $customFields;

        return $this;
    }

    /**
     * @return array|null|\string[]
     */
    public function getCustomColumnIds()
    {
        return $this->customColumnIds;
    }

    /**
     * @param array|null|\string[] $customColumnIds
     *
     * @return $this
     */
    public function setCustomColumnIds($customColumnIds)
    {
        $this->customColumnIds = $customColumnIds;

        return $this;
    }

    /**
     * @return null|ProjectModel
     */
    public function getProject()
    {
        return $this->project;
    }

    /**
     * @param null|ProjectModel $project
     *
     * @return $this
     */
    public function setProject($project)
    {
        $this->project = $project;

        return $this;
    }
}


text:
import {Type} from "../domain/Type";

/**
 * The `@Deprecated()` decorators wraps the given method in such a way that it is marked as deprecated.
 *
 * ```typescript
 * provide Foo {
 *
 * @Deprecated("Foo.method: Use Foo.method2 instead")
 * public method() {
 *
 * }
 * ```
 *
 * When called, @Deprecated() will return a function that will emit a `DeprecationWarning` using the `process.on('warning')` event.
 * By default, this warning will be emitted and printed to `stderr` exactly once, the first time it is called. After the warning is emitted, the wrapped method is called.
 *
 * If either the `--no-deprecation` or `--no-warnings` command line flags are used, or if the `process.noDeprecation`
 * property is set to `true` prior to the first deprecation warning, the `@Deprecated()` decorators does nothing.
 *
 * If the `--trace-deprecation` or `--trace-warnings` command line flags are set, or the `process.traceDeprecation`
 * property is set to `true`, a warning and a stack trace are printed to stderr the first time the deprecated function is called.
 *
 * If the `--throw-deprecation` command line flag is set, or the `process.throwDeprecation` property is set to `true`,
 * then an exception will be thrown when the deprecated function is called.
 *
 * The `--throw-deprecation` command line flag and `process.throwDeprecation` property take precedence over `--trace-deprecation`
 * and `process.traceDeprecation`.
 *
 * @param message
 * @returns {Function}
 * @decorator
 */
export function Deprecated(message: string): Function {
  return (target: Type<any>, targetKey: string, descriptor: TypedPropertyDescriptor<any>) => {
    const originalMethod = descriptor.value;

    descriptor.value = require("util").deprecate(originalMethod, message);

    return descriptor;
  };
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>KDOVisualization</title>

    <form id="form1" runat="server" style="height:100%">

            <input id="telefonicaText" type="text" size="30" maxlength="30">
            <input type="button" id="telefonicaButton" value="Send Filter to Pivot Viewer">

            <object id="pivotControl" data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
		      <param name="source" value="ClientBin/KDOVisualization.xap"/>
		      <param name="onError" value="onSilverlightError" />
		      <param name="background" value="white" />
		      <param name="minRuntimeVersion" value="5.0.61118.0" />
		      <param name="autoUpgrade" value="true" />

	        </object>

    </form>


text:
import sys
import os
import tarfile
import argparse
from os.path import dirname, join, abspath
from shutil import copy, copytree, rmtree
from subprocess import check_call
from contextlib import closing

parser = argparse.ArgumentParser(
        description='Build dynamic cluster RPM',
        )
parser.add_argument('buildid',
        help='The build id to use i.e. the bit after the salt version in the package name',
        )
args = parser.parse_args()

src = abspath(join(dirname(__file__), '..'))

sys.path.append(src)

from dynamiccluster.__version__ import version

rpmbuild = join(os.environ['HOME'], 'rpmbuild')
if os.path.exists(join(rpmbuild, 'SOURCES')):
    rmtree(join(rpmbuild, 'SOURCES'))
copy(join(src, 'pkg/rpm.spec'), join(rpmbuild, 'SPECS'))
os.makedirs(join(rpmbuild, 'SOURCES'))
copy(join(src, 'scripts/initd-script'), join(rpmbuild, 'SOURCES'))
copy(join(src, 'config/dynamiccluster.yaml'), join(rpmbuild, 'SOURCES'))
#copytree(src, join(rpmbuild, 'SOURCES'))
# for f in os.listdir(src):
#     if f in ['bin', 'pkg', 'tests', 'README.md', 'test.sh']:
#         continue
#     print('copying %s...'%f)
#     if os.path.isdir(join(src, f)):
#         copytree(join(src, f), join(rpmbuild, 'SOURCES'))
#     else:
#         copy(join(src, f), join(rpmbuild, 'SOURCES'))

def srcfilter(ti):
    if '/.git' in ti.name:
        return None
    return ti

with closing(tarfile.open(join(rpmbuild, 'SOURCES/dynamiccluster-%s.tar.gz' % version), 'w|gz')) as tf:
    tf.add(src, arcname='dynamiccluster-%s' % version)

cmd = ['rpmbuild', '-bb',
       '--define=version %s' % version,
       '--define=buildid %s' % args.buildid,
       'rpm.spec']
print('Executing: %s' % ' '.join('"%s"' % c for c in cmd))
check_call(cmd, cwd=join(rpmbuild, 'SPECS'))


text:
package router

import (
	"container/list"
	"sync"
	"time"

	"github.com/juju/errors"
	log "github.com/ngaut/logging"
	"github.com/pcncadcache/cachesystem/pkg/proxy/parser"
	"github.com/pcncadcache/cachesystem/pkg/proxy/redisconn"
)

type taskRunner struct {
	evtbus     chan interface{}
	in         chan interface{} //*PipelineRequest
	out        chan interface{}
	redisAddr  string
	tasks      *list.List
	c          *redisconn.Conn
	netTimeout int //second
	closed     bool
	wgClose    *sync.WaitGroup
}

func (tr *taskRunner) readloop() {
	for {
		resp, err := parser.Parse(tr.c.BufioReader())
		if err != nil {
			tr.out <- err
			return
		}

		tr.out <- resp
	}
}

func (tr *taskRunner) dowrite(r *PipelineRequest, flush bool) error {
	b, err := r.req.Bytes()
	if err != nil {
		return errors.Trace(err)
	}

	_, err = tr.c.Write(b)
	if err != nil {
		return errors.Trace(err)
	}

	if flush {
		return errors.Trace(tr.c.Flush())
	}

	return nil
}

func (tr *taskRunner) handleTask(r *PipelineRequest, flush bool) error {
	if r == nil && flush { //just flush
		return tr.c.Flush()
	}

	tr.tasks.PushBack(r)

	return errors.Trace(tr.dowrite(r, flush))
}

func (tr *taskRunner) cleanupQueueTasks() {
	for {
		select {
		case t := <-tr.in:
			tr.processTask(t)
		default:
			return
		}
	}
}

func (tr *taskRunner) cleanupOutgoingTasks(err error) {
	for e := tr.tasks.Front(); e != nil; {
		req := e.Value.(*PipelineRequest)
		log.Info("clean up", req)
		req.backQ <- &PipelineResponse{ctx: req, resp: nil, err: err}
		next := e.Next()
		tr.tasks.Remove(e)
		e = next
	}
}

func (tr *taskRunner) tryRecover(err error) error {
	log.Warning("try recover from ", err)
	tr.cleanupOutgoingTasks(err)
	//try to recover
	c, err := redisconn.NewConnection(tr.redisAddr, tr.netTimeout)
	if err != nil {
		tr.cleanupQueueTasks() //do not block dispatcher
		log.Warning(err)
		time.Sleep(1 * time.Second)
		return err
	}

	tr.c = c
	go tr.readloop()

	return nil
}

func (tr *taskRunner) getOutgoingResponse() {
	for {
		if tr.tasks.Len() == 0 {
			return
		}

		resp := <-tr.out
		err := tr.handleResponse(resp)
		if err != nil {
			tr.cleanupOutgoingTasks(err)
		}
	}
}

func (tr *taskRunner) processTask(t interface{}) error {
	switch t.(type) {
	case *PipelineRequest:
		r := t.(*PipelineRequest)
		var flush bool
		if len(tr.in) == 0 { //force flush
			flush = true
		}

		return tr.handleTask(r, flush)
	case *sync.WaitGroup: //close taskrunner
		err := tr.handleTask(nil, true) //flush
		//get all response for out going request
		tr.getOutgoingResponse()
		tr.closed = true
		tr.wgClose = t.(*sync.WaitGroup)
		return err
	}

	return nil
}

func (tr *taskRunner) handleResponse(e interface{}) error {
	switch e.(type) {
	case error:
		return e.(error)
	case *parser.Resp:
		resp := e.(*parser.Resp)
		e := tr.tasks.Front()
		req := e.Value.(*PipelineRequest)
		req.backQ <- &PipelineResponse{ctx: req, resp: resp, err: nil}
		tr.tasks.Remove(e)
		return nil
	}

	return nil
}

func (tr *taskRunner) writeloop() {
	var err error
	for {
		if tr.closed && tr.tasks.Len() == 0 {
			log.Warning("exit taskrunner", tr.redisAddr)
			tr.wgClose.Done()
			tr.c.Close()
			return
		}

		if err != nil { //clean up
			err = tr.tryRecover(err)
			if err != nil {
				continue
			}
		}

		select {
		case t := <-tr.in:
			err = tr.processTask(t)
		case resp := <-tr.out:
			err = tr.handleResponse(resp)
		}
	}
}

func NewTaskRunner(addr string, netTimeout int) (*taskRunner, error) {
	tr := &taskRunner{
		in:         make(chan interface{}, 1000),
		out:        make(chan interface{}, 1000),
		redisAddr:  addr,
		tasks:      list.New(),
		netTimeout: netTimeout,
	}

	c, err := redisconn.NewConnection(addr, netTimeout)
	if err != nil {
		return nil, err
	}

	tr.c = c

	go tr.writeloop()
	go tr.readloop()

	return tr, nil
}


text:
(function() {
'use strict'

angular.module('ShoppingListCheckOff', [])
.controller("ToBuyController", ToBuyController)
.controller("AlreadyBoughtController", AlreadyBoughtController)
.service("ItemListService", ItemListService)

ToBuyController.$inject = ["ItemListService"]
function ToBuyController(ItemListService) {
  var buy = this
  buy.buyMessage = false

  buy.buyList = ItemListService.getBuyItem()

  buy.removeBuyItem = function(itemIndex) {
    ItemListService.buyToBoughtList(itemIndex)

    if (ItemListService.getBuyItem().length === 0) {
      buy.buyMessage = !buy.buyMessage
    }
  }
}

AlreadyBoughtController.$inject = ["ItemListService"]
function AlreadyBoughtController(ItemListService) {
  var bought = this
  bought.boughtMessage = true

  bought.boughtList = ItemListService.getBoughtList()
}

function ItemListService() {
  var service = this

  // List of shopping items
  var buyItems = [
                   {
                     name: "cookies",
                     quantity: 10
                   },
                   {
                     name: "chips",
                     quantity: 8
                   },
                   {
                     name: "Pepsi",
                     quantity: 4
                   },
                   {
                     name: "bread",
                     quantity: 5
                   },
                   {
                     name: "coffee",
                     quantity: 11
                   }
                 ]
  var boughtItems = []

  service.buyToBoughtList = function(itemIndex) {
    boughtItems.push(buyItems[itemIndex])
    buyItems.splice(itemIndex, 1)
  }

  service.getBuyItem = function() {
    return buyItems
  }

  service.getBoughtList = function() {
    return boughtItems
  }
}

})()


text:
package techreborn.blockentity.machine.tier1;

import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.CraftingInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.recipe.CraftingRecipe;
import net.minecraft.recipe.Ingredient;
import net.minecraft.recipe.RecipeType;
import net.minecraft.screen.ScreenHandler;
import net.minecraft.sound.SoundCategory;
import net.minecraft.util.collection.DefaultedList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.World;
import org.apache.commons.lang3.tuple.Pair;
import org.jetbrains.annotations.Nullable;
import reborncore.api.IToolDrop;
import reborncore.api.blockentity.InventoryProvider;
import reborncore.common.blockentity.MachineBaseBlockEntity;
import reborncore.common.powerSystem.PowerAcceptorBlockEntity;
import reborncore.common.screen.BuiltScreenHandler;
import reborncore.common.screen.BuiltScreenHandlerProvider;
import reborncore.common.screen.builder.ScreenHandlerBuilder;
import reborncore.common.util.ItemUtils;
import reborncore.common.util.RebornInventory;
import techreborn.config.TechRebornConfig;
import techreborn.init.ModSounds;
import techreborn.init.TRBlockEntities;
import techreborn.init.TRContent;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Created by modmuss50 on 20/06/2017.
 */
public class AutoCraftingTableBlockEntity extends PowerAcceptorBlockEntity
		implements IToolDrop, InventoryProvider, BuiltScreenHandlerProvider {

	public static final int CRAFTING_HEIGHT = 3;
	public static final int CRAFTING_WIDTH = 3;
	public static final int CRAFTING_AREA = CRAFTING_HEIGHT*CRAFTING_WIDTH;

	public RebornInventory<AutoCraftingTableBlockEntity> inventory = new RebornInventory<>(CRAFTING_AREA+2, "AutoCraftingTableBlockEntity", 64, this);
	private final int OUTPUT_SLOT = CRAFTING_AREA; // first slot is indexed by 0, so this is the last non crafting slot
	private final int EXTRA_OUTPUT_SLOT = CRAFTING_AREA + 1;

	public int progress;
	public int maxProgress = 120;
	public int euTick = 10;
	public int balanceSlot = 0;

	CraftingInventory inventoryCrafting = null;
	CraftingRecipe lastRecipe = null;

	Item[] layoutInv = new Item[CRAFTING_AREA];

	public boolean locked = false;

	public AutoCraftingTableBlockEntity(BlockPos pos, BlockState state) {
		super(TRBlockEntities.AUTO_CRAFTING_TABLE, pos, state);
	}

	@Nullable
	public CraftingRecipe getCurrentRecipe() {
		if (world == null) return null;
		CraftingInventory crafting = getCraftingInventory();
		if (crafting.isEmpty()) return null;

		if (lastRecipe != null && lastRecipe.matches(crafting, world)) return lastRecipe;

		Item[] currentInvLayout = getCraftingLayout(crafting);
		if(Arrays.equals(layoutInv, currentInvLayout)) return null;

		layoutInv = currentInvLayout;

		Optional<CraftingRecipe> testRecipe = world.getRecipeManager().getFirstMatch(RecipeType.CRAFTING, crafting, world);
		if (testRecipe.isPresent()) {
			lastRecipe = testRecipe.get();
			return lastRecipe;
		}

		return null;
	}

	private Item[] getCraftingLayout(CraftingInventory craftingInventory){
		Item[] layout = new Item[CRAFTING_AREA];
		for (int i = 0; i < CRAFTING_AREA; i++) {
			layout[i] = craftingInventory.getStack(i).getItem();
		}
		return layout;
	}

	private CraftingInventory getCraftingInventory() {
		if (inventoryCrafting == null) {
			inventoryCrafting = new CraftingInventory(new ScreenHandler(null, -1) {
				@Override
				public ItemStack transferSlot(PlayerEntity player, int index) {
					return ItemStack.EMPTY;
				}

				@Override
				public boolean canUse(PlayerEntity playerIn) {
					return false;
				}
			}, CRAFTING_WIDTH, CRAFTING_HEIGHT);
		}
		for (int i = 0; i < CRAFTING_AREA; i++) {
			inventoryCrafting.setStack(i, inventory.getStack(i));
		}
		return inventoryCrafting;
	}

	// Check if we have recipe, inputs and space for outputs
	private boolean canMake(CraftingRecipe recipe) {
		if (world == null) return false;
		if (recipe == null) return false;

		CraftingInventory crafting = getCraftingInventory();
		if (crafting.isEmpty()) return false;

		// Don't allow recipe to change (Keep at least one of each slot stocked, assuming it's actually a recipe)
		if (locked) {
			for(int i = 0; i < CRAFTING_AREA; i++){
				if(crafting.getStack(i).getCount() == 1){
					return false;
				}
			}
		}

		if (!recipe.matches(crafting, world)) return false;

		if (!hasOutputSpace(recipe.getOutput(), OUTPUT_SLOT)) return false;

		DefaultedList<ItemStack> remainingStacks = recipe.getRemainder(crafting);
		for (ItemStack stack : remainingStacks) {
			if (!stack.isEmpty() && !hasRoomForExtraItem(stack)) return false;
		}

		return true;
	}

	private boolean hasRoomForExtraItem(ItemStack stack) {
		ItemStack extraOutputSlot = inventory.getStack(EXTRA_OUTPUT_SLOT);
		if (extraOutputSlot.isEmpty()) {
			return true;
		}
		return hasOutputSpace(stack, EXTRA_OUTPUT_SLOT);
	}

	private boolean hasOutputSpace(ItemStack output, int slot) {
		ItemStack stack = inventory.getStack(slot);
		if (stack.isEmpty()) {
			return true;
		}
		if (ItemUtils.isItemEqual(stack, output, true, true)) {
			return stack.getMaxCount() > stack.getCount() + output.getCount();
		}
		return false;
	}

	private boolean make(CraftingRecipe recipe) {
		if (recipe == null || !canMake(recipe)) {
			return false;
		}
		DefaultedList<Ingredient> ingredients = recipe.getIngredients();
		// each slot can only be used once because in canMake we only checked if decrement by 1 still retains the recipe
		// otherwise recipes can break when an ingredient is used multiple times
		boolean[] slotUsed = new boolean[CRAFTING_AREA];
		for (int i = 0; i < recipe.getIngredients().size(); i++) {
			Ingredient ingredient = ingredients.get(i);
			// Looks for the best slot to take it from
			ItemStack bestSlot = inventory.getStack(i);
			if (ingredient.test(bestSlot) && !slotUsed[i]) {
				slotUsed[i] = true;
				ItemStack remainderStack = getRemainderItem(bestSlot);
				bestSlot.decrement(1);
				if (!remainderStack.isEmpty()) {
					moveExtraOutput(remainderStack);
				}

			} else {
				// check all slots in search of the ingredient
				for (int j = 0; j < CRAFTING_AREA; j++) {
					ItemStack stack = inventory.getStack(j);
					if (ingredient.test(stack) && !slotUsed[j]) {
						slotUsed[j] = true;
						ItemStack remainderStack = getRemainderItem(stack);
						stack.decrement(1);
						if (!remainderStack.isEmpty()) {
							moveExtraOutput(remainderStack);
						}
					}
				}
			}
		}
		ItemStack output = inventory.getStack(OUTPUT_SLOT);
		ItemStack outputStack = recipe.craft(getCraftingInventory());
		if (output.isEmpty()) {
			inventory.setStack(OUTPUT_SLOT, outputStack.copy());
		} else {
			output.increment(recipe.getOutput().getCount());
		}
		return true;
	}

	private void moveExtraOutput(ItemStack stack){
		ItemStack currentExtraOutput = inventory.getStack(EXTRA_OUTPUT_SLOT);
		if (currentExtraOutput.isEmpty()){
			inventory.setStack(EXTRA_OUTPUT_SLOT, stack.copy());
		} else {
			currentExtraOutput.increment(stack.getCount());
		}
	}

	private ItemStack getRemainderItem(ItemStack stack) {
		if (stack.getItem().hasRecipeRemainder()) {
			return new ItemStack(stack.getItem().getRecipeRemainder());
		}

		return ItemStack.EMPTY;
	}

	private Optional<CraftingInventory> balanceRecipe(CraftingInventory craftCache) {
		if (world == null || world.isClient) return Optional.empty();
		if (craftCache.isEmpty()) return Optional.empty();

		CraftingRecipe currentRecipe = getCurrentRecipe();
		if (currentRecipe == null) {
			return Optional.empty();
		}

		balanceSlot++;
		if (balanceSlot > craftCache.size()) {
			balanceSlot = 0;
		}
		// Find the best slot for each item in a recipe, and move it if needed
		ItemStack sourceStack = inventory.getStack(balanceSlot);
		if (sourceStack.isEmpty()) {
			return Optional.empty();
		}
		List<Integer> possibleSlots = new ArrayList<>();
		for (int s = 0; s < currentRecipe.getIngredients().size(); s++) {
			for (int i = 0; i < CRAFTING_AREA; i++) {
				if (possibleSlots.contains(i)) {
					continue;
				}
				ItemStack stackInSlot = inventory.getStack(i);
				Ingredient ingredient = currentRecipe.getIngredients().get(s);
				if (ingredient != Ingredient.EMPTY && ingredient.test(sourceStack)) {
					if (stackInSlot.getItem() == sourceStack.getItem()) {
						possibleSlots.add(i);
						break;
					}
				}
			}

		}

		if (!possibleSlots.isEmpty()) {
			int totalItems = possibleSlots.stream()
					.mapToInt(value -> inventory.getStack(value).getCount()).sum();
			int slots = possibleSlots.size();

			//This makes an array of ints with the best possible slot distribution
			int[] split = new int[slots];
			int remainder = totalItems % slots;
			Arrays.fill(split, totalItems / slots);
			while (remainder > 0) {
				for (int i = 0; i < split.length; i++) {
					if (remainder > 0) {
						split[i] += 1;
						remainder--;
					}
				}
			}

			List<Integer> slotDistribution = possibleSlots.stream()
					.mapToInt(value -> inventory.getStack(value).getCount())
					.boxed().collect(Collectors.toList());

			boolean needsBalance = false;
			for (int required : split) {
				if (slotDistribution.contains(required)) {
					//We need to remove the int, not at the int, this seems to work around that
					slotDistribution.remove(Integer.valueOf(required));
				} else {
					needsBalance = true;
				}
			}
			if (!needsBalance) {
				return Optional.empty();
			}
		} else {
			return Optional.empty();
		}

		//Slot, count
		Pair<Integer, Integer> bestSlot = null;
		for (Integer slot : possibleSlots) {
			ItemStack slotStack = inventory.getStack(slot);
			if (slotStack.isEmpty()) {
				bestSlot = Pair.of(slot, 0);
			}
			if (bestSlot == null) {
				bestSlot = Pair.of(slot, slotStack.getCount());
			} else if (bestSlot.getRight() >= slotStack.getCount()) {
				bestSlot = Pair.of(slot, slotStack.getCount());
			}
		}
		if (bestSlot.getLeft() == balanceSlot
				|| bestSlot.getRight() == sourceStack.getCount()
				|| inventory.getStack(bestSlot.getLeft()).isEmpty()
				|| !ItemUtils.isItemEqual(sourceStack, inventory.getStack(bestSlot.getLeft()), true, true)) {
			return Optional.empty();
		}
		sourceStack.decrement(1);
		inventory.getStack(bestSlot.getLeft()).increment(1);
		inventory.setHashChanged();

		return Optional.of(getCraftingInventory());
	}

	// PowerAcceptorBlockEntity
	@Override
	public void tick(World world, BlockPos pos, BlockState state, MachineBaseBlockEntity blockEntity) {
		super.tick(world, pos, state, blockEntity);
		if (world == null || world.isClient) {
			return;
		}
		CraftingRecipe recipe = getCurrentRecipe();
		if (recipe == null) {
			progress = 0;
			return;
		}

		Optional<CraftingInventory> balanceResult = balanceRecipe(getCraftingInventory());
		balanceResult.ifPresent(craftingInventory -> inventoryCrafting = craftingInventory);

		if (progress >= maxProgress) {
			if (make(recipe)) {
				progress = 0;
			}
		} else {
			if (canMake(recipe)) {
				if (getStored() > euTick) {
					progress++;
					if (progress == 1) {
						world.playSound(null, pos.getX(), pos.getY(), pos.getZ(), ModSounds.AUTO_CRAFTING,
								SoundCategory.BLOCKS, 0.3F, 0.8F);
					}
					useEnergy(euTick);
				}
			} else {
				progress = 0;
			}
		}
	}

	@Override
	public long getBaseMaxPower() {
		return TechRebornConfig.autoCraftingTableMaxEnergy;
	}

	@Override
	public long getBaseMaxOutput() {
		return 0;
	}

	@Override
	public long getBaseMaxInput() {
		return TechRebornConfig.autoCraftingTableMaxInput;
	}

	@Override
	public boolean canProvideEnergy(@Nullable Direction side) {
		return false;
	}

	@Override
	public void writeNbt(NbtCompound tag) {
		tag.putBoolean("locked", locked);
		super.writeNbt(tag);
	}

	@Override
	public void readNbt(NbtCompound tag) {
		if (tag.contains("locked")) {
			locked = tag.getBoolean("locked");
		}
		super.readNbt(tag);
	}

	// MachineBaseBlockEntity
	@Override
	public boolean canBeUpgraded() {
		return false;
	}

	@Override
	public boolean hasSlotConfig() {
		return true;
	}

	// IToolDrop
	@Override
	public ItemStack getToolDrop(PlayerEntity playerIn) {
		return TRContent.Machine.AUTO_CRAFTING_TABLE.getStack();
	}

	// InventoryProvider
	@Override
	public RebornInventory<AutoCraftingTableBlockEntity> getInventory() {
		return inventory;
	}

	// BuiltScreenHandlerProvider
	@Override
	public BuiltScreenHandler createScreenHandler(int syncID, PlayerEntity player) {
		return new ScreenHandlerBuilder("autocraftingtable").player(player.getInventory()).inventory().hotbar().addInventory()
				.blockEntity(this)
				.slot(0, 28, 25).slot(1, 46, 25).slot(2, 64, 25)
				.slot(3, 28, 43).slot(4, 46, 43).slot(5, 64, 43)
				.slot(6, 28, 61).slot(7, 46, 61).slot(8, 64, 61)
				.outputSlot(OUTPUT_SLOT, 145, 42)
				.outputSlot(EXTRA_OUTPUT_SLOT, 145, 70)
				.syncEnergyValue().sync(this::getProgress, this::setProgress)
				.sync(this::getMaxProgress, this::setMaxProgress)
				.sync(this::getLockedInt, this::setLockedInt).addInventory().create(this, syncID);
	}

	public int getProgress() {
		return progress;
	}

	public void setProgress(int progress) {
		this.progress = progress;
	}

	public int getMaxProgress() {
		if (maxProgress == 0) {
			maxProgress = 1;
		}
		return maxProgress;
	}

	public void setMaxProgress(int maxProgress) {
		this.maxProgress = maxProgress;
	}

	public int getLockedInt() {
		return locked ? 1 : 0;
	}

	public void setLockedInt(int lockedInt) {
		locked = lockedInt == 1;
	}

}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('icekit_events', '0024_auto_20170320_1824'),
    ]

    operations = [
        migrations.AddField(
            model_name='eventbase',
            name='admin_notes',
            field=models.TextField(help_text=b"Administrator's notes about this content", blank=True),
        ),
        migrations.AddField(
            model_name='eventbase',
            name='brief',
            field=models.TextField(help_text=b'A document brief describing the purpose of this content', blank=True),
        ),
    ]


text:
class CreateWebhooks < ActiveRecord::Migration[5.1]
  def change
    create_table :webhooks do |t|
      t.string :token
      t.string :team_id
      t.string :team_domain
      t.string :channel_id
      t.string :channel_name
      t.timestamp :timestamp
      t.string :user_id
      t.string :user_name
      t.string :text
      t.string :trigger_word

      t.timestamps
    end
  end
end


text:
odoo.define("pos_debt_sync", function(require) {
    var models = require("point_of_sale.models");

    var PosModelSuper = models.PosModel;
    models.PosModel = models.PosModel.extend({
        initialize: function() {
            PosModelSuper.prototype.initialize.apply(this, arguments);
            var self = this;
            this.bus.add_channel_callback(
                "pos_debt_notebook_sync",
                this.on_debt_updates,
                this
            );
            // Poll connection handlers
            this.ready.then(function() {
                var longpolling_connection = (self.sync_bus || self.bus)
                    .longpolling_connection;
                // Reload_debts request passed, but longpoll is offline
                self.on(
                    "updateDebtHistory",
                    function(partner_ids) {
                        if (!longpolling_connection.is_online) {
                            longpolling_connection.send_ping();
                        }
                    },
                    self
                );
                // Reload_debts request haven't passed, but longpoll is online
                self.on(
                    "updateDebtHistoryFail",
                    function() {
                        if (longpolling_connection.is_online) {
                            longpolling_connection.send_ping();
                        }
                    },
                    self
                );
                // Poll_connection is changed, and longpoll status is online now
                longpolling_connection.on(
                    "change:poll_connection",
                    function(status) {
                        if (status) {
                            self.after_restoring_connection();
                        }
                    },
                    self
                );
            });
        },
        on_debt_updates: function(message) {
            this.reload_debts(message.updated_partners);
        },
        _on_load_debts: function(debts) {
            var self = this;
            var unsent_orders = _.filter(this.db.get_orders(), function(o) {
                return o.data.updates_debt;
            });
            if (unsent_orders) {
                // Since unsent orders are presented it means that connection was recently restored,
                // request for updating data of offline order partners will be sent right after offline orders is pushed.
                // To prevent incorrect debt rendering we delete the partner data come from the server before offline orders were sent

                var offline_order_partners = _.map(unsent_orders, function(o) {
                    return o.data.partner_id;
                });
                debts = _.filter(debts, function(deb) {
                    return !_.contains(offline_order_partners, deb.partner_id);
                });
            }
            PosModelSuper.prototype._on_load_debts.apply(this, [debts]);
        },
        after_restoring_connection: function() {
            var self = this;
            var partners_to_reload = [];
            _.each(this.get_order_list(), function(o) {
                if (o.get_client()) {
                    partners_to_reload.push(o.get_client().id);
                }
            });
            _.each(this.db.get_orders(), function(o) {
                if (o.data.updates_debt && o.data.partner_id) {
                    partners_to_reload.push(o.data.partner_id);
                }
            });
            var client_list_screen = this.gui.screen_instances.clientlist;
            var partner = false;
            if (
                client_list_screen &&
                client_list_screen.clientlist_screen_is_opened()
            ) {
                partner =
                    client_list_screen.new_client ||
                    client_list_screen.pos.get_client();
                if (partner) {
                    partners_to_reload.push(partner.id);
                }
            }

            this.push_order(null, {show_error: true}).then(function() {
                if (partners_to_reload.length) {
                    self.reload_debts(_.uniq(partners_to_reload), 0, {shadow: false});
                }
            });
        },
    });
});


text:
EULER
=====

SPOILER ALERT! THIS IS MY PERSONAL SOLUTIONS REPOSITORY FOR PROJECT EULER

- Folder names are euler levels
- Inside folders are multiple languages


text:
armada
======

## DEPRECATED

The Groups API is no longer used


text:
<?php

return function ($step = NULL, $params = []) {
    App::$cur->db->createTable('textblocks_block', [
        'block_id' => 'pk',
        'block_code' => 'varchar(255) NOT NULL',
        'block_name' => 'varchar(255) NOT NULL',
        'block_text' => 'text NOT NULL',
        'block_date_create' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP',
    ]);
};


text: <button id="like-close-button" ng-click="closeModal()">Cerrar</button>


text:
import React from 'react'
import styled from 'styled-components'
import { Row, Col } from '../../src/index'

const Headline = styled.h1`
  font-size: 2.5rem;

  @media only screen and (min-width: 48rem) {
    font-size: 4rem;
    margin-bottom: 2rem;
  }
`

const Description = styled(p =>
  <Row center='xs'><Col>{p.children}</Col></Row>
)`
  font-size: .95rem;
  margin-bottom: 2rem;

  @media only screen and (min-width: 48rem) {
    font-size: 1.35rem;
  }
`

const Button = styled.a`
  position: relative;
  display: inline-block;
  box-sizing: border-box;
  min-width: 11rem;
  padding: 0 4rem;
  margin: 1rem;
  height: 3rem;
  line-height: 3rem;
  border: 1px solid #007FFF;
  border-radius: 2px;
  color: #007FFF;
  font-size: 1.25rem;
  transition: background-color,.15s;
  text-decoration: none;

  &:hover {
    background: #39F;
    border-color: #39F;
    color: #FFF;
    text-shadow: 0 1px #007FFF;
  }
`

const Hero = styled(props =>

    <Row center='xs'>
      <Headline>React Styled Flexboxgrid</Headline>
    </Row>
    <Description>

Grid system based on styled-components and flexbox

Highly inspired by react-flexbox-grid and flexboxgrid.css

    </Description>
    <Row center='xs'>
      <Button href='https://github.com/loicmahieu/react-styled-flexboxgrid'>Github</Button>
    </Row>

)`
  background: white;
  box-sizing: border-box;
  padding: 2rem;
  border: 1px solid white;
  border-radius: 2px;
`

export default Hero


text:
<?php
namespace Aws\ApplicationAutoScaling;

use Aws\AwsClient;

/**
 * This client is used to interact with the **Application Auto Scaling** service.
 * @method \Aws\Result deleteScalingPolicy(array $args = [])
 * @method \GuzzleHttp\Promise\Promise deleteScalingPolicyAsync(array $args = [])
 * @method \Aws\Result deleteScheduledAction(array $args = [])
 * @method \GuzzleHttp\Promise\Promise deleteScheduledActionAsync(array $args = [])
 * @method \Aws\Result deregisterScalableTarget(array $args = [])
 * @method \GuzzleHttp\Promise\Promise deregisterScalableTargetAsync(array $args = [])
 * @method \Aws\Result describeScalableTargets(array $args = [])
 * @method \GuzzleHttp\Promise\Promise describeScalableTargetsAsync(array $args = [])
 * @method \Aws\Result describeScalingActivities(array $args = [])
 * @method \GuzzleHttp\Promise\Promise describeScalingActivitiesAsync(array $args = [])
 * @method \Aws\Result describeScalingPolicies(array $args = [])
 * @method \GuzzleHttp\Promise\Promise describeScalingPoliciesAsync(array $args = [])
 * @method \Aws\Result describeScheduledActions(array $args = [])
 * @method \GuzzleHttp\Promise\Promise describeScheduledActionsAsync(array $args = [])
 * @method \Aws\Result putScalingPolicy(array $args = [])
 * @method \GuzzleHttp\Promise\Promise putScalingPolicyAsync(array $args = [])
 * @method \Aws\Result putScheduledAction(array $args = [])
 * @method \GuzzleHttp\Promise\Promise putScheduledActionAsync(array $args = [])
 * @method \Aws\Result registerScalableTarget(array $args = [])
 * @method \GuzzleHttp\Promise\Promise registerScalableTargetAsync(array $args = [])
 */
class ApplicationAutoScalingClient extends AwsClient {}


text:
<!DOCTYPE html>

     Proper spacing

     Proper spacing


text:
layout: post
title: Fetish slut takes huge black cocks
titleinfo: pornvd
desc: Watch Fetish slut takes huge black cocks. Pornhub is the ultimate xxx porn and sex site.
---

Fetish slut takes huge black cocks

Watch Fetish slut takes huge black cocks. Pornhub is the ultimate xxx porn and sex site.


text:
package org.kaaproject.kaa.server.admin.client.mvp.view.widget;

import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.HasConstrainedValue;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.RequiresResize;

import org.kaaproject.avro.ui.gwt.client.widget.FqnReferenceBox;
import org.kaaproject.avro.ui.shared.Fqn;
import org.kaaproject.avro.ui.shared.FqnKey;
import org.kaaproject.avro.ui.shared.FqnVersion;
import org.kaaproject.kaa.server.admin.client.util.Utils;
import org.kaaproject.kaa.server.admin.shared.schema.CtlSchemaReferenceDto;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CtlSchemaReferenceBox
    extends HorizontalPanel
    implements HasConstrainedValue<CtlSchemaReferenceDto>, RequiresResize {

  private CtlSchemaReferenceDto value;

  private FqnReferenceBox fqnReferenceBox;
  private IntegerListBox versionsBox;

  private Map<Fqn, List<Integer>> fqnVersionsMap = new HashMap<>();
  private Map<FqnVersion, CtlSchemaReferenceDto> fqnVersionToReferenceMap = new HashMap<>();

  /**
   * Instantiates a new CtlSchemaReferenceBox.
   */
  public CtlSchemaReferenceBox() {
    fqnReferenceBox = new FqnReferenceBox(Utils.constants.schemaReferencePrompt());
    fqnReferenceBox.setWidth("100%");
    add(fqnReferenceBox);
    this.setCellWidth(fqnReferenceBox, "100%");
    versionsBox = new IntegerListBox();
    versionsBox.setWidth("60px");
    versionsBox.setHeight("100%");
    versionsBox.getElement().getStyle().setPaddingTop(2, Unit.PX);
    versionsBox.getElement().getStyle().setPaddingBottom(1, Unit.PX);
    versionsBox.getElement().getStyle().setMarginLeft(6, Unit.PX);
    add(versionsBox);

    fqnReferenceBox.addValueChangeHandler(new ValueChangeHandler<FqnKey>() {
      @Override
      public void onValueChange(ValueChangeEvent<FqnKey> event) {
        updateValueByFqnKeyAndVersion(event.getValue(), null);
      }
    });

    versionsBox.addValueChangeHandler(new ValueChangeHandler<Integer>() {
      @Override
      public void onValueChange(ValueChangeEvent<Integer> event) {
        updateValueByFqnKeyAndVersion(fqnReferenceBox.getValue(), event.getValue());
      }
    });
  }

  private void updateValueByFqnKeyAndVersion(FqnKey fqnKey, Integer version) {
    CtlSchemaReferenceDto newValue = null;
    if (fqnKey != null) {
      Fqn fqn = fqnKey.getFqn();
      if (version == null) {
        List<Integer> versions = fqnVersionsMap.get(fqn);
        version = Collections.max(versions);
      }
      FqnVersion fqnVersion = new FqnVersion(fqn, version);
      newValue = fqnVersionToReferenceMap.get(fqnVersion);
    }
    setValue(newValue, true);
  }

  @Override
  public CtlSchemaReferenceDto getValue() {
    return value;
  }

  @Override
  public void setValue(CtlSchemaReferenceDto value) {
    setValue(value, false);
  }

  @Override
  public void setValue(CtlSchemaReferenceDto value, boolean fireEvents) {
    if (value == this.value
        || (this.value != null && this.value.equals(value))) {
      return;
    }
    CtlSchemaReferenceDto before = this.value;
    this.value = value;

    updateBox();

    if (fireEvents) {
      ValueChangeEvent.fireIfNotEqual(this, before, value);
    }
  }

  @Override
  public HandlerRegistration addValueChangeHandler(
      ValueChangeHandler<CtlSchemaReferenceDto> handler) {
    return addHandler(handler, ValueChangeEvent.getType());
  }

  @Override
  public void setAcceptableValues(Collection<CtlSchemaReferenceDto> values) {
    fqnVersionsMap.clear();
    fqnVersionToReferenceMap.clear();
    Map<FqnKey, Fqn> declaredFqns = new HashMap<>();

    for (CtlSchemaReferenceDto ctlReference : values) {
      Fqn fqn = new Fqn(ctlReference.getMetaInfo().getFqn());
      FqnKey fqnKey = new FqnKey(fqn);
      declaredFqns.put(fqnKey, fqn);

      List<Integer> versions = fqnVersionsMap.get(fqn);
      if (versions == null) {
        versions = new ArrayList<>();
        fqnVersionsMap.put(fqn, versions);
      }
      versions.add(ctlReference.getVersion());

      fqnVersionToReferenceMap.put(new FqnVersion(fqn, ctlReference.getVersion()), ctlReference);
    }
    fqnReferenceBox.updateDeclaredFqns(declaredFqns);

    updateBox();
  }

  /**
   * Reset.
   */
  public void reset() {
    value = null;
    fqnVersionsMap.clear();
    fqnVersionToReferenceMap.clear();
    fqnReferenceBox.reset();
    versionsBox.reset();
  }

  private void updateBox() {
    if (value != null) {
      Fqn fqn = new Fqn(value.getMetaInfo().getFqn());
      fqnReferenceBox.setValue(new FqnKey(fqn));
      List<Integer> versions = fqnVersionsMap.get(fqn);
      Collections.sort(versions);
      versionsBox.setValue(value.getVersion());
      versionsBox.setAcceptableValues(versions);
    } else {
      fqnReferenceBox.setValue(null);
      versionsBox.reset();
    }
  }

  @Override
  public void onResize() {
    fqnReferenceBox.onShown();
  }

}


text:
<?php

namespace Azuki;
/**
 * Inspired by fabpot's Pimple: https://github.com/fabpot/Pimple
 */
class Registry
{
    private static $instance;
    private $store = [];

    /**
     * @return Registry
     */
    public static function getInstance(): Registry
    {
        if (is_null(self::$instance)) {
            self::$instance = new self;
        }

        return self::$instance;
    }

    /**
     * @param string $key
     * @param string $value
     * @return Registry
     */
    public function setParam(string $key, string $value): Registry
    {
        $this->store[$key] = $value;

        return $this;
    }

    /**
     * Set a shared service, using a closure for lazy instantiation.
     *
     *
     * $container->setShared('my_service', function(){return new myService;});
     *
     *
     * @staticvar closure $object
     * @param  string   $key
     * @param  callable  $shared
     * @return Registry
     */
    public function setShared(string $key, callable $shared): Registry
    {
        $this->store[$key] = function ($container) use ($shared) {
                static $object;
                if (is_null($object)) {
                    $object = $shared($container);
                }

                return $object;
            };

        return $this;
    }

    /**
     * Set a transient service, using a closure for lazy instantiation.
     *
     *
     * $container->setTransient('my_service', function(){return new myService;});
     *
     *
     * @param  string $key
     * @param callable $transient
     * @return Registry
     */
    public function setTransient(string $key, callable $transient): Registry
    {
        $this->store[$key] = $transient;

        return $this;
    }

    /**
     * @param string $key
     * @return mixed
     * @throws RegistryException
     */
    public function __get(string $key)
    {
        if (array_key_exists($key, $this->store)) {
            return is_callable($this->store[$key]) ? $this->store[$key]($this) : $this->store[$key];
        }
        throw new RegistryException('No such key: ' . $key, RegistryException::NO_SUCH_KEY);
    }

}


text:
const elixir = require('laravel-elixir');

require('laravel-elixir-vue-2');
require('laravel-elixir-svgstore'); // https://www.npmjs.com/package/laravel-elixir-svgstore

/*
 |--------------------------------------------------------------------------
 | Elixir Asset Management
 |--------------------------------------------------------------------------
 |
 | Elixir provides a clean, fluent API for defining some basic Gulp tasks
 | for your Laravel application. By default, we are compiling the Sass
 | file for your application as well as publishing vendor resources.
 |
 */

/* https://laravel.com/docs/5.3/elixir */
elixir((mix) => {
    mix.sass('app.scss')
       .webpack('app.js');

    mix.version(['css/app.css', 'js/app.js']);

    mix.svgstore();
});


text:
// Copyright (c) Vladimir Sadov. All rights reserved.
//
// This file is distributed under the MIT License. See LICENSE.md for details.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

namespace NonBlocking
{
    internal sealed class DictionaryImplBoxed<TKey, TValue>
            : DictionaryImpl<TKey, Boxed<TKey>, TValue>
    {
        internal DictionaryImplBoxed(int capacity, ConcurrentDictionary<TKey, TValue> topDict)
            : base(capacity, topDict)
        {
        }

        internal DictionaryImplBoxed(int capacity, DictionaryImplBoxed<TKey, TValue> other)
            : base(capacity, other)
        {
        }

        protected override bool TryClaimSlotForPut(ref Boxed<TKey> entryKey, TKey key)
        {
            var entryKeyValue = entryKey;
            if (entryKeyValue == null)
            {
                entryKeyValue = Interlocked.CompareExchange(ref entryKey, new Boxed<TKey>(key), null);
                if (entryKeyValue == null)
                {
                    // claimed a new slot
                    this.allocatedSlotCount.Increment();
                    return true;
                }
            }

            return _keyComparer.Equals(key, entryKey.Value);
        }

        protected override bool TryClaimSlotForCopy(ref Boxed<TKey> entryKey,Boxed<TKey> key)
        {
            var entryKeyValue = entryKey;
            if (entryKeyValue == null)
            {
                entryKeyValue = Interlocked.CompareExchange(ref entryKey, key, null);
                if (entryKeyValue == null)
                {
                    // claimed a new slot
                    this.allocatedSlotCount.Increment();
                    return true;
                }
            }

            return _keyComparer.Equals(key.Value, entryKey.Value);
        }

        protected override bool keyEqual(TKey key, Boxed<TKey> entryKey)
        {
            return _keyComparer.Equals(key, entryKey.Value);
        }

        protected override DictionaryImpl<TKey, Boxed<TKey>, TValue> CreateNew(int capacity)
        {
            return new DictionaryImplBoxed<TKey, TValue>(capacity, this);
        }

        protected override TKey keyFromEntry(Boxed<TKey> entryKey)
        {
            return entryKey.Value;
        }
    }

    internal class Boxed<T>
    {
        public readonly T Value;

        public Boxed(T key)
        {
            this.Value = key;
        }
    }
}


text:
@implementation UIFont (TerminalDosis)

+ (instancetype)terminalDosisExtraLightFontOfSize:(CGFloat)size {
  static dispatch_once_t onceToken;
  [GFIFontLoader loadFontFile:@"TerminalDosis-ExtraLight"
                   fromBundle:@"TerminalDosis"
                    onceToken:&onceToken];
  return [self fontWithName:@"TerminalDosis-ExtraLight" size:size];
}

+ (instancetype)terminalDosisLightFontOfSize:(CGFloat)size {
  static dispatch_once_t onceToken;
  [GFIFontLoader loadFontFile:@"TerminalDosis-Light"
                   fromBundle:@"TerminalDosis"
                    onceToken:&onceToken];
  return [self fontWithName:@"TerminalDosis-Light" size:size];
}

+ (instancetype)terminalDosisRegularFontOfSize:(CGFloat)size {
  static dispatch_once_t onceToken;
  [GFIFontLoader loadFontFile:@"TerminalDosis-Regular"
                   fromBundle:@"TerminalDosis"
                    onceToken:&onceToken];
  return [self fontWithName:@"TerminalDosis-Regular" size:size];
}

+ (instancetype)terminalDosisMediumFontOfSize:(CGFloat)size {
  static dispatch_once_t onceToken;
  [GFIFontLoader loadFontFile:@"TerminalDosis-Medium"
                   fromBundle:@"TerminalDosis"
                    onceToken:&onceToken];
  return [self fontWithName:@"TerminalDosis-Medium" size:size];
}

+ (instancetype)terminalDosisSemiBoldFontOfSize:(CGFloat)size {
  static dispatch_once_t onceToken;
  [GFIFontLoader loadFontFile:@"TerminalDosis-SemiBold"
                   fromBundle:@"TerminalDosis"
                    onceToken:&onceToken];
  return [self fontWithName:@"TerminalDosis-SemiBold" size:size];
}

+ (instancetype)terminalDosisBoldFontOfSize:(CGFloat)size {
  static dispatch_once_t onceToken;
  [GFIFontLoader loadFontFile:@"TerminalDosis-Bold"
                   fromBundle:@"TerminalDosis"
                    onceToken:&onceToken];
  return [self fontWithName:@"TerminalDosis-Bold" size:size];
}

+ (instancetype)terminalDosisExtraBoldFontOfSize:(CGFloat)size {
  static dispatch_once_t onceToken;
  [GFIFontLoader loadFontFile:@"TerminalDosis-ExtraBold"
                   fromBundle:@"TerminalDosis"
                    onceToken:&onceToken];
  return [self fontWithName:@"TerminalDosis-ExtraBold" size:size];
}

@end


text:
package org.wildfly.swarm.container.config;

import org.junit.Test;
import org.wildfly.swarm.spi.api.config.ConfigKey;
import org.wildfly.swarm.spi.api.config.SimpleKey;

import static org.fest.assertions.Assertions.assertThat;

/**
 * @author Bob McWhirter
 */
public class SimpleKeyTest {

    @Test
    public void testHead() {
        SimpleKey key = new SimpleKey("hi");
        assertThat(key.head()).isEqualTo(key);
    }

    @Test
    public void testSubkey() {
        SimpleKey key = new SimpleKey("hi");
        assertThat(key.subkey(0)).isEqualTo(key);
        assertThat(key.subkey(1)).isEqualTo(ConfigKey.EMPTY);
    }

}


text:
	#include <ntifs.h>
#endif
#include "..\Driver\ProtectedEntry.h"

extern NTSTATUS RegGetObject(int Argument1, PVOID Argument2, PVOID* ppObject)
{
	if(Argument1 < 0)
		return STATUS_INVALID_PARAMETER_1;
	if(NULL == Argument2)
		return STATUS_INVALID_PARAMETER_2;
	if(NULL == ppObject)
		return STATUS_INVALID_PARAMETER_3;

	switch((int)Argument1)
	{
	case RegNtPreDeleteKey:
		*ppObject = ((REG_DELETE_KEY_INFORMATION*)Argument2)->Object;
		break;
	case RegNtPreSetValueKey:
		*ppObject = ((REG_SET_VALUE_KEY_INFORMATION*)Argument2)->Object;
		break;
	case RegNtPreDeleteValueKey:
		*ppObject = ((REG_DELETE_VALUE_KEY_INFORMATION*)Argument2)->Object;
		break;
	case RegNtPreSetInformationKey:
		*ppObject = ((REG_SET_INFORMATION_KEY_INFORMATION*)Argument2)->Object;
		break;
	case RegNtPreEnumerateKey:
		*ppObject = ((REG_ENUMERATE_KEY_INFORMATION*)Argument2)->Object;
		break;
	case RegNtPreEnumerateValueKey:
		*ppObject = ((REG_ENUMERATE_VALUE_KEY_INFORMATION*)Argument2)->Object;
		break;
	case RegNtPreQueryKey:
		*ppObject = ((REG_QUERY_KEY_INFORMATION*)Argument2)->Object;
		break;
	case RegNtPreQueryValueKey:
		*ppObject = ((REG_QUERY_VALUE_KEY_INFORMATION*)Argument2)->Object;
		break;
	case RegNtPreQueryMultipleValueKey:
		*ppObject = ((REG_QUERY_MULTIPLE_VALUE_KEY_INFORMATION*)Argument2)->Object;
		break;
	default:
		return STATUS_INVALID_PARAMETER_1;
	}

	return STATUS_SUCCESS;
}


text:
//===-- FuzzerCLI.cpp -----------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "llvm/FuzzMutate/FuzzerCLI.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Bitcode/BitcodeReader.h"
#include "llvm/Bitcode/BitcodeWriter.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/Verifier.h"

using namespace llvm;

void llvm::parseFuzzerCLOpts(int ArgC, char *ArgV[]) {
  std::vector<const char *> CLArgs;
  CLArgs.push_back(ArgV[0]);

  int I = 1;
  while (I < ArgC)
    if (StringRef(ArgV[I++]).equals("-ignore_remaining_args=1"))
      break;
  while (I < ArgC)
    CLArgs.push_back(ArgV[I++]);

  cl::ParseCommandLineOptions(CLArgs.size(), CLArgs.data());
}

void llvm::handleExecNameEncodedBEOpts(StringRef ExecName) {
  std::vector<std::string> Args{ExecName};

  auto NameAndArgs = ExecName.split("--");
  if (NameAndArgs.second.empty())
    return;

  SmallVector<StringRef, 4> Opts;
  NameAndArgs.second.split(Opts, '-');
  for (StringRef Opt : Opts) {
    if (Opt.equals("gisel")) {
      Args.push_back("-global-isel");
      // For now we default GlobalISel to -O0
      Args.push_back("-O0");
    } else if (Opt.startswith("O")) {
      Args.push_back("-" + Opt.str());
    } else if (Triple(Opt).getArch()) {
      Args.push_back("-mtriple=" + Opt.str());
    } else {
      errs() << ExecName << ": Unknown option: " << Opt << ".\n";
      exit(1);
    }
  }
  errs() << NameAndArgs.first << ": Injected args:";
  for (int I = 1, E = Args.size(); I < E; ++I)
    errs() << " " << Args[I];
  errs() << "\n";

  std::vector<const char *> CLArgs;
  CLArgs.reserve(Args.size());
  for (std::string &S : Args)
    CLArgs.push_back(S.c_str());

  cl::ParseCommandLineOptions(CLArgs.size(), CLArgs.data());
}

void llvm::handleExecNameEncodedOptimizerOpts(StringRef ExecName) {
  // TODO: Refactor parts common with the 'handleExecNameEncodedBEOpts'
  std::vector<std::string> Args{ExecName};

  auto NameAndArgs = ExecName.split("--");
  if (NameAndArgs.second.empty())
    return;

  SmallVector<StringRef, 4> Opts;
  NameAndArgs.second.split(Opts, '-');
  for (StringRef Opt : Opts) {
    if (Opt == "instcombine") {
      Args.push_back("-passes=instcombine");
    } else if (Opt == "earlycse") {
      Args.push_back("-passes=early-cse");
    } else if (Opt == "simplifycfg") {
      Args.push_back("-passes=simplify-cfg");
    } else if (Opt == "gvn") {
      Args.push_back("-passes=gvn");
    } else if (Opt == "sccp") {
      Args.push_back("-passes=sccp");

    } else if (Opt == "loop_predication") {
      Args.push_back("-passes=loop-predication");
    } else if (Opt == "guard_widening") {
      Args.push_back("-passes=guard-widening");
    } else if (Opt == "loop_rotate") {
      Args.push_back("-passes=loop(rotate)");
    } else if (Opt == "loop_unswitch") {
      Args.push_back("-passes=loop(unswitch)");
    } else if (Opt == "loop_unroll") {
      Args.push_back("-passes=unroll");
    } else if (Opt == "loop_vectorize") {
      Args.push_back("-passes=loop-vectorize");
    } else if (Opt == "licm") {
      Args.push_back("-passes=licm");
    } else if (Opt == "indvars") {
      Args.push_back("-passes=indvars");
    } else if (Opt == "strength_reduce") {
      Args.push_back("-passes=strength-reduce");
    } else if (Opt == "irce") {
      Args.push_back("-passes=irce");

    } else if (Triple(Opt).getArch()) {
      Args.push_back("-mtriple=" + Opt.str());
    } else {
      errs() << ExecName << ": Unknown option: " << Opt << ".\n";
      exit(1);
    }
  }

  errs() << NameAndArgs.first << ": Injected args:";
  for (int I = 1, E = Args.size(); I < E; ++I)
    errs() << " " << Args[I];
  errs() << "\n";

  std::vector<const char *> CLArgs;
  CLArgs.reserve(Args.size());
  for (std::string &S : Args)
    CLArgs.push_back(S.c_str());

  cl::ParseCommandLineOptions(CLArgs.size(), CLArgs.data());
}

int llvm::runFuzzerOnInputs(int ArgC, char *ArgV[], FuzzerTestFun TestOne,
                            FuzzerInitFun Init) {
  errs() << "*** This tool was not linked to libFuzzer.\n"
         << "*** No fuzzing will be performed.\n";
  if (int RC = Init(&ArgC, &ArgV)) {
    errs() << "Initialization failed\n";
    return RC;
  }

  for (int I = 1; I < ArgC; ++I) {
    StringRef Arg(ArgV[I]);
    if (Arg.startswith("-")) {
      if (Arg.equals("-ignore_remaining_args=1"))
        break;
      continue;
    }

    auto BufOrErr = MemoryBuffer::getFile(Arg, /*FileSize-*/ -1,
                                          /*RequiresNullTerminator=*/false);
    if (std::error_code EC = BufOrErr.getError()) {
      errs() << "Error reading file: " << Arg << ": " << EC.message() << "\n";
      return 1;
    }
    std::unique_ptr<MemoryBuffer> Buf = std::move(BufOrErr.get());
    errs() << "Running: " << Arg << " (" << Buf->getBufferSize() << " bytes)\n";
    TestOne(reinterpret_cast<const uint8_t *>(Buf->getBufferStart()),
            Buf->getBufferSize());
  }
  return 0;
}

std::unique_ptr<Module> llvm::parseModule(
    const uint8_t *Data, size_t Size, LLVMContext &Context) {

  if (Size <= 1)
    // We get bogus data given an empty corpus - just create a new module.
    return std::make_unique<Module>("M", Context);

  auto Buffer = MemoryBuffer::getMemBuffer(
      StringRef(reinterpret_cast<const char *>(Data), Size), "Fuzzer input",
      /*RequiresNullTerminator=*/false);

  SMDiagnostic Err;
  auto M = parseBitcodeFile(Buffer->getMemBufferRef(), Context);
  if (Error E = M.takeError()) {
    errs() << toString(std::move(E)) << "\n";
    return nullptr;
  }
  return std::move(M.get());
}

size_t llvm::writeModule(const Module &M, uint8_t *Dest, size_t MaxSize) {
  std::string Buf;
  {
    raw_string_ostream OS(Buf);
    WriteBitcodeToFile(M, OS);
  }
  if (Buf.size() > MaxSize)
      return 0;
  memcpy(Dest, Buf.data(), Buf.size());
  return Buf.size();
}

std::unique_ptr<Module> llvm::parseAndVerify(const uint8_t *Data, size_t Size,
                                             LLVMContext &Context) {
  auto M = parseModule(Data, Size, Context);
  if (!M || verifyModule(*M, &errs()))
    return nullptr;

  return M;
}


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

import org.activiti5.engine.ActivitiIllegalArgumentException;
import org.activiti5.engine.impl.interceptor.CommandContext;
import org.activiti5.engine.impl.persistence.entity.TaskEntity;
import org.activiti5.engine.task.IdentityLinkType;

/**
 * @author Joram Barrez
 */
public class AddIdentityLinkCmd extends NeedsActiveTaskCmd<Void> {

  private static final long serialVersionUID = 1L;

  public static int IDENTITY_USER = 1;
  public static int IDENTITY_GROUP = 2;

  protected String identityId;

  protected int identityIdType;

  protected String identityType;

  public AddIdentityLinkCmd(String taskId, String identityId, int identityIdType, String identityType) {
    super(taskId);
    validateParams(taskId, identityId, identityIdType, identityType);
    this.taskId = taskId;
    this.identityId = identityId;
    this.identityIdType = identityIdType;
    this.identityType = identityType;
  }

  protected void validateParams(String taskId, String identityId, int identityIdType, String identityType) {
    if (taskId == null) {
      throw new ActivitiIllegalArgumentException("taskId is null");
    }

    if (identityType == null) {
      throw new ActivitiIllegalArgumentException("type is required when adding a new task identity link");
    }

    if (identityId == null && (identityIdType == IDENTITY_GROUP ||
        (IdentityLinkType.ASSIGNEE.equals(identityType) == false && IdentityLinkType.OWNER.equals(identityType) == false))) {

      throw new ActivitiIllegalArgumentException("identityId is null");
    }

    if (identityIdType != IDENTITY_USER && identityIdType != IDENTITY_GROUP) {
      throw new ActivitiIllegalArgumentException("identityIdType allowed values are 1 and 2");
    }
  }

  protected Void execute(CommandContext commandContext, TaskEntity task) {

    boolean assignedToNoOne = false;
    if (IdentityLinkType.ASSIGNEE.equals(identityType)) {
      task.setAssignee(identityId, true, true);
      assignedToNoOne = identityId == null;
    } else if (IdentityLinkType.OWNER.equals(identityType)) {
      task.setOwner(identityId, true);
    } else if (IDENTITY_USER == identityIdType) {
      task.addUserIdentityLink(identityId, identityType);
    } else if (IDENTITY_GROUP == identityIdType) {
      task.addGroupIdentityLink(identityId, identityType);
    }

    boolean forceNullUserId = false;
    if (assignedToNoOne) {
      // ACT-1317: Special handling when assignee is set to NULL, a
      // CommentEntity notifying of assignee-delete should be created
      forceNullUserId = true;

    }

    if (IDENTITY_USER == identityIdType) {
      commandContext.getHistoryManager().createUserIdentityLinkComment(taskId, identityId, identityType, true, forceNullUserId);
    } else {
      commandContext.getHistoryManager().createGroupIdentityLinkComment(taskId, identityId, identityType, true);
    }

    return null;
  }

}


text:
package com.github.igotyou.FactoryMod.properties;

public abstract class AFactoryProperties implements IFactoryProperties{
	protected String name;

	public String getName()
	{
		return name;
	}
}