text:
import errno
import logging
import select
import socket
import time
try:
    import urlparse
except ImportError:
    import urllib.parse as urlparse

from serial.serialutil import SerialBase, SerialException, to_bytes, \
    portNotOpenError, writeTimeoutError, Timeout

# map log level names to constants. used in from_url()
LOGGER_LEVELS = {
    'debug': logging.DEBUG,
    'info': logging.INFO,
    'warning': logging.WARNING,
    'error': logging.ERROR,
}

POLL_TIMEOUT = 5

class Serial(SerialBase):
    """Serial port implementation for plain sockets."""

    BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
                 9600, 19200, 38400, 57600, 115200)

    def open(self):
        """\
        Open port with current settings. This may throw a SerialException
        if the port cannot be opened.
        """
        self.logger = None
        if self._port is None:
            raise SerialException("Port must be configured before it can be used.")
        if self.is_open:
            raise SerialException("Port is already open.")
        try:
            # timeout is used for write timeout support :/ and to get an initial connection timeout
            self._socket = socket.create_connection(self.from_url(self.portstr), timeout=POLL_TIMEOUT)
        except Exception as msg:
            self._socket = None
            raise SerialException("Could not open port {}: {}".format(self.portstr, msg))
        # after connecting, switch to non-blocking, we're using select
        self._socket.setblocking(False)

        # not that there is anything to configure...
        self._reconfigure_port()
        # all things set up get, now a clean start
        self.is_open = True
        if not self._dsrdtr:
            self._update_dtr_state()
        if not self._rtscts:
            self._update_rts_state()
        self.reset_input_buffer()
        self.reset_output_buffer()

    def _reconfigure_port(self):
        """\
        Set communication parameters on opened port. For the socket://
        protocol all settings are ignored!
        """
        if self._socket is None:
            raise SerialException("Can only operate on open ports")
        if self.logger:
            self.logger.info('ignored port configuration change')

    def close(self):
        """Close port"""
        if self.is_open:
            if self._socket:
                try:
                    self._socket.shutdown(socket.SHUT_RDWR)
                    self._socket.close()
                except:
                    # ignore errors.
                    pass
                self._socket = None
            self.is_open = False
            # in case of quick reconnects, give the server some time
            time.sleep(0.3)

    def from_url(self, url):
        """extract host and port from an URL string"""
        parts = urlparse.urlsplit(url)
        if parts.scheme != "socket":
            raise SerialException(
                'expected a string in the form '
                '"socket://<host>:<port>[?logging={debug|info|warning|error}]": '
                'not starting with socket:// ({!r})'.format(parts.scheme))
        try:
            # process options now, directly altering self
            for option, values in urlparse.parse_qs(parts.query, True).items():
                if option == 'logging':
                    logging.basicConfig()   # XXX is that good to call it here?
                    self.logger = logging.getLogger('pySerial.socket')
                    self.logger.setLevel(LOGGER_LEVELS[values[0]])
                    self.logger.debug('enabled logging')
                else:
                    raise ValueError('unknown option: {!r}'.format(option))
            if not 0 <= parts.port < 65536:
                raise ValueError("port not in range 0...65535")
        except ValueError as e:
            raise SerialException(
                'expected a string in the form '
                '"socket://<host>:<port>[?logging={debug|info|warning|error}]": {}'.format(e))

        return (parts.hostname, parts.port)

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -

    @property
    def in_waiting(self):
        """Return the number of bytes currently in the input buffer."""
        if not self.is_open:
            raise portNotOpenError
        # Poll the socket to see if it is ready for reading.
        # If ready, at least one byte will be to read.
        lr, lw, lx = select.select([self._socket], [], [], 0)
        return len(lr)

    # select based implementation, similar to posix, but only using socket API
    # to be portable, additionally handle socket timeout which is used to
    # emulate write timeouts
    def read(self, size=1):
        """\
        Read size bytes from the serial port. If a timeout is set it may
        return less characters as requested. With no timeout it will block
        until the requested number of bytes is read.
        """
        if not self.is_open:
            raise portNotOpenError
        read = bytearray()
        timeout = Timeout(self._timeout)
        while len(read) < size:
            try:
                ready, _, _ = select.select([self._socket], [], [], timeout.time_left())
                # If select was used with a timeout, and the timeout occurs, it
                # returns with empty lists -> thus abort read operation.
                # For timeout == 0 (non-blocking operation) also abort when
                # there is nothing to read.
                if not ready:
                    break   # timeout
                buf = self._socket.recv(size - len(read))
                # read should always return some data as select reported it was
                # ready to read when we get to this point, unless it is EOF
                if not buf:
                    raise SerialException('socket disconnected')
                read.extend(buf)
            except OSError as e:
                # this is for Python 3.x where select.error is a subclass of
                # OSError ignore EAGAIN errors. all other errors are shown
                if e.errno != errno.EAGAIN:
                    raise SerialException('read failed: {}'.format(e))
            except (select.error, socket.error) as e:
                # this is for Python 2.x
                # ignore EAGAIN errors. all other errors are shown
                # see also http://www.python.org/dev/peps/pep-3151/#select
                if e[0] != errno.EAGAIN:
                    raise SerialException('read failed: {}'.format(e))
            if timeout.expired():
                break
        return bytes(read)

    def write(self, data):
        """\
        Output the given byte string over the serial port. Can block if the
        connection is blocked. May raise SerialException if the connection is
        closed.
        """
        if not self.is_open:
            raise portNotOpenError

        d = to_bytes(data)
        tx_len = length = len(d)
        timeout = Timeout(self._write_timeout)
        while tx_len > 0:
            try:
                n = self._socket.send(d)
                if timeout.is_non_blocking:
                    # Zero timeout indicates non-blocking - simply return the
                    # number of bytes of data actually written
                    return n
                elif not timeout.is_infinite:
                    # when timeout is set, use select to wait for being ready
                    # with the time left as timeout
                    if timeout.expired():
                        raise writeTimeoutError
                    _, ready, _ = select.select([], [self._socket], [], timeout.time_left())
                    if not ready:
                        raise writeTimeoutError
                else:
                    assert timeout.time_left() is None
                    # wait for write operation
                    _, ready, _ = select.select([], [self._socket], [], None)
                    if not ready:
                        raise SerialException('write failed (select)')
                d = d[n:]
                tx_len -= n
            except SerialException:
                raise
            except OSError as v:
                if v.errno != errno.EAGAIN:
                    raise SerialException('write failed: {}'.format(v))
                # still calculate and check timeout
                if timeout.expired():
                    raise writeTimeoutError
        return length - len(d)

    def reset_input_buffer(self):
        """Clear input buffer, discarding all that is in the buffer."""
        if not self.is_open:
            raise portNotOpenError

        # just use recv to remove input, while there is some
        ready = True
        while ready:
            ready, _, _ = select.select([self._socket], [], [], 0)
            try:
                self._socket.recv(4096)
            except OSError as e:
                # this is for Python 3.x where select.error is a subclass of
                # OSError ignore EAGAIN errors. all other errors are shown
                if e.errno != errno.EAGAIN:
                    raise SerialException('reset_input_buffer failed: {}'.format(e))
            except (select.error, socket.error) as e:
                # this is for Python 2.x
                # ignore EAGAIN errors. all other errors are shown
                # see also http://www.python.org/dev/peps/pep-3151/#select
                if e[0] != errno.EAGAIN:
                    raise SerialException('reset_input_buffer failed: {}'.format(e))

    def reset_output_buffer(self):
        """\
        Clear output buffer, aborting the current output and
        discarding all that is in the buffer.
        """
        if not self.is_open:
            raise portNotOpenError
        if self.logger:
            self.logger.info('ignored reset_output_buffer')

    def send_break(self, duration=0.25):
        """\
        Send break condition. Timed, returns to idle state after given
        duration.
        """
        if not self.is_open:
            raise portNotOpenError
        if self.logger:
            self.logger.info('ignored send_break({!r})'.format(duration))

    def _update_break_state(self):
        """Set break: Controls TXD. When active, to transmitting is
        possible."""
        if self.logger:
            self.logger.info('ignored _update_break_state({!r})'.format(self._break_state))

    def _update_rts_state(self):
        """Set terminal status line: Request To Send"""
        if self.logger:
            self.logger.info('ignored _update_rts_state({!r})'.format(self._rts_state))

    def _update_dtr_state(self):
        """Set terminal status line: Data Terminal Ready"""
        if self.logger:
            self.logger.info('ignored _update_dtr_state({!r})'.format(self._dtr_state))

    @property
    def cts(self):
        """Read terminal status line: Clear To Send"""
        if not self.is_open:
            raise portNotOpenError
        if self.logger:
            self.logger.info('returning dummy for cts')
        return True

    @property
    def dsr(self):
        """Read terminal status line: Data Set Ready"""
        if not self.is_open:
            raise portNotOpenError
        if self.logger:
            self.logger.info('returning dummy for dsr')
        return True

    @property
    def ri(self):
        """Read terminal status line: Ring Indicator"""
        if not self.is_open:
            raise portNotOpenError
        if self.logger:
            self.logger.info('returning dummy for ri')
        return False

    @property
    def cd(self):
        """Read terminal status line: Carrier Detect"""
        if not self.is_open:
            raise portNotOpenError
        if self.logger:
            self.logger.info('returning dummy for cd)')
        return True

    # - - - platform specific - - -

    # works on Linux and probably all the other POSIX systems
    def fileno(self):
        """Get the file handle of the underlying socket for use with select"""
        return self._socket.fileno()

#
# simple client test
if __name__ == '__main__':
    import sys
    s = Serial('socket://localhost:7000')
    sys.stdout.write('{}\n'.format(s))

    sys.stdout.write("write...\n")
    s.write(b"hello\n")
    s.flush()
    sys.stdout.write("read: {}\n".format(s.read(5)))

    s.close()


text:
template<typename MatrixType> void signed_integer_type_tests(const MatrixType& m)
{
  typedef typename MatrixType::Index Index;
  typedef typename MatrixType::Scalar Scalar;

  enum { is_signed = (Scalar(-1) > Scalar(0)) ? 0 : 1 };
  VERIFY(is_signed == 1);

  Index rows = m.rows();
  Index cols = m.cols();

  MatrixType m1(rows, cols),
             m2 = MatrixType::Random(rows, cols),
             mzero = MatrixType::Zero(rows, cols);

  do {
    m1 = MatrixType::Random(rows, cols);
  } while(m1 == mzero || m1 == m2);

  // check linear structure

  Scalar s1;
  do {
    s1 = internal::random<Scalar>();
  } while(s1 == 0);

  VERIFY_IS_EQUAL(-(-m1),                  m1);
  VERIFY_IS_EQUAL(-m2+m1+m2,               m1);
  VERIFY_IS_EQUAL((-m1+m2)*s1,             -s1*m1+s1*m2);
}

template<typename MatrixType> void integer_type_tests(const MatrixType& m)
{
  typedef typename MatrixType::Index Index;
  typedef typename MatrixType::Scalar Scalar;

  VERIFY(NumTraits<Scalar>::IsInteger);
  enum { is_signed = (Scalar(-1) > Scalar(0)) ? 0 : 1 };
  VERIFY(int(NumTraits<Scalar>::IsSigned) == is_signed);

  typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;

  Index rows = m.rows();
  Index cols = m.cols();

  // this test relies a lot on Random.h, and there's not much more that we can do
  // to test it, hence I consider that we will have tested Random.h
  MatrixType m1(rows, cols),
             m2 = MatrixType::Random(rows, cols),
             m3(rows, cols),
             mzero = MatrixType::Zero(rows, cols);

  typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> SquareMatrixType;
  SquareMatrixType identity = SquareMatrixType::Identity(rows, rows),
                   square = SquareMatrixType::Random(rows, rows);
  VectorType v1(rows),
             v2 = VectorType::Random(rows),
             vzero = VectorType::Zero(rows);

  do {
    m1 = MatrixType::Random(rows, cols);
  } while(m1 == mzero || m1 == m2);

  do {
    v1 = VectorType::Random(rows);
  } while(v1 == vzero || v1 == v2);

  VERIFY_IS_APPROX(               v1,    v1);
  VERIFY_IS_NOT_APPROX(           v1,    2*v1);
  VERIFY_IS_APPROX(               vzero, v1-v1);
  VERIFY_IS_APPROX(               m1,    m1);
  VERIFY_IS_NOT_APPROX(           m1,    2*m1);
  VERIFY_IS_APPROX(               mzero, m1-m1);

  VERIFY_IS_APPROX(m3 = m1,m1);
  MatrixType m4;
  VERIFY_IS_APPROX(m4 = m1,m1);

  m3.real() = m1.real();
  VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), static_cast<const MatrixType&>(m1).real());
  VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), m1.real());

  // check == / != operators
  VERIFY(m1==m1);
  VERIFY(m1!=m2);
  VERIFY(!(m1==m2));
  VERIFY(!(m1!=m1));
  m1 = m2;
  VERIFY(m1==m2);
  VERIFY(!(m1!=m2));

  // check linear structure

  Scalar s1;
  do {
    s1 = internal::random<Scalar>();
  } while(s1 == 0);

  VERIFY_IS_EQUAL(m1+m1,                   2*m1);
  VERIFY_IS_EQUAL(m1+m2-m1,                m2);
  VERIFY_IS_EQUAL(m1*s1,                   s1*m1);
  VERIFY_IS_EQUAL((m1+m2)*s1,              s1*m1+s1*m2);
  m3 = m2; m3 += m1;
  VERIFY_IS_EQUAL(m3,                      m1+m2);
  m3 = m2; m3 -= m1;
  VERIFY_IS_EQUAL(m3,                      m2-m1);
  m3 = m2; m3 *= s1;
  VERIFY_IS_EQUAL(m3,                      s1*m2);

  // check matrix product.

  VERIFY_IS_APPROX(identity * m1, m1);
  VERIFY_IS_APPROX(square * (m1 + m2), square * m1 + square * m2);
  VERIFY_IS_APPROX((m1 + m2).transpose() * square, m1.transpose() * square + m2.transpose() * square);
  VERIFY_IS_APPROX((m1 * m2.transpose()) * m1, m1 * (m2.transpose() * m1));
}

void test_integer_types()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST_1( integer_type_tests(Matrix<unsigned int, 1, 1>()) );
    CALL_SUBTEST_1( integer_type_tests(Matrix<unsigned long, 3, 4>()) );

    CALL_SUBTEST_2( integer_type_tests(Matrix<long, 2, 2>()) );
    CALL_SUBTEST_2( signed_integer_type_tests(Matrix<long, 2, 2>()) );

    CALL_SUBTEST_3( integer_type_tests(Matrix<char, 2, Dynamic>(2, 10)) );
    CALL_SUBTEST_3( signed_integer_type_tests(Matrix<signed char, 2, Dynamic>(2, 10)) );

    CALL_SUBTEST_4( integer_type_tests(Matrix<unsigned char, 3, 3>()) );
    CALL_SUBTEST_4( integer_type_tests(Matrix<unsigned char, Dynamic, Dynamic>(20, 20)) );

    CALL_SUBTEST_5( integer_type_tests(Matrix<short, Dynamic, 4>(7, 4)) );
    CALL_SUBTEST_5( signed_integer_type_tests(Matrix<short, Dynamic, 4>(7, 4)) );

    CALL_SUBTEST_6( integer_type_tests(Matrix<unsigned short, 4, 4>()) );

    CALL_SUBTEST_7( integer_type_tests(Matrix<long long, 11, 13>()) );
    CALL_SUBTEST_7( signed_integer_type_tests(Matrix<long long, 11, 13>()) );

    CALL_SUBTEST_8( integer_type_tests(Matrix<unsigned long long, Dynamic, 5>(1, 5)) );
  }
#ifdef EIGEN_TEST_PART_9
  VERIFY_IS_EQUAL(internal::scalar_div_cost<int>::value, 8);
  VERIFY_IS_EQUAL(internal::scalar_div_cost<unsigned int>::value, 8);
  if(sizeof(long)>sizeof(int)) {
    VERIFY(int(internal::scalar_div_cost<long>::value) > int(internal::scalar_div_cost<int>::value));
    VERIFY(int(internal::scalar_div_cost<unsigned long>::value) > int(internal::scalar_div_cost<int>::value));
  }
#endif
}

redpajama_set_name: RedPajamaGithub


text:
Brought to you by the good folks at [Croovy](http://croovy.com).

This gem provides a handful of functions useful for working with home
loans. Specifically provided are functions for calculating Internal Rate of
Return (irr) and Net Present Value (npv). Both are implemented as described in
Wikipedia, and using the secant method, also as described in Wikipedia.

* http://en.wikipedia.org/wiki/Internal_rate_of_return
* http://en.wikipedia.org/wiki/Net_present_value
* http://en.wikipedia.org/wiki/Secant_method

Also provided is an function for calculating the Annual Percentage Rate
(apr). It is basically sugar for the irr function, making it callable like the
RATE function found in a Google Docs Spreadsheet or Microsoft Excel.

* https://support.google.com/drive/table/25273?hl=en
* http://office.microsoft.com/en-us/excel-help/rate-function-HP010342819.aspx

## How CroovyFinance differs from Finance

The Finance gem uses Newton's method (while CroovyFinance uses the secant
method), and as a result, CroovyFinance's results are more inline with Excel
and Google Docs. In the author's experience, certain reasonable inputs, when
used with the Finance gem, produced obviously incorrect results.

## Installation

Add this line to your application's Gemfile:

    gem 'croovy_finance'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install croovy_finance

## Usage

```ruby
irb(main):001:0> require "croovy/finance"
=> true
irb(main):002:0> CroovyFinance::Apr.new(360, 1_044.50, 238_650).calc
=> 0.0027456868896171853
```

## Contributing

1. Fork it
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 new Pull Request


text:
<!DOCTYPE html>
<html>
  <head>
    <title>InAppBrowser.removeEventListener Example</title>

    <script type="text/javascript" charset="utf-8" src="phonegap.js"></script>

  </head>
  <body>

	<P>
		<video width="320" height="240" controls webkit-playsinline>
			<source src="file:///android_asset/www/mov_bbb.mp4" type="video/mp4">
		</video>
        <video width="320" height="240" controls webkit-playsinline>
			<source src="mov_bbb.mp4" type="video/mp4">
		</video>
        <script>
        	var myFilename = "mov_bbb.mp4";
			var myUrl = cordova.file.applicationDirectory + "www/" + myFilename;
			alert (myUrl)
        </script>
	</P>

  </body>
</html>


text:
package org.xcolab.client.contest.pojo.wrapper;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

import org.xcolab.client.contest.pojo.tables.pojos.FocusArea;

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

@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class FocusAreaWrapper extends FocusArea implements Serializable {

    private final List<OntologyTermWrapper> ontologyTerms = new ArrayList<>();
    private final List<Long> ontologyTermsIds = new ArrayList<>();

    public FocusAreaWrapper() {}

    public FocusAreaWrapper(FocusAreaWrapper value) {
        super(value);
    }

    public FocusAreaWrapper(Long id, String name, Integer order_) {
        super(id, name, order_);
    }

    public FocusAreaWrapper(FocusArea abstractFocusArea) {
        super(abstractFocusArea);
    }

    @JsonIgnore
    public List<OntologyTermWrapper> getOntologyTerms() {
        return ontologyTerms;
    }

    @JsonIgnore
    public void addOntologyTerm(OntologyTermWrapper term) {
        if (term != null) {
            ontologyTerms.add(term);
            ontologyTermsIds.add(term.getId());
        }
    }

    @JsonIgnore
    public String getTermsIdsStr() {
        return ontologyTermsIds.toString();
    }
}


text:
namespace base {
namespace android {

base::android::ScopedJavaLocalRef<jobject>
TestSystemMessageHandlerLink::CreateTestSystemMessageHandler(
    JNIEnv* env,
    base::MessagePump::Delegate* delegate,
    MessagePumpForUI* message_pump,
    WaitableEvent* test_done_event) {
  return Java_TestSystemMessageHandler_create(
      env, reinterpret_cast<intptr_t>(delegate),
      reinterpret_cast<intptr_t>(message_pump),
      reinterpret_cast<intptr_t>(test_done_event));
}

bool TestSystemMessageHandlerLink::RegisterJNI(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

static void NotifyTestDone(JNIEnv* env,
                           const base::android::JavaParamRef<jclass>& jcaller,
                           jlong native_waitable_test_event) {
  WaitableEvent* event =
      reinterpret_cast<WaitableEvent*>(native_waitable_test_event);
  DCHECK(event);
  event->Signal();
}

}  // namespace android
}  // namespace base


text:
package com.pmpet.ui;

import android.os.Bundle;
import android.view.Menu;
import android.webkit.WebView;

import com.pm.commons.BaseActiviy;
import com.pmpet.R;

public class WebInfoActivity extends BaseActiviy {

	private WebView mWebView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_web_info);
		_initView();
	}

	@Override
	protected void _initView() {
		mWebView = (WebView)findViewById(R.id.wv_info);
		mWebView.setBackgroundColor(0);
		mWebView.setBackgroundResource(R.drawable.bg_activity);
		mWebView.getSettings().setJavaScriptEnabled(false);
		mWebView.loadUrl("file:///android_asset/pm_info.html");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.web_info, menu);
		return true;
	}

}


text:
class EvtParticle;

class EvtVectorIsr:public  EvtDecayIncoherent  {

public:

  EvtVectorIsr() {}
  virtual ~EvtVectorIsr();

  std::string getName();

  EvtDecayBase* clone();

  void decay(EvtParticle *p);

  void init();

  void initProbMax();

  double ckhrad1(double xx, double a, double b);

  void ckhrad(const double& e_beam,const double& q2_min,double& e01,double& e02,double& f);

private:

  double csfrmn,csbkmn;
  double fmax;
  bool firstorder;
};

#endif


text:
#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
#endregion

namespace OctoAwesome.Client
{
#if WINDOWS || LINUX
    /// <summary>
    /// The main class.
    /// </summary>
    public static class Program
    {
        static OctoGame game;
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            using (game = new OctoGame())
                game.Run(60,60);
        }

        public static void Restart()
        {
            game.Exit();
            using (game = new OctoGame())
                game.Run(60,60);
        }
    }
#endif
}


text:
#include <cassert>

#include "base/intmath.hh"
#include "base/str.hh"
#include "mem/ruby/filters/BulkBloomFilter.hh"
#include "mem/ruby/system/System.hh"

using namespace std;

BulkBloomFilter::BulkBloomFilter(string str)
{
    string head, tail;

#ifndef NDEBUG
    bool success =
#endif
        split_first(str, head, tail, '_');
    assert(success);

    m_filter_size = atoi(head.c_str());
    m_filter_size_bits = floorLog2(m_filter_size);
    // split the filter bits in half, c0 and c1
    m_sector_bits = m_filter_size_bits - 1;

    m_temp_filter.resize(m_filter_size);
    m_filter.resize(m_filter_size);
    clear();

    // clear temp filter
    for (int i = 0; i < m_filter_size; ++i) {
        m_temp_filter[i] = 0;
    }
}

BulkBloomFilter::~BulkBloomFilter()
{
}

void
BulkBloomFilter::clear()
{
    for (int i = 0; i < m_filter_size; i++) {
        m_filter[i] = 0;
    }
}

void
BulkBloomFilter::increment(const Address& addr)
{
    // Not used
}

void
BulkBloomFilter::decrement(const Address& addr)
{
    // Not used
}

void
BulkBloomFilter::merge(AbstractBloomFilter * other_filter)
{
    // TODO
}

void
BulkBloomFilter::set(const Address& addr)
{
    // c0 contains the cache index bits
    int set_bits = m_sector_bits;
    int block_bits = RubySystem::getBlockSizeBits();
    int c0 = addr.bitSelect( block_bits, block_bits + set_bits - 1);
    // c1 contains the lower m_sector_bits permuted bits
    //Address permuted_bits = permute(addr);
    //int c1 = permuted_bits.bitSelect(0, set_bits-1);
    int c1 = addr.bitSelect( block_bits+set_bits, (block_bits+2*set_bits) - 1);
    //assert(c0 < (m_filter_size/2));
    //assert(c0 + (m_filter_size/2) < m_filter_size);
    //assert(c1 < (m_filter_size/2));
    // set v0 bit
    m_filter[c0 + (m_filter_size/2)] = 1;
    // set v1 bit
    m_filter[c1] = 1;
}

void
BulkBloomFilter::unset(const Address& addr)
{
    // not used
}

bool
BulkBloomFilter::isSet(const Address& addr)
{
    // c0 contains the cache index bits
    int set_bits = m_sector_bits;
    int block_bits = RubySystem::getBlockSizeBits();
    int c0 = addr.bitSelect( block_bits, block_bits + set_bits - 1);
    // c1 contains the lower 10 permuted bits
    //Address permuted_bits = permute(addr);
    //int c1 = permuted_bits.bitSelect(0, set_bits-1);
    int c1 = addr.bitSelect( block_bits+set_bits, (block_bits+2*set_bits) - 1);
    //assert(c0 < (m_filter_size/2));
    //assert(c0 + (m_filter_size/2) < m_filter_size);
    //assert(c1 < (m_filter_size/2));
    // set v0 bit
    m_temp_filter[c0 + (m_filter_size/2)] = 1;
    // set v1 bit
    m_temp_filter[c1] = 1;

    // perform filter intersection. If any c part is 0, no possibility
    // of address being in signature.  get first c intersection part
    bool zero = false;
    for (int i = 0; i < m_filter_size/2; ++i){
        // get intersection of signatures
        m_temp_filter[i] = m_temp_filter[i] && m_filter[i];
        zero = zero || m_temp_filter[i];
    }
    zero = !zero;
    if (zero) {
        // one section is zero, no possiblility of address in signature
        // reset bits we just set
        m_temp_filter[c0 + (m_filter_size / 2)] = 0;
        m_temp_filter[c1] = 0;
        return false;
    }

    // check second section
    zero = false;
    for(int i = m_filter_size / 2; i < m_filter_size; ++i) {
        // get intersection of signatures
        m_temp_filter[i] =  m_temp_filter[i] && m_filter[i];
        zero = zero || m_temp_filter[i];
    }
    zero = !zero;
    if (zero) {
        // one section is zero, no possiblility of address in signature
        m_temp_filter[c0 + (m_filter_size / 2)] = 0;
        m_temp_filter[c1] = 0;
        return false;
    }
    // one section has at least one bit set
    m_temp_filter[c0 + (m_filter_size / 2)] = 0;
    m_temp_filter[c1] = 0;
    return true;
}

int
BulkBloomFilter::getCount(const Address& addr)
{
    // not used
    return 0;
}

int
BulkBloomFilter::getTotalCount()
{
    int count = 0;
    for (int i = 0; i < m_filter_size; i++) {
        if (m_filter[i]) {
            count++;
        }
    }
    return count;
}

int
BulkBloomFilter::getIndex(const Address& addr)
{
    return get_index(addr);
}

int
BulkBloomFilter::readBit(const int index)
{
    return 0;
    // TODO
}

void
BulkBloomFilter::writeBit(const int index, const int value)
{
    // TODO
}

void
BulkBloomFilter::print(ostream& out) const
{
}

int
BulkBloomFilter::get_index(const Address& addr)
{
    return addr.bitSelect(RubySystem::getBlockSizeBits(),
                          RubySystem::getBlockSizeBits() +
                          m_filter_size_bits - 1);
}

Address
BulkBloomFilter::permute(const Address & addr)
{
    // permutes the original address bits according to Table 5
    int block_offset = RubySystem::getBlockSizeBits();
    physical_address_t part1 = addr.bitSelect(block_offset, block_offset + 6),
        part2 = addr.bitSelect(block_offset + 9, block_offset + 9),
        part3 = addr.bitSelect(block_offset + 11, block_offset + 11),
        part4 = addr.bitSelect(block_offset + 17, block_offset + 17),
        part5 = addr.bitSelect(block_offset + 7, block_offset + 8),
        part6 = addr.bitSelect(block_offset + 10, block_offset + 10),
        part7 = addr.bitSelect(block_offset + 12, block_offset + 12),
        part8 = addr.bitSelect(block_offset + 13, block_offset + 13),
        part9 = addr.bitSelect(block_offset + 15, block_offset + 16),
        part10 = addr.bitSelect(block_offset + 18, block_offset + 20),
        part11 = addr.bitSelect(block_offset + 14, block_offset + 14);

    physical_address_t result =
        (part1 << 14) | (part2 << 13) | (part3 << 12) | (part4 << 11) |
        (part5 << 9)  | (part6 << 8)  | (part7 << 7)  | (part8 << 6)  |
        (part9 << 4)  | (part10 << 1) | (part11);

    // assume 32 bit addresses (both virtual and physical)
    // select the remaining high-order 11 bits
    physical_address_t remaining_bits =
        addr.bitSelect(block_offset + 21, 31) << 21;
    result = result | remaining_bits;

    return Address(result);
}


text:
<?php

namespace Oro\Bundle\DataAuditBundle\Migrations\Schema\v1_2;

use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;

class OroDataAuditBundle implements Migration
{
    /**
     * @inheritdoc
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        self::addOrganizationFields($schema);
    }

    /**
     * Adds organization_id field
     *
     * @param Schema $schema
     */
    public static function addOrganizationFields(Schema $schema)
    {
        $table = $schema->getTable('oro_audit');

        $table->addColumn('organization_id', 'integer', ['notnull' => false]);
        $table->addIndex(['organization_id'], 'idx_oro_audit_organization_id', []);
        $table->addForeignKeyConstraint(
            $schema->getTable('oro_organization'),
            ['organization_id'],
            ['id'],
            ['onDelete' => 'SET NULL']
        );
    }
}


text:
package com.kavinschool.testng.examples;

import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class PriorityWithDependencies {

    @BeforeClass(alwaysRun = true)
    public void beforeClass() {
        System.out.println("PriorityWithDependencies.beforeClass");
    }

    @AfterClass(alwaysRun = true)
    public void afterClass() {
        System.out.println("PriorityWithDependencies.afterClass");
    }

    @Test(groups = {"PriorityWithDependencies","testApple"} )
    public void testApple() {
        System.out.println("PriorityWithDependencies.testApple");
    }

    @Test(groups = {"PriorityWithDependencies","testBanana"} )
    public void testBanana() {
        System.out.println("PriorityWithDependencies.testBanana");
    }

    @Test(groups = {"PriorityWithDependencies","testCherry"} )
    public void testCherry() {
        System.out.println("PriorityWithDependencies.testCherry");
    }

}


text:
// Copyright (c) Microsoft.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using Microsoft.WindowsAzure.Management.Network;
using Microsoft.WindowsAzure.Management.Network.Models;

namespace Network.Tests.ApplicationGateways.TestOperations
{
    public class StartApplicationGateway : TestOperation
    {
        private readonly IApplicationGatewayOperations applicationGatewayClient;
        private readonly string gatewayName;
        //private readonly ApplicationGatewayOperation op;

        public ApplicationGatewayOperationResponse InvokeResponse { get; private set; }

        public StartApplicationGateway(IApplicationGatewayOperations applicationGatewayClient, string gatewayName)
        {
            this.applicationGatewayClient = applicationGatewayClient;
            this.gatewayName = gatewayName;
        }

        public void Invoke()
        {
            ApplicationGatewayOperation op = new ApplicationGatewayOperation();
            op.OperationType = "start";

            InvokeResponse = applicationGatewayClient.ExecuteOperation(gatewayName, op);
        }

        public void Undo()
        {
            ApplicationGatewayOperation op = new ApplicationGatewayOperation();
            op.OperationType = "stop";

            applicationGatewayClient.ExecuteOperation(gatewayName, op);
        }
    }
}


text:
package tcplisten

import (
	"fmt"
	"syscall"
)

func newSocketCloexecOld(domain, typ, proto int) (int, error) {
	syscall.ForkLock.RLock()
	fd, err := syscall.Socket(domain, typ, proto)
	if err == nil {
		syscall.CloseOnExec(fd)
	}
	syscall.ForkLock.RUnlock()
	if err != nil {
		return -1, fmt.Errorf("cannot create listening socket: %s", err)
	}
	if err = syscall.SetNonblock(fd, true); err != nil {
		syscall.Close(fd)
		return -1, fmt.Errorf("cannot make non-blocked listening socket: %s", err)
	}
	return fd, nil
}


text:
"""
Modified version of https://github.com/carpedm20/DCGAN-tensorflow/blob/master/utils.py
"""
from __future__ import division
import os
import math
import json
import random
import pprint
import scipy.misc
import numpy as np
from time import gmtime, strftime
from glob import glob

pp = pprint.PrettyPrinter()

get_stddev = lambda x, k_h, k_w: 1/math.sqrt(k_w*k_h*x.get_shape()[-1])

def get_image(image_path, image_size, is_crop=True, resize_w=64, is_grayscale = False):
    return transform(imread(image_path, is_grayscale), image_size, is_crop, resize_w)

def save_images(images, size, image_path):
    return imsave(inverse_transform(images), size, image_path)

def imread(path, is_grayscale = False):
    if (is_grayscale):
        return scipy.misc.imread(path, flatten = True).astype(np.float)
    else:
        return scipy.misc.imread(path).astype(np.float)

def merge_images(images, size):
    return inverse_transform(images)

def merge(images, size):
    h, w = images.shape[1], images.shape[2]
    img = np.zeros((h * size[0], w * size[1], 3))
    for idx, image in enumerate(images):
        i = idx % size[1]
        j = idx // size[1]
        img[j*h:j*h+h, i*w:i*w+w, :] = image

    return img

def imsave(images, size, path):
    return scipy.misc.imsave(path, merge(images, size))

def center_crop(x, crop_h, crop_w=None, resize_w=64):
    if crop_w is None:
        crop_w = crop_h
    h, w = x.shape[:2]
    j = int(round((h - crop_h)/2.))
    i = int(round((w - crop_w)/2.))
    return scipy.misc.imresize(x[j:j+crop_h, i:i+crop_w],
                               [resize_w, resize_w])

def transform(image, npx=64, is_crop=True, resize_w=64):
    # npx : # of pixels width/height of image
    if is_crop:
        cropped_image = center_crop(image, npx, resize_w=resize_w)
    else:
        cropped_image = image
    return np.array(cropped_image)/127.5 - 1.

def inverse_transform(images):
    return (images+1.)/2.

def get_batch_images(batch_index, data, config):

    if type(data) == list:
        is_grayscale = (config.c_dim == 1)

        batch_files = data[batch_index*config.batch_size:(batch_index+1)*config.batch_size]
        batch = [get_image(batch_file, config.image_size, is_crop=config.is_crop, resize_w=config.output_size, is_grayscale = is_grayscale) for batch_file in batch_files]

        if (is_grayscale):
            batch_images = np.array(batch).astype(np.float32)[:, :, :, None]
        else:
            batch_images = np.array(batch).astype(np.float32)

        return batch_images

    elif type(data) == np.ndarray:
        return data[batch_index*config.batch_size:(batch_index+1)*config.batch_size]

def get_data_arr(config):

    is_crop = '_cropped' if config.is_crop == True else ''
    npy_path = os.path.join('./data', config.dataset+is_crop+'.npy')

    is_grayscale = (config.c_dim == 1)
    if not os.path.exists(npy_path):
        files = glob(os.path.join('./data', config.dataset, '*.jpg'))
        data = [get_image(batch_file, config.image_size, is_crop=config.is_crop, resize_w=config.output_size, is_grayscale = is_grayscale) for batch_file in files]
        np.save(npy_path, data)

    data = np.load(npy_path)

    if (is_grayscale):
        data = np.array(data).astype(np.float32)[:, :, :, None]
    else:
        data = np.array(data).astype(np.float32)

    return data


text:
/**
 * @constructor
 * @extends {WebInspector.VBox}
 * @implements {WebInspector.TargetManager.Observer}
 */
WebInspector.RenderingOptionsView = function()
{
    WebInspector.VBox.call(this, true);
    this.registerRequiredCSS("main/renderingOptions.css");

    /** @type {!Map.<string, !Element>} */
    this._settings = new Map();

    var options = [
        {
            label: WebInspector.UIString("Paint Flashing"),
            subtitle: WebInspector.UIString("Highlights areas of the page that need to be repainted"),
            setterName: "setShowPaintRects"
        },
        {
            label: WebInspector.UIString("Layer Borders"),
            subtitle: WebInspector.UIString("Shows layer borders (orange/olive) and tiles (cyan)"),
            setterName: "setShowDebugBorders"
        },
        {
            label: WebInspector.UIString("FPS Meter"),
            subtitle: WebInspector.UIString("Plots frames per second, frame rate distribution, and GPU memory"),
            setterName: "setShowFPSCounter"
        },
        {
            label: WebInspector.UIString("Scrolling Performance Issues"),
            subtitle: WebInspector.UIString("Shows areas of the page that slow down scrolling"),
            setterName: "setShowScrollBottleneckRects",
            tooltip: "Touch and mousewheel event listeners can delay scrolling.\nSome areas need to repaint their content when scrolled."
        }
    ];
    for (var i = 0; i < options.length; i++)
        this._appendCheckbox(options[i].label, options[i].setterName, options[i].subtitle, options[i].tooltip);

    this.contentElement.createChild("div").classList.add("panel-section-separator");

    var cssMediaSubtitle = WebInspector.UIString("Forces media type for testing print and screen styles");
    var checkboxLabel = createCheckboxLabel(WebInspector.UIString("Emulate CSS Media"), false, cssMediaSubtitle);
    this._mediaCheckbox = checkboxLabel.checkboxElement;
    this._mediaCheckbox.addEventListener("click", this._mediaToggled.bind(this), false);
    this.contentElement.appendChild(checkboxLabel);

    var mediaRow = this.contentElement.createChild("div", "media-row");
    this._mediaSelect = mediaRow.createChild("select", "chrome-select");
    this._mediaSelect.appendChild(new Option(WebInspector.UIString("print"), "print"));
    this._mediaSelect.appendChild(new Option(WebInspector.UIString("screen"), "screen"));
    this._mediaSelect.addEventListener("change", this._mediaToggled.bind(this), false);
    this._mediaSelect.disabled = true;

    WebInspector.targetManager.observeTargets(this, WebInspector.Target.Type.Page);
}

WebInspector.RenderingOptionsView.prototype = {
    /**
     * @param {string} label
     * @param {string} setterName
     * @param {string=} subtitle
     * @param {string=} tooltip
     */
    _appendCheckbox: function(label, setterName, subtitle, tooltip)
    {
        var checkboxLabel = createCheckboxLabel(label, false, subtitle);
        this._settings.set(setterName, checkboxLabel.checkboxElement);
        checkboxLabel.checkboxElement.addEventListener("click", this._settingToggled.bind(this, setterName));
        if (tooltip)
            checkboxLabel.title = tooltip;
        this.contentElement.appendChild(checkboxLabel);
    },

    /**
     * @param {string} setterName
     */
    _settingToggled: function(setterName)
    {
        var enabled = this._settings.get(setterName).checked;
        var targets = WebInspector.targetManager.targets(WebInspector.Target.Type.Page);
        for (var i = 0; i < targets.length; ++i)
            targets[i].renderingAgent()[setterName](enabled);
    },

    /**
     * @override
     * @param {!WebInspector.Target} target
     */
    targetAdded: function(target)
    {
        for (var setterName of this._settings.keysArray()) {
            if (this._settings.get(setterName).checked)
                target.renderingAgent()[setterName](true);
        }
        if (this._mediaCheckbox.checked)
            this._applyPrintMediaOverride(target);
    },

    _mediaToggled: function()
    {
        this._mediaSelect.disabled = !this._mediaCheckbox.checked;
        var targets = WebInspector.targetManager.targets(WebInspector.Target.Type.Page);
        for (var target of targets)
            this._applyPrintMediaOverride(target);
    },

    /**
     * @param {!WebInspector.Target} target
     */
    _applyPrintMediaOverride: function(target)
    {
        target.emulationAgent().setEmulatedMedia(this._mediaCheckbox.checked ? this._mediaSelect.value : "");
        var cssModel = WebInspector.CSSModel.fromTarget(target);
        if (cssModel)
            cssModel.mediaQueryResultChanged();
    },

    /**
     * @override
     * @param {!WebInspector.Target} target
     */
    targetRemoved: function(target)
    {
    },

    __proto__: WebInspector.VBox.prototype
}

/**
 * @return {!WebInspector.RenderingOptionsView}
 */
WebInspector.RenderingOptionsView.instance = function()
{
    if (!WebInspector.RenderingOptionsView._instanceObject)
        WebInspector.RenderingOptionsView._instanceObject = new WebInspector.RenderingOptionsView();
    return WebInspector.RenderingOptionsView._instanceObject;
}

/**
 * @constructor
 * @implements {WebInspector.ActionDelegate}
 */
WebInspector.RenderingOptionsView.ShowActionDelegate = function()
{
}

WebInspector.RenderingOptionsView.ShowActionDelegate.prototype = {
    /**
     * @override
     * @param {!WebInspector.Context} context
     * @param {string} actionId
     * @return {boolean}
     */
    handleAction: function(context, actionId)
    {
        WebInspector.inspectorView.showViewInDrawer("rendering");
        return true;
    }
}


text:
package org.kaaproject.kaa.client.logging.future;

public class ExecutionResult<T> {

    private final T t;
    private final Exception e;

    public ExecutionResult(T t, Exception e) {
        super();
        this.t = t;
        this.e = e;
    }

    public T get() {
        return t;
    }

    public Exception getE() {
        return e;
    }

}


text:
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
    {
        "file": "plugins/org.apache.cordova.camera/www/CameraConstants.js",
        "id": "org.apache.cordova.camera.Camera",
        "clobbers": [
            "Camera"
        ]
    },
    {
        "file": "plugins/org.apache.cordova.camera/www/CameraPopoverOptions.js",
        "id": "org.apache.cordova.camera.CameraPopoverOptions",
        "clobbers": [
            "CameraPopoverOptions"
        ]
    },
    {
        "file": "plugins/org.apache.cordova.camera/www/Camera.js",
        "id": "org.apache.cordova.camera.camera",
        "clobbers": [
            "navigator.camera"
        ]
    },
    {
        "file": "plugins/org.apache.cordova.camera/www/CameraPopoverHandle.js",
        "id": "org.apache.cordova.camera.CameraPopoverHandle",
        "clobbers": [
            "CameraPopoverHandle"
        ]
    }
];
module.exports.metadata =
// TOP OF METADATA
{
    "org.apache.cordova.camera": "0.2.8"
}
// BOTTOM OF METADATA
});


text:
using System;
using System.Security;
using System.Runtime.InteropServices;

namespace Microsoft.Win32.SafeHandles
{
    [SecurityCritical]
    internal sealed class SafeBioHandle : SafeHandle
    {
        private SafeBioHandle() :
            base(IntPtr.Zero, ownsHandle: true)
        {
        }

        protected override bool ReleaseHandle()
        {
            Interop.Crypto.BioDestroy(handle);
            SetHandle(IntPtr.Zero);
            return true;
        }

        public override bool IsInvalid
        {
            get { return handle == IntPtr.Zero; }
        }
    }
}


text:
<!DOCTYPE html>

      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css">

      <meta name="viewport" content="width=device-width, height=device-height"/>

				Lets Play Flag!

Home

Admin

Players

Football Field

Players


text:
#include "BurstApplLayer.h"

#include "ApplPkt_m.h"

using std::endl;

Define_Module(BurstApplLayer);

// do some initialization
void BurstApplLayer::initialize(int stage)
{
    TestApplLayer::initialize(stage);

    if(stage==0){
        if(hasPar("burstSize"))
            burstSize = par("burstSize");
        else
            burstSize = 3;
        if(hasPar("burstReply"))
        	bSendReply = par("burstReply");
        else
        	bSendReply = true;
    }
}

void BurstApplLayer::handleSelfMsg(cMessage *msg)
{
    switch(msg->getKind())
    {
    case SEND_BROADCAST_TIMER:
        for(int i=0; i<burstSize; i++) {
            sendBroadcast();
        }
        break;
    default:
        EV <<" Unkown selfmessage! -> delete, kind: "<<msg->getKind()<<endl;
        break;
    }
}

/**
 * There are two kinds of messages that can arrive at this module: The
 * first (kind = BROADCAST_MESSAGE) is a broadcast packet from a
 * neighbor node to which we have to send a reply (if bSendReply is true). The second (kind =
 * BROADCAST_REPLY_MESSAGE) is a reply to a broadcast packet that we
 * have send and just causes some output before it is deleted
 */
void BurstApplLayer::handleLowerMsg( cMessage* msg )
{
	if ( !bSendReply && msg->getKind() == BROADCAST_MESSAGE) {
		ApplPkt *m  = static_cast<ApplPkt *>(msg);
		coreEV << "Received a broadcast packet from host["<<m->getSrcAddr()<<"] -> delete message, no reply" << endl;
		delete msg;
		return;
	}
	TestApplLayer::handleLowerMsg(msg);
}


text:
- Move library over to TypeScript.
- change `execute` to `dispatch`
- Use `whatwg` streams.
- Add more i/o capabilities.

### 5.0.0

- Built with ES6 in mind. Works with `async/await` and `yield` operators.
- [Node Streams](https://nodejs.org/api/stream.html) have been deprecated for Promises.
- API is not more explicit - `ParallelBus` vs `parallel`, and so on.
- No more external dependencies.
- `mesh-*` have been deprecated. More utilities to come into this library.
- All docs have been moved to to the Github repo.


text:
package Paws::Lightsail::GetInstanceStateResult;
  use Moose;
  has State => (is => 'ro', isa => 'Paws::Lightsail::InstanceState', traits => ['NameInRequest'], request_name => 'state' );

  has _request_id => (is => 'ro', isa => 'Str');

### main pod documentation begin ###

=head1 NAME

Paws::Lightsail::GetInstanceStateResult

=head1 ATTRIBUTES

=head2 State => L<Paws::Lightsail::InstanceState>

The state of the instance.

=head2 _request_id => Str

=cut

1;


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;

namespace EE.FutureProof.Bridge
{
    public static class UpgradeServices
    {
        static UpgradeServices()
        {
            try
            {
                var assembly = Assembly.GetExecutingAssembly();
                var upgraders = assembly.GetTypes().Where(t => !t.IsAbstract && typeof(IUpgrader).IsAssignableFrom(t));
                foreach (var upgrader in upgraders)
                {
                    var attr = (UpgraderAttribute)upgrader.GetCustomAttributes(
                            typeof(UpgraderAttribute), true)
                        .FirstOrDefault();
                    if (attr != null)
                    {
                        List<UpgraderData> version;
                        if (!Upgraders.TryGetValue(attr.FromVersion, out version)) Upgraders.Add(attr.FromVersion, version = new List<UpgraderData>());
                        version.Add(new UpgraderData { Attribute = attr, Type = upgrader });
                    }
                }
            }
            catch (ApplicationException ex)
            {
                Trace.TraceError($"FutureProof: Unable to load bridge upgraders. {ex.Message} {ex.InnerException?.Message}");
                throw;
            }
        }

        private static Dictionary<int, List<UpgraderData>> Upgraders { get; } = new Dictionary<int, List<UpgraderData>>();

        public static IUpgrader GetUpgrader(int fromVersion, int toVersion)
        {
            var aggregator = new AggregateUpgrader();

            while (fromVersion < toVersion)
            {
                List<UpgraderData> version;
                if (Upgraders.TryGetValue(fromVersion, out version))
                {
                    var data = version
                        .Where(d => d.Attribute.ToVersion <= toVersion)
                        .OrderByDescending(d => d.Attribute.ToVersion)
                        .First();

                    var upgrader = (IUpgrader)Activator.CreateInstance(data.Type);
                    aggregator.Upgraders.Add(upgrader);

                    fromVersion = data.Attribute.ToVersion;
                }
                else
                {
                    fromVersion++;
                }
            }

            return aggregator;
        }

        private class UpgraderData
        {
            public UpgraderAttribute Attribute { get; set; }
            public Type Type { get; set; }
        }
    }
}


text:
package main

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

type dummyAuth struct {
	usernameSent, passwordSent string
	called                     int
	ret                        bool
}

func (a *dummyAuth) authenticate(username, password string) (bool, error) {
	a.usernameSent = username
	a.passwordSent = password
	a.called += 1
	return a.ret, nil
}

func TestRootHandlerServesLoaderScriptWithDefaultExpiry(t *testing.T) {
	request, _ := http.NewRequest("GET", "/", nil)
	response := httptest.NewRecorder()

	server := newServer(
		configuration{LoaderScript: "testdata/loader.sh"},
		nil,
	)
	server.routes()
	server.ServeHTTP(response, request)

	code := response.Code
	if code != 200 {
		t.Error("response code was not 200:", code)
	}

	body := strings.TrimSpace(response.Body.String())
	if body != "awesome loader script 32400" {
		t.Error("wrong response from /:", body)
	}
}

func TestRootHandlerServesLoaderScriptWithExpiry(t *testing.T) {
	request, _ := http.NewRequest("GET", "/3", nil)
	response := httptest.NewRecorder()

	server := newServer(
		configuration{LoaderScript: "testdata/loader.sh"},
		nil,
	)
	server.routes()
	server.ServeHTTP(response, request)

	code := response.Code
	if code != 200 {
		t.Error("response code was not 200:", code)
	}

	body := strings.TrimSpace(response.Body.String())
	if body != "awesome loader script 10800" {
		t.Error("wrong response from /:", body)
	}
}

func TestKeysHandlerRequiresAuthentication(t *testing.T) {
	request, _ := http.NewRequest("GET", "/key", nil)
	response := httptest.NewRecorder()

	server := newServer(
		configuration{PrivateKey: "testdata/id_rsa"},
		&dummyAuth{},
	)
	server.routes()
	server.ServeHTTP(response, request)

	code := response.Code
	if code != 401 {
		t.Error("request should have been rejected with 401:", code)
	}

	header := response.Header().Get("Authenticate")
	if header != "KeyGuard" {
		t.Error("correct authenticate header was not in response:", header)
	}
}

func TestKeysHandlerRequiresValidCredentials(t *testing.T) {
	request, _ := http.NewRequest("GET", "/key", nil)
	response := httptest.NewRecorder()

	request.SetBasicAuth("cromega", "supersecurepassword")

	server := newServer(
		configuration{PrivateKey: "testdata/id_rsa"},
		&dummyAuth{ret: true},
	)
	server.routes()
	server.ServeHTTP(response, request)

	code := response.Code
	if code != 200 {
		t.Error("http status should be 200:", code)
	}
}

func TestKeysHandlerAuthenticatesTheRequest(t *testing.T) {
	request, _ := http.NewRequest("GET", "/key", nil)
	request.SetBasicAuth("keyguard", "supersecurepassword")
	response := httptest.NewRecorder()

	auth := &dummyAuth{ret: true}
	server := newServer(
		configuration{PrivateKey: "testdata/id_rsa"},
		auth,
	)
	server.routes()
	server.ServeHTTP(response, request)

	if auth.called != 1 {
		t.Error("the authenticator was not called")
	}

	if auth.usernameSent != "keyguard" {
		t.Error("sent the wrong username to the authenticator:", auth.usernameSent)
	}

	if auth.passwordSent != "supersecurepassword" {
		t.Error("sent the wrong password to the authenticator:", auth.passwordSent)
	}

	if response.Code != 200 {
		t.Error("wrong respnse code:", response.Code)
	}
}

func TestKeysHandlerRespondsWithKey(t *testing.T) {
	request, _ := http.NewRequest("GET", "/key", nil)
	request.SetBasicAuth("cromega", "supersecurepassword")
	response := httptest.NewRecorder()

	auth := &dummyAuth{ret: true}
	server := newServer(
		configuration{PrivateKey: "testdata/id_rsa"},
		auth,
	)
	server.routes()
	server.ServeHTTP(response, request)

	body := response.Body.String()
	if body != "awesome private key" {
		t.Error("server should have responded with the correct ssh key:", body)
	}
}

func TestPublicKeyHandlerSendsPublicKey(t *testing.T) {
	request, _ := http.NewRequest("GET", "/pubkey", nil)
	response := httptest.NewRecorder()

	server := newServer(
		configuration{PrivateKey: "testdata/real_id_rsa"},
		nil,
	)
	server.routes()
	server.ServeHTTP(response, request)

	if response.Code != 200 {
		t.Error("response should be OK", response.Code)
	}

	body := response.Body.String()
	if body != "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDBgps60FUrGlCFlH48/cSWaDuZYfCTvgRIZt60CiQ1fPj53SQ6xpcDpSCpt1pJt/Q1xZtHPaNZ+HWKAU3tOgspi/AJdrQAPC54CLzdBsMlL/+JxjMxtCf0bbG8dxoRijxIppXVyIuCLabA2oEhepf3U/H+Dvm3XST22f87FsQVrw==\n" {
		t.Error("server should have responded with a public key:", body)
	}
}


text:
using System;
using org.docx4j;
using org.docx4j.openpackaging.packages;
using org.docx4j.openpackaging.parts;
using org.docx4j.openpackaging.parts.WordprocessingML;
using org.docx4j.wml;

using System.Collections.Specialized;
using Common.Logging;

namespace docx4j.NET.samples
{
    /// <summary>
    /// Demonstrates using docx4j to resolve the XPaths binding content controls to a CustomXML part.
    /// Ordinarily, Word does this when you open the docx in Word.  But sometimes, you want to do it
    /// yourself, for example, when producing PDF or XHTML output.
    ///
    /// You might also want docx4j to do it, to take advantage of additional features, such as
    /// repeats, conditional content, or binding escaped XHTML or docx content.  See http://www.opendope.org
    ///
    /// If you are trying this in Visual Studio, it'll be faster if you "start without debugging" (Ctrl+F5)
    /// And first, remember to set this as the "startup object" in project properties.
    ///
    /// </summary>
    class ContentControlBind
    {
        static ILog clog;
        static void Main(string[] args)
        {

            // set up logging
            clog = LoggingConfigurator.configureLogging();
            clog.Info("Hello from Common Logging");

            string projectDir = System.IO.Directory.GetParent(
                System.IO.Directory.GetParent(
                Environment.CurrentDirectory.ToString()).ToString()).ToString() + "\\";

            // the docx 'template'
            String input_DOCX = projectDir + @"src\samples\resources\ContentControlBind\binding-simple.docx";

            // the instance data
            String input_XML = projectDir + @"src\samples\resources\ContentControlBind\binding-simple-data.xml";

            // resulting docx
            String OUTPUT_DOCX = projectDir + @"OUT_ContentControlsMergeXML.docx";

            // Configure to find docx4j.properties
            // .. add as URL the dir containing docx4j.properties (not the file itself!)
            Plutext.PropertiesConfigurator.setDocx4jPropertiesDir(projectDir + @"src\samples\resources\");

		    // Load input_template.docx
		    WordprocessingMLPackage wordMLPackage = org.docx4j.Docx4J.load(new java.io.File(input_DOCX));

		    // Open the xml stream
		    java.io.FileInputStream xmlStream = new java.io.FileInputStream(new java.io.File(input_XML));

		    // Do the binding:
		    // FLAG_NONE means that all the steps of the binding will be done,
		    // otherwise you could pass a combination of the following flags:
		    // FLAG_BIND_INSERT_XML: inject the passed XML into the document
		    // FLAG_BIND_BIND_XML: bind the document and the xml (including any OpenDope handling)
		    // FLAG_BIND_REMOVE_SDT: remove the content controls from the document (only the content remains)
		    // FLAG_BIND_REMOVE_XML: remove the custom xml parts from the document

		    //Docx4J.bind(wordMLPackage, xmlStream, Docx4J.FLAG_NONE);
		    //If a document doesn't include the Opendope definitions, eg. the XPathPart,
		    //then the only thing you can do is insert the xml
		    //the example document binding-simple.docx doesn't have an XPathPart....
		    Docx4J.bind(wordMLPackage, xmlStream, Docx4J.FLAG_BIND_INSERT_XML & Docx4J.FLAG_BIND_BIND_XML);

		    //Save the document
		    Docx4J.save(wordMLPackage, new java.io.File(OUTPUT_DOCX), Docx4J.FLAG_NONE);
		    clog.Info("Saved: " + OUTPUT_DOCX);

        }

    }

}


text:
/**
 * Fiber Application Class
 * @class
 */
Fiber.Application = Fiber.Object.extend({

  /**
   * Viewport instance
   * @type {Object.<Fiber.Viewport>}
   */
  viewport: null,

  /**
   * Router instance
   * @type {Object.<Fiber.Router>}
   */
  router: null,

  /**
   * Fiber Inversion of Control Container instance
   * @type {Object.<Fiber.Services.Container>}
   */
  container: Fiber.container,

  /**
   * Constructs Application
   * @param {?Object} [options={}]
   */
  constructor: function(options) {
    options = this.handleOptions(options);
    $fn.extensions.init(this);
    this.bootstrap(options);
    this.bindEvents();
    this.$super('initialize', arguments);
  },

  /**
   * Binds events
   */
  bindEvents: function() {
    this.listenTo(this.router, 'execute', this.whenRouteExecute.bind(this));
  },

  /**
   * When router executes hook
   * @param {Object.<Fiber.View>} composed
   * @param {Object.<Fiber.Route>} route
   * @param {Array} args
   */
  whenRouteExecute: function(composed, route) {
    this.viewport.show(composed, route.get('layout'));
  },

  /**
   * Bootstraps Application
   * @param {?Object} [options={}]
   * @returns {Fiber.Application}
   */
  bootstrap: function(options) {
    this.viewport = new Fiber.Viewport(options.viewport);
    this.router = new Fiber.Router(options.router);
    return this;
  },

  /**
   * Runs the Application
   * @return {Fiber.Application}
   */
  start: function() {
    $fn.fireCallCyclic(this, 'start', function() {
      Fiber.history.start();
      this.fire('start', this);
    });
    return this;
  },

  /**
   * Terminates Application
   * @returns {Fiber.Application}
   */
  stop: function() {
    $fn.fireCallCyclic(this, 'stop', function() {
      Fiber.history.stop();
      this.fire('stop', this);
    });
    return this;
  },

  /**
   * Handles income options
   * @param {?Object} [options={}]
   * @returns {Object}
   */
  handleOptions: function(options) {
    return $fn.class.handleOptions(this, options, this.result('defaults'), true);
  },

});


text:
ast_t* evaluate_and_bool(ast_t* receiver, ast_t* args, pass_opt_t* opt)
{
  (void) opt;
  return (ast_id(receiver) == TK_TRUE) ? ast_child(args): receiver;
}

ast_t* evaluate_or_bool(ast_t* receiver, ast_t* args, pass_opt_t* opt)
{
  (void) opt;
  return (ast_id(receiver) == TK_FALSE) ? ast_child(args): receiver;
}

ast_t* evaluate_not_bool(ast_t* receiver, ast_t* args, pass_opt_t* opt)

{
  (void) opt;
  (void) args;
  BUILD(result, receiver, NODE(ast_id(receiver) == TK_FALSE ? TK_TRUE : TK_FALSE));
  return result;
}


text:
#include <mongoc-util-private.h>
#include <mongoc.h>

#include "mongoc-client-private.h"
#include "mongoc-uri-private.h"

#include "mock_server/mock-server.h"
#include "mock_server/future.h"
#include "mock_server/future-functions.h"
#include "mongoc-tests.h"
#include "TestSuite.h"
#include "test-libmongoc.h"
#include "test-conveniences.h"

#undef MONGOC_LOG_DOMAIN
#define MONGOC_LOG_DOMAIN "cluster-test"

static uint32_t server_id_for_reads (mongoc_cluster_t *cluster)
{
   bson_error_t error;
   mongoc_server_stream_t *server_stream;
   uint32_t id;

   server_stream = mongoc_cluster_stream_for_reads (cluster, NULL, &error);
   ASSERT_OR_PRINT (server_stream, error);
   id = server_stream->sd->id;

   mongoc_server_stream_cleanup (server_stream);

   return id;
}

static void
test_get_max_bson_obj_size (void)
{
   mongoc_server_description_t *sd;
   mongoc_cluster_node_t *node;
   mongoc_client_pool_t *pool;
   mongoc_client_t *client;
   int32_t max_bson_obj_size = 16;
   uint32_t id;

   /* single-threaded */
   client = test_framework_client_new ();
   assert (client);

   id = server_id_for_reads (&client->cluster);
   sd = (mongoc_server_description_t *)mongoc_set_get (client->topology->description.servers, id);
   sd->max_bson_obj_size = max_bson_obj_size;
   assert (max_bson_obj_size == mongoc_cluster_get_max_bson_obj_size (&client->cluster));

   mongoc_client_destroy (client);

   /* multi-threaded */
   pool = test_framework_client_pool_new ();
   client = mongoc_client_pool_pop (pool);

   id = server_id_for_reads (&client->cluster);
   node = (mongoc_cluster_node_t *)mongoc_set_get (client->cluster.nodes, id);
   node->max_bson_obj_size = max_bson_obj_size;
   assert (max_bson_obj_size == mongoc_cluster_get_max_bson_obj_size (&client->cluster));

   mongoc_client_pool_push (pool, client);
   mongoc_client_pool_destroy (pool);
}

static void
test_get_max_msg_size (void)
{
   mongoc_server_description_t *sd;
   mongoc_cluster_node_t *node;
   mongoc_client_pool_t *pool;
   mongoc_client_t *client;
   int32_t max_msg_size = 32;
   uint32_t id;

   /* single-threaded */
   client = test_framework_client_new ();
   id = server_id_for_reads (&client->cluster);

   sd = (mongoc_server_description_t *)mongoc_set_get (client->topology->description.servers, id);
   sd->max_msg_size = max_msg_size;
   assert (max_msg_size == mongoc_cluster_get_max_msg_size (&client->cluster));

   mongoc_client_destroy (client);

   /* multi-threaded */
   pool = test_framework_client_pool_new ();
   client = mongoc_client_pool_pop (pool);

   id = server_id_for_reads (&client->cluster);
   node = (mongoc_cluster_node_t *)mongoc_set_get (client->cluster.nodes, id);
   node->max_msg_size = max_msg_size;
   assert (max_msg_size == mongoc_cluster_get_max_msg_size (&client->cluster));

   mongoc_client_pool_push (pool, client);
   mongoc_client_pool_destroy (pool);
}

#define ASSERT_CURSOR_ERR() do { \
      char *error_message = bson_strdup_printf ( \
         "Failed to read 4 bytes from socket within %d milliseconds.", \
         socket_timeout_ms); \
      assert (!future_get_bool (future)); \
      assert (mongoc_cursor_error (cursor, &error)); \
      ASSERT_CMPINT (error.domain, ==, MONGOC_ERROR_STREAM); \
      ASSERT_CMPINT (error.code, ==, MONGOC_ERROR_STREAM_SOCKET); \
      ASSERT_CMPSTR (error.message, error_message); \
      bson_free (error_message); \
   } while (0)

#define START_QUERY(client_port_variable) do { \
      cursor = mongoc_collection_find (collection, \
                                       MONGOC_QUERY_NONE, \
                                       0, 0, 0, tmp_bson ("{}"), \
                                       NULL, NULL); \
      future = future_cursor_next (cursor, &doc); \
      request = mock_server_receives_query (server, "test.test", \
                                            MONGOC_QUERY_SLAVE_OK, 0, 0, \
                                            "{}", NULL); \
      client_port_variable = request_get_client_port (request); \
   } while (0)

#define CLEANUP_QUERY() do { \
      request_destroy (request); \
      future_destroy (future); \
      mongoc_cursor_destroy (cursor); \
   } while (0)

/* test that we reconnect a cluster node after disconnect */
static void
_test_cluster_node_disconnect (bool pooled)
{
   mock_server_t *server;
   const int32_t socket_timeout_ms = 100;
   mongoc_uri_t *uri;
   mongoc_client_pool_t *pool = NULL;
   mongoc_client_t *client;
   mongoc_collection_t *collection;
   const bson_t *doc;
   mongoc_cursor_t *cursor;
   future_t *future;
   request_t *request;
   uint16_t client_port_0, client_port_1;
   bson_error_t error;

   server = mock_server_with_autoismaster (0);
   mock_server_run (server);

   uri = mongoc_uri_copy (mock_server_get_uri (server));
   mongoc_uri_set_option_as_int32 (uri, "socketTimeoutMS", socket_timeout_ms);

   if (pooled) {
      pool = mongoc_client_pool_new (uri);
      client = mongoc_client_pool_pop (pool);
   } else {
      client = mongoc_client_new_from_uri (uri);
   }

   collection = mongoc_client_get_collection (client, "test", "test");

   /* query 0 fails. set client_port_0 to the port used by the query. */
   START_QUERY (client_port_0);
   if (pooled) {
      suppress_one_message ();
   }

   mock_server_resets (request);
   ASSERT_CURSOR_ERR ();
   CLEANUP_QUERY ();

   /* query 1 opens a new socket. set client_port_1 to the new port. */
   START_QUERY (client_port_1);
   ASSERT_CMPINT (client_port_1, !=, client_port_0);
   mock_server_replies_simple (request, "{'a': 1}");

   /* success! */
   BSON_ASSERT (future_get_bool (future));

   CLEANUP_QUERY ();
   mongoc_collection_destroy (collection);

   if (pooled) {
      mongoc_client_pool_push (pool, client);
      mongoc_client_pool_destroy (pool);
   } else {
      mongoc_client_destroy (client);
   }

   mongoc_uri_destroy (uri);
   mock_server_destroy (server);
}

static void
test_cluster_node_disconnect_single (void)
{
   _test_cluster_node_disconnect (false);
}

static void
test_cluster_node_disconnect_pooled (void)
{
   _test_cluster_node_disconnect (true);
}

static void
_test_cluster_command_timeout (bool pooled)
{
   mock_server_t *server;
   mongoc_uri_t *uri;
   mongoc_client_pool_t *pool = NULL;
   mongoc_client_t *client;
   bson_error_t error;
   future_t *future;
   request_t *request;
   uint16_t client_port;
   bson_t reply;

   server = mock_server_with_autoismaster (0);
   mock_server_run (server);
   uri = mongoc_uri_copy (mock_server_get_uri (server));
   mongoc_uri_set_option_as_int32 (uri, "socketTimeoutMS", 200);

   if (pooled) {
      pool = mongoc_client_pool_new (uri);
      client = mongoc_client_pool_pop (pool);
   } else {
      client = mongoc_client_new_from_uri (uri);
   }

   /* server doesn't respond in time */
   suppress_one_message ();
   future = future_client_command_simple (client, "db", tmp_bson ("{'foo': 1}"),
                                          NULL, NULL, &error);
   request = mock_server_receives_command (server, "db", MONGOC_QUERY_SLAVE_OK,
                                           NULL);
   client_port = request_get_client_port (request);

   ASSERT (!future_get_bool (future));
   ASSERT_ERROR_CONTAINS (error,
                          MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET,
                          "Failed to send \"foo\" command with database \"db\"");

   /* late response */
   mock_server_replies_simple (request, "{'ok': 1, 'bar': 1}");
   request_destroy (request);
   future_destroy (future);

   future = future_client_command_simple (client, "db", tmp_bson ("{'baz': 1}"),
                                          NULL, &reply, &error);
   request = mock_server_receives_command (server, "db", MONGOC_QUERY_SLAVE_OK,
                                           "{'baz': 1}");
   /* new socket */
   ASSERT_CMPUINT16 (client_port, !=, request_get_client_port (request));
   mock_server_replies_simple (request, "{'ok': 1, 'quux': 1}");
   ASSERT (future_get_bool (future));

   /* got the proper response */
   ASSERT_HAS_FIELD (&reply, "quux");

   if (pooled) {
      mongoc_client_pool_push (pool, client);
      mongoc_client_pool_destroy (pool);
   } else {
      mongoc_client_destroy (client);
   }

   bson_destroy (&reply);
   request_destroy (request);
   future_destroy (future);
   mongoc_uri_destroy (uri);
   mock_server_destroy (server);
}

static void
test_cluster_command_timeout_single (void)
{
   _test_cluster_command_timeout (false);
}

static void
test_cluster_command_timeout_pooled (void)
{
   _test_cluster_command_timeout (true);
}

static void
_test_write_disconnect (bool legacy)
{
   mock_server_t *server;
   char *ismaster_response;
   mongoc_client_t *client;
   mongoc_collection_t *collection;
   bson_error_t error;
   future_t *future;
   request_t *request;
   mongoc_topology_scanner_node_t *scanner_node;

   server = mock_server_new ();
   mock_server_run (server);
   client = mongoc_client_new_from_uri (mock_server_get_uri (server));

   /*
    * establish connection with an "ismaster" and "ping"
    */
   future = future_client_command_simple (client, "db", tmp_bson ("{'ping': 1}"),
                                          NULL, NULL, &error);
   request = mock_server_receives_ismaster (server);
   ismaster_response = bson_strdup_printf ("{'ok': 1.0,"
                                           " 'ismaster': true,"
                                           " 'minWireVersion': 0,"
                                           " 'maxWireVersion': %d}",
                                           legacy ? 0 : 3);

   mock_server_replies_simple (request, ismaster_response);
   request_destroy (request);

   request = mock_server_receives_command (server, "db", MONGOC_QUERY_SLAVE_OK,
                                           "{'ping': 1}");
   mock_server_replies_simple (request, "{'ok': 1}");
   ASSERT_OR_PRINT (future_get_bool (future), error);

   /*
    * wait for CHECK_CLOSED_DURATION_MSEC to elapse
    */
   _mongoc_usleep (1100 * 1000);

   /*
    * close the socket
    */
   mock_server_hangs_up (request);

   /*
    * next operation detects the hangup
    */
   collection = mongoc_client_get_collection (client, "db", "collection");
   future_destroy (future);
   future = future_collection_insert (collection, MONGOC_INSERT_NONE,
                                      tmp_bson ("{'_id': 1}"), NULL, &error);

   ASSERT (!future_get_bool (future));
   ASSERT_CMPINT (error.domain, ==, MONGOC_ERROR_STREAM);
   ASSERT_CMPINT (error.code, == , MONGOC_ERROR_STREAM_SOCKET);

   scanner_node = mongoc_topology_scanner_get_node (client->topology->scanner,
                                                    1 /* server_id */);
   ASSERT (scanner_node && !scanner_node->stream);

   mongoc_collection_destroy (collection);
   request_destroy (request);
   future_destroy (future);
   bson_free (ismaster_response);
   mongoc_client_destroy (client);
   mock_server_destroy (server);
}

static void
test_write_command_disconnect (void)
{
   _test_write_disconnect (false);
}

static void
test_legacy_write_disconnect (void)
{
   _test_write_disconnect (true);
}

static void
_test_socket_check (bool legacy)
{
   mock_server_t *server;
   mongoc_uri_t *uri;
   char *ismaster_response;
   mongoc_client_t *client;
   mongoc_collection_t *collection;
   bson_error_t error;
   future_t *future;
   request_t *request;
   mongoc_topology_scanner_node_t *scanner_node;

   server = mock_server_new ();
   mock_server_run (server);
   uri = mongoc_uri_copy (mock_server_get_uri (server));
   mongoc_uri_set_option_as_int32 (uri, "socketCheckIntervalMS", 1);
   client = mongoc_client_new_from_uri (uri);

   /*
    * establish connection with an "ismaster" and "ping"
    */
   future = future_client_command_simple (client, "db", tmp_bson ("{'ping': 1}"),
                                          NULL, NULL, &error);
   request = mock_server_receives_ismaster (server);
   ismaster_response = bson_strdup_printf ("{'ok': 1.0,"
                                           " 'ismaster': true,"
                                           " 'minWireVersion': 0,"
                                           " 'maxWireVersion': %d}",
                                           legacy ? 0 : 3);

   mock_server_replies_simple (request, ismaster_response);
   request_destroy (request);

   request = mock_server_receives_command (server, "db", MONGOC_QUERY_SLAVE_OK,
                                           "{'ping': 1}");
   mock_server_replies_simple (request, "{'ok': 1}");
   ASSERT_OR_PRINT (future_get_bool (future), error);

   /*
    * wait for socketCheckIntervalMS to elapse
    */
   _mongoc_usleep (2000);

   /*
    * close the socket
    */
   mock_server_hangs_up (request);

   /*
    * next operation detects the hangup
    */
   collection = mongoc_client_get_collection (client, "db", "collection");
   future_destroy (future);
   future = future_collection_insert (collection, MONGOC_INSERT_NONE,
                                      tmp_bson ("{'_id': 1}"), NULL, &error);

   ASSERT (!future_get_bool (future));
   ASSERT_CMPINT (error.domain, ==, MONGOC_ERROR_STREAM);
   ASSERT_CMPINT (error.code, == , MONGOC_ERROR_STREAM_SOCKET);

   scanner_node = mongoc_topology_scanner_get_node (client->topology->scanner,
                                                    1 /* server_id */);
   ASSERT (scanner_node && !scanner_node->stream);

   mongoc_collection_destroy (collection);
   request_destroy (request);
   future_destroy (future);
   bson_free (ismaster_response);
   mongoc_client_destroy (client);
   mongoc_uri_destroy (uri);
   mock_server_destroy (server);
}

static void
test_write_command_socket_check (void)
{
   _test_socket_check (false);
}

static void
test_legacy_write_socket_check (void)
{
   _test_socket_check (true);
}

void
test_cluster_install (TestSuite *suite)
{
   TestSuite_Add (suite, "/Cluster/test_get_max_bson_obj_size", test_get_max_bson_obj_size);
   TestSuite_Add (suite, "/Cluster/test_get_max_msg_size", test_get_max_msg_size);
   TestSuite_Add (suite, "/Cluster/disconnect/single", test_cluster_node_disconnect_single);
   TestSuite_Add (suite, "/Cluster/disconnect/pooled", test_cluster_node_disconnect_pooled);
   TestSuite_Add (suite, "/Cluster/command/timeout/single", test_cluster_command_timeout_single);
   TestSuite_Add (suite, "/Cluster/command/timeout/pooled", test_cluster_command_timeout_pooled);
   TestSuite_Add (suite, "/Cluster/write_command/disconnect", test_write_command_disconnect);
   TestSuite_Add (suite, "/Cluster/legacy_write/disconnect", test_legacy_write_disconnect);
   TestSuite_Add (suite, "/Cluster/write_command/socket_check", test_write_command_socket_check);
   TestSuite_Add (suite, "/Cluster/legacy_write/socket_check", test_legacy_write_socket_check);
}


text:
<?php

namespace Fridde\Error;

use Fridde\Controller\ErrorController;
use Fridde\Slacker;
use Monolog\Logger;
use Tracy\BlueScreen;

class ExceptionHandler
{

    private $Exception;
    private $Logger;

    /**
     * ExceptionHandler constructor.
     */
    public function __construct(\Exception $exception, Logger $logger)
    {
        $this->Exception = $exception;
        $this->Logger = $logger;
    }

    public function handle()
    {
        $code  = $this->Exception->getCode();
        $severity = Error::getSeverity($code);
        $msg = $this->createMessage();

        if($severity === Error::SEVERITY_FATAL){
            header($_SERVER['SERVER_PROTOCOL'].' 500 Internal Server Error', true, 500);
            echo $msg;
            $slacker = new Slacker(SETTINGS['slacker']);
            $slacker->sendToAdmin('Kritiskt fel på NDB: ' . $msg);
        }
        if($severity === Error::SEVERITY_BAD_DATA){
            $slacker = new Slacker(SETTINGS['slacker']);
            $slacker->sendToAdmin('För kännedom: ' . $msg);
        }
        if($severity === Error::SEVERITY_USER_INTERACTION){
            $params = ['action' => 'displayErrorMessage'];
            $params['message'] = $msg;
            $error_controller = new ErrorController($params);

            $error_controller->handleRequest();

        }

        $this->Logger->addInfo($msg, ['source' => '']);

        if(defined('DEBUG') && !empty(DEBUG)){
            (new BlueScreen())->render($this->Exception);
        }
    }

    protected function createMessage(): string
    {
        $msg = '';

        $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown address';
        $msg .= 'Request from ' . $ip . PHP_EOL;

        $url = $_SERVER['REQUEST_URI'] ?? ($_SERVER['SCRIPT_NAME'] ?? null);
        if(!empty($url)){
            $msg .= 'Request for ' . $url . PHP_EOL;
        }

        $msg .= $this->Exception->getMessage();

        if($this->Exception instanceof NException){
            $code = $this->Exception->getCode();
            $template = Error::getTemplate($code);
            $args = array_values($this->Exception->getInfo());
            $msg .= sprintf($template, ...$args);
        }
        $msg .= ' The error occurred at ';
        $msg .= $this->Exception->getFile().':'.$this->Exception->getLine();
        $msg .= '; Stacktrace: ' . $this->Exception->getTraceAsString();

        return $msg;
    }

}

/*
 *     header($_SERVER['SERVER_PROTOCOL'].' 500 Internal Server Error', true, 500);

header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found', true, 404);
echo 'No match found. Requested url: '.PHP_EOL;
echo $request_url;
exit();
 */


text:
layout: page
title: Orb Gold Holdings Trade Fair
date: 2016-05-24
author: Larry Dean
tags: weekly links, java
status: published
summary: Sed a justo in mi volutpat laoreet.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 06/08/2016
  endDate: 06/13/2016
  ctyhocn: POUKGHX
  groupCode: OGHTF
published: true
---
Maecenas ut orci non nisl condimentum porta. Quisque aliquam ipsum non pulvinar tincidunt. Donec est tellus, condimentum id quam sed, ultricies ornare sapien. Duis maximus consectetur nulla id condimentum. Mauris eget placerat orci. In eget magna tellus. Donec eget justo vitae orci luctus maximus sed vel diam. Nulla eget erat facilisis, gravida leo commodo, pretium ex. Curabitur pretium, erat ac vulputate tincidunt, dolor nunc tristique odio, non pharetra orci nisl nec mi. Sed sollicitudin consectetur mollis. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

* Vestibulum at lacus fringilla, volutpat odio non, blandit risus
* Integer vel metus rhoncus, sodales metus sed, iaculis urna
* Aenean convallis nunc vitae tempor malesuada.

Mauris egestas tellus sed nulla posuere semper. Vivamus sagittis lacus laoreet augue rhoncus gravida. Suspendisse rutrum ligula lectus, et tincidunt nisl condimentum ac. Cras egestas risus ultricies ultrices sollicitudin. Sed non aliquam eros. Integer purus dolor, lacinia a purus nec, viverra rutrum ex. Praesent interdum, orci vel laoreet ultricies, eros tortor vehicula augue, at tincidunt risus lacus et velit.
Integer a mi scelerisque, venenatis tortor et, mollis neque. Integer at ipsum leo. Morbi arcu leo, ultricies in auctor a, venenatis eget mi. Interdum et malesuada fames ac ante ipsum primis in faucibus. Maecenas enim erat, euismod pretium pellentesque id, tempus sed tortor. Nulla aliquam placerat lacus vitae lobortis. Donec ullamcorper eu erat in finibus. Integer sollicitudin ligula dui. Sed iaculis ligula id purus lobortis placerat. Phasellus sagittis dapibus laoreet. Aenean laoreet, tortor ut ultrices pulvinar, quam ante porta tellus, at ornare lorem turpis in arcu. Phasellus id tellus arcu. Donec aliquet luctus velit hendrerit malesuada. Sed eu felis ac lorem porta tincidunt.


text:
package com.ubirch.user.server.route

import akka.actor.ActorSystem
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Route
import com.typesafe.scalalogging.StrictLogging
import com.ubirch.user.config.Config
import com.ubirch.user.core.manager.{ContextManager, GroupManager, UserManager}
import com.ubirch.user.model.db.{Context, Group, User}
import com.ubirch.user.util.defaults.Defaults
import com.ubirch.user.util.server.RouteConstants
import com.ubirch.util.http.response.ResponseUtil
import com.ubirch.util.json.MyJsonProtocol
import com.ubirch.util.mongo.connection.MongoUtil
import com.ubirch.util.rest.akka.directives.CORSDirective

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.language.postfixOps
import scala.util.{Failure, Success}

/**
  * author: cvandrei
  * since: 2017-05-24
  */
class InitDataRoute(implicit mongo: MongoUtil, val system: ActorSystem) extends MyJsonProtocol
  with CORSDirective
  with ResponseUtil
  with WithRoutesHelpers
  with StrictLogging {

  val route: Route = {

    path(RouteConstants.initData / Segment) { environmentName =>
      respondWithCORS {

        get {
          OnComplete(createContextsAndAdminUsers(environmentName)).fold() {

            case Success(result) =>

              if (result) {
                complete(StatusCodes.OK)
              } else {
                complete(serverErrorResponse(errorType = "InitDataFailed", errorMessage = "failed to init data"))
              }

            case Failure(t) =>
              logger.error("failed to init data", t)
              complete(StatusCodes.InternalServerError)

          }
        }

      }
    }

  }

  private def createContextsAndAdminUsers(envName: String): Future[Boolean] = {

    for {
      Some(contextSeq) <- createContexts(envName)
      groups <- createAdminUsers(contextSeq)
    } yield {
      groups.isDefined
    }

  }

  private def createContexts(envName: String): Future[Option[Seq[Context]]] = {

    val futureResults: List[Future[Option[Context]]] = Config.contextPrefixList map { contextPrefix =>

      val contextName = s"$contextPrefix-$envName"
      ContextManager.findByName(contextName) flatMap {

        case None =>

          ContextManager.create(Context(displayName = contextName)) map {

            case None =>
              logger.error(s"initData: failed to created context: $contextName")
              None

            case Some(created: Context) =>
              logger.info(s"initData: created context: $contextName")
              Some(created)

          }

        case Some(existing: Context) =>
          logger.info(s"initData: context already exists: $contextName")
          Future(Some(existing))

      }

    }

    Future.sequence(futureResults) map { results =>
      if (results.contains(None)) {
        None
      } else {
        Some(results.filter(_.isDefined).map(_.get))
      }
    }

  }

  private def createAdminUsers(contextSeq: Seq[Context]): Future[Option[Seq[Group]]] = {

    createUser() flatMap {

      case None =>
        logger.error("failed to create admin user")
        Future(None)

      case Some(user: User) =>

        val futureGroups = contextSeq map { ctx =>

          for {

            groupOpt <- createGroup(user, ctx)

          } yield {
            if (groupOpt.isEmpty) {
              logger.error(s"failed to create admin group: context=${ctx.displayName}")
            }
            groupOpt
          }

        }

        Future.sequence(futureGroups) map { results =>

          if (results.contains(None)) {
            None
          } else {
            Some(results.filter(_.isDefined).map(_.get))
          }

        }

    }

  }

  private def createUser(): Future[Option[User]] = {

    val providerId = Config.adminUserProviderId
    val externalUserId = Config.adminUserExternalId

    UserManager.findByProviderIdAndExternalId(providerId = providerId, externalUserId = externalUserId) flatMap {

      case None =>

        val user = User(
          displayName = Defaults.ADMIN_USER_NAME,
          providerId = providerId,
          externalId = externalUserId,
          locale = "en"
        )

        UserManager.create(user)

      case Some(user: User) =>
        logger.info("initData: admin user already exists")
        Future(Some(user))

    }

  }

  private def createGroup(user: User, context: Context): Future[Option[Group]] = {

    GroupManager.findByContextAndOwner(contextId = context.id, ownerId = user.id) flatMap {

      case None =>

        val group = Group(
          displayName = Defaults.ADMIN_GROUP_NAME,
          ownerIds = Set(user.id),
          contextId = context.id,
          allowedUsers = Set.empty,
          adminGroup = Some(true)
        )

        GroupManager.create(group)

      case Some(existing: Group) =>
        logger.info(s"admin group already exists: context.displayName=${context.displayName}")
        Future(Some(existing))

    }

  }

}


text:
package com.gmind7.bakery.websocket;

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Sets up the timer for the multi-player snake game WebSocket example.
 */
public class SnakeTimer {

    private static final Log log = LogFactory.getLog(SnakeTimer.class);

    private static Timer gameTimer = null;

    private static final long TICK_DELAY = 100;

    private static final ConcurrentHashMap<Integer, Snake> snakes =
            new ConcurrentHashMap<Integer, Snake>();

    public static synchronized void addSnake(Snake snake) {
        if (snakes.size() == 0) {
            startTimer();
        }
        snakes.put(Integer.valueOf(snake.getId()), snake);
    }

    public static Collection<Snake> getSnakes() {
        return Collections.unmodifiableCollection(snakes.values());
    }

    public static synchronized void removeSnake(Snake snake) {
        snakes.remove(Integer.valueOf(snake.getId()));
        if (snakes.size() == 0) {
            stopTimer();
        }
    }

    public static void tick() throws Exception {
        StringBuilder sb = new StringBuilder();
        for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator();
                iterator.hasNext();) {
            Snake snake = iterator.next();
            snake.update(SnakeTimer.getSnakes());
            sb.append(snake.getLocationsJson());
            if (iterator.hasNext()) {
                sb.append(',');
            }
        }
        broadcast(String.format("{'type': 'update', 'data' : [%s]}",
                sb.toString()));
    }

    public static void broadcast(String message) throws Exception {
        for (Snake snake : SnakeTimer.getSnakes()) {
            snake.sendMessage(message);
        }
    }

    public static void startTimer() {
        gameTimer = new Timer(SnakeTimer.class.getSimpleName() + " Timer");
        gameTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                try {
                    tick();
                } catch (Throwable e) {
                    log.error("Caught to prevent timer from shutting down", e);
                }
            }
        }, TICK_DELAY, TICK_DELAY);
    }

    public static void stopTimer() {
        if (gameTimer != null) {
            gameTimer.cancel();
        }
    }
}


text:
package com.huijimuhe.monolog.ui.main;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.huijimuhe.monolog.R;
import com.huijimuhe.monolog.ui.base.AbstractFragment;
import com.huijimuhe.monolog.ui.statue.PublishActivity;

public class NoneFragment extends AbstractFragment implements View.OnClickListener {
    private static final String TAG = "youmi";
    public static NoneFragment newInstance() {
        NoneFragment fragment = new NoneFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    public NoneFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_none, container, false);
        v.findViewById(R.id.btn_publish).setOnClickListener(this);
        v.findViewById(R.id.btn_share).setOnClickListener(this);

        return v;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_share:
                ((MainActivity) getActivity()).openShare();
                break;
            case R.id.btn_publish:
                startActivityForResult(PublishActivity.newIntent(), PublishActivity.REQUEST_PUBLISH);
                break;
        }
    }
}


text:
. /home/turbinia/start-turbinia-common.sh

while [ 1 ] ; do
	$turbiniactl -L $output_dir/logs/turbinia-server.log.txt -o $tmp_dir server 2>> $output_dir/logs/turbinia-server.stdout.log.txt
        sleep 2
done


text:
title: WAI-ARIA Support
page_title: WAI-ARIA Support - RadButton
description: Check our Web Forms article about WAI-ARIA Support.
slug: button/accessibility-and-internationalization/wai-aria-support
tags: wai-aria,support
published: True
position: 3
---

# WAI-ARIA Support

This article demonstrates how to enable and use the WAI-ARIA support of the **RadButton** control.

The [WAI-ARIA Suite](https://www.w3.org/WAI/intro/aria) defines an approach to make web content and web applications more accessible to people with disabilities. **RadButton** offers WAI-ARIA support.

In order to enable the WAI-ARIA support, set the **RadButton** control's `EnableAriaSupport` property to `true` as shown in **Example 1**.

>caption **Example 1**: Enabling WAI-ARIA support for RadButton

````ASP.NET
<telerik:RadButton RenderMode="Lightweight" ID="RadButton1" runat="server" EnableAriaSupport="true" Text="Button with WAI-ARIA attributes">
</telerik:RadButton>
````

>note The implementation of the WAI ARIA support is achieved entirely client-side (using JavaScript) by appending different attributes and appropriate WAI-ARIA roles to the DOM elements.	This is done because an HTML document containing ARIA attributes will not pass validation if they are added on the server.

## See Also

 * [W3C: WAI-ARIA Overview](https://www.w3.org/WAI/intro/aria)


text:
package ontopoly.pages;

import ontopoly.components.FooterPanel;
import ontopoly.components.HeaderPanel;

import org.apache.wicket.Page;
import org.apache.wicket.PageParameters;

public class SignOutPage extends AbstractOntopolyPage {

  public static final String REDIRECTPAGE_PARAM = "redirectpage";

  @SuppressWarnings("unchecked")
  public SignOutPage(final PageParameters parameters) {
    add(new HeaderPanel("header"));
    add(new FooterPanel("footer"));

    String page = parameters.getString(REDIRECTPAGE_PARAM);
    Class<? extends Page> pageClass;
    if (page != null) {
      try {
        pageClass = (Class<? extends Page>) Class.forName(page);
      } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
      }
    } else {
      pageClass = getApplication().getHomePage();
    }
    getSession().invalidate();
    setResponsePage(pageClass);
    setRedirect(true);
  }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('yats', '0008_auto_20180823_1453'),
    ]

    operations = [
        migrations.AddField(
            model_name='ticket_priority',
            name='caldav',
            field=models.CharField(choices=[(b'HIGH', 'high'), (b'MEDIUM', 'medium'), (b'LOW', 'low'), (b'', 'none')], default=b'', max_length=255),
        ),
    ]


text:
"""
Created on Thu Jul 21 10:23:46 2016
"""

import argparse
import cPickle
import seaborn as sns

import matplotlib.pylab as plt
import pandas as pd
import numpy as np

from matplotlib.lines import Line2D
import re

sns.set_style("darkgrid")

lscol_ptn = re.compile("LockingState([0-9]+)")
def determine_num_joints(df, _):
    return len([ lscol_ptn.match(c).group(1) for c in df.columns if lscol_ptn.match(c) is not None])

def plot_locking_states(df, meta, num_joints=None):

    marker_style = dict(linestyle=':', marker='o', s=100,)

    def format_axes(ax):
        ax.margins(0.2)
        ax.set_axis_off()

    if num_joints is None:
        num_joints = determine_num_joints(df)

    points = np.ones(num_joints)

    fig, ax = plt.subplots()
    for j in range(num_joints):
        ax.text(-1.5, j, "%d" % j)
    ax.text(0, -1.5, "time")

    for t in df.index:
        lock_states = df.loc[t][ [ "LockingState%d" % k for k in range(num_joints) ] ].tolist()
        c = ["orange" if l else "k" for l in lock_states]

        ax.scatter((t+0.1) * points, range(num_joints), color=c, **marker_style)
        format_axes(ax)

    ax.set_title('Locking state evolution')
    ax.set_xlabel("t")

    plt.plot()

def plot_entropy(df, meta, num_joints=None):
    if num_joints is None:
        num_joints = determine_num_joints(df)

    plt.figure()
    for j in range(num_joints):
        var_name="Entropy%d"%j
        plt.plot(df[var_name], label=var_name)
    plt.legend()

def plot_dependency_posterior(df, meta, t, num_joints=None):
    if num_joints is None:
        num_joints = determine_num_joints(df)

    plt.figure()
    posterior=np.array([df["Posterior%d"%j].iloc[t] for j in range(num_joints)])
    plt.matshow(posterior, interpolation='nearest')
    plt.show()

def print_actions(df, num_joints=None):
    pd.options.display.float_format = '{:,.2f}'.format
    pd.set_option('expand_frame_repr', False)
    if num_joints is None:
        num_joints = determine_num_joints(df, None)

    print(df[[u'CheckedJoint'] +
             ['DesiredPos{}'.format(j) for j in range(num_joints)] +
             ['LockingState{}'.format(j) for j in range(num_joints)]
            ])

#Index([u'DesiredPos0', u'DesiredPos1', u'DesiredPos2', u'DesiredPos3',
#       u'DesiredPos4', u'CheckedJoint', u'RealPos0', u'RealPos1', u'RealPos2',
#       u'RealPos3', u'RealPos4', u'LockingState0', u'LockingState1',
#       u'LockingState2', u'LockingState3', u'LockingState4', u'Posterior0',
#       u'Entropy0', u'Posterior1', u'Entropy1', u'Posterior2', u'Entropy2',
#       u'Posterior3', u'Entropy3', u'Posterior4', u'Entropy4'],
#      dtype='object')

def open_pickle_file(pkl_file):
    with open(pkl_file) as f:
        df, meta = cPickle.load(f)

    return df, meta

if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument("-f", "--file", required=True,
                        help="pickle file")
    args = parser.parse_args()

    df, meta = open_pickle_file(args.file)
    print_actions(df)

    plot_locking_states(df, meta, num_joints=determine_num_joints(df, meta))
    plot_entropy(df,meta, num_joints=determine_num_joints(df, meta))
    plot_dependency_posterior(df,meta,-1, num_joints=determine_num_joints(df, meta))

    plt.show()