text:
/**
 * Examples for adding routes.
 *
 *
 *
 * // add a simple route.
 * routes.add('e404', {
 *     url: '/e404',
 *     template: 'e404/admin-e404.html'
 * });
 * // add a multiple route that will match with viewIds.
 * routes.add('home-details', {
 *     url: '/home/details',
 *     resolve: function(done) {done()},// resolves before any routes
 *     views: {
 *         main: {
 *             template: 'dashboard/admin-dashboard1.html'
 *         },
 *         popup: {
 *             template: 'dashboard/admin-dashboard1.html'
 *         }
 *     },
 *     // add any custom data you want to the main route, or view routes.
 *     data: {
 *     }
 * });
 * // router should dispatch an "router::change" after all are done.
 */

define('hbRouter', ['hb', 'each', 'routeParser', 'dispatcher', 'extend', 'functionArgs', 'hb.template', 'hb.debug'], function (hb, each, routeParser, dispatcher, extend, functionArgs, template, debug) {

//TODO: figure out html5 to make it not use the #/
    function Router($app, $window) {
        var self = dispatcher(this),
            events = {
                //TODO: need to fire before change.
                BEFORE_CHANGE: 'router::beforeChange',
                RESOLVE_VIEW: 'router::resolveView',
                CHANGE: 'router::change',
                AFTER_CHANGE: 'router::afterChange',
                ERROR: 'router::error'
            },
            $location = $window.document.location,
            $history = $window.history,
            routes = {},
            base = $location.pathname,
            lastHashUrl,
            data = {},
            pending = [],
            processing = null,
            urlCleanRx = /(\:\w+)/g,
            paramCleanRx = /(:\w+)/g,
            escRx = /[-[\]{}()*+?.,\\^$|#\s\/]/g;

        function add(route) {
            if (typeof route === "string") {
                return addRoute(arguments[1], route);
            }
            each(route, addRoute);//expects each route to have an id
            return self;
        }

        function addRoute(route, id) {
            route.id = id;
            routes[id] = route;
            return self;
        }

        function remove(id) {
            delete routes[id];
        }

        function cleanUrl(url) {
            return url.split('#').join('');
        }

        function generateUrl(url, values) {
            url = cleanUrl(url);
            var used = {},
                unusedUrlParams = [],
                result = {
                    url: values && url.replace(urlCleanRx, function (match, p1) {
                        var str = p1.substr(1);
                        used[str] = true;
                        return values[str];
                    })
                };
            if (values) {
                each(values, {used:used, unusedUrlParams:unusedUrlParams}, unusedParams);
                if (unusedUrlParams.length) {
                    result.url = result.url.split('?').shift() + '?' + unusedUrlParams.join('&');
                }
            }
            return result;
        }

        function unusedParams(value, prop, list, params) {
            if (!params.used[prop]) {
                params.unusedUrlParams.push(prop + '=' + value);
            }
        }

        function resolveUrl(evt, skipPush) {
            resolveToUrl($location.hash, skipPush);
        }

        function resolveToUrl(url, skipPush) {
            url = cleanUrl(url) || '/';
            var failedUrl = undefined;
            var route = getRouteFromPath(url);
            if (!route) {
                failedUrl = url;
                url = self.otherwise;
                skipPush = true;
                route = getRouteFromPath(url);
            }
            var params = routeParser.extractParams(route.url, url);
            if (failedUrl) {
                params.params.failedUrl = failedUrl;
            }
            go(route.id, params.params, skipPush);
        }

        function doesRouteMatchPath(route, index, list, params) {
            if (!params.url) {
                return;
            }
            var escUrl = route.url.replace(escRx, "\\$&");
            var rx = new RegExp("^" + escUrl.replace(paramCleanRx, '[\\w\\-]+') + "$", 'i');
            if (params.url.match(rx)) {
                params.route = route;
                return params.route;
            }
        }

        function getRouteFromPath(url) {
            var item = {url:url.split('?').shift(), route:''};
                each(routes, item, doesRouteMatchPath);
            if (item.route && item.route.url) {
                return item.route;
            }
            return null;
        }

        function go(routeName, params, skipPush) {
            var route = routes[routeName], item = {routeName:routeName, params:params, skipPush:skipPush};
            if (!route) {
                resolveToUrl(routeName, skipPush);
                return;
            }
            if (processing) {
                pending.push(item);
                return;
            }
            processing = item;
            var path = generateUrl(route.url, params), url = path.url || route.url;
            if ($history.pushState) {
                if (skipPush || !$history.route) {
                    $history.replaceState({url: url, params: params}, '', base + '#' + url);
                } else if ($history.route && $history.route.url !== url) {
                    $history.pushState({url: url, params: params}, '', base + '#' + url);
                }
            } else if (!skipPush) {
                if ($location.hash === '#' + url) {
                    return;
                }
                $location.hash = '#' + url;
            }
            change(route, params);
        }

        function change(route, params) {
            var evt = self.fire(events.BEFORE_CHANGE, data);
            if (!evt.defaultPrevented) {
                lastHashUrl = $location.hash.replace('#', '');
//                console.log("change from %s to %o", prev, current);
                extend(data, {current:route, params:params, prev:data.current});
                // if we need to resolve the whole route. Do that first. Then resolve the views.
                if (route.resolve) {
                    var args = functionArgs(route.resolve);
                    if (args.length) {
                        route.resolve(onResolve);
                        return;
                    }
                    route.resolve();
                }
                onResolve();
            }
        }

        function onResolve(err) {
            var evt;
            if (err) {
                debug.warn('onResolve error', err);
                evt = self.fire(events.ERROR, {error:err, data:data});
            }
            if (!evt || !evt.defaultPrevented) {
                self.fire(events.RESOLVE_VIEW, data);
            }
            loadTemplates(onChangeComplete);
        }

        function getViewTemplate(view, id, list, result) {
            result.push(view.template);
        }

        function loadTemplates(callback) {
            var result = [];
            if (data.current.template) {
                result.push(data.current.template);
            }
            each(data.current.views, result, getViewTemplate);
            template.get($app, result, callback);
        }

        function onChangeComplete() {
            var next;
            processing = null;
            self.fire(events.CHANGE, data);
            // the change fires and $apply in hbView. So the afterChange would be after the apply.
            self.fire(events.AFTER_CHANGE, data);
            if (pending.length) {
                next = pending.shift();
                go(next.routeName, next.params, next.skipPush);
            }
        }

        function onHashCheck() {
            var hashUrl = $location.hash.replace('#', '');
            if (hashUrl !== lastHashUrl) {
//                console.log("Hash Change Detected");
                resolveUrl(null, true);
                lastHashUrl = hashUrl;
            }
        }

//TODO: need to make sure that the back button is working with all urls.
        hb.on($window, 'popstate', resolveUrl);
        hb.on($window, 'hashchange', onHashCheck);
        setInterval(onHashCheck, 100);// backup plan. make sure we catch if the url changes.

        self.events = events;
        self.go = go;
        self.resolveUrl = resolveUrl;
        self.otherwise = '/';
        self.add = add;
        self.remove = remove;
        self.routes = routes;
        self.data = data;
        self.isProcessing = function() {
            return !self.data.current || !!processing;
        };
    }

    return function (module) {
        var router = (module.router = module.router || module.injector.instantiate(['$app', '$window', Router]));
        module.on(module.events.READY, router.resolveUrl);
        return module.injector.val("$router", router);
    };
});


text:
enum class ExampleMsg : protozero::pbf_tag_type {
    repeated_uint32_x = 1
};

inline std::vector<uint32_t> read_data(const std::string& data) {
    std::vector<uint32_t> values;

    protozero::pbf_message<ExampleMsg> message{data};
    while (message.next()) {
        switch (message.tag_and_type()) {
            case tag_and_type(ExampleMsg::repeated_uint32_x, protozero::pbf_wire_type::length_delimited): {
                    const auto xit = message.get_packed_uint32();
                    std::copy(xit.cbegin(), xit.cend(), std::back_inserter(values));
                }
                break;
            case tag_and_type(ExampleMsg::repeated_uint32_x, protozero::pbf_wire_type::varint): {
                    const auto value = message.get_uint32();
                    values.push_back(value);
                }
                break;
            default:
                REQUIRE(false); // should never be here
        }
    }

    return values;
}

inline std::vector<uint32_t> read_data_packed(const std::string& data) {
    std::vector<uint32_t> values;

    protozero::pbf_message<ExampleMsg> message{data};
    while (message.next(ExampleMsg::repeated_uint32_x, protozero::pbf_wire_type::length_delimited)) {
        const auto xit = message.get_packed_uint32();
        std::copy(xit.cbegin(), xit.cend(), std::back_inserter(values));
    }

    return values;
}

TEST_CASE("read not packed repeated field with tag_and_type") {
    const auto values = read_data(load_data("tag_and_type/data-not-packed"));

    REQUIRE(values.size() == 3);
    const std::vector<uint32_t> result{10, 11, 12};
    REQUIRE(values == result);
}

TEST_CASE("read not packed repeated field with tag_and_type using next(...)") {
    const auto values = read_data_packed(load_data("tag_and_type/data-not-packed"));

    REQUIRE(values.empty());
}

TEST_CASE("read packed repeated field with tag_and_type") {
    const auto values = read_data(load_data("tag_and_type/data-packed"));

    REQUIRE(values.size() == 3);
    const std::vector<uint32_t> result{20, 21, 22};
    REQUIRE(values == result);
}

TEST_CASE("read packed repeated field with tag_and_type using next(...)") {
    const auto values = read_data_packed(load_data("tag_and_type/data-packed"));

    REQUIRE(values.size() == 3);
    const std::vector<uint32_t> result{20, 21, 22};
    REQUIRE(values == result);
}

TEST_CASE("read combined packed and not-packed repeated field with tag_and_type") {
    const auto values = read_data(load_data("tag_and_type/data-combined"));

    REQUIRE(values.size() == 9);
    const std::vector<uint32_t> result{10, 11, 12, 20, 21, 22, 30, 31, 32};
    REQUIRE(values == result);
}

redpajama_set_name: RedPajamaGithub


text:
using IWebsocketClientLite.PCL;
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using WebsocketClientLite.PCL.CustomException;

namespace WebsocketClientLite.PCL.Service
{
    internal class TcpConnectionService : IDisposable
    {
        private readonly bool _keepTcpClientAlive;
        private readonly Func<bool> _isSecureConnectionSchemeFunc;
        private readonly Func<object, X509Certificate, X509Chain, SslPolicyErrors, bool> _validateServerCertificateFunc;
        private readonly Func<TcpClient, Uri, Task> _connectTcpClient;
        private readonly Func<Stream, byte[], CancellationToken, Task<int>> _readOneByteFunc;
        private readonly Action<ConnectionStatus, Exception?> _connectionStatusAction;

        private TcpClient? _tcpClient;
        private Stream? _stream;

        internal Stream ConnectionStream => _stream ?? throw new NullReferenceException("Stream cannot be null");

        public TcpConnectionService(
            Func<bool> isSecureConnectionSchemeFunc,
            Func<object, X509Certificate, X509Chain, SslPolicyErrors, bool> validateServerCertificateFunc,
            Func<TcpClient, Uri, Task> connectTcpClientFunc,
            Func<Stream, byte[], CancellationToken, Task<int>> readOneByteFunc,
            Action<ConnectionStatus, Exception?> connectionStatusAction,
            bool hasTransferTcpSocketLifeCycleOwnership,
            TcpClient? tcpClient = null)
        {
            _keepTcpClientAlive = !hasTransferTcpSocketLifeCycleOwnership;

            _isSecureConnectionSchemeFunc = isSecureConnectionSchemeFunc;
            _validateServerCertificateFunc = validateServerCertificateFunc;
            _connectTcpClient = connectTcpClientFunc;
            _connectionStatusAction = connectionStatusAction;
            _readOneByteFunc = readOneByteFunc;
            _tcpClient = tcpClient;
        }

        internal virtual async Task ConnectTcpStream(
            Uri uri,
            X509CertificateCollection? x509CertificateCollection,
            SslProtocols tlsProtocolType,
            TimeSpan timeout = default)
        {
            await ConnectTcpClient(uri, timeout);

            _stream = await GetTcpStream(uri, _tcpClient, x509CertificateCollection, tlsProtocolType);
        }

        internal IObservable<byte[]?> BytesObservable() =>
            Observable.Defer(() => Observable.FromAsync(ct => ReadByteArrayFromStream(1, ct)))
            .Where(bytes => bytes is not null);

        internal async Task<byte[]?> ReadBytesFromStream(ulong size, CancellationToken ct) =>
            await ReadByteArrayFromStream(size, ct);

        internal async Task<byte[]?> ReadByteArrayFromStream(ulong size, CancellationToken ct)
        {
            if (_stream is null || !_stream.CanRead)
            {
                throw new WebsocketClientLiteException("Stream not ready or not connected.");
            }

            var byteArray = new byte[size];

            try
            {
                if (_stream is null)
                {
                    throw new WebsocketClientLiteException("Read stream cannot be null.");
                }

                if (!_stream.CanRead)
                {
                    throw new WebsocketClientLiteException("Websocket connection have been closed.");
                }

                var readLength = await _readOneByteFunc(_stream, byteArray, ct);

                if (readLength == 0)
                {
                    throw new WebsocketClientLiteException("Websocket connection aborted unexpectedly. Check connection and socket security version/TLS version).");
                }

                if (readLength == -1)
                {
                    return null;
                }
            }
            catch (ObjectDisposedException)
            {
                Debug.WriteLine("Ignoring Object Disposed Exception - This is an expected exception");
            }
            return byteArray;
        }

        private async Task ConnectTcpClient(
            Uri uri,
            TimeSpan timeout = default)
        {
            _connectionStatusAction(ConnectionStatus.ConnectingToTcpSocket, null);

            if (_tcpClient is null)
            {
                _tcpClient = new TcpClient(
                    uri.HostNameType is UriHostNameType.IPv6
                        ? AddressFamily.InterNetworkV6
                        : AddressFamily.InterNetwork);
            }

            try
            {
                if (!_tcpClient.Connected)
                {
                    await _connectTcpClient(_tcpClient, uri)
                        .ToObservable()
                        .Timeout(timeout != default ? timeout : TimeSpan.FromSeconds(15));
                }
            }
            catch (TimeoutException ex)
            {
                throw new WebsocketClientLiteTcpConnectException($"TCP Socket connection timed-out to {uri.Host}:{uri.Port}.", ex);
            }
            catch (ObjectDisposedException)
            {
                // OK to ignore
            }
            catch (Exception ex)
            {
                throw new WebsocketClientLiteTcpConnectException($"Unable to establish TCP Socket connection to: {uri.Host}:{uri.Port}.", ex);
            }

            if (_tcpClient.Connected)
            {
                _connectionStatusAction(ConnectionStatus.TcpSocketConnected, null);
                Debug.WriteLine("Connected");
            }
            else
            {
                throw new WebsocketClientLiteTcpConnectException($"Unable to connect to Tcp socket for: {uri.Host}:{uri.Port}.");
            }
        }

        private async Task<Stream> GetTcpStream(
            Uri uri,
            TcpClient? tcpClient,
            X509CertificateCollection? x509CertificateCollection,
            SslProtocols tlsProtocolType)
        {
            if (tcpClient is null)
            {
                throw new NullReferenceException("Tcp Client cannot be null when trying to get socket stream.");
            }

            _connectionStatusAction(ConnectionStatus.ConnectingToSocketStream, null);

            if (_isSecureConnectionSchemeFunc())
            {
                var secureStream = new SslStream(
                    innerStream: tcpClient.GetStream(),
                    leaveInnerStreamOpen: true,
                    userCertificateValidationCallback: (sender, cert, chain, tlsPolicy)
                        => _validateServerCertificateFunc(sender, cert, chain, tlsPolicy));

                try
                {
                    await secureStream.AuthenticateAsClientAsync(uri.Host, x509CertificateCollection, tlsProtocolType, false);

                    _connectionStatusAction(ConnectionStatus.SecureSocketStreamConnected, null);
                    return secureStream;
                }
                catch (Exception ex)
                {
                    throw new WebsocketClientLiteException("Unable to determine stream type", ex);
                }
            }

            _connectionStatusAction(ConnectionStatus.SocketStreamConnected, null);
            return tcpClient.GetStream();
        }

        public void Dispose()
        {
            _stream?.Dispose();

            if (!_keepTcpClientAlive)
            {
                _tcpClient?.Dispose();
            }
        }
    }
}


text:
#ifndef _RectBinPacker_H_
#define _RectBinPacker_H_

#include <vector>
#include <algorithm>

class RectBinPacker {

public:
    struct Rect {
        float x;
        float y;
        float w;
        float h;

        Rect () {}

        Rect (const Rect& copy) {
            this->x = copy.x;
            this->y = copy.y;
            this->w = copy.w;
            this->h = copy.h;
        }

        Rect& operator= (const Rect& rhs) {
            this->x = rhs.x;
            this->y = rhs.y;
            this->w = rhs.w;
            this->h = rhs.h;
            return *this;
        }

        Rect (float x, float y, float w, float h)
        : x(x), y(y), w(w), h(h) {
        }

        float getArea () const {
            return w * h;
        }

		void rotate () {
            std::swap(w, h);
        }

        // std::sort(rects.rbegin(), rects.rend()); // Sort from greatest to least area
        bool operator< (const Rect& rhs) {
            return this->getArea() < rhs.getArea();
        }
    };

    struct Node {
        Rect rect;
        int userdataID;
        int smallNodeIndex;
        int bigNodeIndex;
        bool rotated;
        bool packed;

        Node ()
		: smallNodeIndex(-1), bigNodeIndex(-1), packed(false), rotated(false) {}

        Node (float x, float y, float w, float h, int userdataID)
        : rect(x, y, w, h), userdataID(userdataID), smallNodeIndex(-1), bigNodeIndex(-1), rotated(false), packed(false) {
        }

        Node (Rect& rect, int userdataID)
        : rect(rect), userdataID(userdataID), smallNodeIndex(-1), bigNodeIndex(-1), rotated(false), packed(false) {
        }

		Node (const Node& copy) {
            this->rect = copy.rect;
            this->userdataID = copy.userdataID;
            this->smallNodeIndex = copy.smallNodeIndex;
            this->bigNodeIndex = copy.bigNodeIndex;
			this->rotated = copy.rotated;
			this->packed = copy.packed;
        }

        Node& operator= (const Node& rhs) {
            this->rect = rhs.rect;
            this->userdataID = rhs.userdataID;
            this->smallNodeIndex = rhs.smallNodeIndex;
            this->bigNodeIndex = rhs.bigNodeIndex;
			this->rotated = rhs.rotated;
			this->packed = rhs.packed;
            return *this;
        }
    };

protected:
    float _maxW;
    float _maxH;
    std::vector<Node> _nodes;

	int tryFill (int nodeIndex, Rect insertRect);
	int tryFill (int nodeIndex, Rect insertRect, bool rotated);
    int fill (int nodeIndex, Rect insertRect, int insertUserdataID);
    int fill (int nodeIndex, Rect insertRect, int insertUserdataID, bool rotated);
    void split (int nodeIndex, Rect insertRect, int insertUserdataID, bool rotated);

public:
    RectBinPacker (float maxW, float maxH);
	RectBinPacker (const RectBinPacker& copy);
	RectBinPacker& operator= (const RectBinPacker& rhs);
    bool getNodeByUserdataID (int userdataID, Node& out);
    bool insert (float insertW, float insertH, int userdataID, Node& out);
    bool insert (float insertW, float insertH, int userdataID, bool allowRotate, Node& out);
	bool tryInsert (float insertW, float insertH);
	bool tryInsert (float insertW, float insertH, bool allowRotate);
    void clear();
    size_t getNodeCount();

};

#endif


text:
<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>factory test</title>
	</head>
	<style>
		div{
			width:100px;
			height: 200px;
			background: red;
		}
	</style>

	<body>
		<div id="feed-readers">
		</div>
	</body>
	<script src="rssReader.js"></script>
	<script>
//		var div = document.getElementById('div1');
//		var listDisplay = new ListDisplay("ul", div);
//		listDisplay.append("tianzx");
//		listDisplay.clear();
		var div =document.getElementById('feed-readers');
		var conf = {
			id: '酷壳Cooshell',
			feedUrl: 'http://coolshell.cn/feed',
//			updateInterval: '60',
			parent: div
		}
//		var feedReader = new FeedReader('',XhrManager.createXhrHandler(),conf);
		feedReader.fetchFeed();
	</script>

</html>


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <name>Applicant__c</name>
    <help>Der Kontakt, der sich bei der Einrichtung oder dem Programm bewirbt.</help>
    <relationshipLabel>Bewerbungen (Bewerber)</relationshipLabel>
    <label>Bewerber</label>
</CustomFieldTranslation>


text:
package com.hazelcast.map.impl;

import com.hazelcast.cluster.ClusterState;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.PartitioningStrategyConfig;
import com.hazelcast.core.PartitioningStrategy;
import com.hazelcast.map.impl.event.MapEventPublisher;
import com.hazelcast.map.impl.eviction.ExpirationManager;
import com.hazelcast.map.impl.nearcache.MapNearCacheManager;
import com.hazelcast.map.impl.operation.MapOperationProvider;
import com.hazelcast.map.impl.query.MapQueryEngine;
import com.hazelcast.map.impl.query.PartitionScanRunner;
import com.hazelcast.map.impl.query.QueryRunner;
import com.hazelcast.map.impl.query.ResultProcessorRegistry;
import com.hazelcast.map.impl.querycache.QueryCacheContext;
import com.hazelcast.map.impl.recordstore.RecordStore;
import com.hazelcast.map.merge.MergePolicyProvider;
import com.hazelcast.monitor.impl.LocalMapStatsImpl;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.query.impl.getters.Extractors;
import com.hazelcast.query.impl.predicates.QueryOptimizer;
import com.hazelcast.spi.EventFilter;
import com.hazelcast.spi.NodeEngine;
import com.hazelcast.spi.Operation;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Context which is needed by a map service.
 *

 * Shared instances, configurations of all maps can be reached over this context.
 *

 * Also this context provides some support methods which are used in map operations and {@link RecordStore} implementations.
 * For example all {@link PartitionContainer} and {@link MapContainer} instances
 * can also be reached by using this interface.
 *

 * It is also responsible for providing methods which are used by lower layers of
 * Hazelcast and exposed on {@link MapService}.
 *

 *
 * @see MapManagedService
 */
public interface MapServiceContext extends MapServiceContextInterceptorSupport, MapServiceContextEventListenerSupport {

    Object toObject(Object data);

    Data toData(Object object, PartitioningStrategy partitionStrategy);

    Data toData(Object object);

    MapContainer getMapContainer(String mapName);

    Map<String, MapContainer> getMapContainers();

    PartitionContainer getPartitionContainer(int partitionId);

    void initPartitionsContainers();

    /**
     * Clears all map partitions which are expected to have lesser backups
     * than given.
     *
     * @param partitionId partition id
     * @param backupCount backup count
     */
    void clearMapsHavingLesserBackupCountThan(int partitionId, int backupCount);

    void clearPartitionData(int partitionId);

    MapService getService();

    /**
     * Clears all partition based data allocated by MapService.
     *
     * @param onShutdown true if {@code clearPartitions} is called during MapService shutdown,
     *                   false otherwise.
     */
    void clearPartitions(boolean onShutdown);

    void destroyMapStores();

    void flushMaps();

    void destroyMap(String mapName);

    void reset();

    /**
     * Releases internal resources solely managed by Hazelcast. This method is
     * called when MapService is shutting down.
     */
    void shutdown();

    RecordStore createRecordStore(MapContainer mapContainer, int partitionId, MapKeyLoader keyLoader);

    RecordStore getRecordStore(int partitionId, String mapName);

    RecordStore getRecordStore(int partitionId, String mapName, boolean skipLoadingOnCreate);

    RecordStore getExistingRecordStore(int partitionId, String mapName);

    Collection<Integer> getOwnedPartitions();

    void reloadOwnedPartitions();

    AtomicInteger getWriteBehindQueueItemCounter();

    ExpirationManager getExpirationManager();

    void setService(MapService mapService);

    NodeEngine getNodeEngine();

    MergePolicyProvider getMergePolicyProvider();

    MapEventPublisher getMapEventPublisher();

    MapQueryEngine getMapQueryEngine(String name);

    QueryRunner getMapQueryRunner(String name);

    QueryOptimizer getQueryOptimizer();

    LocalMapStatsProvider getLocalMapStatsProvider();

    MapOperationProvider getMapOperationProvider(String name);

    MapOperationProvider getMapOperationProvider(MapConfig mapConfig);

    Extractors getExtractors(String mapName);

    void incrementOperationStats(long startTime, LocalMapStatsImpl localMapStats, String mapName, Operation operation);

    boolean removeMapContainer(MapContainer mapContainer);

    PartitioningStrategy getPartitioningStrategy(String mapName, PartitioningStrategyConfig config);

    void removePartitioningStrategyFromCache(String mapName);

    PartitionContainer[] getPartitionContainers();

    void onClusterStateChange(ClusterState newState);

    PartitionScanRunner getPartitionScanRunner();

    ResultProcessorRegistry getResultProcessorRegistry();

    MapNearCacheManager getMapNearCacheManager();

    QueryCacheContext getQueryCacheContext();

    String addListenerAdapter(String cacheName, ListenerAdapter listenerAdaptor);

    String addListenerAdapter(ListenerAdapter listenerAdaptor, EventFilter eventFilter, String mapName);

    String addLocalListenerAdapter(ListenerAdapter listenerAdaptor, String mapName);
}


text:
This was a project for a Human Computer Interface class. The system envisioned in the project is a touch interface in a kiosk to place orders for a subway sandwich. On placing the order, the idea is that the kiosk would print a ticket with an order number and estimated wait time so you don't have to wait in line during rush hours.

## Features:

- Using the app follows the process of ordering a subway sandwich in person
- Selected options are visible and can be deleted

## Running the app:
- App can be accessed easily accessed [here](http://ravichimmalgi.github.io/SubwayInterface/interface.html)
- Download the project and open interface.html in a browser.

## Issues:
This is a front-end interface only. There is no back-end functionality.

## Technology
Html, Javascript


text:
using System;
using System.Collections.Generic;
using System.Linq;
using PokerLeagueManager.Common.Commands;
using PokerLeagueManager.Common.Infrastructure;

namespace PokerLeagueManager.Utilities
{
    public static class GenerateSampleData
    {
        private static Random _rnd = new Random();

        public static void Generate(string[] args)
        {
            if (args.Length != 3)
            {
                throw new ArgumentException("Expected 3 arguments", nameof(args));
            }

            var serviceUrl = args[1];
            var numberOfGames = int.Parse(args[2]);

            Console.WriteLine($"serviceUrl: {serviceUrl}");
            Console.WriteLine($"numberOfGames: {numberOfGames}");

            using (var svc = new CommandServiceProxy())
            {
                svc.SetUrl(serviceUrl);

                foreach (var cmd in GenerateSampleDataCommands(numberOfGames))
                {
                    Console.WriteLine($"Executing Command: {cmd.GetType().Name}");
                    try
                    {
                        svc.ExecuteCommand(cmd);
                    }
                    catch (AggregateException ex)
                    {
                        foreach (var x in ex.InnerExceptions)
                        {
                            Console.WriteLine(x.ToString());
                            Console.WriteLine($"Agg Inner: {x.InnerException?.ToString()}");
                        }

                        throw;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                        Console.WriteLine($"Inner: {ex.InnerException?.ToString()}");
                        throw;
                    }
                }
            }
        }

        private static IEnumerable<ICommand> GenerateSampleDataCommands(int numberOfGames)
        {
            var results = new List<ICommand>();
            var samplePlayers = GenerateSamplePlayers().ToList();

            results.AddRange(samplePlayers);

            for (int g = 0; g < numberOfGames; g++)
            {
                var newGame = new CreateGameCommand();
                newGame.GameId = Guid.NewGuid();
                newGame.GameDate = GetUniqueDate(results);
                results.Add(newGame);

                var numPlayers = _rnd.Next(5, 10);
                var players = new List<AddPlayerToGameCommand>();

                for (int p = 0; p < numPlayers; p++)
                {
                    var newPlayer = new AddPlayerToGameCommand();
                    newPlayer.PlayerId = GetRandomPlayer(samplePlayers, players);
                    newPlayer.GameId = newGame.GameId;

                    players.Add(newPlayer);
                }

                results.AddRange(players);

                for (int p = 1; p < numPlayers; p++)
                {
                    var knockoutCommand = new KnockoutPlayerCommand();
                    knockoutCommand.GameId = newGame.GameId;
                    knockoutCommand.PlayerId = players[p].PlayerId;

                    results.Add(knockoutCommand);
                }
            }

            return results;
        }

        private static IEnumerable<CreatePlayerCommand> GenerateSamplePlayers()
        {
            yield return new CreatePlayerCommand() { PlayerId = Guid.NewGuid(), PlayerName = "Dylan Smith" };
            yield return new CreatePlayerCommand() { PlayerId = Guid.NewGuid(), PlayerName = "Ryan Fritsch" };
            yield return new CreatePlayerCommand() { PlayerId = Guid.NewGuid(), PlayerName = "Sauce" };
            yield return new CreatePlayerCommand() { PlayerId = Guid.NewGuid(), PlayerName = "Shane Wilkins" };
            yield return new CreatePlayerCommand() { PlayerId = Guid.NewGuid(), PlayerName = "G.W. Stein" };
            yield return new CreatePlayerCommand() { PlayerId = Guid.NewGuid(), PlayerName = "Colin Hickson" };
            yield return new CreatePlayerCommand() { PlayerId = Guid.NewGuid(), PlayerName = "Grant Hirose" };
            yield return new CreatePlayerCommand() { PlayerId = Guid.NewGuid(), PlayerName = "Jeff" };
            yield return new CreatePlayerCommand() { PlayerId = Guid.NewGuid(), PlayerName = "Alex K" };
            yield return new CreatePlayerCommand() { PlayerId = Guid.NewGuid(), PlayerName = "Rob Schneider" };
            yield return new CreatePlayerCommand() { PlayerId = Guid.NewGuid(), PlayerName = "Sean Kehoe" };
            yield return new CreatePlayerCommand() { PlayerId = Guid.NewGuid(), PlayerName = "Meghan Mawhinney" };
            yield return new CreatePlayerCommand() { PlayerId = Guid.NewGuid(), PlayerName = "Ray Tara" };
            yield return new CreatePlayerCommand() { PlayerId = Guid.NewGuid(), PlayerName = "Sam Pearce" };
            yield return new CreatePlayerCommand() { PlayerId = Guid.NewGuid(), PlayerName = "Jason The" };
            yield return new CreatePlayerCommand() { PlayerId = Guid.NewGuid(), PlayerName = "Chris Wentz" };
            yield return new CreatePlayerCommand() { PlayerId = Guid.NewGuid(), PlayerName = "Kiana Lindsay" };
            yield return new CreatePlayerCommand() { PlayerId = Guid.NewGuid(), PlayerName = "Sherika Vollmer" };
            yield return new CreatePlayerCommand() { PlayerId = Guid.NewGuid(), PlayerName = "Alfred Rolando" };
            yield return new CreatePlayerCommand() { PlayerId = Guid.NewGuid(), PlayerName = "Chauncey Cavallaro" };
        }

        private static Guid GetRandomPlayer(IEnumerable<CreatePlayerCommand> allPlayers, IEnumerable<AddPlayerToGameCommand> players)
        {
            var result = allPlayers.ElementAt(GenerateRandomInteger(allPlayers.Count())).PlayerId;

            while (players.Any(p => p.PlayerId == result))
            {
                result = allPlayers.ElementAt(GenerateRandomInteger(allPlayers.Count())).PlayerId;
            }

            return result;
        }

        private static DateTime GetUniqueDate(List<ICommand> results)
        {
            var result = GenerateRandomDate();

            while (results.Any(x => x is CreateGameCommand g && DoesDateMatch(g, result)))
            {
                result = GenerateRandomDate();
            }

            return result;
        }

        private static bool DoesDateMatch(CreateGameCommand x, DateTime result)
        {
            return x.GameDate.Year == result.Year && x.GameDate.Month == result.Month && x.GameDate.Day == result.Day;
        }

        private static DateTime GenerateRandomDate()
        {
            var minYear = 1950;
            var maxYear = 2016;
            var randomDays = GenerateRandomInteger((maxYear - minYear) * 365);

            var result = new DateTime(minYear, 1, 1);

            return result.AddDays(randomDays);
        }

        private static int GenerateRandomInteger(int max)
        {
            return _rnd.Next(max);
        }
    }
}


text:
<!doctype html>

  <meta charset="utf-8">
  <title>jQuery UI Effects - Toggle Demo</title>
  <link rel="stylesheet" href="js/jquery-ui.css">

Toggle

      Etiam libero neque, luctus a, eleifend nec, semper at, lorem. Sed pede. Nulla lorem metus, adipiscing ut, luctus sed, hendrerit vitae, mi.

<select name="effects" id="effectTypes">
  <option value="blind">Blind</option>
  <option value="bounce">Bounce</option>
  <option value="clip">Clip</option>
  <option value="drop">Drop</option>
  <option value="explode">Explode</option>
  <option value="fold">Fold</option>
  <option value="highlight">Highlight</option>
  <option value="puff">Puff</option>
  <option value="pulsate">Pulsate</option>
  <option value="scale">Scale</option>
  <option value="shake">Shake</option>
  <option value="size">Size</option>
  <option value="slide">Slide</option>
</select>

<button id="button" class="ui-state-default ui-corner-all">Run Effect</button>


text:
template <class T, class K>
void TProx<T, K>::set_start_end(ulong start, ulong end) {
  if (start >= end)
    TICK_ERROR(get_class_name()
               << " can't have start(" << start
               << ") greater or equal than end(" << end << ")");
  this->has_range = true;
  this->start = start;
  this->end = end;
}

template <class T, class K>
TProx<T, K>::TProx(T strength, bool positive) {
  has_range = false;
  this->strength = strength;
  this->positive = positive;
}

template <class T, class K>
TProx<T, K>::TProx(T strength, ulong start, ulong end, bool positive)
    : TProx<T, K>(strength, positive) {
  set_start_end(start, end);
}

template <class T, class K>
bool TProx<T, K>::is_separable() const {
  return false;
}

template <class T, class K>
void TProx<T, K>::call(const Array<K> &coeffs, T step, Array<K> &out) {
  if (has_range) {
    if (end > coeffs.size())
      TICK_ERROR(get_class_name()
                 << " of range [" << start << ", " << end
                 << "] cannot be called on a vector of size " << coeffs.size());
  } else {
    // If no range is given, we use the size of coeffs to get it
    set_start_end(0, coeffs.size());
    // But no range was given (set_start_end set has_range to true)
    // Still it is mandatory to set `start` and `end` as some prox might need
    // to know if they have changed from one iteration to another (see
    // ProxSortedL1)
    has_range = false;
  }
  call(coeffs, step, out, start, end);
}

template <class T, class K>
void TProx<T, K>::call(const Array<K> &coeffs, T step, Array<K> &out,
                       ulong start, ulong end) {
  TICK_CLASS_DOES_NOT_IMPLEMENT(get_class_name());
}

template <class T, class K>
T TProx<T, K>::value(const Array<K> &coeffs) {
  if (has_range) {
    if (end > coeffs.size())
      TICK_ERROR(get_class_name()
                 << " of range [" << start << ", " << end
                 << "] cannot get value of a vector of size " << coeffs.size());
  } else {
    // If no range is given, we use the size of coeffs to get it
    set_start_end(0, coeffs.size());
    // But no range was given (set_start_end set has_range to true)
    has_range = false;
  }
  return value(coeffs, start, end);
}

template <class T, class K>
T TProx<T, K>::value(const Array<K> &coeffs, ulong start, ulong end) {
  TICK_CLASS_DOES_NOT_IMPLEMENT(get_class_name());
}

template <class T, class K>
T TProx<T, K>::get_strength() const {
  return strength;
}

template <class T, class K>
void TProx<T, K>::set_strength(T strength) {
  this->strength = strength;
}

template <class T, class K>
ulong TProx<T, K>::get_start() const {
  return start;
}

template <class T, class K>
ulong TProx<T, K>::get_end() const {
  return end;
}

template <class T, class K>
bool TProx<T, K>::get_positive() const {
  return positive;
}

template <class T, class K>
void TProx<T, K>::set_positive(bool positive) {
  this->positive = positive;
}

template <class T, class K>
bool TProx<T, K>::is_in_range(ulong i) const {
  return !has_range || ((i >= start) && (i < end));
}

template class TProx<double, double>;
template class TProx<float, float>;

template class TProx<double, std::atomic<double>>;
template class TProx<float, std::atomic<float>>;


text:
<?php

// autoload_files.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    $vendorDir . '/tinify/tinify/lib/Tinify.php',
    $vendorDir . '/tinify/tinify/lib/Tinify/Exception.php',
);


text:
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
from bs4 import BeautifulSoup

register = template.Library()

@register.filter(is_safe=True)
@stringfilter
def html2js(value):
    soup = mark_safe(BeautifulSoup(value))
    return repr(soup)

register.filter('h2j', html2js)

@register.tag('htmltojs')
def htmltojs(parser, token):
    nodelist = parser.parse(('endhtmltojs',))
    parser.delete_first_token()
    return HtmlToJs(nodelist)

class HtmlToJs(template.Node):
    def __init__(self, nodelist):
        self.nodelist = nodelist
    def render(self, context):
        output = self.nodelist.render(context)
        return html2js(output)


text:
namespace ash {

// PSIMemoryMetrics is a background service that periodically
// retrieves memory pressure stall information from ChromeOS and publishes that
// information as UMA metrics, so that we can know the impact of upcoming
// features by examining the memory pressure histograms in dashboards
// with and without a candidate feature.
// Background: PSI (Pressure Stall Information) is a measure of the execution
// stalls that happen while waiting for memory/paging operatios (thrashing),
// and is a widely acceptable method of measuring the impact of low-memory
// stations (ref.: https://lwn.net/Articles/759781/ )
class PSIMemoryMetrics : public base::RefCountedThreadSafe<PSIMemoryMetrics> {
 public:
  explicit PSIMemoryMetrics(uint32_t period);

  PSIMemoryMetrics(const PSIMemoryMetrics&) = delete;
  PSIMemoryMetrics& operator=(const PSIMemoryMetrics&) = delete;
  PSIMemoryMetrics() = delete;

  // Begins data collection.
  void Start();

  // Ends data collection.
  void Stop();

 private:
  ~PSIMemoryMetrics();

  // Friend it so it can see private members for testing
  friend class PSIMemoryMetricsTest;
  FRIEND_TEST_ALL_PREFIXES(PSIMemoryMetricsTest, CustomInterval);
  FRIEND_TEST_ALL_PREFIXES(PSIMemoryMetricsTest, InvalidInterval);
  FRIEND_TEST_ALL_PREFIXES(PSIMemoryMetricsTest, SunnyDay1);
  FRIEND_TEST_ALL_PREFIXES(PSIMemoryMetricsTest, SunnyDay2);
  FRIEND_TEST_ALL_PREFIXES(PSIMemoryMetricsTest, SunnyDay3);
  FRIEND_TEST_ALL_PREFIXES(PSIMemoryMetricsTest, InternalsA);
  FRIEND_TEST_ALL_PREFIXES(PSIMemoryMetricsTest, InternalsB);
  FRIEND_TEST_ALL_PREFIXES(PSIMemoryMetricsTest, InternalsC);
  FRIEND_TEST_ALL_PREFIXES(PSIMemoryMetricsTest, InternalsD);
  FRIEND_TEST_ALL_PREFIXES(PSIMemoryMetricsTest, InternalsE);

  // Enumeration representing success and various failure modes for parsing PSI
  // memory data. These values are persisted to logs. Entries should not be
  // renumbered and numeric values should never be reused.
  enum class ParsePSIMemStatus {
    kSuccess,
    kReadFileFailed,
    kUnexpectedDataFormat,
    kInvalidMetricFormat,
    kParsePSIValueFailed,
    // Magic constant used by the histogram macros.
    kMaxValue = kParsePSIValueFailed,
  };

  static scoped_refptr<PSIMemoryMetrics> CreateForTesting(
      uint32_t period,
      const std::string& testfilename) {
    scoped_refptr<PSIMemoryMetrics> rv =
        base::MakeRefCounted<PSIMemoryMetrics>(period);
    rv->memory_psi_file_ = testfilename;
    return rv;
  }

  // Friend it so it can call our private destructor.
  friend class base::RefCountedThreadSafe<PSIMemoryMetrics>;

  // Retrieves one metric value from |content|, for the currently configured
  // metrics category (10, 60 or 300 seconds).
  // Only considers the substring between |start| (inclusive) and |end|
  // (exclusive).
  // Returns the floating-point string representation converted into an integer
  // which has the value multiplied by 100 - (10.20 = 1020), for
  // histogram usage.
  int GetMetricValue(const std::string& content, size_t start, size_t end);

  // Parses PSI memory pressure from  |content|, for the currently configured
  // metrics category (10, 60 or 300 seconds).
  // The some and full values are output to |metricSome| and |metricFull|,
  // respectively.
  // Returns status of the parse operation - ParsePSIMemStatus::kSuccess
  // or error code otherwise.
  ParsePSIMemStatus ParseMetrics(const std::string& content,
                                 int* metric_some,
                                 int* metric_full);

  ParsePSIMemStatus CollectEvents();

  // Calls CollectEvents and reschedules a future collection.
  void CollectEventsAndReschedule();

  // Schedules a metrics event collection in the future.
  void ScheduleCollector();

  // Cancels the running timer from the same sequence the timer runs in.
  void CancelTimer();

  // Interval between metrics collection.
  std::string memory_psi_file_;
  base::TimeDelta collection_interval_;
  std::string metric_prefix_;

  // Task controllers/monitors.
  scoped_refptr<base::SequencedTaskRunner> runner_;
  base::AtomicFlag stopped_;
  base::DelayedTaskHandle last_timer_;
};

// Items in internal are - as the name implies - NOT for outside consumption.
// Defined here to allow access to unit test.
namespace internal {

// Finds the bounds for a substring of |content| which is sandwiched between
// the given |prefix| and |suffix| indices. Search only considers
// the portion of the string starting from |search_start|.
// Returns false if the prefix and/or suffix are not found, true otherwise.
// |start| and |end| are output parameters populated with the indices
// for the middle string.
bool FindMiddleString(const base::StringPiece& content,
                      size_t search_start,
                      const base::StringPiece& prefix,
                      const base::StringPiece& suffix,
                      size_t* start,
                      size_t* end);

}  // namespace internal

}  // namespace ash

#endif  // CHROME_BROWSER_ASH_PSI_MEMORY_METRICS_H_


text:
class C {
    String foo(int n) {
        switch (n) {
            case 1:
            case 3:
                throw new IllegalArgumentException("A");
            case 2:
                throw new IllegalStateException("A");
        }
        return "";
    }
}


text:
#include "EmscriptenOpenALAudioDevice.hpp"

using namespace gdx::scripten;
bool EmscriptenOpenALAudioDevice::isMono ()
{

}
void EmscriptenOpenALAudioDevice::writeSamples (short * samples, int offset,int numSamples)
{

}
void EmscriptenOpenALAudioDevice::writeSamples (float * samples, int offset,int numSamples)
{

}
int EmscriptenOpenALAudioDevice::getLatency ()
{

}
void EmscriptenOpenALAudioDevice::dispose ()
{

}


text:
import Parse from 'parse/react-native';
import realm from '../data/Realm';
import { currentUser } from '../api/Account';
import { getUserLocationData } from './Geofencing';
import { adminRole } from '../api/Roles';
import { completeForm } from './Forms';
import crypto from 'crypto-js';
import async from 'async';
import _ from 'lodash';

const Submission = Parse.Object.extend('Submission');

/**
 * create a submission Object with acl assigned
 *
 * @param {string} id, the unique id for the realm record
 * @param {string} formId, the unique id for the parse form record
 * @param {object} answers, the answers to the current form
 * @param {object} user, the current parse user saved to AsyncStorage
 * @param {object} role, the adminRole to be assigned to the object
 */
Submission.create = function create(uniqueId, formId, answers, user, geolocation, role) {
  const submission = new Submission();
  submission.set('uniqueId', uniqueId);
  submission.set('formId', formId);
  submission.set('answers', answers);
  submission.set('userId', user);
  submission.set('geolocation', JSON.stringify(geolocation));
  const acl = new Parse.ACL();
  acl.setReadAccess(user, true);
  acl.setWriteAccess(user, true);
  acl.setRoleReadAccess(role, true);
  acl.setRoleWriteAccess(role, true);
  submission.setACL(acl);
  return submission;
};

/**
 * Loads the user's cached submissions. Filtered by options object.
 *
 * @param {object} options          Object containing unique ids to filter with.
 * @param {object} options.userId   Required. The id of the user to load Submissions from.
 * @param {object} options.formId   Optional. The id form related to the submission.
 * @param {object} options.surveyId   Optional. The id survey related to the submission.
 * @param {object} user             The current parse user saved to AsyncStorage
 */
export function loadCachedSubmissions(options = {}) {
  if (!options.userId) {
    console.warn('Unable to load Submissions: No userId found.');
    return;
  }

  let filter = `userId == "${options.userId}"`;
  filter += options.formId ? ` AND formId == "${options.formId}"` : '';
  filter += options.surveyId ? ` AND surveyId == "${options.surveyId}"` : '';

  return realm.objects('Submission').filtered(filter).sorted('created');
}

/**
 * user may only have one submission for each formId
 *
 * @param {string} formId, the unique id for the parse form record
 * @param {object} user, the current parse user saved to AsyncStorage
 */
function genSubmissionId(formId, user, done) {
  const str = `${user.id}${formId}`;
  const id = crypto.MD5(str).toString();
  done(null, id);
}

/**
 * wrapper around Submission.create what will also save asychronously
 *
 * @param {string} id, the unique id for the realm record
 * @param {string} formId, the unique id for the parse form record
 * @param {object} answers, the answers to the current form
 * @param {object} currentUser, the current parse user saved to AsyncStorage
 */
function createParseSubmission(id, formId, answers, user, done) {
  adminRole((err, role) => {
    if (err) {
      done('Invalid role.');
      return;
    }
    getUserLocationData((geolocation) => {
      const submission = Submission.create(id, formId, answers, user, geolocation, role);
      submission.save(null).then(
        (s) => {
          done(null, s);
        },
        () => {
          done('Network Error');
        }
      );
    });
  });
}

/**
 * update an existing submission on parse-server
 *
 * @param {object} submission, a Parse.Object instance
 * @param {object} answers, the answers to the current form
 */
function updateParseSubmission(submission, answers, done) {
  if (submission instanceof Parse.Object) {
    submission.save({answers: answers}).then(
      (s) => {
        done(null, s);
      },
      () => {
        done('Network Error');
      }
    );
  } else {
    done('Invalid submission instance type');
  }
}

/**
 * find a submission on parse by uniqueId
 *
 * @param {string} id, the unique id for the record
 */
function findParseSubmission(id, done) {
  const query = new Parse.Query(Submission);
  query.equalTo('uniqueId', id);
  query.find(
    (submissions) => {
      if (submissions && submissions.length) {
        done(null, submissions[0]);
        return;
      }
      done(null, null);
    },
    () => {
      done('Network Error');
    }
  );
}

/**
 * finds submissions on parse by array of uniqueIds
 *
 * @param {array} uniqueIds, the unique ids for the records
 * @callback {function} done, the callback in node.js format (err, res)
 */
function findParseSubmissions(uniqueIds, done) {
  const query = new Parse.Query(Submission);
  query.containedIn('uniqueId', uniqueIds);
  query.find(
    (submissions) => {
      if (submissions && submissions.length) {
        done(null, submissions);
        return;
      }
      done(null, null);
    },
    () => {
      done('Network Error');
    }
  );
}

/**
 * upsert a submission to the local realm database
 *
 * @param {string} id, the unique id for the realm record
 * @param {object} form, the form object related to the submission
 * @param {string} userId, the unique id for the currentUser
 * @param {object} answers, the answers to the current form
 * @param {boolean} dirty, mark the submission diry
 */
function upsertRealmSubmission(id, form, userId, answers, dirty, inProgress, done) {
  const submissions = realm.objects('Submission').filtered(
    `uniqueId = "${id}"`).sorted('created');
  if (submissions.length > 0) {
    const submission = submissions[0];
    try {
      realm.write(() => {
        submission.dirty = true;
        submission.inProgress = inProgress;
        submission.answers = JSON.stringify(answers);
      });
      if (!inProgress) {
        completeForm(form.id);
      }
      done(null, submission);
    } catch (e) {
      done(`Error updating realm submission ${id}`);
    }
  } else {
    if (!inProgress) {
      completeForm(form.id);
    }
    realm.write(() => {
      try {
        const submission = realm.create('Submission', {
          uniqueId: id,
          formId: form.id,
          surveyId: form.surveyId,
          userId: userId,
          dirty: true,
          inProgress: inProgress,
          created: new Date(),
          answers: JSON.stringify(answers),
        }, true);
        done(null, submission);
      } catch (e) {
        done(`Error saving realm submission ${id}`);
      }
    });
  }
}

/**
 * mark a local realm submission clean
 *
 * @param {string} id, the unique id for the realm record
 */
function markRealmSubmissionClean(id, done) {
  const submissions = realm.objects('Submission').filtered(
    `uniqueId = "${id}"`).sorted('created');
  if (submissions.length > 0) {
    try {
      const submission = submissions[0];
      realm.write(() => {
        submission.dirty = false;
      });
      done(null, submission);
    } catch (e) {
      done(`Error update realm submission ${id}`);
    }
  } else {
    done('Submission does not exist');
  }
}

/**
 * save a submission to realm.io and attempt to propagte to parse-server
 *
 * @param {object} form, data from the related form object for the parse submission record
 * @param {object} answers, the answers to the current form
 */
export function saveSubmission(form, answers, done) {
  async.auto({
    currentUser: (cb) => {
      currentUser(cb);
    },
    id: ['currentUser', (cb, results) => {
      genSubmissionId(form.id, results.currentUser, cb);
    }],
    // save to realm and mark dirty
    dirty: ['id', (cb, results) => {
      upsertRealmSubmission(results.id, form, results.currentUser.id, answers, true, false, cb);
    }],
    // TODO use cloud code for perform upsert vs. find then save
    // https://gist.github.com/kevinzhang96/1d4680b953e33342f6ab
    find: ['dirty', (cb, results) => {
      findParseSubmission(results.id, cb);
    }],
    // save to parse, if successful mark clean
    save: ['find', (cb, results) => {
      if (results.find === null) {
        createParseSubmission(results.id, form.id, answers, results.currentUser, cb);
      } else {
        updateParseSubmission(results.find, answers, cb);
      }
    }],
    // mark the local submission as clean
    clean: ['save', (cb, results) => {
      markRealmSubmissionClean(results.id, cb);
    }],
  }, (err) => {
    if (err) {
      if (err === 'Network Error') {
        return done(null, 'The submission was saved locally.');
      }
      return done(err);
    }
    done(null, 'The submission was saved.');
  });
}

/**
 * Save a submission to realm.io to allow resuming an incomplete form at a later time.
 * Does not propagate to Parse.
 *
 * @param {object} form, data from the related form object for the future parse form record
 * @param {object} answers, the answers to the current form
 */
export function saveIncompleteSubmission(form, answers, done) {
  async.auto({
    currentUser: (cb) => {
      currentUser(cb);
    },
    id: ['currentUser', (cb, results) => {
      genSubmissionId(form.id, results.currentUser, cb);
    }],
    // save to realm and mark as in-progress
    cache: ['id', (cb, results) => {
      upsertRealmSubmission(results.id, form, results.currentUser.id, answers, true, true, cb);
    }],
  }, (err) => {
    if (err) {
      return done(err);
    }
    done(null, 'The submission was saved locally.');
  });
}

/**
 * loads all cached submissions for the currentUser that are marked dirty
 */
export function loadDirtySubmissions(done) {
  async.auto({
    currentUser: (cb) => {
      currentUser(cb);
    },
    submissions: ['currentUser', (cb, results) => {
      const userId = results.currentUser.id;
      const submissions = realm.objects('Submission')
                                .filtered(`userId == "${userId}"`)
                                .filtered('dirty == true AND inProgress == false');
      cb(null, submissions);
    }],
  }, (err, results) => {
    if (err) {
      done(err);
      return;
    }
    done(null, results.submissions);
  });
}

/**
 * attempt to save multiple chached submissions to the remote then mark as
 * clean locally
 *
 * @param {array} submissions, array of realm.io model results
 * @callback {function} done, the callback method in node.js format (err, res)
 */
export function propagateSubmissions(submissions, done) {
  // let work with the realm.io objects in a local scoped array
  const dirty = submissions.slice();
  const uniqueIds = dirty.map((d) => d.uniqueId);
  async.auto({
    // get the current user
    currentUser: (cb) => {
      currentUser(cb);
    },
    // get the admin role
    adminRole: ['currentUser', (cb) => {
      adminRole(cb);
    }],
    // find existing parse objects
    combined: ['adminRole', (cb, results) => {
      findParseSubmissions(uniqueIds, (err, res) => {
        if (err) {
          return done(err);
        }
        if (res === null) {
          done('Network Error');
          return;
        }
        if (res && res.length > 0) {
          // what are the existing uniqueIds on the server
          const existingIds = res.map((e) => {
            return e.get('uniqueId');
          });
          // what is the difference between the cache and server
          const difference = _.difference(uniqueIds, existingIds);
          // get any realm.io submissions that do not exist on the server?
          const filtered = dirty.filter((d) => {
            return difference.indexOf(d.uniqueId) >= 0;
          });
          // create the missing remote objects and add to an array
          const missing = [];
          filtered.forEach((d) => {
            missing.push(Submission.create(d.uniqueId, d.formId, JSON.parse(d.answers), results.currentUser, d.geolocation, results.adminRole));
          });
          // update the existing answers
          res.forEach((e) => {
            const s = dirty.filter((d) => {
              return d.uniqueId === e.get('uniqueId');
            })[0];
            if (typeof s !== 'undefined') {
              e.set('answers', JSON.parse(s.answers));
            }
          });
          // combine all
          const combined = _.union(res, missing);
          cb(null, combined);
          return;
        }
        cb(null, []);
      });
    }],
    // Save all the objects in one http request
    saveAll: ['combined', (cb, results) => {
      const combined = results.combined;
      const total = combined.length;
      if (total > 0) {
        Parse.Object.saveAll(combined,
          () => {
            done(null, total);
          },
          (e) => {
            done(e);
          }
        );
      }
      cb(null, total);
    }],
    // mark the local submission as clean
    clean: ['saveAll', (cb) => {
      const numDirty = submissions.length;
      let count = 0;
      realm.write(() => {
        submissions.forEach((submission) => {
          count++;
          if (typeof submission === 'undefined') {
            return;
          }
          submission.dirty = false;
          if (numDirty === count) {
            cb(null, true);
          }
        });
      });
      cb(null, true);
    }],
  }, (err, results) => {
    if (done && typeof done === 'function') {
      if (err) {
        if (err === 'Network Error') {
          return done(null, 'The submission was saved locally.');
        }
        return done(err);
      }
      done(null, results.saveAll);
    }
  });
}


text:
import 'ng2-bootstrap';
import {Component} from '@angular/core';

import {RAMServices} from '../../services/ram-services';

import {IPrincipal} from '../../../../commons/api';
import {DROPDOWN_DIRECTIVES} from 'ng2-bootstrap';

@Component({
    selector: 'top-menu',
    templateUrl: 'top-menu.component.html',
    directives: [DROPDOWN_DIRECTIVES]
})

export class TopMenuComponent {

    public me: IPrincipal;

    constructor(private services: RAMServices) {
    }

    public ngOnInit() {
        this.services.rest.findMyPrincipal().subscribe(principal => {
                this.me = principal;
            }
        );
    }

    public isLoggedIn() {
        return this.me !== null && this.me !== undefined;
    }

    public goToHomePage() {
        this.services.route.goToHomePage();
    }

    public goToAuthorisationsHomePage() {
        this.services.route.goToAuthorisationsHomePage();
    }

    public goToSoftwareProviderServicesHomePage() {
        this.services.route.goToSoftwareServicesProviderHomePage();
    }

}


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

    <groupId>statut.example</groupId>
    <artifactId>spring-data-es</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>Spring Data For ElasticSearch Example</name>
    <description>Spring Data For ElasticSearch Example: Spring Boot, Spring Data, Spring REST, ElasticSearch 2.4.4
    </description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>net.java.dev.jna</groupId>
            <artifactId>jna</artifactId>
            <version>4.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


text:
EXECUTABLES="mp4tags${NACL_EXEEXT} mp4info${NACL_EXEEXT}"

EnableGlibcCompat


text:
<?php if (is_enabled('timeline')): ?>
	<?php echo html_tag('li', array(
		'class' => check_current_uris(array('member/'.$member->id, 'member/me')) ? 'active' : '',
	), navigation_link('timeline.plural', 'member/'.$member->id)); ?>
<?php endif; ?>
	<?php echo html_tag('li', array(
		'class' => check_current_uri('member/profile/'.$member->id) ? 'active' : '',
	), navigation_link('profile', 'member/profile/'.$member->id)); ?>

<?php
	if (conf('memberRelation.friend.isEnabled'))
	{
		$uri = sprintf('member/%d/relation/friends', $member->id);
		echo html_tag(
			'li',
			array('class' => check_current_uri($uri) ? 'active' : ''),
			anchor($uri, sprintf('%s (%d)', term('friend'), Model_MemberRelation::get_count4member_id($member->id, 'friend')))
		);
	}
?>

<?php
	if (conf('memberRelation.follow.isEnabled'))
	{
		$uri = sprintf('member/%d/relation/follows', $member->id);
		echo html_tag(
			'li',
			array('class' => check_current_uri($uri) ? 'active' : ''),
			anchor($uri, sprintf('%s (%d)', t('following'), Model_MemberRelation::get_count4member_id($member->id, 'follow')))
		);

		$uri = sprintf('member/%d/relation/followers', $member->id);
		echo html_tag(
			'li',
			array('class' => check_current_uri($uri) ? 'active' : ''),
			anchor($uri, sprintf('%s (%d)', t('follower'), Model_MemberRelation::get_count4member_id($member->id, 'follow', 'member_id_to')))
		);
	}
?>


text: put forth your best work for payout


text:
<?xml version="1.0" encoding="utf-8"?>

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/commentsView"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:layout_below="@+id/comment_form"
    >
<RelativeLayout

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="8dp"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <include
        android:id="@+id/task_author_layout"
        layout="@layout/include_task_author"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true" />

    <LinearLayout
        android:id="@+id/newlayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_below="@id/task_author_layout">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginBottom="5dp"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_marginTop="5dp">
            <ImageView
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_gravity="center"
                android:src="@drawable/ic_car"/>
            <TextView
                android:id="@+id/task_category_comment"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginLeft="10dp"
                android:textSize="12dp"
                android:text="Shared Drive"/>
        </LinearLayout>

        <TextView
            android:id="@+id/task_description_comment"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/task_category_comment"
            android:layout_marginBottom="5dp"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_marginTop="5dp"
            android:textSize="16dp"
            android:text="Des"
            android:maxLines="3" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:gravity="left"
            android:weightSum="1">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="0.7"
                android:layout_marginBottom="5dp"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:layout_marginTop="5dp"
                android:text="Minumium people required:"
                android:textSize="12dp"/>
            <TextView
                android:id="@+id/task_minPooling_comment"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
                android:layout_weight="0.3"
            android:layout_marginBottom="5dp"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_marginTop="5dp"
            android:text="1" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginBottom="5dp"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_marginTop="5dp">
            <ImageView
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_gravity="center"
                android:src="@drawable/ic_date"/>
            <TextView
                android:id="@+id/task_date_comment"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginLeft="10dp"
                android:textSize="12dp"
                android:text="Date"/>

        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginBottom="5dp"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_marginTop="5dp">
            <ImageView
                android:id="@+id/showTimePicker"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_gravity="center"
                android:src="@drawable/ic_time"/>
            <TextView
                android:id="@+id/task_time_comment"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginLeft="10dp"
                android:textSize="12dp"
                android:text="time"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginBottom="5dp"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_marginTop="5dp">
            <ImageView
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_gravity="center"
                android:src="@drawable/ic_location"/>
            <TextView
                android:id="@+id/task_location_comment"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="5dp"
                android:layout_marginLeft="16dp"
                android:layout_marginRight="16dp"
                android:layout_marginTop="5dp"
                android:text="location"
                android:textSize="12dp"
                />
        </LinearLayout>

    </LinearLayout>>

    <LinearLayout
        android:id="@+id/comment_form"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/newlayout"
        android:layout_marginTop="10dp"
        android:orientation="horizontal"
        android:weightSum="1.0">

        <EditText
            android:id="@+id/field_comment_text"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.7"
            android:hint="Write a comment..."
            android:maxLines="1" />

        <Button
            android:id="@+id/button_task_comment"
            style="@style/Base.Widget.AppCompat.Button.Borderless"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.3"
            android:text="Comment" />

    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_comments"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/comment_form"
        tools:listitem="@layout/item_comment" />

</RelativeLayout>

</ScrollView>


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/splash_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="welcome"
        android:textColor="@color/lighter_gray"
        android:textSize="12sp" />

    <ImageView
        android:id="@+id/iv_user_gender_menu"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/compose_app_empty" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/splash_text"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="102dp"
        android:textColor="@color/lighter_gray"
        android:text="Beta"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>


text:
package com.remyoukaour.votingsim.votingsystems;

import com.remyoukaour.votingsim.*;
import java.util.Vector;

public class Optimal extends ElectoralSystem {
	public Optimal() {
		super("Optimal");
	}

	public Candidate elect(Populace populace, Vector<Candidate> ballot) {
		Voter voter = new Voter(populace.getMeanX(), populace.getMeanY());
		double[] vote = voter.vote(ballot);
		return ballot.get(Utilities.min(vote));
	}
}


text:
template<class FlowField>
FieldIterator<FlowField>::FieldIterator (FlowField & flowField, const Parameters& parameters, FieldStencil<FlowField> & stencil,
                               int lowOffset, int highOffset):
    Iterator<FlowField>(flowField,parameters), _stencil(stencil), _lowOffset(lowOffset), _highOffset(highOffset){}

template<class FlowField>
void FieldIterator<FlowField>::iterate (){

    const int cellsX = Iterator<FlowField>::_flowField.getCellsX();
    const int cellsY = Iterator<FlowField>::_flowField.getCellsY();
    const int cellsZ = Iterator<FlowField>::_flowField.getCellsZ();
    // The index k can be used for the 2D and 3D cases.

    if (Iterator<FlowField>::_parameters.geometry.dim == 2){

        // Loop without lower boundaries. These will be dealt with by the global boundary stencils
        // or by the subdomain boundary iterators.
        for (int j = 1 + _lowOffset; j < cellsY - 1 + _highOffset; j++){
            for (int i = 1 + _lowOffset; i < cellsX - 1 + _highOffset; i++){
                _stencil.apply ( Iterator<FlowField>::_flowField, i, j );
            }
        }
    }

    if (Iterator<FlowField>::_parameters.geometry.dim == 3){

        for (int k = 1 + _lowOffset; k < cellsZ - 1 + _highOffset; k++){
            for (int j = 1 + _lowOffset; j < cellsY - 1 + _highOffset; j++){
                for (int i = 1 + _lowOffset; i < cellsX - 1 + _highOffset; i++){
                    _stencil.apply ( Iterator<FlowField>::_flowField, i, j, k );
                }
            }
        }
    }
}

template<class FlowField>
GlobalBoundaryIterator<FlowField>::GlobalBoundaryIterator(FlowField & flowField,
                                               const Parameters & parameters,
                                               BoundaryStencil<FlowField> & stencil,
                                               int lowOffset, int highOffset):
    Iterator<FlowField> (flowField,parameters),
    _lowOffset(lowOffset), _highOffset(highOffset),
    _leftWallStencil(stencil), _rightWallStencil(stencil),
    _bottomWallStencil(stencil), _topWallStencil(stencil),
    _frontWallStencil(stencil), _backWallStencil(stencil){}

template<class FlowField>
GlobalBoundaryIterator<FlowField>::GlobalBoundaryIterator(FlowField & flowField,
                                               const Parameters & parameters,
                                               BoundaryStencil<FlowField> & leftWallStencil,
                                               BoundaryStencil<FlowField> & rightWallStencil,
                                               BoundaryStencil<FlowField> & bottomWallStencil,
                                               BoundaryStencil<FlowField> & topWallStencil,
                                               int lowOffset, int highOffset):
    Iterator<FlowField> (flowField,parameters),
    _lowOffset(lowOffset), _highOffset(highOffset),
    _leftWallStencil(leftWallStencil), _rightWallStencil(rightWallStencil),
    _bottomWallStencil(bottomWallStencil), _topWallStencil(topWallStencil),
    // This is plain bad, but it will work. The references had to be initialized somehow
    _frontWallStencil(leftWallStencil), _backWallStencil(leftWallStencil)
{

    if (Iterator<FlowField>::_parameters.geometry.dim == 3){
        handleError(1, "Trying to use 2D constructor for a 3D field");
    }

}

template<class FlowField>
GlobalBoundaryIterator<FlowField>::GlobalBoundaryIterator(FlowField & flowField,
                                               const Parameters & parameters,
                                               BoundaryStencil<FlowField> & leftWallStencil,
                                               BoundaryStencil<FlowField> & rightWallStencil,
                                               BoundaryStencil<FlowField> & bottomWallStencil,
                                               BoundaryStencil<FlowField> & topWallStencil,
                                               BoundaryStencil<FlowField> & frontWallStencil,
                                               BoundaryStencil<FlowField> & backWallStencil,
                                               int lowOffset, int highOffset):
    Iterator<FlowField> (flowField,parameters),
    _lowOffset(lowOffset), _highOffset(highOffset),
    _leftWallStencil(leftWallStencil), _rightWallStencil(rightWallStencil),
    _bottomWallStencil(bottomWallStencil), _topWallStencil(topWallStencil),
    _frontWallStencil(frontWallStencil), _backWallStencil(backWallStencil){}

template<class FlowField>
void GlobalBoundaryIterator<FlowField>::iterate () {

    if (Iterator<FlowField>::_parameters.geometry.dim == 2){

        if (Iterator<FlowField>::_parameters.parallel.leftNb < 0){
            for (int j = _lowOffset; j < Iterator<FlowField>::_flowField.getCellsY() + _highOffset; j++) {
                _leftWallStencil.applyLeftWall (Iterator<FlowField>::_flowField, _lowOffset, j);
            }
        }

        if (Iterator<FlowField>::_parameters.parallel.rightNb < 0){
            for (int j = _lowOffset; j < Iterator<FlowField>::_flowField.getCellsY() + _highOffset; j++) {
                _rightWallStencil.applyRightWall (Iterator<FlowField>::_flowField, Iterator<FlowField>::_flowField.getCellsX()+_highOffset-1,j);
            }
        }

        if (Iterator<FlowField>::_parameters.parallel.bottomNb < 0){
            for (int i = _lowOffset; i < Iterator<FlowField>::_flowField.getCellsX() + _highOffset; i++) {
                _bottomWallStencil.applyBottomWall (Iterator<FlowField>::_flowField, i, _lowOffset);
            }
        }

        if (Iterator<FlowField>::_parameters.parallel.topNb < 0){
            for (int i = _lowOffset; i < Iterator<FlowField>::_flowField.getCellsX() + _highOffset; i++) {
                _topWallStencil.applyTopWall (Iterator<FlowField>::_flowField, i, Iterator<FlowField>::_flowField.getCellsY()+_highOffset-1);
            }
        }
    }

    if (Iterator<FlowField>::_parameters.geometry.dim == 3){

        if (Iterator<FlowField>::_parameters.parallel.leftNb < 0){
            for (int j = _lowOffset; j < Iterator<FlowField>::_flowField.getCellsY()+_highOffset; j++) {
                for (int k = _lowOffset; k < Iterator<FlowField>::_flowField.getCellsZ()+_highOffset; k++) {
                    _leftWallStencil.applyLeftWall   ( Iterator<FlowField>::_flowField, _lowOffset, j, k );
                }
            }
        }

        if (Iterator<FlowField>::_parameters.parallel.rightNb < 0){
            for (int j = _lowOffset; j < Iterator<FlowField>::_flowField.getCellsY()+_highOffset; j++) {
                for (int k = _lowOffset; k < Iterator<FlowField>::_flowField.getCellsZ()+_highOffset; k++) {
                    _rightWallStencil.applyRightWall (Iterator<FlowField>::_flowField, Iterator<FlowField>::_flowField.getCellsX()+_highOffset-1, j, k);
                }
            }
        }

        if (Iterator<FlowField>::_parameters.parallel.bottomNb < 0){
            for (int i = _lowOffset; i < Iterator<FlowField>::_flowField.getCellsX()+_highOffset; i++) {
                for (int k = _lowOffset; k < Iterator<FlowField>::_flowField.getCellsZ()+_highOffset; k++) {
                    _bottomWallStencil.applyBottomWall (Iterator<FlowField>::_flowField, i, _lowOffset, k);
                }
            }
        }

        if (Iterator<FlowField>::_parameters.parallel.topNb < 0){
            for (int i = _lowOffset; i < Iterator<FlowField>::_flowField.getCellsX()+_highOffset; i++) {
                for (int k = _lowOffset; k < Iterator<FlowField>::_flowField.getCellsZ()+_highOffset; k++) {
                    _topWallStencil.applyTopWall (Iterator<FlowField>::_flowField, i, Iterator<FlowField>::_flowField.getCellsY()+_highOffset-1, k);
                }
            }
        }

        if (Iterator<FlowField>::_parameters.parallel.frontNb < 0){
            for (int i = _lowOffset; i < Iterator<FlowField>::_flowField.getCellsX()+_highOffset; i++) {
                for (int j = _lowOffset; j < Iterator<FlowField>::_flowField.getCellsY()+_highOffset; j++) {
                    _frontWallStencil.applyFrontWall (Iterator<FlowField>::_flowField, i, j, _lowOffset);
                }
            }
        }

        if (Iterator<FlowField>::_parameters.parallel.backNb < 0){
            for (int i = _lowOffset; i < Iterator<FlowField>::_flowField.getCellsX()+_highOffset; i++) {
                for (int j = _lowOffset; j < Iterator<FlowField>::_flowField.getCellsY()+_highOffset; j++) {
                    _backWallStencil.applyBackWall (Iterator<FlowField>::_flowField, i, j, Iterator<FlowField>::_flowField.getCellsZ()+_highOffset-1);
                }
            }
        }
    }
}

template <class FlowField>
ParallelBoundaryIterator<FlowField>::ParallelBoundaryIterator (FlowField & flowField,
                                                               const Parameters & parameters,
                                                               BoundaryStencil<FlowField> & stencil,
                                                               int lowOffset, int highOffset):
    Iterator<FlowField>(flowField,parameters), _stencil(stencil),
    _lowOffset(lowOffset), _highOffset(highOffset){}

template<class FlowField>
void ParallelBoundaryIterator<FlowField>::iterate () {

    if (Iterator<FlowField>::_parameters.geometry.dim == 2){

        if (Iterator<FlowField>::_parameters.parallel.leftNb >= 0){
            for (int j = _lowOffset; j < Iterator<FlowField>::_flowField.getCellsY() + _highOffset; j++) {
                _stencil.applyLeftWall (Iterator<FlowField>::_flowField, _lowOffset, j);
            }
        }

        if (Iterator<FlowField>::_parameters.parallel.rightNb >= 0){
            for (int j = _lowOffset; j < Iterator<FlowField>::_flowField.getCellsY() + _highOffset; j++) {
                _stencil.applyRightWall (Iterator<FlowField>::_flowField, Iterator<FlowField>::_flowField.getCellsX()+_highOffset-1,j);
            }
        }

        if (Iterator<FlowField>::_parameters.parallel.bottomNb >= 0){
            for (int i = _lowOffset; i < Iterator<FlowField>::_flowField.getCellsX() + _highOffset; i++) {
                _stencil.applyBottomWall (Iterator<FlowField>::_flowField, i, _lowOffset);
            }
        }

        if (Iterator<FlowField>::_parameters.parallel.topNb >= 0){
            for (int i = _lowOffset; i < Iterator<FlowField>::_flowField.getCellsX() + _highOffset; i++) {
                _stencil.applyTopWall (Iterator<FlowField>::_flowField, i, Iterator<FlowField>::_flowField.getCellsY()+_highOffset-1);
            }
        }
    }

    if (Iterator<FlowField>::_parameters.geometry.dim == 3){

        if (Iterator<FlowField>::_parameters.parallel.leftNb >= 0){
            for (int j = _lowOffset; j < Iterator<FlowField>::_flowField.getCellsY()+_highOffset; j++) {
                for (int k = _lowOffset; k < Iterator<FlowField>::_flowField.getCellsZ()+_highOffset; k++) {
                    _stencil.applyLeftWall   ( Iterator<FlowField>::_flowField, _lowOffset, j, k );
                }
            }
        }

        if (Iterator<FlowField>::_parameters.parallel.rightNb >= 0){
            for (int j = _lowOffset; j < Iterator<FlowField>::_flowField.getCellsY()+_highOffset; j++) {
                for (int k = _lowOffset; k < Iterator<FlowField>::_flowField.getCellsZ()+_highOffset; k++) {
                    _stencil.applyRightWall (Iterator<FlowField>::_flowField, Iterator<FlowField>::_flowField.getCellsX()+_highOffset-1, j, k);
                }
            }
        }

        if (Iterator<FlowField>::_parameters.parallel.bottomNb >= 0){
            for (int i = _lowOffset; i < Iterator<FlowField>::_flowField.getCellsX()+_highOffset; i++) {
                for (int k = _lowOffset; k < Iterator<FlowField>::_flowField.getCellsZ()+_highOffset; k++) {
                    _stencil.applyBottomWall (Iterator<FlowField>::_flowField, i, _lowOffset, k);
                }
            }
        }

        if (Iterator<FlowField>::_parameters.parallel.topNb >= 0){
            for (int i = _lowOffset; i < Iterator<FlowField>::_flowField.getCellsX()+_highOffset; i++) {
                for (int k = _lowOffset; k < Iterator<FlowField>::_flowField.getCellsZ()+_highOffset; k++) {
                    _stencil.applyTopWall (Iterator<FlowField>::_flowField, i, Iterator<FlowField>::_flowField.getCellsY()+_highOffset-1, k);
                }
            }
        }

        if (Iterator<FlowField>::_parameters.parallel.frontNb >= 0){
            for (int i = _lowOffset; i < Iterator<FlowField>::_flowField.getCellsX()+_highOffset; i++) {
                for (int j = _lowOffset; j < Iterator<FlowField>::_flowField.getCellsY()+_highOffset; j++) {
                    _stencil.applyFrontWall (Iterator<FlowField>::_flowField, i, j, _lowOffset);
                }
            }
        }

        if (Iterator<FlowField>::_parameters.parallel.backNb >= 0){
            for (int i = _lowOffset; i < Iterator<FlowField>::_flowField.getCellsX()+_highOffset; i++) {
                for (int j = _lowOffset; j < Iterator<FlowField>::_flowField.getCellsY()+_highOffset; j++) {
                    _stencil.applyBackWall (Iterator<FlowField>::_flowField, i, j, Iterator<FlowField>::_flowField.getCellsZ()+_highOffset-1);
                }
            }
        }
    }
}


text:
namespace {

const int testint = 2093847192;
const std::string teststr("Hello world"); // note non-aligned string length
const std::wstring testwstr(L"Hello, world");
const char testdata[] = "AAA\0BBB\0";
const int testdatalen = arraysize(testdata) - 1;
const bool testbool1 = false;
const bool testbool2 = true;

// checks that the result
void VerifyResult(const Pickle& pickle) {
  void* iter = NULL;

  int outint;
  EXPECT_TRUE(pickle.ReadInt(&iter, &outint));
  EXPECT_EQ(testint, outint);

  std::string outstr;
  EXPECT_TRUE(pickle.ReadString(&iter, &outstr));
  EXPECT_EQ(teststr, outstr);

  std::wstring outwstr;
  EXPECT_TRUE(pickle.ReadWString(&iter, &outwstr));
  EXPECT_EQ(testwstr, outwstr);

  bool outbool;
  EXPECT_TRUE(pickle.ReadBool(&iter, &outbool));
  EXPECT_EQ(testbool1, outbool);
  EXPECT_TRUE(pickle.ReadBool(&iter, &outbool));
  EXPECT_EQ(testbool2, outbool);

  const char* outdata;
  int outdatalen;
  EXPECT_TRUE(pickle.ReadData(&iter, &outdata, &outdatalen));
  EXPECT_EQ(testdatalen, outdatalen);
  EXPECT_EQ(memcmp(testdata, outdata, outdatalen), 0);

  EXPECT_TRUE(pickle.ReadData(&iter, &outdata, &outdatalen));
  EXPECT_EQ(testdatalen, outdatalen);
  EXPECT_EQ(memcmp(testdata, outdata, outdatalen), 0);

  // reads past the end should fail
  EXPECT_FALSE(pickle.ReadInt(&iter, &outint));
}

}  // namespace

TEST(PickleTest, EncodeDecode) {
  Pickle pickle;

  EXPECT_TRUE(pickle.WriteInt(testint));
  EXPECT_TRUE(pickle.WriteString(teststr));
  EXPECT_TRUE(pickle.WriteWString(testwstr));
  EXPECT_TRUE(pickle.WriteBool(testbool1));
  EXPECT_TRUE(pickle.WriteBool(testbool2));
  EXPECT_TRUE(pickle.WriteData(testdata, testdatalen));

  // Over allocate BeginWriteData so we can test TrimWriteData.
  char* dest = pickle.BeginWriteData(testdatalen + 100);
  EXPECT_TRUE(dest);
  memcpy(dest, testdata, testdatalen);

  pickle.TrimWriteData(testdatalen);

  VerifyResult(pickle);

  // test copy constructor
  Pickle pickle2(pickle);
  VerifyResult(pickle2);

  // test operator=
  Pickle pickle3;
  pickle3 = pickle;
  VerifyResult(pickle3);
}

TEST(PickleTest, ZeroLenStr) {
  Pickle pickle;
  EXPECT_TRUE(pickle.WriteString(""));

  void* iter = NULL;
  std::string outstr;
  EXPECT_TRUE(pickle.ReadString(&iter, &outstr));
  EXPECT_EQ("", outstr);
}

TEST(PickleTest, ZeroLenWStr) {
  Pickle pickle;
  EXPECT_TRUE(pickle.WriteWString(L""));

  void* iter = NULL;
  std::string outstr;
  EXPECT_TRUE(pickle.ReadString(&iter, &outstr));
  EXPECT_EQ("", outstr);
}

TEST(PickleTest, BadLenStr) {
  Pickle pickle;
  EXPECT_TRUE(pickle.WriteInt(-2));

  void* iter = NULL;
  std::string outstr;
  EXPECT_FALSE(pickle.ReadString(&iter, &outstr));
}

TEST(PickleTest, BadLenWStr) {
  Pickle pickle;
  EXPECT_TRUE(pickle.WriteInt(-1));

  void* iter = NULL;
  std::wstring woutstr;
  EXPECT_FALSE(pickle.ReadWString(&iter, &woutstr));
}

TEST(PickleTest, FindNext) {
  Pickle pickle;
  EXPECT_TRUE(pickle.WriteInt(1));
  EXPECT_TRUE(pickle.WriteString("Domo"));

  const char* start = reinterpret_cast<const char*>(pickle.data());
  const char* end = start + pickle.size();

  EXPECT_TRUE(end == Pickle::FindNext(pickle.header_size_, start, end));
  EXPECT_TRUE(NULL == Pickle::FindNext(pickle.header_size_, start, end - 1));
  EXPECT_TRUE(end == Pickle::FindNext(pickle.header_size_, start, end + 1));
}

TEST(PickleTest, IteratorHasRoom) {
  Pickle pickle;
  EXPECT_TRUE(pickle.WriteInt(1));
  EXPECT_TRUE(pickle.WriteInt(2));

  const void* iter = 0;
  EXPECT_FALSE(pickle.IteratorHasRoomFor(iter, 1));
  iter = pickle.payload();
  EXPECT_TRUE(pickle.IteratorHasRoomFor(iter, 0));
  EXPECT_TRUE(pickle.IteratorHasRoomFor(iter, 1));
  EXPECT_FALSE(pickle.IteratorHasRoomFor(iter, -1));
  EXPECT_TRUE(pickle.IteratorHasRoomFor(iter, sizeof(int) * 2));
  EXPECT_FALSE(pickle.IteratorHasRoomFor(iter, (sizeof(int) * 2) + 1));
}

TEST(PickleTest, Resize) {
  size_t unit = Pickle::kPayloadUnit;
  scoped_array<char> data(new char[unit]);
  char* data_ptr = data.get();
  for (size_t i = 0; i < unit; i++)
    data_ptr[i] = 'G';

  // construct a message that will be exactly the size of one payload unit,
  // note that any data will have a 4-byte header indicating the size
  const size_t payload_size_after_header = unit - sizeof(uint32_t);
  Pickle pickle;
  pickle.WriteData(data_ptr,
      static_cast<int>(payload_size_after_header - sizeof(uint32_t)));
  size_t cur_payload = payload_size_after_header;

  // note: we assume 'unit' is a power of 2
  EXPECT_EQ(unit, pickle.capacity());
  EXPECT_EQ(pickle.payload_size(), payload_size_after_header);

  // fill out a full page (noting data header)
  pickle.WriteData(data_ptr, static_cast<int>(unit - sizeof(uint32_t)));
  cur_payload += unit;
  EXPECT_EQ(unit * 2, pickle.capacity());
  EXPECT_EQ(cur_payload, pickle.payload_size());

  // one more byte should double the capacity
  pickle.WriteData(data_ptr, 1);
  cur_payload += 5;
  EXPECT_EQ(unit * 4, pickle.capacity());
  EXPECT_EQ(cur_payload, pickle.payload_size());
}

namespace {

struct CustomHeader : Pickle::Header {
  int blah;
};

}  // namespace

TEST(PickleTest, HeaderPadding) {
  const uint32_t kMagic = 0x12345678;

  Pickle pickle(sizeof(CustomHeader));
  pickle.WriteInt(kMagic);

  // this should not overwrite the 'int' payload
  pickle.headerT<CustomHeader>()->blah = 10;

  void* iter = NULL;
  int result;
  ASSERT_TRUE(pickle.ReadInt(&iter, &result));

  EXPECT_EQ(static_cast<uint32_t>(result), kMagic);
}

TEST(PickleTest, EqualsOperator) {
  Pickle source;
  source.WriteInt(1);

  Pickle copy_refs_source_buffer(static_cast<const char*>(source.data()),
                                 source.size());
  Pickle copy;
  copy = copy_refs_source_buffer;
  ASSERT_EQ(source.size(), copy.size());
}