示例#1
0
  var getAllContributions = function(users){
    var the_promises = [];

    var orderBy = {created_on : -1};
    if(req.query.orderBy){
      var o = req.query.orderBy;
      switch(o) {
        case "score" :
          orderBy = {score : -1};
          break;
        case "date" :
          orderBy = {created_on : -1};
          break;
        case "title" :
          orderBy = {title : -1};
          break;
      }
    }
    users.forEach(function(user) {
      var deferred = Q.defer();
      Contribution.find({'owner' : user["_id"]}).populate('owner').sort(orderBy).limit(15).exec(function(err, contributions){
        var userView = {
            user: user,
            contributions: contributions
          }
        deferred.resolve(userView);
      });
      the_promises.push(deferred.promise);
    });

    return Q.all(the_promises);
  }
function collectPluginInfos(dirs) {
  // Stop plugman from spewing JSON
  console.log = function() {};
  var ret = [];
  dirs.forEach(function(dir) {
    if (!fs.existsSync(path.join(dir, 'plugin.xml'))) {
      console.warn('Skipping: ' + dir + ' (no plugin.xml found)');
      return;
    }
    var pluginInfo = new cordovalib.PluginInfo(dir);
    ret.push(cordovalib.plugman.raw.info([pluginInfo.id])
    .then(function(infoResult) {
      return cordovalib.plugman.raw.owner(['ls', pluginInfo.id])
      .then(function(npmOwners) {
        return {
          pluginInfo: pluginInfo,
          npmInfo: infoResult,
          npmOwners: npmOwners.map(function(o) { return o.name })
        };
      });
    }, function(e) {
      console.warn('Failed to get info for: ' + pluginInfo.id);
      console.warn(e);
      return {
        pluginInfo: pluginInfo,
        npmInfo: null,
        npmOwners: null
      };
    }));
  });
  return Q.all(ret).finally(function() {
    delete console.log;
  });
}
示例#3
0
router.get('/customers', function(request, response) {
	var ts = new TradeshiftAPIClient(request.session.auth.accessToken);

	Q.all([
		ts.getInvoices(),
		ts.getConnections(),
	]).spread(function(docs, connections) {
		_.forEach(connections, function(connection) {
			_.assign(connection, {
				documents: [],
			});
		});
		_.forEach(docs, function(doc) {
			var connection = _.find(connections, function(connection) {
				return connection.CompanyName === doc.customerName;
			});
			connection.documents.push(doc);
		});
		var data = _.chain(connections)
			.map(function(connection) {
				return {
					connectionId: connection.ConnectionId,
					companyName: connection.CompanyName,
					isReminded: false,
					purchaseCount: _.size(connection.documents),
					lastPurchase: _.max(connection.documents, function(doc) {
						return doc.issueDate.replace(/-/g, '');
					}),
				};
			})
			.filter(function(connection) {
				return !_.isEmpty(connection.lastPurchase);
			})
			.sortBy(function(connection) {
				return connection.lastPurchase.issueDate.replace(/-/g, '');
			})
			.value();
		response.status(200).send(data);
	}).catch(function(error) {
		console.log('Oh snap! Error building connection documents', error);
		response.status(500).send({
			message: error,
		});
	});
});
module.exports.getMSBuildTools = function () {
    var versions = ['12.0', '4.0'];
    // create chain of promises, which returns specific msbuild version object
    // or null, if specific msbuild path not found in registry
    return Q.all(versions.map(function (version) {
        return exec(
            'reg query HKLM\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\' + version + ' /v MSBuildToolsPath'
        ).then(function(output) {
            // fetch msbuild path from 'reg' output
            var msbPath = /MSBuildToolsPath\s+REG_SZ\s+(.*)/i.exec(output);
            if (msbPath) {
                return {version: version, path: msbPath[1]};
            }
            return null;
        });
    })).then(function (versions) {
        // select first msbuild version available, and resolve promise with it
        return versions[0] || versions[1] ?
            Q.resolve(versions[0] || versions[1]) :
            // Reject promise if no msbuild versions found
            Q.reject('MSBuild tools not found');
    });
};
示例#5
0
    shouldRun(meta).then( function(shouldRun) {

        var context = meta['context'];
        var eventID = meta['eventID'];
        var tileName = context['tileName'];

        if ( !shouldRun ) {
            jive.logger.debug("Execution aborted: " + JSON.stringify(meta,4 ));
            done();
            return;
        }

        var next = function() {
            if ( liveNess ) {
                clearTimeout(liveNess);
            }
            redisClient.set( eventID + ':lastrun', new Date().getTime(), function() {
                done();
            });
        };

        var liveNess = setInterval( function() {
            // update the job every 1 seconds to ensure liveness
            job.update();
        }, 1000);

        var handlers;
        if (tileName) {
            var tileEventHandlers = eventHandlers[tileName];
            if ( !tileEventHandlers ) {
                done();
                return;
            }
            handlers = tileEventHandlers[eventID];
        } else {
            handlers = eventHandlers[eventID];
        }

        if ( !handlers ) {
            // could find no handlers for the eventID; we're done
            done();
            return;
        }

        if ( typeof handlers === 'function' ) {
            // normalize single handler into an array
            handlers = [ handlers ];
        }

        var promises = [];
        handlers.forEach( function(handler) {
            var result = handler(context);
            if ( result && result['then'] ) {
                // its a promise
                promises.push( result );
            }
        });

        if ( promises.length > 0 ) {
            q.all( promises ).then(
                // success
                function(result) {
                    if (result) {
                        // if just one result, don't bother storing an array
                        result = result['forEach'] && result.length == 1 ? result[0] : result;
                        job.data['result'] = { 'result' : result };
                        job.update( function() {
                            next();
                        });
                    } else {
                        next();
                    }
                },

                // error
                function(err) {
                    jive.logger.error("Error!", err);
                    job.data['result'] = { 'err' : err };
                    job.update( function() {
                        next();
                    });
                }
            ).done();
        } else {
            next();
        }
    });
示例#6
0
/**
 * Runs a set of named tasks as a single job, where the results of each task are returned.
 * @param job
 * @returns {Promise.<TResult>|*}
 */
function run(job) {
    const tasks = _.pairs(job);

    return Q.all(tasks.map(pair => pair[1]))
        .then(results => _.object(_.zip(tasks.map(pair => pair[0]), results)));
}
示例#7
0
 .then(function () {
     return q.all([
         r.table('pictures').indexCreate('time').run(conn),
         r.table('pictures').indexCreate('place', {geo: true}).run(conn)
     ]);
 });
 beforeEach('wait for sync', function() {
   return q.all([
     object1Sync.manager.waitForSync(),
     object2Sync.manager.waitForSync()
   ])
 });
示例#9
0
	    .then(function(ticketQueryPromises) {
	        return Q.all(ticketQueryPromises);
	    })
示例#10
0
DriverProvider.prototype.teardownEnv = function() {
  return q.all(this.drivers_.map(this.quitDriver.bind(this)));
};
示例#11
0
utils.parseFBData = function (user, data) {
  var deferred = Q.defer();

  var parsedData = [];
  var foursquareVenueQueries = [];

  _.each(data, function (datum) {
    console.log("this is ma datum: " + datum);
    if (datum !== undefined && datum.place) {
      var place = {
        'checkinID': datum.id,
        'name': datum.place.name,
        'lat': datum.place.location.latitude,
        'lng': datum.place.location.longitude,
        'checkinTime': new Date(datum.created_time),
        'likes': 'null',
        'photoSmall': 'null',
        'photoLarge': 'null',
        'caption': 'null',
        'foursquareID': 'null',
        'city': 'null',
        'country': 'null',
        'category': 'null',
        'source': 'facebook'
      }

      if (datum.likes) {
        place.likes = datum.likes.data.length;
      }

       if (datum.updated_time) {
        place.checkinTime = new Date(datum.updated_time);
      }

      if(datum.name) {
        place.caption = datum.name;
      }

      if (datum.picture) {
        place.photoSmall = datum.picture;
      }

      if (datum.source) {
        place.photoLarge = datum.source;
      }

      var latlng = place.lat.toString() + ',' + place.lng.toString();
      
      parsedData.push(place);
      console.log(user, place.name, latlng);
      foursquareVenueQueries.push(foursquareUtils.generateFoursquarePlaceID(user, place.name, latlng));
    }
  });
  console.log("parsedData before: ", parsedData);
  console.log(foursquareVenueQueries);
  

  Q.all(foursquareVenueQueries)
    .then(function (foursquareVenueIDs) {
      _.each(parsedData, function (datum, index) {
        datum.foursquareID = foursquareVenueIDs[index];
      });
      console.log("parsedData: ", parsedData)
      deferred.resolve(parsedData);
    })
    .catch(function (err) {
      deferred.reject(err);
    });

  return deferred.promise;
};
示例#12
0
文件: texcmp.js 项目: 966647/KaTeX
// Process a single test case: rasterize, then create diff
function processTestCase(key) {
    var itm = data[key];
    var tex = "$" + itm.tex + "$";
    if (itm.display) {
        tex = "\\[" + itm.tex + "\\]";
    }
    if (itm.pre) {
        tex = itm.pre.replace("<br>", "\\\\") + tex;
    }
    if (itm.post) {
        tex = tex + itm.post.replace("<br>", "\\\\");
    }
    tex = template.replace(/\$.*\$/, tex.replace(/\$/g, "$$$$"));
    var texFile = path.join(tmpDir, key + ".tex");
    var pdfFile = path.join(tmpDir, key + ".pdf");
    var pngFile = path.join(teximgDir, key + "-pdflatex.png");
    var browserFile = path.join(imagesDir, key + "-firefox.png");
    var diffFile = path.join(diffDir, key + ".png");

    // Step 1: write key.tex file
    var fftLatex = writeFile(texFile, tex).then(function() {
        // Step 2: call "pdflatex key" to create key.pdf
        return execFile("pdflatex", [
            "-interaction", "nonstopmode", key,
        ], {cwd: tmpDir});
    }).then(function() {
        console.log("Typeset " + key);
        // Step 3: call "convert ... key.pdf key.png" to create key.png
        return execFile("convert", [
            "-density", dpi, "-units", "PixelsPerInch", "-flatten",
            pdfFile, pngFile,
        ]);
    }).then(function() {
        console.log("Rasterized " + key);
        // Step 4: apply FFT to that
        return readPNG(pngFile).then(fftImage);
    });
    // Step 5: apply FFT to reference image as well
    var fftBrowser = readPNG(browserFile).then(fftImage);

    return Q.all([fftBrowser, fftLatex]).spread(function(browser, latex) {
        // Now we have the FFT result from both
        // Step 6: find alignment which maximizes overlap.
        // This uses a FFT-based correlation computation.
        var x;
        var y;
        var real = createMatrix();
        var imag = createMatrix();

        // Step 6a: (real + i*imag) = latex * conjugate(browser)
        for (y = 0; y < alignHeight; ++y) {
            for (x = 0; x < alignWidth; ++x) {
                var br = browser.real.get(y, x);
                var bi = browser.imag.get(y, x);
                var lr = latex.real.get(y, x);
                var li = latex.imag.get(y, x);
                real.set(y, x, br * lr + bi * li);
                imag.set(y, x, br * li - bi * lr);
            }
        }

        // Step 6b: (real + i*imag) = inverseFFT(real + i*imag)
        fft(-1, real, imag);

        // Step 6c: find position where the (squared) absolute value is maximal
        var offsetX = 0;
        var offsetY = 0;
        var maxSquaredNorm = -1; // any result is greater than initial value
        for (y = 0; y < alignHeight; ++y) {
            for (x = 0; x < alignWidth; ++x) {
                var or = real.get(y, x);
                var oi = imag.get(y, x);
                var squaredNorm = or * or + oi * oi;
                if (maxSquaredNorm < squaredNorm) {
                    maxSquaredNorm = squaredNorm;
                    offsetX = x;
                    offsetY = y;
                }
            }
        }

        // Step 6d: Treat negative offsets in a non-cyclic way
        if (offsetY > (alignHeight / 2)) {
            offsetY -= alignHeight;
        }
        if (offsetX > (alignWidth / 2)) {
            offsetX -= alignWidth;
        }
        console.log("Positioned " + key + ": " + offsetX + ", " + offsetY);

        // Step 7: use these offsets to compute difference illustration
        var bx = Math.max(offsetX, 0); // browser left padding
        var by = Math.max(offsetY, 0); // browser top padding
        var lx = Math.max(-offsetX, 0); // latex left padding
        var ly = Math.max(-offsetY, 0); // latex top padding
        var uw = Math.max(browser.width + bx, latex.width + lx); // union width
        var uh = Math.max(browser.height + by, latex.height + ly); // u. height
        return execFile("convert", [
            // First image: latex rendering, converted to grayscale and padded
            "(", pngFile, "-grayscale", "Rec709Luminance",
            "-extent", uw + "x" + uh + "-" + lx + "-" + ly,
            ")",
            // Second image: browser screenshot, to grayscale and padded
            "(", browserFile, "-grayscale", "Rec709Luminance",
            "-extent", uw + "x" + uh + "-" + bx + "-" + by,
            ")",
            // Third image: the per-pixel minimum of the first two images
            "(", "-clone", "0-1", "-compose", "darken", "-composite", ")",
            // First image is red, second green, third blue channel of result
            "-channel", "RGB", "-combine",
            "-trim",  // remove everything with the same color as the corners
            diffFile, // output file name
        ]);
    }).then(function() {
        console.log("Compared " + key);
    });
}
示例#13
0
      }
      else {
        app.locals.globals = data;
        on_connected();
      }
    });
  });
  mongoose.connect(config.mongodb);
  return deferred.promise;
};

var Track = require('./server/track');
var Followers = require('./server/followers');
var Reloadify = require('./server/reloadify');

Q.all([connect_db(), start_server()]).then(function() {

  var reloadify = new Reloadify(app, io, __dirname + '/public/');
  var track = new Track(app, io);
  var followers = new Followers(app, io);

  io.sockets.on('connection', function(socket) {

    socket.on('client-handshake', function(data) {
      logger.info('client connected');
      track.initial_state().then(function(initial_state) {
        socket.emit('globals', app.locals.globals);
        socket.emit('messages', initial_state.last_messages);
        socket.emit('last-zooms', initial_state.last_zooms);
        socket.join('client');
      }).done();
示例#14
0
文件: texcmp.js 项目: 966647/KaTeX
// LaTeX font size is 10pt. There are 72.27pt per inch.
var pxPerEm = 16 * 4 * 1.21;
var pxPerPt = pxPerEm / 10;
var dpi = pxPerPt * 72.27;

var tmpDir = "/tmp/texcmp";
var ssDir = path.normalize(
    path.join(__dirname, "..", "..", "test", "screenshotter"));
var imagesDir = path.join(ssDir, "images");
var teximgDir = path.join(ssDir, "tex");
var diffDir = path.join(ssDir, "diff");
var template;

Q.all([
    readFile(path.join(ssDir, "test.tex"), "utf-8"),
    ensureDir(tmpDir),
    ensureDir(teximgDir),
    ensureDir(diffDir),
]).spread(function(data) {
    template = data;
    // dirs have been created, template has been read, now rasterize.
    return Q.all(todo.map(processTestCase));
}).done();

// Process a single test case: rasterize, then create diff
function processTestCase(key) {
    var itm = data[key];
    var tex = "$" + itm.tex + "$";
    if (itm.display) {
        tex = "\\[" + itm.tex + "\\]";
    }
    if (itm.pre) {
示例#15
0
文件: texcmp.js 项目: 966647/KaTeX
]).spread(function(data) {
    template = data;
    // dirs have been created, template has been read, now rasterize.
    return Q.all(todo.map(processTestCase));
}).done();
示例#16
0
文件: runScript.js 项目: chexxor/clay
 .then( function(){ 
   return Q.all( createPromises() ); 
 })
示例#17
0
 function prepareTestUsers(){
   return q.all([
     createAdminUser(),
     createTestUsers()
   ]);
 }
示例#18
0
 beforeEach(function(done) {
   Q.all([ Author.clear(), Book.clear() ])
     .then(function() {
       done();
     }, _throw);
 });
示例#19
0
    Device.prototype.tryToConnect = function () {
        console.log('tryToConnect()');
        lastCommandWeWereTrying = waitingQueries.pop();
        
        waitingQueries = [];
        thePendingQuery = null;
        counter = 0;
        
        var promises = [];
        promises.push(device.getPotentialEV3Devices());
        q.all(promises).then(function () {
            console.log('promises ok');
            
            potentialEV3Devices.forEach(function (serialport) {
                console.log('attempting to connect with ' + serialport.comName);
                connecting = true;
                var portToConnect = '/dev/tty.' + serialport.comName.substr(8);
                theEV3DevicePort = new SerialPort(portToConnect, baudRate = 56700, function (err) {
                    if (err) {
                        return console.log('Error: ', err.message);
                    }
                    theEV3DevicePort.on('data', function (result) {
                        receive_handler(result);
                    })
                    console.log('CONNECTED TO ' + theEV3DevicePort);
                    console.log('CONNECTED TO ' + serialport.comName);
                    EV3Connected = true;
                    connecting = false;
                    testTheConnection(startupBatteryCheckCallback);
                    waitingForInitialConnection = true;
                    
                    setTimeout(function () {
                        // device.steeringControl('A', 'forward', 100, 6, null);
                        // device.steeringControl('B', 'reverse', 100, 5, null);

                        // setTimeout(function () {
                        //     device.allMotorsOff(1);
                        //     device.startMotors("B+C", 200);
                        // }, 3000);
                        
                        //device.startMotors('A+D', 1000);
                        
                        //device.readFromMotor('speed', 'A', null);
                        
                        // setTimeout(function () {
                        //     device.motorDegrees('C', 100, 90, 1);
                        // }, 7000);
                        
                        //device.whenButtonPressed(1);
                        device.whenRemoteButtonPressed(null, 3);
                        //device.readTouchSensorPort(1, null);
                        
                        //device.readColorSensorPort(2, 'reflected', null);
                        //device.readColorSensorPort(2, 'color', null);
                        //  //device.readColorSensorPort(1, 'RGBcolor', null);
                        //device.readDistanceSensorPort(3, null);
                    }, 5000);
                    
                });
                
                if (!connecting && !EV3Connected) {
                    device.disconnect();
                }
            });
        });
    };
示例#20
0
////http://bridgetown.festivalthing.com/export/schedule/json
FESTIVALTHING_SCHEDULE_URL = "http://127.0.0.1:4200/fixtures/festivalthing-schedule.json";

TMP_PERFORMERS_PATH = festivalData.tmpPerformersPath;
FESTIVALTHING_PERFORMERS_URL = "http://bridgetown.festivalthing.com/export/performers/json";
//FESTIVALTHING_PERFORMERS_URL = "http://bridgetown.festivalthing.com/export/performers/json";

TMP_SHOWS_PATH = festivalData.tmpShowsPath;
FESTIVALTHING_SHOWS_URL = "http://bridgetown.festivalthing.com/export/submitted-shows/json";
//FESTIVALTHING_SHOWS_URL = "http://bridgetown.festivalthing.com/export/submitted-shows/json";


Q.all([
  // util.requestJsonAndSave( FESTIVALTHING_VENUE_URL, TMP_VENUES_PATH ),
  // util.requestJsonAndSave( FESTIVALTHING_EVENTS_URL, TMP_EVENTS_PATH),
  // util.requestJsonAndSave( FESTIVALTHING_SCHEDULE_URL, TMP_SCHEDULE_PATH),
  util.requestJsonAndSave( FESTIVALTHING_PERFORMERS_URL, TMP_PERFORMERS_PATH),
  util.requestJsonAndSave( FESTIVALTHING_SHOWS_URL, TMP_SHOWS_PATH)
]).then(function() {
  // buildVenues();
  // buildEvents();

  var a = new ShowBuilder();
  a.buildFixtures();
  a.createHeadshots();

  var b = new PerformerBuilder();
  b.buildFixtures();
  b.createHeadshots();
}).catch(function(error) {
  console.error(error.stack);
示例#21
0
文件: zip.js 项目: vinnie777/dfx
 .then(function () {
         return Q.all([
             QFS.makeTree( path.join(tmpResourcesPath, '_shared') ),
             QFS.makeTree( path.join(tmpResourcesPath, appName) )
         ])
     }, function (error) {
 afterEach(function() {
   return q.all([
     object1Sync.manager.stop(),
     object2Sync.manager.stop()
   ])
 });
示例#23
0
 function() {
   let promises = conf.translations.map((translation) => extractForLanguage(translation.key));
   return q.all(promises);
 });
示例#24
0
  /**
   * Returns a Promise for an array of two items: the primary resources (either
   * a single Resource or a Collection) and the included resources, as an array.
   *
   * Note: The correct behavior if idOrIds is an empty array is to return no
   * documents, as happens below. If it's undefined, though, we're not filtering
   * by id and should return all documents.
   */
  find(type, idOrIds, fields, sorts, filters, includePaths) {
    let model = this.getModel(this.constructor.getModelName(type));
    let queryBuilder = new mongoose.Query(null, null, model, model.collection);
    let pluralizer = this.inflector.plural;
    let mode = "find", idQuery;
    let primaryDocumentsPromise, includedResourcesPromise = Q(null);

    if(idOrIds) {
      if(typeof idOrIds === "string") {
        mode = "findOne";
        idQuery = idOrIds;
      }
      else {
        idQuery = {"$in": idOrIds};
      }

      queryBuilder[mode]({"_id": idQuery});
    }

    else {
      queryBuilder.find();
    }

    // do sorting
    if(Array.isArray(sorts)) {
      queryBuilder.sort(sorts.join(" "));
    }

    // filter out invalid records with simple fields equality.
    // note that there's a non-trivial risk of sql-like injection here.
    // we're mostly protected by the fact that we're treating the filter's
    // value as a single string, though, and not parsing as JSON.
    if(typeof filters === "object" && !Array.isArray(filters)) {
      queryBuilder.where(filters);
    }

    // in an ideal world, we'd use mongoose here to filter the fields before
    // querying. But, because the fields to filter can be scoped by type and
    // we don't always know about a document's type until after query (becuase
    // of discriminator keys), and because filtering out fields can really
    // complicate population for includes, we don't yet filter at query time but
    // instead just hide filtered fields in @docToResource. There is a more-
    // efficient way to do this down the road, though--something like taking the
    // provided fields and expanding them just enough (by looking at the type
    // heirarachy and the relationship paths) to make sure that we're not going
    // to run into any of the problems outlined above, while still querying for
    // less data than we would without any fields restriction. For reference, the
    // code for safely using the user's `fields` input, by putting them into a
    // mongoose `.select()` object so that the user can't prefix a field with a
    // minus on input to affect the query, is below.
    // Reference: http://mongoosejs.com/docs/api.html#query_Query-select.
    // let arrToSelectObject = (prev, curr) => { prev[curr] = 1; return prev; };
    // for(let type in fields) {
    //   fields[type] = fields[type].reduce(arrToSelectObject, {});
    // }

    // support includes, but only a level deep for now (recursive includes,
    // especially if done in an efficient way query wise, are a pain in the ass).
    if(includePaths) {
      const populatedPaths = [];
      const refPaths = util.getReferencePaths(model);

      includePaths = includePaths.map((it) => it.split("."));
      includePaths.forEach((pathParts) => {
        // first, check that the include path is valid.
        if(!arrayContains(refPaths, pathParts[0])) {
          let title = "Invalid include path.";
          let detail = `Resources of type "${type}" don't have a(n) "${pathParts[0]}" relationship.`;
          throw new APIError(400, undefined, title, detail);
        }

        if(pathParts.length > 1) {
          throw new APIError(501, undefined, "Multi-level include paths aren't yet supported.");
        }

        // Finally, do the population
        populatedPaths.push(pathParts[0]);
        queryBuilder.populate(pathParts[0]);
      });

      let includedResources = [];
      primaryDocumentsPromise = Q(queryBuilder.exec()).then((docs) => {
        forEachArrayOrVal(docs, (doc) => {
          populatedPaths.forEach((path) => {
            // if it's a toOne relationship, doc[path] will be a doc or undefined;
            // if it's a toMany relationship, we have an array (or undefined).
            let refDocs = Array.isArray(doc[path]) ? doc[path] : [doc[path]];
            refDocs.forEach((it) => {
              // only include if it's not undefined.
              if(it) {
                includedResources.push(
                  this.constructor.docToResource(it, pluralizer, fields)
                );
              }
            });
          });
        });

        return docs;
      });

      includedResourcesPromise = primaryDocumentsPromise.then(() =>
        new Collection(includedResources)
      );
    }

    else {
      primaryDocumentsPromise = Q(queryBuilder.exec());
    }

    return Q.all([primaryDocumentsPromise.then((it) => {
      const makeCollection = !idOrIds || Array.isArray(idOrIds) ? true : false;
      return this.constructor.docsToResourceOrCollection(it, makeCollection, pluralizer, fields);
    }), includedResourcesPromise]).catch(util.errorHandler);
  }
            FirebaseService.getUserObjects().child('transactions').once('value', function (snap) {
                var salesReport = {
                    byDay: {},
                    byWeek: {},
                    byMonth: {},
                    byYear: {}
                };
                var blankReport = {
                    subtotal: 0,
                    discount: 0,
                    shipping: 0,
                    tax: 0,
                    total: 0,
                    transactionCount: 0
                };
                var summaryFields = Object.keys(blankReport);

                snap.forEach(function (childSnap) {
                    _.each(childSnap.val(), function (transaction) {
                        var date = moment(transaction.date);
                        var year = date.year().toString();
                        var month = year + '|' + date.format('MM');
                        var week = year + '|' + date.format('ww');
                        var day = year + '|' + date.format('DDDD');
                        var reports = {
                            byYearReport: salesReport.byYear[year],
                            byMonthReport: salesReport.byMonth[month],
                            byWeekReport: salesReport.byWeek[week],
                            byDayReport: salesReport.byDay[day]
                        };
                        var referral = transaction.referral ? slug(transaction.referral.referral) : false;

                        //Fill for empty reports
                        _.each(reports, function (report, key) {
                            if (!report) {
                                report = _.clone(blankReport);
                            }
                            if (referral) {
                                if (!report.referrals) {
                                    report.referrals = {};
                                }
                                if (!report.referrals[referral]) {
                                    report.referrals[referral] = _.clone(blankReport);
                                }
                            }
                            reports[key] = report;
                        });

                        _.each(summaryFields, function (field) {
                            _.each(reports, function (report, key) {
                                var value = transaction[field];

                                if (value && !isNaN(value)) {
                                    report[field] += value;
                                    if (referral) {
                                        report.referrals[referral][field] += value;
                                    }
                                    reports[key] = report;
                                }

                            });
                        });

                        if (reports.byYearReport) {
                            salesReport.byYear[year] = reports.byYearReport;
                            salesReport.byYear[year].key = year;
                        }
                        if (reports.byMonthReport) {
                            salesReport.byMonth[month] = reports.byMonthReport;
                            salesReport.byMonth[month].key = month
                        }
                        if (reports.byWeekReport) {
                            salesReport.byWeek[week] = reports.byWeekReport;
                            salesReport.byWeek[week].key = week;
                        }
                        if (reports.byDayReport) {
                            salesReport.byDay[day] = reports.byDayReport;
                            salesReport.byDay[day].key = day;
                            salesReport.byDay[day].date = date.format();
                        }

                    });
                });

                var salesReportPromises = [];
                _.each(salesReport, function (report, name) {

                    _.each(_.sortBy(_.toArray(report), 'key'), function (result) {
                        var deferred = Q.defer();
                        salesReportPromises.push(deferred.promise);
                        reportsRef.child('sales').child(name).push(result, function (err) {
                            return err ? deferred.reject(err) : deferred.resolve();
                        });
                    });
                });

                Q.all(salesReportPromises).then(function () {
                    reportsRef.child('sales').child('created').set(moment().format(), function (err) {
                        return err ? salesDeferred.reject(err) : salesDeferred.resolve();
                    });
                });

            });
 injectAll: function() {
     return Q.all([this.injectAllModules(), this.injectAllComponents()]);
 }
示例#27
0
 .then(function() {
   // wrap in case one of these throws
   return Q.all([self.getAndPrepareSigningKeychain(params), self.getTransactionPreBuildParams(params)]);
 })
示例#28
0
IonicStartTask.prototype.fetchCodepen = function() {
  var self = this;
  var codepenUrl = this.template.split('?')[0].split('#')[0];
  var wwwPath = path.join(this.targetPath, 'www');

  console.log('\nDownloading Codepen:'.info.bold, codepenUrl);

  var qHTML = Q.defer();
  var qCSS = Q.defer();
  var qJS = Q.defer();

  var proxy = process.env.PROXY || null;

  request({ url: codepenUrl + '.html', proxy: proxy }, function(err, res, html) {
    if(!err && res && res.statusCode === 200 && html) {

      if(html.indexOf('<!DOCTYPE html>') < 0) {
        html = '<!DOCTYPE html>\n' + html;
      }

      var resources = '    <link href="css/style.css" rel="stylesheet">\n' +
                      '    <script src="js/app.js"></script>\n';

      if(self.isCordovaProject) {
        resources += '    <script src="cordova.js"></script>\n';
      }

      resources += '  </head>';

      html = html.replace(/<\/head>/i, '\n' + resources);

      html = self.convertTemplates(html);

      fs.writeFileSync(path.join(wwwPath, 'index.html'), html, 'utf8');
    }
    qHTML.resolve();
  });

  request({ url: codepenUrl + '.css', proxy: proxy }, function(err, res, css) {
    if(!err && res && res.statusCode === 200 && css) {
      var cssPath = path.join(wwwPath, 'css');
      if(!fs.existsSync(cssPath)) {
        fs.mkdirSync(cssPath);
      }
      css = css.replace("cursor: url('http://ionicframework.com/img/finger.png'), auto;", '');
      fs.writeFileSync(path.join(cssPath, 'style.css'), css, 'utf8');
    }
    qCSS.resolve();
  });

  request({ url: codepenUrl + '.js', proxy: proxy }, function(err, res, js) {
    if(!err && res && res.statusCode === 200 && js) {
      var jsPath = path.join(wwwPath, 'js');
      if(!fs.existsSync(jsPath)) {
        fs.mkdirSync(jsPath);
      }
      fs.writeFileSync(path.join(jsPath, 'app.js'), js, 'utf8');
    }
    qJS.resolve();
  });

  return Q.all([qHTML.promise, qCSS.promise, qJS.promise]);
};
示例#29
0
AddNote.prototype.invoke = function(imports, channel, sysImports, contentParts, next) {
  var pod = this.pod,
    $resource = this.$resource,
    noteStore = pod.getNoteStore(sysImports),
    noteBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
    newNote = pod.newNote();

  newNote.title = imports.title;

  noteBody += "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">";

  newNote.notebookGuid = channel.config.notebook_guid;

  if (imports.tags) {
    if ($resource.helper.isArray(imports.tags)) {
      newNote.tagNames = imports.tags;
    } else if ($resource.helper.isString(imports.tags)) {
      newNote.tagNames = imports.tags.split(',').map(function(tag) {
        return tag.trim();
      });
    }
  }

  if (contentParts._files && contentParts._files.length) {
    var deferred, promises = [];
    for (var i = 0; i < contentParts._files.length; i++) {
      deferred = Q.defer();
      promises.push(deferred.promise);

      (function(deferred) {
        pod.getFileResource(contentParts._files[i], function(err, resource) {
          if (err) {
            deferred.reject(err);
          } else {
            deferred.resolve(resource);
          }
        });
      })(deferred);
    }

    Q.all(promises).then(function(resources) {
      newNote.resources = resources;

      noteBody += "<en-note>" + imports.note;

      if (channel.config.embed_attachments) {
        for (var i = 0; i < resources.length; i++) {
          noteBody += '<en-media type="' + resources[i].mime + '" hash="' + resources[i].data.bodyHash + '" />';
        }
      }

      noteBody += '</en-note>';

      newNote.content = noteBody;

      noteStore.createNote(newNote, function(err, note) {
        next(err, note);
      });
    }, function(err) {
      next(err);
    });
  } else {

    noteBody += "<en-note>" + imports.note;
    noteBody += '</en-note>';
    newNote.content = noteBody;

    noteStore.createNote(newNote, function(err, note) {
      next(err, note);
    });
  }

}
示例#30
0
ConfigFile.prototype._loadParents = function() {
  return Q.all(this._parents.map(function(configFile) {
    return configFile.load();
  })).thenResolve(this._parents);
};