text:
package synergynet.contentsystem.items;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import synergynet.contentsystem.ContentSystem;
import synergynet.contentsystem.contentloader.utils.TextUtil;
import synergynet.contentsystem.items.implementation.interfaces.IMultiLineTextLabelImplementation;

public class MultiLineTextLabel extends TextLabel implements IMultiLineTextLabelImplementation, Serializable, Cloneable {

	private static final long serialVersionUID = 7970788844569917633L;

	protected List<String> lines = new ArrayList<String>();

	public MultiLineTextLabel(ContentSystem contentSystem, String name) {
		super(contentSystem, name);
	}

	public void setLines(List<String> lines) {
		this.lines = lines;
		((IMultiLineTextLabelImplementation)this.contentItemImplementation).setLines(lines);
	}

	public void setLines(String s, int charsPerLine){
		this.lines = TextUtil.wrapAt(s, charsPerLine);
		((IMultiLineTextLabelImplementation)this.contentItemImplementation).setLines(s, charsPerLine);
	}

	public void setCRLFSeparatedString(String s) {
		this.text = s;
		lines.clear();
		StringTokenizer st = new StringTokenizer(s, "\n");
		while(st.hasMoreTokens()) {
			lines.add(st.nextToken());
		}
		if(s.endsWith("\n"))
			lines.add("");

		((IMultiLineTextLabelImplementation)this.contentItemImplementation).setCRLFSeparatedString(s);
	}

	public List<String> getLines() {
		return lines;
	}

	public String getFirstLine() {
		if(lines.size() > 0) return lines.get(0);
		return "";
	}

	@Override
	public Object clone() throws CloneNotSupportedException {
		MultiLineTextLabel clonedItem = (MultiLineTextLabel)super.clone();
		clonedItem.lines = new ArrayList<String>();
		for (String s:this.lines){
			clonedItem.lines.add(s);
		}
		return clonedItem;

	}

}

redpajama_set_name: RedPajamaGithub


text:
.FancyBorder {
    border-style: double;
    border-radius: 20px;
    padding: 20px;
}

.FancyBorder-blue {
    border-color: blue;
}


text:
title: 'About North of Tyne LPC'
linktitle: 'About Us'
description: 'North of Tyne LPC is recognised, under section 167 of the NHS Act 2006, as the statutory body representing the community pharmacies in Northumberland, Newcastle and North Tyneside'
date: 2018-09-01
publishdate: 2018-09-01
lastmod: 2018-09-01
categories: ['about']
tags: ['Committee']
menu:
  about:
    parent: "about"
    weight: 1
weight: 1
draft: false
aliases: [/about/]
toc: false
---

North of Tyne Local Pharmaceutical Committee (LPC) is recognised, under section 167 of the NHS Act 2006, as the statutory body representing the community pharmacies in Northumberland, Newcastle and North Tyneside.

We represent 192 community pharmacies across our region.


text:
<?php

namespace Sales\Service;

use MyZend\Service\Service as Service;
use Salse\Document\Quote;

class QuoteService extends Service {

	protected $document = "Sales\Document\Quote";

	public function __construct($sm) {
		$this->dm = $sm->get('doctrine.documentmanager.odm_default');
	}
}


text:
using strange.extensions.mediation.api;
using UnityEngine;

namespace strange.unittests
{
    public class SignalMediatorPrivate : IMediator
    {
            public GameObject contextView { get; set; }

            public static int Value = 0;

            [ListensTo(typeof(OneArgSignal))]
            private void OneArgMethod(int myArg)
            {
                Value += myArg;
            }

            public void PreRegister()
            {
            }

            public void OnRegister()
            {
            }

            public void OnRemove()
            {
            }

            public void OnEnabled()
            {
            }

            public void OnDisabled()
            {
            }
    }
}


text:
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}

{-|
Translating an Encore program to its CCode representation (see "CCode.Main")
-}

module CodeGen.Main (
  compileToC,
  Emitted,
  getClasses,
  getHeader,
  getShared
) where

import CodeGen.Program
import CodeGen.Preprocessor

import qualified AST.AST as A

getClasses = classes
getHeader = header
getShared = shared

compileToC :: A.Program -> Emitted
compileToC = translate . preprocess


text:
cask 'jdownloader' do
  version :latest
  sha256 :no_check

  url 'http://installer.jdownloader.org/clean/JD2Setup.dmg',
      user_agent: :fake
  name 'JDownloader 2'
  homepage 'http://jdownloader.org/'

  auto_updates true

  preflight do
    system_command "#{staged_path}/JDownloader Installer.app/Contents/MacOS/JavaApplicationStub",
                   args:         [
                                   '-dir', staged_path.to_s,
                                   '-q',
                                   '-Dinstall4j.suppressStdout=true',
                                   '-Dinstall4j.debug=false',
                                   '-VcreateDesktopLinkAction\$Boolean=false',
                                   '-VaddToDockAction\$Boolean=false'
                                 ],
                   print_stderr: false
  end

  uninstall delete: '/Applications/JDownloader2.app'

  caveats do
    depends_on_java
  end
end


text:
/**
 *
 */
package com.socialize.test.unit;

import com.socialize.cache.ICacheableFactory;
import com.socialize.cache.ISuicidal;
import com.socialize.cache.Key;
import com.socialize.cache.TTLCache;
import com.socialize.cache.TTLObject;
import com.socialize.test.SocializeUnitTest;
import org.mockito.Mockito;

import java.util.Collection;
import java.util.TreeMap;

/**
 * @author Jason
 */
public class TTLCacheTest extends SocializeUnitTest {

	private TTLCache<String, StringCacheable> cache;
	private CacheListenerTest listener;

	protected void setUp() throws Exception {
		super.setUp();

		cache = new TTLCache<String, StringCacheable>(1, 2);
		cache.setDebug(true);
		cache.setMaxCapacityBytes(20);
		cache.setHardByteLimit(false);

		listener = new CacheListenerTest();

		cache.setEventListener(listener);
	}

	@Override
	protected void tearDown() throws Exception {
		cache.clear();
		super.tearDown();
	}

	/**
	 * Tests that an object put into cache can be retrieved.
	 */
	public void testSimpleCachePut() {
		StringCacheable testObj = new StringCacheable("test");
		cache.put("testKey", testObj);

		StringCacheable fromCache = cache.get("testKey");

		assertNotNull(fromCache);
		assertEquals("test", fromCache.getValue());
	}

	public void testOnPutCalledOnPut() {
		StringCacheable testObj = new StringCacheable("test");
		cache.put("testKey", testObj);
		assertEquals(1, testObj.getOnPutCount());
	}

	public void testOnGetCalledOnGet() {
		StringCacheable testObj = new StringCacheable("test");
		cache.put("testKey", testObj);
		cache.get("testKey");
		assertEquals(1, testObj.getOnGetCount());
	}

	/**
	 * Tests that the reaper was executed when expected.
	 */
	public void testManualCacheReap() {
		assertTrue(cache.doReap());
		assertEquals(1, listener.reapStarts);
		assertEquals(1, listener.reapEnds);
	}

	public void testScheduledCacheReap() {

		assertEquals(0, listener.reapStarts);
		assertEquals(0, listener.reapEnds);

		cache.setReapCycle(2000);

		try {
			Thread.sleep(2200);
		} catch (InterruptedException ignore) {
			ignore.printStackTrace();
		}

		assertEquals(1, listener.reapStarts);
		assertEquals(1, listener.reapEnds);
	}

	/**
	 * Tests that the onRemove method is called when an object is replaced.
	 */
	public void testOnRemoveNOTCalledOnReplace() {
		StringCacheable testObj = new StringCacheable("test");
		StringCacheable testObj2 = new StringCacheable("test2");
		cache.put("testKey", testObj);
		cache.put("testKey", testObj2);

		assertEquals(0, testObj.getOnRemoveCount());
	}

	/**
	 * Tests that an object expires after its ttl.
	 */
	public void testObjectExpiry() {
		StringCacheable testObj = new StringCacheable("test");
		cache.put("testKey", testObj, 100);

		try {
			Thread.sleep(500);
		} catch (InterruptedException ignore) {
			ignore.printStackTrace();
		}

		assertTrue(cache.doReap());
		assertFalse(cache.exists("testKey"));
		assertNull(cache.get("testKey"));
	}

	/**
	 * Tests that the onRemove method is called when an object is reaped.
	 */
	public void testOnRemoveCalledOnReap() {
		StringCacheable testObj = new StringCacheable("test");
		cache.put("testKey", testObj, 100);

		try {
			Thread.sleep(500);
		} catch (InterruptedException ignore) {
			ignore.printStackTrace();
		}

		assertTrue(cache.doReap());
		assertEquals(1, testObj.getOnRemoveCount());
	}

	/**
	 * Tests that the onRemove method is called when an object is manually removed.
	 */
	public void testOnRemoveCalledOnRemove() {
		StringCacheable testObj = new StringCacheable("test");
		cache.put("testKey", testObj);

		assertTrue(cache.exists("testKey"));

		cache.remove("testKey");

		assertFalse(cache.exists("testKey"));
		assertEquals(1, testObj.getOnRemoveCount());
	}

	/**
	 * Tests that the onRemove method is called when an object is manually removed.
	 */
	public void testOnRemoveCalledOnClear() {
		StringCacheable testObj = new StringCacheable("test");
		StringCacheable testObj2 = new StringCacheable("test2");
		cache.put("testKey", testObj);
		cache.put("testKey2", testObj2);

		assertEquals(2, cache.size());

		cache.clear();

		assertEquals(1, testObj.getOnRemoveCount());
		assertEquals(1, testObj2.getOnRemoveCount());
		assertEquals(0, cache.size());
	}

	public void testSizeInBytesIncreasedOnPut() {
		StringCacheable testObj = new StringCacheable("test1");
		StringCacheable testObj2 = new StringCacheable("test2");
		cache.put("testKey", testObj);
		cache.put("testKey2", testObj2);
		assertEquals(10, cache.sizeInBytes());
	}

	public void testSizeInBytesCorrectOnReplace() {
		StringCacheable testObj = new StringCacheable("test1");
		StringCacheable testObj2 = new StringCacheable("test2");
		cache.put("testKey", testObj);
		cache.put("testKey", testObj2);
		assertEquals(5, cache.sizeInBytes());
	}

	public void testSizeInBytesCorrectOnClear() {
		StringCacheable testObj = new StringCacheable("test1");
		StringCacheable testObj2 = new StringCacheable("test2");
		cache.put("testKey", testObj);
		cache.put("testKey2", testObj2);

		cache.clear();

		assertEquals(0, cache.sizeInBytes());
	}

	public void testSizeInBytesCorrectOnReap() {
		StringCacheable testObj = new StringCacheable("test1");
		StringCacheable testObj2 = new StringCacheable("test2");
		cache.put("testKey", testObj);
		cache.put("testKey2", testObj2, 100);

		try {
			Thread.sleep(500);
		} catch (InterruptedException ignore) {
			ignore.printStackTrace();
		}
		assertTrue(cache.doReap());
		assertEquals(0, testObj.getOnRemoveCount());
		assertEquals(1, testObj2.getOnRemoveCount());

		assertEquals(5, cache.sizeInBytes());
	}

	public void testSizeInBytesCorrectOnRemove() {
		StringCacheable testObj = new StringCacheable("test1");
		StringCacheable testObj2 = new StringCacheable("test2");
		cache.put("testKey", testObj);
		cache.put("testKey2", testObj2);

		cache.remove("testKey");

		assertEquals(5, cache.sizeInBytes());
	}

	public void testTrimOnCountExceededAfterReap() {
		StringCacheable testObj = new StringCacheable("test1");
		StringCacheable testObj2 = new StringCacheable("test2");
		StringCacheable testObj3 = new StringCacheable("test3");

		cache.put("testKey", testObj);
		cache.put("testKey2", testObj2);
		cache.put("testKey3", testObj3);

		assertEquals(3, cache.size());

		assertTrue(cache.doReap());

		assertEquals(2, cache.size());
	}

	public void testTrimOnBytesExceededAfterReap() {
		StringCacheable testObj = new StringCacheable("0000000000");
		StringCacheable testObj2 = new StringCacheable("00000000000");

		cache.put("testKey", testObj);
		cache.put("testKey2", testObj2);

		assertEquals(2, cache.size());

		assertTrue(cache.doReap());

		assertEquals(1, cache.size());
	}

	public void testPutFailOnBytesExceededWithHardLimit() {
		StringCacheable testObj = new StringCacheable("0000000000");
		StringCacheable testObj2 = new StringCacheable("00000000000");

		cache.setHardByteLimit(true);
		cache.put("testKey", testObj);
		assertFalse(cache.put("testKey2", testObj2));
		assertEquals(1, cache.size());

	}

	public void testOldestRemoveOnReap() {
		StringCacheable testObj = new StringCacheable("test1");
		StringCacheable testObj2 = new StringCacheable("test2");
		StringCacheable testObj3 = new StringCacheable("test3");

		cache.put("testKey", testObj);
		cache.put("testKey2", testObj2);

		try {
			Thread.sleep(500);
		} catch (InterruptedException ignore) {
			ignore.printStackTrace();
		}

		cache.put("testKey", testObj); // replace so we know it's not just first
		cache.put("testKey3", testObj3);

		assertEquals(3, cache.size());

		assertTrue(cache.doReap());

		assertEquals(2, cache.size());

		assertTrue(cache.exists("testKey"));
		assertFalse(cache.exists("testKey2"));
		assertTrue(cache.exists("testKey3"));
	}

	public void testConstructorUsesDefaultCacheCount() {
		TTLCache<String, StringCacheable> cache = new TTLCache<String, StringCacheable>(1);
		assertEquals(TTLCache.DEFAULT_CACHE_COUNT, cache.getMaxCapacity());
	}

	public void testPauseCallsStopOnReaper() {
		TTLCache<String, StringCacheable> cache = new TTLCache<String, StringCacheable>() {
			@Override
			protected synchronized void stopReaper() {
				addResult(true);
			}
		};

		cache.pause();

		Boolean result = getNextResult();
		assertNotNull(result);
		assertTrue(result);
	}

	public void testResumeCallsStartOnReaper() {
		TTLCache<String, StringCacheable> cache = new TTLCache<String, StringCacheable>() {
			@Override
			protected synchronized void startReaper() {
				addResult(true);
			}
		};

		cache.resume();

		Boolean result = getNextResult();
		assertNotNull(result);
		assertTrue(result);
	}

	public void testPutCallPutWithDefaultTTL() {
		TTLCache<String, StringCacheable> cache = new TTLCache<String, StringCacheable>() {

			@Override
			protected synchronized boolean put(String k, StringCacheable object, long ttl, boolean eternal) {
				addResult(ttl);
				return true;
			}

		};

		cache.put("foobar", null);

		Long result = getNextResult();
		assertNotNull(result);
		assertEquals(cache.getDefaultTTL(), result.longValue());
	}

	@SuppressWarnings("unchecked")
	public void testGetRaw() {
		final TTLObject<String, StringCacheable> object = Mockito.mock(TTLObject.class);
		final StringCacheable cacheable = new StringCacheable();

		Mockito.when(object.getObject()).thenReturn(cacheable);

		TTLCache<String, StringCacheable> cache = new TTLCache<String, StringCacheable>() {
			@Override
			protected TTLObject<String, StringCacheable> getTTLObject(String strKey) {
				return object;
			}

			@Override
			public boolean isExpired(TTLObject<String, StringCacheable> object) {
				return false;
			}
		};

		assertSame(cacheable, cache.getRaw("foobar"));
	}

	@SuppressWarnings("unchecked")
	public void testCreateOnEmptyGet() {

		final String key = "foobar";
		final TTLObject<String, StringCacheable> object = Mockito.mock(TTLObject.class);
		final ICacheableFactory<String, StringCacheable> factory = Mockito.mock(ICacheableFactory.class);
		final StringCacheable cacheable = new StringCacheable();

		Mockito.when(object.getObject()).thenReturn(null);
		Mockito.when(factory.create(key)).thenReturn(cacheable);

		TTLCache<String, StringCacheable> cache = new TTLCache<String, StringCacheable>() {
			@Override
			protected TTLObject<String, StringCacheable> getTTLObject(String strKey) {
				return object;
			}

			@Override
			protected synchronized boolean put(String k, StringCacheable object, long ttl, boolean eternal) {
				addResult(true);
				return true;
			}
		};

		cache.setObjectFactory(factory);

		assertSame(cacheable, cache.get(key));

		Boolean result = getNextResult();
		assertNotNull(result);
		assertTrue(result);
	}

	public void testValues() {

		final int expiredCount = 5;
		int totalCount = 10;

		TTLCache<String, StringCacheable> cache = new TTLCache<String, StringCacheable>() {
			@Override
			public boolean isExpired(TTLObject<String, StringCacheable> object) {
				Integer nextResult = getNextResult();

				if(nextResult == null) {
					addResult(1);
					return true;
				}
				else if(nextResult >= expiredCount) {
					addResult(++nextResult);
					return false;
				}
				else {
					addResult(++nextResult);
					return true;
				}
			}
		};

		for (int i = 0; i < totalCount; i++) {
			StringCacheable value = new StringCacheable(String.valueOf(i));
			cache.put(String.valueOf(i), value);
		}

		Collection<StringCacheable> values = cache.values();
		assertNotNull(values);
		assertEquals((totalCount - expiredCount), values.size());
	}

	@SuppressWarnings("unchecked")
	public void testNotExpired() {

		TTLObject<String, StringCacheable> obj = Mockito.mock(TTLObject.class);
		Mockito.when(obj.getObject()).thenReturn(null);
		Mockito.when(obj.isEternal()).thenReturn(false);
		Mockito.when(obj.getLifeExpectancy()).thenReturn(Long.MAX_VALUE);

        assertFalse(cache.isExpired(obj));
	}

	@SuppressWarnings("unchecked")
	public void testExpired() {

		TTLObject<String, StringCacheable> obj = Mockito.mock(TTLObject.class);
		Mockito.when(obj.getObject()).thenReturn(null);
		Mockito.when(obj.isEternal()).thenReturn(false);
		Mockito.when(obj.getLifeExpectancy()).thenReturn(0L);

		assertTrue(cache.isExpired(obj));
	}

	@SuppressWarnings("unchecked")
	public void testExpiredSuicical() {

		TTLCache<String, ISuicidal<String>> cache = new TTLCache<String, ISuicidal<String>>();

		TTLObject<String, ISuicidal<String>> obj = Mockito.mock(TTLObject.class);
		ISuicidal<String> s = Mockito.mock(ISuicidal.class);
		Mockito.when(obj.getObject()).thenReturn(s);
		Mockito.when(s.isDead()).thenReturn(true);

        assertTrue(cache.isExpired(obj));
	}

	public void testKey() {

		Key<String> key1 = new Key<String>("foobar1", 0);
		Key<String> key2 = new Key<String>("foobar1", 0);
		Key<String> key3 = new Key<String>("foobar2", 0);

		assertFalse(key1.equals(key3));
		assertTrue(key1.equals(key2));
	}

	public void testKeyCompare() {
		Key<String> key1 = new Key<String>("foobar1", 100);
		Key<String> key2 = new Key<String>("foobar1", 200);

		// key1 is oldest
		TreeMap<Key<String>, String> sorted = new TreeMap<Key<String>, String>();

		sorted.put(key1, "foo");
		sorted.put(key2, "bar");

		Key<String> firstKey = sorted.firstKey();

		assertSame(key1, firstKey);

		TreeMap<Key<String>, String> sorted2 = new TreeMap<Key<String>, String>();

		sorted2.put(key2, "bar");
		sorted2.put(key1, "foo");

		Key<String> firstKey2 = sorted2.firstKey();

		assertSame(key1, firstKey2);

	}
}


text:
<?php

declare(strict_types=1);

namespace Saxulum\Tests\ElasticSearchQueryBuilder\Converter;

use PHPUnit\Framework\TestCase;
use Saxulum\ElasticSearchQueryBuilder\Converter\ScalarToNodeConverter;
use Saxulum\ElasticSearchQueryBuilder\Node\BoolNode;
use Saxulum\ElasticSearchQueryBuilder\Node\FloatNode;
use Saxulum\ElasticSearchQueryBuilder\Node\IntNode;
use Saxulum\ElasticSearchQueryBuilder\Node\NullNode;
use Saxulum\ElasticSearchQueryBuilder\Node\StringNode;

/**
 * @covers \Saxulum\ElasticSearchQueryBuilder\Converter\ScalarToNodeConverter
 */
class ScalarToNodeConverterTest extends TestCase
{
    public function testConvertBool()
    {
        $valueConverter = new ScalarToNodeConverter();

        self::assertInstanceOf(BoolNode::class, $valueConverter->convert(true));
    }

    public function testConvertFloat()
    {
        $valueConverter = new ScalarToNodeConverter();

        self::assertInstanceOf(FloatNode::class, $valueConverter->convert(1.234));
    }

    public function testConvertInt()
    {
        $valueConverter = new ScalarToNodeConverter();

        self::assertInstanceOf(IntNode::class, $valueConverter->convert(1));
    }

    public function testConvertNull()
    {
        $valueConverter = new ScalarToNodeConverter();

        self::assertInstanceOf(NullNode::class, $valueConverter->convert(null));
    }

    public function testConvertString()
    {
        $valueConverter = new ScalarToNodeConverter();

        self::assertInstanceOf(StringNode::class, $valueConverter->convert('string'));
    }

    public function testConvertSetsDefaultIsAllowSerializeEmpty()
    {
        $valueConverter = new ScalarToNodeConverter();

        self::assertFalse($valueConverter->convert('string')->isAllowSerializeEmpty());
    }

    public function testConvertSetsIsAllowSerializeEmpty()
    {
        $valueConverter = new ScalarToNodeConverter();

        self::assertTrue($valueConverter->convert('string', '', true)->isAllowSerializeEmpty());
    }

    public function testConvertWithUnsupportedValueExpectException()
    {
        self::expectException(\InvalidArgumentException::class);
        self::expectExceptionMessage('Type DateTime is not supported, at path dates[0]');

        $valueConverter = new ScalarToNodeConverter();
        $valueConverter->convert(new \DateTime(), 'dates[0]');
    }
}


text:
using System.Collections.Generic;

namespace Vending.Core.States
{
    public class PriceState : VendingMachineState
    {
        private readonly decimal _priceInCents;

        public PriceState(VendingMachineState state, int priceInCents)
            :this(state.Context, state.ReturnTray, state.CoinSlot, state.ProductInfoRepository, state.Output, state.Vault, priceInCents)
        {
        }

        public PriceState(StateContext context, List<Coin> returnTray, List<Coin> coinSlot, ProductInfoRepository productInfoRepository, List<string> output, List<Coin> vault, int priceInCents)
            :base(context, returnTray, coinSlot, productInfoRepository, output, vault)
        {
            _priceInCents = priceInCents;
        }

        public override string Display()
        {
            return $"PRICE: {_priceInCents/100:C}";
        }

        protected override void DispenseCallback(string sku)
        {
            // no op
        }
    }
}


text:
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2022 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Markus Pfeiffer
////////////////////////////////////////////////////////////////////////////////

#include "KShortestPathsFinder.h"

#include "Aql/AqlValue.h"
#include "Basics/ResourceUsage.h"
#include "Cluster/ServerState.h"
#include "Graph/EdgeCursor.h"
#include "Graph/EdgeDocumentToken.h"
#include "Graph/ShortestPathOptions.h"
#include "Graph/ShortestPathResult.h"
#include "Graph/TraverserCache.h"
#include "Transaction/Helpers.h"
#include "VocBase/LogicalCollection.h"

#include <velocypack/Iterator.h>
#include <velocypack/Slice.h>

using namespace arangodb;
using namespace arangodb::graph;

template<class ProviderType>
KShortestPathsFinder<ProviderType>::KShortestPathsFinder(
    ShortestPathOptions& options,
    typename ProviderType::Options&& forwardProviderOptions,
    typename ProviderType::Options&& backwardProviderOptions)
    : KShortestPathsFinderInterface(options),
      _resourceMonitor(options.resourceMonitor()),
      _left(FORWARD),
      _right(BACKWARD),
      _forwardProvider(std::make_unique<ProviderType>(
          options.query(), std::move(forwardProviderOptions),
          options.query().resourceMonitor())),
      _backwardProvider(std::make_unique<ProviderType>(
          options.query(), std::move(backwardProviderOptions),
          options.query().resourceMonitor())) {}

template<class ProviderType>
KShortestPathsFinder<ProviderType>::~KShortestPathsFinder() {
  try {
    // necessary to revert memory usage trackers
    clear();
  } catch (...) {
  }
}

template<class ProviderType>
void KShortestPathsFinder<ProviderType>::clear() {
  _shortestPaths.clear();

  while (!_candidatePaths.empty()) {
    _resourceMonitor.decreaseMemoryUsage(_candidatePaths.back().memoryUsage());
    _candidatePaths.pop_back();
  }
  TRI_ASSERT(_candidatePaths.empty());

  // clear cache and forget about its memory usage
  _resourceMonitor.decreaseMemoryUsage(_vertexCache.size() *
                                       vertexCacheEntryMemoryUsage());
  _vertexCache.clear();

  _traversalDone = true;
}

// Sets up k-shortest-paths traversal from start to end
template<class ProviderType>
bool KShortestPathsFinder<ProviderType>::startKShortestPathsTraversal(
    arangodb::velocypack::Slice const& start,
    arangodb::velocypack::Slice const& end) {
  TRI_ASSERT(start.isString());
  TRI_ASSERT(end.isString());
  _start = start.stringView();
  _end = end.stringView();

  clear();
  _traversalDone = false;

  TRI_IF_FAILURE("Travefalse") { THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG); }

  return true;
}

template<class ProviderType>
bool KShortestPathsFinder<ProviderType>::computeShortestPath(
    VertexRef const& start, VertexRef const& end,
    VertexSet const& forbiddenVertices, EdgeSet const& forbiddenEdges,
    Path& result) {
  _left.reset(start);
  _right.reset(end);
  VertexRef join;

  auto currentBest = std::optional<double>{};

  // We will not improve anymore if we have found a best path and the smallest
  // combined distance between left and right is bigger than that path
  while (!_left.done(currentBest) && !_right.done(currentBest)) {
    _options.isQueryKilledCallback();

    // Choose the smaller frontier to expand.
    if (!_left.done(currentBest) &&
        (_left._frontier.size() < _right._frontier.size())) {
      advanceFrontier(_left, _right, forbiddenVertices, forbiddenEdges, join,
                      currentBest);
    } else {
      advanceFrontier(_right, _left, forbiddenVertices, forbiddenEdges, join,
                      currentBest);
    }
  }

  result.clear();
  if (currentBest.has_value()) {
    reconstructPath(_left, _right, join, result);
    return true;
  }
  // No path found
  return false;
}

template<class ProviderType>
void KShortestPathsFinder<ProviderType>::computeNeighbourhoodOfVertexCache(
    VertexRef vertex, Direction direction, std::vector<Step>*& res) {
  // track memory usage for one more item
  // if we can't insert the item into the cache, it means the item is
  // already in the cache. then we are not responsible for tracking its memory
  // usage.
  ResourceUsageScope guard(_resourceMonitor, vertexCacheEntryMemoryUsage());

  auto result = _vertexCache.try_emplace(vertex, FoundVertex(vertex));

  if (result.second) {
    // successful insert - now _vertexCache has taken over responsibility
    // for memory usage tracking
    guard.steal();
  }

  auto& cache =
      result.first->second;  // want to update the cached vertex in place

  switch (direction) {
    case BACKWARD:
      if (!cache._hasCachedInNeighbours) {
        computeNeighbourhoodOfVertex(vertex, direction, cache._inNeighbours);
        cache._hasCachedInNeighbours = true;
      }
      res = &cache._inNeighbours;
      break;
    case FORWARD:
      if (!cache._hasCachedOutNeighbours) {
        computeNeighbourhoodOfVertex(vertex, direction, cache._outNeighbours);
        cache._hasCachedOutNeighbours = true;
      }
      res = &cache._outNeighbours;
      break;
    default:
      TRI_ASSERT(false);
  }
}

template<class ProviderType>
void KShortestPathsFinder<ProviderType>::computeNeighbourhoodOfVertex(
    VertexRef vertex, Direction direction, std::vector<Step>& steps) {
  // Select proper provider (direction based)
  ProviderType* provider =
      direction == BACKWARD ? _backwardProvider.get() : _forwardProvider.get();

  // Create step to use
  arangodb::velocypack::HashedStringRef vertexRef{
      vertex.data(), static_cast<uint32_t>(vertex.length())};
  typename ProviderType::Step step{vertexRef, 0};
  if constexpr (std::is_same_v<typename ProviderType::Step,
                               ClusterProviderStep>) {
    std::vector<typename ProviderType::Step*> stepToFetch{&step};
    futures::Future<std::vector<typename ProviderType::Step*>> futureEnds =
        provider->fetch(stepToFetch);
    futureEnds.wait();
  }

  // Expand the step
  TRI_ASSERT(provider != nullptr);

  // Variant using provider
  size_t previous = 0;  // dummy value

  provider->expand(step, previous, [&](auto n) -> void {
    steps.emplace_back(provider->getEdgeDocumentToken(n.getEdge()),
                       n.getVertex().getID().stringView(),
                       (n.getWeight() - step.getWeight()));
  });
}

template<class ProviderType>
void KShortestPathsFinder<ProviderType>::advanceFrontier(
    Ball& source, Ball const& target, VertexSet const& forbiddenVertices,
    EdgeSet const& forbiddenEdges, VertexRef& join,
    std::optional<double>& currentBest) {
  VertexRef vr;
  DijkstraInfo *v, *w;

  bool success = source._frontier.popMinimal(vr, v);
  TRI_ASSERT(v != nullptr);
  TRI_ASSERT(vr == v->_vertex);
  if (!success) {
    return;
  }

  std::vector<Step>* neighbours;
  computeNeighbourhoodOfVertexCache(vr, source._direction, neighbours);
  TRI_ASSERT(neighbours != nullptr);

  for (auto const& s : *neighbours) {
    if (forbiddenEdges.find(s._edge) == forbiddenEdges.end() &&
        forbiddenVertices.find(s._vertex) == forbiddenVertices.end()) {
      double weight = v->_weight + s._weight;

      auto lookup = source._frontier.find(s._vertex);
      if (lookup != nullptr) {
        if (lookup->_weight > weight) {
          source._frontier.lowerWeight(s._vertex, weight);
          lookup->_pred = vr;
          lookup->_edge = s._edge;
          lookup->_weight = weight;
        }
      } else {
        source._frontier.insert(s._vertex,
                                std::make_unique<DijkstraInfo>(
                                    s._vertex, std::move(s._edge), vr, weight));
      }
    }
  }
  v->_done = true;
  source._closest = v->_weight;

  w = target._frontier.find(v->_vertex);
  if (w != nullptr && w->_done) {
    // The total weight of the found path
    double totalWeight = v->_weight + w->_weight;
    if (!currentBest.has_value() || totalWeight < currentBest.value()) {
      join = v->_vertex;
      currentBest = totalWeight;
    }
  }
}

template<class ProviderType>
void KShortestPathsFinder<ProviderType>::reconstructPath(Ball const& left,
                                                         Ball const& right,
                                                         VertexRef const& join,
                                                         Path& result) {
  // track memory used for reconstructing the path
  ResourceUsageScope guard(_resourceMonitor);

  result.clear();
  TRI_ASSERT(!join.empty());
  result._vertices.emplace_back(join);

  DijkstraInfo* it = left._frontier.find(join);
  TRI_ASSERT(it != nullptr);
  double startToJoin = it->weight();
  result._weight = startToJoin;
  while (it != nullptr && it->getKey() != left.center()) {
    // may throw
    guard.increase(Path::pathItemMemoryUsage());

    result._vertices.push_front(it->_pred);
    result._edges.push_front(it->_edge);
    result._weights.push_front(it->_weight);
    it = left._frontier.find(it->_pred);
  }
  // Initial vertex has weight 0
  result._weights.push_front(0);

  it = right._frontier.find(join);
  TRI_ASSERT(it != nullptr);
  double joinToEnd = it->weight();
  result._weight += joinToEnd;
  while (it != nullptr && it->getKey() != right.center()) {
    // may throw
    guard.increase(Path::pathItemMemoryUsage());

    result._vertices.emplace_back(it->_pred);
    result._edges.emplace_back(it->_edge);
    it = right._frontier.find(it->_pred);
    TRI_ASSERT(it != nullptr);  // should run into 0 weight before
    // cppcheck-suppress nullPointerRedundantCheck
    result._weights.emplace_back(startToJoin + (joinToEnd - it->_weight));
  }

  TRI_IF_FAILURE("TraversalOOMPath") {
    THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG);
  }

  // we don't commit the memory usage to the _resourceMonitor here
  // intentionally. we will do this later at the call site.
}

template<class ProviderType>
bool KShortestPathsFinder<ProviderType>::computeNextShortestPath(Path& result) {
  VertexSet forbiddenVertices;
  EdgeSet forbiddenEdges;
  TRI_ASSERT(!_shortestPaths.empty());
  auto const& lastShortestPath = _shortestPaths.back();

  for (size_t i = lastShortestPath._branchpoint;
       i + 1 < lastShortestPath.length(); ++i) {
    auto& spur = lastShortestPath._vertices[i];

    forbiddenVertices.clear();
    forbiddenEdges.clear();

    // Must not use vertices on the prefix
    for (size_t j = 0; j < i; ++j) {
      forbiddenVertices.emplace(lastShortestPath._vertices[j]);
    }

    // TODO: This can be done more efficiently by storing shortest
    //       paths in a prefix/postfix tree
    // previous paths with same prefix must not be
    for (auto const& p : _shortestPaths) {
      if (i >= p._edges.size()) {
        continue;
      }
      bool eq = true;
      for (size_t e = 0; e < i; ++e) {
        if (!p._edges[e].equals(lastShortestPath._edges.at(e))) {
          eq = false;
          break;
        }
      }
      if (eq) {
        forbiddenEdges.emplace(p._edges[i]);
      }
    }

    // abuse result variable for some intermediate calculations here...
    // the "real" result is only calculated at the very end of this method
    result.clear();

    // computeShortestPath will internally track memory usage for result,
    // however it won't commit the memory usage, because result is only
    // temporary. if we use the result for something else later, we will store
    // it in _candidatePaths and track its memory usage there
    if (computeShortestPath(spur, _end, forbiddenVertices, forbiddenEdges,
                            result)) {
      _candidate.clear();
      _candidate.append(lastShortestPath, 0, i);
      _candidate.append(result, 0, result.length() - 1);
      _candidate._branchpoint = i;

      auto it = find_if(
          _candidatePaths.begin(), _candidatePaths.end(),
          [this](Path const& v) { return v._weight >= _candidate._weight; });
      if (it == _candidatePaths.end() || !(*it == _candidate)) {
        // track memory usage for the path path
        ResourceUsageScope guard(_resourceMonitor, _candidate.memoryUsage());
        _candidatePaths.emplace(it, std::move(_candidate));

        // successful insert - now _candidatePaths has taken over responsibility
        // for memory usage tracking
        guard.steal();
      }
    }
  }

  // only used for function return value, which is currently ignored
  bool available = false;

  result.clear();

  if (!_candidatePaths.empty()) {
    auto const& p = _candidatePaths.front();
    result.append(p, 0, p.length() - 1);
    result._branchpoint = p._branchpoint;

    // count down the memory usage again
    _resourceMonitor.decreaseMemoryUsage(p.memoryUsage());
    _candidatePaths.pop_front();
    available = true;
  }
  return available;
}

template<class ProviderType>
bool KShortestPathsFinder<ProviderType>::getNextPath(Path& result) {
  result.clear();

  // This is for the first time that getNextPath is called
  if (_shortestPaths.empty()) {
    if (_start == _end) {
      TRI_ASSERT(!_start.empty());
      result._vertices.emplace_back(_start);
      result._weight = 0;
    } else {
      // Compute the first shortest path (i.e. the shortest path
      // between _start and _end!)
      computeShortestPath(_start, _end, {}, {}, result);
      result._branchpoint = 0;
    }
  } else {
    // We must not have _start == _end here, because we handle _start == _end
    computeNextShortestPath(result);
  }

  if (result.length() > 0) {
    _shortestPaths.emplace_back(result);
    _options.fetchVerticesCoordinator(result._vertices);

    TRI_IF_FAILURE("TraversalOOMPath") {
      THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG);
    }
  } else {
    // If we did not find a path, traversal is done.
    _traversalDone = true;
  }
  return !_traversalDone;
}

#ifdef ARANGODB_USE_GOOGLE_TESTS
template<class ProviderType>
bool KShortestPathsFinder<ProviderType>::getNextPathShortestPathResult(
    ShortestPathResult& result) {
  _tempPath.clear();

  result.clear();
  if (getNextPath(_tempPath)) {
    result._vertices = _tempPath._vertices;
    result._edges = _tempPath._edges;
    return true;
  }

  return false;
}
#endif

template<class ProviderType>
bool KShortestPathsFinder<ProviderType>::getNextPathAql(
    arangodb::velocypack::Builder& result) {
  if (getNextPath(_tempPath)) {
    result.clear();
    result.openObject();

    result.add("edges", VPackValue(VPackValueType::Array));
    for (auto const& it : _tempPath._edges) {
      _options.cache()->insertEdgeIntoResult(it, result);
    }
    result.close();  // Array

    result.add("vertices", VPackValue(VPackValueType::Array));
    for (auto const& it : _tempPath._vertices) {
      _options.cache()->appendVertex(it, result);
    }
    result.close();  // Array
    if (_options.useWeight()) {
      result.add("weight", VPackValue(_tempPath._weight));
    } else {
      // If not using weight, weight is defined as 1 per edge
      result.add("weight", VPackValue(_tempPath._edges.size()));
    }
    result.close();  // Object
    TRI_ASSERT(result.isClosed());
    return true;
  }

  return false;
}

template<class ProviderType>
bool KShortestPathsFinder<ProviderType>::skipPath() {
  return getNextPath(_tempPath);
}

template<class ProviderType>
size_t KShortestPathsFinder<ProviderType>::vertexCacheEntryMemoryUsage()
    const noexcept {
  return 16 /*arbitrary*/ + sizeof(typename decltype(_vertexCache)::key_type) +
         sizeof(typename decltype(_vertexCache)::value_type);
}

using SingleServerProviderStep = ::arangodb::graph::SingleServerProviderStep;
using ClusterProviderStep = ::arangodb::graph::ClusterProviderStep;

template class ::arangodb::graph::KShortestPathsFinder<
    SingleServerProvider<SingleServerProviderStep>>;

template class ::arangodb::graph::KShortestPathsFinder<
    ClusterProvider<ClusterProviderStep>>;


text:
openldap Cookbook
=================
Configures a server to be an OpenLDAP master, OpenLDAP replication slave, or OpenLDAP client.

Requirements
------------
### Platform
Ubuntu 10.04 was primarily used in testing this cookbook. Other Ubuntu versions and Debian may work. Red Hat and derivatives are not fully supported, but we take patches.

### Cookbooks
- openssh
- nscd
- openssl (for slave recipe)

Attributes
----------
Be aware of the attributes used by this cookbook and adjust the defaults for your environment where required, in `attributes/openldap.rb`.

### Client node attributes

- `openldap[:basedn]` - basedn
- `openldap[:server]` - the LDAP server fully qualified domain name, default `'ldap'.node[:domain]`.
- `openldap[:tls_enabled]` - specifies whether TLS will be used at all. Setting this to fals will result in your credentials being sent in clear-text.
- `openldap[:tls_checkpeer]` - specifies whether the client should verify the server's TLS certificate. Highly recommended to set tls_checkpeer to true for production uses in order to avoid man-in-the-middle attacks. Defaults to false for testing and backwards compatibility.
- `openldap[:pam_password]` - specifies the password change protocol to use. Defaults to md5.

### Server node attributes

- `openldap[:slapd_type]` - master | slave
- `openldap[:slapd_rid]` - unique integer ID, required if type is slave.
- `openldap[:slapd_master]` - hostname of slapd master, attempts to search for slapd_type master.
- `openldap[:manage_ssl]` - Whether or not this cookbook manages your SSL certificates.
   If set to `true`, this cookbook will expect your SSL certificates to be in files/default/ssl and will configure slapd appropriately.
   If set to `false`, you will need to provide your SSL certificates **prior** to this recipe being run. Be sure to set `openldap[:ssl_cert]` and `openldap[:ssl_key]` appropriately.
- `openldap[:ssl_cert]` - The full path to your SSL certificate.
- `openldap[:ssl_key]` - The full path to your SSL key.
- `openldap[:cacert]` - Your certificate authority's certificate (or intermediate authorities), if needed.

### Apache configuration attributes

Attributes useful for Apache authentication with LDAP.

COOK-128 - set automatically based on openldap[:server] and openldap[:basedn] if those attributes are set. openldap[:auth_bindpw] remains nil by default as a default value is not easily predicted.

- `openldap[:auth_type]` - determine whether binddn and bindpw are required (openldap no, ad yes)
- `openldap[:auth_url]` - AuthLDAPURL
- `openldap[:auth_binddn]` - AuthLDAPBindDN
- `openldap[:auth_bindpw]` - AuthLDAPBindPassword

Recipes
-------
### auth

Sets up the system for using openldap for user authentication.

### default

Empty recipe, you may want client.

### client

Install the openldap client packages.

### server

Set up openldap to be a slapd server. Use this if your environment would only have a single slapd server.

### master

Sets the `node['openldap']['slapd_type']` to master and then includes the `openldap::server` recipe.

### slave

Sets the `node['openldap']['slapd_type']` to slave, then includes the `openldap::server` recipe. If the node is running chef-solo, then the `node['openldap']['slapd_replpw']` and `node['openldap']['slapd_master']` attributes must be set in the JSON attributes file passed to `chef-solo`.

Usage
-----
Edit Rakefile variables for SSL certificate.

On client systems,

```ruby
include_recipe "openldap::auth"
```

This will get the required packages and configuration for client systems. This will be required on server systems as well, so this is a good candidate for inclusion in a base role.

On server systems, if there's only one LDAP server, then use the `openldap::server` recipe. If replication is required, use the `openldap::master` and `openldap::slave` recipes instead.

When initially installing a brand new LDAP master server on Ubuntu 8.10, the configuration directory may need to be removed and recreated before slapd will start successfully. Doing this programmatically may cause other issues, so fix the directory manually :-).

    $ sudo slaptest -F /etc/ldap/slapd.d
    str2entry: invalid value for attributeType objectClass #1 (syntax 1.3.6.1.4.1.1466.115.121.1.38)
    => ldif_enum_tree: failed to read entry for /etc/ldap/slapd.d/cn=config/olcDatabase={1}bdb.ldif
    slaptest: bad configuration directory!

For some reason slapd isn't getting started even though the service resource is notified to start, so start it manually.
Solution is to simply remove the configuration:

    $ sudo rm -rf /etc/ldap/slapd.d/ /etc/ldap/slapd.conf
    $ sudo chef-client
    $ sudo /etc/init.d/slapd start

Or in your wrapper cookbook rewind with ubuntu related fix:

    #Fix the wrong content of slapd.d dir on ubuntu 12.04
    chef_gem "chef-rewind"
    require 'chef/rewind'
    case node['platform']
    when 'ubuntu'
        rewind "package[slapd]" do
            response_file "slapd.seed"
            action :upgrade
            notifies :run, "execute[fix-ubuntu-slapdd]", :immediately
        end
    end
    #Removes slapd.d/cn=config and slapd.conf deployed from distribution. They will be re-created during the openldap recipe cooking.
    execute "fix-ubuntu-slapdd" do
        cmd =  "   test -d #{node['openldap']['dir']}/slapd.d && rm -rf #{node['openldap']['dir']}/slapd.d/cn=config"
        cmd << " ; test -d #{node['openldap']['dir']}/slapd.conf && rm -rf #{node['openldap']['dir']}/slapd.conf"
        cmd << " ; touch #{node['openldap']['dir']}/.fix-ubuntu-slapdd.done"
        command cmd
        ignore_failure true
        action :nothing
        not_if { ::File.exists?("#{node['openldap']['dir']}/.fix-ubuntu-slapdd.done") }
    end

### A note about certificates

Certificates created by the Rakefile are self signed. If you have a purchased CA, that can be used.

We provide two methods of managing SSL certificates, based off of `openldap[:manage_ssl]`.

If `openldap[:manage_ssl]` is `true`, then this cookbook manage your certificates itself, and will expect all certificates, intermediate certificates, and keys to be in the same file as defined in `openldap[:ssl_cert]`.

Use https://github.com/atomic-penguin/cookbook-certificate cookbook for advanced certificate deployment or use wrapper cookbook with following code to source ssl files from the wrapper cookbook folder structure:

    r = resources("cookbook_file[#{node['openldap']['ssl_cert']}]")
    r.cookbook('NAME OF YOUR WRAPPER COOKBOK')

    r = resources("cookbook_file[#{node['openldap']['ssl_key']}]")
    r.cookbook('NAME OF YOUR WRAPPER COOKBOK')

Be sure to update the certificate locations in the templates as required. We suggest copying this cookbook to the site-cookbooks for such modifications, so you can still pull from our master for updates, and then merge your changes in.

However, if `openldap[:manage_ssl]` is `false`, then you will need to place the SSL certificates on the client file system **prior** to this cookbook being run. This provides you the flexibility to provide the same set of SSL certificates for multiple uses as well as in one place across your environment, but you will need to manage them.
- Set `openldap[:ssl-cert]`, `openldap[:ssl_key]`, and `openldap[:cacert]` appropriately.
- Ensure that that user openldap can access these files. Watch out for apparmor and SELinux if you are placing your SSL certificates in a non-default location.

### New Directory
If installing for the first time, the initial directory needs to be created. Create an ldif file, and start populating the directory.

### Passwords
Set the password, openldap[:rootpw] for the rootdn in the node's attributes. This should be a password hash generated from slappasswd. The default slappasswd command on Ubuntu 8.10 and Mac OS X 10.5 will generate a SHA1 hash:

    $ slappasswd -s "secretsauce"
    {SSHA}6BjlvtSbVCL88li8IorkqMSofkLio58/

Set this by default in the attributes file, or on the node's entry in the webui.

License & Authors
-----------------
- Author:: Joshua Timberman (<joshua@opscode.com>)

```text
Copyright:: 2009, Opscode, Inc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```


text:
$(document).ready(function() {
	$('[data-toggle="tooltip"]').tooltip();
	$('[data-toggle="popover"]').popover({
		'html': true});

	$('input.batch-controll').change(function(){
		$('.input-batch').prop('checked', this.checked);
		$(".thumbnail").toggleClass('checked', this.checked);
	});
	$('.input-batch').change(function(){
		$(this).closest(".thumbnail").toggleClass('checked', this.checked);
	});

	$("a[href$='.jpg'],a[href$='.jpeg'],a[href$='.png'],a[href$='.gif'],a[href$='.JPG']").attr('rel', 'gallery').fancybox({
		padding: 0,
		helpers	: {
			thumbs: {
				width	: 50,
				height	: 50
			}
		}
	});

	Dropzone.options.imagesform = {
		addRemoveLinks: true,
		init: function() {
			this.on("complete", function() {
				if (this.getQueuedFiles().length == 0 && this.getUploadingFiles().length == 0)
					$('#imagesneedtobee').show();
			});
		}
	};

	$("a.hej").click(function(event){
		event.preventDefault();

		$.post("/admin/images/toggle/", { "this": $(this).attr('id') },
			function(data){
				console.log(data.name);
				console.log(data.time);
			},
			"json"
		);
	});

});

function imagecontrol(action, id)
{
	$.post("/admin/images/edit/",
		{
			'id': id,
			'action': action
		},
		function(data){
			console.log(data.action);
			console.log(data.id);
			console.log(data.status);

			$('#image-'+data.id+' img').toggleClass('opacity-70');
			$('#image-'+data.id+' button.toggle').toggleClass('btn-success');
			$('#image-'+data.id+' button.toggle i').toggleClass('icon-eye-open').toggleClass('icon-eye-close');
			var span = $('#image-'+data.id+' button.toggle span').text();
			$('#image-'+data.id+' button.toggle span').text(span == 'Synlig' ? 'Dold' : 'Synlig');
		},
		"json"
	);
}


text:
#ifndef included_stat_client_h
#define included_stat_client_h

#define STAT_VERSION_MAJOR     1
#define STAT_VERSION_MINOR     2

#include <stdint.h>
#include <unistd.h>
#include <vlib/counter_types.h>
#include <stdbool.h>
#include <vpp/stats/stat_segment_shared.h>

/* Default socket to exchange segment fd */
/* TODO: Get from runtime directory */
#define STAT_SEGMENT_SOCKET_FILE "/run/vpp/stats.sock"
#define STAT_SEGMENT_SOCKET_FILENAME "stats.sock"

typedef struct
{
  char *name;
  stat_directory_type_t type;
  union
  {
    double scalar_value;
    counter_t *error_vector;
    counter_t **simple_counter_vec;
    vlib_counter_t **combined_counter_vec;
    uint8_t **name_vector;
  };
} stat_segment_data_t;

typedef struct
{
  uint64_t current_epoch;
  stat_segment_shared_header_t *shared_header;
  stat_segment_directory_entry_t *directory_vector;
  ssize_t memory_size;
} stat_client_main_t;

extern stat_client_main_t stat_client_main;

stat_client_main_t *stat_client_get (void);
void stat_client_free (stat_client_main_t * sm);
int stat_segment_connect_r (const char *socket_name, stat_client_main_t * sm);
int stat_segment_connect (const char *socket_name);
void stat_segment_disconnect_r (stat_client_main_t * sm);
void stat_segment_disconnect (void);
uint8_t **stat_segment_string_vector (uint8_t ** string_vector,
				      const char *string);
int stat_segment_vec_len (void *vec);
void stat_segment_vec_free (void *vec);
uint32_t *stat_segment_ls_r (uint8_t ** patterns, stat_client_main_t * sm);
uint32_t *stat_segment_ls (uint8_t ** pattern);
stat_segment_data_t *stat_segment_dump_r (uint32_t * stats,
					  stat_client_main_t * sm);
stat_segment_data_t *stat_segment_dump (uint32_t * counter_vec);
stat_segment_data_t *stat_segment_dump_entry_r (uint32_t index,
						stat_client_main_t * sm);
stat_segment_data_t *stat_segment_dump_entry (uint32_t index);

void stat_segment_data_free (stat_segment_data_t * res);
double stat_segment_heartbeat_r (stat_client_main_t * sm);
double stat_segment_heartbeat (void);

char *stat_segment_index_to_name_r (uint32_t index, stat_client_main_t * sm);
char *stat_segment_index_to_name (uint32_t index);
uint64_t stat_segment_version (void);
uint64_t stat_segment_version_r (stat_client_main_t * sm);

typedef struct
{
  uint64_t epoch;
} stat_segment_access_t;

static inline void
stat_segment_access_start (stat_segment_access_t * sa,
			   stat_client_main_t * sm)
{
  stat_segment_shared_header_t *shared_header = sm->shared_header;
  sa->epoch = shared_header->epoch;
  while (shared_header->in_progress != 0)
    ;
  sm->directory_vector = (stat_segment_directory_entry_t *)
    stat_segment_pointer (sm->shared_header,
			  sm->shared_header->directory_offset);
}

static inline bool
stat_segment_access_end (stat_segment_access_t * sa, stat_client_main_t * sm)
{
  stat_segment_shared_header_t *shared_header = sm->shared_header;

  if (shared_header->epoch != sa->epoch || shared_header->in_progress)
    return false;
  return true;
}

#endif /* included_stat_client_h */

/*
 * fd.io coding-style-patch-verification: ON
 *
 * Local Variables:
 * eval: (c-set-style "gnu")
 * End:
 */


text:
<?php

namespace DDM\SmartyStreets;

class AddressValidationRequest extends AbstractRequest
{
    protected $endpoint  = 'street-address';
    protected $addresses = array();

    /**
     * Adds address to be validated
     * @param Address $address
     */
    public function addAddress(Address $address)
    {
      $this->addresses[] = $address;
    }

    /**
     * Getter for addresses
     * @return array
     */
    public function getAddresses()
    {
        return $this->addresses;
    }

    /**
     * Sends Address to be validated
     * @return AddressValidationResponse
     */
    public function validateAddresses()
    {
        $this->setBody($this->getSerializeAddresses());

        $response = $this->send();
        $response->setAddresses($this->getAddresses());
        return $response;
    }

    /**
     * Returns default AddressValidationReponse
     * @return AddressValidationResponse
     */
    public function getDefaultResponse()
    {
        return new AddressValidationResponse();
    }

    /**
     * Json encodes address objects
     * @return string json encoded array of address
     */
    public function getSerializeAddresses()
    {
        $addressesCollection = array();

        foreach ($this->addresses as $address) {
            $addressesCollection[] = $address->toArray();
        }

        return json_encode($addressesCollection);
    }
}


text:
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NUnit.Framework;

namespace FluentNHibernate.Testing.Cfg.Db
{
    [TestFixture]
    public class IngresConfigurationTester
    {
        [Test]
        public void Ingres_should_default_to_the_Ingres_dialect()
        {
            IngresConfiguration.Standard.ToProperties()["dialect"].ShouldEqual("NHibernate.Dialect.IngresDialect, " + typeof(ISession).Assembly.FullName);
        }

        [Test]
        public void Ingres_driver_should_default_to_the_Ingres_ClientDriver()
        {
            IngresConfiguration.Standard.ToProperties()["connection.driver_class"].ShouldEqual("NHibernate.Driver.IngresDriver, " + typeof(ISession).Assembly.FullName);
        }

        [Test]
        public void ConnectionString_is_added_to_the_configuration()
        {
            IngresConfiguration.Standard
                .ConnectionString(c => c
                    .Server("host")
                    .Database("vnode::db")
                    .Port("ii7")
                    .Username("tester")
                    .Password("secret"))
                .ToProperties()["connection.connection_string"].ShouldEqual("Host=host;Database=vnode::db;Port=ii7;User ID=tester;PWD=secret");
        }

        [Test]
        public void ConnectionStringSetExplicitly()
        {
            IngresConfiguration.Standard
                .ConnectionString(c => c
                    .Is("value"))
                .ToProperties().ShouldContain("connection.connection_string", "value");
        }

        [Test]
        public void ConnectionStringSetFromAppSetting()
        {
            IngresConfiguration.Standard
                .ConnectionString(c => c
                    .FromAppSetting("connectionString"))
                .ToProperties().ShouldContain("connection.connection_string", "a-connection-string");
        }

        [Test]
        public void ConnectionStringSetFromConnectionStrings()
        {
            IngresConfiguration.Standard
                .ConnectionString(c => c
                    .FromConnectionStringWithKey("main"))
                .ToProperties().ShouldContain("connection.connection_string", "connection string");
        }

        [Test]
        public void ShouldBeAbleToSpecifyConnectionStringDirectly()
        {
            IngresConfiguration.Standard
                .ConnectionString("conn")
                .ToProperties().ShouldContain("connection.connection_string", "conn");
        }
    }
}


text:
using namespace xercesc;

#include <cstdlib>
#include <iostream>
using namespace std;

void ConfigExtractor::characters (const XMLCh *const chars, const unsigned int length){}

#define EQ(str) XMLString::equals(qname, XStr(str))

ConfigExtractor::ConfigExtractor(): state(init), pi(), re(), vars(){
}

string ConfigExtractor::getAttribute(const Attributes& a, const char * str) const {
	string val;
	int index = a.getIndex(XStr(str));
	if(index == -1)return val;
	StrX s(a.getValue(index));
	const char * value = s;

	while(*value){
		index = XMLString::indexOf(value, '$');
		if(index != -1){
			if(index){
				val += string(value, index);
				value += index;
			}
			if(value[1] == '$'){
				val += '$';
				value += 2;
			}else if(value[1] == '{'){
				int closeIndex = XMLString::indexOf(value, '}');
				if(closeIndex == -1)break;
				string key(value + 2, closeIndex - 2);
				try{
					val += vars[key];
				}catch(Exception e){
					cout<<"Invalid variable: "<<key<<endl;
				}
				value += closeIndex + 1;
			}else{
				val += '$';
				value++;
			}
		}else break;
	}

	if(*value)val += value;
	return val;
}

Types ConfigExtractor::getType(const Attributes& a) const {
	StrX s(a.getValue(XStr("type")));
	const char * type = s;
	if(XMLString::equals(type, "read"))return t_read;
	if(XMLString::equals(type, "exec"))return t_exec;
	if(XMLString::equals(type, "any"))return t_any;
	throw Exception("ConfigFile: Invalid type specified");
}

void ConfigExtractor::startElement (const XMLCh *const uri, const XMLCh *const localname, const XMLCh *const qname, const Attributes &attrs){
	StrX s = StrX(qname);
	const char * e = s;
	switch(state){
		case init:{
			if(EQ("variable")){
				string name = getAttribute(attrs, "name");
				string value = getAttribute(attrs, "value");
				cout<<"Adding variable: "<<name<<": "<<value<<endl;
				vars.set(name,value);
			}else if(EQ("ServerRoot"))ConfigManager::serverRoot = getAttribute(attrs,"value");
			else if(EQ("port"))ConfigManager::port = atoi(getAttribute(attrs,"value").c_str());
			else if(EQ("plugin")){
				state = plugin;
				ConfigManager::pInfo.push_back(PluginInfo());
				PluginInfo& last = ConfigManager::pInfo.back();
				last.setType(getType(attrs));
				string name = getAttribute(attrs, "name");
				last.setName(name);
				PluginInfo * ptr = &last;
				pi.set(name, ptr);
			}else if(EQ("handler")){
				ConfigManager::handlers.push_back(Handler());
				Handler& h = ConfigManager::handlers.back();
				h.setMatch(getAttribute(attrs, "match"));
				string name = getAttribute(attrs, "plugin");
				try{
					const PluginInfo * p = pi[name];
					h.setPluginInfo(p);
				}catch(Exception e){
					string s("Unknown plugin ");
					s += name;
					throw Exception(s);
				}
			}else if(EQ("VirtualDir")){
				state = vdir;
				ConfigManager::vDirs.push_back(VirtualDirectory());
				VirtualDirectory& v = ConfigManager::vDirs.back();
				v.setType(getType(attrs));
				v.setVPath(getAttribute(attrs,"vpath"));
				v.setRPath(getAttribute(attrs,"rpath"));
				string name = getAttribute(attrs, "realm");
				if(name == "")break;
				try{
					const Realm * r = re[name];
					v.setRealm(r);
				}catch(Exception e){
					string s("Unknown realm ");
					s += name;
					throw Exception(s);
				}
			}else if(EQ("Realm")){
				state = realm;
				ConfigManager::realms.push_back(Realm());
				Realm& r = ConfigManager::realms.back();
				string name = getAttribute(attrs, "name");
				r.setName(name);
				Realm * ptr = &r;
				re.set(name, ptr);
			}else if(EQ("error")){
				ConfigManager::errHandler.setErrorFile(getAttribute(attrs,"no"),
					getAttribute(attrs,"file"));
			}else if(EQ("index")){
				ConfigManager::indexFiles.push_back(getAttribute(attrs,"file"));
			}
			break;
		}case realm:{
			Realm& last = ConfigManager::realms.back();
			if(EQ("user"))
				last.addUser(getAttribute(attrs,"name"), getAttribute(attrs,"password"));
			break;
		}case vdir:{
			if(EQ("handler")){
				VirtualDirectory& last = ConfigManager::vDirs.back();
				Handler h;
				h.setMatch(getAttribute(attrs, "match"));
				string name = getAttribute(attrs, "plugin");
				try{
					const PluginInfo * p = pi[name];
					h.setPluginInfo(p);
				}catch(Exception e){
					string s("Unknown plugin ");
					s += name;
					throw Exception(s);
				}
				last.addHandler(h);
			}
			break;
		}case plugin:{
			PluginInfo& last = ConfigManager::pInfo.back();
			if(EQ("file"))last.setPath(getAttribute(attrs, "path"));
			else if(EQ("conf-file"))last.setConfig(getAttribute(attrs, "conf-file"));
			break;
		}
	}
}

void ConfigExtractor::endElement (const XMLCh *const uri, const XMLCh *const localname, const XMLCh *const qname){
	switch(state){
		case realm:
			if(XMLString::equals(qname, XStr("Realm"))) state = init;
			break;
		case vdir:
			if(XMLString::equals(qname, XStr("VirtualDir"))) state = init;
			break;
		case plugin:
			if(XMLString::equals(qname, XStr("plugin"))) state = init;
			break;
	}
}

void ConfigExtractor::extract(){
	cout<<VAR_HTTP_EXEC_DIR<<" "<<ConfigManager::server_dir<<endl;
	cout<<VAR_HTTP_CONFIG_DIR<<" "<<ConfigManager::config_dir<<endl;

	vars.set(string(VAR_HTTP_EXEC_DIR), ConfigManager::server_dir);
	vars.set(string(VAR_HTTP_CONFIG_DIR), ConfigManager::config_dir);
	SAX2XMLReader * reader;

	XMLPlatformUtils::Initialize();
	reader = XMLReaderFactory::createXMLReader();

	reader->setContentHandler(this);
	reader->setExitOnFirstFatalError(true);
	reader->setFeature(XMLUni::fgSAX2CoreValidation, false);

	string configFile = ConfigManager::config_dir + "config.xml";
	cout<<"Parsing file: "<<configFile<<endl;
	reader->parse(configFile.c_str());

	delete reader;
	XMLPlatformUtils::Terminate();

	ConfigManager::vDirs.sort();
}


text:
"""
.. module: lemur.plugins.lemur_email.plugin
    :platform: Unix
    :copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
    :license: Apache, see LICENSE for more details.

.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
import boto3
from flask import current_app
from flask_mail import Message
from sentry_sdk import capture_exception

from lemur.constants import EMAIL_RE, EMAIL_RE_HELP
from lemur.extensions import smtp_mail
from lemur.exceptions import InvalidConfiguration

from lemur.plugins.bases import ExpirationNotificationPlugin
from lemur.plugins import lemur_email as email

from lemur.plugins.lemur_email.templates.config import env
from lemur.plugins.utils import get_plugin_option

def render_html(template_name, options, certificates):
    """
    Renders the html for our email notification.

    :param template_name:
    :param options:
    :param certificates:
    :return:
    """
    message = {"options": options, "certificates": certificates}
    template = env.get_template("{}.html".format(template_name))
    return template.render(
        dict(message=message, hostname=current_app.config.get("LEMUR_HOSTNAME"))
    )

def send_via_smtp(subject, body, targets):
    """
    Attempts to deliver email notification via SMTP.

    :param subject:
    :param body:
    :param targets:
    :return:
    """
    msg = Message(
        subject, recipients=targets, sender=current_app.config.get("LEMUR_EMAIL")
    )
    msg.body = ""  # kinda a weird api for sending html emails
    msg.html = body
    smtp_mail.send(msg)

def send_via_ses(subject, body, targets, **kwargs):
    """
    Attempts to deliver email notification via SES service.
    :param subject:
    :param body:
    :param targets:
    :return:
    """
    email_tags = kwargs.get("email_tags")
    if not email_tags:
        email_tags = {}
    email_tags["subject"] = subject
    email_tags["targets"] = targets

    ses_region = current_app.config.get("LEMUR_SES_REGION", "us-east-1")
    client = boto3.client("ses", region_name=ses_region)
    source_arn = current_app.config.get("LEMUR_SES_SOURCE_ARN")
    args = {
        "Source": current_app.config.get("LEMUR_EMAIL"),
        "Destination": {"ToAddresses": targets},
        "Message": {
            "Subject": {"Data": subject, "Charset": "UTF-8"},
            "Body": {"Html": {"Data": body, "Charset": "UTF-8"}},
        },
    }
    if source_arn:
        args["SourceArn"] = source_arn
    response = client.send_email(**args)
    try:
        # logging information about the email (particularly the message ID) allows reconcilitation with SES bounce notifications
        message_id = response["MessageId"]
        email_tags["ses_message_id"] = message_id
        current_app.logger.info(f"Sent SES email: {message_id}", extra={"SES-Email": email_tags})
    except Exception:
        current_app.logger.error("Unable to log message ID of sent SES email", extra={"SES-Email": email_tags},
                                 exc_info=True)
        capture_exception()

class EmailNotificationPlugin(ExpirationNotificationPlugin):
    title = "Email"
    slug = "email-notification"
    description = "Sends expiration email notifications"
    version = email.VERSION

    author = "Kevin Glisson"
    author_url = "https://github.com/netflix/lemur"

    additional_options = [
        {
            "name": "recipients",
            "type": "str",
            "required": True,
            "validation": EMAIL_RE.pattern,
            "helpMessage": EMAIL_RE_HELP,
        }
    ]

    def __init__(self, *args, **kwargs):
        """Initialize the plugin with the appropriate details."""
        sender = current_app.config.get("LEMUR_EMAIL_SENDER", "ses").lower()

        if sender not in ["ses", "smtp"]:
            raise InvalidConfiguration("Email sender type {0} is not recognized.")

    @staticmethod
    def send(notification_type, message, targets, options, **kwargs):
        if not targets:
            return

        readable_notification_type = ' '.join(map(lambda x: x.capitalize(), notification_type.split('_')))
        subject = f"Lemur: {readable_notification_type} Notification"

        body = render_html(notification_type, options, message)

        s_type = current_app.config.get("LEMUR_EMAIL_SENDER", "ses").lower()

        if s_type == "ses":
            send_via_ses(subject, body, targets, **kwargs)

        elif s_type == "smtp":
            send_via_smtp(subject, body, targets)

    @staticmethod
    def get_recipients(options, additional_recipients, **kwargs):
        notification_recipients = get_plugin_option("recipients", options)
        if notification_recipients:
            notification_recipients = notification_recipients.split(",")

        return list(set(notification_recipients + additional_recipients))


text:
  (G_TYPE_CHECK_INSTANCE_CAST((obj), native_jones_plugin_get_type(), \
                              NativeJonesPlugin))

struct _NativeJonesPlugin {
  GObject parent_instance;
};

G_DEFINE_TYPE(NativeJonesPlugin, native_jones_plugin, g_object_get_type())

// Called when a method call is received from Flutter.
static void native_jones_plugin_handle_method_call(
    NativeJonesPlugin* self,
    FlMethodCall* method_call) {
  g_autoptr(FlMethodResponse) response = nullptr;

  const gchar* method = fl_method_call_get_name(method_call);

  if (strcmp(method, "getPlatformVersion") == 0) {
    struct utsname uname_data = {};
    uname(&uname_data);
    g_autofree gchar *version = g_strdup_printf("Linux %s", uname_data.version);
    g_autoptr(FlValue) result = fl_value_new_string(version);
    response = FL_METHOD_RESPONSE(fl_method_success_response_new(result));
  } else {
    response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new());
  }

  fl_method_call_respond(method_call, response, nullptr);
}

static void native_jones_plugin_dispose(GObject* object) {
  G_OBJECT_CLASS(native_jones_plugin_parent_class)->dispose(object);
}

static void native_jones_plugin_class_init(NativeJonesPluginClass* klass) {
  G_OBJECT_CLASS(klass)->dispose = native_jones_plugin_dispose;
}

static void native_jones_plugin_init(NativeJonesPlugin* self) {}

static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call,
                           gpointer user_data) {
  NativeJonesPlugin* plugin = NATIVE_JONES_PLUGIN(user_data);
  native_jones_plugin_handle_method_call(plugin, method_call);
}

void native_jones_plugin_register_with_registrar(FlPluginRegistrar* registrar) {
  NativeJonesPlugin* plugin = NATIVE_JONES_PLUGIN(
      g_object_new(native_jones_plugin_get_type(), nullptr));

  g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
  g_autoptr(FlMethodChannel) channel =
      fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar),
                            "native_jones",
                            FL_METHOD_CODEC(codec));
  fl_method_channel_set_method_call_handler(channel, method_call_cb,
                                            g_object_ref(plugin),
                                            g_object_unref);

  g_object_unref(plugin);
}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Abstract.AbstractTests.ServiceLog;

namespace System.Abstract.Tests.ServiceLog.Integration
{
    [TestClass]
    public class EmptyServiceLogTest : AbstractServiceLogTest
    {
        protected override IServiceLog CreateServiceLog() =>
            new ServiceLogManager.EmptyServiceLog();
    }
}


text:
package org.apache.cloudstack.api.command.user.network;

import org.apache.log4j.Logger;

import org.apache.cloudstack.acl.SecurityChecker.AccessType;
import org.apache.cloudstack.api.ACL;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseAsyncCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.IPAddressResponse;
import org.apache.cloudstack.api.response.NetworkResponse;
import org.apache.cloudstack.api.response.SuccessResponse;

import com.cloud.event.EventTypes;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.Network;

@APICommand(name = "restartNetwork",
            description = "Restarts the network; includes 1) restarting network elements - virtual routers, DHCP servers 2) reapplying all public IPs 3) reapplying loadBalancing/portForwarding rules",
        responseObject = IPAddressResponse.class, entityType = {Network.class},
            requestHasSensitiveInfo = false,
            responseHasSensitiveInfo = false)
public class RestartNetworkCmd extends BaseAsyncCmd {
    public static final Logger s_logger = Logger.getLogger(RestartNetworkCmd.class.getName());
    private static final String s_name = "restartnetworkresponse";

    /////////////////////////////////////////////////////
    //////////////// API parameters /////////////////////
    /////////////////////////////////////////////////////
    @ACL(accessType = AccessType.OperateEntry)
    @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = NetworkResponse.class, required = true, description = "The ID of the network to restart.")
    private Long id;

    @Parameter(name = ApiConstants.CLEANUP, type = CommandType.BOOLEAN, required = false, description = "If cleanup old network elements")
    private Boolean cleanup;

    /////////////////////////////////////////////////////
    /////////////////// Accessors ///////////////////////
    /////////////////////////////////////////////////////

    public Long getNetworkId() {
        Network network = _networkService.getNetwork(id);
        if (network == null) {
            throw new InvalidParameterValueException("Unable to find network by ID " + id);
        } else {
            return network.getId();
        }
    }

    public Boolean getCleanup() {
        if (cleanup != null) {
            return cleanup;
        }
        return true;
    }

    /////////////////////////////////////////////////////
    /////////////// API Implementation///////////////////
    /////////////////////////////////////////////////////

    @Override
    public String getCommandName() {
        return s_name;
    }

    public static String getResultObjectName() {
        return "addressinfo";
    }

    @Override
    public void execute() throws ResourceUnavailableException, ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
        boolean result = _networkService.restartNetwork(this, getCleanup());
        if (result) {
            SuccessResponse response = new SuccessResponse(getCommandName());
            setResponseObject(response);
        } else {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to restart network");
        }
    }

    @Override
    public String getSyncObjType() {
        return BaseAsyncCmd.networkSyncObject;
    }

    @Override
    public Long getSyncObjId() {
        return id;
    }

    @Override
    public String getEventDescription() {
        return "Restarting network: " + getNetworkId();
    }

    @Override
    public String getEventType() {
        return EventTypes.EVENT_NETWORK_RESTART;
    }

    @Override
    public long getEntityOwnerId() {
        Network network = _networkService.getNetwork(id);
        if (network == null) {
            throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist");
        } else {
            return _networkService.getNetwork(id).getAccountId();
        }
    }
}


text:
package ic2.api.energy.tile;

/**
 * Allows a tile entity (mostly a generator) to emit energy.
 *
 * See ic2/api/energy/usage.txt for an overall description of the energy net api.
 */
public interface IEnergySource extends IEnergyEmitter {
	/**
	 * Energy output provided by the source this tick.
	 * This is typically Math.min(stored energy, max output/tick).
	 *
	 * @note Modifying the energy net from this method is disallowed.
	 *
	 * @return Energy offered this tick
	 */
	double getOfferedEnergy();

	/**
	 * Draw energy from this source's buffer.
	 *
	 * If the source doesn't have a buffer, this is a no-op.
	 *
	 * @param amount amount of EU to draw, may be negative
	 */
	void drawEnergy(double amount);

	/**
	 * Determine the tier of this energy source.
	 * 1 = LV, 2 = MV, 3 = HV, 4 = EV etc.
	 *
	 * @note Modifying the energy net from this method is disallowed.
	 *
	 * @return tier of this energy source
	 */
	int getSourceTier();
}


text:
import {renderToString} from "react-dom/server";
import {merge} from "lodash";
import {svg} from "@patternplate/components";

export default (state, action) => {
  let copy;

  switch (action.type) {
    case "LOAD_SCHEMA_SUCCESS": {
      copy = merge({}, action.payload.config);
      break;
    }
    default: {
      copy = merge({}, state);
    }
  }

  if (!copy.hasOwnProperty("ui")) {
    copy.ui = {};
  }

  const {ui} = copy;

  ui.renderedLogo = ui.hasOwnProperty("logo")
    ? renderToString(svg.render(svg.sanitize(svg.purge([svg.parse(ui.logo)]))[0]))
    : "";

  const favicon = ui.favicon || ui.logo;

  ui.renderedFavicon = global.document && favicon
    ? svg.png(favicon)
    : Promise.resolve("");

  return copy;
};


text:
import React, { Component } from 'react';
import { Link, browserHistory } from 'react-router'

import Store from '../lib/store';
var store = new Store();

class Signup extends Component {
  constructor(props) {
    super(props);

    this.state =  {
      username: '',
      password: '',
      confirmPass: '',
      errorMessage: '',
      messageVisible: false,
    };
  }

  signup() {
    console.log('signing up...');
    if (this.state.password !== this.state.confirmPass ) {
      return this.setState({errorMessage: 'Your passwords do not match', messageVisible: true});
    }

    store.createUser(this.state.username, this.state.password, (error, user) => {
      if (error) {
        this.setState({errorMessage: error.message, messageVisible: true});
      } else {
        this.props.history.push('/notes');
      }
    });
  }

  render() {
    return (

                <button className="delete" onClick={event => this.setState({messageVisible: false})}></button>
                {this.state.errorMessage}

              <input name="username" id="title" type="text" placeholder="Username" onChange={event => this.setState({username: event.target.value})} />

              <input name="password" id="password" type="password" placeholder="Password" onChange={event => this.setState({password: event.target.value})} />

              <input name="confirm_pass" id="confirm_pass" type="password" placeholder="Confirm Password" onChange={event => this.setState({confirmPass: event.target.value})} />

              <input type="submit" className="button is-success" value="Sign Up" onClick={this.signup.bind(this)} />

              <Link to="/login">I have an account...</Link>

    )
  }
}

export default Signup;


text:
package com.alibaba.json.bvt.bug;

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

import org.junit.Assert;
import junit.framework.TestCase;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class Bug_for_lenolix_10 extends TestCase {

    public void test_for_objectKey() throws Exception {
        Map<Integer, User> map2 = new HashMap<Integer, User>();
        User user = new User();
        user.setId(1);
        user.setIsBoy(true);
        user.setName("leno.lix");
        // user.setBirthDay(simpleDateFormat.parse("2012-03-07 22:38:21 CST"));
        // user.setGmtCreate(new java.sql.Date(simpleDateFormat.parse("2012-02-03 22:38:21 CST")
        // .getTime()));
        map2.put(1, user);
        String mapJson2 = JSON.toJSONString(map2, SerializerFeature.WriteClassName, SerializerFeature.WriteMapNullValue);
        System.out.println(mapJson2);
        Object object2 = JSON.parse(mapJson2);

    }

    public static class User {

        private int     id;
        private Boolean isBoy;
        private String  name;

        public int getId() {
            return id;
        }

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

        public Boolean getIsBoy() {
            return isBoy;
        }

        public void setIsBoy(Boolean isBoy) {
            this.isBoy = isBoy;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

    }
}


text:
// NOTE: no native object detectors are currently provided or used by the code
// in this directory. This class remains mainly for historical reasons.
// Detection in the TF demo is done through TensorFlowMultiBoxDetector.java.

#include "tensorflow/tools/android/test/jni/object_tracking/object_detector.h"

namespace tf_tracking {

// This is here so that the vtable gets created properly.
ObjectDetectorBase::~ObjectDetectorBase() {}

}  // namespace tf_tracking


text:
package org.jfree.ui;

import java.io.File;
import javax.swing.filechooser.FileFilter;

/**
 * A filter for JFileChooser that filters files by extension.
 *
 * @author David Gilbert
 */
public class ExtensionFileFilter extends FileFilter {

    /** A description for the file type. */
    private String description;

    /** The extension (for example, "png" for *.png files). */
    private String extension;

    /**
     * Standard constructor.
     *
     * @param description  a description of the file type;
     * @param extension  the file extension;
     */
    public ExtensionFileFilter(final String description, final String extension) {
        this.description = description;
        this.extension = extension;
    }

    /**
     * Returns true if the file ends with the specified extension.
     *
     * @param file  the file to test.
     *
     * @return A boolean that indicates whether or not the file is accepted by the filter.
     */
    public boolean accept(final File file) {

        if (file.isDirectory()) {
            return true;
        }

        final String name = file.getName().toLowerCase();
        if (name.endsWith(this.extension)) {
            return true;
        }
        else {
            return false;
        }

    }

    /**
     * Returns the description of the filter.
     *
     * @return a description of the filter.
     */
    public String getDescription() {
        return this.description;
    }

}


text:
package com.bkahlert.nebula.information;

import org.apache.log4j.Logger;
import org.eclipse.jface.text.AbstractHoverInformationControlManager;
import org.eclipse.jface.util.Geometry;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Listener;

import com.bkahlert.nebula.InformationManagerSourceProvider;

/**
 * Instances of this class are watching a {@link Control} and consult a
 * {@link ISubjectInformationProvider} for information to be displayed in a
 * small popup window.
 *
 * @author bkahlert
 *
 * @param <CONTROL>
 * @param <INFORMATION>
 */
public class InformationControlManager<CONTROL extends Control, INFORMATION>
		extends AbstractHoverInformationControlManager {

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

	private static Listener f2Filter = null;

	@SuppressWarnings("restriction")
	private static void activateF2Filter() {
		if (f2Filter != null) {
			return;
		}
		f2Filter = event -> {
			if (event.keyCode != SWT.F2) {
				return;
			}
			try {
				InformationControlManagerUtils.getCurrentManager()
						.getInternalAccessor().replaceInformationControl(false);
			} catch (NullPointerException e1) {
			} catch (Exception e2) {
				LOGGER.error("Error while enhancing "
						+ InformationControl.class.getSimpleName());
			}
		};
		Display.getCurrent().addFilter(SWT.KeyDown, f2Filter);
	}

	private ISubjectInformationProvider<CONTROL, INFORMATION> subjectInformationProvider;
	private final Class<INFORMATION> informationClass;

	private final StickyHoverManager<INFORMATION> replacer;
	private Rectangle lastSubjectArea;

	@SuppressWarnings("restriction")
	public InformationControlManager(
			Class<INFORMATION> informationClass,
			InformationControlCreator<INFORMATION> creator,
			ISubjectInformationProvider<CONTROL, INFORMATION> subjectInformationProvider) {
		super(creator);
		this.replacer = new StickyHoverManager<INFORMATION>(creator);
		this.getInternalAccessor().setInformationControlReplacer(this.replacer);
		this.subjectInformationProvider = subjectInformationProvider;
		this.informationClass = informationClass;
	}

	public Class<INFORMATION> getInformationClass() {
		return this.informationClass;
	}

	@Override
	public void install(Control subjectControl) {
		super.install(subjectControl);
		this.replacer.install(subjectControl);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected CONTROL getSubjectControl() {
		return (CONTROL) super.getSubjectControl();
	}

	@Override
	public void showInformation() {
		super.showInformation();
		System.err.println(this.getInformationControl());
	}

	/**
	 * Returns whether the standard or enriched version of the
	 * {@link InformationControl} is shown.
	 *
	 * @return
	 */
	public boolean isShowingEnriched() {
		@SuppressWarnings("restriction")
		InformationControl<?> enhancedControl = (InformationControl<?>) this.replacer
				.getCurrentInformationControl2();
		return enhancedControl != null && enhancedControl.isVisible();
	}

	/**
	 * In contrast to {@link #showInformation()} this method does not show what
	 * the {@link #subjectInformationProvider} returns but what you provide.
	 *
	 * @param information
	 */
	@SuppressWarnings("restriction")
	public void setInformation(INFORMATION information) {
		Rectangle subjectArea = new Rectangle(this.lastSubjectArea.x,
				this.lastSubjectArea.y, this.lastSubjectArea.width,
				this.lastSubjectArea.height);
		if (this.isShowingEnriched()) {
			@SuppressWarnings({ "unchecked" })
			InformationControl<CONTROL> informationControl = (InformationControl<CONTROL>) this.replacer
					.getCurrentInformationControl2();
			informationControl.setInput(information);
			if (!informationControl.hasContents()) {
				return;
			}

			if (informationControl != null) {
				Point sizeConstraints = this.computeSizeConstraints(
						this.getSubjectControl(), subjectArea,
						informationControl);
				Rectangle trim = informationControl.computeTrim();
				sizeConstraints.x += trim.width;
				sizeConstraints.y += trim.height;
				informationControl.setSizeConstraints(sizeConstraints.x,
						sizeConstraints.y);

				Point size = null;
				Point location = null;
				Rectangle bounds = this.restoreInformationControlBounds();

				if (bounds != null) {
					if (bounds.x > -1 && bounds.y > -1) {
						location = Geometry.getLocation(bounds);
					}

					if (bounds.width > -1 && bounds.height > -1) {
						size = Geometry.getSize(bounds);
					}
				}

				if (size == null) {
					size = informationControl.computeSizeHint();
				}

				// if (this.fEnforceAsMinimalSize) {
				// size = Geometry.max(size, sizeConstraints);
				// }
				// if (this.fEnforceAsMaximalSize) {
				// size = Geometry.min(size, sizeConstraints);
				// }

				if (location == null) {
					location = this.computeInformationControlLocation(
							subjectArea, size);
				}

				Rectangle controlBounds = Geometry.createRectangle(location,
						size);
				InformationControlManagerUtils.cropToClosestMonitor(this
						.getSubjectControl().getDisplay(), controlBounds);
				location = Geometry.getLocation(controlBounds);
				size = Geometry.getSize(controlBounds);
				informationControl.setLocation(location);
				informationControl.setSize(size.x, size.y);

				this.showInformationControl(subjectArea);
			}
			this.getInternalAccessor().replaceInformationControl(false);
		} else {
			this.setInformation(information, subjectArea);
		}
	}

	@Override
	protected void computeInformation() {
		InformationManagerSourceProvider.managerChanged(this);

		this.lastSubjectArea = this.calculateSubjectArea();
		INFORMATION information = this.subjectInformationProvider
				.getInformation();

		this.setInformation(information, this.lastSubjectArea);
	}

	/**
	 * Calculates the subject area based on the current cursor location.
	 *
	 * @return
	 */
	protected Rectangle calculateSubjectArea() {
		Point hoverArea = this.subjectInformationProvider.getHoverArea();
		if (hoverArea == null) {
			hoverArea = new Point(10, 10);
		}
		Point mouseLocation = Display.getCurrent().getCursorLocation();
		Rectangle bounds = Geometry.toControl(this.getSubjectControl(),
				new Rectangle(mouseLocation.x - hoverArea.x / 2,
						mouseLocation.y - hoverArea.y / 2, hoverArea.x,
						hoverArea.y));
		return bounds;
	}

	@SuppressWarnings("deprecation")
	@Override
	public void setEnabled(boolean enabled) {
		boolean was = this.isEnabled();
		super.setEnabled(enabled);
		boolean is = this.isEnabled();
		if (was != is) {
			if (is) {
				if (this.subjectInformationProvider != null) {
					this.subjectInformationProvider.register(this
							.getSubjectControl());
				}
				activateF2Filter();
				// Display.getCurrent().addFilter(SWT.KeyDown, this.listener);
			} else {
				// Display.getCurrent().removeFilter(SWT.KeyDown,
				// this.listener);
				if (this.subjectInformationProvider != null) {
					this.subjectInformationProvider.unregister(this
							.getSubjectControl());
				}
			}
		}
	}

	@Override
	public void dispose() {
		// Display.getCurrent().removeFilter(SWT.KeyDown, this.listener);
		if (this.subjectInformationProvider != null) {
			this.subjectInformationProvider
					.unregister(this.getSubjectControl());
			this.subjectInformationProvider = null;
		}
		super.dispose();
	}

}


text:
<Record>
<Term>Rapaflo</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<SemanticType>Organic Chemical</SemanticType>
<PrimarySemanticType>Pharmacologic Substance</PrimarySemanticType>
<Synonym>Silodosin</Synonym>
<Source>FDA Registry</Source>
</Record>


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.sakaiproject.mailarchive</groupId>
        <artifactId>mailarchive</artifactId>
        <version>12-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <name>sakai-mailarchive-subetha</name>
    <groupId>org.sakaiproject.mailarchive</groupId>
    <artifactId>sakai-mailarchive-subetha</artifactId>
    <organization>
        <name>Sakai Foundation</name>
        <url>http://sakaiproject.org/</url>
    </organization>
    <inceptionYear>2014</inceptionYear>
    <packaging>sakai-component</packaging>

    <properties>
        <deploy.target>components</deploy.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.sakaiproject.kernel</groupId>
            <artifactId>sakai-kernel-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.sakaiproject.kernel</groupId>
            <artifactId>sakai-component-manager</artifactId>
        </dependency>
        <dependency>
            <groupId>org.sakaiproject.kernel</groupId>
            <artifactId>sakai-kernel-util</artifactId>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>sakai-mailarchive-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.sakaiproject.message</groupId>
            <artifactId>sakai-message-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.subethamail</groupId>
            <artifactId>subethasmtp</artifactId>
            <version>3.1.7</version>
        </dependency>
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>1.9.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>${basedir}/src/bundle</directory>
                <includes>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>${basedir}/src/test</directory>
                <includes>
                    <include>**/*.txt</include>
                    <include>**/log4j.properties</include>
                </includes>
            </testResource>
        </testResources>
    </build>
</project>


text:
package com.github.phiz71.vertx.swagger.router.auth;

import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.AuthProvider;
import io.vertx.ext.auth.User;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.Session;
import io.vertx.ext.web.handler.AuthHandler;
import io.vertx.ext.web.handler.impl.AuthHandlerImpl;

import static com.github.phiz71.vertx.swagger.router.auth.ApiKeyAuthHandler.Location.HEADER;
import static com.github.phiz71.vertx.swagger.router.auth.ApiKeyAuthHandler.Location.QUERY;

public class ApiKeyAuthHandler extends AuthHandlerImpl {

    public static final String API_KEY_NAME_PARAM = "name";
    public static final String API_KEY_VALUE_PARAM = "value";

    private final String name;
    private final ApiKeyAuthHandler.Location location;

    public enum Location {
        HEADER, QUERY;
    }

    public static AuthHandler create(AuthProvider authProvider, ApiKeyAuthHandler.Location location,
            String name) {
        return new ApiKeyAuthHandler(authProvider, location, name);
    }

    private ApiKeyAuthHandler(AuthProvider authProvider, ApiKeyAuthHandler.Location location,
            String name) {
        super(authProvider);
        this.location = location;
        this.name = name;
    }

    public void handle(RoutingContext context) {
        User user = context.user();
        if (user != null) {
            this.authorise(user, context);
        } else {
            HttpServerRequest request = context.request();

            String value = null;
            switch (this.location) {
                case QUERY:
                    value = request.getParam(this.name);
                    break;
                case HEADER:
                    value = request.headers().get(this.name);
                    break;
                default:
                    context.fail(401);
                    return;
            }

            JsonObject authInfo = new JsonObject().put(API_KEY_NAME_PARAM, this.name)
                    .put(API_KEY_VALUE_PARAM, value);

            this.authProvider.authenticate(authInfo, res -> {
                if (res.succeeded()) {
                    User authenticated = res.result();
                    context.setUser(authenticated);
                    Session session = context.session();
                    if (session != null) {
                        session.regenerateId();
                    }
                    this.authorise(authenticated, context);
                } else {
                    context.fail(401);
                }
            });
        }

    }
}


text:
<?xml version="1.0" ?>
<!--

-->
<constraint>
    <assertProductRatingSuccessSaveMessage module="Magento_Review">
        <severity>high</severity>
    </assertProductRatingSuccessSaveMessage>
    <assertProductRatingSuccessDeleteMessage module="Magento_Review">
        <severity>high</severity>
    </assertProductRatingSuccessDeleteMessage>
    <assertProductRatingInGrid module="Magento_Review">
        <severity>middle</severity>
    </assertProductRatingInGrid>
    <assertProductRatingNotInGrid module="Magento_Review">
        <severity>middle</severity>
    </assertProductRatingNotInGrid>
    <assertProductRatingInProductPage module="Magento_Review">
        <severity>middle</severity>
    </assertProductRatingInProductPage>
    <assertProductRatingNotInProductPage module="Magento_Review">
        <severity>middle</severity>
    </assertProductRatingNotInProductPage>
    <assertReviewSuccessSaveMessage module="Magento_Review">
        <severity>high</severity>
    </assertReviewSuccessSaveMessage>
    <assertReviewCreationSuccessMessage module="Magento_Review">
        <severity>high</severity>
    </assertReviewCreationSuccessMessage>
    <assertProductReviewInGrid module="Magento_Review">
        <severity>low</severity>
    </assertProductReviewInGrid>
    <assertProductRatingOnReviewPage module="Magento_Review">
        <severity>middle</severity>
    </assertProductRatingOnReviewPage>
    <assertProductRatingInProductPage module="Magento_Review">
        <severity>middle</severity>
    </assertProductRatingInProductPage>
    <assertProductReviewMassActionSuccessMessage module="Magento_Review">
        <severity>high</severity>
        <require>
            <reviewIndex class="Magento\Review\Test\Page\Adminhtml\ReviewIndex"/>
        </require>
    </assertProductReviewMassActionSuccessMessage>
    <assertProductReviewMassActionSuccessDeleteMessage module="Magento_Review">
        <severity>high</severity>
        <require>
            <reviewIndex class="Magento\Review\Test\Page\Adminhtml\ReviewIndex"/>
        </require>
    </assertProductReviewMassActionSuccessDeleteMessage>
    <assertProductReviewBackendSuccessSaveMessage module="Magento_Review">
        <severity>middle</severity>
    </assertProductReviewBackendSuccessSaveMessage>
    <assertProductReviewNotOnProductPage module="Magento_Review">
        <severity>middle</severity>
    </assertProductReviewNotOnProductPage>
    <assertProductReviewOnProductPage module="Magento_Review">
        <severity>middle</severity>
    </assertProductReviewOnProductPage>
    <assertProductReviewNotInGrid module="Magento_Review">
        <severity>low</severity>
    </assertProductReviewNotInGrid>
    <assertProductReviewInGridOnCustomerPage module="Magento_Review">
        <severity>low</severity>
    </assertProductReviewInGridOnCustomerPage>
</constraint>


text:
function thisinds = doStringMatch(ids, thisids)

thisinds = zeros(size(ids,1),1);
for i=1:numel(thisids)
    %myprintf(i, 100);
    thisinds(strcmp(thisids{i}, ids)) = 1;
end
%myprintfn;