setup(function() { container = uuid.v4(); subject = new BlockStream(service, container, path); });
beforeEach(function () { key = uuid.v4(); value = uuid.v4(); key2 = uuid.v4(); value2 = uuid.v4(); });
function createMedia(infos, next) { // Data var mediaData = { type: 'media', kind: kind, last_update: helpers.timestamp(), slug_id: ++cache.slug_ids.res }; var hash, file; // Specific to kind if (kind === 'image') { if (data.url) { mediaData.internal = false; mediaData.url = data.url; mediaData.html = '<img src="' + data.url + '" />'; } else { hash = uuid.v4().replace(/-/g, ''); file = parseDataUrl(data.file); mediaData.internal = true; mediaData.path = 'admin/' + hash + '.' + file.extension; fse.mkdirpSync(storagePath + '/images/admin'); // Writing file on disk fse.writeFileSync(storagePath + '/images/' + mediaData.path, file.buffer); } } else if (kind === 'pdf') { if (data.url) { // TODO: ... } else { hash = uuid.v4().replace(/-/g, ''); file = parseDataUrl(data.file); mediaData.internal = true; mediaData.path = 'admin/' + hash + '.' + file.extension; fse.mkdirpSync(storagePath + '/pdfs/admin'); // Writing file on disk fse.writeFileSync(storagePath + '/pdfs/' + mediaData.path, file.buffer); } } else if (kind === 'quote') { mediaData.lang = lang; mediaData.text = data.text; mediaData.internal = true; } else if (kind === 'link') { mediaData.internal = false; mediaData.html = '<a href="' + data.url + '" target="_blank">' + (data.title || data.url) + '</a>'; mediaData.url = data.url; mediaData.title = data.title || data.url; } else if (kind === 'video') { mediaData.internal = false; mediaData.url = data.url; mediaData.html = infos.html; } // Creating node mediaNode = batch.save(mediaData); batch.label(mediaNode, 'Media'); next(); },
genid: function(req) { return uuid.v4(); },
router.get('/', (req, res) => { let prefix = 'call/'; if (req.originalUrl.charAt(req.originalUrl.length - 1) === '/') prefix = ''; res.redirect(prefix + uuid.v4()); });
DiskStore.prototype.set = function (key, val, options, cb) { cb = typeof cb === 'function' ? cb : noop; if (typeof options === 'function') { cb = options; options = null; } // get ttl var ttl = (options && (options.ttl || options.ttl === 0)) ? options.ttl : this.options.ttl; // move binary data to binary from value var binary; if (typeof val.binary === 'object' && val.binary != null) { binary = val.binary; delete val['binary']; val.binary = {}; } var metaData = extend({}, new MetaData(), { key: key, value: val, expires: Date.now() + ((ttl || 60) * 1000), filename: this.options.path + '/cache_' + uuid.v4() + '.dat' }); var binarySize = 0; if (binary) { for (var binkey in binary) { if (!binary.hasOwnProperty(binkey)) continue; // put storage filenames into stored value.binary object metaData.value.binary[binkey] = metaData.filename.replace(/\.dat$/, '_' + binkey + '.bin'); // calculate the size of the binary data binarySize += binary[binkey].length || 0; } } metaData.size = JSON.stringify(metaData).length + binarySize; var stream = JSON.stringify(metaData); if (this.options.maxsize && metaData.size > this.options.maxsize) { return cb(new Error('Item size too big.')); } // remove the key from the cache (if it already existed, this updates also the current size of the store) this.del(key, function (err) { if (err) { return cb(err); } // check used space and remove entries if we use too much space this.freeupspace(function () { try { var self = this; // write binary data and cache file async.series( [ function (cb) { // write binary if (binary) { async.forEachOf(binary, function (v, k, cb) { fs.writeFile(metaData.value.binary[k], v, cb); }, function (err) { cb(err); }); } else { cb(); } }, function (cb) { self.zipIfNeeded(stream, function (err, processedStream) { // write data into the cache-file fs.writeFile(metaData.filename, processedStream, function (err) { if (err) { return cb(err); } // remove data value from memory metaData.value = null; delete metaData.value; self.currentsize += metaData.size; // place element with metainfos in internal collection self.collection[metaData.key] = metaData; // restore val binary key if (binary) { if(this.options.binaryAsStream) { for(key in binary){ if(binary.hasOwnProperty(key)){ val.binary[key] = streamifier.createReadStream(binary[key], {encoding: null}); } } }else{ val.binary = binary; } } return cb(null, val); }.bind(self)); }.bind(self)) } ], function (err, result) { cb(err, result); } ); } catch (err) { return cb(err); } }.bind(this)); }.bind(this)); };
it('should return an empty array, if there is no kind', () => { const kind = UUID.v4(); expect(storyStore.getStories(kind)).to.deep.equal([]); });
beforeEach(() => { sandbox = sinon.sandbox.create(); client = new BusinessElementsClient(FAKE_SERVER_URL); conceptId = uuid.v4(); concept = client.tenant("example.com").concepts().concept(conceptId); });
.on('end', function () { // Build Actor Vertices for (var i = 0; i < actorList.length; i++) { var vertex = { id: 'a' + (i + 1), label: 'person', properties: { name: [{ id: uuid.v4(), value: actorList[i], }, ], type: [{ id: uuid.v4(), value: 'Actor', }, ], }, inE: {}, outE: {}, }; actorVertices[i] = vertex; } // Build Film Vertices for (var i = 0; i < filmList.length; i++) { var vertex = { id: 'f' + (i + 1), label: 'film', properties: { name: [{ id: uuid.v4(), value: filmList[i], }, ], type: [{ id: uuid.v4(), value: 'Film', }, ], }, inE: {}, outE: {}, }; filmVertices[i] = vertex; } // Match and add Edges for (var i = 0; i < importData.length; i++) { var actorId = actorList.indexOf(importData[i][0]); var filmId = filmList.indexOf(importData[i][2]); var relationship = importData[i][1]; // Actor -> Film var edgeId = uuid.v4(); var outE = { id: edgeId, inV: 'f' + (filmId + 1), }; if (typeof actorVertices[actorId].outE[relationship] == 'undefined') { actorVertices[actorId].outE[relationship] = []; } actorVertices[actorId].outE[relationship].push(outE); var inE = { id: edgeId, inV: 'a' + (actorId + 1), }; if (typeof filmVertices[filmId].inE[relationship] == 'undefined') { filmVertices[filmId].inE[relationship] = []; }; filmVertices[filmId].inE[relationship].push(inE); // Film -> Actor var edgeId = uuid.v4(); var outE = { id: edgeId, inV: 'a' + (actorId + 1), }; if (typeof filmVertices[filmId].outE[relationship] == 'undefined') { filmVertices[filmId].outE[relationship] = []; }; filmVertices[filmId].outE[relationship].push(outE); var inE = { id: edgeId, inV: 'f' + (filmId + 1), }; if (typeof actorVertices[actorId].inE[relationship] == 'undefined') { actorVertices[actorId].inE[relationship] = []; }; actorVertices[actorId].inE[relationship].push(inE); }; for (var i = 0; i < actorVertices.length; i++) { graphsonArray.push(JSON.stringify(actorVertices[i])); }; for (var i = 0; i < filmVertices.length; i++) { graphsonArray.push(JSON.stringify(filmVertices[i])); }; // console.log(graphsonArray); var graphsonString = graphsonArray.join('\n'); console.log(graphsonString); importDb.io().graphson(graphsonString, function (e, b) { console.log(e); console.log(b); }); fs.writeFile('graphson', graphsonString, function (err) { if (err) { return console.log(err); } console.log('The file was saved!'); }); });
function Session(id) { this.id = id || uuid.v4(); this.results = []; }
render () { let ret = super.render() // if there are no hops selected, apply to entire pattern if (this.props.modification.hops == null) return ret let patterns = this.getPatterns() // not loaded if (patterns === null) return ret let selectedHopGeometries = [] // sort out the hops for (let pattern of patterns) { // figure out selected hop indices then merge consecutive hops let selectedHopIndicesInPattern = [] for (let hop of this.props.modification.hops) { // NB if same stop sequence appears twice, we'll only show the hop once. // This isn't that big a deal, as this is just a display let hopIndex = pattern.stops.findIndex((stop, index, stops) => index < stops.length - 1 && stops[index].stop_id === hop[0] && stops[index + 1].stop_id === hop[1]) if (hopIndex === -1) continue // this hop is not in this pattern selectedHopIndicesInPattern.push(hopIndex) } // to avoid excessive line segmentation operations, we find consecutive hops and show them all at once as a single feature // the lineSlice operation is pretty intensive // uniquify and sort selectedHopIndicesInPattern = [...new Set(selectedHopIndicesInPattern)].sort() // merge consectuive hops // negative number less than -1 so it's not consecutive with hop 0 let startHopIndex = -10 let prevHopIndex = -10 let makeGeometryIfNecessary = () => { if (startHopIndex >= 0) { // get geometry let fromStopId = pattern.stops[startHopIndex].stop_id let fromStop = this.props.data.feeds[this.props.modification.feed].stops.get(fromStopId) // get feature at end of hop let toStopId = pattern.stops[prevHopIndex + 1].stop_id let toStop = this.props.data.feeds[this.props.modification.feed].stops.get(toStopId) let geometry = lineSlice(point([fromStop.stop_lon, fromStop.stop_lat]), point([toStop.stop_lon, toStop.stop_lat]), { type: 'Feature', properties: {}, geometry: pattern.geometry }) selectedHopGeometries.push(geometry) } } for (let hopIndex of selectedHopIndicesInPattern) { if (startHopIndex < 0) startHopIndex = hopIndex if (hopIndex - 1 !== prevHopIndex && prevHopIndex >= 0) { // start of new hop sequence detected makeGeometryIfNecessary() startHopIndex = hopIndex } prevHopIndex = hopIndex } // last hop makeGeometryIfNecessary() } let data = { type: 'FeatureCollection', features: selectedHopGeometries } let { color, map, layerContainer } = this.props return <span> <GeoJson data={data} color={color} map={map} layerContainer={layerContainer} key={uuid.v4()} /> </span> }
User.create = function(params, callback) { var currentTime = new Date().toISOString(); console.log('params: ' + params); var stringToArray = function(anyString) { if (typeof anyString === "undefined" || !anyString) { return ""; } else { var tempArray=anyString.split(","); var resultArray=[]; for (i=0; i<tempArray.length; i++) { var str = tempArray[i]; resultArray[i]= str.trim(); if (resultArray[i]=="") { resultArray.splice(i, 1); } } return resultArray; } }; if (!params.arrayAttributes) { params.arrayAttributes = {}; } if (!params.dropdownAttributes) { params.dropdownAttributes = {}; } if (!params.stringAttributes) { params.stringAttributes = {}; } var userDoc = { // should add a type here, ex. type: "user" uuid: uuid.v4(), password: forge.md.sha1.create().update(params.login.password).digest().toHex(), stringAttributes: {}, arrayAttributes: {}, dropdownAttributes: {}, login: { type: "user", email: params.login.email, administrator: false, hasPicture: false, emailVerified: false }, timeTracker: { registerTime: currentTime, updateTimes: [], loginTimes: [currentTime] } }; for (i=0; i<stringAttributes.length; i++) { userDoc.stringAttributes[stringAttributes[i]] = params.stringAttributes[stringAttributes[i]]; } for (j=0; j<arrayAttributes.length; j++) { userDoc.arrayAttributes[arrayAttributes[j]] = stringToArray(params.arrayAttributes[arrayAttributes[j]]); } for (k=0; k<dropdownAttributes.length; k++) { userDoc.dropdownAttributes[dropdownAttributes[k].varname] = params.dropdownAttributes[dropdownAttributes[k].varname]; } userDoc[primaryAttribute] = params[primaryAttribute]; console.log(userDoc); var insertUser = N1qlQuery.fromString('INSERT INTO `' + userBucketName + '` (KEY, VALUE) VALUES ($1, $2)'); console.log(insertUser); userBucket.query(insertUser, [userDoc.uuid, userDoc], function (err, result) { if (err) { console.log("ERROR IN USERMODEL QUERY: "); console.log(err); callback(err, null); return; } callback(null, {message: "success", data: result, userID: userDoc.uuid, userDoc: userDoc}); }); };
"newUUID" : function () { return uuid.v4() }
/** * Generate uuid, read more from: https://www.npmjs.com/package/uuid. * * @return uuid */ static getUUID() { return UUID.v4() }
var quickconnect = require('rtc-quickconnect'); var mesh = require('../'); var Doc = require('crdt').Doc; var uuid = require('uuid'); // initialise the connection var qc = quickconnect('https://switchboard.rtc.io/', { room: 'meshdemo-crdt' }); // create the model var model = mesh(qc, { model: new Doc() }); model.on('add', function(row) { console.log('new row created: ', row); }); model.add({ id: uuid.v4(), name: 'Fred' });
Task.prototype.send = function(receiver, _socket) { var inst = this; var socket = _socket; this.uuid = uuid.v4(); // Give the task a random id return new Promise(function(resolve, reject) { inst.timeout = setTimeout(function() { reject(new Error('Task timed out')); }, 60000); // One minute var timer; if (inst.type === 'compilation') { _socket.on(inst.uuid, function(msg) { if (msg === 'online') { clearTimeout(timer); var obj = { compile: inst.options.compile, grader: (inst.options.grader !== undefined) }; socket.emit(inst.uuid, obj); } else if (msg === 'ready') { // Client ready to receive files console.log('Task ' + inst.uuid + ': Sending files to judger...'); var files = []; files.push(streamFileAsync(socket, inst.uuid, inst.options.source, inst.options.filename)); if (inst.options.grader !== undefined) files.push(streamFileAsync(socket, inst.uuid, inst.options.grader, inst.options.graderName)); Promise.all(files).then(function() { socket.emit(inst.uuid, 'done'); timer = setTimeout(function() { reject(new Error('Receiver timed out')); }, 20000); // 20 seconds }); } else if (typeof(msg) !== 'object') { reject(new Error('Receiver rejected the task')); } else { clearTimeout(timer); if (msg.result !== 0) { resolve(msg); } else { ss(_socket).on(inst.uuid + '-file', function(file, filename, resolveClient) { receiveFileAsync(file, filename, inst.options.destination).then(function() { resolve({ result: 0, file: path.join(inst.options.destination, filename) }); }).then(resolveClient); }); } } }); } else { _socket.on(inst.uuid, function(msg) { clearTimeout(timer); if (msg === 'online') { socket.emit(inst.uuid, { time: inst.options.time, memory: inst.options.memory, scoreType: inst.options.scoreType, inputFile: inst.options.inputFile, outputFile: inst.options.outputFile }); } else if (msg === 'ready') { console.log('Task ' + inst.uuid + ': Sending files to judger...'); var files = [ streamFileAsync(socket, inst.uuid, inst.options.source, 'code'), streamFileAsync(socket, inst.uuid, inst.options.input , 'input.txt'), streamFileAsync(socket, inst.uuid, inst.options.output, 'output.txt') ]; if (inst.options.grader !== undefined) { files.push(streamFileAsync(socket, inst.uuid, inst.options.grader, 'grader')); } Promise.all(files).then(function() { socket.emit(inst.uuid, 'done'); // Let's go timer = setTimeout(function() { reject(new Error('Receiver timed out')); }, 20000); }); } else if (typeof(msg) !== 'object') { reject(new Error('Receiver rejected the task')); } else { clearTimeout(timer); resolve(msg); } }); } // Check if the receiver is still connected if (socket.adapter.rooms[receiver] === undefined) { reject(new Error('Receiver not found')); } console.log('Task ' + inst.uuid + ' (' + inst.type + ') queued to judge ' + receiver + ' ' + socket.id); socket.emit('queue', inst.uuid, inst.type); timer = setTimeout(function() { reject(new Error('Receiver timed out')); }, 60000); }).then(function(data) { console.log('Task ' + inst.uuid + ': Task completed.'); return data; }) .finally(function(data) { socket.removeAllListeners(inst.uuid); socket.removeAllListeners(inst.uuid + '-file'); return data; }); };
var request = require('superagent'); var storageKey = 'pickadeli'; var localInfo = store.get(storageKey); var shouldPersist = false; if (!_.isPlainObject(localInfo)) { localInfo = {}; shouldPersist = true; } var id = localInfo.id; if (!_.isString(id) || _.size(id) === 0) { localInfo.id = id = uuid.v4(); shouldPersist = true; } if (shouldPersist) { store.set(storageKey, localInfo); } // register the user console.log('requesting??') request .post('/api/user/' + localInfo.id) .send({}) .end(function (err, res) { console.log('registered user?'); });
suite('#content', function() { var id = uuid.v4(); var parts = [ new Buffer('i am the first.\n'), new Buffer('i am the second.\n'), new Buffer('i am the third.\n') ]; var expectedFinalBuffer = Buffer.concat(parts); // we need to add some parts to the entity setup(function() { var promises = []; var offset = 0; parts.forEach(function(part) { var length = part.length; promises.push(subject.add( id, offset, length, part )); offset += length; }); return Promise.all(promises); }); test('stream from the middle of a chunk to the end', function(done) { // Everything fits into a single byte so we can slice randomly // like this.. The expectation is the actual rendering will be // done by something that can buffer incomplete utf8. var offset = Math.floor(expectedFinalBuffer.length / 2); var expected = expectedFinalBuffer.slice(offset); var stream = subject.content(id, offset); var buffers = []; stream.on('data', function(buffer) { buffers.push(buffer); }); stream.on('end', function() { var joined = Buffer.concat(buffers); assert.equal( joined.toString(), expected.toString() ); done(); }); }); test('stream from begining', function(done) { var stream = subject.content(id); var buffers = []; stream.on('data', function(buffer) { buffers.push(buffer); }); stream.on('end', function() { var joined = Buffer.concat(buffers); assert.equal(joined.length, expectedFinalBuffer.length); assert.equal( joined.toString(), expectedFinalBuffer.toString() ); done(); }); }); });
it('should return false if there is no kind', () => { const kind = UUID.v4(); expect(storyStore.hasStoryKind(kind, 'name')).to.be.equal(false); });
it('update a deck', function (done) { var uniqueDeck = [uuid.v4()], uniqueDrawn = [uuid.v4()], uniqueDiscarded = [uuid.v4()], uniqueRemoved = [uuid.v4()]; // create a deck with some unique data request(app) .post('/deck') .send({ deck: uniqueDeck, drawn: uniqueDrawn, discarded: uniqueDiscarded, removed: uniqueRemoved }) .set('Accept', 'application/json') .set('Content-type', 'application/json') .expect(201) .expect(function (res) { if (!res.body.id) { return 'no id returned'; } }) .end(function (err, res) { var uniqueDeck, uniqueDrawn, uniqueDiscarded, uniqueRemoved, deckId; if (err) { return done(err); } uniqueDeck = [uuid.v4()], uniqueDrawn = [uuid.v4()], uniqueDiscarded = [uuid.v4()], uniqueRemoved = [uuid.v4()]; deckId = res.body.id; // update the deck request(app) .put('/deck') .send({ id: deckId, deck: uniqueDeck, drawn: uniqueDrawn, discarded: uniqueDiscarded, removed: uniqueRemoved }) .set('Accept', 'application/json') .set('Content-type', 'application/json') .expect(200) .expect(function (res) { if (res.body.id !== deckId) { return 'put request did not return correct deck id'; } }) .end(function(err, res){ // get the deck and check that it has the new data request(app) .get('/deck/' + deckId) .set('Accept', 'application/json') .expect(200) .expect(function (res) { if (res.body.id !== deckId) { return 'wrong id returned on get'; } else if (!res.body.deck) { return 'no deck returned on get'; } else if (res.body.deck[0] !== uniqueDeck[0] || res.body.drawn[0] !== uniqueDrawn[0] || res.body.discarded[0] !== uniqueDiscarded[0] || res.body.removed[0] !== uniqueRemoved[0]) { return 'deck data was not updated'; } }) .end(function(err, res){ done(err); }); }); }); });
it('should return null if there is no kind', () => { const kind = UUID.v4(); expect(storyStore.getStory(kind, 'name')).to.be.equal(null); });
defaultsTo: () => uuid.v4(),
(() => { if (handleStartupEvent()) { return; } // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let mainWindow = null; // DEV: Make the app single instance const shouldQuit = app.makeSingleInstance(() => { if (mainWindow) { if (mainWindow.isMinimized()) mainWindow.restore(); mainWindow.focus(); mainWindow.show(); mainWindow.setSkipTaskbar(false); if (app.dock && app.dock.show) app.dock.show(); } }); if (shouldQuit) { app.quit(); return; } if (process.env.TEST_SPEC) { global.Settings = new SettingsClass('.test', true); } else { global.Settings = new SettingsClass(); } global.DEV_MODE = process.env['TEST_SPEC'] || argv.development || argv.dev; // eslint-disable-line if (Settings.get('START_IN_DEV_MODE', false)) { global.DEV_MODE = true; Settings.set('START_IN_DEV_MODE', false); } // Initialize the logger with some default logging levels. const defaultFileLogLevel = 'info'; const defaultConsoleLogLevel = global.DEV_MODE ? 'debug' : 'error'; global.Logger = new (winston.Logger)({ transports: [ new (winston.transports.File)({ filename: path.resolve(app.getPath('userData'), 'gpmdp.log'), level: defaultFileLogLevel, maxsize: 5000000, maxfiles: 2, }), new (winston.transports.Console)({ level: defaultConsoleLogLevel, }), ], }); Logger.info('Application started.'); configureApp(app); global.Emitter = new EmitterClass(); global.WindowManager = new WindowManagerClass(); global.PlaybackAPI = new PlaybackAPIClass(); // UA for GA // This is for user reporting Settings.set('uuid', Settings.get('uuid', uuid.v4())); const user = ua('UA-44220619-5', Settings.get('uuid')); setInterval((function sendPageView() { user.pageview('/').send(); return sendPageView; }()), 60000 * 5); // Replace the logger's levels with those from settings. Logger.transports.console.level = Settings.get('consoleLogLevel', defaultConsoleLogLevel); Logger.transports.file.level = Settings.get('fileLogLevel', defaultFileLogLevel); // Quit when all windows are closed. app.on('window-all-closed', () => { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit(); } }); // This method will be called when Electron has finished // initialization and is ready to create browser windows. app.on('ready', () => { mainWindow = new BrowserWindow(generateBrowserConfig()); global.mainWindowID = WindowManager.add(mainWindow, 'main'); const position = Settings.get('position'); const inBounds = positionOnScreen(position); let size = Settings.get('size'); size = size || [1200, 800]; mainWindow.setSize(...size); if (position && inBounds) { mainWindow.setPosition(...position); } else { mainWindow.center(); } if (Settings.get('maximized', false)) { mainWindow.maximize(); } // and load the index.html of the app. mainWindow.loadURL(`file://${__dirname}/public_html/index.html`); require('./main/features'); require('./old_win32'); // Proxy window events through IPC to solve 'webContents destroyed' errors const proxyWindowEvent = (name) => { mainWindow.on(name, (...args) => Emitter.sendToGooglePlayMusic(`BrowserWindow:${name}`, ...args)); }; proxyWindowEvent('app-command'); proxyWindowEvent('swipe'); proxyWindowEvent('scroll-touch-begin'); proxyWindowEvent('scroll-touch-end'); // Emitted when the window is closed. mainWindow.on('closed', () => { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null; PlaybackAPI.reset(); }); // setup i3 listener const I3IpcHelper = new I3IpcHelperClass(); I3IpcHelper.setupEventListener(); }); app.on('before-quit', () => { Logger.info('Application exiting...'); global.quiting = true; }); })();
"use strict" const fs = require("fs") const path = require("path") const uuid = require("uuid") const send = require("send") // express middleware const express = require("express") const session = require("express-session") // express middleware // const sessionFileStore = require("session-file-store")(session) const bodyParser = require("body-parser") // express middleware const compression = require("compression") // express middleware // express.js var express_server = express() let adm_login_route = uuid.v4() let adm_route = uuid.v4() let adm_pass = uuid.v4() console.log("Go to the generated route (ie localhost:3016/{route}) and enter the password") console.log( ` route: \x1b[38;2;255;206;67m ${adm_route} \x1b[0m password: ${adm_pass} login route: ${adm_login_route} ` ) // @Todo: formalise property and variable names to thisKindOfCase express_server.globals = require("./config/globals.json")
apiController.generateUniqueId = function() { var uniqueId = uuid.v4(); return uniqueId; }
import EventEmitter from 'events'; import assign from 'object-assign'; import AppDispatcher from '../dispatcher/AppDispatcher'; import uuid from 'uuid'; const TodoStore = assign({}, EventEmitter.prototype, { todos: [{ id: uuid.v4(), content: 'first one' }, { id: uuid.v4(), content: '2nd one' }], getAll() { return this.todos; }, addTodo(todo) { this.todos.push(todo); }, deleteTodo(id) { this.todos = this.todos.filter(item => item.id !== id); }, emitChange() { this.emit('change'); }, addChangeListener(callback) { this.on('change', callback); }, removeChangeListener(callback) { this.removeListener('change', callback); } }); AppDispatcher.register((action) => { switch (action.actionType) { case 'CREATE_TODO': TodoStore.addTodo(action.todo);
defaultsTo: function() { return uuid.v4(); }
genid : function () { return 'S_' + moment().format('YYMMDD-HHmmss-') + uuid.v4(); },
let appSignup = (req, res, next) => { let uuid = Uuid.v4(); // Generated Universal Unique identifier let dateTime = Moment().format().replace(/T/, ' ').replace(/\..+/, ''); let fullname = req.body.fullname != undefined ? req.body.fullname : ''; let email = req.body.email != undefined ? req.body.email : ''; let mobile_number = req.body.mobile_number != undefined ? req.body.mobile_number : ''; let user_type = req.body.user_type != undefined ? req.body.user_type : ''; let pass = req.body.password != undefined ? req.body.password : ''; let saltRounds = 10; // Encrypt passowrd let salt = Bcrypt.genSaltSync(saltRounds); let hashPass = Bcrypt.hashSync(pass, salt); let where = "email = '"+email+"' OR mobile = '"+mobile_number+"'"; /// whether to check only mobile number or both let findUser = Db.select(Config.tables.tableuser, where); findUser.then( function (value){ value = value[0]; let message, success, userdata; /* Check if user exists */ if(value !== undefined && value.id !== undefined) { success = false; message = 'User already exists!' res.json({ result: success, msg: message }); } /* Else make an account */ else{ let regPost = { 'uuid' : uuid, 'name' : fullname, 'email' : email, 'mobile' : mobile_number, 'password' : hashPass, 'user_type' : user_type, 'is_active' : 1, 'created_at' : dateTime, 'modified_at' : dateTime }; let addUser = Db.insert(Config.tables.tableuser, regPost); addUser.then( function (val){ if(val != undefined || val.insertId != undefined) { /// Whether to send to next step or not /*let mailBody = '<h1>Thank you for registering with us</h1>'; let mailPost = { from: '*****@*****.**', to: req.body.email, subject: "New Registration", html: mailBody }; let sendMail = Common.sendMail(mailPost); console.log('mail sent');*/ let userData = Db.findById(Config.tables.tableuser, val.insertId); userData.then( function (v){ if(v != undefined || v.id != undefined){ message = 'Registered Successfully'; success = true; userdata = v; }else{ message = 'Registered Successfully. Problem in fetching user data'; success = true; userdata = {'userId' : val.insertId}; } res.json({ result: success, msg: message, userdata: userdata }); }, function (r){ message = 'Registered Successfully. Problem in fetching user data'; success = true; res.json({ result: success, msg: message, userdata: userdata }); } ); }else{ message = 'Registration failed'; success = false res.json({ result: success, msg: message, userdata: userdata }); } }, function (reasn) { console.log('failure'); console.log(reasn); } ); } },function (reason){ console.log('Error in promise return : '+reason); res.json({ result: false, msg: reason }); } ); };
const items = input.result.reduce((allItems, item) => { allItems[uuid.v4()] = item return allItems }, {})