<commit_before>const request = require('request');
const twilio = require('./twilioNotifications');
const EventEmitter = require('events');
class StockEventEmitter extends EventEmitter {}
const stockAlert = new StockEventEmitter();
const config = require('./config');

// console.log('process.env.TWILIO_SENT_SMS  ', process.env.TWILIO_SENT_SMS);
// console.log('typeof  ', typeof process.env.TWILIO_SENT_SMS);
const sendSMS = (('' + process.env.TWILIO_SENT_SMS).toLowerCase() == 'true');
console.log('sendSMS : ', sendSMS);

function getStockUrl(symbol) {
  return 'http://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=' + symbol + '&outputsize=compact&interval=1min&apikey=1537';
}

const purchaseDB = config.purchasedDB || 'https://stocks-dd1e5.firebaseio.com/purchase.json';
const favoriteDB = config.favoriteDB || 'https://stocks-dd1e5.firebaseio.com/favorite.json';

const stockEnum = {
  '1. open': 'open',

  '2. high': 'high',

  '3. low': 'low',

  '4. close': 'close',

  '5. volume': 'volume'
};

function getStockData(db) {
  return new Promise((resolve, reject) => {
    request(db, function (error, response, body) {
      // console.log('error:', error); // Print the error if one occurred
      //  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
      // console.log('body:', body); // Print the HTML for the Google homepage.

      if (!error && response.statusCode == 200) {
        data = JSON.parse(body);

        if (Object.keys(data).length) {
          resolve(data);
        } else {
          reject('No data in the Database.');
        }
      }

    });
  });
}

function getPrice(stock) {
  const stockUrl = getStockUrl(stock.symbol);
  // console.log("Stock URL: ", stockUrl);
  return new Promise((resolve, reject) => {
    request(stockUrl,
      (error, response, body) => {
        // console.log(res.statusCode) // 200
        if (error) {
          reject(error);
        }

        if (!error && response.statusCode == 200) {
          let data = JSON.parse(body);
          // parse data, just return the latest stock price
          // console.log('latest data of ' + symbol + ' : ', Object.keys(data['Time Series (Daily)'])[0]);
          if (data && Object.keys(data['Time Series (Daily)']) && data['Time Series (Daily)'][Object.keys(data['Time Series (Daily)'])[0]]) {
            data = data['Time Series (Daily)'][Object.keys(data['Time Series (Daily)'])[0]];

            // change the data key with stockEnum
            const newData = {};
            // tslint:disable-next-line:forin
            for (const key in data) {
              newData[stockEnum[key]] = parseFloat(parseFloat(data[key]).toFixed(2));
            }
            //  console.log(newData);
            resolve(newData);
          }
        }
      });
  });
}

// getPrice({symbol: 'KO'})
// .then( data => console.log(data))

function Checker() {

  const self = this;
  this.stockSent = [];
  const purchasedStockList = [];
  const favoriteStockList = [];
  this.count = 0;

  this.run = function () {

    // get data from database
    getStockData(purchaseDB)
      .then((data) => {
        this.purchasedStockList = data;
        // console.log('purchasedStockList : ', this.purchasedStockList);

        for (const stock of data) {
          if (stock.alert) {
            stockAlert.emit('addStock', stock);
          }
        }
      })
      .catch(err => {
        console.log(err);
      });

    getStockData(favoriteDB)
      .then((data) => {
        this.favoriteStockList = data;
        //  console.log('favoriteStockList : ',  this.favoriteStockList);

        for (const stock of data) {
          if (stock.alert) {
            stockAlert.emit('addStock', stock);
          }
        }
      })
      .catch(err => console.log(err));

  }; //run

  this.reset = function () {
    console.log('Before: length of stockSent = ' + self.stockSent.length);
    this.stockSent = [];
    this.purchasedStockList = [];
    this.favoriteStockList = [];

    console.log('reseting... ');
    console.log('After: length of stockSent = ' + self.stockSent.length);

  };

  // self execution function as listener
  function listener() {
    //  console.log("self execution function is running...")
    stockAlert.on('addStock', (stock) => {
      ++self.count;
      console.log(new Date().toLocaleString() + '  listener called ' + self.count);
      // console.log('stockAlert on addStock: ', stock.symbol);
      // get price based on alertList

      getPrice(stock)
        .then(data => {
          // console.log('getPrice : ' + stock.symbol + '  : ' + JSON.stringify(data));

          // build latest stock price into stock object
          for (const key of Object.keys(data)) {
            stock[key] = data[key];
          }

          // console.log('latest stock detail: ', JSON.stringify(stock));

          // minPrice  drop alert
          if (stock.close <= stock.minPrice) {
            console.log(new Date().toLocaleString() + ' price DROP alert: ' + stock.symbol + ' has dropped at ' + stock.close);

            if (self.stockSent.indexOf(stock.symbol) === -1) {
              // did not send sms today
              self.stockSent.push(stock.symbol);
              console.log(new Date().toLocaleString() + ' Sending sms now for ' + stock.symbol);

              if (sendSMS) {
                twilio.notifyOnPriceDrop(stock);
              }

            } else {
              console.log(new Date().toLocaleString() + ' Already sent sms today for ' + stock.symbol);
            }

          }

          // minPrice  rise alert
          if (stock.close >= stock.maxPrice) {
            console.log(new Date().toLocaleString() + ' price RISE alert: ' + stock.symbol + ' has risen at ' + stock.close);

            if (self.stockSent.indexOf(stock.symbol) === -1) {
              // did not send sms today
              self.stockSent.push(stock.symbol);
              console.log(new Date().toLocaleString() + ' Sending sms now for ' + stock.symbol);

              if (sendSMS) {
                twilio.notifyOnPriceRise(stock);
              }

            } else {
              console.log(new Date().toLocaleString() + 'Already sent sms today for ' + stock.symbol);
            }

          }

        });

    });
    // anonymous end
  }
  listener();

} // Checker end

var checkerInstance = new Checker();

module.exports = {

  // just pass the instance
  checker: checkerInstance

};
<commit_msg>fix Object.keys problem again<commit_after>const request = require('request');
const twilio = require('./twilioNotifications');
const EventEmitter = require('events');
class StockEventEmitter extends EventEmitter {}
const stockAlert = new StockEventEmitter();
const config = require('./config');

// console.log('process.env.TWILIO_SENT_SMS  ', process.env.TWILIO_SENT_SMS);
// console.log('typeof  ', typeof process.env.TWILIO_SENT_SMS);
const sendSMS = (('' + process.env.TWILIO_SENT_SMS).toLowerCase() == 'true');
console.log('sendSMS : ', sendSMS);

function getStockUrl(symbol) {
  return 'http://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=' + symbol + '&outputsize=compact&interval=1min&apikey=1537';
}

const purchaseDB = config.purchasedDB || 'https://stocks-dd1e5.firebaseio.com/purchase.json';
const favoriteDB = config.favoriteDB || 'https://stocks-dd1e5.firebaseio.com/favorite.json';

const stockEnum = {
  '1. open': 'open',

  '2. high': 'high',

  '3. low': 'low',

  '4. close': 'close',

  '5. volume': 'volume'
};

function getStockData(db) {
  return new Promise((resolve, reject) => {
    request(db, function (error, response, body) {
      // console.log('error:', error); // Print the error if one occurred
      //  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
      // console.log('body:', body); // Print the HTML for the Google homepage.

      if (!error && response.statusCode == 200) {
        data = JSON.parse(body);

        if (Object.keys(data).length) {
          resolve(data);
        } else {
          reject('No data in the Database.');
        }
      }

    });
  });
}

function getPrice(stock) {
  const stockUrl = getStockUrl(stock.symbol);
  // console.log("Stock URL: ", stockUrl);
  return new Promise((resolve, reject) => {
    request(stockUrl,
      (error, response, body) => {
        // console.log(res.statusCode) // 200
        if (error) {
          reject(error);
        }

        if (!error && response.statusCode == 200) {
          let data = JSON.parse(body);
          // parse data, just return the latest stock price
          // console.log('latest data of ' + symbol + ' : ', Object.keys(data['Time Series (Daily)'])[0]);
          if (data && data['Time Series (Daily)'] && data['Time Series (Daily)'][Object.keys(data['Time Series (Daily)'])[0]]) {
            data = data['Time Series (Daily)'][Object.keys(data['Time Series (Daily)'])[0]];

            // change the data key with stockEnum
            const newData = {};
            // tslint:disable-next-line:forin
            for (const key in data) {
              newData[stockEnum[key]] = parseFloat(parseFloat(data[key]).toFixed(2));
            }
            //  console.log(newData);
            resolve(newData);
          }
        }
      });
  });
}

// getPrice({symbol: 'KO'})
// .then( data => console.log(data))

function Checker() {

  const self = this;
  this.stockSent = [];
  const purchasedStockList = [];
  const favoriteStockList = [];
  this.count = 0;

  this.run = function () {

    // get data from database
    getStockData(purchaseDB)
      .then((data) => {
        this.purchasedStockList = data;
        // console.log('purchasedStockList : ', this.purchasedStockList);

        for (const stock of data) {
          if (stock.alert) {
            stockAlert.emit('addStock', stock);
          }
        }
      })
      .catch(err => {
        console.log(err);
      });

    getStockData(favoriteDB)
      .then((data) => {
        this.favoriteStockList = data;
        //  console.log('favoriteStockList : ',  this.favoriteStockList);

        for (const stock of data) {
          if (stock.alert) {
            stockAlert.emit('addStock', stock);
          }
        }
      })
      .catch(err => console.log(err));

  }; //run

  this.reset = function () {
    console.log('Before: length of stockSent = ' + self.stockSent.length);
    this.stockSent = [];
    this.purchasedStockList = [];
    this.favoriteStockList = [];

    console.log('reseting... ');
    console.log('After: length of stockSent = ' + self.stockSent.length);

  };

  // self execution function as listener
  function listener() {
    //  console.log("self execution function is running...")
    stockAlert.on('addStock', (stock) => {
      ++self.count;
      console.log(new Date().toLocaleString() + '  listener called ' + self.count);
      // console.log('stockAlert on addStock: ', stock.symbol);
      // get price based on alertList

      getPrice(stock)
        .then(data => {
          // console.log('getPrice : ' + stock.symbol + '  : ' + JSON.stringify(data));

          // build latest stock price into stock object
          for (const key of Object.keys(data)) {
            stock[key] = data[key];
          }

          // console.log('latest stock detail: ', JSON.stringify(stock));

          // minPrice  drop alert
          if (stock.close <= stock.minPrice) {
            console.log(new Date().toLocaleString() + ' price DROP alert: ' + stock.symbol + ' has dropped at ' + stock.close);

            if (self.stockSent.indexOf(stock.symbol) === -1) {
              // did not send sms today
              self.stockSent.push(stock.symbol);
              console.log(new Date().toLocaleString() + ' Sending sms now for ' + stock.symbol);

              if (sendSMS) {
                twilio.notifyOnPriceDrop(stock);
              }

            } else {
              console.log(new Date().toLocaleString() + ' Already sent sms today for ' + stock.symbol);
            }

          }

          // minPrice  rise alert
          if (stock.close >= stock.maxPrice) {
            console.log(new Date().toLocaleString() + ' price RISE alert: ' + stock.symbol + ' has risen at ' + stock.close);

            if (self.stockSent.indexOf(stock.symbol) === -1) {
              // did not send sms today
              self.stockSent.push(stock.symbol);
              console.log(new Date().toLocaleString() + ' Sending sms now for ' + stock.symbol);

              if (sendSMS) {
                twilio.notifyOnPriceRise(stock);
              }

            } else {
              console.log(new Date().toLocaleString() + 'Already sent sms today for ' + stock.symbol);
            }

          }

        });

    });
    // anonymous end
  }
  listener();

} // Checker end

var checkerInstance = new Checker();

module.exports = {

  // just pass the instance
  checker: checkerInstance

};
<|endoftext|>


<commit_before><commit_msg>Rename rowType => RowType<commit_after><|endoftext|>


<commit_before>//React Component import
import React, {Component} from 'react';
//Bootstrap import
import {Glyphicon, Modal, Button, Form, FormGroup, ControlLabel, FormControl,} from 'react-bootstrap';
//Project component import
import {getMonth} from '../DateFunctions'
import CalendarDateBox from './CalendarDateBox';
//CSS import
import '../../styles/modal.css';
import {SUITED_FOR_TYPES} from './SuitedForPicker';
import StarRatingComponent from "react-star-rating-component";
import {
    signupActivity,
    signoffActivity,
    checkIfSignedUp,
    postNewRating,
    postNewComment,
    getComments
} from "../APIFunctions";

class ActivityModal extends Component {

    constructor(props) {
        super(props);
        this.state = {
            show: false,
            hasChecked: false,
            attending: false,
            loggedIn: false,
            fetchedComments: false,
            noComments: true,
            comments: []
        }
    }

    componentWillReceiveProps(props) {
        this.setState({
            show: props.show
        });
    }

    showMap = () => {
        window.open('https://www.google.no/maps/place/' + this.props.activity.location, '_blank');
    };

    editActivity = () => {
        window.location = "/activity/" + this.props.id;
    };

    closeActivityModal = () => {
        this.setState({
            show: false,
            hasChecked: false,
            fetchedComments: false
        });
    };

    onSignup = () => {
        const request = {
            id: this.props.id
        };
        signupActivity(request).then((response) => {
            if (response.status == 204) {
                this.setState({
                    attending: true
                });
            }
        })
    };

    onSignOf = () => {
        const request = {
            id: this.props.id
        };
        signoffActivity(request).then((response) => {
            if (response.status == 210) {
                this.setState({
                    attending: false
                });
            }
        })
    };

    checkIfSignUp = () => {
        const request = {
            id: this.props.id
        };
        checkIfSignedUp(request).then((response) => {
            if (response.status == 204) {
                this.setState({
                    attending: true,
                    hasChecked: true,
                    loggedIn: true
                });
            } else if (response.status == 205) {
                this.setState({
                    loggedIn: true,
                    hasChecked: true
                })
            } else if (response == 206) {
                this.setState({
                    loggedIn: false
                })
            }
        })
    };

    onRateChange = (nextValue, prevValue, name) => {
        const obj = {
            id: this.props.id,
            rating: nextValue
        };
        postNewRating(obj)
    };

    fetchComments = () => {
        getComments(this.props.id).then((result) => {
            if (result.message == "ingen kommentar funnet") {
                this.setState({
                    noComment: true,
                    fetchedComments: true
                })
            } else {
                this.setState({
                    comments: result.reverse(),
                    fetchedComments: true,
                    noComments: false
                });
            }
        });
    };

    onPostComment = () => {
        const obj = {
            id: this.props.id,
            comment2: $("#commentInput").val()
        };
        $("#commentInput").val("");
        postNewComment(obj);
        this.fetchComments();
    };

    render() {
        const {date, activityName, activityType, suitedForType, provider, adaptions, age, time_start, time_end, location, description, videos, images, rating, number_of_ratings} = this.props.activity;

        const starRating = rating / number_of_ratings;
        let suitedForContainer = [];
        if (suitedForType >= 0) {
            suitedForContainer = SUITED_FOR_TYPES.filter(type => parseInt(type.value) === suitedForType)[0];
        }

        //let videoContainer = null;
        //if (videos.length > 0) {
        //    const videos = this.state.videos.map((video, i) => {
        //        const path = "/media/video/" + video;
        //        return (
        //            <video className="modal-video" controls="controls" key={i}>
        //                <source src={path}/>
        //            </video>
        //        )
        //    });
        //    videoContainer =
        //

        //
Video fra arrangementet

        //            {videos}
        //
;
        //}

        let imageContainer = null;

        let images = this.props.images.map(image => {
            return
        });

        if (this.props.images.length > 0) {
            imageContainer =

Bilder fra arrangementet

                        {images}

;
        }

        if (this.state.show && !this.state.hasChecked) {
            this.checkIfSignUp()

        }

        let attendingContainer = null;
        let ratingContainer = null;
        let postCommentContainer = null;
        let commentsContainer =

Ingen kommentarer

;
        let allComments = this.state.comments;

        if (!this.state.loggedIn) {
            attendingContainer =

Påmelding til {activityName}

Du må være logget inn for å kunne melde deg på dette arrangementet

;
        } else if (this.state.attending == false) {
            attendingContainer =

Påmelding til {activityName}

                        <Button className="btn btn-success" onClick={this.onSignup}>Meld på!</Button>

;

        } else {
            attendingContainer =

Du er påmeldt {activityName}

                        <Button onClick={this.onSignOf} className="btn btn-danger">Meld av</Button>

;
        }

        if (this.state.loggedIn) {
            ratingContainer =
                <StarRatingComponent id="activityRating" name="activityRating" emptyStarColor="#BBB" value={starRating}
                                     onStarClick={this.onRateChange.bind(this)}/>;

            postCommentContainer =

                    <form className="comment-form" method="POST" action="/postComment/">

                            <textarea placeholder="Skriv inn din kommentar her" id="commentInput"
                                      className="form-control custom-control"></textarea>
                            Send

                    </form>

;
        }

        if (this.state.show && !this.state.fetchedComments) {
            this.fetchComments();
        }

        if (!this.state.noComments) {
            commentsContainer =

                    {allComments.map((com, i) =>

{com.fields.userProfile_name} - {com.fields.date}

{com.fields.comment}

                    )}

;
        }

        return (
            <Modal
                show={this.state.show}
                onHide={this.closeActivityModal}
                bsSize="large"
                aria-labelledby="contained-modal-title-lg">
                <Modal.Header closeButton>
                    <Modal.Title id="contained-modal-title-lg">
                        <CalendarDateBox date={new Date(date)}/>

{activityName}

Arrangeres av: {provider} {ratingContainer}

                    </Modal.Title>
                </Modal.Header>
                <Modal.Body>

                        Dette arrangementet er tilpasset for: {suitedForContainer.label}

<Glyphicon glyph="glyphicon glyphicon-user"/>
                                Alder: {age}

<Glyphicon glyph="glyphicon glyphicon-time"/>
                                Tid: {time_start} - {time_end}

                                <Glyphicon glyph="glyphicon glyphicon-map-marker"/>
                                Sted: {location}

                                Vis på kart

                        {attendingContainer}

Om arrangementet

{description}

                    {/* videoContainer */}
                    {imageContainer}

Kommentarer

                    {postCommentContainer}
                    {commentsContainer}

                </Modal.Body>
                <Modal.Footer>
                    <Button onClick={this.editActivity}>Endre aktivitet</Button>
                    <Button onClick={this.closeActivityModal}>Lukk</Button>
                </Modal.Footer>
            </Modal>
        )
    }
}

export default ActivityModal;
<commit_msg>removed duplicates of images<commit_after>//React Component import
import React, {Component} from 'react';
//Bootstrap import
import {Glyphicon, Modal, Button, Form, FormGroup, ControlLabel, FormControl,} from 'react-bootstrap';
//Project component import
import {getMonth} from '../DateFunctions'
import CalendarDateBox from './CalendarDateBox';
//CSS import
import '../../styles/modal.css';
import {SUITED_FOR_TYPES} from './SuitedForPicker';
import StarRatingComponent from "react-star-rating-component";
import {
    signupActivity,
    signoffActivity,
    checkIfSignedUp,
    postNewRating,
    postNewComment,
    getComments
} from "../APIFunctions";

class ActivityModal extends Component {

    constructor(props) {
        super(props);
        this.state = {
            show: false,
            hasChecked: false,
            attending: false,
            loggedIn: false,
            fetchedComments: false,
            noComments: true,
            comments: []
        }
    }

    componentWillReceiveProps(props) {
        this.setState({
            show: props.show
        });
    }

    showMap = () => {
        window.open('https://www.google.no/maps/place/' + this.props.activity.location, '_blank');
    };

    editActivity = () => {
        window.location = "/activity/" + this.props.id;
    };

    closeActivityModal = () => {
        this.setState({
            show: false,
            hasChecked: false,
            fetchedComments: false
        });
    };

    onSignup = () => {
        const request = {
            id: this.props.id
        };
        signupActivity(request).then((response) => {
            if (response.status == 204) {
                this.setState({
                    attending: true
                });
            }
        })
    };

    onSignOf = () => {
        const request = {
            id: this.props.id
        };
        signoffActivity(request).then((response) => {
            if (response.status == 210) {
                this.setState({
                    attending: false
                });
            }
        })
    };

    checkIfSignUp = () => {
        const request = {
            id: this.props.id
        };
        checkIfSignedUp(request).then((response) => {
            if (response.status == 204) {
                this.setState({
                    attending: true,
                    hasChecked: true,
                    loggedIn: true
                });
            } else if (response.status == 205) {
                this.setState({
                    loggedIn: true,
                    hasChecked: true
                })
            } else if (response == 206) {
                this.setState({
                    loggedIn: false
                })
            }
        })
    };

    onRateChange = (nextValue, prevValue, name) => {
        const obj = {
            id: this.props.id,
            rating: nextValue
        };
        postNewRating(obj)
    };

    fetchComments = () => {
        getComments(this.props.id).then((result) => {
            if (result.message == "ingen kommentar funnet") {
                this.setState({
                    noComment: true,
                    fetchedComments: true
                })
            } else {
                this.setState({
                    comments: result.reverse(),
                    fetchedComments: true,
                    noComments: false
                });
            }
        });
    };

    onPostComment = () => {
        const obj = {
            id: this.props.id,
            comment2: $("#commentInput").val()
        };
        $("#commentInput").val("");
        postNewComment(obj);
        this.fetchComments();
    };

    render() {
        const {date, activityName, activityType, suitedForType, provider, adaptions, age, time_start, time_end, location, description, videos, rating, number_of_ratings} = this.props.activity;

        const starRating = rating / number_of_ratings;
        let suitedForContainer = [];
        if (suitedForType >= 0) {
            suitedForContainer = SUITED_FOR_TYPES.filter(type => parseInt(type.value) === suitedForType)[0];
        }

        //let videoContainer = null;
        //if (videos.length > 0) {
        //    const videos = this.state.videos.map((video, i) => {
        //        const path = "/media/video/" + video;
        //        return (
        //            <video className="modal-video" controls="controls" key={i}>
        //                <source src={path}/>
        //            </video>
        //        )
        //    });
        //    videoContainer =
        //

        //
Video fra arrangementet

        //            {videos}
        //
;
        //}

        let imageContainer = null;

        let images = this.props.images.map(image => {
            return
        });

        if (this.props.images.length > 0) {
            imageContainer =

Bilder fra arrangementet

                        {images}

;
        }

        if (this.state.show && !this.state.hasChecked) {
            this.checkIfSignUp()

        }

        let attendingContainer = null;
        let ratingContainer = null;
        let postCommentContainer = null;
        let commentsContainer =

Ingen kommentarer

;
        let allComments = this.state.comments;

        if (!this.state.loggedIn) {
            attendingContainer =

Påmelding til {activityName}

Du må være logget inn for å kunne melde deg på dette arrangementet

;
        } else if (this.state.attending == false) {
            attendingContainer =

Påmelding til {activityName}

                        <Button className="btn btn-success" onClick={this.onSignup}>Meld på!</Button>

;

        } else {
            attendingContainer =

Du er påmeldt {activityName}

                        <Button onClick={this.onSignOf} className="btn btn-danger">Meld av</Button>

;
        }

        if (this.state.loggedIn) {
            ratingContainer =
                <StarRatingComponent id="activityRating" name="activityRating" emptyStarColor="#BBB" value={starRating}
                                     onStarClick={this.onRateChange.bind(this)}/>;

            postCommentContainer =

                    <form className="comment-form" method="POST" action="/postComment/">

                            <textarea placeholder="Skriv inn din kommentar her" id="commentInput"
                                      className="form-control custom-control"></textarea>
                            Send

                    </form>

;
        }

        if (this.state.show && !this.state.fetchedComments) {
            this.fetchComments();
        }

        if (!this.state.noComments) {
            commentsContainer =

                    {allComments.map((com, i) =>

{com.fields.userProfile_name} - {com.fields.date}

{com.fields.comment}

                    )}

;
        }

        return (
            <Modal
                show={this.state.show}
                onHide={this.closeActivityModal}
                bsSize="large"
                aria-labelledby="contained-modal-title-lg">
                <Modal.Header closeButton>
                    <Modal.Title id="contained-modal-title-lg">
                        <CalendarDateBox date={new Date(date)}/>

{activityName}

Arrangeres av: {provider} {ratingContainer}

                    </Modal.Title>
                </Modal.Header>
                <Modal.Body>

                        Dette arrangementet er tilpasset for: {suitedForContainer.label}

<Glyphicon glyph="glyphicon glyphicon-user"/>
                                Alder: {age}

<Glyphicon glyph="glyphicon glyphicon-time"/>
                                Tid: {time_start} - {time_end}

                                <Glyphicon glyph="glyphicon glyphicon-map-marker"/>
                                Sted: {location}

                                Vis på kart

                        {attendingContainer}

Om arrangementet

{description}

                    {/* videoContainer */}
                    {imageContainer}

Kommentarer

                    {postCommentContainer}
                    {commentsContainer}

                </Modal.Body>
                <Modal.Footer>
                    <Button onClick={this.editActivity}>Endre aktivitet</Button>
                    <Button onClick={this.closeActivityModal}>Lukk</Button>
                </Modal.Footer>
            </Modal>
        )
    }
}

export default ActivityModal;
<|endoftext|>


<commit_before>function Automobile( year, make, model, type ){
    this.year = year; //integer (ex. 2001, 1995)
    this.make = make; //string (ex. Honda, Ford)
    this.model = model; //string (ex. Accord, Focus)
    this.type = type; //string (ex. Pickup, SUV)

    this.logMe = function(bool) {
       var str = this.year + ' ' + this.make + ' ' + this.model;
       if (bool) {
          str += ' ' + this.type;
       }
       console.log(str);
    }.bind(this);
}

function main(arr, bool) {
   console.log('*****');
   for (var i = 0; i < arr.length; i++) {
      arr[i].logMe(bool);
   }
   console.log('*****');
}

var automobiles = [
    new Automobile(1995, "Honda", "Accord", "Sedan"),
    new Automobile(1990, "Ford", "F-150", "Pickup"),
    new Automobile(2000, "GMC", "Tahoe", "SUV"),
    new Automobile(2010, "Toyota", "Tacoma", "Pickup"),
    new Automobile(2005, "Lotus", "Elise", "Roadster"),
    new Automobile(2008, "Subaru", "Outback", "Wagon")
    ];

var yearSorted = sortArr(yearComparator, automobiles);
console.log("The cars sorted by year are:");
main(yearSorted, false);

var makeSorted = sortArr(makeComparator, automobiles);
console.log("The cars sorted by make are:");
main(makeSorted, false);

var typeSorted = sortArr(typeComparator, automobiles);
console.log("The cars sorted by type are:");
main(typeSorted, true);

/*This function sorts arrays using an arbitrary comparator. You pass it a comparator and an array of objects appropriate for that comparator and it will return a new array which is sorted with the largest object in index 0 and the smallest in the last index*/
function sortArr( comparator, array ){
    return array.sort(comparator);
}

/*A comparator takes two arguments and uses some algorithm to compare them. If the first argument is larger or greater than the 2nd it returns true, otherwise it returns false. Here is an example that works on integers*/
function exComparator( int1, int2){
    if (int1 > int2){
        return true;
    } else {
        return false;
    }
}

/*For all comparators if cars are 'tied' according to the comparison rules then the order of those 'tied' cars is not specified and either can come first*/

/*This compares two automobiles based on their year. Newer cars are "greater" than older cars.*/
function yearComparator(auto1, auto2){
    if (auto1.year > auto2.year) {
       return -1;
    } else if (auto1.year < auto2.year) {
       return 1;
    } else {
       return 0;
    }
}

/*This compares two automobiles based on their make. It should be case insensitive and makes which are alphabetically earlier in the alphabet are "greater" than ones that come later.*/
function makeComparator( auto1, auto2){
    if (auto1.make.toUpperCase() > auto2.make.toUpperCase()) {
       return 1;
    } else if (auto1.make.toUpperCase() < auto2.make.toUpperCase()) {
       return -1;
    } else {
       return 0;
    }
}

/*This compares two automobiles based on their type. The ordering from "greatest" to "least" is as follows: roadster, pickup, suv, wagon, (types not otherwise listed). It should be case insensitive. If two cars are of equal type then the newest one by model year should be considered "greater".*/
function typeComparator( auto1, auto2){
   var typeMap = {
      "Roadster": 1,
      "Pickup": 2,
      "SUV": 3,
      "Wagon": 4,
      "Sedan": 5
   };
   if (typeMap[auto1.type] > typeMap[auto2.type]) {
      return 1;
   } else if (typeMap[auto1.type] < typeMap[auto2.type]) {
      return -1;
   } else if (typeMap[auto1.type] === typeMap[auto2.type]) {
      return yearComparator(auto1, auto2);
   }
}

/*Your program should output the following to the console.log, including the opening and closing 5 stars. All values in parenthesis should be replaced with appropriate values. Each line is a seperate call to console.log.
 *
 * Each line representing a car should be produced via a logMe function. This function should be added to the Automobile class and accept a single boolean argument. If the argument is 'true' then it prints "year make model type" with the year, make, model and type being the values appropriate for the automobile. If the argument is 'false' then the type is ommited and just the "year make model" is logged.
 *
 * *****
 * The cars sorted by year are:
 * (year make model of the 'greatest' car)
 * (...)
 * (year make model of the 'least' car)
 *
 * The cars sorted by make are:
 * (year make model of the 'greatest' car)
 * (...)
 * (year make model of the 'least' car)
 *
 * The cars sorted by type are:
 * (year make model type of the 'greatest' car)
 * (...)
 * (year make model type of the 'least' car)
 * *****
 *
 * As an example of the content in the parenthesis:
 * 1990 Ford F-150 */
<commit_msg>Updated the automobile.js script to use my own implementation of bubble sort<commit_after>function Automobile( year, make, model, type ){
    this.year = year; //integer (ex. 2001, 1995)
    this.make = make; //string (ex. Honda, Ford)
    this.model = model; //string (ex. Accord, Focus)
    this.type = type; //string (ex. Pickup, SUV)

    this.logMe = function(bool) {
       var str = this.year + ' ' + this.make + ' ' + this.model;
       if (bool) {
          str += ' ' + this.type;
       }
       console.log(str);
    }.bind(this);
}

function main(arr, bool) {
   console.log('*****');
   for (var i = 0; i < arr.length; i++) {
      arr[i].logMe(bool);
   }
   console.log('*****');
}

var automobiles = [
    new Automobile(1995, "Honda", "Accord", "Sedan"),
    new Automobile(1990, "Ford", "F-150", "Pickup"),
    new Automobile(2000, "GMC", "Tahoe", "SUV"),
    new Automobile(2010, "Toyota", "Tacoma", "Pickup"),
    new Automobile(2005, "Lotus", "Elise", "Roadster"),
    new Automobile(2008, "Subaru", "Outback", "Wagon")
    ];

var yearSorted = sortArr(yearComparator, automobiles);
console.log("The cars sorted by year are:");
main(yearSorted, false);

var makeSorted = sortArr(makeComparator, automobiles);
console.log("The cars sorted by make are:");
main(makeSorted, false);

var typeSorted = sortArr(typeComparator, automobiles);
console.log("The cars sorted by type are:");
main(typeSorted, true);

/*This function sorts arrays using an arbitrary comparator. You pass it a comparator and an array of objects appropriate for that comparator and it will return a new array which is sorted with the largest object in index 0 and the smallest in the last index*/
function sortArr( comparator, array ){
    var copy = array;
    var swapped;
    do {
      swapped = false;
      for (var i = 0; i < array.length - 1; i++) {
         if (comparator(copy[i], copy[i + 1])) {
            var temp = copy[i];
            copy[i] = copy[i + 1];
            copy[i + 1] = temp;
            swapped = true;
         }
      }
    } while (swapped);

    return copy;
}

/*A comparator takes two arguments and uses some algorithm to compare them. If the first argument is larger or greater than the 2nd it returns true, otherwise it returns false. Here is an example that works on integers*/
function exComparator(int1, int2){
    if (int1 < int2){
        return true;
    } else {
        return false;
    }
}

/*For all comparators if cars are 'tied' according to the comparison rules then the order of those 'tied' cars is not specified and either can come first*/

/*This compares two automobiles based on their year. Newer cars are "greater" than older cars.*/
function yearComparator(auto1, auto2){
    if (auto1.year < auto2.year) {
       return true;
    } else if (auto1.year < auto2.year) {
       return false;
    }
}

/*This compares two automobiles based on their make. It should be case insensitive and makes which are alphabetically earlier in the alphabet are "greater" than ones that come later.*/
function makeComparator( auto1, auto2){
    if (auto1.make.toUpperCase() > auto2.make.toUpperCase()) {
       return true;
    } else if (auto1.make.toUpperCase() < auto2.make.toUpperCase()) {
       return false;
    }
}

/*This compares two automobiles based on their type. The ordering from "greatest" to "least" is as follows: roadster, pickup, suv, wagon, (types not otherwise listed). It should be case insensitive. If two cars are of equal type then the newest one by model year should be considered "greater".*/
function typeComparator(auto1, auto2){
   var typeMap = {
      "Roadster": 1,
      "Pickup": 2,
      "SUV": 3,
      "Wagon": 4,
      "Sedan": 5
   };

   var auto1TypeVal = typeMap[auto1.type];
   var auto2TypeVal = typeMap[auto2.type];

   if (auto1TypeVal === undefined) {
      auto1TypeVal = 6;
   }

   if (auto2TypeVal === undefined) {
      auto2TypeVal = 6;
   }

   if (auto1TypeVal > auto2TypeVal) {
      return true;
   } else if (auto1TypeVal < auto2TypeVal) {
      return false;
   } else if (auto1TypeVal === auto2TypeVal) {
      return yearComparator(auto1, auto2);
   }
}

/*Your program should output the following to the console.log, including the opening and closing 5 stars. All values in parenthesis should be replaced with appropriate values. Each line is a seperate call to console.log.
 *
 * Each line representing a car should be produced via a logMe function. This function should be added to the Automobile class and accept a single boolean argument. If the argument is 'true' then it prints "year make model type" with the year, make, model and type being the values appropriate for the automobile. If the argument is 'false' then the type is ommited and just the "year make model" is logged.
 *
 * *****
 * The cars sorted by year are:
 * (year make model of the 'greatest' car)
 * (...)
 * (year make model of the 'least' car)
 *
 * The cars sorted by make are:
 * (year make model of the 'greatest' car)
 * (...)
 * (year make model of the 'least' car)
 *
 * The cars sorted by type are:
 * (year make model type of the 'greatest' car)
 * (...)
 * (year make model type of the 'least' car)
 * *****
 *
 * As an example of the content in the parenthesis:
 * 1990 Ford F-150 */
<|endoftext|>


<commit_before>/*
 Copyright 2007-2009 WebDriver committers
 Copyright 2007-2009 Google Inc.
 Portions copyright 2011 Software Freedom Conservancy

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

/**
 * @fileoverview Contains a Javascript implementation for
 * a custom nsICertOverrideService. This class will forward requests to the
 * original certificate override service - unless it was told to accept all
 * of them.
 */

goog.provide('WdCertOverrideService');

goog.require('fxdriver.Logger');
goog.require('fxdriver.moz');
goog.require('bot.userAgent');

function getPreferenceFromProfile(prefName, prefDefaultValue) {
  var prefs =
      CC["@mozilla.org/preferences-service;1"].getService(CI["nsIPrefBranch"]);

  if (!prefs.prefHasUserValue(prefName)) {
    fxdriver.Logger.dumpn(prefName + ' not set; defaulting to ' + prefDefaultValue);
    return prefDefaultValue;
  }

  var prefValue = prefs.getBoolPref(prefName);
  fxdriver.Logger.dumpn("Found preference for " + prefName + ": " + prefValue);

  return prefValue;
}

function shouldAcceptUntrustedCerts() {
  return getPreferenceFromProfile("webdriver_accept_untrusted_certs", true);
}

function shouldAssumeUntrustedIssuer() {
  return getPreferenceFromProfile("webdriver_assume_untrusted_issuer", true);
}

WdCertOverrideService = function() {
  // Defaults to true - accepting untrusted certificates.
  // This puts the module into effect - setting it to false
  // will delegate all calls to the original service.
  this.acceptAll = shouldAcceptUntrustedCerts();

  // If untrusted issuer is set to false by the user,
  // the initial bitmask will not include ERROR_UNTRUSTED.
  //
  // See the javadoc for FirefoxProfile and documentation
  // for fillNeededBits for further explanation.
  var untrusted_issuer = shouldAssumeUntrustedIssuer();
  if (untrusted_issuer) {
    this.default_bits = this.ERROR_UNTRUSTED;
  } else {
    this.default_bits = 0;
  }

  fxdriver.Logger.dumpn("Accept untrusted certificates: " + this.acceptAll);

  // UUID of the original implementor of this service.
  var ORIGINAL_OVERRIDE_SERVICE_ID = "{67ba681d-5485-4fff-952c-2ee337ffdcd6}";

  // Keep a reference to the original bad certificate listener.
  var originalService = Components.classesByID[ORIGINAL_OVERRIDE_SERVICE_ID].
      getService();

  this.origListener_ =
      originalService.QueryInterface(
        CI['nsICertOverrideService']);
};

// Constants needed since WdCertOverrideService implements
// nsICertOverrideService
WdCertOverrideService.prototype = {
  ERROR_UNTRUSTED: 1,
  ERROR_MISMATCH: 2,
  ERROR_TIME: 4
};

// Returns the bit needed to mask if the certificate has expired, 0 otherwise.
WdCertOverrideService.prototype.certificateExpiredBit_ = function
  (theCert, verification_result) {
  if ((verification_result & theCert.CERT_EXPIRED) != 0) {
    fxdriver.Logger.dumpn("Certificate expired.");
    return this.ERROR_TIME;
  }

  return 0;
};

// Returns the bit needed to mask untrusted issuers, 0 otherwise.
// Note that this bit is already set by default in default_bits
WdCertOverrideService.prototype.certificateIssuerUntrusted_ = function
  (theCert, verification_result) {
  if (((verification_result & theCert.ISSUER_UNKNOWN) != 0) ||
      ((verification_result & theCert.ISSUER_NOT_TRUSTED) != 0) ||
      ((verification_result & theCert.CERT_NOT_TRUSTED) != 0) ||
      ((verification_result & theCert.INVALID_CA) != 0)) {
    fxdriver.Logger.dumpn("Certificate issuer unknown.");
    fxdriver.Logger.dumpn("Unknown: " + (theCert.ISSUER_UNKNOWN & verification_result));
    fxdriver.Logger.dumpn("Issuer not trusted: " + (theCert.ISSUER_NOT_TRUSTED & verification_result));
    fxdriver.Logger.dumpn("Cert not trusted: " + (theCert.CERT_NOT_TRUSTED & verification_result));
    fxdriver.Logger.dumpn("Invalid CA: " + (theCert.INVALID_CA & verification_result));

    return this.ERROR_UNTRUSTED;
  }

  return 0;
};

// Returns the bit needed to mask mismatch between actual hostname
// and the hostname the certificate was issued for, 0 otherwise.
WdCertOverrideService.prototype.certificateHostnameMismatch_ = function
  (theCert, aHost) {
  var commonNameRE = new RegExp("^" + theCert.commonName.replace('*', '[\\w|\-]+') + "$", "i");
  if (aHost.match(commonNameRE) === null) {
    fxdriver.Logger.dumpn("Host name mismatch: cert: " + theCert.commonName + " get: " + aHost);
    return this.ERROR_MISMATCH;
  }

  return 0;
};

// Given a certificate and the host it was received for, fill in the bits
// needed to accept this certificate for this host, even though the
// certificate is invalid.
//
// Note that the bitmask has to be accurate: At the moment, Firefox expects
// the returned bitmask to match *exactly* to the errors the certificate
// caused. If extra bits will be set, the untrusted certificate screen
// will appear.
WdCertOverrideService.prototype.fillNeededBits = function(aCert, aHost) {
  var verification_bits = aCert.verifyForUsage(aCert.CERT_USAGE_SSLClient);
  var return_bits = this.default_bits;

  fxdriver.Logger.dumpn("Certificate verification results: " + verification_bits);

  return_bits = return_bits | this.certificateExpiredBit_(
      aCert, verification_bits);
  return_bits = return_bits | this.certificateHostnameMismatch_(aCert, aHost);

  // Return bits will be 0 here only if:
  // 1. Both checks above returned 0.
  // 2. shouldAssumeUntrustedIssuer is false (otherwise this.default_bits = 1)
  // It has been observed that if there's a host name mismatch then it
  // may not be required to check the trust status of the certificate issuer.
  if (return_bits == 0) {
    fxdriver.Logger.dumpn("Checking issuer since certificate has not expired or has a host name mismatch.");
    return_bits = return_bits | this.certificateIssuerUntrusted_(
        aCert, verification_bits);
  }

  fxdriver.Logger.dumpn("return_bits now: " + return_bits);
  return return_bits;
};

// Interface functions from now on.
WdCertOverrideService.prototype.hasMatchingOverride = function(
    aHostName, aPort, aCert, aOverrideBits, aIsTemporary) {
  var retval = false;

  if (this.acceptAll === true) {
    fxdriver.Logger.dumpn("Allowing certificate from site: " + aHostName + ":" + aPort);
    retval = true;
    aIsTemporary.value = false;

    aOverrideBits.value = this.fillNeededBits(aCert, aHostName);
    fxdriver.Logger.dumpn("Override Bits: " + aOverrideBits.value);
  } else {
    retval = this.origListener_.hasMatchingOverride(aHostName, aPort,
              aCert, aOverrideBits, aIsTemporary);
  }

  return retval;
};

// Delegate the rest of the functions - they are not interesting as they are not
// called during validation of invalid certificate normally.
WdCertOverrideService.prototype.clearValidityOverride = function(aHostName,
                                                                 aPort) {
  this.origListener_.clearValidityOverride(aHostName, aPort);
};

WdCertOverrideService.prototype.getAllOverrideHostsWithPorts = function(
    aCount, aHostsWithPortsArray) {
  this.origListener_.getAllOverrideHostsWithPorts(aCount, aHostsWithPortsArray);
};

WdCertOverrideService.prototype.getValidityOverride = function(
    aHostName, aPort, aHashAlg, aFingerprint, aOverrideBits, aIsTemporary) {
  return this.origListener_.getValidityOverride(
      aHostName, aPort, aHashAlg, aFingerprint, aOverrideBits, aIsTemporary);
};

WdCertOverrideService.prototype.isCertUsedForOverrides = function(
    aCert, aCheckTemporaries, aCheckPermanents) {
  return this.origListener_.isCertUsedForOverrides(
      aCert, aCheckTemporaries, aCheckPermanents);
};

WdCertOverrideService.prototype.rememberValidityOverride = function(
    aHostName, aPort, aCert, aOverrideBits, aTemporary) {
  this.origListener_.rememberValidityOverride(
      aHostName, aPort, aCert, aOverrideBits, aTemporary);
};

WdCertOverrideService.prototype.QueryInterface = function(aIID) {
  if (aIID.equals(CI['nsICertOverrideService']) ||
      aIID.equals(CI['nsIInterfaceRequestor']) ||
      aIID.equals(CI['nsISupports'])) {
    return this;
  }

  throw CR['NS_ERROR_NO_INTERFACE'];
};

// Service contract ID which we override
/** @const */ var CERTOVERRIDE_CONTRACT_ID = "@mozilla.org/security/certoverride;1";
// UUID for this instance specifically.
/** @const */ var DUMMY_CERTOVERRIDE_SERVICE_CLASS_ID =
  Components.ID('{c8fffaba-9b7a-41aa-872d-7e7366c16715}');

var service = undefined;

var WDCertOverrideFactory = {
  createInstance: function (aOuter, aIID) {
    if (aOuter != null)
      throw CR['NS_ERROR_NO_AGGREGATION'];
    if (service == undefined) {
      service = new WdCertOverrideService();
    }
    return service;
  }
};

function WDBadCertListenerModule() {
  this.firstTime_ = true;
}

WDBadCertListenerModule.prototype.registerSelf = function(
    aCompMgr, aFileSpec, aLocation, aType) {

  if (this.firstTime_) {
    this.firstTime_ = false;
    throw CR['NS_ERROR_FACTORY_REGISTER_AGAIN'];
  }

  fxdriver.Logger.dumpn("Registering Override Certificate service.");
  aCompMgr = aCompMgr.QueryInterface(
      CI['nsIComponentRegistrar']);
  aCompMgr.registerFactoryLocation(
      DUMMY_CERTOVERRIDE_SERVICE_CLASS_ID, "badCertListener",
      CERTOVERRIDE_CONTRACT_ID, aFileSpec, aLocation, aType);
};

WDBadCertListenerModule.prototype.unregisterSelf = function(
    aCompMgr, aLocation, aType) {
  fxdriver.Logger.dumpn("Un-registering Override Certificate service.");
  aCompMgr =
  aCompMgr.QueryInterface(CI['nsIComponentRegistrar']);
  aCompMgr.unregisterFactoryLocation(DUMMY_CERTOVERRIDE_SERVICE_CLASS_ID, aLocation);
};

if (!bot.userAgent.isProductVersion('12')){
/** @const */ var FACTORY = {
  createInstance: function (aOuter, aIID) {
    if (aOuter != null)
      throw CR['NS_ERROR_NO_AGGREGATION'];

    if (service != undefined) {
      return service;
    }

    var raw = new WdCertOverrideService();

    var mainThread = CC["@mozilla.org/thread-manager;1"].getService().mainThread;
    var proxyManager = CC["@mozilla.org/xpcomproxy;1"]
        .getService(CI.nsIProxyObjectManager);

    // 5 == NS_PROXY_ALWAYS | NS_PROXY_SYNC
    service = proxyManager.getProxyForObject(mainThread,
                CI.nsICertOverrideService, raw, 5);

    return service;
    }
  };
}

if (!bot.userAgent.isProductVersion('10')){
  WdCertOverrideService.prototype._xpcom_factory = FACTORY;
}

WDBadCertListenerModule.prototype.getClassObject = function(
    aCompMgr, aCID, aIID) {
  if (!aIID.equals(CI['nsIFactory']))
    throw CR['NS_ERROR_NOT_IMPLEMENTED'];

  if (aCID.equals(DUMMY_CERTOVERRIDE_SERVICE_CLASS_ID)) {
    if (bot.userAgent.isProductVersion('12')){
      return WDCertOverrideFactory;
    }else{
      return FACTORY;
   }
  }

  throw CR['NS_ERROR_NO_INTERFACE'];
};

WDBadCertListenerModule.prototype.canUnload = function(aCompMgr) {
  return true;
};

NSGetModule = function(comMgr, fileSpec) {
  return new WDBadCertListenerModule();
};

WdCertOverrideService.prototype.classID = DUMMY_CERTOVERRIDE_SERVICE_CLASS_ID;
fxdriver.moz.load("resource://gre/modules/XPCOMUtils.jsm");
if (XPCOMUtils.generateNSGetFactory) {
  /** @const */ NSGetFactory = XPCOMUtils.generateNSGetFactory([WdCertOverrideService]);
}
<commit_msg>SimonStewart: Looks like mozilla's version comparator doesn't view 12.0a2 as version 12. This now appears to work as expected on Firefox 3.6 -> 12.<commit_after>/*
 Copyright 2007-2009 WebDriver committers
 Copyright 2007-2009 Google Inc.
 Portions copyright 2011 Software Freedom Conservancy

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

/**
 * @fileoverview Contains a Javascript implementation for
 * a custom nsICertOverrideService. This class will forward requests to the
 * original certificate override service - unless it was told to accept all
 * of them.
 */

goog.provide('WdCertOverrideService');

goog.require('fxdriver.Logger');
goog.require('fxdriver.moz');
goog.require('bot.userAgent');

function getPreferenceFromProfile(prefName, prefDefaultValue) {
  var prefs =
      CC["@mozilla.org/preferences-service;1"].getService(CI["nsIPrefBranch"]);

  if (!prefs.prefHasUserValue(prefName)) {
    fxdriver.Logger.dumpn(prefName + ' not set; defaulting to ' + prefDefaultValue);
    return prefDefaultValue;
  }

  var prefValue = prefs.getBoolPref(prefName);
  fxdriver.Logger.dumpn("Found preference for " + prefName + ": " + prefValue);

  return prefValue;
}

function shouldAcceptUntrustedCerts() {
  return getPreferenceFromProfile("webdriver_accept_untrusted_certs", true);
}

function shouldAssumeUntrustedIssuer() {
  return getPreferenceFromProfile("webdriver_assume_untrusted_issuer", true);
}

WdCertOverrideService = function() {
  // Defaults to true - accepting untrusted certificates.
  // This puts the module into effect - setting it to false
  // will delegate all calls to the original service.
  this.acceptAll = shouldAcceptUntrustedCerts();

  // If untrusted issuer is set to false by the user,
  // the initial bitmask will not include ERROR_UNTRUSTED.
  //
  // See the javadoc for FirefoxProfile and documentation
  // for fillNeededBits for further explanation.
  var untrusted_issuer = shouldAssumeUntrustedIssuer();
  if (untrusted_issuer) {
    this.default_bits = this.ERROR_UNTRUSTED;
  } else {
    this.default_bits = 0;
  }

  fxdriver.Logger.dumpn("Accept untrusted certificates: " + this.acceptAll);

  // UUID of the original implementor of this service.
  var ORIGINAL_OVERRIDE_SERVICE_ID = "{67ba681d-5485-4fff-952c-2ee337ffdcd6}";

  // Keep a reference to the original bad certificate listener.
  var originalService = Components.classesByID[ORIGINAL_OVERRIDE_SERVICE_ID].
      getService();

  this.origListener_ =
      originalService.QueryInterface(
        CI['nsICertOverrideService']);
};

// Constants needed since WdCertOverrideService implements
// nsICertOverrideService
WdCertOverrideService.prototype = {
  ERROR_UNTRUSTED: 1,
  ERROR_MISMATCH: 2,
  ERROR_TIME: 4
};

// Returns the bit needed to mask if the certificate has expired, 0 otherwise.
WdCertOverrideService.prototype.certificateExpiredBit_ = function
  (theCert, verification_result) {
  if ((verification_result & theCert.CERT_EXPIRED) != 0) {
    fxdriver.Logger.dumpn("Certificate expired.");
    return this.ERROR_TIME;
  }

  return 0;
};

// Returns the bit needed to mask untrusted issuers, 0 otherwise.
// Note that this bit is already set by default in default_bits
WdCertOverrideService.prototype.certificateIssuerUntrusted_ = function
  (theCert, verification_result) {
  if (((verification_result & theCert.ISSUER_UNKNOWN) != 0) ||
      ((verification_result & theCert.ISSUER_NOT_TRUSTED) != 0) ||
      ((verification_result & theCert.CERT_NOT_TRUSTED) != 0) ||
      ((verification_result & theCert.INVALID_CA) != 0)) {
    fxdriver.Logger.dumpn("Certificate issuer unknown.");
    fxdriver.Logger.dumpn("Unknown: " + (theCert.ISSUER_UNKNOWN & verification_result));
    fxdriver.Logger.dumpn("Issuer not trusted: " + (theCert.ISSUER_NOT_TRUSTED & verification_result));
    fxdriver.Logger.dumpn("Cert not trusted: " + (theCert.CERT_NOT_TRUSTED & verification_result));
    fxdriver.Logger.dumpn("Invalid CA: " + (theCert.INVALID_CA & verification_result));

    return this.ERROR_UNTRUSTED;
  }

  return 0;
};

// Returns the bit needed to mask mismatch between actual hostname
// and the hostname the certificate was issued for, 0 otherwise.
WdCertOverrideService.prototype.certificateHostnameMismatch_ = function
  (theCert, aHost) {
  var commonNameRE = new RegExp("^" + theCert.commonName.replace('*', '[\\w|\-]+') + "$", "i");
  if (aHost.match(commonNameRE) === null) {
    fxdriver.Logger.dumpn("Host name mismatch: cert: " + theCert.commonName + " get: " + aHost);
    return this.ERROR_MISMATCH;
  }

  return 0;
};

// Given a certificate and the host it was received for, fill in the bits
// needed to accept this certificate for this host, even though the
// certificate is invalid.
//
// Note that the bitmask has to be accurate: At the moment, Firefox expects
// the returned bitmask to match *exactly* to the errors the certificate
// caused. If extra bits will be set, the untrusted certificate screen
// will appear.
WdCertOverrideService.prototype.fillNeededBits = function(aCert, aHost) {
  var verification_bits = aCert.verifyForUsage(aCert.CERT_USAGE_SSLClient);
  var return_bits = this.default_bits;

  fxdriver.Logger.dumpn("Certificate verification results: " + verification_bits);

  return_bits = return_bits | this.certificateExpiredBit_(
      aCert, verification_bits);
  return_bits = return_bits | this.certificateHostnameMismatch_(aCert, aHost);

  // Return bits will be 0 here only if:
  // 1. Both checks above returned 0.
  // 2. shouldAssumeUntrustedIssuer is false (otherwise this.default_bits = 1)
  // It has been observed that if there's a host name mismatch then it
  // may not be required to check the trust status of the certificate issuer.
  if (return_bits == 0) {
    fxdriver.Logger.dumpn("Checking issuer since certificate has not expired or has a host name mismatch.");
    return_bits = return_bits | this.certificateIssuerUntrusted_(
        aCert, verification_bits);
  }

  fxdriver.Logger.dumpn("return_bits now: " + return_bits);
  return return_bits;
};

// Interface functions from now on.
WdCertOverrideService.prototype.hasMatchingOverride = function(
    aHostName, aPort, aCert, aOverrideBits, aIsTemporary) {
  var retval = false;

  if (this.acceptAll === true) {
    fxdriver.Logger.dumpn("Allowing certificate from site: " + aHostName + ":" + aPort);
    retval = true;
    aIsTemporary.value = false;

    aOverrideBits.value = this.fillNeededBits(aCert, aHostName);
    fxdriver.Logger.dumpn("Override Bits: " + aOverrideBits.value);
  } else {
    retval = this.origListener_.hasMatchingOverride(aHostName, aPort,
              aCert, aOverrideBits, aIsTemporary);
  }

  return retval;
};

// Delegate the rest of the functions - they are not interesting as they are not
// called during validation of invalid certificate normally.
WdCertOverrideService.prototype.clearValidityOverride = function(aHostName,
                                                                 aPort) {
  this.origListener_.clearValidityOverride(aHostName, aPort);
};

WdCertOverrideService.prototype.getAllOverrideHostsWithPorts = function(
    aCount, aHostsWithPortsArray) {
  this.origListener_.getAllOverrideHostsWithPorts(aCount, aHostsWithPortsArray);
};

WdCertOverrideService.prototype.getValidityOverride = function(
    aHostName, aPort, aHashAlg, aFingerprint, aOverrideBits, aIsTemporary) {
  return this.origListener_.getValidityOverride(
      aHostName, aPort, aHashAlg, aFingerprint, aOverrideBits, aIsTemporary);
};

WdCertOverrideService.prototype.isCertUsedForOverrides = function(
    aCert, aCheckTemporaries, aCheckPermanents) {
  return this.origListener_.isCertUsedForOverrides(
      aCert, aCheckTemporaries, aCheckPermanents);
};

WdCertOverrideService.prototype.rememberValidityOverride = function(
    aHostName, aPort, aCert, aOverrideBits, aTemporary) {
  this.origListener_.rememberValidityOverride(
      aHostName, aPort, aCert, aOverrideBits, aTemporary);
};

WdCertOverrideService.prototype.QueryInterface = function(aIID) {
  if (aIID.equals(CI['nsICertOverrideService']) ||
      aIID.equals(CI['nsIInterfaceRequestor']) ||
      aIID.equals(CI['nsISupports'])) {
    return this;
  }

  throw CR['NS_ERROR_NO_INTERFACE'];
};

// Service contract ID which we override
/** @const */ var CERTOVERRIDE_CONTRACT_ID = "@mozilla.org/security/certoverride;1";
// UUID for this instance specifically.
/** @const */ var DUMMY_CERTOVERRIDE_SERVICE_CLASS_ID =
  Components.ID('{c8fffaba-9b7a-41aa-872d-7e7366c16715}');

var service = undefined;

var WDCertOverrideFactory = {
  createInstance: function (aOuter, aIID) {
    if (aOuter != null)
      throw CR['NS_ERROR_NO_AGGREGATION'];
    if (service == undefined) {
      service = new WdCertOverrideService();
    }
    return service;
  }
};

function WDBadCertListenerModule() {
  this.firstTime_ = true;
}

WDBadCertListenerModule.prototype.registerSelf = function(
    aCompMgr, aFileSpec, aLocation, aType) {

  if (this.firstTime_) {
    this.firstTime_ = false;
    throw CR['NS_ERROR_FACTORY_REGISTER_AGAIN'];
  }

  fxdriver.Logger.dumpn("Registering Override Certificate service.");
  aCompMgr = aCompMgr.QueryInterface(
      CI['nsIComponentRegistrar']);
  aCompMgr.registerFactoryLocation(
      DUMMY_CERTOVERRIDE_SERVICE_CLASS_ID, "badCertListener",
      CERTOVERRIDE_CONTRACT_ID, aFileSpec, aLocation, aType);
};

WDBadCertListenerModule.prototype.unregisterSelf = function(
    aCompMgr, aLocation, aType) {
  fxdriver.Logger.dumpn("Un-registering Override Certificate service.");
  aCompMgr =
  aCompMgr.QueryInterface(CI['nsIComponentRegistrar']);
  aCompMgr.unregisterFactoryLocation(DUMMY_CERTOVERRIDE_SERVICE_CLASS_ID, aLocation);
};

var FACTORY = null;

if (!bot.userAgent.isProductVersion('10')){
/** @const */ FACTORY = {
  createInstance: function (aOuter, aIID) {
    if (aOuter != null)
      throw CR['NS_ERROR_NO_AGGREGATION'];

    if (service != undefined) {
      return service;
    }

    var raw = new WdCertOverrideService();

    var mainThread = CC["@mozilla.org/thread-manager;1"].getService().mainThread;
    var proxyManager = CC["@mozilla.org/xpcomproxy;1"]
        .getService(CI.nsIProxyObjectManager);

    // 5 == NS_PROXY_ALWAYS | NS_PROXY_SYNC
    service = proxyManager.getProxyForObject(mainThread,
                CI.nsICertOverrideService, raw, 5);

    return service;
    }
  };

  WdCertOverrideService.prototype._xpcom_factory = FACTORY;
}

WDBadCertListenerModule.prototype.getClassObject = function(
    aCompMgr, aCID, aIID) {
  if (!aIID.equals(CI['nsIFactory']))
    throw CR['NS_ERROR_NOT_IMPLEMENTED'];

  if (aCID.equals(DUMMY_CERTOVERRIDE_SERVICE_CLASS_ID)) {
    if (bot.userAgent.isProductVersion('10')) {
      return WDCertOverrideFactory;
    } else{
      return FACTORY;
   }
  }

  throw CR['NS_ERROR_NO_INTERFACE'];
};

WDBadCertListenerModule.prototype.canUnload = function(aCompMgr) {
  return true;
};

NSGetModule = function(comMgr, fileSpec) {
  return new WDBadCertListenerModule();
};

WdCertOverrideService.prototype.classID = DUMMY_CERTOVERRIDE_SERVICE_CLASS_ID;
fxdriver.moz.load("resource://gre/modules/XPCOMUtils.jsm");
if (XPCOMUtils.generateNSGetFactory) {
  /** @const */ NSGetFactory = XPCOMUtils.generateNSGetFactory([WdCertOverrideService]);
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');

module.exports = {
    // Return array of all the possible slots allowed on the ship
    // Each item contains slot type and required pilotSkill to unlock
    // This is the total number of slots possible base don the ship chassis
    getShipSlots: function (build) {
        // elite slots are dependent on pilot level

        var allBaseSlots = _.map(build.currentShip.upgradeSlots, function (upgradeSlot) {
            return {
                type: upgradeSlot
            };
        });

        allBaseSlots = allBaseSlots.concat([
            {
                type: 'Title'
            },
            {
                type: 'Modification'
            },
            {
                type: 'Modification',
                pilotSkill: 4
            },
            {
                type: 'Modification',
                pilotSkill: 6
            },
            {
                type: 'Modification',
                pilotSkill: 8
            },
            {
                type: 'Elite',
                pilotSkill: 3
            },
            {
                type: 'Elite',
                pilotSkill: 5
            },
            {
                type: 'Elite',
                pilotSkill: 7
            },
            {
                type: 'Elite',
                pilotSkill: 9
            }
        ]);

        // Now work out what slots are allowed in current build dependent on PS
        var enabledSlots = [];
        var disabledSlots = [];

        _.each(allBaseSlots, function (slot) {
            if (build.pilotSkill < slot.pilotSkill) {
                // slot should be disabled
                disabledSlots.push(slot);
            } else {
                enabledSlots.push(slot);
            }
        });

        var slotsFromUpgrades = module.exports.getSlotsFromUpgrades(build);

        return {
            allBase: allBaseSlots,
            enabled: enabledSlots,
            disabled: disabledSlots,
            fromUpgrades: slotsFromUpgrades
        };
    },
    // Returns array of slot types granted by starting and purchased upgrade cards
    getSlotsFromUpgrades: function (build) {
        var additionalSlotTypes = [];

        var processGrantsList = function (upgradeList) {
            _.each(upgradeList, function (upgrade) {
                if (upgrade.grants) {
                    _.each(upgrade.grants, function (grant) {
                        if (grant.type === 'slot') {
                            additionalSlotTypes.push(grant.name);
                        }
                    });
                }
            });
        };

        // Process any additional slots from equipped upgrades
        processGrantsList(build.equippedUpgrades.upgrades);

        additionalSlotTypes = _.map(additionalSlotTypes, function (upgradeType) {
            var upgradeSlot = {
                type: upgradeType
            };
            return upgradeSlot;
        });

        return additionalSlotTypes;
    },
    // Return array of upgrade types enabled in current state of ship build (enabled + upgrades)
    allUsableSlotTypes: function (build) {
        var shipSlots = module.exports.getShipSlots(build);

        var allowedSlots = shipSlots.enabled;
        var slotsFromUpgrades = shipSlots.fromUpgrades;

        var allEnabledSlotTypes = allowedSlots.concat(slotsFromUpgrades);
        // map output so that it is just a list of types
        allEnabledSlotTypes = _.map(allEnabledSlotTypes, function (item) {
            return item.type;
        });

        // Remove any duplicates in array
        allEnabledSlotTypes = _.uniq(allEnabledSlotTypes);

        return allEnabledSlotTypes;
    }
};
<commit_msg>fix upgrade slot logic<commit_after>'use strict';

var _ = require('lodash');

module.exports = {
    // Return array of all the possible slots allowed on the ship
    // Each item contains slot type and required pilotSkill to unlock
    // This is the total number of slots possible base don the ship chassis
    getShipSlots: function (build) {
        // elite slots are dependent on pilot level

        var allBaseSlots = _.map(build.currentShip.upgradeSlots, function (upgradeSlot) {
            return {
                type: upgradeSlot
            };
        });

        allBaseSlots = allBaseSlots.concat([
            {
                type: 'Title'
            },
            {
                type: 'Modification'
            },
            {
                type: 'Modification',
                pilotSkill: 4
            },
            {
                type: 'Modification',
                pilotSkill: 6
            },
            {
                type: 'Modification',
                pilotSkill: 8
            },
            {
                type: 'Elite',
                pilotSkill: 3
            },
            {
                type: 'Elite',
                pilotSkill: 5
            },
            {
                type: 'Elite',
                pilotSkill: 7
            },
            {
                type: 'Elite',
                pilotSkill: 9
            }
        ]);

        // Now work out what slots are allowed in current build dependent on PS
        var enabledSlots = [];
        var disabledSlots = [];

        _.each(allBaseSlots, function (slot) {
            if (build.pilotSkill < slot.pilotSkill) {
                // slot should be disabled
                disabledSlots.push(slot);
            } else {
                enabledSlots.push(slot);
            }
        });

        var slotsFromUpgrades = module.exports.getSlotsFromUpgrades(build, enabledSlots);

        return {
            allBase: allBaseSlots,
            enabled: enabledSlots,
            disabled: disabledSlots,
            fromUpgrades: slotsFromUpgrades
        };
    },
    // Returns array of slot types granted by starting and purchased upgrade cards
    getSlotsFromUpgrades: function (build, enabledSlots) {
        var additionalSlotTypes = [];

        var enabledTypes = _.map(enabledSlots, function (slot) {
            return slot.type;
        });

        var unProcessedUpgrades = _.filter(build.equippedUpgrades.upgrades, function (upgrade) {
            return upgrade.grants;
        });

        // Determines if upgrade fits in a slot on the ship or one allowed by another equipped upgrade
        var isAllowedOnShip = function (upgrade) {
            if (enabledTypes.indexOf(upgrade.slot) > -1 || additionalSlotTypes.indexOf(upgrade.slot) > -1) {
                return true;
            }
            return false;
        };

        // array to track which upgrades we've processed grants for, and prevent infinite loop
        var processGrants = function (upgrade) {
            _.each(upgrade.grants, function (grant) {
                if (grant.type === 'slot') {
                    additionalSlotTypes.push(grant.name);
                }
            });
        };

        var foundUpgrade = false;
        // keep looping while we find results. If we find a grant, we have to process the
        // whole list again, in case it affects another upgrade
        do {
            foundUpgrade = _.find(unProcessedUpgrades, isAllowedOnShip);
            if (foundUpgrade && foundUpgrade.id) {
                // process item
                processGrants(foundUpgrade);
                // remove from list to process
                _.remove(unProcessedUpgrades, function (item) {
                    return item.id === foundUpgrade.id;
                });
            }
        } while (foundUpgrade);

        // format slot type array to match getShipSlots() output
        additionalSlotTypes = _.map(additionalSlotTypes, function (upgradeType) {
            var upgradeSlot = {
                type: upgradeType
            };
            return upgradeSlot;
        });

        return additionalSlotTypes;
    },
    // Return array of upgrade types enabled in current state of ship build (enabled + upgrades)
    allUsableSlotTypes: function (build) {
        var shipSlots = module.exports.getShipSlots(build);

        var allowedSlots = shipSlots.enabled;
        var slotsFromUpgrades = shipSlots.fromUpgrades;

        var allEnabledSlotTypes = allowedSlots.concat(slotsFromUpgrades);
        // map output so that it is just a list of types
        allEnabledSlotTypes = _.map(allEnabledSlotTypes, function (item) {
            return item.type;
        });

        // Remove any duplicates in array
        allEnabledSlotTypes = _.uniq(allEnabledSlotTypes);

        return allEnabledSlotTypes;
    }
};
<|endoftext|>


<commit_before>/*jslint indent: 2, nomen: true, maxlen: 100, sloppy: true, vars: true, white: true, plusplus: true */
/*global require, exports, Graph, arguments */

////////////////////////////////////////////////////////////////////////////////
/// @brief Graph functionality
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2014 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Florian Bartels
/// @author Copyright 2011-2014, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var arangodb = require("org/arangodb"),
	ArangoCollection = arangodb.ArangoCollection,
	db = arangodb.db;

// -----------------------------------------------------------------------------
// --SECTION--                             module "org/arangodb/general-graph"
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                                 private functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief transform a string into an array.
////////////////////////////////////////////////////////////////////////////////

var stringToArray = function (x) {
	if (typeof(x) === "string") {
		return [x];
	}
	return x;
};

////////////////////////////////////////////////////////////////////////////////
/// @brief checks if a parameter is not defined, an empty string or an empty
//  array
////////////////////////////////////////////////////////////////////////////////

var isValidCollectionsParameter = function (x) {
	if (!x) {
		return false;
	}
	if (Array.isArray(x) && x.length === 0) {
		return false;
	}
	if (typeof(x) !== "string" && !Array.isArray(x)) {
		return false;
	}
	return true;
};

////////////////////////////////////////////////////////////////////////////////
/// @brief find or create a collection by name
////////////////////////////////////////////////////////////////////////////////

var findOrCreateCollectionByName = function (name, type) {
	var col = db._collection(name),res = false;
	if (col === null) {
		if (type === ArangoCollection.TYPE_DOCUMENT) {
			col = db._create(name);
		} else {
			col = db._createEdgeCollection(name);
		}
		res = true;
	} else if (!(col instanceof ArangoCollection) || col.type() !== type) {
		throw "<" + name + "> must be a " +
			(type === ArangoCollection.TYPE_DOCUMENT ? "document" : "edge")
		+ " collection";
	}
	return res;
};

// -----------------------------------------------------------------------------
// --SECTION--                             module "org/arangodb/general-graph"
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                                 public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief define an undirected relation.
////////////////////////////////////////////////////////////////////////////////

var _undirectedRelationDefinition = function (relationName, vertexCollections) {

	if (arguments.length < 2) {
		throw "method _undirectedRelationDefinition expects 2 arguments";
	}

	if (typeof relationName !== "string" || relationName === "") {
		throw "<relationName> must be a not empty string";
	}

	if (!isValidCollectionsParameter(vertexCollections)) {
		throw "<vertexCollections> must be a not empty string or array";
	}

	return {
		collection: "relationName",
		from: stringToArray(vertexCollections),
		to: stringToArray(vertexCollections)
	};
};

////////////////////////////////////////////////////////////////////////////////
/// @brief define an directed relation.
////////////////////////////////////////////////////////////////////////////////

var _directedRelationDefinition = function (
	relationName, fromVertexCollections, toVertexCollections) {

	if (arguments.length < 3) {
		throw "method _undirectedRelationDefinition expects 3 arguments";
	}

	if (typeof relationName !== "string" || relationName === "") {
		throw "<relationName> must be a not empty string";
	}

	if (!isValidCollectionsParameter(fromVertexCollections)) {
		throw "<fromVertexCollections> must be a not empty string or array";
	}

	if (!isValidCollectionsParameter(toVertexCollections)) {
		throw "<toVertexCollections> must be a not empty string or array";
	}

	return {
		collection: "relationName",
		from: stringToArray(fromVertexCollections),
		to: stringToArray(toVertexCollections)
	};
};

////////////////////////////////////////////////////////////////////////////////
/// @brief create a list of edge definitions
////////////////////////////////////////////////////////////////////////////////

var edgeDefinitions = function () {

	var res = [], args = arguments;
	Object.keys(args).forEach(function (x) {
		res.push(args[x]);
	});

	return res;

};

////////////////////////////////////////////////////////////////////////////////
/// @brief create a new graph
////////////////////////////////////////////////////////////////////////////////

var _create = function (graphName, edgeDefinitions) {

	var gdb = db._collection("_graphs"),
		g,
		graphAlreadyExists = true,
		createdCollections = []
	;

	if (gdb === null) {
		throw "_graphs collection does not exist.";
	}

	if (!graphName) {
		throw "a graph name is required to create a graph.";
	}
	if (!Array.isArray(edgeDefinitions) || edgeDefinitions.length === 0) {
		throw "at least one edge definition is required to create a graph.";
	}

	try {
		g = gdb.document(graphName);
	} catch (e) {
		if (e.errorNum !== 1202) {
			throw e;
		}
		graphAlreadyExists = false;
	}

	if (graphAlreadyExists) {
		throw "graph " + graphName + " already exists.";
	}

	edgeDefinitions.forEach(function (e) {
		e.from.concat(e.to).forEach(function (v) {
			if (findOrCreateCollectionByName(v, ArangoCollection.TYPE_DOCUMENT)) {
				createdCollections.push(v);
			}
		});
		if (findOrCreateCollectionByName(e.collection, ArangoCollection.TYPE_EDGE)) {
			createdCollections.push(e.collection);
		}
	});

	gdb.save({
		'edgeDefinitions' : edgeDefinitions,
		'_key' : graphName
	});

	return new Graph(graphName, edgeDefinitions);

};

////////////////////////////////////////////////////////////////////////////////
/// @brief load a graph.
////////////////////////////////////////////////////////////////////////////////

var Graph = function(graphName, edgeDefinitions) {

};

var _graph = function() {
  return new Graph();
};

Graph.prototype.edgeCollections = function() {
  //testdummy
  return [require("internal").db.w3];
};

Graph.prototype.vertexCollections = function() {
  //testdummy
  return [require("internal").db.a, require("internal").db.b];
};

////////////////////////////////////////////////////////////////////////////////
/// @brief edges(vertexId).
////////////////////////////////////////////////////////////////////////////////

Graph.prototype.edges = function(vertexId) {
  var edgeCollections = this.edgeCollections();
  var result = [];

  edgeCollections.forEach(
    function(edgeCollection) {
      //todo: test, if collection may point to vertex
      result = result.concat(edgeCollection.edges(vertexId));
    }
  );
  return result;
};

////////////////////////////////////////////////////////////////////////////////
/// @brief inEdges(vertexId).
////////////////////////////////////////////////////////////////////////////////

Graph.prototype.inEdges = function(vertexId) {
  var edgeCollections = this.edgeCollections();
  var result = [];

  edgeCollections.forEach(
    function(edgeCollection) {
      //todo: test, if collection may point to vertex
      result = result.concat(edgeCollection.inEdges(vertexId));
    }
  );
  return result;
};

////////////////////////////////////////////////////////////////////////////////
/// @brief outEdges(vertexId).
////////////////////////////////////////////////////////////////////////////////

Graph.prototype.outEdges = function(vertexId) {
  var edgeCollections = this.edgeCollections();
  var result = [];

  edgeCollections.forEach(
    function(edgeCollection) {
      //todo: test, if collection may point to vertex
      result = result.concat(edgeCollection.outEdges(vertexId));
    }
  );
  return result;
};

////////////////////////////////////////////////////////////////////////////////
/// @brief get ingoing vertex of an edge.
////////////////////////////////////////////////////////////////////////////////

Graph.prototype.getInVertex = function(edgeId) {
  var edgeCollection = this.getEdgeCollectionByName(edgeId.split("/")[0]);
  var document = edgeCollection.document(edgeId);
  if (document) {
    var vertexId = document._from;
    var vertexCollection = this.getVertexCollectionByName(vertexId.split("/")[0]);
    return vertexCollection.document(vertexId);
  }
};

////////////////////////////////////////////////////////////////////////////////
/// @brief get outgoing vertex of an edge .
////////////////////////////////////////////////////////////////////////////////

Graph.prototype.getOutVertex = function(edgeId) {
  var edgeCollection = this.getEdgeCollectionByName(edgeId.split("/")[0]);
  var document = edgeCollection.document(edgeId);
  if (document) {
    var vertexId = document._to;
    var vertexCollection = this.getVertexCollectionByName(vertexId.split("/")[0]);
    return vertexCollection.document(vertexId);
  }
};

////////////////////////////////////////////////////////////////////////////////
/// @brief get edge collection by name.
////////////////////////////////////////////////////////////////////////////////

Graph.prototype.getEdgeCollectionByName = function(name) {
  var edgeCollections = this.edgeCollections();
  var results = edgeCollections.filter(
    function(edgeCollection) {
      return edgeCollection.name() === name;
    }
  );

  if (results.length === 1) {
    return results[0];
  }
  throw "Collection " + name + " does not exist in graph.";
};

////////////////////////////////////////////////////////////////////////////////
/// @brief get vertex collection by name.
////////////////////////////////////////////////////////////////////////////////

Graph.prototype.getVertexCollectionByName = function(name) {
  var vertexCollections = this.vertexCollections();
  var results = vertexCollections.filter(
    function(vertexCollection) {
      return vertexCollection.name() === name;
    }
  );

  if (results.length === 1) {
    return results[0];
  }
  throw "Collection " + name + " does not exist in graph.";
};

// -----------------------------------------------------------------------------
// --SECTION--                                                    MODULE EXPORTS
// -----------------------------------------------------------------------------

exports._undirectedRelationDefinition = _undirectedRelationDefinition;
exports._directedRelationDefinition = _directedRelationDefinition;
exports._graph = _graph;
exports.edgeDefinitions = edgeDefinitions;
exports._create = _create;

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:
<commit_msg>added vertex and edge methods<commit_after>/*jslint indent: 2, nomen: true, maxlen: 100, sloppy: true, vars: true, white: true, plusplus: true */
/*global require, exports, Graph, arguments */

////////////////////////////////////////////////////////////////////////////////
/// @brief Graph functionality
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2014 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Florian Bartels
/// @author Copyright 2011-2014, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var arangodb = require("org/arangodb"),
	ArangoCollection = arangodb.ArangoCollection,
	db = arangodb.db,
  _ = require("underscore");

// -----------------------------------------------------------------------------
// --SECTION--                             module "org/arangodb/general-graph"
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                                 private functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief transform a string into an array.
////////////////////////////////////////////////////////////////////////////////

var stringToArray = function (x) {
	if (typeof(x) === "string") {
		return [x];
	}
	return x;
};

////////////////////////////////////////////////////////////////////////////////
/// @brief checks if a parameter is not defined, an empty string or an empty
//  array
////////////////////////////////////////////////////////////////////////////////

var isValidCollectionsParameter = function (x) {
	if (!x) {
		return false;
	}
	if (Array.isArray(x) && x.length === 0) {
		return false;
	}
	if (typeof(x) !== "string" && !Array.isArray(x)) {
		return false;
	}
	return true;
};

////////////////////////////////////////////////////////////////////////////////
/// @brief find or create a collection by name
////////////////////////////////////////////////////////////////////////////////

var findOrCreateCollectionByName = function (name, type) {
	var col = db._collection(name),res = false;
	if (col === null) {
		if (type === ArangoCollection.TYPE_DOCUMENT) {
			col = db._create(name);
		} else {
			col = db._createEdgeCollection(name);
		}
		res = true;
	} else if (!(col instanceof ArangoCollection) || col.type() !== type) {
		throw "<" + name + "> must be a " +
			(type === ArangoCollection.TYPE_DOCUMENT ? "document" : "edge")
		+ " collection";
	}
	return res;
};

// -----------------------------------------------------------------------------
// --SECTION--                             module "org/arangodb/general-graph"
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                                 public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief define an undirected relation.
////////////////////////////////////////////////////////////////////////////////

var _undirectedRelationDefinition = function (relationName, vertexCollections) {

	if (arguments.length < 2) {
		throw "method _undirectedRelationDefinition expects 2 arguments";
	}

	if (typeof relationName !== "string" || relationName === "") {
		throw "<relationName> must be a not empty string";
	}

	if (!isValidCollectionsParameter(vertexCollections)) {
		throw "<vertexCollections> must be a not empty string or array";
	}

	return {
		collection: "relationName",
		from: stringToArray(vertexCollections),
		to: stringToArray(vertexCollections)
	};
};

////////////////////////////////////////////////////////////////////////////////
/// @brief define an directed relation.
////////////////////////////////////////////////////////////////////////////////

var _directedRelationDefinition = function (
	relationName, fromVertexCollections, toVertexCollections) {

	if (arguments.length < 3) {
		throw "method _undirectedRelationDefinition expects 3 arguments";
	}

	if (typeof relationName !== "string" || relationName === "") {
		throw "<relationName> must be a not empty string";
	}

	if (!isValidCollectionsParameter(fromVertexCollections)) {
		throw "<fromVertexCollections> must be a not empty string or array";
	}

	if (!isValidCollectionsParameter(toVertexCollections)) {
		throw "<toVertexCollections> must be a not empty string or array";
	}

	return {
		collection: "relationName",
		from: stringToArray(fromVertexCollections),
		to: stringToArray(toVertexCollections)
	};
};

////////////////////////////////////////////////////////////////////////////////
/// @brief create a list of edge definitions
////////////////////////////////////////////////////////////////////////////////

var edgeDefinitions = function () {

	var res = [], args = arguments;
	Object.keys(args).forEach(function (x) {
		res.push(args[x]);
	});

	return res;

};

////////////////////////////////////////////////////////////////////////////////
/// @brief create a new graph
////////////////////////////////////////////////////////////////////////////////

var _create = function (graphName, edgeDefinitions) {

	var gdb = db._collection("_graphs"),
		g,
		graphAlreadyExists = true;

	if (gdb === null) {
		throw "_graphs collection does not exist.";
	}

	if (!graphName) {
		throw "a graph name is required to create a graph.";
	}
	if (!Array.isArray(edgeDefinitions) || edgeDefinitions.length === 0) {
		throw "at least one edge definition is required to create a graph.";
	}

	try {
		g = gdb.document(graphName);
	} catch (e) {
		if (e.errorNum !== 1202) {
			throw e;
		}
		graphAlreadyExists = false;
	}

	if (graphAlreadyExists) {
		throw "graph " + graphName + " already exists.";
	}

  var vertexCollections = {};
  var edgeCollections = {};
	edgeDefinitions.forEach(function (e) {
		e.from.concat(e.to).forEach(function (v) {
			findOrCreateCollectionByName(v, ArangoCollection.TYPE_DOCUMENT);
      vertexCollections[v] = db[v];
    });
		findOrCreateCollectionByName(e.collection, ArangoCollection.TYPE_EDGE);
    edgeCollections[e] = db[e];
	});

	gdb.save({
		'edgeDefinitions' : edgeDefinitions,
		'_key' : graphName
	});

	return new Graph(graphName, edgeDefinitions, vertexCollections, edgeCollections);

};

////////////////////////////////////////////////////////////////////////////////
/// @brief load a graph.
////////////////////////////////////////////////////////////////////////////////

var Graph = function(graphName, edgeDefinitions, vertexCollections, edgeCollections) {
  this.vertexCollections = vertexCollections;
  this.edgeCollections = edgeCollections;
  this.edgeDefinitions = edgeDefinitions;
};

var _graph = function() {
  return new Graph();
};

////////////////////////////////////////////////////////////////////////////////
/// @brief return all edge collections of the graph.
////////////////////////////////////////////////////////////////////////////////

Graph.prototype.edgeCollections = function() {
  return _.values(this.edgeCollections);
};

////////////////////////////////////////////////////////////////////////////////
/// @brief return all vertex collections of the graph.
////////////////////////////////////////////////////////////////////////////////

Graph.prototype.vertexCollections = function() {
  return _.values(this.vertexCollections);
};

////////////////////////////////////////////////////////////////////////////////
/// @brief edges(vertexId).
////////////////////////////////////////////////////////////////////////////////

Graph.prototype.edges = function(vertexId) {
  var edgeCollections = this.edgeCollections();
  var result = [];

  edgeCollections.forEach(
    function(edgeCollection) {
      //todo: test, if collection may point to vertex
      result = result.concat(edgeCollection.edges(vertexId));
    }
  );
  return result;
};

////////////////////////////////////////////////////////////////////////////////
/// @brief inEdges(vertexId).
////////////////////////////////////////////////////////////////////////////////

Graph.prototype.inEdges = function(vertexId) {
  var edgeCollections = this.edgeCollections();
  var result = [];

  edgeCollections.forEach(
    function(edgeCollection) {
      //todo: test, if collection may point to vertex
      result = result.concat(edgeCollection.inEdges(vertexId));
    }
  );
  return result;
};

////////////////////////////////////////////////////////////////////////////////
/// @brief outEdges(vertexId).
////////////////////////////////////////////////////////////////////////////////

Graph.prototype.outEdges = function(vertexId) {
  var edgeCollections = this.edgeCollections();
  var result = [];

  edgeCollections.forEach(
    function(edgeCollection) {
      //todo: test, if collection may point to vertex
      result = result.concat(edgeCollection.outEdges(vertexId));
    }
  );
  return result;
};

////////////////////////////////////////////////////////////////////////////////
/// @brief get ingoing vertex of an edge.
////////////////////////////////////////////////////////////////////////////////

Graph.prototype.getInVertex = function(edgeId) {
  var edgeCollection = this.getEdgeCollectionByName(edgeId.split("/")[0]);
  var document = edgeCollection.document(edgeId);
  if (document) {
    var vertexId = document._from;
    var vertexCollection = this.getVertexCollectionByName(vertexId.split("/")[0]);
    return vertexCollection.document(vertexId);
  }
};

////////////////////////////////////////////////////////////////////////////////
/// @brief get outgoing vertex of an edge .
////////////////////////////////////////////////////////////////////////////////

Graph.prototype.getOutVertex = function(edgeId) {
  var edgeCollection = this.getEdgeCollectionByName(edgeId.split("/")[0]);
  var document = edgeCollection.document(edgeId);
  if (document) {
    var vertexId = document._to;
    var vertexCollection = this.getVertexCollectionByName(vertexId.split("/")[0]);
    return vertexCollection.document(vertexId);
  }
};

////////////////////////////////////////////////////////////////////////////////
/// @brief get edge collection by name.
////////////////////////////////////////////////////////////////////////////////

Graph.prototype.getEdgeCollectionByName = function(name) {
  var edgeCollections = this.edgeCollections();
  var results = edgeCollections.filter(
    function(edgeCollection) {
      return edgeCollection.name() === name;
    }
  );

  if (results.length === 1) {
    return results[0];
  }
  throw "Collection " + name + " does not exist in graph.";
};

////////////////////////////////////////////////////////////////////////////////
/// @brief get vertex collection by name.
////////////////////////////////////////////////////////////////////////////////

Graph.prototype.getVertexCollectionByName = function(name) {
  var vertexCollections = this.vertexCollections();
  var results = vertexCollections.filter(
    function(vertexCollection) {
      return vertexCollection.name() === name;
    }
  );

  if (results.length === 1) {
    return results[0];
  }
  throw "Collection " + name + " does not exist in graph.";
};

// -----------------------------------------------------------------------------
// --SECTION--                                                    MODULE EXPORTS
// -----------------------------------------------------------------------------

exports._undirectedRelationDefinition = _undirectedRelationDefinition;
exports._directedRelationDefinition = _directedRelationDefinition;
exports._graph = _graph;
exports.edgeDefinitions = edgeDefinitions;
exports._create = _create;

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:
<|endoftext|>