text:
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
/* dbus-message-private.h header shared between dbus-message.c and dbus-message-util.c
 *
 * Copyright (C) 2005  Red Hat Inc.
 *
 * Licensed under the Academic Free License version 2.1
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */
#ifndef DBUS_MESSAGE_PRIVATE_H
#define DBUS_MESSAGE_PRIVATE_H

#include <dbus/dbus-message.h>
#include <dbus/dbus-message-internal.h>
#include <dbus/dbus-string.h>
#include <dbus/dbus-dataslot.h>
#include <dbus/dbus-marshal-header.h>

DBUS_BEGIN_DECLS

/**
 * @addtogroup DBusMessageInternals
 * @{
 */

/**
 * @typedef DBusMessageLoader
 *
 * The DBusMessageLoader object encapsulates the process of converting
 * a byte stream into a series of DBusMessage. It buffers the incoming
 * bytes as efficiently as possible, and generates a queue of
 * messages. DBusMessageLoader is typically used as part of a
 * DBusTransport implementation. The DBusTransport then hands off
 * the loaded messages to a DBusConnection, making the messages
 * visible to the application.
 *
 * @todo write tests for break-loader that a) randomly delete header
 * fields and b) set string fields to zero-length and other funky
 * values.
 *
 */

/**
 * Implementation details of DBusMessageLoader.
 * All members are private.
 */
struct DBusMessageLoader
{
  int refcount;        /**< Reference count. */

  DBusString data;     /**< Buffered data */

  DBusList *messages;  /**< Complete messages. */

  long max_message_size; /**< Maximum size of a message */
  long max_message_unix_fds; /**< Maximum unix fds in a message */

  DBusValidity corruption_reason; /**< why we were corrupted */

  unsigned int corrupted : 1; /**< We got broken data, and are no longer working */

  unsigned int buffer_outstanding : 1; /**< Someone is using the buffer to read */

#ifdef HAVE_UNIX_FD_PASSING
  unsigned int unix_fds_outstanding : 1; /**< Someone is using the unix fd array to read */

  int *unix_fds; /**< File descriptors that have been read from the transport but not yet been handed to any message. Array will be allocated at first use. */
  unsigned n_unix_fds_allocated; /**< Number of file descriptors this array has space for */
  unsigned n_unix_fds; /**< Number of valid file descriptors in array */
#endif
};

/** How many bits are in the changed_stamp used to validate iterators */
#define CHANGED_STAMP_BITS 21

/**
 * @brief Internals of DBusMessage
 *
 * Object representing a message received from or to be sent to
 * another application. This is an opaque object, all members
 * are private.
 */
struct DBusMessage
{
  DBusAtomic refcount; /**< Reference count */

  DBusHeader header; /**< Header network data and associated cache */

  DBusString body;   /**< Body network data. */

  char byte_order; /**< Message byte order. */

  unsigned int locked : 1; /**< Message being sent, no modifications allowed. */

#ifndef DBUS_DISABLE_CHECKS
  unsigned int in_cache : 1; /**< Has been "freed" since it's in the cache (this is a debug feature) */
#endif

  DBusList *counters;   /**< 0-N DBusCounter used to track message size/unix fds. */
  long size_counter_delta;   /**< Size we incremented the size counters by.   */

  dbus_uint32_t changed_stamp : CHANGED_STAMP_BITS; /**< Incremented when iterators are invalidated. */

  DBusDataSlotList slot_list;   /**< Data stored by allocated integer ID */

#ifndef DBUS_DISABLE_CHECKS
  int generation; /**< _dbus_current_generation when message was created */
#endif

#ifdef HAVE_UNIX_FD_PASSING
  int *unix_fds;
  /**< Unix file descriptors associated with this message. These are
     closed when the message is destroyed, hence make sure to dup()
     them when adding or removing them here. */
  unsigned n_unix_fds; /**< Number of valid fds in the array */
  unsigned n_unix_fds_allocated; /**< Allocated size of the array */

  long unix_fd_counter_delta; /**< Size we incremented the unix fd counter by */
#endif
};

dbus_bool_t _dbus_message_iter_get_args_valist (DBusMessageIter *iter,
                                                DBusError       *error,
                                                int              first_arg_type,
                                                va_list          var_args);

typedef struct DBusInitialFDs DBusInitialFDs;
DBusInitialFDs *_dbus_check_fdleaks_enter (void);
void            _dbus_check_fdleaks_leave (DBusInitialFDs *fds);

/** @} */

DBUS_END_DECLS

#endif /* DBUS_MESSAGE_H */


text:
<?php

namespace Mini;

class Config
{
    private static $instance = NULL;
    private $config = NULL;

    private function __construct(array $config)
    {
        $this->config = $config;
    }

    public static function instance()
    {
        if (NULL == self::$instance)
        {
            throw new \Exception('Set a configuration array via Config::set before retrieving a Config instance.');
        }
        return self::$instance;
    }

    public static function set(array $config)
    {
        if (NULL == self::$instance)
        {
            self::$instance == new self($config);
        }
    }

    public function __get($name)
    {
        if (isset($this->config[$name]))
        {
            return $this->config[$name];
        }
        return NULL;
    }

    public function __isset($name)
    {
        return isset($this->config[$name]);
    }

    public function __toString()
    {
        return print_r($this->config, TRUE);
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { Component, OnInit } from '@angular/core';
import { Validators, FormControl, FormGroup, FormBuilder } from '@angular/forms';
import { MessageService } from 'primeng/components/common/messageservice';
import { SessionService } from './../services/session.service';
import { AccountService } from './../services/account.service';
import { Account } from './../shared/models';

@Component({
    selector: 'app-myinfo-component',
    templateUrl: 'myinfo.component.html'
})

export class MyInfoComponent implements OnInit {
    public myinfo: Account;
    dataform: FormGroup;

    constructor(private messageService: MessageService,
                private sessionService: SessionService,
                private accountService: AccountService,
                private fb: FormBuilder) {
    }

    ngOnInit() {
        this.sessionService.setTitle('Account');
        this.sessionService.getCredentials()
            .subscribe(p => {
                this.accountService.getById(p.uniqueID)
                    .subscribe(account => {
                        this.myinfo = account;
                    });
            }, onerror => this.messageService.add({severity: 'error', summary: '', detail: onerror._body}));

        this.dataform = this.fb.group({
            'firstname': new FormControl('', Validators.required),
            'lastname': new FormControl('', Validators.required),
            'email': new FormControl('', Validators.required),
            'username': new FormControl('', Validators.required),
            'password': new FormControl('', Validators.compose([Validators.required, Validators.minLength(6)]))
        });
    }

    saveClick() {
        this.accountService
            .update(this.myinfo.uniqueID, this.myinfo)
            .subscribe(result => { });
    }
}


text:
[![Build Status](https://travis-ci.org/h5bp/html5boilerplate.com-mobile.svg)](https://travis-ci.org/h5bp/html5boilerplate.com-mobile)
[![devDependency Status](https://david-dm.org/h5bp/html5boilerplate.com-mobile/dev-status.svg)](https://david-dm.org/h5bp/html5boilerplate.com-mobile#info=devDependencies)

The HTML5 Boilerplate website is a simple static site.

* The development code is in the
  [`src`](https://github.com/h5bp/mobileboilerplate.com/tree/master/src)
  directory.
* The build process relies on [Grunt](http://gruntjs.com) (a
  [Node.js](https://nodejs.org) task runner).
* The Grunt configurations can be found in the
  [`Gruntfile.js`](https://github.com/h5bp/mobileboilerplate.com/blob/master/Gruntfile.js)
  file.

## Setup

1. Install [Node.js and npm](http://nodejs.org/download/).
2. [Install Grunt's command line interface (CLI)
   globally](http://gruntjs.com/getting-started#installing-the-cli):
   `npm install -g grunt-cli`.
3. Run `npm install`.

## Development

You should be able to work almost entirely in the
[`src`](https://github.com/h5bp/mobileboilerplate.com/tree/master/src) directory.

While developing run `grunt dev` as this will open the website in your default
browser and automatically update it whenever changes are made to the page or any
of the files contained in the page.

## Build

When you have finished your changes, make sure that the distribution package is
correct by running `grunt test` and then checking the output.

## Deploy

This step is done automatically: the server will
[periodically pull](https://github.com/h5bp/html5boilerplate.com/wiki) from
the `gh-pages` branch, branch that will be updated by Travis CI every time a
commit is pushed to the `master` branch and the tests pass.


text:
/*
* SEGS dbtool v0.5 dated 2019-02-11
* A database creation and management tool.
*/

/*!
 * @addtogroup dbtool Projects/CoX/Utilities/dbtool
 * @{
 */

#include "DBConnection.h"
#include "DatabaseConfig.h"

#include "Components/Settings.h"
#include "Components/Logging.h"

#include <QtCore/QDir>
#include <QtCore/QCoreApplication>
#include <QtCore/QCommandLineParser>

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <memory>

#define ProjectName "SEGS dbtool"
#define VersionNumber "0.5"
#define VersionString ProjectName " v" VersionNumber

enum DBToolCommands
{
    CREATE,
    ADDUSER,
    UPGRADE,
    INFO,
};

void Pause(void)
{
    qInfo() << "\nPress ENTER to continue...";
    std::cin.ignore(100000, '\n');  // Ignore characters until an ENTER (newline) is received.
    return;
}

bool setupConfigs(const QString &config_file, std::vector<DatabaseConfig> &configs)
{
    // Setup config file an database configs
    configs.emplace_back(DatabaseConfig());
    configs.emplace_back(DatabaseConfig());

    if(!configs[0].initialize_from_settings(config_file, "AccountDatabase"))
    {
        qCritical(qPrintable(QString("File \"%1\" not found.").arg(config_file)));
        return false;
    }
    // we've just checked if settings exists, so we can safely assume it does here
    configs[1].initialize_from_settings(config_file, "CharacterDatabase");
    return true;
}

bool createDBConns(std::vector<DatabaseConfig> &configs, std::vector< std::unique_ptr<DBConnection> > &segs_dbs)
{
    for(const auto &cfg : configs)
    {
        qInfo() << "Fetching database configuration from settings.cfg for" << cfg.m_filename;
        segs_dbs.push_back(std::make_unique<DBConnection>(cfg));
        segs_dbs.back()->open();

        if(!segs_dbs.back()->isConnected())
        {
            qWarning() << "Database" << cfg.m_db_name << "does not exist, or is an empty file!";
            if(!cfg.isSqlite()) // can't close a sqlite db that doesn't exist (has no data)
                segs_dbs.back()->close();

            continue;
        }
    }

    return true;
}

void errorHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static char log_buffer[4096]={0};
    static char category_text[256];
    log_buffer[0] = 0;
    category_text[0] = 0;
    if(strcmp(context.category,"default")!=0)
        snprintf(category_text, sizeof(category_text), "[%s]", context.category);

    QByteArray localMsg = msg.toLocal8Bit();

    #ifdef Q_OS_WIN
    const char *colorTable[4] = {"","","",""};
    const char * resetColor="";
    #else
    // assume all other platforms use VT color codes
    const char * colorTable[4] = {"","\033[1;33m","\033[91m","\033[41m"};
    const char * resetColor="\033[0m";
    #endif

    switch (type)
    {
        case QtDebugMsg:
            snprintf(log_buffer, sizeof(log_buffer), "%sDebug   : %s\n", category_text, localMsg.constData());
            break;
        case QtInfoMsg:
            // no prefix or category for informational messages, as these are end-user facing
            snprintf(log_buffer, sizeof(log_buffer), "%s\n", localMsg.constData());
            break;
        case QtWarningMsg:
            snprintf(log_buffer, sizeof(log_buffer), "%s%sWARNING!%s %s\n", category_text, colorTable[1], resetColor, localMsg.constData());
            break;
        case QtCriticalMsg:
            snprintf(log_buffer, sizeof(log_buffer), "%s%sCRITICAL!%s %s (%s:%u, %s)\n", category_text, colorTable[2], resetColor, localMsg.constData(),
                    context.file, context.line, context.function);
            break;
        case QtFatalMsg:
            snprintf(log_buffer, sizeof(log_buffer), "%s%sFATAL!%s %s (%s:%u, %s)\n", category_text, colorTable[3], resetColor, localMsg.constData(),
                    context.file, context.line, context.function);
            abort();
    }

    fprintf(stdout, "%s", log_buffer);
    fflush(stdout);
}

int main(int argc, char **argv)
{
    const QStringList known_commands {"create","adduser","upgrade","info"};
    DBToolResult ret = DBToolResult::SUCCESS;

    qInstallMessageHandler(errorHandler);
    QCoreApplication app(argc,argv);
    QCoreApplication::setOrganizationDomain("segs.dev");
    QCoreApplication::setOrganizationName("SEGS Project");
    QCoreApplication::setApplicationName("segs-dbtool");
    QCoreApplication::setApplicationVersion(VersionNumber);

    QCommandLineParser parser;
    parser.setApplicationDescription("SEGS database management utility");
    parser.addHelpOption();
    parser.addVersionOption();

    parser.addPositionalArgument("command",
                                 QCoreApplication::translate("main", "Command to execute.\ncreate\nadduser\nupgrade"),
                                 "<create|adduser|upgrade|info>");

    // A boolean option with multiple names (e.g. -f, --force)
    QCommandLineOption forceOption(QStringList() << "f" << "force",
        QCoreApplication::translate("main", "Overwrite existing database files. THIS CANNOT BE UNDONE."));
    QCommandLineOption loginOption(QStringList() << "l" << "login",
        QCoreApplication::translate("main", "Provide login for added account"),"login");
    QCommandLineOption passOption(QStringList() << "p" << "pass",
        QCoreApplication::translate("main", "Provide password for added account"),"password");
    QCommandLineOption accessLevelOption(QStringList() << "a" << "access_level",
        QCoreApplication::translate("main", "Provide access_level [1-9] for account"),"access_level","1");
    QCommandLineOption configFileOption(QStringList() << "c" << "config",
        QCoreApplication::translate("main", "Use provided settings file, default = settings.cfg"),
                                        "config", "settings.cfg");
    parser.addOption(forceOption);
    parser.addOption(loginOption);
    parser.addOption(passOption);
    parser.addOption(accessLevelOption);
    parser.addOption(configFileOption);

    parser.process(app);

    // Print out Project Name and Version
    qInfo().noquote() << VersionString << "\n";

    const QStringList positionalArguments = parser.positionalArguments();
    if(positionalArguments.size()<1 || !known_commands.contains(positionalArguments.first()))
    {
        if(positionalArguments.size()>=1)
            qWarning() << "Unknown command" << positionalArguments.first();
        else
            qWarning() << "Please run dbTool with a command argument.";

        parser.showHelp(1);
    }

    qInfo() << "Reading configuration file and checking templates...";
    // Locate and setup database configs
    std::vector<DatabaseConfig> configs;
    if(!setupConfigs(parser.value(configFileOption), configs))
        return int(DBToolResult::SETTINGS_MISSING);

    // Set QT Logging filters after we've initialized settings.cfg with the correct path
    setLoggingFilter();

    // stick all db connections in a vector to iterate over when necessary
    std::vector< std::unique_ptr<DBConnection> > segs_dbs;
    if(!createDBConns(configs, segs_dbs))
        return int(DBToolResult::DB_CONN_FAILED);

    // Handle command argument
    int selected_operation = known_commands.indexOf(positionalArguments.first());
    switch (selected_operation)
    {
        case DBToolCommands::CREATE:
        {
            // Check if database already exists
            qInfo() << "Checking for existing databases OR forced (-f) command...";
            bool forced = parser.isSet(forceOption);
            bool dbs_exist = false;
            for(const auto &db : segs_dbs)
            {
                if(db->isConnected())
                {
                    dbs_exist &= true; // dbs_exists must be true all times
                    qWarning() << "Database" << db->m_config.m_db_name << "already exists.";
                }
            }

            if(forced) // if forced flag was used, display warning
                qWarning() << "Forced flag used '-f'. ALL existing databases will be overwritten.";

            if(!forced && dbs_exist)
            {
                qInfo() << "Run dbtool with -f option to overwrite ALL existing databases. "
                        << "THIS CANNOT BE UNDONE.";
                ret = DBToolResult::NOT_FORCED;
                break;
            }

            // if forced || dbs do not exist: create databases one at a time
            for(const auto &db : segs_dbs)
                ret = db->createDB();

            /*!
             * @brief Replaced default admin user creation with a warning that no admin account was created.
             * @brief Also added text to show them the proper format in which to enter to submit an admin account.
             */
            qInfo() << "\nNO ADMIN USER ACCOUNTS CREATED IN DATABASE!"
                    << "\nUse the following example to add an admin account to the database:"
                    << "\ndbtool adduser -l <username> -p <password> -a 9";

            break;
        }
        case DBToolCommands::ADDUSER:
        {
            if(!parser.isSet(loginOption) || !parser.isSet(passOption))
            {
                qCritical()<< "adduser operation requires login and password";
                return int(DBToolResult::NOT_ENOUGH_PARAMS);
            }
            if(configs[0].isSqlite() && !fileExists(configs[0].m_db_name))
            {
                qCritical() << "Cannot add account, the database does not exist";
                return int(DBToolResult::SQLITE_DB_MISSING);
            }
            ret = segs_dbs[0]->addAccount(parser.value(loginOption),
                                     parser.value(passOption),
                                     parser.value(accessLevelOption).toUInt());
            break;
        }
        case DBToolCommands::UPGRADE:
        {
            for(auto &db : segs_dbs)
                db->runUpgrades();

            break;
        }
        case DBToolCommands::INFO:
        {
            qInfo() << "\nDatabase Information:";
            for(auto &db : segs_dbs)
            {
                qInfo().noquote() << QString("Database: %1").arg(db->getName());
                qInfo().noquote() << QString("    Version: %1").arg(db->getDBVersion());
                qInfo().noquote() << QString("    Driver:  %1").arg(db->m_config.m_driver);
                qInfo().noquote() << QString("    Host:    %1:%2").arg(db->m_config.m_host).arg(db->m_config.m_port);
                qInfo().noquote() << QString("    User:    %1").arg(db->m_config.m_user);
                qInfo().noquote() << QString("    Pass:    %1").arg(db->m_config.m_pass);
            }

            break;
        }
    }

    // close all database connections
    for(auto &db : segs_dbs)
        db->close();

    Pause();
    return int(ret);
}

//! @}


text:
std::string generateString(unsigned int size);

template <typename T> hlcanopen::SdoError getSdoError(const folly::Future<T>& e) {
    try {
        e.value();
    } catch (const hlcanopen::SdoError& e) {
        return e;
    }
    throw std::runtime_error("this future has not a SdoError");
}

template <typename C, class = typename std::enable_if<!std::is_array<C>::value>::type, class = int >
  std::string iterableToString(const C& iterable, std::string separator = " ") {
      std::stringstream ss;

      typename C::const_iterator begin = iterable.begin();
      typename C::const_iterator end = iterable.end();

      for (typename C::const_iterator i = begin; i != end; ++i) {
          if(std::distance(i, end) > 1) {
            ss << *i << separator;
          } else {
            ss << *i;
          }
      }

      return ss.str();
}

void registLoggers();

struct TestFixture {

    TestFixture();
    ~TestFixture();

};


text:
package protocol

import (
	"time"

	"github.com/guregu/null"
)

type Protocol struct {
	Id      int64     `json:"id" sql:"AUTO_INCREMENT"`
	Created time.Time `json:"created"`
	Updated time.Time `json:"updated"`
	Action  string    `json:"action"`
	Data    string    `json:"data"`
	UserId  null.Int  `json:"user_id"`
	ModelId null.Int  `json:"model_id"`
}


text:
package com.beem.project.btf.ui;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.beem.project.btf.R;
import com.beem.project.btf.manager.LoginManager;
import com.beem.project.btf.service.Contact;
import com.beem.project.btf.ui.activity.ChatActivity;
import com.beem.project.btf.ui.activity.ContactInfoActivity;
import com.beem.project.btf.ui.activity.OtherTimeFlyMain;
import com.beem.project.btf.ui.activity.base.ActivityController;
import com.beem.project.btf.utils.BBSUtils;
import com.beem.project.btf.utils.SortedList;
import com.beem.project.btf.utils.SortedList.Equalable;
import com.beem.project.btf.utils.Status;
import com.butterfly.vv.vv.utils.CToast;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

/**
 * An Adapter for the contact list. It displays a list of contact in a particular group. 好友列表适配器
 */
public class ContactListAdapter extends BaseAdapter {
	private final ComparatorContactListByStatusAndName<Contact> mComparator = new ComparatorContactListByStatusAndName<Contact>();
	private Equalable<Contact> equaltor = new Equalable<Contact>() {
		@Override
		public boolean equal(Contact t1, Contact t2) {
			return t1.getJIDParsed().equals(t2.getJIDParsed());
		}
	};
	private List<Contact> mCurrentList;
	private final List<Contact> allContacts = new SortedList<Contact>(
			new LinkedList<Contact>(), mComparator, equaltor);
	private final List<Contact> onlineContacts = new SortedList<Contact>(
			new LinkedList<Contact>(), mComparator, equaltor);
	private final Context context;
	private boolean showOnlineOnly;
	private ContactListType mThisType = ContactListType.FRIEND_ADDED;
	protected ImageLoader imageLoader = ImageLoader.getInstance();
	private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();

	public ContactListAdapter(final Context c) {
		mCurrentList = allContacts;
		context = c;
	}
	public void friendClickHandler(Contact contact) {
		OtherTimeFlyMain.launch(context, contact);
	}
	public void setListType(ContactListType type) {
		mThisType = type;
	}
	@Override
	public int getCount() {
		return mCurrentList.size();
	}
	@Override
	public Object getItem(int position) {
		// contactListAdapter有headView 因此position偏移一位
		return mCurrentList.get(position - 1);
	}
	@Override
	public long getItemId(int position) {
		return position;
	}
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder vh;
		if (convertView == null) {
			LayoutInflater mInflater = LayoutInflater.from(context);
			convertView = mInflater.inflate(R.layout.friendtlistcontact,
					parent, false);
			vh = new ViewHolder();
			vh.profile_tv_agenew = (TextView) convertView
					.findViewById(R.id.profile_tv_agenew);
			vh.head = (ImageView) convertView.findViewById(R.id.avatar);
			vh.userName = (TextView) convertView
					.findViewById(R.id.contactlistpseudo);
			vh.vnote = (TextView) convertView
					.findViewById(R.id.contactlistmsgperso);
			vh.vvzone_wraper = (RelativeLayout) convertView
					.findViewById(R.id.vvzone_wraper);
			vh.list = convertView.findViewById(R.id.list);
			convertView.setTag(vh);
		} else {
			vh = (ViewHolder) convertView.getTag();
		}
		bindView(mCurrentList.get(position), position, vh);
		return convertView;
	}

	private static class ViewHolder {
		public View list;
		public ImageView head;
		public TextView profile_tv_agenew;
		public TextView userName, vnote;
		public RelativeLayout vvzone_wraper;
	}

	/**
	 * Put a contact in the list.
	 * @param c the contact
	 */
	public void put(Contact c) {
		// //LogUtils.i("add contact:" + c.getJid());
		put(c, allContacts);
		if (Status.statusOnline(c.getStatus())) {
			put(c, onlineContacts);
		}
	}
	public void put(List<Contact> contacts) {
		for (Contact c : contacts) {
			put(c);
		}
	}
	/**
	 * Remove a contact from the list.
	 * @param c the contact
	 */
	public void remove(Contact c) {
		allContacts.remove(c);
		onlineContacts.remove(c);
	}
	/**
	 * Clear the contact list.
	 */
	public void clear() {
		allContacts.clear();
		onlineContacts.clear();
	}

	private class ChatListener implements OnClickListener {
		private Contact contact;

		public ChatListener(Contact contact) {
			super();
			this.contact = contact;
		}
		@Override
		public void onClick(View v) {
			if (LoginManager.getInstance().isLogined()) {
				ChatActivity.launch(context, contact);
			} else {
				CToast.showToast(context, R.string.timefly_unlogin, Toast.LENGTH_SHORT);
				ActivityController.getInstance().gotoLogin();
			}
		}
	}

	private class VcardListener implements OnClickListener {
		Contact curContact;

		public VcardListener(Contact curContact) {
			this.curContact = curContact;
		}
		@Override
		public void onClick(View v) {
			ContactInfoActivity.launch(context, curContact);
		}
	}

	private class ZoneListener implements OnClickListener {
		private int mposition;
		Contact curContact;

		public ZoneListener(int position, Contact curContact) {
			// TODO Auto-generated constructor stub
			this.mposition = position;
			this.curContact = curContact;
		}
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			friendClickHandler(curContact);
		}
	}

	private void bindView(Contact curContact, int position, ViewHolder vh) {
		// 设置年龄
		vh.profile_tv_agenew.setText(BBSUtils.getAgeByBithday(curContact
				.getBday()));
		// 根据性别来加图像
		vh.profile_tv_agenew.setSelected(curContact.getSexInt() == 0);
		/* 头像 */
		vh.head.setOnClickListener(new VcardListener(curContact));
		curContact.displayPhoto(vh.head, animateFirstListener);
		/* 用户名 */
		vh.userName.setText(curContact.getSuitableNameMix());
		/* 签名 */
		vh.vnote.setText(curContact.getSignature());
		// 看图片组
		vh.vvzone_wraper.setOnClickListener(new ZoneListener(position,
				curContact));
		vh.list.setOnClickListener(new ChatListener(curContact));
	}

	private static class AnimateFirstDisplayListener extends
			SimpleImageLoadingListener {
		static final List<String> displayedImages = Collections
				.synchronizedList(new LinkedList<String>());

		@Override
		public void onLoadingComplete(String imageUri, View view,
				Bitmap loadedImage) {
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 500);
					displayedImages.add(imageUri);
				}
			}
		}
	}

	/**
	 * Put a contact in a list. Helper method.
	 * @param c the contact
	 * @param list the list
	 */
	private void put(Contact c, List<Contact> list) {
		list.remove(c);
		list.add(c);
	}
	/**
	 * Tell if the list display only online contacts.
	 * @return true if only online contacts are shown
	 */
	public boolean isOnlineOnly() {
		return showOnlineOnly;
	}
	/**
	 * Set the list to display only the online contacts.
	 * @param online true to display only online contacts
	 */
	public void setOnlineOnly(boolean online) {
		if (online != showOnlineOnly) {
			showOnlineOnly = online;
			mCurrentList = showOnlineOnly ? onlineContacts : allContacts;
			notifyDataSetChanged();
		}
	}

	/**
	 * Comparator Contact by status and name.
	 */
	private static class ComparatorContactListByStatusAndName<T> implements
			Comparator<T> {
		/**
		 * Constructor.
		 */
		public ComparatorContactListByStatusAndName() {
		}
		@Override
		public int compare(T c1, T c2) {
			if (((Contact) c1).getStatus() < ((Contact) c2).getStatus()) {
				return 1;
			} else if (((Contact) c1).getStatus() > ((Contact) c2).getStatus()) {
				return -1;
			} else
				return ((Contact) c1).getNickName().compareToIgnoreCase(
						((Contact) c2).getNickName());
		}
	}

	public enum ContactListType {
		FRIEND_ADDED, NEARBY_USER, NEW_FRIEND, STRANGER;
	}
}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import hypothesis.strategies as st
import unittest
import caffe2.python.hypothesis_test_util as hu
from caffe2.python import core
from hypothesis import given

class TestResize(hu.HypothesisTestCase):
    @given(height_scale=st.floats(0.25, 4.0) | st.just(2.0),
           width_scale=st.floats(0.25, 4.0) | st.just(2.0),
           height=st.integers(4, 32),
           width=st.integers(4, 32),
           num_channels=st.integers(1, 4),
           batch_size=st.integers(1, 4),
           seed=st.integers(0, 65535),
           **hu.gcs)
    def test_nearest(self, height_scale, width_scale, height, width,
                     num_channels, batch_size, seed,
                     gc, dc):

        np.random.seed(seed)
        op = core.CreateOperator(
            "ResizeNearest",
            ["X"],
            ["Y"],
            width_scale=width_scale,
            height_scale=height_scale,
        )

        X = np.random.rand(
            batch_size, num_channels, height, width).astype(np.float32)

        def ref(X):
            output_height = np.int32(height * height_scale)
            output_width = np.int32(width * width_scale)

            output_h_idxs, output_w_idxs = np.meshgrid(np.arange(output_height),
                                                       np.arange(output_width),
                                                       indexing='ij')

            input_h_idxs = np.minimum(
                output_h_idxs / height_scale, height - 1).astype(np.int32)
            input_w_idxs = np.minimum(
                output_w_idxs / width_scale, width - 1).astype(np.int32)

            Y = X[:, :, input_h_idxs, input_w_idxs]

            return Y,

        self.assertReferenceChecks(gc, op, [X], ref)
        self.assertDeviceChecks(dc, op, [X], [0])
        self.assertGradientChecks(gc, op, [X], 0, [0], stepsize=0.1, threshold=1e-2)

    @given(height_scale=st.floats(0.25, 4.0) | st.just(2.0),
           width_scale=st.floats(0.25, 4.0) | st.just(2.0),
           height=st.integers(4, 32),
           width=st.integers(4, 32),
           num_channels=st.integers(1, 4),
           batch_size=st.integers(1, 4),
           seed=st.integers(0, 65535),
           **hu.gcs)
    def test_nearest_grad(self, height_scale, width_scale, height, width,
                          num_channels, batch_size, seed, gc, dc):

        np.random.seed(seed)

        output_height = np.int32(height * height_scale)
        output_width = np.int32(width * width_scale)
        X = np.random.rand(batch_size,
                           num_channels,
                           height,
                           width).astype(np.float32)
        dY = np.random.rand(batch_size,
                            num_channels,
                            output_height,
                            output_width).astype(np.float32)

        op = core.CreateOperator(
            "ResizeNearestGradient",
            ["dY", "X"],
            ["dX"],
            width_scale=width_scale,
            height_scale=height_scale,
        )

        def ref(dY, X):
            dX = np.zeros_like(X)

            for i in range(output_height):
                for j in range(output_width):
                    input_i = np.minimum(i / height_scale, height - 1).astype(np.int32)
                    input_j = np.minimum(j / width_scale, width - 1).astype(np.int32)
                    dX[:, :, input_i, input_j] += dY[:, :, i, j]

            return dX,

        self.assertDeviceChecks(dc, op, [dY, X], [0])
        self.assertReferenceChecks(gc, op, [dY, X], ref)

if __name__ == "__main__":
    unittest.main()


text:
<!DOCTYPE animal [
<!ELEMENT animal ANY>
<?_ٟ an only legal per 5th edition extender #x65f in PITarget ?>
]>
<animal/>


text:
package org.apereo.cas.config;

import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.support.oauth.OAuth20GrantTypes;
import org.apereo.cas.support.oauth.OAuth20ResponseTypes;
import org.apereo.cas.support.oauth.services.DefaultRegisteredServiceOAuthAccessTokenExpirationPolicy;
import org.apereo.cas.support.oauth.services.DefaultRegisteredServiceOAuthCodeExpirationPolicy;
import org.apereo.cas.support.oauth.services.DefaultRegisteredServiceOAuthRefreshTokenExpirationPolicy;
import org.apereo.cas.support.oauth.services.OAuthRegisteredService;
import org.apereo.cas.ticket.accesstoken.OAuth20AccessTokenExpirationPolicy;
import org.apereo.cas.ticket.accesstoken.OAuth20DefaultAccessToken;
import org.apereo.cas.ticket.code.OAuth20CodeExpirationPolicy;
import org.apereo.cas.ticket.code.OAuth20DefaultCode;
import org.apereo.cas.ticket.device.OAuth20DefaultDeviceToken;
import org.apereo.cas.ticket.device.OAuth20DefaultDeviceUserCode;
import org.apereo.cas.ticket.refreshtoken.OAuth20DefaultRefreshToken;
import org.apereo.cas.ticket.refreshtoken.OAuth20RefreshTokenExpirationPolicy;
import org.apereo.cas.util.serialization.ComponentSerializationPlanConfigurer;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * This is {@link CasOAuth20ComponentSerializationConfiguration}.
 *
 * @author Misagh Moayyed
 * @since 5.2.0
 */
@Configuration(value = "casOAuth20ComponentSerializationConfiguration", proxyBeanMethods = false)
@EnableConfigurationProperties(CasConfigurationProperties.class)
public class CasOAuth20ComponentSerializationConfiguration {

    @Bean
    @ConditionalOnMissingBean(name = "oauthComponentSerializationPlanConfigurer")
    public ComponentSerializationPlanConfigurer oauthComponentSerializationPlanConfigurer() {
        return plan -> {
            plan.registerSerializableClass(OAuth20AccessTokenExpirationPolicy.class);
            plan.registerSerializableClass(OAuth20RefreshTokenExpirationPolicy.class);
            plan.registerSerializableClass(OAuth20RefreshTokenExpirationPolicy.OAuthRefreshTokenStandaloneExpirationPolicy.class);
            plan.registerSerializableClass(OAuth20CodeExpirationPolicy.class);

            plan.registerSerializableClass(OAuthRegisteredService.class);

            plan.registerSerializableClass(DefaultRegisteredServiceOAuthCodeExpirationPolicy.class);
            plan.registerSerializableClass(DefaultRegisteredServiceOAuthAccessTokenExpirationPolicy.class);
            plan.registerSerializableClass(DefaultRegisteredServiceOAuthRefreshTokenExpirationPolicy.class);

            plan.registerSerializableClass(OAuth20DefaultCode.class);
            plan.registerSerializableClass(OAuth20DefaultAccessToken.class);
            plan.registerSerializableClass(OAuth20DefaultRefreshToken.class);
            plan.registerSerializableClass(OAuth20DefaultDeviceToken.class);
            plan.registerSerializableClass(OAuth20DefaultDeviceUserCode.class);

            plan.registerSerializableClass(OAuth20GrantTypes.class);
            plan.registerSerializableClass(OAuth20ResponseTypes.class);
        };
    }
}


text:
layout: post
title: Make a wish…
categories:
- Musing
---

I jogged alone today again! Where are my fitness partners?? All are busy busy busy. Jogging was so lonely even with the loud music of the mp3 player. When the song stops you can hear yourself breathe so hard…as if you can hear what your heart speaks when there is complete silence. I listened hard…and kept jogging.

The leaves were falling due to strong breeze and I caught a falling leaf! I made a wish…I wished …I wished…and I somehow feel that it'll come true.Make a wish…whenever you can. There are [many ways ](http://www.everything2.com/index.pl?node_id=1128237)as to how u can wish…but the most important thing is to believe.

And I do believe.

![](/img/leaf.jpg)


text:
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { Router, Scene } from 'react-native-router-flux';

import ScarletScreen from './screens/ScarletScreen';
import GrayScreen from './screens/GrayScreen';

const TabIcon = ({ selected, title }) => {
  return (
    <Text style={{color: selected ? 'red' : 'black', backgroundColor: 'whitesmoke'}}>{title}</Text>
  );
}

const App = () => {
  return (
    <Router>
      <Scene key="root">
        {/* Tab Container */}
        <Scene
          key="tabbar"
          tabs={true}
          tabBarStyle={{ backgroundColor: '#FFFFFF' }}
        >
          {/* Tab and it's scenes */}
          <Scene key="osu" title='Home' icon={TabIcon}>
            <Scene
              key="scarlet"
              component={ScarletScreen}
              title="Scarlet"
            />
          </Scene>
          <Scene key="dois" title="Notificações" icon={TabIcon}>
            <Scene
              key="gray"
              component={GrayScreen}
              title="Gray"
            />
          </Scene>
          {/* Removed for brevity */}
        </Scene>
      </Scene>
    </Router>
  );
}

const Styles = {
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
}

export default App;


text:
require 'spec_helper'

describe Travis::API::V3::Services::BetaMigrationRequests::Create, set_app: true do
  let(:user)  { FactoryBot.create(:user, login: 'some_beta_user') }
  let(:auth_headers) { { 'HTTP_AUTHORIZATION' => 'internal some_app:sometoken' } }
  let(:params)  { { user_login: user.login, organizations: valid_org_names } }

  let!(:org1) { FactoryBot.create(:org_v3, name: "org_1", login: "org_1")}
  let!(:org2) { FactoryBot.create(:org_v3, name: "org_2", login: "org_2")}
  let!(:org3) { FactoryBot.create(:org_v3, name: "org_3", login: "org_3")}

  let(:valid_org_names) { [org1.login, org2.login, org3.login]}
  let(:valid_orgs) { [org1, org2, org3]}

  let(:invalid_org) { FactoryBot.create(:org_v3, name: "invalid_org") }

  before do
    Travis.config.applications[:some_app] = { token: 'sometoken', full_access: true }

    valid_orgs.each do |org|
      FactoryBot.create(:membership, role: "admin", organization_id: org.id, user_id: user.id)
    end
  end

  after do
    Travis.config.applications.delete(:some_app)
  end

  describe "authenticated" do
    before do
      post("/v3/beta_migration_requests", params, auth_headers)
    end

    example { expect(last_response.status).to be == 200 }
    example { expect(JSON.load(body).to_s).to include(
      "@type",
      "@representation",
      "id",
      "owner_id",
      "owner_name",
      "owner_type")
    }

    example { expect(JSON.load(body)).to include(
      "@type"           => "beta_migration_request",
      "@representation" => "standard",
      "owner_id"        => user.id,
      "owner_name"      => user.login,
      "owner_type"      => "User")
    }

    context "when user has admin access to orgs they have selected" do
      let(:params)  { { user_login: user.login, organizations: valid_org_names } }

      it "selects all the orgs selected by the user" do
        selected_org_names = Travis::API::V3::Models::BetaMigrationRequest.where(owner_id: user.id).last.organizations.pluck(:login)

        expect(valid_org_names & selected_org_names).to eq valid_org_names
      end
    end

    context "when user does not have admin access to some orgs they have selected" do
      let(:params)  { { user_login: user.login, organizations: valid_org_names + [invalid_org.id] } }

      it "selects only the valid orgs selected by the user" do
        selected_org_names = Travis::API::V3::Models::BetaMigrationRequest.where(owner_id: user.id).last.organizations.pluck(:login)

        expect(valid_org_names & selected_org_names).to eq valid_org_names
      end

      it "does not enable beta for invalid orgs selected by the user" do
        selected_org_names = Travis::API::V3::Models::BetaMigrationRequest.where(owner_id: user.id).last.organizations.pluck(:login)
        expect(selected_org_names).to_not include invalid_org
      end
    end
  end
end


text:
"""
Test of MultiArrayDataSource behavior.
"""

import unittest2 as unittest

from numpy import arange, array, empty, isnan, nan, ones
from numpy.testing import assert_array_equal

from chaco.api import MultiArrayDataSource
from traits.testing.unittest_tools import UnittestTools

class MultiArrayDataTestCase(UnittestTools, unittest.TestCase):

    def setUp(self):
        self.myarray = arange(20).reshape(10, 2)
        self.data_source = MultiArrayDataSource(self.myarray)

    def test_init_defaults(self):
        data_source = MultiArrayDataSource()
        assert_array_equal(data_source._data, empty(shape=(0, 1), dtype=float))
        # XXX this doesn't match AbstractDataSource's interface
        self.assertEqual(data_source.value_dimension, 1)
        self.assertEqual(data_source.sort_order, "ascending")
        self.assertFalse(data_source.is_masked())

    def test_basic_setup(self):
        assert_array_equal(self.myarray, self.data_source._data)
        # XXX this doesn't match AbstractDataSource's interface
        self.assertEqual(self.data_source.index_dimension, 0)
        self.assertEqual(self.data_source.value_dimension, 1)
        self.assertEqual(self.data_source.sort_order, "ascending")
        self.assertFalse(self.data_source.is_masked())

    def test_set_data(self):
        new_array = arange(0, 40, 2).reshape(10, 2)

        with self.assertTraitChanges(self.data_source, 'data_changed', count=1):
            self.data_source.set_data(new_array)

        assert_array_equal(new_array, self.data_source._data)
        self.assertEqual(self.data_source.get_bounds(), (0, 38))
        self.assertEqual(self.data_source.sort_order, "ascending")

    def test_get_data(self):
        assert_array_equal(self.myarray, self.data_source.get_data())

    def test_get_data_axes(self):
        assert_array_equal(arange(0, 20, 2), self.data_source.get_data(axes=0))

    def test_get_data_no_data(self):
        data_source = MultiArrayDataSource()

        assert_array_equal(data_source.get_data(),
                           empty(shape=(0, 1), dtype=float))

    def test_get_data_mask(self):
        data, mask = self.data_source.get_data_mask()
        assert_array_equal(data, self.myarray)
        assert_array_equal(mask, ones(shape=(10, 2), dtype=bool))

    def test_bounds(self):
        # ascending
        bounds = self.data_source.get_bounds()
        self.assertEqual(bounds, (0, 19))

        # descending
        myarray = arange(20)[::-1].reshape(10, 2)
        data_source = MultiArrayDataSource(myarray, sort_order='descending')
        bounds = data_source.get_bounds()
        self.assertEqual(bounds, (0, 19))

        # no order
        myarray = array([[12, 3], [0, 9], [2, 18], [3, 10]])
        data_source = MultiArrayDataSource(myarray, sort_order="none")
        bounds = data_source.get_bounds()
        self.assertEqual(bounds, (0, 18))

    def test_bounds_value(self):
        # ascending
        bounds = self.data_source.get_bounds(value=0)
        self.assertEqual(bounds, (0, 18))

        # descending
        myarray = arange(20)[::-1].reshape(10, 2)
        data_source = MultiArrayDataSource(myarray, sort_order='descending')
        bounds = data_source.get_bounds(value=0)
        self.assertEqual(bounds, (1, 19))

        # no order
        myarray = array([[12, 3], [0, 9], [2, 18], [3, 10]])
        data_source = MultiArrayDataSource(myarray, sort_order="none")
        bounds = data_source.get_bounds(value=0)
        self.assertEqual(bounds, (0, 12))

    def test_bounds_index(self):
        # ascending
        bounds = self.data_source.get_bounds(index=0)
        self.assertEqual(bounds, (0, 1))

        # descending
        myarray = arange(20)[::-1].reshape(10, 2)
        data_source = MultiArrayDataSource(myarray, sort_order='descending')
        bounds = data_source.get_bounds(index=0)
        self.assertEqual(bounds, (18, 19))

        # no order
        myarray = array([[12, 3], [0, 9], [2, 18], [3, 10]])
        data_source = MultiArrayDataSource(myarray, sort_order="none")
        bounds = data_source.get_bounds(index=0)
        self.assertEqual(bounds, (3, 12))

    def test_bounds_empty(self):
        data_source = MultiArrayDataSource()
        bounds = data_source.get_bounds()
        # XXX this is sort of inconsistent with test_bounds_all_nans()
        self.assertEqual(bounds, (0, 0))

    def test_bounds_all_nans(self):
        myarray = empty((10, 2))
        myarray[:, :] = nan
        data_source = MultiArrayDataSource(myarray)
        bounds = data_source.get_bounds()
        self.assertTrue(isnan(bounds[0]))
        self.assertTrue(isnan(bounds[1]))

    def test_metadata(self):
        self.assertEqual(self.data_source.metadata,
                         {'annotations': [], 'selections': []})

    @unittest.skip('change handler missing from class')
    def test_metadata_changed(self):
        with self.assertTraitChanges(self.data_source, 'metadata_changed', count=1):
            self.data_source.metadata = {'new_metadata': True}

    @unittest.skip('change handler missing from class')
    def test_metadata_items_changed(self):
        with self.assertTraitChanges(self.data_source, 'metadata_changed', count=1):
            self.data_source.metadata['new_metadata'] = True


text:
<!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/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>My Project: SimpleMC2.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

My Project

Functions

SimpleMC2.h File Reference

#include <PayOff2.h>

Include dependency graph for SimpleMC2.h:

<map name="SimpleMC2_8h" id="SimpleMC2_8h">
<area shape="rect" id="node2" href="PayOff2_8h.html" title="PayOff2.h" alt="" coords="15,80,97,107"/>
</map>

Go to the source code of this file.

Functions

double 	SimpleMonteCarlo2 (const PayOff &thePayOff, double Expiry, double Spot, double Vol, double r, unsigned long NumberOfPaths)

Function Documentation

§ SimpleMonteCarlo2()

          double SimpleMonteCarlo2
          (
          const PayOff &
          thePayOff,

          double
          Expiry,

          double
          Spot,

          double
          Vol,

          double
          r,

          unsigned long
          NumberOfPaths

          )

<address class="footer">
Generated by

 1.8.12
</address>


text:
package ch.eonum.cryptotrader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ch.eonum.pipeline.classification.Classifier;
import ch.eonum.pipeline.core.SequenceDataSet;
import ch.eonum.pipeline.core.SparseSequence;
import ch.eonum.pipeline.transformation.MinMaxNormalizerSequence;
import ch.eonum.pipeline.util.Log;

/**
 * Get market data, apply it to a trained model and predict prices.
 * @author tim
 *
 */
public class PricePredictor {

	/** Feature transformation and normalization */
	private MinMaxNormalizerSequence<SparseSequence> normalizer;
	/** pre trained sequence regressor. */
	private Classifier<SparseSequence> predictor;
	/** market data. */
	private SparseSequence marketData;

	/**
	 * Constructor.
	 *
	 * @param predictor
	 * 			pre trained sequence regressor.
	 * @param normalizer
	 */
	public PricePredictor(Classifier<SparseSequence> predictor,
			MinMaxNormalizerSequence<SparseSequence> normalizer) {
		this.normalizer = normalizer;
		this.predictor = predictor;
		SequenceDataSet<SparseSequence> dataSet = new SequenceDataSet<SparseSequence>();
		this.marketData = new SparseSequence("", "", new HashMap<String, Double>());
		this.marketData.initGroundTruthSequence();
		this.marketData.initSequenceResults();
		dataSet.add(marketData);
		this.predictor.setTestSet(dataSet);
	}

	/**
	 * Get the next prediction.
	 * @param marketData
	 * @return
	 */
	public double nextPrediction(Map<String, Double> marketDataNextPoint) {
		this.normalizer.normSingleTimePoint(marketDataNextPoint);
		this.marketData.addTimePoint(marketDataNextPoint);
		List<Double> gt = new ArrayList<Double>();
		gt.add(0.);
		this.marketData.addGroundTruth(gt);
		if(this.marketData.getSequenceLength() > CryptsyMarketDataReader.SEQUENCE_LENGTH)
			this.marketData.removeSequenceElementAt(0);

		Log.puts(this.marketData);
		this.predictor.test();
		return this.marketData.resultAt(this.marketData.getSequenceLength() - 1, 0);
	}

}


text:
import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';

import PanelGroup from './PanelGroup';

var Accordion = function (_React$Component) {
  _inherits(Accordion, _React$Component);

  function Accordion() {
    _classCallCheck(this, Accordion);

    return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
  }

  Accordion.prototype.render = function render() {
    return React.createElement(
      PanelGroup,
      _extends({}, this.props, { accordion: true }),
      this.props.children
    );
  };

  return Accordion;
}(React.Component);

export default Accordion;


text:
@import url(http://fonts.googleapis.com/css?family=Lato:300,400,700);
@font-face {
	font-weight: normal;
	font-style: normal;
	font-family: 'codropsicons';
	src:url('fonts/codropsicons/codropsicons.eot');
	src:url('fonts/codropsicons/codropsicons.eot?#iefix') format('embedded-opentype'),
		url('fonts/codropsicons/codropsicons.woff') format('woff'),
		url('fonts/codropsicons/codropsicons.ttf') format('truetype'),
		url('fonts/codropsicons/codropsicons.svg#codropsicons') format('svg');
}

body {
	color: #fff;
	font-family: 'Lato', Arial, sans-serif;
}

a,
a:focus {
	outline: none;
}

.codrops-header {
	position: relative;
	margin: 0 auto;
	max-width: 60%;
	text-align: center;
}

.codrops-header a {
	outline: none;
	color: #fff;
	text-decoration: none;
	opacity: 0.7;
}

.codrops-header a:hover,
.codrops-header a:focus {
	opacity: 1;
}

.codrops-header h1 {
	margin: 0;
	font-weight: 300;
	font-size: 2.625em;
	line-height: 1.3;
}

.codrops-header h1 span {
	display: block;
	padding: 0.4em 1em 1em;
	font-size: 60%;
}

.codrops-links {
	margin: 0;
}

.codrops-links a {
	display: inline-block;
	margin: 0 0.6em;
	text-transform: uppercase;
	letter-spacing: 1px;
	font-size: 75%;
}

.codrops-icon:before {
	margin: 0 4px;
	text-transform: none;
	font-weight: normal;
	font-style: normal;
	font-variant: normal;
	font-family: 'codropsicons';
	line-height: 1;
	speak: none;
	-webkit-font-smoothing: antialiased;
}

.codrops-icon-drop:before {
	content: "\e001";
}

.codrops-icon-prev:before {
	content: "\e004";
}


text:
@class DBRoute;

NS_ASSUME_NONNULL_BEGIN

///
/// Stone route objects for the Check namespace. Each route in the Check
/// namespace has its own static object, which contains information about the
/// route.
///
@interface DBCHECKRouteObjects : NSObject

/// Accessor method for the app route object.
+ (DBRoute *)DBCHECKApp;

/// Accessor method for the user route object.
+ (DBRoute *)DBCHECKUser;

@end

NS_ASSUME_NONNULL_END


text:
#ifndef __NET_FIB_RULES_H
#define __NET_FIB_RULES_H

#include <linux/types.h>
#include <linux/slab.h>
#include <linux/netdevice.h>
#include <linux/fib_rules.h>
#include <net/flow.h>
#include <net/rtnetlink.h>

struct fib_rule {
	struct list_head	list;
	atomic_t		refcnt;
	int			iifindex;
	int			oifindex;
	u32			mark;
	u32			mark_mask;
	u32			pref;
	u32			flags;
	u32			table;
	u8			action;
	u32			target;
	struct fib_rule __rcu	*ctarget;
	char			iifname[IFNAMSIZ];
	char			oifname[IFNAMSIZ];
	struct rcu_head		rcu;
	struct net *		fr_net;
};

struct fib_lookup_arg {
	void			*lookup_ptr;
	void			*result;
	struct fib_rule		*rule;
	int			flags;
#define FIB_LOOKUP_NOREF	1
};

struct fib_rules_ops {
	int			family;
	struct list_head	list;
	int			rule_size;
	int			addr_size;
	int			unresolved_rules;
	int			nr_goto_rules;

	int			(*action)(struct fib_rule *,
					  struct flowi *, int,
					  struct fib_lookup_arg *);
	int			(*match)(struct fib_rule *,
					 struct flowi *, int);
	int			(*configure)(struct fib_rule *,
					     struct sk_buff *,
					     struct fib_rule_hdr *,
					     struct nlattr **);
	int			(*compare)(struct fib_rule *,
					   struct fib_rule_hdr *,
					   struct nlattr **);
	int			(*fill)(struct fib_rule *, struct sk_buff *,
					struct fib_rule_hdr *);
	u32			(*default_pref)(struct fib_rules_ops *ops);
	size_t			(*nlmsg_payload)(struct fib_rule *);

	/* Called after modifications to the rules set, must flush
	 * the route cache if one exists. */
	void			(*flush_cache)(struct fib_rules_ops *ops);

	int			nlgroup;
	const struct nla_policy	*policy;
	struct list_head	rules_list;
	struct module		*owner;
	struct net		*fro_net;
	struct rcu_head		rcu;
};

#define FRA_GENERIC_POLICY \
	[FRA_IIFNAME]	= { .type = NLA_STRING, .len = IFNAMSIZ - 1 }, \
	[FRA_OIFNAME]	= { .type = NLA_STRING, .len = IFNAMSIZ - 1 }, \
	[FRA_PRIORITY]	= { .type = NLA_U32 }, \
	[FRA_FWMARK]	= { .type = NLA_U32 }, \
	[FRA_FWMASK]	= { .type = NLA_U32 }, \
	[FRA_TABLE]     = { .type = NLA_U32 }, \
	[FRA_GOTO]	= { .type = NLA_U32 }

static inline void fib_rule_get(struct fib_rule *rule)
{
	atomic_inc(&rule->refcnt);
}

static inline void fib_rule_put_rcu(struct rcu_head *head)
{
	struct fib_rule *rule = container_of(head, struct fib_rule, rcu);
	release_net(rule->fr_net);
	kfree(rule);
}

static inline void fib_rule_put(struct fib_rule *rule)
{
	if (atomic_dec_and_test(&rule->refcnt))
		call_rcu(&rule->rcu, fib_rule_put_rcu);
}

static inline u32 frh_get_table(struct fib_rule_hdr *frh, struct nlattr **nla)
{
	if (nla[FRA_TABLE])
		return nla_get_u32(nla[FRA_TABLE]);
	return frh->table;
}

extern struct fib_rules_ops *fib_rules_register(const struct fib_rules_ops *, struct net *);
extern void fib_rules_unregister(struct fib_rules_ops *);

extern int			fib_rules_lookup(struct fib_rules_ops *,
						 struct flowi *, int flags,
						 struct fib_lookup_arg *);
extern int			fib_default_rule_add(struct fib_rules_ops *,
						     u32 pref, u32 table,
						     u32 flags);
extern u32			fib_default_rule_pref(struct fib_rules_ops *ops);
#endif


text:
function [param, names] = gpDynamicsExtractParam(model, dim)

% GPDYNAMICSEXTRACTPARAM Extract parameters from the GP dynamics model.
% FORMAT
% DESC extracts the model parameters from a structure containing
% the information about a Gaussian process dynamics model.
% ARG model : the model structure containing the information about
% the model.
% RETURN params : a vector of parameters from the model.
%
% FORMAT
% DESC does the same as above, but also returns parameter names.
% ARG model : the model structure containing the information about
% the model.
% RETURN params : a vector of parameters from the model.
% RETURN names : cell array of parameter names.
%
% SEEALSO : gpExtractParam, gpDynamicsCreate, gpDynamicsExpandParam, modelExtractParam
%
% COPYRIGHT : Neil D. Lawrence, 2006, 2009
%
% MODIFICATIONS : Carl Henrik Ek, 2007

% GPMAT

if nargout > 1
  returnNames = true;
else
  returnNames = false;
end

if returnNames
  [param, names] = gpExtractParam(model);
else
  param = gpExtractParam(model);
end

if ~model.learn
  % If we aren't learning model parameters extract only X_u;
  if ~model.learnScales
    if isfield(model, 'fixInducing') & model.fixInducing
      param = [];
      names = {};
    else
      ind = 1:model.k*model.q;
      param = param(ind);
      if returnNames
        names = names(ind);
      end
    end
  else
    % Learning scales, but not parameters.
    switch model.approx
     case 'ftc'
      param =  param(end-model.d + 1:end);
      if returnNames
        names = names(end-model.d + 1:end);
      end
     case {'dtc', 'dtcvar', 'fitc', 'pitc'}
      if isfield(model, 'fixInducing') & model.fixInducing
        param = param(end-model.d:end-1);
        if returnNames
          names = names(end-model.d:end-1);
        end
      else
        param =  [param(1:model.k*model.q) param(end-model.d:end-1)];
        if returnNames
          names = names([1:model.k*model.q end-model.d:end-1]);
        end
      end
    end
  end
end


text:
function sanitize(html, options) {
  return new Element("div").update(html).sanitizeContents(options).innerHTML.toLowerCase();
}

new Test.Unit.Runner({
  testSanitize: function() {
    var runner = this;

    runner.assertEqual(
      "hello",
      sanitize("hello", {})
    );

    runner.assertEqual(
      "hello",
      sanitize("hello", {})
    );

    runner.assertEqual(
      "hello",
      sanitize("hello", {})
    );

    runner.assertEqual(
      "hello",
      sanitize("hello", {allow: "strong"})
    );

    runner.assertEqual(
      "hello",
      sanitize("hello", {allow: "strong"})
    );

    runner.assertEqual(
      "hello",
      sanitize("hello", {allow: "strong"})
    );

    runner.assertEqual(
      "hello world!",
      sanitize("
hello world!
", {allow: "strong"})
    );

    runner.assertEqual(
      "hello",
      sanitize("hello", {allow: "em, strong"})
    );

    runner.assertEqual(
      "google",
      sanitize("google", {allow: "a"})
    );

    runner.assertEqual(
      "google",
      sanitize("google", {allow: "a[href]"})
    );

    if (Prototype.Browser.IE) {
      runner.assertEqual(
        "hello ",
        sanitize("hello ", {allow: "span[id]"})
      );
    } else {
      runner.assertEqual(
        "hello ",
        sanitize("hello ", {allow: "span[id]"})
      );
    }

    runner.assertEqual(
      "",
      sanitize("", {allow: "img[src], a[href]"})
    );

    if (Prototype.Browser.Gecko) {
      var element;

      element = new Element("div").update('dirty formatting.
').sanitizeContents({skip: "[_moz_dirty]"});
      runner.assertEqual(
        'dirty formatting.
',
        element.innerHTML
      );
      // _moz_dirty flag doesn't show up in innerHTML
      runner.assert(element.children[0].hasAttribute('_moz_dirty'));

      element = new Element("div").update('clean and dirty').sanitizeContents({skip: "[_moz_dirty]"})
      runner.assertEqual(
        'clean and dirty',
        element.innerHTML
      );
      // _moz_dirty flag doesn't show up in innerHTML
      runner.assert(element.children[0].hasAttribute('_moz_dirty'));
    }
  }
});


text:
'use strict'

const env = require('process').env

function currentEnv () {
  return env.BABEL_ENV || env.NODE_ENV || 'development'
}
module.exports = currentEnv


text:
package org.apache.hadoop.hbase.client;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.UUID;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.hadoop.hbase.io.TimeRange;
import org.apache.hadoop.hbase.security.access.Permission;
import org.apache.hadoop.hbase.security.visibility.CellVisibility;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.ClassSize;

/**
 * Used to perform Increment operations on a single row.
 *

 * This operation ensures atomicity to readers. Increments are done
 * under a single row lock, so write operations to a row are synchronized, and
 * readers are guaranteed to see this operation fully completed.
 *

 * To increment columns of a row, instantiate an Increment object with the row
 * to increment.  At least one column to increment must be specified using the
 * {@link #addColumn(byte[], byte[], long)} method.
 */
@InterfaceAudience.Public
public class Increment extends Mutation implements Comparable<Row> {
  private static final long HEAP_OVERHEAD =  ClassSize.REFERENCE + ClassSize.TIMERANGE;
  private TimeRange tr = new TimeRange();

  /**
   * Create a Increment operation for the specified row.
   *

   * At least one column must be incremented.
   * @param row row key (we will make a copy of this).
   */
  public Increment(byte [] row) {
    this(row, 0, row.length);
  }

  /**
   * Create a Increment operation for the specified row.
   *

   * At least one column must be incremented.
   * @param row row key (we will make a copy of this).
   */
  public Increment(final byte [] row, final int offset, final int length) {
    checkRow(row, offset, length);
    this.row = Bytes.copy(row, offset, length);
  }
  /**
   * Copy constructor
   * @param i
   */
  public Increment(Increment i) {
    this.row = i.getRow();
    this.ts = i.getTimeStamp();
    this.tr = i.getTimeRange();
    this.familyMap.putAll(i.getFamilyCellMap());
    for (Map.Entry<String, byte[]> entry : i.getAttributesMap().entrySet()) {
      this.setAttribute(entry.getKey(), entry.getValue());
    }
    super.setPriority(i.getPriority());
  }

  /**
   * Add the specified KeyValue to this operation.
   * @param cell individual Cell
   * @return this
   * @throws java.io.IOException e
   */
  public Increment add(Cell cell) throws IOException{
    byte [] family = CellUtil.cloneFamily(cell);
    List<Cell> list = getCellList(family);
    //Checking that the row of the kv is the same as the put
    if (!CellUtil.matchingRows(cell, this.row)) {
      throw new WrongRowIOException("The row in " + cell +
        " doesn't match the original one " +  Bytes.toStringBinary(this.row));
    }
    list.add(cell);
    return this;
  }

  /**
   * Increment the column from the specific family with the specified qualifier
   * by the specified amount.
   *

   * Overrides previous calls to addColumn for this family and qualifier.
   * @param family family name
   * @param qualifier column qualifier
   * @param amount amount to increment by
   * @return the Increment object
   */
  public Increment addColumn(byte [] family, byte [] qualifier, long amount) {
    if (family == null) {
      throw new IllegalArgumentException("family cannot be null");
    }
    List<Cell> list = getCellList(family);
    KeyValue kv = createPutKeyValue(family, qualifier, ts, Bytes.toBytes(amount));
    list.add(kv);
    return this;
  }

  /**
   * Gets the TimeRange used for this increment.
   * @return TimeRange
   */
  public TimeRange getTimeRange() {
    return this.tr;
  }

  /**
   * Sets the TimeRange to be used on the Get for this increment.
   *

   * This is useful for when you have counters that only last for specific
   * periods of time (ie. counters that are partitioned by time).  By setting
   * the range of valid times for this increment, you can potentially gain
   * some performance with a more optimal Get operation.
   *

   * This range is used as [minStamp, maxStamp).
   * @param minStamp minimum timestamp value, inclusive
   * @param maxStamp maximum timestamp value, exclusive
   * @throws IOException if invalid time range
   * @return this
   */
  public Increment setTimeRange(long minStamp, long maxStamp)
  throws IOException {
    tr = new TimeRange(minStamp, maxStamp);
    return this;
  }

  /**
   * @param returnResults True (default) if the increment operation should return the results. A
   *          client that is not interested in the result can save network bandwidth setting this
   *          to false.
   */
  public Increment setReturnResults(boolean returnResults) {
    super.setReturnResults(returnResults);
    return this;
  }

  /**
   * @return current setting for returnResults
   */
  // This method makes public the superclasses's protected method.
  public boolean isReturnResults() {
    return super.isReturnResults();
  }

  /**
   * Method for retrieving the number of families to increment from
   * @return number of families
   */
  @Override
  public int numFamilies() {
    return this.familyMap.size();
  }

  /**
   * Method for checking if any families have been inserted into this Increment
   * @return true if familyMap is non empty false otherwise
   */
  public boolean hasFamilies() {
    return !this.familyMap.isEmpty();
  }

  /**
   * Before 0.95, when you called Increment#getFamilyMap(), you got back
   * a map of families to a list of Longs.  Now, {@link #getFamilyCellMap()} returns
   * families by list of Cells.  This method has been added so you can have the
   * old behavior.
   * @return Map of families to a Map of qualifiers and their Long increments.
   * @since 0.95.0
   */
  public Map<byte[], NavigableMap<byte [], Long>> getFamilyMapOfLongs() {
    NavigableMap<byte[], List<Cell>> map = super.getFamilyCellMap();
    Map<byte [], NavigableMap<byte[], Long>> results = new TreeMap<>(Bytes.BYTES_COMPARATOR);
    for (Map.Entry<byte [], List<Cell>> entry: map.entrySet()) {
      NavigableMap<byte [], Long> longs = new TreeMap<>(Bytes.BYTES_COMPARATOR);
      for (Cell cell: entry.getValue()) {
        longs.put(CellUtil.cloneQualifier(cell),
            Bytes.toLong(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
      }
      results.put(entry.getKey(), longs);
    }
    return results;
  }

  /**
   * @return String
   */
  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("row=");
    sb.append(Bytes.toStringBinary(this.row));
    if(this.familyMap.isEmpty()) {
      sb.append(", no columns set to be incremented");
      return sb.toString();
    }
    sb.append(", families=");
    boolean moreThanOne = false;
    for(Map.Entry<byte [], List<Cell>> entry: this.familyMap.entrySet()) {
      if(moreThanOne) {
        sb.append("), ");
      } else {
        moreThanOne = true;
        sb.append("{");
      }
      sb.append("(family=");
      sb.append(Bytes.toString(entry.getKey()));
      sb.append(", columns=");
      if(entry.getValue() == null) {
        sb.append("NONE");
      } else {
        sb.append("{");
        boolean moreThanOneB = false;
        for(Cell cell : entry.getValue()) {
          if(moreThanOneB) {
            sb.append(", ");
          } else {
            moreThanOneB = true;
          }
          sb.append(CellUtil.getCellKeyAsString(cell) + "+=" +
              Bytes.toLong(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
        }
        sb.append("}");
      }
    }
    sb.append("}");
    return sb.toString();
  }

  @Override
  public int compareTo(Row i) {
    // TODO: This is wrong.  Can't have two the same just because on same row.
    return Bytes.compareTo(this.getRow(), i.getRow());
  }

  @Override
  public int hashCode() {
    // TODO: This is wrong.  Can't have two gets the same just because on same row.  But it
    // matches how equals works currently and gets rid of the findbugs warning.
    return Bytes.hashCode(this.getRow());
  }

  @Override
  public boolean equals(Object obj) {
    // TODO: This is wrong.  Can't have two the same just because on same row.
    if (this == obj) {
      return true;
    }
    if (obj == null || getClass() != obj.getClass()) {
      return false;
    }
    Row other = (Row) obj;
    return compareTo(other) == 0;
  }

  @Override
  protected long extraHeapSize(){
    return HEAP_OVERHEAD;
  }

  @Override
  public Increment setAttribute(String name, byte[] value) {
    return (Increment) super.setAttribute(name, value);
  }

  @Override
  public Increment setId(String id) {
    return (Increment) super.setId(id);
  }

  @Override
  public Increment setDurability(Durability d) {
    return (Increment) super.setDurability(d);
  }

  @Override
  public Increment setFamilyCellMap(NavigableMap<byte[], List<Cell>> map) {
    return (Increment) super.setFamilyCellMap(map);
  }

  @Override
  public Increment setClusterIds(List<UUID> clusterIds) {
    return (Increment) super.setClusterIds(clusterIds);
  }

  @Override
  public Increment setCellVisibility(CellVisibility expression) {
    return (Increment) super.setCellVisibility(expression);
  }

  @Override
  public Increment setACL(String user, Permission perms) {
    return (Increment) super.setACL(user, perms);
  }

  @Override
  public Increment setACL(Map<String, Permission> perms) {
    return (Increment) super.setACL(perms);
  }

  @Override
  public Increment setTTL(long ttl) {
    return (Increment) super.setTTL(ttl);
  }

  @Override
  public Increment setPriority(int priority) {
    return (Increment) super.setPriority(priority);
  }
}


text:
var svg = d3.select("svg")
            .call(d3.zoom().scaleExtent([0.01, 8]).on("zoom", function () {
                  svg.attr("transform", d3.event.transform)
            }))
            .append("g");

var links = [],
    props,
    norm,
    p1 = 0,
    p2 = 0,
    MULTIPLIER = 50,
    forceName,
    distanceFunction,
    simulation,
    velocities,
    rendering = true; // Rendering during the execution.

// Create a color scheme for a range of numbers.
var color = d3.scaleOrdinal(d3.schemeCategory10);

/**
 * Parse the data from the provided csv file using Papa Parse library
 * @param  {file} evt - csv file.
 */
function parseFile(evt) {
  // Clear the previous nodes
  d3.selectAll(".nodes").remove();

  Papa.parse(evt.target.files[0], {
    header: true,
    dynamicTyping: true,
    skipEmptyLines: true,
    complete: function(results) {
      processData(results.data, results.error);
    }
  });
}

/**
 * Process the data and pass it into D3 force simulation.
 * @param  {array} nodes
 * @param  {object} error
 */
function processData(nodes, error) {
  if (error) throw error.message;

  forceName = "";
  velocities = [];

  // Get the width and heigh of the SVG element.
  var width = +document.getElementById('svg').clientWidth,
      height = +document.getElementById('svg').clientHeight;

  // Number of iterations before stopping.
  n = 300;

  // Start by placing the nodes at the center (its starting positions).
  simulation = d3.forceSimulation()
    .alphaDecay(1 - Math.pow(0.001, 1 / n))
    .force("center", d3.forceCenter(width/2, height/2));

  console.log("n =", nodes.length);
  // Calculate normalization arguments and get the list of
  // properties of the nodes.
  norm = calculateNormalization(nodes);
  props = Object.keys(nodes[0]);

  // Add the nodes to DOM.
  var node = svg.append("g")
      .attr("class", "nodes")
        .selectAll("circle")
        .data(nodes)
        .enter().append("circle")
          .attr("r", 10)
            // Color code the data points by a property (for Poker Hands,
            // it is a CLASS property).
           .attr("fill", function(d) { return color(d.CLASS)});

  // Pass the nodes to the D3 force simulation.
  simulation
      .nodes(nodes)
      .on("tick", ticked);

  function ticked() {
    // If rendering is selected, then draw at every iteration.
    if (rendering === true) {
      node
        .attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });
    }

    // Only do the stress and performance calculations at the end of execution.
    if (simulation.alpha() < simulation.alphaMin()  && p2 === 0 && p1 > 0) {
      // If rendering is not selected, then draw at at the end.
      if (rendering !== true) {
        node
          .attr("cx", function(d) { return d.x; })
          .attr("cy", function(d) { return d.y; });
      }

      // Performance time measurement
      p2 = performance.now();
      console.log("Execution time: " + (p2-p1));
      // Do not calculate stress for data sets bigger than 100 000.
      if (nodes.length <= 100000) {
        console.log("Stress: ", simulation.force(forceName).stress());
      }
      p1 = 0;
      p2 = 0;
    }
  }

};

/**
 * Initialize the Chalmers' 1996 algorithm and start simulation.
 */
function startNeighbourSamplingSimulation() {
  p1 = performance.now();
  forceName = "neighbourSampling";

  simulation
      .force(forceName, d3.forceNeighbourSampling()
        // Set the parameters for the algorithm (optional).
        .neighbourSize(6)
        .sampleSize(3)
        // The distance function that will be used to calculate distances
        //  between nodes.
        .distance(function(s, t) { return distanceFunction(s, t, props, norm)*MULTIPLIER; }));
  // Restart the simulation.
  simulation.alpha(1).restart();
}

/**
 * Initialize the t-SNE algorithm and start simulation.
 */
function starttSNE() {
  p1 = performance.now();
  forceName = "t-SNE";

  simulation
      .force(forceName, d3.tSNE()
        // Set the parameter for the algorithm (optional).
        .perplexity(30)
        // The distance function that will be used to calculate distances
        //  between nodes.
        .distance(function(s, t) { return distanceFunction(s, t, props, norm)*MULTIPLIER; }));
  // Restart the simulation.
  simulation.alpha(1).restart();
}

/**
 * Initialize the Barnes-Hut algorithm and start simulation.
 */
function startBarnesHutSimulation() {
  p1 = performance.now();
  forceName = "barnesHut";

  simulation
      .force(forceName, d3.forceBarnesHut()
        // The distance function that will be used to calculate distances
        //  between nodes.
        .distance(function(s, t) { return distanceFunction(s, t, props, norm)*MULTIPLIER; }));
  // Restart the simulation.
  simulation.alpha(1).restart();
}

/**
 * Initialize the link force algorithm and start simulation.
 */
function startLinkSimulation() {
  p1 = performance.now();

  // Initialize link array.
  nodes = simulation.nodes();
  for (i=0; i < nodes.length; i++) {
    for (j=0; j < nodes.length; j++) {
      if (i !== j) {
        links.push({
          source: nodes[i],
          target: nodes[j],
        });
      }
    }
  }

  forceName = "link";
  // Add the links to the simulation.
  simulation.force(forceName, d3.forceLink().links(links));

  simulation.force(forceName)
      // The distance function that will be used to calculate distances
      //  between nodes.
      .distance(function(n) { return distanceFunction(n.source, n.target, props, norm)*MULTIPLIER; })
      // Set the parameter for the algorithm (optional).
      .strength(1);
  // Restart the simulation.
  simulation.alpha(1).restart();
}

/**
 * Halt the execution.
 */
function stopSimulation() {
  simulation.stop();
}

/**
 * Calculate the average values of the array.
 * @param  {array} array
 * @return {number}  the mean of the array.
 */
function getAverage(array) {
  var total = 0;
  for (var i = 0; i < array.length; i++) {
    total += array[i];
  }
  return total/array.length;
}


text:
const test = require('ava');
const hapi = require('hapi');

test('register without errors (no opts)', async t => {
  const server = new hapi.Server();
  await t.notThrows(server.register(require('../forest')));
});

test('register and bootstrap', async t => {
  const server = new hapi.Server({ host: 'localhost' }); // will never be used
  const register = server.register({
    plugin: require('../forest'),
    options: {
      bootstrap: [
        require('./fixtures/test-cat-model'),
      ]
    }
  });
  await t.notThrows(register);
  // TODO: check for routes
});


text:
from django.views import generic
from django.views.generic import View
from django.views.generic.edit import CreateView, UpdateView, DeleteView, FormView
from django.shortcuts import render, redirect
from .models import Information, Images
from .forms import ProjectForm, UserForm
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponse
from django.contrib.auth import authenticate, login

class IndexView(generic.ListView):
	template_name = 'projects/index.html'
	context_object_name = 'all_projects'

	def get_queryset(self):
		return Information.objects.all()

class DetailView(generic.DetailView):
	model = Information
	template_name="projects/project_detail.html"

 # def project_form(request):
#	return render(request, 'projects/project_form.html')

# def add_project(request):
# 	if request.method == 'POST':
# 		#form = ProjectForm(request.POST, request.FILES)
# 		# if form.is_valid():
# 		info = Information()
# 		# info.project_title = form.cleaned_data['project_title']
# 		# info.description = form.cleaned_data['description']
# 		# info.photos = form.cleaned_data['photos']
# 		# i=0
# 		info.project_title = request.POST.get('project_title')
# 		info.description = request.POST.get('description')
# 		# for photo in request.POST.getlist('photos[]'):
# 		# 	info.photos[i]=request.photo
# 		# 	i=i+1
# 		info.photos = request.POST.getlist('photos[]')
# 		info.save()
# 		all_projects = Information.objects.all()
# 	return render(request, 'projects/index.html', {'all_projects': all_projects})

class ProjectForm(FormView):
	form_class = ProjectForm
	template_name = 'projects/project_form.html'

	def post(self, request, *args, **kwargs):
		form_class = self.get_form_class()
		form = self.get_form(form_class)
		info = Information()

		info.project_title = request.POST.get('project_title')
		info.description = request.POST.get('description')
		info.save()
		files = request.FILES.getlist('photos')
		if form.is_valid():
			for f in files:
				img = Images()
				img.information = info
				img.photo = f
				img.save()
		all_projects = Information.objects.all()
		# return redirect("index")
		return render(request, 'projects/index.html', {'all_projects': all_projects})

class UserFormView(View):
	form_class = UserForm
	template_name = 'projects/registration_form.html'

	def get(self, request):
		form = self.form_class(None)
		return render(request, self.template_name, {'form': form})

	def post(self, request):
		form = self.form_class(request.POST)

		if form.is_valid():
			user = form.save(commit = False)
			username = form.cleaned_data['username']
			password = form.cleaned_data['password']
			user.set_password(password)
			user.save()

			user = authenticate(username = username, password = password)

			if user is not None:
				if user.is_active:
					login(request, user)
					return redirect('projects:index')

		return render(request, self.template_name, {'form': form})


text:
/**
 * Created by 给力叔 on 2017/10/4/004.
 */
import {Project} from "../../project/Project";
import {Scene} from "../../scene/Scene";
import {ISceneProperties} from "../../scene/ISceneProperties";
import {GLS_COMPONENT_STAGE, Stage} from "../../display/stage/Stage";
import {DisplayComponentFactory} from "../display/DisplayComponentFactory";
import {utils} from "../../../../../common/utils";
import {DisplayComponent} from "../../display/DisplayComponent";
import axios from 'axios';
import {Properties} from "../../display/property/Properties";
import {DisplayComponentContainer} from "../../display/DisplayComponentContainer";
import {Debounce} from "../../../../../common/utils/Debounce";
import {Injectable} from "angular2-decorators-for-vue";
export interface IDisplayComponentData {
  props: Properties;
  children?: Array<IDisplayComponentData>;
}

@Injectable()
export class SceneService {
  private _debounce = new Debounce(50);
  createScene(project: Project, sceneProperties?: ISceneProperties) {
    let scene = new Scene();
    if (!sceneProperties) {
      scene.props.id = (++project.numSceneCreated).toString();
      scene.props.name = `场景${scene.props.id}`;
    } else {
      for (let key of Object.keys(sceneProperties)) {
        scene.props[key] = sceneProperties[key];
      }
    }
    scene.stage = DisplayComponentFactory.getInstance().createComponent(project, GLS_COMPONENT_STAGE);
    return scene;
  }

  load(project: Project, scene: Scene) {
    scene.destroy();

    axios.get("/api/getScene?id=" + scene.props.id).then((result) => {
      let data: IDisplayComponentData = result.data;
      let stage;
      if (data.props) {
        stage = this.createComponent(project, data);
      } else {
        stage = DisplayComponentFactory.getInstance().createComponent(project, GLS_COMPONENT_STAGE);
      }
      scene.stage = stage as Stage;
    })
  }

  createComponent(project: Project, data: IDisplayComponentData): DisplayComponent {
    let component = DisplayComponentFactory.getInstance().createComponent(project, data.props.type, data.props.id);

    //继承服务器的属性
    for (let key of Object.keys(data.props)) {
      component.props[key] = data.props[key];
    }

    if (utils.isArray(data.children)) {
      data.children.forEach((childData: IDisplayComponentData) => {
        let child = this.createComponent(project, childData);
        (<DisplayComponentContainer>component).addChild(child);
      })
    }
    return component;
  }

  /**
   * 保存场景
   * @param {Project} project
   * @param {Scene} scene
   * @returns {AxiosPromise}
   */
  save(project: Project, scene: Scene) {
    let formData = utils.mapTree(scene.stage, function (component: DisplayComponent) {
      return {props: component.props};
    });
    formData.id = scene.props.id;
    formData.projectId = project.id;
    return axios.put("/api/saveScene", formData);
  }

  /**
   * 删除场景
   * @param {Project} project
   * @returns {Promise<AxiosResponse>}
   */
  deleteScene(project: Project) {
    return axios.delete(utils.getRequestPath('/api/deleteScene', {id: project.selectedScene.props.id})).then((result) => {
      if (result.data !== false) {
        project.removeSelectedScene();
      }
    });
  }

  /**
   * 新增一个空白场景
   * @param {Project} project
   */
  addScene(project: Project) {
    let index = project.scenes.indexOf(project.selectedScene) + 1;
    axios.put(utils.getRequestPath('/api/addScene', {index: index, projectId: project.id})).then(() => {
      let scene = this.createScene(project);
      let scenes = project.scenes;
      scenes.splice(index, 0, scene);
    });
  }

  /**
   * 拷贝场景
   * @param {Project} project
   */
  copyScene(project: Project) {
    let selectedScene = project.selectedScene;
    axios.put(utils.getRequestPath('/api/copyScene', {id: selectedScene.props.id})).then((result) => {
      let data = result.data;
      let scene = this.createScene(project);
      scene.props.id = data.id;
      scene.props.name = data.name;
      let scenes = project.scenes;
      scenes.splice(project.scenes.indexOf(selectedScene) + 1, 0, scene);
    });
  }

  /**
   * 更换场景的位置
   * @param {number} oldIndex
   * @param {number} newIndex
   */
  changeScene(oldIndex:number,newIndex:number){
    axios.post(utils.getRequestPath('/api/changeSceneIndex', {oldIndex: oldIndex,newIndex:newIndex})).catch((result) => {
      //todo 失败就是要回档咯
    });
  }

  /**
   * 修改场景的名称
   * @param {Scene} scene
   */
  changeSceneName(scene:Scene){
    this._debounce.handle(()=>{
      axios.put(utils.getRequestPath('/api/changeSceneName', {id: scene.props.id,name:scene.props.name}));
    })
  }
}


text:
package win32

import (
	"syscall"
)

type _WNDCLASS struct {
	Style         uint32
	LpfnWndProc   uintptr
	CbClsExtra    int32
	CbWndExtra    int32
	HInstance     HINSTANCE
	HIcon         HICON
	HCursor       HCURSOR
	HbrBackground HWND
	LpszMenuName  *uint16
	LpszClassName *uint16
}

type _WINDOWPOS struct {
	HWND            syscall.Handle
	HWNDInsertAfter syscall.Handle
	X               int32
	Y               int32
	Cx              int32
	Cy              int32
	Flags           uint32
}

const (
	_WM_SETFOCUS         = 7
	_WM_KILLFOCUS        = 8
	_WM_PAINT            = 15
	_WM_CLOSE            = 16
	_WM_WINDOWPOSCHANGED = 71
	_WM_KEYDOWN          = 256
	_WM_KEYUP            = 257
	//_WM_SYSKEYDOWN       = 260
	//_WM_SYSKEYUP         = 261
	_WM_MOUSEMOVE       = 512
	_WM_MOUSEWHEEL      = 522
	_WM_LBUTTONDOWN     = 513
	_WM_LBUTTONUP       = 514
	_WM_RBUTTONDOWN     = 516
	_WM_RBUTTONUP       = 517
	_WM_MBUTTONDOWN     = 519
	_WM_MBUTTONUP       = 520
	_WM_USER            = 0x0400
	_WM_INPUTLANGCHANGE = 0x0051
)

// WM_SYSCOMMAND

const (
	_VK_SHIFT   = 16
	_VK_CONTROL = 17
	_VK_MENU    = 18
	_VK_LWIN    = 0x5B
	_VK_RWIN    = 0x5C
)

const (
	IDI_APPLICATION = 32512
	IDC_ARROW       = 32512
)

const (
	_CW_USEDEFAULT = 0x80000000 - 0x100000000

	_SW_SHOWDEFAULT = 10

	_SWP_NOSIZE = 0x0001
)

const (
	_WHEEL_DELTA = 120
)

func _GET_X_LPARAM(lp uintptr) int32 {
	return int32(_LOWORD(lp))
}

func _GET_Y_LPARAM(lp uintptr) int32 {
	return int32(_HIWORD(lp))
}

func _GET_WHEEL_DELTA_WPARAM(lp uintptr) int16 {
	return int16(_HIWORD(lp))
}

func _LOWORD(l uintptr) uint16 {
	return uint16(uint32(l))
}

func _HIWORD(l uintptr) uint16 {
	return uint16(uint32(l >> 16))
}

// notes to self
// UINT = uint32
// callbacks = uintptr
// strings = *uint16

//sys	GetDC(hwnd syscall.Handle) (dc syscall.Handle, err error) = user32.GetDC
//sys	ReleaseDC(hwnd syscall.Handle, dc syscall.Handle) (err error) = user32.ReleaseDC

//sys	_CreateWindowEx(exstyle uint32, className *uint16, windowText *uint16, style uint32, x int32, y int32, width int32, height int32, parent syscall.Handle, menu syscall.Handle, hInstance syscall.Handle, lpParam uintptr) (hwnd syscall.Handle, err error) = user32.CreateWindowExW
//sys	_DefWindowProc(hwnd syscall.Handle, uMsg uint32, wParam uintptr, lParam uintptr) (lResult uintptr) = user32.DefWindowProcW
//sys	_GetClientRect(hwnd syscall.Handle, rect *_RECT) (err error) = user32.GetClientRect
//sys	_GetWindowRect(hwnd syscall.Handle, rect *_RECT) (err error) = user32.GetWindowRect
//sys   _GetKeyboardLayout(threadID uint32) (locale syscall.Handle) = user32.GetKeyboardLayout
//sys   _GetKeyboardState(lpKeyState *byte) (err error) = user32.GetKeyboardState
//sys	_GetKeyState(virtkey int32) (keystatus int16) = user32.GetKeyState
//sys	_GetMessage(msg *_MSG, hwnd syscall.Handle, msgfiltermin uint32, msgfiltermax uint32) (ret int32, err error) [failretval==-1] = user32.GetMessageW
//sys	_LoadCursor(hInstance syscall.Handle, cursorName uintptr) (cursor syscall.Handle, err error) = user32.LoadCursorW
//sys	_LoadIcon(hInstance syscall.Handle, iconName uintptr) (icon syscall.Handle, err error) = user32.LoadIconW
//sys	_MoveWindow(hwnd syscall.Handle, x int32, y int32, w int32, h int32, repaint bool) (err error) = user32.MoveWindow
//sys   _PostQuitMessage(exitCode int32) = user32.PostQuitMessage
//sys	_RegisterClass(wc *_WNDCLASS) (atom uint16, err error) = user32.RegisterClassW
//sys   _ToUnicodeEx(wVirtKey uint32, wScanCode uint32, lpKeyState *byte, pwszBuff *uint16, cchBuff int32, wFlags uint32, dwhkl syscall.Handle) (ret int32) = user32.ToUnicodeEx