<commit_before>'use strict';

var request = require('request'),
    baseURL = '/_fetch_/',
    config = {},

getURL = function (name) {
    var location;

    /*global window*/
    try {
        location = window.location;
        if (location) {
            return location.protocol + '//' + location.host + baseURL + name;
        }
    } catch (E) {
        // do nothing...
    }

    return config[name];
},

fetch = function (name, cfg) {
    if (!name) {
        return Promise.reject(new Error('service name required!'));
    }

    if (!cfg) {
        cfg = {};
    }

    cfg.url = getURL(name);

    return new Promise(function (resolve, reject) {
        request(cfg, function (error, response, body) {
            var O = {
                error: error,
                response: response,
                body: body
            };

            if (error) {
                return reject(O);
            }

            resolve(O);
        });
    });
};

module.exports = fetch;

module.exports.createServices = function (app, serviceCfg, opts) {
    if (!serviceCfg) {
        throw new Error('fetch.createServices() require service config as second parameter!');
    }

    if (!opts) {
        opts = {};
    }

    if (opts.dupeHeaders && !opts.dupeHeaders.map) {
        throw new Error('opts.dupeHeaders for fetch.createServices() should be an Array!');
    }

    config = serviceCfg;

    if (opts.base) {
        if (!opts.base.match || !opts.base.match(/^\/[^:]\/$/)) {
            throw new Error('baseURL should in \'/foobar/\' format!');
        }
        baseURL = base;
    }

    // Provide fetch services
    app.use(baseURL + ':name', function (req, res) {
        var reqCfg = {
            qs: req.query
        };

        if (opts.dupeHeaders) {
            reqCfg.headers = {};
            opts.dupeHeaders.map(function (V) {
                var H = req.header(V);
                if (H !== undefined) {
                    reqCfg.headers[V] = H;
                }
            });
        }

        fetch(req.params.name, reqCfg).then(function (O) {
            res.send(O.body);
        }).catch(function (E) {
            res.status(500).send(E.stack || E);
        });
    });
};
<commit_msg>remove none function opts.base support (it does not build into bundle so never works well)<commit_after>'use strict';

var request = require('request'),
    baseURL = '/_fetch_/',
    config = {},

getURL = function (name) {
    var location;

    /*global window*/
    try {
        location = window.location;
        if (location) {
            return location.protocol + '//' + location.host + baseURL + name;
        }
    } catch (E) {
        // do nothing...
    }

    return config[name];
},

fetch = function (name, cfg) {
    if (!name) {
        return Promise.reject(new Error('service name required!'));
    }

    if (!cfg) {
        cfg = {};
    }

    cfg.url = getURL(name);

    return new Promise(function (resolve, reject) {
        request(cfg, function (error, response, body) {
            var O = {
                error: error,
                response: response,
                body: body
            };

            if (error) {
                return reject(O);
            }

            resolve(O);
        });
    });
};

module.exports = fetch;

module.exports.createServices = function (app, serviceCfg, opts) {
    if (!serviceCfg) {
        throw new Error('fetch.createServices() require service config as second parameter!');
    }

    if (!opts) {
        opts = {};
    }

    if (opts.dupeHeaders && !opts.dupeHeaders.map) {
        throw new Error('opts.dupeHeaders for fetch.createServices() should be an Array!');
    }

    config = serviceCfg;

    // Provide fetch services
    app.use(baseURL + ':name', function (req, res) {
        var reqCfg = {
            qs: req.query
        };

        if (opts.dupeHeaders) {
            reqCfg.headers = {};
            opts.dupeHeaders.map(function (V) {
                var H = req.header(V);
                if (H !== undefined) {
                    reqCfg.headers[V] = H;
                }
            });
        }

        fetch(req.params.name, reqCfg).then(function (O) {
            res.send(O.body);
        }).catch(function (E) {
            res.status(500).send(E.stack || E);
        });
    });
};
<|endoftext|>


<commit_before>'use strict'

import { join } from 'path'
import { stat, unlinkSync } from 'fs'
import { app, protocol, BrowserWindow, dialog, Menu, Tray } from 'electron'
import {
  createProtocol,
  installVueDevtools
} from 'vue-cli-plugin-electron-builder/lib'

import './startUp'
import './server'
import { dir } from './server/utils'
import { localFiles } from './server/externals'
import external from './events'
import menuTemplate from './menu'

const isDevelopment = process.env.NODE_ENV !== 'production'
const baseConfig = localFiles.getFile('config.json')
const userConfig = baseConfig.config

const menu = Menu.buildFromTemplate(menuTemplate.menu)
const gotTheLock = app.requestSingleInstanceLock()

// 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 win
let tray

// Standard scheme must be registered before the app is ready
protocol.registerStandardSchemes(['app'], { secure: true })

function createWindow () {
  // Create the browser window.
  win = new BrowserWindow({
    width: userConfig.bounds.width || 1200,
    height: userConfig.bounds.height || 800,
    x: userConfig.system.center
      ? null
      : userConfig.bounds.x,
    y: userConfig.system.center
      ? null
      : userConfig.bounds.y,
    center: userConfig.system.center || false,
    titleBarStyle: 'hidden',
    frame: process.platform === 'darwin',
    show: false
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }

  win.once('ready-to-show', () => {
    win.show()
  })

  win.on('close', () => {
    const bounds = win.getBounds()
    const config = localFiles.getFile('config.json')

    config.config.bounds = bounds

    localFiles.writeFile(config, 'config.json')
  })

  win.on('closed', () => {
    win = null
  })
}

// Disable error dialogs by overriding
dialog.showErrorBox = (title, content) => {
  console.log(`${title}\n${content}`)
}

if (process.platform !== 'darwin' && process.argv.length) external(null, process.argv)

if (!isDevelopment && !gotTheLock) {
  app.quit()
} else {
  app.on('second-instance', (event, commandLine) => {
    // Someone tried to run a second instance, we should focus our window.
    if (win) {
      if (win.isMinimized()) win.restore()
      win.focus()

      if (process.platform !== 'darwin') external(null, commandLine)
    }
  })

  app.on('ready', async () => {
    const currentSettings = app.getLoginItemSettings()
    Menu.setApplicationMenu(menu)

    if (userConfig.system.toTray) {
      if (process.platform === 'darwin') {
        app.dock.hide()
      }
      tray = new Tray('../assets/images/tray.png')
      const contextMenu = Menu.buildFromTemplate([
        {
          label: 'New window',
          click: () => {
            win === null
              ? createWindow()
              : win.show()
          },
          accelerator: 'CommandOrControl+N'
        },
        { label: 'Show current window', click: win.show },
        { label: 'Close current window', role: 'close', accelerator: 'CommandOrControl+W' },
        { type: 'separator' },
        { label: 'Quit', role: 'quit', accelerator: 'CommandOrControl+Q' }
      ])
      tray.setToolTip('The ultimate otaku software.')
      tray.setContextMenu(contextMenu)
    }

    if (userConfig.system.autoStart) {
      app.setLoginItemSettings({
        openAtLogin: true
      })
    } else {
      if (currentSettings.openAtLogin) {
        app.setLoginItemSettings({
          openAtLogin: false
        })
      }
    }

    if (isDevelopment && !process.env.IS_TEST) {
      // Install Vue Devtools
      try {
        await installVueDevtools()
      } catch (e) {
        console.error('Vue Devtools failed to install:', e.toString())
      }
    }

    createWindow()
  })

  // Quit when all windows are closed.
  app.on('window-all-closed', function () {
    // 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') {
      if (!tray) {
        app.quit()
      }
    }
  })
}

app.on('quit', () => {
  // We remove logs files every once in a while
  const filesToCheck = ['logs.log', 'error.log']

  filesToCheck.forEach((file) => {
    const filePath = join(dir, file)

    stat(filePath, (err, stats) => {
      if (!err) {
        const size = stats.size / 1000000.0

        if (size > 5) {
          unlinkSync(filePath)
        }
      }
    })
  })
})

app.on('open-file', external)
app.on('open-url', external)

app.on('activate', () => {
  win === null
    ? createWindow()
    : win.show()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', data => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}
<commit_msg>Fixed tray behaviour (Could not find the image)<commit_after>'use strict'

import { join } from 'path'
import { stat, unlinkSync } from 'fs'
import { app, protocol, BrowserWindow, dialog, Menu, Tray } from 'electron'
import {
  createProtocol,
  installVueDevtools
} from 'vue-cli-plugin-electron-builder/lib'

import './startUp'
import './server'
import { dir } from './server/utils'
import { localFiles } from './server/externals'
import external from './events'
import menuTemplate from './menu'

const isDevelopment = process.env.NODE_ENV !== 'production'
const baseConfig = localFiles.getFile('config.json')
const userConfig = baseConfig.config

const menu = Menu.buildFromTemplate(menuTemplate.menu)
const gotTheLock = app.requestSingleInstanceLock()

// 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 win
let tray

// Standard scheme must be registered before the app is ready
protocol.registerStandardSchemes(['app'], { secure: true })

function createWindow () {
  // Create the browser window.
  win = new BrowserWindow({
    width: userConfig.bounds.width || 1200,
    height: userConfig.bounds.height || 800,
    x: userConfig.system.center
      ? null
      : userConfig.bounds.x,
    y: userConfig.system.center
      ? null
      : userConfig.bounds.y,
    center: userConfig.system.center || false,
    titleBarStyle: 'hidden',
    frame: process.platform === 'darwin',
    show: false
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }

  win.once('ready-to-show', () => {
    win.show()
  })

  win.on('close', () => {
    const bounds = win.getBounds()
    const config = localFiles.getFile('config.json')

    config.config.bounds = bounds

    localFiles.writeFile(config, 'config.json')
  })

  win.on('closed', () => {
    win = null
  })
}

// Disable error dialogs by overriding
dialog.showErrorBox = (title, content) => {
  console.log(`${title}\n${content}`)
}

if (process.platform !== 'darwin' && process.argv.length) external(null, process.argv)

if (!isDevelopment && !gotTheLock) {
  app.quit()
} else {
  app.on('second-instance', (event, commandLine) => {
    // Someone tried to run a second instance, we should focus our window.
    if (win) {
      if (win.isMinimized()) win.restore()
      win.focus()

      if (process.platform !== 'darwin') external(null, commandLine)
    }
  })

  app.on('ready', async () => {
    const currentSettings = app.getLoginItemSettings()
    Menu.setApplicationMenu(menu)

    if (userConfig.system.toTray) {
      if (process.platform === 'darwin') {
        app.dock.hide()
      }
      // eslint-disable-next-line no-undef
      tray = new Tray(join(__static, 'images', 'tray.png'))
      const contextMenu = Menu.buildFromTemplate([
        {
          label: 'New window',
          click: () => {
            win === null
              ? createWindow()
              : win.show()
          },
          accelerator: 'CommandOrControl+N'
        },
        { label: 'Show current window', click: win ? win.show : createWindow },
        { label: 'Close current window', role: 'close', accelerator: 'CommandOrControl+W' },
        { type: 'separator' },
        { label: 'Quit', role: 'quit', accelerator: 'CommandOrControl+Q' }
      ])
      tray.setToolTip('The ultimate otaku software.')
      tray.setContextMenu(contextMenu)
    }

    if (userConfig.system.autoStart) {
      app.setLoginItemSettings({
        openAtLogin: true
      })
    } else {
      if (currentSettings.openAtLogin) {
        app.setLoginItemSettings({
          openAtLogin: false
        })
      }
    }

    if (isDevelopment && !process.env.IS_TEST) {
      // Install Vue Devtools
      try {
        await installVueDevtools()
      } catch (e) {
        console.error('Vue Devtools failed to install:', e.toString())
      }
    }

    createWindow()
  })

  // Quit when all windows are closed.
  app.on('window-all-closed', function () {
    // 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') {
      if (!tray) {
        app.quit()
      }
    }
  })
}

app.on('quit', () => {
  // We remove logs files every once in a while
  const filesToCheck = ['logs.log', 'error.log']

  filesToCheck.forEach((file) => {
    const filePath = join(dir, file)

    stat(filePath, (err, stats) => {
      if (!err) {
        const size = stats.size / 1000000.0

        if (size > 5) {
          unlinkSync(filePath)
        }
      }
    })
  })
})

app.on('open-file', external)
app.on('open-url', external)

app.on('activate', () => {
  win === null
    ? createWindow()
    : win.show()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', data => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}
<|endoftext|>


<commit_before>/**
 * Created by BK on 20/06/16.
 *
 * @flow
 */

'use strict';

import React from 'react';
import {
    Text,
    View,
    ListView,
    StyleSheet
} from 'react-native';
import Header from '../../common/Header';
import GlobalStyles from '../../common/GlobalStyles';
import Loader from '../../common/Loader';
import TasksListRow from './TasksListRow';
import type {Task} from '../../reducers/tasks';

type Rows = Array<TasksListRow>;
type RowsAndSections = {
  [sectionID: string]: Object;
};

type TaskData = Rows | RowsAndSections;

type State = {
    dataSource: TaskData,
    loaded: boolean
}

export default class TaskView extends React.Component {
    state: State;

    constructor() {
        super();
        this.state = {
            dataSource: new ListView.DataSource({
                getRowData: (dataBlob, sid, rid) => dataBlob[sid][rid],
                getSectionHeaderData: (dataBlob, sid) => dataBlob[sid],
                rowHasChanged: (row1, row2) => row1 !== row2,
                sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
            }),
            loaded: false
        };
    }

    componentDidMount() {
        let testRows = () => {
            let arr = [];
            let flip = false;
            for (let i = 0; i < 20; i++) {
                arr.push({
                    id: i,
                    title: `Task ${i}`,
                    desc: `desc for task ${i}`,
                    reward: '200',
                    complete: '3/5',
                    status: flip ? 'To Do' : 'Done'
                });
                flip = !flip;
            }
            return arr;
        };
        let tr = testRows();
        let {dataBlob, sectionIds} = this.renderListViewData(tr);

        this.setState({
            dataSource: this.state.dataSource.cloneWithRowsAndSections(dataBlob, sectionIds),
            loaded: true
        });
    }

    renderListViewData(tasks: Array<Task>) {
        let dataBlob = {};
        const sectionIds = ["To Do", "Completed"];

        tasks.map((task: Task) => {
            let section = task.status;
            // add section key to `dataBlob` if not present yet
            if (!dataBlob[section]) dataBlob[section] = [];
            // add this task to said section
            dataBlob[section].push(task);
        });

        return {dataBlob, sectionIds};
    }

    renderSectionHeader(data: Object, sectionId: string) {
        return (
            <View style={styles.sectionHeader}>
                <Text style={styles.sectionHeaderText}>{sectionId}</Text>
            </View>
        );
    }

    renderRow(rowData: Object) {
        return (
            <TasksListRow
                row={rowData}
                onPress={() => this.props.navigator.push({id: "task", task: rowData})}
            />
        );
    }

    renderSeparator(sectionId: string, rowId: string) {
        return (
            <View key={sectionId+rowId} style={GlobalStyles.separator} />
        );
    }

    // TODO GH #6; add searchBar header
    render() {
        if (!this.state.loaded)
            return <Loader title='Tasks' />

        return (
            <View style={styles.container}>
                <Header
                    title="Tasks"
                    rightItem={{
                        title: "Add Task",
                        layout: "icon",
                        icon: "ios-add"
                    }}
                />
                <ListView
                    automaticallyAdjustContentInsets={false}
                    style={styles.listView}
                    dataSource={this.state.dataSource}
                    renderRow={this.renderRow.bind(this)}
                    renderSectionHeader={this.renderSectionHeader}
                    renderSeparator={this.renderSeparator}
                />
            </View>
        );
    }

} // END CLASS

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    sectionHeader: {
        backgroundColor: 'gray'
    },
    sectionHeaderText: {
        fontSize: 16,
        color: 'white',
        paddingLeft: 10
    },
});
<commit_msg>Minor fix for correct section headers<commit_after>/**
 * Created by BK on 20/06/16.
 *
 * @flow
 */

'use strict';

import React from 'react';
import {
    Text,
    View,
    ListView,
    StyleSheet
} from 'react-native';
import Header from '../../common/Header';
import GlobalStyles from '../../common/GlobalStyles';
import Loader from '../../common/Loader';
import TasksListRow from './TasksListRow';
import type {Task} from '../../reducers/tasks';

type Rows = Array<TasksListRow>;
type RowsAndSections = {
  [sectionID: string]: Object;
};

type TaskData = Rows | RowsAndSections;

type State = {
    dataSource: TaskData,
    loaded: boolean
}

export default class TaskView extends React.Component {
    state: State;

    constructor() {
        super();
        this.state = {
            dataSource: new ListView.DataSource({
                getRowData: (dataBlob, sid, rid) => dataBlob[sid][rid],
                getSectionHeaderData: (dataBlob, sid) => dataBlob[sid],
                rowHasChanged: (row1, row2) => row1 !== row2,
                sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
            }),
            loaded: false
        };
    }

    componentDidMount() {
        let testRows = () => {
            let arr = [];
            let flip = false;
            for (let i = 0; i < 20; i++) {
                arr.push({
                    id: i,
                    title: `Task ${i}`,
                    desc: `desc for task ${i}`,
                    reward: '200',
                    complete: '3/5',
                    status: flip ? 'To Do' : 'Completed'
                });
                flip = !flip;
            }
            return arr;
        };
        let tr = testRows();
        let {dataBlob, sectionIds} = this.renderListViewData(tr);

        this.setState({
            dataSource: this.state.dataSource.cloneWithRowsAndSections(dataBlob, sectionIds),
            loaded: true
        });
    }

    renderListViewData(tasks: Array<Task>) {
        let dataBlob = {};
        const sectionIds = ["To Do", "Completed"];

        tasks.map((task: Task) => {
            let section = task.status;
            // add section key to `dataBlob` if not present yet
            if (!dataBlob[section]) dataBlob[section] = [];
            // add this task to said section
            dataBlob[section].push(task);
        });

        return {dataBlob, sectionIds};
    }

    renderSectionHeader(data: Object, sectionId: string) {
        return (
            <View style={styles.sectionHeader}>
                <Text style={styles.sectionHeaderText}>{sectionId}</Text>
            </View>
        );
    }

    renderRow(rowData: Object) {
        return (
            <TasksListRow
                row={rowData}
                onPress={() => this.props.navigator.push({id: "task", task: rowData})}
            />
        );
    }

    renderSeparator(sectionId: string, rowId: string) {
        return (
            <View key={sectionId+rowId} style={GlobalStyles.separator} />
        );
    }

    // TODO GH #6; add searchBar header
    render() {
        if (!this.state.loaded)
            return <Loader title='Tasks' />

        return (
            <View style={styles.container}>
                <Header
                    title="Tasks"
                    rightItem={{
                        title: "Add Task",
                        layout: "icon",
                        icon: "ios-add"
                    }}
                />
                <ListView
                    automaticallyAdjustContentInsets={false}
                    style={styles.listView}
                    dataSource={this.state.dataSource}
                    renderRow={this.renderRow.bind(this)}
                    renderSectionHeader={this.renderSectionHeader}
                    renderSeparator={this.renderSeparator}
                />
            </View>
        );
    }

} // END CLASS

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    sectionHeader: {
        backgroundColor: 'gray'
    },
    sectionHeaderText: {
        fontSize: 16,
        color: 'white',
        paddingLeft: 10
    },
});
<|endoftext|>


<commit_before>'use strict';

var last           = require('es5-ext/string/#/last')
  , DbjsError      = require('../error')
  , unserializeKey = require('./key')

  , isTypeId = RegExp.prototype.test.bind(/^[A-Z]/);

module.exports = function (db) {
	var objects = db.objects, Base = db.Base, ObjectType = db.Object
	  , proto = Base.prototype, isObjectType = db.isObjectType
	  , data = objects.__setData__
	  , object, char, str, i, pSKey, resolveObject, reject
	  , $object, $descriptor, $property
	  , $descriptorProperty, $item, proposedProto;

	reject = function () {
		throw new DbjsError(str + ' is not valid object id',
			'INVALID_OBJECT_ADDRESS');
	};

	resolveObject = function () {
		var id = str.slice(0, i), ProtoType, isProto;
		if (!id) reject();
		if (data[id]) {
			object = data[id];
			return;
		}
		if (last.call(id) === '#') {
			isProto = true;
			id = id.slice(0, -1);
		}
		if (proposedProto) {
			if (isTypeId(proposedProto.__id__)) ProtoType = proposedProto;
			proposedProto = null;
		}
		if (isTypeId(id)) {
			object = (ProtoType || Base)._extend_(id);
		} else {
			if (ProtoType && !isObjectType(ProtoType)) ProtoType = null;
			object = (ProtoType || ObjectType)._create_(id);
		}
		if (isProto) object = object.prototype;
	};

	$object = function () {
		while ((char = str[++i])) {
			if (char === '$') {
				resolveObject();
				return $descriptor;
			}
			if (char === '/') {
				resolveObject();
				return $property;
			}
		}
		resolveObject();
	};

	$property = function () {
		var start, sKey;
		if (str[i + 2] === '"') {
			start = ++i;
			++i;
			while ((char = str[++i])) {
				if (char === '\\') {
					char = str[++i];
					continue;
				}
				if (char === '"') break;
			}
			char = str[++i];
			sKey = str.slice(start, i);
			if (!proto._keys_[sKey]) proto._serialize_(unserializeKey(sKey, objects));
		} else {
			start = i + 1;
			while ((char = str[++i])) {
				if (char === '/') break;
				if (char === '*') break;
			}
			sKey = str.slice(start, i);
			if (sKey === '') reject();
			if (!proto._keys_[sKey]) proto._serialize_(unserializeKey(sKey, objects));
		}
		if (!char) {
			object = object._getOwnDescriptor_(sKey);
			return;
		}
		if (char === '/') {
			object = object._getObject_(sKey);
			return $property;
		}
		if (char === '$') {
			object = object._getObject_(sKey);
			return $descriptor;
		}
		if (char === '*') {
			pSKey = sKey;
			return $item;
		}
		reject();
	};

	$descriptor = function () {
		var start, sKey;
		if (str[i + 2] === '"') {
			start = ++i;
			++i;
			while ((char = str[++i])) {
				if (char === '\\') {
					char = str[++i];
					continue;
				}
				if (char === '"') break;
			}
			char = str[++i];
			sKey = str.slice(start, i);
			if (!proto._keys_[sKey]) proto._serialize_(unserializeKey(sKey, objects));
		} else {
			start = i + 1;
			while ((char = str[++i])) {
				if (char === '/') break;
			}
			sKey = str.slice(start, i);
			if (sKey && !proto._keys_[sKey]) {
				proto._serialize_(unserializeKey(sKey, objects));
			}
		}
		if (char !== '/') reject();
		if (!sKey) object = object._descriptorPrototype_;
		else object = object._getOwnDescriptor_(sKey);
		return $descriptorProperty;
	};

	$descriptorProperty = function () {
		var key = str.slice(i + 1);
		object._serialize_(key);
		object = object._getOwnDescriptor_(key);
	};

	$item = function () {
		var sKey, key;
		sKey = str.slice(i + 1);
		key = unserializeKey(sKey, objects);
		object = object._getOwnMultipleItem_(pSKey, key, sKey);
	};

	return function (input, proto) {
		var state;
		str = String(input);
		if (data[str]) return data[str];
		proposedProto = proto;
		state = $object;
		i = -1;
		while ((state = state())) continue; //jslint: skip
		return object;
	};
};
<commit_msg>Better validation of object ids<commit_after>'use strict';

var last           = require('es5-ext/string/#/last')
  , DbjsError      = require('../error')
  , unserializeKey = require('./key')

  , isTypeId = RegExp.prototype.test.bind(/^[A-Z]/);

module.exports = function (db) {
	var objects = db.objects, Base = db.Base, ObjectType = db.Object
	  , proto = Base.prototype, isObjectType = db.isObjectType
	  , data = objects.__setData__
	  , object, char, str, i, pSKey, resolveObject, reject
	  , $object, $descriptor, $property
	  , $descriptorProperty, $item, proposedProto;

	reject = function () {
		throw new DbjsError(str + ' is not valid object id',
			'INVALID_OBJECT_ADDRESS');
	};

	resolveObject = function () {
		var id = str.slice(0, i), ProtoType, isProto;
		if (!id) reject();
		if (data[id]) {
			object = data[id];
			return;
		}
		if (last.call(id) === '#') {
			isProto = true;
			id = id.slice(0, -1);
		}
		if (proposedProto) {
			if (isTypeId(proposedProto.__id__)) ProtoType = proposedProto;
			proposedProto = null;
		}
		if (isTypeId(id)) {
			object = (ProtoType || Base)._extend_(id);
		} else {
			if (ProtoType && !isObjectType(ProtoType)) ProtoType = null;
			object = (ProtoType || ObjectType)._create_(id);
		}
		if (isProto) object = object.prototype;
	};

	$object = function () {
		while ((char = str[++i])) {
			if (char === '$') {
				resolveObject();
				return $descriptor;
			}
			if (char === '/') {
				resolveObject();
				return $property;
			}
		}
		resolveObject();
	};

	$property = function () {
		var start, sKey;
		if (str[i + 2] === '"') {
			start = ++i;
			++i;
			while ((char = str[++i])) {
				if (char === '\\') {
					char = str[++i];
					continue;
				}
				if (char === '"') break;
			}
			char = str[++i];
			sKey = str.slice(start, i);
			if (!proto._keys_[sKey]) proto._serialize_(unserializeKey(sKey, objects));
		} else {
			start = i + 1;
			while ((char = str[++i])) {
				if (char === '/') break;
				if (char === '*') break;
			}
			sKey = str.slice(start, i);
			if ((sKey === '') || (sKey === '$')) reject();
			if (!proto._keys_[sKey]) proto._serialize_(unserializeKey(sKey, objects));
		}
		if (!char) {
			object = object._getOwnDescriptor_(sKey);
			return;
		}
		if (char === '/') {
			object = object._getObject_(sKey);
			return $property;
		}
		if (char === '$') {
			object = object._getObject_(sKey);
			return $descriptor;
		}
		if (char === '*') {
			pSKey = sKey;
			return $item;
		}
		reject();
	};

	$descriptor = function () {
		var start, sKey;
		if (str[i + 2] === '"') {
			start = ++i;
			++i;
			while ((char = str[++i])) {
				if (char === '\\') {
					char = str[++i];
					continue;
				}
				if (char === '"') break;
			}
			char = str[++i];
			sKey = str.slice(start, i);
			if (!proto._keys_[sKey]) proto._serialize_(unserializeKey(sKey, objects));
		} else {
			start = i + 1;
			while ((char = str[++i])) {
				if (char === '/') break;
			}
			sKey = str.slice(start, i);
			if (sKey && !proto._keys_[sKey]) {
				proto._serialize_(unserializeKey(sKey, objects));
			}
		}
		if (char !== '/') reject();
		if (!sKey) object = object._descriptorPrototype_;
		else object = object._getOwnDescriptor_(sKey);
		return $descriptorProperty;
	};

	$descriptorProperty = function () {
		var key = str.slice(i + 1);
		object._serialize_(key);
		object = object._getOwnDescriptor_(key);
	};

	$item = function () {
		var sKey, key;
		sKey = str.slice(i + 1);
		key = unserializeKey(sKey, objects);
		object = object._getOwnMultipleItem_(pSKey, key, sKey);
	};

	return function (input, proto) {
		var state;
		str = String(input);
		if (data[str]) return data[str];
		proposedProto = proto;
		state = $object;
		i = -1;
		while ((state = state())) continue; //jslint: skip
		return object;
	};
};
<|endoftext|>


<commit_before>'use strict';
module.exports =

/*@ngInject*/
function SentencePlayCtrl(
  $scope, $state, SentenceWritingService, RuleService, _
) {

  $scope.$watch('currentRuleQuestion', function(crq) {
    if (_.isObject(crq)) {
      $scope.currentRule = $scope.swSet[crq.ruleIndex];
    }
  });

  $scope.number = 1;

  $scope.$on('correctRuleQuestion', function() {
    $scope.showNextQuestion = true;
  });

  $scope.nextQuestion = function() {
    $scope.showNextQuestion = false;
    var crq = $scope.currentRuleQuestion;
    var ncrq = $scope.questions[_.indexOf($scope.questions, crq) + 1];
    $scope.number = $scope.number + 1;
    $scope.currentRuleQuestion = ncrq;
  };

  if ($state.params.id) {
    SentenceWritingService.getSentenceWriting($state.params.id).then(function(sw) {
      $scope.sentenceWriting = sw;
      var ruleIds = _.pluck(sw.rules, 'ruleId');
      var quantities = _.pluck(sw.rules, 'quantity');
      return retrieveNecessaryRules(ruleIds, quantities);
    }, errorStateChange);
  } else if ($state.params.ids) {
    var ids = _.uniq($state.params.ids.split(','));
    var quantities = _.chain(ids)
      .map(function() { return 3; })
      .value();
    retrieveNecessaryRules(ids, quantities);
  }

  function retrieveNecessaryRules(ruleIds, quantities) {
    RuleService.getRules(ruleIds).then(function(resolvedRules) {
      $scope.swSet = _.chain(resolvedRules)
        .map(function(rr, i) {
          rr.selectedRuleQuestions = _.chain(rr.resolvedRuleQuestions)
            .sample(quantities[i])
            .map(function(rrq) {
              rrq.ruleIndex = i;
              return rrq;
            })
            .value();
          return rr;
        })
        .value();

      $scope.questions = _.chain($scope.swSet)
        .pluck('selectedRuleQuestions')
        .flatten()
        .value();

      $scope.currentRuleQuestion = $scope.questions[0];
      $scope.showNextQuestion = false;
      $scope.showPreviousQuestion = false;
    }, function() {
      //errorStateChange();
    });
  }

  function errorStateChange() {
    $state.go('index');
  }
};
<commit_msg>Change to uid for sentence writings<commit_after>'use strict';
module.exports =

/*@ngInject*/
function SentencePlayCtrl(
  $scope, $state, SentenceWritingService, RuleService, _
) {

  $scope.$watch('currentRuleQuestion', function(crq) {
    if (_.isObject(crq)) {
      $scope.currentRule = $scope.swSet[crq.ruleIndex];
    }
  });

  $scope.number = 1;

  $scope.$on('correctRuleQuestion', function() {
    $scope.showNextQuestion = true;
  });

  $scope.nextQuestion = function() {
    $scope.showNextQuestion = false;
    var crq = $scope.currentRuleQuestion;
    var ncrq = $scope.questions[_.indexOf($scope.questions, crq) + 1];
    $scope.number = $scope.number + 1;
    $scope.currentRuleQuestion = ncrq;
  };

  if ($state.params.uid) {
    SentenceWritingService.getSentenceWriting($state.params.uid).then(function(sw) {
      $scope.sentenceWriting = sw;
      var ruleIds = _.pluck(sw.rules, 'ruleId');
      var quantities = _.pluck(sw.rules, 'quantity');
      return retrieveNecessaryRules(ruleIds, quantities);
    }, errorStateChange);
  } else if ($state.params.ids) {
    var ids = _.uniq($state.params.ids.split(','));
    var quantities = _.chain(ids)
      .map(function() { return 3; })
      .value();
    retrieveNecessaryRules(ids, quantities);
  }

  function retrieveNecessaryRules(ruleIds, quantities) {
    RuleService.getRules(ruleIds).then(function(resolvedRules) {
      $scope.swSet = _.chain(resolvedRules)
        .map(function(rr, i) {
          rr.selectedRuleQuestions = _.chain(rr.resolvedRuleQuestions)
            .sample(quantities[i])
            .map(function(rrq) {
              rrq.ruleIndex = i;
              return rrq;
            })
            .value();
          return rr;
        })
        .value();

      $scope.questions = _.chain($scope.swSet)
        .pluck('selectedRuleQuestions')
        .flatten()
        .value();

      $scope.currentRuleQuestion = $scope.questions[0];
      $scope.showNextQuestion = false;
      $scope.showPreviousQuestion = false;
    }, function() {
      //errorStateChange();
    });
  }

  function errorStateChange() {
    $state.go('index');
  }
};
<|endoftext|>


<commit_before>/**
 * Copyright 2018 The AMP HTML Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

const colors = require('ansi-colors');
const fs = require('fs-extra');
const gulp = require('gulp-help')(require('gulp'));
const log = require('fancy-log');
const {getStdout} = require('../exec');

const runtimeFile = './dist/v0.js';
const maxSize = '81.30KB';

const {green, red, cyan, yellow} = colors;

/**
 * Checks gzipped size of existing v0.js (amp.js) against `maxSize`.
 * Does _not_ rebuild: run `gulp dist --fortesting --noextensions` first.
 */
function checkBundleSize() {
  if (!fs.existsSync(runtimeFile)) {
    log(yellow('Could not find'), cyan(runtimeFile) +
        yellow('. Skipping bundlesize check.'));
    log(yellow('To include this check, run'),
        cyan('gulp dist --fortesting [--noextensions]'),
        yellow('before'), cyan('gulp bundle-size') + yellow('.'));
    return;
  }

  const cmd = `npx bundlesize -f "${runtimeFile}" -s "${maxSize}"`;
  log('Running ' + cyan(cmd) + '...');
  const output = getStdout(cmd);
  const pass = output.match(/PASS .*/);
  const fail = output.match(/FAIL .*/);
  const error = output.match(/ERROR .*/);
  if (error && error.length > 0) {
    log(yellow(error[0]));
  } else if (fail && fail.length > 0) {
    log(red(fail[0]));
    log(red('ERROR:'), cyan('bundlesize'), red('found that'),
        cyan(runtimeFile), red('has exceeded its size cap of'),
        cyan(maxSize) + red('.'));
    log(red(
        'This is part of a new effort to reduce AMP\'s binary size (#14392).'));
    log(red('Please contact @choumx or @jridgewell for assistance.'));
    process.exitCode = 1;
  } else if (pass && pass.length > 0) {
    log(green(pass[0]));
  } else {
    log(yellow(output));
  }
}

gulp.task(
    'bundle-size',
    'Checks if the minified AMP binary has exceeded its size cap',
    checkBundleSize);
<commit_msg>Make bundle-size cap less precise (#17805)<commit_after>/**
 * Copyright 2018 The AMP HTML Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

const colors = require('ansi-colors');
const fs = require('fs-extra');
const gulp = require('gulp-help')(require('gulp'));
const log = require('fancy-log');
const {getStdout} = require('../exec');

const runtimeFile = './dist/v0.js';
const maxSize = '81.4KB'; // Only use 0.1KB of precision i.e no hundredths digit.

const {green, red, cyan, yellow} = colors;

/**
 * Checks gzipped size of existing v0.js (amp.js) against `maxSize`.
 * Does _not_ rebuild: run `gulp dist --fortesting --noextensions` first.
 */
function checkBundleSize() {
  if (!fs.existsSync(runtimeFile)) {
    log(yellow('Could not find'), cyan(runtimeFile) +
        yellow('. Skipping bundlesize check.'));
    log(yellow('To include this check, run'),
        cyan('gulp dist --fortesting [--noextensions]'),
        yellow('before'), cyan('gulp bundle-size') + yellow('.'));
    return;
  }

  const cmd = `npx bundlesize -f "${runtimeFile}" -s "${maxSize}"`;
  log('Running ' + cyan(cmd) + '...');
  const output = getStdout(cmd);
  const pass = output.match(/PASS .*/);
  const fail = output.match(/FAIL .*/);
  const error = output.match(/ERROR .*/);
  if (error && error.length > 0) {
    log(yellow(error[0]));
  } else if (fail && fail.length > 0) {
    log(red(fail[0]));
    log(red('ERROR:'), cyan('bundlesize'), red('found that'),
        cyan(runtimeFile), red('has exceeded its size cap of'),
        cyan(maxSize) + red('.'));
    log(red(
        'This is part of a new effort to reduce AMP\'s binary size (#14392).'));
    log(red('Please contact @choumx or @jridgewell for assistance.'));
    process.exitCode = 1;
  } else if (pass && pass.length > 0) {
    log(green(pass[0]));
  } else {
    log(yellow(output));
  }
}

gulp.task(
    'bundle-size',
    'Checks if the minified AMP binary has exceeded its size cap',
    checkBundleSize);
<|endoftext|>


<commit_before>var cheerio = require('cheerio');
var parserUtil = require('./parserUtil');
var request = require('request');

module.exports.parse = function(html, callback) {

    var $ = cheerio.load(html);

    var menu = [];

    var pic = $('.entry-content img').attr('src');

    if (pic)
    {
        request.post({
            headers: { 'Content-type': 'application/x-www-form-urlencoded' },
            url: 'http://at11ocr.azurewebsites.net/api/process/encoded',
            body: "=" + encodeURIComponent(pic)
        }, function(error, response, body) {
            if (!error)
            {
                parseMenu(body);
            }
            callback(menu);
        });
    }
    else
    {
        parseMenu($('div.entry-content', '#post-2').text());
    }

    function parseMenu(menuString)
    {
        var lines = menuString.split("\n").filter(function(val) {
            return val.trim();
        });
        var now = global.todaysDate;
        var dateReg = new RegExp("^\\s*0?" + now.date() + "\\.\\s*0?" + (now.month() + 1) + "\\.\\s*" + now.year());
        var todayNameReg = new RegExp("^" + now.format("dddd"), "i");
        var price;
        for (var i = 0; i < lines.length; i++)
        {
            if (todayNameReg.test(lines[i]))
            {
                for(var offset = 0; offset < 3; offset++)//3 menu lines each day
                {
                    var txt = lines[i+offset];
                    if(offset === 0)
                        txt = txt.replace(todayNameReg, "");
                    if(offset === 1)
                        txt = txt.replace(dateReg, "");
                    txt = normalize(txt);
                    if(txt)
                        menu.push(txt);
                }
            }
            if (/Hodnota stravy/.test(lines[i]))
            {
                price = parserUtil.parsePrice(lines[i]).price;
            }
        }

        //convert to menu item object
        menu = menu.map(function(item, index) {
            return { isSoup: /polievka/i.test(item), text: item, price: index === 0 ? NaN : price };
        });

        callback(menu);
    }

    function normalize(str) {
        return str.tidyAfterOCR()
            .removeItemNumbering()
            .removeMetrics()
            .normalizeWhitespace()
            .correctCommaSpacing();
    }
};<commit_msg>resolves #69<commit_after>var cheerio = require('cheerio');
var parserUtil = require('./parserUtil');
var request = require('request');

module.exports.parse = function(html, callback) {

    var $ = cheerio.load(html);

    var menu = [];

    var pic = $('.entry-content img').attr('src');

    if (pic)
    {
        request.post({
            headers: { 'Content-type': 'application/x-www-form-urlencoded' },
            url: 'http://at11ocr.azurewebsites.net/api/process/encoded',
            body: "=" + encodeURIComponent(pic)
        }, function(error, response, body) {
            if (!error)
            {
                parseMenu(body);
            }
            callback(menu);
        });
    }
    else
    {
        parseMenu($('div.entry-content', '#post-2').text());
    }

    function parseMenu(menuString)
    {
        var lines = menuString.split("\n").filter(function(val) {
            return val.trim();
        });
        var now = global.todaysDate;
        var dateReg = new RegExp("^\\s*0?" + now.date() + "\\.\\s*0?" + (now.month() + 1) + "\\.\\s*" + now.year());
        var todayNameReg = new RegExp("^" + now.format("dddd"), "i");
        var price;
        for (var i = 0; i < lines.length; i++)
        {
            if (todayNameReg.test(lines[i]))
            {
                for(var offset = 0; offset < 3; offset++)//3 menu lines each day
                {
                    var txt = lines[i+offset];
                    if(offset === 0)
                        txt = txt.replace(todayNameReg, "");
                    if(offset === 1)
                        txt = txt.replace(dateReg, "");
                    txt = normalize(txt);
                    if(txt)
                        menu.push(txt);
                }
            }
            if (/Hodnota stravy/.test(lines[i]))
                price = parserUtil.parsePrice(lines[i]).price;
            else
                price = NaN;
        }

        //convert to menu item object
        menu = menu.map(function(item, index) {
            return { isSoup: /polievka/i.test(item), text: item, price: index === 0 ? NaN : price };
        });

        callback(menu);
    }

    function normalize(str) {
        return str.tidyAfterOCR()
            .removeItemNumbering()
            .removeMetrics()
            .normalizeWhitespace()
            .correctCommaSpacing();
    }
};<|endoftext|>


<commit_before>TcpClient = function(settings) {
    this.queryId=0;
    this.settings = settings;
    var that = this;
    document.addEventListener("notify",function(ev) {
        that.notify(ev.detail.type, ev.detail.value, ev.detail.args);
    });
}

TcpClient.prototype = {
    connect: function() {
        var that = this;
        this.socket = new WebSocket(this.settings.getUri());
        this.socket.onopen = function() {
            that._onOpenCallback();
        };
        this.socket.onmessage = function(msg) {
            that._onMessageCallback(msg);
        };
        this.socket.onclose = function() {
            that._onCloseCallback();
        };
        this.socket.onerror = function(event) {
            that._onErrorCallback(event);
        };
    },
    notify: function(type, value, args) {
        var argsString = "";
        if(args != undefined) {
            for(var key in args) {
                argsString+=" "+key+"='"+args[key]+"'";
            }
        }
        var socketString ="<action type='"+type+"'";
        if(argsString.length) {
            socketString+=argsString;
        }
        socketString+=">";
        if(value != undefined) {
            socketString+=value;
        }
        socketString+="</action>";
        this.socket.send(socketString);
    },
    incrementQueryId: function() {
        this.queryId++;
    },
    _onOpenCallback : function() {
        //Hide the socket connect window
        clearTimeout(this.timeout);
        var that = this;
        $(".splashscreen").hide();
        RemoteEvent.create("notify", {
            type:"screen",
            args: {
                "screen":that.settings.screen
                }
        });
        this.notify("getCatalogList")
    },
    _onMessageCallback : function(msg) {
        xml = $($.parseXML(msg.data));
        eventName = xml.children().get(0).nodeName;
        RemoteEvent.create(eventName, xml)
    },
    _onCloseCallback : function() {
        //Show the socket connect window
        $(".splashscreen").show();
        var that = this;
        this.timeout = setTimeout(function(){
            tcpClient = that.connect();
        },3000);
    },
    _onErrorCallback : function(event) {
    }

}<commit_msg>correction bug affichage splashscreen<commit_after>TcpClient = function(settings) {
    this.queryId=0;
    this.settings = settings;
    var that = this;
    document.addEventListener("notify",function(ev) {
        that.notify(ev.detail.type, ev.detail.value, ev.detail.args);
    });
}

TcpClient.prototype = {
    connect: function() {
        var that = this;
        this.socket = new WebSocket(this.settings.getUri());
        this.socket.onopen = function() {
            that._onOpenCallback();
        };
        this.socket.onmessage = function(msg) {
            that._onMessageCallback(msg);
        };
        this.socket.onclose = function() {
            that._onCloseCallback();
        };
        this.socket.onerror = function(event) {
            that._onErrorCallback(event);
        };
    },
    notify: function(type, value, args) {
        var argsString = "";
        if(args != undefined) {
            for(var key in args) {
                argsString+=" "+key+"='"+args[key]+"'";
            }
        }
        var socketString ="<action type='"+type+"'";
        if(argsString.length) {
            socketString+=argsString;
        }
        socketString+=">";
        if(value != undefined) {
            socketString+=value;
        }
        socketString+="</action>";
        this.socket.send(socketString);
    },
    incrementQueryId: function() {
        this.queryId++;
    },
    _onOpenCallback : function() {
        //Hide the socket connect window
        clearTimeout(this.timeout);
        var that = this;
        $(".splashscreen").hide();
        RemoteEvent.create("notify", {
            type:"screen",
            args: {
                "screen":that.settings.screen
            }
        });
        this.notify("getCatalogList")
    },
    _onMessageCallback : function(msg) {
        xml = $($.parseXML(msg.data));
        eventName = xml.children().get(0).nodeName;
        RemoteEvent.create(eventName, xml)
    },
    _onCloseCallback : function() {
        //Show the socket connect window
        $(".splashscreen").css("display","table");
        var that = this;
        this.timeout = setTimeout(function(){
            tcpClient = that.connect();
        },3000);
    },
    _onErrorCallback : function(event) {
    }

}<|endoftext|>


<commit_before>describe("bookmarkManager", function() {
    var scope,
        response_data,
        $httpBackend;
    beforeEach(angular.mock.module("feedhoos"));
    beforeEach(angular.mock.inject(function($rootScope, _$httpBackend_) {
        scope = $rootScope.$new();
        defalt_id = 0;
        $httpBackend = _$httpBackend_;
        $httpBackend.expect("GET", "/bookmark/list/")
            .respond('{' +
                '"2": {"rating": 3, "folder_id": 1},' +
                '"0": {"rating": 6, "folder_id": 0},' +
                '"3": {"rating": 0, "folder_id": 3},' +
                '"1": {"rating": 5, "folder_id": 3}' +
            '}');
        response_data = {
            "2": {"rating": 3, "folder_id": 1},
            "0": {"rating": 6, "folder_id": 0},
            "3": {"rating": 0, "folder_id": 3},
            "1": {"rating": 5, "folder_id": 3}
        };
    }));

    it('should set', inject(function(bookmarkManager) {
        bookmarkManager.set(scope, function() {});
        $httpBackend.flush();
        expect(bookmarkManager.data).toEqual(response_data);
    }));

    it('should remove', inject(function(bookmarkManager) {
        bookmarkManager.set(scope, function() {});
        $httpBackend.flush();
        var expect_data = {
            "2": {"rating": 3, "folder_id": 1},
            "0": {"rating": 6, "folder_id": 0},
            "3": {"rating": 0, "folder_id": 3},
        };
        bookmarkManager.remove(1);
        expect(bookmarkManager.data).toEqual(expect_data);
    }));
});
<commit_msg>add test for bookmarkManager::add()<commit_after>describe("bookmarkManager", function() {
    var scope,
        response_data,
        $httpBackend;
    beforeEach(angular.mock.module("feedhoos"));
    beforeEach(angular.mock.inject(function($rootScope, _$httpBackend_) {
        scope = $rootScope.$new();
        defalt_id = 0;
        $httpBackend = _$httpBackend_;
        $httpBackend.expect("GET", "/bookmark/list/")
            .respond('{' +
                '"2": {"rating": 3, "folder_id": 1},' +
                '"0": {"rating": 6, "folder_id": 0},' +
                '"3": {"rating": 0, "folder_id": 3},' +
                '"1": {"rating": 5, "folder_id": 3}' +
            '}');
        response_data = {
            "2": {"rating": 3, "folder_id": 1},
            "0": {"rating": 6, "folder_id": 0},
            "3": {"rating": 0, "folder_id": 3},
            "1": {"rating": 5, "folder_id": 3}
        };
    }));

    it('should set', inject(function(bookmarkManager) {
        bookmarkManager.set(scope, function() {});
        $httpBackend.flush();
        expect(bookmarkManager.data).toEqual(response_data);
    }));

    it('should remove', inject(function(bookmarkManager) {
        bookmarkManager.set(scope, function() {});
        $httpBackend.flush();
        var expect_data = {
            "2": {"rating": 3, "folder_id": 1},
            "0": {"rating": 6, "folder_id": 0},
            "3": {"rating": 0, "folder_id": 3},
        };
        bookmarkManager.remove(1);
        expect(bookmarkManager.data).toEqual(expect_data);
    }));

    it('should add', inject(function(bookmarkManager) {
        bookmarkManager.set(scope, function() {});
        $httpBackend.flush();
        var expect_data = {
            "8": {"rating": 0, "folder_id": 0},
            "2": {"rating": 3, "folder_id": 1},
            "0": {"rating": 6, "folder_id": 0},
            "3": {"rating": 0, "folder_id": 3},
            "1": {"rating": 5, "folder_id": 3}
        };
        bookmarkManager.add(8);
        expect(bookmarkManager.data).toEqual(expect_data);
    }));
});
<|endoftext|>


<commit_before>var images = {};
var entities = [];
var canvas, ctx;
var player;

var MISSILE_SPEED = 3;

function loadImages(directory, fileNames, onComplete) {
    var imagesLeft = fileNames.length;

    fileNames.forEach(function(fileName) {
        var img = new Image();
        img.onload = function() {
            imagesLeft--;
            if (imagesLeft <= 0)
                onComplete();
        };
        img.src = directory + '/' + fileName;

        // z "player.png" uzyskamy "player", za pomoca funkcji substring
        var entityName = fileName.substring(0, fileName.lastIndexOf('.'));

        images[entityName] = img;
    });
};

var EntityPrototype = {
    draw: function(context) {
        context.drawImage(this.img, this.x, this.y);
    },
    move: function() {
        this.x += this.vx;
        this.y += this.vy;
    },
    x: 0, y:0, vx:0, vy:0
};

function createEntity(entityName, properties) {
    var entity = Object.create(EntityPrototype);
    entity.img = images[entityName];

    for (var propertyName in properties)
        entity[propertyName] = properties[propertyName];

    entities.push(entity);
    return entity;
};

function initialize() {
    initCanvas();
    console.log('initialize()');
    console.log(images['player']);
    console.log(images['ufo']);

    player = createEntity('player', {x:300,y:280, speed:4});
    player.input = function(key) {
        switch(key){
            case 'left': this.x -= this.speed; break;
            case 'right': this.x += this.speed; break;
            case 'up': this.y -= this.speed; break;
            case 'down': this.y += this.speed; break;
            case 'fire':
                var missile = createEntity('missile', {});
                missile.x = this.x + this.img.width / 2 - missile.img.width / 2;
                missile.y = this.y - missile.img.height;
                missile.vy = -MISSILE_SPEED;
                break;

        }
    }

    createEntity('ufo', {x:0, y:20, vx:1, vy:0.1})
    createEntity('ufo', {x:120, y:80, vx:1.1, vy:0})
    createEntity('ufo', {x:40, y:130, vx:1.05, vy:0})

    setInterval(gameLoop, 1000/60);
};

function gameLoop() {
    ctx.clearRect(0,0,canvas.width, canvas.height);

    entities.forEach(function (entity) {
        entity.move();
    });

    entities.forEach(function (entity) {
        entity.draw(ctx);
    });

}

function initCanvas() {
    canvas = document.getElementById('canvas');
    ctx = canvas.getContext('2d');
};

$(document).ready(function() {
    loadImages('images', ['player.png', 'ufo.png', 'missile.png'], initialize);
    $(document).keydown(function(e) {
        var key = {37: 'left', 38: 'up', 39:'right', 40:'down', 32:'fire'}[e.keyCode];
        player.input(key)
    })
});
<commit_msg>step-5<commit_after>var images = {};
var entities = [];
var canvas, ctx;
var player;

var MISSILE_SPEED = 3;

function loadImages(directory, fileNames, onComplete) {
    var imagesLeft = fileNames.length;

    fileNames.forEach(function(fileName) {
        var img = new Image();
        img.onload = function() {
            imagesLeft--;
            if (imagesLeft <= 0)
                onComplete();
        };
        img.src = directory + '/' + fileName;

        // z "player.png" uzyskamy "player", za pomoca funkcji substring
        var entityName = fileName.substring(0, fileName.lastIndexOf('.'));

        images[entityName] = img;
    });
};

var EntityPrototype = {
    draw: function(context) {
        context.drawImage(this.img, this.x, this.y);
    },
    move: function() {
        this.x += this.vx;
        this.y += this.vy;
    },
    x: 0, y:0, vx:0, vy:0
};

function createEntity(entityName, properties) {
    var entity = Object.create(EntityPrototype);
    entity.img = images[entityName];
    entity.type = entityName;

    for (var propertyName in properties)
        entity[propertyName] = properties[propertyName];

    entities.push(entity);
    return entity;
};

function initialize() {
    initCanvas();
    console.log('initialize()');
    console.log(images['player']);
    console.log(images['ufo']);

    player = createEntity('player', {x:300,y:280, speed:4});
    player.input = function(key) {
        switch(key){
            case 'left': this.x -= this.speed; break;
            case 'right': this.x += this.speed; break;
            case 'up': this.y -= this.speed; break;
            case 'down': this.y += this.speed; break;
            case 'fire':
                var missile = createEntity('missile', {});
                missile.x = this.x + this.img.width / 2 - missile.img.width / 2;
                missile.y = this.y - missile.img.height;
                missile.vy = -MISSILE_SPEED;
                break;

        }
    }

    createEntity('ufo', {x:0, y:20, vx:1, vy:0.1})
    createEntity('ufo', {x:120, y:80, vx:1.1, vy:0})
    createEntity('ufo', {x:40, y:130, vx:1.05, vy:0})

    setInterval(gameLoop, 1000/60);
};

function checkCollisions() {
    function isIntersection(a, b) {
        var aWidth = a.img.width, aHeight = a.img.height,
            bWidth = b.img.width, bHeight = b.img.height;
        var minX = Math.min(a.x, b.x);
        var minY = Math.min(a.y, b.y);

        var maxX = Math.max(a.x + aWidth, b.x + bWidth);
        var maxY = Math.max(a.y + aHeight, b.y + bHeight);

        return (maxX - minX) < (aWidth + bWidth) &&
               (maxY - minY) < (aHeight + bHeight);

    }

    var count = entities.length;
    for (i = 0; i < count - 1; i++) {
        for (j = i + 1; j < count; j++) {
            if (isIntersection(entities[i], entities[j])) {
                if (entities[i].type == 'missile' || entities[j].type == 'missile') {
                    entities[i].dead = true; entities[j].dead = true;
                }

            }
        }
    }

}

function gameLoop() {
    ctx.clearRect(0,0,canvas.width, canvas.height);

    checkCollisions();

    entities.forEach(function (entity) {
        entity.move();
    });

    entities = entities.filter(function (entity) {
            return !entity.dead;
    });

    entities.forEach(function (entity) {
        entity.draw(ctx);
    });
}

function initCanvas() {
    canvas = document.getElementById('canvas');
    ctx = canvas.getContext('2d');
};

$(document).ready(function() {
    loadImages('images', ['player.png', 'ufo.png', 'missile.png'], initialize);
    $(document).keydown(function(e) {
        var key = {37: 'left', 38: 'up', 39:'right', 40:'down', 32:'fire'}[e.keyCode];
        player.input(key)
    })
});
<|endoftext|>


<commit_before>const {
  compose,
  filter,
  ident,
  flatten,
  zip
} = require("lodash/fp");

const { sequence, BaseSequence } = require("./sequence");
const Renderer = require("./renderer");

const zipTemplateSegments = compose(
  filter(ident),
  flatten,
  zip
);

function getSequenceEvent (segment) {
  const segmentType = typeof segment;

  if (segmentType === "string") { return segment; }
  if (segmentType === "function") { return segment(); }
  if (segment instanceof BaseSequence) { return segment; }
  if (segment instanceof Renderer) { return segment.sequence; }

  throw new Error("Unknown value in stream template.", segment);
}

function template (strings, ...values) {
  const seq = sequence();
  const templateSegments = zipTemplateSegments(strings, values);
  templateSegments.forEach(segment => seq.emit(() => getSequenceEvent(segment)));
  return new Renderer(null, seq);
}

module.exports = template;
<commit_msg>Better variable name.<commit_after>const {
  compose,
  filter,
  ident,
  flatten,
  zip
} = require("lodash/fp");

const { sequence, BaseSequence } = require("./sequence");
const Renderer = require("./renderer");

const interlaceTemplateSegments = compose(
  filter(ident),
  flatten,
  zip
);

function getSequenceEvent (segment) {
  const segmentType = typeof segment;

  if (segmentType === "string") { return segment; }
  if (segmentType === "function") { return segment(); }
  if (segment instanceof BaseSequence) { return segment; }
  if (segment instanceof Renderer) { return segment.sequence; }

  throw new Error("Unknown value in stream template.", segment);
}

function template (strings, ...values) {
  const seq = sequence();
  const templateSegments = interlaceTemplateSegments(strings, values);
  templateSegments.forEach(segment => seq.emit(() => getSequenceEvent(segment)));
  return new Renderer(null, seq);
}

module.exports = template;
<|endoftext|>


<commit_before>import themeDarkSvg from 'design-system/assets/img/pm-images/theme-dark.svg';
import themeLightSvg from 'design-system/assets/img/pm-images/theme-light.svg';
import themeBlueSvg from 'design-system/assets/img/pm-images/theme-blue.svg';
import themeTestSvg from 'design-system/assets/img/pm-images/theme-test.svg';
import lightTheme from 'design-system/_sass/pm-styles/_pm-light-theme.scss';
import blueTheme from 'design-system/_sass/pm-styles/_pm-blue-theme.scss';
import { c } from 'ttag';

export const DEFAULT_THEME = {
    getI18NLabel() {
        return c('Theme').t`Dark (Default)`;
    },
    identifier: '/* default-theme */',
    src: themeDarkSvg,
    theme: '',
    customizable: false
};

export const CUSTOM_THEME = {
    getI18NLabel() {
        return c('Theme').t`Custom theme`;
    },
    identifier: '/* custom-theme */',
    src: themeTestSvg,
    customizable: true
};

export const PROTON_THEMES = {
    LIGHT: {
        getI18NLabel() {
            return c('Theme').t`Light`;
        },
        identifier: '/* light-theme */',
        src: themeLightSvg,
        theme: lightTheme,
        customizable: false
    },
    BLUE: {
        getI18NLabel() {
            return c('Theme').t`Blue`;
        },
        identifier: '/* blue-theme */',
        src: themeBlueSvg,
        theme: blueTheme,
        customizable: false
    }
};
<commit_msg>change name of dark theme (#62)<commit_after>import themeDarkSvg from 'design-system/assets/img/pm-images/theme-dark.svg';
import themeLightSvg from 'design-system/assets/img/pm-images/theme-light.svg';
import themeBlueSvg from 'design-system/assets/img/pm-images/theme-blue.svg';
import themeTestSvg from 'design-system/assets/img/pm-images/theme-test.svg';
import lightTheme from 'design-system/_sass/pm-styles/_pm-light-theme.scss';
import blueTheme from 'design-system/_sass/pm-styles/_pm-blue-theme.scss';
import { c } from 'ttag';

export const DEFAULT_THEME = {
    getI18NLabel() {
        return c('Theme').t`Default`;
    },
    identifier: '/* default-theme */',
    src: themeDarkSvg,
    theme: '',
    customizable: false
};

export const CUSTOM_THEME = {
    getI18NLabel() {
        return c('Theme').t`Custom theme`;
    },
    identifier: '/* custom-theme */',
    src: themeTestSvg,
    customizable: true
};

export const PROTON_THEMES = {
    LIGHT: {
        getI18NLabel() {
            return c('Theme').t`Light`;
        },
        identifier: '/* light-theme */',
        src: themeLightSvg,
        theme: lightTheme,
        customizable: false
    },
    BLUE: {
        getI18NLabel() {
            return c('Theme').t`Blue`;
        },
        identifier: '/* blue-theme */',
        src: themeBlueSvg,
        theme: blueTheme,
        customizable: false
    }
};
<|endoftext|>


<commit_before>const rollup = require('rollup'),
      json = require('@rollup/plugin-json'),
      nodeResolve = require('rollup-plugin-node-resolve'),
      esmodule = hasArgument('-m'),
      externals = esmodule || hasArgument('-e'),
      output = `vega${esmodule ? '-module' : externals ? '-core' : ''}.js`;

function hasArgument(_) {
  return process.argv.slice(2).some(a => a === _);
}

const external = [].concat(!externals ? [] : [
  // 'd3-array', // we use d3-array v2, not yet part of D3 v5
  'd3-color',
  'd3-contour',
  'd3-dispatch',
  'd3-dsv',
  'd3-force',
  'd3-format',
  'd3-geo',
  'd3-hierarchy',
  'd3-interpolate',
  'd3-path',
  // 'd3-scale', // we use d3-scale v3, not yet part of D3 v5
  'd3-shape',
  'd3-time',
  'd3-time-format',
  'd3-timer',
  // 'd3-delaunay', // not part of D3 v5
  'topojson-client'
]);

const options = {
  file: 'build/' + output,
  format: 'es'
};

if (!esmodule) Object.assign(options, {
  format: 'umd',
  name: 'vega',
  globals: external.reduce(function(map, _) {
    map[_] = _.split('-')[0]; // map package name to prefix
    return map;
  }, {})
});

rollup.rollup({
  input: 'index.js',
  external: external,
  plugins: [
    nodeResolve({browser: true}),
    json()
  ],
  onwarn: function(warning) {
    // suppress circular dependency warnings
    if (warning.code !== 'CIRCULAR_DEPENDENCY') {
      // eslint-disable-next-line
      console.warn(warning.code, warning.message);
    }
  }
}).then(function(bundle) {
  return bundle.write(options);
}).then(function() {
  // eslint-disable-next-line
  console.warn('↳ build/' + output);
}).catch(abort);

function abort(error) {
  // eslint-disable-next-line
  console.error(error.stack);
}
<commit_msg>Update build script, remove d3-contour.<commit_after>const rollup = require('rollup'),
      json = require('@rollup/plugin-json'),
      nodeResolve = require('rollup-plugin-node-resolve'),
      esmodule = hasArgument('-m'),
      externals = esmodule || hasArgument('-e'),
      output = `vega${esmodule ? '-module' : externals ? '-core' : ''}.js`;

function hasArgument(_) {
  return process.argv.slice(2).some(a => a === _);
}

const external = [].concat(!externals ? [] : [
  // 'd3-array', // we use d3-array v2, not part of D3 v5
  'd3-color',
  'd3-dispatch',
  'd3-dsv',
  'd3-force',
  'd3-format',
  'd3-geo',
  'd3-hierarchy',
  'd3-interpolate',
  'd3-path',
  // 'd3-scale', // we use d3-scale v3, not part of D3 v5
  'd3-shape',
  'd3-time',
  'd3-time-format',
  'd3-timer',
  // 'd3-delaunay', // not part of D3 v5
  'topojson-client'
]);

const options = {
  file: 'build/' + output,
  format: 'es'
};

if (!esmodule) Object.assign(options, {
  format: 'umd',
  name: 'vega',
  globals: external.reduce(function(map, _) {
    map[_] = _.split('-')[0]; // map package name to prefix
    return map;
  }, {})
});

rollup.rollup({
  input: 'index.js',
  external: external,
  plugins: [
    nodeResolve({browser: true}),
    json()
  ],
  onwarn: function(warning) {
    // suppress circular dependency warnings
    if (warning.code !== 'CIRCULAR_DEPENDENCY') {
      // eslint-disable-next-line
      console.warn(warning.code, warning.message);
    }
  }
}).then(function(bundle) {
  return bundle.write(options);
}).then(function() {
  // eslint-disable-next-line
  console.warn('↳ build/' + output);
}).catch(abort);

function abort(error) {
  // eslint-disable-next-line
  console.error(error.stack);
}
<|endoftext|>


<commit_before>
frappe.ui.EnergyPointsNotifications = class {

    constructor() {
        this.$dropdown = $('.navbar').find('.dropdown-energy-points');
        this.$dropdown_list = this.$dropdown.find('.recent-points-list');
        this.$notification_indicator = this.$dropdown.find('.energy-points-notification');
        this.max_length = 20;
        this.setup_energy_points_notifications();
    }

    setup_energy_points_notifications() {
        this.get_energy_points_list(this.max_length).then(user_points_list=> {
            this.dropdown_items = user_points_list;
            this.render_energy_points_dropdown();
            if(this.$dropdown_list.find('.unseen').length) {
                this.$notification_indicator.show();
            }
        });

        this.bind_events();
    }

    bind_events() {
        frappe.realtime.on('energy_points_notification', () => {
            this.$dropdown.find('.energy-points-notification').show();
            this.update_dropdown();
		});

        this.$dropdown.on('hide.bs.dropdown',()=> {
            this.$notification_indicator.hide();
            this.$dropdown_list.find('.unseen').removeClass('unseen');
        });

        this.$dropdown.on('show.bs.dropdown',()=> {
            this.check_seen();
        });
    }

    update_dropdown() {
        this.get_energy_points_list(1).then(r=> {
            let new_item = r[0];
            this.dropdown_items.unshift(new_item);
            if(this.dropdown_items.length > this.max_length) {
                this.$dropdown_list.find('.recent-points-item').last().remove();
                this.dropdown_items.pop();
            }
            let new_item_html = this.get_dropdown_item_html(new_item);
            $(new_item_html).insertAfter(this.$dropdown_list.find('.points-date-range').eq(0));
        });
    }

    check_seen() {
        this.dropdown_items.forEach(item=> {
            if(item.seen === 0) {
                frappe.xcall('frappe.social.doctype.energy_point_log.energy_point_log.set_notification_as_seen', {field: item});
                item.seen = 1;
            }
        });
    }

    get_energy_points_date_range(date) {
        let current_date = frappe.datetime.now_date();
        let prev_week = frappe.datetime.add_days(current_date, -7);
        let prev_month = frappe.datetime.add_months(frappe.datetime.now_date(),-1);
        if(date >= current_date) {
            return 'Today';
        } else if(date > prev_week) {
            return 'Last 7 days';
        } else if(date > prev_month) {
            return 'Last 30 days';
        } else  {
            return 'Older';
        }
    }

    get_energy_points_list(limit) {
        return frappe.db.get_list('Energy Point Log',
            {filters: {user: frappe.session.user, type:['not in',['Review']]},
            fields:['name','user', 'points', 'reference_doctype', 'reference_name', 'reason', 'type', 'seen', 'rule', 'owner', 'creation'],
            limit:limit, order_by:'creation desc'}).then((energy_points_list)=> {
                return energy_points_list;
        });
    }

    render_energy_points_dropdown() {
        let header_html =
            `

                ${__('Energy Points')}
                ${__('Leaderboard')}

`;
        let body_html = '';

        if(this.dropdown_items.length) {
            let date_range= this.get_energy_points_date_range(this.dropdown_items[0].creation);
            body_html += `<li class="points-date-range text-muted">${__(date_range)}</li>`;
            this.dropdown_items.forEach(field=> {
                let current_field_date_range = this.get_energy_points_date_range(field.creation);
                if(date_range !== current_field_date_range) {
                    body_html+=`<li class="points-date-range text-muted">${__(current_field_date_range)}</li>`;
                    date_range=current_field_date_range;
                }
                let item_html = this.get_dropdown_item_html(field);
                if(item_html) body_html += item_html;
            });
        } else {
            body_html += `<li><a href="#" onclick = "return false" class="text-muted text-center">${__('No activity')}</a></li>`
        }

        let dropdown_html = header_html + body_html;
        this.$dropdown_list.html(dropdown_html);
    }

    get_dropdown_item_html(field) {
        let doc_link = frappe.utils.get_form_link(field.reference_doctype,field.reference_name);
        let link_html_string = field.seen? `<a href=${doc_link}>`: `<a href=${doc_link} class="unseen">`;
        let points_html= field.type === 'Auto' || field.type === 'Appreciation'
            ? `<div class="points-update positive-points">+${__(field.points)}</div>`
            : `<div class="points-update negative-points">${__(field.points)}</div>`;
        let message_html = this.get_message_html(field);

        let item_html = `

                            ${link_html_string}
                            ${points_html}

                                ${message_html}

`;
        return item_html;
    }

    get_message_html(field) {
        let owner_name = frappe.user.full_name(field.owner).trim();
        owner_name = this.truncate_value(owner_name);
        let message_html = '';
        if(field.type === 'Auto' ) {
            message_html = `For ${__(field.rule)} <span class="points-reason-name text-muted">${__(field.reference_name)}</span>`;
        } else {
            let message;
            if(field.type === 'Appreciation') {
                message = `${__(owner_name)} appreciated your work on `;
            } else if(field.type === 'Criticism') {
                message =  `${__(owner_name)} criticized your work on `
            } else if(field.type === 'Revert') {
                message =  `${__(owner_name)} reverted your points on `;
            }
            let reason_string = '- "' + this.truncate_value(field.reason) + '"';
            message_html = `${message}${__(field.reference_name)}
                ${__(reason_string)} `;
        }
        return message_html;
    }

    truncate_value(str) {
        if(str.length > 50) str = str.slice(0,50) + '...';
        return str;
    }
}<commit_msg>fix: spaces to tabs<commit_after>
frappe.ui.EnergyPointsNotifications = class {

	constructor() {
		this.$dropdown = $('.navbar').find('.dropdown-energy-points');
		this.$dropdown_list = this.$dropdown.find('.recent-points-list');
		this.$notification_indicator = this.$dropdown.find('.energy-points-notification');
		this.max_length = 20;
		this.setup_energy_points_notifications();
	}

	setup_energy_points_notifications() {
		this.get_energy_points_list(this.max_length).then(user_points_list=> {
			this.dropdown_items = user_points_list;
			this.render_energy_points_dropdown();
			if(this.$dropdown_list.find('.unseen').length) {
				this.$notification_indicator.show();
			}
		});

		this.bind_events();
	}

	bind_events() {
		frappe.realtime.on('energy_points_notification', () => {
			this.$dropdown.find('.energy-points-notification').show();
			this.update_dropdown();
		});

		this.$dropdown.on('hide.bs.dropdown',()=> {
			this.$notification_indicator.hide();
			this.$dropdown_list.find('.unseen').removeClass('unseen');
		});

		this.$dropdown.on('show.bs.dropdown',()=> {
			this.check_seen();
		});
	}

	update_dropdown() {
		this.get_energy_points_list(1).then(r=> {
			let new_item = r[0];
			this.dropdown_items.unshift(new_item);
			if(this.dropdown_items.length > this.max_length) {
				this.$dropdown_list.find('.recent-points-item').last().remove();
				this.dropdown_items.pop();
			}
			let new_item_html = this.get_dropdown_item_html(new_item);
			$(new_item_html).insertAfter(this.$dropdown_list.find('.points-date-range').eq(0));
		});
	}

	check_seen() {
		this.dropdown_items.forEach(item=> {
			if(item.seen === 0) {
				frappe.xcall('frappe.social.doctype.energy_point_log.energy_point_log.set_notification_as_seen', {field: item});
				item.seen = 1;
			}
		});
	}

	get_energy_points_date_range(date) {
		let current_date = frappe.datetime.now_date();
		let prev_week = frappe.datetime.add_days(current_date, -7);
		let prev_month = frappe.datetime.add_months(frappe.datetime.now_date(),-1);
		if(date >= current_date) {
			return 'Today';
		} else if(date > prev_week) {
			return 'Last 7 days';
		} else if(date > prev_month) {
			return 'Last 30 days';
		} else  {
			return 'Older';
		}
	}

	get_energy_points_list(limit) {
		return frappe.db.get_list('Energy Point Log',
			{filters: {user: frappe.session.user, type:['not in',['Review']]},
			fields:['name','user', 'points', 'reference_doctype', 'reference_name', 'reason', 'type', 'seen', 'rule', 'owner', 'creation'],
			limit:limit, order_by:'creation desc'}).then((energy_points_list)=> {
				return energy_points_list;
		});
	}

	render_energy_points_dropdown() {
		let header_html =
			`

				${__('Energy Points')}
				${__('Leaderboard')}

`;
		let body_html = '';

		if(this.dropdown_items.length) {
			let date_range= this.get_energy_points_date_range(this.dropdown_items[0].creation);
			body_html += `<li class="points-date-range text-muted">${__(date_range)}</li>`;
			this.dropdown_items.forEach(field=> {
				let current_field_date_range = this.get_energy_points_date_range(field.creation);
				if(date_range !== current_field_date_range) {
					body_html+=`<li class="points-date-range text-muted">${__(current_field_date_range)}</li>`;
					date_range=current_field_date_range;
				}
				let item_html = this.get_dropdown_item_html(field);
				if(item_html) body_html += item_html;
			});
		} else {
			body_html += `<li><a href="#" onclick = "return false" class="text-muted text-center">${__('No activity')}</a></li>`
		}

		let dropdown_html = header_html + body_html;
		this.$dropdown_list.html(dropdown_html);
	}

	get_dropdown_item_html(field) {
		let doc_link = frappe.utils.get_form_link(field.reference_doctype,field.reference_name);
		let link_html_string = field.seen? `<a href=${doc_link}>`: `<a href=${doc_link} class="unseen">`;
		let points_html= field.type === 'Auto' || field.type === 'Appreciation'
			? `<div class="points-update positive-points">+${__(field.points)}</div>`
			: `<div class="points-update negative-points">${__(field.points)}</div>`;
		let message_html = this.get_message_html(field);

		let item_html = `

							${link_html_string}
							${points_html}

								${message_html}

`;
		return item_html;
	}

	get_message_html(field) {
		let owner_name = frappe.user.full_name(field.owner).trim();
		owner_name = this.truncate_value(owner_name);
		let message_html = '';
		if(field.type === 'Auto' ) {
			message_html = `For ${__(field.rule)} <span class="points-reason-name text-muted">${__(field.reference_name)}</span>`;
		} else {
			let message;
			if(field.type === 'Appreciation') {
				message = `${__(owner_name)} appreciated your work on `;
			} else if(field.type === 'Criticism') {
				message =  `${__(owner_name)} criticized your work on `
			} else if(field.type === 'Revert') {
				message =  `${__(owner_name)} reverted your points on `;
			}
			let reason_string = '- "' + this.truncate_value(field.reason) + '"';
			message_html = `${message}${__(field.reference_name)}
				${__(reason_string)} `;
		}
		return message_html;
	}

	truncate_value(str) {
		if(str.length > 50) str = str.slice(0,50) + '...';
		return str;
	}
}<|endoftext|>


<commit_before>"use strict";

const RequestResults = require("../constants/RequestResults");
const Utils = require("../utils/Utils");

let _requester = null;

module.exports = {

    initialize: function(requester) {
        Utils.assertValidRequester(requester);
        _requester = requester;
    },

    getUserToken: function(username, password, callback) {
        const URL = _requester.getFullEndpoint("/tokens/user");
        const req = _requester.getRequest(URL);
        const authStr = "Basic " +
            new Buffer(username + ":" + password).toString("base64");
        req.set("Authorization", authStr);

        const innerCb = (status, webResp) => {
            if (status == RequestResults.PENDING) {
                return;
            } else if (!Utils.isCallback(callback)) {
                return;
            }

            const resp = Utils.getDefaultApiResp(status, webResp);
            if (!resp.timeout) {
                const body = webResp.body;
                if (status === RequestResults.SUCCESS) {
                    resp.body = body;
                } else if (status === RequestResults.FAILURE) {
                    resp.error = body.errors[0].message;
                }
            }
            callback(resp);
        }
        _requester.execute(req, innerCb);
    }

};
<commit_msg>endpoints/Tokens: support for getting project token<commit_after>"use strict";

const ApiException = require("../exceptions/ApiException");
const RequestResults = require("../constants/RequestResults");
const Utils = require("../utils/Utils");

let _requester = null;

function assertValidPermissions(perms) {
    if (perms === null || typeof(perms) !== "object") {
        throw new ApiException("permissions must be an object");
    }
}

module.exports = {

    initialize: function(requester) {
        Utils.assertValidRequester(requester);
        _requester = requester;
    },

    getUserToken: function(username, password, callback) {
        const URL = _requester.getFullEndpoint("/tokens/user");
        const req = _requester.getRequest(URL);
        const authStr = "Basic " +
            new Buffer(username + ":" + password).toString("base64");
        req.set("Authorization", authStr);

        const innerCb = (status, webResp) => {
            if (status == RequestResults.PENDING) {
                return;
            } else if (!Utils.isCallback(callback)) {
                return;
            }

            const resp = Utils.getDefaultApiResp(status, webResp);
            if (!resp.timeout) {
                const body = webResp.body;
                if (status === RequestResults.SUCCESS) {
                    resp.body = body;
                } else if (status === RequestResults.FAILURE) {
                    resp.error = body.errors[0].message;
                }
            }
            callback(resp);
        }
        _requester.execute(req, innerCb);
    },

    getProjectToken: function(projectId, permissions, userToken, callback) {
        Utils.assertValidProjectId(projectId);
        Utils.assertValidToken(userToken);
        assertValidPermissions(permissions);

        const URL = _requester.getFullEndpoint("/tokens/project");
        const req = _requester.getRequest(URL, userToken);

        const readPerm = permissions.read || false;
        const writePerm = permissions.write || false;
        const adminPerm = permissions.admin || false;
        req.query({read: readPerm, write: writePerm, admin: adminPerm})
            .query({project_id: projectId})
            .query({include_user: false});

        const innerCb = (status, webResp) => {
            if (status == RequestResults.PENDING) {
                return;
            } else if (!Utils.isCallback(callback)) {
                return;
            }

            const resp = Utils.getDefaultApiResp(status, webResp);
            if (!resp.timeout) {
                const body = webResp.body;
                if (status === RequestResults.SUCCESS) {
                    resp.body = body;
                } else if (status === RequestResults.FAILURE) {
                    resp.error = body.errors[0].message;
                }
            }
            callback(resp);
        }
        _requester.execute(req, innerCb);
    }

};
<|endoftext|>


<commit_before>var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var Objectid = mongoose.Schema.Types.ObjectId;

var ProductTypeSchema   = new Schema({
	name: { type: String, required: true, index: true },
	fire_action: String,
	_owner_id: Objectid,
	_deleted: { type: Boolean, default: false, index: true },
}, {
	timestamps: true
});

ProductTypeSchema.set("_perms", {
	admin: "crud",
	owner: "r",
	user: "r",
	all: "r"
});

ProductTypeSchema.index( { "$**": "text" } );

module.exports = mongoose.model('ProductType', ProductTypeSchema);
<commit_msg>price_recommendation_formula<commit_after>var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var Objectid = mongoose.Schema.Types.ObjectId;

var ProductTypeSchema   = new Schema({
	name: { type: String, required: true, index: true },
	fire_action: String,
	price_recommendation_formula: String,
	_owner_id: Objectid,
	_deleted: { type: Boolean, default: false, index: true },
}, {
	timestamps: true
});

ProductTypeSchema.set("_perms", {
	admin: "crud",
	owner: "r",
	user: "r",
	all: "r"
});

module.exports = mongoose.model('ProductType', ProductTypeSchema);
<|endoftext|>


<commit_before>/*
 * Lazy Load - jQuery plugin for lazy loading images
 *
 * Copyright (c) 2007-2012 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   http://www.appelsiini.net/projects/lazyload
 *
 * Version:  1.8.1
 *
 */
(function($, window) {
    var $window = $(window);

    $.fn.lazyload = function(options) {
        var elements = this;
        var $container;
        var settings = {
            threshold       : 0,
            failure_limit   : 0,
            event           : "scroll",
            effect          : "show",
            container       : window,
            data_attribute  : "original",
            skip_invisible  : true,
            appear          : null,
            load            : null
        };

        function update() {
            var counter = 0;

            elements.each(function() {
                var $this = $(this);
                if (settings.skip_invisible && !$this.is(":visible")) {
                    return;
                }
                if ($.abovethetop(this, settings) ||
                    $.leftofbegin(this, settings)) {
                        /* Nothing. */
                } else if (!$.belowthefold(this, settings) &&
                    !$.rightoffold(this, settings)) {
                        $this.trigger("appear");
                        /* if we found an image we'll load, reset the counter */
                        counter = 0;
                } else {
                    if (++counter > settings.failure_limit) {
                        return false;
                    }
                }
            });

        }

        if(options) {
            /* Maintain BC for a couple of versions. */
            if (undefined !== options.failurelimit) {
                options.failure_limit = options.failurelimit;
                delete options.failurelimit;
            }
            if (undefined !== options.effectspeed) {
                options.effect_speed = options.effectspeed;
                delete options.effectspeed;
            }

            $.extend(settings, options);
        }

        /* Cache container as jQuery as object. */
        $container = (settings.container === undefined ||
                      settings.container === window) ? $window : $(settings.container);

        /* Fire one scroll event per scroll. Not one scroll event per image. */
        if (0 === settings.event.indexOf("scroll")) {
            $container.bind(settings.event, function(event) {
                return update();
            });
        }

        this.each(function() {
            var self = this;
            var $self = $(self);

            self.loaded = false;

            /* When appear is triggered load original image. */
            $self.one("appear", function() {
                if (!this.loaded) {
                    if (settings.appear) {
                        var elements_left = elements.length;
                        settings.appear.call(self, elements_left, settings);
                    }
                    $("<img />")
                        .bind("load", function() {
                            $self
                                .hide()
                                .attr("src", $self.data(settings.data_attribute))
                                [settings.effect](settings.effect_speed);
                            self.loaded = true;

                            /* Remove image from array so it is not looped next time. */
                            var temp = $.grep(elements, function(element) {
                                return !element.loaded;
                            });
                            elements = $(temp);

                            if (settings.load) {
                                var elements_left = elements.length;
                                settings.load.call(self, elements_left, settings);
                            }
                        })
                        .attr("src", $self.data(settings.data_attribute));
                }
            });

            /* When wanted event is triggered load original image */
            /* by triggering appear.                              */
            if (0 !== settings.event.indexOf("scroll")) {
                $self.bind(settings.event, function(event) {
                    if (!self.loaded) {
                        $self.trigger("appear");
                    }
                });
            }
        });

        /* Check if something appears when window is resized. */
        $window.bind("resize", function(event) {
            update();
        });

        /* Force initial check if images should appear. */
        $(document).ready(function() {
            update();
        });

        return this;
    };

    /* Convenience methods in jQuery namespace.           */
    /* Use as  $.belowthefold(element, {threshold : 100, container : window}) */

    $.belowthefold = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = $window.height() + $window.scrollTop();
        } else {
            fold = $(settings.container).offset().top + $(settings.container).height();
        }

        return fold <= $(element).offset().top - settings.threshold;
    };

    $.rightoffold = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = $window.width() + $window.scrollLeft();
        } else {
            fold = $(settings.container).offset().left + $(settings.container).width();
        }

        return fold <= $(element).offset().left - settings.threshold;
    };

    $.abovethetop = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = $window.scrollTop();
        } else {
            fold = $(settings.container).offset().top;
        }

        return fold >= $(element).offset().top + settings.threshold  + $(element).height();
    };

    $.leftofbegin = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = $window.scrollLeft();
        } else {
            fold = $(settings.container).offset().left;
        }

        return fold >= $(element).offset().left + settings.threshold + $(element).width();
    };

    $.inviewport = function(element, settings) {
         return !$.rightoffold(element, settings) && !$.leftofbegin(element, settings) &&
                !$.belowthefold(element, settings) && !$.abovethetop(element, settings);
     };

    /* Custom selectors for your convenience.   */
    /* Use as $("img:below-the-fold").something() or */
    /* $("img").filter(":below-the-fold").something() which is faster */

    $.extend($.expr[':'], {
        "below-the-fold" : function(a) { return $.belowthefold(a, {threshold : 0}); },
        "above-the-top"  : function(a) { return !$.belowthefold(a, {threshold : 0}); },
        "right-of-screen": function(a) { return $.rightoffold(a, {threshold : 0}); },
        "left-of-screen" : function(a) { return !$.rightoffold(a, {threshold : 0}); },
        "in-viewport"    : function(a) { return $.inviewport(a, {threshold : 0}); },
        /* Maintain BC for couple of versions. */
        "above-the-fold" : function(a) { return !$.belowthefold(a, {threshold : 0}); },
        "right-of-fold"  : function(a) { return $.rightoffold(a, {threshold : 0}); },
        "left-of-fold"   : function(a) { return !$.rightoffold(a, {threshold : 0}); }
    });

})(jQuery, window);<commit_msg>removes lazyload.js<commit_after><|endoftext|>