<commit_before>/**
 * Created by Pjer1 on 10/3/2016.
 */
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

function blast_req(){
    var s_data = ($('#form_bl').serializeObject());
    console.log(s_data);
    var  dictPost  =  {"plugin":"blast","action":"req","sequence":s_data["sequence"]};
    console.log(dictPost);
    $.ajax({
        type: "POST",
        url: "/plugin/",
        data: dictPost,
        success: function(response){
            var Jr = JSON.parse(response);
            if(Jr['success']==true) {
                //get the result ready for everyone
            }
            else {
                Materialize.toast(Jr['error'], 3000, 'rounded');
            }
        }
    });
}

// initial blast data (should be from serve)

raw_data={"q_length":46,"blast_result":[{'index':0,'ID':'gi|688010384|gb|KM018299.1|',
'description':'Synthetic fluorescent protein expression cassette cat-J23101-mTagBFP2, complete sequence',
    'E-value':7.8e-14,
    'score':84.24,
    'span':46,
    'query_start':0,
    'query_end':46,
'hit_start':21,
'hit_end':67
},
{'index':0,'ID':'gi|688010384|gb|KM018299.1|',
    'description':'Synthetic fluorescent protein expression cassette cat-J23101-mTagBFP2, complete sequence',
    'E-value':7.8e-14,
    'score':84.24,
    'span':46,
    'query_start':0,
    'query_end':46,
    'hit_start':21,
    'hit_end':67,
},{'index':0,'ID':'gi|688010384|gb|KM018299.1|',
    'description':'Synthetic fluorescent protein expression cassette cat-J23101-mTagBFP2, complete sequence',
    'E-value':7.8e-14,
    'score':84.24,
    'span':46,
    'query_start':0,
    'query_end':46,
    'hit_start':21,
    'hit_end':67,
},{'index':0,'ID':'gi|688010384|gb|KM018299.1|',
    'description':'Synthetic fluorescent protein expression cassette cat-J23101-mTagBFP2, complete sequence',
    'E-value':7.8e-14,
    'score':84.24,
    'span':46,
    'query_start':0,
    'query_end':46,
    'hit_start':21,
    'hit_end':67
}]};

console.log(raw_data);
result = raw_data["blast_result"];

sample = result[0];

var draw_arcs = function(svg,target_id,q_start,q_end,hit_start,hit_end){

    var color = d3.scale.linear()
        .range(["hsl(-180,60%,50%)", "hsl(180,60%,50%)"])
        .interpolate(function(a, b) { var i = d3.interpolateString(a, b); return function(t) { return d3.hsl(i(t)); }; });

    var deg2arc  = function (arc){
        return arc*Math.PI/180
    };
    var res_width = 500;
    var res_height = 500;

    var radius = Math.min(res_width, res_height) / 1.9,
        armRadius = radius / 12,
        dotRadius = armRadius - 6;

    var arc_root = d3.svg.arc()
        .startAngle(deg2arc(0.5))
        .endAngle(deg2arc(359.5))
        .innerRadius(0.78 * radius)
        .outerRadius(0.50 * radius)
        .cornerRadius(10);

    var arc_k = d3.svg.arc()
        .startAngle(deg2arc(360*hit_start/(q_end-q_start+1)))
        .endAngle(deg2arc(360*hit_end/(q_end-q_start+1)))
        .innerRadius(0.9 * radius)
        .outerRadius(0.8 * radius)
        .cornerRadius(armRadius-3);

    var total = raw_data["q_length"];

    svg.append("path")
        .attr("d",arc_root)
        .attr("fill",function (d) {
            return color(0.4)
        })
        .attr("id","root_path");

    svg.append("text")
        .attr("dy", "3.35em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .append("textPath")
        .attr("startOffset", "0%")
        .attr("class", "arc-text")
        .attr("xlink:href", "#root_path")
        .text( "Original  Sequence VS "+target_id)
        .attr("style","font-size:24px;font-family:consolas")
        .attr("fill","white");

    svg.append("text")
        .attr("dy", "1.35em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .append("textPath")
        .attr("startOffset", "1.2%")
        .attr("class", "arc-text")
        .attr("xlink:href", "#root_path")
        .text( "start point")
        .attr("style","font-size:14px;font-family:consolas")
        .attr("fill","white");

    svg.append("text")
        .attr("dy", "1.35em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .append("textPath")
        .attr("startOffset", "52.5%")
        .attr("class", "arc-text")
        .attr("xlink:href", "#root_path")
        .text( "end point")
        .attr("style","font-size:14px;font-family:consolas")
        .attr("fill","white");

    svg.append("path")
        .attr("d",arc_k)
        .attr("fill",function (d) {
            return color(0.99)
        })
        .attr("id","hit_path");

    svg.append("text")
        .attr("dy", "1.15em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .append("textPath")
        .attr("startOffset", "1.2%")
        .attr("class", "arc-text")
        .attr("xlink:href", "#hit_path")
        .text(hit_start)
        .attr("style","font-size:14px;font-family:consolas")
        .attr("fill","white");

    svg.append("text")
        .attr("dy", "1.15em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .append("textPath")
        .attr("startOffset", "48.0%")
        .attr("class", "arc-text")
        .attr("xlink:href", "#hit_path")
        .text(hit_end)
        .attr("style","font-size:14px;font-family:consolas")
        .attr("fill","white");

    var c_start = svg.append("circle")
        .attr("cx",17)
        .attr("cy",-0.72*radius)
        .attr("r",8)
        .attr("fill","black")

    var e_start = svg.append("circle")
        .attr("cx",-17)
        .attr("cy",-0.72*radius)
        .attr("r",8)
        .attr("fill","black")

};

window.onload=(
    function () {

        var res_width = 500;
        var res_height = 500;
        var svg = d3.select('#result_blast').append('svg')
            .attr('width',res_width)
            .attr('height',res_height)
            .append("g")
            .attr("transform", "translate(" + res_width / 2 + "," + res_height / 2 + ")");

        draw_arcs(svg,'gi|688010384|gb|KM018299.1|',1,46,8,25)

    }
);<commit_msg>blast graph<commit_after>/**
 * Created by Pjer1 on 10/3/2016.
 */
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

function blast_req(){
    var s_data = ($('#form_bl').serializeObject());
    console.log(s_data);
    var  dictPost  =  {"plugin":"blast","action":"req","sequence":s_data["sequence"]};
    console.log(dictPost);
    $.ajax({
        type: "POST",
        url: "/plugin/",
        data: dictPost,
        success: function(response){
            var Jr = JSON.parse(response);
            if(Jr['success']==true) {
                //get the result ready for everyone
            }
            else {
                Materialize.toast(Jr['error'], 3000, 'rounded');
            }
        }
    });
}

// initial blast data (should be from serve)

raw_data={"q_length":46,"blast_result":[{'index':0,'ID':'gi|688010384|gb|KM018299.1|',
'description':'Synthetic fluorescent protein expression cassette cat-J23101-mTagBFP2, complete sequence',
    'E-value':7.8e-14,
    'score':84.24,
    'span':46,
    'query_start':0,
    'query_end':46,
'hit_start':21,
'hit_end':67
},
{'index':0,'ID':'gi|688010384|gb|KM018299.1|',
    'description':'Synthetic fluorescent protein expression cassette cat-J23101-mTagBFP2, complete sequence',
    'E-value':7.8e-14,
    'score':84.24,
    'span':46,
    'query_start':0,
    'query_end':46,
    'hit_start':21,
    'hit_end':67,
},{'index':0,'ID':'gi|688010384|gb|KM018299.1|',
    'description':'Synthetic fluorescent protein expression cassette cat-J23101-mTagBFP2, complete sequence',
    'E-value':7.8e-14,
    'score':84.24,
    'span':46,
    'query_start':0,
    'query_end':46,
    'hit_start':21,
    'hit_end':67,
},{'index':0,'ID':'gi|688010384|gb|KM018299.1|',
    'description':'Synthetic fluorescent protein expression cassette cat-J23101-mTagBFP2, complete sequence',
    'E-value':7.8e-14,
    'score':84.24,
    'span':46,
    'query_start':0,
    'query_end':46,
    'hit_start':21,
    'hit_end':67
}]};

console.log(raw_data);
result = raw_data["blast_result"];
sample = result[0];

var text_start;
var text_end;
var radius;
var arc_k;

var draw_arcs = function(svg,target_id,q_start,q_end,hit_start,hit_end){

    var color = d3.scale.linear()
        .range(["hsl(-180,60%,50%)", "hsl(180,60%,50%)"])
        .interpolate(function(a, b) { var i = d3.interpolateString(a, b); return function(t) { return d3.hsl(i(t)); }; });

    var deg2arc  = function (arc){
        return arc*Math.PI/180
    };
    var res_width = 500;
    var res_height = 500;

    var radius = Math.min(res_width, res_height) / 1.9,
        armRadius = radius / 12,
        dotRadius = armRadius - 6;

    var arc_root = d3.svg.arc()
        //.startAngle(deg2arc(0.5))
        //.endAngle(deg2arc(359.5))
        .innerRadius(0.78 * radius)
        .outerRadius(0.50 * radius)
        .cornerRadius(10);

    arc_k = d3.svg.arc()
        //.startAngle(deg2arc(360*hit_start/(q_end-q_start+1)))
        //.endAngle(deg2arc(360*hit_end/(q_end-q_start+1)))
        .innerRadius(0.9 * radius)
        .outerRadius(0.8 * radius)
        .cornerRadius(9);

    var total = raw_data["q_length"];

    svg.append("path")
        .datum({endAngle:deg2arc(359),startAngle:deg2arc(1)})
        .attr("d",arc_root)
        .attr("fill",function (d) {
            return color(0.4)
        })
        .attr("id","root_path");

    svg.append("text")
        .attr("dy", "3.35em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .append("textPath")
        .attr("startOffset", "0%")
        .attr("class", "arc-text")
        .attr("xlink:href", "#root_path")
        .text( "Original  Sequence VS "+target_id)
        .attr("style","font-size:24px;font-family:consolas")
        .attr("fill","white");

    svg.append("text")
        .attr("dy", "1.35em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .append("textPath")
        .attr("startOffset", "1.2%")
        .attr("class", "arc-text")
        .attr("xlink:href", "#root_path")
        .text( "start point")
        .attr("style","font-size:14px;font-family:consolas")
        .attr("fill","white");

    svg.append("text")
        .attr("dy", "1.35em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .append("textPath")
        .attr("startOffset", "52%")
        .attr("class", "arc-text")
        .attr("xlink:href", "#root_path")
        .text( "end point")
        .attr("style","font-size:14px;font-family:consolas")
        .attr("fill","white");

    var arc_ret=svg.append("path")
        .datum({endAngle:deg2arc(360*hit_end/(q_end-q_start+1)),startAngle:deg2arc(360*hit_start/(q_end-q_start+1))})
        .attr("d",arc_k)
        .attr("fill",function (d) {
            return color(0.99)
        })
        .attr("id","hit_path");

    text_start = svg.append("text")
        .attr("dy", "1.15em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .append("textPath")
        .attr("startOffset", "0%")
        .attr("class", "arc-text")
        .attr("xlink:href", "#hit_path")
        .text(hit_start)
        .attr("style","font-size:14px;font-family:consolas")
        .attr("fill","white");

    text_end = svg.append("text")
        .attr("dy", "1.15em")
        .attr("dx", "2.15em")
        .style("text-anchor", "end")
        .append("textPath")
        .attr("startOffset", "53.2301%")
        .attr("class", "arc-text")
        .attr("xlink:href", "#hit_path")
        .text(hit_end)
        .attr("style","font-size:14px;font-family:consolas")
        .attr("fill","white");

    var c_start = svg.append("circle")
        .attr("cx",17)
        .attr("cy",-0.72*radius)
        .attr("r",8)
        .attr("fill","black");

    var e_start = svg.append("circle")
        .attr("cx",-17)
        .attr("cy",-0.72*radius)
        .attr("r",8)
        .attr("fill","black");

    return arc_ret

};

function arcTween(start_n,end_n) {
    return function(d) {
        var interpolate_end = d3.interpolate(d.endAngle, end_n);
        var interpolate_begin = d3.interpolate(d.startAngle, start_n);
        return function(t) {
            d.endAngle = interpolate_end(t);
            d.startAngle = interpolate_begin(t);
            return arc_k(d);
        }
    }
}

window.onload=(
    function () {

        var res_width = 500;
        var res_height = 500;
        var svg = d3.select('#result_blast').append('svg')
            .attr('width',res_width)
            .attr('height',res_height+300)
            .append("g")
            .attr("transform", "translate(" + res_width / 2 + "," + res_height / 2 + ")");

        var arc_ret = draw_arcs(svg,'gi|688010384|gb|KM018299.1|',1,146,1,120);
        current_start = 8;
        current_end = 25;

        arc_ret.transition().duration(300).delay(6000)
            .attrTween("d", arcTween(0.3,6)).each("end",function () {
            text_end.text("dsaf");
            text_start.text("asdf");
        });

        console.log(arc_ret);

    }
);<|endoftext|>


<commit_before>const webpack = require('webpack')
const path = require('path')
const projectRoot = path.resolve(__dirname, '../')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const autoprefixer = require('autoprefixer')
const LodashWebpackPlugin = require('lodash-webpack-plugin')

module.exports = {
    entry: {
        app: './src/main.js'
    },
    output: {
        path: path.resolve(__dirname, '../public/'),
        // publicPath: './public/',
        filename: '[name].js'
    },
    resolve: {
        extensions: ['', '.js', '.vue'],
        fallback: [path.join(__dirname, '../node_modules')],
        alias: {
            'src': path.resolve(__dirname, '../src'),
            'components': 'src/components'
        }
    },
    resolveLoader: {
        fallback: [path.join(__dirname, '../node_modules')]
    },
    module: {
        preLoaders: [{
            test: /\.vue$/,
            loader: 'eslint',
            include: projectRoot,
            exclude: /node_modules/
        }, {
            test: /\.js$/,
            loader: 'eslint',
            include: projectRoot,
            exclude: /node_modules/
        }],
        loaders: [{
            test: /\.vue$/,
            loader: 'vue'
        }, {
            test: /\.js$/,
            loader: 'babel',
            include: projectRoot,
            exclude: /node_modules/
        }, {
            test: /\.json$/,
            loader: 'json'
        }, {
            test: /\.html$/,
            loader: 'vue-html'
        }, {
            test: /\.(png|jpe?g|gif|svg|woff2?|eot|ttf|otf)(\?.*)?$/,
            loader: 'url',
            query: {
                limit: 10000,
                name: '[name].[hash:7].[ext]'
            }
        }]
    },
    vue: {
        loaders: {
            css: 'vue-style!css',
            less: 'vue-style!css!less'
        },
        postcss: [autoprefixer({
            browsers: ['last 3 versions']
        })]
    },
    eslint: {
        formatter: require('eslint-friendly-formatter')
    },
    babel: {
        presets: ['es2015', 'stage-2'],
        plugins: ['transform-runtime'],
        comments: false
    },
    postcss: [autoprefixer({
        browsers: ['last 3 versions']
    })],
    plugins: [
        new LodashWebpackPlugin()
    ]
}
<commit_msg>add babel-lodash plugin<commit_after>const webpack = require('webpack')
const path = require('path')
const projectRoot = path.resolve(__dirname, '../')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const autoprefixer = require('autoprefixer')
const LodashWebpackPlugin = require('lodash-webpack-plugin')

module.exports = {
    entry: {
        app: './src/main.js'
    },
    output: {
        path: path.resolve(__dirname, '../public/'),
        // publicPath: './public/',
        filename: '[name].js'
    },
    resolve: {
        extensions: ['', '.js', '.vue'],
        fallback: [path.join(__dirname, '../node_modules')],
        alias: {
            'src': path.resolve(__dirname, '../src'),
            'components': 'src/components'
        }
    },
    resolveLoader: {
        fallback: [path.join(__dirname, '../node_modules')]
    },
    module: {
        preLoaders: [{
            test: /\.vue$/,
            loader: 'eslint',
            include: projectRoot,
            exclude: /node_modules/
        }, {
            test: /\.js$/,
            loader: 'eslint',
            include: projectRoot,
            exclude: /node_modules/
        }],
        loaders: [{
            test: /\.vue$/,
            loader: 'vue'
        }, {
            test: /\.js$/,
            loader: 'babel',
            include: projectRoot,
            exclude: /node_modules/
        }, {
            test: /\.json$/,
            loader: 'json'
        }, {
            test: /\.html$/,
            loader: 'vue-html'
        }, {
            test: /\.(png|jpe?g|gif|svg|woff2?|eot|ttf|otf)(\?.*)?$/,
            loader: 'url',
            query: {
                limit: 10000,
                name: '[name].[hash:7].[ext]'
            }
        }]
    },
    vue: {
        loaders: {
            css: 'vue-style!css',
            less: 'vue-style!css!less'
        },
        postcss: [autoprefixer({
            browsers: ['last 3 versions']
        })]
    },
    eslint: {
        formatter: require('eslint-friendly-formatter')
    },
    babel: {
        presets: ['es2015', 'stage-2'],
        plugins: ['transform-runtime', 'lodash'],
        comments: false
    },
    postcss: [autoprefixer({
        browsers: ['last 3 versions']
    })],
    plugins: [
        new LodashWebpackPlugin()
    ]
}
<|endoftext|>


<commit_before>'use strict'

// import session so we can bind to it's proxies in 'registry.listener.global = ...'
// FIXME Force the user to import this namespace by eg. exposing the interface name as a scoped variable
const westfield = require('westfield-runtime-client')
const session = require('./protocol/session-client-protocol')
const WebSocket = require('ws')
const express = require('express')
const http = require('http')

module.exports = class LocalSession {
  /**
   *
   * @returns {Promise<LocalSession>}
   */
  static create () {
    return new Promise((resolve, reject) => {
      const app = express()
      app.use(express.static('/home/zubzub/git/greenfield/browser/public'))

      const server = http.createServer()
      server.on('request', app)
      const wss = new WebSocket.Server({
        server: server,
        path: '/greenfield'
      })

      const localSession = new LocalSession(wss, resolve)
      wss.on('connection', (ws) => {
        const wfcConnection = new westfield.Connection()

        wfcConnection.onSend = (data) => {
          ws.send(data)
        }

        ws.onmessage = (event) => {
          const b = event.data
          const arrayBuffer = b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength)
          wfcConnection.unmarshall(arrayBuffer)
        }

        // TODO listen for disconnect
        // TODO listen for error
        // TODO tie localSession &  to primaryConnection lifecycle

        if (localSession.primaryConnection) {
          localSession.connectionPromises.shift()(wfcConnection)
        } else {
          localSession.primaryConnection = wfcConnection

          const registryProxy = wfcConnection.createRegistry()
          registryProxy.listener.global = (name, interface_, version) => {
            if (interface_ === session.GrSessionName) {
              const grSessionProxy = registryProxy.bind(name, interface_, version)
              grSessionProxy.listener = localSession
              localSession.grSessionProxy = grSessionProxy

              resolve(localSession)
            }
          }
        }
      })

      server.listen(8080)
    })
  }

  /**
   *
   * @param {WebSocket.Server} wss
   */
  constructor (wss) {
    this._wss = wss
    this.primaryConnection = null
    this.connectionPromises = []
  }

  /**
   *
   * @returns {Promise<wfc.Connection>}
   */
  createConnection () {
    return new Promise((resolve, reject) => {
      this.connectionPromises.push(resolve)
      this.grSessionProxy.client()
    })
  }
}
<commit_msg>clarify TODO<commit_after>'use strict'

// import session so we can bind to it's proxies in 'registry.listener.global = ...'
// FIXME Force the user to import this namespace by eg. exposing the interface name as a scoped variable
const westfield = require('westfield-runtime-client')
const session = require('./protocol/session-client-protocol')
const WebSocket = require('ws')
const express = require('express')
const http = require('http')

module.exports = class LocalSession {
  /**
   *
   * @returns {Promise<LocalSession>}
   */
  static create () {
    return new Promise((resolve, reject) => {
      const app = express()
      app.use(express.static('/home/zubzub/git/greenfield/browser/public'))

      const server = http.createServer()
      server.on('request', app)
      const wss = new WebSocket.Server({
        server: server,
        path: '/greenfield'
      })

      const localSession = new LocalSession(wss, resolve)
      wss.on('connection', (ws) => {
        const wfcConnection = new westfield.Connection()

        wfcConnection.onSend = (data) => {
          ws.send(data)
        }

        ws.onmessage = (event) => {
          const b = event.data
          const arrayBuffer = b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength)
          wfcConnection.unmarshall(arrayBuffer)
        }

        // TODO listen for disconnect
        // TODO listen for error
        // TODO tie localSession to primaryConnection lifecycle, wayland apps should be tied to their own connection

        if (localSession.primaryConnection) {
          localSession.connectionPromises.shift()(wfcConnection)
        } else {
          localSession.primaryConnection = wfcConnection

          const registryProxy = wfcConnection.createRegistry()
          registryProxy.listener.global = (name, interface_, version) => {
            if (interface_ === session.GrSessionName) {
              const grSessionProxy = registryProxy.bind(name, interface_, version)
              grSessionProxy.listener = localSession
              localSession.grSessionProxy = grSessionProxy
              resolve(localSession)
            }
          }
        }
      })

      server.listen(8080)
    })
  }

  /**
   *
   * @param {WebSocket.Server} wss
   */
  constructor (wss) {
    this._wss = wss
    this.primaryConnection = null
    this.connectionPromises = []
  }

  /**
   *
   * @returns {Promise<wfc.Connection>}
   */
  createConnection () {
    return new Promise((resolve, reject) => {
      this.connectionPromises.push(resolve)
      this.grSessionProxy.client()
    })
  }
}
<|endoftext|>


<commit_before>/**
 * Creates an instance of a block
 */
Block = function(blocks, blockType, id)
{
    var defaultFont = 13;
    var defaultWidth = 170;
    var defaultInputWidth = 80;
    var self = this;

    // Id
    this.id = id;

    // Do I have focus ?
    this.hasFocus = false;

    // Division (object)
    this.div = null;

    // Is the user dragging ?
    this.drag = null;

    // Last scale
    this.lastScale = null;

    // Parameters
    this.parameters = null;
    this.parametersManager = null;

    // Position
    this.x = 0;
    this.y = 0;

    // I/Os cardinality
    this.ios = {};

    // Which IO has focus ?
    this.focusedIo = null;

    // Edges
    this.edges = {};

    /**
     * Parses the cardinality
     */
    this.parseCardinality = function(ioCard, isOutput)
    {
        var card = [0, 1];

        if (isOutput) {
            card = [0, '*'];
        }

        if (ioCard != undefined) {
            if (typeof(ioCard) != 'string') {
                card = [ioCard, ioCard];
            } else {
                tab = ioCard.split('-');
                if (tab.length == 1) {
                    card = [0, tab[0]];
                } else {
                    card = tab;
                }
            }
        }

        for (idx in card) {
            if (card[idx] != '*') {
                card[idx] = parseInt(card[idx]);
            }
        }

        return card;
    };

    /**
     * Parses a length
     */
    this.parseLength = function(length)
    {
        if (typeof(length) == 'number') {
            return length;
        }

        expression = length.split(/\./);

        if (expression.length == 2) {
            var key = expression[0];
            var operation = expression[1];

            if (operation == 'length') {
                return self.parametersManager.getParameterSize(key);
            }

            if (operation == 'value') {
                return parseInt(self.parameters[key]);
            }
        }
    };

    /**
     * Returns the render of the block
     */
    this.getHtml = function()
    {
	self.ios = {};

        html = '

';
        html += '
' + blockType.name + '#' + self.id + '

';
        if (blockType.description) {
            html += '

';
            html += '
' + blockType.description + '
';
        }
        html += '

';

        var parameters = self.parametersManager.fields;
        for (k in parameters) {
            var parameter = parameters[k];
            var parameterHtml = parameter.getHtml(self.parameters);
            var key = 'param_'+k;
            if (!blocks.compactMode || (self.edges[key]!=undefined && self.edges[key].length>0)) {
                var card = self.parseCardinality(parameter.card, false)
                self.ios[key] = card;
                if (parameterHtml) {
                    html += '
';
                    if (card[1] == '*' || card[1] > 0) {
                        html += '

';
                    }
                    html += parameterHtml+'
';
                }
            }
        }

        // Handling inputs & outputs
        handle = function(key) {
            html += '
';

            for (k in blockType[key+'s']) {
                var isVariadic = false;
                var io = blockType[key+'s'][k];

                var size = 1;
                if (io.length != undefined) {
                    isVariadic = true;
                    size = self.parseLength(io.length);
                }

                for (x=0; x<size; x++) {
                    var ion = key + '_' + k;
                    var label = io.name.replace('#', x+1);

                    if (isVariadic) {
                        ion += '_' + x;
                    }

                    // Generating HTML
                    html += '

' + label + '
';

                    // Setting cardinality
                    self.ios[ion] = self.parseCardinality(io.card, (key == 'output'));
                }
            }
                html += '
';
        };

        handle('input');
        handle('output');
	this.checkEdges();

        return html;
    };

    /**
     * Render the block
     */
    this.render = function()
    {
        this.lastScale = null;
        this.hasFocus = false;
        this.div.html(this.getHtml());
        this.initListeners();
        this.redraw();
    };

    /**
     * Creates and inject the div
     */
    this.create = function(div)
    {
        html = '

'

        div.append(html);
        this.div = div.find('#block' + this.id);

        if (this.parametersManager == undefined) {
            this.parametersManager = new ParametersManager(blockType, this);
	    if (this.parameters == null) {
                this.parameters = this.parametersManager.getDefaults();
	    }
        }

        this.render();
    };

    /**
     * Sets the position and the scale of the block
     */
    this.redraw = function(selected)
    {
        // Setting the position
        self.div.css('margin-left', blocks.center.x+self.x*blocks.scale+'px');
        self.div.css('margin-top', blocks.center.y+self.y*blocks.scale+'px');

        // Rescaling
        if (this.lastScale != blocks.scale) {
            self.div.css('font-size', Math.round(blocks.scale*defaultFont)+'px');
            self.div.css('width', Math.round(blocks.scale*defaultWidth)+'px');

            var size = Math.round(12*blocks.scale);
            self.div.find('.circle').css('width', size+'px');
            self.div.find('.circle').css('height', size+'px');
            self.div.find('.circle').css('background-size', size+'px '+size+'px');

            self.div.find('.inputs, .outputs').width(self.div.width()/2-10);

            self.cssParameters();
            this.lastScale = blocks.scale
        }

        // Changing the circle rendering
        for (k in self.ios) {
            var circle = self.div.find('.' + k + ' .circle');

            circle.removeClass('io_active');
            if (self.edges[k] != undefined && self.edges[k].length) {
                circle.addClass('io_active');
            }
        }

        // Updating the parameters manager div
        this.parametersManager.div = this.div.find('.parameters');

        // Is selected ?
        self.div.removeClass('block_selected');
        if (selected) {
            self.div.addClass('block_selected');
        }
    };

    /**
     * Sets the css for the inputs
     */
    this.cssParameters = function()
    {
        self.div.find('input').css('font-size', Math.round(blocks.scale*defaultFont)+'px');
        self.div.find('input').css('width', Math.round(blocks.scale*defaultInputWidth)+'px');
        self.div.find('.parameters').css('width', Math.round(blocks.scale*defaultWidth)+'px');
    };

    /**
     * Init the function listeners
     */
    this.initListeners = function()
    {
        // Drag & drop the block
        self.div.find('.blockTitle').mousedown(function(event) {
            if (event.which == 1) {
                self.drag = [blocks.mouseX/blocks.scale-self.x, blocks.mouseY/blocks.scale-self.y];
            }
        });

        // Handle focus
        self.div.hover(function() {
            self.hasFocus = true;
        }, function() {
            self.hasFocus = false;
        });

        // Handle focus on the I/Os
        self.div.find('.input, .output, .parameter').hover(function() {
            self.focusedIo = $(this).attr('rel');
        }, function() {
            self.focusedIo = null;
        });

        // Dragging
        $('html').mousemove(function(evt) {
            if (self.drag) {
                self.x = (blocks.mouseX/blocks.scale-self.drag[0]);
                self.y = (blocks.mouseY/blocks.scale-self.drag[1]);
                blocks.redraw();
            }
        });

        // Drag the block
        $('html').mouseup(function() {
            self.drag = null;
        });

        // Draw a link
        self.div.find('.input, .output').mousedown(function(event) {
            if (event.which == 1) {
                blocks.beginLink(self, $(this).attr('rel'));
                event.preventDefault();
            }
        });

        // Handle the parameters
        self.div.find('.gear').click(function() {
            self.parametersManager.toggle();
            self.cssParameters();
        });

        // Handle the deletion
        self.div.find('.delete').click(function() {
            blocks.removeBlock(blocks.getBlockId(self));
        });

        // Show the description
        self.div.find('.info').hover(function() {
            self.div.find('.description').show();
        }, function() {
            self.div.find('.description').hide();
        });
    };

    /**
     * Gets the link position for an input or output
     */
    this.linkPositionFor = function(io)
    {
        try {
            div = self.div.find('.' + io + ' .circle')

            var x = (div.offset().left-blocks.div.offset().left)+div.width()/2;
            var y = (div.offset().top-blocks.div.offset().top)+div.height()/2;
        } catch (error) {
            throw 'Unable to find link position for '+io+' ('+error+')';
        }

        return {x: x, y: y};
    };

    /**
     * Can the io be linked ?
     */
    this.canLink = function(ion)
    {
        var tab = [];
        if (this.edges[ion] != undefined) {
            tab = this.edges[ion];
        }

        var card = this.ios[ion];

        if (card[1] != '*') {
            return (tab.length < card[1]);
        }

        return true;
    };

    /**
     * Add an edge
     */
    this.addEdge = function(ion, edge)
    {
        var tab = [];
        if (this.edges[ion] != undefined) {
            tab = this.edges[ion];
        }

        tab.push(edge);
        this.edges[ion] = tab;
    };

    /**
     * Check that all edges reference a valid I/O
     */
    this.checkEdges = function()
    {
	var toDelete = [];
	for (ion in this.edges) {
	    var edges = this.edges[ion];

	    if (!(ion in this.ios)) {
		for (k in edges) {
		    toDelete.push(edges[k]);
		}

		delete this.edges[ion];
	    }
	}

	for (k in toDelete) {
	    blocks.removeEdge(blocks.getEdgeId(toDelete[k]));
	}

	if (toDelete.length) {
	    blocks.redraw();
	}
    };

    /**
     * Erase an edge
     */
    this.eraseEdge = function(ion, edge)
    {
        if (this.edges[ion] != undefined) {
            for (k in this.edges[ion]) {
                if (this.edges[ion][k] == edge) {
                    arrayRemove(this.edges[ion], k);
                    break;
                }
            }
        }
    };

    /**
     * Erase the block
     */
    this.erase = function()
    {
        self.div.remove();
    };

    /**
     * Find all successors of a block, and their successors
     */
    this.allSuccessors = function()
    {
        // Blocks already explored
        var explored = {};
        var exploreList = [this];
        var ids = [this.id];
        explored[this.id] = true;

        while (exploreList.length > 0) {
            var currentBlock = exploreList.pop();

            for (key in currentBlock.edges) {
                for (i in currentBlock.edges[key]) {
                    fromTo = currentBlock.edges[key][i].fromTo();

                    if (fromTo[0] == currentBlock) {
                        target = fromTo[1];

                        if (!(target.id in explored)) {
                            explored[target.id] = true;
                            exploreList.push(target);
                            ids.push(target.id);
                        }
                    }
                }
            }
        }

        return ids;
    };

    /**
     * Exports the block to JSON
     */
    this.exportData = function()
    {
	return {
	    id: this.id,
	    x: this.x,
	    y: this.y,
	    type: blockType.name,
	    parameters: this.parametersManager.exportData(this.parameters)
	};
    };
};

/**
 * Imports a block from its data
 */
function BlockImport(blocks, data)
{
    for (t in blocks.blockTypes) {
	var blockType = blocks.blockTypes[t];
	if (blockType.name == data.type) {
	    var block = new Block(blocks, blockType, data.id);
	    block.x = data.x;
	    block.y = data.y;
	    block.parameters = ParametersImport(data.parameters);
	    return block;
	}
    }

    throw 'Unable to create a block of type ' + data.type;
};
<commit_msg>Decreasing default font<commit_after>/**
 * Creates an instance of a block
 */
Block = function(blocks, blockType, id)
{
    var defaultFont = 12;
    var defaultWidth = 170;
    var defaultInputWidth = 80;
    var self = this;

    // Id
    this.id = id;

    // Do I have focus ?
    this.hasFocus = false;

    // Division (object)
    this.div = null;

    // Is the user dragging ?
    this.drag = null;

    // Last scale
    this.lastScale = null;

    // Parameters
    this.parameters = null;
    this.parametersManager = null;

    // Position
    this.x = 0;
    this.y = 0;

    // I/Os cardinality
    this.ios = {};

    // Which IO has focus ?
    this.focusedIo = null;

    // Edges
    this.edges = {};

    /**
     * Parses the cardinality
     */
    this.parseCardinality = function(ioCard, isOutput)
    {
        var card = [0, 1];

        if (isOutput) {
            card = [0, '*'];
        }

        if (ioCard != undefined) {
            if (typeof(ioCard) != 'string') {
                card = [ioCard, ioCard];
            } else {
                tab = ioCard.split('-');
                if (tab.length == 1) {
                    card = [0, tab[0]];
                } else {
                    card = tab;
                }
            }
        }

        for (idx in card) {
            if (card[idx] != '*') {
                card[idx] = parseInt(card[idx]);
            }
        }

        return card;
    };

    /**
     * Parses a length
     */
    this.parseLength = function(length)
    {
        if (typeof(length) == 'number') {
            return length;
        }

        expression = length.split(/\./);

        if (expression.length == 2) {
            var key = expression[0];
            var operation = expression[1];

            if (operation == 'length') {
                return self.parametersManager.getParameterSize(key);
            }

            if (operation == 'value') {
                return parseInt(self.parameters[key]);
            }
        }
    };

    /**
     * Returns the render of the block
     */
    this.getHtml = function()
    {
	self.ios = {};

        html = '

';
        html += '
' + blockType.name + '#' + self.id + '

';
        if (blockType.description) {
            html += '

';
            html += '
' + blockType.description + '
';
        }
        html += '

';

        var parameters = self.parametersManager.fields;
        for (k in parameters) {
            var parameter = parameters[k];
            var parameterHtml = parameter.getHtml(self.parameters);
            var key = 'param_'+k;
            if (!blocks.compactMode || (self.edges[key]!=undefined && self.edges[key].length>0)) {
                var card = self.parseCardinality(parameter.card, false)
                self.ios[key] = card;
                if (parameterHtml) {
                    html += '
';
                    if (card[1] == '*' || card[1] > 0) {
                        html += '

';
                    }
                    html += parameterHtml+'
';
                }
            }
        }

        // Handling inputs & outputs
        handle = function(key) {
            html += '
';

            for (k in blockType[key+'s']) {
                var isVariadic = false;
                var io = blockType[key+'s'][k];

                var size = 1;
                if (io.length != undefined) {
                    isVariadic = true;
                    size = self.parseLength(io.length);
                }

                for (x=0; x<size; x++) {
                    var ion = key + '_' + k;
                    var label = io.name.replace('#', x+1);

                    if (isVariadic) {
                        ion += '_' + x;
                    }

                    // Generating HTML
                    html += '

' + label + '
';

                    // Setting cardinality
                    self.ios[ion] = self.parseCardinality(io.card, (key == 'output'));
                }
            }
                html += '
';
        };

        handle('input');
        handle('output');
	this.checkEdges();

        return html;
    };

    /**
     * Render the block
     */
    this.render = function()
    {
        this.lastScale = null;
        this.hasFocus = false;
        this.div.html(this.getHtml());
        this.initListeners();
        this.redraw();
    };

    /**
     * Creates and inject the div
     */
    this.create = function(div)
    {
        html = '

'

        div.append(html);
        this.div = div.find('#block' + this.id);

        if (this.parametersManager == undefined) {
            this.parametersManager = new ParametersManager(blockType, this);
	    if (this.parameters == null) {
                this.parameters = this.parametersManager.getDefaults();
	    }
        }

        this.render();
    };

    /**
     * Sets the position and the scale of the block
     */
    this.redraw = function(selected)
    {
        // Setting the position
        self.div.css('margin-left', blocks.center.x+self.x*blocks.scale+'px');
        self.div.css('margin-top', blocks.center.y+self.y*blocks.scale+'px');

        // Rescaling
        if (this.lastScale != blocks.scale) {
            self.div.css('font-size', Math.round(blocks.scale*defaultFont)+'px');
            self.div.css('width', Math.round(blocks.scale*defaultWidth)+'px');

            var size = Math.round(12*blocks.scale);
            self.div.find('.circle').css('width', size+'px');
            self.div.find('.circle').css('height', size+'px');
            self.div.find('.circle').css('background-size', size+'px '+size+'px');

            self.div.find('.inputs, .outputs').width(self.div.width()/2-10);

            self.cssParameters();
            this.lastScale = blocks.scale
        }

        // Changing the circle rendering
        for (k in self.ios) {
            var circle = self.div.find('.' + k + ' .circle');

            circle.removeClass('io_active');
            if (self.edges[k] != undefined && self.edges[k].length) {
                circle.addClass('io_active');
            }
        }

        // Updating the parameters manager div
        this.parametersManager.div = this.div.find('.parameters');

        // Is selected ?
        self.div.removeClass('block_selected');
        if (selected) {
            self.div.addClass('block_selected');
        }
    };

    /**
     * Sets the css for the inputs
     */
    this.cssParameters = function()
    {
        self.div.find('input').css('font-size', Math.round(blocks.scale*defaultFont)+'px');
        self.div.find('input').css('width', Math.round(blocks.scale*defaultInputWidth)+'px');
        self.div.find('.parameters').css('width', Math.round(blocks.scale*defaultWidth)+'px');
    };

    /**
     * Init the function listeners
     */
    this.initListeners = function()
    {
        // Drag & drop the block
        self.div.find('.blockTitle').mousedown(function(event) {
            if (event.which == 1) {
                self.drag = [blocks.mouseX/blocks.scale-self.x, blocks.mouseY/blocks.scale-self.y];
            }
        });

        // Handle focus
        self.div.hover(function() {
            self.hasFocus = true;
        }, function() {
            self.hasFocus = false;
        });

        // Handle focus on the I/Os
        self.div.find('.input, .output, .parameter').hover(function() {
            self.focusedIo = $(this).attr('rel');
        }, function() {
            self.focusedIo = null;
        });

        // Dragging
        $('html').mousemove(function(evt) {
            if (self.drag) {
                self.x = (blocks.mouseX/blocks.scale-self.drag[0]);
                self.y = (blocks.mouseY/blocks.scale-self.drag[1]);
                blocks.redraw();
            }
        });

        // Drag the block
        $('html').mouseup(function() {
            self.drag = null;
        });

        // Draw a link
        self.div.find('.input, .output').mousedown(function(event) {
            if (event.which == 1) {
                blocks.beginLink(self, $(this).attr('rel'));
                event.preventDefault();
            }
        });

        // Handle the parameters
        self.div.find('.gear').click(function() {
            self.parametersManager.toggle();
            self.cssParameters();
        });

        // Handle the deletion
        self.div.find('.delete').click(function() {
            blocks.removeBlock(blocks.getBlockId(self));
        });

        // Show the description
        self.div.find('.info').hover(function() {
            self.div.find('.description').show();
        }, function() {
            self.div.find('.description').hide();
        });
    };

    /**
     * Gets the link position for an input or output
     */
    this.linkPositionFor = function(io)
    {
        try {
            div = self.div.find('.' + io + ' .circle')

            var x = (div.offset().left-blocks.div.offset().left)+div.width()/2;
            var y = (div.offset().top-blocks.div.offset().top)+div.height()/2;
        } catch (error) {
            throw 'Unable to find link position for '+io+' ('+error+')';
        }

        return {x: x, y: y};
    };

    /**
     * Can the io be linked ?
     */
    this.canLink = function(ion)
    {
        var tab = [];
        if (this.edges[ion] != undefined) {
            tab = this.edges[ion];
        }

        var card = this.ios[ion];

        if (card[1] != '*') {
            return (tab.length < card[1]);
        }

        return true;
    };

    /**
     * Add an edge
     */
    this.addEdge = function(ion, edge)
    {
        var tab = [];
        if (this.edges[ion] != undefined) {
            tab = this.edges[ion];
        }

        tab.push(edge);
        this.edges[ion] = tab;
    };

    /**
     * Check that all edges reference a valid I/O
     */
    this.checkEdges = function()
    {
	var toDelete = [];
	for (ion in this.edges) {
	    var edges = this.edges[ion];

	    if (!(ion in this.ios)) {
		for (k in edges) {
		    toDelete.push(edges[k]);
		}

		delete this.edges[ion];
	    }
	}

	for (k in toDelete) {
	    blocks.removeEdge(blocks.getEdgeId(toDelete[k]));
	}

	if (toDelete.length) {
	    blocks.redraw();
	}
    };

    /**
     * Erase an edge
     */
    this.eraseEdge = function(ion, edge)
    {
        if (this.edges[ion] != undefined) {
            for (k in this.edges[ion]) {
                if (this.edges[ion][k] == edge) {
                    arrayRemove(this.edges[ion], k);
                    break;
                }
            }
        }
    };

    /**
     * Erase the block
     */
    this.erase = function()
    {
        self.div.remove();
    };

    /**
     * Find all successors of a block, and their successors
     */
    this.allSuccessors = function()
    {
        // Blocks already explored
        var explored = {};
        var exploreList = [this];
        var ids = [this.id];
        explored[this.id] = true;

        while (exploreList.length > 0) {
            var currentBlock = exploreList.pop();

            for (key in currentBlock.edges) {
                for (i in currentBlock.edges[key]) {
                    fromTo = currentBlock.edges[key][i].fromTo();

                    if (fromTo[0] == currentBlock) {
                        target = fromTo[1];

                        if (!(target.id in explored)) {
                            explored[target.id] = true;
                            exploreList.push(target);
                            ids.push(target.id);
                        }
                    }
                }
            }
        }

        return ids;
    };

    /**
     * Exports the block to JSON
     */
    this.exportData = function()
    {
	return {
	    id: this.id,
	    x: this.x,
	    y: this.y,
	    type: blockType.name,
	    parameters: this.parametersManager.exportData(this.parameters)
	};
    };
};

/**
 * Imports a block from its data
 */
function BlockImport(blocks, data)
{
    for (t in blocks.blockTypes) {
	var blockType = blocks.blockTypes[t];
	if (blockType.name == data.type) {
	    var block = new Block(blocks, blockType, data.id);
	    block.x = data.x;
	    block.y = data.y;
	    block.parameters = ParametersImport(data.parameters);
	    return block;
	}
    }

    throw 'Unable to create a block of type ' + data.type;
};
<|endoftext|>


<commit_before>(function() {
    'use strict';

    var app         = require('app'),  // Module to control application life.
        cloudcmd    = require('cloudcmd');

    var BrowserWindow = require('browser-window');  // Module to create native browser window.

    // Report crashes to our server.
    require('crash-reporter').start();

    // Keep a global reference of the window object, if you don't, the window will
    // be closed automatically when the javascript object is GCed.
    var mainWindow = null;

    // Quit when all windows are closed.
    app.on('window-all-closed', function() {
      if (process.platform !== 'darwin')
        app.quit();
    });

    // This method will be called when atom-shell has done everything
    // initialization and ready for creating browser windows.
    app.on('ready', function() {
      var webContents;
      // Create the browser window.
      mainWindow = new BrowserWindow({width: 800, height: 600}),
      webContents = mainWindow.webContents;

      // and load the index.html of the app.

      mainWindow.loadUrl('http://localhost:8000');

      webContents.on('did-finish-load', function() {
          webContents.executeJavaScript('window.module = undefined');
          mainWindow.openDevTools();
      });

      // Emitted when the window is closed.
      mainWindow.on('closed', function() {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        mainWindow = null;
      });
    });
})();
<commit_msg>feature(main) add node-intergration: disabled<commit_after>(function() {
    'use strict';

    var app         = require('app');  // Module to control application life.

    try {
        require('cloudcmd');
    } catch(error) {

    }

    var BrowserWindow = require('browser-window');  // Module to create native browser window.

    // Report crashes to our server.
    require('crash-reporter').start();

    // Keep a global reference of the window object, if you don't, the window will
    // be closed automatically when the javascript object is GCed.
    var mainWindow = null;

    // Quit when all windows are closed.
    app.on('window-all-closed', function() {
      if (process.platform !== 'darwin')
        app.quit();
    });

    // This method will be called when atom-shell has done everything
    // initialization and ready for creating browser windows.
    app.on('ready', function() {
      // Create the browser window.
      mainWindow = new BrowserWindow({
        'width': 1200,
        'height': 820,
        'node-integration': 'disable'
      }),

      mainWindow.loadUrl('http://localhost:8000');

      // and load the index.html of the app.
      /*
      mainWindow.webContents.on('did-finish-load', function() {
          mainWindow.openDevTools();
      });
      */

      // Emitted when the window is closed.
      mainWindow.on('closed', function() {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        mainWindow = null;
      });
    });
})();
<|endoftext|>


<commit_before>/*
   run this command in project root folder for production build:
   r.js -o js/build.js
   server the assets from /build folder in production
*/
({
    appDir: '../',
    baseUrl: 'js',
    dir: '../build',
    mainConfigFile: 'common.js',
    optimize: 'uglify2',
    optimizeCss: 'standard',
    modules: [
        {
            name: 'common',
            include: [
                'Api',
                'AppRouter',
                'Page'
                /* TODO: add other common modules */
            ]
        },
        {
            name: 'Error',
            exclude: ['common']
        },
        {
            name: 'Home',
            exclude: ['common']
        },
        {
            name: 'PathSubPath',
            exclude: ['common']
        }
        /* TODO: add other page modules */
    ]
})
<commit_msg>Update build.js<commit_after>/*
   run this command in project root folder for production build:
   r.js -o js/build.js
   serve the assets from /build folder in production
*/
({
    appDir: '../',
    baseUrl: 'js',
    dir: '../build',
    mainConfigFile: 'common.js',
    optimize: 'uglify2',
    optimizeCss: 'standard',
    modules: [
        {
            name: 'common',
            include: [
                'Api',
                'AppRouter',
                'Page'
                /* TODO: add other common modules */
            ]
        },
        {
            name: 'Error',
            exclude: ['common']
        },
        {
            name: 'Home',
            exclude: ['common']
        },
        {
            name: 'PathSubPath',
            exclude: ['common']
        }
        /* TODO: add other page modules */
    ]
})
<|endoftext|>


<commit_before>var canvas = document.getElementById('canvas');
var max = 500;
var width = Math.min(window.innerWidth, max);
var height = width;
var ctx = canvas.getContext('2d');
var img = document.createElement('img');
var button = document.getElementById('share');
var loaded = false;
var thoughtText = '';
var thought = document.getElementById('thought');

function dataURItoBlob(dataURI) {
  // convert base64/URLEncoded data component to raw binary data held in a string
  var byteString;
  if (dataURI.split(',')[0].indexOf('base64') >= 0)
      byteString = atob(dataURI.split(',')[1]);
  else
      byteString = unescape(dataURI.split(',')[1]);

  // separate out the mime component
  var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

  // write the bytes of the string to a typed array
  var ia = new Uint8Array(byteString.length);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }

  return new Blob([ia], {type:mimeString});
}

function postImageToFacebook( authToken, filename, mimeType, imageData, message )
{
    var data = new FormData();
    data.append('source', dataURItoBlob(imageData), filename);
    data.append('message', message);

    var xhr = new XMLHttpRequest();
    xhr.open( 'POST', 'https://graph.facebook.com/me/photos?access_token=' + authToken, true );
    xhr.onload = xhr.onerror = function() {
      console.log( xhr.responseText );
      try {
        var res = JSON.parse(xhr.responseText);
        if (res.id) {
          var link = document.getElementById('shared-link');
          link.setAttribute('href', 'https://www.facebook.com/photo.php?fbid=' + res.id);
          $('.shared-link-modal').modal({show: true});
          ga('send', 'event', 'Photos', 'upload');
          button.classList.remove('disabled');
        }
      }
      catch(e) {
        console.error(e);
      }
    };
    xhr.send(data);
}

function updateText(val, offset) {
  offset = offset || 0;
  thoughtText = val;
  var fontSize = 0.05 * width;
  ctx.fillStyle = 'white';
  ctx.fillRect(0, 0, width, height);

  if (loaded) {
    var devicePixelRatio = window.devicePixelRatio || 1;
    ctx.drawImage(img, 0, offset * devicePixelRatio, width * devicePixelRatio, height * devicePixelRatio);
  }

  ctx.fillStyle = '#000000'
  ctx.font = fontSize + 'px PingFangTC-Regular, sans-serif';
  ctx.save();
  thoughtText.split('\n').forEach((line, index) => {
    ctx.fillText(line, 0.28 * width, 0.40 * width + (fontSize * index * 1.2) + offset);
  });
  ctx.restore();
}

function update(offset) {
  offset = offset || 0;
  console.log('window width', window.innerWidth);
  width = Math.min(window.innerWidth, max);
  height = width * img.naturalHeight / img.naturalWidth;
  canvas.setAttribute('width', width);
  canvas.setAttribute('height', height + offset);
  ctx = canvas.getContext('2d');
  updateText(thought.value, offset);
}

function setupFb() {
  FB.getLoginStatus(function(response) {
    var login = false;
    var token;
    if (response.status === 'connected') {
      login = true;
      token = response.authResponse.accessToken;
      button.innerText = '分享到 Facebook';
    }
    else {
      button.innerText = '連接 Facebook 分享此圖';
    }

    button.addEventListener('click', evt => {
      if (login) {
        button.classList.add('disabled');
        update(35);
        ctx.fillRect(0, 0, width, 33);
        ctx.fillStyle = '#FFFFFF';
        ctx.font = '20px PingFangTC-Regular, sans-serif';
        var msg = '小孩，不是你的工具。';
        var textwidth = ctx.measureText(msg).width;
        ctx.fillText('小孩，不是你的工具。', (width - textwidth) / 2, 25);

        var c = canvas.toDataURL('image/png');
        var encodedPng = c.substring(c.indexOf(',')+1,c.length);
        var decodedPng = Base64Binary.decode(encodedPng);
        var msg = ['小孩，不是你的工具。',
                   '　',
                   '插圖：謝東霖 Hsieh Tung Lin',
                   '產生自己的圖片： https://yurenju.github.io/youknownothing'];
        postImageToFacebook(token, 'thought.png', 'image/png', canvas.toDataURL('image/png'), msg.join('\n'));
        update();
      }
      else {
        FB.login(response => {
          login = response.status === 'connected'
          if (login) {
            token = response.authResponse.accessToken;
            button.innerText = '分享到 Facebook';
          }
        }, {scope: 'publish_actions'});
      }
    });
  });
}

img.src = 'original.jpg';
img.onload = function () {
  loaded = true;
  update();
}

thought.addEventListener('input', evt => updateText(evt.target.value));
window.addEventListener('resize', evt => update());

window.fbAsyncInit = function() {
  FB.init({
    appId      : '390592127957211',
    xfbml      : true,
    version    : 'v2.8'
  });
  FB.AppEvents.logPageView();
  setupFb();
};

(function(d, s, id){
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) {return;}
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));<commit_msg>remove redundant code<commit_after>var canvas = document.getElementById('canvas');
var max = 500;
var width = Math.min(window.innerWidth, max);
var height = width;
var ctx = canvas.getContext('2d');
var img = document.createElement('img');
var button = document.getElementById('share');
var loaded = false;
var thoughtText = '';
var thought = document.getElementById('thought');

function dataURItoBlob(dataURI) {
  // convert base64/URLEncoded data component to raw binary data held in a string
  var byteString;
  if (dataURI.split(',')[0].indexOf('base64') >= 0)
      byteString = atob(dataURI.split(',')[1]);
  else
      byteString = unescape(dataURI.split(',')[1]);

  // separate out the mime component
  var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

  // write the bytes of the string to a typed array
  var ia = new Uint8Array(byteString.length);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }

  return new Blob([ia], {type:mimeString});
}

function postImageToFacebook( authToken, filename, mimeType, imageData, message )
{
    var data = new FormData();
    data.append('source', dataURItoBlob(imageData), filename);
    data.append('message', message);

    var xhr = new XMLHttpRequest();
    xhr.open( 'POST', 'https://graph.facebook.com/me/photos?access_token=' + authToken, true );
    xhr.onload = xhr.onerror = function() {
      console.log( xhr.responseText );
      try {
        var res = JSON.parse(xhr.responseText);
        if (res.id) {
          var link = document.getElementById('shared-link');
          link.setAttribute('href', 'https://www.facebook.com/photo.php?fbid=' + res.id);
          $('.shared-link-modal').modal({show: true});
          ga('send', 'event', 'Photos', 'upload');
          button.classList.remove('disabled');
        }
      }
      catch(e) {
        console.error(e);
      }
    };
    xhr.send(data);
}

function updateText(val, offset) {
  offset = offset || 0;
  thoughtText = val;
  var fontSize = 0.05 * width;
  ctx.fillStyle = 'white';
  ctx.fillRect(0, 0, width, height);

  if (loaded) {
    var devicePixelRatio = window.devicePixelRatio || 1;
    ctx.drawImage(img, 0, offset * devicePixelRatio, width * devicePixelRatio, height * devicePixelRatio);
  }

  ctx.fillStyle = '#000000'
  ctx.font = fontSize + 'px PingFangTC-Regular, sans-serif';
  ctx.save();
  thoughtText.split('\n').forEach((line, index) => {
    ctx.fillText(line, 0.28 * width, 0.40 * width + (fontSize * index * 1.2) + offset);
  });
  ctx.restore();
}

function update(offset) {
  offset = offset || 0;
  console.log('window width', window.innerWidth);
  width = Math.min(window.innerWidth, max);
  height = width * img.naturalHeight / img.naturalWidth;
  canvas.setAttribute('width', width);
  canvas.setAttribute('height', height + offset);
  ctx = canvas.getContext('2d');
  updateText(thought.value, offset);
}

function setupFb() {
  FB.getLoginStatus(function(response) {
    var login = false;
    var token;
    if (response.status === 'connected') {
      login = true;
      token = response.authResponse.accessToken;
      button.innerText = '分享到 Facebook';
    }
    else {
      button.innerText = '連接 Facebook 分享此圖';
    }

    button.addEventListener('click', evt => {
      if (login) {
        button.classList.add('disabled');
        update(35);
        ctx.fillRect(0, 0, width, 33);
        ctx.fillStyle = '#FFFFFF';
        ctx.font = '20px PingFangTC-Regular, sans-serif';
        var msg = '小孩，不是你的工具。';
        var textwidth = ctx.measureText(msg).width;
        ctx.fillText('小孩，不是你的工具。', (width - textwidth) / 2, 25);

        var msg = ['小孩，不是你的工具。',
                   '　',
                   '插圖：謝東霖 Hsieh Tung Lin',
                   '產生自己的圖片： https://yurenju.github.io/youknownothing'];
        postImageToFacebook(token, 'thought.png', 'image/png', canvas.toDataURL('image/png'), msg.join('\n'));
        update();
      }
      else {
        FB.login(response => {
          login = response.status === 'connected'
          if (login) {
            token = response.authResponse.accessToken;
            button.innerText = '分享到 Facebook';
          }
        }, {scope: 'publish_actions'});
      }
    });
  });
}

img.src = 'original.jpg';
img.onload = function () {
  loaded = true;
  update();
}

thought.addEventListener('input', evt => updateText(evt.target.value));
window.addEventListener('resize', evt => update());

window.fbAsyncInit = function() {
  FB.init({
    appId      : '390592127957211',
    xfbml      : true,
    version    : 'v2.8'
  });
  FB.AppEvents.logPageView();
  setupFb();
};

(function(d, s, id){
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) {return;}
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));<|endoftext|>


<commit_before>require('coffeescript/register')
pageHelper = require('../helpers/pageHelper.coffee')

// GK: a couple of these are dependent on the poll page which we haven't done yet

module.exports = {
  // group invitation form
  'invite_to_group': (test) => {
    page = pageHelper(test)
    page.loadPath('setup_group')
    page.click('.group-page-members-tab')
    page.click('.membership-card__invite', 1000)
    page.fillIn('.announcement-form__input input', 'test@example.com')
    page.expectText('.announcement-chip__content', 'test@example.com')
    page.click('.announcement-chip__content')
    page.expectElement('.headline')
    page.click('.announcement-form__submit')
    page.expectFlash('1 notifications sent')
  },

  // discussion form
  'new_discussion': (test) => {
    page = pageHelper(test)

    page.loadPath('setup_group')
    page.click('.discussions-panel__new-thread-button')
    page.fillIn('.announcement-form__input input', 'test@example.com')
    page.expectText('.announcement-chip__content', 'test@example.com')
    page.click('.announcement-chip__content')
    page.fillIn('.discussion-form__title-input input', 'Immannounce dis')
    page.expectText('.discussion-form__number-notified', '4 people will be notified')
    page.click('.discussion-form__submit')
    page.expectFlash('Thread started')
    // page.expectElement('.announcement-form')
    // page.click('.announcement-form__audience')
    // page.click('.announcement-form__submit', 1000)
    // page.expectFlash('2 notifications sent')
  },

  // strand members list
  'announcement_created': (test) => {
    page = pageHelper(test)

    page.loadPath('setup_discussion')
    page.pause(500)
    page.click('.action-dock__button--announce_thread')
    page.expectElement('.strand-members-list')
    page.pause(500)
    page.fillIn('.announcement-form__input input', 'test@example.com')
    page.expectText('.announcement-chip__content', 'test@example.com')
    page.click('.announcement-chip__content')
    page.expectElement('.headline')
    page.click('.strand-members-list__submit')
    page.expectText('.strand-members-list', 'test@example.com')
    page.expectFlash('1 notifications sent')
  },

  // poll members list
  'poll_created': (test) => {
    page = pageHelper(test)

    page.loadPath('setup_discussion')
    page.click('.activity-panel__add-proposal')
    page.fillIn('.poll-common-form-fields__title input', 'A new proposal')
    page.fillIn('.poll-common-form-fields .lmo-textarea div[contenteditable=true]', 'Some details')
    page.click('.poll-common-form__submit')
    page.expectFlash('Proposal started')
    page.pause(500)

    page.expectElement('.poll-members-list')
    page.fillIn('.announcement-form__input input', 'test@example.com')
    page.expectText('.announcement-chip__content', 'test@example.com')
    page.click('.announcement-chip__content')
    page.expectElement('.headline')
    page.click('.poll-members-list__submit')
    page.expectFlash('1 notifications sent')
  },

  // 'poll_edited': (test) => {
  //   page = pageHelper(test)
  //
  //   page.loadPath('test_poll_in_discussion', { controller: 'polls' })
  //   page.click('.action-dock__button--edit_poll')
  //   page.fillIn('.poll-common-form-fields__title', 'Yo reliability, whatsup? Its me, ya boi, testing')
  //   page.click('.poll-common-form__submit')
  //   page.expectElement('.announcement-form')
  //   page.click('.announcement-form__audience')
  //   page.click('.announcement-form__submit')
  //   page.expectFlash('1 notifications sent')
  // },

  // 'outcome_created': (test) => {
  //   page = pageHelper(test)
  //
  //   page.loadPath('test_proposal_poll_closed', { controller: 'polls' })
  //   page.click('.poll-common-set-outcome-panel__submit')
  //   page.fillIn('.poll-common-outcome-form__statement textarea', 'Immannounce all yall')
  //   page.click('.poll-common-outcome-form__submit')
  //   page.expectFlash('Outcome created')
  //   page.expectElement('.announcement-form')
  //   page.selectFromAutocomplete('.announcement-form__invite input', 'test@example.com')
  //   page.expectText('.announcement-chip__content', 'test@example.com')
  //   page.click('.announcement-form__submit')
  //   page.pause(3000)
  //   page.expectFlash('1 notifications sent')
  // }
}
<commit_msg>don't show count of those notified<commit_after>require('coffeescript/register')
pageHelper = require('../helpers/pageHelper.coffee')

// GK: a couple of these are dependent on the poll page which we haven't done yet

module.exports = {
  // group invitation form
  'invite_to_group': (test) => {
    page = pageHelper(test)
    page.loadPath('setup_group')
    page.click('.group-page-members-tab')
    page.click('.membership-card__invite', 1000)
    page.fillIn('.announcement-form__input input', 'test@example.com')
    page.expectText('.announcement-chip__content', 'test@example.com')
    page.click('.announcement-chip__content')
    page.expectElement('.headline')
    page.click('.announcement-form__submit')
    page.expectFlash('1 notifications sent')
  },

  // discussion form
  'new_discussion': (test) => {
    page = pageHelper(test)

    page.loadPath('setup_group')
    page.click('.discussions-panel__new-thread-button')
    page.fillIn('.announcement-form__input input', 'test@example.com')
    page.expectText('.announcement-chip__content', 'test@example.com')
    page.click('.announcement-chip__content')
    page.fillIn('.discussion-form__title-input input', 'Immannounce dis')
    // page.expectText('.discussion-form__number-notified', '4 people will be notified')
    page.click('.discussion-form__submit')
    page.expectFlash('Thread started')
    // page.expectElement('.announcement-form')
    // page.click('.announcement-form__audience')
    // page.click('.announcement-form__submit', 1000)
    // page.expectFlash('2 notifications sent')
  },

  // strand members list
  'announcement_created': (test) => {
    page = pageHelper(test)

    page.loadPath('setup_discussion')
    page.pause(500)
    page.click('.action-dock__button--announce_thread')
    page.expectElement('.strand-members-list')
    page.pause(500)
    page.fillIn('.announcement-form__input input', 'test@example.com')
    page.expectText('.announcement-chip__content', 'test@example.com')
    page.click('.announcement-chip__content')
    page.expectElement('.headline')
    page.click('.strand-members-list__submit')
    page.expectText('.strand-members-list', 'test@example.com')
    page.expectFlash('1 notifications sent')
  },

  // poll members list
  'poll_created': (test) => {
    page = pageHelper(test)

    page.loadPath('setup_discussion')
    page.click('.activity-panel__add-proposal')
    page.fillIn('.poll-common-form-fields__title input', 'A new proposal')
    page.fillIn('.poll-common-form-fields .lmo-textarea div[contenteditable=true]', 'Some details')
    page.click('.poll-common-form__submit')
    page.expectFlash('Proposal started')
    page.pause(500)

    page.expectElement('.poll-members-list')
    page.fillIn('.announcement-form__input input', 'test@example.com')
    page.expectText('.announcement-chip__content', 'test@example.com')
    page.click('.announcement-chip__content')
    page.expectElement('.headline')
    page.click('.poll-members-list__submit')
    page.expectFlash('1 notifications sent')
  },

  // 'poll_edited': (test) => {
  //   page = pageHelper(test)
  //
  //   page.loadPath('test_poll_in_discussion', { controller: 'polls' })
  //   page.click('.action-dock__button--edit_poll')
  //   page.fillIn('.poll-common-form-fields__title', 'Yo reliability, whatsup? Its me, ya boi, testing')
  //   page.click('.poll-common-form__submit')
  //   page.expectElement('.announcement-form')
  //   page.click('.announcement-form__audience')
  //   page.click('.announcement-form__submit')
  //   page.expectFlash('1 notifications sent')
  // },

  // 'outcome_created': (test) => {
  //   page = pageHelper(test)
  //
  //   page.loadPath('test_proposal_poll_closed', { controller: 'polls' })
  //   page.click('.poll-common-set-outcome-panel__submit')
  //   page.fillIn('.poll-common-outcome-form__statement textarea', 'Immannounce all yall')
  //   page.click('.poll-common-outcome-form__submit')
  //   page.expectFlash('Outcome created')
  //   page.expectElement('.announcement-form')
  //   page.selectFromAutocomplete('.announcement-form__invite input', 'test@example.com')
  //   page.expectText('.announcement-chip__content', 'test@example.com')
  //   page.click('.announcement-form__submit')
  //   page.pause(3000)
  //   page.expectFlash('1 notifications sent')
  // }
}
<|endoftext|>


<commit_before>"use strict";

//mes personnages
let perso1 = {
    nom: "vader",
    pointsvie: 50,
    energie: 60
};

let perso2 = {
    nom: "yoda",
    pointsvie: 50,
    energie: 60
};

// Attaques
function vaderAttack() {
    perso2.pointsvie = perso2.pointsvie - 5;
}

function statsPvYoda() {
    let pointsyoda = document.querySelector(".pointsyoda");
    pointsyoda.innerHTML = perso2.pointsvie;
}

function yodaAttack() {
    perso1.pointsvie = perso1.pointsvie - 5;
}

function statsPvVader() {
    let pointsvader = document.querySelector(".pointsvader");
    pointsvader.innerHTML = perso1.pointsvie;
}

//premier bouton attack//
let btn1 = document.querySelector("#btn1");
btn1.addEventListener("click", function() {
    if (perso2.pointsvie <= 0) {
        alert("J’ai apporté la paix, la justice, la liberté et la sécurité à mon nouvel Empire ! ")
    }
    vaderAttack();
    statsPvYoda();
    move();
    sabermove();
    toggle();
    jouerSon()
    perso1.energie = perso1.energie - 5;
    document.querySelector(".energievader").textContent = perso1.energie;
    perso1.pointsvie = perso1.pointsvie + 10;
    document.querySelector(".pointsvader").textContent = perso1.pointsvie;
});

function move() {
    let vader = document.querySelector(".vader");
    let classes = vader.className;
    vader.classList.add("vader-move");
    vader.addEventListener('animationend', function() {
        vader.className = classes;
    })
}

/* recup les sabres caches */
function toggle() {
    let attacksabre = document.querySelector(".attacksabre");
    if (attacksabre.style.display == "none") {
        attacksabre.style.display = "block";

    } else {
        attacksabre.style.display = "block";
    }
}

/*function isHidden() {
    return (attacksabre.offesetParent === null)
}*/

/*function isHidden(id) {
    let style = window.getComputedStyle(id);
    return (style.display === 'none')
}
*/

function sabermove() {
    let attacksabre = document.querySelector(".attacksabre");
    let classes = attacksabre.className;
    attacksabre.classList.add("attacksabre-move");
    attacksabre.addEventListener('animationend', function() {
        attacksabre.className = classes;
    })
}
/*Pour annuler l'animation
déclarer une variable qui cible la classe d'origine de l'élément
sur lequel je rajoute ensuite une animation en lui attribuant une nouvelle classe.
 Ensuite dans l'event 'animationend' réattribuer sa classe d'origine à l'élément.*/

function jouerSon() {
    let sound = document.querySelector("#sabersound");
    sound.play();
}

//quatrieme bouton attack idem premier//
let btn4 = document.querySelector("#btn4");
btn4.addEventListener("click", function() {
    if (perso1.pointsvie <= 0) {
        alert("Robuste je suis grâce à la Force")
    }
    yodaAttack();
    statsPvVader();
    move2();
    saberymove();
    toggle();
    jouerSon()
    gameOver();
    perso2.energie = perso2.energie - 5;
    document.querySelector(".energieyoda").textContent = perso2.energie;
    perso2.pointsvie = perso2.pointsvie + 10;
    document.querySelector(".pointsyoda").textContent = perso2.pointsvie;
});

function move2() {
    let yoda = document.querySelector(".yoda");
    let classes = yoda.className;
    yoda.classList.add("yoda-move");
    yoda.addEventListener('animationend', function() {
        yoda.className = classes;
    })
}

/* recup les sabres caches */
function toggle() {
    let attacksabrey = document.querySelector(".attacksabrey");
    if (attacksabrey.style.display == "none") {
        attacksabrey.style.display = "block";

    } else {
        attacksabrey.style.display = "block";
    }
}

function saberymove() {
    let attacksabrey = document.querySelector(".attacksabrey");
    let classes = attacksabrey.className;
    attacksabrey.classList.add("attacksabrey-move");
    attacksabrey.addEventListener('animationend', function() {
        attacksabrey.className = classes;
    })
}

function jouerSon() {
    let sound = document.querySelector("#sabersound");
    sound.play();
}

//deuxieme bouton magic//
let btn2 = document.querySelector("#btn2");
btn2.addEventListener("click", function magicperso1() {
    if (perso2.pointsvie <= 0) {
        reinitialise();
    }
    fireballdAnim();
    jouerfSon()
    perso2.pointsvie = perso2.pointsvie - 10;
    document.querySelector(".pointsyoda").textContent = perso2.pointsvie;
});

function fireballdAnim() {
    let fireballd = document.querySelector(".fireballd");
    let classes = fireballd.className;
    fireballd.classList.add("fireballAnimation");
    fireballd.addEventListener("animationend", function() {
        fireballd.className = classes;
        let i = Math.floor(steps(10));
    })
}

function jouerfSon() {
    let sound = document.querySelector("#fireballsound");
    sound.play();
}

//troisieme bouton heal//
let btn3 = document.querySelector("#btn3");
btn3.addEventListener("click", function() {
    heal();
    vaderAttack();
    compter();
    /* vader.style.display = "none"; la fonction display: none;
    masque totalement ou affiche l'élément et annule des propriétés */
});

function heal() {
    console.log((perso1.pointsvie) + 5);
    if (perso1.pointsvie <= 30) {
        perso1.pointsvie = (perso1.pointsvie) + 5;
        document.querySelector(".pointsvader").textContent = perso1.pointsvie;
    }
    if (perso1.pointsvie <= 25) {
        perso1.pointsvie = (perso1.pointsvie) - 5;
        document.querySelector(".pointsvader").textContent = perso1.pointsvie;
        alert("Je ne peux plus utiliser le côté obscur de la Force ");
    }
};

function compter() {
    let nbClick = 0;
    let nbClickMax = 3;
    nbClick++;
    if (nbClick >= nbClickMax) {
        document.getElementById('#btn3').disabled = true;
    }
}

/* A partir de 30 pv on peut utiliser le bouton heal qui nous rajoute 5 pv
au-delà de 20pv on ne peut plus*/

function gameOver() {
    if ((perso1.pointsvie === 0) || (perso2.pointsvie === 0)) {
        gameOver.style.display = "block";
    }
}<commit_msg>modif yoda and vader<commit_after>"use strict";

//mes personnages
let perso1 = {
    nom: "vader",
    pointsvie: 50,
    energie: 60
};

let perso2 = {
    nom: "yoda",
    pointsvie: 50,
    energie: 60
};

// Attaques
function vaderAttack() {
    perso2.pointsvie = perso2.pointsvie - 5;
}

function statsPvYoda() {
    let pointsyoda = document.querySelector(".pointsyoda");
    pointsyoda.innerHTML = perso2.pointsvie;
}

function yodaAttack() {
    perso1.pointsvie = perso1.pointsvie - 5;
}

function statsPvVader() {
    let pointsvader = document.querySelector(".pointsvader");
    pointsvader.innerHTML = perso1.pointsvie;
}

//premier bouton attack//
let btn1 = document.querySelector("#btn1");
btn1.addEventListener("click", function() {
    if (perso2.pointsvie <= 0) {
        alert("J’ai apporté la paix, la justice, la liberté et la sécurité à mon nouvel Empire ! ")
    }
    vaderAttack();
    statsPvYoda();
    move();
    sabermove();
    toggle();
    jouerSon()
    perso1.energie = perso1.energie - 5;
    document.querySelector(".energievader").textContent = perso1.energie;
    perso1.pointsvie = perso1.pointsvie + 10;
    document.querySelector(".pointsvader").textContent = perso1.pointsvie;
});

function move() {
    let vader = document.querySelector(".vader");
    let classes = vader.className;
    vader.classList.add("vader-move");
    vader.addEventListener('animationend', function() {
        vader.className = classes;
    })
}

/* recup les sabres caches */
function toggle() {
    let attacksabre = document.querySelector(".attacksabre");
    if (attacksabre.style.display == "none") {
        attacksabre.style.display = "block";

    } else {
        attacksabre.style.display = "block";
    }
}

/*function isHidden() {
    return (attacksabre.offesetParent === null)
}*/

/*function isHidden(id) {
    let style = window.getComputedStyle(id);
    return (style.display === 'none')
}
*/

function sabermove() {
    let attacksabre = document.querySelector(".attacksabre");
    let classes = attacksabre.className;
    attacksabre.classList.add("attacksabre-move");
    attacksabre.addEventListener('animationend', function() {
        attacksabre.className = classes;
    })
}
/*Pour annuler l'animation
déclarer une variable qui cible la classe d'origine de l'élément
sur lequel je rajoute ensuite une animation en lui attribuant une nouvelle classe.
 Ensuite dans l'event 'animationend' réattribuer sa classe d'origine à l'élément.*/

function jouerSon() {
    let sound = document.querySelector("#sabersound");
    sound.play();
}

//quatrieme bouton attack idem premier//
let btn4 = document.querySelector("#btn4");
btn4.addEventListener("click", function() {
    if (perso1.pointsvie <= 0) {
        alert("Robuste je suis grâce à la Force")
    }
    yodaAttack();
    statsPvVader();
    move2();
    saberymove();
    toggley();
    jouerSon()
    gameOver();
    perso2.energie = perso2.energie - 5;
    document.querySelector(".energieyoda").textContent = perso2.energie;
    perso2.pointsvie = perso2.pointsvie + 10;
    document.querySelector(".pointsyoda").textContent = perso2.pointsvie;
});

function move2() {
    let yoda = document.querySelector(".yoda");
    let classes = yoda.className;
    yoda.classList.add("yoda-move");
    yoda.addEventListener('animationend', function() {
        yoda.className = classes;
    })
}

/* recup les sabres caches */
function toggley() {
    let attacksabrey = document.querySelector(".attacksabrey");
    if (attacksabrey.style.display == "none") {
        attacksabrey.style.display = "block";

    } else {
        attacksabrey.style.display = "block";
    }
}

function saberymove() {
    let attacksabrey = document.querySelector(".attacksabrey");
    let classes = attacksabrey.className;
    attacksabrey.classList.add("attacksabrey-move");
    attacksabrey.addEventListener('animationend', function() {
        attacksabrey.className = classes;
    })
}

function jouerSon() {
    let sound = document.querySelector("#sabersound");
    sound.play();
}

//deuxieme bouton magic//
let btn2 = document.querySelector("#btn2");
btn2.addEventListener("click", function magicperso1() {
    if (perso2.pointsvie <= 0) {
        reinitialise();
    }
    fireballdAnim();
    jouerfSon()
    perso2.pointsvie = perso2.pointsvie - 10;
    document.querySelector(".pointsyoda").textContent = perso2.pointsvie;
});

function fireballdAnim() {
    let fireballd = document.querySelector(".fireballd");
    let classes = fireballd.className;
    fireballd.classList.add("fireballAnimation");
    fireballd.addEventListener("animationend", function() {
        fireballd.className = classes;
        let i = Math.floor(steps(10));
    })
}

function jouerfSon() {
    let sound = document.querySelector("#fireballsound");
    sound.play();
}

//troisieme bouton heal//
let btn3 = document.querySelector("#btn3");
btn3.addEventListener("click", function() {
    heal();
    vaderAttack();
    compter();
    /* vader.style.display = "none"; la fonction display: none;
    masque totalement ou affiche l'élément et annule des propriétés */
});

function heal() {
    console.log((perso1.pointsvie) + 5);
    if (perso1.pointsvie <= 30) {
        perso1.pointsvie = (perso1.pointsvie) + 5;
        document.querySelector(".pointsvader").textContent = perso1.pointsvie;
    }
    if (perso1.pointsvie <= 25) {
        perso1.pointsvie = (perso1.pointsvie) - 5;
        document.querySelector(".pointsvader").textContent = perso1.pointsvie;
        alert("Je ne peux plus utiliser le côté obscur de la Force ");
    }
};

function compter() {
    let nbClick = 0;
    let nbClickMax = 3;
    nbClick++;
    if (nbClick >= nbClickMax) {
        document.getElementById('#btn3').disabled = true;
    }
}

/* A partir de 30 pv on peut utiliser le bouton heal qui nous rajoute 5 pv
au-delà de 20pv on ne peut plus*/

function gameOver() {
    if ((perso1.pointsvie === 0) || (perso2.pointsvie === 0)) {
        gameOver.style.display = "block";
    }
}<|endoftext|>


<commit_before>
/*
 * Waltz - Enterprise Architecture
 * Copyright (C) 2016, 2017 Waltz open source project
 * See README.md for more information
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * Given an entity kind, this will return the matching
 * ui-router state name if avaialble.  Otherwise it
 * will throw an error.
 * @param kind
 * @returns String state name
 */
export function kindToViewState(kind) {
    if (kind === "APPLICATION") {
        return "main.app.view";
    }
    if (kind === "ACTOR") {
        return "main.actor.view";
    }
    if (kind === "APP_GROUP") {
        return "main.app-group.view";
    }
    if (kind === "DATA_TYPE") {
        return "main.data-type.view";
    }
    if (kind === "FLOW_DIAGRAM") {
        return "main.flow-diagram.view";
    }
    if (kind === "LOGICAL_DATA_ELEMENT") {
        return "main.logical-data-element.view";
    }
    if (kind === "LOGICAL_DATA_FLOW") {
        return "main.logical-flow.view";
    }
    if (kind === "MEASURABLE") {
        return "main.measurable.view";
    }
    if (kind === "MEASURABLE_CATEGORY") {
        return "main.measurable-category.view";
    }
    if (kind === "ORG_UNIT") {
        return "main.org-unit.view";
    }
    if (kind === "CHANGE_INITIATIVE") {
        return "main.change-initiative.view";
    }
    if (kind === "ENTITY_STATISTIC") {
        return "main.entity-statistic.view";
    }
    if (kind === "PERSON") {
        return "main.person.id";
    }
    if (kind === "PROCESS") {
        return "main.process.view";
    }
    if (kind === "PHYSICAL_SPECIFICATION") {
        return "main.physical-specification.view";
    }
    if (kind === "PHYSICAL_FLOW") {
        return "main.physical-flow.view";
    }
    if (kind === "ROADMAP") {
        return "main.roadmap.view";
    }
    throw "Unable to convert kind: "+kind+ " to a ui-view state";
}
<commit_msg>Support scenario links<commit_after>
/*
 * Waltz - Enterprise Architecture
 * Copyright (C) 2016, 2017 Waltz open source project
 * See README.md for more information
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * Given an entity kind, this will return the matching
 * ui-router state name if avaialble.  Otherwise it
 * will throw an error.
 * @param kind
 * @returns String state name
 */
export function kindToViewState(kind) {
    if (kind === "APPLICATION") {
        return "main.app.view";
    }
    if (kind === "ACTOR") {
        return "main.actor.view";
    }
    if (kind === "APP_GROUP") {
        return "main.app-group.view";
    }
    if (kind === "DATA_TYPE") {
        return "main.data-type.view";
    }
    if (kind === "FLOW_DIAGRAM") {
        return "main.flow-diagram.view";
    }
    if (kind === "LOGICAL_DATA_ELEMENT") {
        return "main.logical-data-element.view";
    }
    if (kind === "LOGICAL_DATA_FLOW") {
        return "main.logical-flow.view";
    }
    if (kind === "MEASURABLE") {
        return "main.measurable.view";
    }
    if (kind === "MEASURABLE_CATEGORY") {
        return "main.measurable-category.view";
    }
    if (kind === "ORG_UNIT") {
        return "main.org-unit.view";
    }
    if (kind === "CHANGE_INITIATIVE") {
        return "main.change-initiative.view";
    }
    if (kind === "ENTITY_STATISTIC") {
        return "main.entity-statistic.view";
    }
    if (kind === "PERSON") {
        return "main.person.id";
    }
    if (kind === "PROCESS") {
        return "main.process.view";
    }
    if (kind === "PHYSICAL_SPECIFICATION") {
        return "main.physical-specification.view";
    }
    if (kind === "PHYSICAL_FLOW") {
        return "main.physical-flow.view";
    }
    if (kind === "ROADMAP") {
        return "main.roadmap.view";
    }
    if (kind === "SCENARIO") {
        return "main.scenario.view";
    }
    throw "Unable to convert kind: "+kind+ " to a ui-view state";
}
<|endoftext|>


<commit_before>/**
 * Created by Marc Streit on 06.08.2014.
 */
/* global define */

define(['exports', 'd3', '../caleydo_core/main', '../caleydo_core/idtype', 'lineupjsN', '../caleydo_d3/d3util', 'font-awesome', 'css!./style'], function (exports, d3, C, idtypes, LineUpJS, d3utils) {
  "use strict";
  function deriveColumns(columns) {
    return columns.map(function (col) {
      var r = {
        column : col.desc.name
      };
      if (col.desc.color) {
        r.color = col.desc.color;
      } else if (col.desc.cssClass) {
        r.cssClass = col.desc.cssClass;
      }

      //use magic word to find extra attributes
      if (col.desc.lineup) {
        Object.keys(col.desc.lineup).forEach(function(k) {
          r[k] = col.desc.lineup[k];
        });
      }
      var val = col.desc.value;
      switch (val.type) {
      case 'string':
        r.type = 'string';
        break;
      case 'categorical':
        r.type = 'categorical';
        r.categories = col.desc.categories;
        break;
      case 'real':
      case 'int':
        r.type = 'number';
        r.domain = val.range;
        break;
      default:
        r.type = 'string';
        break;
      }
      return r;
    });
  }

  exports.LineUp = d3utils.defineVis('LineUp', {}, function (data) {
    var dim = data.dim;
    return [ Math.min(dim[1] * 100, 1000), Math.min(dim[0] * 20, 600)];
  }, function build($parent) {
    var $div = $parent.append('div');

    var that = this;

    var columns = deriveColumns(this.data.cols());

    var listener = function (event, act) {
      if (that.lineup) {
        that.lineup.data.setSelection(act.dim(0).asList());
      }
    };
    that.data.on('select-selected', listener);
    C.onDOMNodeRemoved($div.node(), function () {
      that.data.off('select-selected', listener);
    });var listener = function (event, act) {
      if (that.lineup) {
        that.lineup.data.setSelection(act.dim(0).asList());
      }
    };
    that.data.on('select-selected', listener);
    C.onDOMNodeRemoved($div.node(), function () {
      that.data.off('select-selected', listener);
    });

    // bind data to chart
    Promise.all([this.data.objects(), this.data.rowIds()]).then(function (promise) {
      var arr = promise[0];
      var rowIds = promise[1].dim(0).asList();
      var data = arr.map(function (obj, i) {
        return C.mixin({
          _id : rowIds[i]
        }, obj);
      });
      that.provider = LineUpJS.createLocalStorage(data, columns);
      var dump = that.option('dump');
      if (dump) {
        that.provider.restore(dump);
      }
      that.lineup = LineUpJS.create(that.provider, $div, that.option('lineup'));
      that.lineup.on('hoverChanged', function(data_index) {
        var id = null;
        if (data_index < 0) {
          that.data.clear(idtypes.hoverSelectionType);
        } else {
          id = data[data_index]._id;
          that.data.select(idtypes.hoverSelectionType, [data_index]);
        }
        that.fire(idtypes.hoverSelectionType, id);
      });
      that.lineup.on('multiSelectionChanged', function(data_indices) {
        if (data_indices.length === 0) {
          that.data.clear(idtypes.defaultSelectionType);
        } else {
          that.data.select(idtypes.defaultSelectionType, data_indices);
        }
        that.fire(idtypes.defaultSelectionType, data_indices.length === 0 ? null : data[data_indices[0]]._id);
      });
      that.provider.deriveDefault();
      that.lineup.update();

      that.data.selections().then(function(act) {
        if (!act.isNone) {
          listener(null, act);
        }
      });

      that.markReady();
    });

    return $div;
  }, {
    transform: function (scale, rotate) {
      var bak = {
        scale: this.options.scale || [1, 1],
        rotate: this.options.rotate || 0
      };
      if (arguments.length === 0) {
        return bak;
      }
      this.$node.style('transform', 'rotate(' + rotate + 'deg)scale(' + scale[0] + ',' + scale[1] + ')');
      var new_ = {
        scale: scale,
        rotate: rotate
      };
      this.fire('transform', new_, bak);
      this.options.scale = scale;
      this.options.rotate = rotate;
      return new_;
    },
    update: function() {
      if (this.lineup) {
        this.lineup.update();
      }
    }
  });

  exports.create = function (data, parent, options) {
    return new exports.LineUp(data, parent, options);
  };
});
<commit_msg>support for showing rownames as column<commit_after>/**
 * Created by Marc Streit on 06.08.2014.
 */
/* global define */

define(['exports', 'd3', '../caleydo_core/main', '../caleydo_core/idtype', 'lineupjsN', '../caleydo_d3/d3util', 'font-awesome', 'css!./style'], function (exports, d3, C, idtypes, LineUpJS, d3utils) {
  "use strict";

  function deriveColumns(columns) {
    return columns.map(function (col) {
      var r = {
        column : col.desc.name
      };
      if (col.desc.color) {
        r.color = col.desc.color;
      } else if (col.desc.cssClass) {
        r.cssClass = col.desc.cssClass;
      }

      //use magic word to find extra attributes
      if (col.desc.lineup) {
        Object.keys(col.desc.lineup).forEach(function(k) {
          r[k] = col.desc.lineup[k];
        });
      }
      var val = col.desc.value;
      switch (val.type) {
      case 'string':
        r.type = 'string';
        break;
      case 'categorical':
        r.type = 'categorical';
        r.categories = col.desc.categories;
        break;
      case 'real':
      case 'int':
        r.type = 'number';
        r.domain = val.range;
        break;
      default:
        r.type = 'string';
        break;
      }
      return r;
    });
  }

  exports.LineUp = d3utils.defineVis('LineUp', {
    rowNames: false
  }, function (data) {
    var dim = data.dim;
    return [ Math.min(dim[1] * 100, 1000), Math.min(dim[0] * 20, 600)];
  }, function build($parent) {
    var $div = $parent.append('div');

    var that = this;
    var rowNames = this.option('rowNames', false) === true;

    var columns = deriveColumns(this.data.cols());

    if (rowNames) {
      columns.unshift({ type: 'string', label: 'Row', column: '_name'});
    }

    var listener = function (event, act) {
      if (that.lineup) {
        that.lineup.data.setSelection(act.dim(0).asList());
      }
    };
    that.data.on('select-selected', listener);
    C.onDOMNodeRemoved($div.node(), function () {
      that.data.off('select-selected', listener);
    });var listener = function (event, act) {
      if (that.lineup) {
        that.lineup.data.setSelection(act.dim(0).asList());
      }
    };
    that.data.on('select-selected', listener);
    C.onDOMNodeRemoved($div.node(), function () {
      that.data.off('select-selected', listener);
    });

    // bind data to chart
    Promise.all([this.data.objects(), this.data.rowIds(), rowNames ? this.data.rows() : Promise.resolve([])]).then(function (promise) {
      var arr = promise[0];
      var rowIds = promise[1].dim(0).asList();
      var names = promise[2];

      var data = arr.map(function (obj, i) {
        return C.mixin({
          _name : names[i],
          _id : rowIds[i]
        }, obj);
      });
      that.provider = LineUpJS.createLocalStorage(data, columns);
      var dump = that.option('dump');
      if (dump) {
        that.provider.restore(dump);
      }
      that.lineup = LineUpJS.create(that.provider, $div, that.option('lineup'));
      that.lineup.on('hoverChanged', function(data_index) {
        var id = null;
        if (data_index < 0) {
          that.data.clear(idtypes.hoverSelectionType);
        } else {
          id = data[data_index]._id;
          that.data.select(idtypes.hoverSelectionType, [data_index]);
        }
        that.fire(idtypes.hoverSelectionType, id);
      });
      that.lineup.on('multiSelectionChanged', function(data_indices) {
        if (data_indices.length === 0) {
          that.data.clear(idtypes.defaultSelectionType);
        } else {
          that.data.select(idtypes.defaultSelectionType, data_indices);
        }
        that.fire(idtypes.defaultSelectionType, data_indices.length === 0 ? null : data[data_indices[0]]._id);
      });
      that.provider.deriveDefault();
      that.lineup.update();

      that.data.selections().then(function(act) {
        if (!act.isNone) {
          listener(null, act);
        }
      });

      that.markReady();
    });

    return $div;
  }, {
    transform: function (scale, rotate) {
      var bak = {
        scale: this.options.scale || [1, 1],
        rotate: this.options.rotate || 0
      };
      if (arguments.length === 0) {
        return bak;
      }
      this.$node.style('transform', 'rotate(' + rotate + 'deg)scale(' + scale[0] + ',' + scale[1] + ')');
      var new_ = {
        scale: scale,
        rotate: rotate
      };
      this.fire('transform', new_, bak);
      this.options.scale = scale;
      this.options.rotate = rotate;
      return new_;
    },
    update: function() {
      if (this.lineup) {
        this.lineup.update();
      }
    }
  });

  exports.create = function (data, parent, options) {
    return new exports.LineUp(data, parent, options);
  };
});
<|endoftext|>