text:
// @file queryutil-inl.h - Inline definitions for frequently called queryutil.h functions

namespace mongo {

    inline bool FieldInterval::equality() const {
        if ( _cachedEquality == -1 ) {
            _cachedEquality = ( _lower._inclusive && _upper._inclusive && _lower._bound.woCompare( _upper._bound, false ) == 0 );
        }
        return _cachedEquality != 0;
    }

    inline bool FieldRange::equality() const {
        return
            !empty() &&
            min().woCompare( max(), false ) == 0 &&
            maxInclusive() &&
            minInclusive();
    }

    inline const FieldRange &FieldRangeSet::range( const char *fieldName ) const {
        map<string,FieldRange>::const_iterator f = _ranges.find( fieldName );
        if ( f == _ranges.end() )
            return universalRange();
        return f->second;
    }

    inline FieldRange &FieldRangeSet::range( const char *fieldName ) {
        map<string,FieldRange>::iterator f = _ranges.find( fieldName );
        if ( f == _ranges.end() ) {
            _ranges.insert( make_pair( string( fieldName ), universalRange() ) );
            return _ranges.find( fieldName )->second;
        }
        return f->second;
    }

    inline bool FieldRangeSet::matchPossible() const {
        for( map<string,FieldRange>::const_iterator i = _ranges.begin(); i != _ranges.end(); ++i ) {
            if ( i->second.empty() ) {
                return false;
            }
        }
        return true;
    }

    inline bool FieldRangeSet::matchPossibleForIndex( const BSONObj &keyPattern ) const {
        if ( !_singleKey ) {
            return matchPossible();
        }
        BSONObjIterator i( keyPattern );
        while( i.more() ) {
            BSONElement e = i.next();
            if ( e.fieldName() == string( "$natural" ) ) {
                return true;
            }
            if ( range( e.fieldName() ).empty() ) {
                return false;
            }
        }
        return true;
    }

    inline unsigned FieldRangeVector::size() {
        unsigned ret = 1;
        for( vector<FieldRange>::const_iterator i = _ranges.begin(); i != _ranges.end(); ++i ) {
            unsigned long long product =
                    (unsigned long long)ret * (unsigned long long)i->intervals().size();
            // Check for overflow SERVER-5415.
            verify( ( product >> 32 ) == 0 );
            ret = product;
        }
        return ret;
    }

    inline void FieldRangeVectorIterator::CompoundRangeCounter::set( int i, int newVal ) {
        resetIntervalCount();
        _i[ i ] = newVal;
    }

    inline void FieldRangeVectorIterator::CompoundRangeCounter::inc( int i ) {
        resetIntervalCount();
        ++_i[ i ];
    }

    inline void FieldRangeVectorIterator::CompoundRangeCounter::setZeroes( int i ) {
        resetIntervalCount();
        for( int j = i; j < (int)_i.size(); ++j ) _i[ j ] = 0;
    }

    inline void FieldRangeVectorIterator::CompoundRangeCounter::setUnknowns( int i ) {
        resetIntervalCount();
        for( int j = i; j < (int)_i.size(); ++j ) _i[ j ] = -1;
    }

    inline FieldRangeSetPair *OrRangeGenerator::topFrsp() const {
        FieldRangeSetPair *ret = new FieldRangeSetPair( _baseSet );
        if (_orSets.size()) {
            *ret &= _orSets.front();
        }
        return ret;
    }

    inline FieldRangeSetPair *OrRangeGenerator::topFrspOriginal() const {
        FieldRangeSetPair *ret = new FieldRangeSetPair( _baseSet );
        if (_originalOrSets.size()) {
            *ret &= _originalOrSets.front();
        }
        return ret;
    }

    inline bool FieldRangeSetPair::matchPossibleForIndex( NamespaceDetails *d, int idxNo, const BSONObj &keyPattern ) const {
        assertValidIndexOrNoIndex( d, idxNo );
        if ( !matchPossible() ) {
            return false;
        }
        if ( idxNo < 0 ) {
            // multi key matchPossible() is true, so return true.
            return true;
        }
        return frsForIndex( d, idxNo ).matchPossibleForIndex( keyPattern );
    }

    inline void FieldRangeSetPair::assertValidIndexOrNoIndex( const NamespaceDetails *d, int idxNo ) const {
        massert( 14049, "FieldRangeSetPair invalid index specified", idxNo >= -1 );
        if ( idxNo >= 0 ) {
            assertValidIndex( d, idxNo );
        }
    }

} // namespace mongo


text:
[![Build Status](https://travis-ci.org/bfontaine/meuh-cli.png?branch=master)](https://travis-ci.org/bfontaine/meuh-cli)
[![Gem Version](https://badge.fury.io/rb/meuh.png)](http://badge.fury.io/rb/meuh)
[![Coverage Status](https://coveralls.io/repos/bfontaine/meuh-cli/badge.png)](https://coveralls.io/r/bfontaine/meuh-cli)
[![Dependency Status](https://gemnasium.com/bfontaine/meuh-cli.png)](https://gemnasium.com/bfontaine/meuh-cli)

**meuh** is a command-line tool to check the current radio track at
[Anticafé][anticafe].

[anticafe]: http://anticafe.fr/en

## Install

```
gem install meuh
```

Windows users: You will need the Win32 Console ANSI gem for the colored output.
Install it with `gem install win32console`.

## Usage

From the command-line:

```
$ meuh
```

That's it! Add `--no-format` if you don't want the fancy formatting.

## Example

```
$ meuh
Mauvaise Mine (Lafayette - Mauvaise Mine (Jupiter remix))

Previously:
* [15:44:21] Tsugi 30 LCD Soundsystem Small Wave (Dolle Jolle - Balearic Incarnation (Todd Terje's Extra Doll Mx))
* [15:37:31] Booker T & the MGs (Green Onions (Luke Danfields Bluehouse Edit))
* [15:33:42] Patchworks Remix Book (Mr Day - Small Fry ( Patchworks Disco mix) - Mr Day)
* [15:28:11] Midnight Riot Volume 4 (Yambee - Blacker (Joey Negro remix))

Next:
* Psychic (Darkside - The Only Shrine I've Seen)
```

## Tests

```
$ git clone https://github.com/bfontaine/meuh-cli.git
$ cd meuh-cli
$ bundle install
$ rake test
```

It'll generate a `coverage/index.html`, which you can open in a Web browser.

redpajama_set_name: RedPajamaGithub


text:
package org.societies.android.api.cis.management;

import org.societies.android.api.css.manager.IServiceManager;
import org.societies.api.schema.cis.community.Community;
import org.societies.api.schema.cis.community.MembershipCrit;
import org.societies.api.schema.cis.directory.CisAdvertisementRecord;

/**
 * @author Babak.Farshchian@sintef.no
 * Implemented by the CommunityManager APKLib service
 */
public interface ICisManager extends IServiceManager {
	//CIS MANAGER INTENTS
	public static final String INTENT_RETURN_VALUE = "org.societies.android.platform.community.ReturnValue";
	public static final String INTENT_RETURN_BOOLEAN = "org.societies.android.platform.community.ReturnBoolean"; // extra from True/False methods
	public static final String CREATE_CIS     		= "org.societies.android.platform.community.CREATE_CIS";
	public static final String DELETE_CIS    		= "org.societies.android.platform.community.DELETE_CIS";
	public static final String GET_CIS_LIST     	= "org.societies.android.platform.community.GET_CIS_LIST";
	public static final String SUBSCRIBE_TO_CIS 	= "org.societies.android.platform.community.SUBSCRIBE_TO_CIS";
	public static final String UNSUBSCRIBE_FROM_CIS = "org.societies.android.platform.community.UNSUBSCRIBE_FROM_CIS";
	public static final String REMOVE_MEMBER 		= "org.societies.android.platform.community.REMOVE_MEMBER";
	public static final String JOIN_CIS      		= "org.societies.android.platform.community.JOIN_CIS";
	public static final String LEAVE_CIS     		= "org.societies.android.platform.community.LEAVE_CIS";

	public String methodsArray[] = {"createCis(String client, String cisName, String cisType, String description, org.societies.api.schema.cis.community.MembershipCrit criteria, String privacyPolicy)",
							 		"deleteCis(String client, String cisId)",
							 		"getCisList(String client, String query)",
							 		"removeMember(String client, String cisId, String memberJid)",
							 		"Join(String client, org.societies.api.schema.cis.directory.CisAdvertisementRecord targetCis)",
							 		"Leave(String client, String cisId)",
									"startService()",
									"stopService()"
									};

	/**
	 * Create a new CIS. The Hosting CSS who creates the CIS will be the owner. Ownership can be changed
	 * later.
	 *
	 * @param cisName is user given name for the CIS, e.g. "Footbal".
	 * @param cisType E.g. "disaster"
	 * @param description More detailed info
	 * @param cisCriteria hashtable of {@link membershipCriteria} objects
	 * @param privacyPolicy privacy policy info
	 */
	public Community createCis(String client, String cisName, String cisType, String description, MembershipCrit criteria, String privacyPolicy);

	/**
	 * Delete a specific CIS represented by cisId. The cisId is available in the
	 * method of {@link ICisEditor} representing the CIS to be deleted. This method
	 * will delete only one CIS with the ID passed as cisId.
	 *
	 * @param cisId The ID of the CIS to be deleted.
	 * @return true if deleted, false otherwise.
	 */
	public Boolean deleteCis(String client, String cisId);

	/**
	 * Return an array of all the CISs that match the query.

	 * @param query Defines what to search for.
	 * @return Array of CIS Records that match the query.
	 */
	public Community[] getCisList(String client, String query);

	/**
	 * Remove a member from this CIS
	 * @param cisId
	 * @param memberJid
	 */
	public void removeMember(String client, String cisId, String memberJid);

	/**
	 * Join a community
	 * @param client
	 * @param targetCis
	 * @param qualifications
	 * @return
	 */
	public String Join(String client, CisAdvertisementRecord targetCis);

	/**
	 * Leave a Community
	 * @param client
	 * @param cisId
	 * @return
	 */
	public String Leave(String client, String cisId);
}


text:
require 'spec_helper'

module WebMock
  describe VersionChecker do
    it 'prints a warning if the major version is too low' do
      checker = VersionChecker.new('foo', '0.7.3', '1.0.0', '1.1')
      expect(Kernel).to receive(:warn).with("\e[31mYou are using foo 0.7.3. WebMock supports version >= 1.0.0, < 1.2.\e[0m")
      checker.check_version!
    end

    it 'prints a warning if the minor version is too low' do
      checker = VersionChecker.new('foo', '1.0.99', '1.1.3', '1.2')
      expect(Kernel).to receive(:warn).with("\e[31mYou are using foo 1.0.99. WebMock supports version >= 1.1.3, < 1.3.\e[0m")
      checker.check_version!
    end

    it 'prints a warning if the patch version is too low' do
      checker = VersionChecker.new('foo', '1.0.8', '1.0.10', '1.2')
      expect(Kernel).to receive(:warn).with("\e[31mYou are using foo 1.0.8. WebMock supports version >= 1.0.10, < 1.3.\e[0m")
      checker.check_version!
    end

    it 'prints a warning if the patch version is too low and max version is not specified' do
      checker = VersionChecker.new('foo', '1.0.8', '1.0.10')
      expect(Kernel).to receive(:warn).with("\e[31mYou are using foo 1.0.8. WebMock supports version >= 1.0.10.\e[0m")
      checker.check_version!
    end

    it 'prints a warning if the major version is too high' do
      checker = VersionChecker.new('foo', '2.0.0', '1.0.0', '1.1')
      expect(Kernel).to receive(:warn).with(/may not work with this version/)
      checker.check_version!
    end

    it 'prints a warning if the minor version is too high' do
      checker = VersionChecker.new('foo', '1.2.0', '1.0.0', '1.1')
      expect(Kernel).to receive(:warn).with(/may not work with this version/)
      checker.check_version!
    end

    it 'does not raise an error or print a warning when the major version is between the min and max' do
      checker = VersionChecker.new('foo', '2.0.0', '1.0.0', '3.0')
      expect(Kernel).not_to receive(:warn)
      checker.check_version!
    end

    it 'does not raise an error or print a warning when the min_patch is 0.6.5, the max_minor is 0.7 and the version is 0.7.3' do
      checker = VersionChecker.new('foo', '0.7.3', '0.6.5', '0.7')
      expect(Kernel).not_to receive(:warn)
      checker.check_version!
    end

    it 'does not raise an error or print a warning when the min_patch is 0.6.5, the max_minor is not specified and the version is 0.8.3' do
      checker = VersionChecker.new('foo', '0.8.3', '0.6.5')
      expect(Kernel).not_to receive(:warn)
      checker.check_version!
    end

    it "prints warning if version is unsupported" do
      checker = VersionChecker.new('foo', '2.0.0', '1.0.0', '3.0', ['2.0.0'])
      expect(Kernel).to receive(:warn).with(%r{You are using foo 2.0.0. WebMock does not support this version. WebMock supports versions >= 1.0.0, < 3.1, except versions 2.0.0.})
      checker.check_version!
    end
  end
end


text:
@class WMFSearchResults;

NS_ASSUME_NONNULL_BEGIN

@interface WMFSearchDataSource : SSArrayDataSource <WMFTitleListDataSource>

@property (nonatomic, strong, readonly) NSURL *searchSiteURL;
@property (nonatomic, strong, readonly) WMFSearchResults *searchResults;

- (nonnull instancetype)initWithSearchSiteURL:(NSURL *)url searchResults:(WMFSearchResults *)searchResults;

@end

NS_ASSUME_NONNULL_END


text:
from mod_pywebsocket import common, msgutil, util
from mod_pywebsocket.handshake import hybi

def web_socket_do_extra_handshake(request):
    request.connection.write('HTTP/1.1 101 Switching Protocols:\x0D\x0AConnection: Upgrade\x0D\x0AUpgrade: WebSocket\x0D\x0ASec-WebSocket-Origin: '+request.ws_origin+'\x0D\x0ASec-WebSocket-Accept: '+hybi.compute_accept(request.headers_in.get(common.SEC_WEBSOCKET_KEY_HEADER))[0]+'\x0D\x0A\x0D\x0A')
    return

def web_socket_transfer_data(request):
     while True:
	return


text:
package org.apache.activemq.bugs;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.util.Enumeration;

import javax.jms.Connection;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueBrowser;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.region.policy.PolicyEntry;
import org.apache.activemq.broker.region.policy.PolicyMap;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AMQ4487Test {

    private static final Logger LOG = LoggerFactory.getLogger(AMQ4487Test.class);

    private final String destinationName = "TEST.QUEUE";
    private BrokerService broker;
    private ActiveMQConnectionFactory factory;

    @Before
    public void startBroker() throws Exception {
        broker = new BrokerService();
        broker.deleteAllMessages();
        broker.setUseJmx(false);
        broker.setAdvisorySupport(false);

        PolicyEntry policy = new PolicyEntry();
        policy.setQueue(">");
        policy.setMaxProducersToAudit(75);
        PolicyMap pMap = new PolicyMap();
        pMap.setDefaultEntry(policy);
        broker.setDestinationPolicy(pMap);

        broker.start();
        broker.waitUntilStarted();
        factory = new ActiveMQConnectionFactory("vm://localhost");
    }

    @After
    public void stopBroker() throws Exception {
        broker.stop();
        broker.waitUntilStopped();
    }

    private void sendMessages(int messageToSend) throws Exception {
        String data = "";
        for (int i = 0; i < 1024 * 2; i++) {
            data += "x";
        }

        Connection connection = factory.createConnection();
        connection.start();

        for (int i = 0; i < messageToSend; i++) {
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Queue queue = session.createQueue(destinationName);
            MessageProducer producer = session.createProducer(queue);
            producer.send(session.createTextMessage(data));
            session.close();
        }

        connection.close();
    }

    @Test
    public void testBrowsingWithLessThanMaxAuditDepth() throws Exception {
        doTestBrowsing(75);
    }

    @Test
    public void testBrowsingWithMoreThanMaxAuditDepth() throws Exception {
        doTestBrowsing(300);
    }

    @SuppressWarnings("rawtypes")
    private void doTestBrowsing(int messagesToSend) throws Exception {

        Connection connection = factory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(destinationName);

        sendMessages(messagesToSend);

        QueueBrowser browser = session.createBrowser(queue);
        Enumeration enumeration = browser.getEnumeration();
        int received = 0;
        while (enumeration.hasMoreElements()) {
            Message m = (Message) enumeration.nextElement();
            assertNotNull(m);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Browsed Message: {}", m.getJMSMessageID());
            }

            received++;
            if (received > messagesToSend) {
                break;
            }
        }

        browser.close();

        assertEquals(messagesToSend, received);
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Hedwigia 40(Beibl. ): 25 (1901)

#### Original name
Puccinia horiana Henn., 1901

### Remarks
null


text:
/* global fetch */
/* global Headers */
import {blob as createBlob, readAsArrayBuffer } from 'pouchdb-binary-utils';

function wrappedFetch() {
  var wrappedPromise = {};

  var promise = new Promise(function (resolve, reject) {
    wrappedPromise.resolve = resolve;
    wrappedPromise.reject = reject;
  });

  var args = new Array(arguments.length);

  for (var i = 0; i < args.length; i++) {
    args[i] = arguments[i];
  }

  wrappedPromise.promise = promise;

  Promise.resolve().then(function () {
    return fetch.apply(null, args);
  }).then(function (response) {
    wrappedPromise.resolve(response);
  }).catch(function (error) {
    wrappedPromise.reject(error);
  });

  return wrappedPromise;
}

function fetchRequest(options, callback) {
  var wrappedPromise, timer, response;

  var headers = new Headers();

  var fetchOptions = {
    method: options.method,
    credentials: 'include',
    headers: headers
  };

  if (options.json) {
    headers.set('Accept', 'application/json');
    headers.set('Content-Type', options.headers['Content-Type'] ||
      'application/json');
  }

  if (options.body &&
      options.processData &&
      typeof options.body !== 'string') {
    fetchOptions.body = JSON.stringify(options.body);
  } else if ('body' in options) {
    fetchOptions.body = options.body;
  } else {
    fetchOptions.body = null;
  }

  Object.keys(options.headers).forEach(function (key) {
    if (options.headers.hasOwnProperty(key)) {
      headers.set(key, options.headers[key]);
    }
  });

  wrappedPromise = wrappedFetch(options.url, fetchOptions);

  if (options.timeout > 0) {
    timer = setTimeout(function () {
      wrappedPromise.reject(new Error('Load timeout for resource: ' +
        options.url));
    }, options.timeout);
  }

  wrappedPromise.promise.then(function (fetchResponse) {
    response = {
      statusCode: fetchResponse.status
    };

    if (options.timeout > 0) {
      clearTimeout(timer);
    }

    if (response.statusCode >= 200 && response.statusCode < 300) {
      return options.binary ? fetchResponse.blob() : fetchResponse.text();
    }

    return fetchResponse.json();
  }).then(function (result) {
    if (response.statusCode >= 200 && response.statusCode < 300) {
      callback(null, response, result);
    } else {
      result.status = response.statusCode;
      callback(result);
    }
  }).catch(function (error) {
    if (!error) {
      // this happens when the listener is canceled
      error = new Error('canceled');
    }
    callback(error);
  });

  return {abort: wrappedPromise.reject};
}

function xhRequest(options, callback) {

  var xhr, timer;
  var timedout = false;

  var abortReq = function () {
    xhr.abort();
    cleanUp();
  };

  var timeoutReq = function () {
    timedout = true;
    xhr.abort();
    cleanUp();
  };

  var ret = {abort: abortReq};

  var cleanUp = function () {
    clearTimeout(timer);
    ret.abort = function () {};
    if (xhr) {
      xhr.onprogress = undefined;
      if (xhr.upload) {
        xhr.upload.onprogress = undefined;
      }
      xhr.onreadystatechange = undefined;
      xhr = undefined;
    }
  };

  if (options.xhr) {
    xhr = new options.xhr();
  } else {
    xhr = new XMLHttpRequest();
  }

  try {
    xhr.open(options.method, options.url);
  } catch (exception) {
    return callback(new Error(exception.name || 'Url is invalid'));
  }

  xhr.withCredentials = ('withCredentials' in options) ?
    options.withCredentials : true;

  if (options.method === 'GET') {
    delete options.headers['Content-Type'];
  } else if (options.json) {
    options.headers.Accept = 'application/json';
    options.headers['Content-Type'] = options.headers['Content-Type'] ||
      'application/json';
    if (options.body &&
        options.processData &&
        typeof options.body !== "string") {
      options.body = JSON.stringify(options.body);
    }
  }

  if (options.binary) {
    xhr.responseType = 'arraybuffer';
  }

  if (!('body' in options)) {
    options.body = null;
  }

  for (var key in options.headers) {
    if (options.headers.hasOwnProperty(key)) {
      xhr.setRequestHeader(key, options.headers[key]);
    }
  }

  if (options.timeout > 0) {
    timer = setTimeout(timeoutReq, options.timeout);
    xhr.onprogress = function () {
      clearTimeout(timer);
      if(xhr.readyState !== 4) {
        timer = setTimeout(timeoutReq, options.timeout);
      }
    };
    if (typeof xhr.upload !== 'undefined') { // does not exist in ie9
      xhr.upload.onprogress = xhr.onprogress;
    }
  }

  xhr.onreadystatechange = function () {
    if (xhr.readyState !== 4) {
      return;
    }

    var response = {
      statusCode: xhr.status
    };

    if (xhr.status >= 200 && xhr.status < 300) {
      var data;
      if (options.binary) {
        data = createBlob([xhr.response || ''], {
          type: xhr.getResponseHeader('Content-Type')
        });
      } else {
        data = xhr.responseText;
      }
      callback(null, response, data);
    } else {
      var err = {};
      if (timedout) {
        err = new Error('ETIMEDOUT');
        err.code = 'ETIMEDOUT';
      } else if (typeof xhr.response === 'string') {
        try {
          err = JSON.parse(xhr.response);
        } catch(e) {}
      }
      err.status = xhr.status;
      callback(err);
    }
    cleanUp();
  };

  if (options.body && (options.body instanceof Blob)) {
    readAsArrayBuffer(options.body, function (arrayBuffer) {
      xhr.send(arrayBuffer);
    });
  } else {
    xhr.send(options.body);
  }

  return ret;
}

function testXhr() {
  try {
    new XMLHttpRequest();
    return true;
  } catch (err) {
    return false;
  }
}

var hasXhr = testXhr();

function ajax(options, callback) {
  if (!process.env.FETCH && (hasXhr || options.xhr)) {
    return xhRequest(options, callback);
  } else {
    return fetchRequest(options, callback);
  }
}

export default ajax;


text:
package com.cedarsoftware.util;

import org.junit.Test;

import java.util.*;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class TestTraverser
{
    class Alpha
    {
        String name;
        Collection contacts;
        Beta beta;
    }

    class Beta
    {
        int age;
        Map friends;
        Charlie charlie;
    }

    class Charlie
    {
        double salary;
        Collection timezones;
        Object[] dates;
        Alpha alpha;
        TimeZone zone = TimeZone.getDefault();
        Delta delta;
    }

    class Delta
    {
        TimeZone timeZone = TimeZone.getDefault();
    }

    @Test
    public void testCyclicTraverse()
    {
        Alpha alpha = new Alpha();
        Beta beta = new Beta();
        Charlie charlie = new Charlie();

        alpha.name = "alpha";
        alpha.beta = beta;
        alpha.contacts = new ArrayList();
        alpha.contacts.add(beta);
        alpha.contacts.add(charlie);
        alpha.contacts.add("Harry");

        beta.age = 45;
        beta.charlie = charlie;
        beta.friends = new LinkedHashMap();
        beta.friends = new LinkedHashMap();
        beta.friends.put("Tom", "Tom Jones");
        beta.friends.put(alpha, "Alpha beta");
        beta.friends.put("beta", beta);

        charlie.salary = 150000.01;
        charlie.alpha = alpha;
        charlie.timezones = new LinkedList();
        charlie.timezones.add(TimeZone.getTimeZone("EST"));
        charlie.timezones.add(TimeZone.getTimeZone("GMT"));
        charlie.dates = new Date[] { new Date() };

        final int[] visited = new int[4];
        visited[0] = 0;
        visited[1] = 0;
        visited[2] = 0;
        visited[3] = 0;

        Traverser.Visitor visitor = new Traverser.Visitor()
        {
            public void process(Object o)
            {
                if (o instanceof Alpha)
                {
                    visited[0]++;
                }
                else if (o instanceof Beta)
                {
                    visited[1]++;
                }
                else if (o instanceof Charlie)
                {
                    visited[2]++;
                }
                else if (o instanceof TimeZone)
                {
                    visited[3]++;
                }
            }
        };
        Traverser.traverse(alpha, visitor);
        assertEquals(1, visited[0]);
        assertEquals(1, visited[1]);
        assertEquals(1, visited[2]);
        assertTrue(visited[3] >= 1);

        visited[0] = 0;
        visited[1] = 0;
        visited[2] = 0;
        visited[3] = 0;
        Traverser.traverse(alpha, new Class[] { TimeZone.class }, visitor);
        assertEquals(1, visited[0]);
        assertEquals(1, visited[1]);
        assertEquals(1, visited[2]);
        assertEquals(0, visited[3]);
    }
}


text:
=begin

Copyright 2012-2013 inBloom, Inc. and its affiliates.

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.

=end

class UserAccountValidationController < ApplicationController
  skip_before_filter :handle_oauth

  # GET /user_account_registrations/validate/1
  # GET /user_account_registrations/validate/1.json
  def show
    @validation_result = UserAccountValidation.validate_account params[:id]
    if @validation_result[:success] and APP_CONFIG["is_sandbox"]
        #email slc operator about newly created user
        begin
          user = APP_LDAP_CLIENT.read_user_emailtoken(params[:id])
          ApplicationMailer.notify_operator_on_acct_creation(user).deliver unless user.nil?
        rescue Exception => e
          logger.error e.message
        end
    end
    render :show
  end # end def show
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Xerces-C++: XSWildcard Class Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Related Pages

Classes

Files

Alphabetical List

Class List

Class Hierarchy

Class Members

XSWildcard Class Reference

Inheritance diagram for XSWildcard:

<map name="XSWildcard_map">
<area href="classXSObject.html" alt="XSObject" shape="rect" coords="0,56,79,80">
<area href="classXMemory.html" alt="XMemory" shape="rect" coords="0,0,79,24">
</map>

List of all members.

Public Types

enum  	NAMESPACE_CONSTRAINT { NSCONSTRAINT_ANY =  1,
NSCONSTRAINT_NOT =  2,
NSCONSTRAINT_DERIVATION_LIST =  3
 }

enum  	PROCESS_CONTENTS { PC_STRICT =  1,
PC_SKIP =  2,
PC_LAX =  3
 }

Public Member Functions

Constructors

 	XSWildcard (SchemaAttDef *const attWildCard, XSAnnotation *const annot, XSModel *const xsModel, MemoryManager *const manager=XMLPlatformUtils::fgMemoryManager)

 	The default constructor.

 	XSWildcard (const ContentSpecNode *const elmWildCard, XSAnnotation *const annot, XSModel *const xsModel, MemoryManager *const manager=XMLPlatformUtils::fgMemoryManager)

Destructor

 	~XSWildcard ()

XSWildcard methods

NAMESPACE_CONSTRAINT 	getConstraintType () const

 	Namespace constraint: A constraint type: any, not, list.

StringList * 	getNsConstraintList ()

 	Namespace constraint.

PROCESS_CONTENTS 	getProcessContents () const

 	[process contents]: one of skip, lax or strict.

XSAnnotation * 	getAnnotation () const

 	Optional.

Protected Attributes

NAMESPACE_CONSTRAINT 	fConstraintType

PROCESS_CONTENTS 	fProcessContents

StringList * 	fNsConstraintList

XSAnnotation * 	fAnnotation

Member Enumeration Documentation

          enum XSWildcard::NAMESPACE_CONSTRAINT

Enumerator:

NSCONSTRAINT_ANY
Namespace Constraint: any namespace is allowed.

NSCONSTRAINT_NOT
Namespace Constraint: namespaces in the list are not allowed.

NSCONSTRAINT_DERIVATION_LIST
Namespace Constraint: namespaces in the list are allowed.

          enum XSWildcard::PROCESS_CONTENTS

Enumerator:

PC_STRICT
There must be a top-level declaration for the item available, or the item must have an xsi:type, and the item must be valid as appropriate.

PC_SKIP
No constraints at all: the item must simply be well-formed XML.

PC_LAX
If the item, or any items among its [children] is an element information item, has a uniquely determined declaration available, it must be valid with respect to that definition, that is, validate where you can, don't worry when you can't.

Constructor & Destructor Documentation

          XSWildcard::XSWildcard
          (
          SchemaAttDef *const
           attWildCard,

          XSAnnotation *const
           annot,

          XSModel *const
           xsModel,

          MemoryManager *const
           manager = XMLPlatformUtils::fgMemoryManager

          )

The default constructor.

Parameters:

	attWildCard

	annot

	xsModel

	manager 	The configurable memory manager

          XSWildcard::XSWildcard
          (
          const ContentSpecNode *const
           elmWildCard,

          XSAnnotation *const
           annot,

          XSModel *const
           xsModel,

          MemoryManager *const
           manager = XMLPlatformUtils::fgMemoryManager

          )

          XSWildcard::~XSWildcard
          (

           )

Member Function Documentation

          XSWildcard::NAMESPACE_CONSTRAINT XSWildcard::getConstraintType
          (

           )
           const

Namespace constraint: A constraint type: any, not, list.

References fConstraintType.

          StringList * XSWildcard::getNsConstraintList
          (

           )

Namespace constraint.

For constraintType NSCONSTRAINT_DERIVATION_LIST, the list contains allowed namespaces. For constraintType NSCONSTRAINT_NOT, the list contains disallowed namespaces.

References fNsConstraintList.

          XSWildcard::PROCESS_CONTENTS XSWildcard::getProcessContents
          (

           )
           const

[process contents]: one of skip, lax or strict.

Valid constants values are: PC_SKIP, PC_LAX, PC_STRICT.

References fProcessContents.

          XSAnnotation * XSWildcard::getAnnotation
          (

           )
           const

Optional.

An [annotation].

References fAnnotation.

Member Data Documentation

          NAMESPACE_CONSTRAINT XSWildcard::fConstraintType [protected]

Referenced by getConstraintType().

          PROCESS_CONTENTS XSWildcard::fProcessContents [protected]

Referenced by getProcessContents().

          StringList* XSWildcard::fNsConstraintList [protected]

Referenced by getNsConstraintList().

          XSAnnotation* XSWildcard::fAnnotation [protected]

Referenced by getAnnotation().

The documentation for this class was generated from the following file:

XSWildcard.hpp

<address style="text-align: right;">Generated on Wed Apr 21 17:55:50 2010 for Xerces-C++ by

 1.5.6 </address>


text:
package jsonapi

type FutureResponse struct {
	IsSuccess       bool
	Success         map[Future]FutureResponseKind
	Failure         []OError
	WaitForComplete chan bool
}


text:
<!DOCTYPE html>

		<link rel="stylesheet" href="style.css">
		<link href='https://fonts.googleapis.com/css?family=Roboto:400,700,500' rel='stylesheet' type='text/css'>
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
		<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.css">

Lista de cosas

			<form action="#">
				<input type="text" placeholder="E.g. Un canguro superduro">
				<input class="invisible" type="submit" value="">
			</form>

				 Enviar

				 Jugar

				Start round

						<form action="#">
							Tiempo:
							<input id="round_time" type="text" name="round_time" placeholder="" size=3>
							<input class="invisible" type="submit" value="">
						</form>

						 Nueva partida

						 Correct
						 Pass

							 Cheat
						 Borrar


text:
'''
Created on 25 Jul 2014

@author: michael
'''

class RectangleCollider(object):
    '''
    This class is the interface for any rectangle collider.
    '''

    #
    # Note to self: ideally the collide_rectangle method would be lazy, so that you could
    # get the first k rectangles collided against efficiently. However, this functionality
    # simply isn't needed at the moment anyway...
    #

    def insert_rectangle(self, rect):
        '''
        Insert a rectangle into the collider.
        @param rect: the rectangle to insert, which should have the form (x_min,y_min,x_max,y_max,key)
        where key is any custom value
        '''
        pass

    def remove_rectangle(self, rect):
        '''
        Remove a rectangle from the collider. Note that the key must also be equal
        to the key of the rectangle you wish to remove.
        @param rect: the rectangle to insert, which should have the form (x_min,y_min,x_max,y_max,key)
        where key is any custom value
        @return: true iff the rectangle was removed, since it was in the tree
        '''
        pass

    def collide_rectangle(self, rect):
        '''
        Collide a rectangle tree with the collider
        @param rect: the rectangle to collide against in the form of (x_min,y_min,x_max,y_max)
        @return: a list of all rectangles that collided with the given rectangle.
        '''
        pass

    def is_colliding(self,rect):
        '''
        Check if a rectangle is colliding with any rectangle inserted into the collider.
        (This is more efficient than using collide_rectangle(..)==[])
        @param rect: the rectangle to check for collisions with in the form of (x_min,y_min,x_max,y_max)
        @return: true iff some rectangle exists in the collider that is colliding
        '''
        pass

    def clear(self):
        '''
        Remove all rectangles from the collider
        '''
        pass

    def __init__(self, size):
        '''
        Construct a new rectangle collider with the specified screen size. For implementation
        reasons, certain types of collider have minimum size restrictions. See each class's
        static fields.
        @param size: the size of the screen as (width,height)
        '''
        pass


text:
//
//  AFBJoinController.m
//  LoveFreshBeeSuper
//
//  Created by xlx on 16/11/24.
//  Copyright © 2016年 gao2015. All rights reserved.
//

#import "AFBJoinController.h"

@interface AFBJoinController ()

@end

@implementation AFBJoinController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}
- (void)setupUI
{
    UIScrollView *scoreView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    scoreView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:scoreView];
    scoreView.contentSize = CGSizeMake(kScreenWidth, 1000);

    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [scoreView addSubview:topView];

    UIImageView *imageview = [[UIImageView alloc] init];
    imageview.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    imageview.image = [UIImage imageNamed:@"join"];
    [topView addSubview:imageview];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
  <distributable/>
  <session-config>
    <session-timeout>60</session-timeout>
    <cookie-config>
      <max-age>60</max-age>
    </cookie-config>
  </session-config>
</web-app>


text:
require 'optparse'
require 'ostruct'
require 'date'

require_relative 'scan'
require_relative 'tools'

module Firebind

  # Firescan command line Ruby client for path scanning to a Firebind server
  class Client
    include Tools
    VERSION = '0.08'

    attr_reader :options

    def initialize(arguments)
      @arguments = arguments

      @opts = nil
      # Set defaults
      @options = OpenStruct.new
      @options.username = nil
      @options.password = nil
      @options.command_server = 'scanme.firebind.com'
      @options.protocol = :Simple
      @options.transport = :TCP
      @options.timeout = 5000
      @options.tcp_port_list = nil
      @options.udp_port_list = nil
      @options.local_address = nil
      @options.tag = nil
    end

    # Parse options, check arguments, then process the command
    def run
      scan = nil
      begin

        if parsed_options? && arguments_valid?
          puts
          verbose "Start at #{DateTime.now}"
          puts "Firescan Ruby client version #{VERSION} ( http://www.firebind.com )"
          #############
          # TCP scan
          #############
          unless @options.tcp_port_list.nil?

            debug "performing scan on TCP #{@options.tcp_port_list} via #{@options.command_server}"

            scan = Scan.new(@options.command_server,
                            @options.tcp_port_list,
                            :TCP,
                            @options.timeout,
                            :SimpleProtocol,
                            @options.username,
                            @options.password,
                            @options.tag)

            scan.add_observer self
            begin
              @tcp_scan = scan.scan

              debug "scan state: #{@tcp_scan.to_s}"
            rescue Errno::EHOSTUNREACH
              puts 'host not reachable'
            end
          end

          #############
          # UDP scan
          #############
          unless @options.udp_port_list.nil?

            debug "performing scan on UDP #{@options.udp_port_list} via #{@options.command_server}"

            scan = Scan.new(@options.command_server,
                            @options.udp_port_list,
                            :UDP,
                            @options.timeout,
                            :SimpleProtocol,
                            @options.username,
                            @options.password,
                            @options.tag)

            scan.add_observer self
            puts
            begin
              @udp_scan = scan.scan

              debug "scan state: #{@udp_scan.to_s}"
            rescue Errno::EHOSTUNREACH
              puts 'host not reachable'
            end
          end

          do_output
          verbose "Finished at #{DateTime.now}"

        else
          puts @opts
        end
      rescue Interrupt
        puts 'Stopping scan'
        scan.stop
      end
    end

    # command line output formatting helpers
    def do_scan_output(state)
      open_ports = state.open_ports
      closed_ports = state.closed_ports

      open_defa = if open_ports.size>1 then 'are' else 'is' end
      closed_defa = if closed_ports.size>1 then 'are' else 'is' end

      port_or_ports = if state.ports_scanned == 1 then 'port' else 'ports' end

      transport_output = ''
      transport_output << "#{state.transport} Port#{'s' unless open_ports.size == 1} #{open_ports.to_s} " \
            "#{open_defa} open\n" unless open_ports.size == 0
      transport_output << "#{state.transport} Port#{'s' unless closed_ports.size == 1} #{closed_ports.to_s} " \
            "#{closed_defa} closed\n" unless closed_ports.size == 0

      scanned_output = ''
      scanned_output << "\nScanned #{state.ports_scanned} #{state.transport} #{port_or_ports}"
      scanned_output << ", #{open_ports.size} #{open_defa} open" unless open_ports.size == 0
      scanned_output << ", #{closed_ports.size} #{closed_defa} closed" unless closed_ports.size == 0

      port_detail_output = ''
      state.result_map.each do |code,ports|
        unless code == $success
          ps = Portspec.new(ports)
          port_detail_output << "#{port_or_ports.capitalize} #{ps.to_s} #{if ps.size>1 then 'are' else 'is' end} closed - #{$result_code_messages[code]}\n"
        end
      end

      return transport_output,scanned_output,port_detail_output
    end

    def do_output

      tcp = @tcp_scan && @tcp_scan.current_state == :SCAN_COMPLETE
      udp = @udp_scan && @udp_scan.current_state == :SCAN_COMPLETE

      # we had a complete scan, show summary

      out = "\n"
      if tcp
        out << "Completed #{@tcp_scan.protocol} scan of #{@tcp_scan.transport} #{@tcp_scan.portspec.to_s}\n"
        tcp_transport_out,tcp_scanned_out,tcp_port_detail_out = do_scan_output(@tcp_scan)
      end
      if udp
        out << "Completed #{@udp_scan.protocol} scan of #{@udp_scan.transport} #{@udp_scan.portspec.to_s}\n"
        udp_transport_out,udp_scanned_out,udp_port_detail_out = do_scan_output(@udp_scan)
      end

      out << tcp_transport_out if tcp_transport_out
      out << udp_transport_out if udp_transport_out

      out << tcp_scanned_out if tcp_scanned_out
      out << udp_scanned_out if udp_scanned_out
      out << "\n"

      out << tcp_port_detail_out if tcp_port_detail_out
      out << udp_port_detail_out if udp_port_detail_out

      puts out

    end

    # scan callback interface
    # @param [Object] state
    def update(state)
      debug "callback #{state.to_s}"

      case state.current_state
        when :PORT_COMPLETE

          if state.port_result_code == $success
            puts " open in #{state.port_duration}ms #{state.percent_complete}%"
          else
            puts " closed after #{state.port_duration}ms - #{$result_code_messages[state.port_result_code]}"
          end

          $stdout.flush
        when :PORT_START
          print "#{state.transport.to_s} #{state.port.to_s}"
        when :PORT_TICK
          print '.'
        when :SCAN_START
          puts "Performing #{state.protocol} scan on #{state.transport} ports #{state.portspec.to_s} via #{state.command_server} with #{state.timeout}ms timeout"
        when :START_FAILURE
          case state.status_code
            when $authentication_failure
              puts 'Authentication failure'
            when $request_invalid
              puts 'Incompatible command server (request invalid) please check for a firescan gem update'
            when $server_bind_error
              puts "Server unable to bind on ports #{state.portspec.to_s}"
            when $command_server_unavailable
              puts "Unable to reach command server #{state.message}"
            else
              puts "Unable to start scan (code #{state.status_code})"
          end
        when :SCAN_COMPLETE

        else
          puts "unhandled callback #{state.to_s}"
      end

    end

    protected

    # figure what arguments we have to work with
    def parsed_options?

      @opts = OptionParser.new do |opt|
        opt.banner = "\nFirescan Ruby client version #{VERSION} ( http://www.firebind.com )\nUsage: firescan [options] "
        opt.separator ''
        opt.separator 'Options'

        opt.on('-h', '--help','Show help and version') do
          puts @opts
          exit
        end
        opt.on('-v', '--verbose','Show verbose output') do
          $verbose = true
        end
        opt.on('-s ADDRESS', '--command-server ADDRESS','Address:port or hostname:port of command server, default port is 80',String) do |address|
          @options.command_server = address
        end
        opt.on('-t PORT_LIST', '--tcp PORT_LIST','TCP Port specification (list), use commas and dashes to specify a list of ports',String) do |tcp_port_list|
          @options.tcp_port_list = tcp_port_list
        end
        opt.on('-u PORT_LIST', '--udp PORT_LIST','UDP Port specification (list), use commas and dashes to specify a list of ports',String) do |udp_port_list|
          @options.udp_port_list = udp_port_list
        end
        opt.on('-i TIMEOUT', '--timeout TIMEOUT','Timeout (in milliseconds) to use for connect, transmit and receive operations',Integer) do |timeout|
          @options.timeout = timeout
        end
        opt.on('-n USERNAME', '--username USERNAME','Specify a username (to connect to command server)',String) do |username|
          @options.username = username
        end
        opt.on('-p PASSWORD', '--password PASSWORD','Specify a password (to connect to command server)',String) do |password|
          @options.password = password
        end
        #opt.on('-r PROTOCOL', '--protocol PROTOCOL','Specify a protocol (defaults to Simple protocol)',String) do |protocol|
          #@options.protocol = protocol
          # todo handle this when IMG is available
        #end
        opt.on('-g TAG', '--tag TAG','tag the scan with value',String) do |tag|
          @options.tag = tag
        end
        #opt.on('-l LOCAL_ADDRESS', '--localaddr LOCAL_ADDRESS','Specify local IP address for client binding',String) do |addr|
        #  @options.local_address = addr
        #end
        opt.on('-d', '--xdebug','Show debug output') do
          $verbose = true
          $debug = true
        end
        opt.separator ''
     end

      @opts.parse!(@arguments) rescue return false

      verbose 'verbose output is on'
      debug 'debug output is on'

      if $debug
        output_options
      end
      #debug @options.to_s

      true
    end

    def output_options
      puts "Options:\           "
      @options.marshal_dump.each do |name, val|
      puts "  #{name} = #{val}"
      end
    end

    # True if required arguments were provided
    def arguments_valid?
      true if @options.udp_port_list != nil || @options.tcp_port_list != nil
    end

  end

end


text:
<?xml version="1.0" encoding="UTF-8"?>
<app>
    <name>Voice Composer Example</name>
    <description>...</description>
    <astivlet>
        <astivletId>VoiceComposer</astivletId>
        <class>org.astivetoolkit.examples.voicecomposer.App</class>
    </astivlet>
    <astivletMapping>
        <astivletId>VoiceComposer</astivletId>
        <urlPattern>/examples/VoiceComposer</urlPattern>
    </astivletMapping>
</app>


text:
.fuelux .search.disabled .input-group-btn {
  cursor: not-allowed;
}
.fuelux .search input::-ms-clear {
  display: none;
}


text:
require_relative '../../spec_helper'
require_relative '../../shared/file/setgid'

describe "File.setgid?" do
  it_behaves_like :file_setgid, :setgid?, File
end

describe "File.setgid?" do
  before :each do
    @name = tmp('test.txt')
    touch @name
  end

  after :each do
    rm_r @name
  end

  it "returns false if the file was just made" do
    File.setgid?(@name).should == false
  end

  it "returns false if the file does not exist" do
    rm_r @name # delete it prematurely, just for this part
    File.setgid?(@name).should == false
  end

  as_superuser do
    platform_is_not :windows do
      it "returns true when the gid bit is set" do
        system "chmod g+s #{@name}"

        File.setgid?(@name).should == true
      end
    end
  end
end


text:
import { API } from '../api';

API.helperMethods.set('isUserFromParams', function _isUserFromParams() {
	const params = this.requestParams();

	return (!params.userId && !params.username && !params.user)
		|| (params.userId && this.userId === params.userId)
		|| (params.username && this.user.username === params.username)
		|| (params.user && this.user.username === params.user);
});


text:
layout: default
title: "Public Service Reform"

---

{% include interests/public-service-reform.md %}

### Who is interested in Public Service Reform?

* [Mr David Laws]({{ site.baseurl }}/members/mr-david-laws.html)


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Example 09.08 - Orbit controls</title>


text:
/**
 * An object containing the search result for a single topic/HTML page.
 * Contains pointer to the topicID, title, short description and the list of words that were found.
 *
 * @param {string} topicID The ID of the topic. Can be used to identify unique a document in the search result.
 * @param {string} relativePath The relative path to the topic.
 * @param {string} title The topic title.
 * @param {string} shortDescription The topic short description.
 * @param {[string]} words The array with words contained by this topic.
 * @param {int} scoring The search scoring computed for this document.
 * @param {int} startsWith The number used to display 5 stars ranking.
 * @param {int} resultID The search result ID.
 * @param {int} linkID The search link ID.
 * @constructor
 */
function SearchResultInfo(topicID, relativePath, title, shortDescription, words, scoring, starWidth, resultID, linkID) {
    this.topicID = topicID;
    this.relativePath = relativePath;
    this.title = title;
    this.shortDescription = shortDescription;
    this.words = words;
    this.scoring = scoring;
    this.starWidth = starWidth;
    this.resultID = resultID;
    this.linkID = linkID;
    this.similarResults = [];
}

/**
 * Last displayed search results items.
 * @type {Array}
 */
var lastSearchResultItems = [];

/**
 * Last displayed search result.
 * @type {Array}
 */
var lastSearchResult;

/**
 * Pre process search result to compute similar results and scoring.
 * The lastSearchResultItems variable will be updated.
 *
 * @param searchResult The seach result to process.
 * @param whDistribution The WebHelp distribution.
 */
function preprocessSearchResult(searchResult, whDistribution) {
    lastSearchResult = searchResult;
    lastSearchResultItems = [];

    var wh_mobile =
        (typeof whDistribution != 'undefined') && whDistribution == 'wh-mobile';
    var wh_Classic =
        (typeof whDistribution != 'undefined') && whDistribution == 'wh-classic';

    if (searchResult.documents !== undefined && searchResult.documents.length > 0) {
        var allPages = searchResult.documents;

        // The score for fist item
        var ttScore_first = 1;
        if (allPages.length > 0) {
            ttScore_first = allPages[0].scoring;
        }

        var currentSimilarPage;
        for (var page = 0; page < allPages.length; page++) {
            /*debug("Page number: " + page);*/

            if (allPages[page].relativePath == 'toc.html') {
                continue;
            }

            var starWidth = 0;
            if (typeof webhelpSearchRanking != "undefined" && webhelpSearchRanking) {
                var hundredPercent = allPages[page].scoring + 100 * allPages[page].words.length;
                var numberOfWords = allPages[page].words.length;
                /*debug("hundredPercent: " + hundredPercent + "; ttScore_first: " + ttScore_first + "; numberOfWords: " + numberOfWords);*/
                var ttScore = allPages[page].scoring;

                // Fake value
                var maxNumberOfWords = allPages[page].words.length;
                starWidth = (ttScore * 100 / hundredPercent) / (ttScore_first / hundredPercent) * (numberOfWords / maxNumberOfWords);
                starWidth = starWidth < 10 ? (starWidth + 5) : starWidth;
                // Keep the 5 stars format
                if (starWidth > 85) {
                    starWidth = 85;
                }
            }

            var idLink = 'foundLink' + page;
            var idResult = 'foundResult' + page;

            // topicID, relativePath, title, shortDescription, words, scoring, starWidth, resultID, linkID, similarResults
            var csri = new SearchResultInfo(
                allPages[page].topicID,
                allPages[page].relativePath,
                allPages[page].title,
                allPages[page].shortDescription,
                allPages[page].words,
                allPages[page].scoring,
                starWidth,
                idResult,
                idLink
            );

            // Similar pages
            var similarPages = !wh_mobile && similarPage(allPages[page], allPages[page - 1]);
            if (!similarPages) {
                currentSimilarPage = csri;
                lastSearchResultItems.push(csri);
            } else {
                currentSimilarPage.similarResults.push(csri);
            }

        }
    }
}

/**
 * Compute the HTML to be displayed in the search results page.
 *
 * @param whDistribution The string with WebHelp distribution. One of wh-classic, wh-mobile or wh-responsive.
 * @param pageNumber The page number to display.
 * @param totalPageNumber The total page number.
 * @param itemsPerPage The number of items to display on a page.
 * @returns {string} The HTML to be displayed as search result.
 */
function computeHTMLResult(whDistribution, pageNumber, totalPageNumber, itemsPerPage) {
    var linkTab = [];
    var results = "";

    var wh_mobile =
        (typeof whDistribution != 'undefined') && whDistribution == 'wh-mobile';
    var wh_Classic =
        (typeof whDistribution != 'undefined') && whDistribution == 'wh-classic';

    if (lastSearchResult.searchExpression.length > 0) {
        if (lastSearchResultItems.length > 0) {

            // Start and end index dependin on the current presented page
            var s = 0;
            var e = lastSearchResultItems.length;

            if (typeof pageNumber != "undefined" && typeof itemsPerPage != "undefined") {
                s = (pageNumber - 1) * itemsPerPage;
                e = Math.min(s + itemsPerPage, lastSearchResultItems.length);
            }

            // Result for: word1 word2
            var txt_results_for = "Results for:";
            var headerHTML = "";

            headerHTML = "
";
            headerHTML += "
";
            headerHTML +=
                lastSearchResultItems.length + " "
                + getLocalization(txt_results_for) + " " +
                "" + lastSearchResult.originalSearchExpression + "";

            headerHTML += "
";
            if (typeof pageNumber != "undefined" && typeof totalPageNumber != "undefined" && totalPageNumber > 1) {
                headerHTML += "
";
                headerHTML += getLocalization('Page')+ " " + pageNumber + "/" + totalPageNumber;
                headerHTML += "
";
            }
            headerHTML += "
";

            linkTab.push(headerHTML);

			// EXM-38967 Start numbering
            var start = (pageNumber - 1) * 10 + 1;
            linkTab.push("
");

            var allSearchWords = lastSearchResult.searchExpression.split(" ");

            for (var page = s; page < e; page++) {
                var csri = lastSearchResultItems[page];

                var hasSimilarPages =
                    csri.similarResults != null &&
                    csri.similarResults.length > 0;

                var siHTML = computeSearchItemHTML(
                    csri,
                    whDistribution,
                    hasSimilarPages,
                    null);
                linkTab.push(siHTML);

                if (hasSimilarPages) {
                    // Add HTML for similar pages
                    for (var smPage = 0; smPage < csri.similarResults.length; smPage++) {
                        var simHTML = computeSearchItemHTML(
                            csri.similarResults[smPage],
                            whDistribution,
                            false,
                            csri.resultID);

                        linkTab.push(simHTML);
                    }
                }
            }

            linkTab.push("
");

            if (linkTab.length > 2) {
                results = "
";
                for (var t in linkTab) {
                    results += linkTab[t].toString();
                }
                results += "
";
            } else {
                results = "";
                results += "
" +
                    getLocalization("Search no results") + " " + "" + lastSearchResult.originalSearchExpression + "" + "
";
            }
        } else {
            results = "";
            results += "
" + getLocalization("Search no results") +
                " " + "" + lastSearchResult.originalSearchExpression + "" + "
";
        }
    } else {
        // Search expression is empty. If there are stop words, display a message accordingly
        if (lastSearchResult.excluded.length > 0) {
            results = "";
            var p1 = getLocalization("no_results_only_stop_words1");
            var pStr = "
" + p1 + "
";
            results += pStr;

            var p2 = getLocalization("no_results_only_stop_words2");
            var pStr = "
" + p2 + "
";
            results += pStr;
        }
    }

    return results;
}

/**
 * Compute the HTML for a single search result item.
 *
 * @param searchItem {SearchResultInfo} The search item to compute HTML.
 * @param whDistribution {String} The WebHelp distribution.
 * @param hasSimilarPages {Boolean} True if this item has similar results.
 * @param similarPageID {Boolean} It is set for a search item that is similar with another
 */
function computeSearchItemHTML(searchItem, whDistribution, hasSimilarPages, similarPageID) {
    var htmlResult = "";

    var wh_mobile =
        (typeof whDistribution != 'undefined') && whDistribution == 'wh-mobile';
    var wh_Classic =
        (typeof whDistribution != 'undefined') && whDistribution == 'wh-classic';

    var allSearchWords = lastSearchResult.searchExpression.split(" ");

    var tempPath = searchItem.relativePath;

    // EXM-27709 START
    // Display words between '<' and '>' in title of search results.
    var tempTitle = searchItem.title;
    // EXM-27709 END
    var tempShortDesc = searchItem.shortDescription;

    var starWidth = searchItem.starWidth;

    var rankingHTML = "";
    if (!wh_mobile && (typeof webhelpSearchRanking != 'undefined') && webhelpSearchRanking) {
        // Add rating values for scoring at the list of matches
        rankingHTML += "
";
        rankingHTML += "
";
        rankingHTML += "
";
        rankingHTML += "

";
        rankingHTML += "
";
        rankingHTML += "
";
        rankingHTML += "
";
        rankingHTML += "
";
    }

    var finalArray = searchItem.words;
    debug(finalArray);
    var arrayString = '';
    if (wh_Classic || wh_mobile) {
        var arrayString = 'Array(';
        for (var x in finalArray) {
            if (finalArray[x].length >= 2 || useCJKTokenizing || (indexerLanguage == "ja" && finalArray[x].length >= 1)) {
                arrayString += "'" + finalArray[x] + "',";
            }
        }
        arrayString = arrayString.substring(0, arrayString.length - 1) + ")";

    } else {
        for (var x in finalArray) {
            if (finalArray[x].length >= 2 || useCJKTokenizing || (indexerLanguage == "ja" && finalArray[x].length >= 1)) {
                arrayString += finalArray[x] + ",";
            }
        }
        arrayString = arrayString.substring(0, arrayString.length - 1);
    }

    // Add highlight param
    if (!wh_Classic && !wh_mobile) {
        tempPath += '?hl=' + encodeURIComponent(arrayString);
    }

    var idLink = searchItem.linkID;
    var idResult = searchItem.resultID;

    var link = 'return openAndHighlight(\'' + tempPath + '\', ' + arrayString + '\)';

    // Similar pages
    if (similarPageID == null) {
        htmlResult = '
';

        htmlResult += '' + tempTitle + '';
    } else {
        htmlResult =
            '
';
        htmlResult +=
            '' + tempTitle + '';
    }

    // Also check if we have a valid description
    if ((tempShortDesc != "null" && tempShortDesc != '...')) {
        // Highlight the search words in short description
        for (var si = 0; si < allSearchWords.length; si++) {
            var sw = allSearchWords[si];
            tempShortDesc = tempShortDesc.replace(
                new RegExp("(" + sw + ")", 'i'),
                "$1");
        }

        htmlResult += "\n
" + tempShortDesc + "
";
    }

    var searchItemInfo = "";

    // Relative Path
    var relPathStr = '
' + searchItem.relativePath + '
';
    searchItemInfo += relPathStr;

    // Missing words
    if (!wh_mobile && allSearchWords.length != searchItem.words.length) {
        //console.info("-------------- all words: ", allSearchWords);
        var missingWords = [];
        allSearchWords.forEach(function (word) {
            if (searchItem.words.indexOf(word) == -1) {
                missingWords.push(word);
            }
        });

        //console.info("missing words: ", missingWords);
        var missingHTML =
            "
" +
            getLocalization('Missing') + " : ";
        for (var widx = 0; widx < missingWords.length; widx++) {
            missingHTML += "" + missingWords[widx] + " "
        }
        missingHTML += "
";
        searchItemInfo += missingHTML;
    }

    if (!wh_mobile && hasSimilarPages) {
        var similarHTML =
            'Similar results...';

        searchItemInfo += similarHTML;
    }

    if (rankingHTML != undefined && searchItemInfo.length > 0) {
        htmlResult += '
';

        htmlResult += '
';
        htmlResult += searchItemInfo;
        htmlResult += '
';

        htmlResult += rankingHTML;
        htmlResult += '
';
    } else if (searchItemInfo.length > 0) {
        htmlResult += searchItemInfo;
    } else if (rankingHTML != undefined) {
        htmlResult += rankingHTML;
    }

    htmlResult += "
";
    return htmlResult;
}

/**
 * @description Compare two result pages to see if there are similar
 * @param result1 Result page
 * @param result2 Result page
 * @returns {boolean} true - result pages are similar
 *                    false - result pages are not similar
 */
function similarPage(result1, result2) {
    var toReturn = false;

    if (result1 === undefined || result2 === undefined) {
        return toReturn;
    }

    var pageTitle1 = result1.title;
    var pageShortDesc1 = result1.shortDescription;

    var pageTitle2 = result2.title;
    var pageShortDesc2 = result2.shortDescription;

    if (pageTitle1.trim() == pageTitle2.trim() && pageShortDesc1.trim() == pageShortDesc2.trim()) {
        toReturn = true;
    }

    return toReturn;
}

/**
 * When it is true, then the score is displayed as tooltip.
 *
 * @type {boolean}
 */
var displayScore = false;

/**
 * @description Show similar results that are hidden by default
 * @param link Link clicked to show similar results
 */
function showSimilarResults(link) {
    var parentLiElement = $(link).parents('li[id]');
    var currentResultId = parentLiElement.attr('id');

    $('[data-similarTo="' + currentResultId + '"]').toggle();
    $(link).toggleClass('expanded');
}


text:
/*!
	\file	kernel/error.h
	\brief	Contains definition of all error values
*/

#ifndef __ERROR__H
#define __ERROR__H

#include <ace.h>
#include <enum.h>

#define ENUM_LIST_ERROR_CODE(_) \
	_(ERROR_SUCCESS,) \
	_(ERROR_NOT_SUPPORTED,) \
	_(ERROR_INVALID_PARAMETER,) \
	_(ERROR_NOT_ENOUGH_MEMORY,) \
	_(ERROR_WRITE_FAULT,) \
	_(ERROR_READ_FAULT,) \
	_(ERROR_LOCK_VIOLATION,) \
	_(ERROR_BUSY,) \
	_(ERROR_RETRY,) \
	_(ERROR_TIMEOUT,) \
	_(ERROR_IO_DEVICE,) \
	_(ERROR_IRQ_BUSY,) \
	_(ERROR_INVALID_FORMAT,) \
	_(ERROR_INVALID_PATH,) \
	_(ERROR_NOT_FOUND,) \
	_(ERROR_SYMBOL_NOT_FOUND,) \
	_(ERROR_RESOURCE_SHORTAGE,)

DEFINE_ENUM(ERROR_CODE, ENUM_LIST_ERROR_CODE)

const char* ERROR_CODE_AS_STRING(ERROR_CODE n);

#endif


text:
using namespace std;

char* bufread_simple_label(shared_data* sd, label_data* ld, char* c)
{
  ld->label = *(float *)c;
  c += sizeof(ld->label);
  if (sd->binary_label && fabs(ld->label) != 1.f && ld->label != FLT_MAX)
    cout << "You are using a label not -1 or 1 with a loss function expecting that!" << endl;
  ld->weight = *(float *)c;
  c += sizeof(ld->weight);
  ld->initial = *(float *)c;
  c += sizeof(ld->initial);
  return c;
}

size_t read_cached_simple_label(shared_data* sd, void* v, io_buf& cache)
{
  label_data* ld = (label_data*) v;
  char *c;
  size_t total = sizeof(ld->label)+sizeof(ld->weight)+sizeof(ld->initial);
  if (buf_read(cache, c, total) < total)
    return 0;
  c = bufread_simple_label(sd, ld,c);

  return total;
}

float get_weight(void* v)
{
  label_data* ld = (label_data*) v;
  return ld->weight;
}

char* bufcache_simple_label(label_data* ld, char* c)
{
  *(float *)c = ld->label;
  c += sizeof(ld->label);
  *(float *)c = ld->weight;
  c += sizeof(ld->weight);
  *(float *)c = ld->initial;
  c += sizeof(ld->initial);
  return c;
}

void cache_simple_label(void* v, io_buf& cache)
{
  char *c;
  label_data* ld = (label_data*) v;
  buf_write(cache, c, sizeof(ld->label)+sizeof(ld->weight)+sizeof(ld->initial));
  c = bufcache_simple_label(ld,c);
}

void default_simple_label(void* v)
{
  label_data* ld = (label_data*) v;
  ld->label = FLT_MAX;
  ld->weight = 1.;
  ld->initial = 0.;
}

void delete_simple_label(void* v)
{
}

void parse_simple_label(parser* p, shared_data* sd, void* v, v_array<substring>& words)
{
  label_data* ld = (label_data*)v;

  switch(words.size()) {
  case 0:
    break;
  case 1:
    ld->label = float_of_substring(words[0]);
    break;
  case 2:
    ld->label = float_of_substring(words[0]);
    ld->weight = float_of_substring(words[1]);
    break;
  case 3:
    ld->label = float_of_substring(words[0]);
    ld->weight = float_of_substring(words[1]);
    ld->initial = float_of_substring(words[2]);
    break;
  default:
    cerr << "malformed example!\n";
    cerr << "words.size() = " << words.size() << endl;
  }
  if (words.size() > 0 && sd->binary_label && fabs(ld->label) != 1.f)
    cout << "You are using a label not -1 or 1 with a loss function expecting that!" << endl;
}

float get_active_coin_bias(float k, float l, float g, float c0)
{
  float b,sb,rs,sl;
  b=(float)(c0*(log(k+1.)+0.0001)/(k+0.0001));
  sb=sqrt(b);
  if (l > 1.0) { l = 1.0; } else if (l < 0.0) { l = 0.0; } //loss should be in [0,1]
  sl=sqrt(l)+sqrt(l+g);
  if (g<=sb*sl+b)
    return 1;
  rs = (sl+sqrt(sl*sl+4*g))/(2*g);
  return b*rs*rs;
}

float query_decision(vw& all, example& ec, float k)
{
  float bias, avg_loss, weighted_queries;
  if (k<=1.)
    bias=1.;
  else{
    weighted_queries = (float)(all.initial_t + all.sd->weighted_examples - all.sd->weighted_unlabeled_examples);
    avg_loss = (float)(all.sd->sum_loss/k + sqrt((1.+0.5*log(k))/(weighted_queries+0.0001)));
    bias = get_active_coin_bias(k, avg_loss, ec.revert_weight/k, all.active_c0);
  }
  if(frand48()<bias)
    return 1.f/bias;
  else
    return -1.;
}

void print_update(vw& all, example& ec)
{
  if (all.sd->weighted_examples >= all.sd->dump_interval && !all.quiet && !all.bfgs)
    {
      label_data* ld = (label_data*) ec.ld;
      char label_buf[32];
      if (ld->label == FLT_MAX)
	strcpy(label_buf," unknown");
      else
	sprintf(label_buf,"%8.4f",ld->label);

      if(!all.holdout_set_off && all.current_pass >= 1){
        if(all.sd->holdout_sum_loss == 0. && all.sd->weighted_holdout_examples == 0.)
          fprintf(stderr, " unknown   ");
        else
	  fprintf(stderr, "%-10.6f " , all.sd->holdout_sum_loss/all.sd->weighted_holdout_examples);

        if(all.sd->holdout_sum_loss_since_last_dump == 0. && all.sd->weighted_holdout_examples_since_last_dump == 0.)
          fprintf(stderr, " unknown   ");
        else
	  fprintf(stderr, "%-10.6f " , all.sd->holdout_sum_loss_since_last_dump/all.sd->weighted_holdout_examples_since_last_dump);

        fprintf(stderr, "%10ld %11.1f %s %8.4f %8lu h\n",
	      (long int)all.sd->example_number,
	      all.sd->weighted_examples,
	      label_buf,
	      ec.final_prediction,
	      (long unsigned int)ec.num_features);

        all.sd->weighted_holdout_examples_since_last_dump = 0.;
        all.sd->holdout_sum_loss_since_last_dump = 0.0;
      }
      else
        fprintf(stderr, "%-10.6f %-10.6f %10ld %11.1f %s %8.4f %8lu\n",
	      all.sd->sum_loss/all.sd->weighted_examples,
	      all.sd->sum_loss_since_last_dump / (all.sd->weighted_examples - all.sd->old_weighted_examples),
	      (long int)all.sd->example_number,
	      all.sd->weighted_examples,
	      label_buf,
	      ec.final_prediction,
	      (long unsigned int)ec.num_features);

      all.sd->sum_loss_since_last_dump = 0.0;
      all.sd->old_weighted_examples = all.sd->weighted_examples;
      VW::update_dump_interval(all);
	  fflush(stderr);
    }
}

void output_and_account_example(vw& all, example& ec)
{
  label_data* ld = (label_data*)ec.ld;

  if(ec.test_only)
  {
    all.sd->weighted_holdout_examples += ec.global_weight;//test weight seen
    all.sd->weighted_holdout_examples_since_last_dump += ec.global_weight;
    all.sd->weighted_holdout_examples_since_last_pass += ec.global_weight;
    all.sd->holdout_sum_loss += ec.loss;
    all.sd->holdout_sum_loss_since_last_dump += ec.loss;
    all.sd->holdout_sum_loss_since_last_pass += ec.loss;//since last pass
  }
  else
  {
    if (ld->label != FLT_MAX)
      all.sd->weighted_labels += ld->label * ld->weight;
    all.sd->weighted_examples += ld->weight;
    all.sd->sum_loss += ec.loss;
    all.sd->sum_loss_since_last_dump += ec.loss;
    all.sd->total_features += ec.num_features;
    all.sd->example_number++;
  }
  all.print(all.raw_prediction, ec.partial_prediction, -1, ec.tag);

  float ai=-1;
  if(all.active && ld->label == FLT_MAX)
    ai=query_decision(all, ec, (float)all.sd->weighted_unlabeled_examples);
  all.sd->weighted_unlabeled_examples += ld->label == FLT_MAX ? ld->weight : 0;

  for (size_t i = 0; i<all.final_prediction_sink.size(); i++)
    {
      int f = (int)all.final_prediction_sink[i];
      if(all.active && all.lda == 0)
	active_print_result(f, ec.final_prediction, ai, ec.tag);
      else if (all.lda > 0)
	print_lda_result(all, f,ec.topic_predictions.begin,0.,ec.tag);
      else
	all.print(f, ec.final_prediction, 0, ec.tag);
    }

  print_update(all, ec);
}

void return_simple_example(vw& all, void*, example& ec)
{
  output_and_account_example(all, ec);
  VW::finish_example(all,&ec);
}

bool summarize_holdout_set(vw& all, size_t& no_win_counter)
{
  float thisLoss = (all.sd->weighted_holdout_examples_since_last_pass > 0) ? (float)(all.sd->holdout_sum_loss_since_last_pass / all.sd->weighted_holdout_examples_since_last_pass) : FLT_MAX;

  if (all.span_server != "")
    thisLoss = accumulate_scalar(all, all.span_server, thisLoss);

  all.sd->weighted_holdout_examples_since_last_pass = 0;
  all.sd->holdout_sum_loss_since_last_pass = 0;

  if (thisLoss < all.sd->holdout_best_loss) {
    all.sd->holdout_best_loss = thisLoss;
    all.sd->holdout_best_pass = all.current_pass;
    no_win_counter = 0;
    return true;
  }

  no_win_counter++;
  return false;
}


text:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:id="@+id/container_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <include
                android:id="@+id/toolbar"
                layout="@layout/toolbar" />
        </LinearLayout>

        <FrameLayout
            android:id="@+id/container_body"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1" >

            <!--<ImageButton
                android:id="@+id/fab"
                android:layout_width="56dp"
                android:layout_height="56dp"
                android:src="@drawable/ic_add_white_24dp"
                android:background="@drawable/circle"
                android:layout_margin="24dp"
                android:layout_gravity="right|bottom"
                android:elevation="6dp"
                />-->
            <android.support.design.widget.FloatingActionButton
                android:layout_width="56dp"
                android:layout_height="56dp"
                android:layout_gravity="bottom|right"
                android:layout_margin="16dp"
                android:clickable="true"
                app:borderWidth="0dp"
                android:src="@drawable/ic_add_white_24dp" />

        </FrameLayout>

    </LinearLayout>

    <fragment
        android:id="@+id/fragment_navigation_drawer"
        android:name="com.bowenchin.android.materialapp.activity.FragmentDrawer"
        android:layout_width="@dimen/nav_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:layout="@layout/fragment_navigation_drawer"
        tools:layout="@layout/fragment_navigation_drawer" />

</android.support.v4.widget.DrawerLayout>


text:
package net.sparkeek.farmdroptest.rest.dto;

import javax.annotation.Generated;
import com.bluelinelabs.logansquare.annotation.JsonField;
import com.bluelinelabs.logansquare.annotation.JsonObject;

@Generated("com.robohorse.robopojogenerator")
@JsonObject
public class DTOPagination {

	@JsonField(name ="next")
	public int next;

	@JsonField(name ="per_page")
	public int perPage;

	@JsonField(name ="current")
	public int current;

	@JsonField(name ="pages")
	public int pages;

	@JsonField(name ="previous")
	public Object previous;

	@JsonField(name ="count")
	public int count;
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>R. Rossi | Gregor von Laszewski</title>
    <link>/author/r.-rossi/</link>
      <atom:link href="/author/r.-rossi/index.xml" rel="self" type="application/rss+xml" />
    <description>R. Rossi</description>
    <generator>Source Themes Academic (https://sourcethemes.com/academic/)</generator><language>en-us</language><lastBuildDate>Sun, 01 Nov 2020 00:00:00 +0000</lastBuildDate>
    <image>
      <url>/images/icon_hufdd866d90d76849587aac6fbf27da1ac_464_512x512_fill_lanczos_center_3.png</url>
      <title>R. Rossi</title>
      <link>/author/r.-rossi/</link>
    </image>

    <item>
      <title>net.science: A Cyberinfrastructure for Sustained Innovation in Network Science and Engineering</title>
      <link>/publication/las-2020-net-science/</link>
      <pubDate>Sun, 01 Nov 2020 00:00:00 +0000</pubDate>
      <guid>/publication/las-2020-net-science/</guid>
      <description></description>
    </item>

  </channel>
</rss>


text:
'use strict';
var false_run = false;

var Service, Characteristic;
var ping = require('ping');
var inherits = require('util').inherits;
var lgtv = require('lgtv-2012').lgtv;

function lgtv_2012_accessory(log, config, api) {
    this.log = function(msg) {
        if(this.host) msg = `TV [${this.host}]: ${msg}`;
        log(msg);
    }
    this.api = api;
    this.powered = false;

    if (config) {
        // import the user configuration
        this.name = config.name;
        this.key = config.pairingKey;
        this.host = config.ip;
        this.port = parseInt(config.port) || 8080;

        // set up tv object and debug flags
        this.tv = new lgtv({ 'host': this.host, 'port': this.port});
        this.tv.debug = (config.debug === true || config.debug == "true")
        this.tv.min_volume = config.min_volume || 2
        this.max_volume = 100 / (parseInt(config.max_volume) || 20);
        this.on_command = String(config.on_command).toUpperCase() || 'MUTE';
        this.tv.false_run = config.false_run == "true"
    }

    this.accessory = new Service.AccessoryInformation();
    this.accessory.setCharacteristic(Characteristic.Name, 'LG TV 2012')
        .setCharacteristic(Characteristic.Manufacturer, 'LG Electronics Inc.')
        .setCharacteristic(Characteristic.Model, '1.0');

    this.service = new Service.Lightbulb(this.name)
    this.service.getCharacteristic(Characteristic.On)
        .on('get', this.getState.bind(this))
        .on('set', this.setState.bind(this));

    this.service.getCharacteristic(Characteristic.Brightness)
        .on('get', this.getVolume.bind(this))
        .on('set', this.setVolume.bind(this));

    this.service.getCharacteristic(Characteristic.Hue)
        .on('get', this.getChannel.bind(this))
        .on('set', this.setChannel.bind(this));

    this.getServices = function() { return [this.service, this.accessory]; }
}

lgtv_2012_accessory.prototype.connect = function(cb) {
    if (this.host && this.host.length && this.port) {
        this.tv.new_session(this.key, (tv) => {
            this.powered = Boolean(tv);
            cb(tv);
        });
    } else {
        this.log('Does not appear to be powered on');
        this.powered = false;
        cb(null);
    }
}

lgtv_2012_accessory.prototype.getState = function(cb) {
    if (!this.host || !this.host.length) cb(null, false)
    else ping.sys.probe(this.host, (isAlive) => {
        this.powered = isAlive;
        this.log(' is' + isAlive?'On':'Off');
        cb(null, isAlive);
    }, { timeout: 1, min_reply: 1 })
}

lgtv_2012_accessory.prototype.setState = function(toggle, cb) {
    if(!this.powered || this.tv.locked) {
        this.log('Unable to change power settings at this time')
        cb(null, false)
    } else {
        this.getState((error, alive) => {
            this.connect((tv) => {
                this.log('Turning ' + toggle?'On':'Off')
                if(toggle) tv.send_command(this.on_command, (err) => { cb(null, true) });
                else tv.send_command('POWER', (err) => { cb(null, true) });
            })
        })
    }
}

lgtv_2012_accessory.prototype.getVolume = function(cb) {
    this.connect((tv) => {
        tv.get_volume( (volume) => {
            this.log('Volume is ' +volume.level+ ' and Mute is ' + volume.mute?'On':'Off');
            cb(null, Math.round(volume.level * this.max_volume));
        })
    })
}

lgtv_2012_accessory.prototype.setVolume = function(to, cb) {
    this.connect((tv) => {
        tv.set_volume(Math.round(to / this.max_volume), (err) => {
            this.log('Setting Volume to ' +to+ '... ' + err?'Success':'Failure');
            cb(null, true);
        })
    })
}

lgtv_2012_accessory.prototype.getChannel = function(cb) {
    if (!this.host || !this.host.length) cb(null, false)
    else {
        this.connect((tv) => {
            tv.get_channel( (channel) => {
                this.log(`On Channel: #${channel.number} ${channel.title}`);
                cb(null, channel.number)
            })
        })
    }
}

lgtv_2012_accessory.prototype.setChannel = function(channel, cb) {
    this.connect((tv) => {
        channel = parseInt(channel);
        if(channel) tv.set_channel(channel, (err) => {
            if(!err) this.log(`Set channel to ${channel}`);
            cb(true, err);
        });
    })
}

lgtv_2012_accessory.prototype.getChannelName = function(cb) {
    this.connect((tv) => {
        tv.get_channel( (channel) => {
            this.log(`Channel: ${channel.title}`);
            cb(null, channel.title);
        })
    })
}

lgtv_2012_accessory.prototype.identify = function(cb) {
    if (this.host && this.host.length) {
        if(this.powered) {
            if(this.key && this.key.length) this.connect((tv) => {
                tv.send_command('APPS', (success) => {
                    this.log('Identifying by launching LG App menu');
                    cb(null, success);
                })
            });
            else tv.pair_request((success) => {
                this.log('Performing request for TV key');
                cb(null, success);
            });
        } else this.checkInterval((alive) => { cb(null, alive) })
    } else cb(null, false)
}

lgtv_2012_accessory.prototype.checkInterval = function(cb) {
    this.getState((err, state) => { cb(state) });
    //setTimeout(cb, this.checkInterval.bind(this, cb), 2000)
}

module.exports = function (homebridge) {
    Service = homebridge.hap.Service;
    Characteristic = homebridge.hap.Characteristic;
    homebridge.registerAccessory('homebridge-lgtv-2012', 'lgtv-2012', lgtv_2012_accessory);
}


text:
Source code
===========

We can include a source code examples in our documentation via
code block:

```java

public static class Fancy extends Object {

  private final static String USELESS = "I am useless string";

}

```

We can link a source code from external file via
[include](https://github.com/rlmv/gitbook-plugin-include) plugin.
That file can be e.g. compiled against a library to make sure the
 code is correct before using it in documentation!
```java
!INCLUDE "../../examples/java/example/Person.java"
```


text:
package de.bornemisza.ds.rest.security;

import javax.security.auth.login.CredentialNotFoundException;

import org.glassfish.jersey.internal.util.Base64;

public class BasicAuthCredentials {

    private final String userName;
    private String password;

    public BasicAuthCredentials(String userName, String password) {
        this.userName = userName;
        this.password = password;
    }

    public BasicAuthCredentials(String authHeader) throws CredentialNotFoundException {
        if (authHeader == null || !authHeader.startsWith("Basic ")) {
            throw new CredentialNotFoundException("401 AuthHeader broken: " + authHeader);
        }
        else {
            authHeader = authHeader.substring(6);
            String decoded = Base64.decodeAsString(authHeader);
            if (decoded.contains(":")) {
                String[] splitted = decoded.split(":");
                this.userName = splitted[0];
                this.password = splitted[1];
            }
            else {
                throw new CredentialNotFoundException("401 AuthHeader unparseable: " + authHeader);
            }
        }
    }

    public String getUserName() {
        return userName;
    }

    public String getPassword() {
        return password;
    }

    public void changePassword(String newPassword) {
        this.password = newPassword;
    }

}


text:
package org.jchlabs.gharonda.handlers;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.jchlabs.gharonda.common.Utils;
import org.jchlabs.gharonda.domain.model.Emailfrequencies;
import org.jchlabs.gharonda.domain.model.Notifierprofiles;
import org.jchlabs.gharonda.domain.model.NumberSearchCriteria;
import org.jchlabs.gharonda.domain.model.SearchCriteriaIFace;
import org.jchlabs.gharonda.domain.model.Serviceproviderdetails;
import org.jchlabs.gharonda.domain.model.StringEqualSearchCriteria;
import org.jchlabs.gharonda.domain.model.Users;
import org.jchlabs.gharonda.domain.pom.dao.iface.EmailfrequenciesDAO;
import org.jchlabs.gharonda.domain.pom.dao.iface.NotifierprofilesDAO;
import org.jchlabs.gharonda.domain.pom.dao.iface.ServiceproviderdetailsDAO;
import org.jchlabs.gharonda.domain.pom.dao.iface.UsersDAO;
import org.jchlabs.gharonda.search.SearchService;
import org.jchlabs.gharonda.shared.rpc.ModifyUser;
import org.jchlabs.gharonda.shared.rpc.ModifyUserResult;
import org.jchlabs.gharonda.shared.rpc.ModifyUserType;
import org.jchlabs.gharonda.shared.rpc.RegistrationStatus;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.gwtplatform.dispatch.server.ExecutionContext;
import com.gwtplatform.dispatch.server.actionhandler.ActionHandler;
import com.gwtplatform.dispatch.shared.ActionException;

/**
 * Handler for login a user via email and password
 *
 */
public class ModifyUserHandler implements ActionHandler<ModifyUser, ModifyUserResult> {

	private final Log logger;
	private final Provider<HttpSession> sessionProvider;
	private final Provider<UsersDAO> uDAOProvider;
	private final Provider<ServiceproviderdetailsDAO> serviceProviderDAOProvider;
	private final Provider<NotifierprofilesDAO> notifierprofilesProvider;
	private final Provider<EmailfrequenciesDAO> emailfrequenciesDAOProvider;

	@Inject
	public ModifyUserHandler(Log logger, Provider<HttpSession> sessionProvider, Provider<UsersDAO> uDAOProvider,
			Provider<ServiceproviderdetailsDAO> serviceProvider,
			Provider<NotifierprofilesDAO> notifierprofilesProvider,
			Provider<EmailfrequenciesDAO> emailfrequenciesDAOProvider) {

		this.logger = logger;
		this.sessionProvider = sessionProvider;
		this.uDAOProvider = uDAOProvider;
		this.serviceProviderDAOProvider = serviceProvider;
		this.notifierprofilesProvider = notifierprofilesProvider;
		this.emailfrequenciesDAOProvider = emailfrequenciesDAOProvider;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see net.customware.gwt.dispatch.server.ActionHandler#execute(net.customware .gwt.dispatch.shared.Action,
	 * net.customware.gwt.dispatch.server.ExecutionContext)
	 */
	public ModifyUserResult execute(ModifyUser action, ExecutionContext context) throws ActionException {
		Users user = action.getUser();
		RegistrationStatus status;
		assert (user != null);
		UsersDAO uDAO = uDAOProvider.get();
		Users existingUser = uDAO.load(action.getUser().getId());
		Integer oldFreqtype = -1;
		if (existingUser == null) {
			existingUser = uDAO.get(action.getUser().getId());
		} else {
			((org.jchlabs.gharonda.domain.pom.dao.UsersDAO) uDAO).getSession().refresh(existingUser);
		}

		try {
			System.out.println("ModifyUser: user email name from client =" + user.getEmail());

			if (action.getModType().equals(ModifyUserType.MOD_PASSWD) && action.getOldPassWord() != null
					&& action.getNewPassWord() != null) {
				if (existingUser.getPasswd().equals(action.getOldPassWord())) {
					existingUser.setPasswd(action.getNewPassWord());
					uDAO.saveOrUpdate(existingUser);
					HttpSession session = sessionProvider.get();
					session.setAttribute("user", existingUser);
					status = RegistrationStatus.SUCCESS;
				} else {
					status = RegistrationStatus.PASSWDS_NOT_MATCH;
					existingUser = user;
				}

			} else if (action.getModType().equals(ModifyUserType.MOD_EMAIL) && action.getNewEmail() != null) {
				List<SearchCriteriaIFace> criteriaList = new ArrayList<SearchCriteriaIFace>();
				StringEqualSearchCriteria emailSrchCriteria = new StringEqualSearchCriteria("Email",
						action.getNewEmail());
				criteriaList.add(emailSrchCriteria);
				SearchService service = new SearchService(Users.class, (org.jchlabs.gharonda.domain.pom.dao.UsersDAO) uDAO);
				List<Object> users = service.search(criteriaList);
				Users _user = null;
				if (users.size() > 0) {
					_user = action.getUser();
					logger.debug("The user with email has been already registered. So new mail is not valid "
							+ _user.getEmail());
					status = RegistrationStatus.ALREADY_EXISTS;
					existingUser = user;
				} else {
					existingUser.setEmail(action.getNewEmail());
					uDAO.saveOrUpdate(existingUser);
					HttpSession session = sessionProvider.get();
					session.setAttribute("user", existingUser);
					status = RegistrationStatus.SUCCESS;

				}
			} else if (action.getModType().equals(ModifyUserType.MOD_DETAILS)) {
				if (user.getServiceproviderdetails() != null) {
					Serviceproviderdetails newServiceProvider = user.getServiceproviderdetails();
					ServiceproviderdetailsDAO sDAO = serviceProviderDAOProvider.get();
					if (newServiceProvider.getId() == null) {
						// First time Serviceproviderdetails being created
						sDAO.saveOrUpdate(newServiceProvider);
						existingUser.setServiceproviderdetails(newServiceProvider);

					} else {
						Serviceproviderdetails existingProvider = sDAO.load(newServiceProvider.getId());
						if (existingProvider == null) {
							existingProvider = sDAO.get(newServiceProvider.getId());
						} else {
							((org.jchlabs.gharonda.domain.pom.dao.ServiceproviderdetailsDAO) sDAO).getSession().refresh(
									existingProvider);
						}
						existingProvider.setAddrLine1(newServiceProvider.getAddrLine1());
						existingProvider.setAddrLine2(newServiceProvider.getAddrLine2());
						existingProvider.setCompanyName(newServiceProvider.getCompanyName());
						existingProvider.setBusinessType(newServiceProvider.getBusinessType());
						existingProvider.setSuburb(newServiceProvider.getSuburb());
						existingProvider.setCity(newServiceProvider.getCity());
						existingProvider.setState(newServiceProvider.getState());
						existingProvider.setZip(newServiceProvider.getZip());
						// existingProvider.setPhone(newServiceProvider.getPhone());
						// existingProvider.setFax(newServiceProvider.getFax());
						existingProvider.setWebsite(newServiceProvider.getWebsite());
						sDAO.saveOrUpdate(existingProvider);
					}
				}
				existingUser.setFirstName(user.getFirstName());
				existingUser.setLastName(user.getLastName());
				existingUser.setPhone(user.getPhone());
				existingUser.setCell(user.getCell());
				uDAO.saveOrUpdate(existingUser);
				// uDAO.saveOrUpdate(user);
				HttpSession session = sessionProvider.get();
				session.setAttribute("user", existingUser);
				status = RegistrationStatus.SUCCESS;
				// existingUser = user;
			} else if (action.getModType().equals(ModifyUserType.MOD_NOTIFIER_PROFILE)) {
				Notifierprofiles newNotifierprofiles = null;
				if (user.getNotifierprofiles() != null) {
					newNotifierprofiles = user.getNotifierprofiles();
					NotifierprofilesDAO nDAO = notifierprofilesProvider.get();
					if (newNotifierprofiles.getId() == null) {
						nDAO.saveOrUpdate(newNotifierprofiles);

					} else {
						Notifierprofiles existingNotifierprofiles = nDAO.load(newNotifierprofiles.getId());
						if (existingNotifierprofiles == null) {
							existingNotifierprofiles = nDAO.get(newNotifierprofiles.getId());
						} else {
							((org.jchlabs.gharonda.domain.pom.dao.NotifierprofilesDAO) nDAO).getSession().refresh(
									existingNotifierprofiles);
						}
						oldFreqtype = existingNotifierprofiles.getFrequency();
						existingNotifierprofiles.setState(newNotifierprofiles.getState());
						existingNotifierprofiles.setCity(newNotifierprofiles.getCity());
						existingNotifierprofiles.setSuburb(newNotifierprofiles.getSuburb());
						existingNotifierprofiles.setFrequency(newNotifierprofiles.getFrequency());
						existingNotifierprofiles.setPType(newNotifierprofiles.getPType());
						existingNotifierprofiles.setPriceLVal(newNotifierprofiles.getPriceLVal());
						existingNotifierprofiles.setPriceComparator(newNotifierprofiles.getPriceComparator());
						existingNotifierprofiles.setPriceRVal(newNotifierprofiles.getPriceRVal());
						existingNotifierprofiles.setRoomNoLVal(newNotifierprofiles.getRoomNoLVal());
						existingNotifierprofiles.setRoomNoComparator(newNotifierprofiles.getRoomNoComparator());
						existingNotifierprofiles.setRoomNoRVal(newNotifierprofiles.getRoomNoRVal());
						existingNotifierprofiles.setSftLVal(newNotifierprofiles.getSftLVal());
						existingNotifierprofiles.setSftRVal(newNotifierprofiles.getSftRVal());
						existingNotifierprofiles.setSftComparator(newNotifierprofiles.getSftComparator());
						existingNotifierprofiles.setAmenity1(newNotifierprofiles.getAmenity1());
						existingNotifierprofiles.setAmenity2(newNotifierprofiles.getAmenity2());
						existingNotifierprofiles.setAmenity3(newNotifierprofiles.getAmenity3());
						existingNotifierprofiles.setAmenity4(newNotifierprofiles.getAmenity4());
						nDAO.saveOrUpdate(existingNotifierprofiles);
						newNotifierprofiles = existingNotifierprofiles;
					}
				}
				existingUser.setNotifierprofiles(newNotifierprofiles);
				existingUser.setLastName(user.getLastName());
				uDAO.saveOrUpdate(existingUser);
				if (action.getModType().equals(ModifyUserType.MOD_NOTIFIER_PROFILE)) {
					postSaveOrUpdateNotifierProfile(existingUser, oldFreqtype);
				}
				HttpSession session = sessionProvider.get();
				session.setAttribute("user", existingUser);
				status = RegistrationStatus.SUCCESS;
			} else {
				status = RegistrationStatus.FAIL;
			}
			return new ModifyUserResult(existingUser, status);

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("Unable to authenticate user " + user);
			throw new ActionException(e);
		}
	}

	private void postSaveOrUpdateNotifierProfile(Users user, Integer oldFreqtype) {
		Integer freqId = user.getNotifierprofiles().getFrequency();
		if (freqId == null) {
			freqId = user.getNotifierprofiles().getFrequency();
		}
		List<SearchCriteriaIFace> cList = new ArrayList<SearchCriteriaIFace>();
		NumberSearchCriteria criteria = new NumberSearchCriteria("FrequencyType", freqId);
		cList.add(criteria);
		SearchService service = new SearchService(Emailfrequencies.class,
				(org.jchlabs.gharonda.domain.pom.dao.EmailfrequenciesDAO) emailfrequenciesDAOProvider.get());
		List<Object> freqList = service.search(cList);
		Emailfrequencies frequency = null;
		if (freqList != null && freqList.size() > 0) {
			frequency = (Emailfrequencies) freqList.get(0);
		} else {
			frequency = new Emailfrequencies();
			frequency.setFrequencyType(freqId);
		}
		if (frequency != null) {
			byte[] bytes = frequency.getUserIds();
			bytes = Utils.addId(bytes, user.getId());
			if (bytes != null) {
				frequency.setUserIds(bytes);
				emailfrequenciesDAOProvider.get().saveOrUpdate(frequency);
			}
			if (oldFreqtype != null && oldFreqtype != -1
					&& oldFreqtype.intValue() != frequency.getFrequencyType().intValue()) {
				cList = new ArrayList<SearchCriteriaIFace>();
				criteria = new NumberSearchCriteria("FrequencyType", oldFreqtype);
				cList.add(criteria);
				freqList = service.search(cList);
				if (freqList != null && freqList.size() > 0) {
					frequency = (Emailfrequencies) freqList.get(0);
					if (frequency.getUserIds() != null) {
						bytes = Utils.removeId(frequency.getUserIds(), user.getId());
						frequency.setUserIds(bytes);
						emailfrequenciesDAOProvider.get().saveOrUpdate(frequency);
					}
				}
			}
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see net.customware.gwt.dispatch.server.ActionHandler#getActionType()
	 */
	public Class<ModifyUser> getActionType() {
		return ModifyUser.class;
	}

	@Override
	public void undo(ModifyUser action, ModifyUserResult result, ExecutionContext context) throws ActionException {
		// TODO Auto-generated method stub

	}
}


text:
using System;
using System.Linq;
using System.Linq.Expressions;

namespace Xtzp.Linq.BatchEnumerable
{
    /// <summary>
    /// BatchEnumerator{TModel, TResult}
    /// </summary>
    public class BatchEnumerator<TModel, TResult> : AbstractBatchEnumerator<TModel, TResult>, IBatchEnumerator<TModel, TResult>
    {

        /// <summary>
        /// Batch enumerator contructor
        /// </summary>
        /// <param name="items"></param>
        /// <param name="response"></param>
        /// <param name="order"></param>
        /// <param name="filter"></param>
        /// <param name="batchSize"></param>
        public BatchEnumerator (
            IQueryable<TModel> items,
            Expression<Func<TModel, TResult>> response,
            Func<IQueryable<TModel>, IOrderedQueryable<TModel>> order = null,
            Expression<Func<TModel, bool>> filter = null,
            int batchSize = 10
        ) : base(
            response,
            order,
            filter,
            batchSize
        )
        {
            if (null == items) {
                throw new ArgumentNullException(nameof(items), "Items cannot be empty");
            }
            Items = items;
        }

        /// <summary>
        /// Move next IEnumerable implementation
        /// </summary>
        /// <returns></returns>
        public override bool MoveNext ()
        {
            CurrentBatchIndex++;
            CurrentItems = GetBatch(Items, Response, Order, Filter, CurrentBatchIndex, BatchSizeLocal);
            if (CurrentItems.Count() == 0) {
                return false;
            }
            return true;
        }
    }

    /// <summary>
    /// BatchEnumerator{TModel}
    /// </summary>
    public class BatchEnumerator<TModel> : BatchEnumerator<TModel, TModel>, IBatchEnumerator<TModel, TModel>
    {

        /// <summary>
        /// Batch enumerator contructor
        /// </summary>
        /// <param name="items"></param>
        /// <param name="response"></param>
        /// <param name="order"></param>
        /// <param name="filter"></param>
        /// <param name="batchSize"></param>
        public BatchEnumerator (
            IQueryable<TModel> items,
            Expression<Func<TModel, TModel>> response,
            Func<IQueryable<TModel>, IOrderedQueryable<TModel>> order = null,
            Expression<Func<TModel, bool>> filter = null,
            int batchSize = 10
            ) : base(
            items,
            response,
            order,
            filter,
            batchSize
        )
        {
        }
    }
}