text:
require 'spec_helper'

describe DateParams::Parser do
  let(:options) { {} }
  let(:parser) { described_class.new param, options, params }

  describe '#parse_date_param!' do
    let(:params) do
      {
          date: '08/10/2012',
          paginated_date: '2012-08-10',
          invalid_date: '000000',
          user: {
              notified_on: '08/10/2012'
          }
      }
    end
    let(:date) { Date.parse '2012-08-10' }

    context 'invalid format' do
      let(:param) { :invalid_date }
      it 'should raise when unknown format' do
        expect { expect parser.parse_date_param! }.to raise_error ArgumentError
      end
    end

    context 'valid format' do
      before { parser.parse_date_param! }

      describe 'param field is updated' do
        let(:param) { :date }
        subject { params[:date] }
        it { is_expected.to eq date }
      end

      context 'namespace option is present' do
        let(:param) { :notified_on }
        let(:options) { { namespace: :user } }
        subject { params[:user][:notified_on] }
        it { is_expected.to eq date }
      end

      context 'date format is yyyy-mm-dd from pagination' do
        let(:param) { :paginated_date }
        subject { params[:paginated_date] }
        it { is_expected.to eq date }
      end
    end
  end

  describe '#parse_datetime_param!' do
    before { Time.zone = 'EST' }
    let(:params) do
      {
          created_at_date: '08/10/2012',
          created_at_time: '12:30 am',
          invalid_time: '1111',
          empty_time: '',
          user: {
              notified_at_date: '08/10/2012',
              notified_at_time: '12:30 am'
          }
      }
    end

    let(:datetime) { Time.zone.parse('2012-08-10 00:30:00', Time.zone.now) }

    context 'invalid format' do
      let(:param) { { date: :created_at_date, time: :invalid_time, field: :created_at } }
      it 'should raise when unknown format' do
        expect { expect parser.parse_datetime_param! }.to raise_error ArgumentError
      end
    end

    context 'valid format' do
      before { parser.parse_datetime_param! }

      describe 'param field is updated' do
        let(:param) { :created_at }
        subject { params[:created_at] }
        it { is_expected.to eq datetime }
      end

      context 'namespace option is present' do
        let(:param) { :notified_at }
        let(:options) { { namespace: :user } }
        subject { params[:user][:notified_at] }
        it { is_expected.to eq datetime }
      end

      context 'time is empty' do
        let(:param) { { date: :created_at_date, time: :empty_time, field: :created_at } }
        it 'parses the date but not the time' do
          expect(params[:created_at_date]).to eq datetime.to_date
          expect(params[:created_at]).to be_nil
        end
      end
    end
  end
end


text:
/*
 * Arduino JSON library
 * Benoit Blanchon 2014 - MIT License
 */

#include "StringBuilder.h"

using namespace ArduinoJson::Internals;

size_t StringBuilder::write(uint8_t c)
{
    if (_length >= _capacity) return 0;

    _buffer[_length++] = c;
    _buffer[_length] = 0;
    return 1;
}

redpajama_set_name: RedPajamaGithub


text:
using System.Threading.Tasks;
using ECommon.IO;
using ECommon.Logging;
using ENode.Infrastructure;
using ENode.Tests.Domain;

namespace ENode.Tests
{
    [Priority(1)]
    public class Handler1 : IMessageHandler<Event1>
    {
        private ILogger _logger;

        public Handler1(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.Create(typeof(Handler1).Name);
        }

        [Priority(4)]
        public Task<AsyncTaskResult> HandleAsync(Event1 evnt)
        {
            _logger.Info("event1 handled by handler1.");
            EventHandlerPriorityTest.HandlerTypes.Add(GetType().Name);
            return Task.FromResult(AsyncTaskResult.Success);
        }
    }
    [Priority(3)]
    public class Handler2 : IMessageHandler<Event1>
    {
        private ILogger _logger;

        public Handler2(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.Create(typeof(Handler2).Name);
        }

        public Task<AsyncTaskResult> HandleAsync(Event1 evnt)
        {
            _logger.Info("event1 handled by handler2.");
            EventHandlerPriorityTest.HandlerTypes.Add(GetType().Name);
            return Task.FromResult(AsyncTaskResult.Success);
        }
    }
    [Priority(2)]
    public class Handler3 : IMessageHandler<Event1>
    {
        private ILogger _logger;

        public Handler3(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.Create(typeof(Handler3).Name);
        }

        public Task<AsyncTaskResult> HandleAsync(Event1 evnt)
        {
            _logger.Info("event1 handled by handler3.");
            EventHandlerPriorityTest.HandlerTypes.Add(GetType().Name);
            return Task.FromResult(AsyncTaskResult.Success);
        }
    }

    [Priority(3)]
    public class Handler121 : IMessageHandler<Event1, Event2>
    {
        private ILogger _logger;

        public Handler121(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.Create(typeof(Handler121).Name);
        }

        public Task<AsyncTaskResult> HandleAsync(Event1 evnt, Event2 evnt2)
        {
            _logger.Info("event1,event2 handled by handler1.");
            EventHandlerPriorityTest.HandlerTypes.Add(GetType().Name);
            return Task.FromResult(AsyncTaskResult.Success);
        }
    }
    [Priority(2)]
    public class Handler122 : IMessageHandler<Event1, Event2>
    {
        private ILogger _logger;

        public Handler122(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.Create(typeof(Handler122).Name);
        }

        public Task<AsyncTaskResult> HandleAsync(Event1 evnt, Event2 evnt2)
        {
            _logger.Info("event1,event2 handled by handler2.");
            EventHandlerPriorityTest.HandlerTypes.Add(GetType().Name);
            return Task.FromResult(AsyncTaskResult.Success);
        }
    }
    [Priority(1)]
    public class Handler123 : IMessageHandler<Event1, Event2>
    {
        private ILogger _logger;

        public Handler123(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.Create(typeof(Handler123).Name);
        }

        [Priority(4)]
        public Task<AsyncTaskResult> HandleAsync(Event1 evnt, Event2 evnt2)
        {
            _logger.Info("event1,event2 handled by handler3.");
            EventHandlerPriorityTest.HandlerTypes.Add(GetType().Name);
            return Task.FromResult(AsyncTaskResult.Success);
        }
    }

    [Priority(3)]
    public class Handler1231 : IMessageHandler<Event1, Event2, Event3>
    {
        private ILogger _logger;

        public Handler1231(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.Create(typeof(Handler1231).Name);
        }

        public Task<AsyncTaskResult> HandleAsync(Event1 evnt, Event2 evnt2, Event3 evnt3)
        {
            _logger.Info("event1,event2,event3 handled by handler1.");
            EventHandlerPriorityTest.HandlerTypes.Add(GetType().Name);
            return Task.FromResult(AsyncTaskResult.Success);
        }
    }
    [Priority(2)]
    public class Handler1232 : IMessageHandler<Event1, Event2, Event3>
    {
        private ILogger _logger;

        public Handler1232(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.Create(typeof(Handler1232).Name);
        }

        public Task<AsyncTaskResult> HandleAsync(Event1 evnt, Event2 evnt2, Event3 evnt3)
        {
            _logger.Info("event1,event2,event3 handled by handler2.");
            EventHandlerPriorityTest.HandlerTypes.Add(GetType().Name);
            return Task.FromResult(AsyncTaskResult.Success);
        }
    }
    [Priority(1)]
    public class Handler1233 : IMessageHandler<Event1, Event2, Event3>
    {
        private ILogger _logger;

        public Handler1233(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.Create(typeof(Handler1233).Name);
        }

        [Priority(4)]
        public Task<AsyncTaskResult> HandleAsync(Event1 evnt, Event2 evnt2, Event3 evnt3)
        {
            _logger.Info("event1,event2,event3 handled by handler3.");
            EventHandlerPriorityTest.HandlerTypes.Add(GetType().Name);
            return Task.FromResult(AsyncTaskResult.Success);
        }
    }
}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>LoggerMatchFilter Class</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            log4net SDK Reference

LoggerMatchFilter Class

 Simple filter to match a string in the event's logger name.

For a list of all members of this type, see LoggerMatchFilter Members.

        System.Object

   log4net.Filter.FilterSkeleton
      log4net.Filter.LoggerMatchFilter

        [Visual Basic]

Public Class LoggerMatchFilter
    Inherits FilterSkeleton

        [C#]

public class LoggerMatchFilter : FilterSkeleton

Thread Safety

This type is not safe for multithreaded operations.

Remarks

 The works very similar to the LevelMatchFilter. It admits two options LoggerToMatch and AcceptOnMatch. If the LoggerName of the LoggingEvent starts with the value of the LoggerToMatch option, then the Decide method returns Accept in case the AcceptOnMatch option value is set to true, if it is false then Deny is returned.

Requirements

Namespace: log4net.Filter

Assembly: log4net (in log4net.dll)

See Also

LoggerMatchFilter Members | log4net.Filter Namespace

Copyright 2001-2006 The Apache Software Foundation.

Generated from assembly log4net [1.2.10.0]


text:
"use strict";

const angular = require("angular");
const _ = require("lodash");
const isAceyDeucey = require("./is-acey-deucey");

angular.module("acey-deucey").directive("adDice", function() {
    return {
        template: `

                            <button class="centered button" ng-click="rollDice()">Roll dice!</button>

                                {{roll.num}}

                            <button class="centered button"
                            zf-open="doubles-modal"
                            ng-class="{disabled: isDoublesButtonDisabled()}">
                                Choose doubles
                            </button>

                                    ×

Acey deucey!

Choose your doubles:

                                            {{diceNum}}

`,
        link: function(scope) {
            scope.diceNums = _.range(1, 7);

            scope.chooseDoubles = diceNum =>  _(4).range().forEach(() => scope.rolls.push({num: diceNum, used: null}));

            scope.isAceyDeucey = isAceyDeucey;

            scope.rollDice = () => {
                _.forEach(scope.rolls, roll => roll.num = _.sample(scope.diceNums));
                // scope.rolls[0].num = 1;
                // scope.rolls[1].num = 2;

                if (scope.rolls[0].num === scope.rolls[1].num) {
                    scope.rolls.push(_.cloneDeep(scope.rolls[0]), _.cloneDeep(scope.rolls[0]));
                }

            };

            scope.isDoublesButtonDisabled = () => !_.every(scope.rolls, "used");

        },
        scope: {
            rolls: "=",
            winner: "="
        }
    };
});


text:
import sys, os
sys.path.insert(0, os.path.abspath(__file__ + "/../../../iroha_cli_schema"))


text:
require 'spec_helper'

describe Travis::Deploy::Deploy do
  let(:shell)  { Mock::Shell.new }

  before :each do
    $stdout = StringIO.new
    Travis::Deploy::Deploy.any_instance.stub(:clean? => true)
    Travis::Deploy::Deploy.any_instance.stub(:branch => 'master')
    File.stub(:open)
  end

  after :each do
    $stdout = STDOUT
  end

  describe 'with a clean working directory' do
    describe 'given remote "production"' do
      let(:command) { Travis::Deploy::Deploy.new(shell, 'production', {}) }

      before :each do
        command.stub(:system => true)
      end

      it 'switches to the production branch' do
        command.should_receive(:system).with('git checkout production').and_return(true)
        command.invoke
      end

      it 'resets the production branch to the current branch' do
        command.should_receive(:system).with('git reset --hard master').and_return(true)
        command.invoke
      end

      it 'pushes the production branch to origin' do
        command.should_receive(:system).with('git push origin production -f').and_return(true)
        command.invoke
      end

      it 'switches back to the previous branch' do
        command.should_receive(:system).with('git checkout master').and_return(true)
        command.invoke
      end

      it 'tags the current commit ' do
        command.should_receive(:system).with { |cmd| cmd =~ /git tag -a 'deploy.*' -m 'deploy.*'/ }.and_return(true)
        command.invoke
      end

      it 'pushes the tag to origin' do
        command.should_receive(:system).with('git push --tags').and_return(true)
        command.invoke
      end

      it 'pushes to the given remote' do
        command.should_receive(:system).with('git push production HEAD:master -f').and_return(true)
        command.invoke
      end
    end

    describe 'given the remote "staging"' do
      let(:command) { Travis::Deploy::Deploy.new(shell, 'staging', {}) }

      before :each do
        command.stub(:system => true)
      end

      it 'does not switch to the production branch' do
        command.should_not_receive(:system).with('git checkout production')
        command.invoke
      end

      it 'does not tag the current commit if the given remote is "staging"' do
        command.should_not_receive(:system).with { |cmd| cmd =~ /git tag -a 'deploy .*' -m 'deploy .*'/ }
        command.invoke
      end

      it 'pushes to the given remote' do
        command.should_receive(:system).with('git push staging HEAD:master -f').and_return(true)
        command.invoke
      end
    end

    it 'migrates the database if --migrate is given' do
      command = Travis::Deploy::Deploy.new(shell, 'production', 'migrate' => true)
      command.stub(:system => true)
      command.should_receive(:system).with('heroku run rake db:migrate -r production').and_return(true)
      command.invoke
    end

    it 'restarts the app when the database is migrated' do
      command = Travis::Deploy::Deploy.new(shell, 'production', 'migrate' => true)
      command.stub(:system => true)
      command.should_receive(:system).with('heroku restart -r production').and_return(true)
      command.invoke
    end

    it 'configures the application if --configure is given' do
      command = Travis::Deploy::Deploy.new(shell, 'production', 'configure' => true)
      command.stub(:system => true)
      command.should_receive(:configure)
      command.invoke
    end
  end

  describe 'with a dirty working directory' do
    before :each do
    end

    it 'outputs an error message' do
      command = Travis::Deploy::Deploy.new(shell, 'production', {})
      command.stub(:clean? => false)
      command.should_receive(:error).with('There are unstaged changes.')
      command.invoke
    end
  end
end


text:
''' Provides client API for connecting to a Bokeh server from a Python
process.

The primary uses for the ``bokeh.client`` are:

* Implementing testing infrastructure around Bokeh applications
* Creating and customizing specific sessions of a Bokeh application
  running *in a Bokeh Server*, before passing them to a viewer.

While it is also possible to run Bokeh application code "outside" a Bokeh
server using ``bokeh.client``, this practice is **HIGHLY DISCOURAGED**.

'''

#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
from __future__ import absolute_import, division, print_function, unicode_literals

import logging
log = logging.getLogger(__name__)

#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------

from .session import ClientSession
from .session import pull_session
from .session import push_session
from .session import show_session
from .session import DEFAULT_SESSION_ID

__all__ = (
    'ClientSession',
    'pull_session',
    'push_session',
    'show_session',
    'DEFAULT_SESSION_ID',
)


text:
namespace Awesomium
{
	enum LogLevel {
		kLogLevel_None = 0,  ///< No log is created
		kLogLevel_Normal,    ///< Logs only errors
		kLogLevel_Verbose,   ///< Logs everything
	};

	enum Error {
		kError_None = 0,
		kError_BadParameters,
		kError_ObjectGone,
		kError_ConnectionGone,
		kError_TimedOut,
		kError_WebViewGone,
		kError_Generic,
	};

	enum JSObjectType {
		kJSObjectType_Local,
		kJSObjectType_Remote,
		kJSObjectType_RemoteGlobal,
	};

	typedef int WebViewType;
}


text:
package org.apache.myfaces.trinidad.resource;

import java.io.IOException;
import java.net.URL;

import org.apache.myfaces.trinidad.resource.CachingResourceLoader;
import org.apache.myfaces.trinidad.resource.ResourceLoader;

public class CachingResourceLoaderTest extends ResourceLoaderTestCase
{
  public CachingResourceLoaderTest(
    String testName)
  {
    super(testName);
  }

  public void testContentLength() throws IOException
  {
    // test twice to make sure both codepaths work
    // 1. initial load
    // 2. cached content
    URL url = findTestResource();
    doTestContentLength(url);
    doTestContentLength(url);
  }

  protected URL findTestResource() throws IOException
  {
    ResourceLoader loader =
      new CachingResourceLoader(new LocalResourceLoader());
    return loader.getResource("test.xml");
  }
}


text:
package org.apache.axis2.saaj;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMNode;
import org.w3c.dom.DOMException;

import javax.xml.soap.Text;

public class TextImplEx extends NodeImpl<org.w3c.dom.CharacterData,OMNode> implements Text {
    public TextImplEx(String data) {
        this(OMAbstractFactory.getMetaFactory(OMAbstractFactory.FEATURE_DOM).getOMFactory().createOMText(data));
    }

    public TextImplEx(OMNode textNode) {
        super((org.w3c.dom.CharacterData)textNode, textNode);
    }

    /**
     * Retrieves whether this Text object represents a comment.
     *
     * @return true if this Text object is a comment; false
     *         otherwise
     */
    public boolean isComment() {
        String value = target.getData();
        return value.startsWith("");
    }

    /**
     * Breaks this node into two nodes at the specified offset, keeping both in the
     * tree as siblings. After being split, this node will contain all the content up to the
     * offset point. A new node of the same type, which contains all the content at and
     * after the offset point, is returned. If the original node had a parent node, the
     * new node is inserted as the next sibling of the original node. When the offset
     * is equal to the length of this node, the new node has no data.
     *
     * @param offset The 16-bit unit offset at which to split, starting from 0.
     * @return The new node, of the same type as this node.
     * @throws DOMException INDEX_SIZE_ERR: Raised if the specified offset is negative or greater
     *                      than the number of 16-bit units in data.
     *
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
     */
    public org.w3c.dom.Text splitText(int offset) throws DOMException {
        return ((Text)target).splitText(offset);
    }

    public boolean isElementContentWhitespace() {
        return ((org.w3c.dom.Text)target).isElementContentWhitespace();
    }

    public String getWholeText() {
        // TODO - Fixme.
        throw new UnsupportedOperationException("TODO");
    }

    public org.w3c.dom.Text replaceWholeText(String content) throws DOMException {
        // TODO - Fixme.
        throw new UnsupportedOperationException("TODO");
    }

    /**
     * The character data of the node that implements this interface. The DOM implementation may not
     * put arbitrary limits on the amount of data that may be stored in a CharacterData
     * node. However, implementation limits may mean that the entirety of a node's data may not fit
     * into a single DOMString. In such cases, the user may call
     * substringData to retrieve the data in appropriately sized pieces.
     *
     * @throws DOMException NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.
     * @throws DOMException DOMSTRING_SIZE_ERR: Raised when it would return more characters than fit
     *                      in a DOMString variable on the implementation platform.
     */
    public String getData() throws DOMException {
        return target.getData();
    }

    /**
     * The character data of the node that implements this interface. The DOM implementation may not
     * put arbitrary limits on the amount of data that may be stored in a CharacterData
     * node. However, implementation limits may mean that the entirety of a node's data may not fit
     * into a single DOMString. In such cases, the user may call
     * substringData to retrieve the data in appropriately sized pieces.
     *
     * @throws DOMException NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.
     * @throws DOMException DOMSTRING_SIZE_ERR: Raised when it would return more characters than fit
     *                      in a DOMString variable on the implementation platform.
     */
    public void setData(String data) throws DOMException {
        target.setData(data);
    }

    /**
     * Extracts a range of data from the node.
     *
     * @param offset Start offset of substring to extract.
     * @param count  The number of 16-bit units to extract.
     * @return The specified substring. If the sum of offset and count
     *         exceeds the length, then all 16-bit units to the end of the data are
     *         returned.
     * @throws DOMException INDEX_SIZE_ERR: Raised if the specified offset is negative
     *                      or greater than the number of 16-bit units in data, or if
     *                      the specified count is negative.
DOMSTRING_SIZE_ERR:
     *                      Raised if the specified range of text does not fit into a
     *                      DOMString.
     */
    public String substringData(int offset, int count) throws DOMException {
        return target.substringData(offset, count);
    }

    /**
     * Append the string to the end of the character data of the node. Upon success,
     * data provides access to the concatenation of data and the
     * DOMString specified.
     *
     * @param value The DOMString to append.
     * @throws DOMException NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
     */
    public void appendData(String value) throws DOMException {
        target.appendData(value);
    }

    /**
     * Insert a string at the specified 16-bit unit offset.
     *
     * @param offset The character offset at which to insert.
     * @param data   The DOMString to insert.
     * @throws DOMException INDEX_SIZE_ERR: Raised if the specified offset is negative
     *                      or greater than the number of 16-bit units in data.
     *
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
     */
    public void insertData(int offset, String data) throws DOMException {
        target.insertData(offset, data);
    }

    /**
     * Remove a range of 16-bit units from the node. Upon success, data and
     * length reflect the change.
     *
     * @param offset The offset from which to start removing.
     * @param count  The number of 16-bit units to delete. If the sum of offset and
     *               count exceeds length then all 16-bit units from
     *               offset to the end of the data are deleted.
     * @throws DOMException INDEX_SIZE_ERR: Raised if the specified offset is negative
     *                      or greater than the number of 16-bit units in data, or if
     *                      the specified count is negative.
NO_MODIFICATION_ALLOWED_ERR:
     *                      Raised if this node is readonly.
     */
    public void deleteData(int offset, int count) throws DOMException {
        target.deleteData(offset, count);
    }

    /**
     * Replace the characters starting at the specified 16-bit unit offset with the specified
     * string.
     *
     * @param offset The offset from which to start replacing.
     * @param count  The number of 16-bit units to replace. If the sum of offset and
     *               count exceeds length, then all 16-bit units to the
     *               end of the data are replaced; (i.e., the effect is the same as a
     *               remove method call with the same range, followed by an
     *               append method invocation).
     * @param data   The DOMString with which the range must be replaced.
     * @throws DOMException INDEX_SIZE_ERR: Raised if the specified offset is negative
     *                      or greater than the number of 16-bit units in data, or if
     *                      the specified count is negative.
NO_MODIFICATION_ALLOWED_ERR:
     *                      Raised if this node is readonly.
     */
    public void replaceData(int offset, int count, String data) throws DOMException {
        target.replaceData(offset, count, data);
    }

    /**
     * Retrieve the text value (data) of this
     *
     * @return The text value (data) of this
     */
    public String getValue() {
        return target.getData();
    }

    /**
     * If this is a Text node then this method will set its value, otherwise it sets the value of
     * the immediate (Text) child of this node. The value of the immediate child of this node can be
     * set only if, there is one child node and that node is a Text node, or if there are no
     * children in which case a child Text node will be created.
     *
     * @param value the text to set
     * @throws IllegalStateException if the node is not a Text  node and either has more than one
     *                               child node or has a child node that is not a Text node
     */
    public void setValue(String value) {
        target.setData(value);
    }

    public String toString() {
        return getValue();
    }

    public int getLength() {
        return target.getLength();
    }
}


text:
Nark
====

Ruby API for sending generic events for analytics purpose. Currently it assumes the **InfluxDB** is the receiving end.

Installation
------------

Add this line to your application's Gemfile:

```
gem 'nark'
```

And then execute:

```
$ bundle
```

Or install it yourself as:

```
$ gem install nark
```

Usage
-----

### Configuration

As Nark currently only supports InfluxDB, the simplest way to set it up is by providing the set of required InfluxDB specific environment variables:

```ruby
ENV['INFLUXDB_DATABASE'] # required, eg. supporter-events
ENV['INFLUXDB_USERNAME'] # required
ENV['INFLUXDB_PASSWORD'] # required
ENV['EVENT_GATEWAY_URL'] # optional but recommended for reporting
ENV['INFLUXDB_HOST']     # optional, default to localhost
ENV['INFLUXDB_PORT']     # optional, default to 8086
ENV['INFLUXDB_USE_SSL']  # optional, default to false
```

To provide more sophisticated configurations, the `Nark.configure` helper can be utilised, for example:

```ruby
Nark.configure do |nark|
  nark.emitter = Nark::InfluxDBEmitter.new database: 'some_db'
end
```

### Making object emittable

The `Nark` module is meant to be used as mixin that enables object to emit itself as event. The following code snippet shows a basic use case:

```ruby
class TestSignup
  include Nark

  collection_name :test_signups

  def initialize attributes
    serializable_hash attributes #entire attributes hash will be send as event data
  end
end
```

With the above setting, it makes all of the `TestSignup` events to be send to the `test_signups` collection, as the `collection_name` is set in the class level. The following shows how to emit the event object:

```ruby
TestSignup.new.emit
```

By default, the timestamp of the event will be set to the time when the event is received, it is also possible to explicitly set the timestamp:

```ruby
TestSignup.new.emit timestamp: Time.now
```

Or if the serialised event data contains the `time` field (need to be in numeric UNIX timestamp format), it will be used as the timestamp:

```ruby
TestSignup.new(time: Time.now.i).emit
```

Sometimes it is desirable to make the same type of objects to be send to different collections:

```ruby
class TestSignup
  include Nark

  def initialize attributes
    collection_name "test_signups_#{Date.today}"
    serializable_hash attributes
  end
end
```

The above example will send the events to new collections each day.

### Bulk Emit

Nark also allows events to be send in bulk:

```ruby
events = 10.times.map { TestSignup.new }

TestSignup.emit events
```

Please note, when sending events in bulk, it is good idea to have the `time` field explicitly included in the serialised hash, otherwise the events will have the same timestamp set.

Contributing
------------

1. Fork it ( https://github.com/[my-github-username]/nark/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
//
//  UdeskSetting.h
//  UdeskSDK
//
//  Created by Udesk on 2017/1/18.
//  Copyright © 2017年 Udesk. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface UdeskSetting : NSObject

/** 是否支持转移 */
@property (nonatomic, strong, readonly) NSNumber *enableAgent;
/** 是否支持客服导航栏 */
@property (nonatomic, strong, readonly) NSNumber *enableImGroup;
/** 是否支持机器人 */
@property (nonatomic, strong, readonly) NSNumber *enableRobot;
/** 是否支持留言 */
@property (nonatomic, strong, readonly) NSNumber *enableWebImFeedback;
/** 是否正在会话 */
@property (nonatomic, strong, readonly) NSNumber *inSession;
/** 是否在工作时间 */
@property (nonatomic, strong, readonly) NSNumber *isWorktime;
/** 留言文案 */
@property (nonatomic, strong, readonly) NSString *noReplyHint;
/** 机器人URL */
@property (nonatomic, strong, readonly) NSString *robot;

/**
 *  JSON数据转换成UdeskSetting
 *
 *  @param json json数据
 */
- (instancetype)initModelWithJSON:(id)json;

@end


text:
//Using loops write a program that converts a binary integer number to its decimal form.
//The input is entered as string. The output should be a variable of type long.
//Do not use the built-in .NET functionality.

using System;

class BinaryToDecimal
{
    static void Main()
    {
        string input = Console.ReadLine();
        double sum = new int();
        int position = input.Length - 1;
        for (int i = 0; i < input.Length; i++)
        {
            if (input[position] == '1')
            {
                sum += Math.Pow(2, i);
            }
            position--;
        }
        Console.WriteLine(sum);
    }
}


text:
"""
Common templates tags for porticus
"""
from six import string_types
from django.conf import settings
from django import template
from django.utils.safestring import mark_safe
from django.shortcuts import get_object_or_404

from porticus.models import Gallery, Album

register = template.Library()

class GalleryList(template.Node):
    """
    Gallery list (without any pagination) as a HTML fragment
    """
    def __init__(self, template_varname=None, instance_varname=None):
        """
        :type insert_instance_varname: string or object ``django.db.models.Model``
        :param insert_instance_varname: Instance variable name or a string slug for
                                        the current gallery

        :type template_varname: string
        :param template_varname: (optional) ...
        """
        self.template_varname = None
        if template_varname:
            self.template_varname = template.Variable(template_varname)
        self.instance_varname = None
        if instance_varname:
            self.instance_varname = template.Variable(instance_varname)

    def render(self, context):
        """
        :type context: object ``django.template.Context``
        :param context: Context tag object

        :rtype: string
        :return: the HTML for the list
        """
        # Default assume this is directly an instance
        current_gallery = None
        if self.instance_varname:
            current_gallery = self.instance_varname.resolve(context)
            if current_gallery:
                # Assume this is slug
                if isinstance(current_gallery, string_types):
                    current_gallery = Gallery.objects.get(slug=current_gallery, publish=True)
                # Only accept Gallery model instance
                elif not isinstance(current_gallery, Gallery):
                    raise template.TemplateSyntaxError("You can only specify a Gallery instance or a slug")

        # Resolve optional template path
        template_path = settings.PORTICUS_GALLERIES_TEMPLATE_FRAGMENT
        if self.template_varname:
            try:
                resolved_var = self.template_varname.resolve(context)
            except template.VariableDoesNotExist:
                pass
            else:
                if resolved_var:
                    template_path = resolved_var

        gallery_list = Gallery.publish.all()

        subcontext = {
            'object_list': gallery_list,
            'current_gallery': current_gallery,
        }

        html = template.loader.get_template(template_path).render(template.Context(subcontext))

        return mark_safe(html)

@register.tag(name="porticus_gallery_list")
def do_porticus_gallery_list(parser, token):
    """
    Display the gallery list

    Usage : ::

        {% porticus_gallery_list [Optional template path] [Optional Gallery slug or instance] %}
    """
    args = token.split_contents()
    return GalleryList(*args[1:])

do_porticus_gallery_list.is_safe = True

class AlbumFragment(template.Node):
    """
    Album ressources as a HTML fragment
    """
    def __init__(self, instance_varname, template_varname=None):
        """
        :type insert_instance_varname: string or object ``django.db.models.Model``
        :param insert_instance_varname: Instance variable name or a string slug

        :type template_varname: string
        :param template_varname: (optional) ...
        """
        self.instance_varname = template.Variable(instance_varname)
        self.template_varname = None
        if template_varname:
            self.template_varname = template.Variable(template_varname)

    def render(self, context):
        """
        :type context: object ``django.template.Context``
        :param context: Context tag object

        :rtype: string
        :return: the HTML for the album
        """
        # Default assume this is directly an instance
        album_instance = self.instance_varname.resolve(context)
        # Assume this is slug
        if isinstance(album_instance, string_types):
            album_instance = Album.objects.get(slug=album_instance, publish=True)
        # Get the album's ressources
        ressources_list = album_instance.ressource_set.filter(publish=True)

        # Resolve optional template path
        template_path = settings.PORTICUS_ALBUM_TEMPLATE_FRAGMENT
        if self.template_varname:
            try:
                template_path = self.template_varname.resolve(context)
            except template.VariableDoesNotExist:
                pass

        subcontext = {
            'gallery_object': album_instance.gallery,
            'album_object': album_instance,
            'ressource_list': ressources_list,
        }

        html = template.loader.get_template(template_path).render(template.Context(subcontext))

        return mark_safe(html)

@register.tag(name="porticus_album_fragment")
def do_porticus_album_fragment(parser, token):
    """
    Display a album

    Usage : ::

        {% porticus_album_fragment [Optional Album slug or instance] [Optional template path] %}
    """
    args = token.split_contents()
    if len(args) < 2:
        raise template.TemplateSyntaxError("You need to specify at less an \"Album\" instance or slug")
    else:
        return AlbumFragment(*args[1:])

do_porticus_album_fragment.is_safe = True

def porticus_album_list(gallery_instance):
    """
    Return a queryset list from a Gallery, this is a flat list of albums, not recursive

    Usage : ::

        {% porticus_album_list [Gallery slug or instance] as gallery_albums %}
    """
    if isinstance(gallery_instance, string_types):
        return get_object_or_404(Gallery, slug=gallery_instance, publish=True).album_set.filter(level=0)

    return gallery_instance.album_set.filter(level=0)

register.assignment_tag(porticus_album_list)

#@register.filter(name='embed')
#def embed(value):
    #return value.replace('watch?v=', 'embed/')


text:
using Android.App;
using Android.Content.PM;
using Android.OS;

namespace Microsoft.ML.OnnxRuntime.InferenceSample.Maui;

[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
public class MainActivity : MauiAppCompatActivity
{
}


text:
package db.core;

public class Tuple {

}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Correspondence.Factual.AST;

namespace Correspondence.Factual.UnitTest.ParserTests
{
    [TestClass]
    public class UniqueTest : TestBase
    {
        [TestMethod]
        public void WhenUnique_UniqueIsRecognized()
        {
            string code =
                "namespace Reversi.GameModel; " +
                "                             " +
                "fact Person {                " +
                "key:                         " +
                "    unique;                  " +
                "}                            ";
            Namespace result = ParseToNamespace(code);
            Fact person = result.WithFactNamed("Person");
            Assert.IsTrue(person.Unique, "The Person fact is not unique.");
        }
    }
}


text:
using System;
using System.Threading.Tasks;
using DotVVM.Framework.Hosting;

namespace DotVVM.Framework.Runtime.Filters
{
    /// <summary>
    /// Allows to modify the response when an exception occurs.
    /// </summary>
    public abstract class ExceptionFilterAttribute : ActionFilterAttribute
    {
        /// <inheritdoc />
        protected internal override Task OnCommandExecutedAsync(IDotvvmRequestContext context, ActionInfo actionInfo, Exception exception)
            => exception != null ? OnCommandExceptionAsync(context, actionInfo, exception) : Task.FromResult(0);

        /// <summary>
        /// Called when the exception occurs during the command invocation.
        /// </summary>
        protected virtual Task OnCommandExceptionAsync(IDotvvmRequestContext context, ActionInfo actionInfo, Exception ex)
            => Task.FromResult(0);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Xunit;
using Prism.Events;

namespace Prism.Tests.Events
{
    public class PubSubEventFixture
    {
        [Fact]
        public void CanSubscribeAndRaiseEvent()
        {
            TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>();
            bool published = false;
            pubSubEvent.Subscribe(delegate { published = true; }, ThreadOption.PublisherThread, true, delegate { return true; });
            pubSubEvent.Publish(null);

            Assert.True(published);
        }

        [Fact]
        public void CanSubscribeAndRaiseEventNonGeneric()
        {
            var pubSubEvent = new TestablePubSubEvent();
            bool published = false;
            pubSubEvent.Subscribe(delegate { published = true; }, ThreadOption.PublisherThread, true);
            pubSubEvent.Publish();

            Assert.True(published);
        }

        [Fact]
        public void CanSubscribeAndRaiseCustomEvent()
        {
            var customEvent = new TestablePubSubEvent<Payload>();
            Payload payload = new Payload();
            var action = new ActionHelper();
            customEvent.Subscribe(action.Action);

            customEvent.Publish(payload);

            Assert.Same(action.ActionArg<Payload>(), payload);
        }

        [Fact]
        public void CanHaveMultipleSubscribersAndRaiseCustomEvent()
        {
            var customEvent = new TestablePubSubEvent<Payload>();
            Payload payload = new Payload();
            var action1 = new ActionHelper();
            var action2 = new ActionHelper();
            customEvent.Subscribe(action1.Action);
            customEvent.Subscribe(action2.Action);

            customEvent.Publish(payload);

            Assert.Same(action1.ActionArg<Payload>(), payload);
            Assert.Same(action2.ActionArg<Payload>(), payload);
        }

        [Fact]
        public void CanHaveMultipleSubscribersAndRaiseEvent()
        {
            var customEvent = new TestablePubSubEvent();
            var action1 = new ActionHelper();
            var action2 = new ActionHelper();
            customEvent.Subscribe(action1.Action);
            customEvent.Subscribe(action2.Action);

            customEvent.Publish();

            Assert.True(action1.ActionCalled);
            Assert.True(action2.ActionCalled);
        }

        [Fact]
        public void SubscribeTakesExecuteDelegateThreadOptionAndFilter()
        {
            TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>();
            var action = new ActionHelper();
            pubSubEvent.Subscribe(action.Action);

            pubSubEvent.Publish("test");

            Assert.Equal("test", action.ActionArg<string>());

        }

        [Fact]
        public void FilterEnablesActionTarget()
        {
            TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>();
            var goodFilter = new MockFilter { FilterReturnValue = true };
            var actionGoodFilter = new ActionHelper();
            var badFilter = new MockFilter { FilterReturnValue = false };
            var actionBadFilter = new ActionHelper();
            pubSubEvent.Subscribe(actionGoodFilter.Action, ThreadOption.PublisherThread, true, goodFilter.FilterString);
            pubSubEvent.Subscribe(actionBadFilter.Action, ThreadOption.PublisherThread, true, badFilter.FilterString);

            pubSubEvent.Publish("test");

            Assert.True(actionGoodFilter.ActionCalled);
            Assert.False(actionBadFilter.ActionCalled);

        }

        [Fact]
        public void SubscribeDefaultsThreadOptionAndNoFilter()
        {
            TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>();
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            SynchronizationContext calledSyncContext = null;
            var myAction = new ActionHelper()
            {
                ActionToExecute =
                    () => calledSyncContext = SynchronizationContext.Current
            };
            pubSubEvent.Subscribe(myAction.Action);

            pubSubEvent.Publish("test");

            Assert.Equal(SynchronizationContext.Current, calledSyncContext);
        }

        [Fact]
        public void SubscribeDefaultsThreadOptionAndNoFilterNonGeneric()
        {
            var pubSubEvent = new TestablePubSubEvent();
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            SynchronizationContext calledSyncContext = null;
            var myAction = new ActionHelper()
            {
                ActionToExecute =
                    () => calledSyncContext = SynchronizationContext.Current
            };
            pubSubEvent.Subscribe(myAction.Action);

            pubSubEvent.Publish();

            Assert.Equal(SynchronizationContext.Current, calledSyncContext);
        }

        [Fact]
        public void ShouldUnsubscribeFromPublisherThread()
        {
            var PubSubEvent = new TestablePubSubEvent<string>();

            var actionEvent = new ActionHelper();
            PubSubEvent.Subscribe(
                actionEvent.Action,
                ThreadOption.PublisherThread);

            Assert.True(PubSubEvent.Contains(actionEvent.Action));
            PubSubEvent.Unsubscribe(actionEvent.Action);
            Assert.False(PubSubEvent.Contains(actionEvent.Action));
        }

        [Fact]
        public void ShouldUnsubscribeFromPublisherThreadNonGeneric()
        {
            var pubSubEvent = new TestablePubSubEvent();

            var actionEvent = new ActionHelper();
            pubSubEvent.Subscribe(
                actionEvent.Action,
                ThreadOption.PublisherThread);

            Assert.True(pubSubEvent.Contains(actionEvent.Action));
            pubSubEvent.Unsubscribe(actionEvent.Action);
            Assert.False(pubSubEvent.Contains(actionEvent.Action));
        }

        [Fact]
        public void UnsubscribeShouldNotFailWithNonSubscriber()
        {
            TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>();

            Action<string> subscriber = delegate { };
            pubSubEvent.Unsubscribe(subscriber);
        }

        [Fact]
        public void UnsubscribeShouldNotFailWithNonSubscriberNonGeneric()
        {
            var pubSubEvent = new TestablePubSubEvent();

            Action subscriber = delegate { };
            pubSubEvent.Unsubscribe(subscriber);
        }

        [Fact]
        public void ShouldUnsubscribeFromBackgroundThread()
        {
            var PubSubEvent = new TestablePubSubEvent<string>();

            var actionEvent = new ActionHelper();
            PubSubEvent.Subscribe(
                actionEvent.Action,
                ThreadOption.BackgroundThread);

            Assert.True(PubSubEvent.Contains(actionEvent.Action));
            PubSubEvent.Unsubscribe(actionEvent.Action);
            Assert.False(PubSubEvent.Contains(actionEvent.Action));
        }

        [Fact]
        public void ShouldUnsubscribeFromBackgroundThreadNonGeneric()
        {
            var pubSubEvent = new TestablePubSubEvent();

            var actionEvent = new ActionHelper();
            pubSubEvent.Subscribe(
                actionEvent.Action,
                ThreadOption.BackgroundThread);

            Assert.True(pubSubEvent.Contains(actionEvent.Action));
            pubSubEvent.Unsubscribe(actionEvent.Action);
            Assert.False(pubSubEvent.Contains(actionEvent.Action));
        }

        [Fact]
        public void ShouldUnsubscribeFromUIThread()
        {
            var PubSubEvent = new TestablePubSubEvent<string>();
            PubSubEvent.SynchronizationContext = new SynchronizationContext();

            var actionEvent = new ActionHelper();
            PubSubEvent.Subscribe(
                actionEvent.Action,
                ThreadOption.UIThread);

            Assert.True(PubSubEvent.Contains(actionEvent.Action));
            PubSubEvent.Unsubscribe(actionEvent.Action);
            Assert.False(PubSubEvent.Contains(actionEvent.Action));
        }

        [Fact]
        public void ShouldUnsubscribeFromUIThreadNonGeneric()
        {
            var pubSubEvent = new TestablePubSubEvent();
            pubSubEvent.SynchronizationContext = new SynchronizationContext();

            var actionEvent = new ActionHelper();
            pubSubEvent.Subscribe(
                actionEvent.Action,
                ThreadOption.UIThread);

            Assert.True(pubSubEvent.Contains(actionEvent.Action));
            pubSubEvent.Unsubscribe(actionEvent.Action);
            Assert.False(pubSubEvent.Contains(actionEvent.Action));
        }

        [Fact]
        public void ShouldUnsubscribeASingleDelegate()
        {
            var PubSubEvent = new TestablePubSubEvent<string>();

            int callCount = 0;

            var actionEvent = new ActionHelper() { ActionToExecute = () => callCount++ };
            PubSubEvent.Subscribe(actionEvent.Action);
            PubSubEvent.Subscribe(actionEvent.Action);

            PubSubEvent.Publish(null);
            Assert.Equal<int>(2, callCount);

            callCount = 0;
            PubSubEvent.Unsubscribe(actionEvent.Action);
            PubSubEvent.Publish(null);
            Assert.Equal<int>(1, callCount);
        }

        [Fact]
        public void ShouldUnsubscribeASingleDelegateNonGeneric()
        {
            var pubSubEvent = new TestablePubSubEvent();

            int callCount = 0;

            var actionEvent = new ActionHelper() { ActionToExecute = () => callCount++ };
            pubSubEvent.Subscribe(actionEvent.Action);
            pubSubEvent.Subscribe(actionEvent.Action);

            pubSubEvent.Publish();
            Assert.Equal<int>(2, callCount);

            callCount = 0;
            pubSubEvent.Unsubscribe(actionEvent.Action);
            pubSubEvent.Publish();
            Assert.Equal<int>(1, callCount);
        }

        [Fact]
        public void ShouldNotExecuteOnGarbageCollectedDelegateReferenceWhenNotKeepAlive()
        {
            var PubSubEvent = new TestablePubSubEvent<string>();

            ExternalAction externalAction = new ExternalAction();
            PubSubEvent.Subscribe(externalAction.ExecuteAction);

            PubSubEvent.Publish("testPayload");
            Assert.Equal("testPayload", externalAction.PassedValue);

            WeakReference actionEventReference = new WeakReference(externalAction);
            externalAction = null;
            GC.Collect();
            Assert.False(actionEventReference.IsAlive);

            PubSubEvent.Publish("testPayload");
        }

        [Fact]
        public void ShouldNotExecuteOnGarbageCollectedDelegateReferenceWhenNotKeepAliveNonGeneric()
        {
            var pubSubEvent = new TestablePubSubEvent();

            var externalAction = new ExternalAction();
            pubSubEvent.Subscribe(externalAction.ExecuteAction);

            pubSubEvent.Publish();
            Assert.True(externalAction.Executed);

            var actionEventReference = new WeakReference(externalAction);
            externalAction = null;
            GC.Collect();
            Assert.False(actionEventReference.IsAlive);

            pubSubEvent.Publish();
        }

        [Fact]
        public void ShouldNotExecuteOnGarbageCollectedFilterReferenceWhenNotKeepAlive()
        {
            var PubSubEvent = new TestablePubSubEvent<string>();

            bool wasCalled = false;
            var actionEvent = new ActionHelper() { ActionToExecute = () => wasCalled = true };

            ExternalFilter filter = new ExternalFilter();
            PubSubEvent.Subscribe(actionEvent.Action, ThreadOption.PublisherThread, false, filter.AlwaysTrueFilter);

            PubSubEvent.Publish("testPayload");
            Assert.True(wasCalled);

            wasCalled = false;
            WeakReference filterReference = new WeakReference(filter);
            filter = null;
            GC.Collect();
            Assert.False(filterReference.IsAlive);

            PubSubEvent.Publish("testPayload");
            Assert.False(wasCalled);
        }

        [Fact]
        public void CanAddSubscriptionWhileEventIsFiring()
        {
            var PubSubEvent = new TestablePubSubEvent<string>();

            var emptyAction = new ActionHelper();
            var subscriptionAction = new ActionHelper
            {
                ActionToExecute = (() =>
                                                  PubSubEvent.Subscribe(
                                                      emptyAction.Action))
            };

            PubSubEvent.Subscribe(subscriptionAction.Action);

            Assert.False(PubSubEvent.Contains(emptyAction.Action));

            PubSubEvent.Publish(null);

            Assert.True((PubSubEvent.Contains(emptyAction.Action)));
        }

        [Fact]
        public void CanAddSubscriptionWhileEventIsFiringNonGeneric()
        {
            var pubSubEvent = new TestablePubSubEvent();

            var emptyAction = new ActionHelper();
            var subscriptionAction = new ActionHelper
            {
                ActionToExecute = (() =>
                                          pubSubEvent.Subscribe(
                                          emptyAction.Action))
            };

            pubSubEvent.Subscribe(subscriptionAction.Action);

            Assert.False(pubSubEvent.Contains(emptyAction.Action));

            pubSubEvent.Publish();

            Assert.True((pubSubEvent.Contains(emptyAction.Action)));
        }

        [Fact]
        public void InlineDelegateDeclarationsDoesNotGetCollectedIncorrectlyWithWeakReferences()
        {
            var PubSubEvent = new TestablePubSubEvent<string>();
            bool published = false;
            PubSubEvent.Subscribe(delegate { published = true; }, ThreadOption.PublisherThread, false, delegate { return true; });
            GC.Collect();
            PubSubEvent.Publish(null);

            Assert.True(published);
        }

        [Fact]
        public void InlineDelegateDeclarationsDoesNotGetCollectedIncorrectlyWithWeakReferencesNonGeneric()
        {
            var pubSubEvent = new TestablePubSubEvent();
            bool published = false;
            pubSubEvent.Subscribe(delegate { published = true; }, ThreadOption.PublisherThread, false);
            GC.Collect();
            pubSubEvent.Publish();

            Assert.True(published);
        }

        [Fact]
        public void ShouldNotGarbageCollectDelegateReferenceWhenUsingKeepAlive()
        {
            var PubSubEvent = new TestablePubSubEvent<string>();

            var externalAction = new ExternalAction();
            PubSubEvent.Subscribe(externalAction.ExecuteAction, ThreadOption.PublisherThread, true);

            WeakReference actionEventReference = new WeakReference(externalAction);
            externalAction = null;
            GC.Collect();
            GC.Collect();
            Assert.True(actionEventReference.IsAlive);

            PubSubEvent.Publish("testPayload");

            Assert.Equal("testPayload", ((ExternalAction)actionEventReference.Target).PassedValue);
        }

        [Fact]
        public void ShouldNotGarbageCollectDelegateReferenceWhenUsingKeepAliveNonGeneric()
        {
            var pubSubEvent = new TestablePubSubEvent();

            var externalAction = new ExternalAction();
            pubSubEvent.Subscribe(externalAction.ExecuteAction, ThreadOption.PublisherThread, true);

            WeakReference actionEventReference = new WeakReference(externalAction);
            externalAction = null;
            GC.Collect();
            GC.Collect();
            Assert.True(actionEventReference.IsAlive);

            pubSubEvent.Publish();

            Assert.True(((ExternalAction)actionEventReference.Target).Executed);
        }

        [Fact]
        public void RegisterReturnsTokenThatCanBeUsedToUnsubscribe()
        {
            var PubSubEvent = new TestablePubSubEvent<string>();
            var emptyAction = new ActionHelper();

            var token = PubSubEvent.Subscribe(emptyAction.Action);
            PubSubEvent.Unsubscribe(token);

            Assert.False(PubSubEvent.Contains(emptyAction.Action));
        }

        [Fact]
        public void RegisterReturnsTokenThatCanBeUsedToUnsubscribeNonGeneric()
        {
            var pubSubEvent = new TestablePubSubEvent();
            var emptyAction = new ActionHelper();

            var token = pubSubEvent.Subscribe(emptyAction.Action);
            pubSubEvent.Unsubscribe(token);

            Assert.False(pubSubEvent.Contains(emptyAction.Action));
        }

        [Fact]
        public void ContainsShouldSearchByToken()
        {
            var PubSubEvent = new TestablePubSubEvent<string>();
            var emptyAction = new ActionHelper();
            var token = PubSubEvent.Subscribe(emptyAction.Action);

            Assert.True(PubSubEvent.Contains(token));

            PubSubEvent.Unsubscribe(emptyAction.Action);
            Assert.False(PubSubEvent.Contains(token));
        }

        [Fact]
        public void ContainsShouldSearchByTokenNonGeneric()
        {
            var pubSubEvent = new TestablePubSubEvent();
            var emptyAction = new ActionHelper();
            var token = pubSubEvent.Subscribe(emptyAction.Action);

            Assert.True(pubSubEvent.Contains(token));

            pubSubEvent.Unsubscribe(emptyAction.Action);
            Assert.False(pubSubEvent.Contains(token));
        }

        [Fact]
        public void SubscribeDefaultsToPublisherThread()
        {
            var PubSubEvent = new TestablePubSubEvent<string>();
            Action<string> action = delegate { };
            var token = PubSubEvent.Subscribe(action, true);

            Assert.Equal(1, PubSubEvent.BaseSubscriptions.Count);
            Assert.Equal(typeof(EventSubscription<string>), PubSubEvent.BaseSubscriptions.ElementAt(0).GetType());
        }

        [Fact]
        public void SubscribeDefaultsToPublisherThreadNonGeneric()
        {
            var pubSubEvent = new TestablePubSubEvent();
            Action action = delegate { };
            var token = pubSubEvent.Subscribe(action, true);

            Assert.Equal(1, pubSubEvent.BaseSubscriptions.Count);
            Assert.Equal(typeof(EventSubscription), pubSubEvent.BaseSubscriptions.ElementAt(0).GetType());
        }

        public class ExternalFilter
        {
            public bool AlwaysTrueFilter(string value)
            {
                return true;
            }
        }

        public class ExternalAction
        {
            public string PassedValue;
            public bool Executed = false;

            public void ExecuteAction(string value)
            {
                PassedValue = value;
                Executed = true;
            }

            public void ExecuteAction()
            {
                Executed = true;
            }
        }

        class TestablePubSubEvent<TPayload> : PubSubEvent<TPayload>
        {
            public ICollection<IEventSubscription> BaseSubscriptions
            {
                get { return base.Subscriptions; }
            }
        }

        class TestablePubSubEvent : PubSubEvent
        {
            public ICollection<IEventSubscription> BaseSubscriptions
            {
                get { return base.Subscriptions; }
            }
        }

        public class Payload { }
    }

    public class ActionHelper
    {
        public bool ActionCalled;
        public Action ActionToExecute = null;
        private object actionArg;

        public T ActionArg<T>()
        {
            return (T)actionArg;
        }

        public void Action(PubSubEventFixture.Payload arg)
        {
            Action((object)arg);
        }

        public void Action(string arg)
        {
            Action((object)arg);
        }

        public void Action(object arg)
        {
            actionArg = arg;
            ActionCalled = true;
            if (ActionToExecute != null)
            {
                ActionToExecute.Invoke();
            }
        }

        public void Action()
        {
            ActionCalled = true;
            if (ActionToExecute != null)
            {
                ActionToExecute.Invoke();
            }
        }
    }

    public class MockFilter
    {
        public bool FilterReturnValue;

        public bool FilterString(string arg)
        {
            return FilterReturnValue;
        }
    }
}


text:
#import <JavaScriptCore/JavaScriptCore.h>

#import "ABI7_0_0RCTJavaScriptExecutor.h"

/**
 * Default name for the JS thread
 */
ABI7_0_0RCT_EXTERN NSString *const ABI7_0_0RCTJSCThreadName;

/**
 * This notification fires on the JS thread immediately after a `JSContext`
 * is fully initialized, but before the JS bundle has been loaded. The object
 * of this notification is the `JSContext`. Native modules should listen for
 * notification only if they need to install custom functionality into the
 * context. Note that this notification won't fire when debugging in Chrome.
 */
ABI7_0_0RCT_EXTERN NSString *const ABI7_0_0RCTJavaScriptContextCreatedNotification;

/**
 * Create a NSError from a JSError object.
 *
 * If available, the error's userInfo property will contain the JS stacktrace under
 * the ABI7_0_0RCTJSStackTraceKey key.
 */
ABI7_0_0RCT_EXTERN NSError *ABI7_0_0RCTNSErrorFromJSError(JSContextRef context, JSValueRef jsError);

/**
 * Uses a JavaScriptCore context as the execution engine.
 */
@interface ABI7_0_0RCTJSCExecutor : NSObject <ABI7_0_0RCTJavaScriptExecutor>

@end


text:
// Copyright 2008 Google Inc. All Rights Reserved.

package com.google.devtools.simple.runtime.components.android.util;

import android.os.Handler;

/**
 * Utilities for handling asynchronous calls.
 *
 */

public class AsynchUtil {

  /**
   * Make an asynchronous call in a separate thread.
   * @param call a {@link Runnable} to run in the thread.
   */
  public static void runAsynchronously(final Runnable call) {
    Thread thread = new Thread(call);
    thread.start();
  }
  /**
   * Make an asynchronous call in a separate thread, with a callback that's run on the current
   * Android UI thread.
   * @param androidUIHandler  the Handler from the current Android context
   * @param call a {@link Runnable} to run in the thread.
   * @param callback a {@Link Runnable) to run in the Android UI thread when the call above returns
   */
  public static void runAsynchronously(final Handler androidUIHandler,
                                       final Runnable call,
                                       final Runnable callback) {
    Runnable runnable = new Runnable() {
      public void run() {
        call.run();
        if (callback != null) {
          androidUIHandler.post(new Runnable() {
            public void run() {
              callback.run();
            }
          });
        }
      }
    };
    Thread thread = new Thread(runnable);
    thread.start();
  }
}