text:
/* jshint strict: false, sub: true */
/* global print */
'use strict';

////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2021 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Andrei Lobov
////////////////////////////////////////////////////////////////////////////////

const functionsDocumentation = {
  'recovery_cluster': 'run recovery tests for cluster'
};
const optionsDocumentation = [
];

const fs = require('fs');
const internal = require('internal');
const pu = require('@arangodb/testutils/process-utils');
const tu = require('@arangodb/testutils/test-utils');
const _ = require('lodash');

const toArgv = require('internal').toArgv;

const RED = require('internal').COLORS.COLOR_RED;
const RESET = require('internal').COLORS.COLOR_RESET;
const BLUE = require('internal').COLORS.COLOR_BLUE;

const termSignal = 15;

const testPaths = {
  'recovery_cluster': [tu.pathForTesting('server/recovery')]
};

/// ensure that we have enough db servers in cluster tests
function ensureServers(options, numServers) {
  if (options.cluster && options.dbServers < numServers) {
    let localOptions = _.clone(options);
    localOptions.dbServers = numServers;
    return localOptions;
  }
  return options;
}

function checkServersGOOD(instanceInfo) {
  try {
    let health = internal.clusterHealth();
    let rc = instanceInfo.arangods.reduce((previous, arangod) => {
        if (arangod.role === "agent") return true;
        if (health.hasOwnProperty(arangod.id)) {
          if (health[arangod.id].Status === "GOOD") {
            return previous;
          } else {
            print(RED + "ClusterHealthCheck failed " + arangod.id + " has status "
                  + health[arangod.id].Status + " (which is not equal to GOOD)");
            return false;
          }
        } else {
          print(RED + "ClusterHealthCheck failed " + arangod.id
                + " does not have health property");
          return false;
        }
      }, true);
    return rc;
  } catch(e) {
    print("Error checking cluster health " + e);
    return false;
  }
}

// //////////////////////////////////////////////////////////////////////////////
// / @brief TEST: recovery_cluster
// //////////////////////////////////////////////////////////////////////////////

function runArangodRecovery (params) {
  let useEncryption = false;
  if (global.ARANGODB_CLIENT_VERSION) {
    let version = global.ARANGODB_CLIENT_VERSION(true);
    if (version.hasOwnProperty('enterprise-version')) {
      useEncryption = true;
    }
  }

  let additionalParams= {
    'foxx.queues': 'false',
    'server.statistics': 'false',
    'log.foreground-tty': 'true',
    'database.ignore-datafile-errors': 'false', // intentionally false!
  };

  // for cluster runs we have separate parameter set for servers and for testagent(arangosh)
  let additionalTestParams  = {};

  if (useEncryption) {
    // randomly turn on or off hardware-acceleration for encryption for both
    // setup and the actual test. given enough tests, this will ensure that we run
    // a good mix of accelerated and non-accelerated encryption code. in addition,
    // we shuffle between the setup and the test phase, so if there is any
    // incompatibility between the two modes, this will likely find it
    additionalParams['rocksdb.encryption-hardware-acceleration'] = (Math.random() * 100 >= 50) ? "true" : "false";
  }
  let argv = [];
  let binary = pu.ARANGOD_BIN;
  // arangosh has different name for parameter :(
  additionalTestParams['javascript.execute'] =  params.script;
  additionalTestParams['javascript.run-main'] = true;

  if (params.setup) {
    additionalTestParams['server.request-timeout'] = '60';
    additionalTestParams['javascript.script-parameter'] = 'setup';

    // special handling for crash-handler recovery tests
    if (params.script.match(/crash-handler/)) {
      // forcefully enable crash handler, even if turned off globally
      // during testing
      internal.env["ARANGODB_OVERRIDE_CRASH_HANDLER"] = "on";
    }

    params.options.disableMonitor = true;
    params.options =  ensureServers(params.options);
    let args = {};
    args['temp.path'] = params.instanceInfo.rootDir;

    // enable development debugging if extremeVerbosity is set
    if (params.options.extremeVerbosity === true) {
      args['log.level'] = 'development=info';
    }
    args = Object.assign(args, params.options.extraArgs);
    args = Object.assign(args, {
      'rocksdb.wal-file-timeout-initial': 10,
      'replication.auto-start': 'true'
    });

    if (useEncryption) {
      let keyDir = fs.join(fs.getTempPath(), 'arango_encryption');
      if (!fs.exists(keyDir)) {  // needed on win32
        fs.makeDirectory(keyDir);
      }
      pu.cleanupDBDirectoriesAppend(keyDir);

      const key = '01234567890123456789012345678901';

      let keyfile = fs.join(keyDir, 'rocksdb-encryption-keyfile');
      fs.write(keyfile, key);

      // special handling for encryption-keyfolder tests
      if (params.script.match(/encryption-keyfolder/)) {
        args['rocksdb.encryption-keyfolder'] = keyDir;
        process.env["rocksdb-encryption-keyfolder"] = keyDir;
      } else {
        args['rocksdb.encryption-keyfile'] = keyfile;
        process.env["rocksdb-encryption-keyfile"] = keyfile;
      }
    }

    params.args = args;

  } else {
    additionalTestParams['javascript.script-parameter'] = 'recovery';
  }

  if (params.setup) {
    params.args = Object.assign(params.args, additionalParams);
    params.instanceInfo = pu.startInstance(params.options.protocol,
                                           params.options,
                                           params.args,
                                           fs.join('recovery_cluster', params.count.toString()));
  } else {
    print(BLUE + "Restarting cluster " + RESET);
    pu.reStartInstance(params.options, params.instanceInfo, {});
    let tryCount = 10;
    while(tryCount > 0 && !checkServersGOOD(params.instanceInfo)) {
      print(RESET + "Waiting for all servers to go GOOD");
      internal.sleep(3); // give agency time to bootstrap DBServers
      --tryCount;
    }
  }
  let agentArgs = pu.makeArgs.arangosh(params.options);
  agentArgs['server.endpoint'] = tu.findEndpoint(params.options, params.instanceInfo);
  if (params.args['log.level']) {
    agentArgs['log.level'] = params.args['log.level'];
  }
  agentArgs['temp.path'] = params.instanceInfo.rootDir;
  Object.assign(agentArgs, additionalTestParams);
  require('internal').env.INSTANCEINFO = JSON.stringify(params.instanceInfo);
  try {
    pu.executeAndWait(pu.ARANGOSH_BIN, toArgv(agentArgs), params.options, 'arangosh', params.instanceInfo.rootDir, false);
  } catch(err) {
    print('Error while launching test:' + err);
    pu.shutdownInstance(params.instanceInfo, params.options, false);
    return; // without test server test will for sure fail
  }
  if (params.setup) {
    let dbServers = params.instanceInfo.arangods.slice().filter((a) => {return a.role === 'dbserver' || a.role === 'coordinator';});
    print(BLUE + "killing " + dbServers.length + " DBServers/Coordinators " + RESET);
    dbServers.forEach((arangod) => {
      internal.debugTerminateInstance(arangod.endpoint);
      // need this to properly mark spawned process as killed in internal test data
      arangod.exitStatus = internal.killExternal(arangod.pid, termSignal);
      arangod.pid = 0;
    });
  } else {
    pu.shutdownInstance(params.instanceInfo, params.options, false);
  }
}

function recovery (options) {
  if ((!global.ARANGODB_CLIENT_VERSION(true)['failure-tests'] ||
       global.ARANGODB_CLIENT_VERSION(true)['failure-tests'] === 'false') ||
      (!global.ARANGODB_CLIENT_VERSION(true)['maintainer-mode'] ||
       global.ARANGODB_CLIENT_VERSION(true)['maintainer-mode'] === 'false')) {
    return {
      recovery: {
        status: false,
        message: 'failure-tests not enabled. please recompile with -DUSE_FAILURE_TESTS=On and -DUSE_MAINTAINER_MODE=On'
      },
      status: false
    };
  }

  if (!options.cluster) {
    return {
      recovery: {
        status: false,
        message: 'cluster_recovery suite need cluster option to be set to true!'
      },
      status: false
    };
  }

  let results = {
    status: true
  };

  let recoveryTests = tu.scanTestPaths(testPaths.recovery_cluster, options);

  recoveryTests = tu.splitBuckets(options, recoveryTests);

  let count = 0;
  let orgTmp = process.env.TMPDIR;
  let tempDir = fs.join(fs.getTempPath(), 'recovery_cluster');
  fs.makeDirectoryRecursive(tempDir);
  process.env.TMPDIR = tempDir;
  pu.cleanupDBDirectoriesAppend(tempDir);

  for (let i = 0; i < recoveryTests.length; ++i) {
    let test = recoveryTests[i];
    let filtered = {};

    if (tu.filterTestcaseByOptions(test, options, filtered)) {
      count += 1;
      ////////////////////////////////////////////////////////////////////////
      print(BLUE + "running setup of test " + count + " - " + test + RESET);
      let params = {
        tempDir: tempDir,
        instanceInfo: {
          rootDir: fs.join(fs.getTempPath(), 'recovery_cluster', count.toString())
        },
        options: _.cloneDeep(options),
        script: test,
        setup: true,
        count: count,
        testDir: ""
      };
      runArangodRecovery(params);

      ////////////////////////////////////////////////////////////////////////
      print(BLUE + "running recovery of test " + count + " - " + test + RESET);
      params.options.disableMonitor = options.disableMonitor;
      params.setup = false;
      try {
        tu.writeTestResult(params.args['temp.path'], {
          failed: 1,
          status: false,
          message: "unable to run recovery test " + test,
          duration: -1
        });
      } catch (er) {}
      runArangodRecovery(params);

      results[test] = tu.readTestResult(
        params.args['temp.path'],
        {
          status: false
        },
        test
      );
      if (!results[test].status) {
        print("Not cleaning up " + params.testDir);
        results.status = false;
      }
      else {
        pu.cleanupLastDirectory(params.options);
      }
    } else {
      if (options.extremeVerbosity) {
        print('Skipped ' + test + ' because of ' + filtered.filter);
      }
    }
  }
  process.env.TMPDIR = orgTmp;
  if (count === 0) {
    print(RED + 'No testcase matched the filter.' + RESET);
    return {
      ALLTESTS: {
        status: true,
        skipped: true
      },
      status: true
    };
  }

  return results;
}

exports.setup = function (testFns, defaultFns, opts, fnDocs, optionsDoc, allTestPaths) {
  Object.assign(allTestPaths, testPaths);
  testFns['recovery_cluster'] = recovery;
  for (var attrname in functionsDocumentation) { fnDocs[attrname] = functionsDocumentation[attrname]; }
  for (var i = 0; i < optionsDocumentation.length; i++) { optionsDoc.push(optionsDocumentation[i]); }
};


text:
<?php
use \Kondrat\DesignPatterns\Command\ConcreteCommand\GarageDoorDownCommand;
use \Kondrat\DesignPatterns\Command\Receiver\GarageDoor;

class GarageDoorDownCommandTest extends PHPUnit_Framework_TestCase
{
    protected $command;

    protected function setUp()
    {
        $this->command = new GarageDoorDownCommand( new GarageDoor() );
    }

    public function testExecute()
    {
        $this->assertEquals("Garage door is closed.\n", $this->command->execute());
    }

    public function testUndo()
    {
        $this->assertEquals("Garage door is open.\n", $this->command->undo());
    }

    public function testToString()
    {
        $this->assertEquals('GarageDoorDownCommand', strval($this->command));
    }
}

redpajama_set_name: RedPajamaGithub


text:
/* ==========================================================================
   CustomForm
   ========================================================================== */
.customform {
  cursor: pointer;
}

.customform.is-disabled,
.customform.is-disabled label,
.customform .is-disabled {
  opacity: .5;
  cursor: default;
}

.customform-input {
  display: block;
  position: relative;
}

.customform-input > input,
.customform-input > select {
  position: absolute;
  z-index: -1;
  opacity: 0;
  visibility: hidden;
}


text:
import os, csv, json
from time import time
import datetime
from collections import Counter
import lib.tweetminer as minetweet
from lib.users import UserAPI
import networkx as nx
import community
from lib.nlp import NLPMiner
import locale

results_path="/home/clemsos/Dev/mitras/results/"
meme_names=["biaoge"]
# meme_names=[ meme for meme in os.listdir(results_path) if meme[-3:] != "csv"]
# meme_names=[
#  'biaoge',
#  'thevoice',
#  'moyan',
#  'hougong',
#  'gangnam',
#  'sextape',
#  'dufu',
#  'ccp',
#  'yuanfang',
#  'qiegao']

print meme_names

t0=time()
minetweet.init_tweet_regex()

locale.setlocale(locale.LC_ALL, "")

nlp=NLPMiner()

stoplist=[i.strip() for i in open("lib/stopwords/zh-stopwords","r")]
stoplist+=[i.strip() for i in open("lib/stopwords/stopwords.txt","r")]
stoplist+=["转发","微博","说 ","一个","【 ","年 ","转 ","请","" ","问题","知道","中 ","已经","现在","说","【",'"',"年","中","今天","应该","真的","月","希望","想","日","这是","太","转","支持"]
# stoplist+=["事儿","中国"]

api=UserAPI()
words_users_time=[]

def get_province(_userid):
    province_code= api.get_province(_userid)
    # print province_code
    try :
        return api.provinces[province_code]
    except KeyError :
        return 0
        pass

def analyze_meme(meme_name):

    # Init
    tstart=time()
    print "Processing meme '%s'"%meme_name

    # files names
    meme_path=outfile=results_path+meme_name
    meme_csv=meme_path+"/"+meme_name+".csv"

    jsondata={}
    jsondata["meme_name"]=meme_name

    user_edges=[]
    user_nodes=[]
    words_series=[]
    words_list=[]
    words_users={}
    count=0

    words_users_time=[]

    # process the data
    with open(meme_csv, 'rb') as csvfile:
        memecsv=csv.reader(csvfile)
        memecsv.next() # skip headers

        for row in memecsv:
            # extract text
            t=row[1]
            count+=1

            timestamp=row[9]

            # regexp extract tweet entities
            mentions,urls,hashtags,clean=minetweet.extract_tweet_entities(t)

            # extract text
            dico=nlp.extract_dictionary(clean)

            # remove stopwords and get clean dico
            clean_dico=nlp.remove_stopwords(dico)

            # remove more stopwords
            tmp_words=[w for w in clean_dico if w.encode('utf-8') not in stoplist and w[0] != "u" ]

            words_list+=tmp_words # global list for counter

            # User diffusion graph
            user_diff=[]
            for mention in mentions:
                user_edges.append((row[0],mention))
                if mention not in user_diff : user_diff.append(mention)

                # retweeted_uid
            if row[7] != "" :
                user_edges.append((row[7],row[0]))
                if row[7] not in user_diff : user_diff.append(row[7])

            words_series.append(tmp_words)

            for w in tmp_words :
                try :
                    words_users[w] += user_diff
                except KeyError:
                    words_users[w] = []
                    words_users[w] += user_diff

            words_users_time.append((tmp_words,user_edges,timestamp))

    # CSV processed
    edges_weighted=[str(p[0][0]+" "+p[0][1]+" "+str(p[1])) for p in Counter(user_edges).most_common()] # if p[1] > 1]

    print "Edges (raw files) : %d edges"%len(user_edges)
    print "Weighted edges %d"%len(edges_weighted)

    G = nx.read_weighted_edgelist(edges_weighted, nodetype=str, delimiter=" ",create_using=nx.DiGraph())

    N,K = G.order(), G.size()
    print "Nodes: ", N
    print "Edges: ", K

    jsondata["graph"]={}
    jsondata["graph"]["total_raw_edges"]=len(user_edges)
    jsondata["graph"]["total_nodes"]=N
    jsondata["graph"]["total_edges"]=K

    # init nodes
    d3nodes={}
    for n in G.nodes(data=True) :
        d3nodes[ n[0] ]=n[1]
        d3nodes[ n[0]]["name"]=n[0]
        d3nodes[ n[0]]["province"]=get_province(n[0])

    # Clustering and degree coeficient
    #################################

    avg_deg = float(K)/N
    print "Average degree: ", avg_deg
    jsondata["graph"]["average_degree"]=avg_deg

    # Clustering coefficient of all nodes (in a dictionary)
    ccs = nx.clustering(G.to_undirected())

    # Average clustering coefficient
    avg_clust_coef = sum(ccs.values()) / len(ccs) # also : nx.algorithms.cluster.average_clustering(G.to_undirected())
    print "Average clustering coeficient: %f"%avg_clust_coef
    jsondata["graph"]["average_clustering_coeficient"]=avg_clust_coef

     # Communities
    # from http://perso.crans.org/aynaud/communities/
    ##################################################################

    jsondata["communities"]={}

    # Best partition
    best_partition = community.best_partition(G.to_undirected())
    modularity=community.modularity(best_partition,G.to_undirected())
    print "Modularity of the best partition: %f"%modularity
    print "Number of nodes in the best partition : ", len(set(best_partition.values()))

    jsondata["communities"]={}
    jsondata["communities"]={}
    jsondata["communities"]["modularity"]=modularity
    jsondata["communities"]["number_of_communities"]=len(set(best_partition.values()))

    for node in best_partition:
        d3nodes[node]["community"]=best_partition[node]

    # CENTRALITIES
    # http://toreopsahl.com/tnet/weighted-networks/node-centrality/
    #################################
    # Betweeness centrality
    # betweeness_centrality={}
    # Create ordered tuple of centrality data
    print "computing betweeness_centrality... (this may take some time)"

    if(N>10000) :cent_dict=nx.betweenness_centrality (G.to_undirected(),k=200)
    else : cent_dict=nx.betweenness_centrality (G.to_undirected())

    cent_items=[(b,a) for (a,b) in cent_dict.iteritems()]
    # add value to nodes
    for node in cent_dict: d3nodes[node]["btw_cent"]=cent_dict[node]

    '''
    # Sort in descending order
    cent_items.sort()
    cent_items.reverse()

    # Highest centrality
    jsondata["betweeness_centrality"]["top"]=[]
    for j,c in enumerate(cent_items[0:5]):
        print "Highest betweeness centrality :%.3f"%c[0]
        jsondata["betweeness_centrality"]["top"].append({"index": j, "value" :"%.3f"%c[0], "id" : c[1] })

    # Collect discretized distribution of centralities
    btw_cent_dist=[{"value":c[0],"count" :c[1] } for c in Counter(["%.3f"%c[0] for c in cent_items]).most_common()]

    jsondata["betweeness_centrality"]["distribution"]=btw_cent_dist
    jsondata["graph"]["average_betweeness_centrality"]=sum([c[0] for c in cent_items])/len(cent_items)
    '''

    # CREATE WORDS GRAPH
    ################################

    data_words={}
    data_words["edges"]=[]
    # node_words=[{"name":word[0],"count":word[1]} for word in Counter(words).most_common() if word[1]>10]

    # build nodesnode_words
    node_words=[c[0] for c in Counter(words_list).most_common(500)]

    # print len(node_words), " nodes in words"
    tmp_words_edges=[]
    word_edges=[]

    for serie in words_series:
        tmp_words_edges+= [(word, serie) for word in serie if word in node_words]

    for edge_pack in tmp_words_edges:
        for word in edge_pack[1]:
            if word is not edge_pack[0] and edge_pack[0] != word:
                tmp=[edge_pack[0], word]
                tmp.sort(cmp=locale.strcoll) # sort chinese characters to create undirected graph
                word_edges.append((tmp[0],tmp[1]))

    data_words["edges"]= [ {"source" : c[0][0], "target" : c[0][1], "weight": c[1] } for c in Counter(word_edges).most_common(200) ]

    words_map={}
    word_user_edges=[]
    for c in Counter(words_list).most_common(500):
        words_map[c[0]]=c[1]
        # create user > word graph
        for user in Counter(words_users[c[0]]).most_common():
            if user[1] > 2 : word_user_edges.append({"source": c[0], "target": user[0], "weight": user[1], "community" : best_partition[user[0]]})

    unique_nodes=[]
    for e in data_words["edges"]:
        if e["source"] not in unique_nodes : unique_nodes.append(e["source"])
        if e["target"] not in unique_nodes : unique_nodes.append(e["target"])

    data_words["nodes"]=[{"name" : node, "count": words_map[node]} for node in unique_nodes]

    # OUTPUT D3 GRAPH
    ################################

    # write d3js conversational graph
    # (only partial graph)
    min_weight=2
    d3_file=meme_path+"/"+meme_name+"_d3graph.json"

    d3data={}
    d3data["info"]=jsondata
    d3data["words"]=data_words
    d3data["words_user"]=word_user_edges

    d3data["nodes"]=[]
    d3data["edges"]=[ {"source":edge[0],"target":edge[1],"weight":edge[2]["weight"] } for edge in G.edges(data=True) if edge[2]["weight"] >= min_weight]

    d3_nodes_done=[]
    for edge in d3data["edges"]:
        if edge["source"] not in d3_nodes_done:
            d3_nodes_done.append(edge["source"])
            d3data["nodes"].append(d3nodes[edge["source"]])
        if edge["target"] not in d3_nodes_done:
            d3_nodes_done.append(edge["target"])
            d3data["nodes"].append(d3nodes[edge["target"]])

    d3data["users"]={}
    d3data["users"]["nodes"]=d3data["nodes"]
    del(d3data["nodes"])
    d3data["users"]["edges"]=d3data["edges"]
    del(d3data["edges"])

    # write d3js annotated graph
    with open(d3_file, 'w') as outfile:
        json.dump(d3data, outfile)
        print "json data have been saved to %s"%(d3_file)

    print "done in %.3fs"%(time()-tstart)

    # d3_file=meme_path+"/"+meme_name+"_d3graph.full.json"

    # d3fulldata={}
    # d3fulldata["info"]=jsondata
    # d3fulldata["nodes"]=[d3nodes[node] for node in d3nodes ]
    # d3fulldata["edges"]=[ {"source":edge[0],"target":edge[1],"weight":edge[2]["weight"] } for edge in G.edges(data=True)]

    # with open(d3_file, 'w') as outfile:
    #     json.dump(d3fulldata, outfile)
    #     print "full json data have been saved to %s"%(d3_file)

for meme in meme_names:
    analyze_meme(meme)

print "Everything done in %.3fs"%(time()-t0)


text:
/**
 * Component definition for frost-select component
 */
import layout from '../templates/components/frost-select'
import keyCodes from '../utils/key-codes'
import Component from './frost-component'
import Ember from 'ember'
import computed, {readOnly} from 'ember-computed-decorators'
import {task, timeout} from 'ember-concurrency'
import {PropTypes} from 'ember-prop-types'

const {$, on, run, typeOf} = Ember

const {DOWN_ARROW, SPACE, UP_ARROW} = keyCodes

/**
 * Compare two string arrays to determine if they contain the same values
 * NOTE: this method does not care about the order of the items
 * @param {Array<String>} a - first array
 * @param {Array<String>} b second array
 * @returns {Boolean} whether or not arrays contain same values
 */
function compareArrays (a, b) {
  if (a.length !== b.length) {
    return false
  }

  a = a.sort()
  b = b.sort()

  return a.every((value, index) => value === b[index])
}

/**
 * Compare two selected value objects to determine if they are equivalent
 * @param {Array<String>|String} a - first selected value object
 * @param {Array<String>|String} b - second selected value object
 * @returns {Boolean} whether or not selected value objects are equivalent
 */
function compareSelectedValues (a, b) {
  if (typeOf(a) === 'array' && typeOf(b) === 'array') {
    return compareArrays(a, b)
  }

  return a === b
}

export default Component.extend({
  // == Dependencies ==========================================================

  // == Keyword Properties ====================================================

  attributeBindings: [
    'ariaLabel:aria-label',
    'computedTabIndex:tabIndex',
    'opened:aria-pressed',
    'role',
    'style'
  ],

  classNameBindings: [
    'disabled:frost-select-disabled',
    'error:frost-select-error',
    'focused:frost-select-focused',
    'opened:frost-select-opened',
    'text::frost-select-placeholder'
  ],

  layout,

  // == PropTypes =============================================================

  propTypes: {
    // options
    autofocus: PropTypes.bool,
    disabled: PropTypes.bool,
    error: PropTypes.bool,
    label: PropTypes.string,
    secondaryLabels: PropTypes.arrayOf(PropTypes.string),
    multiselect: PropTypes.bool,
    onBlur: PropTypes.func,
    onChange: PropTypes.func,
    onFocus: PropTypes.func,
    onInput: PropTypes.func,
    renderTarget: PropTypes.string,
    role: PropTypes.string,
    filterType: PropTypes.oneOf(['startsWith', 'contains']),
    selected: PropTypes.oneOfType([
      PropTypes.array,
      PropTypes.number
    ]),
    selectedValue: PropTypes.oneOfType([
      PropTypes.array,
      PropTypes.bool,
      PropTypes.number,
      PropTypes.null,
      PropTypes.object,
      PropTypes.string
    ]),
    tabIndex: PropTypes.number,
    width: PropTypes.oneOfType([PropTypes.number, PropTypes.null]),
    wrapLabels: PropTypes.bool,

    // state
    $element: PropTypes.object,
    focused: PropTypes.bool,
    internalSelectedValue: PropTypes.oneOfType([
      PropTypes.array,
      PropTypes.bool,
      PropTypes.number,
      PropTypes.null,
      PropTypes.object,
      PropTypes.string
    ]),
    opened: PropTypes.bool,
    debounceInterval: PropTypes.number
  },

  getDefaultProps () {
    return {
      // options
      autofocus: false,
      disabled: false,
      error: false,
      multiselect: false,
      renderTarget: 'frost-select',
      role: 'button',
      filterType: 'contains',
      tabIndex: 0,
      debounceInterval: 0,
      // state
      focused: false
    }
  },

  // == Computed Properties ===================================================

  @readOnly
  @computed('label', 'opened')
  ariaLabel (label, opened) {
    const verb = opened ? 'Hide' : 'Show'

    if (label) {
      return `${verb} ${label} combobox`
    }

    return `${verb} combobox`
  },

  @readOnly
  @computed('data', 'filter', 'onInput')
  items (data, filter, onInput) {
    // If no data to filter we are done
    if (!data) {
      return []
    }

    // External filtering
    if (typeOf(onInput) === 'function') {
      return data
    }

    // Internal filtering

    filter = filter ? filter.toLowerCase() : ''

    return data
      .filter((item) => {
        if (!filter) {
          return true
        }

        const label = item.label || ''
        const secondaryLabels = item.secondaryLabels || []

        if (this.isFilteredItem(label.toLowerCase(), filter)) {
          return true
        }

        const filteredSecondaryLabels = secondaryLabels.filter((secondaryLabel) => {
          if (this.isFilteredItem(secondaryLabel.toLowerCase(), filter)) {
            return true
          }
        })
        return filteredSecondaryLabels.length > 0
      })
  },

  @readOnly
  @computed('data', 'selected', 'internalSelectedValue')
  /* eslint-disable complexity */
  selectedItems (items, selected, selectedValue) {
    if (selectedValue !== undefined) {
      return items.filter((item) => {
        if (typeOf(selectedValue) === 'array') {
          return selectedValue.indexOf(item.value) !== -1
        }

        return item.value === selectedValue
      })
    }

    if (typeOf(selected) === 'array') {
      return selected
        .filter((itemIndex) => itemIndex >= 0 && itemIndex < items.length)
        .map((itemIndex) => items[itemIndex])
    }

    if (selected !== undefined && selected <= 0 && selected < items.length) {
      return [items[selected]]
    }

    return []
  },
  /* eslint-enable complexity */

  @readOnly
  @computed('disabled', 'tabIndex')
  /**
   * Get appropriate tab index
   * disabled state changes.
   * @param {Boolean} disabled - whether or not input is disabled
   * @param {Number} tabIndex - tab index
   * @returns {Number} tab index
   */
  computedTabIndex (disabled, tabIndex) {
    return disabled ? -1 : tabIndex
  },

  @readOnly
  @computed('selectedItems')
  text (selectedItems) {
    switch (selectedItems.length) {
      case 0:
        return null

      case 1:
        return selectedItems[0].label

      case 2:
        return `${selectedItems[0].label}, ${selectedItems[1].label}`
    }

    return `${selectedItems.length} items selected`
  },

  @readOnly
  @computed('width')

  /**
   * Get a style string based on the presence of some properties
   * @param {String} width the width property specified
   * @returns {String} the completed style string
   */
  style (width) {
    let styles = ''

    // if a property is not falsy, append it to the style string
    // note that in the width case, we want the component interface to have absolute power over the width
    // so it will override any max or win widths to ensure ultimate control
    if (width) styles += `width: ${width}px; max-width: initial; min-width:initial; `
    return Ember.String.htmlSafe(styles)
  },

  @readOnly
  @computed('items', 'selectedItems')
  /**
   * As of Ember 2.10, we have to make this a computed property to tell Ember to update our frost-select-dropdown.
   * Any properties that might be updated after the initial render should be observed by this property.
   * (@theotherdude 12/20/2017)
   * @returns {string} 'frost-select-dropdown'
   */
  frostSelectDropdownName () {
    return 'frost-select-dropdown'
  },

  // == Tasks =================================================================

  /**
   * Fires input event after waiting for debounceInterval to clear
   * @param {Function} cb - Reference to onInput
   * @param {String} value - Filter String
   */
  inputTask: task(function * (cb, value) {
    const debounceInterval = this.get('debounceInterval')

    yield timeout(debounceInterval)
    cb(value)
  }).restartable(),

  // == Functions =============================================================
  isFilteredItem (value, filterValue) {
    if (this.filterType === 'startsWith') {
      return value.startsWith(filterValue)
    }
    return value.indexOf(filterValue) !== -1
  },

  selectItem (selectedValue) {
    const isMultiselect = this.get('multiselect')
    const props = {
      opened: isMultiselect,
      internalSelectedValue: selectedValue
    }

    if (!isMultiselect) {
      props.filter = ''
    }

    this.setProperties(props)

    const onChange = this.get('onChange')

    if (typeOf(onChange) === 'function') {
      run.next(() => {
        this.onChange(selectedValue)
      })
    }

    // We need to make sure focus goes back to select since it is on the
    // filter text input while the dropdown is open
    this.$().focus()
  },

  triggerFilterInput (filter) {
    const inputTask = this.get('inputTask')
    const onInput = this.get('onInput')

    if (typeOf(onInput) === 'function') {
      inputTask.perform(onInput, filter)
    } else {
      this.set('filter', filter)
    }
  },

  // == DOM Events ============================================================

  _onClick: on('click', function (e) {
    if (!this.get('disabled')) {
      this.toggleProperty('opened')
    }
    if (this.onClick) {
      this.onClick(e)
    }
  }),

  _onKeyDown: on('keyDown', function (e) {
    if (
      [DOWN_ARROW, UP_ARROW].indexOf(e.keyCode) !== -1 &&
      !this.get('openend')
    ) {
      e.preventDefault() // Keep up/down arrow from scrolling page
      e.stopPropagation()
      this.set('opened', true)
    }
  }),

  _onKeyPress: on('keyPress', function (e) {
    if (e.keyCode === SPACE) {
      e.preventDefault() // Keep space from scrolling page
      e.stopPropagation()
      this.toggleProperty('opened')
    }
  }),

  _onFocusIn: on('focusIn', function () {
    // If select is disabled make sure it can't get focus
    if (this.get('disabled')) {
      this.$().blur()
    } else if (!this.get('focused')) {
      this.set('focused', true)

      const onFocus = this.get('onFocus')

      if (typeOf(onFocus) === 'function') {
        this.get('onFocus')()
      }
    }
  }),

  _onFocusOut: on('focusOut', function () {
    // We must use run.later so filter text input has time to focus when select
    // dropdown is being opened
    /* eslint-disable complexity */
    run.later(() => {
      if (this.isDestroyed || this.isDestroying) {
        return
      }

      const focusedElement = $(':focus')[0]
      const filterElement = $('.frost-select-dropdown .frost-text-input')[0]

      // If focus has moved to filter in select dropdown then keep select
      // visually focused and open
      if (filterElement && focusedElement === filterElement) {
        return
      }

      const isFocused = this.get('focused')
      const onBlur = this.get('onBlur')

      this.setProperties({
        focused: false,
        opened: false
      })

      if (typeOf(onBlur) === 'function' && isFocused) {
        this.get('onBlur')()
      }
    })
    /* eslint-enable complexity */
  }),

  // == Lifecycle Hooks =======================================================

  didInsertElement () {
    this._super(...arguments)

    // We need jQuery instance of components root DOM node to hand off to
    // dropdown so it can position itself properly relative to the select
    this.set('$element', this.$())

    // If autofocus and nothing else has focus, focus on select
    if (this.get('autofocus') && $(':focus').length === 0) {
      this.$().focus()
    }
  },

  didReceiveAttrs () {
    this._super(...arguments)

    const props = {}

    let newSelectedValue = this.get('selectedValue')
    let oldSelectedValue = this.get('_oldSelectedValue')

    // If user provided a new selected value and it doesn't match the internal
    // selected value then update internal selected value
    if (
      !compareSelectedValues(newSelectedValue, oldSelectedValue) &&
      !compareSelectedValues(newSelectedValue, this.get('internalSelectedValue'))
    ) {
      props.internalSelectedValue = newSelectedValue
    }

    if (Object.keys(props).length !== 0) {
      this.setProperties(props)
    }

    this.set('_oldSelectedValue', newSelectedValue)
  },

  // == Actions ===============================================================

  actions: {
    closeDropDown () {
      const filter = ''
      this.setProperties({
        filter,
        opened: false
      })

      this.triggerFilterInput(filter)

      // We need to make sure focus goes back to select since it is on the
      // filter text input while the dropdown is open
      this.$().focus()
    },

    filterInput (e) {
      this.triggerFilterInput(e.target.value)
    },

    selectItem (selectedValue) {
      this.selectItem(selectedValue)
    }
  }
})


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean class="org.socraticgrid.hl7.services.eps.internal.model.TransientTopic"
		name="rootTopic" id="rootTopic">
		<property name="subTopics">
			<map>
				<entry key="Test Topic">
					<ref bean="TestTopicBean" />
				</entry>
			</map>
		</property>
	</bean>

	<bean name="TestTopicBean" id="TestTopicBean"
		class="org.socraticgrid.hl7.services.eps.internal.model.TransientTopic">
		<property name="parentTopic" ref="rootTopic" />
		<property name="topic">
			<bean class="org.socraticgrid.hl7.services.eps.model.Topic">
				<property name="name" value="Test Topic" />
				<property name="optionsList">
					<bean class="org.socraticgrid.hl7.services.eps.model.Options">
						<property name="access" value="Open"></property>
						<property name="durability" value="Transient"></property>
					</bean>
				</property>
				<property name="subscriptionsList">
					<list>
						<ref bean="InternalSubscription"/>
					</list>
				</property>
			</bean>
		</property>
	</bean>

</beans>


text:
/**
 * @author yomotsu / http://yomotsu.net
 * ported from http://webgl-fire.appspot.com/html/fire.html
 *
 * https://www.youtube.com/watch?v=jKRHmQmduDI
 * https://graphics.ethz.ch/teaching/former/imagesynthesis_06/miniprojects/p3/
 * https://www.iusb.edu/math-compsci/_prior-thesis/YVanzine_thesis.pdf
 * modified by
 * @author dahaupt, dahaupt@uos.de
 */

( function (root, factory) {

    if (typeof define === 'function' && define.amd) {

        // AMD. Register as an anonymous module.
        define([], factory);

    } else if (typeof module === 'object' && module.exports) {

        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory();

    } else {

        // Browser globals (root is window)
        root.VolumetricFire = factory(root);

    }

}(this, function () {

    'use strict';

    var vs = [

        'attribute vec3 position;',
        'attribute vec3 tex;',
        'uniform mat4 projectionMatrix;',
        'uniform mat4 modelViewMatrix;',

        'varying vec3 texOut;',

        'void main ( void ) {',

        'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0 );',
        'texOut = tex;',

        '}',

    ].join('\n');

    var fs = [
        'precision highp float;',
        'uniform vec3 fogColor;',
        'uniform float fogDensity;',

        // Modified Blum Blum Shub pseudo-random number generator.
        'vec2 mBBS( vec2 val, float modulus ) {',

        'val = mod( val, modulus ); // For numerical consistancy.',
        'return mod(val * val, modulus);',

        '}',

        // Pregenerated noise texture.
        'uniform sampler2D nzw;',
        'const float modulus = 61.0;  // Value used in pregenerated noise texture.',

        /**
         * Modified noise function.
         * @see http://www.csee.umbc.edu/~olano/papers/index.html#mNoise
         **/
        'float mnoise ( vec3 pos ) {',

        'float intArg = floor( pos.z );',
        'float fracArg = fract( pos.z );',
        'vec2 hash = mBBS( intArg * 3.0 + vec2( 0, 3 ), modulus );',
        'vec4 g = vec4 (',
        'texture2D( nzw, vec2( pos.x, pos.y + hash.x ) / modulus ).xy,',
        'texture2D( nzw, vec2( pos.x, pos.y + hash.y ) / modulus ).xy',
        ') * 2.0 - 1.0;',

        'return mix(',
        'g.x + g.y * fracArg,',
        'g.z + g.w * ( fracArg - 1.0 ),',
        'smoothstep( 0.0, 1.0, fracArg )',
        ');',

        '}',

        'const int octives = 4;',
        'const float lacunarity = 2.0;',
        'const float gain = 0.5;',

        /**
         * Adds multiple octives of noise together.
         **/
        'float turbulence( vec3 pos ) {',

        'float sum  = 0.0;',
        'float freq = 1.0;',
        'float amp  = 1.0;',

        'for ( int i = 0; i < 4; i++ ) {',

        'sum += abs( mnoise( pos * freq ) ) * amp;',
        'freq *= lacunarity;',
        'amp *= gain;',

        '}',

        'return sum;',

        '}',

        'const float magnatude = 1.3;',
        'uniform float time;',
        'uniform sampler2D fireProfile;',

        /**
         * Samples the fire.
         *
         * @param loc the normalized location (0.0-1.0) to sample the fire
         * @param scale the 'size' of the fire in world space and time
         **/
        'vec4 sampleFire( vec3 loc, vec4 scale ) {',

        // Convert xz to [-1.0, 1.0] range.
        'loc.xz = loc.xz * 2.0 - 1.0;',

        // Convert to (radius, height) to sample fire profile texture.
        'vec2 st = vec2( sqrt( dot( loc.xz, loc.xz ) ), loc.y );',

        // Convert loc to 'noise' space
        'loc.y -= time * scale.w; // Scrolling noise upwards over time.',
        'loc *= scale.xyz; // Scaling noise space.',

        // Offsetting vertial texture lookup.
        // We scale this by the sqrt of the height so that things are
        // relatively stable at the base of the fire and volital at the
        // top.
        'float offset = sqrt( st.y ) * magnatude * turbulence( loc );',
        'st.y += offset;',

        // TODO: Update fireProfile texture to have a black row of pixels.
        'if ( st.y > 1.0 ) {',

        'return vec4( 0, 0, 0, 1 );',

        '}',

        'vec4 result = texture2D( fireProfile, st );',

        // Fading out bottom so slice clipping isnt obvious
        'if ( st.y < 0.1 ) {',

        'result *= st.y / 0.1;',

        '}',

        'return result;',

        '}',

        'varying vec3 texOut;',

        'void main( void ) {',

        // Mapping texture coordinate to -1 => 1 for xy, 0=> 1 for y
        'vec3 color = sampleFire( texOut, vec4( 1.0, 2.0, 1.0, .5 ) ).xyz;',

        // fog support
        'float depth = (gl_FragCoord.z / gl_FragCoord.w)+10.0;',
        'depth = depth * fogDensity * 80.0;',
        'gl_FragColor = vec4( (color * 1.5 * 25.0 )/depth, 1.0/depth*80.0 );',
        '}',

    ].join('\n');

    var initMaterial = (function () {

        var material;
        var textureLoader = new THREE.TextureLoader();

        return function () {

            if (!!material) {
                return material;
            }

            // TODO
            // Canvas2D で noise 画像を作る
            var nzw = textureLoader.load(VolumetricFire.texturePath + 'nzw.png');
            nzw.wrapS = THREE.RepeatWrapping;
            nzw.wrapT = THREE.RepeatWrapping;
            nzw.magFilter = THREE.LinearFilter;
            nzw.minFilter = THREE.LinearFilter;

            var fireProfile = textureLoader.load(VolumetricFire.texturePath + 'firetex.png');
            fireProfile.wrapS = THREE.ClampToEdgeWrapping;
            fireProfile.wrapT = THREE.ClampToEdgeWrapping;
            fireProfile.magFilter = THREE.LinearFilter;
            fireProfile.minFilter = THREE.LinearFilter;

            var uniforms = {
                nzw: {
                    type: 't',
                    value: nzw
                },
                fireProfile: {
                    type: 't',
                    value: fireProfile
                },
                time: {
                    type: 'f',
                    value: 1.0
                },
                fogColor: {type: "c", value: scene.fog.color},
                fogDensity: {type: "f", value: scene.fog.density},
            };

            material = new THREE.RawShaderMaterial({
                vertexShader: vs,
                fragmentShader: fs,
                uniforms: uniforms,
                side: THREE.DoubleSide,
                blending: THREE.AdditiveBlending,
                depthWrite: false, // prevents artifacts with smoke
                transparent: true,
                fog: true // enables fog
            });

            return material;

        };

    })();

    var cornerNeighbors = [
        [1, 2, 4],
        [0, 5, 3],
        [0, 3, 6],
        [1, 7, 2],
        [0, 6, 5],
        [1, 4, 7],
        [2, 7, 4],
        [3, 5, 6],
    ];

    var incomingEdges = [
        [-1, 2, 4, -1, 1, -1, -1, -1],
        [5, -1, -1, 0, -1, 3, -1, -1],
        [3, -1, -1, 6, -1, -1, 0, -1],
        [-1, 7, 1, -1, -1, -1, -1, 2],
        [6, -1, -1, -1, -1, 0, 5, -1],
        [-1, 4, -1, -1, 7, -1, -1, 1],
        [-1, -1, 7, -1, 2, -1, -1, 4],
        [-1, -1, -1, 5, -1, 6, 3, -1],
    ];

    var VolumetricFire = function (width, height, depth, sliceSpacing, camera) {

        this.camera = camera;

        this._sliceSpacing = sliceSpacing;
        this._width = width;
        this._height = height;
        this._depth = depth;

        var widthHalf = width * 0.5;
        var heightHalf = height * 0.5;
        var depthHalf = depth * 0.5;

        this._posCorners = [
            new THREE.Vector3(-widthHalf, -heightHalf, -depthHalf),
            new THREE.Vector3(widthHalf, -heightHalf, -depthHalf),
            new THREE.Vector3(-widthHalf, heightHalf, -depthHalf),
            new THREE.Vector3(widthHalf, heightHalf, -depthHalf),
            new THREE.Vector3(-widthHalf, -heightHalf, depthHalf),
            new THREE.Vector3(widthHalf, -heightHalf, depthHalf),
            new THREE.Vector3(-widthHalf, heightHalf, depthHalf),
            new THREE.Vector3(widthHalf, heightHalf, depthHalf)
        ];
        this._texCorners = [
            new THREE.Vector3(0, 0, 0),
            new THREE.Vector3(1, 0, 0),
            new THREE.Vector3(0, 1, 0),
            new THREE.Vector3(1, 1, 0),
            new THREE.Vector3(0, 0, 1),
            new THREE.Vector3(1, 0, 1),
            new THREE.Vector3(0, 1, 1),
            new THREE.Vector3(1, 1, 1)
        ];

        this._viewVector = new THREE.Vector3();

        // TODO
        // still did not figure out, how many vertexes should be...
        // three.jsでは可変にできない、ひとまず多めに用意

        var index = new Uint16Array(( width + height + depth ) * 30);
        var position = new Float32Array(( width + height + depth ) * 30 * 3);
        var tex = new Float32Array(( width + height + depth ) * 30 * 3);

        var geometry = new THREE.BufferGeometry();
        geometry.dynamic = true;
        geometry.setIndex(new THREE.BufferAttribute(index, 1));
        geometry.addAttribute('position', new THREE.BufferAttribute(position, 3));
        geometry.addAttribute('tex', new THREE.BufferAttribute(tex, 3));

        var material = initMaterial();

        this.mesh = new THREE.Mesh(
            geometry,
            material
        );

        this.mesh.updateMatrixWorld();

    }

    VolumetricFire.prototype.update = function (elapsed) {

        this.updateViewVector();
        this.slice();
        this.updateGeometry();
        this.mesh.material.uniforms.time.value = elapsed;

    }

    VolumetricFire.prototype.updateGeometry = function () {

        this.mesh.geometry.index.array.set(this._indexes);
        this.mesh.geometry.attributes.position.array.set(this._points);
        this.mesh.geometry.attributes.tex.array.set(this._texCoords);

        this.mesh.geometry.index.needsUpdate = true;
        this.mesh.geometry.attributes.position.needsUpdate = true;
        this.mesh.geometry.attributes.tex.needsUpdate = true;

    }

    VolumetricFire.prototype.updateViewVector = function () {

        // TODO
        // MVMatrixが前回と同じなら、アップデートしないようにする
        //
        // つまり、カメラの位置とオブジェクトの位置に変化なければ
        // アップデートしないようにする

        var modelViewMatrix = new THREE.Matrix4();

        modelViewMatrix.multiplyMatrices(
            this.camera.matrixWorldInverse,
            this.mesh.matrixWorld
        );

        this._viewVector.set(
            -modelViewMatrix.elements[2],
            -modelViewMatrix.elements[6],
            -modelViewMatrix.elements[10]
        ).normalize();

    };

    VolumetricFire.prototype.slice = function () {

        this._points = [];
        this._texCoords = [];
        this._indexes = [];

        var i;
        var cornerDistance0 = this._posCorners[0].dot(this._viewVector);

        var cornerDistance = [cornerDistance0];
        var maxCorner = 0;
        var minDistance = cornerDistance0;
        var maxDistance = cornerDistance0;

        for (i = 1; i < 8; i = ( i + 1 ) | 0) {

            cornerDistance[i] = this._posCorners[i].dot(this._viewVector);

            if (cornerDistance[i] > maxDistance) {

                maxCorner = i;
                maxDistance = cornerDistance[i];

            }

            if (cornerDistance[i] < minDistance) {

                minDistance = cornerDistance[i];

            }

        }

        // Aligning slices
        var sliceDistance = Math.floor(maxDistance / this._sliceSpacing) * this._sliceSpacing;

        var activeEdges = [];
        var firstEdge = 0;
        var nextEdge = 0;
        var expirations = new PriorityQueue();

        var createEdge = function (startIndex, endIndex) {

            if (nextEdge >= 12) {
                return undefined;
            }

            var activeEdge = {
                expired: false,
                startIndex: startIndex,
                endIndex: endIndex,
                deltaPos: new THREE.Vector3(),
                deltaTex: new THREE.Vector3(),
                pos: new THREE.Vector3(),
                tex: new THREE.Vector3(),
                cur: nextEdge
            }

            var range = cornerDistance[startIndex] - cornerDistance[endIndex];

            if (range !== 0.0) {

                var irange = 1.0 / range;

                activeEdge.deltaPos.subVectors(
                    this._posCorners[endIndex],
                    this._posCorners[startIndex]
                ).multiplyScalar(irange);

                activeEdge.deltaTex.subVectors(
                    this._texCorners[endIndex],
                    this._texCorners[startIndex]
                ).multiplyScalar(irange);

                var step = cornerDistance[startIndex] - sliceDistance;

                activeEdge.pos.addVectors(
                    activeEdge.deltaPos.clone().multiplyScalar(step),
                    this._posCorners[startIndex]
                );

                activeEdge.tex.addVectors(
                    activeEdge.deltaTex.clone().multiplyScalar(step),
                    this._texCorners[startIndex]
                );

                activeEdge.deltaPos.multiplyScalar(this._sliceSpacing);
                activeEdge.deltaTex.multiplyScalar(this._sliceSpacing);

            }

            expirations.push(activeEdge, cornerDistance[endIndex]);
            activeEdges[nextEdge++] = activeEdge;
            return activeEdge;

        };

        for (i = 0; i < 3; i = ( i + 1 ) | 0) {

            var activeEdge = createEdge.call(this, maxCorner, cornerNeighbors[maxCorner][i]);
            activeEdge.prev = ( i + 2 ) % 3;
            activeEdge.next = ( i + 1 ) % 3;

        }

        var nextIndex = 0;

        while (sliceDistance > minDistance) {

            while (expirations.top().priority >= sliceDistance) {

                var edge = expirations.pop().object;

                if (edge.expired) {
                    continue;
                }

                if (
                    edge.endIndex !== activeEdges[edge.prev].endIndex &&
                    edge.endIndex !== activeEdges[edge.next].endIndex
                ) {

                    // split this edge.
                    edge.expired = true;

                    // create two new edges.
                    var activeEdge1 = createEdge.call(
                        this,
                        edge.endIndex,
                        incomingEdges[edge.endIndex][edge.startIndex]
                    );
                    activeEdge1.prev = edge.prev;
                    activeEdges[edge.prev].next = nextEdge - 1;
                    activeEdge1.next = nextEdge;

                    var activeEdge2 = createEdge.call(
                        this,
                        edge.endIndex,
                        incomingEdges[edge.endIndex][activeEdge1.endIndex]
                    );
                    activeEdge2.prev = nextEdge - 2;
                    activeEdge2.next = edge.next;
                    activeEdges[activeEdge2.next].prev = nextEdge - 1;
                    firstEdge = nextEdge - 1;

                } else {

                    // merge edge.
                    var prev;
                    var next;

                    if (edge.endIndex === activeEdges[edge.prev].endIndex) {

                        prev = activeEdges[edge.prev];
                        next = edge;

                    } else {

                        prev = edge;
                        next = activeEdges[edge.next];

                    }

                    prev.expired = true;
                    next.expired = true;

                    // make new edge
                    var activeEdge = createEdge.call(
                        this,
                        edge.endIndex,
                        incomingEdges[edge.endIndex][prev.startIndex]
                    );
                    activeEdge.prev = prev.prev;
                    activeEdges[activeEdge.prev].next = nextEdge - 1;
                    activeEdge.next = next.next;
                    activeEdges[activeEdge.next].prev = nextEdge - 1;
                    firstEdge = nextEdge - 1;

                }

            }

            var cur = firstEdge;
            var count = 0;

            do {

                ++count;
                var activeEdge = activeEdges[cur];
                this._points.push(
                    activeEdge.pos.x,
                    activeEdge.pos.y,
                    activeEdge.pos.z
                );
                this._texCoords.push(
                    activeEdge.tex.x,
                    activeEdge.tex.y,
                    activeEdge.tex.z
                );
                activeEdge.pos.add(activeEdge.deltaPos);
                activeEdge.tex.add(activeEdge.deltaTex);
                cur = activeEdge.next;

            } while (cur !== firstEdge);

            for (i = 2; i < count; i = ( i + 1 ) | 0) {

                this._indexes.push(
                    nextIndex,
                    nextIndex + i - 1,
                    nextIndex + i
                );

            }

            nextIndex += count;
            sliceDistance -= this._sliceSpacing;

        }

    };

    var PriorityQueue = function () {

        this.contents = [];
        this.sorted = false;

    };

    PriorityQueue.prototype = {

        sort: function () {

            this.contents.sort();
            this.sorted = true;

        },

        pop: function () {

            if (!this.sorted) {

                this.sort();

            }

            return this.contents.pop();

        },

        top: function () {

            if (!this.sorted) {

                this.sort();

            }

            return this.contents[this.contents.length - 1];

        },

        push: function (object, priority) {

            this.contents.push({object: object, priority: priority});
            this.sorted = false;

        }

    };

    return VolumetricFire;

}) );


text:
package GoMM

import (
	"testing"
)

func TestNet_IsSelfAddr(t *testing.T) {
	// t.Error("Not implemented.")
}


text:
<?php

namespace Event;

class Join {

    function __construct() { }

    function beforeroute() { }

    function get($f3) {
        header('Content-type: application/json');

        if($f3->exists('GET.idUser') && $f3->exists('GET.idEvent') && $f3->exists('GET.secret'))
        {
            $event = new \Event($f3);

            $idUser=intval($f3->get('GET.idUser'));
            $idEvent = intval($f3->get('GET.idEvent'));
            $secret = $f3->get('GET.secret');

            if($event->isPlaceAvailable($idEvent)) {
                if(!$event->isRegistered($idUser, $idEvent)) {
                    if($event->addPersonToEvent($idUser, $idEvent)) {
                        echo json_encode(array('code'=>200));
                    }
                    else
                        echo json_encode(array('code'=>400));//request failed
                }
                else
                    echo json_encode(array('code'=>507));//already signed up
            }
            else
                echo json_encode(array('code'=>506));//no place available
        }
        else
            echo json_encode(array('code'=>444));//missing
    }

    function put() { }
    function delete() { }

    function post($f3) {
        header('Content-type: application/json');

        if($f3->exists('POST.idUser') && $f3->exists('POST.idEvent') && $f3->exists('POST.secret'))
        {
            $event = new \Event($f3);

            $idUser=intval($f3->get('POST.idUser'));
            $idEvent = intval($f3->get('POST.idEvent'));
            $secret = $f3->get('POST.secret');

            if($event->isPlaceAvailable($idEvent)) {
                if(!$event->isRegistered($idUser, $idEvent)) {
                    if($event->addPersonToEvent($idUser, $idEvent)) {
                        echo json_encode(array('code'=>200));
                    }
                    else
                        echo json_encode(array('code'=>400));//request failed
                }
                else
                    echo json_encode(array('code'=>507));//already signed up
            }
            else
                echo json_encode(array('code'=>506));//no place available
        }
        else
            echo json_encode(array('code'=>444));//missing
    }

    function afterroute() { }

    function __destruct() { }
}
?>


text:
package sun.awt.X11;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class XCreateWindowParams extends HashMap {
    public XCreateWindowParams() {
    }
    public XCreateWindowParams(Object[] map) {
        init(map);
    }
    private void init(Object[] map) {
        if (map.length % 2 != 0) {
            throw new IllegalArgumentException("Map size should be devisible by two");
        }
        for (int i = 0; i < map.length; i += 2) {
            put(map[i], map[i+1]);
        }
    }

    public XCreateWindowParams putIfNull(Object key, Object value) {
        if (!containsKey(key)) {
            put(key, value);
        }
        return this;
    }
    public XCreateWindowParams putIfNull(Object key, int value) {
        if (!containsKey(key)) {
            put(key, Integer.valueOf(value));
        }
        return this;
    }
    public XCreateWindowParams putIfNull(Object key, long value) {
        if (!containsKey(key)) {
            put(key, Long.valueOf(value));
        }
        return this;
    }

    public XCreateWindowParams add(Object key, Object value) {
        put(key, value);
        return this;
    }
    public XCreateWindowParams add(Object key, int value) {
        put(key, Integer.valueOf(value));
        return this;
    }
    public XCreateWindowParams add(Object key, long value) {
        put(key, Long.valueOf(value));
        return this;
    }
    public XCreateWindowParams delete(Object key) {
        remove(key);
        return this;
    }
    public String toString() {
        StringBuffer buf = new StringBuffer();
        Iterator eIter = entrySet().iterator();
        while (eIter.hasNext()) {
            Map.Entry entry = (Map.Entry)eIter.next();
            buf.append(entry.getKey() + ": " + entry.getValue() + "\n");
        }
        return buf.toString();
    }

}


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

namespace Oldmansoft.Html.WebMan.Annotations
{
    /// <summary>
    /// 输入限制长度
    /// </summary>
    public class InputMaxLengthAttribute : ValidationAttribute
    {
        /// <summary>
        /// 长度
        /// </summary>
        public uint Length { get; set; }

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="length"></param>
        public InputMaxLengthAttribute(uint length)
        {
            Length = length;
        }

        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public override bool IsValid(object value)
        {
            if (value == null) return true;
            if (value is IList<string>)
            {
                foreach (var item in (value as IList<string>))
                {
                    if (item == null) continue;
                    if (item.Length > Length) return false;

                }
            }
            else if (value is string)
            {
                if ((value as string).Length > Length) return false;
            }
            return true;
        }
    }
}


text:
					<?php echo explode(',', $judul)[0]; ?>
					<?php echo explode(',', $judul)[1]; ?>

						<form action="<?php echo base_url('soal_akademik/view'); ?>" class="form-horizontal" method="post">

			              Bidang Soal

			                <select id='bidang_soal' name="bidang_soal" class="form-control" required>
			                	<option value="all">Semua Bidang Soal</option>
			                	<?php
			                		foreach ($bidang_soal as $b)
			                		{
			                			echo '<option value="'.$b->ID_BIDANG_SOAL.'">'.$b->NAMA_BIDANG_SOAL.'</option>';
			                		}
			                	?>
			                </select>

			              	<button type="submit" class="btn btn-primary">Tampilkan</button>

						</form>


text:
#include "../../idlib/precompiled.h"
#pragma hdrstop

#include "GEApp.h"
#include "GEInsertModifier.h"

rvGEInsertModifier::rvGEInsertModifier ( const char* name, idWindow* window, idWindow* parent, idWindow* before ) :
	rvGEModifier ( name, window )
{
	mParent  = parent;
	mBefore  = before;

	assert ( mParent );

	mUndoParent = window->GetParent ( );
	mUndoBefore = NULL;
	mUndoRect   = mWrapper->GetClientRect ( );
	mRect		= mWrapper->GetClientRect ( );

	// Find the child window the window being inserted is before
	if ( mUndoParent )
	{
		int				   index;
		rvGEWindowWrapper* pwrapper;

		pwrapper = rvGEWindowWrapper::GetWrapper ( mUndoParent );

		index = mUndoParent->GetChildIndex ( mWindow );

		if ( index + 1 < pwrapper->GetChildCount ( ) )
		{
			mUndoBefore = pwrapper->GetChild ( index + 1 );
		}
	}

	// Since rectangles are relative to the parent rectangle we need to figure
	// out the new x and y coordinate as if this window were a child
	rvGEWindowWrapper* parentWrapper;
	parentWrapper = rvGEWindowWrapper::GetWrapper ( mParent );
	mRect.x = mWrapper->GetScreenRect( )[0] - parentWrapper->GetScreenRect()[0];
	mRect.y = mWrapper->GetScreenRect( )[1] - parentWrapper->GetScreenRect()[1];
}

/*
================
rvGEInsertModifier::Apply

Apply the insert modifier by removing the child from its original parent and
inserting it as a child of the new parent
================
*/
bool rvGEInsertModifier::Apply ( void )
{
	if ( mUndoParent )
	{
		mUndoParent->RemoveChild ( mWindow );
	}

	mParent->InsertChild ( mWindow, mBefore );
	mWrapper->SetRect ( mRect );

	return true;
}

/*
================
rvGEInsertModifier::Undo

Undo the insert modifier by removing the window from the parent it was
added to and re-inserting it back into its original parent
================
*/
bool rvGEInsertModifier::Undo ( void )
{
	mParent->RemoveChild ( mWindow );

	if ( mUndoParent )
	{
		mUndoParent->InsertChild ( mWindow, mUndoBefore );
		mWrapper->SetRect ( mUndoRect );
	}

	return true;
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use app\models\User;

/* @var $this yii\web\View */
/* @var $model app\models\UserAddForm */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'username')->textInput(['maxlength' => 255]) ?>

    <?= $form->field($model, 'email')->textInput(['maxlength' => 255]) ?>

    <?php if (!$update): ?>
        <?= $form->field($model, 'password')->passwordInput() ?>
    <?php endif; ?>

    <?= $form->field($model, 'status')->radioList(User::getStatusOptions()) ?>

        <?= Html::submitButton($update ? 'Update' : 'Create', ['class' => 'btn btn-success']) ?>

    <?php ActiveForm::end(); ?>


text:
layout: post
title: Storify e Video dell'evento "Politiche dell'innovazione, terza missione e sviluppo del territorio"
date: 2015-01-18
feature-img: expostebari.jpg
video: https://www.streamago.tv/movie/93382/desktop-2015-01-19-17-41-17/iframe/
storify: //storify.com/SGInnovazione/politiche-dell-innovazione
categories:
- Innovazione
tags:
- #sgipuglia
- #openpuglia
- #innovazione
- #sgipuglia
status: publish
type: post
published: true
author: Giuseppe Zileni
email: giuseppe.zileni@gmail.com
twitter: http://www.twitter.com/gzileni
linkedin: http://it.linkedin.com/in/giuseppezileni/
---

Riviviamo lo storify, e la diretta streaming dell'evento Politiche dell'innovazione, terza missione e sviluppo del territorio presso l'Università di Bari.


text:
namespace sani {
	namespace rtti {
		Constructor::Constructor()
			: Invokable("INVALID"), type({ Type::Invalid }), _isDynamic(false), createInstance(nullptr) {

		}

		Constructor::Constructor(Type type, Signature signature, CreateInstance instanceFunc, bool isDynamic)
			: Invokable("constructor"), type(type), createInstance(instanceFunc), _isDynamic(isDynamic) {
			this->signature = signature;
		}

		bool Constructor::isValid() const {
			return createInstance != nullptr;
		}

		bool Constructor::isDynamic() const {
			return _isDynamic;
		}

		Type Constructor::getType() const {
			return type;
		}

		Object Constructor::invoke(Arguments& args) const {
			return createInstance(args);
		}

		const Constructor& Constructor::invalid(void) {
			static Constructor instance;
			return instance;
		}

	}
}


text:
{{vm.heading}}

{{vm.subtext}}

                <button class="btn btn-xl btn-danger margin-large-right" ng-click="vm.refresh()">Refresh</button>


text:
/**
 *   ____    __    ____  ____  ____,,___     ____  __  __  ____
 *  (  _ \  /__\  (_   )(_  _)( ___)/ __)   (  _ \(  )(  )(  _ \           Read
 *   )   / /(__)\  / /_  _)(_  )__) \__ \    )___/ )(__)(  ) _ <     README.txt
 *  (_)\_)(__)(__)(____)(____)(____)(___/   (__)  (______)(____/    LICENSE.txt
 */
package razie.wiki

import com.google.inject.Inject
import controllers.{NoWikiAuthorization, WikiAuthorization}
import razie.db.RazMongo
import razie.wiki.model._
import razie.wiki.util.{AuthService, NoAuthService}

/** central point of customization - aka service registry
  *
  * todo use some proper injection pattern - this is not MT-safe
  *
  * right now this is setup in Global and different Module(s), upon startup
  */
object Services {

  @Inject() var auth: AuthService[WikiUser] = NoAuthService
  @Inject() var config: WikiConfig = new SampleConfig
  @Inject() var wikiAuth: WikiAuthorization = new NoWikiAuthorization

  // this is only used for signed scripts - unsafe scripts are not ran here
  var runScriptImpl : (String, String, Option[WikiEntry], Option[WikiUser], Map[String, String], Boolean) => String =
    (script: String, lang:String, page: Option[WikiEntry], user: Option[WikiUser], query: Map[String, String], devMode:Boolean) =>
      "TODO customize scripster"

  var mkReactor : (String, List[Reactor], Option[WikiEntry]) => Reactor = { (realm, fallBack, we)=>
//    new ReactorImpl(realm, fallBack, we)
     throw new IllegalArgumentException("Services.mkReactor implementation needed")
  }

  /** run the given script in the context of the given page and user as well as the query map */
  def runScript (s: String, lang:String, page: Option[WikiEntry], user: Option[WikiUser], query: Map[String, String], devMode:Boolean=false): String =
    runScriptImpl(s,lang, page,user,query,devMode)

  def noInitSample = {
    /** connect to your database, with your connection properties, clustered or not etc */
    import com.mongodb.casbah.MongoConnection
    RazMongo.setInstance {
      MongoConnection("") apply ("")
    }
  }

  /** is this website trusted? if not links will have a "exit" warning */
  var isSiteTrusted : (String,String) => Boolean = {(r,s)=>false }

  /** initialize the event processor */
  def initCqrs (al:EventProcessor) = BasicServices.initCqrs(al)

  /** CQRS dispatcher */
  def ! (a: Any) = BasicServices ! a
}


text:
'use strict';

const URL     = require('url');
const express = require('express');
const router  = express.Router();
const Wechat  = require('../service/Wechat');

module.exports = exports = function () {

  // DEBUG
  router.all('/', (req, res, next) => {
    res.status(403).send('
403 Forbidden
').end();
  });

  router.get('/api/admin/clearQuota', require('../controller/admin/api').clearQuota);

  // 微信
  router.get('/api/wechat/access', require('../controller/wechat/index').wechatValidation);
  router.post('/api/wechat/access', require('../controller/wechat/filter').preventDuplicate);
  router.post('/api/wechat/access', require('../controller/wechat/index').processWechatEvent);
  router.all('/api/wechat/updateAccessToken', require('../controller/wechat/index').updateAccessToken);

  // 普通权限
  router.all('/auth/signIn', require('../controller/auth/view').signIn);
  router.all('/auth/signUp', require('../controller/auth/view').signUp);
  router.all('/auth/signOut', require('../controller/auth/view').signOut);

  router.post('/api/auth/signIn', require('../controller/auth/api').signIn);
  router.post('/api/auth/signUp', require('../controller/auth/api').signUp);

  router.get('/api/qiniu/uptoken'     , require('../controller/qiniu/uptoken').get);
  router.get('/api/qiniu/downloadUrl' , require('../controller/qiniu/downloadUrl').get);

  router.get('/asset/:key', require('../controller/asset/image').view);

  // 运营权限
  router.all('/admin*', ensureAuthenticated);
  router.all('/admin', require('../controller/admin/view').index);
  // 控制台
  router.all('/admin/dashboard', require('../controller/admin/dashboard/view').index);
  // 扫码返图
  router.all('/admin/activity', require('../controller/admin/activity/view').index);
  router.all('/admin/activity/:id/asset', require('../controller/admin/activity/asset/view').index);
  // 图片素材管理
  router.all('/admin/material/image', require('../controller/admin/material/view').image);
  router.all('/admin/material/image/preview', require('../controller/admin/material/view').preview);
  // 自定义菜单管理
  router.all('/admin/menu', require('../controller/admin/menu/view').index);
  // 回复队列管理
  router.all('/admin/replyQueue', require('../controller/admin/replyQueue/view').index);
  // 关注回复管理
  router.all('/admin/subscribeReply', require('../controller/admin/subscribeReply/view').index);
  // 订阅者管理
  router.all('/admin/subscriber', require('../controller/admin/subscriber/view').index);
  // 客服消息群发
  router.all('/admin/customGroupSend', require('../controller/admin/customGroupSend/view').index);
  router.all('/admin/customGroupSend/:id/log', require('../controller/admin/customGroupSend/view').log);
  // 模板消息群发
  router.all('/admin/templateGroupSend', require('../controller/admin/templateGroupSend/view').index);
  router.all('/admin/templateGroupSend/:id/log', require('../controller/admin/templateGroupSend/view').log);
  // 邀请任务管理
  router.all('/admin/invitationTask', require('../controller/admin/invitationTask/view').index);
  router.all('/admin/invitationTask/create', require('../controller/admin/invitationTask/view').create);
  router.all('/admin/invitationTask/modify/:id', require('../controller/admin/invitationTask/view').modify);
  router.all('/admin/invitationTask/cardList/:id', require('../controller/admin/invitationTask/view').cardList);
  // router.all('/admin/invitationTask/settings', require('../controller/admin/invitationTask/view').settings);

  router.all('/api/admin*', ensureAuthenticated);
  // 控制台
  router.all('/api/admin/dashboard/subscribe', require('../controller/admin/dashboard/api').subscribe);
  // 扫码返图
  router.post('/api/admin/activity', require('../controller/admin/activity/api').post);
  router.put('/api/admin/activity/:id', require('../controller/admin/activity/api').put);
  router.delete('/api/admin/activity/:id', require('../controller/admin/activity/api').delete);
  router.get('/api/admin/activity/:id/stat', require('../controller/admin/activity/api').getStat);

  router.post('/api/admin/asset', require('../controller/admin/activity/asset/api').post);
  router.put('/api/admin/asset/:id', require('../controller/admin/activity/asset/api').put);
  router.delete('/api/admin/asset/:id', require('../controller/admin/activity/asset/api').delete);
  // 图片素材管理
  router.get('/api/admin/material/image', require('../controller/admin/material/api').getImage);
  router.post('/api/admin/material', require('../controller/admin/material/api').post);
  router.delete('/api/admin/material/:mediaId', require('../controller/admin/material/api').delete);
  // 自定义菜单管理
  router.get('/api/admin/menu', require('../controller/admin/menu/api').get);
  router.put('/api/admin/menu', require('../controller/admin/menu/api').put);
  router.delete('/api/admin/menu', require('../controller/admin/menu/api').delete);
  // 回复队列管理
  router.get('/api/admin/replyQueue', require('../controller/admin/replyQueue/api').get);
  router.post('/api/admin/replyQueue', require('../controller/admin/replyQueue/api').post);
  router.get('/api/admin/replyQueue/:id', require('../controller/admin/replyQueue/api').getById);
  router.put('/api/admin/replyQueue/:id', require('../controller/admin/replyQueue/api').put);
  router.delete('/api/admin/replyQueue/:id', require('../controller/admin/replyQueue/api').delete);
  // 订阅者管理
  router.post('/api/admin/subscriber/sync', require('../controller/admin/subscriber/api').sync);
  // 关注定时回复
  router.post('/api/admin/subscribeReply', require('../controller/admin/subscribeReply/api').post);
  router.get('/api/admin/subscribeReply/:id', require('../controller/admin/subscribeReply/api').get);
  router.put('/api/admin/subscribeReply/:id', require('../controller/admin/subscribeReply/api').put);
  router.delete('/api/admin/subscribeReply/:id', require('../controller/admin/subscribeReply/api').delete);
  // 客服消息群发
  router.post('/api/admin/customGroupSend', require('../controller/admin/customGroupSend/api').post);
  router.get('/api/admin/customGroupSend/:id', require('../controller/admin/customGroupSend/api').get);
  router.post('/api/admin/customGroupSend/:id/send', require('../controller/admin/customGroupSend/api').send);
  router.put('/api/admin/customGroupSend/:id', require('../controller/admin/customGroupSend/api').put);
  router.delete('/api/admin/customGroupSend/:id', require('../controller/admin/customGroupSend/api').delete);
  // 模板消息群发
  router.post('/api/admin/templateGroupSend', require('../controller/admin/templateGroupSend/api').post);
  router.get('/api/admin/templateGroupSend/:id', require('../controller/admin/templateGroupSend/api').get);
  router.post('/api/admin/templateGroupSend/:id/send', require('../controller/admin/templateGroupSend/api').send);
  router.put('/api/admin/templateGroupSend/:id', require('../controller/admin/templateGroupSend/api').put);
  router.delete('/api/admin/templateGroupSend/:id', require('../controller/admin/templateGroupSend/api').delete);
  // 模板消息
  router.get('/api/admin/messageTemplate', require('../controller/admin/messageTemplate/api').getList);
  // 邀请任务管理
  router.get('/api/admin/invitationTask', require('../controller/admin/invitationTask/api').get);
  router.post('/api/admin/invitationTask', require('../controller/admin/invitationTask/api').post);
  router.get('/api/admin/invitationTask/:id', require('../controller/admin/invitationTask/api').getById);
  router.put('/api/admin/invitationTask/:id', require('../controller/admin/invitationTask/api').put);
  router.delete('/api/admin/invitationTask/:id', require('../controller/admin/invitationTask/api').delete);

  // 管理员权限
  router.all('/root*', ensureAuthenticated);
  router.all('/root*', ensureAdmin);
  router.all('/root/user', require('../controller/root/user/view').index);

  router.all('/api/root*', ensureAdmin);
  router.post('/api/root/user', require('../controller/root/user/api').post);
  router.put('/api/root/user/:id', require('../controller/root/user/api').put);
  router.delete('/api/root/user/:id', require('../controller/root/user/api').delete);

  // 微信活动链接
  router.all('/wechat/*', ensureWechat);
  router.all('/wechat/*', ensureOpenId);
  router.get('/wechat/activity/:id/participate', require('../controller/wechat/activity/participate').view);

  // 错误页面
  router.all('/wechat-404.html', require('../controller/error/wechat-404').view);
  router.all('/wechat-500.html', require('../controller/error/wechat-500').view);
  router.all('/wechat-only.html', require('../controller/error/wechat-only').view);

  return router;
};

// 微信客户端检查
function ensureWechat(req, res, next) {
  let ua = req.get('User-Agent');
  if(ua && ua.indexOf('MicroMessenger') >= 0) {
    return next();
  } else {
    res.redirect(req.app.config.assetHost + '/wechat-only.html');
  }
}

// openId检查
function ensureOpenId(req, res, next) {
  let code = req.query['code'];
  if(code) {
    return Wechat.getOpenIdByCode(code).then((openId) => {
      req.query['openId'] = openId;
      next();
    }).catch((err) => {
      console.error(err, err.stack);
      res.status(500);
    });
  }
  let pathname = URL.parse(req.url).pathname;
  let currentUrl = URL.format({
    protocol: req.protocol,
    host: req.get('host').replace(':80', ''),
    port: req.get('port'),
    pathname
  });
  let redirectUrl = Wechat.getBaseAuthRedirectUrl(currentUrl);
  res.redirect(redirectUrl);
}

// 登录检查
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.set('X-Auth-Required', 'true');
  req.session.returnUrl = req.originalUrl;
  res.redirect('/auth/signIn');
}

// 管理权限检查
function ensureAdmin(req, res, next) {
  if (req.user.canPlayRoleOf('admin')) {
    return next();
  }
  res.status(403).send('您没有权限执行该操作').end();
}


text:
$(document).ready(function() {
	$('#tweet').click(function() {
		bootbox.prompt('Écrire un nouveau Tweet', function(result) {
			if (result !== null && result.length > 0) {
				data = 'status=' + encodeURI(result);

				$.ajax({
					url: 'Touiteure.php?action=tweet',
					type: 'POST',
					data: data,
					error: function(data) {
						alert(data);
					}
				});
			}
		});
	});

	$('#homeload').click(function() {
		var smallestIdTweet = $('.well .row:last');
		var smallestId = (smallestIdTweet.length) ? smallestIdTweet.attr('id') : '';

		$.ajax({
			url: 'TouiteureAjaxDispatcher.php?action=load_home_tweets',
			type: 'POST',
			data: 'id=' + smallestId,
			success: function(data) {
				smallestIdTweet.replaceWith(data);
				$('.sep:last').remove();
			},
			error: function(data) {
				alert(data);
			}
		});
	});

	$('#profileload').click(function() {
		var screenName = $('.lead').attr('id');
		var smallestIdTweet = $('.well .row:last');
		var smallestId = (smallestIdTweet.length) ? smallestIdTweet.attr('id') : '';

		$.ajax({
			url: 'TouiteureAjaxDispatcher.php?action=load_profile_tweets',
			type: 'POST',
			data: 'screen_name=' + screenName + '&id=' + smallestId,
			success: function(data) {
				smallestIdTweet.replaceWith(data);
				$('.sep:last').remove();
			},
			error: function(data) {
				alert(data);
			}
		});
	});
});


text:
package org.spongepowered.api.data.manipulator.immutable.entity;

import org.spongepowered.api.data.manipulator.ImmutableDataManipulator;
import org.spongepowered.api.data.manipulator.mutable.entity.FallDistanceData;
import org.spongepowered.api.data.value.immutable.ImmutableBoundedValue;
import org.spongepowered.api.data.value.immutable.ImmutableValue;

/**
 * A {@link ImmutableDataManipulator} that represents the distance an entity has fallen
 * in the world. Usually the higher this value, the more damage that inflicted
 * when the entity reaches the ground.
 */
public interface ImmutableFallDistanceData extends ImmutableDataManipulator<ImmutableFallDistanceData, FallDistanceData> {

    /**
     * Gets the {@link ImmutableValue} for the current fall distance.
     * @return The value for the fall distance
     */
    ImmutableBoundedValue<Float> fallDistance();

}


text:
package otto

import (
	"fmt"
)

// RegExp

func builtinRegExp(call FunctionCall) Value {
	pattern := call.Argument(0)
	flags := call.Argument(1)
	if object := pattern._object(); object != nil {
		if object.class == "RegExp" && flags.IsUndefined() {
			return pattern
		}
	}
	return toValue_object(call.runtime.newRegExp(pattern, flags))
}

func builtinNewRegExp(self *_object, argumentList []Value) Value {
	return toValue_object(self.runtime.newRegExp(
		valueOfArrayIndex(argumentList, 0),
		valueOfArrayIndex(argumentList, 1),
	))
}

func builtinRegExp_toString(call FunctionCall) Value {
	thisObject := call.thisObject()
	source := thisObject.get("source").string()
	flags := []byte{}
	if thisObject.get("global").bool() {
		flags = append(flags, 'g')
	}
	if thisObject.get("ignoreCase").bool() {
		flags = append(flags, 'i')
	}
	if thisObject.get("multiline").bool() {
		flags = append(flags, 'm')
	}
	return toValue_string(fmt.Sprintf("/%s/%s", source, flags))
}

func builtinRegExp_exec(call FunctionCall) Value {
	thisObject := call.thisObject()
	target := call.Argument(0).string()
	match, result := execRegExp(thisObject, target)
	if !match {
		return nullValue
	}
	return toValue_object(execResultToArray(call.runtime, target, result))
}

func builtinRegExp_test(call FunctionCall) Value {
	thisObject := call.thisObject()
	target := call.Argument(0).string()
	match, _ := execRegExp(thisObject, target)
	return toValue_bool(match)
}

func builtinRegExp_compile(call FunctionCall) Value {
	// This (useless) function is deprecated, but is here to provide some
	// semblance of compatibility.
	// Caveat emptor: it may not be around for long.
	return Value{}
}


text:
<%#
 Copyright 2013-2017 the original author or authors from the StackStack project.

 This file is part of the StackStack project, see http://www.jhipster.tech/
 for more information.

 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.
-%>
package <%=packageName%>.config.cassandra;

import io.github.jhipster.config.JHipsterConstants;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.cassandra.CassandraProperties;<% if (applicationType === 'gateway' && databaseType !== 'cassandra') { %>
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;<% } %>
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.util.StringUtils;

import com.codahale.metrics.MetricRegistry;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.ProtocolVersion;
import com.datastax.driver.core.QueryOptions;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.SocketOptions;
import com.datastax.driver.core.TupleType;
import com.datastax.driver.core.policies.LoadBalancingPolicy;
import com.datastax.driver.core.policies.ReconnectionPolicy;
import com.datastax.driver.core.policies.RetryPolicy;
import com.datastax.driver.extras.codecs.jdk8.InstantCodec;
import com.datastax.driver.extras.codecs.jdk8.LocalDateCodec;
import com.datastax.driver.extras.codecs.jdk8.ZonedDateTimeCodec;

@Configuration<% if (applicationType === 'gateway' && databaseType !== 'cassandra') { %>
@ConditionalOnProperty("jhipster.gateway.rate-limiting.enabled")<% } %>
@EnableConfigurationProperties(CassandraProperties.class)
@Profile({JHipsterConstants.SPRING_PROFILE_DEVELOPMENT, JHipsterConstants.SPRING_PROFILE_PRODUCTION})
public class CassandraConfiguration {

    @Value("${spring.data.cassandra.protocolVersion:V4}")
    private ProtocolVersion protocolVersion;

    @Autowired(required = false)
    MetricRegistry metricRegistry;

    private final Logger log = LoggerFactory.getLogger(CassandraConfiguration.class);

    @Bean
    public Cluster cluster(CassandraProperties properties) {
        Cluster.Builder builder = Cluster.builder()
                .withClusterName(properties.getClusterName())
                .withProtocolVersion(protocolVersion)
                .withPort(getPort(properties));

        if (properties.getUsername() != null) {
            builder.withCredentials(properties.getUsername(), properties.getPassword());
        }
        if (properties.getCompression() != null) {
            builder.withCompression(properties.getCompression());
        }
        if (properties.getLoadBalancingPolicy() != null) {
            LoadBalancingPolicy policy = instantiate(properties.getLoadBalancingPolicy());
            builder.withLoadBalancingPolicy(policy);
        }
        builder.withQueryOptions(getQueryOptions(properties));
        if (properties.getReconnectionPolicy() != null) {
            ReconnectionPolicy policy = instantiate(properties.getReconnectionPolicy());
            builder.withReconnectionPolicy(policy);
        }
        if (properties.getRetryPolicy() != null) {
            RetryPolicy policy = instantiate(properties.getRetryPolicy());
            builder.withRetryPolicy(policy);
        }
        builder.withSocketOptions(getSocketOptions(properties));
        if (properties.isSsl()) {
            builder.withSSL();
        }
        String points = properties.getContactPoints();
        builder.addContactPoints(StringUtils.commaDelimitedListToStringArray(points));

        Cluster cluster = builder.build();

        TupleType tupleType = cluster.getMetadata()
            .newTupleType(DataType.timestamp(), DataType.varchar());

        cluster.getConfiguration().getCodecRegistry()
                .register(LocalDateCodec.instance)
                .register(InstantCodec.instance)
                .register(new ZonedDateTimeCodec(tupleType));

        if (metricRegistry != null) {
            cluster.init();
            metricRegistry.registerAll(cluster.getMetrics().getRegistry());
        }

        return cluster;
    }

    protected int getPort(CassandraProperties properties) {
        return properties.getPort();
    }

    public static <T> T instantiate(Class<T> type) {
        return BeanUtils.instantiate(type);
    }

    private QueryOptions getQueryOptions(CassandraProperties properties) {
        QueryOptions options = new QueryOptions();
        if (properties.getConsistencyLevel() != null) {
            options.setConsistencyLevel(properties.getConsistencyLevel());
        }
        if (properties.getSerialConsistencyLevel() != null) {
            options.setSerialConsistencyLevel(properties.getSerialConsistencyLevel());
        }
        options.setFetchSize(properties.getFetchSize());
        return options;
    }

    private SocketOptions getSocketOptions(CassandraProperties properties) {
        SocketOptions options = new SocketOptions();
        options.setConnectTimeoutMillis(properties.getConnectTimeoutMillis());
        options.setReadTimeoutMillis(properties.getReadTimeoutMillis());
        return options;
    }

    @Bean(destroyMethod = "close")
    public Session session(CassandraProperties properties, Cluster cluster) {
        log.debug("Configuring Cassandra session");
        return StringUtils.hasText(properties.getKeyspaceName()) ? cluster.connect(properties.getKeyspaceName()) : cluster.connect();
    }
}