text:
//---THIS FILE WAS AUTOMATICALLY GENERATED.  DO NOT EDIT---//

//To change this file, alter the niftools/docsys/gen_niflib.py Python script.

#ifndef _BHKCMSD_SOMETHING_H_
#define _BHKCMSD_SOMETHING_H_

#include "../NIF_IO.h"

namespace Niflib {

/*! Unknown, used in bhkCompressedMeshShapeData */
struct bhkCMSD_Something {
	/*! Default Constructor */
	NIFLIB_API bhkCMSD_Something();
	/*! Default Destructor */
	NIFLIB_API ~bhkCMSD_Something();
	/*! Copy Constructor */
	NIFLIB_API bhkCMSD_Something( const bhkCMSD_Something & src );
	/*! Copy Operator */
	NIFLIB_API bhkCMSD_Something & operator=( const bhkCMSD_Something & src );
	/*! Unknown */
	unsigned int largeInt;
	/*! Always 1? */
	unsigned int unknownInteger;
	//--BEGIN MISC CUSTOM CODE--//
	//--END CUSTOM CODE--//
};

}
#endif


text:
template<class T>
struct KeyWrapper
{
	typedef T wrapped_type;
	typedef KeyWrapper<T> self_type;

	enum KeyTypeEnum { KeyType_Normal, KeyType_Empty, KeyType_Deleted };

	KeyTypeEnum type;
	T key;

	KeyWrapper() : type(KeyType_Normal), key(T()) {}
	KeyWrapper(KeyTypeEnum type_) : type(type_), key(T()) {}
	KeyWrapper(const T& key_) : key(key_), type(KeyType_Normal) {}
	KeyWrapper(const self_type& other) : type(other.type), key(other.key) {}

	operator const T& () const { return key; }
	bool isNormal() const { return (type == KeyType_Normal); }

	template <typename KeyComparer>
	struct EqualsComparer
	{
		EqualsComparer(KeyComparer keyComparer) :
			m_KeyComparer(keyComparer)
		{
		}

		bool operator()(const KeyWrapper<T>& left, const KeyWrapper<T>& right) const
		{
			if (left.type != right.type)
				return false;

			if (!left.isNormal())
				return true;

			return m_KeyComparer(left.key, right.key);
		}

	private:
		KeyComparer m_KeyComparer;
	};
};

redpajama_set_name: RedPajamaGithub


text:
/*
 * PROFILE
 */
.profile-header {
    background: #ffffff;
    height: 145px;
    margin: -25px;
    padding: 25px;
    background-size: cover;
    position: relative;
}

.profile-header .profile-header-info {
    padding: 25px;
    position: absolute;
    bottom: 0px;
    left: 0px;
    width: 100%;
}

.profile-user {
    background: #acb7bf;
    margin-top: -145px;
    color: #ffffff;
    background-size: cover;
}

.profile-user .profile-user-title .avatar {
    width: 120px;
    height: 120px;
    margin-bottom: 20px;
    padding: 5px;
    background: #ffffff;
}

.profile-user .profile-user-title .avatar img {
    -webkit-border-radius: 100%;
            border-radius: 100%;
}

.profile-header-title {
    padding-left: 25px;
}

.profile-user-skills progress {
    height: 6px;
    margin-top: 4px;
}

.mode-superclean .profile-header-title {
    padding-left: 15px;
}

@media (max-width: 1200px) {
    .profile-header-title {
        padding-left: 0px !important;
    }
    .profile-user {
        margin-top: 0px;
    }
}

@media (max-width: 1600px) {
    .user-profile-dl dt {
        float: none;
        text-align: left;
    }
    .user-profile-dl dd {
        margin-left: 0px;
        margin-bottom: 10px;
    }
}


text:
Parser for "IDOLM@STER MILLION LIVE!" site.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'millionlive-parser', github: 'gomao9/millionlive-parser'
```

And then execute:

    $ bundle

## Usage

Pending

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
/**
 * Disallows implicit type conversion.
 *
 * Type: `Array`
 *
 * Values: Array of quoted types
 *
 * #### Example
 *
 * ```js
 * "disallowImplicitTypeConversion": ["numeric", "boolean", "binary", "string"]
 * ```
 *
 * ##### Valid
 *
 * ```js
 * x = Boolean(y);
 * x = Number(y);
 * x = String(y);
 * x = s.indexOf('.') !== -1;
 * ```
 *
 * ##### Invalid
 *
 * ```js
 * x = !!y;
 * x = +y;
 * x = '' + y;
 * x = ~s.indexOf('.');
 * ```
 */

var assert = require('assert');

module.exports = function() {};

module.exports.prototype = {

    configure: function(types) {
        assert(Array.isArray(types), this.getOptionName() + ' option requires array value');
        this._typeIndex = {};
        for (var i = 0, l = types.length; i < l; i++) {
            this._typeIndex[types[i]] = true;
        }
    },

    getOptionName: function() {
        return 'disallowImplicitTypeConversion';
    },

    check: function(file, errors) {
        var types = this._typeIndex;
        if (types.numeric || types.boolean || types.binary) {
            file.iterateNodesByType('UnaryExpression', function(node) {
                if (types.numeric && node.operator === '+') {
                    errors.add('Implicit numeric conversion', node);
                }
                if (types.binary && node.operator === '~') {
                    errors.add('Implicit binary conversion', node);
                }
                if (types.boolean &&
                    node.operator === '!' &&
                    node.argument.type === 'UnaryExpression' &&
                    node.argument.operator === '!'
                ) {
                    errors.add('Implicit boolean conversion', node);
                }
            });
        }
        if (types.string) {
            file.iterateNodesByType('BinaryExpression', function(node) {

                if (node.operator !== '+') {
                    return;
                }

                // Do not report concatination for same string literals (#1538)
                if (node.left.type === node.right.type) {
                    return;
                }

                if (
                    (node.left.type === 'Literal' && node.left.value === '') ||
                    (node.right.type === 'Literal' && node.right.value === '')
                ) {
                    errors.add('Implicit string conversion', node);
                }
            });
        }
    }

};


text:
<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vaisakhan S</title>

  <link rel="apple-touch-icon" href="/images/profile.png"/>
  <link rel="shortcut icon" sizes="16x16 24x24 32x32 48x48 64x64" href="http://localhost:4000/favicon.ico" />

  <link rel="stylesheet" href="/assets/normalize.css">
  <link rel="stylesheet" href="/assets/main.css">
  <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
  <link href='https://fonts.googleapis.com/css?family=Vollkorn' rel='stylesheet' type='text/css'>

  <link rel="canonical" href="http://localhost:4000/">

  <meta name="author" content="Vaisakhan S">
  <meta name="description" content=""/>

  <meta property="og:title" content=""/>
  <meta property="og:url" content="http://localhost:4000/"/>
  <meta property="og:image" content="http://localhost:4000/images/profile.png"/>
  <meta property="og:description" content=""/>
  <meta property="og:site_name" content="">

Vaisakhan S

CS Undergrad.
Web developer.
Caffeine addict.

    GitHub

    LinkedIn

    Stack Overflow

Website created using Jekyll.


text:
..
    This work is licensed under the Creative Commons Attribution-
    NonCommercial-ShareAlike 3.0 Unported License. To view a copy of this
    license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ or send a
    letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View,
    California, 94041, USA.

.. currentmodule:: qinfer

Abstract Model Classes
======================

Introduction
------------

A *model* in QInfer is a class that describes the probabilities of observing
data, given a particular experiment and given a particular set of model
parameters. The observation probabilities may be given implicitly or explicitly,
in that the class may only allow for sampling observations, rather than finding
the a distribution explicitly. In the former case, a model is represented by
a subclass of :class:`Simulatable`, while in the latter, the model is
represented by a subclass of :class:`Model`.

:class:`Simulatable` - Base Class for Implicit (Simulatable) Models
-------------------------------------------------------------------

Class Reference
~~~~~~~~~~~~~~~
.. autoclass:: Simulatable
    :members:

:class:`Model` - Base Class for Explicit (Likelihood) Models
------------------------------------------------------------

If a model supports explicit calculation of the likelihood function, then this
is represented by subclassing from :class:`Model`.

Class Reference
~~~~~~~~~~~~~~~

.. autoclass:: Model
    :members:

:class:`FiniteOutcomeModel` - Base Class for  Models with a Finite Number of Outcomes
-------------------------------------------------------------------------------------

The likelihood function provided by a subclass is used to implement
:meth:`Simulatable.simulate_experiment`, which is possible because the
likelihood of all possible outcomes can be computed.
This class also concretely implements the :attr:`~Simulatable.domain` method
by looking at the definition of :attr:`~Simulatable.n_outcomes`.

Class Reference
~~~~~~~~~~~~~~~

.. autoclass:: FiniteOutcomeModel
    :members:

:class:`DifferentiableModel` - Base Class for Explicit Models with Differentiable Likelihoods
---------------------------------------------------------------------------------------------

Class Reference
~~~~~~~~~~~~~~~

.. autoclass:: DifferentiableModel
    :members:


text:
@interface EBSlidingNavigationController : UIViewController <UITableViewDataSource, UITableViewDelegate, UIGestureRecognizerDelegate>

@property (nonatomic, strong) UINavigationController *navigationController;

- (id)initWithViewControllerClasses:(NSArray *)viewControllers andTitles:(NSArray *)titles;
- (id)initWithViewControllerNames:(NSArray *)viewControllers andTitles:(NSArray *)titles;

@end


text:
import {resolve} from 'path'
import {ProvidePlugin} from 'webpack'

const aliases = {},
      extensions = ['.js'],
      globExtensions = ['js'],
      loaders = [],
      plugins = [],
      pkg = require(resolve('package')),
      {dependencies = {}} = pkg,
      {devDependencies = {}} = pkg,
      {optionalDependencies = {}} = pkg,
      {peerDependencies = {}} = pkg,
      keys1 = Object.keys(dependencies),
      keys2 = Object.keys(devDependencies),
      keys3 = Object.keys(optionalDependencies),
      keys4 = Object.keys(peerDependencies),
      modules = [...keys1, ...keys2, ...keys3, ...keys4]
let glob

// JSON
if(moduleExists('json-loader')) {
  extensions.push('.json')
  loaders.push({
    test: /\.json$/,
    loaders: ['json-loader'],
  })
}

// JS with Babel (auto self contain if Babel runtime is available)
if(moduleExists('babel-loader')) {
  extensions.push('.jsx')
  globExtensions.push('jsx')
  loaders.push({
    test: /^(?!.*(bower_components|node_modules))+.+\.jsx?$/,
    loaders: ['babel-loader'],
  })
}

// CoffeeScript
if(moduleExists('coffee-loader')) {
  extensions.push('.coffee', '.coffee.md', '.litcoffee')
  globExtensions.push('coffee', 'coffee.md', 'litcoffee')
  loaders.push({
    test: /\.coffee$/,
    loaders: ['coffee-loader'],
  })
  loaders.push({
    test: /\.(coffee\.md|litcoffee)$/,
    loaders: ['coffee-loader?literate'],
  })
}

// HTML
if(moduleExists('html-loader')) {
  extensions.push('.html')
  loaders.push({
    test: /\.html$/,
    loaders: ['html-loader?-minimize'],
  })
}

// Riot
if(moduleExists('riotjs-loader')) {
  extensions.push('.tag')
  globExtensions.push('tag')
  loaders.push({
    test: /\.tag$/,
    loaders: moduleExists('babel-loader')
      ? ['babel-loader', 'riotjs-loader?type=none']
      : ['riotjs-loader'],
  })
  plugins.push(new ProvidePlugin({riot: 'riot'}))
}

// Build glob
glob = globExtensions.length > 1
  ? `*.{${globExtensions.join(',')}}`
  : `*.${globExtensions[0]}`

export {aliases, extensions, glob, loaders, plugins}

function moduleExists(mod, path = mod) {
  if(~modules.indexOf(mod)) {
    try {
      require.resolve(path)
      return true
    }
    catch(e) {
      return false
    }
  }
  return false
}


text:
package org.apache.ignite.ml.tree;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.ignite.ml.dataset.Dataset;
import org.apache.ignite.ml.dataset.primitive.context.EmptyContext;
import org.apache.ignite.ml.tree.data.DecisionTreeData;
import org.apache.ignite.ml.tree.impurity.ImpurityMeasureCalculator;
import org.apache.ignite.ml.tree.impurity.gini.GiniImpurityMeasure;
import org.apache.ignite.ml.tree.impurity.gini.GiniImpurityMeasureCalculator;
import org.apache.ignite.ml.tree.impurity.util.StepFunctionCompressor;
import org.apache.ignite.ml.tree.leaf.MostCommonDecisionTreeLeafBuilder;

/**
 * Decision tree classifier based on distributed decision tree trainer that allows to fit trees using row-partitioned
 * dataset.
 */
public class DecisionTreeClassificationTrainer extends DecisionTree<GiniImpurityMeasure> {
    /**
     * Constructs a new decision tree classifier with default impurity function compressor.
     *
     * @param maxDeep Max tree deep.
     * @param minImpurityDecrease Min impurity decrease.
     */
    public DecisionTreeClassificationTrainer(int maxDeep, double minImpurityDecrease) {
        this(maxDeep, minImpurityDecrease, null);
    }

    /**
     * Constructs a new decision tree classifier with default impurity function compressor
     * and default maxDeep = 5 and minImpurityDecrease = 0.
     */
    public DecisionTreeClassificationTrainer() {
        this(5, 0, null);
    }

    /**
     * Constructs a new instance of decision tree classifier.
     *
     * @param maxDeep Max tree deep.
     * @param minImpurityDecrease Min impurity decrease.
     */
    public DecisionTreeClassificationTrainer(int maxDeep, double minImpurityDecrease,
        StepFunctionCompressor<GiniImpurityMeasure> compressor) {
        super(maxDeep, minImpurityDecrease, compressor, new MostCommonDecisionTreeLeafBuilder());
    }

    /**
     * Set up the max deep of decision tree.
     * @param maxDeep The parameter value.
     * @return Trainer with new maxDeep parameter value.
     */
    public DecisionTreeClassificationTrainer withMaxDeep(Double maxDeep){
        this.maxDeep = maxDeep.intValue();
        return this;
    }

    /**
     * Set up the min impurity decrease of decision tree.
     * @param minImpurityDecrease The parameter value.
     * @return Trainer with new minImpurityDecrease parameter value.
     */
    public DecisionTreeClassificationTrainer withMinImpurityDecrease(Double minImpurityDecrease){
        this.minImpurityDecrease = minImpurityDecrease;
        return this;
    }

    /**
     * Sets useIndex parameter and returns trainer instance.
     *
     * @param useIndex Use index.
     * @return Decision tree trainer.
     */
    public DecisionTreeClassificationTrainer withUseIndex(boolean useIndex) {
        this.usingIdx = useIndex;
        return this;
    }

    /** {@inheritDoc} */
    @Override protected ImpurityMeasureCalculator<GiniImpurityMeasure> getImpurityMeasureCalculator(
        Dataset<EmptyContext, DecisionTreeData> dataset) {
        Set<Double> labels = dataset.compute(part -> {

            if (part.getLabels() != null) {
                Set<Double> list = new HashSet<>();

                for (double lb : part.getLabels())
                    list.add(lb);

                return list;
            }

            return null;
        }, (a, b) -> {
            if (a == null)
                return b;
            else if (b == null)
                return a;
            else {
                a.addAll(b);
                return a;
            }
        });

        Map<Double, Integer> encoder = new HashMap<>();

        int idx = 0;
        for (Double lb : labels)
            encoder.put(lb, idx++);

        return new GiniImpurityMeasureCalculator(encoder, usingIdx);
    }
}


text:
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;

public class TestTask extends Task {

    public void execute() throws BuildException {
        Project p = this.getProject();
        System.out.println("sourceDirectory:" + p.getProperty("project.build.sourceDirectory"));
        System.out.println("project.cmdline:" + p.getProperty("project.cmdline"));
        System.out.println("basedir:" + p.getProperty("basedir"));
    }

}


text:
package org.xdi.oxauth.service.fido.u2f;

import java.io.IOException;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.xdi.oxauth.crypto.signature.SHA256withECDSASignatureVerification;
import org.xdi.oxauth.model.exception.SignatureException;
import org.xdi.oxauth.model.fido.u2f.exception.BadInputException;
import org.xdi.oxauth.model.fido.u2f.message.RawAuthenticateResponse;
import org.xdi.oxauth.model.fido.u2f.protocol.ClientData;
import org.xdi.oxauth.model.util.Base64Util;
import org.xdi.util.io.ByteDataInputStream;

import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;

/**
 * Provides operations with U2F RAW authentication response
 *
 * @author Yuriy Movchan Date: 05/20/2015
 */
@Stateless
@Named
public class RawAuthenticationService {

	public static final String AUTHENTICATE_GET_TYPE = "navigator.id.getAssertion";
	public static final String AUTHENTICATE_CANCEL_TYPE = "navigator.id.cancelAssertion";
	public static final String[] SUPPORTED_AUTHENTICATE_TYPES = new String[] { AUTHENTICATE_GET_TYPE, AUTHENTICATE_CANCEL_TYPE };

	@Inject
	private Logger log;

	@Inject @Named(value = "sha256withECDSASignatureVerification")
	private SHA256withECDSASignatureVerification signatureVerification;

	public RawAuthenticateResponse parseRawAuthenticateResponse(String rawDataBase64) {
		ByteDataInputStream bis = new ByteDataInputStream(Base64Util.base64urldecode(rawDataBase64));
		try {
			return new RawAuthenticateResponse(bis.readSigned(), bis.readInt(), bis.readAll());
		} catch (IOException ex) {
			throw new BadInputException("Failed to parse RAW authenticate response", ex);
		} finally {
			IOUtils.closeQuietly(bis);
		}
	}

	public void checkSignature(String appId, ClientData clientData, RawAuthenticateResponse rawAuthenticateResponse, byte[] publicKey) throws BadInputException {
		String rawClientData = clientData.getRawClientData();

		byte[] signedBytes = packBytesToSign(signatureVerification.hash(appId), rawAuthenticateResponse.getUserPresence(),
				rawAuthenticateResponse.getCounter(), signatureVerification.hash(rawClientData));
		try {
			signatureVerification.checkSignature(signatureVerification.decodePublicKey(publicKey), signedBytes, rawAuthenticateResponse.getSignature());
		} catch (SignatureException ex) {
			throw new BadInputException("Failed to checkSignature", ex);
		}
	}

	private byte[] packBytesToSign(byte[] appIdHash, byte userPresence, long counter, byte[] challengeHash) {
		ByteArrayDataOutput encoded = ByteStreams.newDataOutput();
		encoded.write(appIdHash);
		encoded.write(userPresence);
		encoded.writeInt((int) counter);
		encoded.write(challengeHash);

		return encoded.toByteArray();
	}

}


text:
TEST(SignalTest, testSetResultAndWait)
{
    dafs::Signal s;
    dafs::Result actual, expected{true, "the_contents"};

    std::thread t([&s, &actual](){ actual = s.Wait(); });
    s.Set(expected);
    t.join();

    ASSERT_EQ(expected.success, actual.success);
    ASSERT_EQ(expected.content, actual.content);
}


text:
```PLStreamingSession.h```

- *Added* method `- (void)reloadVideoConfiguration:(PLVideoStreamingConfiguration *)videoConfiguration;`
- *Added* method `- (void)pushVideoSampleBuffer:(CMSampleBufferRef)sampleBuffer completion:(void (^)(void))handler;`
- *Added* method `- (void)pushPixelBuffer:(CVPixelBufferRef)pixelBuffer completion:(void (^)(void))handler;`
- *Added* method `- (void)pushAudioSampleBuffer:(CMSampleBufferRef)sampleBuffer completion:(void (^)(void))handler;`
- *Added* method `- (void)pushAudioBuffer:(AudioBuffer *)audioBuffer completion:(void (^)(void))handler;`
- *removed* method `- (void)beginUpdateConfiguration;`
- *removed* method `- (void)endUpdateConfiguration;`

```PLVideoStreamingConfiguration.h```

- *Modified* property to writable `@property (nonatomic, PL_STRONG) NSString *videoProfileLevel;`
- *Removed* property `@property (nonatomic, assign) PLStreamingDimension dimension;`
- *Removed* property `@property (nonatomic, PL_STRONG) NSString *videoQuality;`
- *Modified* method `+ (instancetype)configurationWithVideoSize:(CGSize)videoSize
                              videoQuality:(NSString *)quality;`
- *Added* method `- (BOOL)validate;`

```PLTypeDefines.h```

- *Removed* type `PLStreamingDimension`


text:
START_ATF_NAMESPACE
    struct _raceboss_cry_msg_request_clzo
    {
        char sDum;
    };
END_ATF_NAMESPACE


text:
import matplotlib.pyplot as plt

from colormap_utils import remappedColorMap
from results_utils import *
from compare_algos import extractErrRates, computeRankSumZvalsPvals

def plotDf(df, xlabel="Classifier", ylabel="Dataset", title=None,
	symmetricAboutMean=False, cmap='RdBu'):

	data = df.values
	if symmetricAboutMean:
		mean = data.mean()
		bound = max(abs(data.max() - mean), abs(data.min() - mean))
		lower = mean - bound
		upper = mean + bound
	else:
		lower = data.min()
		upper = data.max()

	plt.rcParams["font.size"] = 17
	# plt.figure(figsize=(10, 10))
	fig, ax = plt.subplots(figsize=(10, 10))
	p = ax.pcolormesh(data, cmap=cmap, vmin=lower, vmax=upper)
	plt.colorbar(p, ax=ax)

	plt.yticks(np.arange(0.5, len(df.index), 1), df.index)
	plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns,
		fontsize=13, rotation=80)

	plt.xlabel(xlabel)
	plt.ylabel(ylabel)
	plt.title(title)

	plt.autoscale(True, tight=True)
	plt.tight_layout()
	plt.show()

def plotErrs(df, scoreName="Error Rate", onlySharedDatasets=True):
	df = extractErrRates(df, onlySharedDatasets=onlySharedDatasets)
	print("------------------------")
	print("Err Rates:")
	print("------------------------")
	print(1 - df.mean(axis=1))
	print(1 - df.mean(axis=0))

	title = "%s for Different Classifiers" % scoreName
	plotDf(df, title=title)

def plotZvals(df, lowIsBetter=True):
	errs = extractErrRates(df)
	zvals, pvals = computeRankSumZvalsPvals(errs, lowIsBetter=lowIsBetter)
	plotDf(zvals, title="Rank-Sum Test Z Values", symmetricAboutMean=True)

def plotPvals(df, lowIsBetter=True):
	errs = extractErrRates(df)
	zvals, pvals = computeRankSumZvalsPvals(errs, lowIsBetter=lowIsBetter)

	# make a colormap that's red for p < 5%
	minVal = pvals.min().min()
	maxVal = pvals.max().max()
	cutoff = (np.log10(1.96) - minVal) / (maxVal - minVal)
	cmap = remappedColorMap(plt.cm.RdBu, midpoint=cutoff)

	plotDf(np.log10(pvals), title="Log10 Rank-Sum Test P Values", cmap=cmap)

def main():
	combined = buildCombinedResults()
	setDatasetAsIndex(combined)

	sharedErrs = combined.copy()
	removeEnsembleCols(sharedErrs)

	plotErrs(sharedErrs)
	plotZvals(combined)
	plotPvals(combined)

if __name__ == '__main__':
	main()


text:
if [ $(id -u) != "0" ]; then
    echo "Error: You must be root to run this script."
    exit 1
fi

apt-get update
apt-get autoremove -y
apt-get install -y build-essential gcc g++ make zlibc zlib1g zlib1g-dev

cd /root
#download
wget http://download.redis.io/releases/redis-3.2.3.tar.gz
tar zxvf redis-3.2.3.tar.gz
cd redis-3.2.3/
make
if [ $? -ne 0 ];then
    echo "Make redis source error."
    exit 1
fi

#add redis user group
groupadd redis
useradd -g redis redis
#make dirs
mkdir -pv /usr/local/redis
mkdir -pv /usr/local/redis/bin
mkdir -pv /usr/local/redis/conf
mkdir -pv /usr/local/redis/logs
chown -R redis:redis /usr/local/redis
#copy files
cd src
cp redis-benchmark redis-check-aof redis-cli redis-server /usr/local/redis/bin
cd ..
cp redis.conf /usr/local/redis/conf

cat >>/etc/profile<<eof
export PATH=/usr/local/redis/bin:\$PATH
eof
source /etc/profile
#modify redis.conf
sed -i "s@bind 127.0.0.1@bind 0.0.0.0@g" /usr/local/redis/conf/redis.conf
sed -i "s@daemonize no@daemonize yes@g" /usr/local/redis/conf/redis.conf
sed -i "s@redis_6379.pid@redis.pid@g" /usr/local/redis/conf/redis.conf
sed -i "s@logfile \"\"@logfile \"/usr/local/redis/logs/redis.log\"@g" /usr/local/redis/conf/redis.conf
sed -i "s@dir ./@dir /usr/local/redis@g" /usr/local/redis/conf/redis.conf
#
echo "vm.overcommit_memory=1" >> /etc/sysctl.conf
sysctl -p
echo never > /sys/kernel/mm/transparent_hugepage/enabled
sed -i '/.*exit 0.*/i\echo never > /sys/kernel/mm/transparent_hugepage/enabled' /etc/rc.local
#init scripts
wget https://raw.githubusercontent.com/zhangnq/scripts/master/bash/service/redis-server -O /etc/init.d/redis-server
chmod +x /etc/init.d/redis-server
update-rc.d redis-server defaults

#end
/etc/init.d/redis-server start
ps -ef|grep redis


text:
using System.Collections.Generic;
using System.Data;

namespace Simple.Data.Ado.Schema
{
    public interface ISchemaProvider
    {
        IEnumerable<Table> GetTables();
        IEnumerable<Column> GetColumns(Table table);
        IEnumerable<Procedure> GetStoredProcedures();
        IEnumerable<Parameter> GetParameters(Procedure storedProcedure);
        Key GetPrimaryKey(Table table);
        IEnumerable<ForeignKey> GetForeignKeys(Table table);
        string QuoteObjectName(string unquotedName);
        string NameParameter(string baseName);
        string GetDefaultSchema();
    }
}


text:
package org.apache.storlets.spark.csv;

import java.io.InputStream;
import org.javaswift.joss.instructions.DownloadInstructions;
import org.javaswift.joss.headers.object.range.FirstPartRange;
import org.javaswift.joss.model.StoredObject;

public class StorletCsvObjectContext {
  private StoredObject sobject;
  private long start;
  private long end;
  private long size;
  private String firstLine;
  private String objectName;
  private String containerName;
  private String path;

  StorletCsvObjectContext(StoredObject sobject, Character comment, int maxOffset) {
    DownloadInstructions downloadInstructions = new DownloadInstructions().
      setRange(new FirstPartRange(maxOffset));

    this.sobject = sobject;
    InputStream content = sobject.downloadObjectAsInputStream(downloadInstructions);
    StorletCsvFirstLine csvFirstLine = StorletCsvUtils.getFirstLine(content, comment);
    firstLine = csvFirstLine.getLine();
    start = csvFirstLine.getOffset();     // The position of the first byte to read
    end = sobject.getContentLength() - 1; // The position of the last byte to read
    size = end - start + 1;               // The total data size in bytes
    path = sobject.getPath();
    String[] pathElements = path.split("/");
    containerName = pathElements[1];
    objectName = pathElements[2];
  }

  public long getStart() {
    return start;
  }

  public long getEnd() {
    return end;
  }

  public long getSize() {
    return size;
  }

  public String getFirstLine() {
    return firstLine;
  }

  public String getPath() {
    return path;
  }

  public String getObjectName() {
    return objectName;
  }

  public String getContainerName() {
    return containerName;
  }
}


text:
title: How to add a "Read more" link to a Jekyll blog
layout: post
categories:
  - howto
  - programming
---
We want to add a "read more" link, when the post excerpt
differs from the content. Then we link to the post using the handy `post.url`.

Easily done by adding this within your post loop (mine was part of `home.html`):

```liquid
{% raw %}
{% if post.excerpt != post.content %}
<a href="{{site_url}}{{post.url}}">Read more...</a>
{% endif %}
{% endraw %}
```


text:
using System;
using System.IO;

namespace Line_Numbers
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var streamReader = new StreamReader(@"C:\Users\spide\Desktop\03. Streams-Exercise\text.txt"))
            {
                using (var streamWriter = new StreamWriter("Output.txt"))
                {
                    string line = streamReader.ReadLine();
                    var count = 1;
                    while (line != null)
                    {
                        streamWriter.WriteLine($"Line {count}: {line}");
                        count++;
                        line = streamReader.ReadLine();
                    }
                }
            }
        }
    }
}


text:
/*
Investigating in how many ways objects of two different colours can be grouped.
Problem 181

Having three black objects B and one white object W they can be grouped in 7 ways like this:
In how many ways can sixty black objects B and forty white objects W be  thus grouped?
*/


text:
from sqlalchemy import types, exceptions

from datetime import datetime
import struct
import socket
import time
import ferrox.lib.inet as inet

class DateTime(types.TypeDecorator):
    """Implements a Unix timestamp as an integer."""
    impl = types.Integer

    def __init__(self):
        pass

    def process_bind_param(self, value, engine):
        return int(time.mktime(value.timetuple()))

    def process_result_value(self, value, engine):
        if value == None:
            return None
        else:
            return datetime.fromtimestamp(value)

    def is_mutable(self):
        return False

    def compare_values(self, x, y):
        if type(x) == type(datetime.now()):
            x = self.process_bind_param(x, None)
        if type(y) == type(datetime.now()):
            y = self.process_bind_param(y, None)
        return x == y

# Taken from http://www.sqlalchemy.org/trac/wiki/UsageRecipes/Enum
class Enum(types.TypeDecorator):
    impl = types.SmallInteger

    def __init__(self, *values):
        """Emulate an Enum type.

        values:
           A list of valid values for this column
        """

        if values is None or len(values) is 0:
            raise exceptions.AssertionError('Enum requires a list of values')
        self.values = list(values)

    def process_bind_param(self, value, engine):
        if value not in self.values:
            raise exceptions.AssertionError('"%s" not in Enum.values' % value)
        return self.values.index(value)

    def process_result_value(self, value, engine):
        if value == None:
            return None
        return self.values[value]

    def is_mutable(self):
        return False

    def compare_values(self, x, y):
        if type(x) == type(str()):
            x = self.process_bind_param(x, None)
        if type(y) == type(str()):
            y = self.process_bind_param(y, None)
        return x == y

class IP(types.TypeDecorator):
    """Implements an IP as an integer."""
    impl = types.Binary(length=16)

    def __init__(self):
        pass

    def process_bind_param(self, value, engine):
        try:
            return inet.pton(value);
        except:
            l = len (value)
            if l == 4: return inet.IPV4PREFIX + value
            if l == 16: return value
        raise Exception ('Invalid IP:(' + value +')')

    def process_result_value(self, value, engine):
        return inet.ntop(value);

    def is_mutable(self):
        return False


text: beamchat website


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../libc/fn.readahead.html">

Redirecting to ../../libc/fn.readahead.html...


text:
function Remove-DbaBackup {
    <#
    .SYNOPSIS
        Removes SQL Server backups from disk.

    .DESCRIPTION
        Removes SQL Server backups from disk.

        Provides all of the same functionality for removing SQL backups from disk as a standard maintenance plan would.

        As an addition you have the ability to check the Archive bit on files before deletion. This will allow you to ensure backups have been archived to your archive location before removal.

        Also included is the ability to remove empty folders as part of this cleanup activity.

    .PARAMETER Path
        Specifies the name of the base level folder to search for backup files. Deletion of backup files will be recursive from this location.

    .PARAMETER BackupFileExtension
        Specifies the filename extension of the backup files you wish to remove (typically 'bak', 'trn' or 'log'). Do not include the period.

    .PARAMETER RetentionPeriod
        Specifies the retention period for backup files. Correct format is ##U.

        ## is the retention value and must be an integer value
        U signifies the units where the valid units are:
        h = hours
        d = days
        w = weeks
        m = months

        Formatting Examples:
        '48h' = 48 hours
        '7d' = 7 days
        '4w' = 4 weeks
        '1m' = 1 month

    .PARAMETER CheckArchiveBit
        If this switch is enabled, the filesystem Archive bit is checked before deletion. If this bit is set (which translates to "it has not been backed up to another location yet", the file won't be deleted.

    .PARAMETER RemoveEmptyBackupFolder
        If this switch is enabled, empty folders will be removed after the cleanup process is complete.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.

    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.i

    .NOTES
        Tags: Storage, DisasterRecovery, Backup
        Author: Chris Sommer (@cjsommer), www.cjsommer.com

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Remove-DbaBackup

    .EXAMPLE
        PS C:\> Remove-DbaBackup -Path 'C:\MSSQL\SQL Backup\' -BackupFileExtension trn -RetentionPeriod 48h

        '*.trn' files in 'C:\MSSQL\SQL Backup\' and all subdirectories that are more than 48 hours old will be removed.

    .EXAMPLE
        PS C:\> Remove-DbaBackup -Path 'C:\MSSQL\SQL Backup\' -BackupFileExtension trn -RetentionPeriod 48h -WhatIf

        Same as example #1, but doesn't actually remove any files. The function will instead show you what would be done.
        This is useful when first experimenting with using the function.

    .EXAMPLE
        PS C:\> Remove-DbaBackup -Path 'C:\MSSQL\Backup\' -BackupFileExtension bak -RetentionPeriod 7d -CheckArchiveBit

        '*.bak' files in 'C:\MSSQL\Backup\' and all subdirectories that are more than 7 days old will be removed, but only if the files have been backed up to another location as verified by checking the Archive bit.

    .EXAMPLE
        PS C:\> Remove-DbaBackup -Path 'C:\MSSQL\Backup\' -BackupFileExtension bak -RetentionPeriod 1w -RemoveEmptyBackupFolder

        '*.bak' files in 'C:\MSSQL\Backup\' and all subdirectories that are more than 1 week old will be removed. Any folders left empty will be removed as well.

#>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [parameter(Mandatory, HelpMessage = "Full path to the root level backup folder (ex. 'C:\SQL\Backups'")]
        [Alias("BackupFolder")]
        [string]$Path,
        [parameter(Mandatory, HelpMessage = "Backup File extension to remove (ex. bak, trn, dif)")]
        [string]$BackupFileExtension ,
        [parameter(Mandatory, HelpMessage = "Backup retention period. (ex. 24h, 7d, 4w, 6m)")]
        [string]$RetentionPeriod ,
        [switch]$CheckArchiveBit = $false ,
        [switch]$RemoveEmptyBackupFolder = $false,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        # Ensure BackupFileExtension does not begin with a .
        if ($BackupFileExtension -match "^[.]") {
            Write-Message -Level Warning -Message "Parameter -BackupFileExtension begins with a period '$BackupFileExtension'. A period is automatically prepended to -BackupFileExtension and need not be passed in."
        }
    }
    process {
        # Process stuff
        Write-Message -Message "Removing backups from $Path" -Level Verbose
        Find-DbaBackup -Path $Path -BackupFileExtension $BackupFileExtension -RetentionPeriod $RetentionPeriod -CheckArchiveBit:$CheckArchiveBit -EnableException |
            Foreach-Object {
            $file = $_
            if ($PSCmdlet.ShouldProcess($file.Directory.FullName, "Removing backup file $($file.Name)")) {
                try {
                    $file | Remove-Item -Force -EA Stop
                } catch {
                    Write-Message -Message "Failed to remove $file." -Level Warning -ErrorRecord $_
                }
            }
        }
        Write-Message -Message "File Cleaning ended." -Level Verbose
        # Cleanup empty backup folders.
        if ($RemoveEmptyBackupFolder) {
            Write-Message -Message "Removing empty folders." -Level Verbose
            (Get-ChildItem -Directory -Path $Path -Recurse -ErrorAction SilentlyContinue -ErrorVariable EnumErrors).FullName |
                Sort-Object -Descending |
                Foreach-Object {
                $OrigPath = $_
                try {
                    $Contents = @(Get-ChildItem -Force $OrigPath -ErrorAction Stop)
                } catch {
                    Write-Message -Message "Can't enumerate $OrigPath." -Level Warning -ErrorRecord $_
                }
                if ($Contents.Count -eq 0) {
                    return $_
                }
            } |
                Foreach-Object {
                $FolderPath = $_
                if ($PSCmdlet.ShouldProcess($Path, "Removing empty folder .$($FolderPath.Replace($Path, ''))")) {
                    try {
                        $FolderPath | Remove-Item -ErrorAction Stop
                    } catch {
                        Write-Message -Message "Failed to remove $FolderPath." -Level Warning -ErrorRecord $_
                    }
                }
            }
            if ($EnumErrors) {
                Write-Message "Errors encountered enumerating folders." -Level Warning -ErrorRecord $EnumErrors
            }
            Write-Message -Message "Removed empty folders." -Level Verbose
        }
    }
}


text:
'use strict';

const functionArgumentsSearch = require('../functionArgumentsSearch');

it('passes function arguments to callback', () => {
	expect.assertions(2);

	functionArgumentsSearch('calc(1 + 3)', 'calc', (expression, expressionIndex) => {
		expect(expression).toBe('1 + 3');
		expect(expressionIndex).toBe(5);
	});
});

it('passes function arguments to callback when a case with multiple expressions', () => {
	expect.assertions(2);

	functionArgumentsSearch('4px 5px calc(1px + 3px)', 'calc', (expression, expressionIndex) => {
		expect(expression).toBe('1px + 3px');
		expect(expressionIndex).toBe(13);
	});
});

it('works with nested functions', () => {
	const calcExpressions = [];
	const calcExpressionIndexes = [];

	functionArgumentsSearch(
		'4px 5px calc(calc(1px + 2px) + 3px)',
		'calc',
		(expression, expressionIndex) => {
			calcExpressions.push(expression);
			calcExpressionIndexes.push(expressionIndex);
		},
	);

	expect(calcExpressions).toEqual(['calc(1px + 2px) + 3px', '1px + 2px']);
	expect(calcExpressionIndexes).toEqual([13, 18]);
});

it('works with nested functions inside `color()`', () => {
	expect.assertions(2);

	functionArgumentsSearch(
		'color(red s(- 10%) s( - 10%))',
		'color',
		(expression, expressionIndex) => {
			expect(expression).toBe('red s(- 10%) s( - 10%)');
			expect(expressionIndex).toBe(6);
		},
	);
});

it('works with nested functions inside `s()`', () => {
	const sExpressions = [];
	const sExpressionIndexes = [];

	functionArgumentsSearch('color(red s(- 10%) s( - 10%))', 's', (expression, expressionIndex) => {
		sExpressions.push(expression);
		sExpressionIndexes.push(expressionIndex);
	});

	expect(sExpressions).toEqual(['- 10%', ' - 10%']);
	expect(sExpressionIndexes).toEqual([12, 21]);
});

it('works with interpolation', () => {
	expect.assertions(2);

	functionArgumentsSearch('url(http://$(host)/path)', 'url', (expression, expressionIndex) => {
		expect(expression).toBe('http://$(host)/path');
		expect(expressionIndex).toBe(4);
	});
});

it('works with regex', () => {
	expect.assertions(4);

	functionArgumentsSearch(
		'linear-gradient(#fff, #000)',
		/^(-moz-)?linear-gradient$/,
		(expression, expressionIndex) => {
			expect(expression).toBe('#fff, #000');
			expect(expressionIndex).toBe(16);
		},
	);

	functionArgumentsSearch(
		'-moz-linear-gradient(#fff, #000)',
		/^(-moz-)?linear-gradient$/,
		(expression, expressionIndex) => {
			expect(expression).toBe('#fff, #000');
			expect(expressionIndex).toBe(21);
		},
	);
});

it('ignores strings', () => {
	expect.assertions(3);

	functionArgumentsSearch('calc(1px)', 'calc', (expression, expressionIndex) => {
		expect(expression).toBe('1px');
		expect(expressionIndex).toBe(5);
	});

	const callback = jest.fn();

	functionArgumentsSearch('"calc(1px)"', 'calc', callback);

	expect(callback).not.toHaveBeenCalled();
});


text:
namespace display {

namespace {

// Defines a row and column indices of a cell in the layout matrix.
struct Cell {
  int row;
  int column;

  Cell(int r, int c) : row(r), column(c) {}
};

// Validates that the display placements defines a graph where there is a path
// from each display to the primary display (root) and there are no cycles or
// unparented displays.
using DisplayChildToParentMap = std::map<int64_t, int64_t>;
bool ValidateDisplayGraph(const DisplayChildToParentMap& child_to_parent,
                          int64_t primary_id) {
  for (const auto& iter : child_to_parent) {
    int64_t current_id = iter.first;
    if (current_id == primary_id) {
      // The primary display should not have a parent, and shouldn't exist in
      // the map as a key. That's a potential cycle.
      LOG(ERROR) << "Primary display must not have a parent.";
      return false;
    }

    std::set<int64_t> visited_ids;
    while (current_id != primary_id) {
      if (!visited_ids.emplace(current_id).second) {
        LOG(ERROR) << "A cycle exists at display ID: " << current_id;
        return false;
      }

      const auto parent_iter = child_to_parent.find(current_id);
      if (parent_iter == child_to_parent.end()) {
        LOG(ERROR) << "Display ID: " << current_id << " has no parent.";
        return false;
      }

      current_id = parent_iter->second;
    }
  }

  return true;
}

// Builds and returns the Unified Desktop layout matrix given the display
// |layout|. This function must only be called on an already-validated |layout|.
// Returns an empty matrix if an error occurs.
UnifiedDesktopLayoutMatrix BuildDisplayMatrix(const DisplayLayout& layout) {
  // Maps a display ID to its Cell position in the matrix.
  std::map<int64_t, Cell> displays_cells;
  // The root primary display is at (0, 0).
  displays_cells.emplace(layout.primary_id, Cell(0, 0));

  // After we finish building the Cells, we might have some displays
  // positioned at negative cell coordinates (relative to the root primary
  // display). We need to normalize our Cells so that the least row and column
  // indices are zeros.
  // Calculate the min/max row and column indices.
  int max_row = 0;
  int max_column = 0;
  int min_row = 0;
  int min_column = 0;

  // Calculate the Cell positions of all displays in the placement list.
  for (const auto& placement : layout.placement_list) {
    int64_t current_display_id = placement.display_id;
    base::stack<DisplayPlacement> unhandled_displays;
    while (displays_cells.count(current_display_id) == 0) {
      auto placement_iter = std::find_if(
          layout.placement_list.begin(), layout.placement_list.end(),
          [current_display_id](const DisplayPlacement& p) {
            return p.display_id == current_display_id;
          });
      DCHECK(placement_iter != layout.placement_list.end());
      unhandled_displays.emplace(*placement_iter);
      current_display_id = placement_iter->parent_display_id;
    }

    // For each unhandled display, find its parent's cell, and use it to deduce
    // its own cell.
    while (!unhandled_displays.empty()) {
      const DisplayPlacement current_placement = unhandled_displays.top();
      unhandled_displays.pop();
      const Cell& parent_cell =
          displays_cells.at(current_placement.parent_display_id);
      std::map<int64_t, Cell>::iterator new_cell_itr;
      switch (current_placement.position) {
        case DisplayPlacement::TOP:
          // Top of its parent. Go up a row (row - 1).
          new_cell_itr =
              displays_cells
                  .emplace(current_placement.display_id,
                           Cell(parent_cell.row - 1, parent_cell.column))
                  .first;
          break;

        case DisplayPlacement::RIGHT:
          // Right of its parent. Go right a column (column + 1).
          new_cell_itr =
              displays_cells
                  .emplace(current_placement.display_id,
                           Cell(parent_cell.row, parent_cell.column + 1))
                  .first;
          break;

        case DisplayPlacement::BOTTOM:
          // Bottom of its parent. Go down a row (row + 1).
          new_cell_itr =
              displays_cells
                  .emplace(current_placement.display_id,
                           Cell(parent_cell.row + 1, parent_cell.column))
                  .first;
          break;

        case DisplayPlacement::LEFT:
          // Left of its parent. Go left a column (column - 1).
          new_cell_itr =
              displays_cells
                  .emplace(current_placement.display_id,
                           Cell(parent_cell.row, parent_cell.column - 1))
                  .first;
          break;
      }

      const Cell& cell = new_cell_itr->second;
      max_row = std::max(max_row, cell.row);
      max_column = std::max(max_column, cell.column);
      min_row = std::min(min_row, cell.row);
      min_column = std::min(min_column, cell.column);
    }
  }

  // Now build the matrix.
  UnifiedDesktopLayoutMatrix matrix;
  const size_t num_rows = max_row - min_row + 1;
  const size_t num_columns = max_column - min_column + 1;

  if (displays_cells.size() != num_rows * num_columns) {
    LOG(ERROR) << "Unified Desktop layout matrix has wrong dimentions";
    // Return an empty matrix, ValidateMatrix() will catch it as invalid.
    return matrix;
  }

  matrix.resize(num_rows);
  for (auto& matrix_row : matrix)
    matrix_row.resize(num_columns, display::kInvalidDisplayId);

  for (const auto& iter : displays_cells) {
    const Cell& cell = iter.second;
    const int row_index = cell.row - min_row;
    const int column_index = cell.column - min_column;
    matrix[row_index][column_index] = iter.first;
  }

  return matrix;
}

}  // namespace

bool ValidateMatrix(const UnifiedDesktopLayoutMatrix& matrix) {
  if (matrix.empty())
    return false;

  const size_t column_count = matrix[0].size();
  if (column_count == 0)
    return false;

  for (const auto& row : matrix) {
    if (row.size() != column_count) {
      LOG(ERROR) << "Wrong matrix dimensions. Unequal rows sizes.";
      return false;
    }

    // No holes or repeated IDs are allowed.
    for (const auto& id : row) {
      if (id == display::kInvalidDisplayId) {
        LOG(ERROR) << "Unified Desktop layout matrix has an empty cell in it.";
        return false;
      }
    }
  }

  return true;
}

bool BuildUnifiedDesktopMatrix(const DisplayIdList& ids_list,
                               const DisplayLayout& layout,
                               UnifiedDesktopLayoutMatrix* out_matrix) {
  // The primary display should be in the IDs list.
  if (!base::Contains(ids_list, layout.primary_id)) {
    LOG(ERROR) << "The primary ID: " << layout.primary_id
               << " is not in the IDs list.";
    return false;
  }

  // Each ID in |ids_list| must have a placement in the layout except the
  // primary display.
  for (const auto& id : ids_list) {
    if (id == layout.primary_id)
      continue;
    const auto iter =
        std::find_if(layout.placement_list.begin(), layout.placement_list.end(),
                     [id](const DisplayPlacement& placement) {
                       return placement.display_id == id;
                     });
    if (iter == layout.placement_list.end()) {
      LOG(ERROR) << "Display with ID: " << id << " has no placement.";
      return false;
    }
  }

  if (layout.placement_list.empty()) {
    LOG(ERROR) << "Placement list is empty.";
    return false;
  }

  // This map is used to validate that each display has no more than one child
  // on eithr of its sides.
  std::map<int64_t, std::set<DisplayPlacement::Position>> displays_filled_sides;

  // This map is used to validate that all displays has a path to the primary
  // (root) display with no cycles.
  DisplayChildToParentMap child_to_parent;

  bool has_primary_as_parent = false;
  for (const auto& placement : layout.placement_list) {
    // Unified mode placements are not allowed to have offsets.
    if (placement.offset != 0) {
      LOG(ERROR) << "Unified mode placements are not allowed to have offsets.";
      return false;
    }

    if (placement.display_id == kInvalidDisplayId) {
      LOG(ERROR) << "display_id is not initialized";
      return false;
    }
    if (placement.parent_display_id == kInvalidDisplayId) {
      LOG(ERROR) << "parent_display_id is not initialized";
      return false;
    }
    if (placement.display_id == placement.parent_display_id) {
      LOG(ERROR) << "display_id must not be the same as parent_display_id";
      return false;
    }
    if (!base::Contains(ids_list, placement.display_id)) {
      LOG(ERROR) << "display_id: " << placement.display_id
                 << " is not in the id list: " << placement.ToString();
      return false;
    }

    if (!base::Contains(ids_list, placement.parent_display_id)) {
      LOG(ERROR) << "parent_display_id: " << placement.parent_display_id
                 << " is not in the id list: " << placement.ToString();
      return false;
    }

    if (!displays_filled_sides[placement.parent_display_id]
             .emplace(placement.position)
             .second) {
      LOG(ERROR) << "Parent display with ID: " << placement.parent_display_id
                 << " has more than one display on the same side: "
                 << placement.position;
      return false;
    }

    if (!child_to_parent
             .emplace(placement.display_id, placement.parent_display_id)
             .second) {
      LOG(ERROR) << "Display ID: " << placement.display_id << " appears more "
                 << "than once in the placement list.";
      return false;
    }

    has_primary_as_parent |= layout.primary_id == placement.parent_display_id;
  }

  if (!has_primary_as_parent) {
    LOG(ERROR) << "At least, one placement must have the primary as a parent.";
    return false;
  }

  if (!ValidateDisplayGraph(child_to_parent, layout.primary_id))
    return false;

  UnifiedDesktopLayoutMatrix matrix = BuildDisplayMatrix(layout);
  if (!ValidateMatrix(matrix))
    return false;

  *out_matrix = matrix;
  return true;
}

}  // namespace display


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace Xamarin_Android
{
    [Activity(Label = "Create user")]
    public class CreateUserActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.CreateUser);

            var button = FindViewById<Button>(Resource.Id.Save);
            button.Click += Button_Click;
        }

        private void Button_Click(object sender, EventArgs e)
        {
            var firstname = FindViewById<EditText>(Resource.Id.firstname);
            var lastname = FindViewById<EditText>(Resource.Id.lastname);

            var alert = new AlertDialog.Builder(this);
            alert.SetTitle("Hi " + firstname.Text + " " + lastname.Text + "!");
            alert.SetNeutralButton("OK", (s, args) =>
            {
                StartActivity(typeof(NewsActivity));
            });
            alert.Show();
        }
    }
}


text:
package exifremover.cli;

import java.io.File;
import java.io.IOException;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.sanselan.ImageReadException;
import org.apache.sanselan.ImageWriteException;

import exifremover.model.EXIFRemover;

/**
 * Command line interface for exifremover.
 *
 * @author deque
 *
 */
public class CLI {

	private static final String TEMP_DIR = "temp";
	private static final String VERSION = "EXIFRemover 0.1";
	private static final String USAGE = "exifremover -d <filename/folder>"
			+ " [-dest <filename/folder>]";
	private static final String NEWLINE = System.getProperty("line.separator");
	private static final String EXIF_TITLE = "" + " _____  _____ ___ ___"
			+ NEWLINE + "| __\\ \\/ /_ _| __| _ \\___ _ __  _____ _____ _ _"
			+ NEWLINE + "| _| >  < | || _||   / -_) '  \\/ _ \\ V / -_) '_|"
			+ NEWLINE + "|___/_/\\_\\___|_| |_|_\\___|_|_|_\\___/\\_/\\___|_|        by Deque at"
			+ NEWLINE;
	private static final String HC_TITLE = ""
			+ "_  _ ____ ____ _  _ ____ ____ _  _ _  _ _  _ _  _ _ ___ _   _  ____ ____ _  _"
			+ NEWLINE
			+ "|__| |__| |    |_/  |    |  | |\\/| |\\/| |  | |\\ | |  |   \\_/   |    |  | |\\/|"
			+ NEWLINE
			+ "|  | |  | |___ | \\_ |___ |__| |  | |  | |__| | \\| |  |    |   .|___ |__| |  |"
			+ NEWLINE;

	private static final String FILE_SEPARATOR = System
			.getProperty("file.separator");

	public static void main(String[] args) {
		new CLI(args);
	}

	/**
	 * Initializes options, invokes parsing of command line arguments.
	 *
	 * @param args
	 *            the command line arguments
	 */
	public CLI(String[] args) {
		Options options = initOptions();
		parseCommandLine(args, options);
	}

	/**
	 * Parses arguments for available options.
	 *
	 * @param args
	 *            the command line arguments
	 * @param options
	 *            the command line options for which the arguments are parsed
	 */
	private void parseCommandLine(String[] args, Options options) {
		CommandLineParser parser = new PosixParser();
		System.out.println(EXIF_TITLE);
		System.out.println(HC_TITLE);
		try {
			CommandLine line = parser.parse(options, args);

			if (line.hasOption("version")) {
				System.out.println(VERSION);
			}
			if (line.hasOption("help") || args.length == 0) {
				showHelp(options);
			}
			if (line.hasOption("show-exif")) {
				showExif(line);
			}
			if (line.hasOption("delete-exif")) {
				deleteEXIF(line);
			}
		} catch (ParseException e) {
			System.err.println(e.getMessage());
		} catch (ImageWriteException e) {
			System.err.println(e.getMessage());
		} catch (IOException e) {
			System.err.println(e.getMessage());
		} catch (ImageReadException e) {
			System.err.println(e.getMessage());
		}
	}

	/**
	 * Prints out all EXIF data found in given file.
	 *
	 * @param line
	 *            command line that contains the image path
	 * @throws IOException
	 * @throws ImageReadException
	 */
	private void showExif(CommandLine line) throws IOException,
			ImageReadException {
		File file = new File(line.getOptionValue("show-exif"));
		EXIFRemover remover = new EXIFRemover(file);
		System.out.println(remover.getExifData());
	}

	/**
	 * Prints out help information like usage and available options.
	 *
	 * @param options
	 *            command line options to be shown
	 */
	private void showHelp(Options options) {
		HelpFormatter formatter = new HelpFormatter();
		formatter.printHelp(USAGE, options);
	}

	/**
	 * Removes EXIF data from a single image file or all image files in a folder
	 * given as command line argument.
	 *
	 * If a folder is given, it saves the resulting images into destination
	 * folder. A TEMP_DIR is created if no destination is given (this is mainly
	 * for security reasons, so you are not able to overwrite a whole folder of
	 * images by mistake).
	 *
	 * If a single image file is given, it saves the resulting image into a
	 * given destination. If there is no destination, the image file is
	 * overwritten, which means EXIF data of the original file is lost unless
	 * you have a copy.
	 *
	 * @param line
	 *            command line that contains the paths for source and maybe
	 *            destination
	 * @throws IOException
	 * @throws ImageReadException
	 * @throws ImageWriteException
	 */
	private void deleteEXIF(CommandLine line) throws IOException,
			ImageReadException, ImageWriteException {
		File source = new File(line.getOptionValue("delete-exif"));
		// if no destination folder given, assign source folder to dest
		File dest = line.hasOption("dest") ? new File(
				line.getOptionValue("dest")) : source;

		if (source.isDirectory()) {
			deleteEXIFFromDir(source, dest);
		} else {
			deleteEXIFForSingleFile(source, dest);
		}
	}

	/**
	 * Removes EXIF data from all files in a given source directory and saves
	 * new images into the destination directory. Destination directory is
	 * created if it doesn't exist.
	 *
	 * @param source
	 *            source folder that contains the image files
	 * @param dest
	 *            destination folder where the new images are saved to
	 */
	private void deleteEXIFFromDir(File source, File dest) {
		assert source.isDirectory();
		if (!dest.isDirectory()) {
			if (dest.exists()) {
				System.err.println("destination file is no directory");
				return;
			} else {
				dest.mkdir();
			}

		}
		// create temp folder if destination folder equals source folder
		if (dest.equals(source)) {
			removeAllEXIFFromFolder(source, new File(dest.getAbsolutePath()
					+ FILE_SEPARATOR + TEMP_DIR));
		} else {
			removeAllEXIFFromFolder(source, dest);
		}
	}

	/**
	 * Removes EXIF data from a single image file which is the source file.
	 * Resulting images is saved into the destination file which may be the same
	 * as the source file (in that case the image is overwritten).
	 *
	 * @param source
	 *            source folder that contains the image files
	 * @param dest
	 *            destination folder where the new images are saved to
	 * @throws IOException
	 * @throws ImageReadException
	 * @throws ImageWriteException
	 */
	private void deleteEXIFForSingleFile(File source, File dest)
			throws IOException, ImageReadException, ImageWriteException {
		EXIFRemover remover = new EXIFRemover(source);
		remover.removeEXIFData(dest);
		System.out.println("All EXIF data successfully removed from "
				+ source.getAbsolutePath());
		System.out.println("Result saved in " + dest.getAbsolutePath());
	}

	/**
	 * Deletes EXIF information from every file in a given source folder.
	 * Resulting images are saved the destination folder. The given arguments
	 * files must be directories.
	 *
	 * Directories within the source folder are ignored. Everything else will be
	 * treated as an image.
	 *
	 * @param srcFolder
	 *            source folder that contains the image files
	 * @param destFolder
	 *            destination folder where the new images are saved to
	 */
	private void removeAllEXIFFromFolder(File srcFolder, File destFolder) {
		assert srcFolder.isDirectory() && destFolder.isDirectory();
		File[] files = srcFolder.listFiles();

		if (!destFolder.exists()) {
			destFolder.mkdir();
		}
		for (File file : files) {
			if (file.isFile()) { // make sure that file is no directory

				try {
					EXIFRemover remover = new EXIFRemover(file);
					File destFile = new File(destFolder.getAbsolutePath()
							+ FILE_SEPARATOR + file.getName());
					remover.removeEXIFData(destFile);
					System.out.println("created file "
							+ destFile.getAbsolutePath());
				} catch (IOException e) {
					System.err.println("Can not convert or read file "
							+ file.getAbsolutePath());
				} catch (ImageReadException e) {
					System.err.println("Unable to remove EXIF data from "
							+ file.getAbsolutePath());
				} catch (ImageWriteException e) {
					System.err.println("Unable to remove EXIF data from "
							+ file.getAbsolutePath());
				}
			}
		}
	}

	/**
	 * Initializes command line options like d, s, dest, help.
	 *
	 * @return initialized options
	 */
	private Options initOptions() {
		Options options = new Options();

		options.addOption("v", "version", false, "show version");
		options.addOption("h", "help", false, "print help message");

		options.addOption("s", "show-exif", true, "show exif data");
		options.getOption("s").setArgName("filename");

		options.addOption("d", "delete-exif", true,
				"delete all exif data of given file(s)");
		options.getOption("d").setArgName("filename");

		options.addOption("dest", true, "save changed image(s) into file");
		options.getOption("dest").setArgName("filename");

		return options;
	}

}


text:
namespace node {
namespace debugger {

using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Handle;
using v8::HandleScope;
using v8::Integer;
using v8::Isolate;
using v8::Local;
using v8::Locker;
using v8::Object;
using v8::String;
using v8::Value;

Agent::Agent(Environment* env) : state_(kNone),
                                 port_(5858),
                                 wait_(false),
                                 parent_env_(env),
                                 child_env_(NULL),
                                 dispatch_handler_(NULL) {
  int err;

  err = uv_sem_init(&start_sem_, 0);
  CHECK_EQ(err, 0);

  err = uv_mutex_init(&message_mutex_);
  CHECK_EQ(err, 0);

  QUEUE_INIT(&messages_);
}

Agent::~Agent() {
  Stop();

  uv_sem_destroy(&start_sem_);
  uv_mutex_destroy(&message_mutex_);

  // Clean-up messages
  while (!QUEUE_EMPTY(&messages_)) {
    QUEUE* q = QUEUE_HEAD(&messages_);
    QUEUE_REMOVE(q);
    AgentMessage* msg = ContainerOf(&AgentMessage::member, q);
    delete msg;
  }
}

bool Agent::Start(int port, bool wait) {
  int err;

  if (state_ == kRunning)
    return false;

  err = uv_loop_init(&child_loop_);
  if (err != 0)
    goto loop_init_failed;

  // Interruption signal handler
  err = uv_async_init(&child_loop_, &child_signal_, ChildSignalCb);
  if (err != 0)
    goto async_init_failed;
  uv_unref(reinterpret_cast<uv_handle_t*>(&child_signal_));

  port_ = port;
  wait_ = wait;

  err = uv_thread_create(&thread_,
                         reinterpret_cast<uv_thread_cb>(ThreadCb),
                         this);
  if (err != 0)
    goto thread_create_failed;

  uv_sem_wait(&start_sem_);

  state_ = kRunning;

  return true;

 thread_create_failed:
  uv_close(reinterpret_cast<uv_handle_t*>(&child_signal_), NULL);

 async_init_failed:
  err = uv_loop_close(&child_loop_);
  CHECK_EQ(err, 0);

 loop_init_failed:
  return false;
}

void Agent::Enable() {
  v8::Debug::SetMessageHandler(MessageHandler);

  // Assign environment to the debugger's context
  // NOTE: The debugger context is created after `SetMessageHandler()` call
  parent_env()->AssignToContext(v8::Debug::GetDebugContext());
}

void Agent::Stop() {
  int err;

  if (state_ != kRunning) {
    return;
  }

  v8::Debug::SetMessageHandler(NULL);

  // Send empty message to terminate things
  EnqueueMessage(new AgentMessage(NULL, 0));

  // Signal worker thread to make it stop
  err = uv_async_send(&child_signal_);
  CHECK_EQ(err, 0);

  err = uv_thread_join(&thread_);
  CHECK_EQ(err, 0);

  uv_close(reinterpret_cast<uv_handle_t*>(&child_signal_), NULL);
  uv_run(&child_loop_, UV_RUN_NOWAIT);

  err = uv_loop_close(&child_loop_);
  CHECK_EQ(err, 0);

  state_ = kNone;
}

void Agent::WorkerRun() {
  static const char* argv[] = { "node", "--debug-agent" };
  Isolate* isolate = Isolate::New();
  {
    Locker locker(isolate);
    Isolate::Scope isolate_scope(isolate);

    HandleScope handle_scope(isolate);
    Local<Context> context = Context::New(isolate);

    Context::Scope context_scope(context);
    Environment* env = CreateEnvironment(
        isolate,
        &child_loop_,
        context,
        ARRAY_SIZE(argv),
        argv,
        ARRAY_SIZE(argv),
        argv);

    child_env_ = env;

    // Expose API
    InitAdaptor(env);
    LoadEnvironment(env);

    CHECK_EQ(&child_loop_, env->event_loop());
    uv_run(&child_loop_, UV_RUN_DEFAULT);

    // Clean-up peristent
    api_.Reset();

    // Clean-up all running handles
    env->CleanupHandles();

    env->Dispose();
    env = NULL;
  }
  isolate->Dispose();
}

void Agent::InitAdaptor(Environment* env) {
  Isolate* isolate = env->isolate();
  HandleScope scope(isolate);

  // Create API adaptor
  Local<FunctionTemplate> t = FunctionTemplate::New(isolate);
  t->InstanceTemplate()->SetInternalFieldCount(1);
  t->SetClassName(String::NewFromUtf8(isolate, "DebugAPI"));

  NODE_SET_PROTOTYPE_METHOD(t, "notifyListen", NotifyListen);
  NODE_SET_PROTOTYPE_METHOD(t, "notifyWait", NotifyWait);
  NODE_SET_PROTOTYPE_METHOD(t, "sendCommand", SendCommand);

  Local<Object> api = t->GetFunction()->NewInstance();
  api->SetAlignedPointerInInternalField(0, this);

  api->Set(String::NewFromUtf8(isolate, "port"), Integer::New(isolate, port_));

  env->process_object()->Set(String::NewFromUtf8(isolate, "_debugAPI"), api);
  api_.Reset(env->isolate(), api);
}

Agent* Agent::Unwrap(const v8::FunctionCallbackInfo<v8::Value>& args) {
  void* ptr = args.Holder()->GetAlignedPointerFromInternalField(0);
  return reinterpret_cast<Agent*>(ptr);
}

void Agent::NotifyListen(const FunctionCallbackInfo<Value>& args) {
  Agent* a = Unwrap(args);

  // Notify other thread that we are ready to process events
  uv_sem_post(&a->start_sem_);
}

void Agent::NotifyWait(const FunctionCallbackInfo<Value>& args) {
  Agent* a = Unwrap(args);

  a->wait_ = false;

  int err = uv_async_send(&a->child_signal_);
  CHECK_EQ(err, 0);
}

void Agent::SendCommand(const FunctionCallbackInfo<Value>& args) {
  Agent* a = Unwrap(args);
  Environment* env = a->child_env();
  HandleScope scope(env->isolate());

  String::Value v(args[0]);

  v8::Debug::SendCommand(a->parent_env()->isolate(), *v, v.length());
  if (a->dispatch_handler_ != NULL)
    a->dispatch_handler_(a->parent_env());
}

void Agent::ThreadCb(Agent* agent) {
  agent->WorkerRun();
}

void Agent::ChildSignalCb(uv_async_t* signal) {
  Agent* a = ContainerOf(&Agent::child_signal_, signal);
  Isolate* isolate = a->child_env()->isolate();

  HandleScope scope(isolate);
  Local<Object> api = PersistentToLocal(isolate, a->api_);

  uv_mutex_lock(&a->message_mutex_);
  while (!QUEUE_EMPTY(&a->messages_)) {
    QUEUE* q = QUEUE_HEAD(&a->messages_);
    AgentMessage* msg = ContainerOf(&AgentMessage::member, q);

    // Time to close everything
    if (msg->data() == NULL) {
      QUEUE_REMOVE(q);
      delete msg;

      MakeCallback(isolate, api, "onclose", 0, NULL);
      break;
    }

    // Waiting for client, do not send anything just yet
    // TODO(indutny): move this to js-land
    if (a->wait_)
      break;

    QUEUE_REMOVE(q);
    Local<Value> argv[] = {
      String::NewFromTwoByte(isolate,
                             msg->data(),
                             String::kNormalString,
                             msg->length())
    };

    // Emit message
    MakeCallback(isolate,
                 api,
                 "onmessage",
                 ARRAY_SIZE(argv),
                 argv);
    delete msg;
  }
  uv_mutex_unlock(&a->message_mutex_);
}

void Agent::EnqueueMessage(AgentMessage* message) {
  uv_mutex_lock(&message_mutex_);
  QUEUE_INSERT_TAIL(&messages_, &message->member);
  uv_mutex_unlock(&message_mutex_);
  uv_async_send(&child_signal_);
}

void Agent::MessageHandler(const v8::Debug::Message& message) {
  Isolate* isolate = message.GetIsolate();
  Environment* env = Environment::GetCurrent(isolate);
  Agent* a = env->debugger_agent();
  CHECK_NE(a, NULL);
  CHECK_EQ(isolate, a->parent_env()->isolate());

  HandleScope scope(isolate);
  Local<String> json = message.GetJSON();
  String::Value v(json);

  AgentMessage* msg = new AgentMessage(*v, v.length());
  a->EnqueueMessage(msg);
}

}  // namespace debugger
}  // namespace node


text:
// Copyright (C) 2014 IceMobile Agency B.V.
//
// 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.

/* global describe, it, beforeEach */
var Firgilio = require('../');

describe('Firgilio.loadModule()', function() {
    var ns = null;
    var firgilioOptions = {
        logger: {
            streams: []
        }
    };

    beforeEach(function() {
        ns = Firgilio.create(firgilioOptions);
    });

    it('loads a named module only once', function() {
        var executeCount = 0;
            function testModule() {
                executeCount++;
            }
        Firgilio
            .loadModule(ns, testModule)
            .loadModule(ns, testModule);
        executeCount.must.equal(1);
    });

    it('gets access to the options object', function(done) {
        Firgilio.loadModule(ns, function(ctx, moduleOptions) {
            moduleOptions.must.be(firgilioOptions);
            done();
        });
    });

    describe('it throws an error when loading an invalid module', function() {
        var nonModules = [{}, [1, 2], null, void(0), 'test', /test/];
        nonModules.forEach(function(nonModule) {
            it('throws an error when loading: ' + nonModule, function() {
                var testFunction = function() {
                    Firgilio.loadModule(ns, nonModule);
                };
                testFunction.must.throw(/called with invalid arguments/);
            });
        });
    });
});


text:
package org.ethontos.phylontal.project.impl;

import org.ethontos.phylontal.project.AnnotationTriple;

class AnnotationTripleImpl implements AnnotationTriple{

    private Object subject;
    private Object predicate;
    private Object obj;

    AnnotationTripleImpl(Object s, Object p, Object o){
        subject = s;
        predicate = p;
        obj = o;
    }

    @Override
    public Object getObject() {
        return obj;
    }

    @Override
    public Object getPredicate() {
        return predicate;
    }

    @Override
    public Object getSubject() {
        return subject;
    }

    public String toString(){
        return "<Subject: " + getSubject() + "; " + getPredicate() + "; " + getObject() + ">";
    }
}


text:
name: Bug report
about: Create a report to help us improve
title: "[BUG]"
labels: bug
assignees: ''

---

**Logging**
Add relevant SDK logging.  IMPORTANT NOTE:  Please make sure to NOT share AWS access credentials under any circumstance!  Please make sure they are not in the logs.

**Describe the bug**
A clear and concise description of what the bug is.

**SDK version number**
Include the SDK version you are running. If it is a specific commit on master branch, include that

**Open source building**
If it is a build issue, include 3rd party library version and steps to how you are building it

**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

**Expected behavior**
A clear and concise description of what you expected to happen.

**Screenshots**
If applicable, add screenshots to help explain your problem.

**Desktop (please complete the following information):**
 - OS: [e.g. iOS]
 - Browser [e.g. chrome, safari]
 - Version [e.g. 22]

**Smartphone (please complete the following information):**
 - Device: [e.g. iPhone6]
 - OS: [e.g. iOS8.1]
 - Browser [e.g. stock browser, safari]
 - Version [e.g. 22]

**Additional context**
Add any other context about the problem here.


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace NetCoreCMS.Framework.Core.Data
{
    public class NccDbQueryText
    {
        public string MySql_QueryText { get; set; }
        public string MSSql_QueryText { get; set; }
        public string SQLite_QueryText { get; set; }
    }
}


text:
<?php
	/* Set e-mail recipient */
	$myemail = "bhaktaj7@students.rowan.edu";

	// set CC and BCC recipients
	// $emailForCC = "bayrunsp9@students.rowan.edu";
	// $emailForBcc = "";

	/* Check all form inputs using check_input function */
	$name = check_input($_POST['name'], "Enter your name");
	$subject = check_input($_POST['subject'], "Enter a subject");
	$email = check_input($_POST['email']);
	$message = check_input($_POST['message'], "Write your message");
	$userIpAddress = $_SERVER["REMOTE_ADDR"];

	/* If e-mail is not valid show error message */
	if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
	{
		show_error("E-mail address not valid");
	}

	// get the 'From' part of email
	$emailHeaders = "From: $email . \r\n";
	// for CC
	// $emailHeaders .= "Cc: $emailForCC . \r\n";
	// for BCC
	// $emailHeaders .= "Bcc: $emailForBcc . \r\n";

	/* Let's prepare the message for the e-mail */
	$message = "

	IP Address recorded: $userIpAddress
	Name: $name
	E-mail: $email
	Subject: $subject

	Message:
	$message

	";

	/* Send the message using mail() function */
	mail($myemail, $subject, $message, $emailHeaders);

	/* Redirect visitor to the home page */
	header('Location: index.html');
	exit();

	/* Functions we used */
	function check_input($data, $problem='')
	{
		$data = trim($data);
		$data = stripslashes($data);
		$data = htmlspecialchars($data);
		if ($problem && strlen($data) == 0)
		{
			show_error($problem);
		}
		return $data;
	}

	function show_error($myError)
	{
?>

Please correct the following error:

		 <?php echo $myError; ?>

Hit the back button and try again

<?php
		exit();
	}
?>


text:
$(function(){
  $( 'textarea' ).on( 'toggleAutoWrap', function( event, state ){
    console.log( 'autowrap', state );
  });

  $( 'textarea' ).textWrapper();
});


text:
<!DOCTYPE HTML>

    <title>iOS Docs | TinyCrayon</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="apple-touch-icon" sizes="180x180" href="https://tinycrayon.github.io/TinyCrayon-iOS-SDK/favicons/apple-touch-icon.png">
    <link rel="icon" type="image/png" href="https://tinycrayon.github.io/TinyCrayon-iOS-SDK/favicons/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="https://tinycrayon.github.io/TinyCrayon-iOS-SDK/favicons/favicon-16x16.png" sizes="16x16">
    <link rel="manifest" href="https://tinycrayon.github.io/TinyCrayon-iOS-SDK/favicons/manifest.json">
    <link rel="mask-icon" href="https://tinycrayon.github.io/TinyCrayon-iOS-SDK/favicons/safari-pinned-tab.svg" color="#5bbad5">

    <meta name="theme-color" content="#ffffff"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="https://tinycrayon.github.io/TinyCrayon-iOS-SDK/css/index.css">
    <link rel="stylesheet" type="text/css" href="https://tinycrayon.github.io/TinyCrayon-iOS-SDK/css/iconfont.css">

<link rel="stylesheet" type="text/css" href="https://tinycrayon.github.io/TinyCrayon-iOS-SDK/css/highlight.css">
<link rel="stylesheet" type="text/css" href="https://tinycrayon.github.io/TinyCrayon-iOS-SDK/css/jazzy.css">

TinyCrayon

Home

Guides

Docs

FAQ

  TinyCrayon Reference

  Protocols Reference

        Classes

            TCMask

            TCMaskView

            TCMaskViewMode

            TCUIView

        Enums

            TCMaskTool

        Protocols

            TCMaskViewDelegate

Protocols

The following protocols are available globally.

              TCMaskViewDelegate

Delegate methods for TCMaskView, which includes:

tcMaskViewDidExit: is called after TCMaskView exits

tcMaskViewDidComplete: is called after a popup TCMaskView completes

tcMaskViewWillPushViewController: is called before navigation controller is about to accomplish TCMaskView and process to the next UIViewController

                See more

Declaration

Swift

protocol TCMaskViewDelegate

Objective-C

@protocol TCMaskViewDelegate

            Contact Support

            Privacy Policy

            Terms of Use

Copyright © 2017 TinyCrayon. All rights reserved


text:
package com.eaw1805.www.client.views.economy.trade;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseEvent;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.eaw1805.data.constants.ArmyConstants;
import com.eaw1805.data.constants.GoodConstants;
import com.eaw1805.data.constants.OrderConstants;
import com.eaw1805.data.dto.common.SectorDTO;
import com.eaw1805.data.dto.web.ClientOrderDTO;
import com.eaw1805.data.dto.web.OrderCostDTO;
import com.eaw1805.data.dto.web.economy.BaggageTrainDTO;
import com.eaw1805.www.client.gui.eventHandlers.DelEventHandlerAbstract;
import com.eaw1805.www.client.widgets.ClickAbsolutePanel;
import com.eaw1805.www.client.widgets.DraggablePanel;
import com.eaw1805.www.client.widgets.ImageButton;
import com.eaw1805.www.client.widgets.RenamingLabel;
import com.eaw1805.www.shared.stores.GameStore;
import com.eaw1805.www.shared.stores.economy.OrderStore;
import com.eaw1805.www.shared.stores.units.BaggageTrainStore;
import com.eaw1805.www.shared.stores.util.calculators.CostCalculators;

import java.util.List;

public class BuildRepairBaggageTrainView extends DraggablePanel implements
        ArmyConstants, OrderConstants, GoodConstants {
    private final Label lblBuildrepairBaggageTrains, lblBuild, lblCosts,
            lblCitizents, lblWoodTons, lblHorses;
    private final Button btnPlaceOrder;
    private final ScrollPanel newBtrainsScroll;
    private final Label lblBuiltThisTurn;
    private final VerticalPanel newBtrainsPanel;
    private final Label lblRepairBaggagetrains, lblAvailable;
    private final ScrollPanel avBtrainScroll, repairBtrainScroll;
    private final Label lblRepairing;
    private final VerticalPanel avBtrainPanel, repairBtrainPanel;
    private final Image moneyImg, peopleImg, horsesImg, woodImg;
    private final Label moneyLbl, peopelLbl, woodLbl, horsesLabel;
    private final Label lblNameTitle;
    private final RenamingLabel lblName;
    private final Label lblRepair;
    private final Label lblIndPoints;

    public BuildRepairBaggageTrainView(final SectorDTO bsector) {

        this.setStyleName("barracksNTPanel");

        this.setSize("642px", "616px");

        this.lblBuildrepairBaggageTrains = new Label(
                "Build/Repair Baggage Trains");
        this.lblBuildrepairBaggageTrains
                .setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
        this.lblBuildrepairBaggageTrains.setStyleName("clearFont-large whiteText");
        this.add(this.lblBuildrepairBaggageTrains, 0, 29);
        this.lblBuildrepairBaggageTrains.setSize("642px", "32px");

        final BuildRepairBaggageTrainView myself = this;

        final ImageButton imgX = new ImageButton("http://static.eaw1805.com/images/buttons/ButAcceptOff.png");
        imgX.setStyleName("pointer");
        imgX.setTitle("Close panel");

        (new DelEventHandlerAbstract() {
            @Override
            public void execute(final MouseEvent event) {
                GameStore.getInstance().getLayoutView().removeWidgetFromPanelEAW(myself);
                imgX.deselect();
            }
        }).addToElement(imgX.getElement()).register();

        this.add(imgX, 573, 26);
        imgX.setSize("36px", "36px");

        this.lblBuild = new Label("Build baggage train:");
        this.lblBuild.setStyleName("clearFontMiniTitle whiteText");
        this.add(this.lblBuild, 108, 76);

        this.lblCosts = new Label("Cost: 300,000 pounds");
        this.lblCosts.setStyleName("clearFont whiteText");
        this.add(this.lblCosts, 128, 147);

        this.lblCitizents = new Label("Citizents: 1000");
        this.lblCitizents.setStyleName("clearFont whiteText");
        this.add(this.lblCitizents, 128, 171);

        this.lblWoodTons = new Label("Wood: 500 tons");
        this.lblWoodTons.setStyleName("clearFont whiteText");
        this.add(this.lblWoodTons, 286, 147);

        this.lblHorses = new Label("Horses:2000");
        this.lblHorses.setStyleName("clearFont whiteText");
        this.add(this.lblHorses, 286, 169);

        this.btnPlaceOrder = new Button("Place Order");
        this.btnPlaceOrder.addClickHandler(new ClickHandler() {
            public void onClick(final ClickEvent event) {
                BaggageTrainStore.getInstance().buildNewBaggageTrain(bsector,
                        lblName.getText());
                lblName.setText("Baggage Train "
                        + BaggageTrainStore.getInstance().getTotalSize());
                refreshNewBtrainsPanel(bsector);
            }
        });
        this.add(this.btnPlaceOrder, 291, 193);

        this.newBtrainsScroll = new ScrollPanel();
        this.newBtrainsScroll.setStyleName("noScrollBars");
        this.newBtrainsScroll.setStyleName("prodSitePanelSel", true);
        this.add(this.newBtrainsScroll, 406, 102);
        this.newBtrainsScroll.setSize("158px", "192px");

        this.newBtrainsPanel = new VerticalPanel();
        this.newBtrainsScroll.setWidget(this.newBtrainsPanel);
        this.newBtrainsPanel.setSize("100%", "100%");

        this.lblBuiltThisTurn = new Label("Built this turn:");
        this.lblBuiltThisTurn.setStyleName("clearFontMiniTitle whiteText");
        this.add(this.lblBuiltThisTurn, 406, 76);

        this.lblRepairBaggagetrains = new Label("Repair BaggageTrains:");
        this.lblRepairBaggagetrains.setStyleName("clearFontMiniTitle whiteText");
        this.add(this.lblRepairBaggagetrains, 108, 290);

        this.lblAvailable = new Label("Available:");
        this.lblAvailable.setStyleName("clearFont whiteText");
        this.add(this.lblAvailable, 108, 316);

        this.avBtrainScroll = new ScrollPanel();
        this.avBtrainScroll.setStyleName("noScrollBars");
        this.avBtrainScroll.setStyleName("evenRow", true);
        this.add(this.avBtrainScroll, 108, 340);
        this.avBtrainScroll.setSize("158px", "192px");

        this.avBtrainPanel = new VerticalPanel();
        this.avBtrainScroll.setWidget(this.avBtrainPanel);
        this.avBtrainPanel.setSize("100%", "100%");

        this.repairBtrainScroll = new ScrollPanel();
        this.repairBtrainScroll.setStyleName("noScrollBars");
        this.repairBtrainScroll.setStyleName("oddRow", true);
        this.add(this.repairBtrainScroll, 406, 340);
        this.repairBtrainScroll.setSize("158px", "192px");

        this.repairBtrainPanel = new VerticalPanel();
        this.repairBtrainScroll.setWidget(this.repairBtrainPanel);
        this.repairBtrainPanel.setSize("100%", "100%");

        this.lblRepairing = new Label("Repairing:");
        this.lblRepairing.setStyleName("clearFont whiteText");
        this.add(this.lblRepairing, 406, 316);

        this.moneyImg = new Image("http://static.eaw1805.com/images/goods/good-1.png");
        this.moneyImg.setTitle("Money needed for repairs");
        this.add(this.moneyImg, 272, 367);
        this.moneyImg.setSize("24px", "24px");

        this.peopleImg = new Image("http://static.eaw1805.com/images/goods/good-2.png");
        this.peopleImg.setTitle("People needed for repairs");
        this.add(this.peopleImg, 272, 397);
        this.peopleImg.setSize("24px", "24px");

        this.horsesImg = new Image("http://static.eaw1805.com/images/goods/good-9.png");
        this.horsesImg.setTitle("Horses needed for repairs");
        this.add(this.horsesImg, 272, 499);
        this.horsesImg.setSize("24px", "24px");

        this.woodImg = new Image("http://static.eaw1805.com/images/goods/good-6.png");
        this.woodImg.setTitle("Wood needed for repairs");
        this.add(this.woodImg, 272, 469);
        this.woodImg.setSize("24px", "24px");

        this.moneyLbl = new Label("0");
        this.add(this.moneyLbl, 302, 376);

        this.peopelLbl = new Label("0");
        this.add(this.peopelLbl, 302, 406);

        this.woodLbl = new Label("0");
        this.add(this.woodLbl, 302, 478);

        this.horsesLabel = new Label("0");
        this.add(this.horsesLabel, 302, 508);

        this.lblNameTitle = new Label("Name:");
        this.lblNameTitle.setStyleName("clearFontMiniTitle whiteText");
        this.add(this.lblNameTitle, 118, 108);

        this.lblName = new RenamingLabel("Baggage Train "
                + BaggageTrainStore.getInstance().getTotalSize(), BAGGAGETRAIN,
                -1);
        this.lblName.setStyleName("clearFontDual whiteText");
        this.add(this.lblName, 176, 108);
        this.lblName.setSize("203px", "20px");

        this.lblRepair = new Label("Repair %:");
        this.lblRepair.setStyleName("clearFont whiteText");
        this.add(this.lblRepair, 287, 438);

        this.lblIndPoints = new Label("Ind. Points: 500");
        this.lblIndPoints.setStyleName("clearFont whiteText");
        this.add(this.lblIndPoints, 128, 193);

        refreshNewBtrainsPanel(bsector);
        refreshAvailablePanel(bsector);
        refreshRepairBtrainsPanel(bsector);

    }

    private void refreshNewBtrainsPanel(final SectorDTO sector) {
        newBtrainsPanel.clear();
        for (Integer sIds : BaggageTrainStore.getInstance().getNewBaggageTMap()
                .keySet()) {
            final Label sectorTitle = new Label("Order on sector:" + sIds);
            newBtrainsPanel.add(sectorTitle);
            for (BaggageTrainDTO btrain : BaggageTrainStore.getInstance()
                    .getNewBaggageTMap().get(sIds)) {
                final AbsolutePanel newBtrainPanel = new AbsolutePanel();
                newBtrainPanel.setSize("100%", "20px");
                final Label bTrainName = new Label("Name: " + btrain.getName());
                bTrainName.setWidth("145px");
                bTrainName.setStyleName("clearFont whiteText");
                bTrainName.setStyleName("evenRow", true);
                newBtrainPanel.add(bTrainName, 0, 0);
                if (sector.getId() == sIds) {
                    final Label cancelBuild = new Label("X");
                    cancelBuild.setWidth("13px");
                    newBtrainPanel.add(cancelBuild, 145, 0);
                    final int btrainId = btrain.getId();
                    cancelBuild.addClickHandler(new ClickHandler() {
                        public void onClick(final ClickEvent event) {
                            BaggageTrainStore.getInstance().removeBuildOrder(
                                    sector, btrainId);
                            lblName.setText("Baggage Train "
                                    + BaggageTrainStore.getInstance().getTotalSize());
                            refreshNewBtrainsPanel(sector);

                        }
                    });
                }
                newBtrainsPanel.add(newBtrainPanel);
            }

        }
    }

    private void refreshAvailablePanel(final SectorDTO bsector) {
        avBtrainPanel.clear();
        final List<BaggageTrainDTO> baggageTrains = BaggageTrainStore.getInstance()
                .getBaggageTrainsBySector(bsector, true);
        for (final BaggageTrainDTO btrain : baggageTrains) {
            if (btrain.getCondition() < 100) {
                final ClickAbsolutePanel newBtrainPanel = new ClickAbsolutePanel();
                newBtrainPanel.setSize("100%", "20px");
                final Label bTrainName = new Label("Name: " + btrain.getName());
                bTrainName.setWidth("145px");
                bTrainName.setStyleName("clearFont whiteText");
                bTrainName.setStyleName("evenRow", true);
                newBtrainPanel.add(bTrainName, 0, 0);
                final Image addBuild = new Image("http://static.eaw1805.com/images/buttons/ZoomIn.png");
                addBuild.setSize("13px", "13px");
                addBuild.setStyleName("pointer");
                newBtrainPanel.add(addBuild, 145, 0);
                final int btrainId = btrain.getId();
                addBuild.addClickHandler(new ClickHandler() {
                    public void onClick(final ClickEvent event) {
                        BaggageTrainStore.getInstance().addRepairOrder(
                                btrainId, bsector.getId());
                        refreshAvailablePanel(bsector);
                        refreshRepairBtrainsPanel(bsector);
                    }
                });
                newBtrainPanel.addMouseOverHandler(new MouseOverHandler() {
                    public void onMouseOver(final MouseOverEvent event) {
                        populateRepairCostLabels(btrain.getCondition());
                    }
                });
                newBtrainPanel.addMouseOutHandler(new MouseOutHandler() {
                    public void onMouseOut(final MouseOutEvent event) {
                        populateRepairCostLabels(100);

                    }
                });
                avBtrainPanel.add(newBtrainPanel);
            }
        }
    }

    private void refreshRepairBtrainsPanel(final SectorDTO bsector) {
        repairBtrainPanel.clear();
        final List<ClientOrderDTO> repairOrders = OrderStore.getInstance()
                .getClientOrders().get(ORDER_R_BTRAIN);
        if (repairOrders != null && !repairOrders.isEmpty()) {
            for (ClientOrderDTO order : repairOrders) {
                if (order.getIdentifier(1) == bsector.getId()) {
                    final BaggageTrainDTO btrain = BaggageTrainStore.getInstance()
                            .getBaggageTMap().get(order.getIdentifier(0));
                    final AbsolutePanel newBtrainPanel = new AbsolutePanel();
                    newBtrainPanel.setSize("100%", "20px");
                    final Label bTrainName = new Label("Name: " + btrain.getName());
                    bTrainName.setWidth("145px");
                    bTrainName.setStyleName("clearFont whiteText");
                    bTrainName.setStyleName("evenRow", true);
                    newBtrainPanel.add(bTrainName, 0, 0);
                    final Image addBuild = new Image("http://static.eaw1805.com/images/buttons/ZoomOutSlc.png");
                    addBuild.setSize("13px", "13px");
                    addBuild.setStyleName("pointer");
                    newBtrainPanel.add(addBuild, 145, 0);
                    final int btrainId = btrain.getId();
                    addBuild.addClickHandler(new ClickHandler() {
                        public void onClick(final ClickEvent event) {
                            BaggageTrainStore.getInstance().cancelRepairOrder(
                                    btrainId, bsector.getId());
                            refreshAvailablePanel(bsector);
                            refreshRepairBtrainsPanel(bsector);
                        }
                    });
                    repairBtrainPanel.add(newBtrainPanel);
                }
            }
        }

    }

    private void populateRepairCostLabels(final int condition) {
        final OrderCostDTO baggageTrainCost = CostCalculators.getBaggageTrainRepairCost(condition);
        lblRepair.setText("Condition %:" + (condition));
        woodLbl.setText(baggageTrainCost.getNumericCost(GOOD_WOOD) + " tons");
        moneyLbl.setText(baggageTrainCost.getNumericCost(GOOD_MONEY) + " pounds");
        peopelLbl.setText(baggageTrainCost.getNumericCost(GOOD_PEOPLE) + " people");
        horsesLabel.setText(baggageTrainCost.getNumericCost(GOOD_HORSE) + " horses");
    }
}


text:
This is my implementation of a JWT based Grails restful API

Currently it is set up to bridge between CAS and JWT. I'll need to generalize that in the future as well as pull out some ERP
based code.