<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':1,
    'query_end':46,
'hit_start':21,
'hit_end':67
},
{'index':1,'ID':'gi|6aaaaaaa4|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':15,
    'query_end':45,
    'hit_start':21,
    'hit_end':67,
},{'index':2,'ID':'gi|688044384|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':11,
    'query_end':35,
    'hit_start':21,
    'hit_end':67,
},{'index':3,'ID':'gi|68asdf384|gb|KM018299.1|',
    'description':'bla blabl ablablablab lablab lablab lablabla b labla bla blabla blab  la blabla blabla blablab labla',
    'E_value':7.8e-14,
    'score':84.24,
    'span':46,
    'query_start':11,
    'query_end':25,
    'hit_start':21,
    'hit_end':67
}]};

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

var text_start;
var text_end;
var radius;
var arc_k;
var color;
var root_text;
var text_info;
var text_benchmark;

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

    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");

    root_text=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");

    text_info=svg.append("text")
        .attr("dy", "3.35em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .attr("x",-220)
        .attr("y",250);

    text_benchmark=svg.append("text")
        .attr("dy", "3.35em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .attr("x",-50)
        .attr("y",-20);

    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_container = d3.select('#result_blast').append('svg')
            .attr('width',res_width+280)
            .attr('height',res_height+120);

        var svg  = svg_container.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;

        var data = result;

        var res_data_enter = svg.append("g").selectAll("text")
            .data(result)
            .enter();

        var global_len = 47;

        var rec = res_data_enter.append("rect")
            .attr("rx", 6)
            .attr("ry", 6)
            .attr("x",250)
            .attr("y", function (d) {
                return d.index*24-215
            })
            .attr("width", 215)
            .attr("height", 20)
            .attr("fill",function (d) {
                console.log(color((d.query_end-d.query_start)/global_len));
                return color((d.query_end-d.query_start)/global_len)
            })
            .on("mouseover", function(d){renew_graph(d)});

        var text = res_data_enter.append("text")
            .text(function (d) {return d.ID})
            .attr("x",260)
            .attr("y",function (d) {
                return d.index*24-200
            })
            .attr("pointer-events", "none")
            .classed('noselect',true);

        function renew_graph(d) {
            arc_ret.transition().duration(300)
                .attrTween("d", arcTween(d.query_start*Math.PI*2/global_len,d.query_end*Math.PI*2/global_len)).each("end",function () {
                text_end.text(d.query_end);
                text_start.text(d.query_start);
                root_text.text("Original Sequence VS" + d.ID);
                text_info.text("Description : "+d.description);
                text_benchmark.text("E-value"+d.E_value)
            });

            console.log(arc_ret);
        }

    }
);<commit_msg>movement and color of the blast<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':1,
    'query_end':46,
'hit_start':21,
'hit_end':67
},
{'index':1,'ID':'gi|6aaaaaaa4|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':15,
    'query_end':45,
    'hit_start':21,
    'hit_end':67,
},{'index':2,'ID':'gi|688044384|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':11,
    'query_end':35,
    'hit_start':21,
    'hit_end':67,
},{'index':3,'ID':'gi|68asdf384|gb|KM018299.1|',
    'description':'bla blabl ablablablab lablab lablab lablabla b labla bla blabla blab  la blabla blabla blablab labla',
    'E_value':7.8e-14,
    'score':84.24,
    'span':46,
    'query_start':11,
    'query_end':25,
    'hit_start':21,
    'hit_end':67
}]};

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

var text_start;
var text_end;
var radius;
var arc_k;
var color;
var root_text;
var text_info;
var text_benchmark;

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

    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");

    root_text=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");

    text_info=svg.append("text")
        .attr("dy", "3.35em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .attr("x",-220)
        .attr("y",250);

    text_benchmark=svg.append("text")
        .attr("dy", "3.35em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .attr("x",-50)
        .attr("y",-20);

    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_container = d3.select('#result_blast').append('svg')
            .attr('width',res_width+280)
            .attr('height',res_height+120);

        var svg  = svg_container.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;

        var data = result;

        var res_data_enter = svg.append("g").selectAll("text")
            .data(result)
            .enter();

        var global_len = 47;

        var rec = res_data_enter.append("rect")
            .attr("rx", 6)
            .attr("ry", 6)
            .attr("x",250)
            .attr("y", function (d) {
                return d.index*24-215
            })
            .attr("width", 215)
            .attr("height", 20)
            .attr("fill",function (d) {
                console.log(color((d.query_end-d.query_start)/global_len));
                return color((d.query_end-d.query_start)/global_len)
            })
            .attr("id",function (d) {
                return "rectangle_"+d.index;
            })
            .on("mouseover", function(d){
                renew_graph(d);
                renew_label(d)
            }
            ).on("mouseout",function (d) {
                flash_label(d)
            }).attr("stroke","white").attr("stroke-width",3);;

        var text = res_data_enter.append("text")
            .text(function (d) {return d.ID})
            .attr("x",260)
            .attr("y",function (d) {
                return d.index*24-200
            })
            .attr("pointer-events", "none")
            .classed('noselect',true);

        function flash_label(d) {
            d3.selectAll("#rectangle_"+d.index).attr("stroke","white").attr("stroke-width",3);
            d3.selectAll("#rectangle_"+d.index)
                .transition().duration(200).attrTween("width",function (d,i,a) {
                return d3.interpolate(a,215);

        });
        }

        function renew_label(d) {
            d3.selectAll("#rectangle_"+d.index).attr("stroke","yellow").attr("stroke-width",3);
             d3.selectAll("#rectangle_"+d.index)
                 .transition().duration(200).attrTween("width",function (d,i,a) {
                    return d3.interpolate(a,240)
             });

        }

        function renew_graph(d) {
            arc_ret.transition().duration(300)
                .attrTween("d", arcTween(d.query_start*Math.PI*2/global_len,d.query_end*Math.PI*2/global_len)).each("end",function () {
                text_end.text(d.query_end);
                text_start.text(d.query_start);
                root_text.text("Original Sequence VS" + d.ID);
                text_info.text("Description : "+d.description);
                text_benchmark.text("E-value"+d.E_value)
                arc_ret.attr("fill", color((d.query_end-d.query_start)/global_len))
            })

        }

    }
);<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {Text, StyleSheet, View, TextInput, Button, Alert, ScrollView } from 'react-native';
import Video from 'react-native-video';
import Backend from './DataModification';

export default class EditScreen extends Component {
    static navigationOption = {
      title: 'Add',
    };

    constructor(props) {
        super(props);
        this.state = {
          text: '',
          emoji: ''
        };
    }

    render() {
      const { navigate } = this.props.navigation;
      const { params } = this.props.navigation.state;

      return (
        <View style = {styles.container}>
          <Text style = {styles.baseText}>Please enter emotion/activity:</Text>

          <TextInput
            style={styles.textInput}
            placeholder="Emotion/Activity Name"
            onChangeText={(title) => {
              this.setState({text: title});
              }}
          />

          <Text style = {styles.baseText}>Please choose an emoji to describe it:</Text>

          <TextInput
            style={styles.textInput}
            placeholder="Emoji"
            onChangeText={(emoji) => this.setState({emoji})}
          />

          <Video
            source={{uri: params.videoPath}}   // Can be a URL or a local file.
            // Store reference
            rate={1.0}
            resizeMode="cover"
            volume={1.0}                            // 0 is muted, 1 is normal.
            muted={false}                           // Mutes the audio entirely.
            paused={false}                          // Pauses playback entirely.
            repeat={true}                           // Repeat forever.
            playInBackground={false}                // Audio continues to play when app entering background.
            style={styles.backgroundVideo}
          />

          <View style={styles.button}>
            <Button
              onPress={
                () => {
                   console.log(this.state);
                   Backend.appendData(this.state.emoji,params.videoPath,this.state.text);

                   navigate('Home');

                   } }
              title = "Confirm"
            />
          </View>

        </View>
      );
    }

}

const styles = StyleSheet.create({
  container:{
    flex: 1,
    flexDirection:'column',
  },

  backgroundVideo: {
    flex:1,
    width:'100%',
    backgroundColor: '#E9E9EF',
    marginTop:5,
  },

  baseText: {
    marginTop:12,
    marginBottom:6,
    marginHorizontal:8,
    fontSize: 16,
    color: '#444',
  },

  textInput:{
    height: 45,
    width: '100%',

    borderTopWidth: 1,//StyleSheet.hairlineWidth,
    borderBottomWidth: 1,//StyleSheet.hairlineWidth,
    borderColor: '#ddd',

    paddingLeft:10,
    fontSize:16,
    backgroundColor: '#ffffff'
  },

  button:{
    height: 45,
    width: '100%',

    borderTopWidth: 1,//StyleSheet.hairlineWidth,
    borderBottomWidth: 1,//StyleSheet.hairlineWidth,
    borderColor: '#ddd',

    marginVertical:5,
    paddingLeft:10,
    backgroundColor: '#ffffff'
  },
});
<commit_msg>Fixed a bug where if you click outside of the TextInput, the keyboard would not hide. It should hide now<commit_after>import React, { Component } from 'react';
import {Text, StyleSheet, View, TextInput, Button, Alert, ScrollView } from 'react-native';
import Video from 'react-native-video';
import Backend from './DataModification';

export default class EditScreen extends Component {
    static navigationOption = {
      title: 'Add',
    };

    constructor(props) {
        super(props);
        this.state = {
          text: '',
          emoji: ''
        };
    }

    render() {
      const { navigate } = this.props.navigation;
      const { params } = this.props.navigation.state;

      return (
        <View style = {styles.container}>
          <Text style = {styles.baseText}>Please enter emotion/activity:</Text>
          <ScrollView
            scrollEnabled={false}
            contentContainerStyle={styles.main}
          >
            <TextInput
              style={styles.textInput}
              placeholder="Emotion/Activity Name"
              onChangeText={(title) => {
                this.setState({text: title});
                }}
            />
          </ScrollView>
          <Text style = {styles.baseText}>Please choose an emoji to describe it:</Text>

          <ScrollView
            scrollEnabled={false}
            contentContainerStyle={styles.main}
          >
            <TextInput
              style={styles.textInput}
              placeholder="Emoji"
              onChangeText={(emoji) => this.setState({emoji})}
            />
          </ScrollView>

          <Video
            source={{uri: params.videoPath}}   // Can be a URL or a local file.
            // Store reference
            rate={1.0}
            resizeMode="cover"
            volume={1.0}                            // 0 is muted, 1 is normal.
            muted={false}                           // Mutes the audio entirely.
            paused={false}                          // Pauses playback entirely.
            repeat={true}                           // Repeat forever.
            playInBackground={false}                // Audio continues to play when app entering background.
            style={styles.backgroundVideo}
          />

          <View style={styles.button}>
            <Button
              onPress={
                () => {
                   console.log(this.state);
                   Backend.appendData(this.state.emoji,params.videoPath,this.state.text);

                   navigate('Home');

                   } }
              title = "Confirm"
            />
          </View>

        </View>
      );
    }

}

const styles = StyleSheet.create({
  container:{
    flex: 1,
    flexDirection:'column',
  },

  backgroundVideo: {
    flex:1,
    width:'100%',
    backgroundColor: '#E9E9EF',
    marginTop:5,
  },

  baseText: {
    marginTop:12,
    marginBottom:6,
    marginHorizontal:8,
    fontSize: 16,
    color: '#444',
  },

  textInput:{
    height: 45,
    width: '100%',

    borderTopWidth: 1,//StyleSheet.hairlineWidth,
    borderBottomWidth: 1,//StyleSheet.hairlineWidth,
    borderColor: '#ddd',

    paddingLeft:10,
    fontSize:16,
    backgroundColor: '#ffffff'
  },

  button:{
    height: 45,
    width: '100%',

    borderTopWidth: 1,//StyleSheet.hairlineWidth,
    borderBottomWidth: 1,//StyleSheet.hairlineWidth,
    borderColor: '#ddd',

    marginVertical:5,
    paddingLeft:10,
    backgroundColor: '#ffffff'
  },
});
<|endoftext|>


<commit_before>var constants = require('./constants');

module.exports = function(game) {
  var boxes = game.add.group();
  var one = boxes.create(200, game.world.height - 164, 'box');
  game.physics.enable(one, Phaser.Physics.ARCADE);
  one.scale.setTo(6, 1);
  one.body.immovable = true;
  one.body.rebound = false;
  var velocity = -50
  one.events.onOutOfBounds.add(function (face, thisBody, bodyThatHitMe){
    velocity = -velocity;
  });

  one.body.collideCallback = function() {
    console.log("hit!");
  }

  return {
    group: boxes,
    update: function() {
      one.body.velocity.x = velocity;
    }
  };
};
<commit_msg>back to checking for out of bounds<commit_after>var constants = require('./constants');

module.exports = function(game) {
  var boxes = game.add.group();
  var one = boxes.create(200, game.world.height - 164, 'box');
  game.physics.enable(one, Phaser.Physics.ARCADE);
  one.scale.setTo(6, 1);
  one.body.immovable = true;
  one.body.rebound = false;
  var velocity = -50
  one.checkWorldBounds = true;
  one.events.onOutOfBounds.add(function (face, thisBody, bodyThatHitMe){
    console.log("I'm out of bounds");
    velocity = -velocity;
  });

  one.body.collideCallback = function() {
    console.log("hit!");
  }

  return {
    group: boxes,
    update: function() {
      one.body.velocity.x = velocity;
    }
  };
};
<|endoftext|>


<commit_before>(function() {
	var git         = new( require( 'git-wrapper' ) )();
	var $           = require( './lib/jQuery.js' );
	var fs          = require( 'fs' );
	var exec        = require( 'child_process' ).exec;
	var now         = new Date();

	// Change to oojs-ui dir
	process.chdir( './public_html/oojs-ui' );

	var repoOldRev, repoNewRev, moveAndBuild, addBuild2List;

	addBuild2List = function() {
		// Change to public_html directory
		process.chdir( '..' );
		// Attempt to load JSON data
		var buildList = [];
		try {
			buildList = require( '../public_html/buildlist.json' );
		} catch ( ex ) {
			console.log( ex );
		}
		buildList.push( {
			rev: repoOldRev,
			date: now
		} );
		buildList = JSON.stringify( buildList );
		fs.writeFileSync( 'buildlist.json', buildList, {
			encoding: 'utf8',
			mode: '664'
		} );
		console.log( 'Done! Bye bye!' );
	};

	moveAndBuild = function() {
		var sevenZip = '7zr';
		var filesNFolders2Archive = [
			'lib', 'demos', 'LICENSE-MIT', 'README.md', 'AUTHORS.txt'
		];

		try {
			fs.mkdirSync( '../dist_old', '2775' );
			fs.mkdirSync( '../arch_old', '2775' );
		} catch ( ex ) {}

		console.log( 'Backing up old distro...' );
		fs.mkdirSync( '../dist_old/' + repoOldRev, '2775' );
		fs.renameSync( 'dist', '../dist_old/' + repoOldRev + '/dist' );
		fs.mkdirSync( 'dist', '2775' );

		console.log( 'Backing up dependencies...' );
		git.exec( 'checkout', [ repoOldRev ], function( err, msg ) {
			filesNFolders2Archive.forEach( function( item, index ) {
				fs.renameSync( item, '../dist_old/' + repoOldRev + '/' + item );
			} );

			console.log( 'Creating archive...' );

			exec( sevenZip + ' a "../arch_old/oojs-ui-' + repoOldRev + '.7z" "../dist_old/' + repoOldRev + '/"', function( err, msg ) {
				// console.log( err );
				// console.log( msg );
				git.exec( 'reset', [ '--hard', 'origin/master' ], function( err, msg ) {
					git.exec( 'checkout', {
						f: true
					}, [ 'master' ], function( err, msg ) {
						console.log( 'Building...' );
						exec( 'npm install', function( err, msg ) {
							console.log( 'Running composer...' );
							exec( '~/composer/composer.phar install', function() {
								console.log( 'Creating archive of current version' );
								try {
									fs.unlinkSync( '../oojsui.7z' );
								} catch ( ex ) {}

								var filesNames = '"' + filesNFolders2Archive.join( '" "' ) + '" "dist"';
								var cmd = sevenZip + ' a "../oojsui.7z" ' + filesNames;
								console.log( cmd );
								exec( cmd, function() {
									console.log( 'Listing backup...' );
									addBuild2List();
								} );
							} );
						} );
					} );
				} );
			} );
		} );
	};

	git.exec( 'rev-parse', [ 'HEAD' ], function( err, msg ) {
		repoOldRev = $.trim( msg );

		git.exec( 'pull', [ 'origin master' ], function( err, msg ) {
			git.exec( 'rev-parse', [ 'HEAD' ], function( err, msg ) {
				repoNewRev = $.trim( msg );
				if ( repoOldRev !== repoNewRev ) {
					console.log( 'Move and build' );
					moveAndBuild();
				} else {
					console.log( 'No updates. Aborting.' );
				};
			} );
		} );
	} );
}() );
<commit_msg>Update build script after its build target decided to change<commit_after>(function() {
	var git         = new( require( 'git-wrapper' ) )();
	var $           = require( './lib/jQuery.js' );
	var fs          = require( 'fs-extra' );
	var exec        = require( 'child_process' ).exec;
	var now         = new Date();

	// Change to oojs-ui dir
	process.chdir( './public_html/oojs-ui' );

	var repoOldRev, repoNewRev, moveAndBuild, addBuild2List;

	addBuild2List = function() {
		// Change to public_html directory
		process.chdir( '..' );
		// Attempt to load JSON data
		var buildList = [];
		try {
			buildList = require( '../public_html/buildlist.json' );
		} catch ( ex ) {
			console.log( ex );
		}
		buildList.push( {
			rev: repoOldRev,
			date: now
		} );
		buildList = JSON.stringify( buildList );
		fs.writeFileSync( 'buildlist.json', buildList, {
			encoding: 'utf8',
			mode: '664'
		} );
		console.log( 'Done! Bye bye!' );
	};

	moveAndBuild = function() {
		var sevenZip = '7zr';
		var filesNFolders2Archive = [
			'demos', 'LICENSE-MIT', 'README.md', 'AUTHORS.txt'
		];

		try {
			fs.mkdirSync( '../dist_old', '2775' );
			fs.mkdirSync( '../arch_old', '2775' );
		} catch ( ex ) {}

		console.log( 'Backing up old distro...' );
		fs.mkdirSync( '../dist_old/' + repoOldRev, '2775' );
		fs.renameSync( 'dist', '../dist_old/' + repoOldRev + '/dist' );
		fs.mkdirSync( 'dist', '2775' );

		console.log( 'Backing up dependencies...' );
		git.exec( 'checkout', [ repoOldRev ], function( err, msg ) {
			filesNFolders2Archive.forEach( function( item, index ) {
				fs.renameSync( item, '../dist_old/' + repoOldRev + '/' + item );
			} );
			fs.copySync( 'node_modules/jquery/dist', '../dist_old/' + repoOldRev + '/node_modules/jquery/dist' );
			fs.copySync( 'node_modules/oojs/dist', '../dist_old/' + repoOldRev + '/node_modules/oojs/dist' );

			console.log( 'Creating archive...' );

			exec( sevenZip + ' a "../arch_old/oojs-ui-' + repoOldRev + '.7z" "../dist_old/' + repoOldRev + '/"', function( err, msg ) {
				// console.log( err );
				// console.log( msg );
				git.exec( 'reset', [ '--hard', 'origin/master' ], function( err, msg ) {
					git.exec( 'checkout', {
						f: true
					}, [ 'master' ], function( err, msg ) {
						console.log( 'Building...' );
						exec( 'npm install', function( err, msg ) {
							console.log( 'Running composer...' );
							exec( '~/composer/composer.phar install', function() {
								console.log( 'Creating archive of current version' );
								try {
									fs.unlinkSync( '../oojsui.7z' );
								} catch ( ex ) {}

								filesNFolders2Archive.push('node_modules/jquery/dist');
								filesNFolders2Archive.push('node_modules/oojs/dist');
								var filesNames = '"' + filesNFolders2Archive.join( '" "' ) + '" "dist"';
								var cmd = sevenZip + ' a "../oojsui.7z" ' + filesNames;
								console.log( cmd );
								exec( cmd, function() {
									console.log( 'Listing backup...' );
									addBuild2List();
								} );
							} );
						} );
					} );
				} );
			} );
		} );
	};

	git.exec( 'rev-parse', [ 'HEAD' ], function( err, msg ) {
		repoOldRev = $.trim( msg );

		git.exec( 'pull', [ 'origin master' ], function( err, msg ) {
			git.exec( 'rev-parse', [ 'HEAD' ], function( err, msg ) {
				repoNewRev = $.trim( msg );
				if ( repoOldRev !== repoNewRev ) {
					console.log( 'Move and build' );
					moveAndBuild();
				} else {
					console.log( 'No updates. Aborting.' );
				};
			} );
		} );
	} );
}() );
<|endoftext|>


<commit_before>function segDigitBindOnceDirective(segUtil){
    var directiveDefinitionObject = {
        strict: 'E',
        scope: {
            'segVal': '@'
        },
        templateUrl: 'digit.html'
    };

    return directiveDefinitionObject;
}<commit_msg>Delete segDigitOnce directive.<commit_after><|endoftext|>


<commit_before>
var DOMMarkupEditor = function()
{
  this.base_init(this);
  this.type = "dom-markup-editor";
  // specific context
  this.context_enter =
  {
    rt_id: '',
    obj_id: '',
    parent_obj_id: '',
    outer_html: '',
    host_target: ''
  }
  this.context_cur =
  {
    rt_id: '',
    obj_id: '',
    parent_obj_id: '',
    outer_html: '',
    host_target: ''
  }

  var crlf_encode = function(str)
  {
    return str.replace(/\r\n/g, "\\n");
  }

  var encode = function(str)
  {
    return str.replace(/\u200F\r\n/g, "").replace(/\r\n/g, "\\n").replace(/'/g, "\\'");
  }

  var Host_updater = function(target)
  {
    var
    range_target = document.createRange(),
    timeout = 0,
    new_str = '',
    update = function(str)
    {
      range_target.deleteContents();
      var range_source = document.createRange();
      var temp = document.createElement('df-temp-element');
      ( document.body || document.documentElement || document ).appendChild(temp);
      temp.innerHTML = new_str;
      var first = temp.firstChild;
      var last = temp.lastChild;
      if(first)
      {
        range_source.selectNodeContents(temp);
        var fragment = range_source.extractContents();
        if( temp.parentNode == document )
        {
          document.replaceChild(fragment, temp);
          range_target.selectNode(document.documentElement);
        }
        else
        {
          range_target.insertNode(fragment);
          range_target.setStartBefore(first);
          range_target.setEndAfter(last);
        }
      };
      if(temp.parentNode)
      {
        temp.parentNode.removeChild(temp);
      };
      timeout = 0;
    };

    range_target.selectNode(target);
    this.__defineSetter__
    (
      "outerHTML",
      function(str)
      {
        new_str = str;
        timeout || ( timeout = setTimeout(update, 100) );
      }
    );

  };

  this.__is_active = function()
  {
    return this.context_enter && this.context_enter.host_target && true || false;
  }

  this.__set_host_updater = function(xml, rt_id)
  {
    var
    status = xml.getNodeData('status'),
    obj_id = xml.getNodeData('object-id');

    if(  status == 'completed' && obj_id )
    {
      this.context_enter.host_target = this.context_cur.host_target = obj_id;
    }
    else
    {
      opera.postError("failed __set_host_updater in DOMMarkupEditor");
    }
  }

  this.edit = function(event, ref_ele)
  {
    var
    ele = ref_ele || event.target,
    rt_id = ele.parentElement.parentElement.getAttribute('rt-id'),
    obj_id = ele.parentElement.getAttribute('ref-id'),
    script = "return new (" + Host_updater.toString() + ")(target)",
    tag = tagManager.setCB(this, this.__set_host_updater, [rt_id]),
    prop = '',
    container = ele;

    while( container
            && !/container/.test(container.nodeName)
            && ( container = container.parentElement ) );
    if(container)
    {
      container.firstChild.style.position = 'relative';
      container.firstChild.render(['fade-out']);
      this.context_enter =
      {
        rt_id: rt_id,
        obj_id: obj_id,
        parent_obj_id: dom_data.getParentElement(obj_id),
        outer_html: '',
        host_target: ''
      };
      this.context_cur = {};
      for( prop in this.context_enter )
      {
        this.context_cur[prop] = this.context_enter[prop];
      }
      services['ecmascript-debugger'].eval( tag, rt_id, '', '', script, ['target', obj_id]);
      tag = tagManager.setCB(this, this.__edit, [rt_id, obj_id, ele])
      services['ecmascript-debugger'].inspectDOM( tag, obj_id, 'subtree', 'json' );
    }
  }

  this.__edit = function(xml, rt_id, obj_id, ele)
  {
    var json = xml.getNodeData('jsondata');

    if( json )
    {
      var
      outerHTML = views['dom'].serializeToOuterHTML(eval('(' + json +')')),
      parent = ele.parentNode,
      parent_parent = parent.parentElement,
      margin = parseInt(parent.style.marginLeft),
      next = null;

      this.context_enter.outerHTML = this.context_cur.outerHTML = outerHTML;
      if( !this.base_style['font-size'] )
      {
        this.get_base_style(ele);
      }
      // this should never be needed
      if( this.textarea_container.parentElement )
      {
        opera.postError("this.textarea_container.parentElement is not null in submit");
      }
      this.textarea.value = outerHTML;
      parent.innerHTML = "";
      parent.appendChild(this.textarea_container);
      while( ( next = parent.nextElementSibling ) && parseInt(next.style.marginLeft) > margin )
      {
        parent_parent.removeChild(next);
      };
      if( next && parseInt(next.style.marginLeft) == margin && /<\//.test(next.textContent) )
      {
        parent_parent.removeChild(next);
      }
      this.set_textarea_dimensions();
      // only for click events
      if( event )
      {
        this.textarea.focus();
      }
    }
    else
    {
      opera.postError("get subtree failed in DOMMArkupEditor handleGetSubtree")
    }
  }

  this.oninput = function(event)
  {
    var
    script = "",
    state = this.context_cur;

    if( this.textarea_container.parentElement && state.host_target)
    {
      this.set_textarea_dimensions();
      state.outerHTML = this.textarea.value;
      var script = "host_target.outerHTML = '" + encode(state.outerHTML) + "';";
      services['ecmascript-debugger'].eval
      (
        0, state.rt_id, '', '', script, ['host_target', state.host_target]
      );
    }
  }

  this.submit = function()
  {
    // return a valid navigation target or null
    var
    state = this.context_cur,
    nav_target = this.textarea_container.parentElement;

    if(nav_target)
    {
      // to remove the textarea_container from the dom
      nav_target.textContent = "";
      this.context_cur = this.context_enter = null;
      dom_data.closeNode(state.parent_obj_id, true);
      dom_data.getChildernFromNode(state.parent_obj_id);
    }
    return nav_target;
  }

  this.cancel = function()
  {
    /*
    // return a valid navigation target or null
    var
    script = "",
    state = this.context_enter,
    nav_target = null;

    if( this.textarea_container.parentElement )
    {
      if(this.context_cur.is_new)
      {
        // TODO is this special?
      }
      else
      {
        nav_target = this.textarea_container.parentElement;
        switch(state.type)
        {
          case "key":
          {
            script = 'node.setAttribute("' + crlf_encode(state.key) + '","' + crlf_encode(state.value) + '")';
            services['ecmascript-debugger'].eval(0, state.rt_id, '', '', script, ["node", state.obj_id]);
            nav_target.textContent = state.key;
            break;
          }
          case "value":
          {
            script =  'node.setAttribute("' + crlf_encode(state.key) + '","' + crlf_encode(state.value) + '")';
            services['ecmascript-debugger'].eval(0, state.rt_id, '', '', script, ["node", state.obj_id]);
            nav_target.textContent = '"' + state.value + '"';
            break;
          }
          case "text":
          {
            script = 'node.nodeValue = "' + crlf_ecode(state.text) + '"';
            services['ecmascript-debugger'].eval(0, state.rt_id, '', '', script, ["node", state.obj_id]);
            nav_target.textContent = state.text;
            break;
          }
        }
      }
    }
    return nav_target;
    */
  }

  this.nav_previous = function(event, action_id)
  {
    /*
    // must return a valid navigation target or null
    var
    state = this.context_cur,
    nav_target = this.textarea_container.parentElement,
    nav_target_parent = nav_target.parentElement,
    next = nav_target.previousElementSibling,
    next_next = next && next.previousElementSibling,
    submit_success = this.submit(true),
    container = nav_target_parent.parentElement.parentElement;

    switch(state.type)
    {
      case "key":
      case "value":
      {
        ( next && ( submit_success || next.parentElement ) )
        || ( next = next_next )
        || ( next = nav_target_parent.getPreviousWithFilter(container, nav_filters.attr_text) );
        break;
      }
      case "text":
      {
        next = nav_target.getPreviousWithFilter(container, nav_filters.attr_text);
      }
    }

    if( next )
    {
      if( next.nodeName == 'node' )
      {
        next.firstChild.splitText(next.firstChild.nodeValue.length - 1);
        next = this.create_new_edit(next.firstChild);
      }
      else if( next.parentElement != nav_target_parent
                && next.nodeName == 'value'
                && next == next.parentElement.lastElementChild )
      {
        next = this.create_new_edit(next);
      }
      if(next)
      {
        this.edit({}, next);
      }
    }
    return next;
    */
  }

  this.nav_next = function(event, action_id)
  {
    /*
    // must return a valid navigation target or null
    var
    state = this.context_cur,
    nav_target = this.textarea_container.parentElement,
    nav_target_parent = nav_target.parentElement,
    next = nav_target.nextElementSibling,
    next_next = next && next.nextElementSibling,
    submit_success = this.submit(),
    container = nav_target_parent.parentElement.parentElement;

    switch(state.type)
    {
      case "key":
      case "value":
      {
        ( submit_success && ( next || ( next = this.create_new_edit(submit_success) ) ) )
        || ( next && next.parentElement ) || ( next = next_next )
        || ( next = nav_target_parent.getNextWithFilter(container, nav_filters.attr_text) );
        break;
      }
      case "text":
      {
        next = nav_target.getNextWithFilter(container, nav_filters.attr_text);
      }
    }
    if(next)
    {
      if( next.nodeName == 'node' )
      {
        next.firstChild.splitText(next.firstChild.nodeValue.length - 1);
        next = this.create_new_edit(next.firstChild);
      }
      this.edit({}, next);
    }
    return next;
    */
  }

  // helpers
  this.set_textarea_dimensions = function()
  {
    this.textarea.style.height = this.textarea.scrollHeight + 'px';
  }

  // could be the default method?
  this.onclick = function(event)
  {
    event.preventDefault();
    event.stopPropagation();
    if(!this.textarea_container.contains(event.target))
    {
      this.submit(true);
      return false;
    }
    return true;
  }
}

DOMMarkupEditor.prototype = BaseEditor;<commit_msg>cleanup DOM markup edit<commit_after>var DOMMarkupEditor = function()
{
  this.base_init(this);
  this.type = "dom-markup-editor";
  // specific context
  this.context_enter =
  {
    rt_id: '',
    obj_id: '',
    parent_obj_id: '',
    outerHTML: '',
    host_target: ''
  }

  this.context_cur =
  {
    rt_id: '',
    obj_id: '',
    parent_obj_id: '',
    outerHTML: '',
    host_target: ''
  }

  this.edit = function(event, ref_ele)
  {
    var
    ele = ref_ele || event.target,
    rt_id = ele.parentElement.parentElement.getAttribute('rt-id'),
    obj_id = ele.parentElement.getAttribute('ref-id'),
    script = '',
    tag = '',
    prop = '',
    container = ele;

    while( container
            && !/container/.test(container.nodeName)
            && ( container = container.parentElement ) );
    if(container)
    {
      container.firstChild.style.position = 'relative';
      container.firstChild.render(['fade-out']);
      this.context_enter =
      {
        rt_id: rt_id,
        obj_id: obj_id,
        parent_obj_id: dom_data.getParentElement(obj_id),
        outerHTML: '',
        host_target: ''
      };
      this.context_cur = {};
      for( prop in this.context_enter )
      {
        this.context_cur[prop] = this.context_enter[prop];
      }
      script = this["return new Host_updater(target)"];
      tag = tagManager.setCB(this, this.register_host_updater, [rt_id]);
      services['ecmascript-debugger'].eval( tag, rt_id, '', '', script, ['target', obj_id]);
      tag = tagManager.setCB(this, this.handle_get_outer_html, [rt_id, obj_id, ele, event])
      services['ecmascript-debugger'].inspectDOM( tag, obj_id, 'subtree', 'json' );
    }
  }

  this.oninput = function(event)
  {
    var
    script = "",
    state = this.context_cur;

    if( this.textarea_container.parentElement && state.host_target )
    {
      this.set_textarea_dimensions();
      state.outerHTML = this.textarea.value;
      var script = "host_target.outerHTML = '" + encode(state.outerHTML) + "';";
      services['ecmascript-debugger'].eval
      (
        0, state.rt_id, '', '', script, ['host_target', state.host_target]
      );
    }
  }

  this.submit = function()
  {
    // return a valid navigation target or null
    var
    state = this.context_cur,
    nav_target = this.textarea_container.parentElement;

    if(nav_target)
    {
      var script = "host_target.exit_edit()";
      services['ecmascript-debugger'].eval
      (
        0, state.rt_id, '', '', script, ['host_target', state.host_target]
      );
      this.on_exit_edit(state, nav_target);
    }
    return nav_target;
  }

  this.cancel = function()
  {
    // return a valid navigation target or null
    var
    script = "",
    state = this.context_enter,
    nav_target = this.textarea_container.parentElement;

    if( nav_target )
    {
      if(state.outerHTML != this.context_cur.outerHTML)
      {
        var script = "host_target.cancel_edit()";
        services['ecmascript-debugger'].eval
        (
          0, state.rt_id, '', '', script, ['host_target', state.host_target]
        );
      }
      this.on_exit_edit(state, nav_target);
    }
    return nav_target;
  }

  this.set_textarea_dimensions = function()
  {
    this.textarea.style.height = this.textarea.scrollHeight + 'px';
  }

  this.__is_active = function()
  {
    return this.context_enter && this.context_enter.host_target && true || false;
  }

  // could be the default method?
  this.onclick = function(event)
  {
    event.preventDefault();
    event.stopPropagation();
    if(!this.textarea_container.contains(event.target))
    {
      this.submit(true);
      return false;
    }
    return true;
  }

  // helpers

  this.on_exit_edit = function(state, nav_target)
  {
    // to remove the textarea_container from the dom
    nav_target.textContent = "";
    this.context_cur = this.context_enter = null;
    dom_data.closeNode(state.parent_obj_id, true);
    dom_data.getChildernFromNode(state.parent_obj_id);
  };

  var encode = function(str)
  {
    return str.replace(/\u200F\r\n/g, "").replace(/\r\n/g, "\\n").replace(/'/g, "\\'");
  };

  // class on the host side to update the given DOM range
  var Host_updater = function(target)
  {
    var
    range_target = document.createRange(),
    timeout = 0,
    new_str = '',
    enter_node = null,
    update = function(str)
    {
      if( enter_node )
      {
        range_target.deleteContents();
      }
      else
      {
        enter_node = range_target.extractContents();
      };
      var range_source = document.createRange();
      var temp = document.createElement('df-temp-element');
      ( document.body || document.documentElement || document ).appendChild(temp);
      temp.innerHTML = new_str;
      var first = temp.firstChild;
      var last = temp.lastChild;
      if(first)
      {
        range_source.selectNodeContents(temp);
        var fragment = range_source.extractContents();
        if( temp.parentNode == document )
        {
          document.replaceChild(fragment, temp);
          range_target.selectNode(document.documentElement);
        }
        else
        {
          range_target.insertNode(fragment);
          range_target.setStartBefore(first);
          range_target.setEndAfter(last);
        }
      };
      if(temp.parentNode)
      {
        temp.parentNode.removeChild(temp);
      };
      timeout = 0;
    };

    range_target.selectNode(target);
    this.__defineSetter__
    (
      "outerHTML",
      function(str)
      {
        new_str = str;
        timeout || ( timeout = setTimeout(update, 100) );
      }
    );
    this.cancel_edit = function()
    {
      timeout && ( timeout = clearTimeout(timeout) );
      if(enter_node)
      {
        range_target.deleteContents();
        range_target.insertNode(enter_node);
      }
      this.exit_edit();
    };
    this.exit_edit = function()
    {
      if( timeout )
      {
        timeout = clearTimeout(timeout);
        update();
      };
      range_target = timeout = new_str = enter_node = update = null;
    };
  };

  this["return new Host_updater(target)"] =
    "return new (" + Host_updater.toString() + ")(target)";

  this.register_host_updater = function(xml, rt_id)
  {
    var
    status = xml.getNodeData('status'),
    obj_id = xml.getNodeData('object-id');

    if(  status == 'completed' && obj_id )
    {
      this.context_enter.host_target = this.context_cur.host_target = obj_id;
    }
    else
    {
      opera.postError("failed register_host_updater in DOMMarkupEditor");
    }
  }

  // complete the edit call
  this.handle_get_outer_html = function(xml, rt_id, obj_id, ele, event)
  {
    var json = xml.getNodeData('jsondata');
    if( json )
    {
      var
      outerHTML = views['dom'].serializeToOuterHTML(eval('(' + json +')')),
      parent = ele.parentNode,
      parent_parent = parent.parentElement,
      margin = parseInt(parent.style.marginLeft),
      next = null;

      this.context_enter.outerHTML = this.context_cur.outerHTML = outerHTML;
      if( !this.base_style['font-size'] )
      {
        this.get_base_style(ele);
      }
      // this should never be needed
      if( this.textarea_container.parentElement )
      {
        opera.postError("this.textarea_container.parentElement is not null in submit");
      }
      this.textarea.value = outerHTML;
      parent.innerHTML = "";
      parent.appendChild(this.textarea_container);
      while( ( next = parent.nextElementSibling ) && parseInt(next.style.marginLeft) > margin )
      {
        parent_parent.removeChild(next);
      };
      if( next && parseInt(next.style.marginLeft) == margin && /<\//.test(next.textContent) )
      {
        parent_parent.removeChild(next);
      }
      this.set_textarea_dimensions();
      // only for click events
      if( event )
      {
        this.textarea.focus();
      }
      this.textarea.selectionEnd = this.textarea.selectionStart = 0;
    }
    else
    {
      opera.postError("get subtree failed in DOMMarkupEditor handleGetSubtree")
    }
  }
}

DOMMarkupEditor.prototype = BaseEditor;<|endoftext|>


<commit_before>var count = {};
var games = {};

$(function() {
  $("#steam-id-submit").click(function() {
    var steam_id = $("#steam-id").val();
    if(steam_id.length > 0) {
      count = {}; games = {};
      $(".card-list").html('');
      $('[id^="reddit-table"]').hide();
      getCardsJson(steam_id);
    } else {
      $('.card-list').html("
Please input your Steam ID
");
    }
    return false;
  });

  $("#reddit-table-button").click(function() {
    $("#reddit-table").html(generateRedditTable());
    $("#reddit-table").fadeIn();
    return false;
  });

  $("#show-doubles, #show-all").click(function() {
    $(".card-list").html('');
    if($(this).prop('id') == "show-doubles") {
      listDoubleGames();
      $(this).html("Show all").prop("id", "show-all");
    } else {
       listGames();
      $(this).html("Show only doubles").prop("id", "show-doubles");
    }
    return false;
  });
});

function getCardsJson(steam_id) {
  api_url = "http://whateverorigin.org/get?url=";
  if(/^\d+$/.test(steam_id))
    api_url += encodeURIComponent('https://steamcommunity.com/profiles/' + steam_id);
  else
    api_url += encodeURIComponent('https://steamcommunity.com/id/' + steam_id);
  api_url += encodeURIComponent("/inventory/json/753/6?language=english");

  $.ajax({
    url: api_url,
    dataType: 'jsonp',
    success: function(data) {
      // parse the json
      try {
        cards_json = $.parseJSON(data.contents)['rgDescriptions'];
        count_json = $.parseJSON(data.contents)['rgInventory'];
      }
      catch(err) {
        $('.card-list').html("
And error occurred! Is your Steam profile public? Did you type your Steam ID correctly?
");
        return;
      }

      // count the cards
      for(var key in count_json) {
        var classid = count_json[key]['classid'];
        if(count[classid]) ++count[classid]; else count[classid]=1;
      }

      // build up the card collection by games
      for(var key in cards_json) {
        if (cards_json[key]['tags'][2]['name'] != "Trading Card" && cards_json[key]['tags'][2]['name'] != "Foil") continue;
        card = {
          'name': cards_json[key]['name'].replace(" (Trading Card)", ""),
          'game': cards_json[key]['tags'][1]['name'],
          'icon_url': cards_json[key]['icon_url'],
          'market_name': cards_json[key]['market_name'],
          'market_hash_name': cards_json[key]['market_hash_name'],
          'amount': count[cards_json[key]['classid']],
        }
        if (games[card['game']]) {
          // if there is only 1 card no problem
          if(card['amount'] === 1) games[card['game']].push(card);
          // in case of 2 cards they are twice in the rgDescriptions too
          // so we have to do this to avoid adding them twice
          else {
            var add = true;
            for(var idx in games[card['game']])
              if(games[card['game']][idx]['name'] === card['name']) {add = false; break;}
            if(add) games[card['game']].push(card);
          }
        } else {
          games[card['game']] = [card];
        }
      }
      listGames();
    }
  });
}

// return the HTML of the one card box
function get_card(name, img_src, market_url, amount) {
  return '
' +
          '
' +
            '' +
          '
' +
          '
' +
            name + (amount > 1 ? ' x' + amount : '') + '
' +
            'Steam market' +
          '
' +
         '
';
 }

// generates the HTML with the game names + cards
function generateHTML() {
  html = ""
  for(var key in games) {
    html += "
" + key + "
";
    for(var i in games[key]) {
      card = games[key][i];
      html += get_card(card['name'], card['icon_url'], card['market_hash_name'], card['amount']);
    }
    html += '

';
  }
  return html;
}

// generates the HTML for the double cards list
function generateDoubleHTML() {
  html = ""
  for(var key in games) {
    var hasDouble = false;
    for(var i in games[key]) {
      card = games[key][i];
      if(card['amount'] > 1) {
        if(!hasDouble) {
          html += "
" + key + "
";
          hasDouble = true;
        }
        html += get_card(card['name'], card['icon_url'], card['market_hash_name'], card['amount']);
      }
    }
    html += '

';
  }
  return html;
}

// generates a table code for reddit.com
function generateRedditTable() {
  table = "|Game|Cards\n|:-|:-:|";
  for(var key in games) {
    table += "\n|" + key + "|";
    for(var i in games[key]) {
      var card = games[key][i];
      table += card['name'] + (card['amount'] > 1 ? ' x' + card['amount'] : '') + ', ';
    }
    table = table.substr(0, table.length-2) + '|';
  }
  return table;
}

// adds the generated HTML to the page
function listGames() {
  $(".card-list").html(generateHTML());
  $("#reddit-table-button").fadeIn();
  $("#show-doubles").fadeIn();
}

// adds the doubles to the page
function listDoubleGames() {
  $(".card-list").html(generateDoubleHTML());
}
<commit_msg>fix the card lister<commit_after>var count = {};
var games = {};

$(function() {
  $("#steam-id-submit").click(function() {
    var steam_id = $("#steam-id").val();
    if(steam_id.length > 0) {
      count = {}; games = {};
      $(".card-list").html('');
      $('[id^="reddit-table"]').hide();
      getCardsJson(steam_id);
    } else {
      $('.card-list').html("
Please input your Steam ID
");
    }
    return false;
  });

  $("#reddit-table-button").click(function() {
    $("#reddit-table").html(generateRedditTable());
    $("#reddit-table").fadeIn();
    return false;
  });

  $("#show-doubles, #show-all").click(function() {
    $(".card-list").html('');
    if($(this).prop('id') == "show-doubles") {
      listDoubleGames();
      $(this).html("Show all").prop("id", "show-all");
    } else {
       listGames();
      $(this).html("Show only doubles").prop("id", "show-doubles");
    }
    return false;
  });
});

function getCardsJson(steam_id) {
  api_url = "http://whateverorigin.org/get?url=";
  if(/^\d+$/.test(steam_id))
    api_url += encodeURIComponent('https://steamcommunity.com/profiles/' + steam_id);
  else
    api_url += encodeURIComponent('https://steamcommunity.com/id/' + steam_id);
  api_url += encodeURIComponent("/inventory/json/753/6?language=english");

  $.ajax({
    url: api_url,
    dataType: 'jsonp',
    success: function(data) {
      // parse the json
      try {
        cards_json = $.parseJSON(data.contents)['rgDescriptions'];
        count_json = $.parseJSON(data.contents)['rgInventory'];
      }
      catch(err) {
        $('.card-list').html("
And error occurred! Is your Steam profile public? Did you type your Steam ID correctly?
");
        return;
      }

      // count the cards
      for(var key in count_json) {
        var classid = count_json[key]['classid'];
        if(count[classid]) ++count[classid]; else count[classid]=1;
      }

      // build up the card collection by games
      for(var key in cards_json) {
        if( // if there is no tags key
           (!("tags" in cards_json[key]) || cards_json[key]['tags'].length < 4)
            ||
            // or it's not a Trading Card or Foil
            (cards_json[key]['tags'][3]['internal_name'] != "item_class_2" &&
            cards_json[key]['tags'][3]['internal_name'] != "item_class_1")) continue;

        card = {
          'name': cards_json[key]['name'].replace(" (Trading Card)", ""),
          'game': cards_json[key]['tags'][1]['name'],
          'icon_url': cards_json[key]['icon_url'],
          'market_name': cards_json[key]['market_name'],
          'market_hash_name': cards_json[key]['market_hash_name'],
          'amount': count[cards_json[key]['classid']],
        }
        if (games[card['game']]) {
          // if there is only 1 card no problem
          if(card['amount'] === 1) games[card['game']].push(card);
          // in case of 2 cards they are twice in the rgDescriptions too
          // so we have to do this to avoid adding them twice
          else {
            var add = true;
            for(var idx in games[card['game']])
              if(games[card['game']][idx]['name'] === card['name']) {add = false; break;}
            if(add) games[card['game']].push(card);
          }
        } else {
          games[card['game']] = [card];
        }
      }
      listGames();
    }
  });
}

// return the HTML of the one card box
function get_card(name, img_src, market_url, amount) {
  return '
' +
          '
' +
            '' +
          '
' +
          '
' +
            name + (amount > 1 ? ' x' + amount : '') + '
' +
            'Steam market' +
          '
' +
         '
';
 }

// generates the HTML with the game names + cards
function generateHTML() {
  html = ""
  for(var key in games) {
    html += "
" + key + "
";
    for(var i in games[key]) {
      card = games[key][i];
      html += get_card(card['name'], card['icon_url'], card['market_hash_name'], card['amount']);
    }
    html += '

';
  }
  return html;
}

// generates the HTML for the double cards list
function generateDoubleHTML() {
  html = ""
  for(var key in games) {
    var hasDouble = false;
    for(var i in games[key]) {
      card = games[key][i];
      if(card['amount'] > 1) {
        if(!hasDouble) {
          html += "
" + key + "
";
          hasDouble = true;
        }
        html += get_card(card['name'], card['icon_url'], card['market_hash_name'], card['amount']);
      }
    }
    html += '

';
  }
  return html;
}

// generates a table code for reddit.com
function generateRedditTable() {
  table = "|Game|Cards\n|:-|:-:|";
  for(var key in games) {
    table += "\n|" + key + "|";
    for(var i in games[key]) {
      var card = games[key][i];
      table += card['name'] + (card['amount'] > 1 ? ' x' + card['amount'] : '') + ', ';
    }
    table = table.substr(0, table.length-2) + '|';
  }
  return table;
}

// adds the generated HTML to the page
function listGames() {
  $(".card-list").html(generateHTML());
  $("#reddit-table-button").fadeIn();
  $("#show-doubles").fadeIn();
}

// adds the doubles to the page
function listDoubleGames() {
  $(".card-list").html(generateDoubleHTML());
}
<|endoftext|>


<commit_before>
'use strict';

// @ngInject

var ExpeditionEditController = function($scope, $controller, $routeParams, $http, $sce, Expedition, formula,
  formulaAutoCompleteService, npdcAppConfig, chronopicService, fileFunnelService, NpolarLang,
  npolarApiConfig, NpolarApiSecurity, NpolarMessage, npolarCountryService) {

  var proj4 = require('proj4');

  function init() {

  // EditController -> NpolarEditController
  $controller('NpolarEditController', {
    $scope: $scope
  });

  // Inventory -> npolarApiResource -> ngResource
  $scope.resource = Expedition;

  let formulaOptions = {
      schema: '//api.npolar.no/schema/expedition-1',
      form: 'edit/formula.json',
      language: NpolarLang.getLang(),
      templates: npdcAppConfig.formula.templates.concat([{
        match(field) {
          if (field.id === 'links_item') {
            let match;

          // Hide data links and system links for the ordinary links block (defined in formula as instance === 'links')
            match = ["data", "alternate", "edit", "via"].includes(field.value.rel) && field.parents[field.parents.length-1].instance === 'links';
            console.log(match, field.id, field.path, 'value', field.value, 'instance', field.parents[field.parents.length-1].instance);
            return match;
          }
        },
        hidden: true
      },  {
        match: "locations_item",
        template: "<expedition:coverage></expedition:coverage>"
      } //,
  //  {
  //      match: "placenames_item",
  //      template: '<npdc:formula-placename></npdc:formula-placename>'
  //    }
    ]),
      languages: npdcAppConfig.formula.languages.concat([{
        map: require('./en.json'),
        code: 'en'
      }, {
        map: require('./no.json'),
        code: 'nb_NO',
      }])
    };

  $scope.formula = formula.getInstance(formulaOptions);
  initFileUpload($scope.formula);

  formulaAutoCompleteService.autocomplete({
    match: "@country",
  //  querySource: npolarApiConfig.base + '/country/?q-name=',
    querySource: npolarApiConfig.base + '/country',
    label: 'name',
    value: 'code'
  }, $scope.formula);

  formulaAutoCompleteService.autocomplete({
    match: "@departure_country",
    querySource: npolarApiConfig.base + '/country',
    label: 'name',
    value: 'code'
  }, $scope.formula);

  formulaAutoCompleteService.autocomplete({
    match: "@return_country",
    querySource: npolarApiConfig.base + '/country',
    label: 'name',
    value: 'code'
  }, $scope.formula);

 // formulaAutoCompleteService.autocompleteFacets(['people.first_name',
 //   'people.last_name', 'people.organisation', 'platforms.sponsor', 'tags', 'platforms.vessel_name'], Expedition, $scope.formula);

  formulaAutoCompleteService.autocompleteFacets(['people.first_name',
    'people.last_name', 'platforms.sponsor', 'people.organisation', 'tags', 'platforms.vessel_name'], Expedition, $scope.formula);

//  chronopicService.defineOptions({ match: 'released', format: '{date}'});
//  chronopicService.defineOptions({ match(field) {
//    return field.path.match(/^#\/activity\/\d+\/.+/);
//  }, format: '{date}'});

// Set default #/people/expedition_dates/start_date based on #/start_date
chronopicService.defineOptions({
  match(field) {
    return field.path === "#/start_date";
  },
  format: '{date}',
  onChange(elem, date) {
    $scope.formula.getFieldByPath("#/people/0/expedition_dates/0/start_date").then(function(field) {
      field.schema.default = date.toISOString();
    });
  }
});

// Set default #/people/expedition_dates/end_date based on #/end_date
chronopicService.defineOptions({
  match(field) {
    return field.path === "#/end_date";
  },
  format: '{date}',
  onChange(elem, date) {
    $scope.formula.getFieldByPath("#/people/0/expedition_dates/0/end_date").then(function(field) {
      field.schema.default = date.toISOString();
    });
  }
});

//Set chronopic view format (this does not change the internal value, i.e. ISO string date)
chronopicService.defineOptions({
  match(field) {
    return field.path.match(/^#\/.+?\/.+?_date$/);
  },
  format: '{date}'
});

$scope.formula.getFieldByPath("#/people").then(function(field) {

  // "#/people/expedition_dates/start_date"

  /*
  .getFieldByPath("#/people/expedition_dates/start_date").then(function(field) {
    field.default = "...";
  });
  */

  //field.fieldDefinition.items.fields[6].items.fields[0].default = "2017-03-03T00:00:00Z"; // start
  //field.fieldDefinition.items.fields[6].items.fields[1].default = "2017-03-03T00:00:00Z"; // retur
});

}

 function initFileUpload(formula) {

    let server = `${NpolarApiSecurity.canonicalUri($scope.resource.path)}/restricted/:id/_file`;

    fileFunnelService.fileUploader({
      match(field) {
        return field.id === "files";
      },
      server,
      multiple: true,
      progress: false,
       restricted: function () {
        return formula.getModel().restricted;
      },
      fileToValueMapper: Expedition.fileObject,
      valueToFileMapper: Expedition.hashiObject,
      fields: ['filename'] // 'type', 'hash'
    }, formula);
}

  try {
    init();

     // edit (or new) action
     $scope.edit();

  } catch (e) {
    NpolarMessage.error(e);
  }

  $scope.$watch('formula.getModel().ris', function(ris) {

  let p = $scope.formula.getModel();

  //if it is a ris project number, that is a number with 3-5 digits
  if ((/^[0-9]{3,5}$/).test(p.ris)) {

    //Do call to RiS and use results
    $http.get('https://cors-anywhere.herokuapp.com/https://www.researchinsvalbard.no/api/project/'+p.ris+'.json',{
      headers: {'Accept': 'application/json'}

     }).success(function(data){

        p = get_RIS(p,data);
        console.log("p",p);
        console.log("data", data);

    }).error(function(data, status, headers, config) {
        console.log("Calling Research in SValbard failed.");
        console.log(data, status, headers, config);
    });

  } //if
  }); //end $watch

 //Move RIS values to formula object
 function get_RIS(p,data) {
      //Create a new object if not already existing
      if (!p.id) {
            p = Object.assign({}, Expedition.create(),p);
      }

     //Do the assignments with RiS
        p.type = "fieldwork";
        p.activity_type = "research";
        p.ris = data.risId;
        if (data.summary !== undefined) { p.summary = data.summary; }
        if (data.title !== undefined) { p.code = data.title; }
         let temp_arr = [];
        if ((data.persons) && ((data.persons).length > 0)) {
           //Traverse through all persons objects
           for (let k=0;k<(data.persons).length; k++){
             temp_arr[k] = (({ givenName, surName, role }) => ({ givenName, surName, role }))(data.persons[k]);
             temp_arr[k].first_name = temp_arr[k].givenName; delete temp_arr[k].givenName;
             temp_arr[k].last_name = temp_arr[k].surName; delete temp_arr[k].surName;
             //New names for project owner
             if (temp_arr[k].role === 'Project Owner') {
                 temp_arr[k].role = 'expedition/cruise leader';
                 temp_arr.splice(temp_arr[k], 0, temp_arr.splice(temp_arr[k], 1)[0]);
                 temp_arr.splice(0, 0, temp_arr[k]); //Insert elem at the start
                 temp_arr.splice(k+1,1); //Remove elem from place K
             } else {
                  temp_arr[k].role = 'other';
             }
          }

       }

        //Clean temp_arr for name duplicates
        let m = 0;
        while (m < temp_arr.length) {
          for (let l=(m+1);l<(temp_arr.length); l++){
                 let inner = (({last_name,first_name }) => ({ last_name,first_name }))(temp_arr[l]);
                 let outer = (({last_name,first_name }) => ({ last_name,first_name }))(temp_arr[m]);
                 if (JSON.stringify(inner) === JSON.stringify(outer)) {
                   temp_arr.splice(l,1); l=l-1; }
          }
          m++;
        }

        //Copy result to p.people
        p.people = temp_arr;

        //Fieldworks could be more than one, we select the last fieldwork
        if ((data.fieldworks) && ((data.fieldworks).length > 0)) {
           let count = ((data.fieldworks).length)-1;
          if (data.fieldworks[count].startDate) {
            p.start_date = data.fieldworks[count].startDate + 'T12:00:00Z';
          }
          if (data.fieldworks[count].endDate) {
            p.end_date = data.fieldworks[count].endDate + 'T12:00:00Z';
          }
          //Need location also - goes here - use proj4
          let loc = {};
          let utm33 = proj4('+proj=utm +zone=33 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs');
          let decimal_coord = proj4(utm33,'EPSG:4326').forward([data.fieldworks[count].utm33East, data.fieldworks[count].utm33North]);

          if (data.fieldworks[count].utm33East) {
             loc.east = decimal_coord[0];
             loc.west = decimal_coord[0];
          }
          if (data.fieldworks[count].utm33North) {
             loc.north = decimal_coord[1];
             loc.south = decimal_coord[1];
          }
          //Insert locations from RiS into our return object
          p.locations = [loc];
        }

    return p;
 }

};

module.exports = ExpeditionEditController;<commit_msg>fetching RiS values works<commit_after>
'use strict';

// @ngInject

var ExpeditionEditController = function($scope, $controller, $routeParams, $http, $sce, Expedition, formula,
  formulaAutoCompleteService, npdcAppConfig, chronopicService, fileFunnelService, NpolarLang,
  npolarApiConfig, NpolarApiSecurity, NpolarMessage, npolarCountryService) {

  var proj4 = require('proj4');

  function init() {

  // EditController -> NpolarEditController
  $controller('NpolarEditController', {
    $scope: $scope
  });

  // Inventory -> npolarApiResource -> ngResource
  $scope.resource = Expedition;

  let formulaOptions = {
      schema: '//api.npolar.no/schema/expedition-1',
      form: 'edit/formula.json',
      language: NpolarLang.getLang(),
      templates: npdcAppConfig.formula.templates.concat([{
        match(field) {
          if (field.id === 'links_item') {
            let match;

          // Hide data links and system links for the ordinary links block (defined in formula as instance === 'links')
            match = ["data", "alternate", "edit", "via"].includes(field.value.rel) && field.parents[field.parents.length-1].instance === 'links';
            console.log(match, field.id, field.path, 'value', field.value, 'instance', field.parents[field.parents.length-1].instance);
            return match;
          }
        },
        hidden: true
      },  {
        match: "locations_item",
        template: "<expedition:coverage></expedition:coverage>"
      } //,
  //  {
  //      match: "placenames_item",
  //      template: '<npdc:formula-placename></npdc:formula-placename>'
  //    }
    ]),
      languages: npdcAppConfig.formula.languages.concat([{
        map: require('./en.json'),
        code: 'en'
      }, {
        map: require('./no.json'),
        code: 'nb_NO',
      }])
    };

  $scope.formula = formula.getInstance(formulaOptions);
  initFileUpload($scope.formula);

  formulaAutoCompleteService.autocomplete({
    match: "@country",
  //  querySource: npolarApiConfig.base + '/country/?q-name=',
    querySource: npolarApiConfig.base + '/country',
    label: 'name',
    value: 'code'
  }, $scope.formula);

  formulaAutoCompleteService.autocomplete({
    match: "@departure_country",
    querySource: npolarApiConfig.base + '/country',
    label: 'name',
    value: 'code'
  }, $scope.formula);

  formulaAutoCompleteService.autocomplete({
    match: "@return_country",
    querySource: npolarApiConfig.base + '/country',
    label: 'name',
    value: 'code'
  }, $scope.formula);

 // formulaAutoCompleteService.autocompleteFacets(['people.first_name',
 //   'people.last_name', 'people.organisation', 'platforms.sponsor', 'tags', 'platforms.vessel_name'], Expedition, $scope.formula);

  formulaAutoCompleteService.autocompleteFacets(['people.first_name',
    'people.last_name', 'platforms.sponsor', 'people.organisation', 'tags', 'platforms.vessel_name'], Expedition, $scope.formula);

//  chronopicService.defineOptions({ match: 'released', format: '{date}'});
//  chronopicService.defineOptions({ match(field) {
//    return field.path.match(/^#\/activity\/\d+\/.+/);
//  }, format: '{date}'});

// Set default #/people/expedition_dates/start_date based on #/start_date
chronopicService.defineOptions({
  match(field) {
    return field.path === "#/start_date";
  },
  format: '{date}',
  onChange(elem, date) {
    $scope.formula.getFieldByPath("#/people/0/expedition_dates/0/start_date").then(function(field) {
      field.schema.default = date.toISOString();
    });
  }
});

// Set default #/people/expedition_dates/end_date based on #/end_date
chronopicService.defineOptions({
  match(field) {
    return field.path === "#/end_date";
  },
  format: '{date}',
  onChange(elem, date) {
    $scope.formula.getFieldByPath("#/people/0/expedition_dates/0/end_date").then(function(field) {
      field.schema.default = date.toISOString();
    });
  }
});

//Set chronopic view format (this does not change the internal value, i.e. ISO string date)
chronopicService.defineOptions({
  match(field) {
    return field.path.match(/^#\/.+?\/.+?_date$/);
  },
  format: '{date}'
});

$scope.formula.getFieldByPath("#/people").then(function(field) {

  // "#/people/expedition_dates/start_date"

  /*
  .getFieldByPath("#/people/expedition_dates/start_date").then(function(field) {
    field.default = "...";
  });
  */

  //field.fieldDefinition.items.fields[6].items.fields[0].default = "2017-03-03T00:00:00Z"; // start
  //field.fieldDefinition.items.fields[6].items.fields[1].default = "2017-03-03T00:00:00Z"; // retur
});

}

 function initFileUpload(formula) {

    let server = `${NpolarApiSecurity.canonicalUri($scope.resource.path)}/restricted/:id/_file`;

    fileFunnelService.fileUploader({
      match(field) {
        return field.id === "files";
      },
      server,
      multiple: true,
      progress: false,
       restricted: function () {
        return formula.getModel().restricted;
      },
      fileToValueMapper: Expedition.fileObject,
      valueToFileMapper: Expedition.hashiObject,
      fields: ['filename'] // 'type', 'hash'
    }, formula);
}

  try {
    init();

     // edit (or new) action
     $scope.edit();

  } catch (e) {
    NpolarMessage.error(e);
  }

  $scope.$watch('formula.getModel().ris', function(ris) {

  let p = $scope.formula.getModel();

  //if it is a ris project number, that is a number with 3-5 digits
  if (((/^[0-9]{3,5}$/).test(p.ris))&&(!p.id)&&(p.activity_type==='')) {

    //Do call to RiS and use results
    $http.get('https://cors-anywhere.herokuapp.com/https://www.researchinsvalbard.no/api/project/'+p.ris+'.json',{
      headers: {'Accept': 'application/json'}

     }).success(function(data){

        p = get_RIS(p,data);
        //console.log("p",p);
        //console.log("data", data);
        $scope.formula.setModel(p);

    }).error(function(data, status, headers, config) {
        console.log("Calling Research in SValbard failed.");
        console.log(data, status, headers, config);
    });

  } //if
  }); //end $watch

 //Move RIS values to formula object
 function get_RIS(p,data) {
      //Create a new object if not already existing
      if (!p.id) {
            p = Object.assign({}, Expedition.create(),p);
      }

     //Do the assignments with RiS
        p.type = "fieldwork";
        p.activity_type = "research";
        p.ris = data.risId;
        if (data.summary !== undefined) { p.summary = data.summary; }
        if (data.title !== undefined) { p.code = data.title; }
         let temp_arr = [];
        if ((data.persons) && ((data.persons).length > 0)) {
           //Traverse through all persons objects
           for (let k=0;k<(data.persons).length; k++){
             temp_arr[k] = (({ givenName, surName, role }) => ({ givenName, surName, role }))(data.persons[k]);
             temp_arr[k].first_name = temp_arr[k].givenName; delete temp_arr[k].givenName;
             temp_arr[k].last_name = temp_arr[k].surName; delete temp_arr[k].surName;
             //New names for project owner
             if (temp_arr[k].role === 'Project Owner') {
                 temp_arr[k].role = 'expedition/cruise leader';
                 temp_arr.splice(temp_arr[k], 0, temp_arr.splice(temp_arr[k], 1)[0]);
                 temp_arr.splice(0, 0, temp_arr[k]); //Insert elem at the start
                 temp_arr.splice(k+1,1); //Remove elem from place K
             } else {
                  temp_arr[k].role = 'other';
             }
          }

       }

        //Clean temp_arr for name duplicates
        let m = 0;
        while (m < temp_arr.length) {
          for (let l=(m+1);l<(temp_arr.length); l++){
                 let inner = (({last_name,first_name }) => ({ last_name,first_name }))(temp_arr[l]);
                 let outer = (({last_name,first_name }) => ({ last_name,first_name }))(temp_arr[m]);
                 if (JSON.stringify(inner) === JSON.stringify(outer)) {
                   temp_arr.splice(l,1); l=l-1; }
          }
          m++;
        }

        //Copy result to p.people
        p.people = temp_arr;

        //Fieldworks could be more than one, we select the last fieldwork
        if ((data.fieldworks) && ((data.fieldworks).length > 0)) {
           let count = ((data.fieldworks).length)-1;
          if (data.fieldworks[count].startDate) {
            p.start_date = data.fieldworks[count].startDate + 'T12:00:00Z';
          }
          if (data.fieldworks[count].endDate) {
            p.end_date = data.fieldworks[count].endDate + 'T12:00:00Z';
          }
          //Need location also - goes here - use proj4
          let loc = {};
          let utm33 = proj4('+proj=utm +zone=33 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs');
          let decimal_coord = proj4(utm33,'EPSG:4326').forward([data.fieldworks[count].utm33East, data.fieldworks[count].utm33North]);

          if (data.fieldworks[count].utm33East) {
             loc.east = decimal_coord[0];
             loc.west = decimal_coord[0];
          }
          if (data.fieldworks[count].utm33North) {
             loc.north = decimal_coord[1];
             loc.south = decimal_coord[1];
          }
          //Insert locations from RiS into our return object
          p.locations = [loc];
        }

    return p;
 }

};

module.exports = ExpeditionEditController;<|endoftext|>


<commit_before>//carat pasting api. from http://jsbin.com/aqAYUwu/5 and http://stackoverflow.com/questions/19620439/javascript-get-cursor-position-in-contenteditable-div

scratchpad.modules.define("caret", {
	pasteHtmlAtCaret: function(html, selectPastedContent) {
		var sel, range;
		if(document.activeElement.id == "document-editor") {
			if (window.getSelection) {
				// IE9 and non-IE
				sel = window.getSelection();
				if (sel.getRangeAt && sel.rangeCount) {
					range = sel.getRangeAt(0);
					range.deleteContents();

					var el = document.createElement("div");
					el.innerHTML = html;
					var frag = document.createDocumentFragment(), node, lastNode;
					while (node = el.firstChild) {
						lastNode = frag.appendChild(node);
					}
					var firstNode = frag.firstChild;
					range.insertNode(frag);
				}
			}
			else if ((sel = document.selection) && sel.type != "Control") {
				var originalRange = sel.createRange();
				originalRange.collapse(true);
				sel.createRange().pasteHTML(html);
				if (selectPastedContent) {
					range = sel.createRange();
					range.setEndPoint("StartToStart", originalRange);
					range.select();
				}
			}
		} // end focus check
		else {
			$("#document-editor").append(html);
			var elem = document.getElementsByClassName('page-container')[0]; //scroll to the bottom so the user knows that something was added
			elem.scrollTop = elem.scrollHeight;
		}
	}
});
<commit_msg>use execCommand<commit_after>//carat pasting api. from http://jsbin.com/aqAYUwu/5 and http://stackoverflow.com/questions/19620439/javascript-get-cursor-position-in-contenteditable-div

scratchpad.modules.define("caret", {
	pasteHtmlAtCaret: function(html, selectPastedContent) {
		var sel, range;
		if(document.activeElement.id == "document-editor") {
			document.execCommand("insertHTML", false, html); //TODO add fallback if this is unsupported by using the old caret api
		} // end focus check
		else {
			$("#document-editor").append(html);
			var elem = document.getElementsByClassName('page-container')[0]; //scroll to the bottom so the user knows that something was added
			elem.scrollTop = elem.scrollHeight;
		}
	}
});
<|endoftext|>


<commit_before>/*
    Created by: Casey Cabrales
    8/13/16

    In reference to tutorial at http://blog.alexanderdickson.com/javascript-chip-8-emulator
    by Alexander Dickson.
 */

class Chip8 {
    reset() {
        //Program Counter
        this.pc = 0x200;

        // Memory
        this.memory = new Uint8Array(4096);

        // Stack
        this.stack = new Array(16);

        // Stack Pointer
        this.sp = 0;

        // "V" Registers
        this.v = new Uint8Array(16);

        // "I" Register
        this.i = 0;

        // Delay Timer
        this.delayTimer = 0;

        // Sound Timer
        this.soundTimer = 0;

    }
}<commit_msg>Added basic animation rame/cycle functions for prototype<commit_after>/*
    Created by: Casey Cabrales
    8/13/16

    In reference to tutorial at http://blog.alexanderdickson.com/javascript-chip-8-emulator
    by Alexander Dickson.
 */

class Chip8 {

    requestAnimFrame() {
        for (let i = 0; i < NUM_CYCLES; i++) {
            this.cycle();
        }
    }

    cycle() {

    }

    reset() {
        //Program Counter
        this.pc = DEFAULT_PC;

        // Memory
        this.memory = new Uint8Array(4096);

        // Stack
        this.stack = new Array(16);

        // Stack Pointer
        this.sp = 0;

        // "V" Registers
        this.v = new Uint8Array(16);

        // "I" Register
        this.i = 0;

        // Delay Timer
        this.delayTimer = 0;

        // Sound Timer
        this.soundTimer = 0;
    }
}<|endoftext|>


<commit_before>describe('any', () => {
    it('works for any values', () => {
        expect((Jo) => Jo.any()).not.to.failOn(undefined);
        expect((Jo) => Jo.any()).not.to.failOn(null);
        expect((Jo) => Jo.any()).not.to.failOn('fubar');
    });

    it('takes optional values', () => {
        expect((Jo) => Jo.optional()).not.to.failOn(undefined);
        expect((Jo) => Jo.optional()).not.to.failOn(null);
        expect((Jo) => Jo.optional()).not.to.failOn('fubar');
    });

    it('requires values correctly', () => {
        expect((Jo) => Jo.required()).to.failOn(undefined, [
            {
                context: { key: 'value' },
                message: '"value" is required',
                path: 'value',
                type: 'required'
            }
        ]);

        expect((Jo) => Jo.required()).not.to.failOn(null);
        expect((Jo) => Jo.required()).not.to.failOn('fubar');
    });

    it('disallows forbidden values', () => {
        expect((Jo) => Jo.forbidden()).not.to.failOn(undefined);
        expect((Jo) => Jo.forbidden()).to.failOn(null);
        expect((Jo) => Jo.forbidden()).to.failOn('fubar');
    });

    it('allows valid values', () => {
        expect((Jo) => Jo.valid('a')).to.failOn('c');
        expect((Jo) => Jo.valid('a')).not.to.failOn('a');

        expect((Jo) => Jo.valid('a', 'b')).not.to.failOn('a');
        expect((Jo) => Jo.valid('a', 'b')).not.to.failOn('b');
        expect((Jo) => Jo.valid('a', 'b')).to.failOn('c');

        expect((Jo) => Jo.valid(['a', 'b'])).not.to.failOn('a');
        expect((Jo) => Jo.valid(['a', 'b'])).not.to.failOn('b');
        expect((Jo) => Jo.valid(['a', 'b'])).to.failOn('c');

        expect((Jo) => Jo.valid('a').valid('b')).not.to.failOn('a');
    });

    it('disallows invalid values', () => {
        expect((Jo) => Jo.invalid('a')).not.to.failOn('c');
        expect((Jo) => Jo.invalid('a')).to.failOn('a');

        expect((Jo) => Jo.invalid('a', 'b')).to.failOn('a');
        expect((Jo) => Jo.invalid('a', 'b')).to.failOn('b');
        expect((Jo) => Jo.invalid('a', 'b')).not.to.failOn('c');

        expect((Jo) => Jo.invalid(['a', 'b'])).to.failOn('a');
        expect((Jo) => Jo.invalid(['a', 'b'])).to.failOn('b');
        expect((Jo) => Jo.invalid(['a', 'b'])).not.to.failOn('c');
    });
});
<commit_msg>allow tests for later<commit_after>describe('any', () => {
    it('works for any values', () => {
        expect((Jo) => Jo.any()).not.to.failOn(undefined);
        expect((Jo) => Jo.any()).not.to.failOn(null);
        expect((Jo) => Jo.any()).not.to.failOn('fubar');
    });

    it('takes optional values', () => {
        expect((Jo) => Jo.optional()).not.to.failOn(undefined);
        expect((Jo) => Jo.optional()).not.to.failOn(null);
        expect((Jo) => Jo.optional()).not.to.failOn('fubar');
    });

    it('requires values correctly', () => {
        expect((Jo) => Jo.required()).to.failOn(undefined, [
            {
                context: { key: 'value' },
                message: '"value" is required',
                path: 'value',
                type: 'required'
            }
        ]);

        expect((Jo) => Jo.required()).not.to.failOn(null);
        expect((Jo) => Jo.required()).not.to.failOn('fubar');
    });

    it('disallows forbidden values', () => {
        expect((Jo) => Jo.forbidden()).not.to.failOn(undefined);
        expect((Jo) => Jo.forbidden()).to.failOn(null);
        expect((Jo) => Jo.forbidden()).to.failOn('fubar');
    });

    it('allows valid values', () => {
        expect((Jo) => Jo.valid('a')).to.failOn('c');
        expect((Jo) => Jo.valid('a')).not.to.failOn('a');

        expect((Jo) => Jo.valid('a', 'b')).not.to.failOn('a');
        expect((Jo) => Jo.valid('a', 'b')).not.to.failOn('b');
        expect((Jo) => Jo.valid('a', 'b')).to.failOn('c');

        expect((Jo) => Jo.valid(['a', 'b'])).not.to.failOn('a');
        expect((Jo) => Jo.valid(['a', 'b'])).not.to.failOn('b');
        expect((Jo) => Jo.valid(['a', 'b'])).to.failOn('c');

        expect((Jo) => Jo.valid('a').valid('b')).to.failOn('a');
    });

    it('disallows invalid values', () => {
        expect((Jo) => Jo.invalid('a')).not.to.failOn('c');
        expect((Jo) => Jo.invalid('a')).to.failOn('a');

        expect((Jo) => Jo.invalid('a', 'b')).to.failOn('a');
        expect((Jo) => Jo.invalid('a', 'b')).to.failOn('b');
        expect((Jo) => Jo.invalid('a', 'b')).not.to.failOn('c');

        expect((Jo) => Jo.invalid(['a', 'b'])).to.failOn('a');
        expect((Jo) => Jo.invalid(['a', 'b'])).to.failOn('b');
        expect((Jo) => Jo.invalid(['a', 'b'])).not.to.failOn('c');
    });

    it('allows allowed values', () => {
        expect((Jo) => Jo.allow('a')).to.failOn('c');
        expect((Jo) => Jo.allow('a')).not.to.failOn('a');

        expect((Jo) => Jo.allow('a', 'b')).not.to.failOn('a');
        expect((Jo) => Jo.allow('a', 'b')).not.to.failOn('b');
        expect((Jo) => Jo.allow('a', 'b')).to.failOn('c');

        expect((Jo) => Jo.allow(['a', 'b'])).not.to.failOn('a');
        expect((Jo) => Jo.allow(['a', 'b'])).not.to.failOn('b');
        expect((Jo) => Jo.allow(['a', 'b'])).to.failOn('c');

        expect((Jo) => Jo.allow('a').allow('b')).to.failOn('a');
    });
});
<|endoftext|>


<commit_before>var ffPhp = {
    Init: function() {
        $('form.ffphp > fieldset > legend > span').each(function() {
            $(this).click(ffPhp.ToggleFieldset);
            if(this.innerHTML === '▲')
                this.parentNode.parentNode.getElementsByTagName('ol')[0].style.display = 'none';
        });
    },
    ToggleFieldset: function() {
        var ol = this.parentNode.parentNode.getElementsByTagName('ol')[0];
        if(ol.style.display == 'none') {
            ol.style.display = 'block';
            this.innerHTML = '▼';
        } else {
            ol.style.display = 'none';
            this.innerHTML = '▲';
        }
        return true;
    }
};
<commit_msg>Added some basic js checking for complete input and textares fields<commit_after>var ffPhp = {
    Init: function() {
        $('form.ffphp').submit(ffPhp.BasicCheck);
        $('form.ffphp > fieldset > legend > span').each(function() {
            $(this).click(ffPhp.ToggleFieldset);
            if(this.innerHTML === '▲')
                this.parentNode.parentNode.getElementsByTagName('ol')[0].style.display = 'none';
        });
    },
    ToggleFieldset: function() {
        var ol = this.parentNode.parentNode.getElementsByTagName('ol')[0];
        if(ol.style.display == 'none') {
            ol.style.display = 'block';
            this.innerHTML = '▼';
        } else {
            ol.style.display = 'none';
            this.innerHTML = '▲';
        }
        return true;
    },
    BasicCheck: function() {
        var ok = true;
        $('label > em', this).each(function() {
            //Check input fields
            var input = $(this.parentNode).siblings('input[type=text],textarea');
            if($.trim(input.val()) === '') {
                ok = false;
                input.addClass('ffphp-error');
            } else {
                input.removeClass('ffphp-error');
            }
        });
        return ok;
    }
};
<|endoftext|>


<commit_before>var supertest = require('supertest');
var request = supertest('localhost:3000');

describe('TODO API', function () {
  it('GET /', function (done) {
    request
      .get('/')
      .expect(200)
      .end(function (err, res) {
        if (err) return done(err);
        done();
      });
  });
})
<commit_msg>#2 add app test code<commit_after>var supertest = require('supertest');
var request = supertest('localhost:3000');

describe('Source API', function () {
  it('GET /', function (done) {
    request
      .get('/')
      .expect(200)
      .end(function (err, res) {
        if (err) return done(err);
        done();
      });
  });

  it('GET /sources', function (done) {

  })
})
<|endoftext|>


<commit_before>var uniqueNum = 0;

var nodes = {};

function addNode(){
	var data = {
		label: "",
		value: "",
		inputs: [],
		outputs: [],
		formula: "",
		color: "grey",
		comment: ""
	};

	var id = "n"+uniqueNum;
	nodes[id] = data;
	uniqueNum += 1;
	return id;
}
function removeNode(id){
	var n = nodes[id];
	for(var i=0; i<n.inputs.length; i++){
		nodes[n.inputs[i]].outputs.splice(nodes[n.inputs[i]].outputs.indexOf(id),1);
		$("#"+n.inputs[i]+id).remove();
	}
	for(var i=0; i<n.outputs.length; i++){
		nodes[n.outputs[i]].inputs.splice(nodes[n.outputs[i]].inputs.indexOf(id),1);
		$("#"+id+n.outputs[i]).remove();
	}
	delete nodes.id;
	$("#"+id).remove();
}

function refreshGraph(){
	evalGraph();
	Object.keys(nodes).forEach(function(key){
		$("#"+key+" .right p").html(nodes[key].value);
	});
}

function setLabel(id, label){
	nodes[id].label = label;
	refreshGraph();
}
function setValue(id, value){
	nodes[id].value = value;
	refreshGraph();
}
function addInput(id, id2){
	nodes[id].inputs.push(id2);
}
function addOutput(id, id2){
	nodes[id].outputs.push(id2);
}
function removeInput(id, id2){
	nodes[id].inputs.splice(nodes[id].inputs.indexOf(id2),1);
	refreshGraph();
}
function removeOutput(id, id2){
	nodes[id].outputs.splice(nodes[id].outputs.indexOf(id2),1);
	refreshGraph();
}
function setFormula(id, formula){
	nodes[id].formula = formula;
	refreshGraph();
}
function setColor(id, color){
	nodes[id].color = color;
}
function setComment(id, comment){
	nodes[id].comment = comment;
}

function evalFormula(id){
	var replaced = nodes[id].formula;

	nodes[id].inputs.forEach(function(cell){
		if(nodes[cell].value === '-') return '-';
		var re = new RegExp(nodes[cell].label, "gi");
		replaced = replaced.replace(re, nodes[cell].value);
	});

	try{
		return math.eval(replaced);
	}
	catch(err){
		return '-';
	}
}

function evalGraph(){
	visited = [];
	notYet = Object.keys(nodes);
	function traverse(cell){
		nodes[cell].inputs.forEach(function(next){
			if (visited.indexOf(next) !== -1){
				return traverse(next);
			}
		});

		setValue(cell, evalFormula(cell));
		visited.push(notYet.splice(notYet.indexOf(cell), 1));
	}

	while(notYet.length > 0){
		traverse(notYet[0]);
	}
}<commit_msg>fixing graph traverse bug<commit_after>var uniqueNum = 0;

var nodes = {};

function addNode(){
	var data = {
		label: "",
		value: "",
		inputs: [],
		outputs: [],
		formula: "",
		color: "grey",
		comment: ""
	};

	var id = "n"+uniqueNum;
	nodes[id] = data;
	uniqueNum += 1;
	return id;
}
function removeNode(id){
	var n = nodes[id];
	for(var i=0; i<n.inputs.length; i++){
		nodes[n.inputs[i]].outputs.splice(nodes[n.inputs[i]].outputs.indexOf(id),1);
		$("#"+n.inputs[i]+id).remove();
	}
	for(var i=0; i<n.outputs.length; i++){
		nodes[n.outputs[i]].inputs.splice(nodes[n.outputs[i]].inputs.indexOf(id),1);
		$("#"+id+n.outputs[i]).remove();
	}
	delete nodes.id;
	$("#"+id).remove();
}

function refreshGraph(){
	evalGraph();
	Object.keys(nodes).forEach(function(key){
		$("#"+key+" .right p").html(nodes[key].value);
	});
}

function setLabel(id, label){
	nodes[id].label = label;
	refreshGraph();
}
function setValue(id, value){
	nodes[id].value = value;
	refreshGraph();
}
function addInput(id, id2){
	nodes[id].inputs.push(id2);
}
function addOutput(id, id2){
	nodes[id].outputs.push(id2);
}
function removeInput(id, id2){
	nodes[id].inputs.splice(nodes[id].inputs.indexOf(id2),1);
	refreshGraph();
}
function removeOutput(id, id2){
	nodes[id].outputs.splice(nodes[id].outputs.indexOf(id2),1);
	refreshGraph();
}
function setFormula(id, formula){
	nodes[id].formula = formula;
	refreshGraph();
}
function setColor(id, color){
	nodes[id].color = color;
}
function setComment(id, comment){
	nodes[id].comment = comment;
}

function evalFormula(id){
	var replaced = nodes[id].formula;

	nodes[id].inputs.forEach(function(cell){
		if(nodes[cell].value === '-') return '-';
		var re = new RegExp(nodes[cell].label, "gi");
		replaced = replaced.replace(re, nodes[cell].value);
	});

	try{
		return math.eval(replaced);
	}
	catch(err){
		return '-';
	}
}

function evalGraph(){
	visited = [];
	notYet = Object.keys(nodes);
	function traverse(cell){
		nodes[cell].inputs.forEach(function(next){
			if (visited.indexOf(next) == -1){
				traverse(next);
			}
		});

		setValue(cell, evalFormula(cell));
		visited.push(notYet.splice(notYet.indexOf(cell), 1));
	}

	while(notYet.length > 0){
		traverse(notYet[0]);
	}
}<|endoftext|>


<commit_before>var test = require('tape');
var level = require('../');
var path = require('path');
var bytewise = require('bytewise');
var os = require('os');
var tmpdir = os.tmpdir ? os.tmpdir() : os.tmpDir();
var datadir = path.join(tmpdir, 'level-party-' + Math.random());

var lopts = { keyEncoding: bytewise, valueEncoding: 'json' };

test('two handles', function (t) {
    t.plan(1);
    var adb = level(datadir, lopts);
    var bdb = level(datadir, lopts);
    var value = Math.floor(Math.random() * 100000);

    adb.put([ 'a' ], value, function (err) {
        if (err) t.fail(err);
        var times = 0;

        bdb.get([ 'a' ], function (err, x) {
            t.equal(x, value);
        });
    });

    t.on('end', function () {
        adb.close();
        bdb.close();
    });
});
<commit_msg>read stream tho<commit_after>var test = require('tape');
var level = require('../');
var path = require('path');
var bytewise = require('bytewise');
var os = require('os');
var tmpdir = os.tmpdir ? os.tmpdir() : os.tmpDir();
var datadir = path.join(tmpdir, 'level-party-' + Math.random());

var lopts = { keyEncoding: bytewise, valueEncoding: 'json' };

test('bytewise key encoding', function (t) {
    t.plan(5);
    var adb = level(datadir, lopts);
    var bdb = level(datadir, lopts);
    var value = Math.floor(Math.random() * 100000);

    adb.put([ 'a' ], value, function (err) {
        t.ifError(err);
        var times = 0;

        bdb.get([ 'a' ], function (err, x) {
            t.ifError(err);
            t.equal(x, value);
        });

        bdb.createReadStream().on('data', function (row) {
            t.deepEqual(row.key, [ 'a' ]);
            t.deepEqual(row.value, value);
        });
    });

    t.on('end', function () {
        adb.close();
        bdb.close();
    });
});
<|endoftext|>