text:
package red.yelo.chat;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;

import red.yelo.data.DBInterface;
import red.yelo.data.DatabaseColumns;
import red.yelo.data.SQLConstants;
import red.yelo.data.TableChatMessages;
import red.yelo.data.TableChats;
import red.yelo.data.TableUsers;
import red.yelo.http.HttpConstants;
import red.yelo.http.JsonUtils;
import red.yelo.http.api.ChatApi;
import red.yelo.retromodels.GetUserModel;
import red.yelo.retromodels.request.SendChatRequestModel;
import red.yelo.utils.AppConstants;
import red.yelo.utils.AppConstants.ChatStatus;
import red.yelo.utils.AppConstants.ChatType;
import red.yelo.utils.DateFormatter;
import red.yelo.utils.Logger;
import red.yelo.utils.Utils;

/**
 * Runnable implementation to process chat messages
 */
class ChatProcessTask implements Runnable {

    private static final String TAG = "ChatProcessTask";

    private static final String CHAT_SELECTION = DatabaseColumns.CHAT_ID
            + SQLConstants.EQUALS_ARG;

    private static final String USER_SELECTION = DatabaseColumns.USER_ID
            + SQLConstants.EQUALS_ARG;

    private static final String USER_SELECTION_TABLEUSERS = DatabaseColumns.ID
            + SQLConstants.EQUALS_ARG;

    public static final int PROCESS_SEND = 1;
    public static final int PROCESS_RECEIVE = 2;

    /**
     * The process type of the task, either {@linkplain #PROCESS_SEND} or
     * {@linkplain #PROCESS_RECEIVE}
     */
    private int mProcessType;

    /**
     * Reference to the context to prepare notifications
     */
    private Context mContext;

    /**
     * The message Model
     */
    private SendChatRequestModel mMessageModel;

    /**
     * Date formatter for formatting chat timestamps
     */
    private DateFormatter mChatDateFormatter;

    /**
     * Date formatter for formatting timestamps for messages
     */
    private DateFormatter mMessageDateFormatter;

    /**
     * Callback for receiving when it is ready to send the chat message
     */
    private SendChatCallback mSendChatCallback;

    /**
     * received message in json string
     */
    private String mMessage;

    private ChatApi mChatApi;

    /**
     * Callback defined for when the local chat has been saved to the database
     * and the request can be sent
     */
    public static interface SendChatCallback {

        /**
         * Send the chat request
         *
         * @param messageModel The request model
         * @param dbRowId      The row id of the inserted local chat message
         */
        public void sendChat(final SendChatRequestModel messageModel, final long dbRowId);
    }

    private ChatProcessTask() {
        //Private constructor
    }

    private ChatProcessTask(final Context context, final ChatApi chatApi) {
        mContext = context;
        mChatApi = chatApi;
    }

    public int getProcessType() {
        return mProcessType;
    }

    public SendChatRequestModel getMessage() {
        return mMessageModel;
    }

    public DateFormatter getChatDateFormatter() {
        return mChatDateFormatter;
    }

    public DateFormatter getMessageDateFormatter() {
        return mMessageDateFormatter;
    }

    public SendChatCallback getSendChatCallback() {
        return mSendChatCallback;
    }

    @Override
    public void run() {

        if (mProcessType == PROCESS_RECEIVE) {
            processReceivedMessage();
        } else if (mProcessType == PROCESS_SEND) {
            saveMessageAndCallback();
        }

    }

    /**
     * Save a local message in the database, and give a callback to make the
     * chat send request once it is saved
     */
    private void saveMessageAndCallback() {

        try {

            final String senderId = mMessageModel.sender_id;
            final String receiverId = mMessageModel.receiver_id;
            final String sentAtTime = mMessageModel.sent_at;
            final String messageText = mMessageModel.message;
            final String serverReplyId = mMessageModel.reply_id;

            final ContentValues chatValues = new ContentValues(10);

            final String chatId = Utils.generateChatId(senderId, receiverId);

            Logger.d(TAG, "chat id : " + chatId);

            chatValues.put(DatabaseColumns.CHAT_ID, chatId);
            chatValues.put(DatabaseColumns.SERVER_CHAT_ID, serverReplyId);
            chatValues.put(DatabaseColumns.SENDER_ID, senderId);
            chatValues.put(DatabaseColumns.RECEIVER_ID, receiverId);
            chatValues.put(DatabaseColumns.MESSAGE, messageText);
            chatValues.put(DatabaseColumns.TIMESTAMP, sentAtTime);
            chatValues.put(DatabaseColumns.SENT_AT, sentAtTime);
            chatValues.put(DatabaseColumns.CHAT_STATUS, ChatStatus.SENDING);
            chatValues.put(DatabaseColumns.TIMESTAMP_EPOCH, mMessageDateFormatter
                    //server's time is 15 seconds ahead which creates sorting bugs,
                    //so we added server lag time in seconds
                    .getEpoch(sentAtTime) + AppConstants.SERVER_LAG_TIME);
            chatValues.put(DatabaseColumns.TIMESTAMP_HUMAN, mMessageDateFormatter
                    .getOutputTimestamp(sentAtTime));

            final long insertRowId = DBInterface
                    .insert(TableChatMessages.NAME, null, chatValues, true);

            Logger.d(TAG,insertRowId+"");

            if (insertRowId >= 0) {

                final ContentValues values = new ContentValues(7);
                values.put(DatabaseColumns.CHAT_ID, chatId);
                values.put(DatabaseColumns.SERVER_CHAT_ID, serverReplyId);
                values.put(DatabaseColumns.LAST_MESSAGE_ID, insertRowId);

                values.put(DatabaseColumns.CHAT_TYPE, ChatType.PERSONAL);
                values.put(DatabaseColumns.TIMESTAMP, sentAtTime);
                try {
                    values.put(DatabaseColumns.TIMESTAMP_HUMAN, mChatDateFormatter
                            .getOutputTimestamp(sentAtTime));
                    values.put(DatabaseColumns.TIMESTAMP_EPOCH, mChatDateFormatter
                            .getEpoch(sentAtTime));
                } catch (ParseException e) {
                    //Shouldn't happen
                    e.printStackTrace();
                }

                values.put(DatabaseColumns.ID, receiverId);

                Logger.v(TAG, "Updating chats for Id %s", chatId);
                final int updateCount = DBInterface
                        .update(TableChats.NAME, values, CHAT_SELECTION, new String[]{
                                chatId
                        }, true);

                if (updateCount == 0) {
                    Logger.v(TAG, "INSERTED chats for Id %s", chatId);
                    //Insert the chat message
                    DBInterface.insert(TableChats.NAME, null, values, true);
                }
            }

            //After finishing the local chat insertion, give a callback to do the actual network call
            mSendChatCallback.sendChat(mMessageModel, insertRowId);
        } catch (ParseException e) {
            Logger.e(TAG, e, "Invalid timestamp");
        }
    }

    /**
     * Processes a received message, stores it in the database
     */
    private void processReceivedMessage() {
        try {
            final JSONObject messageJson = new JSONObject(mMessage);
            //TODO we need some change in backend
            if (!mMessage.contains("Chatter not found")) {

                Logger.d(TAG, "1");

                final String messageText = JsonUtils
                        .readString(messageJson, HttpConstants.MESSAGE, false, false);

                final String serverReplyId = JsonUtils
                        .readString(messageJson, HttpConstants.REPLY_ID, false, false);

                String timestamp = JsonUtils
                        .readString(messageJson, HttpConstants.SERVER_SENT_AT, false, false);

                final String sentAtTime = JsonUtils
                        .readString(messageJson, HttpConstants.SENT_AT, false, false);

                String status = JsonUtils
                        .readString(messageJson, HttpConstants.STATUS, false, false);

                String senderId = "",
                        receiverId = "";
                if (status.equals(AppConstants.TRUE)) {
                    //sender values
                    senderId = JsonUtils
                            .readString(messageJson, HttpConstants.SENDER_ID, false, false);

                    //receiver values
                    receiverId = JsonUtils
                            .readString(messageJson, HttpConstants.RECEIVER_ID, false, false);
                } else if (status.equals(AppConstants.ERROR)) {

                    senderId = JsonUtils
                            .readString(messageJson, HttpConstants.SENDER_ID, false, false);

                    //receiver values
                    receiverId = JsonUtils
                            .readString(messageJson, HttpConstants.RECEIVER_ID, false, false);

                    timestamp = JsonUtils
                            .readString(messageJson, HttpConstants.SENT_AT, false, false);
                }

                final String chatId = Utils.generateChatId(receiverId, senderId);

                final ContentValues chatValues = new ContentValues(7);

                boolean isSenderCurrentUser = senderId
                        .equals(AppConstants.UserInfo.INSTANCE.getId());
                Logger.d(TAG, "2");

                Cursor cursorSender = getUserDetails(senderId);

                Cursor cursorReceiver = getUserDetails(receiverId);

                cursorSender.moveToFirst();
                cursorReceiver.moveToFirst();

                Logger.d(TAG, "chat id received : " + chatId);

                final String senderName = cursorSender.getString
                        (cursorSender.getColumnIndex(DatabaseColumns.USER_NAME));

                final String senderImage = cursorSender.getString
                        (cursorSender.getColumnIndex(DatabaseColumns.USER_IMAGE));

                chatValues.put(DatabaseColumns.CHAT_ID, chatId);
                chatValues.put(DatabaseColumns.SERVER_CHAT_ID, serverReplyId);
                chatValues.put(DatabaseColumns.SENDER_ID, senderId);
                chatValues.put(DatabaseColumns.SENDER_NAME, cursorSender.getString
                        (cursorSender.getColumnIndex(DatabaseColumns.USER_NAME)));
                chatValues.put(DatabaseColumns.SENDER_IMAGE, cursorSender.getString
                        (cursorSender.getColumnIndex(DatabaseColumns.USER_IMAGE)));
                chatValues.put(DatabaseColumns.RECEIVER_ID, receiverId);
                chatValues.put(DatabaseColumns.RECEIVER_NAME, cursorReceiver.getString
                        (cursorSender.getColumnIndex(DatabaseColumns.USER_NAME)));
                chatValues.put(DatabaseColumns.RECEIVER_IMAGE, cursorReceiver.getString
                        (cursorSender.getColumnIndex(DatabaseColumns.USER_IMAGE)));
                chatValues.put(DatabaseColumns.MESSAGE, messageText);
                chatValues.put(DatabaseColumns.TIMESTAMP, timestamp);
                chatValues.put(DatabaseColumns.SENT_AT, sentAtTime);
                chatValues.put(DatabaseColumns.CHAT_STATUS, isSenderCurrentUser ? ChatStatus.SENT
                        : ChatStatus.RECEIVED);
                chatValues.put(DatabaseColumns.TIMESTAMP_EPOCH, mMessageDateFormatter
                        .getEpoch(timestamp));
                chatValues.put(DatabaseColumns.TIMESTAMP_HUMAN, mMessageDateFormatter
                        .getOutputTimestamp(timestamp));

                Logger.d(TAG, "3");
                if (isSenderCurrentUser) {
                    //Update the locally saved message to mark it as sent

                    //Insert the chat message into DB
                    final String selection = DatabaseColumns.SENDER_ID
                            + SQLConstants.EQUALS_ARG + SQLConstants.AND
                            + DatabaseColumns.SENT_AT
                            + SQLConstants.EQUALS_ARG;

                    final String[] args = new String[]{
                            senderId, sentAtTime
                    };

                    Logger.d(TAG, "updated message in current user");

                    if (DBInterface.update(TableChatMessages.NAME, chatValues, selection, args, true) == 0) {
                        DBInterface.insert(TableChatMessages.NAME, null, chatValues, true);
                    }

                } else {

                    Logger.d(TAG, "inserted message");
                    //Insert the message in the db
                    final long insertRowId = DBInterface
                            .insert(TableChatMessages.NAME, null, chatValues, true);

                /*
                 * Parse and store sender info. We will receive messages both
                 * when we send and receive, so we need to check the sender id
                 * if it is our own id first to detect who sent the message
                 */

                    ChatNotificationHelper
                            .getInstance(mContext)
                            .showChatReceivedNotification(mContext, chatId, senderId, receiverId,
                                    senderName, messageText, senderImage);

                    final ContentValues values = new ContentValues(7);
                    values.put(DatabaseColumns.CHAT_ID, chatId);
                    values.put(DatabaseColumns.LAST_MESSAGE_ID, insertRowId);
                    values.put(DatabaseColumns.SERVER_CHAT_ID, serverReplyId);
                    values.put(DatabaseColumns.CHAT_TYPE, ChatType.PERSONAL);
                    values.put(DatabaseColumns.UNREAD_COUNT,1);

                    values.put(DatabaseColumns.ID, isSenderCurrentUser ? receiverId
                            : senderId);
                    values.put(DatabaseColumns.TIMESTAMP_HUMAN, mChatDateFormatter
                            .getOutputTimestamp(timestamp));
                    values.put(DatabaseColumns.TIMESTAMP, timestamp);
                    values.put(DatabaseColumns.TIMESTAMP_EPOCH, mChatDateFormatter
                            .getEpoch(timestamp));

                    final int updateCount = DBInterface
                            .update(TableChats.NAME, values, CHAT_SELECTION, new String[]{
                                    chatId
                            }, true);

                    Logger.v(TAG, "Updating chats for Id %s", chatId);

                    if (updateCount == 0) {
                        DBInterface.insert(TableChats.NAME, null, values, true);

                    }
                }
            } else {
                Logger.d(TAG, "some error in message sending");
            }

        } catch (JSONException e) {
            Logger.e(TAG, e, "Invalid message json");
        } catch (ParseException e) {
            Logger.e(TAG, e, "Invalid timestamp");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * Builder for Chat Process tasks
     */
    public static class Builder {

        private Context mContext;

        private ChatProcessTask mChatProcessTask;

        private ChatApi mChatService;

        public Builder(Context context, ChatApi chatApi) {
            mContext = context;
            mChatProcessTask = new ChatProcessTask(mContext, chatApi);
            mChatService = chatApi;
        }

        public Builder setProcessType(int processType) {
            mChatProcessTask.mProcessType = processType;
            return this;
        }

        public Builder setMessage(String message) {
            mChatProcessTask.mMessage = message;
            return this;
        }

        public Builder setMessageModel(SendChatRequestModel messageModel) {
            mChatProcessTask.mMessageModel = messageModel;
            return this;
        }

        public Builder setChatDateFormatter(DateFormatter chatDateFormatter) {
            mChatProcessTask.mChatDateFormatter = chatDateFormatter;
            return this;
        }

        public Builder setMessageDateFormatter(
                DateFormatter messageDateFormatter) {
            mChatProcessTask.mMessageDateFormatter = messageDateFormatter;
            return this;
        }

        public Builder setSendChatCallback(SendChatCallback sendChatCallback) {
            mChatProcessTask.mSendChatCallback = sendChatCallback;
            return this;
        }

        /**
         * Builds the chat process task
         *
         * @return The complete chat process task
         * @throws IllegalStateException If the chat process task is invalid
         */
        public ChatProcessTask build() {

            if (mChatProcessTask.mProcessType != PROCESS_RECEIVE
                    && mChatProcessTask.mProcessType != PROCESS_SEND) {
                throw new IllegalStateException("Invalid process type");
            }

            if (mChatProcessTask.mMessageModel != null) {
                if (TextUtils.isEmpty(mChatProcessTask.mMessageModel.message)) {
                    throw new IllegalStateException("Empty or null message");
                }
            } else {
                if (TextUtils.isEmpty(mChatProcessTask.mMessage)) {
                    throw new IllegalStateException("Empty or null message");
                }
            }

            if (mChatProcessTask.mChatDateFormatter == null) {
                throw new IllegalStateException("No chat date formatter set");
            }

            if (mChatProcessTask.mMessageDateFormatter == null) {
                throw new IllegalStateException("No message date formatter set");
            }

            if (mChatProcessTask.mProcessType == PROCESS_SEND
                    && mChatProcessTask.mSendChatCallback == null) {
                throw new IllegalStateException("No send chat callback set for a send message");
            }

            return mChatProcessTask;
        }

        /**
         * Resets the builder for preparing another chat process task
         */
        public Builder reset() {
            mChatProcessTask = new ChatProcessTask(mContext, mChatService);
            return this;
        }
    }

    private Cursor getUserDetails(String userId) {

        String selection = DatabaseColumns.ID + SQLConstants.EQUALS_ARG;
        Cursor cursor = DBInterface.query(true, TableUsers.NAME, null, selection, new String[]{userId}, null, null, null
                , null);

        if (cursor.getCount() != 0) {
            return cursor;
        } else {

            GetUserModel userDetail = mChatApi.getUserDetail(userId);

            ContentValues values = new ContentValues();
            values.put(DatabaseColumns.ID, userId);
            values.put(DatabaseColumns.USER_IMAGE, userDetail.user.image_url);
            values.put(DatabaseColumns.USER_NAME, userDetail.user.name);
            values.put(DatabaseColumns.USER_DESCRIPTION, userDetail.user.description);

            DBInterface.insert(TableUsers.NAME, null, values, false);

            String selection1 = DatabaseColumns.ID + SQLConstants.EQUALS_ARG;

            return DBInterface.query(true, TableUsers.NAME, null, selection1, new String[]{userId}, null, null, null
                    , null);
        }
    }

}


text:
export {
    meta,
    isDestroyed,
    guid,
    mixin,
    merge,
    clone,
    isEqual,
    classes,
    Class,
} from './Core.js';
export { sortByProperties } from './sortByProperties.js';
export { keyOf, filter, zip, fromQueryString } from './KeyValue.js';
export { limit, mod } from './Math.js';
export { email as emailRegExp, url as urlRegExp } from './RegExp.js';

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace noFlash\SupercacheBundle\Filesystem;

use FilesystemIterator;
use Iterator;
use noFlash\SupercacheBundle\Exceptions\FilesystemException;
use noFlash\SupercacheBundle\Exceptions\PathNotFoundException;
use noFlash\SupercacheBundle\Exceptions\SecurityViolationException;
use Psr\Log\LoggerInterface;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RegexIterator;
use SplFileInfo;

/**
 * Handles all filesystem operations.
 * This class always uses / (slash) as directory separator, however it accepts \.
 */
class Finder
{
    const CACHE_FILE_REGEX = '/index\.(html|js|bin)$/';

    /**
     * @var string
     */
    private $cacheDir;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @param string $cacheDir Patch to caching directory
     * @param LoggerInterface $logger
     *
     * @throws FilesystemException Unknown or invalid cache directory specified. It may be a permission problem.
     */
    public function __construct($cacheDir, LoggerInterface $logger)
    {
        $realCacheDir = $this->unixRealpath($cacheDir);

        if (!$realCacheDir) {
            throw new FilesystemException("Supercache data directory $cacheDir is invalid or inaccessible");
        }

        $this->cacheDir = $realCacheDir;
        $this->logger = $logger;
    }

    /**
     * Method works like realpath(), but it always return paths with slashes (while builtin one uses backslashes on Windos)
     *
     * @param $path
     *
     * @return string Unlike realpath() this method never returns false.
     */
    private function unixRealpath($path)
    {
        return (DIRECTORY_SEPARATOR==='/') ? (string)realpath($path) : str_replace('\\', '/', realpath($path));
    }

    /**
     * Provides real filesystem path to cache directory (with all variables and symlinks resolved)
     *
     * @return string
     */
    public function getRealCacheDir()
    {
        return $this->cacheDir;
    }

    /**
     * Converts relative path into physical path in filesystem.
     *
     * @param string $path
     *
     * @return string
     * @throws PathNotFoundException
     * @throws SecurityViolationException Thrown while path is not located under cache directory
     */
    private function getAbsolutePathFromRelative($path)
    {
        $absolute = $this->unixRealpath($this->cacheDir . '/' . $path);

        if (empty($absolute)) {
            throw new PathNotFoundException($path, 'entry cannot be located inside supercache directory');
        }

        if (strpos($absolute, $this->cacheDir) !== 0) {
            throw new SecurityViolationException("Requested path $path is located above supercache directory");
        }

        return $absolute;
    }

    /**
     * Provides raw list of cache files.
     *
     * @return Iterator|SplFileInfo[]
     *
     * @throw UnexpectedValueException Exception is thrown while cache directory cannot be opened or traversed.
     */
    public function getFilesList()
    {
        $dir = new RecursiveDirectoryIterator($this->cacheDir, FilesystemIterator::CURRENT_AS_FILEINFO);
        $ite = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::CHILD_FIRST);
        $files = new RegexIterator($ite, self::CACHE_FILE_REGEX);

        return $files;
    }

    /**
     * Get cache file content.
     *
     * @param string $path
     *
     * @return string|false Will return file contents or false if cannot be retrieved.
     * @throws PathNotFoundException
     * @throws SecurityViolationException Thrown while path is not located under cache directory
     * @throws \InvalidArgumentException Given path doesn't look like file created by this bundle
     */
    public function readFile($path)
    {
        try {
            $path = $this->getAbsolutePathFromRelative($path);

        } catch(PathNotFoundException $e) {
            return false;
        }

        if (!preg_match(static::CACHE_FILE_REGEX, $path)) {
            throw new \InvalidArgumentException("Finder can only read cache files - $path is not one of them");
        }

        return @file_get_contents($path);
    }

    /**
     * Deletes cache file.
     *
     * @param string $path
     *
     * @return bool
     * @throws PathNotFoundException
     * @throws SecurityViolationException Thrown while path is not located under cache directory
     * @throws \InvalidArgumentException Given path doesn't look like file created by this bundle
     */
    public function deleteFile($path)
    {
        $path = $this->getAbsolutePathFromRelative($path);
        if (!$path) {
            return false;
        }

        if (!preg_match(static::CACHE_FILE_REGEX, $path)) {
            throw new \InvalidArgumentException("Finder can only delete cache files - $path is not one of them");
        }

        return @unlink($path);
    }

    /**
     * Deletes EMPTY directory.
     *
     * @param string $path
     *
     * @return bool
     * @throws PathNotFoundException
     * @throws SecurityViolationException Thrown while path is not located under cache directory
     */
    public function deleteDirectory($path)
    {
        $path = $this->getAbsolutePathFromRelative($path);

        return ($path && @rmdir($path));
    }

    /**
     * Deletes directory with it's content.
     *
     *
     * @param string $path
     * @param bool $safeDelete By default this option is enabled and prevents deleting files and folders not created by
     *     that bundle.
     *
     * @return bool
     * @throws FilesystemException
     * @throws PathNotFoundException
     * @throws SecurityViolationException Thrown while path is not located under cache directory
     * @throws \RuntimeException Exception is used while unknown file is found and $safeDelete is enabled
     */
    public function deleteDirectoryRecursive($path, $safeDelete = true)
    {
        $path = $this->getAbsolutePathFromRelative($path);
        if (empty($path)) {
            return false;
        }

        $dir = new RecursiveDirectoryIterator($path,
            RecursiveDirectoryIterator::SKIP_DOTS | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::UNIX_PATHS);
        $iterator = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::CHILD_FIRST);

        /** @var SplFileInfo $fileInfo */
        foreach ($iterator as $fileInfo) {
            $realPath = $this->unixRealpath($fileInfo->getRealPath());

            if ($fileInfo->isDir()) {
                if (@!rmdir($realPath)) {
                    throw new FilesystemException('Failed to delete directory ' . $realPath);
                }

            } else {
                if (strpos($realPath, $this->cacheDir .  '/.') === 0) { //Skip dot-files in root directory
                    continue;
                }

                if ($safeDelete && !preg_match(self::CACHE_FILE_REGEX, $realPath)) {
                    throw new \RuntimeException('Finder found unknown file ' . $realPath . ' - this was not created by SupercacheBundle. Inspect this issue manually.');
                }

                if (@!unlink($realPath)) {
                    throw new FilesystemException('Failed to delete file ' . $realPath);
                }
            }
        }

        if ($path !== $this->cacheDir) {
            return rmdir($path);
        }

        return true;
    }

    /**
     * Saves content to given cache file.
     *
     * @param $path
     * @param $content
     *
     * @return bool
     * @throws FilesystemException
     * @throws SecurityViolationException Should never be thrown from this method. If thrown it means some security
     *     mechanisms failed to sanitize $path and file gets created outside cache directory. This method is smart
     *     enough to rollback that change by deleting file (so no harm is expected). If you seen that exception while
     *     calling this method fill bug report asap.
     * @throws \InvalidArgumentException Given path doesn't look like file created by this bundle.
     */
    public function writeFile($path, $content)
    {
        $fullPath = preg_replace('/(\/|\\\)+/','/', $this->cacheDir . '/' . $path); //Convert to absolute path with unix separators & remove duplicated slashed

        if (preg_match('/\/\.\.|\.\.\//', $fullPath)) { //Don't look at me that way, please...
            throw new SecurityViolationException("Requested path $path is invalid");
        }

        if (!preg_match(self::CACHE_FILE_REGEX, $fullPath)) {
            throw new \InvalidArgumentException("Finder can only create cache files - $path is not one of them");
        }

        $info = pathinfo($fullPath);
        if (!isset($info['dirname']) || (!is_dir($info['dirname']) && !mkdir($info['dirname'], 0777, true))) {
            throw new FilesystemException('Failed to create directory for ' . $path);
        }

        if (file_put_contents($fullPath, $content) === false) {
            $this->logger->error("Unable to write cache file $fullPath (requested write to $path)",
                array('content' => $content));

            return false;
        }

        //Last verification to be 100% sure we did the right thing...
        try {
            $this->getAbsolutePathFromRelative($path);

            return true;

        } catch (\Exception $e) {
            @unlink($fullPath); //Remove bogus file

            $this->logger->error("Cache file verification failed after write - file not found after writing to $fullPath (requested $path)");

            if($e instanceof SecurityViolationException) {
                $this->logger->error("Cache file verification failed after write - file not found after writing to $fullPath (requested $path)");
            }

            return false;
        }
    }

    /**
     * Checks if given cache file/folder is readable.
     *
     * @param $path
     *
     * @return bool
     * @throws SecurityViolationException Tried to access file outside cache directory.
     */
    public function isReadable($path)
    {
        try {
            $this->getAbsolutePathFromRelative($path);

            return true;

        } catch(PathNotFoundException $e) {
            return false;
        }
    }
}


text:
require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/fixtures/classes'

describe "Hash#invert" do
  it "returns a new hash where keys are values and vice versa" do
    { 1 => 'a', 2 => 'b', 3 => 'c' }.invert.should == { 'a' => 1, 'b' => 2, 'c' => 3 }
  end

  it "handles collisions by overriding with the key coming later in keys()" do
    h = { :a => 1, :b => 1 }
    override_key = h.keys.last
    h.invert[1].should == override_key
  end

  it "compares new keys with eql? semantics" do
    h = { :a => 1.0, :b => 1 }
    i = h.invert
    i[1.0].should == :a
    i[1].should == :b
  end

  it "does not return subclass instances for subclasses" do
    MyHash[1 => 2, 3 => 4].invert.class.should == Hash
    MyHash[].invert.class.should == Hash
  end
end


text:
'use strict';

var Backoff = require('./backoff'),
Listener = require('./listener'),
utils = require('./utils'),
processArgs = utils.processArgs,
callbackify = utils.callbackify,

LocalFirst = function (pouchMirror){
    var self = this;
    self.pouchMirror = pouchMirror;
    self._localDB = pouchMirror._localDB;
    self._remoteDB = pouchMirror._remoteDB;
    self._initState();
};

LocalFirst.prototype._initState = function(failOver) {
  var self = this;
  // remoteDB is the source of truth until initial sync is complete
  if (!failOver){
    self._writeDB = self._readDB = self._remoteDB;
  }
  else {
    // Sync failed fatally, failover to localDB
    self._writeDB = self._readDB = self._localDB;
  }
  self._remoteSynced = false;
  self._active = false;
};

LocalFirst.prototype._destroyIfPending = function(){
    var self = this;
    if (typeof self._resolvePendingDestroy == 'function'){
      self._resolvePendingDestroy();
      self._resolvePendingDestroy = null;
    }
};

LocalFirst.prototype.destroy = function(){
    var self = this,
        args = arguments;
    // If delta sync is scheduled, wait for it to complete.
    if (self._deltaSyncHandle != null){
        return (new Promise(function (resolve, reject){
            self._resolvePendingDestroy = resolve;
        })
        .then(function(){
            return self.destroy.apply(self, args);
        }));
    }

    return self._localDB.destroy.apply(self._localDB, args);
};

LocalFirst.prototype._deltaSync = function(){
    var self = this;
    self._listener = new Listener(self._localDB);
    var replicator = self._localDB.sync(self._remoteDB,
    {
        live: false,
        back_off_function: self._defaultBackoff
    })
    .on('complete', function (info) {
      if (!self._remoteSynced) {
        self._remoteSynced = true;
        self._deltaSyncHandle = null;
        replicator.emit('up-to-date-delta', {db: self._localDB._db_name});
        self._destroyIfPending();
      }
    })
    .on('pause', function(err){
     if (err){
        console.error('[PouchMirror] Non-fatal delta replication error', err);
     }
    })
    .on('denied', function (err) {
      console.error('[PouchMirror] Fatal delta replication error', err);
      self._listener.cancel();
      self._deltaSyncHandle = null;
      self._destroyIfPending();
    })
    .on('error', function (err) {
      console.error('[PouchMirror] Fatal replication error', err);
      self._listener.cancel();
      self._deltaSyncHandle = null;
      self._destroyIfPending();
    });

  replicator._superCancel = replicator.cancel;
  replicator.cancel = function() {
    self._listener.cancel();
    replicator._superCancel();
  };
  self._deltaSyncReplicator = replicator;
  return replicator;
};

LocalFirst.prototype._scheduleDeltaSyncOnce = function(debounceIntervalInMs){
    var self = this;
    // Clear pending sync on re-entry.
    if (self._deltaSyncHandle){
        clearTimeout(self._deltaSyncHandle);
        self._deltaSyncHandle = null;
    }

    self._deltaSyncHandle = setTimeout(self._deltaSync.bind(self), debounceIntervalInMs);
};

LocalFirst.prototype._monitorLocalChanges = function(debounceIntervalInMs){
    var self = this;
    self._localDB.changes({
        since: 'now',
        live: true})
    .on('change', self._scheduleDeltaSyncOnce.bind(self, debounceIntervalInMs))
    .on('error', function(err){
        console.error('[PouchMirror] Non-fatal changes feed error', err);
    });
};

LocalFirst.prototype.start = function (options) {
  var self = this;
  if(!options) options = {};
  options.live = false;
  if(options.retry && typeof options.back_off_function !== 'function') {
    var backoff = new Backoff(options.maxTimeout);
    options.back_off_function = backoff;
    // Store this for delta-sync too.
    self._defaultBackoff = backoff;
  }
  if (self._active) throw new Error('[PouchMirror] Error: sync already active');
  self._active = true;
  // Start buffering changes as they come in
  self._listener = new Listener(self._localDB);
  var replicator = self._localDB.sync(self._remoteDB, options)
    .on('complete', function (info) {
        console.log('initial-sync-completed');
      if (!self._remoteSynced) {
        self._remoteSynced = true;
        // Switch local DB as the source of truth.
        self._writeDB = self._readDB = self._localDB;
        replicator.emit('up-to-date', {db: self._localDB._db_name});
        // Start monitoring local changes
        self._monitorLocalChanges(options.debounceInterval || 1000);
      }
    })
    .on('pause', function(err){
     if (err){
        console.error('[PouchMirror] Non-fatal replication error', err);
     }
    })
    .on('denied', function (err) {
      self._listener.cancel();
      self._initState(true);
      console.error('[PouchMirror] Fatal replication error', err);
    })
    .on('error', function (err) {
      self._listener.cancel();
      self._initState(true);
      console.error('[PouchMirror] Fatal replication error', err);
    });
  replicator._superCancel = replicator.cancel;
  replicator.cancel = function() {
    self._listener.cancel();
    replicator._superCancel();
    self._initState();
  };
  self._syncReplicator = replicator;
  return replicator;
};

LocalFirst.prototype.pause = function() {
  var self = this;
  self._syncReplicator.cancel();
  self._deltaSyncReplicator.cancel();
};

LocalFirst.prototype.get = function () {
  var self = this;
  return self._readDB.get.apply(self._readDB, arguments);
};

LocalFirst.prototype.allDocs = function () {
  var self = this;
  return self._readDB.allDocs.apply(self._readDB, arguments);
};

LocalFirst.prototype.bulkGet = function () {
  var self = this;
  return self._readDB.bulkGet.apply(self._readDB, arguments);
};

LocalFirst.prototype.put = function () {
  var self = this;
  var argObj = processArgs(arguments);
  var output;
  var promise = self._writeDB.put.apply(self._writeDB, argObj.args)
    .then(function (response) {
      output = response;
      if(!self._active) return Promise.resolve();
      return self._listener.waitForChange(response.rev);
    })
    .then(function () {
      return Promise.resolve(output);
    });
  if (argObj.cb) callbackify(promise, argObj.cb);
  return promise;
};

LocalFirst.prototype.post = function () {
  var self = this;
  var argObj = processArgs(arguments);
  var output;
  console.log("Writing to remotedDB? " + (self._writeDB == self._remoteDB));
  console.log("Writing to localDB? " + (self._writeDB == self._localDB));
  var promise = self._writeDB.post.apply(self._writeDB, argObj.args)
    .then(function (response) {
      output = response;
      if(!self._active) return Promise.resolve();
      return self._listener.waitForChange(response.rev);
    })
    .then(function () {
      return Promise.resolve(output);
    });
  if (argObj.cb) callbackify(promise, argObj.cb);
  return promise;
};

LocalFirst.prototype.bulkDocs = function () {
  var self = this;
  var argObj = processArgs(arguments);
  var output;
  var promise = self._writeDB.bulkDocs.apply(self._writeDB, argObj.args)
    .then(function (results) {
      output = results;
      var promises = [];
      results.forEach(function (row) {
        if (row.ok === true) {
          promises.push(self._listener.waitForChange(row.rev));
        }
      });
      if(!self._active) return Promise.resolve();
      return Promise.all(promises);
    })
    .then(function () {
      return Promise.resolve(output);
    });
  if (argObj.cb) callbackify(promise, argObj.cb);
  return promise;
};

LocalFirst.prototype.remove = function () {
  var self = this;
  var argObj = processArgs(arguments);
  var output;
  var promise = self._writeDB.remove.apply(self._writeDB, argObj.args)
    .then(function (result) {
      output = result;
      if(!self._active) return Promise.resolve();
      return self._listener.waitForChange(result.rev);
    })
    .then(function () {
      return Promise.resolve(output);
    });
  if (argObj.cb) callbackify(promise, argObj.cb);
  return promise;
};

LocalFirst.prototype.putAttachment = function () {
  var self = this;
  var argObj = processArgs(arguments);
  var output;
  var promise = self._writeDB.putAttachment.apply(self._writeDB, argObj.args)
    .then(function (response) {
      output = response;
      if(!self._active) return Promise.resolve();
      return self._listener.waitForChange(response.rev);
    })
    .then(function () {
      return Promise.resolve(output);
    });
  if (argObj.cb) callbackify(promise, argObj.cb);
  return promise;
};

LocalFirst.prototype.getAttachment = function () {
  var self = this;
  return self._readDB.getAttachment.apply(self._readDB, arguments);
};

LocalFirst.prototype.removeAttachment = function () {
  var self = this;
  var argObj = processArgs(arguments);
  var output;
  var promise = self._writeDB.removeAttachment.apply(self._writeDB, argObj.args)
    .then(function (response) {
      output = response;
      if(!self._active) return Promise.resolve();
      return self._listener.waitForChange(response.rev);
    })
    .then(function () {
      return Promise.resolve(output);
    });
  if (argObj.cb) callbackify(promise, argObj.cb);
  return promise;
};

LocalFirst.prototype.query = function () {
  var self = this;
  return self._readDB.query.apply(self._readDB, arguments);
};

LocalFirst.prototype.info = function () {
  var self = this;
  var argObj = processArgs(arguments);
  var theinfo = {};
  var promise = Promise.all([
      self._remoteDB.info.apply(self._remoteDB, argObj.args),
      self._localDB.info.apply(self._localDB, argObj.args)
    ])
    .then(function (results) {
      theinfo.remote = results[0];
      theinfo.local = results[1];
      return Promise.resolve(theinfo);
    });
  if (argObj.cb) callbackify(promise, argObj.cb);
  return promise;
};

LocalFirst.prototype.replicate = {
  to: function() {
    this._localDB.replicate.to.apply(this._localDB, arguments);
  },
  from: function() {
    this._localDB.replicate.from.apply(this._localDB, arguments);
  }
};

module.exports = LocalFirst;


text:
function nebulaShowError(messageId,message) {
	$("#formid_"+messageId+"_error").html(message);
}

function nebulaClearError(messageId,message) {
	$("#formid_"+messageId+"_error").html("");
}

function nebulaAlert(message) {
	alert(message);
}


text:
require 'spec_helper'

<<-COMMENT
This spec covers our user issue with his setup.py file
which uses more spaces and \" as string literal.

COMMENT

describe PythonSetupParser do
  context 'parse' do

    let(:testfile_url){"https://s3.amazonaws.com/veye_test_env/python_1/setup.py"}
    let(:parser){PythonSetupParser.new}
    let(:product1){ProductFactory.create_for_pip "requests", "1.2.3"}

    after :each do
      product1.delete
      Project.delete_all
      Dependency.delete_all
    end

    it "imports from S3 successfully" do
      project = parser.parse testfile_url
      project.should_not be_nil
    end

    it "parses project file correctly" do
      product1.save
      project = parser.parse testfile_url
      project.should_not be_nil

      project.dependencies.size.should eq(1)

      dep1 = project.dependencies.first
      dep1.name.should eq(product1.name)
      dep1.version_requested.should eq(product1.version)

    end
  end
end


text:
class GURL;

namespace net {
class URLFetcher;
}  // namespace

namespace content {

// Mark URLRequests started by the URLFetcher to stem from the given render
// view.
CONTENT_EXPORT void AssociateURLFetcherWithRenderView(
    net::URLFetcher* url_fetcher,
    const GURL& first_party_for_cookies,
    int render_process_id,
    int render_view_id);

}  // namespace content

#endif  // CONTENT_PUBLIC_COMMON_URL_FETCHER_H_


text:
#include <ieee754.h>
#include <stdlib.h>
#include <limits.h>

extern int __drand48_iterate(unsigned short xsubi[3],
	struct drand48_data *buffer);

int erand48_r (xsubi, buffer, result)
     unsigned short int xsubi[3];
     struct drand48_data *buffer;
     double *result;
{
    union ieee754_double temp;

    /* Compute next state.  */
    if (__drand48_iterate (xsubi, buffer) < 0)
	return -1;

    /* Construct a positive double with the 48 random bits distributed over
       its fractional part so the resulting FP number is [0.0,1.0).  */

    temp.ieee.negative = 0;
    temp.ieee.exponent = IEEE754_DOUBLE_BIAS;
    temp.ieee.mantissa0 = (xsubi[2] << 4) | (xsubi[1] >> 12);
    temp.ieee.mantissa1 = ((xsubi[1] & 0xfff) << 20) | (xsubi[0] << 4);

    /* Please note the lower 4 bits of mantissa1 are always 0.  */
    *result = temp.d - 1.0;

    return 0;
}


text:
<?php

namespace GhaenCollege\ScrumBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ProjectType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title')
            ->add('description')
            ->add('createDate')
            ->add('startDate')
            ->add('endDate')
            ->add('status')
            ->add('schedule')
            ->add('builder')
            ->add('parent')
            ->add('productOwner')
            ->add('members')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'GhaenCollege\ScrumBundle\Entity\Project'
        ));
    }

    public function getName()
    {
        return 'ghaencollege_scrumbundle_projecttype';
    }
}


text:
(function() {
    //console.log('main loaded');
})();


text:
<?PHP
// +---------------------------------------------------------+
// | Cadastro de miniaturas - exibi��o modo tabela           |
// +---------------------------------------------------------+

include "../inc_dbConexao.php";

SESSION_START();

if ($_GET['id'] == "") {
	$idsel = $_POST['id'];
} else {
	$idsel = $_GET['id'];
}
$sql = "SELECT * FROM miniaturas";
$sql = $sql . " ORDER BY id ";
$rs = mysql_query($sql, $conexao);
$total_registros = mysql_num_rows($rs);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>MiniERP - Administrativo</title>
<link href="estilo_adm.css" rel="stylesheet" type="text/css" />

Administração do Site

<?PHP include "inc_menu.php" ?>

Manutenção Cadastral  Miniaturas

Total de registros no cadastro: <?PHP print $total_registros; ?>

Código
Descrição
Estoque
Preço

Ações

<?PHP
// Exibe os registros na tabela
while ($reg = mysql_fetch_array($rs)) {
$id = $reg["id"];
$codigo = $reg["codigo"];
$nome = $reg["nome"];
$estoque = $reg["estoque"];
$preco = $reg["preco"];

//Destaca a linha do �ltimo registro selecionado (fundo azul claro)
if ($idsel == $id) {
  $fundo = "registro_sel";
} else {
  $fundo = "registro";
}
?>

<td class="<?PHP print $fundo; ?>"><?PHP print $codigo; ?>
<td class="<?PHP print $fundo; ?>"><?PHP print $nome; ?>
<td align="right" class="<?PHP print $fundo; ?>"><?PHP print $estoque; ?>
<td align="right" class="<?PHP print $fundo; ?>">R$ <?PHP print number_format($preco,2,',','.'); ?>

<td width="6%" class="<?PHP print $fundo; ?>"><a href="cad_miniaturas.php?acao=exc&id=<?PHP print $id; ?>&titulo=Exclusão de registro">

<td width="5%" class="<?PHP print $fundo; ?>"><a href="cad_miniaturas.php?acao=alt&id=<?PHP print $id; ?>&titulo=Alteração de registro">

<td width="3%" class="<?PHP print $fundo; ?>"><a href="cad_miniaturas.php?acao=ver&id=<?PHP print $id; ?>&titulo=Detalhes da miniatura">

<?PHP } ?>

<?PHP include "inc_rodape.php" ?>

<?PHP
// Libera os recursos usados pela conex�o atual
mysql_free_result($rs);
mysql_close ($conexao);
?>


text:
<?php

/**
 * @file
 * Contains \Drupal\Console\Core\Command\Settings\SetCommand.
 */

namespace Drupal\Console\Core\Command\Settings;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Yaml\Dumper;
use Symfony\Component\Yaml\Parser;
use Drupal\Console\Core\Command\Command;
use Drupal\Console\Core\Utils\ConfigurationManager;
use Drupal\Console\Core\Utils\NestedArray;
use Drupal\Console\Core\Style\DrupalStyle;

/**
 * Class SetCommand
 *
 * @package Drupal\Console\Core\Command\Settings
 */
class SetCommand extends Command
{
    /**
     * @var ConfigurationManager
     */
    protected $configurationManager;

    /**
     * @var NestedArray
     */
    protected $nestedArray;

    /**
     * CheckCommand constructor.
     *
     * @param ConfigurationManager $configurationManager
     * @param NestedArray          $nestedArray
     */
    public function __construct(
        ConfigurationManager $configurationManager,
        NestedArray $nestedArray
    ) {
        $this->configurationManager = $configurationManager;
        $this->nestedArray = $nestedArray;

        parent::__construct();
    }

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('settings:set')
            ->addArgument(
                'name',
                InputArgument::REQUIRED,
                $this->trans('commands.settings.set.arguments.name'),
                null
            )
            ->addArgument(
                'value',
                InputArgument::REQUIRED,
                $this->trans('commands.settings.set.arguments.value'),
                null
            )
            ->setDescription($this->trans('commands.settings.set.description'));
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new DrupalStyle($input, $output);
        $parser = new Parser();
        $dumper = new Dumper();

        $settingName = $input->getArgument('name');
        $settingValue = $input->getArgument('value');

        $userConfigFile = sprintf(
            '%s/.console/config.yml',
            $this->configurationManager->getHomeDirectory()
        );

        if (!file_exists($userConfigFile)) {
            $io->error(
                sprintf(
                    $this->trans('commands.settings.set.messages.missing-file'),
                    $userConfigFile
                )
            );
            return 1;
        }

        try {
            $userConfigFileParsed = $parser->parse(
                file_get_contents($userConfigFile)
            );
        } catch (\Exception $e) {
            $io->error(
                $this->trans(
                    'commands.settings.set.messages.error-parsing'
                ) . ': ' . $e->getMessage()
            );
            return 1;
        }

        $parents = array_merge(['application'], explode(".", $settingName));

        $this->nestedArray->setValue(
            $userConfigFileParsed,
            $parents,
            $settingValue,
            true
        );

        try {
            $userConfigFileDump = $dumper->dump($userConfigFileParsed, 10);
        } catch (\Exception $e) {
            $io->error(
                [
                    $this->trans('commands.settings.set.messages.error-generating'),
                    $e->getMessage()
                ]
            );

            return 1;
        }

        if ($settingName == 'language') {
            $this->getApplication()
                ->getTranslator()
                ->changeCoreLanguage($settingValue);

            $translatorLanguage = $this->getApplication()->getTranslator()->getLanguage();
            if ($translatorLanguage != $settingValue) {
                $io->error(
                    sprintf(
                        $this->trans('commands.settings.set.messages.missing-language'),
                        $settingValue
                    )
                );

                return 1;
            }
        }

        try {
            file_put_contents($userConfigFile, $userConfigFileDump);
        } catch (\Exception $e) {
            $io->error(
                [
                    $this->trans('commands.settings.set.messages.error-writing'),
                    $e->getMessage()
                ]
            );

            return 1;
        }

        $io->success(
            sprintf(
                $this->trans('commands.settings.set.messages.success'),
                $settingName,
                $settingValue
            )
        );

        return 0;
    }
}


text:
'use strict';

var invariant = require('fbjs/lib/invariant');
var shallowEqual = require('fbjs/lib/shallowEqual');

var SCENE_KEY_PREFIX = 'scene_';

function compareKey(one, two) {
  var delta = one.length - two.length;
  if (delta > 0) {
    return 1;
  }
  if (delta < 0) {
    return -1;
  }
  return one > two ? 1 : -1;
}

function compareScenes(one, two) {
  if (one.index > two.index) {
    return 1;
  }
  if (one.index < two.index) {
    return -1;
  }

  return compareKey(one.key, two.key);
}

function areScenesShallowEqual(one, two) {
  return one.key === two.key && one.index === two.index && one.isStale === two.isStale && one.isActive === two.isActive && areRoutesShallowEqual(one.route, two.route);
}

function areRoutesShallowEqual(one, two) {
  if (!one || !two) {
    return one === two;
  }

  if (one.key !== two.key) {
    return false;
  }

  return shallowEqual(one, two);
}

function NavigationScenesReducer(scenes, nextState, prevState) {
  if (prevState === nextState) {
    return scenes;
  }

  var prevScenes = new Map();
  var freshScenes = new Map();
  var staleScenes = new Map();

  scenes.forEach(function (scene) {
    var key = scene.key;

    if (scene.isStale) {
      staleScenes.set(key, scene);
    }
    prevScenes.set(key, scene);
  });

  var nextKeys = new Set();
  nextState.routes.forEach(function (route, index) {
    var key = SCENE_KEY_PREFIX + route.key;
    var scene = {
      index: index,
      isActive: false,
      isStale: false,
      key: key,
      route: route
    };
    invariant(!nextKeys.has(key), 'navigationState.routes[' + index + '].key "' + key + '" conflicts with ' + 'another route!');
    nextKeys.add(key);

    if (staleScenes.has(key)) {
      staleScenes.delete(key);
    }
    freshScenes.set(key, scene);
  });

  if (prevState) {
    prevState.routes.forEach(function (route, index) {
      var key = SCENE_KEY_PREFIX + route.key;
      if (freshScenes.has(key)) {
        return;
      }
      staleScenes.set(key, {
        index: index,
        isActive: false,
        isStale: true,
        key: key,
        route: route
      });
    });
  }

  var nextScenes = [];

  var mergeScene = function mergeScene(nextScene) {
    var key = nextScene.key;

    var prevScene = prevScenes.has(key) ? prevScenes.get(key) : null;
    if (prevScene && areScenesShallowEqual(prevScene, nextScene)) {
      nextScenes.push(prevScene);
    } else {
      nextScenes.push(nextScene);
    }
  };

  staleScenes.forEach(mergeScene);
  freshScenes.forEach(mergeScene);

  nextScenes.sort(compareScenes);

  var activeScenesCount = 0;
  nextScenes.forEach(function (scene, ii) {
    var isActive = !scene.isStale && scene.index === nextState.index;
    if (isActive !== scene.isActive) {
      nextScenes[ii] = babelHelpers.extends({}, scene, {
        isActive: isActive
      });
    }
    if (isActive) {
      activeScenesCount++;
    }
  });

  invariant(activeScenesCount === 1, 'there should always be only one scene active, not %s.', activeScenesCount);

  if (nextScenes.length !== scenes.length) {
    return nextScenes;
  }

  if (nextScenes.some(function (scene, index) {
    return !areScenesShallowEqual(scenes[index], scene);
  })) {
    return nextScenes;
  }

  return scenes;
}

module.exports = NavigationScenesReducer;


text:
/**
 *
 * Component that renders NCBI annotations for circular genomes such as bacterial genomes or mitocondria.
 *
 * @class
 * @extends Biojs
 *
 * @author José Villaveces
 * @version 1.0.0_beta
 * @category 2
 *
 *
 * @requires D3 Data-Driven Documents
 * @dependency
 *
 * @requires underscore.js
 * @dependency
 *
 * @requires jQuery
 * @dependency
 *
 * @requires Circular Feature Viewer
 * @dependency
 *
 * @param {Object} options An object with the options for this component.
 *
 * @option {string} target
 *    id of the div where the component should be displayed.
 *
 * @option {string} nucleotide
 * 	  The NCBI nucleotide id.
 *
 * @option {int} width
 * 	  desired width of the component.
 *
 * @option {int} height
 * 	  desired height of the component.
 *
 * @option {string[]} elementsToDisplay
 * 	  desired annotation types to display. Possible values include : source, gene, STS, rRNA, D-loop
 *
 * @option {boolean} mergeAnnotations
 * 	  wether NCBI annotations should be merged or not
 *
 * @option {Object[]} features
 * 	  Array containing additional annotations to be rendered.
 *
 * @option {int} id
 * 	  Annotation identifier.
 *
 * @option {int} start
 * 	  Position at wich the annotation starts.
 *
 * @option {int} stop
 * 	  Position at wich the annotation terminates.
 *
 * @option {string[] || string} type
 * 	  Annotation type, annotation color is decided uppon the annotation type
 *
 * @example
 * var myCircularGenomeFeatureViewer = new Biojs.CircularGenomeFeatureViewer({
 *      target: 'YourOwnDivId',
 *		nucleotide: 'NC_012920.1',// Human Mitochondrion
 *      features:[
 *          { "id": 0, "start": 19, "stop": 305, "type": "voluptate", "color":"green" },
 *          { "id": 1, "start": 143, "stop": 283, "type": "non", "color":"red"}
 *      ],
 *      width:715,
 *      height:505,
 *      mergeAnnotations:false
 * });
 */

var _ = require("underscore");
var CircularFeatureViewer = require("./circular");
var Class = require('js-class');

module.exports = CircularGenomeFeatureViewer = Class(CircularFeatureViewer,
/** @lends Biojs.CircularGenomeFeatureViewer# */
{
    constructor: function (options) {

        require('js-extend').extend(this.opt, options)
        this._getNCBIAnnotations(this.opt.nucleotide);

        this._render();
    },

    /**
	 * Default values for the options
	 * @name Biojs.CircularGenomeFeatureViewer-opt
	 */
    opt: {
        target: 'YourOwnDivId',
        nucleotide: 'NC_012920.1',
        features: [],
        elementsToDisplay: ['source', 'gene', 'STS', 'rRNA', 'D-loop'],
        width: 500,
        height: 500,
        speed: 5,
        mergeAnnotations: true
    },

    // internal members
    _efetch: 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi',//NCBI efetch URL
    _database : 'nucleotide',//NCBI database to query
    _format : 'xml',//query result format
    _rettype: 'gb',//query rettype

    /**
	 * Rotates all annotations so the desired sequence position is at 12 o'çlock.
	 * @param {int} pos The sequence position.
	 *
	 * @example
	 * myCircularGenomeFeatureViewer.goTo(1000);
     *
     * @example
	 * myCircularGenomeFeatureViewer.goTo(1);
	 *
	 */
	  /*
    goTo : function(pos){
        this.base(pos);
    },
    /**
	 * Adds a new annotation.
	 * @param {Object} annotation The annotation.
	 *
	 * @example
	 * myCircularGenomeFeatureViewer.addAnnotation({ "id": 14, "start": 351, "stop": 1200, "type": "dolore" });
	 *
	 */
	  /*
    addAnnotation : function(annotation){
        this.base(annotation);
    },
	 */

    /**
	 * Removes an annotation from the visualization.
	 * @param {int} id The annotation id.
	 *
	 * @example
	 * myCircularGenomeFeatureViewer.removeAnnotation(1);
	 *
	 */
	  /*
    removeAnnotation : function(id){
        this.base(id);
    },
	 */

    /*
     * Function: Biojs.CircularGenomeFeatureViewer._getNCBIAnnotations
     * Purpose:  Queries the NCBI in order to retrieve nucleotide annotations
     * Returns:  -
     * Inputs: nucleotide -> {String} The nucleotide.
     */
    _getNCBIAnnotations: function(nucleotide){
        var xml = null;
        $.ajax({
            url: this._efetch,
            data: { db: this._database, rettype: this._rettype, retmode: this._format, id: nucleotide},
            async: false,
            dataType: "xml",
            success: function(res){
                xml = res;
            }
        });

        this.opt.sequence = $(xml).first().find('GBSeq_sequence').text();

        var self = this, feats = [];
        _.each($(xml).find('GBFeature'), function(feat){
            var key = $(feat).find('GBFeature_key').text();

            if(_.contains(self.opt.elementsToDisplay, key))
                self._mapFeature(feat, feats);
        });

        if(self.opt.mergeAnnotations){

            feats = _.groupBy(feats, function(feat){
                return feat.start+'-'+feat.stop;
            });

            feats = _.map(feats,function(arr){
                return _.reduce(arr, function(prev, now){ prev.type.push(now.type[0]); return prev; });
            });
        }

        this.opt.features = feats.concat(this.opt.features);
    },
    /*
     * Function: Biojs.CircularGenomeFeatureViewer._mapFeature
     * Purpose:  Transforms an XML annotation into a JSON one and adds it to an array
     * Returns:  -
     * Inputs: feature -> {Object} The XML annotation.
     *         array -> the array to add the json annotation.
     */
    _mapFeature: function(feature, array){
        var key = $(feature).find('GBFeature_key').text();
        _.each($(feature).find('GBInterval'), function(interval){
            var isComp = $(interval).find('GBInterval_iscomp').attr('value'),
                start = +$(interval).find('GBInterval_from').text(),
                stop = +$(interval).find('GBInterval_to').text();

            var feat = {};
            if(isComp === undefined){
                feat = { start : start, stop : stop, type : [key], text : $(interval).find('GBInterval_accession').text()}
            }else{
                feat = { start : stop, stop : start, type : [key], text : $(interval).find('GBInterval_accession').text()}
            }

            array.push(feat)
        });
    }
});


text:
jest.dontMock('../results.jsx');

describe('Results', function() {
    it('contains table in section', function() {
        var React = require('react/addons');
        var Results = require('../results.jsx');
        var TestUtils = React.addons.TestUtils;
        var data = require("../../../../models/data.js");

        var component = TestUtils.renderIntoDocument(
            <Results data={data.values} />
        );

        var tableSection = TestUtils.findRenderedDOMComponentWithClass(component, 'table-wrapper');
        expect(tableSection.props.children.type).toEqual('table');
    });
});


text:
package java.awt.image;

import gnu.java.awt.Buffers;

import java.util.Arrays;

/* FIXME: This class does not yet support data type TYPE_SHORT */

/**
 * ComponentSampleModel supports a flexible organization of pixel samples in
 * memory, permitting pixel samples to be interleaved by band, by scanline,
 * and by pixel.
 *
 * A DataBuffer for this sample model has K banks of data.  Pixels have N
 * samples, so there are N bands in the DataBuffer.  Each band is completely
 * contained in one bank of data, but a bank may contain more than one band.
 * Each pixel sample is stored in a single data element.
 *
 * Within a bank, each band begins at an offset stored in bandOffsets.  The
 * banks containing the band is given by bankIndices.  Within the bank, there
 * are three dimensions - band, pixel, and scanline.  The dimension ordering
 * is controlled by bandOffset, pixelStride, and scanlineStride, which means
 * that any combination of interleavings is supported.
 *
 * @author Rolf W. Rasmussen (rolfwr@ii.uib.no)
 */
public class ComponentSampleModel extends SampleModel
{
  /** The offsets to the first sample for each band. */
  protected int[] bandOffsets;

  /** The indices of the bank used to store each band in a data buffer. */
  protected int[] bankIndices;

  /**
   * The number of bands in the image.
   * @specnote This field shadows the protected numBands in SampleModel.
   */
  protected int numBands;

  /** Used when creating data buffers. */
  protected int numBanks;

  /**
   * The number of data elements between a sample in one row and the
   * corresponding sample in the next row.
   */
  protected int scanlineStride;

  /**
   * The number of data elements between a sample for one pixel and the
   * corresponding sample for the next pixel in the same row.
   */
  protected int pixelStride;

  private boolean tightPixelPacking = false;

  /**
   * Creates a new sample model that assumes that all bands are stored in a
   * single bank of the {@link DataBuffer}.
   *

   * Note that the bandOffsets array is copied to internal storage
   * to prevent subsequent changes to the array from affecting this object.
   *
   * @param dataType  the data type (one of {@link DataBuffer#TYPE_BYTE},
   *   {@link DataBuffer#TYPE_USHORT}, {@link DataBuffer#TYPE_SHORT},
   *   {@link DataBuffer#TYPE_INT}, {@link DataBuffer#TYPE_FLOAT} or
   *   {@link DataBuffer#TYPE_DOUBLE}).
   * @param w  the width in pixels.
   * @param h  the height in pixels.
   * @param pixelStride  the number of data elements in the step from a sample
   *   in one pixel to the corresponding sample in the next pixel.
   * @param scanlineStride  the number of data elements in the step from a
   *   sample in a pixel to the corresponding sample in the pixel in the next
   *   row.
   * @param bandOffsets  the offset to the first element for each band, with
   *   the size of the array defining the number of bands (null
   *   not permitted).
   *
   * @throws IllegalArgumentException if dataType is not one of
   *   the specified values.
   * @throws IllegalArgumentException if w is less than or equal
   *   to zero.
   * @throws IllegalArgumentException if h is less than or equal
   *   to zero.
   * @throws IllegalArgumentException if w * h exceeds
   *   {@link Integer#MAX_VALUE}.
   * @throws IllegalArgumentException if pixelStride is negative.
   * @throws IllegalArgumentException if scanlineStride is less
   *   than or equal to zero.
   * @throws IllegalArgumentException if bandOffsets has zero
   *   length.
   */
  public ComponentSampleModel(int dataType,
                              int w, int h,
                              int pixelStride,
                              int scanlineStride,
                              int[] bandOffsets)
  {
    this(dataType, w, h, pixelStride, scanlineStride,
         new int[bandOffsets.length], bandOffsets);
  }

  /**
   * Creates a new sample model that assumes that all bands are stored in a
   * single bank of the {@link DataBuffer}.
   *
   * @param dataType  the data type (one of {@link DataBuffer#TYPE_BYTE},
   *   {@link DataBuffer#TYPE_USHORT}, {@link DataBuffer#TYPE_SHORT},
   *   {@link DataBuffer#TYPE_INT}, {@link DataBuffer#TYPE_FLOAT} or
   *   {@link DataBuffer#TYPE_DOUBLE}).
   * @param w  the width in pixels.
   * @param h  the height in pixels.
   * @param pixelStride  the number of data elements in the step from a sample
   *   in one pixel to the corresponding sample in the next pixel.
   * @param scanlineStride  the number of data elements in the step from a
   *   sample in a pixel to the corresponding sample in the pixel in the next
   *   row.
   * @param bankIndices  the index of the bank in which each band is stored
   *   (null not permitted).  This array is copied to internal
   *   storage so that subsequent updates to the array do not affect the sample
   *   model.
   * @param bandOffsets  the offset to the first element for each band, with
   *   the size of the array defining the number of bands (null
   *   not permitted).  This array is copied to internal storage so that
   *   subsequent updates to the array do not affect the sample model.
   *
   * @throws IllegalArgumentException if dataType is not one of
   *   the specified values.
   * @throws IllegalArgumentException if w is less than or equal
   *   to zero.
   * @throws IllegalArgumentException if h is less than or equal
   *   to zero.
   * @throws IllegalArgumentException if w * h exceeds
   *   {@link Integer#MAX_VALUE}.
   * @throws IllegalArgumentException if pixelStride is negative.
   * @throws IllegalArgumentException if scanlineStride is less
   *   than or equal to zero.
   * @throws IllegalArgumentException if bandOffsets has zero
   *   length.
   */
  public ComponentSampleModel(int dataType,
                              int w, int h,
                              int pixelStride,
                              int scanlineStride,
                              int[] bankIndices,
                              int[] bandOffsets)
  {
    super(dataType, w, h, bandOffsets.length);

    // super permits DataBuffer.TYPE_UNDEFINED but this class doesn't...
    if (dataType == DataBuffer.TYPE_UNDEFINED)
      throw new IllegalArgumentException("Unsupported dataType.");

    if ((pixelStride < 0) || (scanlineStride < 0) || (bandOffsets.length < 1)
        || (bandOffsets.length != bankIndices.length))
      throw new IllegalArgumentException();

    this.bandOffsets = (int[]) bandOffsets.clone();
    this.bankIndices = (int[]) bankIndices.clone();
    this.numBands = bandOffsets.length;

    this.numBanks = 0;
    for (int b = 0; b < bankIndices.length; b++)
      this.numBanks = Math.max(this.numBanks, bankIndices[b] + 1);

    this.scanlineStride = scanlineStride;
    this.pixelStride = pixelStride;

    // See if we can use some speedups

    /* FIXME: May these checks should be reserved for the
       PixelInterleavedSampleModel? */

    if (pixelStride == numBands)
      {
        tightPixelPacking = true;
        for (int b = 0; b < numBands; b++) {
          if ((bandOffsets[b] != b) || (bankIndices[b] != 0))
            {
              tightPixelPacking = false;
              break;
            }
        }
      }
  }

  /**
   * Creates a new sample model that is compatible with this one, but with the
   * specified dimensions.
   *
   * @param w  the width (must be greater than zero).
   * @param h  the height (must be greater than zero).
   *
   * @return A new sample model.
   */
  public SampleModel createCompatibleSampleModel(int w, int h)
  {
    return new ComponentSampleModel(dataType, w, h, pixelStride,
                                    scanlineStride, bankIndices,
                                    bandOffsets);
  }

  /**
   * Creates a new sample model that provides access to a subset of the bands
   * that this sample model supports.
   *
   * @param bands  the bands (null not permitted).
   *
   * @return The new sample model.
   */
  public SampleModel createSubsetSampleModel(int[] bands)
  {
    int numBands = bands.length;

    int[] bankIndices = new int[numBands];
    int[] bandOffsets = new int[numBands];
    for (int b = 0; b < numBands; b++)
      {
        bankIndices[b] = this.bankIndices[bands[b]];
        bandOffsets[b] = this.bandOffsets[bands[b]];
      }

    return new ComponentSampleModel(dataType, width, height, pixelStride,
                                    scanlineStride, bankIndices,
                                    bandOffsets);
  }

  /**
   * Creates a new data buffer that is compatible with this sample model.
   *
   * @return The new data buffer.
   */
  public DataBuffer createDataBuffer()
  {
    // Maybe this value should be precalculated in the constructor?
    int highestOffset = 0;
    for (int b = 0; b < numBands; b++)
      highestOffset = Math.max(highestOffset, bandOffsets[b]);
    int size = pixelStride * (width - 1) + scanlineStride * (height - 1)
        + highestOffset + 1;

    return Buffers.createBuffer(getDataType(), size, numBanks);
  }

  /**
   * Returns the offset of the sample in band 0 for the pixel at location
   * (x, y).  This offset can be used to read a sample value from
   * a {@link DataBuffer}.
   *
   * @param x  the x-coordinate.
   * @param y  the y-coordinate.
   *
   * @return The offset.
   *
   * @see #getOffset(int, int, int)
   */
  public int getOffset(int x, int y)
  {
    return getOffset(x, y, 0);
  }

  /**
   * Returns the offset of the sample in band b for the pixel at
   * location (x, y).  This offset can be used to read a sample
   * value from a {@link DataBuffer}.
   *
   * @param x  the x-coordinate.
   * @param y  the y-coordinate.
   * @param b  the band index.
   *
   * @return The offset.
   */
  public int getOffset(int x, int y, int b)
  {
    return bandOffsets[b] + pixelStride * x + scanlineStride * y;
  }

  /**
   * Returns the size in bits for each sample (one per band).  For this sample
   * model, each band has the same sample size and this is determined by the
   * data type for the sample model.
   *
   * @return The sample sizes.
   *
   * @see SampleModel#getDataType()
   */
  public final int[] getSampleSize()
  {
    int size = DataBuffer.getDataTypeSize(getDataType());
    int[] sizes = new int[numBands];

    java.util.Arrays.fill(sizes, size);
    return sizes;
  }

  /**
   * Returns the size in bits for the samples in the specified band.  In this
   * class, the sample size is the same for every band and is determined from
   * the data type for the model.
   *
   * @param band  the band index (ignored here).
   *
   * @return The sample size in bits.
   *
   * @see SampleModel#getDataType()
   */
  public final int getSampleSize(int band)
  {
    return DataBuffer.getDataTypeSize(getDataType());
  }

  /**
   * Returns the indices of the bank(s) in the {@link DataBuffer} used to
   * store the samples for each band.  The returned array is a copy, so that
   * altering it will not impact the sample model.
   *
   * @return The bank indices.
   */
  public final int[] getBankIndices()
  {
    return (int[]) bankIndices.clone();
  }

  /**
   * Returns the offsets to the first sample in each band.  The returned array
   * is a copy, so that altering it will not impact the sample model.
   *
   * @return The offsets.
   */
  public final int[] getBandOffsets()
  {
    return (int[]) bandOffsets.clone();
  }

  /**
   * Returns the distance (in terms of element indices) between the sample for
   * one pixel and the corresponding sample for the equivalent pixel in the
   * next row.  This is used in the calculation of the element offset for
   * retrieving samples from a {@link DataBuffer}.
   *
   * @return The distance between pixel samples in consecutive rows.
   */
  public final int getScanlineStride()
  {
    return scanlineStride;
  }

  /**
   * Returns the distance (in terms of element indices) between the sample for
   * one pixel and the corresponding sample for the next pixel in a row.  This
   * is used in the calculation of the element offset for retrieving samples
   * from a {@link DataBuffer}.
   *
   * @return The distance between pixel samples in the same row.
   */
  public final int getPixelStride()
  {
    return pixelStride;
  }

  /**
   * Returns the number of data elements used to store the samples for one
   * pixel.  In this model, this is the same as the number of bands.
   *
   * @return The number of data elements used to store the samples for one
   *   pixel.
   */
  public final int getNumDataElements()
  {
    return numBands;
  }

  /**
   * Returns the samples for the pixel at location (x, y) in
   * a primitive array (the array type is determined by the data type for
   * this model).  The obj argument provides an option to supply
   * an existing array to hold the result, if this is null a new
   * array will be allocated.
   *
   * @param x  the x-coordinate.
   * @param y  the y-coordinate.
   * @param obj  a primitive array that, if not null, will be
   *   used to store and return the sample values.
   * @param data  the data buffer (null not permitted).
   *
   * @return An array of sample values for the specified pixel.
   */
  public Object getDataElements(int x, int y, Object obj, DataBuffer data)
  {
    int xyOffset = pixelStride * x + scanlineStride * y;

    int[] totalBandDataOffsets = new int[numBands];

    /* Notice that band and bank offsets are different. Band offsets
       are managed by the sample model, and bank offsets are managed
       by the data buffer. Both must be accounted for. */

    /* FIXME: For single pixels, it is probably easier to simple
       call getElem instead of calculating the bank offset ourself.

       On the other hand, then we need to push the value through
       the int type returned by the getElem method.  */

    int[] bankOffsets = data.getOffsets();

    for (int b = 0; b < numBands; b++)
      {
        totalBandDataOffsets[b] = bandOffsets[b] + bankOffsets[bankIndices[b]]
                                  + xyOffset;
      }

    try
      {
        switch (getTransferType())
          {
          case DataBuffer.TYPE_BYTE:
            DataBufferByte inByte = (DataBufferByte) data;
            byte[] outByte = (byte[]) obj;
            if (outByte == null)
              outByte = new byte[numBands];

            for (int b = 0; b < numBands; b++)
              {
                int dOffset = totalBandDataOffsets[b];
                outByte[b] = inByte.getData(bankIndices[b])[dOffset];
              }
            return outByte;

          case DataBuffer.TYPE_USHORT:
            DataBufferUShort inUShort = (DataBufferUShort) data;
            short[] outUShort = (short[]) obj;
            if (outUShort == null)
              outUShort = new short[numBands];

            for (int b = 0; b < numBands; b++)
              {
                int dOffset = totalBandDataOffsets[b];
                outUShort[b] = inUShort.getData(bankIndices[b])[dOffset];
              }
            return outUShort;

          case DataBuffer.TYPE_SHORT:
            DataBufferShort inShort = (DataBufferShort) data;
            short[] outShort = (short[]) obj;
            if (outShort == null)
              outShort = new short[numBands];

            for (int b = 0; b < numBands; b++)
              {
                int dOffset = totalBandDataOffsets[b];
                outShort[b] = inShort.getData(bankIndices[b])[dOffset];
              }
            return outShort;

          case DataBuffer.TYPE_INT:
            DataBufferInt inInt = (DataBufferInt) data;
            int[] outInt = (int[]) obj;
            if (outInt == null)
              outInt = new int[numBands];

            for (int b = 0; b < numBands; b++)
              {
                int dOffset = totalBandDataOffsets[b];
                outInt[b] = inInt.getData(bankIndices[b])[dOffset];
              }
            return outInt;

          case DataBuffer.TYPE_FLOAT:
            DataBufferFloat inFloat = (DataBufferFloat) data;
            float[] outFloat = (float[]) obj;
            if (outFloat == null)
              outFloat = new float[numBands];

            for (int b = 0; b < numBands; b++)
              {
                int dOffset = totalBandDataOffsets[b];
                outFloat[b] = inFloat.getData(bankIndices[b])[dOffset];
              }
            return outFloat;

          case DataBuffer.TYPE_DOUBLE:
            DataBufferDouble inDouble = (DataBufferDouble) data;
            double[] outDouble = (double[]) obj;
            if (outDouble == null)
              outDouble = new double[numBands];

            for (int b = 0; b < numBands; b++)
              {
                int dOffset = totalBandDataOffsets[b];
                outDouble[b] = inDouble.getData(bankIndices[b])[dOffset];
              }
            return outDouble;

          default:
              throw new IllegalStateException("unknown transfer type "
                                              + getTransferType());
          }
      }
    catch (ArrayIndexOutOfBoundsException aioobe)
      {
        String msg = "While reading data elements, " +
          "x=" + x + ", y=" + y +", " + ", xyOffset=" + xyOffset +
          ", data.getSize()=" + data.getSize() + ": " + aioobe;
        throw new ArrayIndexOutOfBoundsException(msg);
      }
  }

  /**
   * Returns the samples for the pixels in the region defined by
   * (x, y, w, h) in a primitive array (the array type is
   * determined by the data type for this model).  The obj
   * argument provides an option to supply an existing array to hold the
   * result, if this is null a new array will be allocated.
   *
   * @param x  the x-coordinate.
   * @param y  the y-coordinate.
   * @param w  the width.
   * @param h  the height.
   * @param obj  a primitive array that, if not null, will be
   *   used to store and return the sample values.
   * @param data  the data buffer (null not permitted).
   *
   * @return An array of sample values for the specified pixels.
   *
   * @see #setDataElements(int, int, int, int, Object, DataBuffer)
   */
  public Object getDataElements(int x, int y, int w, int h, Object obj,
                                DataBuffer data)
  {
    if (!tightPixelPacking)
      {
        return super.getDataElements(x, y, w, h, obj, data);
      }

    // using get speedup

    // We can copy whole rows
    int rowSize = w * numBands;
    int dataSize = rowSize * h;

    DataBuffer transferBuffer = Buffers.createBuffer(getTransferType(), obj,
                                                     dataSize);
    obj = Buffers.getData(transferBuffer);

    int inOffset = pixelStride * x + scanlineStride * y + data.getOffset();
                                           // Assumes only one band is used

    /* We don't add band offsets since we assume that bands have
       offsets 0, 1, 2, ... */

    // See if we can copy everything in one go
    if (scanlineStride == rowSize)
      {
        // Collapse scan lines:
        rowSize *= h;
        // We ignore scanlineStride since it won't be of any use
        h = 1;
      }

    int outOffset = 0;
    Object inArray = Buffers.getData(data);
    for (int yd = 0; yd < h; yd++)
      {
        System.arraycopy(inArray, inOffset, obj, outOffset, rowSize);
        inOffset  += scanlineStride;
        outOffset += rowSize;
      }
    return obj;
  }

  /**
   * Sets the samples for the pixels in the region defined by
   * (x, y, w, h) from a supplied primitive array (the array type
   * must be consistent with the data type for this model).
   *
   * @param x  the x-coordinate.
   * @param y  the y-coordinate.
   * @param w  the width.
   * @param h  the height.
   * @param obj  a primitive array containing the sample values.
   * @param data  the data buffer (null not permitted).
   *
   * @see #getDataElements(int, int, int, int, Object, DataBuffer)
   */
  public void setDataElements(int x, int y, int w, int h,
                              Object obj, DataBuffer data)
  {
    if (!tightPixelPacking)
      {
        super.setDataElements(x, y, w, h, obj, data);
        return;
      }

    // using set speedup, we can copy whole rows
    int rowSize = w * numBands;
    int dataSize = rowSize * h;

    DataBuffer transferBuffer
        = Buffers.createBufferFromData(getTransferType(), obj, dataSize);

    int[] bankOffsets = data.getOffsets();

    int outOffset = pixelStride * x + scanlineStride * y + bankOffsets[0];
                                                // same assumptions as in get...

    // See if we can copy everything in one go
    if (scanlineStride == rowSize)
      {
        // Collapse scan lines:
        rowSize *= h;
        h = 1;
      }

    int inOffset = 0;
    Object outArray = Buffers.getData(data);
    for (int yd = 0; yd < h; yd++)
      {
        System.arraycopy(obj, inOffset, outArray, outOffset, rowSize);
        outOffset += scanlineStride;
        inOffset += rowSize;
      }
  }

  /**
   * Returns all the samples for the pixel at location (x, y)
   * stored in the specified data buffer.
   *
   * @param x  the x-coordinate.
   * @param y  the y-coordinate.
   * @param iArray  an array that will be populated with the sample values and
   *   returned as the result.  The size of this array should be equal to the
   *   number of bands in the model.  If the array is null, a new
   *   array is created.
   * @param data  the data buffer (null not permitted).
   *
   * @return The samples for the specified pixel.
   *
   * @see #setPixel(int, int, int[], DataBuffer)
   */
  public int[] getPixel(int x, int y, int[] iArray, DataBuffer data)
  {
    if (x < 0 || x >= width || y < 0 || y >= height)
      throw new ArrayIndexOutOfBoundsException("Pixel (" + x + ", " + y
                                               + ") is out of bounds.");
    int offset = pixelStride * x + scanlineStride * y;
    if (iArray == null)
      iArray = new int[numBands];
    for (int b = 0; b < numBands; b++)
      {
        iArray[b] = data.getElem(bankIndices[b], offset + bandOffsets[b]);
      }
    return iArray;
  }

  /**
   * Returns the samples for all the pixels in a rectangular region.
   *
   * @param x  the x-coordinate.
   * @param y  the y-coordinate.
   * @param w  the width.
   * @param h  the height.
   * @param iArray  an array that if non-null will be populated
   *   with the sample values and returned as the result.
   * @param data  the data buffer (null not permitted).
   *
   * @return The samples for all the pixels in the rectangle.
   */
  public int[] getPixels(int x, int y, int w, int h, int[] iArray,
                         DataBuffer data)
  {
    int offset = pixelStride * x + scanlineStride * y;
    if (iArray == null)
      iArray = new int[numBands * w * h];
    int outOffset = 0;
    for (y = 0; y < h; y++)
      {
        int lineOffset = offset;
        for (x = 0; x < w; x++)
          {
            for (int b = 0; b < numBands; b++)
              {
                iArray[outOffset++]
                    = data.getElem(bankIndices[b], lineOffset+bandOffsets[b]);
              }
            lineOffset += pixelStride;
          }
        offset += scanlineStride;
      }
    return iArray;
  }

  /**
   * Returns the sample for band b of the pixel at
   * (x, y) that is stored in the specified data buffer.
   *
   * @param x  the x-coordinate.
   * @param y  the y-coordinate.
   * @param b  the band index.
   * @param data  the data buffer (null not permitted).
   *
   * @return The sample value.
   *
   * @throws ArrayIndexOutOfBoundsException if (x, y) is outside
   *     the bounds [0, 0, width, height].
   *
   * @see #setSample(int, int, int, int, DataBuffer)
   */
  public int getSample(int x, int y, int b, DataBuffer data)
  {
    if (x < 0 || x >= width || y < 0 || y >= height)
      throw new ArrayIndexOutOfBoundsException("Sample (" + x + ", " + y
                                               + ") is out of bounds.");
    return data.getElem(bankIndices[b], getOffset(x, y, b));
  }

  /**
   * Sets the samples for the pixel at location (x, y) from the
   * supplied primitive array (the array type must be consistent with the data
   * type for this model).
   *
   * @param x  the x-coordinate.
   * @param y  the y-coordinate.
   * @param obj  a primitive array containing the pixel's sample values.
   * @param data  the data buffer (null not permitted).
   *
   * @see #setDataElements(int, int, Object, DataBuffer)
   */
  public void setDataElements(int x, int y, Object obj, DataBuffer data)
  {
    int offset = pixelStride * x + scanlineStride * y;
    int[] totalBandDataOffsets = new int[numBands];
    int[] bankOffsets = data.getOffsets();
    for (int b = 0; b < numBands; b++)
      totalBandDataOffsets[b] = bandOffsets[b] + bankOffsets[bankIndices[b]]
                                + offset;

    switch (getTransferType())
      {
      case DataBuffer.TYPE_BYTE:
        {
          DataBufferByte out = (DataBufferByte) data;
          byte[] in = (byte[]) obj;

          for (int b = 0; b < numBands; b++)
            out.getData(bankIndices[b])[totalBandDataOffsets[b]] = in[b];

          return;
        }
      case DataBuffer.TYPE_USHORT:
        {
          DataBufferUShort out = (DataBufferUShort) data;
          short[] in = (short[]) obj;

          for (int b = 0; b < numBands; b++)
            out.getData(bankIndices[b])[totalBandDataOffsets[b]] = in[b];

          return;
        }
      case DataBuffer.TYPE_SHORT:
        {
          DataBufferShort out = (DataBufferShort) data;
          short[] in = (short[]) obj;

          for (int b = 0; b < numBands; b++)
            out.getData(bankIndices[b])[totalBandDataOffsets[b]] = in[b];

          return;
        }
      case DataBuffer.TYPE_INT:
        {
          DataBufferInt out = (DataBufferInt) data;
          int[] in = (int[]) obj;

          for (int b = 0; b < numBands; b++)
            out.getData(bankIndices[b])[totalBandDataOffsets[b]] = in[b];

          return;
        }
      case DataBuffer.TYPE_FLOAT:
        {
          DataBufferFloat out = (DataBufferFloat) data;
          float[] in = (float[]) obj;

          for (int b = 0; b < numBands; b++)
            out.getData(bankIndices[b])[totalBandDataOffsets[b]] = in[b];

          return;
        }
      case DataBuffer.TYPE_DOUBLE:
        {
          DataBufferDouble out = (DataBufferDouble) data;
          double[] in = (double[]) obj;

          for (int b = 0; b < numBands; b++)
            out.getData(bankIndices[b])[totalBandDataOffsets[b]] = in[b];

          return;
        }
      default:
        throw new UnsupportedOperationException("transfer type not " +
                                                "implemented");
      }
  }

  /**
   * Sets the sample values for the pixel at location (x, y)
   * stored in the specified data buffer.
   *
   * @param x  the x-coordinate.
   * @param y  the y-coordinate.
   * @param iArray  the pixel sample values (null not permitted).
   * @param data  the data buffer (null not permitted).
   *
   * @see #getPixel(int, int, int[], DataBuffer)
   */
  public void setPixel(int x, int y, int[] iArray, DataBuffer data)
  {
    int offset = pixelStride * x + scanlineStride * y;
    for (int b = 0; b < numBands; b++)
      data.setElem(bankIndices[b], offset + bandOffsets[b], iArray[b]);
  }

  /**
   * Sets the sample value for band b of the pixel at location
   * (x, y) in the specified data buffer.
   *
   * @param x  the x-coordinate.
   * @param y  the y-coordinate.
   * @param b  the band index.
   * @param s  the sample value.
   * @param data  the data buffer (null not permitted).
   *
   * @see #getSample(int, int, int, DataBuffer)
   */
  public void setSample(int x, int y, int b, int s, DataBuffer data)
  {
    data.setElem(bankIndices[b], getOffset(x, y, b), s);
  }

  /**
   * Tests this sample model for equality with an arbitrary object.  Returns
   * true if and only if:
   *

   *
obj is not null;

   *
obj is an instance of ComponentSampleModel;
   *

   *
both models have the same values for the dataType,
   *   width, height, pixelStride,
   *   scanlineStride, bandOffsets and
   *   bankIndices fields.

   *

   *
   * @param obj  the object to test (null permitted).
   *
   * @return true if this sample model is equal to
   *   obj, and false otherwise.
   */
  public boolean equals(Object obj)
  {
    if (obj == null)
      return false;
    if (! (obj instanceof ComponentSampleModel))
      return false;
    ComponentSampleModel that = (ComponentSampleModel) obj;
    if (this.dataType != that.dataType)
      return false;
    if (this.width != that.width)
      return false;
    if (this.height != that.height)
      return false;
    if (this.pixelStride != that.pixelStride)
      return false;
    if (this.scanlineStride != that.scanlineStride)
      return false;
    if (! Arrays.equals(this.bandOffsets, that.bandOffsets))
      return false;
    if (! Arrays.equals(this.bankIndices, that.bankIndices))
      return false;
    // couldn't find any difference, so...
    return true;
  }

  /**
   * Returns a hash code for this sample model.
   *
   * @return The hash code.
   */
  public int hashCode()
  {
    // this computation is based on the method described in Chapter 3
    // of Joshua Bloch's Effective Java...
    int result = 17;
    result = 37 * result + dataType;
    result = 37 * result + width;
    result = 37 * result + height;
    result = 37 * result + pixelStride;
    result = 37 * result + scanlineStride;
    for (int i = 0; i < bandOffsets.length; i++)
      result = 37 * result + bandOffsets[i];
    for (int i = 0; i < bankIndices.length; i++)
      result = 37 * result + bankIndices[i];
    return result;
  }
}


text:
D&D 5 - Carac builder

      <select id="select-race" class="light-blue-text lighten-1">
        <option value="" disabled selected>Sélectionnez votre race</option>
        <template ngFor #race [ngForOf]="races">
          <optgroup *ngIf="race.subraces" [attr.label]="race.label">
            <option *ngFor="#subrace of race.subraces" (click)="selectRace(subrace)" [value]="subrace.racial">{{ subrace.label }} ({{ subrace.bonus }})</option>
          </optgroup>
          <option *ngIf="!race.subraces" (click)="selectRace(race)" [value]="race.racial">{{ race.label }} ({{ race.bonus }})</option>
        </template>
      </select>

Total modificateurs : {{ totalMods }}

          Caractéristiques
          Score
          Modificateur

            {{ line.label }}
            help

                <input class="other-bonus" type="checkbox" [disabled]="(line.bonus === 0) && (othersBonus <= 0)" (change)="chooseBonus(line)">

                Bonus racial

          {{ line.value }}
          {{ line.mod }}

            <button class="btn-floating waves-effect waves-light btn green" (click)="add(line)" [disabled]="(line.score === 15) || (points < cost(line.score, line.score + 1))">add</button>
            <button class="btn-floating waves-effect waves-light btn red" (click)="remove(line)" [disabled]="line.score === 8">remove</button>

Points : {{ points }}


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

namespace Microsoft.Azure.Commands.Network
{
    using Microsoft.Azure.Commands.Network.Models;
    using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
    using Microsoft.Azure.Management.Internal.Resources.Utilities.Models;
    using Microsoft.Azure.Management.Network;
    using Microsoft.WindowsAzure.Commands.Utilities.Common;
    using System.Management.Automation;

    [Cmdlet("Remove", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "PublicIpPrefix", SupportsShouldProcess = true, DefaultParameterSetName = RemoveAzurePublicIpPrefixParameterSetNames.Default), OutputType(typeof(bool))]
    public class RemoveAzurePublicIpPrefixCommand : PublicIpPrefixBaseCmdlet
    {
        [Alias("ResourceName")]
        [Parameter(
            Mandatory = true,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "The resource name.",
            ParameterSetName = RemoveAzurePublicIpPrefixParameterSetNames.RemoveByName)]
        [ResourceNameCompleter("Microsoft.Network/publicIPPrefixes", "ResourceGroupName")]
        [ValidateNotNullOrEmpty]
        public virtual string Name { get; set; }

        [Parameter(
            Mandatory = true,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "The resource group name.",
            ParameterSetName = RemoveAzurePublicIpPrefixParameterSetNames.RemoveByName)]
        [ResourceGroupCompleter]
        [ValidateNotNullOrEmpty]
        public virtual string ResourceGroupName { get; set; }

        [Parameter(
            Mandatory = true,
            ValueFromPipelineByPropertyName = true,
            ParameterSetName = RemoveAzurePublicIpPrefixParameterSetNames.DeleteByResourceId)]
        [ValidateNotNullOrEmpty]
        public virtual string ResourceId { get; set; }

        [Parameter(
            Mandatory = true,
            ValueFromPipeline = true,
            ParameterSetName = RemoveAzurePublicIpPrefixParameterSetNames.DeleteByInputObject)]
        [ValidateNotNull]
        public PSPublicIpPrefix InputObject
        {
            get; set;
        }

        [Parameter(
            Mandatory = false,
            HelpMessage = "Do not ask for confirmation.")]
        public SwitchParameter Force { get; set; }

        [Parameter(Mandatory = false)]
        public SwitchParameter PassThru { get; set; }

        [Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")]
        public SwitchParameter AsJob { get; set; }

        public override void Execute()
        {
            base.Execute();

            if (this.IsParameterBound(c => c.InputObject))
            {
                this.ResourceGroupName = this.InputObject.ResourceGroupName;
                this.Name = this.InputObject.Name;
            }

            if (this.IsParameterBound(c => c.ResourceId))
            {
                var resourceIdentifier = new ResourceIdentifier(this.ResourceId);
                this.ResourceGroupName = resourceIdentifier.ResourceGroupName;
                this.Name = resourceIdentifier.ResourceName;
            }

            ConfirmAction(
                Force.IsPresent,
                string.Format(Microsoft.Azure.Commands.Network.Properties.Resources.RemovingResource, Name),
                Microsoft.Azure.Commands.Network.Properties.Resources.RemoveResourceMessage,
                Name,
                () =>
                {
                    if (this.ShouldProcess(this.Name, $"Deleting PublicIpPrefix {this.Name} in ResourceGroup {this.ResourceGroupName}"))
                    {
                        this.PublicIpPrefixClient.Delete(this.ResourceGroupName, this.Name);
                        if (PassThru)
                        {
                            WriteObject(true);
                        }
                    }
                });
        }
    }

    public static class RemoveAzurePublicIpPrefixParameterSetNames
    {
        public const string RemoveByName = "RemoveByNameParameterSet";
        public const string DeleteByResourceId = "DeleteByResourceIdParameterSet";
        public const string DeleteByInputObject = "DeleteByInputObjectParameterSet";

        // The Default
        public const string Default = RemoveAzurePublicIpPrefixParameterSetNames.RemoveByName;
    }
}


text:
extends: posts.liquid

title:  Custom paths
date:  3 May 2015 07:05:20 +0100
---
# {{ title }}

This asserts that you can have normal and custom file paths side by side.