text:
namespace base {

class DictionaryValue;
class FundamentalValue;
class ListValue;
class StringValue;
class Value;

typedef std::vector<Value*> ValueVector;
typedef std::map<std::string, Value*> ValueMap;

// The Value class is the base class for Values. A Value can be instantiated
// via the Create*Value() factory methods, or by directly creating instances of
// the subclasses.
//
// See the file-level comment above for more information.
class BASE_EXPORT Value {
 public:
  enum Type {
    TYPE_NULL = 0,
    TYPE_BOOLEAN,
    TYPE_INTEGER,
    TYPE_DOUBLE,
    TYPE_STRING,
    TYPE_BINARY,
    TYPE_DICTIONARY,
    TYPE_LIST
    // Note: Do not add more types. See the file-level comment above for why.
  };

  virtual ~Value();

  static Value* CreateNullValue();
  // DEPRECATED: Do not use the following 5 functions. Instead, use
  // new FundamentalValue or new StringValue.
  static FundamentalValue* CreateBooleanValue(bool in_value);
  static FundamentalValue* CreateIntegerValue(int in_value);
  static FundamentalValue* CreateDoubleValue(double in_value);
  static StringValue* CreateStringValue(const std::string& in_value);
  static StringValue* CreateStringValue(const string16& in_value);

  // Returns the type of the value stored by the current Value object.
  // Each type will be implemented by only one subclass of Value, so it's
  // safe to use the Type to determine whether you can cast from
  // Value* to (Implementing Class)*.  Also, a Value object never changes
  // its type after construction.
  Type GetType() const { return type_; }

  // Returns true if the current object represents a given type.
  bool IsType(Type type) const { return type == type_; }

  // These methods allow the convenient retrieval of the contents of the Value.
  // If the current object can be converted into the given type, the value is
  // returned through the |out_value| parameter and true is returned;
  // otherwise, false is returned and |out_value| is unchanged.
  virtual bool GetAsBoolean(bool* out_value) const;
  virtual bool GetAsInteger(int* out_value) const;
  virtual bool GetAsDouble(double* out_value) const;
  virtual bool GetAsString(std::string* out_value) const;
  virtual bool GetAsString(string16* out_value) const;
  virtual bool GetAsList(ListValue** out_value);
  virtual bool GetAsList(const ListValue** out_value) const;
  virtual bool GetAsDictionary(DictionaryValue** out_value);
  virtual bool GetAsDictionary(const DictionaryValue** out_value) const;
  // Note: Do not add more types. See the file-level comment above for why.

  // This creates a deep copy of the entire Value tree, and returns a pointer
  // to the copy.  The caller gets ownership of the copy, of course.
  //
  // Subclasses return their own type directly in their overrides;
  // this works because C++ supports covariant return types.
  virtual Value* DeepCopy() const;

  // Compares if two Value objects have equal contents.
  virtual bool Equals(const Value* other) const;

  // Compares if two Value objects have equal contents. Can handle NULLs.
  // NULLs are considered equal but different from Value::CreateNullValue().
  static bool Equals(const Value* a, const Value* b);

 protected:
  // These aren't safe for end-users, but they are useful for subclasses.
  explicit Value(Type type);
  Value(const Value& that);
  Value& operator=(const Value& that);

 private:
  Type type_;
};

// FundamentalValue represents the simple fundamental types of values.
class BASE_EXPORT FundamentalValue : public Value {
 public:
  explicit FundamentalValue(bool in_value);
  explicit FundamentalValue(int in_value);
  explicit FundamentalValue(double in_value);
  virtual ~FundamentalValue();

  // Overridden from Value:
  virtual bool GetAsBoolean(bool* out_value) const OVERRIDE;
  virtual bool GetAsInteger(int* out_value) const OVERRIDE;
  virtual bool GetAsDouble(double* out_value) const OVERRIDE;
  virtual FundamentalValue* DeepCopy() const OVERRIDE;
  virtual bool Equals(const Value* other) const OVERRIDE;

 private:
  union {
    bool boolean_value_;
    int integer_value_;
    double double_value_;
  };
};

class BASE_EXPORT StringValue : public Value {
 public:
  // Initializes a StringValue with a UTF-8 narrow character string.
  explicit StringValue(const std::string& in_value);

  // Initializes a StringValue with a string16.
  explicit StringValue(const string16& in_value);

  virtual ~StringValue();

  // Overridden from Value:
  virtual bool GetAsString(std::string* out_value) const OVERRIDE;
  virtual bool GetAsString(string16* out_value) const OVERRIDE;
  virtual StringValue* DeepCopy() const OVERRIDE;
  virtual bool Equals(const Value* other) const OVERRIDE;

 private:
  std::string value_;
};

class BASE_EXPORT BinaryValue: public Value {
 public:
  // Creates a BinaryValue with a null buffer and size of 0.
  BinaryValue();

  // Creates a BinaryValue, taking ownership of the bytes pointed to by
  // |buffer|.
  BinaryValue(scoped_ptr<char[]> buffer, size_t size);

  virtual ~BinaryValue();

  // For situations where you want to keep ownership of your buffer, this
  // factory method creates a new BinaryValue by copying the contents of the
  // buffer that's passed in.
  static BinaryValue* CreateWithCopiedBuffer(const char* buffer, size_t size);

  size_t GetSize() const { return size_; }

  // May return NULL.
  char* GetBuffer() { return buffer_.get(); }
  const char* GetBuffer() const { return buffer_.get(); }

  // Overridden from Value:
  virtual BinaryValue* DeepCopy() const OVERRIDE;
  virtual bool Equals(const Value* other) const OVERRIDE;

 private:
  scoped_ptr<char[]> buffer_;
  size_t size_;

  DISALLOW_COPY_AND_ASSIGN(BinaryValue);
};

// DictionaryValue provides a key-value dictionary with (optional) "path"
// parsing for recursive access; see the comment at the top of the file. Keys
// are |std::string|s and should be UTF-8 encoded.
class BASE_EXPORT DictionaryValue : public Value {
 public:
  DictionaryValue();
  virtual ~DictionaryValue();

  // Overridden from Value:
  virtual bool GetAsDictionary(DictionaryValue** out_value) OVERRIDE;
  virtual bool GetAsDictionary(
      const DictionaryValue** out_value) const OVERRIDE;

  // Returns true if the current dictionary has a value for the given key.
  bool HasKey(const std::string& key) const;

  // Returns the number of Values in this dictionary.
  size_t size() const { return dictionary_.size(); }

  // Returns whether the dictionary is empty.
  bool empty() const { return dictionary_.empty(); }

  // Clears any current contents of this dictionary.
  void Clear();

  // Sets the Value associated with the given path starting from this object.
  // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
  // into the next DictionaryValue down.  Obviously, "." can't be used
  // within a key, but there are no other restrictions on keys.
  // If the key at any step of the way doesn't exist, or exists but isn't
  // a DictionaryValue, a new DictionaryValue will be created and attached
  // to the path in that location.
  // Note that the dictionary takes ownership of the value referenced by
  // |in_value|, and therefore |in_value| must be non-NULL.
  void Set(const std::string& path, Value* in_value);

  // Convenience forms of Set().  These methods will replace any existing
  // value at that path, even if it has a different type.
  void SetBoolean(const std::string& path, bool in_value);
  void SetInteger(const std::string& path, int in_value);
  void SetDouble(const std::string& path, double in_value);
  void SetString(const std::string& path, const std::string& in_value);
  void SetString(const std::string& path, const string16& in_value);

  // Like Set(), but without special treatment of '.'.  This allows e.g. URLs to
  // be used as paths.
  void SetWithoutPathExpansion(const std::string& key, Value* in_value);

  // Convenience forms of SetWithoutPathExpansion().
  void SetBooleanWithoutPathExpansion(const std::string& path, bool in_value);
  void SetIntegerWithoutPathExpansion(const std::string& path, int in_value);
  void SetDoubleWithoutPathExpansion(const std::string& path, double in_value);
  void SetStringWithoutPathExpansion(const std::string& path,
                                     const std::string& in_value);
  void SetStringWithoutPathExpansion(const std::string& path,
                                     const string16& in_value);

  // Gets the Value associated with the given path starting from this object.
  // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
  // into the next DictionaryValue down.  If the path can be resolved
  // successfully, the value for the last key in the path will be returned
  // through the |out_value| parameter, and the function will return true.
  // Otherwise, it will return false and |out_value| will be untouched.
  // Note that the dictionary always owns the value that's returned.
  bool Get(const std::string& path, const Value** out_value) const;
  bool Get(const std::string& path, Value** out_value);

  // These are convenience forms of Get().  The value will be retrieved
  // and the return value will be true if the path is valid and the value at
  // the end of the path can be returned in the form specified.
  bool GetBoolean(const std::string& path, bool* out_value) const;
  bool GetInteger(const std::string& path, int* out_value) const;
  bool GetDouble(const std::string& path, double* out_value) const;
  bool GetString(const std::string& path, std::string* out_value) const;
  bool GetString(const std::string& path, string16* out_value) const;
  bool GetStringASCII(const std::string& path, std::string* out_value) const;
  bool GetBinary(const std::string& path, const BinaryValue** out_value) const;
  bool GetBinary(const std::string& path, BinaryValue** out_value);
  bool GetDictionary(const std::string& path,
                     const DictionaryValue** out_value) const;
  bool GetDictionary(const std::string& path, DictionaryValue** out_value);
  bool GetList(const std::string& path, const ListValue** out_value) const;
  bool GetList(const std::string& path, ListValue** out_value);

  // Like Get(), but without special treatment of '.'.  This allows e.g. URLs to
  // be used as paths.
  bool GetWithoutPathExpansion(const std::string& key,
                               const Value** out_value) const;
  bool GetWithoutPathExpansion(const std::string& key, Value** out_value);
  bool GetBooleanWithoutPathExpansion(const std::string& key,
                                      bool* out_value) const;
  bool GetIntegerWithoutPathExpansion(const std::string& key,
                                      int* out_value) const;
  bool GetDoubleWithoutPathExpansion(const std::string& key,
                                     double* out_value) const;
  bool GetStringWithoutPathExpansion(const std::string& key,
                                     std::string* out_value) const;
  bool GetStringWithoutPathExpansion(const std::string& key,
                                     string16* out_value) const;
  bool GetDictionaryWithoutPathExpansion(
      const std::string& key,
      const DictionaryValue** out_value) const;
  bool GetDictionaryWithoutPathExpansion(const std::string& key,
                                         DictionaryValue** out_value);
  bool GetListWithoutPathExpansion(const std::string& key,
                                   const ListValue** out_value) const;
  bool GetListWithoutPathExpansion(const std::string& key,
                                   ListValue** out_value);

  // Removes the Value with the specified path from this dictionary (or one
  // of its child dictionaries, if the path is more than just a local key).
  // If |out_value| is non-NULL, the removed Value will be passed out via
  // |out_value|.  If |out_value| is NULL, the removed value will be deleted.
  // This method returns true if |path| is a valid path; otherwise it will
  // return false and the DictionaryValue object will be unchanged.
  virtual bool Remove(const std::string& path, scoped_ptr<Value>* out_value);

  // Like Remove(), but without special treatment of '.'.  This allows e.g. URLs
  // to be used as paths.
  virtual bool RemoveWithoutPathExpansion(const std::string& key,
                                          scoped_ptr<Value>* out_value);

  // Makes a copy of |this| but doesn't include empty dictionaries and lists in
  // the copy.  This never returns NULL, even if |this| itself is empty.
  DictionaryValue* DeepCopyWithoutEmptyChildren() const;

  // Merge |dictionary| into this dictionary. This is done recursively, i.e. any
  // sub-dictionaries will be merged as well. In case of key collisions, the
  // passed in dictionary takes precedence and data already present will be
  // replaced. Values within |dictionary| are deep-copied, so |dictionary| may
  // be freed any time after this call.
  void MergeDictionary(const DictionaryValue* dictionary);

  // Swaps contents with the |other| dictionary.
  virtual void Swap(DictionaryValue* other);

  // This class provides an iterator over both keys and values in the
  // dictionary.  It can't be used to modify the dictionary.
  class BASE_EXPORT Iterator {
   public:
    explicit Iterator(const DictionaryValue& target);

    bool IsAtEnd() const { return it_ == target_.dictionary_.end(); }
    void Advance() { ++it_; }

    const std::string& key() const { return it_->first; }
    const Value& value() const { return *it_->second; }

   private:
    const DictionaryValue& target_;
    ValueMap::const_iterator it_;
  };

  // Overridden from Value:
  virtual DictionaryValue* DeepCopy() const OVERRIDE;
  virtual bool Equals(const Value* other) const OVERRIDE;

 private:
  ValueMap dictionary_;

  DISALLOW_COPY_AND_ASSIGN(DictionaryValue);
};

// This type of Value represents a list of other Value values.
class BASE_EXPORT ListValue : public Value {
 public:
  typedef ValueVector::iterator iterator;
  typedef ValueVector::const_iterator const_iterator;

  ListValue();
  virtual ~ListValue();

  // Clears the contents of this ListValue
  void Clear();

  // Returns the number of Values in this list.
  size_t GetSize() const { return list_.size(); }

  // Returns whether the list is empty.
  bool empty() const { return list_.empty(); }

  // Sets the list item at the given index to be the Value specified by
  // the value given.  If the index beyond the current end of the list, null
  // Values will be used to pad out the list.
  // Returns true if successful, or false if the index was negative or
  // the value is a null pointer.
  bool Set(size_t index, Value* in_value);

  // Gets the Value at the given index.  Modifies |out_value| (and returns true)
  // only if the index falls within the current list range.
  // Note that the list always owns the Value passed out via |out_value|.
  bool Get(size_t index, const Value** out_value) const;
  bool Get(size_t index, Value** out_value);

  // Convenience forms of Get().  Modifies |out_value| (and returns true)
  // only if the index is valid and the Value at that index can be returned
  // in the specified form.
  bool GetBoolean(size_t index, bool* out_value) const;
  bool GetInteger(size_t index, int* out_value) const;
  bool GetDouble(size_t index, double* out_value) const;
  bool GetString(size_t index, std::string* out_value) const;
  bool GetString(size_t index, string16* out_value) const;
  bool GetBinary(size_t index, const BinaryValue** out_value) const;
  bool GetBinary(size_t index, BinaryValue** out_value);
  bool GetDictionary(size_t index, const DictionaryValue** out_value) const;
  bool GetDictionary(size_t index, DictionaryValue** out_value);
  bool GetList(size_t index, const ListValue** out_value) const;
  bool GetList(size_t index, ListValue** out_value);

  // Removes the Value with the specified index from this list.
  // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
  // passed out via |out_value|.  If |out_value| is NULL, the removed value will
  // be deleted.  This method returns true if |index| is valid; otherwise
  // it will return false and the ListValue object will be unchanged.
  virtual bool Remove(size_t index, scoped_ptr<Value>* out_value);

  // Removes the first instance of |value| found in the list, if any, and
  // deletes it. |index| is the location where |value| was found. Returns false
  // if not found.
  bool Remove(const Value& value, size_t* index);

  // Removes the element at |iter|. If |out_value| is NULL, the value will be
  // deleted, otherwise ownership of the value is passed back to the caller.
  // Returns an iterator pointing to the location of the element that
  // followed the erased element.
  iterator Erase(iterator iter, scoped_ptr<Value>* out_value);

  // Appends a Value to the end of the list.
  void Append(Value* in_value);

  // Convenience forms of Append.
  void AppendBoolean(bool in_value);
  void AppendInteger(int in_value);
  void AppendDouble(double in_value);
  void AppendString(const std::string& in_value);
  void AppendString(const string16& in_value);
  void AppendStrings(const std::vector<std::string>& in_values);
  void AppendStrings(const std::vector<string16>& in_values);

  // Appends a Value if it's not already present. Takes ownership of the
  // |in_value|. Returns true if successful, or false if the value was already
  // present. If the value was already present the |in_value| is deleted.
  bool AppendIfNotPresent(Value* in_value);

  // Insert a Value at index.
  // Returns true if successful, or false if the index was out of range.
  bool Insert(size_t index, Value* in_value);

  // Searches for the first instance of |value| in the list using the Equals
  // method of the Value type.
  // Returns a const_iterator to the found item or to end() if none exists.
  const_iterator Find(const Value& value) const;

  // Swaps contents with the |other| list.
  virtual void Swap(ListValue* other);

  // Iteration.
  iterator begin() { return list_.begin(); }
  iterator end() { return list_.end(); }

  const_iterator begin() const { return list_.begin(); }
  const_iterator end() const { return list_.end(); }

  // Overridden from Value:
  virtual bool GetAsList(ListValue** out_value) OVERRIDE;
  virtual bool GetAsList(const ListValue** out_value) const OVERRIDE;
  virtual ListValue* DeepCopy() const OVERRIDE;
  virtual bool Equals(const Value* other) const OVERRIDE;

 private:
  ValueVector list_;

  DISALLOW_COPY_AND_ASSIGN(ListValue);
};

// This interface is implemented by classes that know how to serialize and
// deserialize Value objects.
class BASE_EXPORT ValueSerializer {
 public:
  virtual ~ValueSerializer();

  virtual bool Serialize(const Value& root) = 0;

  // This method deserializes the subclass-specific format into a Value object.
  // If the return value is non-NULL, the caller takes ownership of returned
  // Value. If the return value is NULL, and if error_code is non-NULL,
  // error_code will be set with the underlying error.
  // If |error_message| is non-null, it will be filled in with a formatted
  // error message including the location of the error if appropriate.
  virtual Value* Deserialize(int* error_code, std::string* error_str) = 0;
};

// Stream operator so Values can be used in assertion statements.  In order that
// gtest uses this operator to print readable output on test failures, we must
// override each specific type. Otherwise, the default template implementation
// is preferred over an upcast.
BASE_EXPORT std::ostream& operator<<(std::ostream& out, const Value& value);

BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
                                            const FundamentalValue& value) {
  return out << static_cast<const Value&>(value);
}

BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
                                            const StringValue& value) {
  return out << static_cast<const Value&>(value);
}

BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
                                            const DictionaryValue& value) {
  return out << static_cast<const Value&>(value);
}

BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
                                            const ListValue& value) {
  return out << static_cast<const Value&>(value);
}

}  // namespace base

// http://crbug.com/88666
using base::DictionaryValue;
using base::ListValue;
using base::StringValue;
using base::Value;

#endif  // BASE_VALUES_H_


text:
<?php

namespace Stato\Webflow;

require_once __DIR__ . '/../TestsHelper.php';

class FlashTest extends TestCase
{
    private $flash;

    public function setUp()
    {
        $this->flash = new Flash();
    }

    public function testVariableAssigns()
    {
        $this->flash['foo'] = 'bar';
        $this->flash['hello'] = array();
        $this->flash['hello']['world'] = 'php';
        $this->assertEquals('bar', $this->flash['foo']);
        $this->assertEquals('php', $this->flash['hello']['world']);
    }

    public function testDiscard()
    {
        $this->flash['notice'] = 'Hello world';
        $this->flash['warning'] = 'DANGEROUS !';
        $this->flash->discard();
        $this->assertEquals('Hello world', $this->flash['notice']);
        $this->assertEquals('DANGEROUS !', $this->flash['warning']);
        $this->flash->discard();
        $this->assertFalse(isset($this->flash['notice']));
        $this->assertFalse(isset($this->flash['warning']));
    }

    public function testKeep()
    {
        $this->flash['notice'] = 'Hello world';
        $this->flash['warning'] = 'DANGEROUS !';
        $this->flash->discard();
        $this->assertEquals('Hello world', $this->flash['notice']);
        $this->assertEquals('DANGEROUS !', $this->flash['warning']);
        $this->flash->keep('notice');
        $this->flash->discard();
        $this->assertTrue(isset($this->flash['notice']));
        $this->assertFalse(isset($this->flash['warning']));
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper;

class AgeInYears extends AbstractHelper
{
    public function __invoke($dob, $type=null)
    {
       $birthday = new \DateTime($dob);
       $today = new \DateTime();
       $interval = $birthday->diff($today);
       if(strtolower($type) == 'years') {
           return $interval->y;
       } else {
          return $interval->y." years, ".$interval->m." months, ".$interval->d." days";
       }

    }
}


text:
package org.glowroot.agent.jul;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class LevelTest {

    @Test
    public void testGetName() {
        assertThat(Level.WARNING.getName()).isEqualTo("WARNING");
    }
}


text:
#include <aws/managedblockchain/model/ListNodesResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::ManagedBlockchain::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

ListNodesResult::ListNodesResult()
{
}

ListNodesResult::ListNodesResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

ListNodesResult& ListNodesResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("Nodes"))
  {
    Aws::Utils::Array<JsonView> nodesJsonList = jsonValue.GetArray("Nodes");
    for(unsigned nodesIndex = 0; nodesIndex < nodesJsonList.GetLength(); ++nodesIndex)
    {
      m_nodes.push_back(nodesJsonList[nodesIndex].AsObject());
    }
  }

  if(jsonValue.ValueExists("NextToken"))
  {
    m_nextToken = jsonValue.GetString("NextToken");

  }

  return *this;
}


text:
//this source code was auto-generated by tolua#, do not modify it
using System;
using LuaInterface;

public class UnityEngine_AsyncOperationWrap
{
	public static void Register(LuaState L)
	{
		L.BeginClass(typeof(UnityEngine.AsyncOperation), typeof(System.Object));
		L.RegFunction("New", _CreateUnityEngine_AsyncOperation);
		L.RegFunction("__tostring", ToLua.op_ToString);
		L.RegVar("isDone", get_isDone, null);
		L.RegVar("progress", get_progress, null);
		L.RegVar("priority", get_priority, set_priority);
		L.RegVar("allowSceneActivation", get_allowSceneActivation, set_allowSceneActivation);
		L.RegVar("completed", get_completed, set_completed);
		L.EndClass();
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int _CreateUnityEngine_AsyncOperation(IntPtr L)
	{
		try
		{
			int count = LuaDLL.lua_gettop(L);

			if (count == 0)
			{
				UnityEngine.AsyncOperation obj = new UnityEngine.AsyncOperation();
				ToLua.PushObject(L, obj);
				return 1;
			}
			else
			{
				return LuaDLL.luaL_throw(L, "invalid arguments to ctor method: UnityEngine.AsyncOperation.New");
			}
		}
		catch (Exception e)
		{
			return LuaDLL.toluaL_exception(L, e);
		}
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int get_isDone(IntPtr L)
	{
		object o = null;

		try
		{
			o = ToLua.ToObject(L, 1);
			UnityEngine.AsyncOperation obj = (UnityEngine.AsyncOperation)o;
			bool ret = obj.isDone;
			LuaDLL.lua_pushboolean(L, ret);
			return 1;
		}
		catch(Exception e)
		{
			return LuaDLL.toluaL_exception(L, e, o, "attempt to index isDone on a nil value");
		}
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int get_progress(IntPtr L)
	{
		object o = null;

		try
		{
			o = ToLua.ToObject(L, 1);
			UnityEngine.AsyncOperation obj = (UnityEngine.AsyncOperation)o;
			float ret = obj.progress;
			LuaDLL.lua_pushnumber(L, ret);
			return 1;
		}
		catch(Exception e)
		{
			return LuaDLL.toluaL_exception(L, e, o, "attempt to index progress on a nil value");
		}
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int get_priority(IntPtr L)
	{
		object o = null;

		try
		{
			o = ToLua.ToObject(L, 1);
			UnityEngine.AsyncOperation obj = (UnityEngine.AsyncOperation)o;
			int ret = obj.priority;
			LuaDLL.lua_pushinteger(L, ret);
			return 1;
		}
		catch(Exception e)
		{
			return LuaDLL.toluaL_exception(L, e, o, "attempt to index priority on a nil value");
		}
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int get_allowSceneActivation(IntPtr L)
	{
		object o = null;

		try
		{
			o = ToLua.ToObject(L, 1);
			UnityEngine.AsyncOperation obj = (UnityEngine.AsyncOperation)o;
			bool ret = obj.allowSceneActivation;
			LuaDLL.lua_pushboolean(L, ret);
			return 1;
		}
		catch(Exception e)
		{
			return LuaDLL.toluaL_exception(L, e, o, "attempt to index allowSceneActivation on a nil value");
		}
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int get_completed(IntPtr L)
	{
		ToLua.Push(L, new EventObject(typeof(System.Action<UnityEngine.AsyncOperation>)));
		return 1;
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int set_priority(IntPtr L)
	{
		object o = null;

		try
		{
			o = ToLua.ToObject(L, 1);
			UnityEngine.AsyncOperation obj = (UnityEngine.AsyncOperation)o;
			int arg0 = (int)LuaDLL.luaL_checknumber(L, 2);
			obj.priority = arg0;
			return 0;
		}
		catch(Exception e)
		{
			return LuaDLL.toluaL_exception(L, e, o, "attempt to index priority on a nil value");
		}
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int set_allowSceneActivation(IntPtr L)
	{
		object o = null;

		try
		{
			o = ToLua.ToObject(L, 1);
			UnityEngine.AsyncOperation obj = (UnityEngine.AsyncOperation)o;
			bool arg0 = LuaDLL.luaL_checkboolean(L, 2);
			obj.allowSceneActivation = arg0;
			return 0;
		}
		catch(Exception e)
		{
			return LuaDLL.toluaL_exception(L, e, o, "attempt to index allowSceneActivation on a nil value");
		}
	}

	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static int set_completed(IntPtr L)
	{
		try
		{
			UnityEngine.AsyncOperation obj = (UnityEngine.AsyncOperation)ToLua.CheckObject(L, 1, typeof(UnityEngine.AsyncOperation));
			EventObject arg0 = null;

			if (LuaDLL.lua_isuserdata(L, 2) != 0)
			{
				arg0 = (EventObject)ToLua.ToObject(L, 2);
			}
			else
			{
				return LuaDLL.luaL_throw(L, "The event 'UnityEngine.AsyncOperation.completed' can only appear on the left hand side of += or -= when used outside of the type 'UnityEngine.AsyncOperation'");
			}

			if (arg0.op == EventOp.Add)
			{
				System.Action<UnityEngine.AsyncOperation> ev = (System.Action<UnityEngine.AsyncOperation>)arg0.func;
				obj.completed += ev;
			}
			else if (arg0.op == EventOp.Sub)
			{
				System.Action<UnityEngine.AsyncOperation> ev = (System.Action<UnityEngine.AsyncOperation>)arg0.func;
				obj.completed -= ev;
			}

			return 0;
		}
		catch (Exception e)
		{
			return LuaDLL.toluaL_exception(L, e);
		}
	}
}


text:
function getTweets(){
	$.ajax({
	cache: false,
	type: "GET",
	url: url+"/twitter/index.php?type=json",
	contentType: "application/json",
	async: false,
	success: function(data) {
		var JSONData = JSON.stringify(data);
		var parsedData = JSON.parse(JSONData);
		//console.log('getTweetsAthena succes');
		for (var JSONCounter=0; JSONCounter < data.tweet.length; JSONCounter++) {
				var username = data.tweet[JSONCounter]["username"];
				var text = data.tweet[JSONCounter]["text"];
				var listItem = '
'+username+': '+text+'
';
				//listItem.appendTo( "#tweetNewsFeed" );
				$("#tweetNewsFeed").html(listItem);
			};
		},
		error: function(){
			alert('twitter error');
		}
	});
}


text:
#include "WanderingComponent.h"
#include "PathfindingAgentComponent.h"
#include "World.h"

#include <cstdlib>
#include <ctime>
#include <glm/glm.hpp>

WanderingComponent::WanderingComponent( GameObject * a_go , EComponentTypes a_type ) :
  Component( a_go , a_type )
{

}

WanderingComponent::~WanderingComponent()
{
}

void WanderingComponent::BeginPlay()
{
  GameObject* owner = GetParent();
  if( owner )
  {
    m_pathfindingComp = reinterpret_cast<PathfindingAgentComponent*>( owner->GetComponentOfType( EComponentTypes::CT_PathfindingAgentComponent ) );
  }
}

void WanderingComponent::Update( float a_dt )
{
  if( m_pathfindingComp )
  {
    Path* path = m_pathfindingComp->GetPath();
    if( !path && !m_pathfindingComp->HasPathBeenRequested() )
    {
      World* world = GetParent()->GetWorld();
      if( world )
      {
        WorldLimits limits = world->GetWorldLimits();
        float destX , destY = 0.0f;
        destX = (float)( std::rand() % (int)limits.bottomRight.x ) + limits.topLeft.x;
        destY = (float)( std::rand() % (int)limits.bottomRight.y ) + limits.topLeft.y;
        glm::vec2 destination( destX , destY );
        Transform parentTransform = GetParent()->GetTransform();
        std::weak_ptr<Grid> gridWkPtr = m_pathfindingComp->GetGrid();
        if( !gridWkPtr.expired() )
        {
          std::shared_ptr<Grid> grid = gridWkPtr.lock();
          Node* node = grid->GetNode( destination );
          Node* currentNode = grid->GetNode( parentTransform.position );
          /*while( !node->bwalkable && node != currentNode );
          {

            destination.x = (float)( std::rand() % (int)limits.bottomRight.x ) + limits.topLeft.x;
            destination.y = (float)( std::rand() % (int)limits.bottomRight.y ) + limits.topLeft.y;
            node = grid->GetNode( destination );
          }*/
          m_pathfindingComp->RequestPath( parentTransform.position , destination );
        }
      }
    }
    else if( path )
    {
      if( path->nodes.size() > 0 )
      {
        glm::vec2 currentNode = path->nodes[ 0 ];
        Transform parentTransform = GetParent()->GetTransform();
        glm::vec2 vecBetween = currentNode - parentTransform.position;
        float length = glm::length( vecBetween );
        if( length < 2.0f )
        {
          path->nodes.erase( path->nodes.begin() );
          if( path->nodes.size() == 0 )
          {
            m_pathfindingComp->ClearPath();
            return;
          }
          else
            currentNode = path->nodes[ 0 ];
          vecBetween = currentNode - parentTransform.position;
        }
        glm::vec2 direction = glm::normalize( vecBetween );
        parentTransform.position += direction* 128.0f * a_dt;
        GetParent()->SetPosition( parentTransform.position );
      }
      else
        m_pathfindingComp->ClearPath();
    }

  }
}


text:
namespace NLog.UnitTests.Targets
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.Common;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using NLog.Common;
    using NLog.Config;
    using NLog.Targets;
    using Xunit;
    using Xunit.Extensions;
    using System.Data.SqlClient;

    public class DatabaseTargetTests : NLogTestBase
    {
#if !MONO
        static DatabaseTargetTests()
        {
            var data = (DataSet)ConfigurationManager.GetSection("system.data");
            var providerFactories = data.Tables["DBProviderFactories"];
            providerFactories.Rows.Add("MockDb Provider", "MockDb Provider", "MockDb",
                typeof(MockDbFactory).AssemblyQualifiedName);
            providerFactories.AcceptChanges();
        }
#endif

        [Fact]
        public void SimpleDatabaseTest()
        {
            MockDbConnection.ClearLog();
            DatabaseTarget dt = new DatabaseTarget()
            {
                CommandText = "INSERT INTO FooBar VALUES('${message}')",
                ConnectionString = "FooBar",
                DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
            };

            dt.Initialize(null);
            Assert.Same(typeof(MockDbConnection), dt.ConnectionType);

            List<Exception> exceptions = new List<Exception>();
            dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add));
            dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add));
            dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add));
            foreach (var ex in exceptions)
            {
                Assert.Null(ex);
            }

            string expectedLog = @"Open('FooBar').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1')
Close()
Dispose()
Open('FooBar').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2')
Close()
Dispose()
Open('FooBar').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3')
Close()
Dispose()
";

            AssertLog(expectedLog);
        }

        [Fact]
        public void SimpleBatchedDatabaseTest()
        {
            MockDbConnection.ClearLog();
            DatabaseTarget dt = new DatabaseTarget()
            {
                CommandText = "INSERT INTO FooBar VALUES('${message}')",
                ConnectionString = "FooBar",
                DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
            };

            dt.Initialize(null);
            Assert.Same(typeof(MockDbConnection), dt.ConnectionType);

            List<Exception> exceptions = new List<Exception>();
            var events = new[]
            {
                new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add),
            };

            dt.WriteAsyncLogEvents(events);
            foreach (var ex in exceptions)
            {
                Assert.Null(ex);
            }

            string expectedLog = @"Open('FooBar').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3')
Close()
Dispose()
";

            AssertLog(expectedLog);
        }

        [Fact]
        public void KeepConnectionOpenTest()
        {
            MockDbConnection.ClearLog();
            DatabaseTarget dt = new DatabaseTarget()
            {
                CommandText = "INSERT INTO FooBar VALUES('${message}')",
                ConnectionString = "FooBar",
                DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
                KeepConnection = true,
            };

            dt.Initialize(null);
            Assert.Same(typeof(MockDbConnection), dt.ConnectionType);

            List<Exception> exceptions = new List<Exception>();
            dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add));
            dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add));
            dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add));
            foreach (var ex in exceptions)
            {
                Assert.Null(ex);
            }

            string expectedLog = @"Open('FooBar').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3')
";

            AssertLog(expectedLog);

            MockDbConnection.ClearLog();
            dt.Close();
            expectedLog = @"Close()
Dispose()
";

            AssertLog(expectedLog);
        }

        [Fact]
        public void KeepConnectionOpenBatchedTest()
        {
            MockDbConnection.ClearLog();
            DatabaseTarget dt = new DatabaseTarget()
            {
                CommandText = "INSERT INTO FooBar VALUES('${message}')",
                ConnectionString = "FooBar",
                DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
                KeepConnection = true,
            };

            dt.Initialize(null);
            Assert.Same(typeof(MockDbConnection), dt.ConnectionType);
            var exceptions = new List<Exception>();

            var events = new[]
            {
                new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add),
            };

            dt.WriteAsyncLogEvents(events);
            foreach (var ex in exceptions)
            {
                Assert.Null(ex);
            }

            string expectedLog = @"Open('FooBar').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3')
";

            AssertLog(expectedLog);

            MockDbConnection.ClearLog();
            dt.Close();
            expectedLog = @"Close()
Dispose()
";

            AssertLog(expectedLog);
        }

        [Fact]
        public void KeepConnectionOpenTest2()
        {
            MockDbConnection.ClearLog();
            DatabaseTarget dt = new DatabaseTarget()
            {
                CommandText = "INSERT INTO FooBar VALUES('${message}')",
                ConnectionString = "Database=${logger}",
                DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
                KeepConnection = true,
            };

            dt.Initialize(null);
            Assert.Same(typeof(MockDbConnection), dt.ConnectionType);

            List<Exception> exceptions = new List<Exception>();
            dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add));
            dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add));
            dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger2", "msg3").WithContinuation(exceptions.Add));
            dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg4").WithContinuation(exceptions.Add));
            foreach (var ex in exceptions)
            {
                Assert.Null(ex);
            }

            string expectedLog = @"Open('Database=MyLogger').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2')
Close()
Dispose()
Open('Database=MyLogger2').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3')
Close()
Dispose()
Open('Database=MyLogger').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg4')
";

            AssertLog(expectedLog);

            MockDbConnection.ClearLog();
            dt.Close();
            expectedLog = @"Close()
Dispose()
";

            AssertLog(expectedLog);
        }

        [Fact]
        public void KeepConnectionOpenBatchedTest2()
        {
            MockDbConnection.ClearLog();
            DatabaseTarget dt = new DatabaseTarget()
            {
                CommandText = "INSERT INTO FooBar VALUES('${message}')",
                ConnectionString = "Database=${logger}",
                DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
                KeepConnection = true,
            };

            dt.Initialize(null);

            Assert.Same(typeof(MockDbConnection), dt.ConnectionType);

            // when we pass multiple log events in an array, the target will bucket-sort them by
            // connection string and group all commands for the same connection string together
            // to minimize number of db open/close operations
            // in this case msg1, msg2 and msg4 will be written together to MyLogger database
            // and msg3 will be written to MyLogger2 database

            List<Exception> exceptions = new List<Exception>();
            var events = new[]
            {
                new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "MyLogger2", "msg3").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "MyLogger", "msg4").WithContinuation(exceptions.Add),
            };

            dt.WriteAsyncLogEvents(events);
            foreach (var ex in exceptions)
            {
                Assert.Null(ex);
            }

            string expectedLog = @"Open('Database=MyLogger').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg4')
Close()
Dispose()
Open('Database=MyLogger2').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3')
";

            AssertLog(expectedLog);

            MockDbConnection.ClearLog();
            dt.Close();
            expectedLog = @"Close()
Dispose()
";

            AssertLog(expectedLog);
        }

        [Fact]
        public void ParameterTest()
        {
            MockDbConnection.ClearLog();
            DatabaseTarget dt = new DatabaseTarget()
            {
                CommandText = "INSERT INTO FooBar VALUES(@msg, @lvl, @lg)",
                DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
                KeepConnection = true,
                Parameters =
                {
                    new DatabaseParameterInfo("msg", "${message}"),
                    new DatabaseParameterInfo("lvl", "${level}"),
                    new DatabaseParameterInfo("lg", "${logger}")

                }
            };

            dt.Initialize(null);

            Assert.Same(typeof(MockDbConnection), dt.ConnectionType);

            // when we pass multiple log events in an array, the target will bucket-sort them by
            // connection string and group all commands for the same connection string together
            // to minimize number of db open/close operations
            // in this case msg1, msg2 and msg4 will be written together to MyLogger database
            // and msg3 will be written to MyLogger2 database

            List<Exception> exceptions = new List<Exception>();
            var events = new[]
            {
                new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Debug, "MyLogger2", "msg3").WithContinuation(exceptions.Add),
            };

            dt.WriteAsyncLogEvents(events);
            foreach (var ex in exceptions)
            {
                Assert.Null(ex);
            }

            string expectedLog = @"Open('Server=.;Trusted_Connection=SSPI;').
CreateParameter(0)
Parameter #0 Direction=Input
Parameter #0 Name=msg
Parameter #0 Value=msg1
Add Parameter Parameter #0
CreateParameter(1)
Parameter #1 Direction=Input
Parameter #1 Name=lvl
Parameter #1 Value=Info
Add Parameter Parameter #1
CreateParameter(2)
Parameter #2 Direction=Input
Parameter #2 Name=lg
Parameter #2 Value=MyLogger
Add Parameter Parameter #2
ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg)
CreateParameter(0)
Parameter #0 Direction=Input
Parameter #0 Name=msg
Parameter #0 Value=msg3
Add Parameter Parameter #0
CreateParameter(1)
Parameter #1 Direction=Input
Parameter #1 Name=lvl
Parameter #1 Value=Debug
Add Parameter Parameter #1
CreateParameter(2)
Parameter #2 Direction=Input
Parameter #2 Name=lg
Parameter #2 Value=MyLogger2
Add Parameter Parameter #2
ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg)
";

            AssertLog(expectedLog);

            MockDbConnection.ClearLog();
            dt.Close();
            expectedLog = @"Close()
Dispose()
";

            AssertLog(expectedLog);
        }

        [Fact]
        public void ParameterFacetTest()
        {
            MockDbConnection.ClearLog();
            DatabaseTarget dt = new DatabaseTarget()
            {
                CommandText = "INSERT INTO FooBar VALUES(@msg, @lvl, @lg)",
                DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
                KeepConnection = true,
                Parameters =
                {
                    new DatabaseParameterInfo("msg", "${message}")
                    {
                        Precision = 3,
                        Scale = 7,
                        Size = 9,
                    },
                    new DatabaseParameterInfo("lvl", "${level}")
                    {
                        Scale = 7
                    },
                    new DatabaseParameterInfo("lg", "${logger}")
                    {
                        Precision = 0
                    },
                }
            };

            dt.Initialize(null);

            Assert.Same(typeof(MockDbConnection), dt.ConnectionType);

            // when we pass multiple log events in an array, the target will bucket-sort them by
            // connection string and group all commands for the same connection string together
            // to minimize number of db open/close operations
            // in this case msg1, msg2 and msg4 will be written together to MyLogger database
            // and msg3 will be written to MyLogger2 database

            var exceptions = new List<Exception>();
            var events = new[]
            {
                new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Debug, "MyLogger2", "msg3").WithContinuation(exceptions.Add),
            };

            dt.WriteAsyncLogEvents(events);
            dt.Close();
            foreach (var ex in exceptions)
            {
                Assert.Null(ex);
            }

            string expectedLog = @"Open('Server=.;Trusted_Connection=SSPI;').
CreateParameter(0)
Parameter #0 Direction=Input
Parameter #0 Name=msg
Parameter #0 Size=9
Parameter #0 Precision=3
Parameter #0 Scale=7
Parameter #0 Value=msg1
Add Parameter Parameter #0
CreateParameter(1)
Parameter #1 Direction=Input
Parameter #1 Name=lvl
Parameter #1 Scale=7
Parameter #1 Value=Info
Add Parameter Parameter #1
CreateParameter(2)
Parameter #2 Direction=Input
Parameter #2 Name=lg
Parameter #2 Value=MyLogger
Add Parameter Parameter #2
ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg)
CreateParameter(0)
Parameter #0 Direction=Input
Parameter #0 Name=msg
Parameter #0 Size=9
Parameter #0 Precision=3
Parameter #0 Scale=7
Parameter #0 Value=msg3
Add Parameter Parameter #0
CreateParameter(1)
Parameter #1 Direction=Input
Parameter #1 Name=lvl
Parameter #1 Scale=7
Parameter #1 Value=Debug
Add Parameter Parameter #1
CreateParameter(2)
Parameter #2 Direction=Input
Parameter #2 Name=lg
Parameter #2 Value=MyLogger2
Add Parameter Parameter #2
ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg)
Close()
Dispose()
";
            AssertLog(expectedLog);
        }

        [Fact]
        public void ConnectionStringBuilderTest1()
        {
            DatabaseTarget dt;

            dt = new DatabaseTarget();
            Assert.Equal("Server=.;Trusted_Connection=SSPI;", this.GetConnectionString(dt));

            dt = new DatabaseTarget();
            dt.DBHost = "${logger}";
            Assert.Equal("Server=Logger1;Trusted_Connection=SSPI;", this.GetConnectionString(dt));

            dt = new DatabaseTarget();
            dt.DBHost = "HOST1";
            dt.DBDatabase = "${logger}";
            Assert.Equal("Server=HOST1;Trusted_Connection=SSPI;Database=Logger1", this.GetConnectionString(dt));

            dt = new DatabaseTarget();
            dt.DBHost = "HOST1";
            dt.DBDatabase = "${logger}";
            dt.DBUserName = "user1";
            dt.DBPassword = "password1";
            Assert.Equal("Server=HOST1;User id=user1;Password=password1;Database=Logger1", this.GetConnectionString(dt));

            dt = new DatabaseTarget();
            dt.ConnectionString = "customConnectionString42";
            dt.DBHost = "HOST1";
            dt.DBDatabase = "${logger}";
            dt.DBUserName = "user1";
            dt.DBPassword = "password1";
            Assert.Equal("customConnectionString42", this.GetConnectionString(dt));
        }

        [Fact]
        public void DatabaseExceptionTest1()
        {
            MockDbConnection.ClearLog();
            var exceptions = new List<Exception>();

            var db = new DatabaseTarget();
            db.CommandText = "not important";
            db.ConnectionString = "cannotconnect";
            db.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName;
            db.Initialize(null);
            db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            db.Close();

            Assert.Equal(1, exceptions.Count);
            Assert.NotNull(exceptions[0]);
            Assert.Equal("Cannot open fake database.", exceptions[0].Message);
            Assert.Equal("Open('cannotconnect').\r\n", MockDbConnection.Log);
        }

        [Fact]
        public void DatabaseExceptionTest2()
        {
            MockDbConnection.ClearLog();
            var exceptions = new List<Exception>();

            var db = new DatabaseTarget();
            db.CommandText = "not important";
            db.ConnectionString = "cannotexecute";
            db.KeepConnection = true;
            db.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName;
            db.Initialize(null);
            db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            db.Close();

            Assert.Equal(3, exceptions.Count);
            Assert.NotNull(exceptions[0]);
            Assert.NotNull(exceptions[1]);
            Assert.NotNull(exceptions[2]);
            Assert.Equal("Failure during ExecuteNonQuery", exceptions[0].Message);
            Assert.Equal("Failure during ExecuteNonQuery", exceptions[1].Message);
            Assert.Equal("Failure during ExecuteNonQuery", exceptions[2].Message);

            string expectedLog = @"Open('cannotexecute').
ExecuteNonQuery: not important
Close()
Dispose()
Open('cannotexecute').
ExecuteNonQuery: not important
Close()
Dispose()
Open('cannotexecute').
ExecuteNonQuery: not important
Close()
Dispose()
";
            AssertLog(expectedLog);
        }

        [Fact]
        public void DatabaseExceptionTest3()
        {
            MockDbConnection.ClearLog();
            var exceptions = new List<Exception>();

            var db = new DatabaseTarget();
            db.CommandText = "not important";
            db.ConnectionString = "cannotexecute";
            db.KeepConnection = true;
            db.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName;
            db.Initialize(null);
            db.WriteAsyncLogEvents(
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            db.Close();

            Assert.Equal(3, exceptions.Count);
            Assert.NotNull(exceptions[0]);
            Assert.NotNull(exceptions[1]);
            Assert.NotNull(exceptions[2]);
            Assert.Equal("Failure during ExecuteNonQuery", exceptions[0].Message);
            Assert.Equal("Failure during ExecuteNonQuery", exceptions[1].Message);
            Assert.Equal("Failure during ExecuteNonQuery", exceptions[2].Message);

            string expectedLog = @"Open('cannotexecute').
ExecuteNonQuery: not important
Close()
Dispose()
Open('cannotexecute').
ExecuteNonQuery: not important
Close()
Dispose()
Open('cannotexecute').
ExecuteNonQuery: not important
Close()
Dispose()
";
            AssertLog(expectedLog);
        }

        [Fact]
        public void ConnectionStringNameInitTest()
        {
            var dt = new DatabaseTarget
            {
                ConnectionStringName = "MyConnectionString",
                CommandText = "notimportant",
            };

            Assert.Same(ConfigurationManager.ConnectionStrings, dt.ConnectionStringsSettings);
            dt.ConnectionStringsSettings = new ConnectionStringSettingsCollection()
            {
                new ConnectionStringSettings("MyConnectionString", "cs1", "MockDb"),
            };

            dt.Initialize(null);
            Assert.Same(MockDbFactory.Instance, dt.ProviderFactory);
            Assert.Equal("cs1", dt.ConnectionString.Render(LogEventInfo.CreateNullEvent()));
        }

        [Fact]
        public void ConnectionStringNameNegativeTest_if_ThrowConfigExceptions()
        {
            LogManager.ThrowConfigExceptions = true;
            var dt = new DatabaseTarget
            {
                ConnectionStringName = "MyConnectionString",
                CommandText = "notimportant",
                ConnectionStringsSettings = new ConnectionStringSettingsCollection(),
            };

            try
            {
                dt.Initialize(null);
                Assert.True(false, "Exception expected.");
            }
            catch (NLogConfigurationException configurationException)
            {
                Assert.Equal(
                    "Connection string 'MyConnectionString' is not declared in <connectionStrings /> section.",
                    configurationException.Message);
            }
        }

        [Fact]
        public void ProviderFactoryInitTest()
        {
            var dt = new DatabaseTarget();
            dt.DBProvider = "MockDb";
            dt.CommandText = "Notimportant";
            dt.Initialize(null);
            Assert.Same(MockDbFactory.Instance, dt.ProviderFactory);
            dt.OpenConnection("myConnectionString");
            Assert.Equal(1, MockDbConnection2.OpenCount);
            Assert.Equal("myConnectionString", MockDbConnection2.LastOpenConnectionString);
        }

        [Fact]
        public void SqlServerShorthandNotationTest()
        {
            foreach (string provName in new[] { "microsoft", "msde", "mssql", "sqlserver" })
            {
                var dt = new DatabaseTarget()
                {
                    Name = "myTarget",
                    DBProvider = provName,
                    ConnectionString = "notimportant",
                    CommandText = "notimportant",
                };

                dt.Initialize(null);
                Assert.Equal(typeof(System.Data.SqlClient.SqlConnection), dt.ConnectionType);
            }
        }

        [Fact]
        public void OleDbShorthandNotationTest()
        {
            var dt = new DatabaseTarget()
            {
                Name = "myTarget",
                DBProvider = "oledb",
                ConnectionString = "notimportant",
                CommandText = "notimportant",
            };

            dt.Initialize(null);
            Assert.Equal(typeof(System.Data.OleDb.OleDbConnection), dt.ConnectionType);
        }

        [Fact]
        public void OdbcShorthandNotationTest()
        {
            var dt = new DatabaseTarget()
            {
                Name = "myTarget",
                DBProvider = "odbc",
                ConnectionString = "notimportant",
                CommandText = "notimportant",
            };

            dt.Initialize(null);
            Assert.Equal(typeof(System.Data.Odbc.OdbcConnection), dt.ConnectionType);
        }

        [Fact]
        public void SqlServer_InstallAndLogMessage()
        {

            if (SqlServerTest.IsTravis())
            {
                Console.WriteLine("skipping test SqlServer_InstallAndLogMessage because we are running in Travis");
                return;
            }

            SqlServerTest.TryDropDatabase();

            try
            {
                SqlServerTest.CreateDatabase();

                var connectionString = SqlServerTest.GetConnectionString();
                LogManager.Configuration = CreateConfigurationFromString(@"
            <nlog xmlns='http://www.nlog-project.org/schemas/NLog.xsd'
                  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' throwExceptions='true'>
                <targets>
                    <target name='database' xsi:type='Database' connectionstring=""" + connectionString + @"""
                        commandText='insert into dbo.NLogSqlServerTest (Uid) values (@uid);'>
                        <parameter name='@uid' layout='${event-properties:uid}' />
<install-command ignoreFailures=""false""
                 text=""CREATE TABLE dbo.NLogSqlServerTest (
    Id       int               NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED,
    Uid      uniqueidentifier  NULL
);""/>

                    </target>
                </targets>
                <rules>
                    <logger name='*' writeTo='database' />
                </rules>
            </nlog>");

                //install
                InstallationContext context = new InstallationContext();
                LogManager.Configuration.Install(context);

                var tableCatalog = SqlServerTest.IssueScalarQuery(@"SELECT TABLE_CATALOG FROM INFORMATION_SCHEMA.TABLES
                 WHERE TABLE_SCHEMA = 'Dbo'
                 AND  TABLE_NAME = 'NLogSqlServerTest'");

                //check if table exists
                Assert.Equal("NLogTest", tableCatalog);

                var logger = LogManager.GetLogger("A");
                var target = LogManager.Configuration.FindTargetByName<DatabaseTarget>("database");

                var uid = new Guid("e7c648b4-3508-4df2-b001-753148659d6d");
                var logEvent = new LogEventInfo(LogLevel.Info, null, null);
                logEvent.Properties["uid"] = uid;
                logger.Log(logEvent);

                var count = SqlServerTest.IssueScalarQuery("SELECT count(1) FROM dbo.NLogSqlServerTest");

                Assert.Equal(1, count);

                var result = SqlServerTest.IssueScalarQuery("SELECT Uid FROM dbo.NLogSqlServerTest");

                Assert.Equal(uid, result);
            }
            finally
            {
                SqlServerTest.TryDropDatabase();
            }

        }

        public void GetProviderNameFromAppConfig()
        {
            LogManager.ThrowExceptions = true;
            var databaseTarget = new DatabaseTarget()
            {
                Name = "myTarget",
                ConnectionStringName = "test_connectionstring_with_providerName",
                CommandText = "notimportant",
            };
            databaseTarget.ConnectionStringsSettings = new ConnectionStringSettingsCollection()
            {
                new ConnectionStringSettings("test_connectionstring_without_providerName", "some connectionstring"),
                new ConnectionStringSettings("test_connectionstring_with_providerName", "some connectionstring",
                    "System.Data.SqlClient"),
            };

            databaseTarget.Initialize(null);
            Assert.NotNull(databaseTarget.ProviderFactory);
            Assert.Equal(typeof(System.Data.SqlClient.SqlClientFactory), databaseTarget.ProviderFactory.GetType());
        }

        [Fact]
        public void DontRequireProviderNameInAppConfig()
        {
            LogManager.ThrowExceptions = true;
            var databaseTarget = new DatabaseTarget()
            {
                Name = "myTarget",
                ConnectionStringName = "test_connectionstring_without_providerName",
                CommandText = "notimportant",
                DBProvider = "System.Data.SqlClient"
            };

            databaseTarget.ConnectionStringsSettings = new ConnectionStringSettingsCollection()
            {
                new ConnectionStringSettings("test_connectionstring_without_providerName", "some connectionstring"),
                new ConnectionStringSettings("test_connectionstring_with_providerName", "some connectionstring",
                    "System.Data.SqlClient"),
            };

            databaseTarget.Initialize(null);
            Assert.NotNull(databaseTarget.ProviderFactory);
            Assert.Equal(typeof(System.Data.SqlClient.SqlClientFactory), databaseTarget.ProviderFactory.GetType());
        }

        [Theory]
        [InlineData("usetransactions='false'", true)]
        [InlineData("usetransactions='true'", true)]
        [InlineData("", false)]
        public void WarningForObsoleteUseTransactions(string property, bool printWarning)
        {
            LoggingConfiguration c = CreateConfigurationFromString(string.Format(@"
            <nlog ThrowExceptions='true'>
                <targets>
                    <target type='database' {0} name='t1' commandtext='fake sql' connectionstring='somewhere' />
                </targets>
                <rules>
                      <logger name='*' writeTo='t1'>

                      </logger>
                    </rules>
            </nlog>", property));

            StringWriter writer1 = new StringWriter()
            {
                NewLine = "\n"
            };
            InternalLogger.LogWriter = writer1;
            var t = c.FindTargetByName<DatabaseTarget>("t1");
            t.Initialize(null);
            var internalLog = writer1.ToString();

            if (printWarning)
            {
                Assert.Contains("obsolete", internalLog, StringComparison.InvariantCultureIgnoreCase);
                Assert.Contains("usetransactions", internalLog, StringComparison.InvariantCultureIgnoreCase);
            }
            else
            {
                Assert.DoesNotContain("obsolete", internalLog, StringComparison.InvariantCultureIgnoreCase);
                Assert.DoesNotContain("usetransactions", internalLog, StringComparison.InvariantCultureIgnoreCase);
            }

        }

        private static void AssertLog(string expectedLog)
        {
            Assert.Equal(expectedLog.Replace("\r", ""), MockDbConnection.Log.Replace("\r", ""));
        }

        private string GetConnectionString(DatabaseTarget dt)
        {
            MockDbConnection.ClearLog();
            dt.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName;
            dt.CommandText = "NotImportant";

            var exceptions = new List<Exception>();
            dt.Initialize(null);
            dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "msg1").WithContinuation(exceptions.Add));
            dt.Close();

            return MockDbConnection.LastConnectionString;
        }

        public class MockDbConnection : IDbConnection
        {
            public static string Log { get; private set; }
            public static string LastConnectionString { get; private set; }

            public MockDbConnection()
            {
            }

            public MockDbConnection(string connectionString)
            {
                this.ConnectionString = connectionString;
            }

            public IDbTransaction BeginTransaction(IsolationLevel il)
            {
                throw new NotImplementedException();
            }

            public IDbTransaction BeginTransaction()
            {
                throw new NotImplementedException();
            }

            public void ChangeDatabase(string databaseName)
            {
                throw new NotImplementedException();
            }

            public void Close()
            {
                AddToLog("Close()");
            }

            public string ConnectionString { get; set; }

            public int ConnectionTimeout
            {
                get { throw new NotImplementedException(); }
            }

            public IDbCommand CreateCommand()
            {
                return new MockDbCommand() { Connection = this };
            }

            public string Database
            {
                get { throw new NotImplementedException(); }
            }

            public void Open()
            {
                LastConnectionString = this.ConnectionString;
                AddToLog("Open('{0}').", this.ConnectionString);
                if (this.ConnectionString == "cannotconnect")
                {
                    throw new InvalidOperationException("Cannot open fake database.");
                }
            }

            public ConnectionState State
            {
                get { throw new NotImplementedException(); }
            }

            public void Dispose()
            {
                AddToLog("Dispose()");
            }

            public static void ClearLog()
            {
                Log = string.Empty;
            }

            public void AddToLog(string message, params object[] args)
            {
                if (args.Length > 0)
                {
                    message = string.Format(CultureInfo.InvariantCulture, message, args);
                }

                Log += message + "\r\n";
            }
        }

        private class MockDbCommand : IDbCommand
        {
            private int paramCount;
            private IDataParameterCollection parameters;

            public MockDbCommand()
            {
                this.parameters = new MockParameterCollection(this);
            }

            public void Cancel()
            {
                throw new NotImplementedException();
            }

            public string CommandText { get; set; }

            public int CommandTimeout { get; set; }

            public CommandType CommandType { get; set; }

            public IDbConnection Connection { get; set; }

            public IDbDataParameter CreateParameter()
            {
                ((MockDbConnection)this.Connection).AddToLog("CreateParameter({0})", this.paramCount);
                return new MockDbParameter(this, paramCount++);
            }

            public int ExecuteNonQuery()
            {
                ((MockDbConnection)this.Connection).AddToLog("ExecuteNonQuery: {0}", this.CommandText);
                if (this.Connection.ConnectionString == "cannotexecute")
                {
                    throw new InvalidOperationException("Failure during ExecuteNonQuery");
                }

                return 0;
            }

            public IDataReader ExecuteReader(CommandBehavior behavior)
            {
                throw new NotImplementedException();
            }

            public IDataReader ExecuteReader()
            {
                throw new NotImplementedException();
            }

            public object ExecuteScalar()
            {
                throw new NotImplementedException();
            }

            public IDataParameterCollection Parameters
            {
                get { return parameters; }
            }

            public void Prepare()
            {
                throw new NotImplementedException();
            }

            public IDbTransaction Transaction { get; set; }

            public UpdateRowSource UpdatedRowSource
            {
                get { throw new NotImplementedException(); }
                set { throw new NotImplementedException(); }
            }

            public void Dispose()
            {
                throw new NotImplementedException();
            }
        }

        private class MockDbParameter : IDbDataParameter
        {
            private readonly MockDbCommand mockDbCommand;
            private readonly int paramId;
            private string parameterName;
            private object parameterValue;
            private DbType parameterType;

            public MockDbParameter(MockDbCommand mockDbCommand, int paramId)
            {
                this.mockDbCommand = mockDbCommand;
                this.paramId = paramId;
            }

            public DbType DbType
            {
                get { return this.parameterType; }
                set { this.parameterType = value; }
            }

            public ParameterDirection Direction
            {
                get { throw new NotImplementedException(); }
                set
                {
                    ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Direction={1}", paramId,
                        value);
                }
            }

            public bool IsNullable
            {
                get { throw new NotImplementedException(); }
            }

            public string ParameterName
            {
                get { return this.parameterName; }
                set
                {
                    ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Name={1}", paramId, value);
                    this.parameterName = value;
                }
            }

            public string SourceColumn
            {
                get { throw new NotImplementedException(); }
                set { throw new NotImplementedException(); }
            }

            public DataRowVersion SourceVersion
            {
                get { throw new NotImplementedException(); }
                set { throw new NotImplementedException(); }
            }

            public object Value
            {
                get { return this.parameterValue; }
                set
                {
                    ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Value={1}", paramId, value);
                    this.parameterValue = value;
                }
            }

            public byte Precision
            {
                get { throw new NotImplementedException(); }
                set
                {
                    ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Precision={1}", paramId,
                        value);
                }
            }

            public byte Scale
            {
                get { throw new NotImplementedException(); }
                set
                {
                    ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Scale={1}", paramId, value);
                }
            }

            public int Size
            {
                get { throw new NotImplementedException(); }
                set
                {
                    ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Size={1}", paramId, value);
                }
            }

            public override string ToString()
            {
                return "Parameter #" + this.paramId;
            }
        }

        private class MockParameterCollection : IDataParameterCollection
        {
            private readonly MockDbCommand command;

            public MockParameterCollection(MockDbCommand command)
            {
                this.command = command;
            }

            public IEnumerator GetEnumerator()
            {
                throw new NotImplementedException();
            }

            public void CopyTo(Array array, int index)
            {
                throw new NotImplementedException();
            }

            public int Count
            {
                get { throw new NotImplementedException(); }
            }

            public object SyncRoot
            {
                get { throw new NotImplementedException(); }
            }

            public bool IsSynchronized
            {
                get { throw new NotImplementedException(); }
            }

            public int Add(object value)
            {
                ((MockDbConnection)command.Connection).AddToLog("Add Parameter {0}", value);
                return 0;
            }

            public bool Contains(object value)
            {
                throw new NotImplementedException();
            }

            public void Clear()
            {
                throw new NotImplementedException();
            }

            public int IndexOf(object value)
            {
                throw new NotImplementedException();
            }

            public void Insert(int index, object value)
            {
                throw new NotImplementedException();
            }

            public void Remove(object value)
            {
                throw new NotImplementedException();
            }

            public void RemoveAt(int index)
            {
                throw new NotImplementedException();
            }

            object IList.this[int index]
            {
                get { throw new NotImplementedException(); }
                set { throw new NotImplementedException(); }
            }

            public bool IsReadOnly
            {
                get { throw new NotImplementedException(); }
            }

            public bool IsFixedSize
            {
                get { throw new NotImplementedException(); }
            }

            public bool Contains(string parameterName)
            {
                throw new NotImplementedException();
            }

            public int IndexOf(string parameterName)
            {
                throw new NotImplementedException();
            }

            public void RemoveAt(string parameterName)
            {
                throw new NotImplementedException();
            }

            object IDataParameterCollection.this[string parameterName]
            {
                get { throw new NotImplementedException(); }
                set { throw new NotImplementedException(); }
            }
        }

        public class MockDbFactory : DbProviderFactory
        {
            public static readonly MockDbFactory Instance = new MockDbFactory();

            public override DbConnection CreateConnection()
            {
                return new MockDbConnection2();
            }
        }

        public class MockDbConnection2 : DbConnection
        {
            public static int OpenCount { get; private set; }

            public static string LastOpenConnectionString { get; private set; }

            protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
            {
                throw new NotImplementedException();
            }

            public override void ChangeDatabase(string databaseName)
            {
                throw new NotImplementedException();
            }

            public override void Close()
            {
                throw new NotImplementedException();
            }

            public override string ConnectionString { get; set; }

            protected override DbCommand CreateDbCommand()
            {
                throw new NotImplementedException();
            }

            public override string DataSource
            {
                get { throw new NotImplementedException(); }
            }

            public override string Database
            {
                get { throw new NotImplementedException(); }
            }

            public override void Open()
            {
                LastOpenConnectionString = this.ConnectionString;
                OpenCount++;
            }

            public override string ServerVersion
            {
                get { throw new NotImplementedException(); }
            }

            public override ConnectionState State
            {
                get { throw new NotImplementedException(); }
            }
        }

        private static class SqlServerTest
        {

            static SqlServerTest()
            {
            }

            public static string GetConnectionString()
            {
                var connectionString = ConfigurationManager.AppSettings["SqlServerTestConnectionString"];
                if (String.IsNullOrWhiteSpace(connectionString))
                {
                    connectionString = IsAppVeyor() ? AppVeyorConnectionStringNLogTest : LocalConnectionStringNLogTest;
                }
                return connectionString;
            }

            /// <summary>
            /// AppVeyor connectionstring for SQL 2012, see https://www.appveyor.com/docs/services-databases/
            /// </summary>
            private const string AppVeyorConnectionStringMaster =
                @"Server=(local)\SQL2012SP1;Database=master;User ID=sa;Password=Password12!";

            private const string AppVeyorConnectionStringNLogTest =
                @"Server=(local)\SQL2012SP1;Database=NLogTest;User ID=sa;Password=Password12!";

            private const string LocalConnectionStringMaster =
                @"Data Source=(localdb)\MSSQLLocalDB; Database=master; Integrated Security=True;";

            private const string LocalConnectionStringNLogTest =
                @"Data Source=(localdb)\MSSQLLocalDB; Database=NLogTest; Integrated Security=True;";

            public static void CreateDatabase()
            {
                var connectionString = GetMasterConnectionString();
                IssueCommand("CREATE DATABASE NLogTest", connectionString);
            }

            public static bool NLogTestDatabaseExists()
            {
                var connectionString = GetMasterConnectionString();
                var dbId = IssueScalarQuery("select db_id('NLogTest')", connectionString);
                return dbId != null && dbId != DBNull.Value;

            }

            private static string GetMasterConnectionString()
            {
                return IsAppVeyor() ? AppVeyorConnectionStringMaster : LocalConnectionStringMaster;
            }

            /// <summary>
            /// Are we running on AppVeyor?
            /// </summary>
            /// <returns></returns>
            private static bool IsAppVeyor()
            {
                var val = Environment.GetEnvironmentVariable("APPVEYOR");
                return val != null && val.Equals("true", StringComparison.OrdinalIgnoreCase);
            }

            /// <summary>
            /// Are we running on Travis?
            /// </summary>
            /// <returns></returns>
            public static bool IsTravis()
            {
                var val = Environment.GetEnvironmentVariable("TRAVIS");
                return val != null && val.Equals("true", StringComparison.OrdinalIgnoreCase);
            }

            public static void IssueCommand(string commandString, string connectionString = null)
            {
                using (var connection = new SqlConnection(connectionString ?? GetConnectionString()))
                {
                    connection.Open();
                    if (connectionString == null)
                        connection.ChangeDatabase("NLogTest");
                    using (var command = new SqlCommand(commandString, connection))
                    {
                        command.ExecuteNonQuery();
                    }
                }
            }

            public static object IssueScalarQuery(string commandString, string connectionString = null)
            {
                using (var connection = new SqlConnection(connectionString ?? GetConnectionString()))
                {
                    connection.Open();
                    if (connectionString == null)
                        connection.ChangeDatabase("NLogTest");
                    using (var command = new SqlCommand(commandString, connection))
                    {
                        var scalar = command.ExecuteScalar();
                        return scalar;
                    }
                }
            }

            /// <summary>
            /// Try dropping. IF fail, not exception
            /// </summary>
            public static bool TryDropDatabase()
            {
                try
                {
                    if (NLogTestDatabaseExists())
                    {
                        var connectionString = GetMasterConnectionString();
                        IssueCommand(
                            "ALTER DATABASE [NLogTest] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE NLogTest;",
                            connectionString);
                        return true;
                    }
                    return false;

                }
                catch (Exception)
                {

                    //ignore
                    return false;
                }

            }
        }
    }

}

#endif


text:
package net.imagej.ops.threshold.localBernsen;

import net.imagej.ops.Ops;
import net.imagej.ops.map.neighborhood.CenterAwareComputerOp;
import net.imagej.ops.special.function.Functions;
import net.imagej.ops.special.function.UnaryFunctionOp;
import net.imagej.ops.threshold.LocalThresholdMethod;
import net.imagej.ops.threshold.apply.LocalThreshold;
import net.imagej.ops.threshold.localMidGrey.LocalMidGreyThreshold;
import net.imglib2.type.logic.BitType;
import net.imglib2.type.numeric.RealType;
import net.imglib2.util.Pair;

import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

/**
 * LocalThresholdMethod which is similar to {@link LocalMidGreyThreshold}, but uses a
 * constant value rather than the value of the input pixel when the contrast in
 * the neighborhood of that pixel is too small.
 *
 * @author Jonathan Hale
 * @author Stefan Helfrich (University of Konstanz)
 * @param <T> input type
 */
@Plugin(type = Ops.Threshold.LocalBernsenThreshold.class)
public class LocalBernsenThreshold<T extends RealType<T>> extends
	LocalThreshold<T> implements Ops.Threshold.LocalBernsenThreshold
{

	@Parameter
	private double contrastThreshold;

	@Parameter
	private double halfMaxValue;

	@Override
	protected CenterAwareComputerOp<T, BitType> unaryComputer(final T inClass,
		final BitType outClass)
	{
		final LocalThresholdMethod<T> op = new LocalThresholdMethod<T>() {

			private UnaryFunctionOp<Iterable<T>, Pair<T, T>> minMaxFunc;

			@SuppressWarnings({ "unchecked", "rawtypes" })
			@Override
			public void compute(final Iterable<T> neighborhood, final T center,
				final BitType output)
			{

				if (minMaxFunc == null) {
					minMaxFunc = (UnaryFunctionOp) Functions.unary(ops(), Ops.Stats.MinMax.class, Pair.class, neighborhood);
				}

				final Pair<T, T> outputs = minMaxFunc.calculate(neighborhood);
				final double minValue = outputs.getA().getRealDouble();
				final double maxValue = outputs.getB().getRealDouble();
				final double midGrey = (maxValue + minValue) / 2.0;

				if ((maxValue - minValue) < contrastThreshold) {
					output.set(midGrey >= halfMaxValue);
				}
				else {
					output.set(center.getRealDouble() >= midGrey);
				}
			}

			};

		op.setEnvironment(ops());
		return op;
	}

}


text:
ICoordinateMapper::GetDepthFrameToCameraSpaceTable Method
=========================================================

Generates a table of camera space points.

Syntax
======

<colgroup>
<col width="100%" />
</colgroup>

C++

public:
HRESULT GetDepthFrameToCameraSpaceTable(
         UINT32 *tableEntryCount,
         PointF **tableEntries
)

#### Parameters

*tableEntryCount*
Type: UINT32
[out] The number of camera space points.

*tableEntries*
Type: PointF
[out] The table of camera space points.

#### Return value

Type: HRESULT
Returns S\_OK if successful; otherwise, returns a failure code.

Remarks
=======

The table of camera space points must be released with a call to [CoTaskMemFree](http://go.microsoft.com/fwlink/?LinkId=510209).

Requirements
============

**Header:** kinect.h
**Library:** kinect20.lib


text:
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <property name="jnlp.title"    value="JST TranslucentScrollBar" />
  <property name="jnlp.Name"     value="TranslucentScrollBar" />
  <property name="jnlp.name"     value="translucentscrollbar" />
  <property name="jnlp.codebase" value="https://ateraimemo.com/swing/translucentscrollbar/" />
  <property name="jnlp.homepage" value="https://ateraimemo.com/Swing/TranslucentScrollBar.html" />
</project>


text:
@implementation NSDictionary (BFKit)

- (NSString *)dictionaryToJson
{
    return [NSDictionary dictionaryToJson:self];
}

+ (NSString *)dictionaryToJson:(NSDictionary *)dictionary
{
    NSString *json = nil;
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];

    if(!jsonData)
    {
        return @"{}";
    }
    else if(!error)
    {
        json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        return json;
    }
    else
    {
        return error.localizedDescription;
    }
}

@end


text:
/**
 * Created by Cyril on 14-3-8.
 */

"use strict";
var Log =  require('../models/database').Log;
var Site = require("../models/database").Site;
var Email = require('../models/database').Email;
var Diary = require('../models/database').Diary;
var setting = require('../settings');
var mail = require('../controller/utils').mail;
var cheerio = require('cheerio');
exports.updateAbout = function(q,s, next){
    if(!q.body.site||!q.body.site.about){
        q.flash('error',"Sorry, About content can't be blank!");
        s.redirect('back');
        return;
    }
    Site.count(function(err,count){
        if(count > 1){
            q.flash('error',"Server is Error....");
            s.redirect('back');
            return;
        }
        if(count <1){
            var site = new Site({
                logo: "Cyrilis.com",
                name: "Eblog",
                desc: "github/cyrilis/Eblog",
                about: q.body.site.about
            });
            site.save(function(err,site){
                if(err){
                    next(err);
                    return;
                }
                s.locals({
                    site: site
                });
                q.flash('success',"Site Updated Successfully!");
                s.redirect('back');
            });
        }
        Site.findOne(function(err,site){
            if(err){
                next(err);
                return;
            }
            site.about = q.body.site.about;
            q.flash("success","Site Updated Successfully!");
            s.locals({
                site: site
            });
            s.redirect('back');
            site.save();
        });
    });
};

exports.getAbout = function(q,s){
    s.render("about");
};
exports.updateSite= function(q,s,next){
    if(q.body.site){
        Site.findOneAndUpdate(null, q.body.site, function(err,site){
            if(err){
                next(err);
                return;
            }
            q.flash('success',"Site information updated Successfully!");
            s.locals({
                site: site
            });
            s.redirect('back');
        });
    }
    next();
};

exports.visiteLogs = function(q,s,next){
    var limit = 100;
    var skip = ((q.query.page||1)-1)*limit;
    Log.find().limit(limit).skip(skip).sort("-date").exec(function(err,logs){
        if(err){
            console.log(err);
            next(err);
            return;
        }
        s.render('settings/logs',{
            logs: logs,
            limit: limit,
            page: q.query.page||1
        });
    });
};

exports.receiveEmail = function(q,s,next){
    var emailInfo = q.body;
    emailInfo.time = new Date();
    emailInfo.type = "receive";
    var email = new Email(emailInfo);
    email.save(function(err,email){
        if (err){
            console.log(err);
            next(err);
        }
        console.log(email.Subject);
        mail(email.sender, setting.mailto, email.subject + "[To: "+(email.To||email.recipient)+"]", email['body-html'], email['body-text']);
        s.send('Got it!');
    });
    if (emailInfo.subject.indexOf('[Daily Mail]') > -1 && emailInfo.sender === setting.mailto){
        console.log('Diary Got, saving.....');
        var diaryParams = {
            content: emailInfo['body-html'],
            time: new Date(),
            from: emailInfo.sender
        };
        var $ = cheerio.load( diaryParams.content);

        $(".gmail_quote").remove();
        diaryParams.content = $.html();

        new Diary(diaryParams).save(function(err, result){
            if(err){
                console.log(err);
                return false;
            }
            console.log("New Diary Saved.");
            console.log(result);
        });
    }
};

exports.handleGithub = function(q,s, next){

};


text:
package iso20022

// Provides information about event of a corporate action.
type EventInformation9 struct {

	// Reference assigned by the account servicer to unambiguously identify a corporate action event.
	CorporateActionEventIdentification *Max35Text `xml:"CorpActnEvtId"`

	// Provides the reference of the linked official corporate action event.
	OfficialCorporateActionEventIdentification *Max35Text `xml:"OffclCorpActnEvtId,omitempty"`

	// Type of corporate action event.
	EventType *CorporateActionEventType52Choice `xml:"EvtTp"`

	// Specifies whether the event is mandatory, mandatory with options or voluntary.
	MandatoryVoluntaryEventType *CorporateActionMandatoryVoluntary3Choice `xml:"MndtryVlntryEvtTp"`

	// Provides information about the identification of the last notification.
	LastNotificationIdentification *NotificationIdentification3 `xml:"LastNtfctnId,omitempty"`
}

func (e *EventInformation9) SetCorporateActionEventIdentification(value string) {
	e.CorporateActionEventIdentification = (*Max35Text)(&value)
}

func (e *EventInformation9) SetOfficialCorporateActionEventIdentification(value string) {
	e.OfficialCorporateActionEventIdentification = (*Max35Text)(&value)
}

func (e *EventInformation9) AddEventType() *CorporateActionEventType52Choice {
	e.EventType = new(CorporateActionEventType52Choice)
	return e.EventType
}

func (e *EventInformation9) AddMandatoryVoluntaryEventType() *CorporateActionMandatoryVoluntary3Choice {
	e.MandatoryVoluntaryEventType = new(CorporateActionMandatoryVoluntary3Choice)
	return e.MandatoryVoluntaryEventType
}

func (e *EventInformation9) AddLastNotificationIdentification() *NotificationIdentification3 {
	e.LastNotificationIdentification = new(NotificationIdentification3)
	return e.LastNotificationIdentification
}


text:
module STingsRoutes #:nodoc:
  module Routing #:nodoc:
    module MapperExtensions
      def s_tings
        send :resources, :settings, :except => [:edit, :create, :new], :collection => {:update_all => :put}
      end
    end
  end
end

ActionController::Routing::RouteSet::Mapper.send :include, STingsRoutes::Routing::MapperExtensions


text:
package de.sopa.helper;

import de.sopa.model.game.Level;
import de.sopa.model.game.Tile;
import de.sopa.model.game.TileType;
import org.junit.Before;
import org.junit.Test;

import static de.sopa.model.game.TileType.FINISH;
import static de.sopa.model.game.TileType.PUZZLE;
import static de.sopa.model.game.TileType.START;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

/**
 * @author David Schilling - davejs92@gmail.com
 */
public class LevelTranslatorTest {

    private LevelTranslator sut;
    private static final String[] levelAsString = {
            "5",
            "2",
            "6",
            "#",
            "nnnsnn",
            "ncooen",
            "noooin",
            "noooin",
            "ngooun",
            "nnnfnn"
    };
    private static final String[] invalidLevelAsString = {
            "5",
            "2",
            "6",
            "#",
            "nonsnn",
            "ncooen",
            "noooin",
            "noooin",
            "ngooun",
            "nnnfnn"
    };
    private Level level;

    @Before
    public void setUp() {
        sut = new LevelTranslator();
        level = new Level();
        setupLevel();
    }

    @Test
    public void fromString() {
        Level resultingLevel = sut.fromString(levelAsString);
        assertThat(resultingLevel, is(level));
    }

    @Test(expected = IllegalArgumentException.class)
    public void fromStringInvalid() {
        sut.fromString(invalidLevelAsString);
    }

    private void setupLevel() {
        level.setId(5);
        level.setMinimumMovesToSolve(2);
        level.setTilesCount(6);
        level.setStartX(3);
        level.setStartY(0);
        Tile[][] field = new Tile[][]{
                new Tile[]{new Tile(), new Tile(), new Tile(), new Tile(false, true, false, false, START, 's'), new Tile(), new Tile()},
                new Tile[]{new Tile(), new Tile(false, true, true, false, TileType.PUZZLE, 'c'), new Tile(PUZZLE, 'o'), new Tile(PUZZLE, 'o'), new Tile(true, false, false, true, PUZZLE, 'e'), new Tile()},
                new Tile[]{new Tile(), new Tile(TileType.PUZZLE, 'o'), new Tile(PUZZLE, 'o'), new Tile(PUZZLE, 'o'), new Tile(true, true, false, false, PUZZLE, 'i'), new Tile()},
                new Tile[]{new Tile(), new Tile(TileType.PUZZLE, 'o'), new Tile(PUZZLE, 'o'), new Tile(PUZZLE, 'o'), new Tile(true, true, false, false, PUZZLE, 'i'), new Tile()},
                new Tile[]{new Tile(), new Tile(true, false, true, false, TileType.PUZZLE, 'g'), new Tile(PUZZLE, 'o'), new Tile(PUZZLE, 'o'), new Tile(false, true, false, true, PUZZLE, 'u'), new Tile()},
                new Tile[]{new Tile(), new Tile(), new Tile(), new Tile(true, false, false, false, FINISH, 'f'), new Tile(), new Tile()},
        };
        level.setField(swapColumnAndRow(field));
    }

    private Tile[][] swapColumnAndRow(Tile[][] field) {
        Tile[][] fieldSwapped = new Tile[field[0].length][];
        for (int row = 0; row < field[0].length; row++) {
            fieldSwapped[row] = new Tile[field.length];
        }
        for (int row = 0; row < field.length; row++) {
            for (int col = 0; col < field[row].length; col++) {
                fieldSwapped[col][row] = field[row][col];
            }
        }
        return fieldSwapped;

    }
}