<commit_before>/**
 * Copyright 2013-2019 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * 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.
 */
const chalk = require('chalk');
const _ = require('lodash');
const needleClientBase = require('./needle-client');
const constants = require('../../generator-constants');
const jhipsterUtils = require('../../utils');

const CLIENT_MAIN_SRC_DIR = constants.CLIENT_MAIN_SRC_DIR;

module.exports = class extends needleClientBase {
    addGlobalSCSSStyle(style, comment) {
        const filePath = `${CLIENT_MAIN_SRC_DIR}content/scss/global.scss`;
        this.addStyle(style, comment, filePath, 'jhipster-needle-scss-add-main');
    }

    addVendorSCSSStyle(style, comment) {
        const filePath = `${CLIENT_MAIN_SRC_DIR}content/scss/vendor.scss`;
        super.addStyle(style, comment, filePath, 'jhipster-needle-scss-add-vendor');
    }

    addModule(appName, angularName, folderName, fileName, enableTranslation, clientFramework) {
        const modulePath = `${CLIENT_MAIN_SRC_DIR}app/app.module.ts`;
        const importNeedle = 'jhipster-needle-angular-add-module-import';
        const moduleNeedle = 'jhipster-needle-angular-add-module';

        this._genericAddModule(
            appName,
            angularName,
            folderName,
            fileName,
            enableTranslation,
            clientFramework,
            modulePath,
            importNeedle,
            moduleNeedle
        );
    }

    addToAdminModule(appName, adminAngularName, adminFolderName, adminFileName, enableTranslation, clientFramework) {
        const adminModulePath = `${CLIENT_MAIN_SRC_DIR}app/admin/admin.module.ts`;
        const importNeedle = 'jhipster-needle-add-admin-module-import';
        const moduleNeedle = 'jhipster-needle-add-admin-module';

        this._genericAddModule(
            appName,
            adminAngularName,
            adminFolderName,
            adminFileName,
            enableTranslation,
            clientFramework,
            adminModulePath,
            importNeedle,
            moduleNeedle
        );
    }

    _genericAddModule(
        appName,
        angularName,
        folderName,
        fileName,
        enableTranslation,
        clientFramework,
        modulePath,
        importNeedle,
        moduleNeedle
    ) {
        const errorMessage = `${chalk.yellow('Reference to ') +
            angularName +
            folderName +
            fileName +
            enableTranslation +
            clientFramework} ${chalk.yellow(`not added to ${modulePath}.\n`)}`;

        const importRewriteFileModel = this._generateRewriteFileModelWithImportStatement(
            appName,
            angularName,
            folderName,
            fileName,
            modulePath,
            importNeedle
        );
        this.addBlockContentToFile(importRewriteFileModel, errorMessage);

        const moduleRewriteFileModel = this._generateRewriteFileModelAddModule(appName, angularName, modulePath, moduleNeedle);
        this.addBlockContentToFile(moduleRewriteFileModel, errorMessage);
    }

    _generateRewriteFileModelWithImportStatement(appName, angularName, folderName, fileName, modulePath, needle) {
        const importStatement = this._generateImportStatement(appName, angularName, folderName, fileName);

        return this.generateFileModel(modulePath, needle, this.generator.stripMargin(importStatement));
    }

    _generateImportStatement(appName, angularName, folderName, fileName) {
        let importStatement = `|import { ${appName}${angularName}Module } from './${folderName}/${fileName}.module';`;
        if (importStatement.length > constants.LINE_LENGTH) {
            // prettier-ignore
            importStatement = `|import {
                        |    ${appName}${angularName}Module
                        |} from './${folderName}/${fileName}.module';`;
        }

        return importStatement;
    }

    _generateRewriteFileModelAddModule(appName, angularName, modulePath, needle) {
        return this.generateFileModel(modulePath, needle, this.generator.stripMargin(`|${appName}${angularName}Module,`));
    }

    addEntityToMenu(routerName, enableTranslation, entityTranslationKeyMenu) {
        const errorMessage = `${chalk.yellow('Reference to ') + routerName} ${chalk.yellow('not added to menu.\n')}`;
        const entityMenuPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
        const entityEntry =
            // prettier-ignore
            this.generator.stripMargin(`|

                             |
                             |                            <fa-icon icon="asterisk" fixedWidth="true"></fa-icon>
                             |                            <span${enableTranslation ? ` jhiTranslate="global.menu.entities.${entityTranslationKeyMenu}"` : ''}>${_.startCase(routerName)}
                             |
                             |
`);
        const rewriteFileModel = this.generateFileModel(entityMenuPath, 'jhipster-needle-add-entity-to-menu', entityEntry);

        this.addBlockContentToFile(rewriteFileModel, errorMessage);
    }

    addElementToMenu(routerName, glyphiconName, enableTranslation) {
        const errorMessage = `${chalk.yellow('Reference to ') + routerName} ${chalk.yellow('not added to menu.\n')}`;
        const entityMenuPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
        // prettier-ignore
        const entityEntry = `

                                    <fa-icon [icon]="'${glyphiconName}'" [fixedWidth]="true"></fa-icon>
                                    <span${enableTranslation ? ` jhiTranslate="global.menu.${routerName}"` : ''}>${_.startCase(routerName)}

`;
        const rewriteFileModel = this.generateFileModel(entityMenuPath, 'jhipster-needle-add-element-to-menu', entityEntry);

        this.addBlockContentToFile(rewriteFileModel, errorMessage);
    }

    addElementToAdminMenu(routerName, glyphiconName, enableTranslation) {
        const errorMessage = `${chalk.yellow('Reference to ') + routerName} ${chalk.yellow('not added to admin menu.\n')}`;
        const navbarAdminPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
        // prettier-ignore
        const entityEntry = `

                            <fa-icon [icon]="'${glyphiconName}'" [fixedWidth]="true"></fa-icon>
                            <span${enableTranslation ? ` jhiTranslate="global.menu.admin.${routerName}"` : ''}>${_.startCase(routerName)}

`;
        const rewriteFileModel = this.generateFileModel(navbarAdminPath, 'jhipster-needle-add-element-to-admin-menu', entityEntry);

        this.addBlockContentToFile(rewriteFileModel, errorMessage);
    }

    addEntityToModule(entityInstance, entityClass, entityAngularName, entityFolderName, entityFileName, entityUrl, microServiceName) {
        const entityModulePath = `${CLIENT_MAIN_SRC_DIR}app/entities/entity.module.ts`;
        const errorMessage = `${chalk.yellow('Reference to ') +
            entityInstance +
            entityClass +
            entityFolderName +
            entityFileName} ${chalk.yellow(`not added to ${entityModulePath}.\n`)}`;

        try {
            const isSpecificEntityAlreadyGenerated = jhipsterUtils.checkStringInFile(
                entityModulePath,
                `path: '${entityUrl}'`,
                this.generator
            );

            if (!isSpecificEntityAlreadyGenerated) {
                const appName = this.generator.getAngularXAppName();
                const isEntityAlreadyGenerated = jhipsterUtils.checkStringInFile(entityModulePath, 'loadChildren', this.generator);

                const modulePath = `./${entityFolderName}/${entityFileName}.module`;
                const moduleName = microServiceName
                    ? `${this.generator.upperFirstCamelCase(microServiceName)}${entityAngularName}Module`
                    : `${appName}${entityAngularName}Module`;

                const splicable = isEntityAlreadyGenerated
                    ? `|,{
                            |                path: '${entityUrl}',
                            |                loadChildren: '${modulePath}#${moduleName}'
                            |            }`
                    : `|{
                                |                path: '${entityUrl}',
                                |                loadChildren: '${modulePath}#${moduleName}'
                                |            }`;
                const rewriteFileModel = this.generateFileModel(
                    entityModulePath,
                    'jhipster-needle-add-entity-route',
                    this.generator.stripMargin(splicable)
                );

                this.addBlockContentToFile(rewriteFileModel, errorMessage);
            }
        } catch (e) {
            this.generator.debug('Error:', e);
        }
    }
};
<commit_msg>improve variable naming<commit_after>/**
 * Copyright 2013-2019 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * 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.
 */
const chalk = require('chalk');
const _ = require('lodash');
const needleClientBase = require('./needle-client');
const constants = require('../../generator-constants');
const jhipsterUtils = require('../../utils');

const CLIENT_MAIN_SRC_DIR = constants.CLIENT_MAIN_SRC_DIR;

module.exports = class extends needleClientBase {
    addGlobalSCSSStyle(style, comment) {
        const filePath = `${CLIENT_MAIN_SRC_DIR}content/scss/global.scss`;
        this.addStyle(style, comment, filePath, 'jhipster-needle-scss-add-main');
    }

    addVendorSCSSStyle(style, comment) {
        const filePath = `${CLIENT_MAIN_SRC_DIR}content/scss/vendor.scss`;
        super.addStyle(style, comment, filePath, 'jhipster-needle-scss-add-vendor');
    }

    addModule(appName, angularName, folderName, fileName, enableTranslation, clientFramework) {
        const modulePath = `${CLIENT_MAIN_SRC_DIR}app/app.module.ts`;
        const importNeedle = 'jhipster-needle-angular-add-module-import';
        const moduleNeedle = 'jhipster-needle-angular-add-module';

        this._genericAddModule(
            appName,
            angularName,
            folderName,
            fileName,
            enableTranslation,
            clientFramework,
            modulePath,
            importNeedle,
            moduleNeedle
        );
    }

    addToAdminModule(appName, adminAngularName, adminFolderName, adminFileName, enableTranslation, clientFramework) {
        const adminModulePath = `${CLIENT_MAIN_SRC_DIR}app/admin/admin.module.ts`;
        const importNeedle = 'jhipster-needle-add-admin-module-import';
        const moduleNeedle = 'jhipster-needle-add-admin-module';

        this._genericAddModule(
            appName,
            adminAngularName,
            adminFolderName,
            adminFileName,
            enableTranslation,
            clientFramework,
            adminModulePath,
            importNeedle,
            moduleNeedle
        );
    }

    _genericAddModule(
        appName,
        angularName,
        folderName,
        fileName,
        enableTranslation,
        clientFramework,
        modulePath,
        importNeedle,
        moduleNeedle
    ) {
        const errorMessage = `${chalk.yellow('Reference to ') +
            angularName +
            folderName +
            fileName +
            enableTranslation +
            clientFramework} ${chalk.yellow(`not added to ${modulePath}.\n`)}`;

        const importRewriteFileModel = this._generateRewriteFileModelWithImportStatement(
            appName,
            angularName,
            folderName,
            fileName,
            modulePath,
            importNeedle
        );
        this.addBlockContentToFile(importRewriteFileModel, errorMessage);

        const moduleRewriteFileModel = this._generateRewriteFileModelAddModule(appName, angularName, modulePath, moduleNeedle);
        this.addBlockContentToFile(moduleRewriteFileModel, errorMessage);
    }

    _generateRewriteFileModelWithImportStatement(appName, angularName, folderName, fileName, modulePath, needle) {
        const importStatement = this._generateImportStatement(appName, angularName, folderName, fileName);

        return this.generateFileModel(modulePath, needle, this.generator.stripMargin(importStatement));
    }

    _generateImportStatement(appName, angularName, folderName, fileName) {
        let importStatement = `|import { ${appName}${angularName}Module } from './${folderName}/${fileName}.module';`;
        if (importStatement.length > constants.LINE_LENGTH) {
            // prettier-ignore
            importStatement = `|import {
                        |    ${appName}${angularName}Module
                        |} from './${folderName}/${fileName}.module';`;
        }

        return importStatement;
    }

    _generateRewriteFileModelAddModule(appName, angularName, modulePath, needle) {
        return this.generateFileModel(modulePath, needle, this.generator.stripMargin(`|${appName}${angularName}Module,`));
    }

    addEntityToMenu(routerName, enableTranslation, entityTranslationKeyMenu) {
        const errorMessage = `${chalk.yellow('Reference to ') + routerName} ${chalk.yellow('not added to menu.\n')}`;
        const entityMenuPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
        const entityEntry =
            // prettier-ignore
            this.generator.stripMargin(`|

                             |
                             |                            <fa-icon icon="asterisk" fixedWidth="true"></fa-icon>
                             |                            <span${enableTranslation ? ` jhiTranslate="global.menu.entities.${entityTranslationKeyMenu}"` : ''}>${_.startCase(routerName)}
                             |
                             |
`);
        const rewriteFileModel = this.generateFileModel(entityMenuPath, 'jhipster-needle-add-entity-to-menu', entityEntry);

        this.addBlockContentToFile(rewriteFileModel, errorMessage);
    }

    addElementToMenu(routerName, glyphiconName, enableTranslation) {
        const errorMessage = `${chalk.yellow('Reference to ') + routerName} ${chalk.yellow('not added to menu.\n')}`;
        const entityMenuPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
        // prettier-ignore
        const entityEntry = `

                                    <fa-icon [icon]="'${glyphiconName}'" [fixedWidth]="true"></fa-icon>
                                    <span${enableTranslation ? ` jhiTranslate="global.menu.${routerName}"` : ''}>${_.startCase(routerName)}

`;
        const rewriteFileModel = this.generateFileModel(entityMenuPath, 'jhipster-needle-add-element-to-menu', entityEntry);

        this.addBlockContentToFile(rewriteFileModel, errorMessage);
    }

    addElementToAdminMenu(routerName, glyphiconName, enableTranslation) {
        const errorMessage = `${chalk.yellow('Reference to ') + routerName} ${chalk.yellow('not added to admin menu.\n')}`;
        const navbarAdminPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
        // prettier-ignore
        const entityEntry = `

                            <fa-icon [icon]="'${glyphiconName}'" [fixedWidth]="true"></fa-icon>
                            <span${enableTranslation ? ` jhiTranslate="global.menu.admin.${routerName}"` : ''}>${_.startCase(routerName)}

`;
        const rewriteFileModel = this.generateFileModel(navbarAdminPath, 'jhipster-needle-add-element-to-admin-menu', entityEntry);

        this.addBlockContentToFile(rewriteFileModel, errorMessage);
    }

    addEntityToModule(entityInstance, entityClass, entityAngularName, entityFolderName, entityFileName, entityUrl, microServiceName) {
        const entityModulePath = `${CLIENT_MAIN_SRC_DIR}app/entities/entity.module.ts`;
        const errorMessage = `${chalk.yellow('Reference to ') +
            entityInstance +
            entityClass +
            entityFolderName +
            entityFileName} ${chalk.yellow(`not added to ${entityModulePath}.\n`)}`;

        try {
            const isSpecificEntityAlreadyGenerated = jhipsterUtils.checkStringInFile(
                entityModulePath,
                `path: '${entityUrl}'`,
                this.generator
            );

            if (!isSpecificEntityAlreadyGenerated) {
                const appName = this.generator.getAngularXAppName();
                const isAnyEntityAlreadyGenerated = jhipsterUtils.checkStringInFile(
                    entityModulePath,
                    'loadChildren',
                    this.generator
                );

                const modulePath = `./${entityFolderName}/${entityFileName}.module`;
                const moduleName = microServiceName
                    ? `${this.generator.upperFirstCamelCase(microServiceName)}${entityAngularName}Module`
                    : `${appName}${entityAngularName}Module`;

                const splicable = isAnyEntityAlreadyGenerated
                    ? `|,{
                            |                path: '${entityUrl}',
                            |                loadChildren: '${modulePath}#${moduleName}'
                            |            }`
                    : `|{
                                |                path: '${entityUrl}',
                                |                loadChildren: '${modulePath}#${moduleName}'
                                |            }`;
                const rewriteFileModel = this.generateFileModel(
                    entityModulePath,
                    'jhipster-needle-add-entity-route',
                    this.generator.stripMargin(splicable)
                );

                this.addBlockContentToFile(rewriteFileModel, errorMessage);
            }
        } catch (e) {
            this.generator.debug('Error:', e);
        }
    }
};
<|endoftext|>


<commit_before><commit_msg>this shouldn't have been added<commit_after><|endoftext|>


<commit_before>/* See license.txt for terms of usage */

var FBTestFireCookie = FBTest.FireCookie =
{
// ************************************************************************************************
// Firecookie specific APIs

enableCookiePanel: function(callback)
{
    FBTestFirebug.updateModelPermission(FW.Firebug.FireCookieModel, callback, "enable");
}

// ************************************************************************************************
};
<commit_msg>New API for FBTest.FireCookie namespace.<commit_after>/* See license.txt for terms of usage */

var FBTestFireCookie = FBTest.FireCookie =
{
// ************************************************************************************************
// Firecookie specific APIs

enableCookiePanel: function(callback)
{
    FBTestFirebug.updateModelPermission(FW.Firebug.FireCookieModel, callback, "enable");
},

getCookieRowByName: function(panelNode, cookieName)
{
    var cookieRows = FW.FBL.getElementsByClass(panelNode, "cookieRow");
    for (var i=0; i<cookieRows.length; i++)
    {
        var row = cookieRows[i];
        var label = FW.FBL.getElementsByClass(row, "cookieNameLabel");
        if (label.length != 1)
            return null;

        if (label[0].textContent == cookieName)
            return row;
    }
    return null;
},

getCookieByName: function(panelNode, cookieName)
{
    var row = this.getCookieRowByName(panelNode, cookieName);
    return row ? row.repObject : null;
},

// ************************************************************************************************
};
<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 *
*/

module.exports = {
    id: 'browser',
    cordovaVersion: '4.2.0', // cordova-js

    bootstrap: function() {

        var modulemapper = require('cordova/modulemapper');
        var channel = require('cordova/channel');

        modulemapper.clobbers('cordova/exec/proxy', 'cordova.commandProxy');

        channel.onNativeReady.fire();

        document.addEventListener("visibilitychange", function(){
            if(document.hidden) {
                channel.onPause.fire();
            }
            else {
                channel.onResume.fire();
            }
        });

    // End of bootstrap
    }
};
<commit_msg>Register service worker if no one else does<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 *
*/

module.exports = {
    id: 'browser',
    cordovaVersion: '4.2.0', // cordova-js

    bootstrap: function() {

        var cache = navigator.serviceWorker.register;
        var cacheCalled = false;
        navigator.serviceWorker.register = function() {
            cacheCalled = true;
            navigator.serviceWorker.register = cache;
            return cache.apply(navigator.serviceWorker,arguments);
        }

        document.addEventListener('deviceready',function(){
            if(!cacheCalled) {
                navigator.serviceWorker.register('/cordova-sw.js').then(function(registration) {
                    // Registration was successful
                    console.log('ServiceWorker registration successful with scope: ', registration.scope);
                }, function(err) {
                    // registration failed :(
                    console.log('ServiceWorker registration failed: ', err);
                });
            }
        });

        var modulemapper = require('cordova/modulemapper');
        var channel = require('cordova/channel');

        modulemapper.clobbers('cordova/exec/proxy', 'cordova.commandProxy');

        channel.onNativeReady.fire();

        document.addEventListener("visibilitychange", function(){
            if(document.hidden) {
                channel.onPause.fire();
            }
            else {
                channel.onResume.fire();
            }
        });

    // End of bootstrap
    }
};
<|endoftext|>


<commit_before>var config = require(__dirname + '/../config.js');
var utils  = require(__dirname + '/../utils.js');
var md5 = require('md5');

/* table: connectors
   cid   mid   type  name
   1 	   1 	   1 	   Poloniex
	2 	   1 	   2 	   Poloniex Margin
	3 	   2 	   3 	   OKCoin Contracts BTC Quarterly
	4 	   2 	   3 	   OKCoin Contracts LTC Quarterly
	5 	   5 	   1 	   1broker
	6 	   1 	   5 	   NXT Wallet
	7 	   1 	   6 	   Poloniex Loan
	8 	   1 	   5 	   wallet.counterwallet.io
	9 	   2 	   1 	   OKCoin
*/

var markets = {
   // ----------------
   // Poloniex.com (all rates)
   // ----------------
   'poloniex': {
      url:  function() { return {url:'https://poloniex.com/public?command=returnTicker'}; },
      fData: function(data){return data},
      keys: {
         internId: 'id'
      },
      values: {
         mid: 1,
         cid: 1
      }
   },
   // ----------------
   // Bitstamp.net (BTC_USD)
   // ----------------
   // {"high": "1425.00", "last": "1419.99", "timestamp": "1493660529", "bid": "1418.01",
   // "vwap": "1370.34", "volume": "7604.50280261", "low": "1325.35", "ask": "1419.99", "open": "1348.88"}
   'bitstamp': {
      url: function() { return {url:'https://www.bitstamp.net/api/v2/ticker_hour/btcusd/'}; },
      fData: function(data) {return {'BTC_USD':data}},
      keys:  {
         lowestAsk: 'ask',
         highestBid: 'bid',
         baseVolume: 'volume',
         quoteVolume: 'ywap',
         high24h : 'high',
         low24h: 'low'
      },
      values: {
         mid: 3,
         cid: 12
      }
   },
   // ----------------
   // 1Broker (user net worth)
   // ----------------
   '1broker': {
      url: function() {
         var baseUrl = 'https://1broker.com/api/v2/';
         var api_token = config.api['1broker'].key;
         return  {url: baseUrl + 'user/overview.php?token=' + api_token + '&pretty=1'};
      },
      fData: function(data) {return {'BTC_1B':data.response}},
      keys: {
         last: 'net_worth'
      },
      values: {
         mid: 5,
         cid: 5
      }

   },
   // ----------------
   // okex.com (user net worth BTC and LTC)
   // ----------------
   /* Return Value of API Call
      {
          "info": {
              "btc": {
                  "balance": 99.95468925,
                  "contracts": [
                      {
                          "available": 99.95468925,
                          "balance": 0.03779061,
                          "bond": 0,
                          "contract_id": 20140815012,
                          "contract_type": "this_week",
                          "freeze": 0,
                          "profit": -0.03779061,
                          "unprofit": 0
                      }
                  ],
                  "rights": 99.95468925
              },
              "ltc": {
                  "balance": 77,
                  "contracts": [
                      {
                          "available": 99.95468925,
                          "balance": 0.03779061,
                          "bond": 0,
                          "contract_id": 20140815012,
                          "contract_type": "this_week",
                          "freeze": 0,
                          "profit": -0.03779061,
                          "unprofit": 0
                      }
                  ],
                  "rights": 100
              }
          },
          "result": true
      }

   */
   'okex': {
      url: function() {
         var baseUrl = 'https://www.okex.com/api/v1/future_userinfo_4fix.do';
         var api_key = config.api.okex.key;
         var api_secret = config.api.okex.secret;
         var sign = 'api_key='+ api_key + '&secret_key=' + api_secret;
         utils.log('String to be signed: ' + sign);
         var sign = md5(sign).toUpperCase();
         utils.log('Sign: ' + sign);
         var options = {
            url: baseUrl,
            method: 'POST',
            form: {
               api_key: api_key,
               sign: sign}
         };
         utils.log('okex.js > ratesRawGet() > options: ');
         utils.log(options);
         return options;
      },
      fData: function(data) {return {'BTC_OKEX':[data.info.btc.rights], 'LTC_OKEX':[data.info.ltc.rights]}},
      keys: {last: 0},
      values: {
         mid: 8,
         cid: 3
      }
   },
   // ----------------
   // bitgrail (BTC_XRB)
   // ----------------
   // {"success":1,"response":{"last":"0.00006098","high":"0.00007164","low":"0.00004965",
   // "volume":"188.72162927","coinVolume":"3025380.63175435","bid":"0.00005903","ask":"0.00006099"}}
   'bitgrail': {
      url: function() {return {url:'https://bitgrail.com/api/v1/BTC-XRB/ticker'}},
      fData: function(data) {return {'BTC_XRB':data.response}},
      keys: {
         lowestAsk  : 'ask',
         highestBid : 'bid',
         baseVolume : 'volume',
         quoteVolume: 'coinVolume',
         high24h    : 'high',
         low24h     : 'low'
      },
      values: {
         internId: 'BTC-XRB',
         mid: 6,
         cid: 14
      }
   }
};
exports.markets = markets;

var splitPair = function(pair) {
   var p = pair.split('_');
   return {
      name: p[0].toUpperCase() + '_' + p[1].toUpperCase(),
      base: p[0].toUpperCase(),
      counter: p[1].toUpperCase()
   };
};
exports.splitPair = splitPair;

var mirrorPair = function(pair) {
   return {name:pair.name, base:pair.counter, counter:pair.base};
};
exports.mirrorPair = mirrorPair;

var getAssetId = function(pair, mysqlconnection, callback){
   var query = '';
   query += 'SELECT * FROM assets WHERE ' +
      'base LIKE \'' + pair.base + '\' AND ' +
      'counter LIKE \'' + pair.counter + '\' ' +
      'LIMIT 0,1';
   if (config.dev) utils.log(query);
   mysqlconnection.query(query, function(err, rowsStats) {
      if(err) {
         utils.log(err)
         callback(err);
      }
      else if (!rowsStats.length) {
         // Create new asset if non existent
         mysqlconnection.query('INSERT INTO assets SET ?', pair, function(e, results, fields){
            if (e) callback(e);
            if (config.dev) console.log(e);
            if (config.dev) console.log(results);
            callback(null, [{aid:results.insertId}]);
         });
      }
      else {
         utils.log(rowsStats);
         callback(null, rowsStats);
      }

   });
};
exports.getAssetId = getAssetId;<commit_msg>remove bitgrail<commit_after>var config = require(__dirname + '/../config.js');
var utils  = require(__dirname + '/../utils.js');
var md5 = require('md5');

/* table: connectors
   cid   mid   type  name
   1 	   1 	   1 	   Poloniex
	2 	   1 	   2 	   Poloniex Margin
	3 	   2 	   3 	   OKCoin Contracts BTC Quarterly
	4 	   2 	   3 	   OKCoin Contracts LTC Quarterly
	5 	   5 	   1 	   1broker
	6 	   1 	   5 	   NXT Wallet
	7 	   1 	   6 	   Poloniex Loan
	8 	   1 	   5 	   wallet.counterwallet.io
	9 	   2 	   1 	   OKCoin
*/

var markets = {
   // ----------------
   // Poloniex.com (all rates)
   // ----------------
   'poloniex': {
      url:  function() { return {url:'https://poloniex.com/public?command=returnTicker'}; },
      fData: function(data){return data},
      keys: {
         internId: 'id'
      },
      values: {
         mid: 1,
         cid: 1
      }
   },
   // ----------------
   // Bitstamp.net (BTC_USD)
   // ----------------
   // {"high": "1425.00", "last": "1419.99", "timestamp": "1493660529", "bid": "1418.01",
   // "vwap": "1370.34", "volume": "7604.50280261", "low": "1325.35", "ask": "1419.99", "open": "1348.88"}
   'bitstamp': {
      url: function() { return {url:'https://www.bitstamp.net/api/v2/ticker_hour/btcusd/'}; },
      fData: function(data) {return {'BTC_USD':data}},
      keys:  {
         lowestAsk: 'ask',
         highestBid: 'bid',
         baseVolume: 'volume',
         quoteVolume: 'ywap',
         high24h : 'high',
         low24h: 'low'
      },
      values: {
         mid: 3,
         cid: 12
      }
   },
   // ----------------
   // 1Broker (user net worth)
   // ----------------
   '1broker': {
      url: function() {
         var baseUrl = 'https://1broker.com/api/v2/';
         var api_token = config.api['1broker'].key;
         return  {url: baseUrl + 'user/overview.php?token=' + api_token + '&pretty=1'};
      },
      fData: function(data) {return {'BTC_1B':data.response}},
      keys: {
         last: 'net_worth'
      },
      values: {
         mid: 5,
         cid: 5
      }

   },
   // ----------------
   // okex.com (user net worth BTC and LTC)
   // ----------------
   /* Return Value of API Call
      {
          "info": {
              "btc": {
                  "balance": 99.95468925,
                  "contracts": [
                      {
                          "available": 99.95468925,
                          "balance": 0.03779061,
                          "bond": 0,
                          "contract_id": 20140815012,
                          "contract_type": "this_week",
                          "freeze": 0,
                          "profit": -0.03779061,
                          "unprofit": 0
                      }
                  ],
                  "rights": 99.95468925
              },
              "ltc": {
                  "balance": 77,
                  "contracts": [
                      {
                          "available": 99.95468925,
                          "balance": 0.03779061,
                          "bond": 0,
                          "contract_id": 20140815012,
                          "contract_type": "this_week",
                          "freeze": 0,
                          "profit": -0.03779061,
                          "unprofit": 0
                      }
                  ],
                  "rights": 100
              }
          },
          "result": true
      }

   */
   'okex': {
      url: function() {
         var baseUrl = 'https://www.okex.com/api/v1/future_userinfo_4fix.do';
         var api_key = config.api.okex.key;
         var api_secret = config.api.okex.secret;
         var sign = 'api_key='+ api_key + '&secret_key=' + api_secret;
         utils.log('String to be signed: ' + sign);
         var sign = md5(sign).toUpperCase();
         utils.log('Sign: ' + sign);
         var options = {
            url: baseUrl,
            method: 'POST',
            form: {
               api_key: api_key,
               sign: sign}
         };
         utils.log('okex.js > ratesRawGet() > options: ');
         utils.log(options);
         return options;
      },
      fData: function(data) {return {'BTC_OKEX':[data.info.btc.rights], 'LTC_OKEX':[data.info.ltc.rights]}},
      keys: {last: 0},
      values: {
         mid: 8,
         cid: 3
      }
   },
   // ----------------
   // bitgrail (BTC_XRB)
   // ----------------
   // {"success":1,"response":{"last":"0.00006098","high":"0.00007164","low":"0.00004965",
   // "volume":"188.72162927","coinVolume":"3025380.63175435","bid":"0.00005903","ask":"0.00006099"}}
   'bitgrail': {
      url: function() {return {url:'https://bitgrail.com/api/v1/BTC-XRB/ticker'}},
      fData: function(data) {return {'BTC_XRB':data.response}},
      keys: {
         lowestAsk  : 'ask',
         highestBid : 'bid',
         baseVolume : 'volume',
         quoteVolume: 'coinVolume',
         high24h    : 'high',
         low24h     : 'low'
      },
      values: {
         internId: 'BTC-XRB',
         mid: 6,
         cid: 14
      }
   }
};
delete markets.bitgrail;
exports.markets = markets;

var splitPair = function(pair) {
   var p = pair.split('_');
   return {
      name: p[0].toUpperCase() + '_' + p[1].toUpperCase(),
      base: p[0].toUpperCase(),
      counter: p[1].toUpperCase()
   };
};
exports.splitPair = splitPair;

var mirrorPair = function(pair) {
   return {name:pair.name, base:pair.counter, counter:pair.base};
};
exports.mirrorPair = mirrorPair;

var getAssetId = function(pair, mysqlconnection, callback){
   var query = '';
   query += 'SELECT * FROM assets WHERE ' +
      'base LIKE \'' + pair.base + '\' AND ' +
      'counter LIKE \'' + pair.counter + '\' ' +
      'LIMIT 0,1';
   if (config.dev) utils.log(query);
   mysqlconnection.query(query, function(err, rowsStats) {
      if(err) {
         utils.log(err)
         callback(err);
      }
      else if (!rowsStats.length) {
         // Create new asset if non existent
         mysqlconnection.query('INSERT INTO assets SET ?', pair, function(e, results, fields){
            if (e) callback(e);
            if (config.dev) console.log(e);
            if (config.dev) console.log(results);
            callback(null, [{aid:results.insertId}]);
         });
      }
      else {
         utils.log(rowsStats);
         callback(null, rowsStats);
      }

   });
};
exports.getAssetId = getAssetId;<|endoftext|>


<commit_before>var Message = function(options) {

    this.options = options;
    this.data = {};
    this.validation_data = {};

};

//Publics
Message.prototype.setReceivers = function(numbers){
    this.validation_data['to'] = numbers;
    if (this._isStringOrNumber(numbers) && this._isNumberValid(numbers)) {
        this.data['to'] = numbers;
    } else if (numbers instanceof Array) {
        this.data['to'] = new Array();
        for(var i = 0; i < numbers.length; i++){
            if (this._isStringOrNumber(numbers[i]) && this._isNumberValid(numbers[i])){
                this.data.to.push(parseInt(numbers[i]));
            }
        }
    }

};

Message.prototype.setParams = function(param1, param2, param3, param4){
    this.validation_data['parameters'] = new Array();
    this._setSingleParam(1, param1);
    this._setSingleParam(2, param2);
    this._setSingleParam(3, param3);
    this._setSingleParam(4, param4);

};

Message.prototype.setMessage = function(msg){
    if(typeof msg == 'string'){
        this.data.message = msg;
    }
};

Message.prototype.setTemplate = function(template){
    this.data.template = template
};

Message.prototype.test = function(){
    this.data.test = 1;
};

//Privates
Message.prototype._setSingleParam = function(i, params){
    var param_name = new String('param' + i);
    if(params){
        this.validation_data.parameters.push(params.length);
        this.data[param_name] = params;
    }

};

Message.prototype._isStringOrNumber = function(x){
    if(typeof x == 'string' || typeof x == 'number')
        return true;
    return false;
};

Message.prototype._isNumberValid = function(number){
    if(parseInt(number).toString().length == 11 || parseInt(number).toString().length == 9)
        return true;
    return false;
};

Message.prototype._validate = function(){
    //this method will validate some of data
};

module.exports = Message;<commit_msg>Version 0.0.0<commit_after>var Message = function(options) {

    this.options = options;
    this.data = {};
    this.validation_data = {};

};

//Publics
Message.prototype.to = function(numbers){
    this.validation_data['to'] = numbers;
    if (this._isStringOrNumber(numbers) && this._isNumberValid(numbers)) {
        this.data['to'] = numbers;
    } else if (numbers instanceof Array) {
        this.data['to'] = new Array();
        for(var i = 0; i < numbers.length; i++){
            if (this._isStringOrNumber(numbers[i]) && this._isNumberValid(numbers[i])){
                this.data.to.push(parseInt(numbers[i]));
            }
        }
    }

};

Message.prototype.params = function(param1, param2, param3, param4){
    this.validation_data['parameters'] = new Array();
    this._setSingleParam(1, param1);
    this._setSingleParam(2, param2);
    this._setSingleParam(3, param3);
    this._setSingleParam(4, param4);

};

Message.prototype.message = function(msg){
    if(typeof msg == 'string'){
        this.data.message = msg;
    }
};

Message.prototype.template = function(template){
    this.data.template = template
};

Message.prototype.test = function(){
    this.data.test = 1;
};

//Privates
Message.prototype._setSingleParam = function(i, params){
    var param_name = new String('param' + i);
    if(params){
        this.validation_data.parameters.push(params.length);
        this.data[param_name] = params;
    }

};

Message.prototype._isStringOrNumber = function(x){
    if(typeof x == 'string' || typeof x == 'number')
        return true;
    return false;
};

Message.prototype._isNumberValid = function(number){
    if(parseInt(number).toString().length == 11 || parseInt(number).toString().length == 9)
        return true;
    return false;
};

Message.prototype._validate = function(){
    //this method will validate some of data
};

module.exports = Message;
<|endoftext|>


<commit_before>/*
 * App Bar - Makes a window an App Bar, like the taskbar.
 *
 * Copyright 2020 Raising the Floor - International
 *
 * Licensed under the New BSD license. You may not use this file except in
 * compliance with this License.
 *
 * The R&D leading to these results received funding from the
 * Department of Education - Grant H421A150005 (GPII-APCP). However,
 * these results do not necessarily represent the policy of the
 * Department of Education, and you should not assume endorsement by the
 * Federal Government.
 *
 * You may obtain a copy of the License at
 * https://github.com/GPII/universal/blob/master/LICENSE.txt
 */

"use strict";

var fluid = require("gpii-universal");

var gpii = fluid.registerNamespace("gpii");

fluid.registerNamespace("gpii.windows.appBar");

fluid.defaults("gpii.windows.appBar", {
    gradeNames: ["fluid.component"],

    listeners: {
        "onCreate.appBar": {
            funcName: "gpii.windows.appBar.created",
            args: ["{that}"]
        },
        "onDestroy.appBar": {
            funcName: "gpii.windows.appBar.destroyed",
            args: ["{that}"]
        }
    },
    invokers: {
        // Set these to the corresponding functions of the electron window.
        getNativeWindowHandle: "fluid.notImplemented",
        hookWindowMessage: "fluid.notImplemented",
        unhookWindowMessage: "fluid.notImplemented",

        listenForMessage: {
            funcName: "gpii.windows.appBar.listenForMessage",
            args: ["{that}", "{arguments}.0"]
        },
        updateAppBar: {
            funcName: "gpii.windows.appBar.updateAppBar", // // message, appBarData, (out) approveRect
            args: [ "{that}.hwnd", "{arguments}.0", "{arguments}.1", "{arguments}.2" ]
        },
        enable: {
            funcName: "gpii.windows.appBar.enable",
            args: ["{that}"]
        },
        disable: {
            funcName: "gpii.windows.appBar.disable",
            args: ["{that}"]
        },
        getTaskbarPos: {
            funcName: "gpii.windows.appBar.getTaskbarPos"
        },
        getWorkAreaBottom: {
            funcName: "gpii.windows.appBar.getWorkAreaBottom"
        }
    },
    events: {
        onAppBarChange: null,
        onPositionChange: null
    },
    members: {
        hwnd: 0,
        hookedMessages: [],
        WM_GPII_APPBAR: "@expand:gpii.windows.messages.registeredMessage(WM_GPII_APPBAR)",
        enabled: false,
        bottomTaskbar: true
    }

});

/**
 * @typedef {Object} AppBarData
 * @property {Number} callbackMessage
 * @property {Number} edge
 * @property {RECT} rc
 * @property {Number} lParam
 */

/**
 * Start some message hooks on the QSS window.
 * @param {Component} that The gpii.windows.appBar instance.
 */
gpii.windows.appBar.created = function (that) {
    that.hwnd = that.getNativeWindowHandle().readInt32LE();
    that.listenForMessage(that.WM_GPII_APPBAR);
    that.listenForMessage(gpii.windows.API_constants.WM_WINDOWPOSCHANGING);
    that.listenForMessage(gpii.windows.API_constants.WM_WINDOWPOSCHANGED);
    that.listenForMessage(gpii.windows.API_constants.WM_ACTIVATE);

    that.updateAppBar(gpii.windows.API_constants.ABM_NEW, {
        callbackMessage: that.WM_GPII_APPBAR
    });
};

/**
 * Release the message hooks on the QSS window.
 * @param {Component} that The gpii.windows.appBar instance.
 */
gpii.windows.appBar.destroyed = function (that) {
    fluid.each(that.hookedMessages, function (msg) {
        that.unhookWindowMessage(msg);
    });
};

/**
 * Adds a message hook to the QSS window
 * @param {Component} that The gpii.windows.appBar instance.
 * @param {Number} msg The window message to listen for.
 */
gpii.windows.appBar.listenForMessage = function (that, msg) {
    if (!that.hookedMessages.includes(msg)) {
        that.hookedMessages.push(msg);
        that.hookWindowMessage(msg, function (wParam, lParam) {
            return gpii.windows.appBar.windowMessage(that, that.hwnd, msg, wParam, lParam);
        });
    }
};

/**
 * Handles messages from the window.
 *
 * @param {Component} that An instance of gpii.app
 * @param {Number} hwnd Window handle.
 * @param {Number} msg The message.
 * @param {Number} wParam Message parameter.
 * @param {Number} lParam Message parameter.
 */
gpii.windows.appBar.windowMessage = function (that, hwnd, msg, wParam, lParam) {
    switch (msg) {
    case that.WM_GPII_APPBAR:
        if (wParam.readUInt32LE() === gpii.windows.API_constants.ABN_POSCHANGED) {
            if (that.enabled) {
                gpii.windows.appBar.updatePosition(that);
            }
        }
        break;

    case gpii.windows.API_constants.WM_ACTIVATE:
        that.updateAppBar(gpii.windows.API_constants.ABM_ACTIVATE);
        break;

    case gpii.windows.API_constants.WM_WINDOWPOSCHANGED:
        that.updateAppBar(gpii.windows.API_constants.ABM_WINDOWPOSCHANGED);
        break;

    case gpii.windows.API_constants.WM_WINDOWPOSCHANGING:

        if (that.enabled) {
            // Put the memory pointed to by (WINDOWPOS)lParam into windowPos
            var windowPos = new gpii.windows.WINDOWPOS();
            var windowPosPtr = lParam.readPointer().reinterpret(gpii.windows.WINDOWPOS.size);
            windowPosPtr.copy(windowPos.ref());

            var SWP_NOMOVE = 0x2;
            var SWP_NOREDRAW = 0x8;
            var windowRect = gpii.windows.getWindowRect(that.hwnd);
            if (!windowPos.cy) {
                windowPos.cy = windowRect.height;
            }
            windowPos.flags |= SWP_NOREDRAW;
            windowPos.flags &= ~(0x100 | 0x0020);
            // Just after the work area change, Windows sometimes adjusts the position to inside the work area.
            // Remove the SWP_NOMOVE bit and set the location to prevent this.
            if (windowPos.flags & SWP_NOMOVE) {
                windowPos.flags &= ~SWP_NOMOVE;
                windowPos.x = windowRect.left;
                windowPos.y = windowRect.top;
            }

            // Keep it at the bottom
            var bottom = that.getWorkAreaBottom();
            if (windowPos.y + windowPos.cy < bottom) {
                windowPos.y = bottom - windowPos.cy;
            }

            // Copy the struct back to the pointer.
            windowPos.ref().copy(windowPosPtr);
        }
        break;
    }
};

/**
 * Update the app bar state.
 *
 * A wrapper for SHAppBarMessage: https://docs.microsoft.com/windows/win32/api/shellapi/nf-shellapi-shappbarmessage
 *
 * @param {Number} hwnd The window handle.
 * @param {Number} message The message (ABM_*)
 * @param {AppBarData} appBarData Information about the state.
 * @return {Number} The return of SHAppBarMessage. Message specific, normally !0 for success.
 */
gpii.windows.appBar.updateAppBar = function (hwnd, message, appBarData) {
    if (!appBarData) {
        appBarData = {};
    }
    var data = new gpii.windows.APPBARDATA();
    data.ref().fill(0);
    data.cbSize = gpii.windows.APPBARDATA.size;

    data.hWnd = hwnd;
    data.uCallbackMessage = appBarData.callbackMessage || 0;
    data.uEdge = appBarData.edge || 0;
    data.lParam = appBarData.lParam || 0;

    if (appBarData.rc) {
        data.rc.left = appBarData.rc.left;
        data.rc.top = appBarData.rc.top;
        data.rc.right = appBarData.rc.right === undefined
            ? appBarData.rc.left + appBarData.rc.width
            : appBarData.rc.right;
        data.rc.bottom = appBarData.rc.bottom === undefined
            ? appBarData.rc.top + appBarData.rc.height
            : appBarData.rc.bottom;
    }

    return gpii.windows.shell32.SHAppBarMessage(message, data.ref());
};

/**
 * Update the position of the window.
 * @param {Component} that The gpii.windows.appBar instance.
 */
gpii.windows.appBar.updatePosition = function (that) {
    var rect;
    var windowRect = gpii.windows.getWindowRect(that.hwnd);
    var taskbarRect = gpii.windows.getWindowRect(gpii.windows.getTasktrayWindow());

    if (taskbarRect.left === 0 && taskbarRect.top > 0) {
        // Taskbar is at the bottom (the usual position)
        rect = {
            left: 0,
            top: taskbarRect.top - windowRect.height - 1,
            right: taskbarRect.width,
            bottom: taskbarRect.top
        };
    } else {
        var desktopRect = gpii.windows.display.getDesktopSize();
        rect = {
            left: 0,
            top: desktopRect.height - windowRect.height - 1,
            width: desktopRect.width,
            bottom: desktopRect.height
        };
    }

    var destRect = {};
    that.updateAppBar(gpii.windows.API_constants.ABM_SETPOS, {
        edge: gpii.windows.API_constants.ABE_BOTTOM,
        rc: rect
    }, destRect);

    that.events.onPositionChange.fire();
};

/**
 * Sets the window to be an app bar.
 * @param {Component} that The gpii.windows.appBar instance.
 */
gpii.windows.appBar.enable = function (that) {
    if (!that.enabled) {
        that.enabled = true;
        that.updateAppBar(gpii.windows.API_constants.ABM_NEW, {callbackMessage: that.WM_GPII_APPBAR});
        gpii.windows.appBar.updatePosition(that);
    }
};

/**
 * Stops the window from being an app bar.
 * @param {Component} that The gpii.windows.appBar instance.
 */
gpii.windows.appBar.disable = function (that) {
    if (that.enabled) {
        that.enabled = false;
        that.updateAppBar(gpii.windows.API_constants.ABM_REMOVE);
    }
};

/**
 * Gets the position of the taskbar.
 *
 * @param {Rectangle} rect [optional] The bounding rectangle of the taskbar.
 * @return {String} "left", "top", "right", or "bottom".
 */
gpii.windows.appBar.getTaskbarPos = function (rect) {
    if (!rect) {
        rect = gpii.windows.getWindowRect(gpii.windows.getTasktrayWindow());
    }

    var togo;
    if (rect.top > 0) {
        togo = "bottom";
    } else if (rect.left > 0) {
        togo = "right";
    } else {
        var desktop = gpii.windows.display.getDesktopSize();
        if (rect.width < desktop.width) {
            togo = "left";
        } else {
            togo = "top";
        }
    }

    return togo;
};

/**
 * Gets the lowest part of the screen.
 * @return {Number} The top of the taskbar (if it's at the bottom of the screen), or the bottom of the screen.
 */
gpii.windows.appBar.getWorkAreaBottom = function () {
    var bottom;
    var taskRect = gpii.windows.getWindowRect(gpii.windows.getTasktrayWindow());
    var taskPos = gpii.windows.appBar.getTaskbarPos(taskRect);
    if (taskPos === "bottom") {
        bottom = taskRect.top;
    } else {
        var desktop = gpii.windows.display.getDesktopSize();
        bottom = desktop.height;
    }

    return bottom;
};
<commit_msg>GPII-4289: Calculating QSS height, rather than using the window size.<commit_after>/*
 * App Bar - Makes a window an App Bar, like the taskbar.
 *
 * Copyright 2020 Raising the Floor - International
 *
 * Licensed under the New BSD license. You may not use this file except in
 * compliance with this License.
 *
 * The R&D leading to these results received funding from the
 * Department of Education - Grant H421A150005 (GPII-APCP). However,
 * these results do not necessarily represent the policy of the
 * Department of Education, and you should not assume endorsement by the
 * Federal Government.
 *
 * You may obtain a copy of the License at
 * https://github.com/GPII/universal/blob/master/LICENSE.txt
 */

"use strict";

var fluid = require("gpii-universal");

var gpii = fluid.registerNamespace("gpii");

fluid.registerNamespace("gpii.windows.appBar");

fluid.defaults("gpii.windows.appBar", {
    gradeNames: ["fluid.component"],

    listeners: {
        "onCreate.appBar": {
            funcName: "gpii.windows.appBar.created",
            args: ["{that}"]
        },
        "onDestroy.appBar": {
            funcName: "gpii.windows.appBar.destroyed",
            args: ["{that}"]
        }
    },
    invokers: {
        // Set these to the corresponding functions of the electron window.
        getNativeWindowHandle: "fluid.notImplemented",
        hookWindowMessage: "fluid.notImplemented",
        unhookWindowMessage: "fluid.notImplemented",
        getBarHeight: "fluid.notImplemented",

        listenForMessage: {
            funcName: "gpii.windows.appBar.listenForMessage",
            args: ["{that}", "{arguments}.0"]
        },
        updateAppBar: {
            funcName: "gpii.windows.appBar.updateAppBar", // // message, appBarData, (out) approveRect
            args: [ "{that}.hwnd", "{arguments}.0", "{arguments}.1", "{arguments}.2" ]
        },
        enable: {
            funcName: "gpii.windows.appBar.enable",
            args: ["{that}"]
        },
        disable: {
            funcName: "gpii.windows.appBar.disable",
            args: ["{that}"]
        },
        getTaskbarPos: {
            funcName: "gpii.windows.appBar.getTaskbarPos"
        },
        getWorkAreaBottom: {
            funcName: "gpii.windows.appBar.getWorkAreaBottom"
        }
    },
    events: {
        onAppBarChange: null,
        onPositionChange: null
    },
    members: {
        hwnd: 0,
        hookedMessages: [],
        WM_GPII_APPBAR: "@expand:gpii.windows.messages.registeredMessage(WM_GPII_APPBAR)",
        enabled: false,
        bottomTaskbar: true,
        height: undefined
    }

});

/**
 * @typedef {Object} AppBarData
 * @property {Number} callbackMessage
 * @property {Number} edge
 * @property {RECT} rc
 * @property {Number} lParam
 */

/**
 * Start some message hooks on the QSS window.
 * @param {Component} that The gpii.windows.appBar instance.
 */
gpii.windows.appBar.created = function (that) {
    that.hwnd = that.getNativeWindowHandle().readInt32LE();
    that.listenForMessage(that.WM_GPII_APPBAR);
    that.listenForMessage(gpii.windows.API_constants.WM_WINDOWPOSCHANGING);
    that.listenForMessage(gpii.windows.API_constants.WM_WINDOWPOSCHANGED);
    that.listenForMessage(gpii.windows.API_constants.WM_ACTIVATE);

    that.updateAppBar(gpii.windows.API_constants.ABM_NEW, {
        callbackMessage: that.WM_GPII_APPBAR
    });
};

/**
 * Release the message hooks on the QSS window.
 * @param {Component} that The gpii.windows.appBar instance.
 */
gpii.windows.appBar.destroyed = function (that) {
    fluid.each(that.hookedMessages, function (msg) {
        that.unhookWindowMessage(msg);
    });
};

/**
 * Adds a message hook to the QSS window
 * @param {Component} that The gpii.windows.appBar instance.
 * @param {Number} msg The window message to listen for.
 */
gpii.windows.appBar.listenForMessage = function (that, msg) {
    if (!that.hookedMessages.includes(msg)) {
        that.hookedMessages.push(msg);
        that.hookWindowMessage(msg, function (wParam, lParam) {
            return gpii.windows.appBar.windowMessage(that, that.hwnd, msg, wParam, lParam);
        });
    }
};

/**
 * Handles messages from the window.
 *
 * @param {Component} that An instance of gpii.app
 * @param {Number} hwnd Window handle.
 * @param {Number} msg The message.
 * @param {Number} wParam Message parameter.
 * @param {Number} lParam Message parameter.
 */
gpii.windows.appBar.windowMessage = function (that, hwnd, msg, wParam, lParam) {
    switch (msg) {
    case that.WM_GPII_APPBAR:
        if (wParam.readUInt32LE() === gpii.windows.API_constants.ABN_POSCHANGED) {
            if (that.enabled) {
                gpii.windows.appBar.updatePosition(that);
            }
        }
        break;

    case gpii.windows.API_constants.WM_ACTIVATE:
        that.updateAppBar(gpii.windows.API_constants.ABM_ACTIVATE);
        break;

    case gpii.windows.API_constants.WM_WINDOWPOSCHANGED:
        that.updateAppBar(gpii.windows.API_constants.ABM_WINDOWPOSCHANGED);
        break;

    case gpii.windows.API_constants.WM_WINDOWPOSCHANGING:

        if (that.enabled) {
            // Put the memory pointed to by (WINDOWPOS)lParam into windowPos
            var windowPos = new gpii.windows.WINDOWPOS();
            var windowPosPtr = lParam.readPointer().reinterpret(gpii.windows.WINDOWPOS.size);
            windowPosPtr.copy(windowPos.ref());

            var SWP_NOMOVE = 0x2;
            var SWP_NOREDRAW = 0x8;
            var windowRect = gpii.windows.getWindowRect(that.hwnd);
            if (!windowPos.cy) {
                windowPos.cy = windowRect.height;
            }
            windowPos.flags |= SWP_NOREDRAW;
            windowPos.flags &= ~(0x100 | 0x0020);
            // Just after the work area change, Windows sometimes adjusts the position to inside the work area.
            // Remove the SWP_NOMOVE bit and set the location to prevent this.
            if (windowPos.flags & SWP_NOMOVE) {
                windowPos.flags &= ~SWP_NOMOVE;
                windowPos.x = windowRect.left;
                windowPos.y = windowRect.top;
            }

            // Keep it at the bottom
            var bottom = that.getWorkAreaBottom();
            if (windowPos.y + windowPos.cy < bottom) {
                windowPos.y = bottom - windowPos.cy;
            }

            // Copy the struct back to the pointer.
            windowPos.ref().copy(windowPosPtr);
        }
        break;
    }
};

/**
 * Update the app bar state.
 *
 * A wrapper for SHAppBarMessage: https://docs.microsoft.com/windows/win32/api/shellapi/nf-shellapi-shappbarmessage
 *
 * @param {Number} hwnd The window handle.
 * @param {Number} message The message (ABM_*)
 * @param {AppBarData} appBarData Information about the state.
 * @return {Number} The return of SHAppBarMessage. Message specific, normally !0 for success.
 */
gpii.windows.appBar.updateAppBar = function (hwnd, message, appBarData) {
    if (!appBarData) {
        appBarData = {};
    }
    var data = new gpii.windows.APPBARDATA();
    data.ref().fill(0);
    data.cbSize = gpii.windows.APPBARDATA.size;

    data.hWnd = hwnd;
    data.uCallbackMessage = appBarData.callbackMessage || 0;
    data.uEdge = appBarData.edge || 0;
    data.lParam = appBarData.lParam || 0;

    if (appBarData.rc) {
        data.rc.left = appBarData.rc.left;
        data.rc.top = appBarData.rc.top;
        data.rc.right = appBarData.rc.right === undefined
            ? appBarData.rc.left + appBarData.rc.width
            : appBarData.rc.right;
        data.rc.bottom = appBarData.rc.bottom === undefined
            ? appBarData.rc.top + appBarData.rc.height
            : appBarData.rc.bottom;
    }

    return gpii.windows.shell32.SHAppBarMessage(message, data.ref());
};

/**
 * Update the position of the window.
 * @param {Component} that The gpii.windows.appBar instance.
 */
gpii.windows.appBar.updatePosition = function (that) {
    var rect;
    var height = that.getBarHeight();
    var taskbarRect = gpii.windows.getWindowRect(gpii.windows.getTasktrayWindow());

    if (taskbarRect.left === 0 && taskbarRect.top > 0) {
        // Taskbar is at the bottom (the usual position)
        rect = {
            left: 0,
            top: taskbarRect.top - height,
            right: taskbarRect.width,
            bottom: taskbarRect.top - 1
        };
    } else {
        var desktopRect = gpii.windows.display.getDesktopSize();
        rect = {
            left: 0,
            top: desktopRect.height - height,
            width: desktopRect.width,
            bottom: desktopRect.height
        };
    }

    var destRect = {};
    that.updateAppBar(gpii.windows.API_constants.ABM_SETPOS, {
        edge: gpii.windows.API_constants.ABE_BOTTOM,
        rc: rect
    }, destRect);

    that.events.onPositionChange.fire();
};

/**
 * Sets the window to be an app bar.
 * @param {Component} that The gpii.windows.appBar instance.
 */
gpii.windows.appBar.enable = function (that) {
    if (!that.enabled) {
        that.enabled = true;
        that.updateAppBar(gpii.windows.API_constants.ABM_NEW, {callbackMessage: that.WM_GPII_APPBAR});
        gpii.windows.appBar.updatePosition(that);
    }
};

/**
 * Stops the window from being an app bar.
 * @param {Component} that The gpii.windows.appBar instance.
 */
gpii.windows.appBar.disable = function (that) {
    if (that.enabled) {
        that.enabled = false;
        that.updateAppBar(gpii.windows.API_constants.ABM_REMOVE);
    }
};

/**
 * Gets the position of the taskbar.
 *
 * @param {Rectangle} rect [optional] The bounding rectangle of the taskbar.
 * @return {String} "left", "top", "right", or "bottom".
 */
gpii.windows.appBar.getTaskbarPos = function (rect) {
    if (!rect) {
        rect = gpii.windows.getWindowRect(gpii.windows.getTasktrayWindow());
    }

    var togo;
    if (rect.top > 0) {
        togo = "bottom";
    } else if (rect.left > 0) {
        togo = "right";
    } else {
        var desktop = gpii.windows.display.getDesktopSize();
        if (rect.width < desktop.width) {
            togo = "left";
        } else {
            togo = "top";
        }
    }

    return togo;
};

/**
 * Gets the lowest part of the screen.
 * @return {Number} The top of the taskbar (if it's at the bottom of the screen), or the bottom of the screen.
 */
gpii.windows.appBar.getWorkAreaBottom = function () {
    var bottom;
    var taskRect = gpii.windows.getWindowRect(gpii.windows.getTasktrayWindow());
    var taskPos = gpii.windows.appBar.getTaskbarPos(taskRect);
    if (taskPos === "bottom") {
        bottom = taskRect.top;
    } else {
        var desktop = gpii.windows.display.getDesktopSize();
        bottom = desktop.height;
    }

    return bottom;
};
<|endoftext|>


<commit_before>'use strict';

import ParticleSystem from './ParticleSystem';
import Spring from './Spring';

class Cloth extends ParticleSystem
{
   constructor({
      mesh,
      gravity,
      timestep,
      solver,
      paused,
      name = 'cloth',
      stiffness = 0,
      damping = 0
   } = {})
   {
      super({ name, mesh, gravity, timestep, solver, paused });

      this.stiffness = stiffness;

      this.damping = damping;

      this.springs = [];

      this.inheritance = ['Entity', 'ParticleSystem', 'Cloth'];

      this.model();
   }

   get stiffness()
   {
      return this._stiffness;
   }

   set stiffness(stiffness)
   {
      this._stiffness = stiffness;
   }

   get damping()
   {
      return this._damping;
   }

   set damping(damping)
   {
      this._damping = damping;
   }

   get springs()
   {
      return this._springs;
   }

   set springs(springs)
   {
      this._springs = springs;
   }

   model()
   {
      let indices = this.mesh.indices;
      let faces = [];
      let corners = 3;

      for (let index = 0, _index = indices.length; index < _index; index += corners)
      {
         let face = indices.slice(index, index + corners);

         faces.push(face);
      }

      this.particles.forEach(this.find.bind(this, faces));
   }

   find(faces, particle, i)
   {
      let cache = [];

      faces.forEach(this.thread.bind(this, cache, i));
   }

   thread(cache, i, face)
   {
      if (~face.indexOf(i))
      {
         let neighbors = face.filter(neighbor => neighbor !== i && !~cache.indexOf(neighbor));
         let springs = neighbors.map(this.stitch.bind(this, i));

         this.springs.push(...springs);
         cache.push(...neighbors);
      }
   }

   stitch(i, j, locale)
   {
      let particles = this.particles;
      let type = 'SHEAR';

      if (locale % 2)
      {
         type = 'STRUCTURAL';
      }

      return new Spring({ i: particles[i], j: particles[j], stiffness: this.stiffness, damping: this.damping, type: type });
   }

   solve()
   {
      if (!this.paused)
      {
         this.springs.forEach(spring => spring.relax());

         super.solve();
      }
   }
}

export default Cloth;
<commit_msg>Flip the local check for Spring instantiation in Cloth<commit_after>'use strict';

import ParticleSystem from './ParticleSystem';
import Spring from './Spring';

class Cloth extends ParticleSystem
{
   constructor({
      mesh,
      gravity,
      timestep,
      solver,
      paused,
      name = 'cloth',
      stiffness = 0,
      damping = 0
   } = {})
   {
      super({ name, mesh, gravity, timestep, solver, paused });

      this.stiffness = stiffness;

      this.damping = damping;

      this.springs = [];

      this.inheritance = ['Entity', 'ParticleSystem', 'Cloth'];

      this.model();
   }

   get stiffness()
   {
      return this._stiffness;
   }

   set stiffness(stiffness)
   {
      this._stiffness = stiffness;
   }

   get damping()
   {
      return this._damping;
   }

   set damping(damping)
   {
      this._damping = damping;
   }

   get springs()
   {
      return this._springs;
   }

   set springs(springs)
   {
      this._springs = springs;
   }

   model()
   {
      let indices = this.mesh.indices;
      let faces = [];
      let corners = 3;

      for (let index = 0, _index = indices.length; index < _index; index += corners)
      {
         let face = indices.slice(index, index + corners);

         faces.push(face);
      }

      this.particles.forEach(this.find.bind(this, faces));
   }

   find(faces, particle, i)
   {
      let cache = [];

      faces.forEach(this.thread.bind(this, cache, i));
   }

   thread(cache, i, face)
   {
      if (~face.indexOf(i))
      {
         let nearest = face.filter(neighbor => neighbor !== i && !~cache.indexOf(neighbor));
         let springs = nearest.map(this.stitch.bind(this, i));

         this.springs.push(...springs);
         cache.push(...nearest);
      }
   }

   stitch(i, j, locale)
   {
      let particles = this.particles;
      let type = 'SHEAR';

      if (locale % 2 === 0)
      {
         type = 'STRUCTURAL';
      }

      return new Spring({ i: particles[i], j: particles[j], stiffness: this.stiffness, damping: this.damping, type: type });
   }

   solve()
   {
      if (!this.paused)
      {
         this.springs.forEach(spring => spring.relax());

         super.solve();
      }
   }
}

export default Cloth;
<|endoftext|>


<commit_before>export default function(ngapp, xelib) {
    ngapp.service('xelibService', function() {
        var service = this;

        this.getExceptionInformation = function() {
            try {
                console.log(xelib.GetMessages());
                console.log(xelib.GetExceptionMessage());
            } catch (e) {
                console.log("Failed to get exception information: " + e);
            }
        };

        this.printGlobals = function() {
            try {
                console.log(xelib.GetGlobals());
            } catch (e) {
                console.log(e);
                service.getExceptionInformation();
            }
        };

        this.logXELibMessages = function() {
            console.log(xelib.GetMessages());
        };

        this.buildObjectView = function(obj) {
            var children = [];
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    var child = { key: obj.Constructor === Array ? '[' + key + ']' : key };
                    if (typeof(obj[key]) === 'object') {
                        if (Object.keys(obj).length == 0) {
                            child.value = '';
                        } else {
                            child.children = service.buildObjectView(obj[key]);
                        }
                    } else {
                        child.value = obj[key];
                    }
                    children.push(child);
                }
            }
            return children;
        };

        this.getRecordView = function(handle) {
            try {
                var obj = xelib.ElementToObject(handle);
                return service.buildObjectView(obj);
            } catch (e) {
                console.log(e);
                return [];
            }
        };

        this.highlightElement = function(view, path) {
            try {
                var parts = path.split('\\');
                var nodes = view;
                parts.forEach(function(part) {
                    if (part.startsWith('[') && part.endsWith(']')) {
                        part = part.slice(1, -1);
                    }
                    var nextNode = nodes.find(function(node) {
                        return (node.key === part);
                    });
                    if (!nextNode) {
                        throw "Could not find node " + part;
                    } else if (nextNode.hasOwnProperty('children')) {
                        nextNode.showChildren = true;
                        nodes = nextNode.children;
                    } else {
                        nextNode.highlight = true;
                    }
                });
            } catch (e) {
                console.log(e);
            }
        };
    });
}
<commit_msg>refactored highlightElement to highlightField<commit_after>export default function(ngapp, xelib) {
    ngapp.service('xelibService', function() {
        var service = this;

        this.getExceptionInformation = function() {
            try {
                console.log(xelib.GetMessages());
                console.log(xelib.GetExceptionMessage());
            } catch (e) {
                console.log("Failed to get exception information: " + e);
            }
        };

        this.printGlobals = function() {
            try {
                console.log(xelib.GetGlobals());
            } catch (e) {
                console.log(e);
                service.getExceptionInformation();
            }
        };

        this.logXELibMessages = function() {
            console.log(xelib.GetMessages());
        };

        this.buildObjectView = function(obj) {
            var children = [];
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    var child = { key: obj.Constructor === Array ? '[' + key + ']' : key };
                    if (typeof(obj[key]) === 'object') {
                        if (Object.keys(obj).length == 0) {
                            child.value = '';
                        } else {
                            child.children = service.buildObjectView(obj[key]);
                        }
                    } else {
                        child.value = obj[key];
                    }
                    children.push(child);
                }
            }
            return children;
        };

        this.getRecordView = function(handle) {
            try {
                var obj = xelib.ElementToObject(handle);
                return service.buildObjectView(obj);
            } catch (e) {
                console.log(e);
                return [];
            }
        };

        this.highlightField = function(view, path) {
            try {
                var parts = path.split('\\');
                var fields = view;
                parts.forEach(function(part) {
                    if (part.startsWith('[') && part.endsWith(']')) {
                        part = part.slice(1, -1);
                    }
                    var nextField = fields.find(function(field) {
                        return (field.key === part);
                    });
                    if (!nextField) {
                        throw "Could not find field " + part;
                    } else if (nextField.hasOwnProperty('children')) {
                        nextField.showChildren = true;
                        fields = nextField.children;
                    } else {
                        nextField.highlight = true;
                    }
                });
            } catch (e) {
                console.log(e);
            }
        };
    });
}
<|endoftext|>


<commit_before>var mongo = require('mongodb').MongoClient;

var url = process.env.MONGODB_URL;

//don't want to connect if already connected
if(!global.db) {
  mongo.connect('mongodb://localhost:27017/express_basics', function(err, db) {
    global.db = db; //available everywhere
  });
}

<commit_msg>changed url<commit_after>var mongo = require('mongodb').MongoClient;

var url = process.env.MONGODB_URL;

//don't want to connect if already connected
if(!global.db) {
  mongo.connect(url, function(err, db) {
    global.db = db; //available everywhere
  });
}

<|endoftext|>


<commit_before>var mongo = require('mongodb').MongoClient;

if(!global.db){
  mongo.connect('mongodb://localhost:27017/nodetunes', function(err, db){
    global.db = db;
  });
}
<commit_msg>updated mongodb.js to include the env variable<commit_after>var mongo = require('mongodb').MongoClient;

if(!global.db) {
  var url = process.env.MONGODB_URL;
  mongo.connect(url,function(err,db) {
    global.db = db;
  });
}

<|endoftext|>


<commit_before>var App;

(function($, _, Converter, CategoryMenu, ConversionWindow, Calculator, Conversions){
    App = function(el) {
        this.el = el;
        this.$el = $(el);
    };

    _.extend(App.prototype, {
        init: function() {
            _.bindAll(this, '_handleToggleClick', '_handleSwipeLeft', '_handleSwipeRight', 'updateUnitType', '_handleMenuItemClick', '_handlePercent', '_handleDigit', '_handleDecimal', '_handleClear', '_handleInvert', '_handleAdd', '_handleSubtract', '_handleDivide', '_handleMultiply', '_handleEvaluate', 'updateConversions');

            var self = this;

            self.ui = {
                toggle: self.$el.find('.toggle'),
                menu: self.$el.find('.unit-category'),
                conversions: self.$el.find('.conversions'),
                calc: self.$el.find('.calc'),
                stage: self.$el.find('.stage')
            };

            self.converter = new Converter(Conversions);
            self.menu = new CategoryMenu(this.ui.menu[0], this.converter.getUnitTypes());
            self.conversion = new ConversionWindow(this.ui.conversions[0]);
            self.calc = new Calculator(this.ui.calc[0]);

            self.silentClear = true;
            self.silentDigit = false;

            self.ui.toggle.hammer().on({
                tap: self._handleToggleClick
            });

            self.$el.hammer().on({
                dragleft: self._handleSwipeLeft,
                dragright: self._handleSwipeRight
            });

            self.menu.$el.bind({
                'click:item': self._handleMenuItemClick
            });

            self.conversion.$el.bind({
                'change:fromValue': self.updateConversions,
                'clear:fromValue': self._handleClear
            });

            self.calc.$el.bind({
                'digit': self._handleDigit,
                'decimal': self._handleDecimal,
                'percent': self._handlePercent,
                'clear': self._handleClear,
                'invert': self._handleInvert,
                'add': self._handleAdd,
                'subtract': self._handleSubtract,
                'divide': self._handleDivide,
                'multiply': self._handleMultiply,
                'evaluate': self._handleEvaluate
            });

            this.updateUnitType(_.first(_.keys(this.converter.getUnitTypes())));
        },

        getSilentClear: function () {
            return this.silentClear;
        },

        setSilentClear: function (val) {
            this.silentClear = val;
        },

        getSilentDigit: function () {
            return this.silentDigit;
        },

        setSilentDigit: function (val) {
            this.silentDigit = val;
        },

        toggleOpen: function(isOpen) {
            if(_.isUndefined(isOpen)) { isOpen = !this.isOpen(); }
            this.$el.toggleClass('menu-open', isOpen);
        },

        isOpen: function() {
            return this.$el.hasClass('menu-open');
        },

        updateConversions: function () {
            console.log(this.converter.convertAll(this.conversion.getFromValue(true),  this.conversion.getFromUnit()));
            console.log('Convert ' + this.conversion.getFromValue(true) + ' ' + this.conversion.getFromUnit() + ' to ' + this.conversion.getToUnit());
            this.conversion.setToValue(this.converter.convert(this.conversion.getFromValue(true), this.conversion.getFromUnit(), this.conversion.getToUnit()));
        },

        updateUnitType: function (item) {
            this.toggleOpen(false);
            this.converter.setUnitType(item);
            this.menu.setActive(this.converter.getUnitType());
            this.conversion.setFromUnit(this.converter.getDefaultFromUnit(), this.converter.getUnit(this.converter.getDefaultFromUnit()));
            this.conversion.setToUnit(this.converter.getDefaultToUnit(), this.converter.getUnit(this.converter.getDefaultToUnit()));this._handleClear();
        },

        _operationPrep: function () {
            this.calc.evaluate();
            this.setSilentClear(true);
            this.setSilentDigit(true);
        },

        _handleToggleClick: function () {
            this.toggleOpen();
        },

        _handleSwipeLeft: function () {
            this.toggleOpen(false);
        },

        _handleSwipeRight: function () {
            this.toggleOpen(true);
        },

        _handleMenuItemClick: function (e, item) {
            this.updateUnitType(item);
        },

        _handleDigit: function (e, digit) {
            var val = (this.getSilentClear()) ? digit : this.conversion.getFromValue() + digit;
            this.conversion.setFromValue(val, this.getSilentDigit());
            this.setSilentClear(false);
        },

        _handleDecimal: function () {
            // Make sure there isn't already a decimal
            if (!_.contains(_.toArray(this.conversion.getFromValue()), '.')) {
                this.conversion.setFromValue(this.conversion.getFromValue() + '.', this.getSilentDigit());
            } else if (this.getSilentClear()) {
                this.conversion.setFromValue('0.', this.getSilentDigit());
                this.setSilentClear(false);
            }
        },

        _handlePercent: function () {
            this.conversion.setFromValue(this.conversion.getFromValue(true) / 100);
        },

        _handleClear: function () {
            this.calc.evaluate();
            this.conversion.setFromValue(0, this.getSilentDigit());
            this.setSilentClear(true);
            this.setSilentDigit(false);
        },

        _handleInvert: function () {
            if(this.conversion.getFromValue(true) === 0) {
                this.conversion.setFromValue('-', true);
            } else {
                this.conversion.setFromValue(this.conversion.getFromValue(true) * -1, this.getSilentDigit());
            }

            this.setSilentClear(false);

        },

        _handleAdd: function () {
            this._operationPrep();

            var self = this,
                mem = self.conversion.getFromValue(true);

            self.calc.$el.one('evaluate', function () {
                self.setSilentDigit(false);
                self.conversion.setFromValue(mem + self.conversion.getFromValue(true), self.getSilentDigit());
            });
        },

        _handleSubtract: function () {
            this._operationPrep();

            var self = this,
                mem = self.conversion.getFromValue(true);

            self.calc.$el.one('evaluate', function () {
                self.setSilentDigit(false);
                self.conversion.setFromValue(mem - self.conversion.getFromValue(true), self.getSilentDigit());
            });
        },

        _handleDivide: function () {
            this._operationPrep();

            var self = this,
                mem = self.conversion.getFromValue(true);

            mem = self.conversion.getFromValue(true);

            self.calc.$el.one('evaluate', function () {
                self.setSilentDigit(false);
                self.conversion.setFromValue(mem / self.conversion.getFromValue(true), self.getSilentDigit());
            });
        },

        _handleMultiply: function () {
            this._operationPrep();

            var self = this,
                mem = self.conversion.getFromValue(true);

            self.calc.$el.one('evaluate', function () {
                self.setSilentDigit(false);
                self.conversion.setFromValue(mem * self.conversion.getFromValue(true), self.getSilentDigit());
            });
        },

        _handleEvaluate: function () {
            this.setSilentClear(true);
            this.setSilentDigit(false);
        }
    });
})(jQuery, window._, window.Converter, window.CategoryMenu, window.ConversionWindow, window.Calculator, window.Conversions);<commit_msg>Commented "convertAll" statement out<commit_after>var App;

(function($, _, Converter, CategoryMenu, ConversionWindow, Calculator, Conversions){
    App = function(el) {
        this.el = el;
        this.$el = $(el);
    };

    _.extend(App.prototype, {
        init: function() {
            _.bindAll(this, '_handleToggleClick', '_handleSwipeLeft', '_handleSwipeRight', 'updateUnitType', '_handleMenuItemClick', '_handlePercent', '_handleDigit', '_handleDecimal', '_handleClear', '_handleInvert', '_handleAdd', '_handleSubtract', '_handleDivide', '_handleMultiply', '_handleEvaluate', 'updateConversions');

            var self = this;

            self.ui = {
                toggle: self.$el.find('.toggle'),
                menu: self.$el.find('.unit-category'),
                conversions: self.$el.find('.conversions'),
                calc: self.$el.find('.calc'),
                stage: self.$el.find('.stage')
            };

            self.converter = new Converter(Conversions);
            self.menu = new CategoryMenu(this.ui.menu[0], this.converter.getUnitTypes());
            self.conversion = new ConversionWindow(this.ui.conversions[0]);
            self.calc = new Calculator(this.ui.calc[0]);

            self.silentClear = true;
            self.silentDigit = false;

            self.ui.toggle.hammer().on({
                tap: self._handleToggleClick
            });

            self.$el.hammer().on({
                dragleft: self._handleSwipeLeft,
                dragright: self._handleSwipeRight
            });

            self.menu.$el.bind({
                'click:item': self._handleMenuItemClick
            });

            self.conversion.$el.bind({
                'change:fromValue': self.updateConversions,
                'clear:fromValue': self._handleClear
            });

            self.calc.$el.bind({
                'digit': self._handleDigit,
                'decimal': self._handleDecimal,
                'percent': self._handlePercent,
                'clear': self._handleClear,
                'invert': self._handleInvert,
                'add': self._handleAdd,
                'subtract': self._handleSubtract,
                'divide': self._handleDivide,
                'multiply': self._handleMultiply,
                'evaluate': self._handleEvaluate
            });

            this.updateUnitType(_.first(_.keys(this.converter.getUnitTypes())));
        },

        getSilentClear: function () {
            return this.silentClear;
        },

        setSilentClear: function (val) {
            this.silentClear = val;
        },

        getSilentDigit: function () {
            return this.silentDigit;
        },

        setSilentDigit: function (val) {
            this.silentDigit = val;
        },

        toggleOpen: function(isOpen) {
            if(_.isUndefined(isOpen)) { isOpen = !this.isOpen(); }
            this.$el.toggleClass('menu-open', isOpen);
        },

        isOpen: function() {
            return this.$el.hasClass('menu-open');
        },

        updateConversions: function () {
            //console.log(this.converter.convertAll(this.conversion.getFromValue(true),  this.conversion.getFromUnit()));
            console.log('Convert ' + this.conversion.getFromValue(true) + ' ' + this.conversion.getFromUnit() + ' to ' + this.conversion.getToUnit());
            this.conversion.setToValue(this.converter.convert(this.conversion.getFromValue(true), this.conversion.getFromUnit(), this.conversion.getToUnit()));
        },

        updateUnitType: function (item) {
            this.toggleOpen(false);
            this.converter.setUnitType(item);
            this.menu.setActive(this.converter.getUnitType());
            this.conversion.setFromUnit(this.converter.getDefaultFromUnit(), this.converter.getUnit(this.converter.getDefaultFromUnit()));
            this.conversion.setToUnit(this.converter.getDefaultToUnit(), this.converter.getUnit(this.converter.getDefaultToUnit()));this._handleClear();
        },

        _operationPrep: function () {
            this.calc.evaluate();
            this.setSilentClear(true);
            this.setSilentDigit(true);
        },

        _handleToggleClick: function () {
            this.toggleOpen();
        },

        _handleSwipeLeft: function () {
            this.toggleOpen(false);
        },

        _handleSwipeRight: function () {
            this.toggleOpen(true);
        },

        _handleMenuItemClick: function (e, item) {
            this.updateUnitType(item);
        },

        _handleDigit: function (e, digit) {
            var val = (this.getSilentClear()) ? digit : this.conversion.getFromValue() + digit;
            this.conversion.setFromValue(val, this.getSilentDigit());
            this.setSilentClear(false);
        },

        _handleDecimal: function () {
            // Make sure there isn't already a decimal
            if (!_.contains(_.toArray(this.conversion.getFromValue()), '.')) {
                this.conversion.setFromValue(this.conversion.getFromValue() + '.', this.getSilentDigit());
            } else if (this.getSilentClear()) {
                this.conversion.setFromValue('0.', this.getSilentDigit());
                this.setSilentClear(false);
            }
        },

        _handlePercent: function () {
            this.conversion.setFromValue(this.conversion.getFromValue(true) / 100);
        },

        _handleClear: function () {
            this.calc.evaluate();
            this.conversion.setFromValue(0, this.getSilentDigit());
            this.setSilentClear(true);
            this.setSilentDigit(false);
        },

        _handleInvert: function () {
            if(this.conversion.getFromValue(true) === 0) {
                this.conversion.setFromValue('-', true);
            } else {
                this.conversion.setFromValue(this.conversion.getFromValue(true) * -1, this.getSilentDigit());
            }

            this.setSilentClear(false);

        },

        _handleAdd: function () {
            this._operationPrep();

            var self = this,
                mem = self.conversion.getFromValue(true);

            self.calc.$el.one('evaluate', function () {
                self.setSilentDigit(false);
                self.conversion.setFromValue(mem + self.conversion.getFromValue(true), self.getSilentDigit());
            });
        },

        _handleSubtract: function () {
            this._operationPrep();

            var self = this,
                mem = self.conversion.getFromValue(true);

            self.calc.$el.one('evaluate', function () {
                self.setSilentDigit(false);
                self.conversion.setFromValue(mem - self.conversion.getFromValue(true), self.getSilentDigit());
            });
        },

        _handleDivide: function () {
            this._operationPrep();

            var self = this,
                mem = self.conversion.getFromValue(true);

            mem = self.conversion.getFromValue(true);

            self.calc.$el.one('evaluate', function () {
                self.setSilentDigit(false);
                self.conversion.setFromValue(mem / self.conversion.getFromValue(true), self.getSilentDigit());
            });
        },

        _handleMultiply: function () {
            this._operationPrep();

            var self = this,
                mem = self.conversion.getFromValue(true);

            self.calc.$el.one('evaluate', function () {
                self.setSilentDigit(false);
                self.conversion.setFromValue(mem * self.conversion.getFromValue(true), self.getSilentDigit());
            });
        },

        _handleEvaluate: function () {
            this.setSilentClear(true);
            this.setSilentDigit(false);
        }
    });
})(jQuery, window._, window.Converter, window.CategoryMenu, window.ConversionWindow, window.Calculator, window.Conversions);<|endoftext|>


<commit_before>var exec = require( 'child_process' ).exec,
    csv = require( 'csv' ),
    fs = require( 'fs' ),
    path = require( 'path' ),
    system32 = 'C:\\Windows\\System32',
    taskListPath = path.join( system32, 'tasklist.exe' ),
    taskKillPath = path.join( system32, 'taskkill.exe' );

// Call tasklist.exe with the supplied arguments
// See https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/tasklist.mspx?mfr=true
function taskList( arg, callback ){
    exec( cmdJoin( taskListPath, arg ), function( err, stdout ){
        callback( err, stdout )
    })
}

// Search for one or more PIDs that match a give process name
function pidOf( procName, callback ){
    if ( isString( procName )){
        var pids = [];

        procStat( procName, function( err, processes, amount ){
            processes.object.forEach( function( proc ){
                pids.push( proc.pid )
            });

            callback( err, pids, amount )
        })
    } else callback( new Error( 'A non-string process name was supplied' ), null, null )
}

// Search for the process name that corresponds with the supplied PID
function nameOf( pid, callback ){
    if( isNumber( pid )){
        procStat( pid, function( err, proc ){
            callback( err, proc.object[ 0 ].name );
        })
    } else callback( new Error( 'A non-numeric PID was supplied' ), null )
}

// Search for a given process name or PID
function procStat( proc, callback ){
    var type = isNumber( proc ) ? 'PID' : 'IMAGENAME',
        arg = '/fi \"' + type + ' eq ' + proc + '\" /fo CSV',
        processes = {
            array: [],
            object: []
        };

    taskList( arg, function( err, stdout ){
        csv.parse( stdout, function( err, rows ){
            if ( rows.length > 0 ){
                rows.forEach( function( row ){
                    if ( row[ 0 ] !== 'Image Name'){
                        processes.array.push( row );
                        processes.object.push({
                            name: row[ 0 ],
                            pid: row[ 1 ],
                            sessionName: row[ 2 ],
                            sessionNumber: row[ 3 ],
                            memUsage: row[ 4 ]
                        })
                    }
                })
            } else {
                var noun = isNumber( proc ) ? 'PIDs' : 'process names';
                err = new Error( 'There were no ' + noun + ' found when searching for \"' + proc + '\"' )
            }

            callback( err, processes, processes.array.length )
        })
    })
}

// Kill a given process name or PID
function kill( proc, callback ){
    var arg = isNumber( proc ) ? '/F /PID ' + proc : '/F /IM ' + proc;

    if ( isNumber( proc ) || isString( proc )){
        exec( cmdJoin( taskKillPath, arg ), function( err ){
            if( callback ) callback( err )
        })
    } else {
        callback( new Error( 'The first kill() argument provided is neither a string nor an integer (not a valid process).' ))
    }
}

function cmdJoin( cmd, params ){
    params = typeof params == 'undefined' ? '' : ' ' + params;
    return cmd + params
}

function isString( obj ){
    return Object.prototype.toString.call( obj ) == '[object String]'
}

function isNumber( obj ){
    return !isNaN( parseFloat( obj ))
}

module.exports = taskList;
module.exports.list = taskList;
module.exports.procStat = procStat;
module.exports.pidOf = pidOf;
module.exports.nameOf = nameOf;
module.exports.kill = kill;<commit_msg>Remove cmdJoin()<commit_after>var exec = require( 'child_process' ).exec,
    csv = require( 'csv' ),
    fs = require( 'fs' ),
    path = require( 'path' ),
    system32 = 'C:\\Windows\\System32',
    taskListPath = path.join( system32, 'tasklist.exe' ) + ' ',
    taskKillPath = path.join( system32, 'taskkill.exe' ) + ' ';

// Call tasklist.exe with the supplied arguments
// See https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/tasklist.mspx?mfr=true
function taskList( arg, callback ){
    exec( taskListPath + arg, function( err, stdout ){
        callback( err, stdout )
    })
}

// Search for one or more PIDs that match a give process name
function pidOf( procName, callback ){
    if ( isString( procName )){
        var pids = [];

        procStat( procName, function( err, processes, amount ){
            processes.object.forEach( function( proc ){
                pids.push( proc.pid )
            });

            callback( err, pids, amount )
        })
    } else callback( new Error( 'A non-string process name was supplied' ), null, null )
}

// Search for the process name that corresponds with the supplied PID
function nameOf( pid, callback ){
    if( isNumber( pid )){
        procStat( pid, function( err, proc ){
            callback( err, proc.object[ 0 ].name );
        })
    } else callback( new Error( 'A non-numeric PID was supplied' ), null )
}

// Search for a given process name or PID
function procStat( proc, callback ){
    var type = isNumber( proc ) ? 'PID' : 'IMAGENAME',
        arg = '/fi \"' + type + ' eq ' + proc + '\" /fo CSV',
        processes = {
            array: [],
            object: []
        };

    taskList( arg, function( err, stdout ){
        csv.parse( stdout, function( err, rows ){
            if ( rows.length > 0 ){
                rows.forEach( function( row ){
                    if ( row[ 0 ] !== 'Image Name'){
                        processes.array.push( row );
                        processes.object.push({
                            name: row[ 0 ],
                            pid: row[ 1 ],
                            sessionName: row[ 2 ],
                            sessionNumber: row[ 3 ],
                            memUsage: row[ 4 ]
                        })
                    }
                })
            } else {
                var noun = isNumber( proc ) ? 'PIDs' : 'process names';
                err = new Error( 'There were no ' + noun + ' found when searching for \"' + proc + '\"' )
            }

            callback( err, processes, processes.array.length )
        })
    })
}

// Kill a given process name or PID
function kill( proc, callback ){
    var arg = isNumber( proc ) ? '/F /PID ' + proc : '/F /IM ' + proc;

    if ( isNumber( proc ) || isString( proc )){
        exec( taskKillPath + arg, function( err ){
            if( callback ) callback( err )
        })
    } else {
        callback( new Error( 'The first kill() argument provided is neither a string nor an integer (not a valid process).' ))
    }
}

function isString( obj ){
    return Object.prototype.toString.call( obj ) == '[object String]'
}

function isNumber( obj ){
    return !isNaN( parseFloat( obj ))
}

module.exports = taskList;
module.exports.list = taskList;
module.exports.procStat = procStat;
module.exports.pidOf = pidOf;
module.exports.nameOf = nameOf;
module.exports.kill = kill;<|endoftext|>