text:
function ParseWranglerFile (job_id) {
  WranglerFileJob.call(this, job_id);
}
ParseWranglerFile.prototype = Object.create(WranglerFileJob.prototype);
ParseWranglerFile.prototype.constructor = ParseWranglerFile;

ParseWranglerFile.prototype.run = function () {
  var self = this;

  WranglerFiles.update(this.wranglerFile._id, {
    $set: {
      status: "processing",
    },
    $unset: {
      error_description: true,
    }
  });

  // get a sample of the text inside the blob, as well as the number of lines
  // of blob
  var textSample = {}; // so that textSample.promise will be undefined
  if (!self.wranglerFile.blob_text_sample) {
    textSample = Q.defer();
    getBlobTextSample(self.blob)
      .then(Meteor.bindEnvironment(function (setObject) {
        WranglerFiles.update(self.wranglerFile._id, {
          $set: setObject
        });
        textSample.resolve("hello");
      }, textSample.reject));
  }

  var deferred = Q.defer();
  Q.when(textSample.promise)
    .then(Meteor.bindEnvironment(function (first) {
      // try to guess options that have not been manually specified
      var options = self.wranglerFile.options;
      if (options === undefined) {
        options = {};
      }
      function setFileOptions(newOptions) {
        _.extend(options, newOptions); // keeps `options` up to date
        WranglerFiles.update(self.wranglerFile._id, {
          $set: {
            "options": options
          }
        });
      }

      // for guesses of file name
      var blobName = self.blob.original.name;
      function extensionEquals(extension) {
        return blobName.slice(-extension.length) === extension;
      }

      // try to guess file_type
      if (!options.file_type) {
        if (blobName.match(/\.rsem\.genes\.[a-z_]*\.(hugo\.|)tab/g)) {
          // http://regexr.com/3d9i7
          setFileOptions({ file_type: "RectGenomicExpression" });
        } else if (blobName.match(/\.gmt$/g)) {
          setFileOptions({ file_type: "GeneSetGroup" });
        }
      }

      // // try to guess normalization
      // if (!options.normalization) {
      //   // try to guess normalization
      //   if (blobName.match(/raw_counts/g)) {
      //     setFileOptions({ normalization: "raw_counts" });
      //   } else if (blobName.match(/norm_counts/g)) {
      //     setFileOptions({ normalization: "quantile_counts" });
      //   } else if (blobName.match(/norm_tpm/g)) {
      //     setFileOptions({ normalization: "tpm" });
      //   } else if (blobName.match(/norm_fpkm/g)) {
      //     setFileOptions({ normalization: "fpkm" });
      //   }
      // }

      if (self.blob.metadata && self.blob.metadata.wrangler_file_options) {
        setFileOptions(self.blob.metadata.wrangler_file_options);
      }

      // we can now show the options to the user
      WranglerFiles.update(self.wranglerFile._id, {
        $set: { parsed_options_once_already: true }
      });

      // make sure we've got a file_type
      if (!options.file_type) {
        throw "File type could not be inferred. " +
            "Please manually select a file type";
      }

      var fileHandlerClass = WranglerFileHandlers[options.file_type];
      if (!fileHandlerClass) {
        throw new Error("file handler not yet defined (" + options.file_type +
            ")");
      }

      // figure out which FileHandler to create
      var fileHandler = new fileHandlerClass(self.wranglerFile._id);

      // make sure the options match the schema
      var optionsSchema = Wrangler.fileTypes[options.file_type].schema;
      if (!optionsSchema.newContext().validate(_.omit(options, "file_type"))) {
        throw "Invalid options";
      }

      fileHandler.parse()
        .then(Meteor.bindEnvironment(function () {
          WranglerFiles.update(self.wranglerFile._id, {
            $set: {
              status: "done",
            }
          });

          deferred.resolve();
        }, deferred.reject))
        .catch(deferred.reject);
    }, deferred.reject))
    .catch(deferred.reject);

  return deferred.promise;
};
ParseWranglerFile.prototype.onError = function (error) {
  var error_description = error.toString();
  var status = "done";
  if (error.stack) {
    error_description = "Internal error encountered while parsing file";
    status = "error";
  }

  WranglerFiles.update(this.job.args.wrangler_file_id, {
    $set: {
      status: status,
      error_description: error_description,
    }
  });
};

JobClasses.ParseWranglerFile = ParseWranglerFile;


text:
Since Kubernetes services changed to assign a single IP address to each service, it is
now possible to use DNS to resolve a DNS name directly to a Kubernetes service, which
would then use Kubernetes' proxy to connect to an appropriate pod running the application
pointed to by the service definition.

## How it Works
Version 2.0.1a of [SkyDNS](https://github.com/skynetservices/skydns) added a change that
allows it to poll the Kubernetes API looking for changes to the service definitions.  Newly
added services are published in SkyDNS, and removed services are deleted from SkyDNS's
internal registry.

### Concrete Example
If you run the Guestbook example in the Kubernetes repository, you'll end up with a service
called `redismaster`.  If you were also running SkyDNS with the `-kubernetes=true` flag and
`-master=http://my.kubernetes.master:8080` you would immediately be able to run queries against
the SkyDNS server for the `redismaster` service.  By default, SkyDNS is authoratative for the
domain `skydns.local`, so a query to the SkyDNS server requesting redismaster.skydns.local will
return the IP Address of the `redismaster` service.

## Configuration
SkyDNS allows you to change the domain name that it will resolve by passing in a domain on the
command line using `-domain=mydomain.com` or by setting an environment variable `SKYDNS_DOMAIN`.

If you change the Docker daemon on your Kubernetes minions to use SkyDNS for domain name resolution,
your pods will all be able to connect to services via DNS instead of using environment variables
or other configuration methods.  To change Docker to use SkyDNS resolution, add `--dns=ip.of.skydns.server`
to the Docker startup command.
```
docker -d --dns=10.2.0.5 ...
```

SkyDNS uses the etcd instance in Kubernetes as its storage backend, which means that you can run
multiple SkyDNS daemons if you wish to have more than one resolver on your cluster.  You could run
a SkyDNS instance on each node in your Kubernetes cluster, and set Docker to use 127.0.0.1 as the
DNS resolver.

## Starting SkyDNS in a Kubernetes Cluster
At a minimum, you need to provide the `-kubernetes` flag, and the `-master=http://my.kubernetes.master.ip:8080`
flag when you start SkyDNS.  You may also wish to use `-domain=mydomain.com` to change the domain that
SkyDNS resolves.

SkyDNS can act as your external resolver, too.  If you set your domain to use the external IP address of
the server running SkyDNS and bind SkyDNS to listen on all interfaces, SkyDNS will serve DNS for
your domain.  You could then use a mixture of manually created hosts in SkyDNS and Kubernetes service
resolution to serve your various DNS endpoints.  A simple example might be to run a Wordpress pod in Kubernetes
and create a service called `blog` in Kubernetes.  Then external DNS requests to `blog.mydomain.com` will
automatically resolve to the service proxy and be forwarded to the pods running Wordpress.

Full documentation of the SkyDNS server is in the [SkyDNS repository](https://github.com/skynetservices/skydns)
and abbreviated information is available by typing `skydns --help`.

redpajama_set_name: RedPajamaGithub


text:
package io.quarkus.it.jpa.derby;

import io.quarkus.test.junit.QuarkusIntegrationTest;

/**
 * Test various JPA operations running in native mode
 */
@QuarkusIntegrationTest
public class JPAFunctionalityInGraalITCase extends JPAFunctionalityTest {

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Abstraction (Java Machine Learning Library 0.1.7)</title>
<meta name="date" content="2012-07-09">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

net.sf.javaml.distance.fastdtw

Class Abstraction

java.lang.Object

net.sf.javaml.distance.AbstractDistance

net.sf.javaml.distance.fastdtw.Abstraction

All Implemented Interfaces:

java.io.Serializable, DistanceMeasure

public class Abstraction
extends AbstractDistance

Author:

Thomas Abeel (thomas@abeel.be), Stan Salvador, stansalvador@hotmail.com

See Also:

Serialized Form

Constructor Summary

Constructors

Constructor and Description

Abstraction(int radius)

Method Summary

Methods

Modifier and Type
Method and Description

static void
main(java.lang.String[] args)

double
measure(Instance x,
       Instance y)

Calculates the distance between two instances.

Methods inherited from class net.sf.javaml.distance.AbstractDistance

compare, getMaxValue, getMinValue

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Abstraction

public Abstraction(int radius)

Method Detail

measure

public double measure(Instance x,
             Instance y)

Description copied from interface: DistanceMeasure

Calculates the distance between two instances.

Returns:

the distance between the two instances

main

public static void main(java.lang.String[] args)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

			Copyright © 2006-2012 - Thomas Abeel - All Rights Reserved.


text:
'use strict';

var DocBlock = require('../../lib/docBlock');
var inspect = require('inspect.js');

describe('Generic rules', function() {
    describe('tags', function() {
        it('Should parse @module tag', function() {
            var docArray = [
                { tag: 'module', value: 'foo' }
            ];

            var docBlock = new DocBlock('js').create(docArray);
            inspect(docBlock).hasProps({
                tags: {
                    module: 'foo'
                }
            });
        });

        it('Should parse @submodule tag', function() {
            var docArray = [
                { tag: 'submodule', value: 'foo' }
            ];

            var docBlock = new DocBlock('js').create(docArray);
            inspect(docBlock).hasProps({
                tags: {
                    submodule: 'foo'
                }
            });
        });

        it('Should parse @package tag', function() {
            var docArray = [
                { tag: 'package', value: 'foo' }
            ];

            var docBlock = new DocBlock('js').create(docArray);
            inspect(docBlock).hasProps({
                tags: {
                    'package': 'foo'
                }
            });
        });

        it('Should parse @subpackage tag', function() {
            var docArray = [
                { tag: 'subpackage', value: 'foo' }
            ];

            var docBlock = new DocBlock('js').create(docArray);
            inspect(docBlock).hasProps({
                tags: {
                    subpackage: 'foo'
                }
            });
        });

        it('Should parse @group tag', function() {
            var docArray = [
                { tag: 'group', value: 'foo' }
            ];

            var docBlock = new DocBlock('js').create(docArray);
            inspect(docBlock).hasProps({
                group: 'foo'
            });
        });

        it('Should parse @group tag with spaces in group name', function() {
            var docArray = [
                { tag: 'group', value: 'Foo group' }
            ];

            var docBlock = new DocBlock('js').create(docArray);
            inspect(docBlock).hasProps({
                group: 'Foo group'
            });
        });

        it('Should parse @name tag', function() {
            var docArray = [
                { tag: 'name', value: 'foo' }
            ];

            var docBlock = new DocBlock('js').create(docArray);
            inspect(docBlock).hasProps({
                name: 'foo'
            });
        });

        it('Should parse @type tag', function() {
            var docArray = [
                { tag: 'type', value: 'string' }
            ];

            var docBlock = new DocBlock('js').create(docArray);
            inspect(docBlock).hasProps({
                tags: {
                    type: 'string'
                }
            });
        });

        it('Should parse an @example tag', function() {
            var docArray = [
                { tag: 'example', value: '{js}\n var foo = \'bar\';' }
            ];

            var docBlock = new DocBlock('js').create(docArray);
            inspect(docBlock).hasProps({
                tags: {
                    examples: [{
                        type: 'js',
                        title: '',
                        content: 'var foo = \'bar\';'
                    }]
                }
            });
        });

        it('Should parse an @uninplemented tag', function() {
            var docArray = [
                { tag: 'unimplemented', value: '' }
            ];

            var docBlock = new DocBlock('js').create(docArray);
            inspect(docBlock).hasProps({
                tags: {
                    isUnimplemented: true
                }
            });
        });

        it('Should parse an @beta tag', function() {
            var docArray = [
                { tag: 'beta', value: '' }
            ];

            var docBlock = new DocBlock('js').create(docArray);
            inspect(docBlock).hasProps({
                tags: {
                    isBeta: true
                }
            });
        });

        it('Should parse an @new tag', function() {
            var docArray = [
                { tag: 'new', value: '' }
            ];

            var docBlock = new DocBlock('js').create(docArray);
            inspect(docBlock).hasProps({
                tags: {
                    isNew: true
                }
            });
        });

        it('Should parse a @link tag', function() {
            var docArray = [
                { tag: 'link', value: 'External link https://example.com' },
                { tag: 'link', value: 'http://www.foo.com' }
            ];

            var docBlock = new DocBlock('js').create(docArray);
            inspect(docBlock).hasProps({
                tags: {
                    links: [{
                        name: 'External link',
                        link: 'https://example.com'
                    }, {
                        name: '',
                        link: 'http://www.foo.com'
                    }]
                }
            });
        });

        it('Should parse @ignore tag', function() {
            var docArray = [
                { tag: 'ignore', value: '' }
            ];

            var docBlock = new DocBlock('js').create(docArray);
            inspect(docBlock).hasProps({
                tags: {
                    ignore: true
                }
            });
        });

        it('Should parse an @preview tag', function() {
            var docArray = [
                { tag: 'preview', value: '{js}\n
Preview
' }
            ];

            var docBlock = new DocBlock('js').create(docArray);
            inspect(docBlock).hasProps({
                tags: {
                    previews: [{
                        type: 'js',
                        name: '',
                        html: '
Preview
'
                    }]
                }
            });
        });

        it('Should parse a multiline @preview tag', function() {
            var docArray = [
                { tag: 'preview', value: '{js}\n
Preview
\nSubline' }
            ];

            var docBlock = new DocBlock('js').create(docArray);
            inspect(docBlock).hasProps({
                tags: {
                    previews: [{
                        type: 'js',
                        name: '',
                        html: '
Preview
\nSubline'
                    }]
                }
            });
        });

        it('Should parse an @preview tag without type and name', function() {
            var docArray = [
                { tag: 'preview', value: '\n
Preview
' }
            ];

            var docBlock = new DocBlock('js').create(docArray);
            inspect(docBlock).hasProps({
                tags: {
                    previews: [{
                        type: 'js',
                        name: '',
                        html: '
Preview
'
                    }]
                }
            });
        });
    });
});


text:
package org.zstack.appliancevm;

import org.zstack.header.core.workflow.Flow;

/**
 */
public interface ApplianceVmBootstrapFlowFactory {
    String getHypervisorTypeForApplianceVmBootstrapFlow();

    Flow createApplianceVmBootstrapInfoFlow();
}


text:
/* @LICENSE(MUSLC_MIT) */

#include <unistd.h>
#include "internal/syscall.h"

int symlink(const char *existing, const char *new)
{
	return syscall(SYS_symlink, existing, new);
}


text:
package org.apache.cassandra.service;

import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

import com.google.common.cache.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.io.util.RandomAccessReader;
import org.apache.cassandra.metrics.FileCacheMetrics;

public class FileCacheService
{
    private static final Logger logger = LoggerFactory.getLogger(FileCacheService.class);

    private static final long MEMORY_USAGE_THRESHOLD = DatabaseDescriptor.getFileCacheSizeInMB() * 1024L * 1024L;
    private static final int AFTER_ACCESS_EXPIRATION = 512; // in millis

    public static FileCacheService instance = new FileCacheService();

    private static final AtomicLong cacheKeyIdCounter = new AtomicLong();
    public static final class CacheKey
    {
        final long id;
        public CacheKey()
        {
            this.id = cacheKeyIdCounter.incrementAndGet();
        }
        public boolean equals(Object that)
        {
            return that instanceof CacheKey && ((CacheKey) that).id == this.id;
        }
        public int hashCode()
        {
            return (int) id;
        }
    }

    private static final Callable<CacheBucket> cacheForPathCreator = new Callable<CacheBucket>()
    {
        @Override
        public CacheBucket call()
        {
            return new CacheBucket();
        }
    };

    private static final AtomicInteger memoryUsage = new AtomicInteger();

    private final Cache<CacheKey, CacheBucket> cache;
    private final FileCacheMetrics metrics = new FileCacheMetrics();

    private static final class CacheBucket
    {
        final ConcurrentLinkedQueue<RandomAccessReader> queue = new ConcurrentLinkedQueue<>();
        volatile boolean discarded = false;
    }

    protected FileCacheService()
    {
        RemovalListener<CacheKey, CacheBucket> onRemove = new RemovalListener<CacheKey, CacheBucket>()
        {
            @Override
            public void onRemoval(RemovalNotification<CacheKey, CacheBucket> notification)
            {
                CacheBucket bucket = notification.getValue();
                if (bucket == null)
                    return;

                // set discarded before deallocating the readers, to ensure we don't leak any
                bucket.discarded = true;
                Queue<RandomAccessReader> q = bucket.queue;
                boolean first = true;
                for (RandomAccessReader reader = q.poll() ; reader != null ; reader = q.poll())
                {
                    if (logger.isDebugEnabled() && first)
                    {
                        logger.debug("Evicting cold readers for {}", reader.getPath());
                        first = false;
                    }
                    memoryUsage.addAndGet(-1 * reader.getTotalBufferSize());
                    reader.deallocate();
                }
            }
        };

        cache = CacheBuilder.newBuilder()
                .expireAfterAccess(AFTER_ACCESS_EXPIRATION, TimeUnit.MILLISECONDS)
                .concurrencyLevel(DatabaseDescriptor.getConcurrentReaders())
                .removalListener(onRemove)
                .initialCapacity(16 << 10)
                .build();
    }

    public RandomAccessReader get(CacheKey key)
    {
        metrics.requests.mark();

        CacheBucket bucket = getCacheFor(key);
        RandomAccessReader result = bucket.queue.poll();
        if (result != null)
        {
            metrics.hits.mark();
            memoryUsage.addAndGet(-result.getTotalBufferSize());
        }

        return result;
    }

    private CacheBucket getCacheFor(CacheKey key)
    {
        try
        {
            return cache.get(key, cacheForPathCreator);
        }
        catch (ExecutionException e)
        {
            throw new AssertionError(e);
        }
    }

    @SuppressWarnings("resource")
    public void put(CacheKey cacheKey, RandomAccessReader instance)
    {
        int memoryUsed = memoryUsage.get();
        if (logger.isTraceEnabled())
            logger.trace("Estimated memory usage is {} compared to actual usage {}", memoryUsed, sizeInBytes());

        CacheBucket bucket = cache.getIfPresent(cacheKey);
        if (memoryUsed >= MEMORY_USAGE_THRESHOLD || bucket == null)
        {
            instance.deallocate();
        }
        else
        {
            memoryUsage.addAndGet(instance.getTotalBufferSize());
            bucket.queue.add(instance);
            if (bucket.discarded)
            {
                RandomAccessReader reader = bucket.queue.poll();
                if (reader != null)
                {
                    memoryUsage.addAndGet(-1 * reader.getTotalBufferSize());
                    reader.deallocate();
                }
            }
        }
    }

    public void invalidate(CacheKey cacheKey, String path)
    {
        if (logger.isDebugEnabled())
            logger.debug("Invalidating cache for {}", path);
        cache.invalidate(cacheKey);
    }

    // TODO: this method is unsafe, as it calls getTotalBufferSize() on items that can have been discarded
    public long sizeInBytes()
    {
        long n = 0;
        for (CacheBucket bucket : cache.asMap().values())
            for (RandomAccessReader reader : bucket.queue)
                n += reader.getTotalBufferSize();
        return n;
    }
}


text:
import _ from 'underscore';
import $ from 'jquery';

console.log(_.flatten([[1], [2], [3]]));

export default function bike1() {
  $("body").append("Bikes");
};


text:
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="PATH_TO_PLUGIN/jump.js"></script>
$('#map_canvas').jump({'credentials': 'AvOW5Fz4QTsubTTdmaVnseeZnAQ0JYwbx_6zdMdgHk6iF-pnoTE7vojUFJ1kXFTP', 'enableSearchLogo': false }, function() {
	var self = this;
	$.getJSON( YOUR_URL, function(response) {
		$.each( response.SOME_ARRAY, function(i, obj) {
			var location = new Microsoft.Maps.Location(obj.lat, obj.lng);
			self.addMarker({ 'location': location, 'bounds': true, 'title': obj.title } )
			.click(function() {
				self.openInfoWindow({
					'title': this.target.title //'GET THE PROPERTY BY this.target.YOUR_PROPERTY'
				}, this);
			});
		});
	});
});


text:
package org.rioproject.system.measurable;

import com.sun.jini.config.Config;
import net.jini.config.Configuration;
import net.jini.config.ConfigurationException;
import org.rioproject.costmodel.ResourceCost;
import org.rioproject.costmodel.ResourceCostModel;
import org.rioproject.costmodel.ResourceCostProducer;
import org.rioproject.costmodel.ZeroCostModel;
import org.rioproject.sla.SLA;
import org.rioproject.system.MeasuredResource;
import org.rioproject.watch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * A MeasurableCapability refers to a depletion oriented resource or capability on
 * a ComputeResource
 *
 * @author Dennis Reedy
 */
public abstract class MeasurableCapability extends PeriodicWatch implements ResourceCostProducer,
                                                                            MeasurableCapabilityMBean {
    /**
     * Collection of secondary ThresholdManager instances
     */
    private final Collection<ThresholdManager> thresholdManagers = new ArrayList<ThresholdManager>();
    /**
     * The SLA for the MeasurableCapability
     */
    private SLA sla;
    /**
     * The ResourceCostModel, determining how to charge for use of the
     * MeasurableCapability
     */
    private ResourceCostModel costModel;
    /**
     * The sampleSize property specifies the amount of samples the
     * MeasurableCapability will accumulate in the period defined by the reportRate
     * in order to produce a result.
     */
    protected int sampleSize = 1;
    /** Configuration object */
    private Configuration config;
    /** Whether or not this measurable capability is enabled */
    private AtomicBoolean isEnabled = new AtomicBoolean(true);

    /** The {@link MeasurableMonitor} to use */
    protected MeasurableMonitor monitor;

    protected MeasuredResource lastMeasured;
    /** Defines the default history size */
    public final static int DEFAULT_COLLECTION_SIZE = 10;
    /** Defines the default history max size */
    public final static int MAX_COLLECTION_SIZE = 100;
    private int collectionSize;
    private static final Logger logger = LoggerFactory.getLogger(MeasurableCapability.class);

    protected MeasurableCapability(String id, String componentName, Configuration config) {
        super(id, config);
        this.config = config;
        try {
            isEnabled.set((Boolean) config.getEntry(componentName, "enabled", boolean.class, Boolean.TRUE));
        } catch (ConfigurationException e) {
            logger.error("Getting WatchDataSource Size", e);
        }
        if(!isEnabled.get())
            return;

        try {
            collectionSize = Config.getIntEntry(config, componentName,
                                                "collectionSize",
                                                DEFAULT_COLLECTION_SIZE,
                                                1,
                                                MAX_COLLECTION_SIZE);
        } catch(ConfigurationException e) {
            if(logger.isTraceEnabled())
            logger.trace("Getting WatchDataSource collection size", e);
            collectionSize = DEFAULT_COLLECTION_SIZE;
        }
        try {
            WatchDataSource wds = (WatchDataSource)config.getEntry(componentName,
                                                                   "watchDataSource",
                                                                   WatchDataSource.class,
                                                                   null);
            if(wds!=null) {
                doSetWatchDataSource(wds);
            }
        } catch (ConfigurationException e) {
            logger.error("Getting WatchDataSource Size", e);
        }
        if(localRef!=null)
            localRef.setMaxSize(collectionSize);
    }

    public void addWatchDataReplicator(WatchDataReplicator replicator) {
        if(localRef!=null) {
            localRef.addWatchDataReplicator(replicator);
        } else {
            try {
                watchDataSource.addWatchDataReplicator(replicator);
            } catch (RemoteException e) {
                logger.error("Could not add WatchDataReplicator", e);
            }
        }
    }

    protected void setEnabled(boolean enabled) {
        this.isEnabled.set(enabled);
    }

    /**
     * Get is this measurable capability is enabled
     *
     * @return If the measurable capability is enabled return true, otherwise
     * false. If the measurable capability is not enabled, it will not be added
     */
    public boolean isEnabled() {
        return isEnabled.get();
    }

    private void checkEnabled() {
        if(!isEnabled.get())
            throw new IllegalStateException("The MeasurableCapability ["+getId()+"] is not enabled");
    }

    /**
     * Get the Configuration property
     *
     * @return The configuration for the MeasurableCapability
     */
    public Configuration getConfiguration() {
        return(config);
    }

    /**
     * Override parent's setWatchDataSource to set the size
     */
    @Override
    public void setWatchDataSource(WatchDataSource watchDataSource) {
        doSetWatchDataSource(watchDataSource);
    }

    private void doSetWatchDataSource(WatchDataSource watchDataSource) {
        checkEnabled();
        super.setWatchDataSource(watchDataSource);
        if(watchDataSource!=null) {
            try {
                watchDataSource.setMaxSize(collectionSize);
            } catch(Exception e) {
                logger.error("Setting WatchDataSource Size", e);
            }
        }
    }

    /**
     * Set the SLA for ths MeasurableCapability.
     *
     * @param sla The SLA for this MeasurableCapability
     */
    public void setSLA(SLA sla) {
        checkEnabled();
        if(sla == null)
            throw new IllegalArgumentException("sla is null");
        this.sla = sla;
        getThresholdManager().setThresholdValues(sla);
    }

    /**
     * Get the SLA for ths MeasurableCapability.
     *
     * @return The SLA for this MeasurableCapability
     */
    public SLA getSLA() {
        return(sla);
    }

    /**
     * @see org.rioproject.system.measurable.MeasurableCapabilityMBean#setSampleSize
     */
    public void setSampleSize(int sampleSize) {
        checkEnabled();
        this.sampleSize = sampleSize;
    }

    /**
     * @see org.rioproject.system.measurable.MeasurableCapabilityMBean#getSampleSize()
     */
    public int getSampleSize() {
        return(sampleSize);
    }

    /**
     * Add a secondary ThresholdManager to the MeasurableCapability. The primary
     * ThresholdManager and the ThresholdValues are set when this class is loaded.
     * By offering secondary ThresholdManager instances, services can set their own
     * ranges and be notified accordingly
     *
     * @param thresholdManager The ThresholdManager
     */
    public void addSecondaryThresholdManager(ThresholdManager thresholdManager) {
        checkEnabled();
        if(thresholdManager==null)
            throw new IllegalArgumentException("thresholdManager is null");
        thresholdManagers.add(thresholdManager);
    }

    /**
     * Remove a secondary ThresholdManager from the MeasurableCapability
     *
     * @param thresholdManager The ThresholdManager
     */
    public void removeSecondaryThresholdManager(ThresholdManager thresholdManager) {
        if(thresholdManager!=null)
            thresholdManagers.remove(thresholdManager);
    }

    /**
     * Set the ResourceCostModel for the MeasurableCapability
     *
     * @param costModel The ResourceCostModel which will determine the cost of
     * using this MeasurableCapability
     */
    public void setResourceCostModel(ResourceCostModel costModel) {
        checkEnabled();
        if(costModel==null)
            throw new IllegalArgumentException("costModel is null");
        this.costModel = costModel;
    }

    /**
     * @see org.rioproject.costmodel.ResourceCostProducer#calculateResourceCost
     */
    public ResourceCost calculateResourceCost(double units, long duration) {
        checkEnabled();
        if(costModel==null)
            costModel = new ZeroCostModel();
        double cost = costModel.getCostPerUnit(duration)*units;
        return(new ResourceCost(getId(),
                                cost,
                                units,
                                costModel.getDescription(),
                                new Date(System.currentTimeMillis())));
    }

    /**
     * Get the MeasuredResource object, which represents this object's measured
     * capability
     *
     * @return This object's measured capability
     */
    public MeasuredResource getMeasuredResource() {
        checkEnabled();
        if(lastMeasured==null)
            checkValue();

        return lastMeasured;
    }

    protected void setLastMeasuredResource(MeasuredResource lastMeasured) {
        this.lastMeasured = lastMeasured;
    }

    /**
     * Set the {@link MeasurableMonitor}
     *
     * @param monitor The MeasurableMonitor
     */
    public void setMeasurableMonitor(MeasurableMonitor monitor) {
        this.monitor = monitor;
        this.monitor.setID(getId());
        this.monitor.setThresholdValues(getThresholdValues());
    }

    /**
     * Add a Calculable to the watch and update state
     *
     * @param record A Calculable record
     */
    public void addWatchRecord(Calculable record) {
        checkEnabled();
        super.addWatchRecord(record);
        for (ThresholdManager tManager : getThresholdManagers())
            tManager.checkThreshold(record);
    }

    /**
     * Get the registered {@link ThresholdManager}s
     *
     * @return The registered {@link ThresholdManager}s. A new unmodifiable collection is allocated each time
     */
    protected Collection<ThresholdManager> getThresholdManagers() {
        Collection<ThresholdManager> tMgrs;
        synchronized(thresholdManagers) {
            tMgrs = Collections.unmodifiableCollection(thresholdManagers);
        }
        return tMgrs;
    }

}


text:
import numpy as np
import sys

from .base import Prox
from .build.prox import ProxEqualityDouble as _ProxEqualityDouble
from .build.prox import ProxEqualityFloat as _ProxEqualityFloat

__author__ = 'Stephane Gaiffas'

dtype_map = {
    np.dtype("float64"): _ProxEqualityDouble,
    np.dtype("float32"): _ProxEqualityFloat
}

class ProxEquality(Prox):
    """Projection operator onto the set of vector with all coordinates equal
    (or in the given range if given one).
    Namely, this simply replaces all coordinates by their average

    Parameters
    ----------
    strength : `float`, default=0.
        Not used in this prox, but kept for compatibility issues

    range : `tuple` of two `int`, default=`None`
        Range on which the prox is applied. If `None` then the prox is
        applied on the whole vector

    positive : `bool`, default=`False`
        If True, ensures that the output of the prox has only non-negative
        entries (in the given range)

    Attributes
    ----------
    dtype : `{'float64', 'float32'}`
        Type of the arrays used.
    """

    _attrinfos = {"positive": {"writable": True, "cpp_setter": "set_positive"}}

    def __init__(self, strength: float = 0, range: tuple = None,
                 positive: bool = False):
        Prox.__init__(self, range)
        self.positive = positive
        self._prox = self._build_cpp_prox("float64")

    def _call(self, coeffs: np.ndarray, step: object, out: np.ndarray):
        self._prox.call(coeffs, step, out)

    def value(self, coeffs: np.ndarray):
        """
        Simply returns 0 if all coeffs in range are equal. Other wise returns
        infinity. This is not a penalization but a projection.

        Parameters
        ----------
        coeffs : `numpy.ndarray`, shape=(n_coeffs,)
            Vector to be projected

        Returns
        -------
        output : `float`
            Returns 0 or np.inf
        """
        raw_value = self._prox.value(coeffs)
        if raw_value == sys.float_info.max:
            return np.inf
        else:
            return 0

    @property
    def strength(self):
        return None

    @strength.setter
    def strength(self, val):
        # Strength is not settable in this prox
        pass

    def _build_cpp_prox(self, dtype_or_object_with_dtype):
        self.dtype = self._extract_dtype(dtype_or_object_with_dtype)
        prox_class = self._get_typed_class(dtype_or_object_with_dtype,
                                           dtype_map)
        if self.range is None:
            return prox_class(0., self.positive)
        else:
            return prox_class(0., self.range[0], self.range[1], self.positive)
        return None


text:
package com.github.tckz916.jumppad.listener;

import com.github.tckz916.jumppad.JumpPad;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;

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

/**
 * Created by tckz916 on 2016/02/05
 */
public class PlayerListener implements Listener {

    private JumpPad plugin = JumpPad.getInstance();

    @EventHandler
    public void move(PlayerMoveEvent event) {
        if (!((event.getFrom().getBlock().getType() != Material.GOLD_PLATE && event.getTo().getBlock().getType() == Material.GOLD_PLATE)
                || (event.getFrom().getBlock().getType() != Material.IRON_PLATE && event.getTo().getBlock().getType() == Material.IRON_PLATE)
                || (event.getFrom().getBlock().getType() != Material.STONE_PLATE && event.getTo().getBlock().getType() == Material.STONE_PLATE)
                || (event.getFrom().getBlock().getType() != Material.WOOD_PLATE && event.getTo().getBlock().getType() == Material.WOOD_PLATE))) {
            return;
        }
        Player player = event.getPlayer();
        Block block = event.getTo().getBlock().getRelative(BlockFace.DOWN, 2);
        if (!(block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN)) {
            return;
        }

        Sign sign = (Sign) block.getState();
        List<String> lines = new ArrayList<>(Arrays.asList(sign.getLines()));
        if (!lines.get(0).equals("[jump]")) {
            return;
        }

        double multiply = isDouble(lines.get(1)) ? Double.parseDouble(lines.get(1)) : 3.0;
        double location_y = isDouble(lines.get(2)) ? Double.parseDouble(lines.get(2)) : 1.0;
        player.setVelocity(player.getLocation().getDirection().multiply(multiply).setY(location_y));
        player.playSound(player.getLocation(), Sound.ZOMBIE_INFECT, 4.0F, 2.0F);

    }

    private boolean isDouble(String string) {
        try {
            Double.parseDouble(string);
        } catch (NumberFormatException e) {
            return false;
        }
        return true;
    }

}


text:
package org.daylight.pathweaver.api.config;

import org.apache.log4j.Logger;
import org.daylight.pathweaver.common.config.Configuration;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class PluginConfiguration {
    private static final Logger logger = Logger.getLogger(PluginConfiguration.class);

    private static final String CLASSPATH = "classpath:";

    /**
     * Returns the plugin name (eg. null, zeus, netscaler etc) specified in the configuration file.
     */
    public static String getPluginPrefix() {
        Configuration configuration = new RestApiConfiguration();
        return configuration.getString(PublicApiServiceConfigurationKeys.plugin);
    }

    /**
     *  Returns the extension prefix name (eg. rax, citrix) if any  specified in the configuration file.
     */
    public static String getExtensionPrefix() {
        Configuration configuration = new RestApiConfiguration();
        return configuration.getString(PublicApiServiceConfigurationKeys.extensions);

    }

    /**
     *  Returns a list of spring configuration files required by both core and extension deployment.
     */
    public static List<String> getCommonContexts() {
        List<String> contexts = new ArrayList<String>();
        contexts.add("api-context.xml");
        return contexts;
    }

    /**
     * Returns a list of all spring configurations files required by the core.
     */
    public static List<String> getCoreContexts(String pluginName) {
        List<String> core_contexts = new ArrayList<String>();
        core_contexts.add("api-context.xml");
        core_contexts.add("persistence-context.xml");
        core_contexts.add("data-model-context.xml");
        //contexts.add("dozer-context.xml");
        core_contexts.add(pluginName + "-plugin-context.xml");
        validateCoreContexts(core_contexts);

        return core_contexts;
    }

    /**
     * Returns a list of all spring configurations files (including optional ones) required by the core.
     */
    public static List<String> getCoreAndOptionalContexts(String pluginName) {

        List<String> coreContexts = getCoreContexts(pluginName);

        // The plugin layer may have a persistence layer or not.
        List<String> optional_contexts = new ArrayList<String>();
        optional_contexts.add("plugin-persistence-context.xml");
        validateOptionalContexts(optional_contexts);
        List<String> allContexts = new ArrayList<String>(coreContexts);
        allContexts.addAll(optional_contexts);

        return allContexts;
    }
    /**
     * Prepends each of the core configuration file names with the extension name to derive the extension configuration
     * file name as per the naming convention. Eg. persistence-context.xml will become rax-persistence-context.xml
     */
    public static List<String> getExtensionContexts(String extensionName, String pluginName) {
        List<String> extensionContexts = new ArrayList<String>();
        List<String> coreContexts = getCoreContexts(pluginName);
        for (String context : coreContexts) {
            extensionContexts.add(extensionName + "-" + context);
        }

        // The plugin layer may have a persistence layer or not.
        extensionContexts.add("plugin-persistence-context.xml");

        return extensionContexts;
    }

    /**
     * Checks if all of the given core configuration files exist in classpath, else throws runtime error. And this will
     * prevent the war from being deployed as all configuration files are required.
     */
    public static void validateCoreContexts(List<String> contexts) {
        for (String context : contexts) {
            if (!doesContextExist(context)) {
                logger.warn("All of the core configuration files must exist.");
                throw new RuntimeException("Missing a required Configuration file: " + context);
            }
        }
    }

    /**
     *
     */
    public static void validateOptionalContexts(List<String> contexts) {
        for (String context : contexts) {
            if (!doesContextExist(context)) {
                logger.warn("Could not find the configuration file " + context + ". Quietly ignoring it .....");
            }
        }
    }

    /**
     * Prepends all of the configuration file names with classpath: coz thats what the spring application context likes.
     */
    public static List<String> classpathify(List<String> contexts) {
        List<String> classpathContexts = new ArrayList<String>();
        for(String context: contexts) {
            classpathContexts.add(CLASSPATH + context);
        }
        return classpathContexts;
    }

    /**
     *  Checks if the configuration file is in the classloader. This means that the file exists.
     */
    private static boolean doesContextExist(String context) {
        URL url = PluginConfiguration.class.getClassLoader().getResource(context);
        if (url != null) {
            return true;
        }
        return false;
    }
}


text:
package shell

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	gohttp "net/http"
	"os"
	"path"
	"strings"
	"time"

	homedir "github.com/mitchellh/go-homedir"
	ma "github.com/multiformats/go-multiaddr"
	manet "github.com/multiformats/go-multiaddr-net"
	files "github.com/whyrusleeping/go-multipart-files"
	tar "github.com/whyrusleeping/tar-utils"
)

const (
	DefaultPathName = ".ipfs"
	DefaultPathRoot = "~/" + DefaultPathName
	DefaultApiFile  = "api"
	EnvDir          = "IPFS_PATH"
)

type Shell struct {
	url     string
	httpcli *gohttp.Client
}

func NewLocalShell() *Shell {
	baseDir := os.Getenv(EnvDir)
	if baseDir == "" {
		baseDir = DefaultPathRoot
	}

	baseDir, err := homedir.Expand(baseDir)
	if err != nil {
		return nil
	}

	apiFile := path.Join(baseDir, DefaultApiFile)

	if _, err := os.Stat(apiFile); err != nil {
		return nil
	}

	api, err := ioutil.ReadFile(apiFile)
	if err != nil {
		return nil
	}

	return NewShell(strings.TrimSpace(string(api)))
}

func NewShell(url string) *Shell {
	c := &gohttp.Client{
		Transport: &gohttp.Transport{
			DisableKeepAlives: true,
		},
	}

	return NewShellWithClient(url, c)
}

func NewShellWithClient(url string, c *gohttp.Client) *Shell {
	if a, err := ma.NewMultiaddr(url); err == nil {
		_, host, err := manet.DialArgs(a)
		if err == nil {
			url = host
		}
	}

	return &Shell{
		url:     url,
		httpcli: c,
	}
}

func (s *Shell) SetTimeout(d time.Duration) {
	s.httpcli.Timeout = d
}

func (s *Shell) newRequest(ctx context.Context, command string, args ...string) *Request {
	return NewRequest(ctx, s.url, command, args...)
}

type IdOutput struct {
	ID              string
	PublicKey       string
	Addresses       []string
	AgentVersion    string
	ProtocolVersion string
}

// ID gets information about a given peer.  Arguments:
//
// peer: peer.ID of the node to look up.  If no peer is specified,
//   return information about the local peer.
func (s *Shell) ID(peer ...string) (*IdOutput, error) {
	if len(peer) > 1 {
		return nil, fmt.Errorf("Too many peer arguments")
	}

	resp, err := NewRequest(context.Background(), s.url, "id", peer...).Send(s.httpcli)
	if err != nil {
		return nil, err
	}

	defer resp.Close()
	if resp.Error != nil {
		return nil, resp.Error
	}

	decoder := json.NewDecoder(resp.Output)
	out := new(IdOutput)
	err = decoder.Decode(out)
	if err != nil {
		return nil, err
	}

	return out, nil
}

// Cat the content at the given path. Callers need to drain and close the returned reader after usage.
func (s *Shell) Cat(path string) (io.ReadCloser, error) {
	resp, err := NewRequest(context.Background(), s.url, "cat", path).Send(s.httpcli)
	if err != nil {
		return nil, err
	}
	if resp.Error != nil {
		return nil, resp.Error
	}

	return resp.Output, nil
}

type object struct {
	Hash string
}

// Add a file to ipfs from the given reader, returns the hash of the added file
func (s *Shell) Add(r io.Reader) (string, error) {
	return s.addWithOpts(r, true)
}

// AddNoPin a file to ipfs from the given reader, returns the hash of the added file without pinning the file
func (s *Shell) AddNoPin(r io.Reader) (string, error) {
	return s.addWithOpts(r, false)
}

func (s *Shell) addWithOpts(r io.Reader, pin bool) (string, error) {
	var rc io.ReadCloser
	if rclose, ok := r.(io.ReadCloser); ok {
		rc = rclose
	} else {
		rc = ioutil.NopCloser(r)
	}

	// handler expects an array of files
	fr := files.NewReaderFile("", "", rc, nil)
	slf := files.NewSliceFile("", "", []files.File{fr})
	fileReader := files.NewMultiFileReader(slf, true)

	req := NewRequest(context.Background(), s.url, "add")
	req.Body = fileReader
	req.Opts["progress"] = "false"
	if !pin {
		req.Opts["pin"] = "false"
	}

	resp, err := req.Send(s.httpcli)
	if err != nil {
		return "", err
	}
	defer resp.Close()
	if resp.Error != nil {
		return "", resp.Error
	}

	var out object
	err = json.NewDecoder(resp.Output).Decode(&out)
	if err != nil {
		return "", err
	}

	return out.Hash, nil
}

func (s *Shell) AddLink(target string) (string, error) {
	link := files.NewLinkFile("", "", target, nil)
	slf := files.NewSliceFile("", "", []files.File{link})
	reader := files.NewMultiFileReader(slf, true)

	req := s.newRequest(context.Background(), "add")
	req.Body = reader

	resp, err := req.Send(s.httpcli)
	if err != nil {
		return "", err
	}
	defer resp.Close()
	if resp.Error != nil {
		return "", resp.Error
	}

	var out object
	err = json.NewDecoder(resp.Output).Decode(&out)
	if err != nil {
		return "", err
	}

	return out.Hash, nil
}

// AddDir adds a directory recursively with all of the files under it
func (s *Shell) AddDir(dir string) (string, error) {
	stat, err := os.Lstat(dir)
	if err != nil {
		return "", err
	}
	fmt.Println("file")
	sf, err := files.NewSerialFile("", dir, stat)
	if err != nil {
		return "", err
	}
	slf := files.NewSliceFile("", dir, []files.File{sf})
	reader := files.NewMultiFileReader(slf, true)

	fmt.Println()
	req := NewRequest(context.Background(), s.url, "add")
	req.Opts["r"] = "true"
	req.Body = reader

	resp, err := req.Send(s.httpcli)
	if err != nil {
		return "", err
	}
	defer resp.Close()
	if resp.Error != nil {
		return "", resp.Error
	}

	dec := json.NewDecoder(resp.Output)
	var final string
	for {
		var out object
		err = dec.Decode(&out)
		if err != nil {
			if err == io.EOF {
				break
			}
			return "", err
		}
		final = out.Hash
	}

	if final == "" {
		return "", errors.New("no results received")
	}

	return final, nil
}

const (
	TRaw = iota
	TDirectory
	TFile
	TMetadata
	TSymlink
)

// List entries at the given path
func (s *Shell) List(path string) ([]*LsLink, error) {
	resp, err := NewRequest(context.Background(), s.url, "ls", path).Send(s.httpcli)
	if err != nil {
		return nil, err
	}
	defer resp.Close()

	if resp.Error != nil {
		return nil, resp.Error
	}

	var out struct{ Objects []LsObject }
	err = json.NewDecoder(resp.Output).Decode(&out)
	if err != nil {
		return nil, err
	}

	return out.Objects[0].Links, nil
}

type LsLink struct {
	Hash string
	Name string
	Size uint64
	Type int
}

type LsObject struct {
	Links []*LsLink
	LsLink
}

// Pin the given path
func (s *Shell) Pin(path string) error {
	req := NewRequest(context.Background(), s.url, "pin/add", path)
	req.Opts["r"] = "true"

	resp, err := req.Send(s.httpcli)
	if err != nil {
		return err
	}
	defer resp.Close()
	if resp.Error != nil {
		return resp.Error
	}

	return nil
}

// Unpin the given path
func (s *Shell) Unpin(path string) error {
	req := NewRequest(context.Background(), s.url, "pin/rm", path)
	req.Opts["r"] = "true"

	resp, err := req.Send(s.httpcli)
	if err != nil {
		return err
	}
	defer resp.Close()
	if resp.Error != nil {
		return resp.Error
	}

	return nil
}

const (
	DirectPin    = "direct"
	RecursivePin = "recursive"
	IndirectPin  = "indirect"
)

type PinInfo struct {
	Type string
}

// Pins returns a map of the pin hashes to their info (currently just the
// pin type, one of DirectPin, RecursivePin, or IndirectPin. A map is returned
// instead of a slice because it is easier to do existence lookup by map key
// than unordered array searching. The map is likely to be more useful to a
// client than a flat list.
func (s *Shell) Pins() (map[string]PinInfo, error) {
	resp, err := s.newRequest(context.Background(), "pin/ls").Send(s.httpcli)
	if err != nil {
		return nil, err
	}
	defer resp.Close()

	if resp.Error != nil {
		return nil, resp.Error
	}

	raw := struct{ Keys map[string]PinInfo }{}
	err = json.NewDecoder(resp.Output).Decode(&raw)
	if err != nil {
		return nil, err
	}

	return raw.Keys, nil
}

type PeerInfo struct {
	Addrs []string
	ID    string
}

func (s *Shell) FindPeer(peer string) (*PeerInfo, error) {
	resp, err := s.newRequest(context.Background(), "dht/findpeer", peer).Send(s.httpcli)
	if err != nil {
		return nil, err
	}
	defer resp.Close()

	if resp.Error != nil {
		return nil, resp.Error
	}

	str := struct{ Responses []PeerInfo }{}
	err = json.NewDecoder(resp.Output).Decode(&str)
	if err != nil {
		return nil, err
	}

	if len(str.Responses) == 0 {
		return nil, errors.New("peer not found")
	}

	return &str.Responses[0], nil
}

func (s *Shell) Refs(hash string, recursive bool) (<-chan string, error) {
	req := s.newRequest(context.Background(), "refs", hash)
	if recursive {
		req.Opts["r"] = "true"
	}

	resp, err := req.Send(s.httpcli)
	if err != nil {
		return nil, err
	}

	if resp.Error != nil {
		return nil, resp.Error
	}

	out := make(chan string)
	go func() {
		var ref struct {
			Ref string
		}
		defer resp.Close()
		defer close(out)
		dec := json.NewDecoder(resp.Output)
		for {
			err := dec.Decode(&ref)
			if err != nil {
				return
			}
			if len(ref.Ref) > 0 {
				out <- ref.Ref
			}
		}
	}()

	return out, nil
}

func (s *Shell) Patch(root, action string, args ...string) (string, error) {
	cmdargs := append([]string{root}, args...)
	resp, err := s.newRequest(context.Background(), "object/patch/"+action, cmdargs...).Send(s.httpcli)
	if err != nil {
		return "", err
	}
	defer resp.Close()

	if resp.Error != nil {
		return "", resp.Error
	}

	dec := json.NewDecoder(resp.Output)
	var out object
	err = dec.Decode(&out)
	if err != nil {
		return "", err
	}

	return out.Hash, nil
}

func (s *Shell) PatchData(root string, set bool, data interface{}) (string, error) {
	var read io.Reader
	switch d := data.(type) {
	case io.Reader:
		read = d
	case []byte:
		read = bytes.NewReader(d)
	case string:
		read = strings.NewReader(d)
	default:
		return "", fmt.Errorf("unrecognized type: %#v", data)
	}

	cmd := "append-data"
	if set {
		cmd = "set-data"
	}

	fr := files.NewReaderFile("", "", ioutil.NopCloser(read), nil)
	slf := files.NewSliceFile("", "", []files.File{fr})
	fileReader := files.NewMultiFileReader(slf, true)

	req := s.newRequest(context.Background(), "object/patch/"+cmd, root)
	req.Body = fileReader

	resp, err := req.Send(s.httpcli)
	if err != nil {
		return "", err
	}
	defer resp.Close()

	if resp.Error != nil {
		return "", resp.Error
	}

	dec := json.NewDecoder(resp.Output)
	var out object
	err = dec.Decode(&out)
	if err != nil {
		return "", err
	}

	return out.Hash, nil
}

func (s *Shell) PatchLink(root, path, childhash string, create bool) (string, error) {
	cmdargs := []string{root, path, childhash}

	req := s.newRequest(context.Background(), "object/patch/add-link", cmdargs...)
	if create {
		req.Opts["create"] = "true"
	}

	resp, err := req.Send(s.httpcli)
	if err != nil {
		return "", err
	}
	defer resp.Close()

	if resp.Error != nil {
		return "", resp.Error
	}

	var out object
	err = json.NewDecoder(resp.Output).Decode(&out)
	if err != nil {
		return "", err
	}

	return out.Hash, nil
}

func (s *Shell) Get(hash, outdir string) error {
	resp, err := s.newRequest(context.Background(), "get", hash).Send(s.httpcli)
	if err != nil {
		return err
	}
	defer resp.Close()

	if resp.Error != nil {
		return resp.Error
	}

	extractor := &tar.Extractor{Path: outdir}
	return extractor.Extract(resp.Output)
}

func (s *Shell) NewObject(template string) (string, error) {
	args := []string{}
	if template != "" {
		args = []string{template}
	}

	resp, err := s.newRequest(context.Background(), "object/new", args...).Send(s.httpcli)
	if err != nil {
		return "", err
	}
	defer resp.Close()

	if resp.Error != nil {
		return "", resp.Error
	}

	var out object
	err = json.NewDecoder(resp.Output).Decode(&out)
	if err != nil {
		return "", err
	}

	return out.Hash, nil
}

func (s *Shell) ResolvePath(path string) (string, error) {
	resp, err := s.newRequest(context.Background(), "object/stat", path).Send(s.httpcli)
	if err != nil {
		return "", err
	}
	defer resp.Close()

	if resp.Error != nil {
		return "", resp.Error
	}

	var out object
	err = json.NewDecoder(resp.Output).Decode(&out)
	if err != nil {
		return "", err
	}

	return out.Hash, nil
}

// returns ipfs version and commit sha
func (s *Shell) Version() (string, string, error) {
	resp, err := s.newRequest(context.Background(), "version").Send(s.httpcli)
	if err != nil {
		return "", "", err
	}

	defer resp.Close()
	if resp.Error != nil {
		return "", "", resp.Error
	}

	ver := struct {
		Version string
		Commit  string
	}{}

	err = json.NewDecoder(resp.Output).Decode(&ver)
	if err != nil {
		return "", "", err
	}

	return ver.Version, ver.Commit, nil
}

func (s *Shell) IsUp() bool {
	_, _, err := s.Version()
	return err == nil
}

func (s *Shell) BlockStat(path string) (string, int, error) {
	resp, err := s.newRequest(context.Background(), "block/stat", path).Send(s.httpcli)
	if err != nil {
		return "", 0, err
	}
	defer resp.Close()

	if resp.Error != nil {
		return "", 0, resp.Error
	}

	var inf struct {
		Key  string
		Size int
	}

	err = json.NewDecoder(resp.Output).Decode(&inf)
	if err != nil {
		return "", 0, err
	}

	return inf.Key, inf.Size, nil
}

func (s *Shell) BlockGet(path string) ([]byte, error) {
	resp, err := s.newRequest(context.Background(), "block/get", path).Send(s.httpcli)
	if err != nil {
		return nil, err
	}
	defer resp.Close()

	if resp.Error != nil {
		return nil, resp.Error
	}

	return ioutil.ReadAll(resp.Output)
}

func (s *Shell) BlockPut(block []byte) (string, error) {
	data := bytes.NewReader(block)
	rc := ioutil.NopCloser(data)
	fr := files.NewReaderFile("", "", rc, nil)
	slf := files.NewSliceFile("", "", []files.File{fr})
	fileReader := files.NewMultiFileReader(slf, true)

	req := s.newRequest(context.Background(), "block/put")
	req.Body = fileReader
	resp, err := req.Send(s.httpcli)
	if err != nil {
		return "", err
	}
	defer resp.Close()

	if resp.Error != nil {
		return "", resp.Error
	}

	var out struct {
		Key string
	}
	err = json.NewDecoder(resp.Output).Decode(&out)
	if err != nil {
		return "", err
	}

	return out.Key, nil
}

type IpfsObject struct {
	Links []ObjectLink
	Data  string
}

type ObjectLink struct {
	Name, Hash string
	Size       uint64
}

func (s *Shell) ObjectGet(path string) (*IpfsObject, error) {
	resp, err := s.newRequest(context.Background(), "object/get", path).Send(s.httpcli)
	if err != nil {
		return nil, err
	}
	defer resp.Close()

	if resp.Error != nil {
		return nil, resp.Error
	}

	var obj IpfsObject
	err = json.NewDecoder(resp.Output).Decode(&obj)
	if err != nil {
		return nil, err
	}

	return &obj, nil
}

func (s *Shell) ObjectPut(obj *IpfsObject) (string, error) {
	data := new(bytes.Buffer)
	err := json.NewEncoder(data).Encode(obj)
	if err != nil {
		return "", err
	}

	rc := ioutil.NopCloser(data)

	fr := files.NewReaderFile("", "", rc, nil)
	slf := files.NewSliceFile("", "", []files.File{fr})
	fileReader := files.NewMultiFileReader(slf, true)

	req := s.newRequest(context.Background(), "object/put")
	req.Body = fileReader
	resp, err := req.Send(s.httpcli)
	if err != nil {
		return "", err
	}
	defer resp.Close()

	if resp.Error != nil {
		return "", resp.Error
	}

	var out object
	err = json.NewDecoder(resp.Output).Decode(&out)
	if err != nil {
		return "", err
	}

	return out.Hash, nil
}

func (s *Shell) PubSubSubscribe(topic string) (*PubSubSubscription, error) {
	// connect
	req := s.newRequest(context.Background(), "pubsub/sub", topic)

	resp, err := req.Send(s.httpcli)
	if err != nil {
		return nil, err
	}

	return newPubSubSubscription(resp), nil
}

func (s *Shell) PubSubPublish(topic, data string) (err error) {
	resp, err := s.newRequest(context.Background(), "pubsub/pub", topic, data).Send(s.httpcli)
	if err != nil {
		return
	}
	defer func() {
		err1 := resp.Close()
		if err == nil {
			err = err1
		}
	}()

	return nil
}

type ObjectStats struct {
	Hash           string
	BlockSize      int
	CumulativeSize int
	DataSize       int
	LinksSize      int
	NumLinks       int
}

// ObjectStat gets stats for the DAG object named by key. It returns
// the stats of the requested Object or an error.
func (s *Shell) ObjectStat(key string) (*ObjectStats, error) {
	resp, err := s.newRequest(context.Background(), "object/stat", key).Send(s.httpcli)
	if err != nil {
		return nil, err
	}
	defer resp.Close()

	if resp.Error != nil {
		return nil, resp.Error
	}

	stat := &ObjectStats{}

	err = json.NewDecoder(resp.Output).Decode(stat)
	if err != nil {
		return nil, err
	}

	return stat, nil
}

func (s *Shell) DiagNet(format string) ([]byte, error) {
	var result = new(bytes.Buffer)

	req := s.newRequest(context.Background(), "diag/net")
	req.Opts["vis"] = format

	resp, err := req.Send(s.httpcli)
	if err != nil {
		return []byte{}, err
	}

	defer resp.Close()
	if resp.Error != nil {
		return []byte{}, resp.Error
	}

	result.ReadFrom(resp.Output)

	return result.Bytes(), nil
}


text:
var Connection = require('../models/Connection')
var UserManager = require('../models/UserManager');
var ConnectionManager = require('../models/ConnectionManager');

function objLen(obj) {
    var i = 0;
    for (var k in obj) {
        i++;
    }
    return i;
}

var denyAuthenticator = {
    verify: function() {
        return false;
    }
};

var approveAuthenticator = {
    verify: function() {
        return true;
    }
};

exports.handleIdentSendsNegativeResponseToConnection = function(test) {
    test.expect(2);
    var conn = new Connection({});
    var userMan = new UserManager();
    var connMan = new ConnectionManager({
        authenticator: denyAuthenticator,
        usermanager: userMan
    });

    //usermanger needs to call send on connection, lets intercept the call and test it
    conn.send = function(event, data) {
        test.equal("ERROR", event, "UserManager sends error");
        test.equal("IDENT not verified", data, "Error message");
    };

    connMan.addConnection(conn);
    conn.receive("ident", {});
    test.done();
};

exports.handleIdentSendsPositiveResponseToConnection = function(test) {
    test.expect(2);

    var conn = new Connection({});
    var userMan = new UserManager();
    var connMan = new ConnectionManager({
        authenticator: approveAuthenticator,
        usermanager: userMan
    });

    //usermanger needs to call send on connection, lets intercept the call and test it
    conn.send = function(event, data) {
        test.equal("OK", event, "UserManager sends ok");
        test.deepEqual(data, {username: "fred"}, "Returns username");
    };

    connMan.addConnection(conn);
    conn.receive("ident", {"username": "fred"});
    test.done();
};

exports.returnsAllUsersConnections = function(test) {
    test.expect(6);

    //mock an authenticator that always accepts
    var auth = {};
    auth.verify = function() {
        return true;
    }

    var userMan = new UserManager(auth);
    var conn1 = new Connection({});
    var conn2 = new Connection({});
    var conn3 = new Connection({});
    userMan.addUserConnection("asdf", conn1);
    userMan.addUserConnection("asdf", conn2);
    userMan.addUserConnection("qwer", conn3);

    test.equal(objLen(userMan.getUserConnections("asdf")), 2, "Returns 2 for asdf");
    test.equal(objLen(userMan.getUserConnections("qwer")), 1, "Returns 1 for qwer");
    test.deepEqual(userMan.getUserConnections("none"), {}, "Returns 0 for non-existant");
    conn3.close();
    test.deepEqual(userMan.users.has("qwer"), false, "User is unregistered if his last connection left");
    test.deepEqual(userMan.getUserConnections("qwer"), {}, "Returns 0 if user conn left");
    conn1.close();
    test.equal(objLen(userMan.getUserConnections("asdf")), 1, "Returns 1 after second left");

    test.done();
}


text:
package ru.furry.furview2.drivers.e621;

import org.joda.time.DateTime;

import java.math.BigInteger;
import java.util.List;

import ru.furry.furview2.images.Rating;
import ru.furry.furview2.images.RemoteFurImage;

public class RemoteFurImageE621 extends RemoteFurImage {

    private final int idE621;
    private String author;
    private DateTime createdAt;
    private List<String> sources;
    private List<String> tags;
    private List<String> artists;
    private int score;
    private BigInteger md5;
    private int fileSize;
    private int fileWidth;
    private int fileHeight;
    private String filePath;

    public RemoteFurImageE621(String searchQuery, String description, int score, Rating rating, String fileUrl, String fileExt, String pageUrl, int idE621, String author, DateTime createdAt, List<String> sources, List<String> tags, List<String> artists, BigInteger md5, int fileSize, int fileWidth, int fileHeight, String filePath, String previewUrl) {
        super(searchQuery, description, rating, fileUrl, fileExt, pageUrl, previewUrl);
        this.idE621 = idE621;
        this.author = author;
        this.createdAt = createdAt;
        this.sources = sources;
        this.tags = tags;
        this.artists = artists;
        this.score = score;
        this.md5 = md5;
        this.fileSize = fileSize;
        this.fileWidth = fileWidth;
        this.fileHeight = fileHeight;
        this.filePath = filePath;
    }

    public int getIdE621() {
        return idE621;
    }

    public String getAuthor() {
        return author;
    }

    public DateTime getCreatedAt() {
        return createdAt;
    }

    public List<String> getSources() {
        return sources;
    }

    public List<String> getTags() {
        return tags;
    }

    public List<String> getArtists() {
        return artists;
    }

    public BigInteger getMd5() {
        return md5;
    }

    public int getFileSize() {
        return fileSize;
    }

    public int getFileWidth() {
        return fileWidth;
    }

    public int getFileHeight() {
        return fileHeight;
    }

    public int getScore() {
        return score;
    }

    public String getFilePath() {
        return filePath;
    }
}


text:
package io.redlink.smarti.chatpal.repo;

import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.GroupOperation;
import org.springframework.data.mongodb.core.aggregation.ProjectionOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import com.mongodb.WriteResult;

import io.redlink.smarti.chatpal.model.ChatpalMessage;
import io.redlink.smarti.repositories.UpdatedIds;

public class ChatpalRepositoryImpl implements ChatpalRepositoryCustom {

    private final Logger log = LoggerFactory.getLogger(getClass());

    private static final ProjectionOperation ID_MODIFIED_PROJECTION = Aggregation.project("id","modified");
    private static final GroupOperation GROUP_MODIFIED = Aggregation.group()
            .addToSet("id").as("ids")
            .max("modified").as("lastModified");

    private final MongoTemplate mongoTemplate;

    public ChatpalRepositoryImpl(MongoTemplate mongoTemplate){
        this.mongoTemplate = mongoTemplate;
    }

    /* (non-Javadoc)
     * @see io.redlink.smarti.chatpal.repo.ChatpalRepositoryCustom#store(org.bson.types.ObjectId, java.util.Map)
     */
    @Override
    public void store(ObjectId client, Map<String,Object> chatpalMessage){
        assert chatpalMessage.get("id") != null;
        Object msgId = chatpalMessage.get("id");
        WriteResult result = mongoTemplate.upsert(
                Query.query(Criteria.where("msgId").is(msgId).and("client").is(client)),
                Update.update("data", chatpalMessage)
                    .set("removed", false) //
                    .currentDate("modified"),
                ChatpalMessage.class);
        if(log.isTraceEnabled()){
            if(result.isUpdateOfExisting()){
                log.trace("updated chatpal message {} for client {} [data: {}]", msgId, client, chatpalMessage);
            } else {
                log.trace("created chatpal message {} for client {} [data: {}]", msgId, client, chatpalMessage);
            }
        }
    }

    @Override
    public void markAsDeleted(ObjectId client, String msgId) {
        WriteResult result = mongoTemplate.updateMulti(
                Query.query(Criteria.where("msgId").is(msgId).and("client").is(client)),
                Update.update("removed", true).unset("data").currentDate("modified"),
                ChatpalMessage.class);
        if(log.isTraceEnabled()){
            if(result.getN() > 0){
                log.trace("marked chatpal message {} for client {} as deleted", msgId, client);
            } else {
                log.trace("no chatpal message {} for client {} present (no need to mark as deleted)", msgId, client);
            }
        }

    }
    @Override
    public void markAsDeleted(ObjectId client) {
        WriteResult result = mongoTemplate.updateMulti(
                Query.query(Criteria.where("client").is(client)),
                Update.update("removed", true).unset("data").currentDate("modified"),
                ChatpalMessage.class);
        if(log.isTraceEnabled()){
            if(result.getN() > 0){
                log.trace("marked {} chatpal messages for client {} as deleted", result.getN(), client);
            } else {
                log.trace("no chatpal messages for client {} present (no need to mark anything as deleted)", client);
            }
        }
    }

    /* (non-Javadoc)
     * @see io.redlink.smarti.chatpal.repo.ChatpalRepositoryCustom#updatedSince(java.util.Date)
     */
    @Override
    public UpdatedIds<ObjectId> updatedSince(Date date, int limit) {
        //IMPLEMENTATION NOTES (Rupert Westenthaler, 2017-07-19):
        // * we need to use $gte as we might get additional updates in the same ms ...
        // * Instead of $max: modified we would like to use the current Server time of the
        //   aggregation, but this is not possible ATM (see https://jira.mongodb.org/browse/SERVER-23656)
        // * The use of $gte together with lastModified menas that we will repeat reporting the
        //   Entities updated at lastModified on every call. To avoid this a Workaround is used
        //   that increases the reported lastModified time by 1ms in cases no update was done
        //   since the last call (meaning the parsed date equals the lastModified)
        @SuppressWarnings("rawtypes")
        AggregationResults<UpdatedIds> aggResult = mongoTemplate.aggregate(
                getUpdatedSinceAggregation(date, limit), ChatpalMessage.class, UpdatedIds.class);
        if(log.isTraceEnabled()){
            log.trace("{} : {} updated since {}", ChatpalMessage.class, aggResult.getMappedResults(),
                    date == null ? null : date.toInstant());
        }
        if(aggResult.getUniqueMappedResult() == null){
            return new UpdatedIds<>(date, Collections.emptyList());
        } else {
            UpdatedIds<ObjectId> updates = aggResult.getUniqueMappedResult();
            //NOTE: workaround for SERVER-23656 (see above impl. notes)
            if(date != null && date.equals(updates.getLastModified())) { //no update since the last request
                //increase the time by 1 ms to avoid re-indexing the last update
                return new UpdatedIds<>(new Date(date.getTime()+1), updates.ids());
            } else {
                return updates;
            }
        }
    }

    private Aggregation getUpdatedSinceAggregation(Date since, long limit) {
        List<AggregationOperation> ops = new LinkedList<>();
        if(since != null){
            ops.add(Aggregation.match(Criteria.where("modified").gte(since)));
        }
        ops.add(Aggregation.sort(Direction.ASC,"modified"));
        if(limit > 0){
            ops.add(Aggregation.limit(limit));
        }
        ops.add(ID_MODIFIED_PROJECTION);
        ops.add(GROUP_MODIFIED);
        Aggregation agg = Aggregation.newAggregation(ops);
        log.trace("UpdatedSince Aggregation: {}", agg);
        return agg;
    }
}


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer/autoload_real.php';

return ComposerAutoloaderInit72f06975cb8760d03e461dd84ef9d084::getLoader();


text:
package main

import (
	"database/sql"
	"encoding/csv"
	"flag"
	"fmt"
	"io/ioutil"
	"regexp"

	_ "github.com/mattn/go-sqlite3"

	"bytes"
	"encoding/hex"
	"io"
	"log"
	"os"
	"os/exec"
	"os/user"
	"path/filepath"
	"strings"
	"time"
	"unicode/utf8"
)

func main() {
	// Parse command line opts
	commands := flag.String("sql", "", "SQL Command(s) to run on the data")
	source_text := flag.String("source", "stdin", "Source file to load, or defaults to stdin")
	delimiter := flag.String("dlm", ",", "Delimiter between fields -dlm=tab for tab, -dlm=0x## to specify a character code in hex")
	lazyQuotes := flag.Bool("lazy-quotes", false, "Enable LazyQuotes in the csv parser")
	header := flag.Bool("header", false, "Treat file as having the first row as a header row")
	outputHeader := flag.Bool("output-header", false, "Display column names in output")
	tableName := flag.String("table-name", "tbl", "Override the default table name (tbl)")
	save_to := flag.String("save-to", "", "If set, sqlite3 db is left on disk at this path")
	console := flag.Bool("console", false, "After all commands are run, open sqlite3 console with this data")
	verbose := flag.Bool("verbose", false, "Enable verbose logging")
	flag.Parse()

	if *console && (*source_text == "stdin") {
		log.Fatalln("Can not open console with pipe input, read a file instead")
	}

	separator := determineSeparator(delimiter)

	// Open db, in memory if possible
	db, openPath := openDB(save_to, console)

	// Open the input source
	var fp *os.File
	fp = openFileOrStdin(source_text)
	defer fp.Close()

	// Init a structured text reader
	reader := csv.NewReader(fp)
	reader.FieldsPerRecord = 0
	reader.Comma = separator
	reader.LazyQuotes = *lazyQuotes

	// Read the first row
	first_row, read_err := reader.Read()

	if read_err != nil {
		log.Fatalln(read_err)
	}

	var headerRow []string

	if *header {
		headerRow = first_row
		first_row, read_err = reader.Read()

		if read_err != nil {
			log.Fatalln(read_err)
		}
	} else {
		headerRow = make([]string, len(first_row))

		// Name each field after the column
		reStartDigit := regexp.MustCompile("^[0-9]")
		for i := 0; i < len(first_row); i++ {
			if reStartDigit.MatchString(first_row[i]) {
				headerRow[i] = "c" + first_row[i]
			} else {
				headerRow[i] = first_row[i]
			}
		}
	}

	// Create the table to load to
	createTable(tableName, &headerRow, db, verbose)

	// Start the clock for importing
	t0 := time.Now()

	// Create transaction
	tx, tx_err := db.Begin()

	if tx_err != nil {
		log.Fatalln(tx_err)
	}

	// Load first row
	stmt := createLoadStmt(tableName, &headerRow, tx)
	loadRow(tableName, &first_row, tx, stmt, verbose)

	// Read the data
	for {
		row, file_err := reader.Read()
		if file_err == io.EOF {
			break
		} else if file_err != nil {
			log.Println(file_err)
		} else {
			loadRow(tableName, &row, tx, stmt, verbose)
		}
	}
	stmt.Close()
	tx.Commit()

	t1 := time.Now()

	if *verbose {
		fmt.Fprintf(os.Stderr, "Data loaded in: %v\n", t1.Sub(t0))
	}

	// Determine what sql to execute
	sqls_to_execute := strings.Split(*commands, ";")

	t0 = time.Now()

	// Execute given SQL
	for _, sql_cmd := range sqls_to_execute {
		if strings.Trim(sql_cmd, " ") != "" {
			result, err := db.Query(sql_cmd)
			if err != nil {
				log.Fatalln(err)
			}
			displayResult(result, outputHeader, separator)
		}
	}

	t1 = time.Now()

	if *verbose {
		fmt.Fprintf(os.Stderr, "Queries run in: %v\n", t1.Sub(t0))
	}

	// Open console
	if *console {
		db.Close()
		args := []string{*openPath}
		if *outputHeader {
			args = append(args, "-header")
		}
		cmd := exec.Command("sqlite3", args...)

		cmd.Stdin = os.Stdin
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		cmd_err := cmd.Run()
		if cmd.Process != nil {
			cmd.Process.Release()
		}

		if len(*save_to) == 0 {
			os.RemoveAll(filepath.Dir(*openPath))
		}

		if cmd_err != nil {
			log.Fatalln(cmd_err)
		}
	} else if len(*save_to) == 0 {
		db.Close()
		os.Remove(*openPath)
	} else {
		db.Close()
	}
}

func createTable(tableName *string, columnNames *[]string, db *sql.DB, verbose *bool) error {
	var buffer bytes.Buffer

	buffer.WriteString("CREATE TABLE IF NOT EXISTS " + (*tableName) + " (")

	for i, col := range *columnNames {
		var col_name string

		reg := regexp.MustCompile(`[^a-zA-Z0-9]`)

		col_name = reg.ReplaceAllString(col, "_")
		if *verbose && col_name != col {
			fmt.Fprintf(os.Stderr, "Column %x renamed to %s\n", col, col_name)
		}

		buffer.WriteString(col_name + " TEXT")

		if i != len(*columnNames)-1 {
			buffer.WriteString(", ")
		}
	}

	buffer.WriteString(");")

	_, err := db.Exec(buffer.String())

	if err != nil {
		log.Fatalln(err)
	}

	return err
}

func createLoadStmt(tableName *string, values *[]string, db *sql.Tx) *sql.Stmt {
	if len(*values) == 0 {
		log.Fatalln("Nothing to build insert with!")
	}
	var buffer bytes.Buffer

	buffer.WriteString("INSERT INTO " + (*tableName) + " VALUES (")
	for i := range *values {
		buffer.WriteString("?")
		if i != len(*values)-1 {
			buffer.WriteString(", ")
		}
	}
	buffer.WriteString(");")
	stmt, err := db.Prepare(buffer.String())
	if err != nil {
		log.Fatalln(err)
	}
	return stmt
}

func loadRow(tableName *string, values *[]string, db *sql.Tx, stmt *sql.Stmt, verbose *bool) error {
	if len(*values) == 0 {
		return nil
	}
	vals := make([]interface{}, 0)
	for _, val := range *values {
		vals = append(vals, val)
	}
	_, err := stmt.Exec(vals...)
	if err != nil && *verbose {
		fmt.Fprintln(os.Stderr, "Bad row: ", err)
	}
	return err
}

type csvWriter struct {
	*csv.Writer
}

func (w csvWriter) put(record []string) {
	if err := w.Write(record); err != nil {
		log.Fatalln(err)
	}
}

func displayResult(rows *sql.Rows, outputHeader *bool, sep rune) {
	cols, cols_err := rows.Columns()

	if cols_err != nil {
		log.Fatalln(cols_err)
	}

	out := csvWriter{csv.NewWriter(os.Stdout)}

	out.Comma = sep

	if *outputHeader {
		out.put(cols)
	}

	rawResult := make([][]byte, len(cols))
	result := make([]string, len(cols))

	dest := make([]interface{}, len(cols))
	for i := range cols {
		dest[i] = &rawResult[i]
	}

	for rows.Next() {
		rows.Scan(dest...)

		for i, raw := range rawResult {
			result[i] = string(raw)
		}

		out.put(result)
	}

	out.Flush()
}

func openFileOrStdin(path *string) *os.File {
	var fp *os.File
	var err error
	if (*path) == "stdin" {
		fp = os.Stdin
		err = nil
	} else {
		fp, err = os.Open(*cleanPath(path))
	}

	if err != nil {
		log.Fatalln(err)
	}

	return fp
}

func cleanPath(path *string) *string {
	var result string
	usr, err := user.Current()
	if err != nil {
		log.Fatalln(err)
	}

	if (*path)[:2] == "~/" {
		dir := usr.HomeDir + "/"
		result = strings.Replace(*path, "~/", dir, 1)
	} else {
		result = (*path)
	}

	abs_result, abs_err := filepath.Abs(result)
	if abs_err != nil {
		log.Fatalln(err)
	}

	clean_result := filepath.Clean(abs_result)

	return &clean_result
}

func openDB(path *string, no_memory *bool) (*sql.DB, *string) {
	openPath := ":memory:"
	if len(*path) != 0 {
		openPath = *cleanPath(path)
	} else if *no_memory {
		outDir, err := ioutil.TempDir(os.TempDir(), "textql")
		if err != nil {
			log.Fatalln(err)
		}
		openPath = filepath.Join(outDir, "textql.db")
	}

	db, err := sql.Open("sqlite3", openPath)

	if err != nil {
		log.Fatalln(err)
	}
	return db, &openPath
}

func determineSeparator(delimiter *string) rune {
	var separator rune

	if (*delimiter) == "tab" {
		separator = '\t'
	} else if strings.Index((*delimiter), "0x") == 0 {
		dlm, hex_err := hex.DecodeString((*delimiter)[2:])

		if hex_err != nil {
			log.Fatalln(hex_err)
		}

		separator, _ = utf8.DecodeRuneInString(string(dlm))
	} else {
		separator, _ = utf8.DecodeRuneInString(*delimiter)
	}
	return separator
}


text:
________________________________________________________________________

This file is part of Logtalk <https://logtalk.org/>
Copyright 1998-2022 Paulo Moura <pmoura@logtalk.org>
SPDX-License-Identifier: Apache-2.0

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
________________________________________________________________________

Design pattern:
	Lazy initialization

Description:
	Delay creation of a required instance (accessed using a key)
	until the instance is requested.

This pattern can be used with both classes and prototypes. The description
above is from the Wikipedia page on this pattern:

https://en.wikipedia.org/wiki/Lazy_initialization

This pattern is not described in the GoF book. See the Wikipedia page for
details and references.

The sample implementation uses classes.


text:
/*
Memoized solution
*/
package main

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

type M struct {
	tree       *TreeNode
	can_choose bool
}

// Naive recursive solution
func max(x int, y int) int {
	if x >= y {
		return x
	} else {
		return y
	}
}

func __rob(memoized map[M]int, root *TreeNode, can_choose bool) int {
	if root == nil {
		return 0
	}

	if count, has := memoized[M{root, can_choose}]; has {
		return count
	}

	result := 0
	if !can_choose {
		result = __rob(memoized, root.Left, true) + __rob(memoized, root.Right, true)
	} else {
		result = max(
			root.Val+__rob(memoized, root.Left, false)+__rob(memoized, root.Right, false),
			__rob(memoized, root.Left, true)+__rob(memoized, root.Right, true))
	}
	memoized[M{root, can_choose}] = result
	return result
}

func rob(root *TreeNode) int {
	return __rob(make(map[M]int), root, true)
}


text:
/* based on http://www.boost.org/doc/libs/1_61_0/doc/html/boost_asio/example/cpp03/echo/blocking_tcp_echo_client.cpp */

#include <iostream>
#include <fstream>
#include <libgen.h> /* for basename */
#include <boost/asio.hpp>
#include "../http_parser.hpp"

using boost::asio::ip::tcp;
using namespace http;

std::string determineFileName(const std::string& urlPath,
        const http::response_head& rh)
{
    (void) rh;
    // TODO this obviously needs refinement
    return basename((char*) urlPath.c_str());
}

int main(int argc, char* argv[])
{
    try {
        if (argc != 2) {
            std::cerr << "Usage: " << argv[0] << " <URL>" << std::endl;
            return 1;
        }

        url_t url;
        bool urlParsedOk = false;
        try {
            url = parse_url(argv[1]);
            urlParsedOk = true;
        } catch (const url_parse_error&) {
        }
        if (!urlParsedOk || url.host.empty()) {
            std::cerr << "This does not appear to be a valid URL of a HTTP resource: "
            << argv[1] << std::endl;
            return 1;
        }
        if (url.schema != "http") {
            std::cerr << "This program only supports plain HTTP." << std::endl;
            return 1;
        }
        if (0 == url.port) { // no port specified explicitly in the URL
            url.port = 80; // good as long as we only support http://
        }

        std::ostringstream ss;
        ss << "GET " << url.path;
        if (!url.query.empty()) {
            ss << '?' << url.query;
        }
        ss << " HTTP/1.1\r\n"
                << "Host: " << url.host << "\r\n"
                << "Connection: close\r\n"
                << "\r\n";
        const std::string request = ss.str();
        std::cout << request << std::endl;

        boost::asio::io_service ioService;

        tcp::resolver resolver(ioService);
        tcp::resolver::query query(tcp::v4(), url.host, std::to_string(url.port));
        tcp::resolver::iterator it = resolver.resolve(query);

        tcp::socket socket(ioService);
        std::cout << "Connecting to " << url.host << ':' << url.port << "... "
                << std::flush;
        boost::asio::connect(socket, it);
        std::cout << "done\nSending request." << std::endl;
        boost::asio::write(socket, boost::asio::buffer(request));

        std::cout << "Reading response." << std::endl;
        std::string fileName;
        std::ofstream outputFile;
        outputFile.exceptions(std::ofstream::failbit | std::ofstream::badbit);
        bool completed = false;
        auto myCallback = [&] (const http::response_head& response,
                const char *bodyPart, std::size_t bodyPartLength, bool finished) {
            if (!outputFile.is_open()) {
                fileName = determineFileName(url.path, response);
                std::cout << "Saving to " << fileName << std::endl;
                outputFile.open(fileName,
                        std::ios::out | std::ios::trunc | std::ios::binary);
            }
            outputFile.write(bodyPart, bodyPartLength);
            completed = finished;
            if (completed) {
                std::cout << "Done." << std::endl;
            }
        };
        http::big_response_parser parser(myCallback);
        parser.set_max_headers_length(1024 * 1024);
        while (!completed) {
            boost::system::error_code ec;
            char reply[2048];
            size_t reply_length = boost::asio::read(socket,
                    boost::asio::buffer(reply, sizeof(reply)), ec);
            if (reply_length > 0U) {
                parser.feed(reply, reply_length);
            }
            if (boost::asio::error::eof == ec) {
                parser.feed_eof();
            } else if (ec) {
                throw boost::system::system_error(ec);
            }
        }
    } catch (const std::runtime_error& e) {
        std::cerr << "Interrupted by exception: " << e.what() << std::endl;
        return 1;
    }
    return 0;
}


text:
/**
 *
 */
package org.minnal.examples.petclinic.domain;

import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.MappedSuperclass;

import org.minnal.instrument.entity.Searchable;
import org.minnal.jpa.entity.BaseDomain;

/**
 * @author ganeshs
 *
 */
@MappedSuperclass
@Access(AccessType.FIELD)
public class NamedEntity extends BaseDomain {

	@Searchable
	private String name;

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
}


text:
#ifndef ThreadableLoader_h
#define ThreadableLoader_h

#include "core/CoreExport.h"
#include "core/fetch/ResourceLoaderOptions.h"
#include "platform/CrossThreadCopier.h"
#include "wtf/Allocator.h"
#include "wtf/Noncopyable.h"
#include <memory>

namespace blink {

class ResourceRequest;
class ExecutionContext;
class ThreadableLoaderClient;

enum CrossOriginRequestPolicy {
    DenyCrossOriginRequests,
    UseAccessControl,
    AllowCrossOriginRequests
};

enum PreflightPolicy {
    ConsiderPreflight,
    ForcePreflight,
    PreventPreflight
};

enum ContentSecurityPolicyEnforcement {
    EnforceContentSecurityPolicy,
    DoNotEnforceContentSecurityPolicy,
};

struct ThreadableLoaderOptions {
    DISALLOW_NEW();
    ThreadableLoaderOptions()
        : preflightPolicy(ConsiderPreflight)
        , crossOriginRequestPolicy(DenyCrossOriginRequests)
        , contentSecurityPolicyEnforcement(EnforceContentSecurityPolicy)
        , timeoutMilliseconds(0) { }

    // When adding members, CrossThreadThreadableLoaderOptionsData should
    // be updated.
    PreflightPolicy preflightPolicy; // If AccessControl is used, how to determine if a preflight is needed.
    CrossOriginRequestPolicy crossOriginRequestPolicy;
    AtomicString initiator;
    ContentSecurityPolicyEnforcement contentSecurityPolicyEnforcement;
    unsigned long timeoutMilliseconds;
};

// Encode AtomicString as String to cross threads.
struct CrossThreadThreadableLoaderOptionsData {
    STACK_ALLOCATED();
    explicit CrossThreadThreadableLoaderOptionsData(const ThreadableLoaderOptions& options)
        : preflightPolicy(options.preflightPolicy)
        , crossOriginRequestPolicy(options.crossOriginRequestPolicy)
        , initiator(options.initiator.getString().isolatedCopy())
        , contentSecurityPolicyEnforcement(options.contentSecurityPolicyEnforcement)
        , timeoutMilliseconds(options.timeoutMilliseconds) { }

    operator ThreadableLoaderOptions() const
    {
        ThreadableLoaderOptions options;
        options.preflightPolicy = preflightPolicy;
        options.crossOriginRequestPolicy = crossOriginRequestPolicy;
        options.initiator = AtomicString(initiator);
        options.contentSecurityPolicyEnforcement = contentSecurityPolicyEnforcement;
        options.timeoutMilliseconds = timeoutMilliseconds;
        return options;
    }

    PreflightPolicy preflightPolicy;
    CrossOriginRequestPolicy crossOriginRequestPolicy;
    String initiator;
    ContentSecurityPolicyEnforcement contentSecurityPolicyEnforcement;
    unsigned long timeoutMilliseconds;
};

template <>
struct CrossThreadCopier<ThreadableLoaderOptions> {
    typedef CrossThreadThreadableLoaderOptionsData Type;
    static Type copy(const ThreadableLoaderOptions& options)
    {
        return CrossThreadThreadableLoaderOptionsData(options);
    }
};

// Useful for doing loader operations from any thread (not threadsafe,
// just able to run on threads other than the main thread).
//
// Arguments common to both loadResourceSynchronously() and create():
//
// - ThreadableLoaderOptions argument configures this ThreadableLoader's
//   behavior.
//
// - ResourceLoaderOptions argument will be passed to the FetchRequest
//   that this ThreadableLoader creates. It can be altered e.g. when
//   redirect happens.
class CORE_EXPORT ThreadableLoader {
    WTF_MAKE_NONCOPYABLE(ThreadableLoader);
public:
    // ThreadableLoaderClient methods may not destroy the ThreadableLoader
    // instance in them.
    static void loadResourceSynchronously(ExecutionContext&, const ResourceRequest&, ThreadableLoaderClient&, const ThreadableLoaderOptions&, const ResourceLoaderOptions&);

    // This method never returns nullptr.
    //
    // This method must always be followed by start() call.
    // ThreadableLoaderClient methods are never called before start() call.
    //
    // The async loading feature is separated into the create() method and
    // and the start() method in order to:
    // - reduce work done in a constructor
    // - not to ask the users to handle failures in the constructor and other
    //   async failures separately
    //
    // Loading completes when one of the following methods are called:
    // - didFinishLoading()
    // - didFail()
    // - didFailAccessControlCheck()
    // - didFailRedirectCheck()
    // After any of these methods is called, the loader won't call any of the
    // ThreadableLoaderClient methods.
    //
    // A user must guarantee that the loading completes before the attached
    // client gets invalid. Also, a user must guarantee that the loading
    // completes before the ThreadableLoader is destructed.
    //
    // When ThreadableLoader::cancel() is called,
    // ThreadableLoaderClient::didFail() is called with a ResourceError
    // with isCancellation() returning true, if any of didFinishLoading()
    // or didFail.*() methods have not been called yet. (didFail() may be
    // called with a ResourceError with isCancellation() returning true
    // also for cancellation happened inside the loader.)
    //
    // ThreadableLoaderClient methods:
    // - may call cancel()
    // - can destroy the ThreadableLoader instance in them (by clearing
    //   std::unique_ptr<ThreadableLoader>).
    static std::unique_ptr<ThreadableLoader> create(ExecutionContext&, ThreadableLoaderClient*, const ThreadableLoaderOptions&, const ResourceLoaderOptions&);

    // The methods on the ThreadableLoaderClient passed on create() call
    // may be called synchronous to start() call.
    virtual void start(const ResourceRequest&) = 0;

    // A ThreadableLoader may have a timeout specified. It is possible, in some cases, for
    // the timeout to be overridden after the request is sent (for example, XMLHttpRequests
    // may override their timeout setting after sending).
    //
    // Set a new timeout relative to the time the request started, in milliseconds.
    virtual void overrideTimeout(unsigned long timeoutMilliseconds) = 0;

    virtual void cancel() = 0;

    virtual ~ThreadableLoader() { }

protected:
    ThreadableLoader() { }
};

} // namespace blink

#endif // ThreadableLoader_h


text:
using BenchmarkDotNet.Attributes;
using DragonSpark.Compose;
using DragonSpark.Model.Selection;
using FluentAssertions;
using System.Collections.Generic;
using System.Linq;
using Xunit;

namespace DragonSpark.Testing.Model.Sequences.Query;

// ReSharper disable once TestFileNameWarning
public sealed class SelectManyTests
{
	readonly static Numbers[] Data =
	{
		new Numbers(1, 2, 3, 4),
		new Numbers(5, 6, 7, 8),
		new Numbers(9, 10)
	};

	public sealed class Numbers
	{
		public Numbers(params int[] elements) => Elements = elements;

		public int[] Elements { get; }
	}

	public class Benchmarks
	{
		readonly IEnumerable<int>          _classic;
		readonly ISelect<Numbers[], int[]> _subject;

		public Benchmarks() : this(Data.Hide().SelectMany(x => x.Elements),
		                           Start.A.Selection<Numbers>()
		                                .As.Sequence.Open.By.Self
		                                .Select(x => x.SelectMany(numbers => numbers.Elements).ToArray())
		                                .Get()
		                          ) {}

		public Benchmarks(IEnumerable<int> classic, ISelect<Numbers[], int[]> subject)
		{
			_classic = classic;
			_subject = subject;
		}

		[Benchmark(Baseline = true)]
		public int[] Classic() => _classic.ToArray();

		[Benchmark]
		public int[] Subject() => _subject.Get(Data);
	}

	[Fact]
	public void Verify()
	{
		Start.A.Selection<Numbers>()
		     .As.Sequence.Open.By.Self.Select(x => x.SelectMany(y => y.Elements).ToArray())
		     .Get(Data)
		     .Should()
		     .Equal(Data.SelectMany(x => x.Elements));
	}

	[Fact]
	public void VerifyBody()
	{
		Start.A.Selection<Numbers>()
		     .As.Sequence.Open.By.Self.Select(x => x.Skip(2)
		                                            .SelectMany(y => y.Elements)
		                                            .ToArray())
		     .Get(Data)
		     .Should()
		     .Equal(Data.Skip(2).SelectMany(x => x.Elements));
	}

	[Fact]
	public void VerifyBodyFirst()
	{
		Start.A.Selection<Numbers>()
		     .As.Sequence.Open.By.Self.Select(x => x.Skip(1)
		                                            .SelectMany(y => y.Elements)
		                                            .FirstOrDefault())
		     .Get(Data)
		     .Should()
		     .Be(Data.Skip(1).SelectMany(x => x.Elements).First());

		Start.A.Selection<Numbers>()
		     .As.Sequence.Open.By.Self.Select(x => x.Skip(1)
		                                            .SelectMany(y => y.Elements)
		                                            .Skip(2)
		                                            .FirstOrDefault())
		     .Get(Data)
		     .Should()
		     .Be(Data.Skip(1).SelectMany(x => x.Elements).Skip(2).First());
	}
}


text:
layout: page
title: Gould Dart Media Trade Fair
date: 2016-05-24
author: Scott Gaines
tags: weekly links, java
status: published
summary: Nunc metus odio, lobortis sit amet vulputate.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 08/23/2019
  endDate: 08/24/2019
  ctyhocn: FPAALHX
  groupCode: GDMTF
published: true
---
Mauris bibendum orci nec nisl tincidunt suscipit. Proin ut sollicitudin purus, ut pharetra sapien. Nam nec sodales elit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce id ex et odio convallis ullamcorper in eget sapien. Nam eu odio enim. Fusce finibus lobortis metus, ut varius diam blandit id. Duis hendrerit sit amet urna ac convallis.
Duis quis diam pulvinar, dictum leo quis, hendrerit turpis. Praesent ac tellus odio. Vestibulum ultricies porta mi ut mollis. Maecenas vel purus orci. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vestibulum sit amet lobortis lectus. Donec vitae sem pellentesque, convallis nulla sit amet, congue velit. Duis luctus eros posuere tempor lobortis. Suspendisse tristique mi vel justo tincidunt viverra. Integer vitae commodo augue, a elementum neque. Sed ac odio sed nunc condimentum elementum.

* Integer eget arcu sit amet tortor pellentesque faucibus nec sed metus
* Duis ultrices lacus a auctor ultricies
* Praesent luctus mi id lobortis condimentum.

Suspendisse mattis nisl quis nisi pretium, vulputate aliquam erat suscipit. Ut urna magna, iaculis id maximus id, blandit varius urna. Aliquam sit amet felis at ante tincidunt posuere ac sit amet purus. Nunc eu massa finibus, rutrum mauris at, ultricies metus. Sed imperdiet tortor ac ligula ornare, non iaculis ante dignissim. Mauris facilisis eu ex vel sodales. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nunc eu magna dignissim, faucibus lacus eget, dictum magna. Cras id leo a lacus finibus tristique. Praesent vulputate id est nec tempor. Maecenas quis luctus libero. Vivamus interdum accumsan libero sit amet egestas.