text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using BeatBuilder.Audio;
using System.Threading.Tasks;
using Windows.Media;

namespace BeatBuilder.WinApp
{
    public sealed partial class MainPage : Page
    {
        SystemMediaTransportControls systemControls;
        AudioRenderer renderer;
        DrumPad drumPad;
        Looper looper;
        Oscillator oscillator;
        AudioDemultiplexer demultiplexer;

        public MainPage()
        {
            this.InitializeComponent();
            this.Loaded += MainPage_Loaded;
        }

        async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.systemControls = SystemMediaTransportControls.GetForCurrentView();
            this.systemControls.ButtonPressed += systemControls_ButtonPressed;
            this.systemControls.IsPlayEnabled = true;
            this.systemControls.IsPauseEnabled = true;

            this.renderer = await AudioRenderer.CreateAsync();

            var rootPath = Windows.ApplicationModel.Package.Current.InstalledLocation.Path + "\\Sounds\\";
            this.drumPad = new DrumPad();
            this.drumPad.SetDrumSound(DrumKind.Bass, rootPath + "Drum-Bass.wav");
            this.drumPad.SetDrumSound(DrumKind.Snare, rootPath + "Drum-Snare.wav");
            this.drumPad.SetDrumSound(DrumKind.Shaker, rootPath + "Drum-Shaker.wav");
            this.drumPad.SetDrumSound(DrumKind.ClosedHiHat, rootPath + "Drum-Closed-Hi-Hat.wav");
            this.drumPad.SetDrumSound(DrumKind.Cowbell, rootPath + "Cowbell.wav");
            this.drumPad.SetDrumSound(DrumKind.OpenHiHat, rootPath + "Drum-Open-Hi-Hat.wav");
            this.drumPad.SetDrumSound(DrumKind.RideCymbal, rootPath + "Drum-Ride-Cymbal.wav");
            this.drumPad.SetDrumSound(DrumKind.FloorTom, rootPath + "developer_loud.wav");
            this.drumPad.SetDrumSound(DrumKind.HighTom, rootPath + "satya_fantastic.wav");

            this.oscillator = new Oscillator();
            this.looper = new Looper();
            this.demultiplexer = new AudioDemultiplexer();

            this.looper.ListenTo(this.drumPad);
            this.demultiplexer.ListenTo(this.looper);
            this.demultiplexer.ListenTo(this.oscillator);
            this.renderer.ListenTo(this.demultiplexer);

            Play();
        }

        void systemControls_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
        {
            switch (args.Button)
            {
                case SystemMediaTransportControlsButton.Play:
                    Play();
                    break;

                case SystemMediaTransportControlsButton.Pause:
                    Pause();
                    break;

                default:
                    break;
            }
        }

        private void Play()
        {
            this.renderer.Start();
            this.systemControls.PlaybackStatus = MediaPlaybackStatus.Playing;
        }

        private void Pause()
        {
            this.renderer.Stop();
            this.systemControls.PlaybackStatus = MediaPlaybackStatus.Paused;
        }

        private void BassButton_Click(object sender, RoutedEventArgs e)
        {
            this.drumPad.PlayDrum(DrumKind.Bass);
        }

        private void SnareButton_Click(object sender, RoutedEventArgs e)
        {
            this.drumPad.PlayDrum(DrumKind.Snare);
        }

        private void ShakerButton_Click(object sender, RoutedEventArgs e)
        {
            this.drumPad.PlayDrum(DrumKind.Shaker);
        }

        private void ClosedHiHatButton_Click(object sender, RoutedEventArgs e)
        {
            this.drumPad.PlayDrum(DrumKind.ClosedHiHat);
        }

        private void CowbellButton_Click(object sender, RoutedEventArgs e)
        {
            this.drumPad.PlayDrum(DrumKind.Cowbell);
        }

        private void OpenHiHatButton_Click(object sender, RoutedEventArgs e)
        {
            this.drumPad.PlayDrum(DrumKind.OpenHiHat);
        }

        private void RideCymbalButton_Click(object sender, RoutedEventArgs e)
        {
            this.drumPad.PlayDrum(DrumKind.RideCymbal);
        }

        private void FloorTomButton_Click(object sender, RoutedEventArgs e)
        {
            this.drumPad.PlayDrum(DrumKind.FloorTom);
        }

        private void HighTomButton_Click(object sender, RoutedEventArgs e)
        {
            this.drumPad.PlayDrum(DrumKind.HighTom);
        }

        private void RecordStartButton_Click(object sender, RoutedEventArgs e)
        {
            this.looper.StartRecording();
        }

        private void RecordStopButton_Click(object sender, RoutedEventArgs e)
        {
            this.looper.StopRecording();
        }

        private void ResetButton_Click(object sender, RoutedEventArgs e)
        {
            this.looper.ResetLoops();
        }

        private void Bass_PointerPressed(object sender, PointerRoutedEventArgs e)
        {
            this.drumPad.PlayDrum(DrumKind.Bass);
        }

        private void OscillatorTestButton_PointerReleased(object sender, PointerRoutedEventArgs e)
        {
            this.oscillator.TurnOff();
        }

        private void OscillatorTestButton_Click(object sender, RoutedEventArgs e)
        {
            this.oscillator.TurnOn();
        }
    }
}


text:
package cucumber.eclipse.editor.steps;

import java.util.List;

import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.templates.DocumentTemplateContext;
import org.eclipse.jface.text.templates.Template;
import org.eclipse.jface.text.templates.TemplateBuffer;
import org.eclipse.jface.text.templates.TemplateCompletionProcessor;
import org.eclipse.jface.text.templates.TemplateContext;
import org.eclipse.jface.text.templates.TemplateContextType;
import org.eclipse.jface.text.templates.TemplateException;
import org.eclipse.jface.text.templates.TemplateProposal;
import org.eclipse.swt.graphics.Image;

import cucumber.eclipse.editor.editors.Editor;
import cucumber.eclipse.steps.integration.Step;

public class StepCompletionProcessor extends TemplateCompletionProcessor {

	private static class StepCompletionTemplateContext extends DocumentTemplateContext {

		StepCompletionTemplateContext(TemplateContextType type, IDocument document,
				int offset, int length) {
			super(type, document, offset, length);
		}

		@Override
		public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
			if (!canEvaluate(template))
				return null;

			TemplateBuffer buffer = ((StepCompletionTemplate) template).toBuffer();
			getContextType().resolve(buffer, this);
			return buffer;
		}
	}

	private static class StepCompletionProposal extends TemplateProposal {

		StepCompletionProposal(Template template, TemplateContext context, IRegion region,
				Image image, int relevance) {
			super(template, context, region, image, relevance);
		}

		@Override
		public String getDisplayString() {
			return getTemplate().getName();
		}

		@Override
		public boolean validate(IDocument document, int offset, DocumentEvent event) {
			Step step = ((StepCompletionTemplate) getTemplate()).getStep();
			return StepCompletionUtil.isStepValidForPosition(step, document, offset);
		}
	}

	private static final TemplateContextType CONTEXT_TYPE = new TemplateContextType(
			StepCompletionProcessor.class.getName());

	private final Editor editor;

	public StepCompletionProcessor(Editor editor) {
		this.editor = editor;
	}

	@Override
	protected TemplateContext createContext(ITextViewer viewer, IRegion region) {
		TemplateContextType contextType = getContextType(viewer, region);
		if (contextType != null) {
			IDocument document = viewer.getDocument();
			return new StepCompletionTemplateContext(contextType, document, region.getOffset(),
					region.getLength());
		}
		return null;
	}

	@Override
	protected ICompletionProposal createProposal(Template template, TemplateContext context,
			IRegion region, int relevance) {
		return new StepCompletionProposal(template, context, region, getImage(template), relevance);
	}

	protected String extractPrefix(ITextViewer viewer, int offset) {
		return StepCompletionUtil.getStepPrefix(viewer.getDocument(), offset);
	}

	@Override
	protected Template[] getTemplates(String contextTypeId) {
		List<Step> availableSteps = editor.getAvailableSteps();
		Template[] result = new Template[availableSteps.size()];
		for (int i = 0; i < availableSteps.size(); i ++) {
			Step step = availableSteps.get(i);
			result[i] = new StepCompletionTemplate(step, contextTypeId);
		}
		return result;
	}

	@Override
	protected TemplateContextType getContextType(ITextViewer viewer,
			IRegion region) {
		return CONTEXT_TYPE;
	}

	@Override
	protected Image getImage(Template template) {
		return null;
	}
}

redpajama_set_name: RedPajamaGithub


text:
using System;

namespace Game.Model
{
	public class GameOptions
	{
		PlayerOptions[] players = new PlayerOptions[]
			{
				new PlayerOptions() { Control = ControlType.WASD},
				new PlayerOptions() {Control = ControlType.None},
			};

		public PlayerOptions[] Players { get
		{
			return this.players;
		} set
		{
			this.players = value;
		}}

		public VoxelArray VoxelArray
		{
			get
			{
				return this.voxelArray ?? (this.voxelArray = CreateVoxelArray());
			}
			set
			{
				this.voxelArray = value;
			}
		}

		private VoxelArray CreateVoxelArray()
		{
			var voxelArray = new VoxelArray(32, 32, 32);

			voxelArray.OutlineBox(1, 0, 0, 0, 31, 31, 31);
			for (int i = 0; i < 100; ++i)
			{
				int size = rnd.Next(3);
				var index = rnd.Next(voxelArray.SizeX * voxelArray.SizeY * voxelArray.SizeZ);
				var x = index % voxelArray.SizeX;
				index /= voxelArray.SizeX;
				var y = index % voxelArray.SizeY;
				index /= voxelArray.SizeY;
				var z = index % voxelArray.SizeZ;
				voxelArray.FillBox((byte)(rnd.Next(3) + 2), x, y, z, x + size, y + size, z + size);
			}
			return voxelArray;
		}

		private static Random rnd = new Random(0);

		private VoxelArray voxelArray;

	}
}


text:
// Copyright (C) 2008 The Android Open Source Project
//
// 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 com.google.gerrit.client.patches;

import com.google.gerrit.client.Dispatcher;
import com.google.gerrit.client.ErrorDialog;
import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.RpcStatus;
import com.google.gerrit.client.changes.CommitMessageBlock;
import com.google.gerrit.client.changes.PatchTable;
import com.google.gerrit.client.changes.Util;
import com.google.gerrit.client.rpc.GerritCallback;
import com.google.gerrit.client.rpc.ScreenLoadCallback;
import com.google.gerrit.client.ui.ListenableAccountDiffPreference;
import com.google.gerrit.client.ui.Screen;
import com.google.gerrit.common.data.PatchScript;
import com.google.gerrit.common.data.PatchSetDetail;
import com.google.gerrit.prettify.client.ClientSideFormatter;
import com.google.gerrit.prettify.common.PrettyFactory;
import com.google.gerrit.reviewdb.AccountDiffPreference;
import com.google.gerrit.reviewdb.Change;
import com.google.gerrit.reviewdb.Patch;
import com.google.gerrit.reviewdb.PatchSet;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.logical.shared.OpenEvent;
import com.google.gwt.event.logical.shared.OpenHandler;
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.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwtexpui.globalkey.client.GlobalKey;
import com.google.gwtexpui.globalkey.client.KeyCommand;
import com.google.gwtexpui.globalkey.client.KeyCommandSet;
import com.google.gwtjsonrpc.client.VoidResult;

public abstract class PatchScreen extends Screen implements
    CommentEditorContainer {
  static final PrettyFactory PRETTY = ClientSideFormatter.FACTORY;

  public static class SideBySide extends PatchScreen {
    public SideBySide(final Patch.Key id, final int patchIndex,
        final PatchSetDetail patchSetDetail, final PatchTable patchTable) {
      super(id, patchIndex, patchSetDetail, patchTable);
    }

    @Override
    protected SideBySideTable createContentTable() {
      return new SideBySideTable();
    }

    @Override
    protected PatchScreen.Type getPatchScreenType() {
      return PatchScreen.Type.SIDE_BY_SIDE;
    }
  }

  public static class Unified extends PatchScreen {
    public Unified(final Patch.Key id, final int patchIndex,
        final PatchSetDetail patchSetDetail, final PatchTable patchTable) {
      super(id, patchIndex, patchSetDetail, patchTable);
    }

    @Override
    protected UnifiedDiffTable createContentTable() {
      return new UnifiedDiffTable();
    }

    @Override
    protected PatchScreen.Type getPatchScreenType() {
      return PatchScreen.Type.UNIFIED;
    }
  }

  // Which patch set id's are being diff'ed
  private static PatchSet.Id diffSideA = null;
  private static PatchSet.Id diffSideB = null;

  private static Boolean historyOpen = null;
  private static final OpenHandler<DisclosurePanel> cacheOpenState =
      new OpenHandler<DisclosurePanel>() {
        @Override
        public void onOpen(OpenEvent<DisclosurePanel> event) {
          historyOpen = true;
        }
      };
  private static final CloseHandler<DisclosurePanel> cacheCloseState =
      new CloseHandler<DisclosurePanel>() {
        @Override
        public void onClose(CloseEvent<DisclosurePanel> event) {
          historyOpen = false;
        }
      };

  protected final Patch.Key patchKey;
  protected PatchSetDetail patchSetDetail;
  protected PatchTable fileList;
  protected PatchSet.Id idSideA;
  protected PatchSet.Id idSideB;
  protected PatchScriptSettingsPanel settingsPanel;

  private DisclosurePanel historyPanel;
  private HistoryTable historyTable;
  private FlowPanel contentPanel;
  private Label noDifference;
  private AbstractPatchContentTable contentTable;
  private CommitMessageBlock commitMessageBlock;
  private NavLinks topNav;
  private NavLinks bottomNav;

  private int rpcSequence;
  private PatchScript lastScript;

  /** The index of the file we are currently looking at among the fileList */
  private int patchIndex;
  private ListenableAccountDiffPreference prefs;

  /** Keys that cause an action on this screen */
  private KeyCommandSet keysNavigation;
  private HandlerRegistration regNavigation;
  private boolean intralineFailure;

  /**
   * How this patch should be displayed in the patch screen.
   */
  public static enum Type {
    UNIFIED, SIDE_BY_SIDE
  }

  protected PatchScreen(final Patch.Key id, final int patchIndex,
      final PatchSetDetail detail, final PatchTable patchTable) {
    patchKey = id;
    patchSetDetail = detail;
    fileList = patchTable;

    if (patchTable != null) {
      diffSideA = patchTable.getPatchSetIdToCompareWith();
    } else {
      diffSideA = null;
    }
    if (diffSideA == null) {
      historyOpen = null;
    }

    idSideA = diffSideA; // null here means we're diff'ing from the Base
    idSideB = diffSideB != null ? diffSideB : id.getParentKey();
    this.patchIndex = patchIndex;

    prefs = fileList != null ? fileList.getPreferences() :
                               new ListenableAccountDiffPreference();
    prefs.addValueChangeHandler(
        new ValueChangeHandler<AccountDiffPreference>() {
          @Override
          public void onValueChange(ValueChangeEvent<AccountDiffPreference> event) {
            update(event.getValue());
          }
        });

    settingsPanel = new PatchScriptSettingsPanel(prefs);
    settingsPanel.getReviewedCheckBox().addValueChangeHandler(
        new ValueChangeHandler<Boolean>() {
          @Override
          public void onValueChange(ValueChangeEvent<Boolean> event) {
            setReviewedByCurrentUser(event.getValue());
          }
        });
  }

  @Override
  public void notifyDraftDelta(int delta) {
    lastScript = null;
  }

  @Override
  public void remove(CommentEditorPanel panel) {
    lastScript = null;
  }

  private void update(AccountDiffPreference dp) {
    if (lastScript != null && canReuse(dp, lastScript)) {
      lastScript.setDiffPrefs(dp);
      RpcStatus.INSTANCE.onRpcStart(null);
      settingsPanel.setEnabled(false);
      Scheduler.get().scheduleDeferred(new ScheduledCommand() {
        @Override
        public void execute() {
          try {
            onResult(lastScript, false /* not the first time */);
          } finally {
            RpcStatus.INSTANCE.onRpcComplete(null);
          }
        }
      });
    } else {
      refresh(false);
    }
  }

  private boolean canReuse(AccountDiffPreference dp, PatchScript last) {
    if (last.getDiffPrefs().getIgnoreWhitespace() != dp.getIgnoreWhitespace()) {
      // Whitespace ignore setting requires server computation.
      return false;
    }

    final int ctx = dp.getContext();
    if (ctx == AccountDiffPreference.WHOLE_FILE_CONTEXT && !last.getA().isWholeFile()) {
      // We don't have the entire file here, so we can't render it.
      return false;
    }

    if (last.getDiffPrefs().getContext() < ctx && !last.getA().isWholeFile()) {
      // We don't have sufficient context.
      return false;
    }

    if (dp.isSyntaxHighlighting()
        && !last.getA().isWholeFile()) {
      // We need the whole file to syntax highlight accurately.
      return false;
    }

    return true;
  }

  @Override
  protected void onInitUI() {
    super.onInitUI();

    keysNavigation = new KeyCommandSet(Gerrit.C.sectionNavigation());
    keysNavigation.add(new UpToChangeCommand(patchKey.getParentKey(), 0, 'u'));
    keysNavigation.add(new FileListCmd(0, 'f', PatchUtil.C.fileList()));

    historyTable = new HistoryTable(this);
    historyPanel = new DisclosurePanel(PatchUtil.C.patchHistoryTitle());
    historyPanel.setContent(historyTable);
    historyPanel.setVisible(false);
    // If the user selected a different patch set than the default for either
    // side, expand the history panel
    historyPanel.setOpen(diffSideA != null || diffSideB != null
        || (historyOpen != null && historyOpen));
    historyPanel.addOpenHandler(cacheOpenState);
    historyPanel.addCloseHandler(cacheCloseState);

    VerticalPanel vp = new VerticalPanel();
    vp.add(historyPanel);
    vp.add(settingsPanel);
    commitMessageBlock = new CommitMessageBlock("6em");
    HorizontalPanel hp = new HorizontalPanel();
    hp.setWidth("100%");
    hp.add(vp);
    hp.add(commitMessageBlock);
    add(hp);

    noDifference = new Label(PatchUtil.C.noDifference());
    noDifference.setStyleName(Gerrit.RESOURCES.css().patchNoDifference());
    noDifference.setVisible(false);

    contentTable = createContentTable();
    contentTable.fileList = fileList;

    topNav = new NavLinks(keysNavigation, patchKey.getParentKey());
    bottomNav = new NavLinks(null, patchKey.getParentKey());

    add(topNav);
    contentPanel = new FlowPanel();
    contentPanel.setStyleName(Gerrit.RESOURCES.css()
        .sideBySideScreenSideBySideTable());
    contentPanel.add(noDifference);
    contentPanel.add(contentTable);
    add(contentPanel);
    add(bottomNav);

    if (fileList != null) {
      topNav.display(patchIndex, getPatchScreenType(), fileList);
      bottomNav.display(patchIndex, getPatchScreenType(), fileList);
    }
  }

  void setReviewedByCurrentUser(boolean reviewed) {
    if (fileList != null) {
      fileList.updateReviewedStatus(patchKey, reviewed);
    }

    PatchUtil.DETAIL_SVC.setReviewedByCurrentUser(patchKey, reviewed,
        new AsyncCallback<VoidResult>() {
          @Override
          public void onFailure(Throwable arg0) {
            // nop
          }

          @Override
          public void onSuccess(VoidResult result) {
            // nop
          }
        });
  }

  @Override
  protected void onLoad() {
    super.onLoad();
    if (patchSetDetail == null) {
      Util.DETAIL_SVC.patchSetDetail(idSideB, null, null,
          new GerritCallback<PatchSetDetail>() {
            @Override
            public void onSuccess(PatchSetDetail result) {
              patchSetDetail = result;
              if (fileList == null) {
                fileList = new PatchTable(prefs);
                fileList.display(result);
                patchIndex = fileList.indexOf(patchKey);
              }
              refresh(true);
            }
          });
    } else {
      refresh(true);
    }
  }

  @Override
  protected void onUnload() {
    if (regNavigation != null) {
      regNavigation.removeHandler();
      regNavigation = null;
    }
    super.onUnload();
  }

  @Override
  public void registerKeys() {
    super.registerKeys();
    contentTable.setRegisterKeys(contentTable.isVisible());
    if (regNavigation != null) {
      regNavigation.removeHandler();
      regNavigation = null;
    }
    regNavigation = GlobalKey.add(this, keysNavigation);
  }

  protected abstract AbstractPatchContentTable createContentTable();

  protected abstract PatchScreen.Type getPatchScreenType();

  protected void refresh(final boolean isFirst) {
    final int rpcseq = ++rpcSequence;
    lastScript = null;
    settingsPanel.setEnabled(false);
    PatchUtil.DETAIL_SVC.patchScript(patchKey, idSideA, idSideB, //
        settingsPanel.getValue(), new ScreenLoadCallback<PatchScript>(this) {
          @Override
          protected void preDisplay(final PatchScript result) {
            if (rpcSequence == rpcseq) {
              onResult(result, isFirst);
            }
          }

          @Override
          public void onFailure(final Throwable caught) {
            if (rpcSequence == rpcseq) {
              settingsPanel.setEnabled(true);
              super.onFailure(caught);
            }
          }
        });
  }

  private void onResult(final PatchScript script, final boolean isFirst) {

    final Change.Key cid = script.getChangeId();
    final String path = PatchTable.getDisplayFileName(patchKey);
    String fileName = path;
    final int last = fileName.lastIndexOf('/');
    if (last >= 0) {
      fileName = fileName.substring(last + 1);
    }

    setWindowTitle(PatchUtil.M.patchWindowTitle(cid.abbreviate(), fileName));
    setPageTitle(PatchUtil.M.patchPageTitle(cid.abbreviate(), path));

    if (idSideB.equals(patchSetDetail.getPatchSet().getId())) {
      commitMessageBlock.setVisible(true);
      commitMessageBlock.display(patchSetDetail.getInfo().getMessage());
    } else {
      commitMessageBlock.setVisible(false);
      Util.DETAIL_SVC.patchSetDetail(idSideB, null, null,
          new GerritCallback<PatchSetDetail>() {
            @Override
            public void onSuccess(PatchSetDetail result) {
              commitMessageBlock.setVisible(true);
              commitMessageBlock.display(result.getInfo().getMessage());
            }
          });
    }

    historyTable.display(script.getHistory());
    historyPanel.setVisible(true);

    // True if there are differences between the two patch sets
    boolean hasEdits = !script.getEdits().isEmpty();
    // True if this change is a mode change or a pure rename/copy
    boolean hasMeta = !script.getPatchHeader().isEmpty();

    boolean hasDifferences = hasEdits || hasMeta;
    boolean pureMetaChange = !hasEdits && hasMeta;

    if (contentTable instanceof SideBySideTable && pureMetaChange) {
      // User asked for SideBySide (or a link guessed, wrong) and we can't
      // show a binary or pure-rename change there accurately. Switch to
      // the unified view instead.
      //
      contentTable.removeFromParent();
      contentTable = new UnifiedDiffTable();
      contentTable.fileList = fileList;
      contentPanel.add(contentTable);
      setToken(Dispatcher.toPatchUnified(patchKey));
    }

    if (hasDifferences) {
      contentTable.display(patchKey, idSideA, idSideB, script);
      contentTable.display(script.getCommentDetail(), script.isExpandAllComments());
      contentTable.finishDisplay();
    }
    showPatch(hasDifferences);
    settingsPanel.setEnableSmallFileFeatures(!script.isHugeFile());
    settingsPanel.setEnableIntralineDifference(script.hasIntralineDifference());
    settingsPanel.setEnabled(true);
    lastScript = script;

    if (fileList != null) {
      topNav.display(patchIndex, getPatchScreenType(), fileList);
      bottomNav.display(patchIndex, getPatchScreenType(), fileList);
    }

    // Mark this file reviewed as soon we display the diff screen
    if (Gerrit.isSignedIn() && isFirst) {
      settingsPanel.getReviewedCheckBox().setValue(true);
      setReviewedByCurrentUser(true /* reviewed */);
    }

    intralineFailure = isFirst && script.hasIntralineFailure();
  }

  @Override
  public void onShowView() {
    super.onShowView();
    if (intralineFailure) {
      intralineFailure = false;
      new ErrorDialog(PatchUtil.C.intralineFailure()).show();
    }
  }

  private void showPatch(final boolean showPatch) {
    noDifference.setVisible(!showPatch);
    contentTable.setVisible(showPatch);
    contentTable.setRegisterKeys(isCurrentView() && showPatch);
  }

  public void setSideA(PatchSet.Id patchSetId) {
    idSideA = patchSetId;
    diffSideA = patchSetId;
  }

  public void setSideB(PatchSet.Id patchSetId) {
    idSideB = patchSetId;
    diffSideB = patchSetId;
  }

  public class FileListCmd extends KeyCommand {
    public FileListCmd(int mask, int key, String help) {
      super(mask, key, help);
    }

    @Override
    public void onKeyPress(final KeyPressEvent event) {
      if (fileList == null || fileList.isAttached()) {
        final PatchSet.Id psid = patchKey.getParentKey();
        fileList = new PatchTable(prefs);
        fileList.setSavePointerId("PatchTable " + psid);
        Util.DETAIL_SVC.patchSetDetail(psid, null, null,
            new GerritCallback<PatchSetDetail>() {
              public void onSuccess(final PatchSetDetail result) {
                fileList.display(result);
              }
            });
      }

      final PatchBrowserPopup p = new PatchBrowserPopup(patchKey, fileList);
      p.open();
    }
  }
}


text:
package de.elomagic.mag;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

public class TargetSmbTest extends AbstractTest {

    private static final String FILENAME = "Report" + UUID.randomUUID().toString() + " .pdf";

    @Before
    public void beforeFileSystemTest() throws Exception {
        try (InputStream in = getClass().getResourceAsStream("/configuration.properties"); Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8)) {
            Configuration.loadConfiguration(reader);
        }

        startEMailServer();

        main = new MAG();
    }

    @After
    public void afterWebDAVTest() throws Exception {
        Files.deleteIfExists(Paths.get(System.getProperty("java.io.tmpdir"), FILENAME));
    }

    @Test
    @Ignore
    public void testMain() throws Exception {

        Configuration.set(Configuration.ConfigurationKey.TargetSmbEnabled, true);
        Configuration.set(Configuration.ConfigurationKey.TargetSmbHostname, "hostname");
        Configuration.set(Configuration.ConfigurationKey.TargetSmbShare, "share");
        Configuration.set(Configuration.ConfigurationKey.TargetSmbDomain, "domain");
        Configuration.set(Configuration.ConfigurationKey.TargetSmbUsername, "username");
        Configuration.set(Configuration.ConfigurationKey.TargetSmbPassword, "secret");

        greeUser.deliver(createMimeMessage(FILENAME));

        main.start();

        Future<byte[]> future = createFileExistsFuture(Paths.get(System.getProperty("java.io.tmpdir"), FILENAME));

        byte[] received = future.get(5, TimeUnit.SECONDS);
        Assert.assertArrayEquals(getOriginalMailAttachment(), received);

    }

}


text:
package org.basex.query.expr.ft;

import static org.basex.query.QueryText.*;

import org.basex.query.*;
import org.basex.query.util.ft.*;
import org.basex.query.var.*;
import org.basex.util.*;
import org.basex.util.ft.*;
import org.basex.util.hash.*;

/**
 * FTContent expression.
 *
 * @author BaseX Team 2005-22, BSD License
 * @author Christian Gruen
 */
public final class FTContent extends FTFilter {
  /** Content type. */
  private final FTContents content;

  /**
   * Constructor.
   * @param info input info
   * @param expr expression
   * @param content contents type
   */
  public FTContent(final InputInfo info, final FTExpr expr, final FTContents content) {
    super(info, expr);
    this.content = content;
  }

  @Override
  protected boolean filter(final QueryContext qc, final FTMatch match, final FTLexer lexer) {
    if(content == FTContents.START) {
      for(final FTStringMatch sm : match) {
        if(sm.start == 0) return true;
      }
    } else if(content == FTContents.END) {
      final int p = lexer.count() - 1;
      for(final FTStringMatch sm : match) {
        if(sm.end == p) return true;
      }
    } else {
      final int s = lexer.count();
      final boolean[] bl = new boolean[s];
      for(final FTStringMatch sm : match) {
        if(sm.gaps) continue;
        for(int p = sm.start; p <= sm.end; ++p) bl[p] = true;
      }
      for(final boolean b : bl) {
        if(!b) return false;
      }
      return true;
    }
    return false;
  }

  @Override
  protected boolean content() {
    return content != FTContents.START;
  }

  @Override
  public FTExpr copy(final CompileContext cc, final IntObjMap<Var> vm) {
    return copyType(new FTContent(info, exprs[0].copy(cc, vm), content));
  }

  @Override
  public void toXml(final QueryPlan plan) {
    plan.add(plan.create(this, CONTENT, content), exprs);
  }

  @Override
  public void toString(final QueryString qs) {
    qs.token(exprs[0]);
    if(content == FTContents.START) qs.token(AT).token(START);
    if(content == FTContents.END) qs.token(AT).token(END);
    qs.token(ENTIRE).token(CONTENT);
  }
}


text:
@implementation KCCursor
MJLogAllIvars
@end


text:
<?php
namespace Rz\Bundle\UrlShortenerBundle\Entity\Repository;

use Doctrine\ORM\EntityRepository;
use Rz\Bundle\UrlShortenerBundle\Entity\UrlStat;

class UrlStatRepository extends EntityRepository
{
    /**
     * Get URL stats count
     *
     * @param int $id
     *
     * @return int
     */
    public function getUrlStatCount($id)
    {
        return (int) $this->createQueryBuilder('c')
            ->select('count(c)')
            ->where('c.Url = :url_id')
            ->setParameter('url_id', $id)
            ->getQuery()
            ->getSingleScalarResult();
    }

    /**
     * Get URL stats
     *
     * @param int $id
     * @param int $first
     * @param int $max
     *
     * @return array|UrlStat[]
     */
    public function getUrlStats($id, $first, $max)
    {
        return $this->createQueryBuilder('c')
            ->select('c')
            ->where('c.Url = :url_id')
            ->setParameter('url_id', $id)
            ->setFirstResult($first)
            ->setMaxResults($max)
            ->getQuery()
            ->getResult();
    }
}


text:
/* skin detected, extra file: skins/dhx_terrace.less */

.dhx_tooltip {
	display: none;
	position: absolute;
	font-family: Arial, Helvetica;
	color: #626262;
	font-size: 13px;
	z-index: 10000;
	padding: 4px 10px 4px 10px;
	border: 1px solid #fff;
	border-radius: 3px;
	-moz-border-radius: 3px;
	-webkit-border-radius: 3px;
	-moz-box-shadow: 0 0 3px #d9d9d9;
	-webkit-box-shadow: 0 0 3px #d9d9d9;
	text-shadow: 0px 1px 1px #fff;
	box-shadow: 0 0 5px #d9d9d9;
	background: -webkit-gradient(linear,left top,left bottom,color-stop(0,#efefef),color-stop(0.5,#f6f6f6),color-stop(1,#efefef));
	background: -o-linear-gradient(#efefef 0%,#f6f6f6 50%,#efefef 100%);
	background: -ms-linear-gradient(#efefef 0%,#f6f6f6 50%,#efefef 100%);
	background: -moz-linear-gradient(#efefef 0%,#f6f6f6 50%,#efefef 100%);
	background: #efefef;
}
.dhx_noselect {
	-moz-user-select: none;
	-moz-user-select: -moz-none;
	-khtml-user-select: none;
}
.dhx_allow_selection {
	-moz-user-select: text;
	-user-select: text;
}
.dhx_dataview {
	overflow-y: auto;
	-webkit-overflow-scrolling: touch;
	overflow-x: hidden;
	-moz-user-select: none;
	-moz-user-select: -moz-none;
	-khtml-select: none;
}
.dhx_drag_zone {
	position: absolute;
	border: 1px solid #A4BED4;
	z-index: 8000;
	-moz-box-shadow: 5px 5px 5px #888;
	-khtml-box-shadow: 5px 5px 5px #888;
}
.dhx_dataview_default_item,
.dhx_dataview_default_item_selected {
	cursor: pointer;
	background-color: #ffffff;
}
.dhx_dataview .dhx_dataview_default_item,
.dhx_dataview .dhx_dataview_default_item_selected {
	border-right: 1px solid #cccccc;
	border-bottom: 1px dotted #cccccc;
}
.dhx_dataview_default_item_selected {
	background-color: #fff3a1;
	color: #fff3a1;
	border-color: #fff3a1;
	background-repeat: repeat-x;
}
.dhx_dataview_item {
	font-family: Arial, Helvetica;
	font-size: 13px;
	color: black;
}
.dhx_dataview_item .dhx_strong {
	font-weight: bold;
	display: block;
	padding-bottom: 6px;
}
.dhx_dataview_default_item_selected .dhx_light {
	color: #C3C3C3;
}
.dhx_dataview_item .dhx_light {
	color: #919191;
}
.dhx_drag_over {
	background-color: #faf768;
	background-image: url("../imgs/dhxdataview_terrace/marker.png");
	background-repeat: repeat-x;
}
.dhx_pager_item,
.dhx_pager_item_selected {
	float: left;
	text-align: center;
	height: 16px;
	font-family: Arial, Helvetica;
	font-size: 10pt;
	border: 1px solid gray;
	padding: 2px 4px;
	margin-left: 5px;
	cursor: pointer;
	background-color: white;
}
.dhx_pager_item_selected {
	background-color: lightgrey;
	color: white;
	cursor: default;
	font-weight: bold;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="management.goods.modelcomponent">
	<resultMap id="modelDetailVo" type="vo.goods.ModelDetailVo">
		<result property="modelId" column="model_id" />
		<result property="modelCode" column="model_code" />
		<result property="goodsId" column="goods_id" />
		<result property="goodsName" column="goods_name" />
		<collection property="config" column="modelId = model_id" select="modelcomponentquery"/>
	</resultMap>

	<resultMap id="modelComponentVo" type="vo.goods.ModelComponentVo">
		<result property="modelId" column="model_id" />
		<result property="modelName" column="model_name" />
		<result property="componentId" column="item_id" />
		<result property="componentName" column="item_title" />
		<result property="supplierName" column="supplier_name" />
	</resultMap>

	<insert id="insertList" parameterType="java.util.List" useGeneratedKeys="false">
		insert into airdevice.goods_component(model_id, item_id, supplier_name, block_flag, create_time)
		values
		<foreach collection="list" item="item" index="index" separator="," >
			(#{item.model.modelId}, #{item.componentId}, #{item.supplierName}, #{item.blockFlag}, #{item.createAt})
		</foreach>
	</insert>

	<select id="query" parameterType="java.util.Map" resultMap="modelDetailVo">
		select model_id, model_code, goods_id, goods_name
		from airdevice.goods_model_view
		where 1 = 1
		<if test="modelId != null">
			and model_id = #{modelId}
		</if>
		<if test="goodsId != null">
			and goods_id = #{goodsId}
		</if>
	</select>

	<select id="modelcomponentquery" parameterType="java.util.Map" resultMap="modelComponentVo">
		select model_id, model_name, item_id, item_title, supplier_name
		from airdevice.model_component_view
		where model_id = #{modelId}
	</select>
</mapper>


text:
var $: any;
module VORLON {

    export class OfficeTools {

        public static IsOutlook() {
            var parentTreeCategory = "window.Office.context.mailbox";

            return (document.getElementById(parentTreeCategory) !== null && document.getElementById(parentTreeCategory) !== undefined)
        }

        public static AddTreeFunction(treeCategory: string, functionName: string): FluentDOM {

            if (document.getElementById(treeCategory) === null || document.getElementById(treeCategory) === undefined) {
                return;
            }
            var fullpathName = treeCategory + "." + functionName;
            var category = document.getElementById(treeCategory).querySelector('.expand-content');
            var zone = new FluentDOM('DIV', 'obj-func', category);
            var func = zone.createChild("SPAN", "func-name").text(functionName);

            return func;
        }

        private static _ClearPropertiesAndResults() {
            // var propertiesDiv = <HTMLDivElement>document.querySelector('#office-results');

            // if (propertiesDiv !== undefined && propertiesDiv !== null) {
            //     while (propertiesDiv.hasChildNodes()) {
            //         propertiesDiv.removeChild(propertiesDiv.lastChild);
            //     }

            // }

            var propertiesDiv = <HTMLDivElement>document.querySelector('#office-properties');

            if (propertiesDiv !== undefined && propertiesDiv !== null) {
                while (propertiesDiv.hasChildNodes()) {
                    propertiesDiv.removeChild(propertiesDiv.lastChild);
                }
            }
        }

        public static GetOfficeType(sets: any) {

            if (sets == "Outlook") {
                return { officeType: "Outlook", version: "", background: "#0173C7" }
            }

            if (sets.wordapi) {
                return { officeType: "Word", version: sets.wordapi, background: "#2A579A" }
            }
            if (sets.excelapi) {
                return { officeType: "Excel", version: sets.excelapi, background: "#227447" }
            }
            if (!sets.excelapi && !sets.wordapi) {
                return { officeType: "PowerPoint", version: sets.pdf, background: "#B7472A" }
            }
            if (sets.project) {
                return { officeType: "Project", version: sets.projectapi, background: "#2E7237" }
            }

            return { officeType: "Office", version: '1.0', background: "#0173C7" }

        }

        public static ShowFunctionResult(r: any) {

            if (r.value !== undefined && r.value !== null)
                r.value = JSON.parse(r.value);
            var jsonValue = JSON.stringify(r.value, undefined, 4);

            var propertiesDiv = document.querySelector('#office-properties');
            var propValues = document.querySelector('#office-results-values');

            if (propValues !== undefined && propValues !== null) {
                while (propValues.hasChildNodes()) {
                    propValues.removeChild(propValues.lastChild);
                }
            } else {
                propValues = document.createElement('DIV');
                propValues.className = 'office-results-values';
                propValues.id = 'office-results-values';
                propertiesDiv.appendChild(propValues);
            }

            var container = document.createElement('pre');
            container.className = 'results';
            container.innerHTML = OfficeTools.FormatJson(jsonValue);

            propValues.appendChild(container);

        }

        public static FormatJson(json) {
            json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');

            return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, (match) => {
                var cls = 'number';
                if (/^"/.test(match)) {
                    if (/:$/.test(match)) {
                        cls = 'key';
                    } else {
                        cls = 'string';
                    }
                } else if (/true|false/.test(match)) {
                    cls = 'boolean';
                } else if (/null/.test(match)) {
                    cls = 'null';
                }
                return '' + match + '';
            });
        }

        public static ShowFunction(fullpathName: string, callbackClick: () => void, options?: HTMLElement[]) {
            VORLON.OfficeTools._ClearPropertiesAndResults();

            var propertiesDiv = <HTMLDivElement>document.querySelector('#office-properties');
            var titleDive = <HTMLDivElement>document.querySelector('#office-properties-title');
            titleDive.innerHTML = "Function";

            var zone = new FluentDOM('DIV', 'office-properties-values', propertiesDiv);

            zone.append('div', 'fullpath', container => {
                container.createChild("SPAN", "function-name").text('Function');
                container.createChild("SPAN", "function-value").text(fullpathName);
            });

            if (options !== undefined && options.length > 0) {
                for (var i in options) {
                    var option = options[i];

                    zone.append('div', 'options', container => {
                        container.createChild("SPAN", "function-name").text(option.attributes.getNamedItem('tag').value);
                        container.element.appendChild(option);
                    });
                }

            }

            zone.append('div', 'invoker', container => {
                var btn = new FluentDOM("INPUT", 'function-invoker', container.element);
                btn.attr('type', 'button');
                btn.attr('value', 'invoke');
                btn.attr('id', fullpathName);
                btn.click(callbackClick);
            });
        }

        public static ShowProperty(prop: any) {

            VORLON.OfficeTools._ClearPropertiesAndResults();

            var propertiesDiv = <HTMLDivElement>document.querySelector('#office-properties');
            var titleDive = <HTMLDivElement>document.querySelector('#office-properties-title');
            titleDive.innerHTML = "Property";

            var zone = new FluentDOM('DIV', 'office-properties-values', propertiesDiv);

            zone.append('div', 'prop-fullpath', container => {
                container.createChild("SPAN", "name").text('Name');
                container.createChild("SPAN", "value").text(prop.fullpath);
            });

            zone.append('div', 'prop-name', container => {
                container.createChild("SPAN", "name").text('Type');
                container.createChild("SPAN", "value").text(prop.type);
            });

            zone.append('div', 'prop-type', container => {
                container.createChild("SPAN", "name").text('Value');
                container.createChild("SPAN", "value").text(prop.value);
            });

        }

        public static AddZone(parentTreeCategory: string, category: string) {

            if (document.getElementById(parentTreeCategory) === null || document.getElementById(parentTreeCategory) === undefined) {
                return;
            }

            if (document.getElementById(parentTreeCategory + "." + category) !== null && document.getElementById(parentTreeCategory + "." + category) !== undefined) {
                return;
            }

            var itemBody = document.getElementById(parentTreeCategory).children[1];

            // root of all
            var elt = new FluentDOM('DIV', 'objdescriptor', itemBody);

            // Create the div for the current path
            elt.append('DIV', 'expandable expanded', (zone) => {
                var btn: FluentDOM;
                zone.attr("id", parentTreeCategory + "." + category);

                // create the div containing both sigle (+ or -) and the label
                zone.append('DIV', 'expand', container => {
                    btn = container.createChild("SPAN", "expand-btn").text("-")
                    btn.click((arg) => {
                        arg.stopPropagation();
                        Tools.ToggleClass(zone.element, "expanded", (expanded) => {
                            expanded ? btn.text("-") : btn.text("+");
                        });
                    });
                    container.createChild("SPAN", "expand-label").text(category);

                });

                zone.append("DIV", "expand-content", (category) => {

                });

            });

        }

        public static CreateTextArea(name: string, label: string, value?: string): HTMLTextAreaElement {
            var formData = document.createElement('textarea');
            formData.setAttribute("rows", "4");
            formData.setAttribute("cols", "40");
            formData.setAttribute("name", name);
            formData.setAttribute("id", name);
            if (value)
                formData.value = value;
            formData.setAttribute("tag", label + ": ");

            return formData
        }

        public static CreateTextBlock(name: string, label: string, value?: string): HTMLInputElement {

            var inputText = document.createElement('input');
            inputText.setAttribute("type", "text");
            inputText.setAttribute("name", name + ".coercionType");
            inputText.setAttribute("id", name + ".coercionType ");

            if (value !== undefined) {
                inputText.value = value;
            }

            inputText.setAttribute("tag", label + " : ");

            return inputText;
        }
    }
}


text:
<?php echo Form::open(array("class"=>"form-horizontal", 'style' => 'padding-right: 15px;', 'enctype'=>"multipart/form-data")); ?>

	<fieldset>

			<?php echo Form::label('Categoria', 'categoria', array('class'=>'control-label col-lg-2')); ?>

<?php echo Form::input('categoria', Input::post('categoria', isset($turismo_servicio) ? $turismo_servicio->categoria : ''), array('class' => 'form-control input-sm', 'placeholder'=>'Categoria')); ?>

			<?php echo Form::label('Nombre', 'nombre', array('class'=>'control-label col-lg-2')); ?>

<?php echo Form::input('nombre', Input::post('nombre', isset($turismo_servicio) ? $turismo_servicio->nombre : ''), array('class' => 'col-md-4 form-control input-sm', 'placeholder'=>'Nombre')); ?>

			<?php echo Form::label('Direccion', 'direccion', array('class'=>'control-label col-lg-2')); ?>

<?php echo Form::input('direccion', Input::post('direccion', isset($turismo_servicio) ? $turismo_servicio->direccion : ''), array('class' => 'col-md-4 form-control input-sm', 'placeholder'=>'Direccion')); ?>

			<?php echo Form::label('Telefono', 'telefono', array('class'=>'control-label col-lg-2')); ?>

<?php echo Form::input('telefono', Input::post('telefono', isset($turismo_servicio) ? $turismo_servicio->telefono : ''), array('class' => 'col-md-4 form-control input-sm', 'placeholder'=>'Telefono')); ?>

			<?php echo Form::label('Email', 'email', array('class'=>'control-label col-lg-2')); ?>

<?php echo Form::input('email', Input::post('email', isset($turismo_servicio) ? $turismo_servicio->email : ''), array('class' => 'col-md-4 form-control input-sm', 'placeholder'=>'Email')); ?>

			<?php echo Form::label('Web', 'web', array('class'=>'control-label col-lg-2')); ?>

<?php echo Form::input('web', Input::post('web', isset($turismo_servicio) ? $turismo_servicio->web : ''), array('class' => 'col-md-4 form-control input-sm', 'placeholder'=>'Web')); ?>

			<?php echo Form::label('Texto', 'texto', array('class'=>'control-label col-lg-2')); ?>

<?php echo Form::textarea('texto', Input::post('texto', isset($turismo_servicio) ? $turismo_servicio->texto : ''), array('class' => 'col-md-8 form-control input-sm', 'rows' => 8, 'placeholder'=>'Texto')); ?>

			<?php echo Form::label('Imagenes', 'imagenes', array('class'=>'control-label col-lg-2')); ?>

<?php echo Form::file('imagenes[]', array('class' => 'col-md-4 form-control input-sm ', 'multiple')); ?>

			<?php echo Form::submit('submit', 'Guardar', array('class' => 'btn btn-primary')); ?>

	</fieldset>
<?php echo Form::close(); ?>


text:
#pragma once

#include <atomic>
#include <future>
#include <memory>
#include <mutex>
#include <shared_mutex>
#include <thread>
#include <vector>

#include "glad/glad.h"

//#include "mmcore/utility/gl/FramebufferObject.h"
#include "mmcore/view/Renderer3DModuleGL.h"

#include "FBOCommFabric.h"
#include "FBOProto.h"
#include "mmcore/param/ParamSlot.h"
#include "mmcore/utility/sys/FutureReset.h"

#include "image_calls/Image2DCall.h"

namespace megamol {
namespace remote {

class FBOCompositor2 : public megamol::core::view::Renderer3DModuleGL {
public:
    /**
     * Answer the name of this module.
     *
     * @return The name of this module.
     */
    static const char* ClassName(void) {
        return "FBOCompositor2";
    }

    /**
     * Answer a human readable description of this module.
     *
     * @return A human readable description of this module.
     */
    static const char* Description(void) {
        return "Composits images from socket into a rendering.";
    }

    /**
     * Answers whether this module is available on the current system.
     *
     * @return 'true' if the module is available, 'false' otherwise.
     */
    static bool IsAvailable(void) {
        return true;
    } //gladLoadGL(); }

    FBOCompositor2(void);

    ~FBOCompositor2(void);

protected:
    bool create(void) override;

    void release(void) override;

private:
    bool GetExtents(core::view::CallRender3DGL& call) override;

    bool Render(core::view::CallRender3DGL& call) override;

    void swapBuffers(void) {
        std::scoped_lock<std::mutex, std::mutex> guard{buffer_write_guard_, buffer_recv_guard_};
        swap(fbo_msg_recv_, fbo_msg_write_);
        /*swap(color_buf_recv_, color_buf_write_);
        swap(depth_buf_recv_, depth_buf_write_);*/
        data_has_changed_.store(true);
    }

    void receiverJob(
        FBOCommFabric& comm, core::utility::sys::FutureReset<fbo_msg_t>* fbo_msg_future, std::future<bool>&& close);

    void collectorJob(std::vector<FBOCommFabric>&& comms);

    void registerJob(std::vector<std::string>& addresses);

    void initTextures(size_t n, GLsizei width, GLsizei heigth);

    void resize(size_t n, GLsizei width, GLsizei height);

    bool initThreads();

    bool shutdownThreads();

    bool getImageCallback(megamol::core::Call& c);

    bool startCallback(megamol::core::param::ParamSlot& p);

    static void RGBAtoRGB(std::vector<char> const& rgba, std::vector<unsigned char>& rgb);

    megamol::core::CalleeSlot provide_img_slot_;

    std::vector<std::string> getAddresses(std::string const& str) const noexcept;

    std::vector<FBOCommFabric> connectComms(std::vector<std::string> const& addr) const;

    std::vector<FBOCommFabric> connectComms(std::vector<std::string>&& addr) const;

    bool printShaderInfoLog(GLuint shader) const;

    bool printProgramInfoLog(GLuint shaderProg) const;

    // megamol::core::param::ParamSlot addressesSlot_;

    megamol::core::param::ParamSlot commSelectSlot_;

    megamol::core::param::ParamSlot targetBandwidthSlot_;

    megamol::core::param::ParamSlot numRendernodesSlot_;

    megamol::core::param::ParamSlot handshakePortSlot_;

    megamol::core::param::ParamSlot startSlot_;

    megamol::core::param::ParamSlot restartSlot_;

    megamol::core::param::ParamSlot renderOnlyRequestedFramesSlot_;

    // megamol::core::utility::gl::FramebufferObject fbo_;

    std::thread collector_thread_;

    std::promise<bool> close_promise_;

    std::future<bool> close_future_;

    std::condition_variable_any heartbeat_;

    std::condition_variable_any promise_exchange_;

    std::condition_variable_any promise_release_;

    std::atomic<bool> promise_atomic_;

    std::shared_mutex heartbeat_lock_;

    std::shared_mutex promise_exchange_lock_;

    std::shared_mutex promise_release_lock_;

    std::mutex buffer_write_guard_;

    std::mutex buffer_recv_guard_;

    // std::vector<std::thread> receiver_thread_pool_;

    std::unique_ptr<std::vector<fbo_msg>> fbo_msg_write_;

    std::unique_ptr<std::vector<fbo_msg>> fbo_msg_recv_;

    /*std::unique_ptr<fbo_msg_header_t> fbo_msg_write_;

    std::unique_ptr<fbo_msg_header_t> fbo_msg_recv_;

    std::unique_ptr<std::vector<char>> color_buf_write_;

    std::unique_ptr<std::vector<char>> depth_buf_write_;

    std::unique_ptr<std::vector<char>> color_buf_recv_;

    std::unique_ptr<std::vector<char>> depth_buf_recv_;*/

    std::atomic<bool> data_has_changed_;

    int col_buf_el_size_;

    int depth_buf_el_size_;

    GLsizei width_;

    GLsizei height_;

    float frame_times_[2];

    float camera_params_[9];

    std::vector<GLuint> color_textures_;

    std::vector<GLuint> depth_textures_;

    bool connected_;

    GLuint shader;

    GLuint vao, vbo;

    FBOCommFabric registerComm_;

    std::thread registerThread_;

    std::thread initThreadsThread_;

    std::atomic<bool> isRegistered_;

    std::vector<std::string> addresses_;

    std::vector<unsigned char> img_data_;

    // std::shared_ptr<unsigned char[]> img_data_ptr_;

    size_t hash_;

    bool shutdown_ = false;

    bool register_done_ = false;

}; // end class FBOCompositor2

} // end namespace remote
} // end namespace megamol


text:
package io.sponges.dubtrack4j.internal.subscription.callback;

import io.sponges.dubtrack4j.DubtrackAPI;
import org.json.JSONObject;

public class UserKickCall extends SubCallback {

    private final DubtrackAPI dubtrack;

    public UserKickCall(DubtrackAPI dubtrack) {
        this.dubtrack = dubtrack;
    }

    @Override
    public void run(JSONObject json) {
        // TODO implement user kick callback

        //String roomId =

        //Room room = dubtrack.loadRoom(roomId);

        //User kicker = null;
        //User kicked = null;
    }
}


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.flowable.engine.impl.bpmn.behavior;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.model.Activity;
import org.flowable.bpmn.model.BoundaryEvent;
import org.flowable.bpmn.model.CallActivity;
import org.flowable.bpmn.model.CompensateEventDefinition;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.SubProcess;
import org.flowable.bpmn.model.Transaction;
import org.flowable.engine.common.api.FlowableIllegalArgumentException;
import org.flowable.engine.common.impl.interceptor.CommandContext;
import org.flowable.engine.common.impl.util.CollectionUtil;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.impl.bpmn.helper.ScopeUtil;
import org.flowable.engine.impl.delegate.ActivityBehavior;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityManager;
import org.flowable.engine.impl.util.CommandContextUtil;

/**
 * @author Joram Barrez
 * @author Tijs Rademakers
 */
public class ParallelMultiInstanceBehavior extends MultiInstanceActivityBehavior {

    private static final long serialVersionUID = 1L;

    public ParallelMultiInstanceBehavior(Activity activity, AbstractBpmnActivityBehavior originalActivityBehavior) {
        super(activity, originalActivityBehavior);
    }

    /**
     * Handles the parallel case of spawning the instances. Will create child executions accordingly for every instance needed.
     */
    protected int createInstances(DelegateExecution multiInstanceRootExecution) {
        int nrOfInstances = resolveNrOfInstances(multiInstanceRootExecution);
        if (nrOfInstances < 0) {
            throw new FlowableIllegalArgumentException("Invalid number of instances: must be non-negative integer value" + ", but was " + nrOfInstances);
        }

        setLoopVariable(multiInstanceRootExecution, NUMBER_OF_INSTANCES, nrOfInstances);
        setLoopVariable(multiInstanceRootExecution, NUMBER_OF_COMPLETED_INSTANCES, 0);
        setLoopVariable(multiInstanceRootExecution, NUMBER_OF_ACTIVE_INSTANCES, nrOfInstances);

        List<ExecutionEntity> concurrentExecutions = new ArrayList<>();
        for (int loopCounter = 0; loopCounter < nrOfInstances; loopCounter++) {
            ExecutionEntity concurrentExecution = CommandContextUtil.getExecutionEntityManager()
                    .createChildExecution((ExecutionEntity) multiInstanceRootExecution);
            concurrentExecution.setCurrentFlowElement(activity);
            concurrentExecution.setActive(true);
            concurrentExecution.setScope(false);

            concurrentExecutions.add(concurrentExecution);
            logLoopDetails(concurrentExecution, "initialized", loopCounter, 0, nrOfInstances, nrOfInstances);

            //CommandContextUtil.getHistoryManager().recordActivityStart(concurrentExecution);
        }

        // Before the activities are executed, all executions MUST be created up front
        // Do not try to merge this loop with the previous one, as it will lead
        // to bugs, due to possible child execution pruning.
        for (int loopCounter = 0; loopCounter < nrOfInstances; loopCounter++) {
            ExecutionEntity concurrentExecution = concurrentExecutions.get(loopCounter);
            // executions can be inactive, if instances are all automatics
            // (no-waitstate) and completionCondition has been met in the meantime
            if (concurrentExecution.isActive()
                    && !concurrentExecution.isEnded()
                    && !concurrentExecution.getParent().isEnded()) {
                executeOriginalBehavior(concurrentExecution, loopCounter);
            }
        }

        // See ACT-1586: ExecutionQuery returns wrong results when using multi
        // instance on a receive task The parent execution must be set to false, so it wouldn't show up in
        // the execution query when using .activityId(something). Do not we cannot nullify the
        // activityId (that would have been a better solution), as it would break boundary event behavior.
        if (!concurrentExecutions.isEmpty()) {
            multiInstanceRootExecution.setActive(false);
        }

        return nrOfInstances;
    }

    /**
     * Called when the wrapped {@link ActivityBehavior} calls the {@link AbstractBpmnActivityBehavior#leave(DelegateExecution)} method. Handles the completion of one of the parallel instances
     */
    public void leave(DelegateExecution execution) {

        boolean zeroNrOfInstances = false;
        if (resolveNrOfInstances(execution) == 0) {
            // Empty collection, just leave.
            zeroNrOfInstances = true;
            super.leave(execution); // Plan the default leave
        }

        int loopCounter = getLoopVariable(execution, getCollectionElementIndexVariable());
        int nrOfInstances = getLoopVariable(execution, NUMBER_OF_INSTANCES);
        int nrOfCompletedInstances = getLoopVariable(execution, NUMBER_OF_COMPLETED_INSTANCES) + 1;
        int nrOfActiveInstances = getLoopVariable(execution, NUMBER_OF_ACTIVE_INSTANCES) - 1;

        CommandContextUtil.getHistoryManager().recordActivityEnd((ExecutionEntity) execution, null);
        callActivityEndListeners(execution);

        if (zeroNrOfInstances) {
            return;
        }

        DelegateExecution miRootExecution = getMultiInstanceRootExecution(execution);
        if (miRootExecution != null) { // will be null in case of empty collection
            setLoopVariable(miRootExecution, NUMBER_OF_COMPLETED_INSTANCES, nrOfCompletedInstances);
            setLoopVariable(miRootExecution, NUMBER_OF_ACTIVE_INSTANCES, nrOfActiveInstances);
        }

        logLoopDetails(execution, "instance completed", loopCounter, nrOfCompletedInstances, nrOfActiveInstances, nrOfInstances);

        ExecutionEntity executionEntity = (ExecutionEntity) execution;
        if (executionEntity.getParent() != null) {

            executionEntity.inactivate();
            lockFirstParentScope(executionEntity);

            boolean isCompletionConditionSatisfied = completionConditionSatisfied(execution.getParent());
            if (nrOfCompletedInstances >= nrOfInstances || isCompletionConditionSatisfied) {

                ExecutionEntity leavingExecution = null;
                if (nrOfInstances > 0) {
                    leavingExecution = executionEntity.getParent();
                } else {
                    CommandContextUtil.getHistoryManager().recordActivityEnd((ExecutionEntity) execution, null);
                    leavingExecution = executionEntity;
                }

                Activity activity = (Activity) execution.getCurrentFlowElement();
                verifyCompensation(execution, leavingExecution, activity);
                verifyCallActivity(leavingExecution, activity);

                if (isCompletionConditionSatisfied) {
                    LinkedList<DelegateExecution> toVerify = new LinkedList<>(miRootExecution.getExecutions());
                    while (!toVerify.isEmpty()) {
                        DelegateExecution childExecution = toVerify.pop();
                        if (((ExecutionEntity) childExecution).isInserted()) {
                            childExecution.inactivate();
                        }

                        List<DelegateExecution> childExecutions = (List<DelegateExecution>) childExecution.getExecutions();
                        if (childExecutions != null && !childExecutions.isEmpty()) {
                            toVerify.addAll(childExecutions);
                        }
                    }
                }

                super.leave(leavingExecution);
            }

        } else {
            super.leave(execution);
        }
    }

    protected Activity verifyCompensation(DelegateExecution execution, ExecutionEntity executionToUse, Activity activity) {
        boolean hasCompensation = false;
        if (activity instanceof Transaction) {
            hasCompensation = true;
        } else if (activity instanceof SubProcess) {
            SubProcess subProcess = (SubProcess) activity;
            for (FlowElement subElement : subProcess.getFlowElements()) {
                if (subElement instanceof Activity) {
                    Activity subActivity = (Activity) subElement;
                    if (CollectionUtil.isNotEmpty(subActivity.getBoundaryEvents())) {
                        for (BoundaryEvent boundaryEvent : subActivity.getBoundaryEvents()) {
                            if (CollectionUtil.isNotEmpty(boundaryEvent.getEventDefinitions()) &&
                                    boundaryEvent.getEventDefinitions().get(0) instanceof CompensateEventDefinition) {

                                hasCompensation = true;
                                break;
                            }
                        }
                    }
                }
            }
        }

        if (hasCompensation) {
            ScopeUtil.createCopyOfSubProcessExecutionForCompensation(executionToUse);
        }
        return activity;
    }

    protected void verifyCallActivity(ExecutionEntity executionToUse, Activity activity) {
        if (activity instanceof CallActivity) {
            ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager();
            if (executionToUse != null) {
                List<String> callActivityExecutionIds = new ArrayList<>();

                // Find all execution entities that are at the call activity
                List<ExecutionEntity> childExecutions = executionEntityManager.collectChildren(executionToUse);
                if (childExecutions != null) {
                    for (ExecutionEntity childExecution : childExecutions) {
                        if (activity.getId().equals(childExecution.getCurrentActivityId())) {
                            callActivityExecutionIds.add(childExecution.getId());
                        }
                    }

                    // Now all call activity executions have been collected, loop again and check which should be removed
                    for (int i = childExecutions.size() - 1; i >= 0; i--) {
                        ExecutionEntity childExecution = childExecutions.get(i);
                        if (StringUtils.isNotEmpty(childExecution.getSuperExecutionId())
                                && callActivityExecutionIds.contains(childExecution.getSuperExecutionId())) {

                            executionEntityManager.deleteProcessInstanceExecutionEntity(childExecution.getId(), activity.getId(),
                                    "call activity completion condition met", true, false, true);
                        }
                    }

                }
            }
        }
    }

    protected void lockFirstParentScope(DelegateExecution execution) {

        ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager();

        boolean found = false;
        ExecutionEntity parentScopeExecution = null;
        ExecutionEntity currentExecution = (ExecutionEntity) execution;
        while (!found && currentExecution != null && currentExecution.getParentId() != null) {
            parentScopeExecution = executionEntityManager.findById(currentExecution.getParentId());
            if (parentScopeExecution != null && parentScopeExecution.isScope()) {
                found = true;
            }
            currentExecution = parentScopeExecution;
        }

        parentScopeExecution.forceUpdate();
    }

    // TODO: can the ExecutionManager.deleteChildExecution not be used?
    protected void deleteChildExecutions(ExecutionEntity parentExecution, boolean deleteExecution, CommandContext commandContext) {
        // Delete all child executions
        ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
        Collection<ExecutionEntity> childExecutions = executionEntityManager.findChildExecutionsByParentExecutionId(parentExecution.getId());
        if (CollectionUtil.isNotEmpty(childExecutions)) {
            for (ExecutionEntity childExecution : childExecutions) {
                deleteChildExecutions(childExecution, true, commandContext);
            }
        }

        if (deleteExecution) {
            executionEntityManager.deleteExecutionAndRelatedData(parentExecution, null);
        }
    }

}


text:
using System.Runtime;
using System.Runtime.Diagnostics;
using System.Security.Authentication.ExtendedProtection;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Diagnostics.Application;
using System.ServiceModel.Security;
using System.Threading;
using System.Threading.Tasks;

namespace System.ServiceModel.Channels
{
    public abstract class TransportDuplexSessionChannel : TransportOutputChannel, IDuplexSessionChannel
    {
        private BufferManager _bufferManager;
        private IDuplexSession _duplexSession;
        private bool _isInputSessionClosed;
        private bool _isOutputSessionClosed;
        private MessageEncoder _messageEncoder;
        private SynchronizedMessageSource _messageSource;
        private SecurityMessageProperty _remoteSecurity;
        private EndpointAddress _localAddress;
        private SemaphoreSlim _sendLock;
        private Uri _localVia;
        private static Action<object> s_onWriteComplete = new Action<object>(OnWriteComplete);

        protected TransportDuplexSessionChannel(
                  ChannelManagerBase manager,
                  ITransportFactorySettings settings,
                  EndpointAddress localAddress,
                  Uri localVia,
                  EndpointAddress remoteAddresss,
                  Uri via)
                : base(manager, remoteAddresss, via, settings.ManualAddressing, settings.MessageVersion)
        {
            _localAddress = localAddress;
            _localVia = localVia;
            _bufferManager = settings.BufferManager;
            _sendLock = new SemaphoreSlim(1);
            _messageEncoder = settings.MessageEncoderFactory.CreateSessionEncoder();
            this.Session = new ConnectionDuplexSession(this);
        }

        public EndpointAddress LocalAddress
        {
            get { return _localAddress; }
        }

        public SecurityMessageProperty RemoteSecurity
        {
            get { return _remoteSecurity; }
            protected set { _remoteSecurity = value; }
        }

        public IDuplexSession Session
        {
            get { return _duplexSession; }
            protected set { _duplexSession = value; }
        }

        protected BufferManager BufferManager
        {
            get
            {
                return _bufferManager;
            }
        }

        protected MessageEncoder MessageEncoder
        {
            get { return _messageEncoder; }
            set { _messageEncoder = value; }
        }

        internal SynchronizedMessageSource MessageSource
        {
            get { return _messageSource; }
        }

        protected abstract bool IsStreamedOutput { get; }

        public Message Receive()
        {
            return this.Receive(this.DefaultReceiveTimeout);
        }

        public Message Receive(TimeSpan timeout)
        {
            Message message = null;
            if (DoneReceivingInCurrentState())
            {
                return null;
            }

            bool shouldFault = true;
            try
            {
                message = _messageSource.Receive(timeout);
                this.OnReceiveMessage(message);
                shouldFault = false;
                return message;
            }
            finally
            {
                if (shouldFault)
                {
                    if (message != null)
                    {
                        message.Close();
                        message = null;
                    }

                    this.Fault();
                }
            }
        }

        public async Task<Message> ReceiveAsync(TimeSpan timeout)
        {
            Message message = null;
            if (DoneReceivingInCurrentState())
            {
                return null;
            }

            bool shouldFault = true;
            try
            {
                message = await _messageSource.ReceiveAsync(timeout);
                this.OnReceiveMessage(message);
                shouldFault = false;
                return message;
            }
            finally
            {
                if (shouldFault)
                {
                    if (message != null)
                    {
                        message.Close();
                        message = null;
                    }

                    this.Fault();
                }
            }
        }

        public IAsyncResult BeginReceive(AsyncCallback callback, object state)
        {
            return this.BeginReceive(this.DefaultReceiveTimeout, callback, state);
        }

        public IAsyncResult BeginReceive(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return this.ReceiveAsync(timeout).ToApm(callback, state);
        }

        public Message EndReceive(IAsyncResult result)
        {
            return result.ToApmEnd<Message>();
        }

        public IAsyncResult BeginTryReceive(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return this.ReceiveAsync(timeout).ToApm(callback, state);
        }

        public bool EndTryReceive(IAsyncResult result, out Message message)
        {
            try
            {
                message = result.ToApmEnd<Message>();
                return true;
            }
            catch (TimeoutException e)
            {
                if (TD.ReceiveTimeoutIsEnabled())
                {
                    TD.ReceiveTimeout(e.Message);
                }

                message = null;
                return false;
            }
        }

        public bool TryReceive(TimeSpan timeout, out Message message)
        {
            try
            {
                message = this.Receive(timeout);
                return true;
            }
            catch (TimeoutException e)
            {
                if (TD.ReceiveTimeoutIsEnabled())
                {
                    TD.ReceiveTimeout(e.Message);
                }
                message = null;
                return false;
            }
        }

        public async Task<bool> WaitForMessageAsync(TimeSpan timeout)
        {
            if (DoneReceivingInCurrentState())
            {
                return true;
            }

            bool shouldFault = true;
            try
            {
                bool success = await _messageSource.WaitForMessageAsync(timeout);
                shouldFault = !success; // need to fault if we've timed out because we're now toast
                return success;
            }
            finally
            {
                if (shouldFault)
                {
                    this.Fault();
                }
            }
        }

        public bool WaitForMessage(TimeSpan timeout)
        {
            if (DoneReceivingInCurrentState())
            {
                return true;
            }

            bool shouldFault = true;
            try
            {
                bool success = _messageSource.WaitForMessage(timeout);
                shouldFault = !success; // need to fault if we've timed out because we're now toast
                return success;
            }
            finally
            {
                if (shouldFault)
                {
                    this.Fault();
                }
            }
        }

        public IAsyncResult BeginWaitForMessage(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return this.WaitForMessageAsync(timeout).ToApm(callback, state);
        }

        public bool EndWaitForMessage(IAsyncResult result)
        {
            return result.ToApmEnd<bool>();
        }

        protected void SetMessageSource(IMessageSource messageSource)
        {
            _messageSource = new SynchronizedMessageSource(messageSource);
        }

        protected abstract Task CloseOutputSessionCoreAsync(TimeSpan timeout);

        protected abstract void CloseOutputSessionCore(TimeSpan timeout);

        protected async Task CloseOutputSessionAsync(TimeSpan timeout)
        {
            ThrowIfNotOpened();
            ThrowIfFaulted();
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            // If timeout == TimeSpan.MaxValue, then we want to pass Timeout.Infinite as
            // SemaphoreSlim doesn't accept timeouts > Int32.MaxValue.
            // Using TimeoutHelper.RemainingTime() would yield a value less than TimeSpan.MaxValue
            // and would result in the value Int32.MaxValue so we must use the original timeout specified.
            if (!await _sendLock.WaitAsync(TimeoutHelper.ToMilliseconds(timeout)))
            {
                if (TD.CloseTimeoutIsEnabled())
                {
                    TD.CloseTimeout(SR.Format(SR.CloseTimedOut, timeout));
                }

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(
                                                SR.Format(SR.CloseTimedOut, timeout),
                                                TimeoutHelper.CreateEnterTimedOutException(timeout)));
            }

            try
            {
                // check again in case the previous send faulted while we were waiting for the lock
                ThrowIfFaulted();

                // we're synchronized by sendLock here
                if (_isOutputSessionClosed)
                {
                    return;
                }

                _isOutputSessionClosed = true;
                bool shouldFault = true;
                try
                {
                    await this.CloseOutputSessionCoreAsync(timeout);
                    this.OnOutputSessionClosed(ref timeoutHelper);
                    shouldFault = false;
                }
                finally
                {
                    if (shouldFault)
                    {
                        this.Fault();
                    }
                }
            }
            finally
            {
                _sendLock.Release();
            }
        }

        protected void CloseOutputSession(TimeSpan timeout)
        {
            ThrowIfNotOpened();
            ThrowIfFaulted();
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            // If timeout == TimeSpan.MaxValue, then we want to pass Timeout.Infinite as
            // SemaphoreSlim doesn't accept timeouts > Int32.MaxValue.
            // Using TimeoutHelper.RemainingTime() would yield a value less than TimeSpan.MaxValue
            // and would result in the value Int32.MaxValue so we must use the original timeout specified.
            if (!_sendLock.Wait(TimeoutHelper.ToMilliseconds(timeout)))
            {
                if (TD.CloseTimeoutIsEnabled())
                {
                    TD.CloseTimeout(SR.Format(SR.CloseTimedOut, timeout));
                }

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(
                                                SR.Format(SR.CloseTimedOut, timeout),
                                                TimeoutHelper.CreateEnterTimedOutException(timeout)));
            }

            try
            {
                // check again in case the previous send faulted while we were waiting for the lock
                ThrowIfFaulted();

                // we're synchronized by sendLock here
                if (_isOutputSessionClosed)
                {
                    return;
                }

                _isOutputSessionClosed = true;
                bool shouldFault = true;
                try
                {
                    this.CloseOutputSessionCore(timeout);
                    this.OnOutputSessionClosed(ref timeoutHelper);
                    shouldFault = false;
                }
                finally
                {
                    if (shouldFault)
                    {
                        this.Fault();
                    }
                }
            }
            finally
            {
                _sendLock.Release();
            }
        }

        // used to return cached connection to the pool/reader pool
        protected abstract void ReturnConnectionIfNecessary(bool abort, TimeSpan timeout);

        protected override void OnAbort()
        {
            this.ReturnConnectionIfNecessary(true, TimeSpan.Zero);
        }

        protected override void OnFaulted()
        {
            base.OnFaulted();
            this.ReturnConnectionIfNecessary(true, TimeSpan.Zero);
        }

        protected internal override async Task OnCloseAsync(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            await this.CloseOutputSessionAsync(timeoutHelper.RemainingTime());

            // close input session if necessary
            if (!_isInputSessionClosed)
            {
                await this.EnsureInputClosedAsync(timeoutHelper.RemainingTime());
                this.OnInputSessionClosed();
            }

            this.CompleteClose(timeoutHelper.RemainingTime());
        }

        protected override void OnClose(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            this.CloseOutputSession(timeoutHelper.RemainingTime());

            // close input session if necessary
            if (!_isInputSessionClosed)
            {
                this.EnsureInputClosed(timeoutHelper.RemainingTime());
                this.OnInputSessionClosed();
            }

            this.CompleteClose(timeoutHelper.RemainingTime());
        }

        protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return OnCloseAsync(timeout).ToApm(callback, state);
        }

        protected override void OnEndClose(IAsyncResult result)
        {
            result.ToApmEnd();
        }

        protected override void OnClosed()
        {
            base.OnClosed();
            // clean up the CBT after transitioning to the closed state
            //ChannelBindingUtility.Dispose(ref this.channelBindingToken);
        }

        protected virtual void OnReceiveMessage(Message message)
        {
            if (message == null)
            {
                this.OnInputSessionClosed();
            }
            else
            {
                this.PrepareMessage(message);
            }
        }

        protected void ApplyChannelBinding(Message message)
        {
            //ChannelBindingUtility.TryAddToMessage(this.channelBindingToken, message, false);
        }

        protected virtual void PrepareMessage(Message message)
        {
            message.Properties.Via = _localVia;

            this.ApplyChannelBinding(message);

            if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled)
            {
                EventTraceActivity eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
                Guid relatedActivityId = EventTraceActivity.GetActivityIdFromThread();
                if (eventTraceActivity == null)
                {
                    eventTraceActivity = EventTraceActivity.GetFromThreadOrCreate();
                    EventTraceActivityHelper.TryAttachActivity(message, eventTraceActivity);
                }

                if (TD.MessageReceivedByTransportIsEnabled())
                {
                    TD.MessageReceivedByTransport(
                        eventTraceActivity,
                        this.LocalAddress != null && this.LocalAddress.Uri != null ? this.LocalAddress.Uri.AbsoluteUri : string.Empty,
                        relatedActivityId);
                }
            }
        }

        protected abstract AsyncCompletionResult StartWritingBufferedMessage(Message message, ArraySegment<byte> messageData, bool allowOutputBatching, TimeSpan timeout, Action<object> callback, object state);

        protected abstract AsyncCompletionResult BeginCloseOutput(TimeSpan timeout, Action<object> callback, object state);

        protected virtual void FinishWritingMessage()
        {
        }

        protected abstract ArraySegment<byte> EncodeMessage(Message message);

        protected abstract void OnSendCore(Message message, TimeSpan timeout);

        protected abstract AsyncCompletionResult StartWritingStreamedMessage(Message message, TimeSpan timeout, Action<object> callback, object state);

        protected override async Task OnSendAsync(Message message, TimeSpan timeout)
        {
            this.ThrowIfDisposedOrNotOpen();

            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            // If timeout == TimeSpan.MaxValue, then we want to pass Timeout.Infinite as
            // SemaphoreSlim doesn't accept timeouts > Int32.MaxValue.
            // Using TimeoutHelper.RemainingTime() would yield a value less than TimeSpan.MaxValue
            // and would result in the value Int32.MaxValue so we must use the original timeout specified.
            if (!await _sendLock.WaitAsync(TimeoutHelper.ToMilliseconds(timeout)))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(
                                            SR.Format(SR.SendToViaTimedOut, Via, timeout),
                                            TimeoutHelper.CreateEnterTimedOutException(timeout)));
            }

            byte[] buffer = null;

            try
            {
                // check again in case the previous send faulted while we were waiting for the lock
                this.ThrowIfDisposedOrNotOpen();
                this.ThrowIfOutputSessionClosed();

                bool success = false;
                try
                {
                    this.ApplyChannelBinding(message);

                    var tcs = new TaskCompletionSource<bool>(this);

                    AsyncCompletionResult completionResult;
                    if (this.IsStreamedOutput)
                    {
                        completionResult = this.StartWritingStreamedMessage(message, timeoutHelper.RemainingTime(), s_onWriteComplete, this);
                    }
                    else
                    {
                        bool allowOutputBatching;
                        ArraySegment<byte> messageData;
                        allowOutputBatching = message.Properties.AllowOutputBatching;
                        messageData = this.EncodeMessage(message);

                        buffer = messageData.Array;
                        completionResult = this.StartWritingBufferedMessage(
                                                                          message,
                                                                          messageData,
                                                                          allowOutputBatching,
                                                                          timeoutHelper.RemainingTime(),
                                                                          s_onWriteComplete,
                                                                          tcs);
                    }

                    if (completionResult == AsyncCompletionResult.Completed)
                    {
                        tcs.TrySetResult(true);
                    }

                    await tcs.Task;

                    this.FinishWritingMessage();

                    success = true;
                    if (TD.MessageSentByTransportIsEnabled())
                    {
                        EventTraceActivity eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
                        TD.MessageSentByTransport(eventTraceActivity, this.RemoteAddress.Uri.AbsoluteUri);
                    }
                }
                finally
                {
                    if (!success)
                    {
                        this.Fault();
                    }
                }
            }
            finally
            {
                _sendLock.Release();
            }
            if (buffer != null)
            {
                _bufferManager.ReturnBuffer(buffer);
            }
        }

        private static void OnWriteComplete(object state)
        {
            if (state == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("state");
            }

            var tcs = state as TaskCompletionSource<bool>;
            if (tcs == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("state", SR.SPS_InvalidAsyncResult);
            }

            tcs.TrySetResult(true);
        }

        protected override void OnSend(Message message, TimeSpan timeout)
        {
            this.ThrowIfDisposedOrNotOpen();

            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            // If timeout == TimeSpan.MaxValue, then we want to pass Timeout.Infinite as
            // SemaphoreSlim doesn't accept timeouts > Int32.MaxValue.
            // Using TimeoutHelper.RemainingTime() would yield a value less than TimeSpan.MaxValue
            // and would result in the value Int32.MaxValue so we must use the original timeout specified.
            if (!_sendLock.Wait(TimeoutHelper.ToMilliseconds(timeout)))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(
                                            SR.Format(SR.SendToViaTimedOut, Via, timeout),
                                            TimeoutHelper.CreateEnterTimedOutException(timeout)));
            }

            try
            {
                // check again in case the previous send faulted while we were waiting for the lock
                this.ThrowIfDisposedOrNotOpen();
                this.ThrowIfOutputSessionClosed();

                bool success = false;
                try
                {
                    this.ApplyChannelBinding(message);

                    this.OnSendCore(message, timeoutHelper.RemainingTime());
                    success = true;
                    if (TD.MessageSentByTransportIsEnabled())
                    {
                        EventTraceActivity eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
                        TD.MessageSentByTransport(eventTraceActivity, this.RemoteAddress.Uri.AbsoluteUri);
                    }
                }
                finally
                {
                    if (!success)
                    {
                        this.Fault();
                    }
                }
            }
            finally
            {
                _sendLock.Release();
            }
        }

        // cleanup after the framing handshake has completed
        protected abstract void CompleteClose(TimeSpan timeout);

        // must be called under sendLock
        private void ThrowIfOutputSessionClosed()
        {
            if (_isOutputSessionClosed)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SendCannotBeCalledAfterCloseOutputSession));
            }
        }

        private async Task EnsureInputClosedAsync(TimeSpan timeout)
        {
            Message message = await this.MessageSource.ReceiveAsync(timeout);
            if (message != null)
            {
                using (message)
                {
                    ProtocolException error = ProtocolException.ReceiveShutdownReturnedNonNull(message);
                    throw TraceUtility.ThrowHelperError(error, message);
                }
            }
        }

        private void EnsureInputClosed(TimeSpan timeout)
        {
            Message message = this.MessageSource.Receive(timeout);
            if (message != null)
            {
                using (message)
                {
                    ProtocolException error = ProtocolException.ReceiveShutdownReturnedNonNull(message);
                    throw TraceUtility.ThrowHelperError(error, message);
                }
            }
        }

        private void OnInputSessionClosed()
        {
            lock (ThisLock)
            {
                if (_isInputSessionClosed)
                {
                    return;
                }

                _isInputSessionClosed = true;
            }
        }

        private void OnOutputSessionClosed(ref TimeoutHelper timeoutHelper)
        {
            bool releaseConnection = false;
            lock (ThisLock)
            {
                if (_isInputSessionClosed)
                {
                    // we're all done, release the connection
                    releaseConnection = true;
                }
            }

            if (releaseConnection)
            {
                this.ReturnConnectionIfNecessary(false, timeoutHelper.RemainingTime());
            }
        }

        public class ConnectionDuplexSession : IDuplexSession
        {
            private static UriGenerator s_uriGenerator;
            private TransportDuplexSessionChannel _channel;
            private string _id;

            public ConnectionDuplexSession(TransportDuplexSessionChannel channel)
                : base()
            {
                _channel = channel;
            }

            public string Id
            {
                get
                {
                    if (_id == null)
                    {
                        lock (_channel)
                        {
                            if (_id == null)
                            {
                                _id = UriGenerator.Next();
                            }
                        }
                    }

                    return _id;
                }
            }

            public TransportDuplexSessionChannel Channel
            {
                get { return _channel; }
            }

            private static UriGenerator UriGenerator
            {
                get
                {
                    if (s_uriGenerator == null)
                    {
                        s_uriGenerator = new UriGenerator();
                    }

                    return s_uriGenerator;
                }
            }

            public IAsyncResult BeginCloseOutputSession(AsyncCallback callback, object state)
            {
                return this.BeginCloseOutputSession(_channel.DefaultCloseTimeout, callback, state);
            }

            public IAsyncResult BeginCloseOutputSession(TimeSpan timeout, AsyncCallback callback, object state)
            {
                return _channel.CloseOutputSessionAsync(timeout).ToApm(callback, state);
            }

            public void EndCloseOutputSession(IAsyncResult result)
            {
                result.ToApmEnd();
            }

            public void CloseOutputSession()
            {
                this.CloseOutputSession(_channel.DefaultCloseTimeout);
            }

            public void CloseOutputSession(TimeSpan timeout)
            {
                _channel.CloseOutputSession(timeout);
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">@color/blue_light</color>
    <color name="colorPrimaryDark">@color/blue_dark</color>
    <color name="colorAccent">@color/pink</color>

    <color name="viewpager_indicator_default">@color/gray_dark</color>
    <color name="viewpager_indicator_selector">@color/green</color>

    <color name="white">#FFFFFF</color>
    <color name="black">#000000</color>
    <color name="transparent">#00000000</color>
    <color name="red">#FF0000</color>
    <color name="gray_light">#E0E0E0</color>
    <color name="gray_dark">#BDBDBD</color>
    <color name="blue_light">#303F9F</color>
    <color name="blue_dark">#303F9F</color>
    <color name="pink">#FF4081</color>
    <color name="green">#00897B</color>
</resources>


text:
<?php

use OAuth\OAuth2\Service\Mailchimp;
use OAuth\Common\Storage\Session;
use OAuth\Common\Consumer\Credentials;

$_SERVER['SERVER_PORT'] = 80;

/**
 * Bootstrap the example
 */
require_once __DIR__ . '/bootstrap.php';

// Session storage
$storage = new Session();

// Setup the credentials for the requests
$credentials = new Credentials(
    $servicesCredentials['mailchimp']['key'],
    $servicesCredentials['mailchimp']['secret'],
    $currentUri->getAbsoluteUri()
);

// Instantiate the Mailchimp service using the credentials, http client and storage mechanism for the token
/** @var $mailchimpService Mailchimp */
$mailchimpService = $serviceFactory->createService('mailchimp', $credentials, $storage, array());

if (!empty($_GET['code'])) {
    // This was a callback request from mailchimp, get the token
    $token = $mailchimpService->requestAccessToken($_GET['code']);

    // Send a request with it
    $result = $mailchimpService->request('/users/profile.json');

    header('Content-Type: application/json');
    echo $result; exit;

} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') {
    $url = $mailchimpService->getAuthorizationUri();
    header('Location: ' . $url);
} else {
    $url = $currentUri->getRelativeUri() . '?go=go';
    echo "Login with Mailchimp!";
}


text:
using Jal.Router.Impl;
using Jal.Router.Interface;
using Jal.Router.Model;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
using System.Threading.Tasks;

namespace Jal.Router.Tests
{
    [TestClass]
    public class ProducerTests
    {
        private Producer Build(ISenderContextLifecycle lifecycle)
        {
            return new Producer(new NullLogger(), lifecycle);
        }

        [TestMethod]
        public async Task Bus_With_ShouldBeExecuted()
        {
            var factorymock = Builder.CreateFactoryMock();

            var lifecyclemock = new Mock<ISenderContextLifecycle>();

            var senderchannelmock = new Mock<IChannelSender>();

            factorymock.Setup(x => x.CreateSenderChannel(It.IsAny<ChannelType>(), It.IsAny<Type>())).Returns((senderchannelmock.Object, null, new NullPointToPointChannel(), new NullPointToPointChannel(), new NullPointToPointChannel()));

            var factory = factorymock.Object;

            var messagecontext = Builder.CreateMessageContextToSend(factory: factory);

            lifecyclemock.Setup(x => x.Get(It.IsAny<Channel>())).Returns(Builder.CreateSenderContext(factory));

            var sut = Build(lifecyclemock.Object);

            await sut.Produce(messagecontext);

            senderchannelmock.WasExecuted();

        }
    }
}


text:
ClassType = GraphQL::ObjectType.define do
  name "Class"
  field :name, types.String
  field :ancestors, -> { types[ClassType] }
end