<commit_before>/**
 * @author Jonathan Cardoso Machado
 * @license MIT
 * @copyright 2015, Jonathan Cardoso Machado
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * Example showing how to use the Multi handle to make async requests.
 */
var Curl = require( '../lib/Curl' ),
    Easy = require( '../lib/Easy' ),
    Multi= require( '../lib/Multi' ),
    urls = [
        'http://google.com', 'http://bing.com',
        'http://msn.com', 'http://ask.com/'
    ],
    multi = new Multi(),
    finished = 0,
    handles = [],
    handle;

multi.onMessage(function( err, handle, errCode ) {

    if ( err ) {
        console.log( err );
    }

    var responseCode = handle.getInfo( 'RESPONSE_CODE' ).data;

    console.log( '# of handles active: ' + multi.getCount() );
    console.log( urls[ handles.indexOf( handle ) ] + ' returned response code: ' + responseCode );

    multi.removeHandle( handle );
    handle.close();

    if ( ++finished == urls.length ) {

        console.log( 'Finished all requests!' );
        multi.close();
    }
});

for ( var i = 0, len = urls.length; i < len; i++ ) {

    handle = new Easy();
    handle.setOpt( 'URL', urls[i] );
    handle.setOpt( 'FOLLOWLOCATION', true );

    handles.push( handle );

    multi.addHandle( handle );
}
<commit_msg>improved multi-interface example showing how to get the response body of the requests.<commit_after>/**
 * @author Jonathan Cardoso Machado
 * @license MIT
 * @copyright 2015, Jonathan Cardoso Machado
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * Example showing how to use the Multi handle to make async requests.
 */
var Curl = require( '../lib/Curl' ),
    Easy = require( '../lib/Easy' ),
    Multi= require( '../lib/Multi' ),
    urls = [
        'http://google.com', 'http://bing.com',
        'http://msn.com', 'http://ask.com/'
    ],
    multi       = new Multi(),
    finished    = 0,
    handles     = [],
    handlesData = [],
    handle;

multi.onMessage(function( err, handle, errCode ) {

    var responseCode = handle.getInfo( 'RESPONSE_CODE' ).data,
        handleData   = handlesData[ handles.indexOf( handle  ) ],
        handleUrl    = urls[ handles.indexOf( handle ) ],
        responseData = '',
        i, len;

    console.log( '# of handles active: ' + multi.getCount() );

    if ( err ) {

        console.log( handleUrl + ' returned error: ' + err.message );

    } else {

        for ( i = 0, len = handleData.length; i < len; i++ ) {

            responseData += handleData[i].toString();
        }

        console.log( handleUrl + ' returned response code: ' + responseCode );

        console.log( handleUrl + ' returned response body: ' + responseData );
    }

    multi.removeHandle( handle );
    handle.close();

    if ( ++finished == urls.length ) {

        console.log( 'Finished all requests!' );
        multi.close();
    }
});

//This callback is like the CURLOPT_WRITEFUNCTION libcurl option.
function onData( data, n, nmemb ) {

    //this === the handle, see the .bind( handle ) call below.
    var key = handles.indexOf( this );

    handlesData[key].push( data );

    return n * nmemb;
}

for ( var i = 0, len = urls.length; i < len; i++ ) {

    handle = new Easy();
    handle.setOpt( 'URL', urls[i] );
    handle.setOpt( 'FOLLOWLOCATION', true );

    handle.onData = onData.bind( handle );

    handlesData.push( [] );
    handles.push( handle );

    multi.addHandle( handle );
}
<|endoftext|>


<commit_before>"use strict";

const _ = require("ramda")

require("./pcss/main.pcss")

const DB = require("./local-pouch-db")
const sound = require("./sound")

async function boot() {

    const dbMap = {
        "todo-db": await DB("todo-db"),
        "project-db": await DB("project-db"),
        "context-db": await DB("context-db")
    }

    // _.mapObjIndexed(db=>db.startRemoteSync(), dbMap)

    const todos = await dbMap["todo-db"].find({selector: {"_id": {"$ne": null}}})
    const projects = await dbMap["project-db"].find({selector: {"_id": {"$ne": null}}})
    const contexts = await dbMap["context-db"].find({selector: {"_id": {"$ne": null}}})

    const flags = {
        now: Date.now(),
        encodedTodoList: todos,
        encodedProjectList: projects,
        encodedContextList: contexts
    }

    const Elm = require("elm/Main.elm")
    const app = Elm["Main"]
        .embed(document.getElementById("root"), flags)

    app.ports["pouchDBUpsert"].subscribe(async ([dbName, id, doc]) => {
        // console.log("upserting", dbName, doc, id)
        const upsertResult = await dbMap[dbName].upsert(id, doc)
        if (_.F()) {
            console.log("upsertResult", upsertResult)
        }
    });

    setupNotifications(app)
        .catch(console.error)

    app.ports["focusPaperInput"].subscribe((selector) => {
        setTimeout(() => {
            requestAnimationFrame(() => {
                const toFocus = document.querySelector(selector)
                // console.log("toFocus", toFocus, document.activeElement)
                if (toFocus && document.activeElement !== toFocus) {
                    toFocus.focus()
                } else {
                    // console.log("not focusing")
                }
                if (toFocus) {
                    toFocus.$.input.focus()
                }
            })
        }, 0)
    })

    app.ports["startAlarm"].subscribe(() => {
        sound.start()
    })

    app.ports["stopAlarm"].subscribe(() => {
        sound.stop()
    })
}

boot().catch(console.error)

async function setupNotifications(app) {

    if (!'serviceWorker' in navigator) return
    const swScriptPath = WEB_PACK_DEV_SERVER ? "/notification-sw.js" : '/service-worker.js'

    navigator.serviceWorker.addEventListener('message', event => {
        console.info("message event received", event.data)
        app.ports["notificationClicked"].send(event.data)
        // event.ports[0].postMessage("Client 1 Says 'Hello back!'");
    });
    const reg = await navigator.serviceWorker.register(swScriptPath)

    app.ports["showNotification"].subscribe(showNotification(reg))

}

const showNotification = reg => async ({tag, title, data}) => {
    //console.info(msg)
    const permission = await Notification.requestPermission()
    if (permission !== "granted") return
    reg.showNotification(title, {
        tag,
        requiresInteraction:true,
        sticky:true,
        renotify:true,
        vibrate: [500,110,500,110,450,110,200,110,170,40,450,110,200,110,170,40,500],
        sound:"/alarm.ogg",

        /*actions: [
            {title: "Mark Done", action: "mark-done"},
            {title: "Snooze", action: "snooze"},
        ],*/
        data
    })
}
/*
 //noinspection JSUnresolvedVariable
 if (!WEB_PACK_DEV_SERVER && 'serviceWorker' in navigator) {
 //noinspection JSUnresolvedVariable
 navigator.serviceWorker.register('/service-worker.js');
 }
 */
<commit_msg>reminder notification<commit_after>"use strict";

const _ = require("ramda")

require("./pcss/main.pcss")

const DB = require("./local-pouch-db")
const sound = require("./sound")

async function boot() {

    const dbMap = {
        "todo-db": await DB("todo-db"),
        "project-db": await DB("project-db"),
        "context-db": await DB("context-db")
    }

    // _.mapObjIndexed(db=>db.startRemoteSync(), dbMap)

    const todos = await dbMap["todo-db"].find({selector: {"_id": {"$ne": null}}})
    const projects = await dbMap["project-db"].find({selector: {"_id": {"$ne": null}}})
    const contexts = await dbMap["context-db"].find({selector: {"_id": {"$ne": null}}})

    const flags = {
        now: Date.now(),
        encodedTodoList: todos,
        encodedProjectList: projects,
        encodedContextList: contexts
    }

    const Elm = require("elm/Main.elm")
    const app = Elm["Main"]
        .embed(document.getElementById("root"), flags)

    app.ports["pouchDBUpsert"].subscribe(async ([dbName, id, doc]) => {
        // console.log("upserting", dbName, doc, id)
        const upsertResult = await dbMap[dbName].upsert(id, doc)
        if (_.F()) {
            console.log("upsertResult", upsertResult)
        }
    });

    setupNotifications(app)
        .catch(console.error)

    app.ports["focusPaperInput"].subscribe((selector) => {
        setTimeout(() => {
            requestAnimationFrame(() => {
                const toFocus = document.querySelector(selector)
                // console.log("toFocus", toFocus, document.activeElement)
                if (toFocus && document.activeElement !== toFocus) {
                    toFocus.focus()
                } else {
                    // console.log("not focusing")
                }
                if (toFocus) {
                    toFocus.$.input.focus()
                }
            })
        }, 0)
    })

    app.ports["startAlarm"].subscribe(() => {
        sound.start()
    })

    app.ports["stopAlarm"].subscribe(() => {
        sound.stop()
    })
}

boot().catch(console.error)

async function setupNotifications(app) {

    if (!'serviceWorker' in navigator) return
    const swScriptPath = WEB_PACK_DEV_SERVER ? "/notification-sw.js" : '/service-worker.js'

    navigator.serviceWorker.addEventListener('message', event => {
        console.info("message event received", event.data)
        app.ports["notificationClicked"].send(event.data)
        // event.ports[0].postMessage("Client 1 Says 'Hello back!'");
    });
    const reg = await navigator.serviceWorker.register(swScriptPath)

    app.ports["showNotification"].subscribe(showNotification(reg))

}

const showNotification = reg => async ({tag, title, data}) => {
    //console.info(msg)
    const permission = await Notification.requestPermission()
    if (permission !== "granted") return
    reg.showNotification(title, {
        tag,
        requiresInteraction:true,
        sticky:true,
        renotify:true,
        vibrate: [500,110,500,110,450,110,200,110,170,40,450,110,200,110,170,40,500],
        sound:"/alarm.ogg",
        actions: [
            {title: "Mark Done", action: "mark-done"},
            {title: "Snooze", action: "snooze"},
        ],
        data
    })
}
/*
 //noinspection JSUnresolvedVariable
 if (!WEB_PACK_DEV_SERVER && 'serviceWorker' in navigator) {
 //noinspection JSUnresolvedVariable
 navigator.serviceWorker.register('/service-worker.js');
 }
 */
<|endoftext|>


<commit_before>var http = require('http'),
  fs = require('fs'),
  path = require('path'),
  utile = require('utile'),
  libxml = require('libxmljs');

var stream = null;
var json_arr = [];
var srw_config = { // TODO: limit options
  start: 1,
  limit: 100
};

// args
var argv = require('minimist')(process.argv.slice(2), {
  string: ['q, O, d, f, h'],
  boolean: ['s', 'i', 'a', 'p'],
  alias: {
    'q': 'query',
    'O': 'output',
    'd': 'dir',
    'f': 'format',
    'h': 'host',
    's': 'stream',
		'i': 'include-all',
    'a': 'include-anno',
    'p': 'validate-pids',
  },
  default: {
    'd': 'output',
    'O': 'output',
    'f': 'csv',
    'h': 'devtools.clarin.dk'
  }
});

var delimiter = (argv.f == 'tsv') ? '\t' : '%'; // TODO: custom delimiter
var validate = argv.p;

console.log('include all: ' + argv.i);
console.log('include anno: ' + argv.a);
console.log('validate: ' + validate);

var annotationsOnly = (!argv.i && argv.a);

// eSciDoc 1.3.x SRW Namespaces
var ns_obj = {
  'sru-zr': 'http://www.loc.gov/zing/srw/',
  'escidocItem': 'http://www.escidoc.de/schemas/item/0.10',
  'escidocMetadataRecords': 'http://www.escidoc.de/schemas/metadatarecords/0.5',
  'container': 'http://www.escidoc.de/schemas/container/0.9',
  'escidocContentStreams': 'http://www.escidoc.de/schemas/contentstreams/0.7',
  'escidocComponents': 'http://www.escidoc.de/schemas/components/0.9',
  'version': 'http://escidoc.de/core/01/properties/version/',
  'release': 'http://escidoc.de/core/01/properties/release/',
  'prop': 'http://escidoc.de/core/01/properties/',
  'srel': 'http://escidoc.de/core/01/structural-relations/',
  'relations': 'http://www.escidoc.de/schemas/relations/0.3',
  'xlink': 'http://www.w3.org/1999/xlink'
};

var getProperties = function(obj, callback) {
  var props = {}; // Properties object
  props.name = obj.name();

  var xpathRoot = '';
  if(props.name == 'item') xpathRoot = 'escidocItem:properties/'
  else if(props.name == 'container') xpathRoot = 'container:properties/';

	var escidocID_href = obj.attr('href').value();
  props.escidocID = escidocID_href.substring(escidocID_href.indexOf('dkclarin'), escidocID_href.length);
	if(props.escidocID.indexOf('properties') != -1) props.escidocID = props.escidocID.substring(0, props.escidocID.indexOf('properties')-1);

  var contentModelID_href = obj.get(xpathRoot + 'srel:content-model', ns_obj).attr('href').value();
  props.contentModelID = contentModelID_href.substring(contentModelID_href.indexOf('dkclarin'), contentModelID_href.length);

  var obj_pid = obj.get(xpathRoot + 'prop:pid', ns_obj);
	var ver_pid = obj.get(xpathRoot + 'prop:version/version:pid', ns_obj);
  props.ver_no = obj.get(xpathRoot + 'prop:latest-version/version:number', ns_obj).text();

  var last_date = obj.attr('last-modification-date').value();

  props.pid = "none";

  if (ver_pid != null)
    props.pid = ver_pid.text();
  else if(obj_pid != null)
    props.pid = obj_pid.text();
	else
		console.error('No PID value found for ' + props.name + ': ' + props.escidocID);

  if(validate) {
    if(validatePIDVersion(props)) { // PID must be in format of version PID
      console.log('validated found Handle PID: ' + props.pid); // add to member
      callback(props);
    }
  } else
    callback(props);
}

// Validate HDL PIDs against the version no ref (CLARIN-DK based PID implementaton)
var validatePIDVersion = function(props, callback) {
  if(props.pid.indexOf('hdl:') == 0) {
    var sProps = props.pid.split('-');
    if(sProps.length < 5)
      return true; // object PID
    else
      return (parseInt(sProps[sProps.length-1], 16) == props.ver_no);
  } else
    return true;
}

// Parse and pull ID data from the XMLDocument
var parse = function(doc) {
  var totalRecords = doc.get('//sru-zr:numberOfRecords', ns_obj).text();
  var items = doc.find('//escidocItem:item', ns_obj);
  var containers = doc.find('//container:container', ns_obj);

  console.log('Total records in query: ' + totalRecords);

  if (utile.isArray(items)) console.log('Found ' + items.length + ' items.');
  else console.error('Found 0 items in XMLDocument.');

  if (utile.isArray(containers)) console.log('Found ' + containers.length + ' containers.');
  else console.error('Found 0 containers in XMLDocument.');

  // Add the items to list
  items.forEach(function(item){
    // CSV format: item%{escidocID}%[{objectPID}}|{lastVersionPID}]%{versionNo}
    if (!annotationsOnly) {
      getProperties(item, addMember);
    }

		if(argv.a && item != null){
      var relations = item.find('relations:relations/relations:relation', ns_obj);
      relations.forEach(function(relation) {
        if (relation != undefined || relation != null) {
          relation_type = relation.attr('predicate').value();
          if (relation_type.indexOf('HasAnnotation') != -1) {
            var relation_href = relation.attr('href').value();
            var relationObjID = relation_href.substring(relation_href.indexOf('dkclarin'), relation.length);

            console.log('Found Annotation: ' + relationObjID);

            // retrieve properties for Annotation item from eSciDoc REST
            retrieveItemProperties(relationObjID, function(annoPropsItem) {
							console.log('props xml: ' + annoPropsItem.toString());
              getProperties(annoPropsItem.root(),
                function(props) {
                  addMember(props);
                  if(items.indexOf(index) >= items.length)
                    if(Number(totalRecords) < (srw_config.limit + srw_config.start))
                      if(argv.f == 'json')
                        createStream(function() { addMemberToFile(JSON.stringify(json_arr)); });
                }); // add annotation member to file
            });
          } else if (relation_type.indexOf('IsAnnotationOf') != -1
                     || relation_type.indexOf('isDependentOf') != -1
                     || relation_type.indexOf('hasDependent') != -1) { // add annotation member to file including parent ID (annotation)
            retrieveItemProperties(relationObjID, function(annoPropsItem) {
              getProperties(annoPropsItem.root(), function(propsAnno) {
                getProperties(item, function(props) { addMember(propsAnno, props.escidocID); });
              });
            });
          }
        }
      });
    }
  });

  // TODO: Handle containers array
  containers.forEach(function(container) {
      if(!annotationsOnly)
          getProperties(container, addMember);
  });

  // iterate over complete SRW result set
  if(Number(totalRecords) >= (srw_config.start + srw_config.limit)) {
    srw_config.start += srw_config.limit;
    retrieveSRWResult(srw_config, function(xml) {
      parse(xml);
    });
  } else {
    if(!argv.a && argv.f == 'json')
      createStream(function() { addMemberToFile(JSON.stringify(json_arr)); }); // write JSON object to output file
    //if(stream instanceof fs.WriteStream)
      //stream.destroySoon();
  }
}

/** SRW Query fetch */
var retrieveSRWResult = function(config, callback) {
  return execGET(srw_options(argv.q, config), callback);
}

/* Item Properties */
var retrieveItemProperties = function(escidocID, callback) {
  return execGET(ir_options(escidocID, '/properties'), callback);
}

var execGET = function(options, callback) {
  http.get(options, function(res) {
    var str = "";
    res.on('data', function(chunk) {
      str += chunk;
    });
    res.on('end', function() {
      if (res.statusCode == "200")
        callback(libxml.parseXmlString(str));
      else
        throw new Error("Error code: " + res.statusCode);
    });
  }).on('error', function(e) {
    console.error(e);
  });

  return true;
}

/** SRW query options */
var srw_options = function(queryCQL, record_vals) {
  var search_path_limits = "&maximumRecords=" + record_vals.limit + "&startRecord=" + record_vals.start;
  var targetUrl = argv.h;
  return {
    host: (targetUrl.indexOf('http://') != -1) ? targetUrl.replace('http://', '') : targetUrl,
    path: '/srw/search/escidoc_all?query=' + encodeURIComponent(queryCQL.replace(/\s/g, "%20")) + search_path_limits + '&d=' + Date.now()
  };
};

/* eSciDoc Item REST */
var ir_options = function(escidocID, path) {
  var targetUrl = argv.h;
  return {
    host: (targetUrl.indexOf('http://') != -1) ? targetUrl.replace('http://', '') : targetUrl,
    path: '/ir/item/' + escidocID + path
  };
};

// append props to output file
var addMember = function(props, parentID) {
  if (argv.f == 'csv' || argv.f == 'tsv') {
    var dataArr = [props.name, props.escidocID, props.contentModelID, props.pid, props.ver_no];
    if(parentID != null)
      dataArr.push(parentID);

    addMemberToFile(dataArr.join(delimiter) + '\n');
  } else if (argv.f == 'json') // write output to JSON object
    json_arr.push({
		  type: props.name,
		  systemID: props.escidocID,
		  contentModelID: props.contentModelID,
		  PID: props.pid,
		  versionNo: props.ver_no,
      parentID: (parentID != null) ? parentID : undefined
		});
  else
    throw new Error('Unsupported format:' + argv.f);
}

// write output to file
var addMemberToFile = function(data) {
  if (stream != null)
    if (stream.write(data)) console.log('Data written: ' + data);
    else console.log('Buffer full waiting for drain..');
  else
    process.send(data);
}

var createStream = function(callback) {

  var is_json = (argv.f == 'json');
  var is_csv = (argv.f == 'csv');
  var is_tsv = (argv.f == 'tsv');

  var file_name = argv.O;
  var file_dir = argv.d;
  var file_path = null;

  if (!argv.s) {
    console.log("Exists?: " + file_dir);
    if (fs.existsSync(file_dir)) {
      if (is_json)
        file_path = path.join(file_dir, file_name + '.json');
      else if (is_csv)
        file_path = path.join(file_dir, file_name + '.csv');
      else if (is_tsv)
        file_path = path.join(file_dir, file_name + '.tsv');

      stream = fs.createWriteStream(file_path, {
        encoding: 'utf8'
      });
      stream.on('error', function(err) {
        if (err) throw err;
      });
      stream.on('drain', function() {
        console.log('Data drained from buffer to file:' + file_path);
        stream.end();
      });
      stream.on('close', function() {
        console.log('Closing file stream.');
      });

      console.log('Using query: ' + argv.q);
    } else {
      console.log('Target directory doesn\'t exist: ' + file_dir);
      fs.mkdir(file_dir, function(err) {
        if (err) throw err;
        console.log('Created directory: ' + file_dir);
        return callback();
      });
    }
  }

  return callback();
}

var run = function() {
   if(argv.f != "json")
   createStream(function() {
     if (argv.s || stream != null)
      retrieveSRWResult(srw_config, function(xml) {
        parse(xml);
      });
   });
   else
      retrieveSRWResult(srw_config, function(xml) {
        parse(xml);
      });

}

module.exports = run;

run();
<commit_msg>Fix typo.<commit_after>var http = require('http'),
  fs = require('fs'),
  path = require('path'),
  utile = require('utile'),
  libxml = require('libxmljs');

var stream = null;
var json_arr = [];
var srw_config = { // TODO: limit options
  start: 1,
  limit: 100
};

// args
var argv = require('minimist')(process.argv.slice(2), {
  string: ['q, O, d, f, h'],
  boolean: ['s', 'i', 'a', 'p'],
  alias: {
    'q': 'query',
    'O': 'output',
    'd': 'dir',
    'f': 'format',
    'h': 'host',
    's': 'stream',
		'i': 'include-all',
    'a': 'include-anno',
    'p': 'validate-pids',
  },
  default: {
    'd': 'output',
    'O': 'output',
    'f': 'csv',
    'h': 'devtools.clarin.dk'
  }
});

var delimiter = (argv.f == 'tsv') ? '\t' : '%'; // TODO: custom delimiter
var validate = argv.p;

console.log('include all: ' + argv.i);
console.log('include anno: ' + argv.a);
console.log('validate: ' + validate);

var annotationsOnly = (!argv.i && argv.a);

// eSciDoc 1.3.x SRW Namespaces
var ns_obj = {
  'sru-zr': 'http://www.loc.gov/zing/srw/',
  'escidocItem': 'http://www.escidoc.de/schemas/item/0.10',
  'escidocMetadataRecords': 'http://www.escidoc.de/schemas/metadatarecords/0.5',
  'container': 'http://www.escidoc.de/schemas/container/0.9',
  'escidocContentStreams': 'http://www.escidoc.de/schemas/contentstreams/0.7',
  'escidocComponents': 'http://www.escidoc.de/schemas/components/0.9',
  'version': 'http://escidoc.de/core/01/properties/version/',
  'release': 'http://escidoc.de/core/01/properties/release/',
  'prop': 'http://escidoc.de/core/01/properties/',
  'srel': 'http://escidoc.de/core/01/structural-relations/',
  'relations': 'http://www.escidoc.de/schemas/relations/0.3',
  'xlink': 'http://www.w3.org/1999/xlink'
};

var getProperties = function(obj, callback) {
  var props = {}; // Properties object
  props.name = obj.name();

  var xpathRoot = '';
  if(props.name == 'item') xpathRoot = 'escidocItem:properties/'
  else if(props.name == 'container') xpathRoot = 'container:properties/';

	var escidocID_href = obj.attr('href').value();
  props.escidocID = escidocID_href.substring(escidocID_href.indexOf('dkclarin'), escidocID_href.length);
	if(props.escidocID.indexOf('properties') != -1) props.escidocID = props.escidocID.substring(0, props.escidocID.indexOf('properties')-1);

  var contentModelID_href = obj.get(xpathRoot + 'srel:content-model', ns_obj).attr('href').value();
  props.contentModelID = contentModelID_href.substring(contentModelID_href.indexOf('dkclarin'), contentModelID_href.length);

  var obj_pid = obj.get(xpathRoot + 'prop:pid', ns_obj);
	var ver_pid = obj.get(xpathRoot + 'prop:version/version:pid', ns_obj);
  props.ver_no = obj.get(xpathRoot + 'prop:latest-version/version:number', ns_obj).text();

  var last_date = obj.attr('last-modification-date').value();

  props.pid = "none";

  if (ver_pid != null)
    props.pid = ver_pid.text();
  else if(obj_pid != null)
    props.pid = obj_pid.text();
	else
		console.error('No PID value found for ' + props.name + ': ' + props.escidocID);

  if(validate) {
    if(validatePIDVersion(props)) { // PID must be in format of version PID
      console.log('validated found Handle PID: ' + props.pid); // add to member
      callback(props);
    }
  } else
    callback(props);
}

// Validate HDL PIDs against the version no ref (CLARIN-DK based PID implementaton)
var validatePIDVersion = function(props, callback) {
  if(props.pid.indexOf('hdl:') == 0) {
    var sProps = props.pid.split('-');
    if(sProps.length < 5)
      return true; // object PID
    else
      return (parseInt(sProps[sProps.length-1], 16) == props.ver_no);
  } else
    return true;
}

// Parse and pull ID data from the XMLDocument
var parse = function(doc) {
  var totalRecords = doc.get('//sru-zr:numberOfRecords', ns_obj).text();
  var items = doc.find('//escidocItem:item', ns_obj);
  var containers = doc.find('//container:container', ns_obj);

  console.log('Total records in query: ' + totalRecords);

  if (utile.isArray(items)) console.log('Found ' + items.length + ' items.');
  else console.error('Found 0 items in XMLDocument.');

  if (utile.isArray(containers)) console.log('Found ' + containers.length + ' containers.');
  else console.error('Found 0 containers in XMLDocument.');

  // Add the items to list
  items.forEach(function(item){
    // CSV format: item%{escidocID}%[{objectPID}}|{lastVersionPID}]%{versionNo}
    if (!annotationsOnly) {
      getProperties(item, addMember);
    }

		if(argv.a && item != null){
      var relations = item.find('relations:relations/relations:relation', ns_obj);
      relations.forEach(function(relation) {
        if (relation != undefined || relation != null) {
          relation_type = relation.attr('predicate').value();
          if (relation_type.indexOf('HasAnnotation') != -1) {
            var relation_href = relation.attr('href').value();
            var relationObjID = relation_href.substring(relation_href.indexOf('dkclarin'), relation.length);

            console.log('Found Annotation: ' + relationObjID);

            // retrieve properties for Annotation item from eSciDoc REST
            retrieveItemProperties(relationObjID, function(annoPropsItem) {
							console.log('props xml: ' + annoPropsItem.toString());
              getProperties(annoPropsItem.root(),
                function(props) {
                  addMember(props);
                  if(items.indexOf(item) >= items.length)
                    if(Number(totalRecords) < (srw_config.limit + srw_config.start))
                      if(argv.f == 'json')
                        createStream(function() { addMemberToFile(JSON.stringify(json_arr)); });
                }); // add annotation member to file
            });
          } else if (relation_type.indexOf('IsAnnotationOf') != -1
                     || relation_type.indexOf('isDependentOf') != -1
                     || relation_type.indexOf('hasDependent') != -1) { // add annotation member to file including parent ID (annotation)
            retrieveItemProperties(relationObjID, function(annoPropsItem) {
              getProperties(annoPropsItem.root(), function(propsAnno) {
                getProperties(item, function(props) { addMember(propsAnno, props.escidocID); });
              });
            });
          }
        }
      });
    }
  });

  // TODO: Handle containers array
  containers.forEach(function(container) {
      if(!annotationsOnly)
          getProperties(container, addMember);
  });

  // iterate over complete SRW result set
  if(Number(totalRecords) >= (srw_config.start + srw_config.limit)) {
    srw_config.start += srw_config.limit;
    retrieveSRWResult(srw_config, function(xml) {
      parse(xml);
    });
  } else {
    if(!argv.a && argv.f == 'json')
      createStream(function() { addMemberToFile(JSON.stringify(json_arr)); }); // write JSON object to output file
    //if(stream instanceof fs.WriteStream)
      //stream.destroySoon();
  }
}

/** SRW Query fetch */
var retrieveSRWResult = function(config, callback) {
  return execGET(srw_options(argv.q, config), callback);
}

/* Item Properties */
var retrieveItemProperties = function(escidocID, callback) {
  return execGET(ir_options(escidocID, '/properties'), callback);
}

var execGET = function(options, callback) {
  http.get(options, function(res) {
    var str = "";
    res.on('data', function(chunk) {
      str += chunk;
    });
    res.on('end', function() {
      if (res.statusCode == "200")
        callback(libxml.parseXmlString(str));
      else
        throw new Error("Error code: " + res.statusCode);
    });
  }).on('error', function(e) {
    console.error(e);
  });

  return true;
}

/** SRW query options */
var srw_options = function(queryCQL, record_vals) {
  var search_path_limits = "&maximumRecords=" + record_vals.limit + "&startRecord=" + record_vals.start;
  var targetUrl = argv.h;
  return {
    host: (targetUrl.indexOf('http://') != -1) ? targetUrl.replace('http://', '') : targetUrl,
    path: '/srw/search/escidoc_all?query=' + encodeURIComponent(queryCQL.replace(/\s/g, "%20")) + search_path_limits + '&d=' + Date.now()
  };
};

/* eSciDoc Item REST */
var ir_options = function(escidocID, path) {
  var targetUrl = argv.h;
  return {
    host: (targetUrl.indexOf('http://') != -1) ? targetUrl.replace('http://', '') : targetUrl,
    path: '/ir/item/' + escidocID + path
  };
};

// append props to output file
var addMember = function(props, parentID) {
  if (argv.f == 'csv' || argv.f == 'tsv') {
    var dataArr = [props.name, props.escidocID, props.contentModelID, props.pid, props.ver_no];
    if(parentID != null)
      dataArr.push(parentID);

    addMemberToFile(dataArr.join(delimiter) + '\n');
  } else if (argv.f == 'json') // write output to JSON object
    json_arr.push({
		  type: props.name,
		  systemID: props.escidocID,
		  contentModelID: props.contentModelID,
		  PID: props.pid,
		  versionNo: props.ver_no,
      parentID: (parentID != null) ? parentID : undefined
		});
  else
    throw new Error('Unsupported format:' + argv.f);
}

// write output to file
var addMemberToFile = function(data) {
  if (stream != null)
    if (stream.write(data)) console.log('Data written: ' + data);
    else console.log('Buffer full waiting for drain..');
  else
    process.send(data);
}

var createStream = function(callback) {

  var is_json = (argv.f == 'json');
  var is_csv = (argv.f == 'csv');
  var is_tsv = (argv.f == 'tsv');

  var file_name = argv.O;
  var file_dir = argv.d;
  var file_path = null;

  if (!argv.s) {
    console.log("Exists?: " + file_dir);
    if (fs.existsSync(file_dir)) {
      if (is_json)
        file_path = path.join(file_dir, file_name + '.json');
      else if (is_csv)
        file_path = path.join(file_dir, file_name + '.csv');
      else if (is_tsv)
        file_path = path.join(file_dir, file_name + '.tsv');

      stream = fs.createWriteStream(file_path, {
        encoding: 'utf8'
      });
      stream.on('error', function(err) {
        if (err) throw err;
      });
      stream.on('drain', function() {
        console.log('Data drained from buffer to file:' + file_path);
        stream.end();
      });
      stream.on('close', function() {
        console.log('Closing file stream.');
      });

      console.log('Using query: ' + argv.q);
    } else {
      console.log('Target directory doesn\'t exist: ' + file_dir);
      fs.mkdir(file_dir, function(err) {
        if (err) throw err;
        console.log('Created directory: ' + file_dir);
        return callback();
      });
    }
  }

  return callback();
}

var run = function() {
   if(argv.f != "json")
   createStream(function() {
     if (argv.s || stream != null)
      retrieveSRWResult(srw_config, function(xml) {
        parse(xml);
      });
   });
   else
      retrieveSRWResult(srw_config, function(xml) {
        parse(xml);
      });

}

module.exports = run;

run();
<|endoftext|>


<commit_before>//Module wrapper for the core classes.
define( [
  "pex/core/Context",
  "pex/core/Vec2",
  "pex/core/Vec3",
  "pex/core/Vec4",
  "pex/core/Mat4",
  "pex/core/Quat",
  "pex/core/Edge",
  "pex/core/Face3",
  "pex/core/Face4",
  "pex/core/Color",
  "pex/core/Ray",
  "pex/core/Vbo",
  "pex/core/Mesh",
  "pex/core/Program",
  "pex/core/Material",
  "pex/core/Texture",
  "pex/core/Texture2D",
  "pex/core/TextureCube",
  "pex/core/Fbo",
  "pex/core/Geometry",
  "pex/core/Spline",
  "pex/core/Rect",
  "pex/core/Line2D",
  "pex/core/Triangle2D",
  "pex/core/RenderTarget"
  ],
  function(
      Context, Vec2, Vec3, Vec4, Mat4, Quat, Edge, Face3, Face4, Color,
      Ray, Vbo, Mesh, Program, Material, Texture, Texture2D, TextureCube,
      Fbo, Geometry, Spline, Rect, Line2D, Triangle2D, RenderTarget
    ) {
    return {
      Context : Context,
      Vec2 : Vec2,
      Vec3 : Vec3,
      Vec4 : Vec4,
      Mat4 : Mat4,
      Quat : Quat,
      Edge : Edge,
      Face3 : Face3,
      Face4 : Face4,
      Color : Color,
      Ray : Ray,
      Vbo : Vbo,
      Mesh : Mesh,
      Program : Program,
      Material : Material,
      Texture : Texture,
      Texture2D : Texture2D,
      TextureCube: TextureCube,
      Fbo : Fbo,
      Geometry : Geometry,
      Spline : Spline,
      Rect : Rect,
      Line2D : Line2D,
      Triangle2D : Triangle2D,
      RenderTarget : RenderTarget
    };
});<commit_msg>Updated core package<commit_after>//Module wrapper for the core classes.
define( [
  "pex/core/Context",
  "pex/core/Vec2",
  "pex/core/Vec3",
  "pex/core/Vec4",
  "pex/core/Mat4",
  "pex/core/Quat",
  "pex/core/Edge",
  "pex/core/Face3",
  "pex/core/Face4",
  "pex/core/Color",
  "pex/core/Ray",
  "pex/core/Vbo",
  "pex/core/Mesh",
  "pex/core/Program",
  "pex/core/Material",
  "pex/core/Texture",
  "pex/core/Texture2D",
  "pex/core/TextureCube",
  "pex/core/Fbo",
  "pex/core/Geometry",
  "pex/core/Spline",
  "pex/core/Rect",
  "pex/core/Line2D",
  "pex/core/Triangle2D",
  "pex/core/RenderTarget",
  "pex/core/Polygon2D",
  "pex/core/FullScreenQuad"
  ],
  function(
      Context, Vec2, Vec3, Vec4, Mat4, Quat, Edge, Face3, Face4, Color,
      Ray, Vbo, Mesh, Program, Material, Texture, Texture2D, TextureCube,
      Fbo, Geometry, Spline, Rect, Line2D, Triangle2D, RenderTarget,
      Polygon2D, FullScreenQuad
    ) {
    return {
      Context : Context,
      Vec2 : Vec2,
      Vec3 : Vec3,
      Vec4 : Vec4,
      Mat4 : Mat4,
      Quat : Quat,
      Edge : Edge,
      Face3 : Face3,
      Face4 : Face4,
      Color : Color,
      Ray : Ray,
      Vbo : Vbo,
      Mesh : Mesh,
      Program : Program,
      Material : Material,
      Texture : Texture,
      Texture2D : Texture2D,
      TextureCube: TextureCube,
      Fbo : Fbo,
      Geometry : Geometry,
      Spline : Spline,
      Rect : Rect,
      Line2D : Line2D,
      Triangle2D : Triangle2D,
      RenderTarget : RenderTarget,
      Polygon2D : Polygon2D,
      FullScreenQuad : FullScreenQuad
    };
});<|endoftext|>


<commit_before>// @flow
import { getWalletCfg, getGlobalCfg } from "../config";
import { isTestNet } from "selectors";
import { equalElements } from "helpers";
import * as wallet from "wallet";
import { closeWalletRequest } from "actions/WalletLoaderActions";
import { closeDaemonRequest } from "actions/DaemonActions";

export const SETTINGS_SAVE = "SETTINGS_SAVE";
export const SETTINGS_CHANGED = "SETTINGS_CHANGED";
export const SETTINGS_UNCHANGED = "SETTINGS_UNCHANGED";

export const saveSettings = (settings) => (dispatch, getState) => {
  const { settings: { needNetworkReset } } = getState();
  const { daemon: { walletName } } = getState();

  const config = getGlobalCfg();
  const oldAllowedExternalRequests = config.get("allowed_external_requests");
  const updatedProxy =
    (config.get("proxy_type") !== settings.proxyType) ||
    (config.get("proxy_location") !== settings.proxyLocation);

  config.set("locale", settings.locale);
  config.set("daemon_start_advanced", settings.daemonStartAdvanced);
  config.set("allowed_external_requests", settings.allowedExternalRequests);
  config.set("proxy_type", settings.proxyType);
  config.set("proxy_location", settings.proxyLocation);
  config.set("timezone", settings.timezone);
  config.set("spv_mode", settings.spvMode);
  config.set("spv_connect", settings.spvConnect);

  const walletConfig = getWalletCfg(isTestNet(getState()), walletName);
  walletConfig.set("currency_display", settings.currencyDisplay);
  walletConfig.set("gaplimit", settings.gapLimit);

  if (!equalElements(oldAllowedExternalRequests, settings.allowedExternalRequests)) {
    wallet.reloadAllowedExternalRequests();
  }

  dispatch({ settings, type: SETTINGS_SAVE });

  if (updatedProxy) {
    wallet.setupProxy();
  }

  if (needNetworkReset) {
    dispatch(closeWalletRequest());
    dispatch(closeDaemonRequest());
  }

};

export function updateStateSettingsChanged(settings) {
  return (dispatch, getState) => {
    const { tempSettings, currentSettings } = getState().settings;
    const newSettings = { ...tempSettings, ...settings };
    const settingsFields = Object.keys(tempSettings);
    const networkChange = {
      network: true,
      spvMode: true,
      daemonStartAdvanced: true,
    };
    const newDiffersFromTemp = settingsFields
      .reduce((d, f) => (d || newSettings[f] !== tempSettings[f]), false);

    if (newDiffersFromTemp) {
      const newDiffersFromCurrent = settingsFields
        .reduce((d, f) => (d || newSettings[f] !== currentSettings[f]), false);
      const needNetworkReset =  Object.keys(networkChange)
        .reduce((d, f) => (d || newSettings[f] !== currentSettings[f]), false);
      newDiffersFromCurrent
        ? dispatch({ tempSettings: newSettings, needNetworkReset, type: SETTINGS_CHANGED })
        : dispatch({ tempSettings: currentSettings, type: SETTINGS_UNCHANGED });
    }
  };
}

export const updateStateVoteSettingsChanged = (settings) => (dispatch, getState) => {
  const { settings: { tempSettings, currentSettings } } = getState();
  const { daemon: { walletName } } = getState();
  if (settings.enableTicketBuyer !== tempSettings.enableTicketBuyer) {
    const config = getWalletCfg(isTestNet(getState()), walletName);
    config.set("enableticketbuyer", settings.enableTicketBuyer);
    dispatch({ tempSettings: settings, type: SETTINGS_CHANGED });
  } else {
    dispatch({ tempSettings: currentSettings, type: SETTINGS_UNCHANGED });
  }
};
<commit_msg>[launcher] Fix initial privacy page (#1707)<commit_after>// @flow
import { getWalletCfg, getGlobalCfg } from "../config";
import { isTestNet } from "selectors";
import { equalElements } from "helpers";
import * as wallet from "wallet";
import { closeWalletRequest } from "actions/WalletLoaderActions";
import { closeDaemonRequest } from "actions/DaemonActions";

export const SETTINGS_SAVE = "SETTINGS_SAVE";
export const SETTINGS_CHANGED = "SETTINGS_CHANGED";
export const SETTINGS_UNCHANGED = "SETTINGS_UNCHANGED";

export const saveSettings = (settings) => (dispatch, getState) => {
  const { settings: { needNetworkReset } } = getState();
  const { daemon: { walletName } } = getState();

  const config = getGlobalCfg();
  const oldAllowedExternalRequests = config.get("allowed_external_requests");
  const updatedProxy =
    (config.get("proxy_type") !== settings.proxyType) ||
    (config.get("proxy_location") !== settings.proxyLocation);

  config.set("locale", settings.locale);
  config.set("daemon_start_advanced", settings.daemonStartAdvanced);
  config.set("allowed_external_requests", settings.allowedExternalRequests);
  config.set("proxy_type", settings.proxyType);
  config.set("proxy_location", settings.proxyLocation);
  config.set("timezone", settings.timezone);
  config.set("spv_mode", settings.spvMode);
  config.set("spv_connect", settings.spvConnect);

  if (walletName) {
    const walletConfig = getWalletCfg(isTestNet(getState()), walletName);
    walletConfig.set("currency_display", settings.currencyDisplay);
    walletConfig.set("gaplimit", settings.gapLimit);
  }

  if (!equalElements(oldAllowedExternalRequests, settings.allowedExternalRequests)) {
    wallet.reloadAllowedExternalRequests();
  }

  dispatch({ settings, type: SETTINGS_SAVE });

  if (updatedProxy) {
    wallet.setupProxy();
  }

  if (needNetworkReset) {
    dispatch(closeWalletRequest());
    dispatch(closeDaemonRequest());
  }

};

export function updateStateSettingsChanged(settings) {
  return (dispatch, getState) => {
    const { tempSettings, currentSettings } = getState().settings;
    const newSettings = { ...tempSettings, ...settings };
    const settingsFields = Object.keys(tempSettings);
    const networkChange = {
      network: true,
      spvMode: true,
      daemonStartAdvanced: true,
    };
    const newDiffersFromTemp = settingsFields
      .reduce((d, f) => (d || newSettings[f] !== tempSettings[f]), false);

    if (newDiffersFromTemp) {
      const newDiffersFromCurrent = settingsFields
        .reduce((d, f) => (d || newSettings[f] !== currentSettings[f]), false);
      const needNetworkReset =  Object.keys(networkChange)
        .reduce((d, f) => (d || newSettings[f] !== currentSettings[f]), false);
      newDiffersFromCurrent
        ? dispatch({ tempSettings: newSettings, needNetworkReset, type: SETTINGS_CHANGED })
        : dispatch({ tempSettings: currentSettings, type: SETTINGS_UNCHANGED });
    }
  };
}

export const updateStateVoteSettingsChanged = (settings) => (dispatch, getState) => {
  const { settings: { tempSettings, currentSettings } } = getState();
  const { daemon: { walletName } } = getState();
  if (settings.enableTicketBuyer !== tempSettings.enableTicketBuyer) {
    const config = getWalletCfg(isTestNet(getState()), walletName);
    config.set("enableticketbuyer", settings.enableTicketBuyer);
    dispatch({ tempSettings: settings, type: SETTINGS_CHANGED });
  } else {
    dispatch({ tempSettings: currentSettings, type: SETTINGS_UNCHANGED });
  }
};
<|endoftext|>


<commit_before>module.exports = {
  debug: true,
  verifyConditions: [
    '@semantic-release/changelog',
    '@semantic-release/npm',
    '@semantic-release/github',
  ],
  prepare: [
    {
      'path': '@semantic-release/exec',
      'cmd': 'VERSION=${nextRelease.version} node tools/build-dist'
    },
    '@semantic-release/changelog',
    '@semantic-release/npm',
    '@semantic-release/git',
  ],
  publish: [
    '@semantic-release/npm',
    '@semantic-release/github',
  ],
  success: [
    '@semantic-release/github',
    {
      'path': '@semantic-release/exec',
      'cmd': 'node tools/purge-jsdelivr'
    },
  ]
}
<commit_msg>chore(semantic-release): explicitly specify master as the releasing branch<commit_after>module.exports = {
  debug: true,
  branch: 'master',
  verifyConditions: [
    '@semantic-release/changelog',
    '@semantic-release/npm',
    '@semantic-release/github',
  ],
  prepare: [
    {
      'path': '@semantic-release/exec',
      'cmd': 'VERSION=${nextRelease.version} node tools/build-dist'
    },
    '@semantic-release/changelog',
    '@semantic-release/npm',
    '@semantic-release/git',
  ],
  publish: [
    '@semantic-release/npm',
    '@semantic-release/github',
  ],
  success: [
    '@semantic-release/github',
    {
      'path': '@semantic-release/exec',
      'cmd': 'node tools/purge-jsdelivr'
    },
  ]
}
<|endoftext|>


<commit_before><commit_msg>Update LMexpress.js<commit_after><|endoftext|>


<commit_before>enyo.kind({
	name : "moon.Panel",
	kind: "FittableRows",
	fit : true,
	classes: "moon-panel",
	published: {
		index: 0,
		title: "Title",
		titleBelow: ""
    },
	events : {
    	//* This panel has completed it's pre-arrangement transition
		onPreTransitionComplete: "",
		//* This panel has completed it's post-arrangement transition
		onPostTransitionComplete: ""
	},
	panelTools : [
		{name: "header", kind: "moon.Header"},
		{name: "panelBody", fit: true, classes: "moon-panel-body"},
		{name: "animator", kind: "StyleAnimator", onComplete: "animationComplete"}
	],
	headerComponents: [
		{content: "This is a TEST!"}
	],
	isBreadcrumb: false,

	create: function() {
		this.inherited(arguments);
		this.$.header.createComponents(this.headerComponents);
	},
	initComponents: function() {
		this.createTools();
		this.controlParentName = "panelBody";
		this.discoverControlParent();
		this.inherited(arguments);
	},
	createTools: function() {
		this.createComponents(this.panelTools);
	},
	rendered: function() {
		this.inherited(arguments);
		this.setHeader({
			titleAbove: this.getIndex(),
			title: this.getTitle(),
			titleBelow: this.getTitleBelow(),
		});
	},
	titleChanged: function() {
		this.setHeader({
			title: this.getTitle(),
		});
	},
	titleBelowChanged: function() {
		this.setHeader({
			titleBelow: this.getTitleBelow(),
		});
	},
	preTransitionComplete: function() {
		this.isBreadcrumb = true;
		this.doPreTransitionComplete();
	},
	postTransitionComplete: function() {
		this.isBreadcrumb = false;
		this.doPostTransitionComplete();
	},
	setHeader: function(inData) {
		inData.titleAbove || this.$.header.setTitleAbove(inData.titleAbove);
		this.$.header.setTitle(inData.title);
		this.$.header.setTitleBelow(inData.titleBelow);
	},
	/**
		@param thisIndex panel index in this.container
	*/
	preTransition: function(thisIndex, inFromIndex, inToIndex) {
		//var myIndex = this.container.getPanels().indexOf(this);
		var myIndex = thisIndex;
		if (!this.isBreadcrumb && this.container.layout.isBreadcrumb(myIndex, inToIndex)) {
			this.shrinkPanel();
			return true;
		}

		return false;
	},
	postTransition: function(thisIndex, inFromIndex, inToIndex) {
		//var myIndex = this.container.getPanels().indexOf(this);
		var myIndex = thisIndex;
		if (this.isBreadcrumb && !this.container.layout.isBreadcrumb(myIndex, inToIndex)) {
			this.growPanel();
			return true;
		}

		return false;
	},
	shrinkPanel: function() {
		this.$.animator.newAnimation({
			animationName: "preTransition",
			duration: 800,
			timingFunction: "cubic-bezier(.42, 0, .16, 1.1)",
			keyframes: {
				0: [{
					control: this.$.panelBody,
					properties: {
						"height" : "current"
					}
				}],
				25: [{
					control: this.$.panelBody,
					properties: {
						"opacity" : "1"
					}
				}],
				50: [{
					control: this.$.panelBody,
					properties: {
						"height"  : "0px",
						"opacity" : "0"
					}
				},
				{
					control: this,
					properties: {
						"width"     : "current",
						"min-width" : "current",
						"max-width" : "current"
					}
				}],
				100: [{
					control: this,
					properties: {
						"width" : "200px",
						"min-width" : "200px",
						"max-width" : "200px"
					}
				}]
			}
		});

		this.$.header.animateCollapse();
		this.$.animator.play();
	},
	growPanel: function() {
		this.$.animator.newAnimation({
			animationName: "postTransition",
			duration: 800,
			timingFunction: "cubic-bezier(.42, 0, .16, 1.1)",
			keyframes: {
				0: [{
					control: this,
					properties: {
						"width"     : "current",
						"min-width" : "current",
						"max-width" : "current"
					}
				}],
				25: [{
					control: this,
					properties: {
						"width"     : this.width+"px",
						"min-width" : this.width+"px",
						"max-width" : this.width+"px"
					}
				},
				{
					control: this.$.panelBody,
					properties: {
						"height"  : "current",
						"opacity" : "current"
					}
				}],
				75: [{
					control: this.$.panelBody,
					properties: {
						"opacity" : "1"
					}
				}],
				100: [
				{
					control: this.$.panelBody,
					properties: {
						"height"  : "auto"
					}
				}]
			}
		});

		this.$.header.animateExpand();
		this.$.animator.play();
	},
	animationComplete: function(inSender, inEvent) {
		switch (inEvent.animationName) {
			case "preTransition":
				this.preTransitionComplete();
				break;
			case "postTransition":
				this.postTransitionComplete();
				break;
		}
	}
});<commit_msg>Reduce useless condition check.<commit_after>enyo.kind({
	name : "moon.Panel",
	kind: "FittableRows",
	fit : true,
	classes: "moon-panel",
	published: {
		index: 0,
		title: "Title",
		titleBelow: ""
    },
	events : {
    	//* This panel has completed it's pre-arrangement transition
		onPreTransitionComplete: "",
		//* This panel has completed it's post-arrangement transition
		onPostTransitionComplete: ""
	},
	panelTools : [
		{name: "header", kind: "moon.Header"},
		{name: "panelBody", fit: true, classes: "moon-panel-body"},
		{name: "animator", kind: "StyleAnimator", onComplete: "animationComplete"}
	],
	headerComponents: [
		{content: "This is a TEST!"}
	],
	isBreadcrumb: false,

	create: function() {
		this.inherited(arguments);
		this.$.header.createComponents(this.headerComponents);
	},
	initComponents: function() {
		this.createTools();
		this.controlParentName = "panelBody";
		this.discoverControlParent();
		this.inherited(arguments);
	},
	createTools: function() {
		this.createComponents(this.panelTools);
	},
	rendered: function() {
		this.inherited(arguments);
		this.setHeader({
			titleAbove: this.getIndex(),
			title: this.getTitle(),
			titleBelow: this.getTitleBelow(),
		});
	},
	titleChanged: function() {
		this.setHeader({
			title: this.getTitle(),
		});
	},
	titleBelowChanged: function() {
		this.setHeader({
			titleBelow: this.getTitleBelow(),
		});
	},
	preTransitionComplete: function() {
		this.isBreadcrumb = true;
		this.doPreTransitionComplete();
	},
	postTransitionComplete: function() {
		this.isBreadcrumb = false;
		this.doPostTransitionComplete();
	},
	setHeader: function(inData) {
		this.$.header.setTitleAbove(inData.titleAbove);
		this.$.header.setTitle(inData.title);
		this.$.header.setTitleBelow(inData.titleBelow);
	},
	/**
		@param thisIndex panel index in this.container
	*/
	preTransition: function(thisIndex, inFromIndex, inToIndex) {
		//var myIndex = this.container.getPanels().indexOf(this);
		var myIndex = thisIndex;
		if (!this.isBreadcrumb && this.container.layout.isBreadcrumb(myIndex, inToIndex)) {
			this.shrinkPanel();
			return true;
		}

		return false;
	},
	postTransition: function(thisIndex, inFromIndex, inToIndex) {
		//var myIndex = this.container.getPanels().indexOf(this);
		var myIndex = thisIndex;
		if (this.isBreadcrumb && !this.container.layout.isBreadcrumb(myIndex, inToIndex)) {
			this.growPanel();
			return true;
		}

		return false;
	},
	shrinkPanel: function() {
		this.$.animator.newAnimation({
			animationName: "preTransition",
			duration: 800,
			timingFunction: "cubic-bezier(.42, 0, .16, 1.1)",
			keyframes: {
				0: [{
					control: this.$.panelBody,
					properties: {
						"height" : "current"
					}
				}],
				25: [{
					control: this.$.panelBody,
					properties: {
						"opacity" : "1"
					}
				}],
				50: [{
					control: this.$.panelBody,
					properties: {
						"height"  : "0px",
						"opacity" : "0"
					}
				},
				{
					control: this,
					properties: {
						"width"     : "current",
						"min-width" : "current",
						"max-width" : "current"
					}
				}],
				100: [{
					control: this,
					properties: {
						"width" : "200px",
						"min-width" : "200px",
						"max-width" : "200px"
					}
				}]
			}
		});

		this.$.header.animateCollapse();
		this.$.animator.play();
	},
	growPanel: function() {
		this.$.animator.newAnimation({
			animationName: "postTransition",
			duration: 800,
			timingFunction: "cubic-bezier(.42, 0, .16, 1.1)",
			keyframes: {
				0: [{
					control: this,
					properties: {
						"width"     : "current",
						"min-width" : "current",
						"max-width" : "current"
					}
				}],
				25: [{
					control: this,
					properties: {
						"width"     : this.width+"px",
						"min-width" : this.width+"px",
						"max-width" : this.width+"px"
					}
				},
				{
					control: this.$.panelBody,
					properties: {
						"height"  : "current",
						"opacity" : "current"
					}
				}],
				75: [{
					control: this.$.panelBody,
					properties: {
						"opacity" : "1"
					}
				}],
				100: [
				{
					control: this.$.panelBody,
					properties: {
						"height"  : "auto"
					}
				}]
			}
		});

		this.$.header.animateExpand();
		this.$.animator.play();
	},
	animationComplete: function(inSender, inEvent) {
		switch (inEvent.animationName) {
			case "preTransition":
				this.preTransitionComplete();
				break;
			case "postTransition":
				this.postTransitionComplete();
				break;
		}
	}
});<|endoftext|>


<commit_before>enyo.kind({
	name : "moon.Panel",
	kind : "Control",
	fit : true,
	realtimeFit : true,
	clientObject : null,
	spaceHeight : 100,

	create : function(oSender, oEvent){
		this.inherited(arguments);

		if(arguments[0].header){
			this.setHeader( arguments[0].header );
		}
	},

	events : {
		onTapHandler : ""
	},

	fadeIn : function(){
		this.$.layer.applyStyle("opacity",1.0);
		this.$.space.applyStyle("height","0px");
	},

	fadeOut : function(){
		this.$.layer.applyStyle("opacity",.0);
		this.$.space.applyStyle("height", this.spaceHeight + "px");
	},

	components : [
		{name : "panel", components : [
			{kind : "FittableRows", classes :"moon moon-sample enyo-fit", components : [
				// header
				{name : "header", style:"padding:20px;height:150px", components : [
					{name : "index", style:"font-size:20px", content :""},
					{name : "title", style:"font-size:60px", content :""}
				]},

				// divider
				{ name : "divider", kind : "moon.Divider"},

				// space : this space is using for transition annimation effect
				{ name : "space",
				 	style : "width: 0px; height:" + this.spaceHeight + "px;" +
				            "-webkit-transition: height .35s ease;",
				},

				// client
				{ name : "client", style : "margin-left : 20px", ontap : "tapHandler",
				  components : [{
				  		name : "layer",
					 	style : "opacity : .0;" +
					            "-webkit-transition: opacity .35s ease",
				  }]
				}
			]}
		]}
	],

	tapHandler : function(inSenter, inEvent){
		var tIndex = this.$.layer.children.indexOf(inEvent.originator);
		//this.doTapHandler({index : tIndex })
		this.doTapHandler( inEvent.originator );
	},

	// header setting
	setHeader : function(pObj){
		this.$.index.setContent("0" + pObj.index);
		this.$.title.setContent(pObj.title);

		this.fadeIn();
	},

	addClient : function(pArray){
		this.fadeOut();

		setTimeout( enyo.bind(this, function(){
			// destory
			this.destoryClient();

			// create
			this.$.layer.createComponents(pArray,{owner:this});
			this.$.layer.render();
			this.fadeIn();
		}), 500 );
	},

	destoryClient : function(){
		var tArray = this.$.layer.children;
		for(var i=0;i<tArray.length;i++){
			if(tArray[i].destory) tArray[i].destory();
		}
		this.$.layer.children = [];
	}
});<commit_msg>GF-3217: Add preTransitionStart/Finish event<commit_after>enyo.kind({
	name : "moon.Panel",
	fit : true,
	realtimeFit : true,
	clientObject : null,
	spaceHeight : 100,
	published: {
		/**
			_transitionReady_ indicates that this object is ready to transit.
			If this object does not have any transition or it has and conducted already,
			true value will be assigned.
			Otherhand, if this object has some transition and conducted yet, false will be assinged.
			Default value is null.
		*/
		transitionReady: null
    },

    events: {
		onTapHandler : ""
    	/**
    		Notify that this object will transit.
    	*/
    	onPreTransitionStart: "",
    	/**
    		Notify that this object just finished its transition
    	*/
    	onPreTransitionFinish: "",
    },

	handlers: {
    	onTransitionFinish: "finishPreTransition"
    },

	create : function(oSender, oEvent){
		this.inherited(arguments);

		if(arguments[0].header){
			this.setHeader( arguments[0].header );
		}
	},
	fadeIn : function(){
		this.$.layer.applyStyle("opacity",1.0);
		this.$.space.applyStyle("height","0px");
	},

	fadeOut : function(){
		this.$.layer.applyStyle("opacity",.0);
		this.$.space.applyStyle("height", this.spaceHeight + "px");
	},

	components : [
		{name : "panel", components : [
			{kind : "FittableRows", classes :"moon moon-sample enyo-fit", components : [
				// header
				{name : "header", style:"padding:20px;height:150px", components : [
					{name : "index", style:"font-size:20px", content :""},
					{name : "title", style:"font-size:60px", content :""}
				]},

				// divider
				{ name : "divider", kind : "moon.Divider"},

				// space : this space is using for transition annimation effect
				{ name : "space",
				 	style : "width: 0px; height:" + this.spaceHeight + "px;" +
				            "-webkit-transition: height .35s ease;",
				},

				// client
				{ name : "client", style : "margin-left : 20px", ontap : "tapHandler",
				  components : [{
				  		name : "layer",
					 	style : "opacity : .0;" +
					            "-webkit-transition: opacity .35s ease",
				  }]
				}
			]}
		]}
	],

	tapHandler : function(inSenter, inEvent){
		var tIndex = this.$.layer.children.indexOf(inEvent.originator);
		//this.doTapHandler({index : tIndex })
		this.doTapHandler( inEvent.originator );
	},

	// header setting
	setHeader : function(pObj){
		this.$.index.setContent("0" + pObj.index);
		this.$.title.setContent(pObj.title);

		this.fadeIn();
	},

	addClient : function(pArray){
		this.fadeOut();

		setTimeout( enyo.bind(this, function(){
			// destory
			this.destoryClient();

			// create
			this.$.layer.createComponents(pArray,{owner:this});
			this.$.layer.render();
			this.fadeIn();
		}), 500 );
	},

	destoryClient : function(){
		var tArray = this.$.layer.children;
		for(var i=0;i<tArray.length;i++){
			if(tArray[i].destory) tArray[i].destory();
		}
		this.$.layer.children = [];
	},
	/**
		If this object has internal transition, set transitionReady as false to notify that
		it is not prepared to be transited by arranger.
	*/
	startPreTransition: function() {
		this.setTransitionReady(false);
		this.firePreTransitionStart();
	},

	firePreTransitionStart: function() {
		this.doPreTransitionStart();
	},

	finishPreTransition: function() {
		if (this.transitionReady != null) {
			this.setTransitionReady(true);
			this.firePreTransitionFinish();
		}
	},

	firePreTransitionFinish: function() {
		this.doPreTransitionFinish();
	},
});<|endoftext|>


<commit_before>import {
  validateIsArray,
  createValidateMinCount,
  createValidateMaxCount,
} from '../validators.js';
import {
  combine,
  isArray,
  each,
} from '../utils.js';

const getOptions = (options) => {
  const newOptions = {};
  each(options, (value, key) => {
    if (key.charAt(0) === '$' && key.charAt(1) === '.') {
      newOptions[key.substr(2)] = value;
    }
  });
  return newOptions;
};

const pluginArray = {
  compile: compiler => next => (validator, schemaDef, schemaOptions) => {
    if (isArray(schemaDef) && schemaDef.length === 1) {
      const {
        label,
        minCount,
        maxCount,
        defaultValue,
        ...options
      } = schemaOptions;
      const $ = compiler.compile({}, schemaDef[0], getOptions(options));
      return next({
        ...validator,
        $,
        isArray: true,
        typeName: `array of ${$.typeName}`,
        validate: combine([
          validateIsArray,
          minCount !== undefined && createValidateMinCount(minCount),
          maxCount !== undefined && createValidateMaxCount(maxCount),
          (value) => {
            const errors = value.map(x => $.validate(x));
            return errors.some(err => !!err) ? { errors } : undefined;
          },
        ]),
        clean: (value = defaultValue) => {
          if (!isArray(value)) {
            return value;
          }
          return value.map(x => $.clean(x));
        },
      }, schemaDef, { label });
    }
    return next(validator, schemaDef, schemaOptions);
  },
  mixin(Schema) {
    Object.assign(Schema, {
      arrayOf: (schemaDef, schemaOptions) =>
        new Schema([schemaDef], schemaOptions),
    });
  },
};

export default pluginArray;
<commit_msg>Fix array not passing all options down the stream<commit_after>import {
  validateIsArray,
  createValidateMinCount,
  createValidateMaxCount,
} from '../validators.js';
import {
  combine,
  isArray,
  each,
} from '../utils.js';

const getOptions = (options) => {
  const newOptions = {};
  each(options, (value, key) => {
    if (key.charAt(0) === '$' && key.charAt(1) === '.') {
      newOptions[key.substr(2)] = value;
    }
  });
  return newOptions;
};

const pluginArray = {
  compile: compiler => next => (validator, schemaDef, schemaOptions) => {
    if (isArray(schemaDef) && schemaDef.length === 1) {
      const {
        minCount,
        maxCount,
        defaultValue,
        ...options
      } = schemaOptions;
      const $ = compiler.compile({}, schemaDef[0], getOptions(options));
      return next({
        ...validator,
        $,
        isArray: true,
        typeName: `array of ${$.typeName}`,
        validate: combine([
          validateIsArray,
          minCount !== undefined && createValidateMinCount(minCount),
          maxCount !== undefined && createValidateMaxCount(maxCount),
          (value) => {
            const errors = value.map(x => $.validate(x));
            return errors.some(err => !!err) ? { errors } : undefined;
          },
        ]),
        clean: (value = defaultValue) => {
          if (!isArray(value)) {
            return value;
          }
          return value.map(x => $.clean(x));
        },
      }, schemaDef, schemaOptions);
    }
    return next(validator, schemaDef, schemaOptions);
  },
  mixin(Schema) {
    Object.assign(Schema, {
      arrayOf: (schemaDef, schemaOptions) =>
        new Schema([schemaDef], schemaOptions),
    });
  },
};

export default pluginArray;
<|endoftext|>


<commit_before>"use strict"

/*
 * A generic pouch adapter
 */
var PouchAdapter = function(opts, callback) {
  var api = Pouch.adapters[opts.adapter](opts, callback);

  api.replicate = {};

  if (!api.hasOwnProperty('post')) {
    api.post = function (doc, opts, callback) {
      if (typeof opts === 'function') {
        callback = opts;
        opts = {};
      }
      return api.bulkDocs({docs: [doc]}, opts, yankError(callback));
    };
  }

  if (!api.hasOwnProperty('put')) {

    api.put = function(doc, opts, callback) {
      if (typeof opts === 'function') {
        callback = opts;
        opts = {};
      }

      if (!doc || !('_id' in doc)) {
        return call(callback, Pouch.Errors.MISSING_ID);
      }
      return api.bulkDocs({docs: [doc]}, opts, yankError(callback));
    };

  }

  if (!api.hasOwnProperty('putAttachment')) {
    api.putAttachment = api.putAttachment = function (id, rev, doc, type, callback) {
      id = parseDocId(id);
      api.get(id.docId, {attachments: true}, function(err, obj) {
        obj._attachments || (obj._attachments = {});
        obj._attachments[id.attachmentId] = {
          content_type: type,
          data: btoa(doc)
        }
        api.put(obj, callback);
      });
    };
  }

  if (!api.hasOwnProperty('removeAttachment')) {
     api.removeAttachment = function (id, rev, callback) {
      id = parseDocId(id);
      api.get(id.docId, function(err, obj) {
        if (err) {
          call(callback, err);
          return;
        }

        if (obj._rev != rev) {
          call(callback, Pouch.Errors.REV_CONFLICT);
          return;
        }

        obj._attachments || (obj._attachments = {});
        delete obj._attachments[id.attachmentId];
        api.put(obj, callback);
      });
    };
  }

  if (!api.hasOwnProperty('remove')) {
    api.remove = function (doc, opts, callback) {
      if (typeof opts === 'function') {
        callback = opts;
        opts = {};
      }
      if (opts === undefined) {
        opts = {};
      }
      opts.was_delete = true;
      var newDoc = extend(true, {}, doc);
      newDoc._deleted = true;
      return api.bulkDocs({docs: [newDoc]}, opts, yankError(callback));
    };

  }

  if (!api.hasOwnProperty('revsDiff')) {
    api.revsDiff = function (req, opts, callback) {
      if (typeof opts === 'function') {
        callback = opts;
        opts = {};
      }
      var ids = Object.keys(req);
      var count = 0;
      var missing = {};

      function readDoc(err, doc, id) {
        req[id].map(function(revId) {
          var matches = function(x) { return x.rev !== revId; };
          if (!doc || doc._revs_info.every(matches)) {
            if (!missing[id]) {
              missing[id] = {missing: []};
            }
            missing[id].missing.push(revId);
          }
        });

        if (++count === ids.length) {
          return call(callback, null, missing);
        }
      }

      ids.map(function(id) {
        api.get(id, {revs_info: true}, function(err, doc) {
          readDoc(err, doc, id);
        });
      });
    };

  }

  api.replicate.from = function (url, opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    return Pouch.replicate(url, api, opts, callback);
  };

  api.replicate.to = function (dbName, opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    return Pouch.replicate(api, dbName, opts, callback);
  };

  return api;
};

if (typeof module !== 'undefined' && module.exports) {
  module.exports = PouchAdapter;
}
<commit_msg>(#416) - Fix most lint errors in pouch.adapter.js<commit_after>/*globals yankError: false, extend: false, call: false, parseDocId: false */

"use strict";

/*
 * A generic pouch adapter
 */
var PouchAdapter = function(opts, callback) {
  var api = Pouch.adapters[opts.adapter](opts, callback);

  api.replicate = {};

  if (!api.hasOwnProperty('post')) {
    api.post = function (doc, opts, callback) {
      if (typeof opts === 'function') {
        callback = opts;
        opts = {};
      }
      return api.bulkDocs({docs: [doc]}, opts, yankError(callback));
    };
  }

  if (!api.hasOwnProperty('put')) {

    api.put = function(doc, opts, callback) {
      if (typeof opts === 'function') {
        callback = opts;
        opts = {};
      }

      if (!doc || !('_id' in doc)) {
        return call(callback, Pouch.Errors.MISSING_ID);
      }
      return api.bulkDocs({docs: [doc]}, opts, yankError(callback));
    };

  }

  if (!api.hasOwnProperty('putAttachment')) {
    api.putAttachment = api.putAttachment = function (id, rev, doc, type, callback) {
      id = parseDocId(id);
      api.get(id.docId, {attachments: true}, function(err, obj) {
        obj._attachments = obj._attachments || {};
        obj._attachments[id.attachmentId] = {
          content_type: type,
          data: btoa(doc)
        };
        api.put(obj, callback);
      });
    };
  }

  if (!api.hasOwnProperty('removeAttachment')) {
     api.removeAttachment = function (id, rev, callback) {
      id = parseDocId(id);
      api.get(id.docId, function(err, obj) {
        if (err) {
          call(callback, err);
          return;
        }

        if (obj._rev !== rev) {
          call(callback, Pouch.Errors.REV_CONFLICT);
          return;
        }

        obj._attachments = obj._attachments || {};
        delete obj._attachments[id.attachmentId];
        api.put(obj, callback);
      });
    };
  }

  if (!api.hasOwnProperty('remove')) {
    api.remove = function (doc, opts, callback) {
      if (typeof opts === 'function') {
        callback = opts;
        opts = {};
      }
      if (opts === undefined) {
        opts = {};
      }
      opts.was_delete = true;
      var newDoc = extend(true, {}, doc);
      newDoc._deleted = true;
      return api.bulkDocs({docs: [newDoc]}, opts, yankError(callback));
    };

  }

  if (!api.hasOwnProperty('revsDiff')) {
    api.revsDiff = function (req, opts, callback) {
      if (typeof opts === 'function') {
        callback = opts;
        opts = {};
      }
      var ids = Object.keys(req);
      var count = 0;
      var missing = {};

      function readDoc(err, doc, id) {
        req[id].map(function(revId) {
          var matches = function(x) { return x.rev !== revId; };
          if (!doc || doc._revs_info.every(matches)) {
            if (!missing[id]) {
              missing[id] = {missing: []};
            }
            missing[id].missing.push(revId);
          }
        });

        if (++count === ids.length) {
          return call(callback, null, missing);
        }
      }

      ids.map(function(id) {
        api.get(id, {revs_info: true}, function(err, doc) {
          readDoc(err, doc, id);
        });
      });
    };

  }

  api.replicate.from = function (url, opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    return Pouch.replicate(url, api, opts, callback);
  };

  api.replicate.to = function (dbName, opts, callback) {
    if (typeof opts === 'function') {
      callback = opts;
      opts = {};
    }
    return Pouch.replicate(api, dbName, opts, callback);
  };

  return api;
};

if (typeof module !== 'undefined' && module.exports) {
  module.exports = PouchAdapter;
}
<|endoftext|>


<commit_before>$(document).ready(function() {

  CheckLiveValidations.checkSignUpValidations();
  DeleteSnippetWidget.autoDeleteIncompleteSnippet();
  SaveWidget.autoSaveContent();
  warnBeforePublish();
  indexPage();

});

var warnBeforePublish = function() {
  $('#story_published_true').on("click", function(){
    $('#publish-warning').show();
  })
}

var indexPage = function() {
  var fullPage = document.getElementById('fullpage');
  if(fullPage) {
    $('#fullpage').fullpage({
      menu: true,
      anchors:['firstSlide', 'secondSlide'],
      navigation: true,
      navigationPosition: 'right',
      navigationTooltips: ['firstSlide', 'secondSlide'],
      slidesNavigation: true,
      slidesNavPosition: 'bottom',
    });
  }
}
<commit_msg>Vote up and vote down ajax calls<commit_after>$(document).ready(function() {

  CheckLiveValidations.checkSignUpValidations();
  DeleteSnippetWidget.autoDeleteIncompleteSnippet();
  SaveWidget.autoSaveContent();
  warnBeforePublish();
  indexPage();
  voteUpdate();
  voteDown();
});

var warnBeforePublish = function() {
  $('#story_published_true').on("click", function(){
    $('#publish-warning').show();
  })
}

var indexPage = function() {
  var fullPage = document.getElementById('fullpage');
  if(fullPage) {
    $('#fullpage').fullpage({
      menu: true,
      anchors:['firstSlide', 'secondSlide'],
      navigation: true,
      navigationPosition: 'right',
      navigationTooltips: ['firstSlide', 'secondSlide'],
      slidesNavigation: true,
      slidesNavPosition: 'bottom',
    });
  }
}

var voteUpdate = function() {
  var voteFormExists = document.getElementsByClassName('edit_story')[0];

  if (voteFormExists) {
    $('.edit_story').on('submit', function(event) {
      event.preventDefault();
      var $target = $(event.target);
      $target.hide();
      var $url = $('.edit_story')[0].action;
      $.ajax({
        type: "PATCH",
        url: $url,
        dataType: "text"
      }).done(function(response) {
        $('.vote-count').html(response);
      });
    });
  }
}

var voteDown = function() {
  var downVoteButton = document.getElementsByClassName('button_to')[0];
  if (downVoteButton) {
    console.log("hello");
    $('.button_to').on('submit', function(event) {
      event.preventDefault();
      var $target = $(event.target);
      $target.hide();
      var $url = $('.button_to')[0].action;
      $.ajax({
        type: "DELETE",
        url: $url,
        dataType: "text"
      }).done(function(response) {
        $('.vote-count').html(response);
      });
    });
  }
}

<|endoftext|>


<commit_before>$(document).on("ready page:load", function() {
  var dropAtPlay;
  var playPauseButton = $('.play-button');
  var state = {
    isPlaying: false,
    isBuffering: false
  };
  hideForwardAndRewindButton();
  var options = {
    onfinish: function() {
      playPauseButton.html('');
      hideForwardAndRewindButton();
    }
  }

  function showForwardAndRewindButton() {
    $(".forward").show();
    $(".rewind").show();
  }

  function hideForwardAndRewindButton() {
    $(".forward").hide();
    $(".rewind").hide();
  }

  function setupBufferingState() {
    if (state.isBuffering) {
      hideForwardAndRewindButton();
      playPauseButton.html('');
      state.isBuffering = false;
    } else {
      hideForwardAndRewindButton();
      playPauseButton.html('');
      state.isBuffering = true;
    }
  }

  function setupPlayOrPauseState(){
    if(state.isPlaying) {
      hideForwardAndRewindButton();
      dropAtPlay.pause();
      playPauseButton.html('');
      state.isPlaying = false;
    }else {
      showForwardAndRewindButton();
      dropAtPlay.play();
      playPauseButton.html('');
      state.isPlaying = true;
    }
  }

  SC.initialize({
    client_id: '69e93cf2209402f6f3137a6452cf498f'
  });

  $('.rewind').on('click', function(event) {
    //pause();
    var rewind = dropAtPlay.position - 5000;
    if (rewind > 0 && rewind < dropAtPlay.duration) {
      dropAtPlay.setPosition(rewind);
    } else {
      dropAtPlay.setPosition(0);
    }
  });

  $('.forward').on('click', function(event) {
    //pause();
    var forward = dropAtPlay.position + 5000;
    if (forward < dropAtPlay.duration) {
      dropAtPlay.setPosition(forward);
    } else {
      dropAtPlay.setPosition(dropAtPlay.duration);
    }
  });

  //setup on click
  playPauseButton.on('click', function(event) {
    if (dropAtPlay) {
      showForwardAndRewindButton();
      setupPlayOrPauseState();
    }else{
      hideForwardAndRewindButton();
      setupBufferingState();
    }
  });

  //Fetch stream
  setTimeout(function() {
    if (typeof(dropAtSC) != "undefined") {
      SC.stream(dropAtSC.id, options, function(sound) {
        console.log("Streaming");
        //if we comment this line we can test the else ( if drop is not true)
        dropAtPlay = sound;
        console.log("drop ready");
        if (state.isBuffering) {
          showForwardAndRewindButton();
          dropAtPlay.play();
          playPauseButton.html('');
          state.isPlaying = true;
          state.isBuffering = false;

        }
      });
    }
  }, 3000);
});
<commit_msg>change API calls based on SC documentation<commit_after>$(document).on("ready page:load", function() {
  var dropAtPlay;
  var playPauseButton = $('.play-button');
  var state = {
    isPlaying: false,
    isBuffering: false
  };
  hideForwardAndRewindButton();
  var options = {
    onfinish: function() {
      playPauseButton.html('');
      hideForwardAndRewindButton();
    }
  }

  function showForwardAndRewindButton() {
    $(".forward").show();
    $(".rewind").show();
  }

  function hideForwardAndRewindButton() {
    $(".forward").hide();
    $(".rewind").hide();
  }

  function setupBufferingState() {
    if (state.isBuffering) {
      hideForwardAndRewindButton();
      playPauseButton.html('');
      state.isBuffering = false;
    } else {
      hideForwardAndRewindButton();
      playPauseButton.html('');
      state.isBuffering = true;
    }
  }

  function setupPlayOrPauseState(){
    if(state.isPlaying) {
      hideForwardAndRewindButton();
      dropAtPlay.pause();
      playPauseButton.html('');
      state.isPlaying = false;
    }else {
      showForwardAndRewindButton();
      dropAtPlay.play();
      playPauseButton.html('');
      state.isPlaying = true;
    }
  }

  SC.initialize({
    client_id: '69e93cf2209402f6f3137a6452cf498f'
  });

  $('.rewind').on('click', function(event) {
    //pause();
    var rewind = dropAtPlay.currentTime() - 5000;
    if (rewind > 0 && rewind < dropAtPlay.streamInfo.duration) {
      dropAtPlay.seek(rewind);
    } else {
      dropAtPlay.seek(0);
    }
  });

  $('.forward').on('click', function(event) {
    //pause();
    var forward = dropAtPlay.currentTime() + 5000;
    if (forward < dropAtPlay.streamInfo.duration) {
      dropAtPlay.seek(forward);
    } else {
      dropAtPlay.seek(dropAtPlay.streamInfo.duration);
    }
  });

  //setup on click
  playPauseButton.on('click', function(event) {
    if (dropAtPlay) {
      showForwardAndRewindButton();
      setupPlayOrPauseState();
    }else{
      hideForwardAndRewindButton();
      setupBufferingState();
    }
  });

  //Fetch stream
  setTimeout(function() {
    if (typeof(dropAtSC) !== "undefined") {
      SC.stream('/tracks/' + dropAtSC.id).then(function(sound) {
        console.log("Streaming");
        if (sound.options.protocols[0] === 'rtmp') {
            sound.options.protocols.splice(0, 1);
        }
        dropAtPlay = sound;
        console.log("drop ready");
        if (state.isBuffering) {
          showForwardAndRewindButton();
          dropAtPlay.play();
          playPauseButton.html('');
          state.isPlaying = true;
          state.isBuffering = false;
        }
      });
    }
  }, 3000);
});
<|endoftext|>


<commit_before>import _ from 'lodash';
import path from 'path';
import net from 'net';
import { Observable, Disposable } from 'rx';
import { fs } from './promisify';

const spawnOg = require('child_process').spawn;
const isWindows = process.platform === 'win32';

const d = require('debug')('serf:promise-array');

export function asyncMap(array, selector, maxConcurrency=4) {
  return Observable.from(array)
    .map((k) =>
      Observable.defer(() =>
        Observable.fromPromise(selector(k))
          .map((v) => ({ k, v }))))
    .merge(maxConcurrency)
    .reduce((acc, kvp) => {
      acc[kvp.k] = kvp.v;
      return acc;
    }, {})
    .toPromise();
}

export async function asyncReduce(array, selector, seed) {
  let acc = seed;
  for (let x of array) {
    acc = await selector(acc, x);
  }

  return acc;
}

export function delay(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

export function statSyncNoException(file) {
  try {
    return fs.statSync(file);
  } catch (e) {
    return null;
  }
}

function runDownPath(exe) {
  // NB: Windows won't search PATH looking for executables in spawn like
  // Posix does

  // Files with any directory path don't get this applied
  if (exe.match(/\\\//)) {
    return exe;
  }

  let target = path.join('.', exe);
  if (statSyncNoException(target)) {
    return target;
  }

  let haystack = process.env.PATH.split(isWindows ? ';' : ':');
  for (let p of haystack) {
    let needle = path.join(p, exe);
    if (statSyncNoException(needle)) return needle;
  }

  return target;
}

export function spawnDetached(exe, params, opts=null) {
  const newParams = [exe].concat(params);
  if (!isWindows) newParams.unshift(require.resolve('./spawn-child'));

  let target = isWindows ?
    path.join(__dirname, '..', 'vendor', 'jobber', 'jobber.exe') :
    process.execPath;

  let options = _.assign({ detached: true, jobber: true }, opts || {});
  return spawn(target, newParams, options);
}

export function spawn(exe, params, opts=null) {
  let spawnObs = Observable.create((subj) => {
    let proc = null;

    let fullPath = runDownPath(exe);
    if (!opts) {
      d(`spawning process: ${fullPath} ${params.join()}`);
      proc = spawnOg(fullPath, params);
    } else {
      d(`spawning process: ${fullPath} ${params.join()}, ${JSON.stringify(opts)}`);
      proc = spawnOg(fullPath, params, _.omit(opts, 'jobber'));
    }

    let stdout = '';
    let bufHandler = (b) => {
      let chunk = b.toString();

      stdout += chunk;
      subj.onNext(chunk);
    };

    proc.stdout.on('data', bufHandler);
    proc.stderr.on('data', bufHandler);
    proc.on('error', (e) => subj.onError(e));

    proc.on('close', (code) => {
      if (code === 0) {
        subj.onCompleted();
      } else {
        subj.onError(new Error(`Failed with exit code: ${code}\nOutput:\n${stdout}`));
      }
    });

    return Disposable.create(() => {
      if (!opts.jobber) {
        proc.kill();
        return;
      }

      if (isWindows) {
        // NB: Connecting to Jobber's named pipe will kill it
        net.connect(`\\\\.\\pipe\\jobber-${proc.pid}`);
      } else {
        // Send secret handshake to spawn-child
        proc.stdin.write(new Buffer('__die__'));
      }

      setTimeout(() => proc.kill(), 5*1000);
    });
  });

  return spawnObs.reduce((acc, x) => acc += x, '').publishLast().refCount();
}
<commit_msg>Don't attempt to close if we exit super fast<commit_after>import _ from 'lodash';
import path from 'path';
import net from 'net';
import { Observable, Disposable } from 'rx';
import { fs } from './promisify';

const spawnOg = require('child_process').spawn;
const isWindows = process.platform === 'win32';

const d = require('debug')('serf:promise-array');

export function asyncMap(array, selector, maxConcurrency=4) {
  return Observable.from(array)
    .map((k) =>
      Observable.defer(() =>
        Observable.fromPromise(selector(k))
          .map((v) => ({ k, v }))))
    .merge(maxConcurrency)
    .reduce((acc, kvp) => {
      acc[kvp.k] = kvp.v;
      return acc;
    }, {})
    .toPromise();
}

export async function asyncReduce(array, selector, seed) {
  let acc = seed;
  for (let x of array) {
    acc = await selector(acc, x);
  }

  return acc;
}

export function delay(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

export function statSyncNoException(file) {
  try {
    return fs.statSync(file);
  } catch (e) {
    return null;
  }
}

function runDownPath(exe) {
  // NB: Windows won't search PATH looking for executables in spawn like
  // Posix does

  // Files with any directory path don't get this applied
  if (exe.match(/\\\//)) {
    return exe;
  }

  let target = path.join('.', exe);
  if (statSyncNoException(target)) {
    return target;
  }

  let haystack = process.env.PATH.split(isWindows ? ';' : ':');
  for (let p of haystack) {
    let needle = path.join(p, exe);
    if (statSyncNoException(needle)) return needle;
  }

  return target;
}

export function spawnDetached(exe, params, opts=null) {
  const newParams = [exe].concat(params);
  if (!isWindows) newParams.unshift(require.resolve('./spawn-child'));

  let target = isWindows ?
    path.join(__dirname, '..', 'vendor', 'jobber', 'jobber.exe') :
    process.execPath;

  let options = _.assign({ detached: true, jobber: true }, opts || {});
  return spawn(target, newParams, options);
}

export function spawn(exe, params, opts=null) {
  let spawnObs = Observable.create((subj) => {
    let proc = null;

    let fullPath = runDownPath(exe);
    if (!opts) {
      d(`spawning process: ${fullPath} ${params.join()}`);
      proc = spawnOg(fullPath, params);
    } else {
      d(`spawning process: ${fullPath} ${params.join()}, ${JSON.stringify(opts)}`);
      proc = spawnOg(fullPath, params, _.omit(opts, 'jobber'));
    }

    let stdout = '';
    let bufHandler = (b) => {
      let chunk = b.toString();

      stdout += chunk;
      subj.onNext(chunk);
    };

    let noClose = false;
    proc.stdout.on('data', bufHandler);
    proc.stderr.on('data', bufHandler);
    proc.on('error', (e) => {
      noClose = true;
      subj.onError(e);
    });

    proc.on('close', (code) => {
      noClose = true;
      if (code === 0) {
        subj.onCompleted();
      } else {
        subj.onError(new Error(`Failed with exit code: ${code}\nOutput:\n${stdout}`));
      }
    });

    return Disposable.create(() => {
      if (noClose) return;
      if (!opts.jobber) {
        proc.kill();
        return;
      }

      if (isWindows) {
        // NB: Connecting to Jobber's named pipe will kill it
        net.connect(`\\\\.\\pipe\\jobber-${proc.pid}`);
      } else {
        // Send secret handshake to spawn-child
        proc.stdin.write(new Buffer('__die__'));
      }

      setTimeout(() => proc.kill(), 5*1000);
    });
  });

  return spawnObs.reduce((acc, x) => acc += x, '').publishLast().refCount();
}
<|endoftext|>


<commit_before>var lr = require('./linear_regression.js');

var requestsHandledPerInterval = 10
var list = []

function calculateOptimalServers(redisClient, timeInterval, seriesTag, callback){
    redisClient.get(seriesTag + ":requests:" + timeInterval, function(err, value){
        list.push(Number(value));
        if(list.length == 100){
            var s = "";
            for(var i = 0; i < 100; i++){
                s += list[i] + ","
            }
            console.log(s);
        }

        var optimalServers = Math.ceil(value / requestsHandledPerInterval);
        callback(timeInterval, optimalServers);
    });
}

function createEmitOptimal(io, series){
    return function(timeInterval, optimalServers){
        io.emit('optimal-servers', JSON.stringify({"series": series, "timeInterval": timeInterval, "optimalServers": optimalServers}));
    }
}

function predictOptimal(redisClient, timeInterval, callback){
    calculateOptimalServers(redisClient, timeInterval, "training", function(tiMinusOneYear, tMinusOneYear){
        calculateOptimalServers(redisClient, timeInterval - 10000, "testing", function(tiMinusOneHour, tMinusOneHour){

            console.log("ti - 10000" + (timeInterval - 10000));

            if(timeInterval - 10000 < 0){
                callback(tMinusOneYear);
            }
            else {
            callback(lr.predict(tMinusOneYear,tMinusOneHour));
            }
        });
    });
}

function createEmitMLData(io){
    var data = [];
    return function(t_label) {
        return function(timeInterval, optimalServers){
            data.push([t_label, optimalServers]);
            if(data.length == 3){
                data.sort(function(v){
                    return v[0];
                });

                data = data.map(function(v){
                    return v[1];
                });

                lr.addData(data);
                io.emit('ml-data', JSON.stringify(data));
            }
        }
    }
}

module.exports = {
    emitTrainingData: function(redisClient, io){
        for(var i = 10000; i <= 1000000; i += 10000){
            calculateOptimalServers(redisClient, i, "training", createEmitOptimal(io, "Training_Data"));
        }
    },

    emitTestData: function(redisClient, timeInterval, io){
        if(timeInterval != 10000){
        var add_ml_scalar = createEmitMLData(io);
        calculateOptimalServers(redisClient, timeInterval, "testing", add_ml_scalar(2));
        calculateOptimalServers(redisClient, timeInterval - 10000, "testing", add_ml_scalar(1));
        calculateOptimalServers(redisClient, timeInterval, "training", add_ml_scalar(0));
        }

        calculateOptimalServers(redisClient, timeInterval, "testing", createEmitOptimal(io, "Test_Recording"));
    },

    scale: function(redisClient, timeInterval, io){
        predictOptimal(redisClient, timeInterval, function(prediction){
            io.emit('scale-request', prediction);
            io.emit('optimal-servers', JSON.stringify({"series": "Prediction", "timeInterval": timeInterval, "optimalServers": prediction}));
        });
    }
}

/*var prevInterval = timeInterval - (10 * 1000);
//Calculate true optimal for previous timeframe
redisClient.get("testing:requests:" + prevInterval, function(err,value){
var optimalServers = Math.ceil(value / requestsHandledPerInterval);
io.emit('optimal-servers', JSON.stringify({"timeInterval": timeInterval, "optimalServers": optimalServers}))
});*/
<commit_msg>Fix inital scaling<commit_after>var lr = require('./linear_regression.js');

var requestsHandledPerInterval = 10
var list = []

function calculateOptimalServers(redisClient, timeInterval, seriesTag, callback){
    redisClient.get(seriesTag + ":requests:" + timeInterval, function(err, value){
        list.push(Number(value));
        if(list.length == 100){
            var s = "";
            for(var i = 0; i < 100; i++){
                s += list[i] + ","
            }
            console.log(s);
        }

        var optimalServers = Math.ceil(value / requestsHandledPerInterval);
        callback(timeInterval, optimalServers);
    });
}

function createEmitOptimal(io, series){
    return function(timeInterval, optimalServers){
        io.emit('optimal-servers', JSON.stringify({"series": series, "timeInterval": timeInterval, "optimalServers": optimalServers}));
    }
}

function predictOptimal(redisClient, timeInterval, callback){
    calculateOptimalServers(redisClient, timeInterval, "training", function(tiMinusOneYear, tMinusOneYear){
        calculateOptimalServers(redisClient, timeInterval - 10000, "testing", function(tiMinusOneHour, tMinusOneHour){

            if(tiMinusOneHour == 0){
                callback(tMinusOneYear);
            }
            else {
            callback(lr.predict(tMinusOneYear,tMinusOneHour));
            }
        });
    });
}

function createEmitMLData(io){
    var data = [];
    return function(t_label) {
        return function(timeInterval, optimalServers){
            data.push([t_label, optimalServers]);
            if(data.length == 3){
                data.sort(function(v){
                    return v[0];
                });

                data = data.map(function(v){
                    return v[1];
                });

                lr.addData(data);
                io.emit('ml-data', JSON.stringify(data));
            }
        }
    }
}

module.exports = {
    emitTrainingData: function(redisClient, io){
        for(var i = 10000; i <= 1000000; i += 10000){
            calculateOptimalServers(redisClient, i, "training", createEmitOptimal(io, "Training_Data"));
        }
    },

    emitTestData: function(redisClient, timeInterval, io){
        if(timeInterval != 10000){
        var add_ml_scalar = createEmitMLData(io);
        calculateOptimalServers(redisClient, timeInterval, "testing", add_ml_scalar(2));
        calculateOptimalServers(redisClient, timeInterval - 10000, "testing", add_ml_scalar(1));
        calculateOptimalServers(redisClient, timeInterval, "training", add_ml_scalar(0));
        }

        calculateOptimalServers(redisClient, timeInterval, "testing", createEmitOptimal(io, "Test_Recording"));
    },

    scale: function(redisClient, timeInterval, io){
        predictOptimal(redisClient, timeInterval, function(prediction){
            io.emit('scale-request', prediction);
            io.emit('optimal-servers', JSON.stringify({"series": "Prediction", "timeInterval": timeInterval, "optimalServers": prediction}));
        });
    }
}

/*var prevInterval = timeInterval - (10 * 1000);
//Calculate true optimal for previous timeframe
redisClient.get("testing:requests:" + prevInterval, function(err,value){
var optimalServers = Math.ceil(value / requestsHandledPerInterval);
io.emit('optimal-servers', JSON.stringify({"timeInterval": timeInterval, "optimalServers": optimalServers}))
});*/
<|endoftext|>