text:
#include "config.h"
#include "platform/image-decoders/png/PNGImageDecoder.h"

#include "platform/PlatformInstrumentation.h"
#include "wtf/PassOwnPtr.h"

#include "png.h"
#if !defined(PNG_LIBPNG_VER_MAJOR) || !defined(PNG_LIBPNG_VER_MINOR)
#error version error: compile against a versioned libpng.
#endif
#if USE(QCMSLIB)
#include "qcms.h"
#endif

#if PNG_LIBPNG_VER_MAJOR > 1 || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 4)
#define JMPBUF(png_ptr) png_jmpbuf(png_ptr)
#else
#define JMPBUF(png_ptr) png_ptr->jmpbuf
#endif

namespace {

inline blink::PNGImageDecoder* imageDecoder(png_structp png)
{
    return static_cast<blink::PNGImageDecoder*>(png_get_progressive_ptr(png));
}

void PNGAPI pngHeaderAvailable(png_structp png, png_infop)
{
    imageDecoder(png)->headerAvailable();
}

void PNGAPI pngRowAvailable(png_structp png, png_bytep row, png_uint_32 rowIndex, int state)
{
    imageDecoder(png)->rowAvailable(row, rowIndex, state);
}

void PNGAPI pngComplete(png_structp png, png_infop)
{
    imageDecoder(png)->complete();
}

void PNGAPI pngFailed(png_structp png, png_const_charp)
{
    longjmp(JMPBUF(png), 1);
}

} // anonymous

namespace blink {

class PNGImageReader {
    WTF_MAKE_FAST_ALLOCATED;
public:
    PNGImageReader(PNGImageDecoder* decoder)
        : m_decoder(decoder)
        , m_readOffset(0)
        , m_currentBufferSize(0)
        , m_decodingSizeOnly(false)
        , m_hasAlpha(false)
#if USE(QCMSLIB)
        , m_transform(0)
        , m_rowBuffer()
#endif
    {
        m_png = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, pngFailed, 0);
        m_info = png_create_info_struct(m_png);
        png_set_progressive_read_fn(m_png, m_decoder, pngHeaderAvailable, pngRowAvailable, pngComplete);
    }

    ~PNGImageReader()
    {
        close();
    }

    void close()
    {
        if (m_png && m_info)
            // This will zero the pointers.
            png_destroy_read_struct(&m_png, &m_info, 0);
#if USE(QCMSLIB)
        clearColorTransform();
#endif
        m_readOffset = 0;
    }

    bool decode(const SharedBuffer& data, bool sizeOnly)
    {
        m_decodingSizeOnly = sizeOnly;

        // We need to do the setjmp here. Otherwise bad things will happen.
        if (setjmp(JMPBUF(m_png)))
            return m_decoder->setFailed();

        const char* segment;
        while (unsigned segmentLength = data.getSomeData(segment, m_readOffset)) {
            m_readOffset += segmentLength;
            m_currentBufferSize = m_readOffset;
            png_process_data(m_png, m_info, reinterpret_cast<png_bytep>(const_cast<char*>(segment)), segmentLength);
            // We explicitly specify the superclass isSizeAvailable() because we
            // merely want to check if we've managed to set the size, not
            // (recursively) trigger additional decoding if we haven't.
            if (sizeOnly ? m_decoder->ImageDecoder::isSizeAvailable() : m_decoder->isComplete())
                return true;
        }

        return false;
    }

    png_structp pngPtr() const { return m_png; }
    png_infop infoPtr() const { return m_info; }

    void setReadOffset(unsigned offset) { m_readOffset = offset; }
    unsigned currentBufferSize() const { return m_currentBufferSize; }
    bool decodingSizeOnly() const { return m_decodingSizeOnly; }
    void setHasAlpha(bool hasAlpha) { m_hasAlpha = hasAlpha; }
    bool hasAlpha() const { return m_hasAlpha; }

    png_bytep interlaceBuffer() const { return m_interlaceBuffer.get(); }
    void createInterlaceBuffer(int size) { m_interlaceBuffer = adoptArrayPtr(new png_byte[size]); }
#if USE(QCMSLIB)
    png_bytep rowBuffer() const { return m_rowBuffer.get(); }
    void createRowBuffer(int size) { m_rowBuffer = adoptArrayPtr(new png_byte[size]); }
    qcms_transform* colorTransform() const { return m_transform; }

    void clearColorTransform()
    {
        if (m_transform)
            qcms_transform_release(m_transform);
        m_transform = 0;
    }

    void createColorTransform(const ColorProfile& colorProfile, bool hasAlpha, bool sRGB)
    {
        clearColorTransform();

        if (colorProfile.isEmpty() && !sRGB)
            return;
        qcms_profile* deviceProfile = ImageDecoder::qcmsOutputDeviceProfile();
        if (!deviceProfile)
            return;
        qcms_profile* inputProfile = 0;
        if (!colorProfile.isEmpty())
            inputProfile = qcms_profile_from_memory(colorProfile.data(), colorProfile.size());
        else
            inputProfile = qcms_profile_sRGB();
        if (!inputProfile)
            return;
        // We currently only support color profiles for RGB and RGBA images.
        ASSERT(icSigRgbData == qcms_profile_get_color_space(inputProfile));
        qcms_data_type dataFormat = hasAlpha ? QCMS_DATA_RGBA_8 : QCMS_DATA_RGB_8;
        // FIXME: Don't force perceptual intent if the image profile contains an intent.
        m_transform = qcms_transform_create(inputProfile, dataFormat, deviceProfile, dataFormat, QCMS_INTENT_PERCEPTUAL);
        qcms_profile_release(inputProfile);
    }
#endif

private:
    png_structp m_png;
    png_infop m_info;
    PNGImageDecoder* m_decoder;
    unsigned m_readOffset;
    unsigned m_currentBufferSize;
    bool m_decodingSizeOnly;
    bool m_hasAlpha;
    OwnPtr<png_byte[]> m_interlaceBuffer;
#if USE(QCMSLIB)
    qcms_transform* m_transform;
    OwnPtr<png_byte[]> m_rowBuffer;
#endif
};

PNGImageDecoder::PNGImageDecoder(ImageSource::AlphaOption alphaOption, ImageSource::GammaAndColorProfileOption colorOptions, size_t maxDecodedBytes)
    : ImageDecoder(alphaOption, colorOptions, maxDecodedBytes)
    , m_hasColorProfile(false)
{
}

PNGImageDecoder::~PNGImageDecoder()
{
}

bool PNGImageDecoder::isSizeAvailable()
{
    if (!ImageDecoder::isSizeAvailable())
         decode(true);

    return ImageDecoder::isSizeAvailable();
}

ImageFrame* PNGImageDecoder::frameBufferAtIndex(size_t index)
{
    if (index)
        return 0;

    if (m_frameBufferCache.isEmpty()) {
        m_frameBufferCache.resize(1);
        m_frameBufferCache[0].setPremultiplyAlpha(m_premultiplyAlpha);
    }

    ImageFrame& frame = m_frameBufferCache[0];
    if (frame.status() != ImageFrame::FrameComplete) {
        PlatformInstrumentation::willDecodeImage("PNG");
        decode(false);
        PlatformInstrumentation::didDecodeImage();
    }

    frame.notifyBitmapIfPixelsChanged();
    return &frame;
}

#if USE(QCMSLIB)
static void getColorProfile(png_structp png, png_infop info, ColorProfile& colorProfile, bool& sRGB)
{
#ifdef PNG_iCCP_SUPPORTED
    ASSERT(colorProfile.isEmpty());
    if (png_get_valid(png, info, PNG_INFO_sRGB)) {
        sRGB = true;
        return;
    }

    char* profileName;
    int compressionType;
#if (PNG_LIBPNG_VER < 10500)
    png_charp profile;
#else
    png_bytep profile;
#endif
    png_uint_32 profileLength;
    if (!png_get_iCCP(png, info, &profileName, &compressionType, &profile, &profileLength))
        return;

    // Only accept RGB color profiles from input class devices.
    bool ignoreProfile = false;
    char* profileData = reinterpret_cast<char*>(profile);
    if (profileLength < ImageDecoder::iccColorProfileHeaderLength)
        ignoreProfile = true;
    else if (!ImageDecoder::rgbColorProfile(profileData, profileLength))
        ignoreProfile = true;
    else if (!ImageDecoder::inputDeviceColorProfile(profileData, profileLength))
        ignoreProfile = true;

    if (!ignoreProfile)
        colorProfile.append(profileData, profileLength);
#endif
}
#endif

void PNGImageDecoder::headerAvailable()
{
    png_structp png = m_reader->pngPtr();
    png_infop info = m_reader->infoPtr();
    png_uint_32 width = png_get_image_width(png, info);
    png_uint_32 height = png_get_image_height(png, info);

    // Protect against large PNGs. See http://bugzil.la/251381 for more details.
    const unsigned long maxPNGSize = 1000000UL;
    if (width > maxPNGSize || height > maxPNGSize) {
        longjmp(JMPBUF(png), 1);
        return;
    }

    // Set the image size now that the image header is available.
    if (!setSize(width, height)) {
        longjmp(JMPBUF(png), 1);
        return;
    }

    int bitDepth, colorType, interlaceType, compressionType, filterType, channels;
    png_get_IHDR(png, info, &width, &height, &bitDepth, &colorType, &interlaceType, &compressionType, &filterType);

    // The options we set here match what Mozilla does.

    // Expand to ensure we use 24-bit for RGB and 32-bit for RGBA.
    if (colorType == PNG_COLOR_TYPE_PALETTE || (colorType == PNG_COLOR_TYPE_GRAY && bitDepth < 8))
        png_set_expand(png);

    png_bytep trns = 0;
    int trnsCount = 0;
    if (png_get_valid(png, info, PNG_INFO_tRNS)) {
        png_get_tRNS(png, info, &trns, &trnsCount, 0);
        png_set_expand(png);
    }

    if (bitDepth == 16)
        png_set_strip_16(png);

    if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
        png_set_gray_to_rgb(png);

#if USE(QCMSLIB)
    if ((colorType & PNG_COLOR_MASK_COLOR) && !m_ignoreGammaAndColorProfile) {
        // We only support color profiles for color PALETTE and RGB[A] PNG. Supporting
        // color profiles for gray-scale images is slightly tricky, at least using the
        // CoreGraphics ICC library, because we expand gray-scale images to RGB but we
        // do not similarly transform the color profile. We'd either need to transform
        // the color profile or we'd need to decode into a gray-scale image buffer and
        // hand that to CoreGraphics.
        bool sRGB = false;
        ColorProfile colorProfile;
        getColorProfile(png, info, colorProfile, sRGB);
        bool imageHasAlpha = (colorType & PNG_COLOR_MASK_ALPHA) || trnsCount;
        m_reader->createColorTransform(colorProfile, imageHasAlpha, sRGB);
        m_hasColorProfile = !!m_reader->colorTransform();
    }
#endif

    if (!m_hasColorProfile) {
        // Deal with gamma and keep it under our control.
        const double inverseGamma = 0.45455;
        const double defaultGamma = 2.2;
        double gamma;
        if (!m_ignoreGammaAndColorProfile && png_get_gAMA(png, info, &gamma)) {
            const double maxGamma = 21474.83;
            if ((gamma <= 0.0) || (gamma > maxGamma)) {
                gamma = inverseGamma;
                png_set_gAMA(png, info, gamma);
            }
            png_set_gamma(png, defaultGamma, gamma);
        } else {
            png_set_gamma(png, defaultGamma, inverseGamma);
        }
    }

    // Tell libpng to send us rows for interlaced pngs.
    if (interlaceType == PNG_INTERLACE_ADAM7)
        png_set_interlace_handling(png);

    // Update our info now.
    png_read_update_info(png, info);
    channels = png_get_channels(png, info);
    ASSERT(channels == 3 || channels == 4);

    m_reader->setHasAlpha(channels == 4);

    if (m_reader->decodingSizeOnly()) {
        // If we only needed the size, halt the reader.
#if PNG_LIBPNG_VER_MAJOR > 1 || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 5)
        // '0' argument to png_process_data_pause means: Do not cache unprocessed data.
        m_reader->setReadOffset(m_reader->currentBufferSize() - png_process_data_pause(png, 0));
#else
        m_reader->setReadOffset(m_reader->currentBufferSize() - png->buffer_size);
        png->buffer_size = 0;
#endif
    }
}

void PNGImageDecoder::rowAvailable(unsigned char* rowBuffer, unsigned rowIndex, int)
{
    if (m_frameBufferCache.isEmpty())
        return;

    // Initialize the framebuffer if needed.
    ImageFrame& buffer = m_frameBufferCache[0];
    if (buffer.status() == ImageFrame::FrameEmpty) {
        png_structp png = m_reader->pngPtr();
        if (!buffer.setSize(size().width(), size().height())) {
            longjmp(JMPBUF(png), 1);
            return;
        }

        unsigned colorChannels = m_reader->hasAlpha() ? 4 : 3;
        if (PNG_INTERLACE_ADAM7 == png_get_interlace_type(png, m_reader->infoPtr())) {
            m_reader->createInterlaceBuffer(colorChannels * size().width() * size().height());
            if (!m_reader->interlaceBuffer()) {
                longjmp(JMPBUF(png), 1);
                return;
            }
        }

#if USE(QCMSLIB)
        if (m_reader->colorTransform()) {
            m_reader->createRowBuffer(colorChannels * size().width());
            if (!m_reader->rowBuffer()) {
                longjmp(JMPBUF(png), 1);
                return;
            }
        }
#endif
        buffer.setStatus(ImageFrame::FramePartial);
        buffer.setHasAlpha(false);

        // For PNGs, the frame always fills the entire image.
        buffer.setOriginalFrameRect(IntRect(IntPoint(), size()));
    }

    /* libpng comments (here to explain what follows).
     *
     * this function is called for every row in the image. If the
     * image is interlacing, and you turned on the interlace handler,
     * this function will be called for every row in every pass.
     * Some of these rows will not be changed from the previous pass.
     * When the row is not changed, the new_row variable will be NULL.
     * The rows and passes are called in order, so you don't really
     * need the row_num and pass, but I'm supplying them because it
     * may make your life easier.
     */

    // Nothing to do if the row is unchanged, or the row is outside
    // the image bounds: libpng may send extra rows, ignore them to
    // make our lives easier.
    if (!rowBuffer)
        return;
    int y = rowIndex;
    if (y < 0 || y >= size().height())
        return;

    /* libpng comments (continued).
     *
     * For the non-NULL rows of interlaced images, you must call
     * png_progressive_combine_row() passing in the row and the
     * old row.  You can call this function for NULL rows (it will
     * just return) and for non-interlaced images (it just does the
     * memcpy for you) if it will make the code easier. Thus, you
     * can just do this for all cases:
     *
     *    png_progressive_combine_row(png_ptr, old_row, new_row);
     *
     * where old_row is what was displayed for previous rows. Note
     * that the first pass (pass == 0 really) will completely cover
     * the old row, so the rows do not have to be initialized. After
     * the first pass (and only for interlaced images), you will have
     * to pass the current row, and the function will combine the
     * old row and the new row.
     */

    bool hasAlpha = m_reader->hasAlpha();
    png_bytep row = rowBuffer;

    if (png_bytep interlaceBuffer = m_reader->interlaceBuffer()) {
        unsigned colorChannels = hasAlpha ? 4 : 3;
        row = interlaceBuffer + (rowIndex * colorChannels * size().width());
        png_progressive_combine_row(m_reader->pngPtr(), row, rowBuffer);
    }

#if USE(QCMSLIB)
    if (qcms_transform* transform = m_reader->colorTransform()) {
        qcms_transform_data(transform, row, m_reader->rowBuffer(), size().width());
        row = m_reader->rowBuffer();
    }
#endif

    // Write the decoded row pixels to the frame buffer. The repetitive
    // form of the row write loops is for speed.
    ImageFrame::PixelData* address = buffer.getAddr(0, y);
    unsigned alphaMask = 255;
    int width = size().width();

    png_bytep pixel = row;
    if (hasAlpha) {
        if (buffer.premultiplyAlpha()) {
            for (int x = 0; x < width; ++x, pixel += 4) {
                buffer.setRGBAPremultiply(address++, pixel[0], pixel[1], pixel[2], pixel[3]);
                alphaMask &= pixel[3];
            }
        } else {
            for (int x = 0; x < width; ++x, pixel += 4) {
                buffer.setRGBARaw(address++, pixel[0], pixel[1], pixel[2], pixel[3]);
                alphaMask &= pixel[3];
            }
        }
    } else {
        for (int x = 0; x < width; ++x, pixel += 3) {
            buffer.setRGBARaw(address++, pixel[0], pixel[1], pixel[2], 255);
        }
    }

    if (alphaMask != 255 && !buffer.hasAlpha())
        buffer.setHasAlpha(true);

    buffer.setPixelsChanged(true);
}

void PNGImageDecoder::complete()
{
    if (m_frameBufferCache.isEmpty())
        return;

    m_frameBufferCache[0].setStatus(ImageFrame::FrameComplete);
}

bool PNGImageDecoder::isComplete() const
{
    if (m_frameBufferCache.isEmpty())
        return false;

    return m_frameBufferCache[0].status() == ImageFrame::FrameComplete;
}

void PNGImageDecoder::decode(bool onlySize)
{
    if (failed())
        return;

    if (!m_reader)
        m_reader = adoptPtr(new PNGImageReader(this));

    // If we couldn't decode the image but have received all the data, decoding
    // has failed.
    if (!m_reader->decode(*m_data, onlySize) && isAllDataReceived())
        setFailed();

    // If decoding is done or failed, we don't need the PNGImageReader anymore.
    if (isComplete() || failed())
        m_reader.clear();
}

} // namespace blink


text:
'''load 4 arrays
>x-train
>y-train
>x-test
>y-test: true labels

'''
import numpy as np
import scipy as sp
import scipy.io as scio

#import matplotlib as mpl

#from wyrm import plot
#plot.beautify()
from wyrm.types import Data
from wyrm import processing as proc
#from wyrm.io import load_bcicomp3_ds2

#function to load data
def load_graz(filename):
   # load the training
   data_mat = scio.loadmat('dataset_BCIcomp1.mat')
   data = data_mat['x_train'].astype('double')
   #print data.shape
   data = data.swapaxes(-3, -2)
   data = data.swapaxes(-1, -3)
   labels = data_mat['y_train'].astype('int').ravel()
   #print data.shape

   # convert into wyrm Data
   axes = [np.arange(i) for i in data.shape]
   axes[0] = labels
   axes[2] = [str(i) for i in range(data.shape[2])]
   names = ['Class', 'Time', 'Channel']
   units = ['#', 'ms', '#']
   dat_train = Data(data=data, axes=axes, names=names, units=units)
   dat_train.fs = 128
   dat_train.class_names = ['left', 'right']

   # load the test data
   #test_data_mat = loadmat(test_file)
   data = data_mat['x_test'].astype('double')
   data = data.swapaxes(-3, -2)
   data = data.swapaxes(-1, -3)

   # convert into wyrm Data
   axes = [np.arange(i) for i in data.shape]
   axes[2] = [str(i) for i in range(data.shape[2])]
   names = ['Class','Time', 'Channel']
   units = ['#','ms', '#']
   dat_test = Data(data=data, axes=axes, names=names, units=units)
   dat_test.fs = 128

   # map labels 2 -> 0
   dat_test.axes[0][dat_test.axes[0] == 2] = 0
   dat_train.axes[0][dat_train.axes[0] == 2] = 0

   return dat_train, dat_test

#function for preprocessing
def preprocess(dat,filt=None):
    	'''fs_n = dat.fs / 2
    	b, a = proc.signal.butter(5, [13 / fs_n], btype='low')
	dat = proc.lfilter(dat, b, a)
	b, a = proc.signal.butter(5, [8 / fs_n], btype='high')
	dat = proc.lfilter(dat, b, a)
	print dat'''

        dat = proc.subsample(dat, 64)
        #epo = proc.segment_dat(dat, MRK_DEF, SEG_IVAL)

        #fv = proc.jumping_means(epo, JUMPING_MEANS_IVALS)
        #fv = proc.create_feature_vectors(dat)

        if filt is None:
        	filt, pattern, _ = proc.calculate_csp(dat)
        	#plot_csp_pattern(pattern)
    	dat = proc.apply_csp(dat, filt)

   	dat = proc.variance(dat)
    	dat = proc.logarithm(dat)
    	return dat, filt

dat_train, dat_test=load_graz('dataset_BCIcomp1.mat')

labels=scio.loadmat('labels_data_set_iii.mat')
'''print type(labels)
print labels.shape'''
y_test=labels['y_test']
y_test[y_test == 2] = 0
print "true labels\n"
print y_test.swapaxes(1,0)

#dat_test=graz_data['x_test']
fv_train, filt = preprocess(dat_train)
fv_test, _ = preprocess(dat_test, filt)

cfy= proc.lda_train(fv_train)
result=proc.lda_apply(fv_test,cfy)
result = (np.sign(result) + 1) / 2

print "generated labels\n"
print result

#print y_test.shape
#print result.shape

sum=0.0
for i in range(len(result)):
	if result[i]==y_test[i]:
		sum=sum+1

print 'LDA Accuracy %.2f' % (sum/(len(result)))

redpajama_set_name: RedPajamaGithub


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_firm extends CI_Migration {

	public function up()
	{
		$this->dbforge->add_field(array(
			'firm_id' => array(
				'type' => 'INT',
				'constraint' => 5,
				'unsigned' => TRUE,
				'auto_increment' => TRUE
			),
			'firm_name' => array(
				'type' => 'VARCHAR',
				'constraint' => '100',
			),
		));

		$this->dbforge->add_key('firm_id', TRUE);
		$this->dbforge->create_table('firm');
	}

	public function down()
	{
		$this->dbforge->drop_table('firm');
	}
}

?>


text:
var async = require('async');
var helpers = require('./helpers');

/**
 * TODO: Add discription here ...
 *
 */
var Dependence = module.exports = function(shared) {
	this.shareDependencies = shared === undefined ? true : !!shared;

	this.dependencies = {};
	this.shared = {};
	this.providers = [];

	this.use = Dependence.prototype.use.bind(this);
	this.register = Dependence.prototype.register.bind(this);
	this.resolve = Dependence.prototype.resolve.bind(this);
}

Dependence.prototype = {

	/**
	 * Use a provider to resolve dependencies by name.
	 * param {Function} provider Provider to resolve a dependency by name.
	 */
	use: function(provider) {
		switch (typeof provider) {
			case 'function':
				this.providers.unshift(provider);
				break;
			case 'string':
				this.registerFiles(provider);
				break;
			default:
				throw "'provider' must be either of string or function! Actual type: " + typeof provider;
		}
	},

	/**
	 * Register a dependency directly without using a provider.
	 * You can also overwrite dependencies here!
	 * param {String} name Name of the dependency. Should be the same as the parameter name of the resolving function.
	 * param {Function} dependency Dependency that can also have multiple dependencies in its parameters.
	 */
	register: function(name, dependency) {
		if (typeof dependency === 'function')
			return this.dependencies[name] = dependency;

		this.shared[name] = dependency;
	},

	/**
	 * Resolves all dependencies defined in the parameters of a function
	 * or just a single dependency by passing the specific name.
	 * param {Function|String} arg Either the name or a function to resolve.
	 * param {Function(err, dependency)} callback Function to receive either an error and a dependency (if resolving directly by name) or the return value of the resolved function.
	 */
	resolve: function(arg, callback) {
		switch (typeof arg) {
			case 'string':
				this.resolveDependency(arg, callback);
				break;
			case 'function':
				this.resolveFunction(arg, callback);
				break;
			default:
				throw "'arg' must be either string or function! It was: " + typeof arg;
		}
	},

	/**
	 * Resolves all dependencies defined in the parameters of a function
	 * param {Function} func Function that can have multiple dependencies in its parameters.
	 * param {Function} callback Receives the result of func.
	 */
	resolveFunction: function(func, callback, history) {
		var self = this;

		// Extract dependency names
		var dependencyNames = func.require || helpers.extractFunctionParameters(func);

		// If there is nothing to resolve -> just call func
		if (dependencyNames.length == 0)
			return callback(func());

		if (!history)
			history = [];

		// Resolve dependencies and call func
		async.map(dependencyNames, function(name, callback) {
			// Resolve dependency pasing the cloned history.
			self.resolveDependency(name, function(dependency) {
				callback(null, dependency);
			}, history.slice());
		}, function done(err, dependencies) {
			callFunc(dependencies);
		});

		function callFunc(dependencies) {
			var result = func.apply(self, dependencies); // Calls the dependency constructor passing the dependencies
			if (callback) callback(result); // Provide the result of func to callback
		}
	},

	/**
	 * Tries to resolve a dependency directly by name
	 * param {String} name Dependency name
	 * param {Function(dependency)} callback Provides the resolved dependency
	 */
	resolveDependency: function(name, callback, history) {
		var self = this;
		if (!history) history = [];

		// Check circular dependency
		if (history.indexOf(name) !== -1) {
			history.push("[" + name + "]");
			console.error("Circular dependency found!\n" + history.join("\n -> "));
			return callback(null);
		}
		else {
			history.push(name);
		}

		// If dependency was resolved already -> return the result
		var shared = this.shared[name];
		if (shared) return callback(shared);

		// If dependency was found already -> resolve it and return result
		var dependency = this.dependencies[name];
		if (dependency)
			return done(dependency);

		// Walk through the providers until one of them gives back a dependency
		async.eachSeries(self.providers, function(provider, callback) {
			provider(name, function(dependency) {
				if (!dependency) return callback();
				if (typeof dependency !== 'function') {
					callback();
					throw "Provider returned an invalid dependency of type: " + typeof dependency;
				}

				callback(dependency);
			});
		}, done);

		// Resolve the dependencies of the dependency and return the result
		function done(dependency) {
			// Could not be resolved
			if (!dependency) {
				return callback(undefined);
			}

			// Ensure dependency is a function
			if (typeof dependency !== 'function') {
				return callback(undefined);
			}

			// Save dependency
			self.dependencies[name] = dependency;

			// Resolve dependency
			self.resolveFunction(dependency, function(resolved) {
				var saveToShared = dependency.shared !== undefined ? dependency.shared : self.shareDependencies;
				if (saveToShared)
					self.shared[name] = resolved;

				callback(resolved);
			}, history || [])
		}
	}
}


text:
"""evohomeclient provides a client for the oiginal Evohome API.

Further information at: https://evohome-client.readthedocs.io
"""
import codecs
import json
import logging
import sys
import time

import requests

try:
    import http.client as http_client
except ImportError:
    # Python 2
    import httplib as http_client

# Are we are dealing with Python 2 or 3
_VER = sys.version_info
#: Python 2.x?
IS_PY2 = _VER[0] == 2
#: Python 3.x?
IS_PY3 = _VER[0] == 3

logging.basicConfig()
_LOGGER = logging.getLogger(__name__)

class EvohomeClient(object):  # pylint: disable=useless-object-inheritance
    """Provide a client to access the Honeywell Evohome system."""

    # pylint: disable=too-many-instance-attributes,too-many-arguments

    def __init__(
        self,
        username,
        password,
        debug=False,
        user_data=None,
        hostname="https://tccna.honeywell.com",
    ):
        """Take the username and password for the service.

        If user_data is given then this will be used to try and reduce the number of
        calls to the authentication service which is known to be rate limited.
        """
        if debug is True:
            _LOGGER.setLevel(logging.DEBUG)
            _LOGGER.debug("Debug mode is explicitly enabled.")

            requests_logger = logging.getLogger("requests.packages.urllib3")
            requests_logger.setLevel(logging.DEBUG)
            requests_logger.propagate = True

            http_client.HTTPConnection.debuglevel = 1
        else:
            _LOGGER.debug(
                "Debug mode is not explicitly enabled (but may be enabled elsewhere)."
            )

        self.username = username
        self.password = password

        self.user_data = user_data
        self.hostname = hostname

        self.full_data = None
        self.gateway_data = None
        self.reader = codecs.getdecoder("utf-8")

        self.location_id = ""
        self.devices = {}
        self.named_devices = {}
        self.postdata = {}
        self.headers = {}

    def _convert(self, content):
        return json.loads(self.reader(content)[0])

    def _populate_full_data(self, force_refresh=False):
        if self.full_data is None or force_refresh:
            self._populate_user_info()

            user_id = self.user_data["userInfo"]["userID"]
            session_id = self.user_data["sessionId"]

            url = (
                self.hostname + "/WebAPI/api/locations?userId=%s&allData=True" % user_id
            )
            self.headers["sessionId"] = session_id

            response = self._do_request("get", url, json.dumps(self.postdata))

            self.full_data = self._convert(response.content)[0]

            self.location_id = self.full_data["locationID"]

            self.devices = {}
            self.named_devices = {}

            for device in self.full_data["devices"]:
                self.devices[device["deviceID"]] = device
                self.named_devices[device["name"]] = device

    def _populate_user_info(self):
        if self.user_data is None:
            url = self.hostname + "/WebAPI/api/Session"
            self.postdata = {
                "Username": self.username,
                "Password": self.password,
                "ApplicationId": "91db1612-73fd-4500-91b2-e63b069b185c",
            }
            self.headers = {"content-type": "application/json"}

            response = self._do_request(
                "post", url, data=json.dumps(self.postdata), retry=False
            )

            self.user_data = self._convert(response.content)

        return self.user_data

    def temperatures(self, force_refresh=False):
        """Retrieve the current details for each zone."""
        self._populate_full_data(force_refresh)

        for device in self.full_data["devices"]:
            set_point = 0
            status = ""
            if "heatSetpoint" in device["thermostat"]["changeableValues"]:
                set_point = float(
                    device["thermostat"]["changeableValues"]["heatSetpoint"]["value"]
                )
                status = device["thermostat"]["changeableValues"]["heatSetpoint"][
                    "status"
                ]

            else:
                status = device["thermostat"]["changeableValues"]["status"]
            yield {
                "thermostat": device["thermostatModelType"],
                "id": device["deviceID"],
                "name": device["name"],
                "temp": float(device["thermostat"]["indoorTemperature"]),
                "setpoint": set_point,
                "status": status,
                "mode": device["thermostat"]["changeableValues"]["mode"],
            }

    def get_modes(self, zone):
        """Return the set of modes the device can be assigned."""
        self._populate_full_data()
        device = self._get_device(zone)
        return device["thermostat"]["allowedModes"]

    def _get_device(self, zone):
        if isinstance(zone, str) or (
            IS_PY2 and isinstance(zone, basestring)  # noqa: F821
        ):
            device = self.named_devices[zone]
        else:
            device = self.devices[zone]
        return device

    def _get_task_status(self, task_id):
        self._populate_full_data()
        url = self.hostname + "/WebAPI/api/commTasks?commTaskId=%s" % task_id

        response = self._do_request("get", url)

        return self._convert(response.content)["state"]

    def _get_task_id(self, response):
        ret = self._convert(response.content)

        if isinstance(ret, list):
            task_id = ret[0]["id"]
        else:
            task_id = ret["id"]
        return task_id

    def _do_request(self, method, url, data=None, retry=True):
        if method == "get":
            func = requests.get
        elif method == "put":
            func = requests.put
        elif method == "post":
            func = requests.post

        response = func(url, data=data, headers=self.headers)

        # catch 401/unauthorized since we may retry
        if (
            response.status_code == requests.codes.unauthorized and retry
        ):  # pylint: disable=no-member
            # Attempt to refresh sessionId if it has expired
            if "code" in response.text:  # don't use response.json() here!
                if response.json()[0]["code"] == "Unauthorized":
                    _LOGGER.debug("Session expired, re-authenticating...")
                    # Get a new sessionId
                    self.user_data = None
                    self._populate_user_info()
                    # Set headers with new sessionId
                    session_id = self.user_data["sessionId"]
                    self.headers["sessionId"] = session_id
                    _LOGGER.debug("sessionId = %s", session_id)

                    response = func(url, data=data, headers=self.headers)

        # display error message if the vendor provided one
        if response.status_code != requests.codes.ok:  # pylint: disable=no-member
            if "code" in response.text:  # don't use response.json()!
                message = (
                    "HTTP Status = "
                    + str(response.status_code)
                    + ", Response = "
                    + response.text
                )
                raise requests.HTTPError(message)

        response.raise_for_status()

        return response

    def _set_status(self, status, until=None):
        self._populate_full_data()
        url = (
            self.hostname
            + "/WebAPI/api/evoTouchSystems?locationId=%s" % self.location_id
        )

        if until is None:
            data = {"QuickAction": status, "QuickActionNextTime": None}
        else:
            data = {
                "QuickAction": status,
                "QuickActionNextTime": until.strftime("%Y-%m-%dT%H:%M:%SZ"),
            }

        response = self._do_request("put", url, json.dumps(data))

        task_id = self._get_task_id(response)

        while self._get_task_status(task_id) != "Succeeded":
            time.sleep(1)

    def set_status_normal(self):
        """Set the system to normal operation."""
        self._set_status("Auto")

    def set_status_custom(self, until=None):
        """Set the system to the custom programme."""
        self._set_status("Custom", until)

    def set_status_eco(self, until=None):
        """Set the system to the eco mode."""
        self._set_status("AutoWithEco", until)

    def set_status_away(self, until=None):
        """Set the system to the away mode."""
        self._set_status("Away", until)

    def set_status_dayoff(self, until=None):
        """Set the system to the day off mode."""
        self._set_status("DayOff", until)

    def set_status_heatingoff(self, until=None):
        """Set the system to the heating off mode."""
        self._set_status("HeatingOff", until)

    def _get_device_id(self, zone):
        device = self._get_device(zone)
        return device["deviceID"]

    def _set_heat_setpoint(self, zone, data):
        self._populate_full_data()

        device_id = self._get_device_id(zone)

        url = (
            self.hostname
            + "/WebAPI/api/devices/%s/thermostat/changeableValues/heatSetpoint"
            % device_id
        )

        response = self._do_request("put", url, json.dumps(data))

        task_id = self._get_task_id(response)

        while self._get_task_status(task_id) != "Succeeded":
            time.sleep(1)

    def set_temperature(self, zone, temperature, until=None):
        """Set the temperature of the given zone."""
        if until is None:
            data = {"Value": temperature, "Status": "Hold", "NextTime": None}
        else:
            data = {
                "Value": temperature,
                "Status": "Temporary",
                "NextTime": until.strftime("%Y-%m-%dT%H:%M:%SZ"),
            }

        self._set_heat_setpoint(zone, data)

    def cancel_temp_override(self, zone):
        """Remove an existing temperature override."""
        data = {"Value": None, "Status": "Scheduled", "NextTime": None}
        self._set_heat_setpoint(zone, data)

    def _get_dhw_zone(self):
        for device in self.full_data["devices"]:
            if device["thermostatModelType"] == "DOMESTIC_HOT_WATER":
                return device["deviceID"]

    def _set_dhw(self, status="Scheduled", mode=None, next_time=None):
        """Set DHW to On, Off or Auto, either indefinitely, or until a set time."""
        data = {
            "Status": status,
            "Mode": mode,
            "NextTime": next_time,
            "SpecialModes": None,
            "HeatSetpoint": None,
            "CoolSetpoint": None,
        }

        self._populate_full_data()
        dhw_zone = self._get_dhw_zone()
        if dhw_zone is None:
            raise Exception("No DHW zone reported from API")
        url = (
            self.hostname
            + "/WebAPI/api/devices/%s/thermostat/changeableValues" % dhw_zone
        )

        response = self._do_request("put", url, json.dumps(data))

        task_id = self._get_task_id(response)

        while self._get_task_status(task_id) != "Succeeded":
            time.sleep(1)

    def set_dhw_on(self, until=None):
        """Set DHW to on, either indefinitely, or until a specified time.

        When On, the DHW controller will work to keep its target temperature at/above
        its target temperature.  After the specified time, it will revert to its
        scheduled behaviour.
        """
        time_until = None if until is None else until.strftime("%Y-%m-%dT%H:%M:%SZ")

        self._set_dhw(status="Hold", mode="DHWOn", next_time=time_until)

    def set_dhw_off(self, until=None):
        """Set DHW to on, either indefinitely, or until a specified time.

        When Off, the DHW controller will ignore its target temperature. After the
        specified time, it will revert to its scheduled behaviour.
        """
        time_until = None if until is None else until.strftime("%Y-%m-%dT%H:%M:%SZ")

        self._set_dhw(status="Hold", mode="DHWOff", next_time=time_until)

    def set_dhw_auto(self):
        """Set DHW to On or Off, according to its schedule."""
        self._set_dhw(status="Scheduled")


text:
package org.locationtech.geomesa.kafka.consumer

import com.typesafe.scalalogging.Logger
import org.apache.kafka.clients.consumer.{Consumer, ConsumerRecord, OffsetAndMetadata, OffsetCommitCallback}
import org.apache.kafka.common.TopicPartition
import org.apache.kafka.common.errors.{InterruptException, WakeupException}
import org.locationtech.geomesa.kafka.KafkaConsumerVersions
import org.locationtech.geomesa.kafka.consumer.ThreadedConsumer.{ConsumerErrorHandler, LogOffsetCommitCallback}

import java.time.Duration
import scala.util.control.NonFatal

abstract class ThreadedConsumer(
    consumers: Seq[Consumer[Array[Byte], Array[Byte]]],
    frequency: Duration,
    closeConsumers: Boolean = true
  ) extends BaseThreadedConsumer(consumers) {

  import scala.collection.JavaConverters._

  private val callback = new LogOffsetCommitCallback(logger)

  override protected def createConsumerRunnable(
      id: String,
      consumer: Consumer[Array[Byte], Array[Byte]],
      handler: ConsumerErrorHandler): Runnable = {
    new ConsumerRunnable(id, consumer, handler)
  }

  protected def consume(record: ConsumerRecord[Array[Byte], Array[Byte]]): Unit

  class ConsumerRunnable(id: String, consumer: Consumer[Array[Byte], Array[Byte]], handler: ConsumerErrorHandler)
      extends Runnable {

    private var errorCount = 0

    lazy private val topics = consumer.subscription().asScala.mkString(", ")

    override def run(): Unit = {
      try {
        var interrupted = false
        while (isOpen && !interrupted) {
          try {
            val result = KafkaConsumerVersions.poll(consumer, frequency)
            lazy val topics = result.partitions.asScala.map(tp => s"[${tp.topic}:${tp.partition}]").mkString(",")
            logger.debug(s"Consumer [$id] poll received ${result.count()} records for $topics")
            if (!result.isEmpty) {
              val records = result.iterator()
              while (records.hasNext) {
                consume(records.next())
              }
              logger.trace(s"Consumer [$id] finished processing ${result.count()} records from topic $topics")
              consumer.commitAsync(callback)
              errorCount = 0 // reset error count
            }
          } catch {
            case _: WakeupException | _: InterruptException | _: InterruptedException => interrupted = true
            case NonFatal(e) =>
              errorCount += 1
              logger.warn(s"Consumer [$id] error receiving message from topic $topics:", e)
              if (errorCount <= 300 || handler.handle(id, e)) {
                Thread.sleep(1000)
              } else {
                logger.error(s"Consumer [$id] shutting down due to too many errors from topic $topics:", e)
                throw e
              }
          }
        }
      } finally {
        if (closeConsumers) {
          try { consumer.close() } catch {
            case NonFatal(e) => logger.warn(s"Error calling close on consumer: ", e)
          }
        }
      }
    }
  }
}

object ThreadedConsumer {

  import scala.collection.JavaConverters._

  /**
    * Handler for asynchronous errors in the consumer threads
    */
  trait ConsumerErrorHandler {

    /**
      * Invoked on a fatal error
      *
      * @param consumer consumer identifier
      * @param e exception
      * @return true to continue processing, false to terminate the consumer
      */
    def handle(consumer: String, e: Throwable): Boolean
  }

  class LoggingConsumerErrorHandler(logger: Logger, topics: Seq[String]) extends ConsumerErrorHandler {
    override def handle(consumer: String, e: Throwable): Boolean = {
      logger.error(s"Consumer [$consumer] error receiving message from topic ${topics.mkString(", ")}:", e)
      false
    }
  }

  class LogOffsetCommitCallback(logger: Logger) extends OffsetCommitCallback() {
    override def onComplete(offsets: java.util.Map[TopicPartition, OffsetAndMetadata], exception: Exception): Unit = {
      lazy val o = offsets.asScala.map { case (tp, om) => s"[${tp.topic}:${tp.partition}:${om.offset}]"}.mkString(",")
      if (exception == null) {
        logger.trace(s"Consumer committed offsets: $o")
      } else {
        logger.error(s"Consumer error committing offsets: $o : ${exception.getMessage}", exception)
      }
    }
  }
}


text:
create or replace function weather.trigger_set_id () returns trigger as $$
begin
  new.id = nextval ('weather.zseq_vantage_pro_loop_data');
  new.start_rain_date = '1970-1-1';
  return new;
end $$ language plpgsql;

create trigger a_set_id before insert on weather.vantage_pro_loop_data for each row execute procedure weather.trigger_set_id ();


text:
module TaskBearing extend ActiveSupport::Concern

  included do
    belongs_to :current_task, class_name:"Task"
    belongs_to :current_location, class_name:"Location"
    has_many :tasks, -> { order :id }, dependent: :destroy
  end

  # Process tasks will have to be run for every Character every time the game
  # time is advanced. This shouldn't be as big of a burden as it sounds. It
  # will provide a place to hook into task completion.

  def process_tasks!
    new_task = first_valid_task

    if current_task.present? && (current_task != new_task)
      complete_current_task!
    end

    if current_task.present? && (current_task == new_task)
      update_location_from_task!
    end

    if current_task.nil? && new_task.present?
      start_new_task! new_task
    end
  end

  # === Job specific task methods ===

  def job_for_day day
    tasks.where(on:day).where("job_id IS NOT NULL").first
  end

  def destroy_job_on! day
    job = job_for_day(day)
    job.destroy if job.present?
  end

  def total_hours_worked
    tasks.where("job_id IS NOT NULL AND length IS NOT NULL").map(&:length).sum
  end

private

  def complete_current_task!
    current_task.complete!

    update_attributes(
      current_task: nil,
      current_location: nil,
      moved_to_location_at: nil,
    )
  end

  def start_new_task! task
    update_attributes(
      current_task: task,
      current_location: nil,
      moved_to_location_at: nil,
    )

    current_task.start!
    update_location_from_task!
  end

  # This method needs to set a character's location based on their current task.
  # If the character's task has a location then they simply go to that location.
  # If they have a job and the character has been at the location for longer
  # then their job's dwelling map suggests that they should be randomly select
  # a new location from the dwellings.

  def update_location_from_task!
    if current_task.location.present? && current_location.nil?
      update_attributes(
        current_location: current_task.location,
        moved_to_location_at: game.time,
      )
      return
    end

    if current_task.job.present?

      if current_location.nil?
        set_location_from_job!
        return
      end

      at_location = (game.time - moved_to_location_at).to_i / 60

      current_task.job.dwellings.each do |dwell|
        if (dwell[:where] == current_location.disposition)
          if (dwell[:time] < at_location)
            set_location_from_job!
            return
          end
        end
      end

    end
  end

  def set_location_from_job!
    roll = Roll.random(1,100)

    current_task.job.dwellings.each do |dwell|
      if dwell[:frequency].member? roll
        update_attributes(
          current_location: game.location_with_disposition(dwell[:where]),
          moved_to_location_at: game.time
        )
      end
    end
  end

  # This is done in 4 loops now because we want to choose more specific tasks
  # over less specific ones. That way we can specify a "monday" task, or an any
  # day from 2-3 task, without that task getting chosen over their normal work
  # tasks. This method should return nil when there is not task for this time.

  def first_valid_task

    day_now = game.real_day

    tasks.each do |task|
      if task.on.present? && task.from.present?
        start_time = task.start_time_on(game.time)
        end_time = task.end_time_on(game.time)
        return task if (task.on == day_now) && (start_time <= game.time) && (end_time >= game.time)
      end
    end

    tasks.each do |task|
      if task.on.nil? && task.from.present?
        start_time = task.start_time_on(game.time)
        end_time = task.end_time_on(game.time)
        return task if (start_time <= game.time) && (end_time >= game.time)
      end
    end

    tasks.each do |task|
      if task.on.present? && task.from.nil?
        return task if task.on == day_now
      end
    end

    tasks.each do |task|
      return task if task.on.nil? && task.from.nil?
    end

    nil
  end

end


text:
layout: post
title: Advanced HTML & CSS
lesson_num: '16'
week_num: 6
class_date: October 1, 2014
lead:
dontlink: false
---

## Due For This Class

1. Make sure your project-portfolio index.html has the following features:
  - a list of your current projects with links to each of the project pages
  - color squares with your color scheme (review the [in-class activity](/lessons/2014-09-19.html) where we built this - I've rewritten it to be easier to follow if you missed it).
2. When we were writing our color squares, we repeated an awful lot of CSS, didn't we! See if you can make this more modular / less repetative.  **There are multiple solutions to this problem** - please come prepared to share your ideas!
3. Read Chapter 14 in your Learning Web Design book.

## Lesson

1. Possible solutions to color squares questions
2. Measurements in CSS ([article link](http://demosthenes.info/blog/775/Which-CSS-Measurements-To-Use-When))
3. The Box Model
4. CSS Display ([article link](http://learnlayout.com/display.html))

## Homework

1. [Project #4](http://com372-14.github.io/projects/04-tables.html) will be due on Friday.
2. Work through the first 13 ([Learn CSS Layout](http://learnlayout.com/display.html) lessons (stop after you have read the **percent width** page).


text:
namespace principia {
namespace integrators {
namespace termination_condition {

inline void UpdateWithAbort(absl::Status const& updater,
                            absl::Status& updated) {
  if (absl::IsAborted(updater)) {
    updated = updater;
  } else {
    updated.Update(updater);
  }
}

}  // namespace termination_condition

namespace internal_ordinary_differential_equations {

using base::for_all_of;

template<typename IndependentVariable, typename... State>
ExplicitFirstOrderOrdinaryDifferentialEquation<IndependentVariable, State...>::
SystemState::SystemState(IndependentVariable const& s, State const& y)
    : s(s) {
  for_all_of(y, this->y).loop([](auto const& y, auto& this_y) {
    for (auto const& y_i : y) {
      this_y.emplace_back(y_i);
    }
  });
}

template<typename IndependentVariable, typename... State>
void
ExplicitFirstOrderOrdinaryDifferentialEquation<IndependentVariable, State...>::
SystemState::WriteToMessage(
    not_null<serialization::SystemState*> message) const {
  // Writing the tuple would be tricky.
  LOG(FATAL) << "NYI";
}

template<typename IndependentVariable, typename... State>
typename ExplicitFirstOrderOrdinaryDifferentialEquation<IndependentVariable,
                                                        State...>::SystemState
ExplicitFirstOrderOrdinaryDifferentialEquation<IndependentVariable, State...>::
SystemState::ReadFromMessage(serialization::SystemState const& message) {
  // Reading the tuple would be tricky.
  LOG(FATAL) << "NYI";
}

template<typename... State>
DecomposableFirstOrderDifferentialEquation<State...>::SystemState::SystemState(
    State const& y,
    Instant const& t)
    : y(y), time(t) {}

template<typename Position_>
ExplicitSecondOrderOrdinaryDifferentialEquation<
    Position_>::SystemState::SystemState(std::vector<Position> const& q,
                                         std::vector<Velocity> const& v,
                                         Instant const& t)
    : time(t) {
  for (int i = 0; i < q.size(); ++i) {
    positions.emplace_back(q[i]);
    velocities.emplace_back(v[i]);
  }
}

template<typename Position>
void ExplicitSecondOrderOrdinaryDifferentialEquation<Position>::SystemState::
    WriteToMessage(not_null<serialization::SystemState*> const message) const {
  for (auto const& position : positions) {
    position.WriteToMessage(message->add_position());
  }
  for (auto const& velocity : velocities) {
    velocity.WriteToMessage(message->add_velocity());
  }
  time.WriteToMessage(message->mutable_time());
}

template<typename Position>
typename ExplicitSecondOrderOrdinaryDifferentialEquation<Position>::SystemState
ExplicitSecondOrderOrdinaryDifferentialEquation<Position>::SystemState::
    ReadFromMessage(serialization::SystemState const& message) {
  SystemState system_state;
  for (auto const& p : message.position()) {
    system_state.positions.push_back(
        DoublePrecision<Position>::ReadFromMessage(p));
  }
  for (auto const& v : message.velocity()) {
    system_state.velocities.push_back(
        DoublePrecision<Velocity>::ReadFromMessage(v));
  }
  system_state.time = DoublePrecision<Instant>::ReadFromMessage(message.time());
  return system_state;
}

}  // namespace internal_ordinary_differential_equations
}  // namespace integrators
}  // namespace principia


text:
Plugin.define "AlstraSoft-AskMe" do
author "Brendan Coles <bcoles@gmail.com>" # 2010-10-12
version "0.1"
description "AskMe Pro is an expert knowledge management system that allows site owners to setup an expert advice service similar to highly popular sites like   Google Answers, Yahoo Answers and Kasamba.com."
website "http://www.alstrasoft.com/askme.htm"

# Google results as at 2010-10-12 #
# 21 for "powered by AlstraSoft AskMe Pro" -vulnerability

# Dorks #
dorks [
'"powered by AlstraSoft AskMe Pro" -vulnerability'
]

matches [

# Main page # Default text
{ :text=>'Enter details about your question and press the button bellow. All fields are required.' },

# Admin login page
{ :text=>'AskMe Pro Admin' },
{ :text=>"
 Powered by AlstraSoft AskMe Pro

" },

# Login page
{ :text=>'Forgotten Password?	' },
{ :text=>'Powered By AlstraSoft AskMe Pro

' }

]

end


text:
require.paths.unshift('./../Source/');
var Deck = require('deck').setup(global, 'ringo');
var http = require('ringo/httpserver');

/* App */
var Application = function(request, response){
	response.setStatus(200);
	response.setHeader('content-type', 'text/html');
	if (request.params.name) response.write(['Hello ', request.params.name, '!\n'].join(''));
	if (request.params.age) response.write(['You are', request.params.age, 'years old.\n'].join(' '));
	response.write('Have a nice Day!');
	response.finish();
};

/* Deck Instance */
var Serv = new Deck();
Serv.addRoute('/{:name{/:age}}', Application);

var httpserv = new http.Server();
httpserv.addApplication('/', null, function(env){
	return Serv.dispatch(env);
});
httpserv.start();


text:
package org.apache.ibatis.builder;

import org.apache.ibatis.reflection.factory.DefaultObjectFactory;

import java.util.List;
import java.util.Properties;

public class ExampleObjectFactory extends DefaultObjectFactory {

  @Override
  public <T> T create(Class<T> type) {
    return super.<T>create(type);
  }

  @Override
  public <T> T create(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
    return super.<T>create(type, constructorArgTypes, constructorArgs);
  }

  @Override
  public void setProperties(Properties properties) {
    super.setProperties(properties);
  }

}


text:
require 'rails_helper'

include Warden::Test::Helpers
Warden.test_mode!

describe 'Sign in' do

  it 'registers new user' do
    visit new_user_registration_path
    fill_in('Sähköpostiosoite', with:Faker::Internet.email)
    fill_in('Salasana', with:'Ihanmitavaan1')
    fill_in('Salasana uudelleen', with:'Ihanmitavaan1')

    click_button('Rekisteröidy')

    expect(page).to have_content 'Rekisteröintisi onnistui'
  end

  it 'rejects email' do
    visit new_user_registration_path
    fill_in('Sähköpostiosoite', with: 'jarmo@pekkarinen')

    click_button('Rekisteröidy')

    expect(page).to have_content 'Sähköpostiosoite ei ole mahdollinen'

    visit new_user_registration_path
    fill_in('Sähköpostiosoite', with: 'jarmo[at]pekkarinen.net')

    click_button('Rekisteröidy')

    expect(page).to have_content 'Sähköpostiosoite ei ole mahdollinen'
  end

  # it 'accepts first name' do
  #   visit new_user_registration_path
  #   fill_in('Etunimi', with: 'Ville-Veikko')
  #
  #   click_button('Rekisteröidy')
  #
  #   expect(page).to have_no_content 'Etunimi saa sisältää vain kirjaimia sekä väliliviivan tai välin nimien välissä'
  # end
  #
  # it 'accepts last name' do
  #   visit new_user_registration_path
  #   fill_in('Sukunimi', with: 'Von Hertzen')
  #
  #   click_button('Rekisteröidy')
  #
  #   expect(page).to have_no_content 'Sukunimi saa sisältää vain kirjaimia sekä väliliviivan tai välin nimien välissä'
  # end
  #
  # it 'rejects first name' do
  #   visit new_user_registration_path
  #   fill_in('Etunimi', with: 'V1ll3')
  #
  #   click_button('Rekisteröidy')
  #
  #   expect(page).to have_content 'Etunimi saa sisältää vain kirjaimia sekä väliliviivan tai välin nimien välissä'
  # end
  #
  # it 'rejects last name' do
  #   visit new_user_registration_path
  #   fill_in('Etunimi', with: '-lol--@')
  #
  #   click_button('Rekisteröidy')
  #
  #   expect(page).to have_content 'Sukunimi saa sisältää vain kirjaimia sekä väliliviivan tai välin nimien välissä'
  # end
  #
  # it 'rejects hetu' do
  #   visit new_user_registration_path
  #   fill_in('Henkilötunnus tai passin numero', with: '010191-123V')
  #
  #   click_button('Rekisteröidy')
  #
  #   expect(page).to have_content 'Henkilötunnus tai passin numero on virheellinen'
  #
  #   visit new_user_registration_path
  #   fill_in('Henkilötunnus tai passin numero', with: '010191+123V')
  #
  #   click_button('Rekisteröidy')
  #
  #   expect(page).to have_content 'Henkilötunnus tai passin numero on virheellinen'
  #
  #   visit new_user_registration_path
  #   fill_in('Henkilötunnus tai passin numero', with: '010106A235K')
  #
  #   click_button('Rekisteröidy')
  #
  #   expect(page).to have_content 'Henkilötunnus tai passin numero - palveluun voivat rekisteröityä vain yli 15 vuotiaat'
  # end
  #
  # it 'accepts passport number' do
  #   visit new_user_registration_path
  #   page.check('user_passport_number')
  #   fill_in('Henkilötunnus tai passin numero', with: 'M9989MFHFIEI2676')
  #
  #   click_button('Rekisteröidy')
  #
  #   expect(page).to have_no_content 'Henkilötunnus tai passin numero on virheellinen'
  # end
  #
  # it 'rejects phone number' do
  #   visit new_user_registration_path
  #   fill_in('Puhelinnumero', with: '112')
  #
  #   click_button('Rekisteröidy')
  #
  #   expect(page).to have_content 'Puhelinnumero ei ole mahdollinen'
  # end
  #
  # it 'rejects address' do
  #   visit new_user_registration_path
  #   fill_in('Osoite', with: 'Å')
  #
  #   click_button('Rekisteröidy')
  #
  #   expect(page).to have_content 'Osoite on liian lyhyt'
  # end
  #
  # it 'rejects city' do
  #   visit new_user_registration_path
  #   fill_in('Kaupunki', with: '11710')
  #
  #   click_button('Rekisteröidy')
  #
  #   expect(page).to have_content 'Kaupunki saa sisältää vain kirjaimia sekä väliliviivan tai välin nimien välissä'
  # end

  it 'rejects password' do
    visit new_user_registration_path
    fill_in('Salasana', with: 'password')

    click_button('Rekisteröidy')

    expect(page).to have_content 'Salasana on mustalistattu'

    visit new_user_registration_path
    fill_in('Salasana', with: 'lol12')

    click_button('Rekisteröidy')

    expect(page).to have_content 'Salasana on liian lyhyt'

    visit new_user_registration_path
    fill_in('Salasana', with: 'Elokuva123')
    fill_in('Salasana uudelleen', with:'Elokuva12')

    click_button('Rekisteröidy')

    expect(page).to have_content 'Salasana uudelleen ei vastaa varmennusta'
  end

end


text:
/*
 - Factory function faz uma invocação e tem um objeto de retorno
*/
app.factory('pedidosAPI', ['$http', 'config', function($http, config){
	var _getpedidos = function() {
		return $http.get( config.baseURL + 'public/pedidos/');
	};

	var _addpedido = function(pedido) {
		return $http.post( config.baseURL + 'public/pedidos', pedido);
	};

	var _updatepedido = function(pedido) {
		return $http.put( config.baseURL + 'public/pedidos', pedido);
	};

	var _deletepedido = function(pedidoId) {
		return $http.delete( config.baseURL + 'public/pedidos?pedidoId=' + pedidoId);
	};

	return {
		getPedidos: _getpedidos,
		addPedido: _addpedido,
		updatePedido: _updatepedido,
		deletePedido: _deletepedido
	};
}])


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <padding android:left="10dp"
             android:right="10dp"
             android:top="10dp"
             android:bottom="10dp"/>
    <stroke android:width="2dp" android:color="@color/gsr_text_gray"/>
    <corners android:radius="5dp"/>
</shape>


text:
import time

from flask import url_for as _url_for, current_app, _request_ctx_stack

def timestamp():
    """Return the current timestamp as an integer."""
    return int(time.time())

def url_for(*args, **kwargs):
    """
    url_for replacement that works even when there is no request context.
    """
    if '_external' not in kwargs:
        kwargs['_external'] = False
    reqctx = _request_ctx_stack.top
    if reqctx is None:
        if kwargs['_external']:
            raise RuntimeError('Cannot generate external URLs without a '
                               'request context.')
        with current_app.test_request_context():
            return _url_for(*args, **kwargs)
    return _url_for(*args, **kwargs)


text:
package brooklyn.management.internal;

import brooklyn.config.ConfigKey;
import brooklyn.entity.Effector;
import brooklyn.event.AttributeSensor;
import brooklyn.policy.Enricher;
import brooklyn.policy.Policy;

public interface EntityChangeListener {

    // TODO for testing only!
    public static final EntityChangeListener NOOP = new EntityChangeListener() {
        @Override public void onChanged() {}
        @Override public void onAttributeChanged(AttributeSensor<?> attribute) {}
        @Override public void onConfigChanged(ConfigKey<?> key) {}
        @Override public void onLocationsChanged() {}
        @Override public void onMembersChanged() {}
        @Override public void onChildrenChanged() {}
        @Override public void onPolicyAdded(Policy policy) {}
        @Override public void onPolicyRemoved(Policy policy) {}
        @Override public void onEnricherAdded(Enricher enricher) {}
        @Override public void onEnricherRemoved(Enricher enricher) {}
        @Override public void onEffectorStarting(Effector<?> effector) {}
        @Override public void onEffectorCompleted(Effector<?> effector) {}
    };

    void onChanged();

    void onAttributeChanged(AttributeSensor<?> attribute);

    void onConfigChanged(ConfigKey<?> key);

    void onLocationsChanged();

    void onMembersChanged();

    void onChildrenChanged();

    void onPolicyAdded(Policy policy);

    void onPolicyRemoved(Policy policy);

    void onEnricherAdded(Enricher enricher);

    void onEnricherRemoved(Enricher enricher);

    void onEffectorStarting(Effector<?> effector);

    void onEffectorCompleted(Effector<?> effector);
}


text:
A Trait representation represents a Tinkers' Construct Trait.
You can get such an object either from the [Trait Builder](/Mods/ContentTweaker/Tinkers_Construct/TraitBuilder/) or from the [Trait Bracket Handler](/Mods/ContentTweaker/Tinkers_Construct/Brackets/Bracket_Trait/).

## Importing the class
It might be required for you to import the class if you encounter any issues (like casting an [Array](/AdvancedFunctions/Arrays_and_Loops/)), so better be safe than sorry and add the import.
`import mods.contenttweaker.tconstruct.Trait`

## ZenGetter

| ZenGetter     | Type    |
|---------------|---------|
| identifier    | string  |
| commandString | string  |

## Adding trait items

If you combine the given ingredient together with a tool in a tinker's tool forge, you can apply the trait as modifier.
```zenscript
//myTrait.addModifierItem(IIngredient item, @Optional(1) int amountNeeded, @Optional(1) int amountMatched));
myTrait.addModifierItem(<item:minecraft:iron_pickaxe>);
myTrait.addModifierItem(<item:minecraft:iron_block>, 4, 2);
```

- `item` is the item that is matched against. You can use [Item Conditions](/Vanilla/Items/Item_Conditions/) but no Transformers.
- `amountNeeded` is the amount of items that is matched against. You can split them over all the slots the toolforge provides, which also allows you to go above 64. In the example above, you need 4 iron blocks per addition. Defaults to 1.
- `amountMatched` is the amount of trait points added per `amountNeeded`. In the example above four iron blocks give two trait points. Defaults to 1.

## Accessing Trait Data

Trait data is the data that belongs to a trait and is itemBound. As such, you can provide the [IItemStack](/Vanilla/Items/IItemStack/) and retrieve the [TraitDataRepresentation](/Mods/ContentTweaker/Tinkers_Construct/TraitDataRepresentation/) object.
```
val myTraitData = myTrait.getData(itemWithTrait);
```


text:
/*!
 * Start Bootstrap - Creative Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

html,
body {
    width: 100%;
    height: 100%;
}

body {
    font-family: Merriweather,'Helvetica Neue',Arial,sans-serif;
}

hr {
    max-width: 50px;
    border-color: #eb3812;
    border-width: 3px;
}

hr.light {
    border-color: #fff;
}

a {
    color: #eb3812;
    text-decoration: none;
    -webkit-transition: all .35s;
    -moz-transition: all .35s;
    transition: all .35s;
}

a:hover,
a:focus {
    color: #a30000;
    text-decoration: none;
}

h1,
h2,
h3,
h4,
h5,
h6 {
    font-family: 'Open Sans Condensed','Helvetica Neue',Arial,sans-serif;
}

h3 {
    color: gray;
    font-size: 40px;
}

h4 {
    font-size: 60px;
}

p {
    margin-bottom: 20px;
    font-size: 16px;
    line-height: 1.5;
    text-indent: 30px;
}

p.noindent {
    margin-bottom: 20px;
    font-size: 20px;
    line-height: 1.5;
    text-indent: 0px;
}

p.center {
    margin-bottom: 20px;
    font-size: 16px;
    line-height: 1.5;
    text-indent: 0px;
    text-align: center;
}
.logo-image{
    width: 100px;
    height: 21.7px;
}
.bg-primary {
    background-color: #F0F3F4;
    text-align: center;
}

.bg-second {

  background-color: #4D4D4D;
  background-blend-mode: lighten;
}

.bg-dark {
    color: #fff;
    background-color: #222;
    background: url(../img/PS1-laugh.jpg) no-repeat center fixed;
    -webkit-box-pack: center;
    padding-top: 200px;
    padding-bottom: 120px;
}

.bg-gray {
    color: #fff;
    /*background-color: #DDDDDD;*/
    background: url(../img/PS1-laugh.jpg) no-repeat center center fixed;
  -webkit-background-size: contain;
  -moz-background-size: contain;
  -o-background-size: contain;
background-size: contain;
    -webkit-box-pack: center;
    padding-top: 80px;
    padding-bottom: 80px;
}

.bg-white {
    color: #F0F3F4;
    /*background-color: #DDDDDD;*/
    background: url(../img/PS1_head2.jpg) no-repeat left fixed;
    background-position: 50px 150px;
    box-shadow: 0 0 8px 8px #F0F3F4 inset;
  -webkit-background-size: contain;
  -moz-background-size: contain;
  -o-background-size: contain;
background-size: contain;
    -webkit-box-pack: center;
}

.text-faded {
    color: #000;
}

}
.textWithBlurredBg-container {
  text-align: center;
}

.textWithBlurredBg{
    width:300px;
    height:auto;
    display:inline-block;
    position:relative;
    transition:.3s;
    margin:10px;

  }

  .textWithBlurredBg img{
    width:100%;
    height:100%;
    transition:.3s;
    border-radius:4px;
  }

  .textWithBlurredBg:hover img{
    filter:blur(2px) brightness(60%);
    box-shadow:0 0 16px orange;
  }

  .textWithBlurredBg :not(img){
    position:absolute;
    z-index:1;
    top:30%;
    width:100%;
    text-align:center;
    color:#fff;
    opacity:0;
    transition:.3s;
  }

  .textWithBlurredBg h2{
    top:10%
  }

  .textWithBlurredBg h3{
    top:25%
  }

  .textWithBlurredBg audio{
    top:75%
  }

  .textWithBlurredBg iframe{
    top:75%;
    left: 0;
  }

  .textWithBlurredBg:hover :not(img){
    opacity:1;
  }

  .video {
    position:relative;
    	padding-bottom:35%;
    	padding-top:30px;
    	height:0;
    	overflow:hidden;
      text-align: center;

  }

  .video iframe, .video object, .video embed {
    position: relative;
	text-align: center;
  top:0;
	left:0;
	width:889PX;
	height:500px;
    box-shadow: 13px 13px 13px 0px #888888;
  }

body {
    padding: 0px;
}

section {
    padding: 20px 0;
}

aside {
    padding: 50px 0;
}

.no-padding {
    padding: 0;
}

.navbar-default {
    border-color: rgba(34,34,34,.05);
    font-family: 'Open Sans Condensed','Helvetica Neue',Arial,sans-serif;
    background-color: rgba(0,0,0,.8);
    -webkit-transition: all .35s;
    -moz-transition: all .35s;
    transition: all .35s;
}

.navbar-default .navbar-header .navbar-brand {
    /*text-transform: uppercase;*/
    font-family: 'Open Sans Condensed','Helvetica Neue',Arial,sans-serif;
    font-size: 2em;
    font-weight: 700;
    color: #f05f40;
}

.navbar-default .navbar-header .navbar-brand:hover,
.navbar-default .navbar-header .navbar-brand:focus {
    color: #eb3812;
}

.navbar-default .nav > li>a,
.navbar-default .nav>li>a:focus {
    /*text-transform: uppercase;*/
    font-size: 18px;
    font-weight: 700;
    color: white;
}

.navbar-default .nav > li>a:hover,
.navbar-default .nav>li>a:focus:hover {
    color: #f05f40;
}

.navbar-default .nav > li.active>a,
.navbar-default .nav>li.active>a:focus {
    color: #f05f40!important;
    background-color: transparent;
}

.navbar-default .nav > li.active>a:hover,
.navbar-default .nav>li.active>a:focus:hover {
    background-color: transparent;
}

@media(min-width:768px) {
    .navbar-default {
        /*border-color: rgba(255,255,255,.3);*/
        /*Nav background color in header*/
        background-color: rgba(0,0,0,.4);
    }

    .navbar-default .navbar-header .navbar-brand {
        /*"Wesley Skold DJ" color in header*/
        color: rgba(255,255,255,.7);
    }

    .navbar-default .navbar-header .navbar-brand:hover,
    .navbar-default .navbar-header .navbar-brand:focus {
        /*"Wesley Skold DJ" color:hover in header*/
        color: #fff;
    }

    .navbar-default .nav > li>a,
    .navbar-default .nav>li>a:focus {
        color: rgba(255,255,255,.7);
    }

    .navbar-default .nav > li>a:hover,
    .navbar-default .nav>li>a:focus:hover {
        color: #fff;
    }

    .navbar-default.affix {
        border-color: rgba(34,34,34,0);
        /*controls navbar */
        background-color: rgba(0,0,0,0);
    }

    .navbar-default.affix .navbar-header .navbar-brand {
        /*"Wesley Skold DJ" size change*/
        font-size: 20px;
        color: #f05f40;
    }

    .navbar-default.affix .navbar-header .navbar-brand:hover,
    .navbar-default.affix .navbar-header .navbar-brand:focus {
        /*"Wesley Skold DJ" 2nd color:hover*/
        color: #eb3812;
    }

    .navbar-default.affix .nav > li>a,
    .navbar-default.affix .nav>li>a:focus {
        /*navbar items color*/
        color: #C6C6C6;
    }

    .navbar-default.affix .nav > li>a:hover,
    .navbar-default.affix .nav>li>a:focus:hover {
        color: #f05f40;
    }
}

header {
    position: relative;
    width: 100%;
    min-height: auto;
    text-align: center;
    color: #fff;
    background-image: url(../img/PS1_bio1_v.jpg);
    background-position: center;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    -o-background-size: cover;
}

header .header-content {
    position: relative;
    width: 100%;
    padding: 160px 15px 40px 15px;
    text-align: center;
}

header .header-content-two {
    position: relative;
    width: 100%;
    padding: 160px 10px 40px 15px;
    text-align: right;
}

header .header-content .header-content-inner h1 {
    margin-top: 0;
    margin-bottom: 0;
    text-transform: uppercase;
    font-weight: 700;
    text-shadow:
    -1px -1px 0 #000,
    1px -1px 0 #000,
    -1px 1px 0 #000,
    1px 1px 0 #000;
}

header .header-content .header-content-inner hr {
    margin: 10px auto;
}

header .header-content .header-content-inner p {
    margin-bottom: 50px;
    font-size: 16px;
    font-weight: 300;
    color: rgba(255,255,255,.7);
}

@media(min-width:768px) {
    header {
        min-height: 100%;
    }

    header .header-content {
        position: absolute;
        top: 50%;
        padding: 0 50px;
        -webkit-transform: translateY(-50%);
        -ms-transform: translateY(-50%);
        transform: translateY(-50%);
    }

    header .header-content .header-content-inner {
        margin-right: auto;
        margin-left: auto;
        max-width: 1000px;
    }

    header .header-content .header-content-inner p {
        margin-right: auto;
        margin-left: auto;
        max-width: 80%;
        font-size: 18px;
    }
}

.section-heading {
    margin-top: 0;
    color: #000
}

.service-box {
    margin: 50px auto 0;
    max-width: auto;
    background: transparent;
    border-radius: 5px;
    padding: 10px;
    color: white;
}

@media(min-width:992px) {
    .service-box {
        margin: 20px auto 0;
    }
}

.service-box p {
    margin-bottom: 0;
}

.portfolio-box {
    display: block;
    position: relative;
    margin: 0 auto;
    max-width: 650px;
}

.portfolio-box .portfolio-box-caption {
    display: block;
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 100%;
    text-align: center;
    color: #fff;
    opacity: 0;
    background: rgba(240,95,64,.9);
    -webkit-transition: all .35s;
    -moz-transition: all .35s;
    transition: all .35s;
}

.portfolio-box .portfolio-box-caption .portfolio-box-caption-content {
    position: absolute;
    top: 50%;
    width: 100%;
    text-align: center;
    transform: translateY(-50%);
}

.portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-category,
.portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-name {
    padding: 0 15px;
    font-family: 'Open Sans Condensed','Helvetica Neue',Arial,sans-serif;
}

.portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-category {
    text-transform: uppercase;
    font-size: 14px;
    font-weight: 600;
}

.portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-name {
    font-size: 18px;
}

.portfolio-box:hover .portfolio-box-caption {
    opacity: 1;
}

@media(min-width:768px) {
    .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-category {
        font-size: 16px;
    }

    .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-name {
        font-size: 22px;
    }
}

.call-to-action h2 {
    margin: 0 auto 20px;
}

.text-primary {
    color: #f05f40;
}

.no-gutter > [class*=col-] {
    padding-right: 0;
    padding-left: 0;
}

.btn-default {
    border-color: #fff;
    color: #222;
    background-color: #fff;
    -webkit-transition: all .35s;
    -moz-transition: all .35s;
    transition: all .35s;
}

.btn-default:hover,
.btn-default:focus,
.btn-default.focus,
.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
    border-color: #ededed;
    color: #222;
    background-color: #f2f2f2;
}

.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
    background-image: none;
}

.btn-default.disabled,
.btn-default[disabled],
fieldset[disabled] .btn-default,
.btn-default.disabled:hover,
.btn-default[disabled]:hover,
fieldset[disabled] .btn-default:hover,
.btn-default.disabled:focus,
.btn-default[disabled]:focus,
fieldset[disabled] .btn-default:focus,
.btn-default.disabled.focus,
.btn-default[disabled].focus,
fieldset[disabled] .btn-default.focus,
.btn-default.disabled:active,
.btn-default[disabled]:active,
fieldset[disabled] .btn-default:active,
.btn-default.disabled.active,
.btn-default[disabled].active,
fieldset[disabled] .btn-default.active {
    border-color: #fff;
    background-color: #fff;
}

.btn-default .badge {
    color: #fff;
    background-color: #222;
}

.btn-primary {
    border-color: #f05f40;
    color: #fff;
    background-color: rgba(0, 0, 0, 0.5);
    -webkit-transition: all .35s;
    -moz-transition: all .35s;
    transition: all .35s;
}

.btn-primary:hover,
.btn-primary:focus,
.btn-primary.focus,
.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
    border-color: #ed431f;
    color: #fff;
    background-color: #eb3812;
}

.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
    background-image: none;
}

.btn-primary.disabled,
.btn-primary[disabled],
fieldset[disabled] .btn-primary,
.btn-primary.disabled:hover,
.btn-primary[disabled]:hover,
fieldset[disabled] .btn-primary:hover,
.btn-primary.disabled:focus,
.btn-primary[disabled]:focus,
fieldset[disabled] .btn-primary:focus,
.btn-primary.disabled.focus,
.btn-primary[disabled].focus,
fieldset[disabled] .btn-primary.focus,
.btn-primary.disabled:active,
.btn-primary[disabled]:active,
fieldset[disabled] .btn-primary:active,
.btn-primary.disabled.active,
.btn-primary[disabled].active,
fieldset[disabled] .btn-primary.active {
    border-color: #f05f40;
    background-color: #f05f40;
}

.btn-primary .badge {
    color: #f05f40;
    background-color: #fff;
}

.btn {
    border: 0;
    border-radius: 300px;
    text-transform: uppercase;
    font-family: 'Open Sans Condensed','Helvetica Neue',Arial,sans-serif;
    font-weight: 700;
}

.btn-xl {
    padding: 15px 30px;
    font-size: 25px
}

::-moz-selection {
    text-shadow: none;
    color: #fff;
    background: #222;
}

::selection {
    text-shadow: none;
    color: #fff;
    background: #222;
}

img::selection {
    color: #fff;
    background: 0 0;
}

img::-moz-selection {
    color: #fff;
    background: 0 0;
}

body {
    webkit-tap-highlight-color: #222;
}

.image-padding {
    padding-top: 40px;
}

.reviewbox{
    padding: 20px 10px;
    background: rgba(0,0,0,.8);
    /*border-top: 1px solid #858585;
    border-bottom: 1px solid #858585;*/
    border-radius: 5px;
    margin: 20px 0px;
}

.songbox{
    padding: 10px 0px;
    background: rgba(255,255,255,1);
    /*border-top: 1px solid #858585;
    border-bottom: 1px solid #858585;*/
    border-radius: 5px;
    margin: 2px 0px;
    width: 100%
}

.reviewtitle{
    padding: 20px 0px 10px 0px;
    background: rgba(0,0,0,.8);
    /*border-top: 1px solid #858585;
    border-bottom: 1px solid #858585;*/
    border-radius: 5px;
    /*margin: 20px 0px;*/
}
#footer{
    border-top: 1px solid #eb3812;
    background-color: #000
    height: 200px;

}

#footer a{
    font-family: 'Open Sans Condensed','Helvetica Neue',Arial,sans-serif;
    font-size: 20px;
    color: #C6C6C6;
}

#footer a:hover{
    color: #eb3812;
}

.dark-button {
    color: #F8F8F8;
    background: #343434;
    border-width: 1px;
    font-family: 'Open Sans Condensed','Helvetica Neue',Arial,sans-serif;

}


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

namespace Mozu.Api.Contracts.Tenant
{
		///
		///	Properties of a master product catalog defined for a tenant. All catalogs and sites associated with a master catalog share product definitions.
		///
		public class MasterCatalog
		{
			public List<Catalog> Catalogs { get; set; }

			public DateTime CreateDate { get; set; }

			public string DefaultCurrencyCode { get; set; }

			public string DefaultLocaleCode { get; set; }

			public DateTime DeleteDate { get; set; }

			public int Id { get; set; }

			public bool IsDeleted { get; set; }

			public string Name { get; set; }

			///
			///The current status of the object.This value is read only. Valid values for this field are: "Active", "Expired", and "Inactive".
			///
			public string Status { get; set; }

			///
			///Unique identifier of the Mozu tenant.
			///
			public int TenantId { get; set; }

			public DateTime UpdateDate { get; set; }

		}

}


text:
package org.jon.ivmark.graphit.core.graph.edge.repository;

import com.google.common.base.Preconditions;
import org.jon.ivmark.graphit.core.graph.edge.EdgeId;
import org.jon.ivmark.graphit.core.graph.edge.EdgePrimitive;
import org.jon.ivmark.graphit.core.graph.edge.EdgeType;

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

/**
 * An {@link EdgePrimitivesBuffer} that consists of multiple buffers for
 * improved concurrency.
 *
 * This buffer is thread safe.
 *
 * @author jon
 *
 */
public class ConcurrentEdgePrimitivesBuffer implements EdgePrimitivesBuffer {

    private final EdgeType edgeType;
    private final List<EdgePrimitivesBuffer> segments;

    /**
     * Creates a new buffer.
     *
     * @param edgeType
     *            The type of the edges in this buffer.
     * @param concurrencyLevel
     *            The number of segments to use (typically related to the number
     *            of processors) .
     * @param inititalCapacity
     *            The initial capaicity, i.e. an estimation of how many edges
     *            this buffer will contain.
     */
    public ConcurrentEdgePrimitivesBuffer(EdgeType edgeType, int concurrencyLevel, int inititalCapacity) {
        this.edgeType = edgeType;
        this.segments = new ArrayList<EdgePrimitivesBuffer>(concurrencyLevel);
        for (int i = 0; i < concurrencyLevel; i++) {
            segments.add(new EdgePrimitivesBufferImpl(edgeType, inititalCapacity / concurrencyLevel));
        }
    }

    @Override
    public int size() {
        int size = 0;
        for (EdgePrimitivesBuffer buffer : segments) {
            size += buffer.size();
        }
        return size;
    }

    @Override
    public void upsert(int index, int startNode, int endNode, float weight) {
        EdgePrimitivesBuffer buffer = getSegment(index);
        buffer.upsert(mapIndex(index), startNode, endNode, weight);
    }

    @Override
    public EdgePrimitive get(int index) {
        EdgePrimitivesBuffer buffer = getSegment(index);
        EdgePrimitive edge = buffer.get(mapIndex(index));
        if (edge == null) {
            return null;
        }
        return new EdgePrimitive(new EdgeId(edge.getEdgeType(), index), edge.getStartNodeIndex(),
                                 edge.getEndNodeIndex(), edge.getWeight());
    }

    @Override
    public EdgePrimitive remove(int index) {
        EdgePrimitivesBuffer buffer = getSegment(index);
        EdgePrimitive edge = buffer.remove(mapIndex(index));
        if (edge == null) {
            return null;
        }
        return new EdgePrimitive(new EdgeId(edge.getEdgeType(), index), edge.getStartNodeIndex(),
                                 edge.getEndNodeIndex(), edge.getWeight());

    }

    private EdgePrimitivesBuffer getSegment(int index) {
        Preconditions.checkArgument(index >= 0, "Index must not be negative");
        int i = index % segments.size();
        return segments.get(i);
    }

    private int mapIndex(int index) {
        return index / segments.size();
    }

    @Override
    public EdgeType getEdgeType() {
        return edgeType;
    }
}


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W29217_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans2.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans5.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Page 3

    <p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">HALLIBURTDN

    <p class="styleSans2.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">1 1 Cementing Job Summary
Ra

    <p class="styleSans617.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Created: Tuesday, October 14, 2014

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">CONOCO PHILLIPS 901729539Case 1

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">


text:
import base64
import pprint
import boto3
import config
from PIL import Image
called_aws = False
client = boto3.client('rekognition',
	aws_access_key_id=config.get('aws_access_key_id'),
	aws_secret_access_key=config.get('aws_secret_access_key'),
	region_name=config.get('aws_region')
)

def get_username_from_image(image):
	global called_aws

	# TODO: rate limit AWS instead of only allowing one call
	if not called_aws:
		im = Image.fromarray(image)
		im.save('rekognition.jpg', 'JPEG')

		with open('rekognition.jpg', 'rb') as source_image:
			source_bytes = source_image.read()

		response = client.search_faces_by_image(
			CollectionId = 'Synthia',
			Image = {'Bytes' : source_bytes}
		)
		called_aws = True

		if response['FaceMatches']:
			return response['FaceMatches'][0]['Face']['ExternalImageId']
		else:
			return None
	else:
		return None


text:
package com.sugary.fragmentcapsulation.base;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.sugary.fragmentcapsulation.rxlife.RxSupportFragment;
import com.sugary.fragmentcapsulation.utils.RxBus;
import com.zhy.m.permission.MPermissions;

import butterknife.ButterKnife;
import rx.functions.Action1;
import rx.subscriptions.CompositeSubscription;

/**
 * 给rootView设置一个OnKeyListener来监听key事件
 *

 * mRootView.setFocusable(true);
 * mRootView.setFocusableInTouchMode(true);
 * mRootView.setOnKeyListener(new View.OnKeyListener() {
 *
 * @Override public boolean onKey(View v, int keyCode, KeyEvent event) {
 * if (keyCode == KeyEvent.KEYCODE_BACK) {
 * //不一定是要触发返回栈,可以做一些其他的事情
 * getActivity().onBackPressed();
 * return true;
 * }
 * return false;
 * }
 * });
 *

 * Created by Ethan on 17/1/17.
 * 1.绑定视图  2.RxBus订阅管理  3.Fragment回退栈回调管理  4.危险权限适配
 * 5.bundle解析  6.底部导航条动画管理
 */
public abstract class BasicFragment extends RxSupportFragment {

    private static final String TAG = "BasicFragment";

    private BasicActivity mActivity;
    private int mLastChildStackEntryCount = 0;
    private int mLastSupportStackEntryCount = 0;

    /**
     * hide后,再次show一个Fragment时传入的bundle
     */
    private Bundle mSupportArguments;
    /**
     * Subscription对象的容器
     */
    private CompositeSubscription mCompositeSubscription;

    /**
     * 防止fragment onDetach后调用getActivity空指针,不足:有可能内存泄漏
     *
     * @param context
     */
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = (BasicActivity) context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        parseArguments(getArguments());

        getChildFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {
                int currentStackEntryCount = getChildFragmentManager().getBackStackEntryCount();
                if (currentStackEntryCount - mLastChildStackEntryCount < 0) {
                    configureToolbar();
                    onChildBackStack();
                }
                mLastChildStackEntryCount = currentStackEntryCount;
            }
        });

        final FragmentManager manager = mActivity.getSupportFragmentManager();
        manager.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {
                int currentStackEntryCount = manager.getBackStackEntryCount();
                if (currentStackEntryCount - mLastSupportStackEntryCount < 0) {
                    onSupportBackStack(getAttachActivity().getSupportBackStackArguments());
                }
                mLastSupportStackEntryCount = currentStackEntryCount;
            }
        });
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(getLayoutResID(), container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            parseArguments(getSupportArguments());
        }
    }

    /**
     * Fragment Argument解析
     *
     * @param arguments
     */
    protected void parseArguments(Bundle arguments) {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mCompositeSubscription != null) {
            mCompositeSubscription.clear();
        }
    }

    private CompositeSubscription getCompositeSubscription() {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        return mCompositeSubscription;
    }

    /**
     * 添加RxBus订阅
     *
     * @param tClass
     * @param action1
     * @param errorAction1
     * @param <T>
     */
    protected <T> void addSubscription(Class<T> tClass, Action1<T> action1, Action1<Throwable> errorAction1) {
        getCompositeSubscription()
                .add(RxBus.getInstance().toSubscription(tClass, action1, errorAction1));
    }

    public BasicActivity getAttachActivity() {
        return mActivity;
    }

    private Bundle getSupportArguments() {
        return mSupportArguments;
    }

    public void setSupportArguments(Bundle supportArguments) {
        mSupportArguments = supportArguments;
    }

    protected void startEnterBottomBarAnimation(){

    }

    protected void startExitBottomBarAnimation(){

    }

    /**
     * 当replace的置换Fragment时,重新show时,需要更新toolbar信息
     */
    protected void configureToolbar() {
    }

    /**
     * 子Fragment回退栈 回调
     */
    protected void onChildBackStack() {

    }

    /**
     * Fragment里监听虚拟按键和实体按键的返回事件
     *
     * @param bundle
     */
    protected void onSupportBackStack(Bundle bundle) {

    }

    /**
     * Fragment 监听回退键
     *
     * @return true 消费,回退到此不再往下
     */
    protected boolean onBackPressed() {

        return false;
    }

    /**
     * 获取要替换的布局ID
     *
     * @return 替换的布局ID
     */
    protected int getChildrenFragmentContainerResID() {
        return -1;
    }

    protected abstract
    @LayoutRes
    int getLayoutResID();

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MPermissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }
}


text:
. ../helper.sh || . ./scripts/helper.sh || . ./helper.sh || wget -q 'https://github.com/jmcerrejon/PiKISS/raw/master/scripts/helper.sh'
clear
check_board || { echo "Missing file helper.sh. I've tried to download it for you. Try to run the script again." && exit 1; }

add_global_github_user() {
    git config --global credential.helper store
    git config --global user.name "$GITHUB_NAME"
    git config --global user.email "$GITHUB_EMAIL"
    git config --global --list
}

install() {
    install_nginx
    install_mariadb
    add_global_github_user
    install_php
}

install_script_message
echo "
LEMP Server stack
=================

· Linux.
· Nginx (pronunced Engine-X).
· MariaDB (MySQL fork).
· PHP 7 or 8 (You choose).
"
install


text:
#
#
# ifndef CHAOS_PREPROCESSOR_DEBUG_ASSERT_H
# define CHAOS_PREPROCESSOR_DEBUG_ASSERT_H
#
# include <chaos/preprocessor/config.h>
# include <chaos/preprocessor/control/inline_when.h>
# include <chaos/preprocessor/debug/failure.h>
# include <chaos/preprocessor/facilities/empty.h>
# include <chaos/preprocessor/lambda/ops.h>
# include <chaos/preprocessor/logical/not.h>
#
# /* CHAOS_PP_ASSERT */
#
# define CHAOS_PP_ASSERT(cond) CHAOS_PP_INLINE_WHEN(CHAOS_PP_NOT(cond))(CHAOS_PP_FAILURE())
# define CHAOS_PP_ASSERT_ID() CHAOS_PP_ASSERT
#
# if CHAOS_PP_VARIADICS
#    define CHAOS_PP_ASSERT_ CHAOS_PP_LAMBDA(CHAOS_PP_ASSERT)
# endif
#
# /* CHAOS_PP_ASSERT_MSG */
#
# if CHAOS_PP_VARIADICS
#    define CHAOS_PP_ASSERT_MSG(cond, ...) CHAOS_PP_INLINE_WHEN(CHAOS_PP_NOT(cond))(__VA_ARGS__)
#    define CHAOS_PP_ASSERT_MSG_ CHAOS_PP_LAMBDA(CHAOS_PP_ASSERT_MSG)
# else
#    define CHAOS_PP_ASSERT_MSG(cond, msg) CHAOS_PP_INLINE_WHEN(CHAOS_PP_NOT(cond))(msg)
# endif
#
# define CHAOS_PP_ASSERT_MSG_ID() CHAOS_PP_ASSERT_MSG
#
# endif


text:
      <button
        type="button"
        ng-focus="focus=true"
        ng-blur="focus=false"
        class="ui-grid-menu-close-button"
        ng-class="{'ui-grid-sr-only': (!focus)}">

      </button>


text:
#pragma once
#include <aws/cognito-idp/CognitoIdentityProvider_EXPORTS.h>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace CognitoIdentityProvider
{
namespace Model
{
  class AWS_COGNITOIDENTITYPROVIDER_API DeleteUserPoolDomainResult
  {
  public:
    DeleteUserPoolDomainResult();
    DeleteUserPoolDomainResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    DeleteUserPoolDomainResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

  };

} // namespace Model
} // namespace CognitoIdentityProvider
} // namespace Aws


text:
//
//  UITextField+TKCategory.m
//  Created by Devin Ross on 7/5/13.
//

#import "UITextField+TKCategory.h"

@implementation UITextField (TKCategory)

- (void) selectTextAtRange:(NSRange)range{
    UITextPosition *start = [self positionFromPosition:[self beginningOfDocument] offset:range.location];
    UITextPosition *end = [self positionFromPosition:start offset:range.length];
    [self setSelectedTextRange:[self textRangeFromPosition:start toPosition:end]];
}

@end


text:
var fs      = require('fs');
var path    = require('path');

exports.name = "Main Menu";
var options = exports.options = [];

var menuDir = path.dirname(module.filename);
fs.readdirSync(menuDir).forEach(function(file){
    if (file != 'index.js') {
        options.push(require(path.join(menuDir, file)));
    }
});


text:
@interface FNMeController () <UICollectionViewDataSource,UICollectionViewDelegate,SFSafariViewControllerDelegate>

@property (nonatomic, strong) NSMutableArray<FNMeSquareItem *> *squareArray;

@property (nonatomic, weak) UICollectionView *collectionV;

@property (nonatomic, strong) NSMutableArray<YJGridButtonitem *> *itemArray;

@end

@implementation FNMeController

static NSString *const ID = @"cell";
- (NSMutableArray *)squareArray
{
    if (!_squareArray){
        self.squareArray = [[NSMutableArray alloc] init];
    }
    return _squareArray;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.backgroundColor = FNCommonColor;
    // 设置
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"设置" style:0 target:self action:@selector(setBtnClick)];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];

    [FNMeGetSquareItem squareItem:^(NSArray *array) {
        self.squareArray = (NSMutableArray *)array;

        // 设置footView为collectionView
        [self setupFooterView];

        // 刷新内容
        [self.tableView reloadData];
    }];

    self.tableView.sectionFooterHeight = 10;
    self.tableView.sectionHeaderHeight = 0;

    // 减少额外滚动区域
    self.tableView.contentInset = UIEdgeInsetsMake(-25, 0, 0, 0);

}

//
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

// 设置tableView.footView为自己定义的collectionView
- (void)setupFooterView
{

    NSMutableArray *itemArray = [NSMutableArray array];

    for (int i = 0; i<self.squareArray.count; i++) {
        YJGridButtonitem *item = [[YJGridButtonitem alloc] init];
        FNMeSquareItem *squareItem = self.squareArray[i];
        item.image = squareItem.icon;
        item.desc = squareItem.name;
        item.url = squareItem.url;
        item.index = i;
        [itemArray addObject:item];
    }
    self.itemArray = itemArray;
    YJGridView *gridView = [YJGridView gridViewWithlist:itemArray];
    CGFloat gridX = 0;
    CGFloat gridY = 0;
    CGFloat gridW = FNScreenW;
    CGFloat gridH = (itemArray.count / 4 + 1) * FNScreenW/4;
    gridView.frame = CGRectMake(gridX, gridY, gridW, gridH);
    gridView.listBtnClickBlock = ^(YJGridItemListButton *btn){
        [self btnClick:btn];
    };
    // 关键代码
    self.tableView.tableFooterView = gridView;
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.squareArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    FNMeSquareViewCell *cell = [self.collectionV dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];

    cell.item = self.squareArray[indexPath.row];

    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    FNWKWebController *webVC = [[FNWKWebController alloc] init];
    webVC.url = self.squareArray[indexPath.row].url;
    [self.navigationController pushViewController:webVC animated:YES];

}

- (void)btnClick:(YJGridItemListButton *)btn
{
    FNWKWebController *webVC = [[FNWKWebController alloc] init];
    webVC.url = btn.url;
    [self.navigationController pushViewController:webVC animated:YES];
}

// 跳转到设置界面
- (void)setBtnClick
{
    FNMeSettingController *settingVC = [[FNMeSettingController alloc] init];

    [self.navigationController pushViewController:settingVC animated:YES];
}

@end