text:
require "spec_helper"

describe Siphon::Base do

  describe "#initialize" do

    it "must initialize with an ActiveRelation" do
      expect { Siphon::Base.new }.to raise_error(ArgumentError)
    end

    it "sets @relation" do
      relation = double
      siphon = Siphon::Base.new(relation)

      expect(siphon.relation).to eq(relation)
    end
  end

  describe "#with", broken: true do

    it "returns proxy" do
      siphon = Siphon::Base.new("")

      expect(siphon.with({published: nil})).to be_kind_of(Siphon::Proxy)
    end

    it "sets params" do
      siphon = Siphon::Base.new("").with(published: :integer)

      expect(siphon.params).to eq(published: :integer)
    end
  end

  describe "#proxy", broken: true do
    it "handles the scope calls" do
      relation = double
      siphon = Siphon::Base.new(relation)

      expect(relation).to receive(:admin).with("yes").and_return(relation)
      expect(relation).to receive(:published).with("yes").and_return(relation)

      siphon.with(admin: "yes", published: "yes").admin("no").published
    end
  end

  describe "#recall", broken: true do
    it "exposes a proxy whose method_missing will record calls to be recalled conditionally" do
      relation = double
      expect(relation).to receive(:admin).with("yes").and_return(relation)
      expect(relation).to receive(:published).with("yes").and_return(relation)

      Siphon::Base.new(relation).recall.admin("no").published.when({admin: "yes", published: "yes"})
    end
  end

  describe "functional testing", broken: true  do
    it "kinda works" do
      relation = double
      formobj = Formobj.new(admin: true, after: 1950, name: "")

      expect(relation).to receive(:admin).with(true).and_return(relation)
      expect(relation).to receive(:after).with(1950).and_return(relation)

      Siphon::Base.new(relation).admin(false).after(1).scope(formobj)
    end
  end
end


text:
<?php namespace ZN;
/**
 * ZN PHP Web Framework
 *
 * "Simplicity is the ultimate sophistication." ~ Da Vinci
 *
 * @package ZN
 * @license MIT [http://opensource.org/licenses/MIT]
 * @author  Ozan UYKUN [ozan@znframework.com]
 */

class StaticAccess
{
    /**
     * Magic call static
     *
     * @param string $method
     * @param array  $parameters
     *
     * @return mixed
     */
    public static function __callStatic($method, $parameters)
    {
        return self::useClassName($method, $parameters);
    }

    /**
     * Magic call
     *
     * @param string $method
     * @param array  $parameters
     *
     * @return mixed
     */
    public function __call($method, $parameters)
    {
        return self::useClassName($method, $parameters);
    }

    /**
     * protected use class name
     *
     * @param string $method
     * @param array  $parameters
     *
     * @return mixed
     */
    protected static function useClassName($method, $parameters)
    {
        return Singleton::class(INTERNAL_ACCESS . static::getClassName())->$method(...$parameters);
    }
}

redpajama_set_name: RedPajamaGithub


text:
/* Device Context Functions: http://msdn.microsoft.com/en-us/library/dd183554 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <freerdp/freerdp.h>

#include "gdi.h"
#include "gdi_region.h"

#include "gdi_dc.h"

/**
 * Get the current device context (a new one is created each time).\n
 * @msdn{dd144871}
 * @return current device context
 */

HGDI_DC gdi_GetDC()
{
	HGDI_DC hDC = (HGDI_DC) malloc(sizeof(GDI_DC));
	hDC->bytesPerPixel = 4;
	hDC->bitsPerPixel = 32;
	hDC->drawMode = GDI_R2_BLACK;
	hDC->clip = gdi_CreateRectRgn(0, 0, 0, 0);
	hDC->clip->null = 1;
	hDC->hwnd = NULL;
	return hDC;
}

/**
 * Create a new device context compatible with the given device context.\n
 * @msdn{dd183489}
 * @param hdc device context
 * @return new compatible device context
 */

HGDI_DC gdi_CreateCompatibleDC(HGDI_DC hdc)
{
	HGDI_DC hDC = (HGDI_DC) malloc(sizeof(GDI_DC));
	hDC->bytesPerPixel = hdc->bytesPerPixel;
	hDC->bitsPerPixel = hdc->bitsPerPixel;
	hDC->drawMode = hdc->drawMode;
	hDC->clip = gdi_CreateRectRgn(0, 0, 0, 0);
	hDC->clip->null = 1;
	hDC->hwnd = NULL;
	hDC->alpha = hdc->alpha;
	hDC->invert = hdc->invert;
	hDC->rgb555 = hdc->rgb555;
	return hDC;
}

/**
 * Select a GDI object in the current device context.\n
 * @msdn{dd162957}
 * @param hdc device context
 * @param hgdiobject new selected GDI object
 * @return previous selected GDI object
 */

HGDIOBJECT gdi_SelectObject(HGDI_DC hdc, HGDIOBJECT hgdiobject)
{
	HGDIOBJECT previousSelectedObject = hdc->selectedObject;

	if (hgdiobject == NULL)
		return NULL;

	if (hgdiobject->objectType == GDIOBJECT_BITMAP)
	{
		hdc->selectedObject = hgdiobject;
	}
	else if (hgdiobject->objectType == GDIOBJECT_PEN)
	{
		previousSelectedObject = (HGDIOBJECT) hdc->pen;
		hdc->pen = (HGDI_PEN) hgdiobject;
	}
	else if (hgdiobject->objectType == GDIOBJECT_BRUSH)
	{
		previousSelectedObject = (HGDIOBJECT) hdc->brush;
		hdc->brush = (HGDI_BRUSH) hgdiobject;
	}
	else if (hgdiobject->objectType == GDIOBJECT_REGION)
	{
		hdc->selectedObject = hgdiobject;
	}
	else if (hgdiobject->objectType == GDIOBJECT_RECT)
	{
		hdc->selectedObject = hgdiobject;
	}
	else
	{
		/* Unknown GDI Object Type */
		return 0;
	}

	return previousSelectedObject;
}

/**
 * Delete a GDI object.\n
 * @msdn{dd183539}
 * @param hgdiobject GDI object
 * @return 1 if successful, 0 otherwise
 */

int gdi_DeleteObject(HGDIOBJECT hgdiobject)
{
	if (hgdiobject == NULL)
		return 0;

	if (hgdiobject->objectType == GDIOBJECT_BITMAP)
	{
		HGDI_BITMAP hBitmap = (HGDI_BITMAP) hgdiobject;

		if (hBitmap->data != NULL)
			free(hBitmap->data);

		free(hBitmap);
	}
	else if (hgdiobject->objectType == GDIOBJECT_PEN)
	{
		HGDI_PEN hPen = (HGDI_PEN) hgdiobject;
		free(hPen);
	}
	else if (hgdiobject->objectType == GDIOBJECT_BRUSH)
	{
		HGDI_BRUSH hBrush = (HGDI_BRUSH) hgdiobject;

		if(hBrush->style == GDI_BS_PATTERN)
			gdi_DeleteObject((HGDIOBJECT) hBrush->pattern);

		free(hBrush);
	}
	else if (hgdiobject->objectType == GDIOBJECT_REGION)
	{
		free(hgdiobject);
	}
	else if (hgdiobject->objectType == GDIOBJECT_RECT)
	{
		free(hgdiobject);
	}
	else
	{
		/* Unknown GDI Object Type */
		free(hgdiobject);
		return 0;
	}

	return 1;
}

/**
 * Delete device context.\n
 * @msdn{dd183533}
 * @param hdc device context
 * @return 1 if successful, 0 otherwise
 */

int gdi_DeleteDC(HGDI_DC hdc)
{
	if (hdc->hwnd)
	{
		free(hdc->hwnd->invalid);
		free(hdc->hwnd);
	}

	free(hdc->clip);
	free(hdc);

	return 1;
}


text:
'use strict';

var Analytics = require('@segment/analytics.js-core').constructor;
var integration = require('@segment/analytics.js-integration');
var tester = require('@segment/analytics.js-integration-tester');
var sandbox = require('@segment/clear-env');
var Drip = require('../lib/');

describe('Drip', function() {
  var analytics;
  var drip;
  var options = {
    account: '3826504',
    campaignId: ''
  };

  beforeEach(function() {
    analytics = new Analytics();
    drip = new Drip(options);
    analytics.use(Drip);
    analytics.use(tester);
    analytics.add(drip);
  });

  afterEach(function() {
    analytics.restore();
    analytics.reset();
    drip.reset();
    sandbox();
  });

  it('should have the right settings', function() {
    analytics.compare(Drip, integration('Drip')
      .global('_dc')
      .global('_dcq')
      .global('_dcqi')
      .global('_dcs')
      .option('account', ''));
  });

  describe('before loading', function() {
    beforeEach(function() {
      analytics.stub(drip, 'load');
    });

    describe('#initialize', function() {
      it('should create window._dcq', function() {
        analytics.assert(!window._dcq);
        analytics.initialize();
        analytics.page();
        analytics.assert(window._dcq instanceof Array);
      });

      it('should create window._dcs', function() {
        analytics.assert(!window._dcs);
        analytics.initialize();
        analytics.page();
        analytics.assert(window._dcs);
        analytics.assert(window._dcs.account === options.account);
      });

      it('should call #load', function() {
        analytics.initialize();
        analytics.page();
        analytics.called(drip.load);
      });
    });
  });

  describe('loading', function() {
    it('should load', function(done) {
      analytics.load(drip, done);
    });
  });

  describe('after loading', function() {
    beforeEach(function(done) {
      analytics.once('ready', done);
      analytics.initialize();
      analytics.page();
    });

    describe('#track', function() {
      beforeEach(function() {
        analytics.stub(window._dcq, 'push');
      });

      it('should send event as the action', function() {
        analytics.track('event');
        analytics.called(window._dcq.push, ['track', 'event', {}]);
      });

      it('should convert and alias revenue', function() {
        analytics.track('event', { revenue: '9.99' });
        analytics.called(window._dcq.push, ['track', 'event', { value: 999 }]);
      });

      it('should replace spaces with underscores in for property keys', function() {
        analytics.track('event', { 'ahoy mate there': 'howdy' });
        analytics.called(window._dcq.push, ['track', 'event', { ahoy_mate_there: 'howdy' }]);
      });
    });

    describe('#identify', function() {
      beforeEach(function() {
        analytics.stub(window._dcq, 'push');
      });

      it('should send identify with traits', function() {
        var traits = { email: 'philz@philz.com', heyyou: 'know yourself' };
        analytics.identify('id', traits);
        analytics.called(window._dcq.push, ['identify', { id: 'id', heyyou: 'know yourself', email: 'philz@philz.com' }]);
      });

      it('should not send if email is not there', function() {
        analytics.identify('id', { trait: true });
        analytics.didNotCall(window._dcq.push);
      });

      it('should subscribe to campaignId if provided in the settings', function() {
        drip.options.campaignId = '83702741';
        var traits = { email: 'philz@philz.com', heyyou: 'know yourself', id: 'id' };
        analytics.identify('id', traits);
        analytics.deepEqual(window._dcq.push.args[1], [['subscribe', { campaign_id: drip.options.campaignId, fields: traits }]]);
      });

      it('should let you override subscribing to campaignId if provided in integration specific settings', function() {
        drip.options.campaignId = '83702741';
        var traits = { email: 'philz@philz.com', heyyou: 'know yourself', id: 'id' };
        var intOptions = { Drip: { campaignId: '12345678' } };
        analytics.identify('id', traits, intOptions);
        analytics.deepEqual(window._dcq.push.args[1], [['subscribe', { campaign_id: '12345678', fields: traits }]]);
      });
    });
  });
});


text:
if [ $# -ne 0 ]; then
  echo "$0: nothing needed"
  exit 1
fi

APPLICATIONS="docker docker-compose"

pacman -S $APPLICATIONS --noconfirm --needed

systemctl enable docker


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

$lang['ftp_no_connection']       = 'Nebolo nájdené platné ID spojenia. Uistite sa, že máte otvorené pripojenie predtým ako začnete akúkoľvek manipuláciu so súbormi.';
$lang['ftp_unable_to_connect']   = 'Nie je možné pripojiť sa k FTP serveru zo zadanou adresou.';
$lang['ftp_unable_to_login']     = 'Nie je možné pripojiť sa k FTP serveru. Skontrolujte zadané užívateľské meno a heslo.';
$lang['ftp_unable_to_mkdir']     = 'Požadovaný adresár nie je možné vytvoriť.';
$lang['ftp_unable_to_changedir'] = 'Adresáre nie je možné zmeniť.';
$lang['ftp_unable_to_chmod']     = 'Nie je možné nastaviť práva k súboru. Skontrolujte cestu. Poznámka: Táto funkcia je dostupná iba v PHP verzie 5 a vyšších.';
$lang['ftp_unable_to_upload']    = 'Požadovaný súbor nemožno nahrať. Skontrolujte cestu.';
$lang['ftp_unable_to_download']  = 'Nepodařilo se stáhnout soubor. Zkontrolujte prosím cestu.';
$lang['ftp_no_source_file']      = 'Zrojový súbor nebol nájdený. Skontrolujte cestu.';
$lang['ftp_unable_to_rename']    = 'Súbor sa nedá premenovať.';
$lang['ftp_unable_to_delete']    = 'Súbor sa nedá zmazať.';
$lang['ftp_unable_to_move']      = 'Súbor sa nedá presunúť. Uistite sa, že cieľový adresár existuje.';


text:
var DetailView = require('ui/common/DetailView');
var Model = require('services/Model');

//Master View Component Constructor
function MasterView() {
	//create object instance, parasitic subclass of Observable
	var self = Ti.UI.createView({
	});

	var groupData = Ti.UI.createTableViewSection({
	});

	var moneyRow = Ti.UI.createTableViewRow({
		touchEnabled : false,
		selectionStyle : Titanium.UI.iPhone.TableViewCellSelectionStyle.NONE
	});
	groupData.add(moneyRow);
	moneyRow.add(Ti.UI.createLabel({
		text: '金額',
		left: 5,
		top: 5,
		bottom: 5,
		height: 'auto'
	}));
	var moneyField = Ti.UI.createTextField({
		hintText: '総額を入力',
		right: 5,
		width: 200,
		clearButtonMode: Titanium.UI.INPUT_BUTTONMODE_ALWAYS,
		keyboardType: Titanium.UI.KEYBOARD_NUMBER_PAD
	});
	moneyField.addEventListener('change', function() {
		Model.money = moneyField.value | 0;
	});
	moneyRow.add(moneyField);

	var peopleRow = Ti.UI.createTableViewRow({
		touchEnabled : false,
		selectionStyle : Titanium.UI.iPhone.TableViewCellSelectionStyle.NONE
	});
	groupData.add(peopleRow);
	peopleRow.add(Ti.UI.createLabel({
		text: '人数',
		left: 5,
		top: 5,
		bottom: 5,
		height: 'auto'
	}));
	var peopleField = Ti.UI.createTextField({
		hintText: '幹事も含めて入力',
		right: 5,
		width: 200,
		clearButtonMode: Titanium.UI.INPUT_BUTTONMODE_ALWAYS,
		keyboardType: Titanium.UI.KEYBOARD_NUMBER_PAD
	});
	peopleField.addEventListener('change', function() {
		Model.people = peopleField.value | 0;
	});
	peopleRow.add(peopleField);

	var unitRow = Ti.UI.createTableViewRow({
		touchEnabled : false,
		selectionStyle : Titanium.UI.iPhone.TableViewCellSelectionStyle.NONE
	});
	groupData.add(unitRow);
	var unitLabel;
	unitRow.add(unitLabel = Ti.UI.createLabel({
		text: '500円単位で計算',
		left: 5,
		top: 5,
		width: 300,
		bottom: 5,
		height: 'auto'
	}));
	var unitField = Ti.UI.createSlider({
		min: 0,
		max: 8,
		value: 5,
		right: 5,
		left: 155,
		keyboardType: Titanium.UI.KEYBOARD_NUMBER_PAD
	});
	Model.unit = 5;
	unitField.addEventListener('change', function() {
		var units = [1, 5, 10, 50, 100, 500, 1000, 5000, 10000];
		var unit = units[Math.round(unitField.value)];
		Model.unit = unit;
		unitLabel.text = unit + '円単位で計算';
	});
	unitRow.add(unitField);

	var calcPositiveRow = Ti.UI.createTableViewRow({
	});
	groupData.add(calcPositiveRow);
	calcPositiveRow.add(Ti.UI.createLabel({
		text: '幹事有利で計算',
		top: 5,
		bottom: 5,
		height: 'auto'
	}));

	var calcNegativeRow = Ti.UI.createTableViewRow({
	});
	groupData.add(calcNegativeRow);
	calcNegativeRow.add(Ti.UI.createLabel({
		text: '幹事不利で計算',
		top: 5,
		bottom: 5,
		height: 'auto'
	}));

	var tableView = Ti.UI.createTableView({
		data: [groupData],
		style: Titanium.UI.iPhone.TableViewStyle.GROUPED
	});
	tableView.addEventListener('click', function(e) {
		if(e.index == 3 || e.index == 4) {
			if(!Model.money || !Model.people) {
				var dialog = Titanium.UI.createAlertDialog();
				dialog.setTitle('不正な入力です');
				dialog.setMessage('金額と人数を入力してください。');
				dialog.show();
			} else {
				Model.calcFunc = (e.index == 3)? Math.ceil: Math.floor;
				var win = Ti.UI.createWindow({
					title: '計算結果',
					backButtonTitle: '戻る'
				});
				var detailView = new DetailView(win);
				win.add(detailView);
				self.nav.open(win);
			}
		}
	});
	self.add(tableView);

	return self;
};

module.exports = MasterView;


text:
namespace xixEngine {
	//Helpers functions
	void fatalError(std::string errorString);
}


text:
class String;

class Scheduler
{
public:
	virtual ~Scheduler();

	static String currTimeInDayHourMin();
	static String convertFromDayHourMinInDecimal( String timeDate );
	static String CurrTimeDateInDecimal();
	static String ConvertFromSingleTimeInDecimal( String singleTime );

private:
	// static only, not instantiated
	Scheduler();
};

#endif // !defined(AFX_SCHEDULER_H__7F6C16A2_D25E_11D3_9CBC_00C026FFE74C__INCLUDED_)


text:
A `rm -rf` for node.

Install with `npm install rimraf`, or just drop rimraf.js somewhere.

## API

`rimraf(f, [options,] callback)`

The callback will be called with an error if there is one.  Certain
errors are handled for you:

* `EBUSY` -  rimraf will back off a maximum of opts.maxBusyTries times
  before giving up.
* `EMFILE` - If too many file descriptors get opened, rimraf will
  patiently wait until more become available.

## Options

The options object is optional.  These fields are respected:

* `maxBusyTries` -  The number of times to retry a file or folder in the
  event of an `EBUSY` error.  The default is 3.
* `gently` - If provided a `gently` path, then rimraf will only delete
  files and folders that are beneath this path, and only delete symbolic
  links that point to a place within this path.  (This is very important
  to npm's use-case, and shows rimraf's pedigree.)

## rimraf.sync

It can remove stuff synchronously, too.  But that's not so good.  Use
the async API.  It's better.


text:
/*
 * ZapShowChannelsCompleteEvent.cpp
 *
 *  Created on: May 3, 2012
 *      Author: augcampos
 */

#include "asteriskcpp/manager/events/ZapShowChannelsCompleteEvent.h"

namespace asteriskcpp {

    ZapShowChannelsCompleteEvent::ZapShowChannelsCompleteEvent(const std::string & values) :
    ResponseEvent(values) {

    }

    ZapShowChannelsCompleteEvent::~ZapShowChannelsCompleteEvent() {
    }

} /* namespace asteriskcpp */


text:
package com.ctrip.xpipe.api.lifecycle;

/**
 * @author wenchao.meng
 *
 * 2016年4月21日 下午4:57:05
 */
public interface Stoppable {

	public static final String PHASE_NAME_BEGIN = "stopping";

	public static final String PHASE_NAME_END = "stopped";

	void stop() throws Exception;
}


text:
/*
 * =====================================================================================
 *
 *       Filename:  processor.h
 *
 *       Description:  The HOD of profiler, who init the profiler.
 *
 *       Version:  1.0
 *       Created:  Monday 21 November 2016 11:16:48  IST
 *       Revision:  none
 *       Compiler:  gcc
 *
 *       Author:  SIGCONT (suman roy), email.suman.roy@gmail.com
 *       Organization:  OPEN SOURCE
 *       LICENSE: Apache License
 * =====================================================================================
 */
#ifndef PROCESSOR_H
#define PROCESSOR_H

#include "profiler.h"
#include "processData.h"

class Processor: public JavaProfiler {
    public:
        explicit Processor(jvmtiEnv* jvmtiEnv, JavaVM* javaVM): JavaProfiler(jvmtiEnv, javaVM) {}

        virtual ~Processor(void) {}

        inline void init(void) {
            (void)startProfiler();
        }

        inline void exit(void) {
            (void)stopProfiler();
        }
};

#endif


text:
package com.facebook.buck.features.ocaml;

import com.facebook.buck.core.cell.CellPathResolver;
import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.core.filesystems.AbsPath;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.Flavor;
import com.facebook.buck.core.model.InternalFlavor;
import com.facebook.buck.core.model.TargetConfiguration;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.rules.BuildRuleParams;
import com.facebook.buck.core.rules.BuildRuleResolver;
import com.facebook.buck.core.rules.common.BuildableSupport;
import com.facebook.buck.core.sourcepath.BuildTargetSourcePath;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.sourcepath.resolver.SourcePathResolverAdapter;
import com.facebook.buck.core.util.graph.AbstractBreadthFirstTraversal;
import com.facebook.buck.core.util.graph.DirectedAcyclicGraph;
import com.facebook.buck.core.util.graph.MutableDirectedGraph;
import com.facebook.buck.core.util.graph.TopologicalSort;
import com.facebook.buck.cxx.CxxPreprocessables;
import com.facebook.buck.cxx.CxxPreprocessorDep;
import com.facebook.buck.cxx.CxxPreprocessorInput;
import com.facebook.buck.cxx.toolchain.linker.Linker;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkableGroup;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkableGroups;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkableInput;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkables;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.rules.args.Arg;
import com.facebook.buck.rules.args.StringArg;
import com.facebook.buck.rules.macros.StringWithMacros;
import com.facebook.buck.util.Console;
import com.facebook.buck.util.DefaultProcessExecutor;
import com.facebook.buck.util.ProcessExecutor;
import com.facebook.buck.util.ProcessExecutorParams;
import com.facebook.buck.util.stream.RichStream;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Stream;

/** Compute transitive dependencies and generate ocaml build rules */
public class OcamlRuleBuilder {

  private static final Flavor OCAML_STATIC_FLAVOR = InternalFlavor.of("static");
  private static final Flavor OCAML_LINK_BINARY_FLAVOR = InternalFlavor.of("binary");

  private OcamlRuleBuilder() {}

  public static Function<BuildRule, ImmutableList<String>> getLibInclude(
      OcamlPlatform platform, boolean isBytecode) {
    return input -> {
      if (input instanceof OcamlLibrary) {
        OcamlLibrary library = (OcamlLibrary) input;
        if (isBytecode) {
          return ImmutableList.copyOf(library.getBytecodeIncludeDirs(platform));
        } else {
          return ImmutableList.of(library.getIncludeLibDir(platform).toString());
        }
      } else {
        return ImmutableList.of();
      }
    };
  }

  @VisibleForTesting
  protected static BuildTarget createStaticLibraryBuildTarget(BuildTarget target) {
    return target.withAppendedFlavors(OCAML_STATIC_FLAVOR);
  }

  @VisibleForTesting
  protected static BuildTarget createOcamlLinkTarget(BuildTarget target) {
    return target.withAppendedFlavors(OCAML_LINK_BINARY_FLAVOR);
  }

  static boolean shouldUseFineGrainedRules(
      BuildRuleResolver resolver, ImmutableList<SourcePath> srcs) {
    boolean noYaccOrLexSources =
        srcs.stream()
            .noneMatch(
                OcamlUtil.sourcePathExt(
                    resolver.getSourcePathResolver(),
                    OcamlCompilables.OCAML_MLL,
                    OcamlCompilables.OCAML_MLY));
    boolean noGeneratedSources =
        FluentIterable.from(srcs).filter(BuildTargetSourcePath.class).isEmpty();
    return noYaccOrLexSources && noGeneratedSources;
  }

  private static ImmutableList<OcamlLibrary> getTransitiveOcamlLibraryDeps(
      BuildRuleResolver buildRuleResolver,
      OcamlPlatform platform,
      Iterable<? extends BuildRule> deps) {
    MutableDirectedGraph<OcamlLibrary> graph = new MutableDirectedGraph<>();

    new AbstractBreadthFirstTraversal<OcamlLibrary>(
        RichStream.from(deps).filter(OcamlLibrary.class).toImmutableList()) {
      @Override
      public Iterable<OcamlLibrary> visit(OcamlLibrary node) {
        graph.addNode(node);
        Iterable<OcamlLibrary> deps =
            RichStream.from(node.getOcamlLibraryDeps(buildRuleResolver, platform))
                .filter(OcamlLibrary.class)
                .toImmutableList();
        for (OcamlLibrary dep : deps) {
          graph.addEdge(node, dep);
        }
        return deps;
      }
    }.start();

    return TopologicalSort.sort(new DirectedAcyclicGraph<>(graph));
  }

  private static NativeLinkableInput getNativeLinkableInput(
      BuildRuleResolver buildRuleResolver, OcamlPlatform platform, Iterable<BuildRule> deps) {
    List<NativeLinkableInput> inputs = new ArrayList<>();

    // Add in the linkable input from OCaml libraries.
    ImmutableList<OcamlLibrary> ocamlDeps =
        getTransitiveOcamlLibraryDeps(buildRuleResolver, platform, deps);
    for (OcamlLibrary dep : ocamlDeps) {
      inputs.add(dep.getNativeLinkableInput(platform));
    }

    return NativeLinkableInput.concat(inputs);
  }

  private static NativeLinkableInput getBytecodeLinkableInput(
      BuildRuleResolver buildRuleResolver, OcamlPlatform platform, Iterable<BuildRule> deps) {
    List<NativeLinkableInput> inputs = new ArrayList<>();

    // Add in the linkable input from OCaml libraries.
    ImmutableList<OcamlLibrary> ocamlDeps =
        getTransitiveOcamlLibraryDeps(buildRuleResolver, platform, deps);
    for (OcamlLibrary dep : ocamlDeps) {
      inputs.add(dep.getBytecodeLinkableInput(platform));
    }

    return NativeLinkableInput.concat(inputs);
  }

  private static NativeLinkableInput getCLinkableInput(
      OcamlPlatform platform,
      ActionGraphBuilder graphBuilder,
      TargetConfiguration targetConfiguration,
      Iterable<BuildRule> deps) {
    // Get the topologically sorted native linkables.
    ImmutableMap<BuildTarget, NativeLinkableGroup> roots =
        NativeLinkableGroups.getNativeLinkableRoots(
            deps,
            (Function<? super BuildRule, Optional<Iterable<? extends BuildRule>>>)
                r ->
                    r instanceof OcamlLibrary
                        ? Optional.of(
                            ((OcamlLibrary) r).getOcamlLibraryDeps(graphBuilder, platform))
                        : Optional.empty());

    return NativeLinkables.getTransitiveNativeLinkableInput(
        graphBuilder,
        targetConfiguration,
        Iterables.transform(
            roots.values(), g -> g.getNativeLinkable(platform.getCxxPlatform(), graphBuilder)),
        Linker.LinkableDepType.STATIC);
  }

  static OcamlBuild createBulkCompileRule(
      BuildTarget buildTarget,
      OcamlPlatform ocamlPlatform,
      BuildTarget compileBuildTarget,
      ProjectFilesystem projectFilesystem,
      BuildRuleParams params,
      ActionGraphBuilder graphBuilder,
      Iterable<BuildRule> deps,
      ImmutableList<SourcePath> srcs,
      boolean isLibrary,
      boolean bytecodeOnly,
      ImmutableList<Arg> argFlags,
      ImmutableList<String> ocamlDepFlags) {
    CxxPreprocessorInput cxxPreprocessorInputFromDeps =
        CxxPreprocessorInput.concat(
            CxxPreprocessables.getTransitiveCxxPreprocessorInput(
                ocamlPlatform.getCxxPlatform(),
                graphBuilder,
                FluentIterable.from(deps).filter(CxxPreprocessorDep.class)));

    ImmutableList<String> nativeIncludes =
        FluentIterable.from(deps)
            .transformAndConcat(getLibInclude(ocamlPlatform, false)::apply)
            .toList();

    ImmutableList<String> bytecodeIncludes =
        FluentIterable.from(deps)
            .transformAndConcat(getLibInclude(ocamlPlatform, true)::apply)
            .toList();

    NativeLinkableInput nativeLinkableInput =
        getNativeLinkableInput(graphBuilder, ocamlPlatform, deps);
    NativeLinkableInput bytecodeLinkableInput =
        getBytecodeLinkableInput(graphBuilder, ocamlPlatform, deps);
    NativeLinkableInput cLinkableInput =
        getCLinkableInput(ocamlPlatform, graphBuilder, buildTarget.getTargetConfiguration(), deps);

    ImmutableList<OcamlLibrary> ocamlInput =
        getTransitiveOcamlLibraryDeps(graphBuilder, ocamlPlatform, deps);

    ImmutableSortedSet.Builder<BuildRule> allDepsBuilder = ImmutableSortedSet.naturalOrder();
    allDepsBuilder.addAll(graphBuilder.filterBuildRuleInputs(srcs));
    allDepsBuilder.addAll(
        Stream.of(nativeLinkableInput, bytecodeLinkableInput, cLinkableInput)
            .flatMap(input -> input.getArgs().stream())
            .flatMap(arg -> BuildableSupport.getDeps(arg, graphBuilder))
            .iterator());
    for (OcamlLibrary library : ocamlInput) {
      allDepsBuilder.addAll(library.getNativeCompileDeps(ocamlPlatform));
      allDepsBuilder.addAll(library.getBytecodeCompileDeps(ocamlPlatform));
      allDepsBuilder.addAll(library.getBytecodeLinkDeps(ocamlPlatform));
    }
    allDepsBuilder.addAll(
        BuildableSupport.getDepsCollection(
            ocamlPlatform
                .getCCompiler()
                .resolve(graphBuilder, buildTarget.getTargetConfiguration()),
            graphBuilder));
    allDepsBuilder.addAll(
        BuildableSupport.getDepsCollection(
            ocamlPlatform
                .getCxxCompiler()
                .resolve(graphBuilder, buildTarget.getTargetConfiguration()),
            graphBuilder));
    allDepsBuilder.addAll(
        argFlags.stream().flatMap(arg -> BuildableSupport.getDeps(arg, graphBuilder)).iterator());

    // The bulk rule will do preprocessing on sources, and so needs deps from the preprocessor
    // input object.
    allDepsBuilder.addAll(cxxPreprocessorInputFromDeps.getDeps(graphBuilder));

    ImmutableSortedSet<BuildRule> allDeps = allDepsBuilder.build();

    ImmutableList.Builder<Arg> flagsBuilder = ImmutableList.builder();
    flagsBuilder.addAll(argFlags);

    ImmutableSortedSet.Builder<BuildRule> nativeCompileDepsBuilder =
        ImmutableSortedSet.naturalOrder();
    ImmutableSortedSet.Builder<BuildRule> bytecodeCompileDepsBuilder =
        ImmutableSortedSet.naturalOrder();
    ImmutableSortedSet.Builder<BuildRule> bytecodeLinkDepsBuilder =
        ImmutableSortedSet.naturalOrder();
    ImmutableSortedSet.Builder<String> transitiveBytecodeIncludesBuilder =
        ImmutableSortedSet.naturalOrder();
    for (OcamlLibrary library : ocamlInput) {
      nativeCompileDepsBuilder.addAll(library.getNativeCompileDeps(ocamlPlatform));
      bytecodeCompileDepsBuilder.addAll(library.getBytecodeCompileDeps(ocamlPlatform));
      bytecodeLinkDepsBuilder.addAll(library.getBytecodeLinkDeps(ocamlPlatform));
      transitiveBytecodeIncludesBuilder.addAll(library.getBytecodeIncludeDirs(ocamlPlatform));
    }
    OcamlBuildContext ocamlContext =
        OcamlBuildContext.builder(ocamlPlatform, graphBuilder, buildTarget.getTargetConfiguration())
            .setProjectFilesystem(projectFilesystem)
            .setSourcePathResolver(graphBuilder.getSourcePathResolver())
            .setFlags(flagsBuilder.build())
            .setOcamlDepFlags(ocamlDepFlags)
            .setNativeIncludes(nativeIncludes)
            .setBytecodeIncludes(bytecodeIncludes)
            .setTransitiveBytecodeIncludes(transitiveBytecodeIncludesBuilder.build())
            .setNativeLinkableInput(nativeLinkableInput)
            .setBytecodeLinkableInput(bytecodeLinkableInput)
            .setCLinkableInput(cLinkableInput)
            .setBuildTarget(buildTarget)
            .setLibrary(isLibrary)
            .setCxxPreprocessorInput(cxxPreprocessorInputFromDeps)
            .setInput(srcs)
            .setNativeCompileDeps(nativeCompileDepsBuilder.build())
            .setBytecodeCompileDeps(bytecodeCompileDepsBuilder.build())
            .setBytecodeLinkDeps(bytecodeLinkDepsBuilder.build())
            .setCPreprocessor(
                ocamlPlatform
                    .getCPreprocessor()
                    .resolve(graphBuilder, buildTarget.getTargetConfiguration()))
            .build();

    return graphBuilder.addToIndex(
        new OcamlBuild(
            compileBuildTarget,
            projectFilesystem,
            params.withDeclaredDeps(allDeps).withoutExtraDeps(),
            ocamlContext,
            ocamlPlatform
                .getCCompiler()
                .resolve(graphBuilder, buildTarget.getTargetConfiguration()),
            ocamlPlatform
                .getCxxPlatform()
                .getLd()
                .resolve(graphBuilder, buildTarget.getTargetConfiguration()),
            bytecodeOnly));
  }

  static OcamlGeneratedBuildRules createFineGrainedBuildRules(
      BuildTarget buildTarget,
      OcamlPlatform ocamlPlatform,
      BuildTarget compileBuildTarget,
      ProjectFilesystem projectFilesystem,
      BuildRuleParams params,
      ActionGraphBuilder graphBuilder,
      Iterable<BuildRule> deps,
      ImmutableList<SourcePath> srcs,
      boolean isLibrary,
      boolean bytecodeOnly,
      ImmutableList<Arg> argFlags,
      ImmutableList<String> ocamlDepFlags,
      boolean buildNativePlugin) {

    CxxPreprocessorInput cxxPreprocessorInputFromDeps =
        CxxPreprocessorInput.concat(
            CxxPreprocessables.getTransitiveCxxPreprocessorInput(
                ocamlPlatform.getCxxPlatform(),
                graphBuilder,
                FluentIterable.from(deps).filter(CxxPreprocessorDep.class)));

    ImmutableList<String> nativeIncludes =
        FluentIterable.from(deps)
            .transformAndConcat(getLibInclude(ocamlPlatform, false)::apply)
            .toList();

    ImmutableList<String> bytecodeIncludes =
        FluentIterable.from(deps)
            .transformAndConcat(getLibInclude(ocamlPlatform, true)::apply)
            .toList();

    NativeLinkableInput nativeLinkableInput =
        getNativeLinkableInput(graphBuilder, ocamlPlatform, deps);
    NativeLinkableInput bytecodeLinkableInput =
        getBytecodeLinkableInput(graphBuilder, ocamlPlatform, deps);
    NativeLinkableInput cLinkableInput =
        getCLinkableInput(ocamlPlatform, graphBuilder, buildTarget.getTargetConfiguration(), deps);

    ImmutableList<OcamlLibrary> ocamlInput =
        getTransitiveOcamlLibraryDeps(graphBuilder, ocamlPlatform, deps);

    BuildRuleParams compileParams =
        params
            .withDeclaredDeps(
                ImmutableSortedSet.<BuildRule>naturalOrder()
                    .addAll(graphBuilder.filterBuildRuleInputs(srcs))
                    .addAll(
                        Stream.of(nativeLinkableInput, bytecodeLinkableInput, cLinkableInput)
                            .flatMap(input -> input.getArgs().stream())
                            .flatMap(arg -> BuildableSupport.getDeps(arg, graphBuilder))
                            .iterator())
                    .addAll(
                        argFlags.stream()
                            .flatMap(arg -> BuildableSupport.getDeps(arg, graphBuilder))
                            .iterator())
                    .addAll(
                        BuildableSupport.getDepsCollection(
                            ocamlPlatform
                                .getCCompiler()
                                .resolve(graphBuilder, buildTarget.getTargetConfiguration()),
                            graphBuilder))
                    .addAll(
                        BuildableSupport.getDepsCollection(
                            ocamlPlatform
                                .getCxxCompiler()
                                .resolve(graphBuilder, buildTarget.getTargetConfiguration()),
                            graphBuilder))
                    .build())
            .withoutExtraDeps();

    ImmutableList.Builder<Arg> flagsBuilder = ImmutableList.builder();
    flagsBuilder.addAll(argFlags);

    ImmutableSortedSet.Builder<BuildRule> nativeCompileDepsBuilder =
        ImmutableSortedSet.naturalOrder();
    ImmutableSortedSet.Builder<BuildRule> bytecodeCompileDepsBuilder =
        ImmutableSortedSet.naturalOrder();
    ImmutableSortedSet.Builder<BuildRule> bytecodeLinkDepsBuilder =
        ImmutableSortedSet.naturalOrder();
    ImmutableSortedSet.Builder<String> transitiveBytecodeIncludesBuilder =
        ImmutableSortedSet.naturalOrder();
    for (OcamlLibrary library : ocamlInput) {
      nativeCompileDepsBuilder.addAll(library.getNativeCompileDeps(ocamlPlatform));
      bytecodeCompileDepsBuilder.addAll(library.getBytecodeCompileDeps(ocamlPlatform));
      bytecodeLinkDepsBuilder.addAll(library.getBytecodeLinkDeps(ocamlPlatform));
      transitiveBytecodeIncludesBuilder.addAll(library.getBytecodeIncludeDirs(ocamlPlatform));
    }
    OcamlBuildContext ocamlContext =
        OcamlBuildContext.builder(ocamlPlatform, graphBuilder, buildTarget.getTargetConfiguration())
            .setProjectFilesystem(projectFilesystem)
            .setSourcePathResolver(graphBuilder.getSourcePathResolver())
            .setFlags(flagsBuilder.build())
            .setOcamlDepFlags(ocamlDepFlags)
            .setNativeIncludes(nativeIncludes)
            .setBytecodeIncludes(bytecodeIncludes)
            .setTransitiveBytecodeIncludes(transitiveBytecodeIncludesBuilder.build())
            .setNativeLinkableInput(nativeLinkableInput)
            .setBytecodeLinkableInput(bytecodeLinkableInput)
            .setCLinkableInput(cLinkableInput)
            .setBuildTarget(buildTarget)
            .setLibrary(isLibrary)
            .setCxxPreprocessorInput(cxxPreprocessorInputFromDeps)
            .setInput(srcs)
            .setNativeCompileDeps(nativeCompileDepsBuilder.build())
            .setBytecodeCompileDeps(bytecodeCompileDepsBuilder.build())
            .setBytecodeLinkDeps(bytecodeLinkDepsBuilder.build())
            .setCPreprocessor(
                ocamlPlatform
                    .getCPreprocessor()
                    .resolve(graphBuilder, buildTarget.getTargetConfiguration()))
            .build();

    AbsPath baseDir = projectFilesystem.getRootPath();
    ImmutableMap<Path, ImmutableList<Path>> mlInput = getMLInputWithDeps(baseDir, ocamlContext);

    ImmutableList<SourcePath> cInput = getCInput(graphBuilder.getSourcePathResolver(), srcs);

    OcamlBuildRulesGenerator generator =
        new OcamlBuildRulesGenerator(
            compileBuildTarget,
            projectFilesystem,
            compileParams,
            graphBuilder,
            ocamlContext,
            mlInput,
            cInput,
            ocamlPlatform
                .getCCompiler()
                .resolve(graphBuilder, buildTarget.getTargetConfiguration()),
            ocamlPlatform
                .getCxxPlatform()
                .getLd()
                .resolve(graphBuilder, buildTarget.getTargetConfiguration()),
            bytecodeOnly,
            buildNativePlugin);

    return generator.generate();
  }

  private static ImmutableList<SourcePath> getCInput(
      SourcePathResolverAdapter resolver, ImmutableList<SourcePath> input) {
    return input.stream()
        .filter(OcamlUtil.sourcePathExt(resolver, OcamlCompilables.OCAML_C))
        .collect(ImmutableList.toImmutableList());
  }

  private static ImmutableMap<Path, ImmutableList<Path>> getMLInputWithDeps(
      AbsPath baseDir, OcamlBuildContext ocamlContext) {

    ImmutableList<String> ocamlDepFlags =
        ImmutableList.<String>builder()
            .addAll(ocamlContext.getIncludeFlags(/* isBytecode */ false, /* excludeDeps */ true))
            .addAll(ocamlContext.getOcamlDepFlags())
            .build();

    OcamlDepToolStep depToolStep =
        new OcamlDepToolStep(
            baseDir,
            ocamlContext.getSourcePathResolver(),
            ocamlContext.getOcamlDepTool().get(),
            ocamlContext.getMLInput(),
            ocamlDepFlags);
    ImmutableList<String> cmd = depToolStep.getShellCommandInternal(null);
    Optional<String> depsString;
    try {
      depsString = executeProcessAndGetStdout(baseDir, cmd);
    } catch (IOException e) {
      throw new HumanReadableException(
          e, "Unable to execute ocamldep due to io error: %s", Joiner.on(" ").join(cmd));
    } catch (InterruptedException e) {
      throw new HumanReadableException(
          e,
          "Unable to calculate dependencies. ocamldep is interrupted: %s",
          Joiner.on(" ").join(cmd));
    }
    if (depsString.isPresent()) {
      OcamlDependencyGraphGenerator graphGenerator = new OcamlDependencyGraphGenerator();
      return filterCurrentRuleInput(
          ocamlContext.getSourcePathResolver().getAllAbsolutePaths(ocamlContext.getMLInput()),
          graphGenerator.generateDependencyMap(depsString.get()));
    } else {
      throw new HumanReadableException("ocamldep execution failed");
    }
  }

  private static ImmutableMap<Path, ImmutableList<Path>> filterCurrentRuleInput(
      Set<Path> mlInput, ImmutableMap<Path, ImmutableList<Path>> deps) {
    ImmutableMap.Builder<Path, ImmutableList<Path>> builder = ImmutableMap.builder();
    for (ImmutableMap.Entry<Path, ImmutableList<Path>> entry : deps.entrySet()) {
      if (mlInput.contains(entry.getKey())) {
        builder.put(
            entry.getKey(),
            FluentIterable.from(entry.getValue()).filter(mlInput::contains).toList());
      }
    }
    return builder.build();
  }

  private static Optional<String> executeProcessAndGetStdout(
      AbsPath baseDir, ImmutableList<String> cmd) throws IOException, InterruptedException {
    ImmutableSet.Builder<ProcessExecutor.Option> options = ImmutableSet.builder();
    options.add(ProcessExecutor.Option.EXPECTING_STD_OUT);
    ProcessExecutor exe = new DefaultProcessExecutor(Console.createNullConsole());
    ProcessExecutorParams params =
        ProcessExecutorParams.builder().setCommand(cmd).setDirectory(baseDir.getPath()).build();
    ProcessExecutor.Result result =
        exe.launchAndExecute(
            params,
            options.build(),
            /* stdin */ Optional.empty(),
            /* timeOutMs */ Optional.empty(),
            /* timeOutHandler */ Optional.empty());
    if (result.getExitCode() != 0) {
      throw new HumanReadableException(result.getStderr().get());
    }
    return result.getStdout();
  }

  static ImmutableList<Arg> getFlags(
      BuildTarget target,
      CellPathResolver cellRoots,
      ActionGraphBuilder graphBuilder,
      OcamlPlatform platform,
      ImmutableList<StringWithMacros> compilerFlags,
      Optional<String> warningsFlags) {
    ImmutableList.Builder<Arg> flags = ImmutableList.builder();
    flags.addAll(
        OcamlDescriptionEnhancer.toStringWithMacrosArgs(
            target, cellRoots, graphBuilder, compilerFlags));
    if (platform.getWarningsFlags().isPresent() || warningsFlags.isPresent()) {
      flags.addAll(
          StringArg.from("-w", platform.getWarningsFlags().orElse("") + warningsFlags.orElse("")));
    }
    return flags.build();
  }
}


text:
package li.l1t.common.sql.sane.sanebox;

import java.sql.SQLException;

/**
 * Something that runs unsafe code that may throw {@link SQLException}.
 *
 * @author Literallie
 * @since 2016-10-18
 */
@FunctionalInterface
public interface SaneboxRunnable {
    void run() throws SQLException;
}


text:
using Autofac;

namespace IdentityManager.Configuration.Hosting
{
    internal class AutofacDependencyResolver : IDependencyResolver
    {
        readonly IComponentContext ctx;
        public AutofacDependencyResolver(IComponentContext ctx)
        {
            this.ctx = ctx;
        }

        public T Resolve<T>(string name)
        {
            if (name != null)
            {
                return ctx.ResolveNamed<T>(name);
            }

            return ctx.Resolve<T>();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <padding
            android:top="10dp"
            android:bottom="10dp"
            android:left="10dp"
            android:right="10dp"
            />
    <stroke
            android:color="#ffd2d2d2"/>
    <solid
            android:color="#ffd2d2d2"/>
    <gradient
            android:startColor="#ff8c8c8c"
            android:endColor="#ffa8a8a8"
            android:angle="45"/>
    <corners
            android:radius="3dp"/>
</shape>


text:
struct TreeNode {
  int val;
  TreeNode* left;
  TreeNode* right;
  TreeNode(int x) : val(x), left(0), right(0) {}
};

#include <vector>
#include <stack>

class Solution {
public:
  std::vector<int> inorderTraversal(TreeNode* root) {
    std::vector<int> v = {};
    if (root == 0) return v;

    auto current = root;
    std::stack<TreeNode*> pending;

    while (current != 0 || !pending.empty()) {
      if (current) {
        pending.push(current);
        current = current->left;
      } else {
        TreeNode* node = pending.top();
        v.push_back(node->val);
        pending.pop();
        current = node->right;
      }
    }
    return v;
  }
};


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.test.regression;

import java.util.HashMap;
import java.util.Map;

import org.flowable.common.engine.impl.history.HistoryLevel;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.impl.test.HistoryTestHelper;
import org.flowable.engine.impl.test.PluggableFlowableTestCase;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.test.Deployment;
import org.flowable.job.api.Job;
import org.junit.jupiter.api.Test;
//SLF4J
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * From http://forums.activiti.org/content/inability-completely-delete-process- instance-when
 */
public class DeleteProcessInstanceTest extends PluggableFlowableTestCase {

    private static final Logger LOGGER = LoggerFactory.getLogger(DeleteProcessInstanceTest.class);

    @Test
    @Deployment
    public void testNoEndTimeSet() {

        // Note that the instance with a org.flowable.task.service.Task Type of "user" is being started.
        LOGGER.info("Starting an instance of \"Demo Partial Deletion\" with a org.flowable.task.service.Task Type of \"user\".");

        // Set the inputs for the first process instance, which we will be able
        // to completely delete.
        Map<String, Object> inputParamsUser = new HashMap<>();
        inputParamsUser.put("taskType", "user");

        // Start the process instance & ensure it's started.
        ProcessInstance instanceUser = runtimeService.startProcessInstanceByKey("DemoPartialDeletion", inputParamsUser);
        assertNotNull(instanceUser);
        LOGGER.info("Process instance (of process model {}) started with id: {}.", instanceUser.getProcessDefinitionId(), instanceUser.getId());

        // Assert that the process instance is active.
        Execution executionUser = runtimeService.createExecutionQuery().processInstanceId(instanceUser.getProcessInstanceId()).onlyChildExecutions().singleResult();
        assertFalse(executionUser.isEnded());

        // Assert that a user task is available for claiming.
        org.flowable.task.api.Task taskUser = taskService.createTaskQuery().processInstanceId(instanceUser.getProcessInstanceId()).singleResult();
        assertNotNull(taskUser);

        // Delete the process instance.
        runtimeService.deleteProcessInstance(instanceUser.getId(), null);

        if (HistoryTestHelper.isHistoryLevelAtLeast(HistoryLevel.ACTIVITY, processEngineConfiguration)) {
            // Retrieve the HistoricProcessInstance and assert that there is an
            // end time.
            HistoricProcessInstance hInstanceUser = historyService.createHistoricProcessInstanceQuery().processInstanceId(instanceUser.getId()).singleResult();
            assertNotNull(hInstanceUser.getEndTime());
            LOGGER.info("End time for the deleted instance of \"Demo Partial Deletion\" that was started with a org.flowable.task.service.Task Type of \"user\": {}.", hInstanceUser.getEndTime());
            LOGGER.info("Successfully deleted the instance of \"Demo Partial Deletion\" that was started with a org.flowable.task.service.Task Type of \"user\".");
        }

        // Note that the instance with a org.flowable.task.service.Task Type of "java" is being started.
        LOGGER.info("Starting an instance of \"Demo Partial Deletion\" with a org.flowable.task.service.Task Type of \"java\".");

        // Set the inputs for the second process instance, which we will NOT be
        // able to completely delete.
        Map<String, Object> inputParamsJava = new HashMap<>();
        inputParamsJava.put("taskType", "java");

        // Start the process instance & ensure it's started.
        ProcessInstance instanceJava = runtimeService.startProcessInstanceByKey("DemoPartialDeletion", inputParamsJava);
        assertNotNull(instanceJava);
        LOGGER.info("Process instance (of process model {}) started with id: {}.", instanceJava.getProcessDefinitionId(), instanceJava.getId());

        // Assert that the process instance is active.
        Execution executionJava = runtimeService.createExecutionQuery().processInstanceId(instanceJava.getProcessInstanceId()).onlyChildExecutions().singleResult();
        assertFalse(executionJava.isEnded());

        // Try to execute job 3 times
        Job jobJava = managementService.createJobQuery().processInstanceId(instanceJava.getId()).singleResult();
        assertNotNull(jobJava);

        try {
            managementService.executeJob(jobJava.getId());
            fail("Expected exception");
        } catch (Exception e) {
            // expected
        }

        try {
            managementService.moveTimerToExecutableJob(jobJava.getId());
            managementService.executeJob(jobJava.getId());
            fail("Expected exception");
        } catch (Exception e) {
            // expected
        }

        try {
            managementService.moveTimerToExecutableJob(jobJava.getId());
            managementService.executeJob(jobJava.getId());
            fail("Expected exception");
        } catch (Exception e) {
            // expected
        }

        // Assert that there is a failed job.
        assertEquals(0, managementService.createTimerJobQuery().processInstanceId(instanceJava.getId()).count());
        jobJava = managementService.createDeadLetterJobQuery().processInstanceId(instanceJava.getId()).singleResult();
        assertNotNull(jobJava);

        // Delete the process instance.
        runtimeService.deleteProcessInstance(instanceJava.getId(), null);

        if (HistoryTestHelper.isHistoryLevelAtLeast(HistoryLevel.ACTIVITY, processEngineConfiguration)) {
            // Retrieve the HistoricProcessInstance and assert that there is no
            // end time.
            HistoricProcessInstance hInstanceJava = historyService.createHistoricProcessInstanceQuery().processInstanceId(instanceJava.getId()).singleResult();
            assertNotNull(hInstanceJava.getEndTime());
        }
    }

}


text:
package com.googlecode.charts4j.parameters;

import java.util.List;

import com.googlecode.charts4j.collect.Lists;

/**
 * Class for building axis types parameter string for the Google Chart API.
 *
 * @author Julien Chastang (julien.c.chastang at gmail dot com)
 */
final class AxisTypesParameter extends AbstractParameter {

    /** The Google Chart API axis types parameter. */
    private static final String   URL_PARAMETER_KEY = "chxt";

    /** The axis types list. */
    private final List<AxisTypes> axisTypesList     = Lists.newLinkedList();

    /**
     * Add an axis type.
     *
     * @param axisTypes
     *            the axis types
     */
    void addAxisTypes(final AxisTypes axisTypes) {
        axisTypesList.add(axisTypes);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getKey() {
        return URL_PARAMETER_KEY;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getValue() {
        final StringBuilder sb = new StringBuilder();

        int cnt = 0;
        for (AxisTypes axisType : axisTypesList) {
            sb.append(cnt++ > 0 ? "," : "").append(axisType);
        }

        return !axisTypesList.isEmpty() ? sb.toString() : "";
    }
}


text:
package com.gs.collections.impl.jmh.domain;

import java.util.ArrayList;
import java.util.Collections;
import java.util.PrimitiveIterator;
import java.util.Random;

import com.gs.collections.api.set.Pool;
import com.gs.collections.impl.list.mutable.FastList;
import com.gs.collections.impl.set.mutable.UnifiedSet;
import org.apache.commons.lang.RandomStringUtils;

public class Positions
{
    private static final int DEFAULT_SIZE = 3_000_000;
    private static final Random RANDOM = new Random(System.currentTimeMillis());
    private static final PrimitiveIterator.OfDouble DOUBLES = RANDOM.ints(1, 100).asDoubleStream().iterator();
    private static final PrimitiveIterator.OfInt INTS = RANDOM.ints(1, 100).iterator();
    private final Pool<Account> accountPool = UnifiedSet.newSet();
    private final Pool<Product> productPool = UnifiedSet.newSet();
    private final Pool<String> stringPool = UnifiedSet.newSet();

    private final FastList<Position> gscPositions;
    private final ArrayList<Position> jdkPositions;

    public Positions()
    {
        this(DEFAULT_SIZE);
    }

    public Positions(int size)
    {
        this.gscPositions = FastList.newWithNValues(size, this::createPosition);
        this.jdkPositions = new ArrayList<>(FastList.newWithNValues(size, this::createPosition));
    }

    public Positions shuffle()
    {
        Collections.shuffle(this.gscPositions);
        Collections.shuffle(this.jdkPositions);
        return this;
    }

    public Position createPosition()
    {
        String accountName = this.stringPool.put(RandomStringUtils.randomNumeric(5));
        String category = this.stringPool.put(RandomStringUtils.randomAlphabetic(1).toUpperCase());
        String productName = this.stringPool.put(RandomStringUtils.randomNumeric(3));
        Account account = this.accountPool.put(new Account(accountName));
        Product product = this.productPool.put(new Product(productName, category, DOUBLES.nextDouble()));
        return new Position(account, product, INTS.nextInt());
    }

    public FastList<Position> getGscPositions()
    {
        return this.gscPositions;
    }

    public ArrayList<Position> getJdkPositions()
    {
        return this.jdkPositions;
    }
}


text:
package com.thinkgem.jeesite.modules.comment.entity;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.thinkgem.jeesite.common.persistence.BaseEntity;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.modules.sys.entity.User;

/**
 * 评论附件Entity
 * @author 俞超
 * @version 2015-02-05
 */
@Entity
@Table(name = "comment_affix")
public class Affix extends BaseEntity<Affix> implements Serializable{

	private static final long serialVersionUID = 1L;
	private String id; 		// 编号

	private Comment comment;//评论

	private String affixName;//附件名称

	private String affixUrl;//附件地址

	private String type;//附件类型

	private String icon;//显示图标

	private Date generateTime;//上传时间

	private User generateUser;//上传用户

	private String remarks;//备注

	@SuppressWarnings("unused")
	private Boolean isImageType;//是不是图片

	public String getAffixName() {
		return affixName;
	}

	public String getAffixUrl() {
		return affixUrl;
	}

	@ManyToOne
	@JoinColumn(name="COMMENT_ID")
	@NotFound(action = NotFoundAction.IGNORE)
	@JsonIgnore
	public Comment getComment() {
		return comment;
	}

	public Date getGenerateTime() {
		return generateTime;
	}

	@ManyToOne
	@JoinColumn(name="SYS_USER__ID")
	@NotFound(action = NotFoundAction.IGNORE)
	@JsonIgnore
	public User getGenerateUser() {
		return generateUser;
	}

	public String getIcon() {
		return icon;
	}

	@Id
	public String getId() {
		return id;
	}

	public String getRemarks() {
		return remarks;
	}

	public String getType() {
		return type;
	}

	@PrePersist
	public void prePersist(){
		this.id = IdGen.uuid();
	}

	public void setAffixName(String affixName) {
		this.affixName = affixName;
	}

	public void setAffixUrl(String affixUrl) {
		this.affixUrl = affixUrl;
	}

	public void setComment(Comment comment) {
		this.comment = comment;
	}

	public void setGenerateTime(Date generateTime) {
		this.generateTime = generateTime;
	}

	public void setGenerateUser(User generateUser) {
		this.generateUser = generateUser;
	}

	public void setIcon(String icon) {
		this.icon = icon;
	}

	public void setId(String id) {
		this.id = id;
	}

	public void setRemarks(String remarks) {
		this.remarks = remarks;
	}

	public void setType(String type) {
		this.type = type;
	}

	@Transient
	public Boolean getIsImageType() {
		return ("gif".equalsIgnoreCase(this.type)||"png".equalsIgnoreCase(this.type)||"jpg".equalsIgnoreCase(this.type)||"jpeg".equalsIgnoreCase(this.type)||"bmp".equalsIgnoreCase(this.type));
	}

	public void setIsImageType(Boolean isImageType) {
		this.isImageType=isImageType;
	}

}


text:
package it.redhat.demo.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;

/**
 * @author Fabio Massimo Ercoli
 *         fabio.ercoli@redhat.com
 *         on 09/06/16
 */

@Path("")
public class RestService {

    @GET
    public String letsGo() {
        return "let's go!";
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/search_music"
        android:icon="@mipmap/ic_search_black"
        android:title="Search"
        app:showAsAction="ifRoom"/>
</menu>


text:
"""Run any MEAD embeddings within the SentEval framework

The SentEval framework (https://github.com/facebookresearch/SentEval) facilitates
testing the quality of sentence embeddings.  To prepare your data, you can clone
that repo and do a `pip install -e .`.  This program allows you to control which
sets of tasks are run.  By default, it will run all STS and classification probing
examples.

Please note that its common when evaluating against STS to use a different approach
from the one in SentEval (following SentenceBERT).  A drop-in replacement is available
from the SimCSE repository (https://github.com/princeton-nlp/SimCSE).

To use their modified benchmark, clone that repo instead
and within their SentEval directory, do a `pip install -e .`, and pay attention instead
to the ALL Spearman metrics:

"""
import argparse
import baseline
import sys
from mead.api_examples.preproc_utils import *
from baseline.embeddings import load_embeddings_overlay
from eight_mile.utils import read_config_stream
from baseline.pytorch.embeddings import *
from baseline.embeddings import *
from baseline.vectorizers import *
from mead.utils import convert_path, parse_extra_args, configure_logger, parse_and_merge_overrides, read_config_file_or_json, index_by_label
import senteval
logging.basicConfig(format='%(asctime)s : %(message)s', level=logging.DEBUG)
DEFAULT_SETTINGS_LOC = 'config/mead-settings.json'
DEFAULT_DATASETS_LOC = 'config/datasets.json'
DEFAULT_EMBEDDINGS_LOC = 'config/embeddings.json'
DEFAULT_VECTORIZERS_LOC = 'config/vecs.json'
SUBWORD_EXTRA = 30

def main():
    parser = argparse.ArgumentParser(description='Run senteval harness')
    parser.add_argument('--nctx', default=512, type=int)
    parser.add_argument("--module", default=None, help="Module containing custom tokenizers")
    parser.add_argument('--tasks', nargs="+", default=['sts', 'class', 'probe'])
    parser.add_argument('--batchsz', default=20, type=int)
    parser.add_argument('--tok', help='Optional tokenizer, e.g. "gpt2" or "basic". These can be defined in extra module')
    parser.add_argument('--pool', help='Should a reduction be applied on the embeddings?  Only use if your embeddings arent already pooled', type=str)
    parser.add_argument('--vec_id', help='Reference to a specific embedding type')
    parser.add_argument('--embed_id', help='What type of embeddings to use')
    parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu", help="Device (cuda or cpu)")
    parser.add_argument('--max_len1d', type=int, default=100)
    parser.add_argument('--embeddings', help='index of embeddings: local file, remote URL or mead-ml/hub ref', type=convert_path)
    parser.add_argument('--vecs', help='index of vectorizers: local file, remote URL or hub mead-ml/ref', type=convert_path)
    parser.add_argument('--fast', help="Run fast, but not necessarily as accurate", action='store_true')
    parser.add_argument('--data', help="Path to senteval data",
                        default=os.path.expanduser("~/dev/work/SentEval/data"))
    args = parser.parse_args()

    if args.module:
        logger.warning("Loading custom user module %s for masking rules and tokenizers", args.module)
        baseline.import_user_module(args.module)

    tokenizer = create_tokenizer(args.tok) if args.tok else None

    args.embeddings = convert_path(DEFAULT_EMBEDDINGS_LOC) if args.embeddings is None else args.embeddings
    args.embeddings = read_config_stream(args.embeddings)

    args.vecs = convert_path(DEFAULT_VECTORIZERS_LOC) if args.vecs is None else args.vecs

    vecs_index = read_config_stream(args.vecs)
    vecs_set = index_by_label(vecs_index)
    vec_params = vecs_set[args.vec_id]
    vec_params['mxlen'] = args.nctx

    if 'transform' in vec_params:
        vec_params['transform_fn'] = vec_params['transform']

    if 'transform_fn' in vec_params and isinstance(vec_params['transform_fn'], str):
        vec_params['transform_fn'] = eval(vec_params['transform_fn'])

    vectorizer = create_vectorizer(**vec_params)
    if not isinstance(vectorizer, HasPredefinedVocab):
        raise Exception("We currently require a vectorizer with a pre-defined vocab to run this script")
    embeddings_index = read_config_stream(args.embeddings)
    embeddings_set = index_by_label(embeddings_index)
    embeddings_params = embeddings_set[args.embed_id]
    embeddings = load_embeddings_overlay(embeddings_set, embeddings_params, vectorizer.vocab)

    embedder = embeddings['embeddings']
    embedder.to(args.device).eval()

    def _mean_pool(inputs, embeddings):
        mask = (inputs != 0)
        seq_lengths = mask.sum(1).unsqueeze(-1)
        return embeddings.sum(1)/seq_lengths

    def _zero_tok_pool(_, embeddings):
        pooled = embeddings[:, 0]
        return pooled

    def _max_pool(inputs, embeddings):
        mask = (inputs != 0)
        embeddings = embeddings.masked_fill(mask.unsqueeze(-1) == False, -1e8)
        return torch.max(embeddings, 1, False)[0]

    if args.pool:
        if args.pool == 'max':
            pool = _max_pool
        elif args.pool == 'zero' or args.pool == 'cls':
            pool = _zero_tok_pool
        else:
            pool = _mean_pool
    else:
        pool = lambda x, y: y

    params_senteval = {'task_path': args.data, 'usepytorch': True, 'kfold': 10}
    params_senteval['classifier'] = {'nhid': 0, 'optim': 'adam', 'batch_size': 64,
                                     'tenacity': 5, 'epoch_size': 4}
    if args.fast:
        logging.info("Setting fast params")
        params_senteval['kfold'] = 5
        params_senteval['classifier']['epoch_size'] = 2
        params_senteval['classifier']['tenacity'] = 3
        params_senteval['classifier']['batch_size'] = 128

    # SentEval prepare and batcher
    def prepare(params, samples):
        max_sample = max(len(s) for s in samples)
        vectorizer.mxlen = min(args.nctx, max_sample + SUBWORD_EXTRA)
        logging.info('num_samples %d, mxlen set to %d', max_sample, vectorizer.mxlen)

    def batcher(params, batch):
        if not tokenizer:
            batch = [sent if sent != [] else ['.'] for sent in batch]
        else:
            batch = [tokenizer(' '.join(sent)) for sent in batch]

        vs = []
        for sent in batch:
            v, l = vectorizer.run(sent, vectorizer.vocab)
            vs.append(v)
        vs = np.stack(vs)
        with torch.no_grad():
            inputs = torch.tensor(vs, device=args.device)
            encoding = embedder(inputs)
            encoding = pool(inputs, encoding)
            encoding = encoding.cpu().numpy()
        return encoding

    se = senteval.engine.SE(params_senteval, batcher, prepare)
    transfer_tasks = []
    if 'sts' in args.tasks:
        transfer_tasks += ['STS12', 'STS13', 'STS14', 'STS15', 'STS16', 'SICKRelatedness', 'STSBenchmark']
    if 'class' in args.tasks:
        transfer_tasks += ['MR', 'CR', 'MPQA', 'SUBJ', 'SST2', 'SST5', 'TREC', 'MRPC',
                           'SICKEntailment']
    if 'probe' in args.tasks:
        transfer_tasks += ['Length', 'WordContent', 'Depth', 'TopConstituents',
                           'BigramShift', 'Tense', 'SubjNumber', 'ObjNumber',
                           'OddManOut', 'CoordinationInversion']

    results = se.eval(transfer_tasks)
    print(results)

if __name__ == '__main__':
    main()


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Immutable;

namespace Microsoft.CodeAnalysis.Semantics
{
    /// <summary>
    /// Represents a reference to a declared local variable.
    /// </summary>
    /// <remarks>
    /// This interface is reserved for implementation by its associated APIs. We reserve the right to
    /// change it in the future.
    /// </remarks>
    public interface ILocalReferenceExpression : IOperation
    {
        /// <summary>
        /// Referenced local variable.
        /// </summary>
        ILocalSymbol Local { get; }

        /// <summary>
        /// True if this reference is also the declaration site of this variable. This is true in out variable declarations
        /// and in deconstruction operations where a new variable is being declared.
        /// </summary>
        bool IsDeclaration { get; }
    }
}


text:
"""Utilities for clang.

Attributes:
    log (logging.log): logger for this module
"""
import platform
import logging
import subprocess
import html

from os import path

log = logging.getLogger("ECC")

class MacroParser(object):
    """Parse info from macros.

    Clang doesn't provide much information for MACRO_DEFINITION cursors,
    so we have to parse this info ourselves.
    """

    def __init__(self, name, location):
        """Parse the macro with the given name from its location.

        Args:
            name (str): Macro's name.
            location (cindex.SourceLocation): Macro definition's location.
                Can be None for unittests that parse with text content
                directly instead of loading from file.

        Future improvement: if there are line continuation characters
            in a macro with parenthesis, continue parsing into the next line
            to find it and create a proper args string.
        """
        self._args_string = ''
        self._name = name
        if location and location.file and location.file.name:
            with open(location.file.name, 'r') as f:
                macro_file_lines = f.readlines()
                self._parse_macro_file_lines(macro_file_lines, location.line)

    def _parse_macro_file_lines(self, macro_file_lines, macro_line_number):
        """Parse a macro from lines of text containing the macro.

        Args:
            macro_file_lines (list[str]): lines of text containing the macro
            macro_line_number (int): line number (1-based) of the macro
               in macro_file_lines.
        """
        macro_line = macro_file_lines[macro_line_number - 1].strip()
        # strip leading '#<whitespace>define<whitespace><macro name>'
        macro_line = macro_line.lstrip('#').lstrip().lstrip('define')
        macro_line = macro_line.lstrip().lstrip(self._name)
        # macro that looks like a function, possibly with args
        if macro_line.startswith('('):
            end_args_index = macro_line.find(')')
            # There should always be a closing parenthesis, but check
            # just in case a) the code is malformed or b) the macro
            # definition is continued on the next line so we can't
            # find it on this line.
            if end_args_index != -1:
                # If extra spaces, e.g. "#define MACRO( x ,  y  , z )",
                # then flatten down to just "(x, y, z)"
                args_str = macro_line[1:end_args_index]
                args_str = ''.join(args_str.split())
                args_str = args_str.replace(',', ', ')
                self._args_string = '(' + args_str + ')'

    @property
    def args_string(self):
        """Get arguments string.

        Examples:
            '#define MACRO()' would return '()'
            '#define MACRO(x, y)' would return '(x, y)'
            '#define MACRO' would return ''
        """
        return self._args_string

class ClangUtils:
    """Utils to help handling libclang, e.g. searching for it.

    Attributes:
        libclang_name (str): name of the libclang library file
        linux_suffixes (list): suffixes for linux
        osx_suffixes (list): suffixes for osx
        windows_suffixes (list): suffixes for windows
    """
    libclang_name = None

    windows_suffixes = ['.dll', '.lib']
    linux_suffixes = ['.so', '.so.1']
    osx_suffixes = ['.dylib']

    suffixes = {
        'Windows': windows_suffixes,
        'Linux': linux_suffixes,
        'Darwin': osx_suffixes
    }

    # MSYS2 has `clang.dll` instead of `libclang.dll`
    possible_filenames = {
        'Windows': ['libclang', 'clang'],
        'Linux': ['libclang-$version', 'libclang'],
        'Darwin': ['libclang']
    }

    @staticmethod
    def dir_from_output(output):
        """Get library directory based on the output of clang.

        Args:
            output (str): raw output from clang

        Returns:
            str: path to folder with libclang
        """
        log.debug("real output: %s", output)
        if platform.system() == "Darwin":
            # [HACK] uh... I'm not sure why it happens like this...
            folder_to_search = path.join(output, '..', '..')
            log.debug("folder to search: %s", folder_to_search)
            return folder_to_search
        elif platform.system() == "Windows":
            log.debug("architecture: %s", platform.architecture())
            return path.normpath(output)
        elif platform.system() == "Linux":
            return path.normpath(path.dirname(output))
        return None

    @staticmethod
    def try_load_from_user_hint(libclang_path):
        """Load library hinted by the user.

        Args:
            libclang_path (str): full path to the libclang library file.

        Returns:
            str: folder of the libclang library or None if not found.
        """
        if path.exists(libclang_path):
            return path.dirname(libclang_path)

    @staticmethod
    def find_libclang_dir(clang_binary, libclang_path, version_str):
        """Find directory with libclang.

        Args:
            clang_binary (str): clang binary to call
            libclang_path (str): libclang path provided by user.
                Does not have to be valid.
            version_str(str): version of libclang to be used in format 3.8.0
        Returns:
            str: folder with libclang
        """
        stdin = None
        stderr = None
        log.debug("platform: %s", platform.architecture())
        log.debug("python version: %s", platform.python_version())
        current_system = platform.system()
        log.debug("we are on '%s'", platform.system())
        log.debug("user provided libclang_path: %s", libclang_path)
        # Get version string for help finding the proper libclang library on
        # Linux
        if libclang_path:
            # User thinks he knows better. Let him try his luck.
            libclang_dir = ClangUtils.try_load_from_user_hint(libclang_path)
            if libclang_dir:
                # It was found! No need to search any further!
                ClangUtils.libclang_name = path.basename(libclang_path)
                log.info("using user-provided libclang: '%s'", libclang_path)
                return libclang_dir
        # If the user hint did not work, we look for it normally
        if current_system == "Linux":
            # we only care about first two digits
            version_str = version_str[0:3]
        for suffix in ClangUtils.suffixes[current_system]:
            # pick a name for a file
            for name in ClangUtils.possible_filenames[current_system]:
                file = "{name}{suffix}".format(name=name, suffix=suffix)
                log.debug("searching for: '%s'", file)
                startupinfo = None
                # let's find the library
                if platform.system() == "Darwin":
                    # [HACK]: wtf??? why does it not find libclang.dylib?
                    get_library_path_cmd = [clang_binary, "-print-file-name="]
                elif platform.system() == "Windows":
                    get_library_path_cmd = [clang_binary, "-print-prog-name="]
                    # Don't let console window pop-up briefly.
                    startupinfo = subprocess.STARTUPINFO()
                    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
                    startupinfo.wShowWindow = subprocess.SW_HIDE
                    stdin = subprocess.PIPE
                    stderr = subprocess.PIPE
                elif platform.system() == "Linux":
                    file = file.replace("$version", version_str)
                    get_library_path_cmd = [
                        clang_binary, "-print-file-name={}".format(file)]
                output = subprocess.check_output(
                    get_library_path_cmd,
                    stdin=stdin,
                    stderr=stderr,
                    startupinfo=startupinfo).decode('utf8').strip()
                log.debug("libclang search output = '%s'", output)
                if output:
                    libclang_dir = ClangUtils.dir_from_output(output)
                    if path.isdir(libclang_dir):
                        full_libclang_path = path.join(libclang_dir, file)
                        if path.exists(full_libclang_path):
                            log.info("found libclang library file: '%s'",
                                     full_libclang_path)
                            ClangUtils.libclang_name = file
                            return libclang_dir
                log.warning(" clang could not find '%s'", file)
        # if we haven't found anything there is nothing to return
        log.error("no libclang found at all")
        return None

    @staticmethod
    def location_from_type(clangType):
        """Return location from type.

        Return proper location from type.
        Remove all inderactions like pointers etc.

        Args:
            clangType (cindex.Type): clang type.

        """
        cursor = clangType.get_declaration()
        if cursor and cursor.location and cursor.location.file:
            return cursor.location

        cursor = clangType.get_pointee().get_declaration()
        if cursor and cursor.location and cursor.location.file:
            return cursor.location

        return None

    @staticmethod
    def link_from_location(location, text):
        """Provide link to given cursor.

        Transforms SourceLocation object into html string.

        Args:
            location (Cursor.location): Current location.
            text (str): Text to be added as info.
        """
        result = ""
        if location and location.file and location.file.name:
            result += "" + text + ""
        else:
            result += text
        return result

    @staticmethod
    def build_info_details(cursor, cindex):
        """Provide information about given cursor.

        Builds detailed information about cursor.

        Args:
            cursor (Cursor): Current cursor.
            cindex (module): clang cindex.py module for the correct version

        """
        result = ""

        result += 'Declaration:
'

        # Show the return type of the function/method if applicable,
        # macros just show that they are a macro.
        macro_parser = None
        is_macro = cursor.kind == cindex.CursorKind.MACRO_DEFINITION
        if is_macro:
            macro_parser = MacroParser(cursor.spelling, cursor.location)
            result += '#define '
        else:
            if cursor.result_type.spelling:
                result_type = cursor.result_type
            elif cursor.type.spelling:
                result_type = cursor.type
            else:
                result_type = None
                log.warning("No spelling for type provided in info.")
                return ""

            if cursor.is_static_method():
                result += "static "

            if cursor.spelling != cursor.type.spelling:
                # Don't show duplicates if the user focuses type, not variable
                result += ClangUtils.link_from_location(
                    ClangUtils.location_from_type(result_type),
                    html.escape(result_type.spelling))
                result += ' '

        # Link to declaration of item under cursor
        if cursor.location:
            result += ClangUtils.link_from_location(
                cursor.location,
                html.escape(cursor.spelling))
        else:
            result += html.escape(cursor.spelling)

        # Macro/function/method arguments
        args_string = None
        if is_macro:
            # cursor.get_arguments() doesn't give us anything for macros,
            # so we have to parse those ourselves
            args_string = macro_parser.args_string
        else:
            args = []
            for arg in cursor.get_arguments():
                if arg.spelling:
                    args.append(arg.type.spelling + ' ' + arg.spelling)
                else:
                    args.append(arg.type.spelling + ' ')
            if cursor.kind in [cindex.CursorKind.FUNCTION_DECL,
                               cindex.CursorKind.CXX_METHOD]:
                args_string = '('
                if len(args):
                    args_string += html.escape(', '.join(args))
                args_string += ')'
        if args_string:
            result += args_string

        # Method modifiers
        if cursor.is_const_method():
            result += " const"

        # Doxygen comments
        if cursor.brief_comment:
            result += "

Brief documentation:
"
            result += "
" + cursor.brief_comment + "
"

        if cursor.raw_comment:
            html_raw_comment = ClangUtils.cleanup_comment(cursor.raw_comment)
            if len(html_raw_comment) > 0:
                result += "
Full Doxygen comment:"
                result += "

" + html_raw_comment + "
"

        return result

    @staticmethod
    def build_objc_message_info_details(cursor):
        """Provide information about cursor to Objective C message expression.

        Builds detailed information about cursor when cursor is
        a CursorKind.OBJC_MESSAGE_EXPR. OBJC_MESSAGE_EXPR cursors
        behave very differently from other C/C++ cursors in that:
        - The return type we want to show in the tooltip
          is stored in the original 'cursor.type' from the cursor the user is
          hovering over; in C/C++ we only used 'cursor.referenced' but nothing
          else from the original cursor.
        - 'cursor.referenced' is still important, as it holds the name and args
          of the method being called in the message. But
          'cursor.referenced.spelling' comes in a different format then what
          For example, if we have this method declaration for 'bar':
            @interface Foo
              -(void)bar:(BOOL)b1 boolParam2:(BOOL):b2
            @end
          And later, we hover over the text calling bar():
            Foo* foo = [[Foo alloc] init];
            [foo bar:YES boolParam2:NO]; // <- Hover over 'bar' here
          Then we would see:
            cursor.kind = CursorKind.OBJC_INSTANCE_METHOD_DECL
            cursor.type.spelling = 'void'
            cursor.referenced.kind: CursorKind.OBJC_INSTANCE_METHOD_DECL
            cursor.referenced.spelling = 'bar:boolParam2:'
            cursor.referenced.arguments[0].type.spelling = 'BOOL'
            cursor.referenced.arguments[0].spelling = 'b1'
            cursor.referenced.arguments[1].spelling = 'BOOL'
            cursor.referenced.arguments[1].spelling = 'b2'
          Our goal is to make the tooltip match the method declaration:
            'void bar:(BOOL)b1 boolParam2:(BOOL):b2'
        - Objective C methods also don't need to worry about static/const

        Args:
            cursor (Cursor): Current cursor.
        """
        result = ""
        return_type = cursor.type
        result += ClangUtils.link_from_location(
            ClangUtils.location_from_type(return_type),
            html.escape(return_type.spelling))

        result += ' '

        method_cursor = cursor.referenced
        method_and_params = method_cursor.spelling.split(':')
        method_name = method_and_params[0]
        if method_cursor.location:
            result += ClangUtils.link_from_location(
                method_cursor.location,
                html.escape(method_name))
        else:
            result += html.escape(method_cursor.spelling)

        method_params_index = 1
        for arg in method_cursor.get_arguments():
            result += ":(" + arg.type.spelling + ")"
            if arg.spelling:
                result += arg.spelling + " "
            result += method_and_params[method_params_index]
            method_params_index += 1

        if method_cursor.brief_comment:
            result += "

"
            result += method_cursor.brief_comment + ""

        return result

    @staticmethod
    def cleanup_comment(raw_comment):
        """Cleanup raw doxygen comment."""
        def pop_prepending_empty_lines(lines):
            first_non_empty_line_idx = 0
            for line in lines:
                if line == '':
                    first_non_empty_line_idx += 1
                else:
                    break
            return lines[first_non_empty_line_idx:]

        import string
        lines = raw_comment.split('\n')
        chars_to_strip = '/' + '*' + string.whitespace
        lines = [line.lstrip(chars_to_strip) for line in lines]
        lines = pop_prepending_empty_lines(lines)
        clean_lines = []
        is_brief_comment = True
        for line in lines:
            if line == '' and is_brief_comment:
                # Skip lines that belong to brief comment.
                is_brief_comment = False
                continue
            if is_brief_comment:
                continue
            clean_lines.append(line)
        return '
'.join(clean_lines)


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Konva Tween Filter Demo</title>


text:
package timer;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.SimpleTimeZone;

import userInterface.HomeScreen;

public class Timer {
	static boolean TimerRunning = false;
	static SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");

	static Date start = new Date();
	static Date stop = start;
	public Timer(){

	}
	public static String getTime(){
		sdf.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC"));

		String curTime = "";
		if(TimerRunning == true){
			Date now = new Date();
			curTime = sdf.format(new Date(now.getTime() - start.getTime()));
		}
		else{
			curTime = sdf.format(new Date(stop.getTime() - start.getTime()));
		}
		return curTime;

	}

	public static void startTimer(){
		if (TimerRunning){
			return;
		}
		else{
			start = new Date();
			TimerRunning = true;
			HomeScreen.btnStop.setEnabled(true);
			HomeScreen.btnStart.setEnabled(false);
		}

	}
	public static void stopTimer(){
		if(TimerRunning){
			stop = new Date();
			TimerRunning = false;
			HomeScreen.btnStop.setText("Reset");
		}
		else{
			start = new Date();
			stop = start;
			HomeScreen.btnStop.setText("Stop");
			HomeScreen.btnStop.setEnabled(false);
			HomeScreen.btnStart.setEnabled(true);

		}

	}
	public static boolean getTimerRunning(){
		return TimerRunning;
	}

}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: CommunicationMessageType.proto

package ProtoMessages;

public final class CommunicationMessageTypeBase {
  private CommunicationMessageTypeBase() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistryLite registry) {
  }
  /**
   * Protobuf enum {@code eCommunicationMessageType}
   */
  public enum eCommunicationMessageType
      implements com.google.protobuf.Internal.EnumLite {
    /**
     * cmtNone = 0;
     */
    cmtNone(0),
    /**
     *

     * simple message that send client to server
     *

     *
     * cmtPing = 1;
     */
    cmtPing(1),
    /**
     *

     * simple message that send server to client
     *

     *
     * cmtPong = 2;
     */
    cmtPong(2),
    ;

    /**
     * cmtNone = 0;
     */
    public static final int cmtNone_VALUE = 0;
    /**
     *

     * simple message that send client to server
     *

     *
     * cmtPing = 1;
     */
    public static final int cmtPing_VALUE = 1;
    /**
     *

     * simple message that send server to client
     *

     *
     * cmtPong = 2;
     */
    public static final int cmtPong_VALUE = 2;

    public final int getNumber() {
      return value;
    }

    /**
     * @deprecated Use {@link #forNumber(int)} instead.
     */
    @java.lang.Deprecated
    public static eCommunicationMessageType valueOf(int value) {
      return forNumber(value);
    }

    public static eCommunicationMessageType forNumber(int value) {
      switch (value) {
        case 0: return cmtNone;
        case 1: return cmtPing;
        case 2: return cmtPong;
        default: return null;
      }
    }

    public static com.google.protobuf.Internal.EnumLiteMap<eCommunicationMessageType>
        internalGetValueMap() {
      return internalValueMap;
    }
    private static final com.google.protobuf.Internal.EnumLiteMap<
        eCommunicationMessageType> internalValueMap =
          new com.google.protobuf.Internal.EnumLiteMap<eCommunicationMessageType>() {
            public eCommunicationMessageType findValueByNumber(int number) {
              return eCommunicationMessageType.forNumber(number);
            }
          };

    private final int value;

    private eCommunicationMessageType(int value) {
      this.value = value;
    }

    // @@protoc_insertion_point(enum_scope:eCommunicationMessageType)
  }

  static {
  }

  // @@protoc_insertion_point(outer_class_scope)
}


text:
using namespace std;
typedef map<string, int> course;
int main()
{
    //output the objective and the programmer to the user
    cout << "Programmer : Niall Smith " << endl;
    cout << "lab final"<<endl;
    cout << "Description:"<<endl;
    cout << "_______________________________________________________"<<endl<<endl;
    // for parsing the inputfile
    char* token;
    char buf[1000];
    const char* const tab = "\t";
    map<string, course> subject; // map within map
    set<string> temp;     //check duplicates
    //start clock
    clock_t startTime = clock();
    // open the input file
    ifstream fin;
    fin.open("dvc-schedule.txt");
    if (!fin.good()) throw "I/O error";
    // read the input file
    while (fin.good())
    {
        // read the line
        string line;
        getline(fin, line);
        strcpy(buf, line.c_str());
        if (buf[0] == 0) continue;

        // parse the line
        const string term(token = strtok(buf, tab));
        const string section(token = strtok(0, tab));
        const string course((token = strtok(0, tab)) ? token : "");
        const string instructor((token = strtok(0, tab)) ? token : "");
        const string whenWhere((token = strtok(0, tab)) ? token : "");
        if (course.find('-') == string::npos) continue;
        const string subjectCode(course.begin(), course.begin() + course.find('-'));

        // check for duplicate entry is not found, add the term && ++ courses
        if (temp.find(term + section) == temp.end())
        {
            temp.insert(term + section);
            subject[subjectCode][course]++;
        }
    }
    //close file
    fin.close();
    // print the elements
    map<string,course>::iterator it;     // for the subject map
    map<string, int>::iterator inner_it; //for the course map
    for (it = subject.begin(); it != subject.end(); it++)
    {
        cout << it->first << "\n";
        cout << "------------------------------------------\n";
        for( inner_it= it->second.begin(); inner_it != it->second.end(); inner_it++)
        {
            cout << "   " << inner_it->first << ", " << inner_it->second << " class(es)" << endl;
        }
        cout << "------------------------------------------\n";
    }
    //prints the elapsed time
    double elapsedSeconds = (double)(clock() - startTime) / CLOCKS_PER_SEC;
    cout << "\nElapsed Time: " << elapsedSeconds << " seconds" << endl;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>React Contacts</title>
    <link rel="stylesheet" href="style.css">


text:
using System.Drawing;
using System.Windows.Forms;

namespace org.lime.tree.controls.helper
{
    public static class RichtTextboxHelper
    {

        /// <summary>
        /// http://dotnet-snippets.de/snippet/farbigen-text-zu-richtextbox-hinzufuegen/1697
        /// </summary>
        /// <param name="rtb"></param>
        /// <param name="txt"></param>
        /// <param name="col"></param>
        public static void AddText(RichTextBox rtb, string txt, Color col, bool appendNewline = true)
        {
            int pos = rtb.TextLength;
            rtb.AppendText(txt);
            rtb.Select(pos, txt.Length);
            rtb.SelectionColor = col;
            rtb.Select();
            if (appendNewline) rtb.AppendText("\n");
        }

        public static void AddText(RichTextBox rtb, string txt)
        {
            AddText(rtb, txt, rtb.ForeColor);
        }

    }
}


text:
<?php

namespace Decoda;

/**
 * Defines the methods for all Filters to implement.
 */
interface Filter extends Component {

    /**
     * Regex patterns for attribute parsing.
     */
    const WILDCARD = '/(.*?)/';
    const ALPHA = '/^[a-z_\-\s]+$/i';
    const ALNUM = '/^[a-z0-9,_\s\.\-\+\/]+$/i';
    const NUMERIC = '/^[0-9,\.\-\+\/]+$/';

    /**
     * Return a tag if it exists, and merge with defaults.
     *
     * @param string $tag
     * @return array
     */
    public function getTag($tag);

    /**
     * Return all tags.
     *
     * @return array
     */
    public function getTags();

    /**
     * Parse the node and its content into an HTML tag.
     *
     * @param array $tag
     * @param string $content
     * @return string
     */
    public function parse(array $tag, $content);

    /**
     * Add any hook dependencies.
     *
     * @param \Decoda\Decoda $decoda
     * @return \Decoda\Filter
     */
    public function setupHooks(Decoda $decoda);

    /**
     * Strip a node and remove content dependent on settings.
     *
     * @param array $tag
     * @param string $content
     * @return string
     */
    public function strip(array $tag, $content);

}


text:
layout: projects-page
image-dir: crossfit
categories: Identity
subtitle: Crossfit box in the heart of Seminyak
year: 2018
scope:
    - Brand Identity
    - Digital
agency: Léon
collaborator:
credit:
    - Interior Design by Mahallati
creative-director:
status: in-progress
featured:
thumbnail-type: image
---
Brand identity for Crossfit box in the heart of Seminyak. More details soon.


text:
{{artist.name}}

{{artist.reknown}}

{{artist.bio}}


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;

namespace CSharpGL
{
    /// <summary>
    /// A rectangle control that displays an image.
    /// </summary>
    public partial class CtrlImage : GLControl
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="bitmap">bitmap to be displayed.</param>
        /// <param name="autoDispose">auto dispose <paramref name="bitmap"/> after this object's initialization.</param>
        public CtrlImage(Bitmap bitmap, bool autoDispose = false)
            : base(GUIAnchorStyles.Left | GUIAnchorStyles.Top)
        {
            var model = new CtrlImageModel();
            var vs = new VertexShader(vert);
            var fs = new FragmentShader(frag);
            var codes = new ShaderArray(vs, fs);
            var map = new AttributeMap();
            map.Add(inPosition, CtrlImageModel.position);
            map.Add(inUV, CtrlImageModel.uv);
            var methodBuilder = new RenderMethodBuilder(codes, map, new BlendFuncSwitch(BlendSrcFactor.SrcAlpha, BlendDestFactor.OneMinusSrcAlpha));
            this.RenderUnit = new ModernRenderUnit(model, methodBuilder);

            this.bitmap = bitmap;
            this.autoDispose = autoDispose;

            this.Initialize();
        }

        private Bitmap bitmap;
        private bool autoDispose;

        /// <summary>
        ///
        /// </summary>
        public ModernRenderUnit RenderUnit { get; private set; }

        /// <summary>
        ///
        /// </summary>
        protected override void DoInitialize()
        {
            this.RenderUnit.Initialize();

            {
                var bitmap = this.bitmap;
                bitmap.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipX);
                var texImageBitmap = new TexImageBitmap(bitmap);
                var texture = new Texture(texImageBitmap);
                texture.BuiltInSampler.Add(new TexParameteri(TexParameter.PropertyName.TextureWrapS, (int)GL.GL_CLAMP_TO_EDGE));
                texture.BuiltInSampler.Add(new TexParameteri(TexParameter.PropertyName.TextureWrapT, (int)GL.GL_CLAMP_TO_EDGE));
                texture.BuiltInSampler.Add(new TexParameteri(TexParameter.PropertyName.TextureWrapR, (int)GL.GL_CLAMP_TO_EDGE));
                texture.BuiltInSampler.Add(new TexParameteri(TexParameter.PropertyName.TextureMinFilter, (int)GL.GL_LINEAR));
                texture.BuiltInSampler.Add(new TexParameteri(TexParameter.PropertyName.TextureMagFilter, (int)GL.GL_LINEAR));

                texture.Initialize();

                if (this.autoDispose) { bitmap.Dispose(); }
                this.bitmap = null;

                RenderMethod method = this.RenderUnit.Methods[0];
                method.Program.SetUniform("tex", texture);
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="arg"></param>
        public override void RenderGUIBeforeChildren(GUIRenderEventArgs arg)
        {
            base.RenderGUIBeforeChildren(arg);

            ModernRenderUnit unit = this.RenderUnit;
            RenderMethod method = unit.Methods[0];
            method.Render();
        }
    }
}


text:
CBanknodeConfig banknodeConfig;

void CBanknodeConfig::add(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex) {
    CBanknodeEntry cme(alias, ip, privKey, txHash, outputIndex);
    entries.push_back(cme);
}

bool CBanknodeConfig::read(std::string& strErr) {
    boost::filesystem::ifstream streamConfig(GetBanknodeConfigFile());
    if (!streamConfig.good()) {
        return true; // No banknode.conf file is OK
    }

    for(std::string line; std::getline(streamConfig, line); )
    {
        if(line.empty()) {
            continue;
        }
        std::istringstream iss(line);
        std::string alias, ip, privKey, txHash, outputIndex;
        if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) {
            strErr = "Could not parse banknode.conf line: " + line;
            streamConfig.close();
            return false;
        }

        add(alias, ip, privKey, txHash, outputIndex);
    }

    streamConfig.close();
    return true;
}