text:
package main

import (
	"fmt"
	"github.com/swpecht/GoMM"
	"time"
)

func main() {
	numIterations := 50
	headNode := "10.0.2.15:7946" // "130.211.122.241:7946"

	f := GoMM.ClientFactory{}
	client, err := GoMM.GetTCPClient(f)
	if err != nil {
		fmt.Println("Failed to create client", err.Error())
		return
	}

	client.Start()
	client.Join(headNode)

	client.WaitActive()
	// Check if first worker
	iter := 0
	if client.NumActiveMembers() > 1 {
		// If not, should be getting the iteration
		msg := <-client.BroadcastChannel
		iter = int(msg.FloatData[0])
	}

	id := client.GetId()
	numNodes := client.NumActiveMembers()
	start := time.Now()
	for i := iter; i < numIterations; i++ {
		oldId := id
		oldNum := numNodes

		UpdatePool(client, i)

		id = client.GetId()
		numNodes = client.NumActiveMembers()

		// Shuffle if update or first iteration
		if oldId != id || oldNum != numNodes || i == iter {
			// Need to reshuffle data
			Shuffle(id, numNodes, client)
		}
		DoIteration(id, numNodes, i, client)
	}
	elapsed := time.Since(start)
	fmt.Println("Benchmark took", elapsed, "for", numIterations-iter, "iterations on", numNodes, "nodes")
	fmt.Println("Average seconds per iteration:", elapsed.Seconds()/float64(numIterations-iter))
}

// Returns the current iteration
func UpdatePool(client *GoMM.Client, iter int) int {
	if client.NumMembers() != client.NumActiveMembers() {
		client.UpdateActiveMembers()
		// If client 0, sent the iteration broadcast to everyone
		if client.GetId() == 0 {
			client.Broadcast([]string{}, []float64{float64(iter)})
		}
		// Receive the iteration broadcast
		msg := <-client.BroadcastChannel
		iter = int(msg.FloatData[0])

	}
	fmt.Println("Doing UpdatePool barrier")
	client.Barrier()
	return iter
}

// Shuffles / distributes the data between all nods
func Shuffle(id, numNodes int, client *GoMM.Client) {
	// Do a barrier for worst case coordination
	fmt.Println("Doing Shuffle barrier")
	client.Barrier()
}

// Perform the actual iterations
func DoIteration(id, numNodes, iter int, client *GoMM.Client) {
	duration := time.Duration(500 / numNodes)
	time.Sleep(duration * time.Millisecond)
	// Assume worst case communications
	// client.Barrier()
	fmt.Printf("Iteration %v \n", iter)
}

redpajama_set_name: RedPajamaGithub


text:
"""

Copyright 2014 Sotera Defense Solutions, Inc.

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.

"""

import json

import tangelo
import datawake.util.dataconnector.factory as factory
from datawake.util.db import datawake_mysql as db
from datawake.util.graph import helper as graph_helper
from datawake.util.session.helper import is_in_session
from datawake.util.session.helper import has_team
from datawake.util.session.helper import has_domain
from datawake.util.session.helper import has_trail
from datawake.util.session import helper

"""

Serves graphs for the datawake forensic viewer.  Graph building is primailry done in datawake.util.graphs

"""

DEBUG = True

#
# Return the graph display options
#
@is_in_session
def listGraphs():
    graphs = dict(graphs=[
                                   'browse path',
                                   'browse path - with adjacent urls',
                                   'browse path - with adjacent urls min degree 2',
                                   'browse path - with adjacent phone #\'s',
                                   'browse path - with adjacent email #\'s',
                                   'browse path - with phone and email #\'s',
                                   'browse path - with bitcoin addresses',
                                   'browse path - with text selections',
                                   'browse path - with adjacent info',])

    return json.dumps(graphs)

#
# return all time stamps from the selected trail,users,org
# returns a dictionary of the form  {'min':0,'max':0,'data':[]}
#
@is_in_session
def getTimeWindow(users, trail=u'*'):
    org = helper.get_org()
    if trail == u'':
        trail = u'*'
    print 'getTimeWindow(', users, ',', trail, ')'
    if len(users) > 0:
        users = users.split(",")
    else:
        users = []
    return json.dumps(db.getTimeWindow(org, users, trail))

@is_in_session
def get_entities(trail_id):
    tangelo.log('Getting entities for trail: %s' % trail_id)
    entities = {}
    entityList = []
    urls = []
    rows = db.getBrowsePathUrls(trail_id)
    for row in rows:
        urls.append(row['url'])

    entity_data_connector = factory.get_entity_data_connector()
    results = entity_data_connector.get_extracted_entities_from_urls(urls)

    tangelo.log('Got entities')

    for result in results:
        for entityType in results[result]:
            for entityName in results[result][entityType]:
                if entityName in entities:
                    entities[entityName]['pages'] = entities[entityName]['pages'] + 1
                else:
                    entities[entityName] = {'type': entityType, 'pages':1}
    # TODO either figure out how how map the data or do this differently
    for entity in entities:
        entityList.append({'name': entity, 'type': entities[entity]['type'], 'pages': entities[entity]['pages']})
    return json.dumps(entityList)

@is_in_session
def get_links(domain_name, trail_name):
    tangelo.log('Getting links for %s:%s'%(domain_name,trail_name))
    results = db.get_prefetch_results(domain_name, trail_name)
    return json.dumps(results)

@is_in_session
def get_visited(trail_id):
    tangelo.log('Getting visited links for %s'%trail_id)
    results = db.getBrowsePathUrls(trail_id)
    return json.dumps(results)

@is_in_session
@has_team
@has_domain
@has_trail
@tangelo.types(trail_id=int,domain_id=int,team_id=int,startdate=int,enddate=int)
def getGraph(team_id,domain_id,trail_id,view, startdate=u'', enddate=u'', users=[]):

    tangelo.log('getGraph( )')
    tangelo.log(users)

    if view == 'browse path':
        graph = graph_helper.getBrowsePathEdges(trail_id,startdate, enddate, users)
        return json.dumps(graph_helper.processEdges(graph['edges'], graph['nodes']))

    if view == 'browse path - with adjacent urls':
        graph = graph_helper.getBrowsePathAndAdjacentWebsiteEdgesWithLimit(domain_id,trail_id, startdate, enddate, 1, users)
        return json.dumps(graph_helper.processEdges(graph['edges'], graph['nodes']))

    if view == 'browse path - with adjacent urls min degree 2':
        graph = graph_helper.getBrowsePathAndAdjacentWebsiteEdgesWithLimit(domain_id,trail_id, startdate, enddate, 2, users)
        return json.dumps(graph_helper.processEdges(graph['edges'], graph['nodes']))

    if view == 'browse path - with adjacent phone #\'s':
        graph = graph_helper.getBrowsePathAndAdjacentPhoneEdgesWithLimit(domain_id,trail_id, startdate, enddate, 1, users)
        return json.dumps(graph_helper.processEdges(graph['edges'], graph['nodes']))

    if view == 'browse path - with adjacent email #\'s':
        graph = graph_helper.getBrowsePathAndAdjacentEmailEdgesWithLimit(domain_id,trail_id, startdate, enddate, 1, users)
        return json.dumps(graph_helper.processEdges(graph['edges'], graph['nodes']))

    if view ==  'browse path - with phone and email #\'s':
        graph = graph_helper.getBrowsePathAndAdjacentEdgesWithLimit(domain_id,trail_id,startdate,enddate,['email','phone'],1,users)
        return json.dumps(graph_helper.processEdges(graph['edges'], graph['nodes']))

    if view == 'browse path - with adjacent info':
        graph = graph_helper.getBrowsePathAndAdjacentInfoEdges(domain_id,trail_id, startdate, enddate,1,users)
        return json.dumps(graph_helper.processEdges(graph['edges'], graph['nodes']))

    if view == 'browse path - with bitcoin addresses':
        graph = graph_helper.getBrowsePathAndAdjacentBitcoinEdgesWithLimit(domain_id,trail_id,startdate,enddate,1,users)
        return json.dumps(graph_helper.processEdges(graph['edges'], graph['nodes']))

    if view == 'OculusForensicRequest':
        rows = graph_helper.getOculusForensicGraph(org,startdate,enddate,userlist,trail,domain)
        return json.dumps(rows)

    if view == 'browse path - with text selections':
        graph = graph_helper.getBrowsePathWithTextSelections(trail_id, startdate, enddate,users)
        return json.dumps(graph_helper.processEdges(graph['edges'], graph['nodes']))

    return json.dumps(dict(nodes=[], links=[]))

get_actions = {
    'list': listGraphs,
}

post_actions = {
    'timewindow': getTimeWindow,
    'get': getGraph,
    'entities': get_entities,
    'links': get_links,
    'visited': get_visited
}

@tangelo.restful
def post(action, *args, **kwargs):
    post_data = json.loads(tangelo.request_body().read())

    def unknown(**kwargs):
        return tangelo.HTTPStatusCode(400, "invalid service call")

    return post_actions.get(action, unknown)(**post_data)

@tangelo.restful
def get(action, *args, **kwargs):
    def unknown(**kwargs):
        return tangelo.HTTPStatusCode(400, "invalid service call")

    return get_actions.get(action, unknown)(**kwargs)


text:
// Java Genetic Algorithm Library.
// Copyright (c) 2017 Franz Wilhelmstötter
//
// 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.
//
// Author:
//    Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)

using System;
using Jenetics.Internal.Util;

namespace Jenetics
{
    public class LinearRankSelector<TGene, TAllele> : ProbabilitySelectorBase<TGene, TAllele>
        where TGene : IGene<TGene>
        where TAllele : IComparable<TAllele>, IConvertible
    {
        private readonly double _nminus;
        private readonly double _nplus;

        public LinearRankSelector(double nminus) : base(true)
        {
            if (nminus < 0)
                throw new ArgumentOutOfRangeException(nameof(nminus), $"nminus is smaller than zero: {nminus}");

            _nminus = nminus;
            _nplus = 2 - _nminus;
        }

        public LinearRankSelector() : this(0.5)
        {
        }

        public override double[] Probabilities(Population<TGene, TAllele> population, int count)
        {
            double n = population.Count;
            var probabilities = new double[population.Count];

            if (n.Equals(1))
                probabilities[0] = 1;
            else
                for (var i = probabilities.Length; --i >= 0;)
                    probabilities[probabilities.Length - i - 1] =
                        (_nminus + (_nplus - _nminus) * i / (n - 1)) / n;

            return probabilities;
        }

        public override bool Equals(object obj)
        {
            return obj is LinearRankSelector<TGene, TAllele> selector &&
                   ProbabilitySelector.Eq(selector._nminus, _nminus) &&
                   ProbabilitySelector.Eq(selector._nplus, _nplus);
        }

        public override int GetHashCode()
        {
            return Hash.Of(GetType()).And(_nminus).And(_nplus).Value;
        }

        public override string ToString()
        {
            return $"{GetType().Name}[(n-)={_nminus}, (n+)={_nplus}]";
        }
    }
}


text:
using System;

namespace PdfSharp.Drawing
{
    /// <summary>
    /// Specifies whether smoothing (or antialiasing) is applied to lines and curves
    /// and the edges of filled areas.
    /// </summary>
    [Flags]
    public enum XSmoothingMode  // same values as System.Drawing.Drawing2D.SmoothingMode
    {
        // Not used in PDF rendering process.

        /// <summary>
        /// Specifies an invalid mode.
        /// </summary>
        Invalid = -1,

        /// <summary>
        /// Specifies the default mode.
        /// </summary>
        Default = 0,

        /// <summary>
        /// Specifies high speed, low quality rendering.
        /// </summary>
        HighSpeed = 1,

        /// <summary>
        /// Specifies high quality, low speed rendering.
        /// </summary>
        HighQuality = 2,

        /// <summary>
        /// Specifies no antialiasing.
        /// </summary>
        None = 3,

        /// <summary>
        /// Specifies antialiased rendering.
        /// </summary>
        AntiAlias = 4,
    }
}


text:
FROM jupyter/datascience-notebook
RUN pip install --upgrade pip
RUN pip install --upgrade plotly==1.9.6
#compatible with old layout
RUN pip install --upgrade bokeh==0.12.5
ADD install_sampledata.py .
RUN python install_sampledata.py
RUN pip install jupyterlab --upgrade
RUN jupyter serverextension enable --py jupyterlab
RUN pip install git+https://github.com/altair-viz/altair
RUN jupyter nbextension install --sys-prefix --py vega
RUN pip3 install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.2.1-cp36-cp36m-linux_x86_64.whl
# start jupyterlab


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Svensk bot. Tidskr. 69(1): 58 (1975)

#### Original name
Sphaeria acanthostroma Mont., 1855

### Remarks
null


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.clicoy</groupId>
    <artifactId>bbs</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>bbs Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit-dep</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>1.4.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.6.2</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>bbs</finalName>
    </build>
</project>


text:
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('first_app.html')

if __name__ == '__main__':
    app.run()


text:
/**
 * Module dependencies.
 */
var util = require('util')
  , OAuthStrategy = require('passport-oauth').OAuthStrategy
  , InternalOAuthError = require('passport-oauth').InternalOAuthError;

/**
 * `Strategy` constructor.
 *
 * The 500px authentication strategy authenticates requests by delegating to
 * 500px using the OAuth protocol.
 *
 * Applications must supply a `verify` callback which accepts a `token`,
 * `tokenSecret` and service-specific `profile`, and then calls the `done`
 * callback supplying a `user`, which should be set to `false` if the
 * credentials are not valid.  If an exception occured, `err` should be set.
 *
 * Options:
 *   - `consumerKey`     identifies client to 500px
 *   - `consumerSecret`  secret used to establish ownership of the consumer key
 *   - `callbackURL`     URL to which 500px will redirect the user after obtaining authorization
 *
 * Examples:
 *
 *     passport.use(new _500pxStrategy({
 *         consumerKey: '123-456-789',
 *         consumerSecret: 'shhh-its-a-secret'
 *         callbackURL: 'https://www.example.net/auth/500px/callback'
 *       },
 *       function(token, tokenSecret, profile, done) {
 *         User.findOrCreate(..., function (err, user) {
 *           done(err, user);
 *         });
 *       }
 *     ));
 *
 * @param {Object} options
 * @param {Function} verify
 * @api public
 */
function Strategy(options, verify) {
  options = options || {};
  options.requestTokenURL = options.requestTokenURL || 'https://api.500px.com/v1/oauth/request_token';
  options.accessTokenURL = options.accessTokenURL || 'https://api.500px.com/v1/oauth/access_token';
  options.userAuthorizationURL = options.userAuthorizationURL || 'https://api.500px.com/v1/oauth/authorize';
  options.sessionKey = options.sessionKey || 'oauth:500px';

  OAuthStrategy.call(this, options, verify);
  this.name = '500px';
}

/**
 * Inherit from `OAuthStrategy`.
 */
util.inherits(Strategy, OAuthStrategy);

/**
 * Retrieve user profile from 500px.
 *
 * This function constructs a normalized profile, with the following properties:
 *
 *   - `provider`         always set to `facebook`
 *   - `id`               the user's 500px ID
 *   - `username`         the user's 500px username
 *   - `displayName`      the user's full name
 *   - `name.familyName`  the user's last name
 *   - `name.givenName`   the user's first name
 *   - `profileUrl`       the URL of the profile for the user on 500px
 *   - `emails`           the proxied or contact email address granted by the user
 *
 * @param {String} accessToken
 * @param {Function} done
 * @api protected
 */
Strategy.prototype.userProfile = function(token, tokenSecret, params, done) {
  this._oauth.get('https://api.500px.com/v1/users', token, tokenSecret, function (err, body, res) {
    if (err) { return done(new InternalOAuthError('failed to fetch user profile', err)); }

    try {
      var json = JSON.parse(body);

      var profile = { provider: '500px' };
      profile.id = json.user.id;
      profile.username = json.user.username;
      profile.displayName = json.user.fullname;
      profile.name = { familyName: json.user.lastname,
                       givenName: json.user.firstname };
      profile.profileUrl = 'http://500px.com/'+json.user.username;
      profile.emails = [{ value: json.user.email }];

      profile._raw = body;
      profile._json = json;

      done(null, profile);
    } catch(e) {
      done(e);
    }
  });
}

/**
 * Expose `Strategy`.
 */
module.exports = Strategy;


text:
module Simple2ch
  class Board
    # @return [Bbs2chUrlValidator::URL] 板のURL
    attr_reader :url
    # @return [String] 板のタイトル
    attr_reader :title
    # @return [Time] 板オブジェクト更新日時
    attr_reader :updated_at

    # @param [String] title 板の名前
    # @param [String] url 板のURL
    # @option [Boolean] fetch_title 板の名前を自動取得するか
    def initialize(url, title: nil)
      @url = validate_url(url)
      @title = title
      @updated_at = Time.now
    end

    # 板に属する全てのスレッドを返す
    # @return [Array<Thre>] 板に属する全てのスレッド
    def threads
      @threads ||= fetch_all_threads
    end

    def ==(other)
      @url.to_s == other.url.to_s
    end

    private

    def validate_url(url)
      parsed = if url.instance_of?(Bbs2chUrlValidator::UrlInfo)
                 url
               else
                 Bbs2chUrlValidator::URL.parse(url)
               end
      return parsed if parsed && !parsed.board_name.empty?
      raise NotA2chBoardUrlError
    end

    # 板に属する全てのスレッドをsubject.txtから取得する
    # @return [Array<Thre>] 板に属する全てのスレッド
    def fetch_all_threads
      subject_url = @url.subject

      subject_txt = Simple2ch.fetch(subject_url)
      @threads = []
      subject_txt.each_line do |line|
        @threads << Simple2ch::Thread.parse(@url, line)
      end
      @updated_at = Time.now
      @threads
    end
  end
end


text:
namespace PH
{

    bool RelationItem::init(PH::HeroRelation &_relation)
    {
        if(!CCSprite::initWithFile("gameui/yuanfen_hong_xiao.png"))
            return false;

        relation = _relation;

        CCSize size = getContentSize();
        mask = GetSprite("gameui/yuanfen_lv_xiao.png");
        mask->setTag(10);
        mask->setVisible(false);
        mask->setPosition(ccp(size.width*0.5f, size.height*0.5f));
        addChild(mask);
        label = CCLabelTTF::create(relation.name.c_str(),
                                               FONT_CN,
                                               32,
                                               CCSize(80, 80),
                                               kCCTextAlignmentCenter);

        label->setPosition(ccp(size.width*0.5f, size.height*0.5f-5));
        label->setAnchorPoint(ccp(0.5f,0.5f));
        addChild(label);
        return true;
    }

    void RelationItem::setOpacity(GLubyte value)
    {
        CCSprite::setOpacity(value);
        mask->setOpacity(value);
        label->setOpacity(value);
    }

    void RelationItem::lock(bool value)
    {
        mask->setVisible(value);
    }

bool RelationJuanZhou::init(Hero* hero)
{
    if(!JuanZhou::init())
        return false;

    viewPort = CCSize(20 , 204);
    heroNum = 1;

    CCSprite *bg = GetSprite("gameui/xiyuanfen_1_3.png");
    bg->setAnchorPoint(ccp(0.5 , 1));
    addChild(bg);

    itemContainer = CCLayer::create();
    addChild(itemContainer);

    locations.push_back(CCRectMake(-257 , -151 , 100 , 100));
    heroVec = std::vector<Hero*>(1 , (Hero*)NULL);
    heroImgVec = std::vector<HeroIcon*>(1, (HeroIcon*)NULL);

    for(int i =0; i<3;i++)
        itemPos.push_back(ccp(-64+136*i, -156));

    addHero(hero, 0);

    listRelations();

    setTouchEnabled(true);

    return true;
}

void RelationJuanZhou::listRelations()
{
    itemContainer->removeAllChildrenWithCleanup(true);
    relItems.clear();
    btns.clear();

    for(int i = 0; i < 3; i++)
    {
        if(i < heroVec[0]->relations.size())
        {
            RelationItem* item = RelationItem::create((heroVec[0]->relations[i]));
            item->setPosition(ccp(-64+136*i, -78));
            relItems.push_back(item);
            itemContainer->addChild(item);

            CCSprite* btn = createBtn("锁定", ButtonType::SMALL_RED);
            CCSprite* btnMask = createBtn("解锁", ButtonType::SMALL_BLUE);
            btnMask->setPosition(ccp(btn->getContentSize().width*0.5f, btn->getContentSize().height*0.5f));
            btnMask->setTag(10);
            btnMask->setVisible(false);
            btn->addChild(btnMask);
            btn->setPosition(itemPos[i]);
            btns.push_back(btn);
            itemContainer->addChild(btn);
        }
        else
        {
            CCSprite* item = GetSprite("gameui/xiyuanfen_1_4.png");
            item->setPosition(ccp(-64+136*i, -100));
            itemContainer->addChild(item);
        }
    }
}

void RelationJuanZhou::lock(int i, bool value)
{
    relItems[i]->lock(value);
    lockRelItem(btns[i], value);
}

void RelationJuanZhou::onSingleClick(CCTouch* touch)
{
    CCPoint localPoint = convertTouchToNodeSpace(touch);
    for(int i = 0; i < btns.size(); i++)
        if(btns[i]->boundingBox().containsPoint(localPoint))
        {
            attachLayer->lock(i);
        }

    for(int j = 0; j < relItems.size(); j++)
        if(relItems[j]->boundingBox().containsPoint(localPoint))
            attachLayer->locateBoard(relItems[j]->relation);

    if(heroImgVec[0]->boundingBox().containsPoint(localPoint))
        GameScene::getInstance()->pushLayerWithDefaultAnimation(HeroProfileLayer::create(heroVec[0]));
}

void RelationJuanZhou::onLongClick(CCTouch* touch)
{
    CCPoint localPoint = convertTouchToNodeSpace(touch);
    if(heroImgVec[0]->boundingBox().containsPoint(localPoint))
        GameScene::getInstance()->pushLayerWithDefaultAnimation(HeroProfileLayer::create(heroVec[0]));
}

CCSprite* RelationJuanZhou::createRelItem(HeroRelation& r)
{
    CCSprite* item = GetSprite("gameui/yuanfen_lv_xiao.png");
    CCSize size = item->getContentSize();
    CCSprite *mask = GetSprite("gameui/yuanfen_hong_xiao.png");
    mask->setTag(10);
    mask->setVisible(false);
    mask->setPosition(ccp(size.width*0.5f, size.height*0.5f));
    item->addChild(mask);
    CCLabelTTF* label = CCLabelTTF::create(r.name.c_str(),
                                           FONT_CN,
                                           32,
                                           CCSize(80, 80),
                                           kCCTextAlignmentCenter);

    label->setPosition(ccp(size.width*0.5f, size.height*0.5f));
    label->setAnchorPoint(ccp(0.5f,0.5f));
    item->addChild(label);

    return item;
}

void RelationJuanZhou::lockRelItem(CCSprite* target, bool value)
{
    if(target->getChildByTag(10))
        target->getChildByTag(10)->setVisible(value);
}

bool RelationBoard::init(HeroRelation& _relation)
{
    if(!CCSprite::init())
        return false;
    relation = _relation;
    int MaxTextWidth = 255;

    mask = NULL;
    sigh = NULL;
    bg = GetSprite("gameui/yuanfen_hong_neirong.png");
    addChild(bg,-2);

    mask = GetSprite("gameui/yuanfen_lv_neirong.png");
    lockSigh = GetSprite("gameui/suo.png");
    lockSigh->setPosition(ccp(262,270));
    mask->addChild(lockSigh);
    mask->setVisible(false);
    addChild(mask,-1);

    size = bg->getContentSize();

    addLabelTTF(this, name, relation.name.c_str() , FONT_CN, 40, ccp(0,size.height*0.5-42), ccp(0.5,0.5));

    std::string nameMsg;
    for(int id : relation.withHeroes)
        nameMsg += (HPT(id).nameCN + " ");

    heroLabel = CCLabelTTF::create(nameMsg.c_str(),
                                               FONT_CN,
                                               26,
                                               CCSize(MaxTextWidth, 0),
                                               kCCTextAlignmentCenter);
    heroLabel->setAnchorPoint(ccp(0.5, 0.5));
    heroLabel->setPosition(ccp(0,30));
    addChild(heroLabel);

    std::string effectStr = "";
    for(boost::tuple<RelationEffects, double> t : relation.effects)
    {
        boost::get<0>(t) == RelationEffects::HP ? effectStr += "血量增加" :
        (boost::get<0>(t) == RelationEffects::STRENGTH ? effectStr += "攻击增加" : effectStr += "恢复增加");

        effectStr += (toStr(int(boost::get<1>(t)*100)) + "%\n");
    }

    effectLabel = CCLabelTTF::create(effectStr.c_str(),
                                                 FONT_CN,
                                                 24,
                                                 CCSize(MaxTextWidth, 0),
                                                 kCCTextAlignmentCenter);
    effectLabel->setPosition(ccp(0,-83));
    addChild(effectLabel);

    return true;
}

void RelationBoard::setOpacity(GLubyte value)
{
    CCSprite::setOpacity(value);
    bg->setOpacity(value);
    mask->setOpacity(value);
    heroLabel->setOpacity(value);
    effectLabel->setOpacity(value);
    name->setOpacity(value);
    lockSigh->setOpacity(value);
    if(sigh)
        sigh->setOpacity(value);
}

void RelationBoard::setColor(const ccColor3B& value)
{
    CCSprite::setColor(value);
    bg->setColor(value);
    mask->setColor(value);
    heroLabel->setColor(value);
    effectLabel->setColor(value);
    name->setColor(value);
    lockSigh->setColor(value);
    if(sigh)
        sigh->setColor(value);
}

void RelationBoard::lock(bool value)
{
    mask->setVisible(value);
}

void RelationBoard::occupied(bool value)
{
    if(value && !sigh)
    {
        sigh = GetSprite("gameui/yuanfen_yiyou.png");
        sigh->setPosition(ccp(-100,size.height*0.5-45));
        addChild(sigh);
    }
    else if(!value && sigh)
    {
        sigh->removeFromParent();
        sigh = NULL;
    }
}

bool WashPoolLayer::init(PH::Hero *hero)
{
    if(!ContentLayer::init())
        return false;

    isShowBottom = false;
    target = hero;
    lockMap = std::vector<bool>(3 , false);
    priceLabel = pillsLabel = NULL;
    price = NULL;
    isPayByGold = true;

    CCSprite* bg = GetSprite("gameui/10lian_bg.png");
    bg->setAnchorPoint(ccp(0.5,1));
    bg->setPositionY(160);
    addChild(bg);

    CCMenu *menu = CCMenu::create();

	CCMenuItem *backItem = CCMenuItemSprite::create(GetSprite("gameui/back_t.png"), GetSprite("gameui/back_t.png"),
                                                    this , menu_selector(WashPoolLayer::onBack));
	CCMenuItem *titleItem = CCMenuItemSprite::create(GetSprite("gameui/hongchengdi_t_tongyong.png"), GetSprite("gameui/hongchengdi_t_tongyong.png"));
    LabelX* name = LabelX::create("缘分", FONT_CN, 36);
    name->setColor(ccWHITE);
    name->setAnchorPoint(ccp(0.5, 0.5));
    name->setPosition(ccp( 141 , 34));
    titleItem->addChild(name);

	menu->addChild(backItem);
	menu->addChild(titleItem);

    backItem->setAnchorPoint(ccp(0.5 , 1));
    titleItem->setAnchorPoint(ccp(0.5 , 1));
	menu->alignItemsHorizontallyWithPadding(8);
	menu->setPosition(ccp(-70 , 18));
	addChild(menu,10);

    {
        CCSprite* guo = GetSprite("gameui/guo.png");
        guo->setPositionY(-480);
        addChild(guo);

        CCSprite* light_back = GetSprite("gameui/yuanfen_guang_al.png");
        light_back->setPositionY(-355);
        addChild(light_back,100);

        light_back->runAction(CCRepeatForever::create(CCSequence::create(CCFadeTo::create(1, 100),
                                                                         CCFadeTo::create(1, 255),
                                                                         NULL)
                                                      )
                              );

        boil = CCParticleSystemQuad::create("particle/boil_water.plist");
        boil->setPosition(ccp(0 , -380));
        boil->unscheduleUpdate();
        this->addChild(boil);

        light_front = GetSprite("gameui/yuanfen_guang_bf.png");
        light_front->setAnchorPoint(ccp(0.5,0));
        light_front->setPositionY(-430);
        light_front->setVisible(false);
        addChild(light_front,101);
    }

    {
        showPrice();

        confirmBtn = createBtn("洗缘", ButtonType::NORMAL_RED);
        confirmBtn->setPositionY(-540);
        addChild(confirmBtn);

    }

    juanzhou = RelationJuanZhou::create(hero);
    juanzhou->attachLayer = this;
	CCSprite *zhou1 = GetSprite("gameui/suosou_1_1.png");
	CCSprite *zhou2 = GetSprite("gameui/suosou_1_1.png");
    zhou2->setFlipX(true);
	jz = JuanZhouLayer::create();
	jz->addSkin(juanzhou , zhou1 , zhou2);
	jz->setPositionY(-560);
	this->addChild(jz);

    return true;
}

void WashPoolLayer::showPrice()
{
    if(PlayerData::getInstance()->freeRelationTimes>0)
    {
        price = CCSprite::create();
        price->setPositionY(-460);
        addChild(price);
        addLabelBMFont(price, (toStr(PlayerData::getInstance()->freeRelationTimes)+"次免費").c_str(), "bmfont/Sumo_38_orange.fnt", ccp(0, 0))->setScale(contentScale());
        priceLabel = NULL;
    }
    else
    {
        price = GetSprite("gameui/jiage_chendi.png");
        price->setPositionY(-460);
        addChild(price, 100);

        CCSprite* gasBg = GetSprite("gameui/xuanzhong.png");
        CCSprite* gas = GetSprite("gameui/yuanfensan.png");
        gas->setPosition(ccp(gasBg->getContentSize().width*0.5, gasBg->getContentSize().height*0.5));
        gasBg->addChild(gas);
        CCSprite* dot = GetSprite("gameui/shezhi_xuanzhong.png");
        dot->setPosition(ccp(-21, gasBg->getContentSize().height*0.5));
        gasBg->addChild(dot);
        relPillBtn = ButtonSprite::create(gasBg, GetSprite("gameui/yuanfensan.png"),
                                          kCCMenuHandlerPriority, false);
        relPillBtn->setOnClickListener([=](){
            bool isGoldEnough = PlayerData::getInstance()->player->golds >= calPrice();
            bool isPillEnough = PlayerData::getInstance()->getNumOfHero(HeroIdOfType::Hero_RelPill) >= calPrice()/50;
            if(!isPillEnough)
            {
                if(isGoldEnough)
                    SystemInform::alertMessage(runningScene(), "洗缘散数量不足,请使用元宝重置", "提示", [=](){choosePayWay(true);});
                else
                    SystemInform::alertConfirmPanel(runningScene(), "你的道具和元宝不足, 是否充值?", "提示",
                                                    [](){GameScene::getInstance()->pushLayerWithDefaultAnimation(ChongZhiLayer::create());},
                                                    [](){});
                return;
            }
            choosePayWay(false);
        });
        relPillBtn->setPosition(ccp(84, 45));
        price->addChild(relPillBtn);
        pillsLabel = addLabelBMFont(relPillBtn, "", "bmfont/Sumo_22_yellow.fnt", ccp(70, 15), ccp(1, 0.5));
        pillsLabel->setScale(contentScale());

        CCSprite* goldBg = GetSprite("gameui/xuanzhong.png");
        CCSprite* gold = GetSprite("gameui/yuanbao_dan.png");
        gold->setPosition(ccp(goldBg->getContentSize().width*0.5f, goldBg->getContentSize().height*0.5f));
        goldBg->addChild(gold);
        CCSprite* dot2 = GetSprite("gameui/shezhi_xuanzhong.png");
        dot2->setPosition(ccp(-19, gasBg->getContentSize().height*0.5));
        goldBg->addChild(dot2);
        goldBtn = ButtonSprite::create(goldBg, GetSprite("gameui/yuanbao_dan.png"),
                                       kCCMenuHandlerPriority, false);
        goldBtn->setOnClickListener([=](){
            bool isGoldEnough = PlayerData::getInstance()->player->golds >= calPrice();
            bool isPillEnough = PlayerData::getInstance()->getNumOfHero(HeroIdOfType::Hero_RelPill) >= calPrice()/50;
            if(!isGoldEnough)
            {
                if(isPillEnough)
                    SystemInform::alertMessage(runningScene(), "元宝数量不足,请使用洗缘散重置", "提示", [=](){choosePayWay(false);});
                else
                    SystemInform::alertConfirmPanel(runningScene(), "你的道具和元宝不足, 是否充值?", "提示",
                                                    [](){GameScene::getInstance()->pushLayerWithDefaultAnimation(ChongZhiLayer::create());},
                                                    [](){});
                return;
            }
            choosePayWay(true);
        });
        goldBtn->setPosition(ccp(204, 45));
        price->addChild(goldBtn);
        priceLabel = addLabelBMFont(goldBtn, "", "bmfont/Sumo_22_yellow.fnt", ccp(50, 15), ccp(0.5, 0.5));
        priceLabel->setScale(contentScale());
        updatePrice();
        choosePayWay(false);
    }

}

void WashPoolLayer::choosePayWay(bool isGold)
{
    isPayByGold = isGold;
    if(isGold)
    {
        goldBtn->onRelease();
        relPillBtn->onPressed();

    }
    else
    {
        goldBtn->onPressed();
        relPillBtn->onRelease();
    }

}

void WashPoolLayer::updatePrice()
{
    if(priceLabel)
    {
        priceLabel->setString(toStr(calPrice()).c_str());
        int total = PlayerData::getInstance()->getNumOfHero(HeroIdOfType::Hero_RelPill);
        pillsLabel->setString((toStr(total)+"/"+toStr(calPrice()/50)).c_str());
        if(total >= calPrice()/50)
            pillsLabel->setFntFile("bmfont/Sumo_22_yellow.fnt");
        else
            pillsLabel->setFntFile("bmfont/Sumo_22_red.fnt");
    }
}

void WashPoolLayer::onEnterAnimationDone()
{
    jz->startAnim();
    boil->scheduleUpdate();
}

void WashPoolLayer::onSingleClick(CCTouch* touch)
{
    CCPoint point = convertTouchToNodeSpace(touch);

    if(confirmBtn->boundingBox().containsPoint(point))
        onConfirm();
}

void WashPoolLayer::locateBoard(HeroRelation& r)
{
    for(int i = 0; i < boards.size(); i++)
        if(r == ((RelationBoard*)boards[i])->relation)
            scrollView->moveTo(i);
}

void WashPoolLayer::lock(int i)
{
    assert(i < target->relations.size() && i >= 0);
    if(lockNum() >= target->relations.size()-1 && !lockMap[i])
        return;

    lockMap[i] = !lockMap[i];

    juanzhou->lock(i, lockMap[i]);
    lockRelationBoard(target->relations[i], lockMap[i]);
    updatePrice();
}

void WashPoolLayer::lockRelationBoard(HeroRelation& r,bool value)
{
    for(CCNode* node : boards)
        if(((RelationBoard*)node)->relation == r)
            ((RelationBoard*)node)->lock(value);
}

void WashPoolLayer::showOwnedRelations()
{
    std::vector<HeroRelation> relations = target->relations;
    for(CCNode* node : boards)
    {
        std::vector<HeroRelation>::iterator it = find(relations.begin(),
                                                      relations.end(),
                                                      ((RelationBoard*)node)->relation);
        ((RelationBoard*)node)->occupied(it != relations.end());
    }
}

int WashPoolLayer::calPrice()
{
    int p = 50;
    int num = lockNum();
    p += num==0?0:(num==1?50:150);
    return p;

}

int WashPoolLayer::lockNum()
{
    int num = 0;
    for(bool value : lockMap)
        if(value)num++;
    return num;
}

void WashPoolLayer::makeRelations(std::vector<HeroRelation>& relations)
{
    if(scrollView)
    {
        removeChild(scrollView,true);
        boards.clear();
        lockMap[0] = lockMap[1] = lockMap[2]= false;
    }

    for(int i = 0; i < relations.size(); i++)
    {
        boards.push_back(RelationBoard::create(relations[i]));
    }

    scrollView = RoundPageScrollView::create(boards,220);
    scrollView->setPositionY(-40);
    scrollView->setVisible(false);
    scrollView->runAction(CCSequence::create(CCShow::create(), CCFadeIn::create(1), NULL));
    addChild(scrollView);

    showOwnedRelations();
}

void WashPoolLayer::washAnima()
{
    juanzhou->setTouchEnabled(false);
    setTouchEnabled(false);
    scrollView->close();
    boil->setSpeed(100);
    boil->setGravity(ccp(0,80));
    price->removeFromParentAndCleanup(true);
    priceLabel = NULL;
    confirmBtn->setVisible(false);

    scrollView->runAction(CCSequence::create(CCMoveBy::create(0.5, ccp(0,-280)),
                                             CCDelayTime::create(0.5),
                                             createLightAction(),
                                             createRItemOutAction(),
                                             CCCallLambda::create([=]()
                                             {
                                                 scrollView->open();
                                                 for(CCNode* node : boards)
                                                     ((RelationBoard*)node)->lock(false);
                                                 juanzhou->listRelations();
                                                 boil->setSpeed(10);
                                                 boil->setGravity(ccp(0,30));
                                             }),
                                             CCMoveBy::create(0.5, ccp(0,280)),
                                             CCCallLambda::create([=](){
        this->setTouchEnabled(true);
        juanzhou->setTouchEnabled(true);
        confirmBtn->setVisible(true);
        this->showOwnedRelations();
        showPrice();
    }),
                                             NULL));
}

CCAction* WashPoolLayer::createLightAction()
{
    return CCTargetedAction::create(light_front,
                                    CCSequence::create(CCShow::create(),
                                                       CCFadeIn::create(0.6),
                                                       CCFadeOut::create(0.4),
                                                       CCHide::create(),
                                                       NULL));
}

CCAction* WashPoolLayer::createRItemOutAction()
{
    CCArray* actions = CCArray::create();
    for(int i = 0; i < target->relations.size(); i++)
    {
        HeroRelation r = target->relations[i];
        for(CCNode* b : boards)
            if(((RelationBoard*)b)->relation == r)
            {
                RelationItem* board = RelationItem::create(r);
                board->setPositionY(-400);
                board->setScale(0.2);
                board->setVisible(false);
                addChild(board);

                actions->addObject(
                            CCTargetedAction::create(board,
                                             CCSequence::create(CCDelayTime::create(0.3*i),
                                                                CCShow::create(),
                                                                CCSpawn::create(
                                                                        CCFadeIn::create(0.5),
                                                                        CCMoveTo::create(0.5, ccp(-160+160*i,-200)),
                                                                        CCScaleTo::create(0.5, 1),
                                                                        NULL),
                                                                CCDelayTime::create(0.6),
                                                                CCMoveTo::create(0.3, getItemPos(i)),
                                                                CCCallLambda::create([=](){this->removeChild(board,true);}),
                                                                NULL)));
            }
    }

    return CCSpawn::create(actions);
}

CCPoint WashPoolLayer::getItemPos(int i)
{
    return this->convertToNodeSpace(juanzhou->convertToWorldSpace(juanzhou->itemPos[i]));
}

void WashPoolLayer::onConfirm()
{
    auto toConfirm = [=](){
        SystemInform* inform = SystemInform::alertLoading(GameScene::getInstance());

        std::vector<std::string> lockRe;
        for(int i = 0; i < lockMap.size(); i++)
            if(lockMap[i])
                lockRe.push_back(target->relations[i].id);

        int prevGold = PlayerData::getInstance()->getPlayer()->golds;
        RelationChangeType type =PlayerData::getInstance()->freeRelationTimes>0 ? RelationChangeType::Free :
                                    (isPayByGold ? RelationChangeType::Golds : RelationChangeType::Potions);

        PuzzleRPC::getInstance()->changeRelations(PlayerData::getInstance()->getToken(),
                                                  target->id,
                                                  lockRe,
                                                  type,
                                                  [=](std::auto_ptr<Hero> hero,
                                                      std::auto_ptr<Error> e)
        {
            inform->cancel();
            if(e.get())
            {
                e->handleErrorInform();
                return;
            }

            PlayerData* data = PlayerData::getInstance();
            data->updateHero(hero.get());
            if(data->freeRelationTimes>0)
                data->freeRelationTimes--;

            int golds = data->getPlayer()->golds;
            if(type == RelationChangeType::Golds)
            {
                data->setGolds(golds-calPrice());
            }
            else if(type == RelationChangeType::Potions)
            {
                data->removeNumOfHero(HeroIdOfType::Hero_RelPill, calPrice()/50);
            }

            lockMap = std::vector<bool>(3 , false);

            washAnima();
        });

    };
    bool isGoldEnough = PlayerData::getInstance()->player->golds >= calPrice();
    bool isPillEnough = PlayerData::getInstance()->getNumOfHero(HeroIdOfType::Hero_RelPill) >= calPrice()/50;
    if(isPayByGold && !isGoldEnough)
    {
        SystemInform::alertMessage(runningScene(), "元宝数量不足!", "提示", [=](){choosePayWay(false);});
        return;
    }
    if(!isPayByGold && !isPillEnough)
    {
        SystemInform::alertMessage(runningScene(), "洗缘散数量不足!", "提示", [=](){choosePayWay(false);});
        return;
    }
    SystemInform::alertConfirmPanel(GameScene::getInstance(),
                                    "确定要洗缘分吗?",
                                    "提示",
                                    toConfirm,
                                    [](){});
}

void WashPoolLayer::onBack()
{
    GameScene::getInstance()->popLayer();
}

bool WashRelHeroBoard::init()
{
    displayPlaceholder = false;
    if(!HeroBoard::init(PlayerData::getInstance()->getStorage(), false))
        return false;

    return true;
}

void WashRelHeroBoard::refresh(const std::vector<PH::Hero *>& heroVec)
{
    std::vector<PH::Hero*> heroesRemoveMats;
    for(Hero* h : heroVec)
        if(h->profile->tableId >= 10000)
            heroesRemoveMats.push_back(h);

    HeroBoard::refresh(heroesRemoveMats);

    for (auto h : heroesRemoveMats)
    {
        HeroIcon *icon = getHeroImg(h);
        icon->setEnabled(!(h->profile->isMat() || h->profile->star < 3));
    }
}

void WashRelHeroBoard::reOrder(const std::vector<PH::Hero *>& heroVec)
{
    std::vector<PH::Hero*> heroesRemoveMats;
    for(Hero* h : heroVec)
        if(h->profile->tableId >= 10000)
            heroesRemoveMats.push_back(h);

    HeroBoard::reOrder(heroesRemoveMats);
}

bool WashRelationLayer::init()
{
    if(!ContentLayer::init())
        return false;

    CCMenu *menu = CCMenu::create();

	CCMenuItem *backItem = CCMenuItemSprite::create(GetSprite("gameui/back_t.png"), GetSprite("gameui/back_t.png"),
                                                    this , menu_selector(WashRelationLayer::onBack));
    backItem->setAnchorPoint(ccp(0.5 , 1));
    menu->addChild(backItem);

    {
        CCMenuItem* sortButton = CCMenuItemSprite::create(GetSprite("gameui/hongchengdi_t_tongyong.png"),
                                                          GetSprite("gameui/hongchengdi_t_tongyong.png"),
                                                          this,
                                                          menu_selector(WashRelationLayer::onTitleClick));
        sortButton->setAnchorPoint(ccp(0.5 , 1));

        LabelX* name = LabelX::create("缘分", FONT_CN, 36);
        name->setColor(ccWHITE);
        name->setAnchorPoint(ccp(0.5, 0.5));
        name->setPosition(ccp(90 , sortButton->getContentSize().height*0.5f+2));
        sortButton->addChild(name);

        title = LabelX::create(PlayerData::getInstance()->getSortTypeMsg(), FONT_CN, 20, LabelX::FontEffect::SHADOW, ccp(2, -2));
        title->setColor(ccWHITE);
        title->setPosition(ccp( 170 , sortButton->getContentSize().height*0.5f));
        title->setAnchorPoint(ccp(0, 0.5));
        sortButton->addChild(title);

        CCSprite *xian = GetSprite("gameui/hongchengdi_huang_tongyong.png");
        xian->setPosition(ccp(160 , sortButton->getContentSize().height*0.5f));
        sortButton->addChild(xian);
        menu->addChild(sortButton);
    }

	menu->alignItemsHorizontallyWithPadding(8);
	menu->setPosition(ccp(-70 , 18));
	addChild(menu,10);

    scrollView = ZqlScrollView::create();
	scrollView->setViewSize(CCSize(winSize.width, 900),
                            CCRect(0, -110, winSize.width, 610));

	board = WashRelHeroBoard::create();
	scrollView->addLayer(board);
	scrollView->setPositionY(70);
	this->addChild(scrollView);

    if(GameConfig::shared()->getTutorialProgress() == TutorialShuffleRelation)
    {
        AlertMessage::create("", "缘分重置:选择你想要重置缘分的侠客!花费元宝可以随机重置一次哦!\t只有三星或者以上的侠客才可以重置缘分。");
        GameConfig::shared()->setTutorialProgress(TutorialSkip);
    }
    return true;
}

void WashRelationLayer::onTitleClick()
{
    PlayerData::getInstance()->switchSortType();
	board->reOrder(PlayerData::getInstance()->getStorage());
	title->setString(PlayerData::getInstance()->getSortTypeMsg());

    ring("sound/v/button_click.mp3");
}

void WashRelationLayer::onEnter()
{
    ContentLayer::onEnter();

    board->refresh(PlayerData::getInstance()->getStorage());
}

void WashRelationLayer::onSingleClick(CCTouch* touch)
{
    CCPoint localPoint = scrollView->convertTouchToNodeSpace(touch);
    Hero* hero = NULL;
    if(scrollView->boundingBox().containsPoint(localPoint))
        hero = board->getHero(touch);

    if(hero && hero->profile->star >= 3)
    {
        SystemInform* inform = SystemInform::alertLoading(GameScene::getInstance());
        PuzzleRPC::getInstance()->getRelations(PlayerData::getInstance()->getToken(), hero->heroId,
       [=](std::vector<HeroRelation> relations, std::auto_ptr<Error> e){
           inform->cancel();
           if(e.get())
           {
               e->handleErrorInform();
               return;
           }
           if(relations.size() == 0 || relations.size() <= hero->relations.size())
           {
               SystemInform::alertMessage(GameScene::getInstance(),
                                          "该侠客无其他缘分",
                                          "提示",
                                          [](){});
               return;
           }
           WashPoolLayer* layer = WashPoolLayer::create(hero);
           layer->makeRelations(relations);
           GameScene::getInstance()->pushLayerWithDefaultAnimation(layer);
       });
    }

}

void WashRelationLayer::onLongClick(CCTouch* touch)
{
    CCPoint localPoint = scrollView->convertTouchToNodeSpace(touch);
    Hero* hero = NULL;
    if(scrollView->boundingBox().containsPoint(localPoint))
        hero = board->getHero(touch);

    if(hero)
        GameScene::getInstance()->pushLayerWithDefaultAnimation(HeroProfileLayer::create(hero));
}

void WashRelationLayer::onBack()
{
    GameScene::getInstance()->popLayer();
}

}


text:
<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', function () {
    if (Auth::check())
      return redirect('/home');
    if (Auth::guard('admin')->check())
      return redirect('/admin/home');
    return view('welcome');
});

// for user to login
Route::get('/login', function(){
  return view('auth.login');
});

Route::post('/login', 'UserController@DoLogin');

// for user to register
Route::get('/register', function(){
    return view('auth.register');
});

Route::post('/register', 'UserController@AddNewUser');

// for user logout
Route::get('/logout', 'UserController@DoLogout');
// for user dashboard
Route::get('/home', function(){
  if (Auth::check())
    return view ('home');
  if (Auth::guard('admin')->check())
    return redirect('/admin/home');
  return redirect('/');
});

// to disaplay question response form
Route::get('/questions', 'QuizController@DisplayForm');

// to record the user response
Route::post('/questions', 'QuizController@AddQuizResponse');

//--------------------------< Admin Area >--------------------------------------

// for admin to login
Route::get('/admin/login', function(){
  return view('admin.auth.login');
});

Route::post('/admin/login', 'AdminController@DoLogin');

// for admin to register
Route::get('/admin/register', function(){
    return view('admin.auth.register');
});

Route::post('/admin/register', 'AdminController@AddNewAdmin');

// for admin logout
Route::get('/admin/logout', 'AdminController@DoLogout');
// for admin dashboard
Route::get('/admin/home', function(){
  return view('admin.home');
});

// for adding question sets
Route::get('/admin/questions', 'QuizController@AddQuestionsForm');

Route::post('/admin/questions', 'QuizController@AddQuestions');

Route::get('/admin/score', 'QuizController@DisplayScorecard');


text:
namespace ExceptionsHomework
{
    using System;
    using System.Collections.Generic;
    using System.Text;

    public class ExceptionsHomework
    {
        public static void Main()
        {
            var substr = Utils.Subsequence("Hello!".ToCharArray(), 2, 3);
            Console.WriteLine(substr);

            var subarr = Utils.Subsequence(new int[] { -1, 3, 2, 1 }, 0, 2);
            Console.WriteLine(string.Join(" ", subarr));

            var allarr = Utils.Subsequence(new int[] { -1, 3, 2, 1 }, 0, 4);
            Console.WriteLine(string.Join(" ", allarr));

            var emptyarr = Utils.Subsequence(new int[] { -1, 3, 2, 1 }, 0, 0);
            Console.WriteLine(string.Join(" ", emptyarr));

            Console.WriteLine(Utils.ExtractEnding("I love C#", 2));
            Console.WriteLine(Utils.ExtractEnding("Nakov", 4));
            Console.WriteLine(Utils.ExtractEnding("beer", 4));

            //Console.WriteLine(Utils.ExtractEnding("Hi", 100));
            if (Utils.CheckPrime(23))
            {
                Console.WriteLine("23 is prime.");
            }
            else
            {
                Console.WriteLine("23 is not prime");
            }

            if (Utils.CheckPrime(33))
            {
                Console.WriteLine("33 is prime.");
            }
            else
            {
                Console.WriteLine("33 is not prime");
            }

            List<Exam> peterExams = new List<Exam>()
            {
                new SimpleMathExam(2),
                new CSharpExam(55),
                new CSharpExam(100),
                new SimpleMathExam(1),
                new CSharpExam(0),
            };
            Student peter = new Student("Peter", "Petrov", peterExams);
            double peterAverageResult = peter.CalcAverageExamResultInPercents();
            Console.WriteLine("Average results = {0:p0}", peterAverageResult);
        }
    }
}


text:
import React, { Component } from "react";
import _ from "lodash";

class PropuestasCambios extends Component {
    constructor(props) {
        super(props);
        this.state = {
            propuestaList : [
                {
                    id: 0,
                    userOrigin: "Saul",
                    idUser: 1,
                    new: "Nueva",
                    old: "Vieja",
                    date: "14/09/17",
                    table: "Candidato",
                    bibliography : ["Wiki", "lol"]
                },
                {
                    id: 1,
                    userOrigin: "Anguiano",
                    idUser: 2,
                    new: "Nueva",
                    old: "Vieja",
                    date: "14/09/17",
                    table: "Candidato",
                    bibliography : ["Wiki", "lol"]
                },
                {
                    id: 2,
                    userOrigin: "Jaiba",
                    idUser: 3,
                    new: "Nueva",
                    old: "Vieja",
                    date: "14/09/17",
                    table: "Candidato",
                    bibliography : ["Wiki", "lol"]
                }
            ],
            propuestaActive : 0
        };
        this.renderPropuestaList = this.renderPropuestaList.bind(this);
        this.updatePropuestaActive = this.updatePropuestaActive.bind(this);
    }

    updatePropuestaActive(int){
        return(()=>{
            this.setState({ propuestaActive : int });
        });
    }

    renderPropuestaList() {
        return _.map(this.state.propuestaList, propuestaItem => {
            if(this.state.propuestaList[this.state.propuestaActive] == propuestaItem){
                return (

                        Propuesta hecha en {propuestaItem.table}

                            Info. anterior
                            Aprobar

                            Info. nueva
                            Aprobar

                  );
            }else{
                return (

                            Propuesta hecha en {propuestaItem.table}

                );
            }
        });
      }
    renderPropuestaDetail() {
        let propuesta = this.state.propuestaList[this.state.propuestaActive];
          return (

                {propuesta.idUser}

                {propuesta.userOrigin}

                {propuesta.date}

                {propuesta.new}

                {propuesta.old}

                {propuesta.bibliography}

          );
      }

  /**
  * Es una forma de capturar cualquier error en la clase
  * y que este no crashe el programa, ayuda con la depuracion
  * de errores
  * @method componentDidCatch
  * @const info Es más informacion acerca del error
  * @const error Es el titulo del error
  */
  componentDidCatch(error, info) {
    console.log("Error: " + error);
    console.log("Info: " + info);
  }

    render() {
        return (

                    {this.renderPropuestaList()}

                    {this.renderPropuestaDetail()}

        )
    }
}

export default PropuestasCambios;


text:
module RubySpark

  class ApiRequest
    class ApiError < StandardError; end

    attr_reader :response

    def initialize()
    end

    def devices
      get('/devices')
    end

    def function
      post("/devices/#{core}/#{function}", arguments)
    end

    def var
      get("/devices/#{core}/#{var}", arguments)
    end

    def attributes
      get("/devices/#{core}")
    end

    private

    def authorization_header(access_token)
      {"Authorization" => "Bearer #{access_token}"} if access_token
    end

    def basic_auth_params(username, password)
      {:username => username, :password => password}
    end

    def timeout
      RubySpark.timeout
    end

  end
end


text:
<?php

/**
 * @package Prb
 * @abstract
 */
abstract class Prb_Abstract_Collection
{
	const DELEGATE = 'Prb_DelegateFor_Collection';

	protected $array;

	// TODO: Document!
	function __construct( $array = array() )
	{
		$this->array = $array;
	}

	// TODO: Document!
	function __call( $method, $args )
	{
		if ( method_exists( self::DELEGATE, $method ) )
		{
			array_unshift( $args, $this );
			return call_user_func_array( array( self::DELEGATE, $method ), $args );
		}

		$this_class = get_class( $this );
		throw new Prb_Exception_Runtime_DelegationFailed( "cannot delegate {$method} in {$this_class}" );
	}

	// TODO: Document!
	public function length()
	{
		return sizeof( $this->array );
	}

	// TODO: Document!
	public function sortBy( $callback )
	{
		if ( !is_callable( $callback ) )
			throw new Prb_Exception_Callback( 'provided sortBy callback not callable' );

		$proxies = $this->map( $callback );
		$keys    = array_keys( $this->array );
		$links   = array();

		foreach ( $proxies->raw() as $index => $proxy )
			$links[ spl_object_hash( $proxy ) ] = $keys[ $index ];

		$sorted = array();
		foreach ( $proxies->sort()->raw() as $proxy )
		{
			$key            = $links[ spl_object_hash( $proxy ) ];
			$sorted[ $key ] = $this->array[ $key ];
		}

		return $sorted;
	}

	public function count() { return $this->length(); }
	public function size()  { return $this->length(); }

	// TODO: Document!
	public function isEmpty()
	{
		return ( $this->length() == 0 );
	}

	// TODO: Document!
	public function raw()
	{
		return $this->array;
	}
}


text:
(function() {
  'use strict';

  var app = angular.module('genieApp', ['uxGenie', 'ga']);

  // Makes this modular if we don't just use the global instance and use it as a module instead
  app.constant('genie', genie);

  app.controller('GenieCtrl', function($scope, genie, ga) {
    $scope.demoContext = 'genie-demo';
    $scope.iconPrefix = 'fa fa-';
    genie.context($scope.demoContext);

    $scope.genieStyle = {
      color: 'light',
      size: 'large',
      animationSpeed: 'fast',
      template: 'default'
    };
    $scope.wishesMade = 0;

    $scope.lamp = {
      wishMade: function(wish) {
        $scope.wishesMade++;
        ga('send', 'event', 'wish', 'made', $scope.wishesMade);
      },
      genieVisible: false
    };

    $scope.customLamp = angular.copy($scope.lamp);

    $scope.rubLamp = function($event, lampTemplate) {
      if (lampTemplate === 'default') {
        $scope.customLamp.genieVisible = !$scope.customLamp.genieVisible;
      } else {
        $scope.lamp.genieVisible = !$scope.lamp.genieVisible;
      }
      $event.stopPropagation();
    };

    $scope.wishMagicWords = '';

    $scope.addWishFromInput = function() {
      if ($scope.wishMagicWords) {
        ga('send', 'event', 'button', 'click', 'Create Wish: ' + $scope.wishMagicWords);
        addWish($scope.wishMagicWords, null, {
          uxGenie: {
            iIcon: 'glyphicon glyphicon-exclamation-sign'
          }
        });
        $scope.wishMagicWords = '';
      }
    };

    function addWish(magicWords, action, data) {
      if (typeof magicWords === 'string') {
        magicWords = magicWords.split(',');
      }
      return genie({
        magicWords: magicWords,
        action: action || function(wish) {
          alert('Your "' + wish.magicWords[0] + '" wish is my command!');
        },
        context: $scope.demoContext,
        data: data
      });
    }

    function addStyleWish(style, altStyle, property, iIcon, altiIcon, wishCalled) {
      var originalWish, altWish;
      function swapWishes(wish) {
        genie.removeContext(wish.context.all);
        genie.addContext(wish.data.otherWish.context.all);
      }
      function applyStyleAndSwapWishes(wish) {
        $scope.genieStyle[property] = wish.data.style.toLowerCase();
        swapWishes(wish);
        wishCalled && wishCalled(wish);
      }
      originalWish = genie({
        magicWords: 'Make lamp ' + style,
        context: {
          all: ['genie-style-' + property + '-' + style, $scope.demoContext]
        },
        action: applyStyleAndSwapWishes,
        data: {
          style: style,
          uxGenie: {
            iIcon: 'glyphicon glyphicon-' + iIcon
          }
        }
      });
      altWish = genie({
        magicWords: 'Make lamp ' + altStyle,
        context: {
          all: ['genie-style-' + property + '-' + altStyle, $scope.demoContext]
        },
        action: applyStyleAndSwapWishes,
        data: {
          style: altStyle,
          otherWish: originalWish,
          uxGenie: {
            iIcon: 'glyphicon glyphicon-' + altiIcon
          }
        }
      });
      originalWish.data.otherWish = altWish;
      $scope.$watch('genieStyle["' + property + '"]', function(newVal) {
        if (newVal === style.toLowerCase()) {
          swapWishes(originalWish);
        } else {
          swapWishes(altWish);
        }
      });
    }

    addStyleWish('Dark', 'Light', 'color', 'picture', 'picture');
    addStyleWish('Small', 'Large', 'size', 'resize-small', 'resize-full');
    addStyleWish('Slow', 'Fast', 'animationSpeed', 'fast-backward', 'fast-forward');
    addStyleWish('Custom', 'Default', 'template', 'random', 'random', function() {
      $scope.lamp.genieVisible = false;
      $scope.customLamp.genieVisible = false;
    });

    var genieTagline = encodeURIComponent('Genie: Better than keyboard shortcuts');
    var genieHome = encodeURIComponent('http://kent.doddsfamily.us/genie');

    function addNavigateWishWithoutPrefix(magicWord, shareUrl, iIcon) {
      addWish(magicWord, {
        destination: shareUrl,
        openNewTab: true
      }, {
        uxGenie: {
          iIcon: iIcon
        }
      });
    }

    addNavigateWishWithoutPrefix('Tweet #GenieJS', 'https://twitter.com/intent/tweet?hashtags=GenieJS&original_referer=' + genieHome + '&text=' + genieTagline + '&tw_p=tweetbutton&url=' + genieHome + '&via=kentcdodds', $scope.iconPrefix + 'share');
    addNavigateWishWithoutPrefix('Share #GenieJS on Google+', 'http://plus.google.com/share?&url=' + genieHome, $scope.iconPrefix + 'share');
    addNavigateWishWithoutPrefix('Email about GenieJS', 'mailto:?&subject=' + encodeURIComponent('Cool JavaScript Library: Genie') + '&body=' + genieTagline + encodeURIComponent('\nCheck it out here: ') + genieHome, $scope.iconPrefix + 'envelope');

    addNavigateWishWithoutPrefix('Code with @kentcdodds', 'http://www.github.com/kentcdodds', $scope.iconPrefix + 'github');
    addNavigateWishWithoutPrefix('Follow @kentcdodds', 'https://twitter.com/intent/follow?original_referer=' + genieHome + '&region=follow_link&screen_name=kentcdodds&tw_p=followbutton&variant=2.0', $scope.iconPrefix + 'twitter');
    addNavigateWishWithoutPrefix('Circle +KentCDodds', 'http://plus.google.com/+KentCDodds', $scope.iconPrefix + 'google-plus');
    addNavigateWishWithoutPrefix('Visit Kent\'s website', 'http://kent.doddsfamily.us', $scope.iconPrefix + 'globe');

  });

})();


text:
"""Configuration for JavaScript library dependencies."""

# A dict mapping dependency ids to the Angular module names they
# should insert when the Angular app is first initialized.
DEPENDENCIES_TO_ANGULAR_MODULES_DICT = {
    'codemirror': ['ui.codemirror'],
    'ui_leaflet': ['ui-leaflet'],
    'guppy': [],
    'logic_proof': [],
    'math_expressions': [],
    'midijs': [],
    'pencilcode': [],
    'skulpt': [],
}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('tools', '0009_auto_20170226_0353'),
    ]

    operations = [
        migrations.AddField(
            model_name='comment',
            name='post',
            field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='tools.Post'),
            preserve_default=False,
        ),
    ]


text:
from UserDict import UserDict

class Panel(UserDict):
    data = dict() # Global registry.

    def __init__(self, logger, listener, hostname=None):
        self.logger = logger
        self.hostname = hostname
        self.listener = listener

    @classmethod
    def register(cls, method, name=None):
        cls.data[name or method.__name__] = method
        return method


text:
  * Refactor render code into callable function - ([@mattconnolly][])

## 0.1.6 2012-12-04
### major enhancements
  * Added support for JPEG and GIF rendering - ([@shawnpyle][])

## 0.1.5 2012-02-10
### major enhancements
  * Added :level option
  * Added :unit size option

## 0.1.4 2012-02-09
### minor enhancements
  * [#11][]: Check whether mime types are already defined (suppress warnings) - ([@peternash][])
  * Version of rqrcode bumped up to 0.4.2

## 0.1.3 2011-07-11
### major enhancements
  * Added :size option and default size calculator

## 0.1.2 2011-06-08
### bug fixes
  * gem no longer needs to have a require statement
  * Basic color setting options implemented, however they render poorly or not at all in PNG format


text:
#include "EffekseerRendererDX12.Renderer.h"
#include "../../3rdParty/LLGI/src/DX12/LLGI.CommandListDX12.h"
#include "../../3rdParty/LLGI/src/DX12/LLGI.GraphicsDX12.h"
#include "../../3rdParty/LLGI/src/DX12/LLGI.TextureDX12.h"
#include "../EffekseerMaterialCompiler/DirectX12/EffekseerMaterialCompilerDX12.h"
#include "../EffekseerRendererLLGI/EffekseerRendererLLGI.RendererImplemented.h"

namespace Sprite_Unlit_VS_Ad
{
static
#include "ShaderHeader/ad_sprite_unlit_vs.h"
} // namespace Sprite_Unlit_VS_Ad

namespace Sprite_Distortion_VS_Ad
{
static
#include "ShaderHeader/ad_sprite_distortion_vs.h"
} // namespace Sprite_Distortion_VS_Ad

namespace Sprite_Lit_VS_Ad
{
static
#include "ShaderHeader/ad_sprite_lit_vs.h"
} // namespace Sprite_Lit_VS_Ad

namespace Model_Unlit_VS_Ad
{
static
#include "ShaderHeader/ad_model_unlit_vs.h"
} // namespace Model_Unlit_VS_Ad

namespace Model_Unlit_PS_Ad
{
static
#include "ShaderHeader/ad_model_unlit_ps.h"
} // namespace Model_Unlit_PS_Ad

namespace Model_Distortion_VS_Ad
{
static
#include "ShaderHeader/ad_model_distortion_vs.h"
} // namespace Model_Distortion_VS_Ad

namespace Model_Distortion_PS_Ad
{
static
#include "ShaderHeader/ad_model_distortion_ps.h"
} // namespace Model_Distortion_PS_Ad

namespace Model_Lit_VS_Ad
{
static
#include "ShaderHeader/ad_model_lit_vs.h"
} // namespace Model_Lit_VS_Ad

namespace Model_Lit_PS_Ad
{
static
#include "ShaderHeader/ad_model_lit_ps.h"
} // namespace Model_Lit_PS_Ad

namespace Sprite_Unlit_VS
{
static
#include "ShaderHeader/sprite_unlit_vs.h"
} // namespace Sprite_Unlit_VS

namespace Sprite_Distortion_VS
{
static
#include "ShaderHeader/sprite_distortion_vs.h"
} // namespace Sprite_Distortion_VS

namespace Sprite_Lit_VS
{
static
#include "ShaderHeader/sprite_lit_vs.h"
} // namespace Sprite_Lit_VS

namespace Model_Unlit_VS
{
static
#include "ShaderHeader/model_unlit_vs.h"
} // namespace Model_Unlit_VS

namespace Model_Unlit_PS
{
static
#include "ShaderHeader/model_unlit_ps.h"
} // namespace Model_Unlit_PS

namespace Model_Distortion_VS
{
static
#include "ShaderHeader/model_distortion_vs.h"
} // namespace Model_Distortion_VS

namespace Model_Distortion_PS
{
static
#include "ShaderHeader/model_distortion_ps.h"
} // namespace Model_Distortion_PS

namespace Model_Lit_VS
{
static
#include "ShaderHeader/model_lit_vs.h"
} // namespace Model_Lit_VS

namespace Model_Lit_PS
{
static
#include "ShaderHeader/model_lit_ps.h"
} // namespace Model_Lit_PS

namespace EffekseerRendererDX12
{

::Effekseer::Backend::GraphicsDeviceRef CreateGraphicsDevice(ID3D12Device* device, ID3D12CommandQueue* commandQueue, int32_t swapBufferCount)
{
	std::function<std::tuple<D3D12_CPU_DESCRIPTOR_HANDLE, LLGI::Texture*>()> getScreenFunc =
		[]() -> std::tuple<D3D12_CPU_DESCRIPTOR_HANDLE, LLGI::Texture*> {
		return std::tuple<D3D12_CPU_DESCRIPTOR_HANDLE, LLGI::Texture*>();
	};

	auto graphics = new LLGI::GraphicsDX12(
		device, getScreenFunc, []() -> void {}, commandQueue, swapBufferCount);

	auto ret = Effekseer::MakeRefPtr<EffekseerRendererLLGI::Backend::GraphicsDevice>(graphics);
	ES_SAFE_RELEASE(graphics);
	return ret;
}

::EffekseerRenderer::RendererRef Create(::Effekseer::Backend::GraphicsDeviceRef graphicsDevice,
										DXGI_FORMAT* renderTargetFormats,
										int32_t renderTargetCount,
										DXGI_FORMAT depthFormat,
										bool isReversedDepth,
										int32_t squareMaxCount)
{
	auto renderer = ::Effekseer::MakeRefPtr<::EffekseerRendererLLGI::RendererImplemented>(squareMaxCount);

	auto allocate_ = [](std::vector<LLGI::DataStructure>& ds, const unsigned char* data, int32_t size) -> void {
		ds.resize(1);
		ds[0].Size = size;
		ds[0].Data = data;
		return;
	};

	allocate_(renderer->fixedShader_.AdvancedSpriteUnlit_VS, Sprite_Unlit_VS_Ad::g_main, sizeof(Sprite_Unlit_VS_Ad::g_main));
	allocate_(renderer->fixedShader_.AdvancedSpriteDistortion_VS, Sprite_Distortion_VS_Ad::g_main, sizeof(Sprite_Distortion_VS_Ad::g_main));
	allocate_(renderer->fixedShader_.AdvancedSpriteLit_VS, Sprite_Lit_VS_Ad::g_main, sizeof(Sprite_Lit_VS_Ad::g_main));

	allocate_(renderer->fixedShader_.AdvancedModelUnlit_VS, Model_Unlit_VS_Ad::g_main, sizeof(Model_Unlit_VS_Ad::g_main));
	allocate_(renderer->fixedShader_.AdvancedModelUnlit_PS, Model_Unlit_PS_Ad::g_main, sizeof(Model_Unlit_PS_Ad::g_main));
	allocate_(renderer->fixedShader_.AdvancedModelDistortion_VS, Model_Distortion_VS_Ad::g_main, sizeof(Model_Distortion_VS_Ad::g_main));
	allocate_(renderer->fixedShader_.AdvancedModelDistortion_PS, Model_Distortion_PS_Ad::g_main, sizeof(Model_Distortion_PS_Ad::g_main));
	allocate_(renderer->fixedShader_.AdvancedModelLit_VS, Model_Lit_VS_Ad::g_main, sizeof(Model_Lit_VS_Ad::g_main));
	allocate_(renderer->fixedShader_.AdvancedModelLit_PS, Model_Lit_PS_Ad::g_main, sizeof(Model_Lit_PS_Ad::g_main));

	allocate_(renderer->fixedShader_.SpriteUnlit_VS, Sprite_Unlit_VS::g_main, sizeof(Sprite_Unlit_VS::g_main));
	allocate_(renderer->fixedShader_.SpriteDistortion_VS, Sprite_Distortion_VS::g_main, sizeof(Sprite_Distortion_VS::g_main));
	allocate_(renderer->fixedShader_.SpriteLit_VS, Sprite_Lit_VS::g_main, sizeof(Sprite_Lit_VS::g_main));

	allocate_(renderer->fixedShader_.ModelUnlit_VS, Model_Unlit_VS::g_main, sizeof(Model_Unlit_VS::g_main));
	allocate_(renderer->fixedShader_.ModelUnlit_PS, Model_Unlit_PS::g_main, sizeof(Model_Unlit_PS::g_main));

	allocate_(renderer->fixedShader_.ModelLit_VS,
			  Model_Lit_VS::g_main,
			  sizeof(Model_Lit_VS::g_main));
	allocate_(renderer->fixedShader_.ModelLit_PS,
			  Model_Lit_PS::g_main,
			  sizeof(Model_Lit_PS::g_main));

	allocate_(
		renderer->fixedShader_.ModelDistortion_VS, Model_Distortion_VS::g_main, sizeof(Model_Distortion_VS::g_main));
	allocate_(
		renderer->fixedShader_.ModelDistortion_PS, Model_Distortion_PS::g_main, sizeof(Model_Distortion_PS::g_main));

	renderer->platformType_ = Effekseer::CompiledMaterialPlatformType::DirectX12;
	renderer->materialCompiler_ = new Effekseer::MaterialCompilerDX12();

	LLGI::RenderPassPipelineStateKey key;
	key.RenderTargetFormats.resize(renderTargetCount);

	for (size_t i = 0; i < key.RenderTargetFormats.size(); i++)
	{
		key.RenderTargetFormats.at(i) = LLGI::ConvertFormat(renderTargetFormats[i]);
	}

	key.DepthFormat = LLGI::ConvertFormat(depthFormat);

	auto gd = graphicsDevice.DownCast<EffekseerRendererLLGI::Backend::GraphicsDevice>();

	if (renderer->Initialize(gd, key, isReversedDepth))
	{
		return renderer;
	}

	return nullptr;
}

::EffekseerRenderer::RendererRef Create(ID3D12Device* device,
										ID3D12CommandQueue* commandQueue,
										int32_t swapBufferCount,
										DXGI_FORMAT* renderTargetFormats,
										int32_t renderTargetCount,
										DXGI_FORMAT depthFormat,
										bool isReversedDepth,
										int32_t squareMaxCount)
{
	auto graphicDevice = CreateGraphicsDevice(device, commandQueue, swapBufferCount);

	auto ret = Create(graphicDevice, renderTargetFormats, renderTargetCount, depthFormat, isReversedDepth, squareMaxCount);

	if (ret != nullptr)
	{
		return ret;
	}

	return nullptr;
}

Effekseer::Backend::TextureRef CreateTexture(::Effekseer::Backend::GraphicsDeviceRef graphicsDevice, ID3D12Resource* texture)
{
	auto g = static_cast<::EffekseerRendererLLGI::Backend::GraphicsDevice*>(graphicsDevice.Get());
	return g->CreateTexture((uint64_t)texture, [] {});
}

TextureProperty GetTextureProperty(::Effekseer::Backend::TextureRef texture)
{
	if (texture != nullptr)
	{
		auto t = texture.DownCast<::EffekseerRendererLLGI::Backend::Texture>();
		auto lt = static_cast<LLGI::TextureDX12*>(t->GetTexture().get());
		return TextureProperty{lt->Get()};
	}
	else
	{
		return TextureProperty{};
	}
}

CommandListProperty GetCommandListProperty(Effekseer::RefPtr<EffekseerRenderer::CommandList> commandList)
{
	if (commandList != nullptr)
	{
		auto cl = commandList.DownCast<::EffekseerRendererLLGI::CommandList>();
		auto clDx12 = static_cast<LLGI::CommandListDX12*>(cl->GetInternal());
		return CommandListProperty{clDx12->GetCommandList()};
	}
	else
	{
		return CommandListProperty{};
	}
}

void BeginCommandList(Effekseer::RefPtr<EffekseerRenderer::CommandList> commandList, ID3D12GraphicsCommandList* dx12CommandList)
{
	assert(commandList != nullptr);

	if (dx12CommandList)
	{
		LLGI::PlatformContextDX12 context;
		context.commandList = dx12CommandList;

		auto c = static_cast<EffekseerRendererLLGI::CommandList*>(commandList.Get());
		c->GetInternal()->BeginWithPlatform(&context);
		c->SetState(EffekseerRendererLLGI::CommandListState::RunningWithPlatformCommandList);
	}
	else
	{
		auto c = static_cast<EffekseerRendererLLGI::CommandList*>(commandList.Get());
		c->GetInternal()->Begin();
		c->SetState(EffekseerRendererLLGI::CommandListState::Running);
	}
}

void EndCommandList(Effekseer::RefPtr<EffekseerRenderer::CommandList> commandList)
{
	assert(commandList != nullptr);
	auto c = static_cast<EffekseerRendererLLGI::CommandList*>(commandList.Get());

	if (c->GetState() == EffekseerRendererLLGI::CommandListState::RunningWithPlatformCommandList)
	{
		c->GetInternal()->EndWithPlatform();
	}
	else
	{
		c->GetInternal()->End();
	}
}

void ExecuteCommandList(Effekseer::RefPtr<EffekseerRenderer::CommandList> commandList)
{
	assert(commandList != nullptr);
	auto c = static_cast<EffekseerRendererLLGI::CommandList*>(commandList.Get());
	c->GetGraphics()->Execute(c->GetInternal());
}

} // namespace EffekseerRendererDX12


text:
/*
 * ResultsStatisticsActionsOJ.java
 * fully documented
 *
 * used to handle actions from  statistics visibility checkboxes
 */
package oj.gui.results;

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import oj.OJ;
import oj.gui.results.ProjectResultsOJ;
import oj.project.results.statistics.StatisticsOJ;

public class StatisticsActionsOJ {

    /** Makes all statistics invisible
     */
    public static Action HideAll = new AbstractAction("Hide All") {

        public void actionPerformed(ActionEvent e) {
            StatisticsOJ statistics = OJ.getData().getResults().getStatistics();
            for (int i = 0; i < statistics.getStatisticsCount(); i++) {
                statistics.getStatisticsByIndex(i).setVisible(false);
            }
            ProjectResultsOJ.getInstance().updateResultsStatisticsView();
        }
    };
    /** Not used yet
     */
    public static Action HideOthers = new AbstractAction("Hide Others") {

        public void actionPerformed(ActionEvent e) {
            StatisticsOJ statistics = OJ.getData().getResults().getStatistics();
            for (int i = 0; i < statistics.getStatisticsCount(); i++) {
                statistics.getStatisticsByIndex(i).setVisible(!statistics.getStatisticsByIndex(i).getVisible());
            }
            ProjectResultsOJ.getInstance().updateResultsStatisticsView();
        }
    };
    /** Makes all statistics visible
     */
    public static Action ShowAll = new AbstractAction("Show All") {

        public void actionPerformed(ActionEvent e) {
            StatisticsOJ statistics = OJ.getData().getResults().getStatistics();
            for (int i = 0; i < statistics.getStatisticsCount(); i++) {
                statistics.getStatisticsByIndex(i).setVisible(true);
            }
            ProjectResultsOJ.getInstance().updateResultsStatisticsView();
        }
    };
}


text:
package ij.io;

import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;
import ij.*;
import ij.gui.*;
import ij.process.*;
import ij.util.*;
import ij.plugin.frame.Recorder;
import ij.plugin.FolderOpener;
import ij.plugin.FileInfoVirtualStack;
import ij.measure.Calibration;

/** This is a dialog box used to imports raw 8, 16, 24 and 32-bit images. */
public class ImportDialog {
	private String fileName;
    private String directory;
	static final String TYPE = "raw.type";
	static final String WIDTH = "raw.width";
	static final String HEIGHT = "raw.height";
	static final String OFFSET = "raw.offset";
	static final String N = "raw.n";
	static final String GAP = "raw.gap";
	static final String OPTIONS = "raw.options";
	static final int WHITE_IS_ZERO = 1;
	static final int INTEL_BYTE_ORDER = 2;
	static final int OPEN_ALL = 4;

    // default settings
    private static int choiceSelection = Prefs.getInt(TYPE,0);
    private static int width = Prefs.getInt(WIDTH,512);
    private static int height = Prefs.getInt(HEIGHT,512);
    private static long offset = Prefs.getInt(OFFSET,0);
    private static int nImages = Prefs.getInt(N,1);
    private static int gapBetweenImages = Prefs.getInt(GAP,0);
	private static int options;
    private static boolean whiteIsZero,intelByteOrder;
    private static boolean virtual;
    private boolean openAll;
    private static FileInfo lastFileInfo;
    private static String[] types = {"8-bit", "16-bit Signed", "16-bit Unsigned",
		"32-bit Signed", "32-bit Unsigned", "32-bit Real", "64-bit Real", "24-bit RGB",
		"24-bit RGB Planar", "24-bit BGR", "24-bit Integer", "32-bit ARGB", "32-bit ABGR", "1-bit Bitmap"};

    static {
    	options = Prefs.getInt(OPTIONS,0);
    	whiteIsZero = (options&WHITE_IS_ZERO)!=0;
    	intelByteOrder = (options&INTEL_BYTE_ORDER)!=0;
    }

    public ImportDialog(String fileName, String directory) {
        this.fileName = fileName;
        this.directory = directory;
		IJ.showStatus("Importing: " + fileName);
	}

    public ImportDialog() {
	}

	boolean showDialog() {
		if (choiceSelection>=types.length)
			choiceSelection = 0;
		getDimensionsFromName(fileName);
		GenericDialog gd = new GenericDialog("Import>Raw...", IJ.getInstance());
		gd.addChoice("Image type:", types, types[choiceSelection]);
		gd.addNumericField("Width:", width, 0, 6, "pixels");
		gd.addNumericField("Height:", height, 0, 6, "pixels");
		gd.addNumericField("Offset to first image:", offset, 0, 6, "bytes");
		gd.addNumericField("Number of images:", nImages, 0, 6, null);
		gd.addNumericField("Gap between images:", gapBetweenImages, 0, 6, "bytes");
		gd.addCheckbox("White is zero", whiteIsZero);
		gd.addCheckbox("Little-endian byte order", intelByteOrder);
		gd.addCheckbox("Open all files in folder", openAll);
		gd.addCheckbox("Use virtual stack", virtual);
		gd.addHelp(IJ.URL+"/docs/menus/file.html#raw");
		gd.showDialog();
		if (gd.wasCanceled())
			return false;
		choiceSelection = gd.getNextChoiceIndex();
		width = (int)gd.getNextNumber();
		height = (int)gd.getNextNumber();
		offset = (long)gd.getNextNumber();
		nImages = (int)gd.getNextNumber();
		gapBetweenImages = (int)gd.getNextNumber();
		whiteIsZero = gd.getNextBoolean();
		intelByteOrder = gd.getNextBoolean();
		openAll = gd.getNextBoolean();
		virtual = gd.getNextBoolean();
		IJ.register(ImportDialog.class);
		return true;
	}

	/** Opens all the images in the directory. */
	void openAll(String[] list, FileInfo fi) {
		FolderOpener fo = new FolderOpener();
		list = fo.trimFileList(list);
		list = fo.sortFileList(list);
		if (list==null) return;
		ImageStack stack=null;
		ImagePlus imp=null;
		double min = Double.MAX_VALUE;
		double max = -Double.MAX_VALUE;
		int digits = 0;
		for (int i=0; i<list.length; i++) {
			if (list[i].startsWith("."))
				continue;
			fi.fileName = list[i];
			imp = new FileOpener(fi).open(false);
			if (imp==null)
				IJ.log(list[i] + ": unable to open");
			else {
				if (stack==null)
					stack = imp.createEmptyStack();
				try {
					ImageStack stack2 = imp.getStack();
					int slices = stack2.getSize();
					if (digits==0) {
						digits = 2;
						if (slices>99) digits=3;
						if (slices>999) digits=4;
						if (slices>9999) digits=5;
					}
					for (int n=1; n<=slices; n++) {
						ImageProcessor ip = stack2.getProcessor(n);
						if (ip.getMin()<min) min = ip.getMin();
						if (ip.getMax()>max) max = ip.getMax();
						String label = list[i];
						if (slices>1) label += "-" + IJ.pad(n,digits);
						stack.addSlice(label, ip);
					}
				} catch(OutOfMemoryError e) {
					IJ.outOfMemory("OpenAll");
					stack.trim();
					break;
				}
				IJ.showStatus((stack.getSize()+1) + ": " + list[i]);
			}
		}
		if (stack!=null) {
			imp = new ImagePlus("Imported Stack", stack);
			if (imp.getBitDepth()==16 || imp.getBitDepth()==32)
				imp.getProcessor().setMinAndMax(min, max);
                Calibration cal = imp.getCalibration();
                if (fi.fileType==FileInfo.GRAY16_SIGNED)
                	cal.setSigned16BitCalibration();
			imp.show();
		}
	}

	/** Displays the dialog and opens the specified image or images.
		Does nothing if the dialog is canceled. */
	public void openImage() {
		FileInfo fi = getFileInfo();
		if (fi==null) return;
		if (openAll) {
			if (virtual) {
				virtual = false;
				IJ.error("Import Raw", "\"Open All\" does not currently support virtual stacks");
				return;
			}
			String[] list = new File(directory).list();
			if (list==null) return;
			openAll(list, fi);
		} else if (virtual)
			new FileInfoVirtualStack(fi);
		else {
			FileOpener fo = new FileOpener(fi);
			ImagePlus imp = fo.open(false);
			if (imp!=null) {
				imp.show();
				int n = imp.getStackSize();
				if (n>1) {
					imp.setSlice(n/2);
					ImageProcessor ip = imp.getProcessor();
					ip.resetMinAndMax();
					imp.setDisplayRange(ip.getMin(),ip.getMax());
				}
			}
		}
	}

	/** Displays the dialog and returns a FileInfo object that can be used to
		open the image. Returns null if the dialog is canceled. The fileName
		and directory fields are null if the no argument constructor was used. */
	public FileInfo getFileInfo() {
		if (!showDialog())
			return null;
		String imageType = types[choiceSelection];
		FileInfo fi = new FileInfo();
		fi.fileFormat = fi.RAW;
		fi.fileName = fileName;
		fi.directory = directory;
		fi.width = width;
		fi.height = height;
		if (offset>2147483647)
			fi.longOffset = offset;
		else
			fi.offset = (int)offset;
		fi.nImages = nImages;
		fi.gapBetweenImages = gapBetweenImages;
		fi.intelByteOrder = intelByteOrder;
		fi.whiteIsZero = whiteIsZero;
		if (imageType.equals("8-bit"))
			fi.fileType = FileInfo.GRAY8;
		else if (imageType.equals("16-bit Signed"))
			fi.fileType = FileInfo.GRAY16_SIGNED;
		else if (imageType.equals("16-bit Unsigned"))
			fi.fileType = FileInfo.GRAY16_UNSIGNED;
		else if (imageType.equals("32-bit Signed"))
			fi.fileType = FileInfo.GRAY32_INT;
		else if (imageType.equals("32-bit Unsigned"))
			fi.fileType = FileInfo.GRAY32_UNSIGNED;
		else if (imageType.equals("32-bit Real"))
			fi.fileType = FileInfo.GRAY32_FLOAT;
		else if (imageType.equals("64-bit Real"))
			fi.fileType = FileInfo.GRAY64_FLOAT;
		else if (imageType.equals("24-bit RGB"))
			fi.fileType = FileInfo.RGB;
		else if (imageType.equals("24-bit RGB Planar"))
			fi.fileType = FileInfo.RGB_PLANAR;
		else if (imageType.equals("24-bit BGR"))
			fi.fileType = FileInfo.BGR;
		else if (imageType.equals("24-bit Integer"))
			fi.fileType = FileInfo.GRAY24_UNSIGNED;
		else if (imageType.equals("32-bit ARGB"))
			fi.fileType = FileInfo.ARGB;
		else if (imageType.equals("32-bit ABGR"))
			fi.fileType = FileInfo.ABGR;
		else if (imageType.equals("1-bit Bitmap"))
			fi.fileType = FileInfo.BITMAP;
		else
			fi.fileType = FileInfo.GRAY8;
		if (IJ.debugMode) IJ.log("ImportDialog: "+fi);
		lastFileInfo = (FileInfo)fi.clone();
		return fi;
	}

	/** Called once when ImageJ quits. */
	public static void savePreferences(Properties prefs) {
		prefs.put(TYPE, Integer.toString(choiceSelection));
		prefs.put(WIDTH, Integer.toString(width));
		prefs.put(HEIGHT, Integer.toString(height));
		prefs.put(OFFSET, Integer.toString(offset>2147483647?0:(int)offset));
		prefs.put(N, Integer.toString(nImages));
		prefs.put(GAP, Integer.toString(gapBetweenImages));
		int options = 0;
		if (whiteIsZero)
			options |= WHITE_IS_ZERO;
		if (intelByteOrder)
			options |= INTEL_BYTE_ORDER;
		prefs.put(OPTIONS, Integer.toString(options));
	}

	/** Returns the FileInfo object used to import the last raw image,
		or null if a raw image has not been imported. */
	public static FileInfo getLastFileInfo() {
		return lastFileInfo;
	}

	private void getDimensionsFromName(String name) {
		if (name==null) return;
		int lastUnderscore = name.lastIndexOf("_");
		String name2 = name;
		if (lastUnderscore>=0)
			name2 = name.substring(lastUnderscore);
		char[] chars = new char[name2.length()];
		for (int i=0; i<name2.length(); i++)  // change non-digits to spaces
			chars[i] = Character.isDigit(name2.charAt(i))?name2.charAt(i):' ';
		name2 = new String(chars);
		String[] numbers = Tools.split(name2);
		int n = numbers.length;
		if (n<2 || n>3) return;
		int w = (int)Tools.parseDouble(numbers[0],0);
		if (w<10) return;
		int h = (int)Tools.parseDouble(numbers[1],0);
		if (h<10) return;
		width = w;
		height = h;
		nImages = 1;
		if (n==3) {
			int d = (int)Tools.parseDouble(numbers[2],0);
			if (d>0)
				nImages = d;
		}
		guessFormat(directory, name);
	}

	private void guessFormat(String dir, String name) {
		if (dir==null) return;
		File file = new File(dir+name);
		long imageSize = (long)width*height*nImages;
		long fileSize = file.length();
		if (fileSize==4*imageSize) {
			choiceSelection = 5; // 32-bit real
			intelByteOrder = true;
		} else if (fileSize==2*imageSize) {
			choiceSelection = 2;	// 16-bit unsigned
			intelByteOrder = true;
		} else if (fileSize==3*imageSize) {
			choiceSelection = 7;	// 24-bit RGB
		} else if (fileSize==imageSize)
			choiceSelection = 0;	// 8-bit
		if (name.endsWith("be.raw"))
			intelByteOrder = false;
	}

}


text:
import { closest, doc, hasTouch, includes, isTouch, isVisible, matches, once, pointerEnter, pointerLeave, queryAll, trigger, win } from '../util/index';

export default function (UIkit) {

    UIkit.component('toggle', {

        mixins: [UIkit.mixin.togglable],

        args: 'target',

        props: {
            href: String,
            target: null,
            mode: 'list',
            media: 'media'
        },

        defaults: {
            href: false,
            target: false,
            mode: 'click',
            queued: true,
            media: false
        },

        computed: {

            target({href, target}, $el) {
                target = queryAll(target || href, $el);
                return target.length && target || [$el];
            }

        },

        events: [

            {

                name: `${pointerEnter} ${pointerLeave}`,

                filter() {
                    return includes(this.mode, 'hover');
                },

                handler(e) {
                    if (!isTouch(e)) {
                        this.toggle(`toggle${e.type === pointerEnter ? 'show' : 'hide'}`);
                    }
                }

            },

            {

                name: 'click',

                filter() {
                    return includes(this.mode, 'click') || hasTouch;
                },

                handler(e) {

                    if (!isTouch(e) && !includes(this.mode, 'click')) {
                        return;
                    }

                    // TODO better isToggled handling
                    var link;
                    if (closest(e.target, 'a[href="#"], button')
                        || (link = closest(e.target, 'a[href]')) && (
                            this.cls
                            || !isVisible(this.target)
                            || link.hash && matches(this.target, link.hash)
                        )
                    ) {
                        once(doc, 'click', e => e.preventDefault());
                    }

                    this.toggle();
                }

            }
        ],

        update: {

            write() {

                if (!includes(this.mode, 'media') || !this.media) {
                    return;
                }

                var toggled = this.isToggled(this.target);
                if (win.matchMedia(this.media).matches ? !toggled : toggled) {
                    this.toggle();
                }

            },

            events: ['load', 'resize']

        },

        methods: {

            toggle(type) {
                if (trigger(this.target, type || 'toggle', [this])) {
                    this.toggleElement(this.target);
                }
            }

        }

    });

}


text:
#ifndef __CCDATAVISITOR_H__
#define __CCDATAVISITOR_H__

#include "platform/CCPlatformMacros.h"
#include <string>

NS_CC_BEGIN

class Object;
class Bool;
class Integer;
class Float;
class Double;
class String;
class Array;
class Dictionary;
class Set;
class Data;

/**
 * @addtogroup data_structures
 * @{
 */

/**
 * Visitor that helps to perform action that depends on polymorphic object type
 *
 * Use cases:
 *  - data serialization,
 *  - pretty printing of Object *
 *  - safe value reading from Array, Dictionary, Set
 *
 * Usage:
 *  1. subclass DataVisitor
 *  2. overload visit() methods for object that you need to handle
 *  3. handle other objects in visitObject()
 *  4. pass your visitor to Object::acceptVisitor()
 */
class CC_DLL DataVisitor
{
public:
    virtual ~DataVisitor() {}

    /** default method, called from non-overloaded methods and for unrecognized objects */
    virtual void visitObject(const Object *p) = 0;

    virtual void visit(const Bool *p);
    virtual void visit(const Integer *p);
    virtual void visit(const Float *p);
    virtual void visit(const Double *p);
    virtual void visit(const String *p);
    virtual void visit(const Array *p);
    virtual void visit(const Dictionary *p);
    virtual void visit(const Set *p);
    virtual void visit(const Data *p);
};

class CC_DLL PrettyPrinter : public DataVisitor
{
public:
    PrettyPrinter(int indentLevel = 0);

    virtual void clear();
    virtual std::string getResult();

    virtual void visitObject(const Object *p);
    virtual void visit(const Bool * p);
    virtual void visit(const Integer *p);
    virtual void visit(const Float *p);
    virtual void visit(const Double *p);
    virtual void visit(const String *p);
    virtual void visit(const Array *p);
    virtual void visit(const Dictionary *p);
    virtual void visit(const Set *p);
    virtual void visit(const Data *p);
private:
    void setIndentLevel(int indentLevel);
    int _indentLevel;
    std::string _indentStr;
    std::string _result;
};

// end of data_structure group
/// @}

NS_CC_END

#endif // __CCDATAVISITOR_H__


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

namespace Dapper.SimpleSave.Tests.RealisticDtos
{
    [Table("[app].[LEGAL_INFO_MST]")]
    public class LegalInfoDto
    {
        [PrimaryKey]
        public int? LegalInfoKey { get; set; }

        [ForeignKeyReference(typeof(ApplicationDetailsDto))]
        public Guid? ApplicationGuid { get; set; }

        [ManyToOne]
        [Column("MerchantLegalInfoKey")]
        public MerchantLegalInfoDto MerchantLegalInfo { get; set; }

        public string BacsName { get; set; }

        public decimal CurrentOverdraftLimit { get; set; }
    }
}


text:
package o;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import com.quizup.core.activities.DiagnosticActivity;

public class ĭ extends ArrayAdapter<ĭ.if>
{
  private static final String ˊ = ĭ.class.getName();
  private ĭ.if[] ˋ;
  private DiagnosticActivity ˎ;
  private int ˏ;
  private ĭ.if ᐝ;

  public ĭ(DiagnosticActivity paramDiagnosticActivity, int paramInt, ĭ.if[] paramArrayOfif)
  {
    super(paramDiagnosticActivity, 2130903046, paramArrayOfif);
    this.ˋ = paramArrayOfif;
    this.ˎ = paramDiagnosticActivity;
    this.ˏ = 2130903046;
  }

  public int getCount()
  {
    return this.ˋ.length;
  }

  public View getView(int paramInt, View paramView, ViewGroup paramViewGroup)
  {
    View localView = paramView;
    ĭ.ˊ localˊ1;
    if (paramView == null)
    {
      localView = ((Activity)this.ˎ).getLayoutInflater().inflate(this.ˏ, paramViewGroup, false);
      ĭ.ˊ localˊ2 = new ĭ.ˊ();
      localˊ1 = localˊ2;
      localˊ2.ˊ = ((TextView)localView.findViewById(2131296299));
      localˊ1.ˋ = ((CheckBox)localView.findViewById(2131296300));
      localView.setTag(localˊ1);
    }
    else
    {
      localˊ1 = (ĭ.ˊ)localView.getTag();
    }
    this.ᐝ = this.ˋ[paramInt];
    localˊ1.ˊ.setText(this.ᐝ.ˊ);
    localˊ1.ˋ.setChecked(this.ᐝ.ˎ);
    localˊ1.ˋ.setTag(this.ᐝ.ˋ);
    localˊ1.ˋ.setOnCheckedChangeListener(new ĭ.1(this));
    return localView;
  }
}

/* Location:           /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
 * Qualified Name:     o.ĭ
 * JD-Core Version:    0.6.2
 */


text:
"""
name: manage.py
desc: A set of commands to make our lives easier.
    HOW TO RUN: python ./manage.py <command>
    COMMANDS:
        python ./manage.py runserver
        python ./manage.py cleanpyc
"""

from flask.ext.script import Manager
from birdseye.application import app
import os

manager = Manager(app)

@manager.command
def runserver():
    """ Runs the flask server """
    app.run(host="0.0.0.0", debug=True, threaded=True)

@manager.command
def cleanpyc():
    """ Removes all those yucky .pyc files """
    print "Recursivley cleaning up .pyc files..."
    os.system("find . -name '*.pyc' -exec rm -rf {} \;")
    print "Done."

if __name__ == "__main__":
    manager.run()