<commit_before>import Cookies from 'js-cookie';

import config from '../config';

export class StatusCodeError extends Error {}

const DEFAULT_OPTS = {
  credentials: 'same-origin',
};

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new StatusCodeError(response.statusText);
  error.statusCode = response.status;
  error.response = response;

  throw error;
}

function makeApiUrl(apiPath) {
  return `${config.backend.baseUrl}${config.backend.apiPrefix}${apiPath}`;
}

function requestWithBody(method) {
  return (apiPath, body = {}, requestOpts = {}) => {
    const
      headers = new Headers({
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'X-CSRFToken': Cookies.get('csrftoken'),
      }),
      opts = Object.assign({}, DEFAULT_OPTS, {
        method,
        headers,
        body: JSON.stringify(body),
      }, requestOpts);

    return fetch(makeApiUrl(apiPath), opts)
      .then(checkStatus)
      .then(res => res.json());
  };
}

function requestWithoutBody(method) {
  return (apiPath, requestOpts) => {
    const
      headers = new Headers({
        Accept: 'application/json',
        'X-CSRFToken': Cookies.get('csrftoken'),
      }),
      opts = Object.assign({}, DEFAULT_OPTS, {method, headers}, requestOpts);

    return fetch(makeApiUrl(apiPath), opts)
      .then(checkStatus)
      .then(res => res.json());
  };
}

export const get = requestWithoutBody('GET');
export const post = requestWithBody('POST');
export const put = requestWithBody('PUT');
export const patch = requestWithBody('PATCH');
export const del = requestWithoutBody('DELETE');
export default get;
<commit_msg>http: CONSTANT VIGILANCE! There may not be a body NEXT time!<commit_after>import Cookies from 'js-cookie';

import config from '../config';

export class StatusCodeError extends Error {}

const DEFAULT_OPTS = {
  credentials: 'same-origin',
};

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new StatusCodeError(response.statusText);
  error.statusCode = response.status;
  error.response = response;

  throw error;
}

function decodeBody(response) {
  if (response.status === 204) return undefined;
  return response.json();
}

function makeApiUrl(apiPath) {
  return `${config.backend.baseUrl}${config.backend.apiPrefix}${apiPath}`;
}

function requestWithBody(method) {
  return (apiPath, body = {}, requestOpts = {}) => {
    const
      headers = new Headers({
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'X-CSRFToken': Cookies.get('csrftoken'),
      }),
      opts = Object.assign({}, DEFAULT_OPTS, {
        method,
        headers,
        body: JSON.stringify(body),
      }, requestOpts);

    return fetch(makeApiUrl(apiPath), opts)
      .then(checkStatus)
      .then(decodeBody);
  };
}

function requestWithoutBody(method) {
  return (apiPath, requestOpts) => {
    const
      headers = new Headers({
        Accept: 'application/json',
        'X-CSRFToken': Cookies.get('csrftoken'),
      }),
      opts = Object.assign({}, DEFAULT_OPTS, {method, headers}, requestOpts);

    return fetch(makeApiUrl(apiPath), opts)
      .then(checkStatus)
      .then(decodeBody);
  };
}

export const get = requestWithoutBody('GET');
export const post = requestWithBody('POST');
export const put = requestWithBody('PUT');
export const patch = requestWithBody('PATCH');
export const del = requestWithoutBody('DELETE');
export default get;
<|endoftext|>


<commit_before>/*jslint node: true */
"use strict";

var dualapi = require('../index');
var _ = require('lodash');
var assert = require('assert');

describe('dualapi', function () {

    describe('mount', function () {

        it('should return the api', function (done) {
            var dual = dualapi();
            var called = [];
            dual
                .mount(['big'], function () {
                    called.push('bad');
                })
                .mount(['wolf'], function () {
                    called.push('laser');
                });

            dual.send(['big']);
            dual.send(['wolf'])
            .then(function () {
                assert.deepEqual(['bad', 'laser'], called);
                done();
            });

        });

        it('should be able to mount undefined', function (done) {
            // perhaps not useful, but nothing technically wrong...
            var dual = dualapi();
            dual.mount([void 0], function () {
                done();
            });
            dual.send([void 0], [], 'acting');
        });

        it('should throw exception on empty mount destination', function () {
            var dual = dualapi();
            assert.throws(function () {
                dual.mount([], function () {});
            }, /empty/);
        });

    });

    describe('send', function () {
        it('should return promise value true when an event is matched', function (done) {
            var dual = dualapi();

            dual.mount(['food'], function () {});

            dual.send(['food'])
            .then(function (called) {
                assert(called);
                done();
            });
        });

        it('should return promise value false when an event is matched', function (done) {
            var dual = dualapi();

            dual.mount(['seed'], function () {});

            dual.send(['wad'])
            .then(function (called) {
                assert(!called);
                done();
            });
        });
    });

    describe('mounted host', function () {

        var dual = dualapi();

        it('should be triggered on target message', function (done) {
            dual.mount(['host'], function () {
                done();
            });

            dual.send(['host']);
        });

        it('should be triggered with destination field in context', function (done) {
            dual.mount(['hostA'], function (ctxt) {
                assert.deepEqual(ctxt.to, ['hostA']);
                done();
            });

            dual.send(['hostA']);
        });

        it('should be triggered with from field', function (done) {
            dual.mount(['hostB'], function (ctxt) {
                assert.deepEqual(ctxt.from, ['sourceA']);
                done();
            });
            dual.send(['hostB'], ['sourceA']);
        });

        it('should be triggered with undefined body when no body is provided', function (done) {
            dual.mount(['hostC'], function (ctxt) {
                assert(_.isUndefined(ctxt.body));
                done();
            });

            dual.send(['hostC'], ['sourceB']);
        });

        it('should be triggered with source body when one is provided', function (done) {
            dual.mount(['hostD'], function (ctxt) {
                assert.deepEqual(ctxt.body, {a: 1});
                done();
            });

            dual.send(['hostD'], [], {a: 1});
        });

        it('should NOT be triggered on target message for other hosts', function (done) {
            var received = 0;
            dual.mount(['hostE'], function () {
                received++;
            });
            dual.mount(['host1'], function () {
                assert.equal(received, 0);
                received++;
                done();
            });

            dual.send(['host1']);
        });

    });

    describe('mounted tree', function () {

        var dual = dualapi();

        it('should be possible to mount hosts in a tree structure', function (done) {
            dual.mount([], {
                host: function () {
                    done();
                }
            });

            dual.send(['host']);
        });

        it('should be possible to mount host trees directly', function (done) {
            dual.mount({
                go: function () {
                    done();
                }
            });

            dual.send(['go']);
        });

        it('should be possible to mount hosts in a tree structure below a static trunk', function (done) {
            dual.mount(['cookie'], {
                sword: function () {
                    done();
                }
            });

            dual.send(['cookie', 'sword']);
        });

        it('should be possible to mount deep tree structure', function (done) {
            dual.mount([], {
                treat: {
                    grass: function () {
                        done();
                    }
                }
            });

            dual.send(['treat', 'grass']);
        });

        it('should be possible to mount deep tree structure under a static root', function (done) {
            dual.mount(['phew'], {
                come: {
                    around: function () {
                        done();
                    }
                }
            });

            dual.send(['phew', 'come', 'around']);
        });

        it('should be possible to mount multiple deep tree structure', function (done) {
            var called = [];
            dual.mount([], {
                huh: {
                    pizza: function () {
                        called.push('pizza');
                    }
                }
                , no: {
                    more: function () {
                        assert.deepEqual(called, ['pizza']);
                        done();
                    }
                }
            });

            dual.send(['huh', 'pizza']);
            dual.send(['no', 'more']);
        });

        it('should be possible to mount array', function (done) {
            var called = [];
            dual.mount(['yeah'], [
                function () {
                    called.push('dragon');
                }
                , function () {
                    called.push('drag-on');
                }
            ]);

            dual.send(['yeah']).then(function () {
                assert.deepEqual(['dragon', 'drag-on'], called);
                done();
            });
        });

        it('should be possible to mount nested array', function (done) {
            var called = [];
            dual.mount([], {
                juicy: {
                    apple:[
                        function () {
                            called.push('no');
                        }
                        , function () {
                            called.push('acceptable');
                        }
                    ]
                }
            });

            dual.send(['juicy', 'apple']).then(function () {
                assert.deepEqual(['no', 'acceptable'], called);
                done();
            });
        });

    });

});
<commit_msg>Add constraint to remove hosts via removeListener.<commit_after>/*jslint node: true */
"use strict";

var dualapi = require('../index');
var _ = require('lodash');
var assert = require('assert');

describe('dualapi', function () {

    describe('mount', function () {

        it('should return the api', function (done) {
            var dual = dualapi();
            var called = [];
            dual
                .mount(['big'], function () {
                    called.push('bad');
                })
                .mount(['wolf'], function () {
                    called.push('laser');
                });

            dual.send(['big']);
            dual.send(['wolf'])
            .then(function () {
                assert.deepEqual(['bad', 'laser'], called);
                done();
            });

        });

        it('should be able to mount undefined', function (done) {
            // perhaps not useful, but nothing technically wrong...
            var dual = dualapi();
            dual.mount([void 0], function () {
                done();
            });
            dual.send([void 0], [], 'acting');
        });

        it('should throw exception on empty mount destination', function () {
            var dual = dualapi();
            assert.throws(function () {
                dual.mount([], function () {});
            }, /empty/);
        });

    });

    describe('send', function () {
        it('should return promise value true when an event is matched', function (done) {
            var dual = dualapi();

            dual.mount(['food'], function () {});

            dual.send(['food'])
            .then(function (called) {
                assert(called);
                done();
            });
        });

        it('should return promise value false when an event is matched', function (done) {
            var dual = dualapi();

            dual.mount(['seed'], function () {});

            dual.send(['wad'])
            .then(function (called) {
                assert(!called);
                done();
            });
        });
    });

    describe('mounted host', function () {

        var dual = dualapi();

        it('should be triggered on target message', function (done) {
            dual.mount(['host'], function () {
                done();
            });

            dual.send(['host']);
        });

        it('should be removable via removeListener', function (done) {
            var removable = function () {
                done('should have been removed');
            };
            dual.mount(['guiness'], removable);

            dual.mount(['guiness'], function () {
                done();
            });

            dual.removeListener(['guiness'], removable);
            dual.send(['guiness']);
        });

        it('should be triggered with destination field in context', function (done) {
            dual.mount(['hostA'], function (ctxt) {
                assert.deepEqual(ctxt.to, ['hostA']);
                done();
            });

            dual.send(['hostA']);
        });

        it('should be triggered with from field', function (done) {
            dual.mount(['hostB'], function (ctxt) {
                assert.deepEqual(ctxt.from, ['sourceA']);
                done();
            });
            dual.send(['hostB'], ['sourceA']);
        });

        it('should be triggered with undefined body when no body is provided', function (done) {
            dual.mount(['hostC'], function (ctxt) {
                assert(_.isUndefined(ctxt.body));
                done();
            });

            dual.send(['hostC'], ['sourceB']);
        });

        it('should be triggered with source body when one is provided', function (done) {
            dual.mount(['hostD'], function (ctxt) {
                assert.deepEqual(ctxt.body, {a: 1});
                done();
            });

            dual.send(['hostD'], [], {a: 1});
        });

        it('should NOT be triggered on target message for other hosts', function (done) {
            var received = 0;
            dual.mount(['hostE'], function () {
                received++;
            });
            dual.mount(['host1'], function () {
                assert.equal(received, 0);
                received++;
                done();
            });

            dual.send(['host1']);
        });

    });

    describe('mounted tree', function () {

        var dual = dualapi();

        it('should be possible to mount hosts in a tree structure', function (done) {
            dual.mount([], {
                host: function () {
                    done();
                }
            });

            dual.send(['host']);
        });

        it('should be possible to mount host trees directly', function (done) {
            dual.mount({
                go: function () {
                    done();
                }
            });

            dual.send(['go']);
        });

        it('should be possible to mount hosts in a tree structure below a static trunk', function (done) {
            dual.mount(['cookie'], {
                sword: function () {
                    done();
                }
            });

            dual.send(['cookie', 'sword']);
        });

        it('should be possible to mount deep tree structure', function (done) {
            dual.mount([], {
                treat: {
                    grass: function () {
                        done();
                    }
                }
            });

            dual.send(['treat', 'grass']);
        });

        it('should be possible to mount deep tree structure under a static root', function (done) {
            dual.mount(['phew'], {
                come: {
                    around: function () {
                        done();
                    }
                }
            });

            dual.send(['phew', 'come', 'around']);
        });

        it('should be possible to mount multiple deep tree structure', function (done) {
            var called = [];
            dual.mount([], {
                huh: {
                    pizza: function () {
                        called.push('pizza');
                    }
                }
                , no: {
                    more: function () {
                        assert.deepEqual(called, ['pizza']);
                        done();
                    }
                }
            });

            dual.send(['huh', 'pizza']);
            dual.send(['no', 'more']);
        });

        it('should be possible to mount array', function (done) {
            var called = [];
            dual.mount(['yeah'], [
                function () {
                    called.push('dragon');
                }
                , function () {
                    called.push('drag-on');
                }
            ]);

            dual.send(['yeah']).then(function () {
                assert.deepEqual(['dragon', 'drag-on'], called);
                done();
            });
        });

        it('should be possible to mount nested array', function (done) {
            var called = [];
            dual.mount([], {
                juicy: {
                    apple:[
                        function () {
                            called.push('no');
                        }
                        , function () {
                            called.push('acceptable');
                        }
                    ]
                }
            });

            dual.send(['juicy', 'apple']).then(function () {
                assert.deepEqual(['no', 'acceptable'], called);
                done();
            });
        });

    });

});
<|endoftext|>


<commit_before>import RNTest from './react-native-testkit/'
import React from 'react'
import RNFetchBlob from 'react-native-fetch-blob'

import {
  Text,
  View,
  Platform,
  Dimensions,
  Image,
} from 'react-native';

const fs = RNFetchBlob.fs
const { Assert, Comparer, Info, prop } = RNTest
const describe = RNTest.config({
  group : '0.8.0',
  run : true,
  expand : true,
  timeout : 999999999,
})
const { TEST_SERVER_URL, TEST_SERVER_URL_SSL, FILENAME, DROPBOX_TOKEN, styles } = prop()
const  dirs = RNFetchBlob.fs.dirs

false && describe('upload BASE64 v.s. Storage', (report, done) => {

  let b64data = null
  let storageFile = dirs.DocumentDir + '/benchmark-cache'
  let b64res, storageRes
  let iteration = 50
  let target = `${TEST_SERVER_URL}/public/1mb-dummy`

  RNFetchBlob
    .config({ path : storageFile })
    .fetch('get', target)
    .then((res) => res.readFile('base64'))
    .then((data) => {
      b64data = data
      report(
        <Info key="test data should correct">
          <Text>size of b64data = {data.length}</Text>
        </Info>)
      b64Test()
    })

    // base64 upload benchmark
    function b64Test() {
      let p = Promise.resolve()
      let begin = Date.now()
      let count = 0
      for(let i=0; i< iteration; i++) {
        p = p.then(() => {
          if(++count <iteration){
            report(
              <Info key="benchmark progress" uid="report">
                <Text style={{textAlign:'center'}}>BASE64 {count}/{iteration}</Text>
              </Info>)
            return RNFetchBlob.fetch('POST', `${TEST_SERVER_URL}/echo`, {}, b64data)
          }
          else {
            b64res = Date.now() - begin
            storageTest()
          }
        })
      }
    }

    // storage upload benchmark
    function storageTest() {
      let p = Promise.resolve()
      let begin = Date.now()
      let count = 0
      for(let i=0; i< iteration; i++) {
        p = p.then(() => {
          if(++count < iteration){
            report(
              <Info key="benchmark progress" uid="report">
                <Text style={{textAlign:'center'}}>Storage {count}/{iteration}</Text>
              </Info>)
            return RNFetchBlob.fetch('POST', `${TEST_SERVER_URL}/echo`, {}, RNFetchBlob.wrap(storageFile))
          }
          else {
            storageRes = Date.now() - begin
            summary()
          }
        })
      }
    }

    function summary() {
      report(
        <Info key="BASE64">
          <Text>{`BASE64 ${b64res/iteration} ms/req`}</Text>
        </Info>,
        <Info key="Storage">
          <Text>{`Storage ${storageRes/iteration} ms/req`}</Text>
        </Info>)
      done()
    }

})

false && describe('write file BASE64 v.s. URI', (report, done) => {
  let iteration = 200
  let target = `${TEST_SERVER_URL}/public/6mb-dummy`
  let sourceURI = dirs.DocumentDir + '/benchmark2-source'
  let sourceBASE64 = null
  let b64Res = 0
  let uriRes = 0
  RNFetchBlob.fetch('GET', target)
  .then((res) => {
    sourceBASE64 = res.base64()
    return fs.writeFile(sourceURI, res.base64(), 'base64')
  })
  .then(() => {
    let p = Promise.resolve()
    let begin = Date.now()
    let count = 0
    for(let i=0; i< iteration; i++) {
      p = p.then(() => {
        if(++count < iteration){
          report(
            <Info key="benchmark progress" uid="report2">
              <Text style={{textAlign:'center'}}>BASE64 {count}/{iteration}</Text>
            </Info>)
          return fs.writeFile(dirs.DocumentDir +'/benchmark2-target', sourceBASE64, 'base64')
        }
        else {
          b64Res = Date.now() - begin
          uriTest()
        }
      })
    }
  })

  function uriTest() {
    let p = Promise.resolve()
    let begin = Date.now()
    let count = 0
    for(let i=0; i< iteration; i++) {
      p = p.then(() => {
        if(++count < iteration){
          report(
            <Info key="benchmark progress" uid="report2">
              <Text style={{textAlign:'center'}}>URI {count}/{iteration}</Text>
            </Info>)
          return fs.writeFile(dirs.DocumentDir +'/benchmark2-target', sourceURI, 'uri')
        }
        else {
          uriRes = Date.now() - begin
          summary()
        }
      })
    }
  }

  function summary() {
    report(
      <Info key="BASE64 - writeFile">
        <Text>{`BASE64 ${b64Res/iteration} ms/req`}</Text>
      </Info>,
      <Info key="URI - writeFile">
        <Text>{`URI ${uriRes/iteration} ms/req`}</Text>
      </Info>)
    done()
  }

})

describe('read file benchmark', (report, done) => {

  let iteration = 200
  let target = `${TEST_SERVER_URL}/public/6mb-dummy`
  let source = dirs.DocumentDir + '/benchmark3-source'
  let res = {}
  RNFetchBlob.fetch('GET', target)
  .then((res) => {
    return fs.writeFile(source, res.base64(), 'base64')
  })
  .then(() => {
    test('base64', () => {
      test('ascii', () => {
        test('utf8', summary)
      })
    })
  })

  function test(encode, cb) {
    let p = Promise.resolve()
    let begin = Date.now()
    let count = 0
    for(let i=0; i< iteration; i++) {
      p = p.then(() => {
        if(++count < iteration){
          report(
            <Info key="benchmark progress" uid="report3">
              <Text style={{textAlign:'center'}}>{encode} {count}/{iteration}</Text>
            </Info>)
          return fs.readFile(source, encode)
        }
        else {
          res[encode] = Date.now() - begin
          cb()
        }
      })
    }
  }

  function summary() {
    report(
      <Info key="BASE64 - readFile">
        <Text>{`BASE64 ${res['base64']/iteration} ms/req`}</Text>
      </Info>,
      <Info key="ASCII - readFile">
        <Text>{`ASCII ${res['ascii']/iteration} ms/req`}</Text>
      </Info>,
      <Info key="UTF8 - readFile">
        <Text>{`UTF8 ${res['utf8']/iteration} ms/req`}</Text>
      </Info>)
    done()
  }

})
<commit_msg>Change test case<commit_after>import RNTest from './react-native-testkit/'
import React from 'react'
import RNFetchBlob from 'react-native-fetch-blob'

import {
  Text,
  View,
  Platform,
  Dimensions,
  Image,
} from 'react-native';

const fs = RNFetchBlob.fs
const { Assert, Comparer, Info, prop } = RNTest
const describe = RNTest.config({
  group : '0.8.0',
  run : true,
  expand : true,
  timeout : 999999999,
})
const { TEST_SERVER_URL, TEST_SERVER_URL_SSL, FILENAME, DROPBOX_TOKEN, styles } = prop()
const  dirs = RNFetchBlob.fs.dirs

false && describe('upload BASE64 v.s. Storage', (report, done) => {

  let b64data = null
  let storageFile = dirs.DocumentDir + '/benchmark-cache'
  let b64res, storageRes
  let iteration = 50
  let target = `${TEST_SERVER_URL}/public/1mb-dummy`

  RNFetchBlob
    .config({ path : storageFile })
    .fetch('GET', target)
    .then((res) => res.readFile('base64'))
    .then((data) => {
      b64data = data
      report(
        <Info key="test data should correct">
          <Text>size of b64data = {data.length}</Text>
        </Info>)
      b64Test()
    })

    // base64 upload benchmark
    function b64Test() {
      let p = Promise.resolve()
      let begin = Date.now()
      let count = 0
      for(let i=0; i< iteration; i++) {
        p = p.then(() => {
          if(++count <iteration){
            report(
              <Info key="benchmark progress" uid="report">
                <Text style={{textAlign:'center'}}>BASE64 {count}/{iteration}</Text>
              </Info>)
            return RNFetchBlob.fetch('POST', `${TEST_SERVER_URL}/echo`, {}, b64data)
          }
          else {
            b64res = Date.now() - begin
            storageTest()
          }
        })
      }
    }

    // storage upload benchmark
    function storageTest() {
      let p = Promise.resolve()
      let begin = Date.now()
      let count = 0
      for(let i=0; i< iteration; i++) {
        p = p.then(() => {
          if(++count < iteration){
            report(
              <Info key="benchmark progress" uid="report">
                <Text style={{textAlign:'center'}}>Storage {count}/{iteration}</Text>
              </Info>)
            return RNFetchBlob.fetch('POST', `${TEST_SERVER_URL}/echo`, {}, RNFetchBlob.wrap(storageFile))
          }
          else {
            storageRes = Date.now() - begin
            summary()
          }
        })
      }
    }

    function summary() {
      report(
        <Info key="BASE64">
          <Text>{`BASE64 ${b64res/iteration} ms/req`}</Text>
        </Info>,
        <Info key="Storage">
          <Text>{`Storage ${storageRes/iteration} ms/req`}</Text>
        </Info>)
      done()
    }

})

false && describe('write file BASE64 v.s. URI', (report, done) => {
  let iteration = 200
  let target = `${TEST_SERVER_URL}/public/6mb-dummy`
  let sourceURI = dirs.DocumentDir + '/benchmark2-source'
  let sourceBASE64 = null
  let b64Res = 0
  let uriRes = 0
  RNFetchBlob.fetch('GET', target)
  .then((res) => {
    sourceBASE64 = res.base64()
    return fs.writeFile(sourceURI, res.base64(), 'base64')
  })
  .then(() => {
    let p = Promise.resolve()
    let begin = Date.now()
    let count = 0
    for(let i=0; i< iteration; i++) {
      p = p.then(() => {
        if(++count < iteration){
          report(
            <Info key="benchmark progress" uid="report2">
              <Text style={{textAlign:'center'}}>BASE64 {count}/{iteration}</Text>
            </Info>)
          return fs.writeFile(dirs.DocumentDir +'/benchmark2-target', sourceBASE64, 'base64')
        }
        else {
          b64Res = Date.now() - begin
          uriTest()
        }
      })
    }
  })

  function uriTest() {
    let p = Promise.resolve()
    let begin = Date.now()
    let count = 0
    for(let i=0; i< iteration; i++) {
      p = p.then(() => {
        if(++count < iteration){
          report(
            <Info key="benchmark progress" uid="report2">
              <Text style={{textAlign:'center'}}>URI {count}/{iteration}</Text>
            </Info>)
          return fs.writeFile(dirs.DocumentDir +'/benchmark2-target', sourceURI, 'uri')
        }
        else {
          uriRes = Date.now() - begin
          summary()
        }
      })
    }
  }

  function summary() {
    report(
      <Info key="BASE64 - writeFile">
        <Text>{`BASE64 ${b64Res/iteration} ms/req`}</Text>
      </Info>,
      <Info key="URI - writeFile">
        <Text>{`URI ${uriRes/iteration} ms/req`}</Text>
      </Info>)
    done()
  }

})

describe('read file benchmark', (report, done) => {

  let iteration = 50
  let target = `${TEST_SERVER_URL}/public/1mb-dummy`
  let source = dirs.DocumentDir + '/benchmark3-source'
  let res = {}
  RNFetchBlob.fetch('GET', target)
  .then((res) => {
    return fs.writeFile(source, res.base64(), 'base64')
  })
  .then(() => {
    test('base64', () => {
      test('ascii', () => {
        test('utf8', summary)
      })
    })
  })

  function test(encode, cb) {
    let p = Promise.resolve()
    let begin = Date.now()
    let count = 0
    for(let i=0; i< iteration; i++) {
      p = p.then(() => {
        if(++count < iteration){
          report(
            <Info key="benchmark progress" uid="report3">
              <Text style={{textAlign:'center'}}>{encode} {count}/{iteration}</Text>
            </Info>)
          return fs.readFile(source, encode)
        }
        else {
          res[encode] = Date.now() - begin
          cb()
        }
      })
    }
  }

  function summary() {
    report(
      <Info key="BASE64 - readFile">
        <Text>{`BASE64 ${res['base64']/iteration} ms/req`}</Text>
      </Info>,
      <Info key="ASCII - readFile">
        <Text>{`ASCII ${res['ascii']/iteration} ms/req`}</Text>
      </Info>,
      <Info key="UTF8 - readFile">
        <Text>{`UTF8 ${res['utf8']/iteration} ms/req`}</Text>
      </Info>)
    done()
  }

})
<|endoftext|>


<commit_before>var rUrl = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[.\!\/\\w]*))?)/;

/**
* Fancybox tag
*
* Syntax:
*   {% fancybox /path/to/image [/path/to/thumbnail] [title] %}
*/

hexo.extend.tag.register('fancybox', function(args){
  var original = args.shift(),
    thumbnail = '';

  if (args.length && rUrl.test(args[0])){
    thumbnail = args.shift();
  }

  var title = args.join(' ');

  return '' +
    ''
    '' +
    (title ? '' + title + '' : '');
});<commit_msg>remove fancybox<commit_after><|endoftext|>


<commit_before>var redis = require('redis');
var client = redis.createClient();

var geo = require('../main.js').initialize(client, {
    nativeGeo: false
});

var geoNative = require('../main.js').initialize(client, {
    nativeGeo: true
});

var old = require('geo-proximity').initialize(client);

var Benchmark = require('benchmark');

var lat = 43.646838;
var lon = -79.403723;

var testPoint = {
    latitude: lat,
    longitude: lon
};

var locationRange;
var distance = 0;
var cycleCount = 0;

client.flushall();

var locationSet = {};

locationSet['center_0'] = testPoint;

for (var i = 0; i < 100000; i++) {
    distance = i * (i / 100);
    locationRange = getMinMaxs(lat, lon, distance);

    locationSet['sw_' + distance] = {
        latitude: locationRange.latmin % 90,
        longitude: locationRange.lonmin % 180
    };
    locationSet['nw_' + distance] = {
        latitude: locationRange.latmax % 90,
        longitude: locationRange.lonmin % 180
    };
    locationSet['se_' + distance] = {
        latitude: locationRange.latmin % 90,
        longitude: locationRange.lonmax % 180
    };
    locationSet['ne_' + distance] = {
        latitude: locationRange.latmax % 90,
        longitude: locationRange.lonmax % 180
    };
}

// BENCHMARKING

var suite = new Benchmark.Suite('GeoRedis Performance Test');

suite.on('start', function() {
    action = false;
    cycleCount = 0;
});

suite.on('cycle', function(event) {
    console.log('\n', String(event.target));
});

suite.on('complete', function() {
    var fastest = this.filter('fastest');
    var slowest = this.filter('slowest');

    var fastestSpeed = fastest[0].stats.mean;
    var slowestSpeed = slowest[0].stats.mean;

    // console.log(fastest.pluck('name')[0], 'is the Fastest at ', fastestSpeed, 'per cycle');
    // console.log(slowest.pluck('name')[0], 'is the Slowest at ', slowestSpeed, 'per cycle');

    // console.log(fastest.pluck('name')[0], 'is', slowestSpeed / fastestSpeed, 'times faster than', slowest.pluck('name')[0]);

});

suite.on('error', function(e) {
    console.log('Benchmark ERROR:', e);
});

suite.add({
    name: 'Old Nearby',
    defer: true,
    fn: function(deferred) {
        old.nearby(lat, lon, 50000, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {}
});

suite.add({
    name: 'New Nearby',
    defer: true,
    fn: function(deferred) {
        geo.nearby(testPoint, 50000, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

suite.add({
    name: 'Old Nearby with Coordinates',
    defer: true,
    fn: function(deferred) {
        old.nearby(lat, lon, 50000, {
            values: true
        }, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {}
});

suite.add({
    name: 'New Nearby with Coordinates',
    defer: true,
    fn: function(deferred) {
        geo.nearby(testPoint, 50000, {
            withCoordinates: true
        }, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

geo.addLocations(locationSet, function(err, reply) {

    if (err) throw err;
    suite.run({
        'async': false
    });
});

function getMinMaxs(lat, lon, radius) {

    var latr = radius / 111111;
    var lonr = radius / (111111 * Math.abs(Math.cos(lat)));

    var latmin = lat - latr;
    var latmax = lat + latr;
    var lonmin = lon - lonr;
    var lonmax = lon + lonr;

    return {
        latmin: latmin,
        latmax: latmax,
        lonmin: lonmin,
        lonmax: lonmax
    };
}
<commit_msg>Adding and updating benchmarks.<commit_after>var Benchmark = require('benchmark');
var suite = new Benchmark.Suite('GeoRedis Performance Test');

var redis = require('redis');
var client = redis.createClient();

var geo = require('../main.js').initialize(client, {
    nativeGeo: true,
    zset: 'geo:native'
});

var geoEmulated = geo.addSet().initialize(client, {
    nativeGeo: false,
    zset: 'geo:emulated'
});

var old = require('geo-proximity').initialize(client, {
    zset: 'geo:old'
});

var lat = 43.646838;
var lon = -79.403723;
var testPoint = {
    latitude: lat,
    longitude: lon
};
var locationRange;
var distance = 0;
var cycleCount = 0;
var locationSet = {};
var locationsArray = [];

var i;
var locationName;

// Set Up

client.del('geo:native');
client.del('geo:emulated');
client.del('geo:old');

locationSet.center_0 = testPoint;

for (i = 0; i < 50000; i++) {
    distance = i * (i / 100);
    locationRange = getMinMaxs(lat, lon, distance);

    locationSet['sw_' + distance] = {
        latitude: locationRange.latmin % 85,
        longitude: locationRange.lonmin % 180
    };
    locationSet['nw_' + distance] = {
        latitude: locationRange.latmax % 85,
        longitude: locationRange.lonmin % 180
    };
    locationSet['se_' + distance] = {
        latitude: locationRange.latmin % 85,
        longitude: locationRange.lonmax % 180
    };
    locationSet['ne_' + distance] = {
        latitude: locationRange.latmax % 85,
        longitude: locationRange.lonmax % 180
    };
}

for (locationName in locationSet) {
    locationsArray.push([locationSet[locationName].latitude, locationSet[locationName].longitude, locationName]);
}

// BENCHMARKING

suite.on('start', function() {
    cycleCount = 0;
});

suite.on('cycle', function(event) {
    console.log('\n', String(event.target), '\n');
});

suite.on('complete', function() {
    // var fastest = this.filter('fastest');
    // var slowest = this.filter('slowest');
    // var fastestSpeed = fastest[0].stats.mean;
    // var slowestSpeed = slowest[0].stats.mean;
    // console.log(fastest.pluck('name')[0], 'is the Fastest at ', fastestSpeed, 'per cycle');
    // console.log(slowest.pluck('name')[0], 'is the Slowest at ', slowestSpeed, 'per cycle');
    // console.log(fastest.pluck('name')[0], 'is', slowestSpeed / fastestSpeed, 'times faster than', slowest.pluck('name')[0]);

    process.exit(0);
});

suite.on('error', function(e) {
    console.log('Benchmark ERROR:', e);
});

// BENCHMARKS

//  Sorting and Precision, 500km

suite.add({
    name: 'NEW NATIVE: Nearby and Sort and Precise - 500km',
    defer: true,
    fn: function(deferred) {
        geo.nearby(testPoint, 500000, {
            order: true,
            precise: true
        }, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

suite.add({
    name: 'NEW EMULATED: Nearby and Sort and Precise - 500km',
    defer: true,
    fn: function(deferred) {
        geoEmulated.nearby(testPoint, 500000, {
            order: true,
            precise: true
        }, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

//  Sorting and Precision and Count, 50km

suite.add({
    name: 'NEW NATIVE: Nearby and Sort, Precise and Count - 50km',
    defer: true,
    fn: function(deferred) {
        geo.nearby(testPoint, 50000, {
            order: true,
            precise: true,
            count: 10
        }, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

suite.add({
    name: 'NEW EMULATED: Nearby and Sort, Precise and Count - 50km',
    defer: true,
    fn: function(deferred) {
        geoEmulated.nearby(testPoint, 50000, {
            order: true,
            precise: true,
            count: 10
        }, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

//  Sorting and Precision, 500m

suite.add({
    name: 'NEW NATIVE: Nearby and Sort and Precise - 500m',
    defer: true,
    fn: function(deferred) {
        geo.nearby(testPoint, 500, {
            order: true,
            precise: true
        }, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

suite.add({
    name: 'NEW EMULATED: Nearby and Sort and Precise - 500m',
    defer: true,
    fn: function(deferred) {
        geoEmulated.nearby(testPoint, 500, {
            order: true,
            precise: true
        }, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

//  Sorting and Precision with Distance and Coordinates, 500m

suite.add({
    name: 'NEW NATIVE: Nearby and Sort and Precise, with Distance, Coordinates - 500m',
    defer: true,
    fn: function(deferred) {
        geo.nearby(testPoint, 500, {
            order: true,
            precise: true,
            withDistances: true,
            withCoordinates: true
        }, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

suite.add({
    name: 'NEW EMULATED: Nearby and Sort and Precise, with Distance, Coordinates - 500m',
    defer: true,
    fn: function(deferred) {
        geoEmulated.nearby(testPoint, 500, {
            order: true,
            precise: true,
            withDistances: true,
            withCoordinates: true
        }, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

//  Sorting and Precision with Distance and Coordinates, 5m

suite.add({
    name: 'NEW NATIVE: Nearby and Sort and Precise, with Distance, Coordinates - 5m',
    defer: true,
    fn: function(deferred) {
        geo.nearby(testPoint, 5, {
            order: true,
            precise: true,
            withDistances: true,
            withCoordinates: true
        }, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

suite.add({
    name: 'NEW EMULATED: Nearby and Sort and Precise, with Distance, Coordinates - 5m',
    defer: true,
    fn: function(deferred) {
        geoEmulated.nearby(testPoint, 5, {
            order: true,
            precise: true,
            withDistances: true,
            withCoordinates: true
        }, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

// 500km

suite.add({
    name: 'OLD GEO-PROXIMITY: Nearby - 500km',
    defer: true,
    fn: function(deferred) {
        old.nearby(lat, lon, 500000, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {}
});

suite.add({
    name: 'NEW NATIVE: Nearby - 500km',
    defer: true,
    fn: function(deferred) {
        geo.nearby(testPoint, 500000, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

suite.add({
    name: 'NEW EMULATED: Nearby - 500km',
    defer: true,
    fn: function(deferred) {
        geoEmulated.nearby(testPoint, 500000, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

// 50 km

suite.add({
    name: 'OLD GEO-PROXIMITY: Nearby - 50km',
    defer: true,
    fn: function(deferred) {
        old.nearby(lat, lon, 50000, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {}
});

suite.add({
    name: 'NEW NATIVE: Nearby - 50km',
    defer: true,
    fn: function(deferred) {
        geo.nearby(testPoint, 50000, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

suite.add({
    name: 'NEW EMULATED: Nearby - 50km',
    defer: true,
    fn: function(deferred) {
        geoEmulated.nearby(testPoint, 50000, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

// 5 km

suite.add({
    name: 'OLD GEO-PROXIMITY: Nearby - 5km',
    defer: true,
    fn: function(deferred) {
        old.nearby(lat, lon, 5000, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {}
});

suite.add({
    name: 'NEW NATIVE: Nearby - 5km',
    defer: true,
    fn: function(deferred) {
        geo.nearby(testPoint, 5000, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

suite.add({
    name: 'NEW EMULATED: Nearby - 5km',
    defer: true,
    fn: function(deferred) {
        geoEmulated.nearby(testPoint, 5000, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

// .5 km

suite.add({
    name: 'OLD GEO-PROXIMITY: Nearby - 500m',
    defer: true,
    fn: function(deferred) {
        old.nearby(lat, lon, 500, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {}
});

suite.add({
    name: 'NEW NATIVE: Nearby - 500m',
    defer: true,
    fn: function(deferred) {
        geo.nearby(testPoint, 500, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

suite.add({
    name: 'NEW EMULATED: Nearby - 500m',
    defer: true,
    fn: function(deferred) {
        geoEmulated.nearby(testPoint, 500, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

// 50 km w/ Coordinates

suite.add({
    name: 'OLD GEO-PROXIMITY: Nearby with Coordinates - 50km',
    defer: true,
    fn: function(deferred) {
        old.nearby(lat, lon, 50000, {
            values: true
        }, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {}
});

suite.add({
    name: 'NEW NATIVE: Nearby with Coordinates - 50km',
    defer: true,
    fn: function(deferred) {
        geo.nearby(testPoint, 50000, {
            withCoordinates: true
        }, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

suite.add({
    name: 'NEW EMULATED: Nearby with Coordinates - 50km',
    defer: true,
    fn: function(deferred) {
        geoEmulated.nearby(testPoint, 50000, {
            withCoordinates: true
        }, function(err, replies) {
            if (err) throw err;
            deferred.resolve();
        });
    },
    onStart: function() {
        cycleCount = 0;
        console.log('Starting:', this.name);
    },
    onCycle: function() {
        process.stdout.write('\r Cycle:' + cycleCount++);
    },
    onComplete: function() {

    }
});

// Setup and Run

geo.addLocations(locationSet, function(err, reply) {

    if (err) throw err;

    geoEmulated.addLocations(locationSet, function(erra, replya) {

        if (erra) throw erra;

        old.addLocations(locationsArray, function(errb, replyb) {

            if (errb) throw errb;

            suite.run({
                'async': false
            });
        });
    });
});

function getMinMaxs(latitude, longitude, radius) {

    var latr = radius / 111111;
    var lonr = radius / (111111 * Math.abs(Math.cos(latitude)));

    var latmin = latitude - latr;
    var latmax = latitude + latr;
    var lonmin = longitude - lonr;
    var lonmax = longitude + lonr;

    return {
        latmin: latmin,
        latmax: latmax,
        lonmin: lonmin,
        lonmax: lonmax
    };
}
<|endoftext|>


<commit_before>var navh, sh, sideNavh, sideNavAh;
$(window).resize(function () {
    // Formatting with jQuery
    navh = $(".navbar").innerHeight();
    sh = $(window).height();
    var remainH = Math.max(sh - navh, 512);
    sideNavh = remainH / 5;
    sideNavAh = $(".sideNav a:last").height();
    $(".setMargin").css("margin-top", navh);
    $(".setMargin").css("height", remainH);
    $(".sideNav").css("height", sideNavh);
    $("#profilePic a").css("height", sideNavh);
    $(".sideNav a").css("padding-top", (sideNavh - sideNavAh) / 2);
});
$(window).trigger('resize');

$(document).ready(function () {
    // Default hidden classes
    $(".updateProfileView").hide();
    $(".searchResultView").hide();
    $(".outboxView").hide();
    $(".createEventView").hide();
    $(".updateTeamInfoView").hide();
    $(".updateEventInfoView").hide();

    // Formatting with jQuery
    $(window).trigger('resize');

    // click functions that toggle the view
    // toggle the dashboard view
    $("#updateProfile").click(function () {
        $(".profileView").hide();
        $(".updateProfileView").show();
    });
    // toggle the explore view
    $("#searchButton").click(function(){
        $(".recommendationView").hide();
        $(".searchResultView").show();
    });

    // toggle the message view
    $("#inboxButton").click(function(){
        $("#inboxButton").attr("class", "active");
        $("#outboxButton").attr("class", "");
        $(".outboxView").hide();
        $(".inboxView").show();
    });
    $("#outboxButton").click(function(){
        $("#inboxButton").attr("class", "");
        $("#outboxButton").attr("class", "active");
        $(".inboxView").hide();
        $(".outboxView").show();
    });
    $(".inboxView .messageBrief").click(function(){
        $(".inboxView .messageBrief.active").attr("class", "messageBrief");
        $(this).attr("class", "messageBrief active");
    });
    $(".outboxView .messageBrief").click(function(){
        $(".outboxView .messageBrief.active").attr("class", "messageBrief");
        $(this).attr("class", "messageBrief active");
    });
    // toggle the event view
    $("#createNewEvent").click(function(){
        $(".eventView").hide();
        $(".createEventView").show();
    });
    // toggle the team management view
    $("#updateTeamInfo").click(function() {
        $(".teamInfoView").hide();
        $(".updateTeamInfoView").show();
    });
    $("#updateEventInfo").click(function() {
        $(".eventInfoView").hide();
        $(".updateEventInfoView").show();
    });
    $(".fa-times").click(function() {
        $(this).parent().hide();
    });
});

angular.module('teamform-dashboard-app', ['firebase'])
.controller('DashboardCtrl', ['$scope', '$firebaseObject', '$firebaseArray', function($scope, $firebaseObject, $firebaseArray) {

    initializeFirebase();
    uid = getCookie("uid");

    $scope.username;
    $scope.email;
    $scope.photoUrl;
    $scope.gender;
    $scope.birthday;
    $scope.languages;
    $scope.education;
    $scope.skills
    $scope.intoduction;

    //////////////////////////////////////////////////////////////SCOPE FUNCTIONS

    $scope.loadFunc = function() {
        if(uid != "")
        {
            var refPath = "Users/" + getURLParameter("q") + uid;
            retrieveOnceFirebase(firebase, refPath, function(data) {

                if ( data.child("Name").val() != null ) {
                    $scope.username = data.child("Name").val();
                } else {
                    $scope.username = "";
                }

                if ( data.child("Email").val() != null ) {
                    $scope.email = data.child("Email").val();
                } else {
                    $scope.email = "";
                }

                if ( data.child("Gender").val() != null ) {
                    $scope.gender = data.child("Gender").val();
                } else {
                    $scope.gender = "";
                }

                if ( data.child("Birthday").val() != null ) {
                    $scope.birthday = data.child("Birthday").val();
                } else {
                    $scope.birthday = "";
                }

                if ( data.child("Languages").val() != null ) {
                    $scope.languages = data.child("Languages").val();
                } else {
                    $scope.languages = "";
                }

                if ( data.child("Country").val() != null ) {
                    $scope.country = data.child("Country").val();
                } else {
                    $scope.country = "";
                }

                if ( data.child("City").val() != null ) {
                    $scope.city = data.child("City").val();
                } else {
                    $scope.city = "";
                }

                if ( data.child("Education").val() != null ) {
                    $scope.education = data.child("Education").val();
                } else {
                    $scope.education = "";
                }

                if ( data.child("Skills").val() != null ) {
                    $scope.skills = data.child("Skills").val();
                } else {
                    $scope.skills = "";
                }

                if ( data.child("Introduction").val() != null ) {
                    $scope.introduction = data.child("Introduction").val();
                } else {
                    $scope.introduction = "";
                }

                $scope.$apply();
            });
        }
    }

    $scope.UpdateUser = function()
    {
        var userInfo = {};
        userInfo.Name = $scope.username;
        userInfo.Email = $scope.email;
        userInfo.Birthday = $scope.birthday;
        userInfo.Languages = $scope.languages;
        userInfo.Country = $scope.country;
        userInfo.City = $scope.city;
        userInfo.Skills = $scope.skills;
        userInfo.Introduction = $scope.introduction;
        userInfo.Gender = $scope.gender;
        userInfo.Education = $scope.Education;

        var refPath = "Users/" + getURLParameter("q") + uid;
        var ref = firebase.database().ref(refPath);

        ref.set(userInfo, function(){
            window.location.href= "dashboard.html";
        }).catch(function(error) {
            console.log(error);
        });
    }

    //////////////////////////////////////////////////END FUNCTIONS

    $scope.loadFunc();

}]);

<commit_msg>fixed typo<commit_after>var navh, sh, sideNavh, sideNavAh;
$(window).resize(function () {
    // Formatting with jQuery
    navh = $(".navbar").innerHeight();
    sh = $(window).height();
    var remainH = Math.max(sh - navh, 512);
    sideNavh = remainH / 5;
    sideNavAh = $(".sideNav a:last").height();
    $(".setMargin").css("margin-top", navh);
    $(".setMargin").css("height", remainH);
    $(".sideNav").css("height", sideNavh);
    $("#profilePic a").css("height", sideNavh);
    $(".sideNav a").css("padding-top", (sideNavh - sideNavAh) / 2);
});
$(window).trigger('resize');

$(document).ready(function () {
    // Default hidden classes
    $(".updateProfileView").hide();
    $(".searchResultView").hide();
    $(".outboxView").hide();
    $(".createEventView").hide();
    $(".updateTeamInfoView").hide();
    $(".updateEventInfoView").hide();

    // Formatting with jQuery
    $(window).trigger('resize');

    // click functions that toggle the view
    // toggle the dashboard view
    $("#updateProfile").click(function () {
        $(".profileView").hide();
        $(".updateProfileView").show();
    });
    // toggle the explore view
    $("#searchButton").click(function(){
        $(".recommendationView").hide();
        $(".searchResultView").show();
    });

    // toggle the message view
    $("#inboxButton").click(function(){
        $("#inboxButton").attr("class", "active");
        $("#outboxButton").attr("class", "");
        $(".outboxView").hide();
        $(".inboxView").show();
    });
    $("#outboxButton").click(function(){
        $("#inboxButton").attr("class", "");
        $("#outboxButton").attr("class", "active");
        $(".inboxView").hide();
        $(".outboxView").show();
    });
    $(".inboxView .messageBrief").click(function(){
        $(".inboxView .messageBrief.active").attr("class", "messageBrief");
        $(this).attr("class", "messageBrief active");
    });
    $(".outboxView .messageBrief").click(function(){
        $(".outboxView .messageBrief.active").attr("class", "messageBrief");
        $(this).attr("class", "messageBrief active");
    });
    // toggle the event view
    $("#createNewEvent").click(function(){
        $(".eventView").hide();
        $(".createEventView").show();
    });
    // toggle the team management view
    $("#updateTeamInfo").click(function() {
        $(".teamInfoView").hide();
        $(".updateTeamInfoView").show();
    });
    $("#updateEventInfo").click(function() {
        $(".eventInfoView").hide();
        $(".updateEventInfoView").show();
    });
    $(".fa-times").click(function() {
        $(this).parent().hide();
    });
});

angular.module('teamform-dashboard-app', ['firebase'])
.controller('DashboardCtrl', ['$scope', '$firebaseObject', '$firebaseArray', function($scope, $firebaseObject, $firebaseArray) {

    initializeFirebase();
    uid = getCookie("uid");

    $scope.username;
    $scope.email;
    $scope.photoUrl;
    $scope.gender;
    $scope.birthday;
    $scope.languages;
    $scope.education;
    $scope.skills
    $scope.intoduction;

    //////////////////////////////////////////////////////////////SCOPE FUNCTIONS

    $scope.loadFunc = function() {
        if(uid != "")
        {
            var refPath = "Users/" + getURLParameter("q") + uid;
            retrieveOnceFirebase(firebase, refPath, function(data) {

                if ( data.child("Name").val() != null ) {
                    $scope.username = data.child("Name").val();
                } else {
                    $scope.username = "";
                }

                if ( data.child("Email").val() != null ) {
                    $scope.email = data.child("Email").val();
                } else {
                    $scope.email = "";
                }

                if ( data.child("Gender").val() != null ) {
                    $scope.gender = data.child("Gender").val();
                } else {
                    $scope.gender = "";
                }

                if ( data.child("Birthday").val() != null ) {
                    $scope.birthday = data.child("Birthday").val();
                } else {
                    $scope.birthday = "";
                }

                if ( data.child("Languages").val() != null ) {
                    $scope.languages = data.child("Languages").val();
                } else {
                    $scope.languages = "";
                }

                if ( data.child("Country").val() != null ) {
                    $scope.country = data.child("Country").val();
                } else {
                    $scope.country = "";
                }

                if ( data.child("City").val() != null ) {
                    $scope.city = data.child("City").val();
                } else {
                    $scope.city = "";
                }

                if ( data.child("Education").val() != null ) {
                    $scope.education = data.child("Education").val();
                } else {
                    $scope.education = "";
                }

                if ( data.child("Skills").val() != null ) {
                    $scope.skills = data.child("Skills").val();
                } else {
                    $scope.skills = "";
                }

                if ( data.child("Introduction").val() != null ) {
                    $scope.introduction = data.child("Introduction").val();
                } else {
                    $scope.introduction = "";
                }

                $scope.$apply();
            });
        }
    }

    $scope.UpdateUser = function()
    {
        var userInfo = {};
        userInfo.Name = $scope.username;
        userInfo.Email = $scope.email;
        userInfo.Birthday = $scope.birthday;
        userInfo.Languages = $scope.languages;
        userInfo.Country = $scope.country;
        userInfo.City = $scope.city;
        userInfo.Skills = $scope.skills;
        userInfo.Introduction = $scope.introduction;
        userInfo.Gender = $scope.gender;
        userInfo.Education = $scope.education;

        var refPath = "Users/" + getURLParameter("q") + uid;
        var ref = firebase.database().ref(refPath);

        ref.set(userInfo, function(){
            window.location.href= "dashboard.html";
        }).catch(function(error) {
            console.log(error);
        });
    }

    //////////////////////////////////////////////////END FUNCTIONS

    $scope.loadFunc();

}]);

<|endoftext|>


<commit_before>
function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
        loginUserIntoApplication();
    } else if (response.status === 'not_authorized') {
        logout();
    } else {
        logout();
    }
}

function subscribeToEvents() {
    FB.Event.subscribe('auth.logout', logout_event);
}

function checkLoginState() {
    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
    });
}

window.fbAsyncInit = function() {
    FB.init({
        appId      : '177757152673157',
        cookie     : true,  // enable cookies to allow the server to access
                            // the session
        xfbml      : true,  // parse social plugins on this page
        version    : 'v2.5' // use graph api version 2.5
    });

    // Now that we've initialized the JavaScript SDK, we call
    // FB.getLoginStatus().  This function gets the state of the
    // person visiting this page and can return one of three states to
    // the callback you provide.  They can be:
    //
    // 1. Logged into your app ('connected')
    // 2. Logged into Facebook, but not your app ('not_authorized')
    // 3. Not logged into Facebook and can't tell if they are logged into
    //    your app or not.
    //
    // These three cases are handled in the callback function.

    if(localStorage.getItem("id")){
        checkLoginState();
    }else{
        performLogoutActions();
    }

};

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

function loginUserIntoApplication() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me',{ fields: 'name, email' }, function(response) {
        console.log('Successful login for: ' + response.name + " "+response.email);
        makeCorsRequest("GET", "https://ivebeenthereapi-matyapav.rhcloud.com/users", null, function (responseText) {
            var userIdByEmail = null;
            var alreadyExists = false;
            if(responseText){
                var users = JSON.parse(responseText);
                alreadyExists = checkIfUserAlreadyExists(users, response.email);
            }
            if(!alreadyExists){
                var data = "name="+response.name+"&email="+response.email;
                makeCorsRequest("POST", "https://ivebeenthereapi-matyapav.rhcloud.com/users", data, function (responseText) {
                    console.log(JSON.parse(responseText).message);
                    userIdByEmail = JSON.parse(responseText).id;
                    saveUserIdInLocalStorage(userIdByEmail);
                });
            }else{
                userIdByEmail = users[id]._id;
                saveUserIdInLocalStorage(userIdByEmail);
            }

            console.log(localStorage.getItem("id"));
            performLoginActions();
            document.getElementById('status').innerHTML =
                'Přihlášen jako,  ' + response.name + '!';

        });

    });
}

function checkIfUserAlreadyExists(users, email){
    for (id in users){
        if(users[id].email == email){
            return true;
        };
    }
    return false;
}

function  showUserInfo() {
    var userid = localStorage.getItem('id');
    if(userid){
        makeCorsRequest('GET', 'https://ivebeenthereapi-matyapav.rhcloud.com/users/'+userid, null, function (responseText) {
            initModal();
            var modalInfo = document.getElementById("modal-info");
            modalInfo.innerHTML = "Name: "+JSON.parse(responseText).name+"
 Email: "+JSON.parse(responseText).email;
        })
    }

}

function saveUserIdInLocalStorage(user_id){
    // Check browser support
    if (typeof(Storage) !== "undefined") {
        // Store
        localStorage.setItem("id", user_id);

    } else {
        document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
    }
}

function fblogin() {
    FB.login(function (response) {
        if (response.authResponse) {
            checkLoginState();
        } else {
            console.log('User cancelled login or did not fully authorize.');
        }
    }, { scope: ['email', 'user_friends'] });
}

function logout(){
    if(confirm("Do you really want to logout?")){
        localStorage.removeItem("id");
        performLogoutActions();
    }
}

function getFriends(){
    FB.api('me/friends', { fields: 'id, first_name,picture', limit: 6 },function(response){
        var data = response.data;
        data.forEach(function (friend) {
            var photoUrl = friend.data.url;
            document.getElementById("place-friends").innerHTML+= ""
        })
        console.log(response);
    });
}

function performLoginActions() {
    document.getElementById('login_btn').style = "display: none";
    document.getElementById('logout_btn').style = "display: block";
    if(somePlaceIsSelected){
        document.getElementById('actions').style = "visibility: visible";
    }
    document.getElementById('radius-input').addEventListener('change', getNearbyLocations);
    getNearbyLocations();
}

function performLogoutActions(){
    document.getElementById('status').innerHTML = 'Přihlašte se do této aplikace.';
    document.getElementById('login_btn').style = "display: block";
    document.getElementById('logout_btn').style = "display: none";
    document.getElementById('actions').style = "visibility: hidden";
    //clear previous markers
    clearMap();
    //unselect selected place
    clearTable();
}

var logout_event = function(response) {
    console.log("logout_event");
    console.log(response.status);
    console.log(response);
    checkLoginState();
}
<commit_msg>Get friends #4<commit_after>
function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
        loginUserIntoApplication();
    } else if (response.status === 'not_authorized') {
        logout();
    } else {
        logout();
    }
}

function subscribeToEvents() {
    FB.Event.subscribe('auth.logout', logout_event);
}

function checkLoginState() {
    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
    });
}

window.fbAsyncInit = function() {
    FB.init({
        appId      : '177757152673157',
        cookie     : true,  // enable cookies to allow the server to access
                            // the session
        xfbml      : true,  // parse social plugins on this page
        version    : 'v2.5' // use graph api version 2.5
    });

    // Now that we've initialized the JavaScript SDK, we call
    // FB.getLoginStatus().  This function gets the state of the
    // person visiting this page and can return one of three states to
    // the callback you provide.  They can be:
    //
    // 1. Logged into your app ('connected')
    // 2. Logged into Facebook, but not your app ('not_authorized')
    // 3. Not logged into Facebook and can't tell if they are logged into
    //    your app or not.
    //
    // These three cases are handled in the callback function.

    if(localStorage.getItem("id")){
        checkLoginState();
    }else{
        performLogoutActions();
    }

};

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

function loginUserIntoApplication() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me',{ fields: 'name, email' }, function(response) {
        console.log('Successful login for: ' + response.name + " "+response.email);
        makeCorsRequest("GET", "https://ivebeenthereapi-matyapav.rhcloud.com/users", null, function (responseText) {
            var userIdByEmail = null;
            var alreadyExists = false;
            if(responseText){
                var users = JSON.parse(responseText);
                alreadyExists = checkIfUserAlreadyExists(users, response.email);
            }
            if(!alreadyExists){
                var data = "name="+response.name+"&email="+response.email;
                makeCorsRequest("POST", "https://ivebeenthereapi-matyapav.rhcloud.com/users", data, function (responseText) {
                    console.log(JSON.parse(responseText).message);
                    userIdByEmail = JSON.parse(responseText).id;
                    saveUserIdInLocalStorage(userIdByEmail);
                });
            }else{
                userIdByEmail = users[id]._id;
                saveUserIdInLocalStorage(userIdByEmail);
            }

            console.log(localStorage.getItem("id"));
            performLoginActions();
            document.getElementById('status').innerHTML =
                'Přihlášen jako,  ' + response.name + '!';

        });

    });
}

function checkIfUserAlreadyExists(users, email){
    for (id in users){
        if(users[id].email == email){
            return true;
        };
    }
    return false;
}

function  showUserInfo() {
    var userid = localStorage.getItem('id');
    if(userid){
        makeCorsRequest('GET', 'https://ivebeenthereapi-matyapav.rhcloud.com/users/'+userid, null, function (responseText) {
            initModal();
            var modalInfo = document.getElementById("modal-info");
            modalInfo.innerHTML = "Name: "+JSON.parse(responseText).name+"
 Email: "+JSON.parse(responseText).email;
        })
    }

}

function saveUserIdInLocalStorage(user_id){
    // Check browser support
    if (typeof(Storage) !== "undefined") {
        // Store
        localStorage.setItem("id", user_id);

    } else {
        document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
    }
}

function fblogin() {
    FB.login(function (response) {
        if (response.authResponse) {
            checkLoginState();
        } else {
            console.log('User cancelled login or did not fully authorize.');
        }
    }, { scope: ['email', 'user_friends'] });
}

function logout(){
    if(confirm("Do you really want to logout?")){
        localStorage.removeItem("id");
        performLogoutActions();
    }
}

function getFriends(){
    FB.api('me/friends', { fields: 'id, first_name,picture', limit: 6 },function(response){
        console.log(response);
        var data = response.data;
        data.forEach(function (friend) {
            var photoUrl = friend.picture.data.url;
            document.getElementById("place-friends").innerHTML+= ""
        })

    });
}

function performLoginActions() {
    document.getElementById('login_btn').style = "display: none";
    document.getElementById('logout_btn').style = "display: block";
    if(somePlaceIsSelected){
        document.getElementById('actions').style = "visibility: visible";
    }
    document.getElementById('radius-input').addEventListener('change', getNearbyLocations);
    getNearbyLocations();
}

function performLogoutActions(){
    document.getElementById('status').innerHTML = 'Přihlašte se do této aplikace.';
    document.getElementById('login_btn').style = "display: block";
    document.getElementById('logout_btn').style = "display: none";
    document.getElementById('actions').style = "visibility: hidden";
    //clear previous markers
    clearMap();
    //unselect selected place
    clearTable();
}

var logout_event = function(response) {
    console.log("logout_event");
    console.log(response.status);
    console.log(response);
    checkLoginState();
}
<|endoftext|>


<commit_before>var calc = require('../src/calc.js');

describe('The add method of the string calculator', function () {
	it('should return 0 if string is empty', function () {
		expect(calc.add()).toBe(0);
	});

});<commit_msg>Should return 1 if string is 1<commit_after>var calc = require('../src/calc.js');

describe('The add method of the string calculator', function () {
	it('should return 0 if string is empty', function () {
		expect(calc.add()).toBe(0);
	});

	it('should return 0 if string is ', function () {
		expect(calc.add("")).toBe(0);
	});

	it('should return 1 if string is 1', function () {
		expect(calc.add(1)).toBe(1);
	});

});<|endoftext|>


<commit_before>var navh, sh, sideNavh, sideNavAh;
$(window).resize(function () {
    // Formatting with jQuery
    navh = $(".navbar").innerHeight();
    sh = $(window).height();
    var remainH = Math.max(sh - navh, 512);
    sideNavh = remainH / 5;
    sideNavAh = $(".sideNav a:last").height();
    $(".setMargin").css("margin-top", navh);
    $(".setMargin").css("height", remainH);
    $(".sideNav").css("height", sideNavh);
    $("#profilePic a").css("height", sideNavh);
    $(".sideNav a").css("padding-top", (sideNavh - sideNavAh) / 2);
});
$(window).trigger('resize');

$(document).ready(function () {
    // Default hidden classes
    $(".updateProfileView").hide();
    $(".searchResultView").hide();
    $(".outboxView").hide();
    $(".createEventView").hide();
    $(".updateTeamInfoView").hide();
    $(".updateEventInfoView").hide();

    // Formatting with jQuery
    $(window).trigger('resize');

    // click functions that toggle the view
    // toggle the dashboard view
    $("#updateProfile").click(function () {
        $(".profileView").hide();
        $(".updateProfileView").show();
    });
    // toggle the explore view
    $("#searchButton").click(function(){
        $(".recommendationView").hide();
        $(".searchResultView").show();
    });

    // toggle the message view
    $("#inboxButton").click(function(){
        $("#inboxButton").attr("class", "active");
        $("#outboxButton").attr("class", "");
        $(".outboxView").hide();
        $(".inboxView").show();
    });
    $("#outboxButton").click(function(){
        $("#inboxButton").attr("class", "");
        $("#outboxButton").attr("class", "active");
        $(".inboxView").hide();
        $(".outboxView").show();
    });
    $(".inboxView .messageBrief").click(function(){
        $(".inboxView .messageBrief.active").attr("class", "messageBrief");
        $(this).attr("class", "messageBrief active");
    });
    $(".outboxView .messageBrief").click(function(){
        $(".outboxView .messageBrief.active").attr("class", "messageBrief");
        $(this).attr("class", "messageBrief active");
    });
    // toggle the event view
    $("#createNewEvent").click(function(){
        $(".eventView").hide();
        $(".createEventView").show();
    });
    // toggle the team management view
    $("#updateTeamInfo").click(function() {
        $(".teamInfoView").hide();
        $(".updateTeamInfoView").show();
    });
    $("#updateEventInfo").click(function() {
        $(".eventInfoView").hide();
        $(".updateEventInfoView").show();
    });
    $(".fa-times").click(function() {
        $(this).parent().hide();
    });
});

angular.module('teamform-dashboard-app', ['firebase'])
.controller('DashboardCtrl', ['$scope', '$firebaseObject', '$firebaseArray', function($scope, $firebaseObject, $firebaseArray) {

    initializeFirebase();
    uid = getCookie("uid");

    $scope.username;
    $scope.email;
    $scope.photoUrl;
    $scope.gender;
    $scope.birthday;
    $scope.birthdayString;
    $scope.languages;
    $scope.education;
    $scope.skills
    $scope.skillsRaw;
    $scope.intoduction;
    $scope.intoductionRaw;

    //////////////////////////////////////////////////////////////SCOPE FUNCTIONS

    $scope.loadFunc = function() {
        if(uid != "")
        {
            var refPath = "Users/" + getURLParameter("q") + uid;
            retrieveOnceFirebase(firebase, refPath, function(data) {

                if ( data.child("Name").val() != null ) {
                    $scope.username = data.child("Name").val();
                } else {
                    $scope.username = "";
                }

                if ( data.child("Email").val() != null ) {
                    $scope.email = data.child("Email").val();
                } else {
                    $scope.email = "";
                }

                if ( data.child("Gender").val() != null ) {
                    $scope.gender = data.child("Gender").val();
                } else {
                    $scope.gender = "";
                }

                if ( data.child("Birthday").val() != null ) {
                    $scope.birthday = data.child("Birthday").val();
                    birthDate = new Date($scope.birthday);
                    $scope.birthdayString = birthDate.toDateString();
                } else {
                    $scope.birthday = "";
                }

                if ( data.child("Languages").val() != null ) {
                    $scope.languagesRaw = data.child("Languages").val();
                    var temp = "";
                    temp += $scope.languagesRaw;
                    temp = temp.replace("[","");
                    $scope.languages = temp.replace("\"","");
                } else {
                    $scope.languages = "";
                }

                if ( data.child("Country").val() != null ) {
                    $scope.country = data.child("Country").val();
                } else {
                    $scope.country = "";
                }

                if ( data.child("City").val() != null ) {
                    $scope.city = data.child("City").val();
                } else {
                    $scope.city = "";
                }

                if ( data.child("Education").val() != null ) {
                    $scope.education = data.child("Education").val();
                } else {
                    $scope.education = "";
                }

                if ( data.child("Skills").val() != null ) {
                    $scope.skillsRaw = data.child("Skills").val();
                    var temp = "";
                    temp += $scope.skillsRaw;
                    temp = temp.replace("[","");
                    $scope.skills = temp.replace("\"","");
                } else {
                    $scope.skills = "";
                }

                if ( data.child("Introduction").val() != null ) {
                    $scope.introduction = data.child("Introduction").val();
                } else {
                    $scope.introduction = "";
                }

                $scope.$apply();
            });
        }
    }

    $scope.UpdateUser = function()
    {
        var userInfo = {};
        userInfo.Name = $scope.username;
        userInfo.Email = $scope.email;

        birthDate = new Date($scope.birthdayString);
        $scope.birthday = birthDate.getTime();
        userInfo.Birthday = $scope.birthday;

        userInfo.Languages = $scope.languages;
        userInfo.Country = $scope.country;
        userInfo.City = $scope.city;
        userInfo.Skills = $scope.skills;
        userInfo.Introduction = $scope.introduction;
        userInfo.Gender = $scope.gender;
        userInfo.Education = $scope.education;

        var refPath = "Users/" + getURLParameter("q") + uid;
        var ref = firebase.database().ref(refPath);

        ref.set(userInfo, function(){
            window.location.href= "dashboard.html";
        }).catch(function(error) {
            console.log(error);
        });
    }

    //////////////////////////////////////////////////END FUNCTIONS

    $scope.loadFunc();

}]);

<commit_msg>added space between vars<commit_after>var navh, sh, sideNavh, sideNavAh;
$(window).resize(function () {
    // Formatting with jQuery
    navh = $(".navbar").innerHeight();
    sh = $(window).height();
    var remainH = Math.max(sh - navh, 512);
    sideNavh = remainH / 5;
    sideNavAh = $(".sideNav a:last").height();
    $(".setMargin").css("margin-top", navh);
    $(".setMargin").css("height", remainH);
    $(".sideNav").css("height", sideNavh);
    $("#profilePic a").css("height", sideNavh);
    $(".sideNav a").css("padding-top", (sideNavh - sideNavAh) / 2);
});
$(window).trigger('resize');

$(document).ready(function () {
    // Default hidden classes
    $(".updateProfileView").hide();
    $(".searchResultView").hide();
    $(".outboxView").hide();
    $(".createEventView").hide();
    $(".updateTeamInfoView").hide();
    $(".updateEventInfoView").hide();

    // Formatting with jQuery
    $(window).trigger('resize');

    // click functions that toggle the view
    // toggle the dashboard view
    $("#updateProfile").click(function () {
        $(".profileView").hide();
        $(".updateProfileView").show();
    });
    // toggle the explore view
    $("#searchButton").click(function(){
        $(".recommendationView").hide();
        $(".searchResultView").show();
    });

    // toggle the message view
    $("#inboxButton").click(function(){
        $("#inboxButton").attr("class", "active");
        $("#outboxButton").attr("class", "");
        $(".outboxView").hide();
        $(".inboxView").show();
    });
    $("#outboxButton").click(function(){
        $("#inboxButton").attr("class", "");
        $("#outboxButton").attr("class", "active");
        $(".inboxView").hide();
        $(".outboxView").show();
    });
    $(".inboxView .messageBrief").click(function(){
        $(".inboxView .messageBrief.active").attr("class", "messageBrief");
        $(this).attr("class", "messageBrief active");
    });
    $(".outboxView .messageBrief").click(function(){
        $(".outboxView .messageBrief.active").attr("class", "messageBrief");
        $(this).attr("class", "messageBrief active");
    });
    // toggle the event view
    $("#createNewEvent").click(function(){
        $(".eventView").hide();
        $(".createEventView").show();
    });
    // toggle the team management view
    $("#updateTeamInfo").click(function() {
        $(".teamInfoView").hide();
        $(".updateTeamInfoView").show();
    });
    $("#updateEventInfo").click(function() {
        $(".eventInfoView").hide();
        $(".updateEventInfoView").show();
    });
    $(".fa-times").click(function() {
        $(this).parent().hide();
    });
});

angular.module('teamform-dashboard-app', ['firebase'])
.controller('DashboardCtrl', ['$scope', '$firebaseObject', '$firebaseArray', function($scope, $firebaseObject, $firebaseArray) {

    initializeFirebase();
    uid = getCookie("uid");

    $scope.username;
    $scope.email;
    $scope.photoUrl;
    $scope.gender;
    $scope.birthday;
    $scope.birthdayString;
    $scope.languages;
    $scope.education;
    $scope.skills
    $scope.skillsRaw;
    $scope.intoduction;
    $scope.intoductionRaw;

    //////////////////////////////////////////////////////////////SCOPE FUNCTIONS

    $scope.loadFunc = function() {
        if(uid != "")
        {
            var refPath = "Users/" + getURLParameter("q") + uid;
            retrieveOnceFirebase(firebase, refPath, function(data) {

                if ( data.child("Name").val() != null ) {
                    $scope.username = data.child("Name").val();
                } else {
                    $scope.username = "";
                }

                if ( data.child("Email").val() != null ) {
                    $scope.email = data.child("Email").val();
                } else {
                    $scope.email = "";
                }

                if ( data.child("Gender").val() != null ) {
                    $scope.gender = data.child("Gender").val();
                } else {
                    $scope.gender = "";
                }

                if ( data.child("Birthday").val() != null ) {
                    $scope.birthday = data.child("Birthday").val();
                    birthDate = new Date($scope.birthday);
                    $scope.birthdayString = birthDate.toDateString();
                } else {
                    $scope.birthday = "";
                }

                if ( data.child("Languages").val() != null ) {
                    $scope.languagesRaw = data.child("Languages").val();
                    var temp = "";
                    temp += $scope.languagesRaw;
                    temp = temp.replace("[","");
                    temp = temp.replace(",",", ");
                    $scope.languages = temp.replace("\"","");
                } else {
                    $scope.languages = "";
                }

                if ( data.child("Country").val() != null ) {
                    $scope.country = data.child("Country").val();
                } else {
                    $scope.country = "";
                }

                if ( data.child("City").val() != null ) {
                    $scope.city = data.child("City").val();
                } else {
                    $scope.city = "";
                }

                if ( data.child("Education").val() != null ) {
                    $scope.education = data.child("Education").val();
                } else {
                    $scope.education = "";
                }

                if ( data.child("Skills").val() != null ) {
                    $scope.skillsRaw = data.child("Skills").val();
                    var temp = "";
                    temp += $scope.skillsRaw;
                    temp = temp.replace("[","");
                    temp = temp.replace(",",", ");
                    $scope.skills = temp.replace("\"","");
                } else {
                    $scope.skills = "";
                }

                if ( data.child("Introduction").val() != null ) {
                    $scope.introduction = data.child("Introduction").val();
                } else {
                    $scope.introduction = "";
                }

                $scope.$apply();
            });
        }
    }

    $scope.UpdateUser = function()
    {
        var userInfo = {};
        userInfo.Name = $scope.username;
        userInfo.Email = $scope.email;

        birthDate = new Date($scope.birthdayString);
        $scope.birthday = birthDate.getTime();
        userInfo.Birthday = $scope.birthday;

        userInfo.Languages = $scope.languages;
        userInfo.Country = $scope.country;
        userInfo.City = $scope.city;
        userInfo.Skills = $scope.skills;
        userInfo.Introduction = $scope.introduction;
        userInfo.Gender = $scope.gender;
        userInfo.Education = $scope.education;

        var refPath = "Users/" + getURLParameter("q") + uid;
        var ref = firebase.database().ref(refPath);

        ref.set(userInfo, function(){
            window.location.href= "dashboard.html";
        }).catch(function(error) {
            console.log(error);
        });
    }

    //////////////////////////////////////////////////END FUNCTIONS

    $scope.loadFunc();

}]);

<|endoftext|>