<commit_before>'use strict';
var chokidar = require('chokidar');
const readChunk = require('read-chunk'); // npm install read-chunk
const fileType = require('file-type');
const mv = require('mv');
const path_object = require('path');
const exec = require('child_process').exec;
const rmdir = require('rmdir');

var fs = require('fs');
var Buffer = require('buffer').Buffer;

var log = console.log.bind(console);

var config = {};
  config['watched_folder'] = '/Users/dsteplight/Downloads';
  config['jpeg_folder'] = '/Users/dsteplight/Documents/JPEG';
  config['pdf_folder'] = '/Users/dsteplight/Documents/PDF';
  config['gif_folder'] = '/Users/dsteplight/Documents/GIF';
  config['png_folder'] = '/Users/dsteplight/Documents/PNG';
  config['wmv_folder'] = '/Users/dsteplight/Movies/WMV';
  config['mp4_folder'] = '/Users/dsteplight/Movies/MP4';
  config['flv_folder'] = '/Users/dsteplight/Movies/FLV';
  config['avi_folder'] = '/Users/dsteplight/Movies/AVI';
  config['screen_saver_folder'] = '/Users/dsteplight/Documents/SCREEN-SAVER';
  config['zip_folder'] = '/Users/dsteplight/ZIP';

for (var key in config)
{
   //make sure there is a path set and skipped over the watch folder
   if ((typeof config[key]) != 'undefined' && key !== 'watched_folder') {
       let path_string = config[key];
      if (!fs.existsSync(path_string)){
          fs.mkdirSync(path_string);
         console.log('A NEW FOLDER HAS BEEN CREATED: '+path_string);
      }
   }
}

var watcher = chokidar.watch(config.watched_folder, {
  ignored: /[\/\\]\./,
  interval: 10000,
  persistent: true,
  depth: 0
});

function moveFile( folder, file, path_of_current_file)
{
         let targeted_file = folder+path_object.sep+file;

         mv(path_of_current_file, targeted_file, function(err)
         {
             log('This file has been moved to ', targeted_file);

         });

return true;
}

watcher
  .on('add', function(path) {

      const file_name = path_object.basename(path);
      const file_type = path_object.extname(path);

         if( file_type !== null )
         {
            switch(file_type)
            {
               case '.jpg':
               case '.jpeg':
                     var target_folder = config.jpeg_folder;
                     moveFile( target_folder, file_name, path );
                  break;
               case '.gif':
                     var target_folder = config.gif_folder;
                     moveFile( target_folder, file_name, path );
                  break;
               case '.png':
                     var target_folder = config.png_folder;
                     moveFile( target_folder, file_name, path );
                  break;
               case '.pdf':
                     var target_folder = config.pdf_folder;
                     moveFile( target_folder, file_name, path );
                  break;
               case '.wmv':
                     var target_folder = config.wmv_folder;
                     moveFile( target_folder, file_name, path );
                  break;
               case '.mp4':
                     var target_folder = config.mp4_folder;
                     moveFile( target_folder, file_name, path );
                  break;
               case '.flv':
                     var target_folder = config.flv_folder;
                     moveFile( target_folder, file_name, path );
                  break;
               case '.avi':
                     var target_folder = config.avi_folder;
                     moveFile( target_folder, file_name, path );
                  break;
               case '.saver':
                     var target_folder = config.screen_saver_folder;
                     moveFile( target_folder, file_name, path );
                  break;
               default:
                  break;
            }
         }

   })
  .on('addDir', function(path) {

      let directory_name = path_object.basename(path);
      let file_name = directory_name+".zip";
      let target_folder = config.zip_folder;
      let targeted_file = target_folder+path_object.sep+file_name;

         fs.stat(path, function (err, stats)
         {

           if (err)
           {
             //this should always exsits since we are only dealing with directories right now
           }

           //make sure not to also zip up the actual folder that is being watched
           if (stats.isDirectory() && path !== config.watched_folder )
           {
            let child = exec("zip -r "+directory_name+".zip "+path,{maxBuffer: 1024 * 1000}, function (error, stdout, stderr)
                        {
                             if (error !== null)
                             {
                               console.log('exec error: ' + error);
                             }
                             else
                             {
                                 console.log("THERE SHOULD BE A NEW ZIP FOLDER "+directory_name+".zip");

                                 //the newly created zip folder will exist in the same folder where this script is running and not in the config.watched_folder path
                                 mv(file_name, targeted_file, function(err)
                                 {
                                     log('This zippped file has been moved to ', targeted_file);
                                     //now delete the folder from the config.watched_files directory
                                     rmdir(path, function (err, dirs, files)
                                     {
                                      console.log(dirs);
                                      console.log(files);
                                      console.log('all files are removed from '+ path);
                                     });

                                 });
                              }
                        });

           }

         });

  })
  .on('change', function(path) {

})
  .on('unlink', function(path) {
  })
  .on('unlinkDir', function(path) {
  })
  .on('error', function(error) {
         console.log('DEBUG: The script caught an error', error);
  })
  .on('ready', function() { log('Initial scan complete. Ready for changes.'); })

<commit_msg>adding more files<commit_after>'use strict';
var chokidar = require('chokidar');
const readChunk = require('read-chunk'); // npm install read-chunk
const fileType = require('file-type');
const mv = require('mv');
const path_object = require('path');
const exec = require('child_process').exec;
const rmdir = require('rmdir');

var fs = require('fs');
var Buffer = require('buffer').Buffer;

var log = console.log.bind(console);

var config = {};
  config['watched_folder'] = '/Users/dsteplight/Downloads';

  config['jpeg_folder'] = '/Users/dsteplight/Documents/JPEG';
  config['pdf_folder'] = '/Users/dsteplight/Documents/PDF';
  config['gif_folder'] = '/Users/dsteplight/Documents/GIF';
  config['png_folder'] = '/Users/dsteplight/Documents/PNG';

  config['wmv_folder'] = '/Users/dsteplight/Movies/WMV';
  config['mp4_folder'] = '/Users/dsteplight/Movies/MP4';
  config['flv_folder'] = '/Users/dsteplight/Movies/FLV';
  config['avi_folder'] = '/Users/dsteplight/Movies/AVI';
  config['webm_folder'] = '/Users/dsteplight/Movies/WEBM';

  config['mp3_folder'] = '/Users/dsteplight/Music/MP3';
  config['screen_saver_folder'] = '/Users/dsteplight/Documents/SCREEN-SAVER';
  config['zip_folder'] = '/Users/dsteplight/ZIP';

for (var key in config)
{
   //make sure there is a path set and skipped over the watch folder
   if ((typeof config[key]) != 'undefined' && key !== 'watched_folder') {
       let path_string = config[key];
      if (!fs.existsSync(path_string)){
          fs.mkdirSync(path_string);
         console.log('A NEW FOLDER HAS BEEN CREATED: '+path_string);
      }
   }
}

var watcher = chokidar.watch(config.watched_folder, {
  ignored: /[\/\\]\./,
  interval: 10000,
  persistent: true,
  depth: 0
});

function moveFile( folder, file, path_of_current_file)
{
         let targeted_file = folder+path_object.sep+file;

         mv(path_of_current_file, targeted_file, function(err)
         {
             log('This file has been moved to ', targeted_file);

         });

return true;
}

watcher
  .on('add', function(path) {

      const file_name = path_object.basename(path);
      const file_type = path_object.extname(path);

         if( file_type !== null )
         {
            switch(file_type)
            {
               case '.jpg':
               case '.jpeg':
                     var target_folder = config.jpeg_folder;
                     moveFile( target_folder, file_name, path );
                  break;
               case '.gif':
                     var target_folder = config.gif_folder;
                     moveFile( target_folder, file_name, path );
                  break;
               case '.png':
                     var target_folder = config.png_folder;
                     moveFile( target_folder, file_name, path );
                  break;
               case '.pdf':
                     var target_folder = config.pdf_folder;
                     moveFile( target_folder, file_name, path );
                  break;
               case '.wmv':
                     var target_folder = config.wmv_folder;
                     moveFile( target_folder, file_name, path );
                  break;
               case '.mp4':
                     var target_folder = config.mp4_folder;
                     moveFile( target_folder, file_name, path );
                  break;
               case '.flv':
                     var target_folder = config.flv_folder;
                     moveFile( target_folder, file_name, path );
                  break;
               case '.avi':
                     var target_folder = config.avi_folder;
                     moveFile( target_folder, file_name, path );
                  break;
               case '.mp3':
                     var target_folder = config.mp3_folder;
                     moveFile( target_folder, file_name, path );
                  break;
               case '.webm':
                     var target_folder = config.webm_folder;
                     moveFile( target_folder, file_name, path );
                  break;
               case '.saver':
                     var target_folder = config.screen_saver_folder;
                     moveFile( target_folder, file_name, path );
                  break;
               default:
                  break;
            }
         }

   })
  .on('addDir', function(path) {

      let directory_name = path_object.basename(path);
      let file_name = directory_name+".zip";
      let target_folder = config.zip_folder;
      let targeted_file = target_folder+path_object.sep+file_name;

         fs.stat(path, function (err, stats)
         {

           if (err)
           {
             //this should always exsits since we are only dealing with directories right now
           }

           //make sure not to also zip up the actual folder that is being watched
           if (stats.isDirectory() && path !== config.watched_folder )
           {
            let child = exec("zip -r "+directory_name+".zip "+path,{maxBuffer: 1024 * 1000}, function (error, stdout, stderr)
                        {
                             if (error !== null)
                             {
                               console.log('exec error: ' + error);
                             }
                             else
                             {
                                 console.log("THERE SHOULD BE A NEW ZIP FOLDER "+directory_name+".zip");

                                 //the newly created zip folder will exist in the same folder where this script is running and not in the config.watched_folder path
                                 mv(file_name, targeted_file, function(err)
                                 {
                                     log('This zippped file has been moved to ', targeted_file);
                                     //now delete the folder from the config.watched_files directory
                                     rmdir(path, function (err, dirs, files)
                                     {
                                      console.log(dirs);
                                      console.log(files);
                                      console.log('all files are removed from '+ path);
                                     });

                                 });
                              }
                        });

           }

         });

  })
  .on('change', function(path) {

})
  .on('unlink', function(path) {
  })
  .on('unlinkDir', function(path) {
  })
  .on('error', function(error) {
         console.log('DEBUG: The script caught an error', error);
  })
  .on('ready', function() { log('Initial scan complete. Ready for changes.'); })

<|endoftext|>


<commit_before>import React from 'react';

import Component from '../Component';
import Button from '../Button';
import Popup from '../Popup';
import Menu from '../Menu';
import Icon from '../Icon';
import Group from '../Group';
import Item from '../Item';

class Select extends Component {
    constructor(props) {
        super(props);

        this.state = {
            popupVisible: false,
        };

        this._shouldRestoreButtonFocus = false;
        this._cachedItems = null;

        this.onButtonClick = this.onButtonClick.bind(this);
        this.onMenuChange = this.onMenuChange.bind(this);
        this.onMenuFocusChange = this.onMenuFocusChange.bind(this);
        this.onMenuItemClick = this.onMenuItemClick.bind(this);
        this.onPopupRequestHide = this.onPopupRequestHide.bind(this);
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.children !== this.props.children) {
            this._cachedItems = null;
        }
    }

    componentDidUpdate() {
        if (this._shouldRestoreButtonFocus) {
            this._shouldRestoreButtonFocus = false;
        }
    }

    componentWillUnmount() {
        this._cachedItems = null;
    }

    render() {
        return (

                {this.renderInputs()}
                {this.renderButton()}
                <Popup theme={this.props.theme} size={this.props.size}
                    anchor={this.refs.button}
                    directions={['bottom-left', 'bottom-right', 'top-left', 'top-right']}
                    visible={this.state.popupVisible}
                    onRequestHide={this.onPopupRequestHide}
                >
                    {this.renderMenu()}
                </Popup>

        );
    }

    renderButton() {
        const { theme, size, disabled, mode, value } = this.props;
        const focused = (!disabled && this._shouldRestoreButtonFocus) ? true : undefined;
        const checked = (
            (mode === 'check' || mode === 'radio-check') &&
            Array.isArray(value) && value.length > 0
        );

        const text = this.getItems().reduce((res, item) => {
            if (value.indexOf(item.props.value) !== -1) {
                if (value.length === 1) {
                    res.push(Component.textValue(item));
                } else {
                    res.push(item.props.checkedText || Component.textValue(item));
                }
            }
            return res;
        }, []);
        const buttonText = text.join(', ') || this.props.placeholder || '—';

        return (
            <Button ref="button" theme={theme} size={size} className="select__button"
                disabled={disabled}
                checked={checked}
                focused={focused}
                onClick={this.onButtonClick}
            >
                {buttonText}
                <Icon className="select__tick"/>
            </Button>
        );
    }

    renderMenu() {
        const { theme, size, disabled, mode, value } = this.props;
        const focused = this.state.popupVisible;
        const tabIndex = -1;

        return (
            <Menu ref="menu" theme={theme} size={size} className="select__menu"
                mode={mode}
                value={value}
                tabIndex={tabIndex}
                disabled={disabled}
                focused={focused}
                onItemClick={this.onMenuItemClick}
                onChange={this.onMenuChange}
                onFocusChange={this.onMenuFocusChange}
            >
                {this.props.children}
            </Menu>
        );
    }

    renderInputs() {
        if (this.props.disabled) {
            return null;
        }

        const { name } = this.props;
        return this.props.value.map(value => React.createElement('input', { type: 'hidden', name, value }));
    }

    className() {
        var className = 'select';

        const theme = this.props.theme || this.context.theme;
        if (theme) {
            className += ' select_theme_' + theme;
        }
        if (this.props.size) {
            className += ' select_size_' + this.props.size;
        }
        if (this.props.mode) {
            className += ' select_mode_' + this.props.mode;
        }
        if (this.props.disabled) {
            className += ' select_disabled';
        }
        if (this.state.popupVisible) {
            className += ' select_opened';
        }

        if (this.props.className) {
            className += ' ' + this.props.className;
        }
        return className;
    }

    getItems() {
        if (!this._cachedItems) {
            let items = [];

            React.Children.forEach(this.props.children, child => {
                if (Component.is(child, Item)) {
                    items.push(child);
                } else if (Component.is(child, Group)) {
                    //  Предполагаем, что ничего, кроме Item внутри Group уже нет.
                    items = items.concat(React.Children.toArray(child.props.children));
                }
            });

            this._cachedItems = items;
        }

        return this._cachedItems;
    }

    getMenu() {
        return this.refs.menu;
    }

    trapMenuFocus() {
        this.getMenu().componentWillGainFocus();
    }

    onButtonClick() {
        this.setState({ popupVisible: !this.state.popupVisible });
    }

    onMenuItemClick() {
        if (this.props.mode === 'radio' || this.props.mode === 'radio-check') {
            this._shouldRestoreButtonFocus = true;
            // NOTE(narqo@): select with mode radio* must be closed on click within <Menu>
            this.setState({ popupVisible: false });
        }
    }

    onMenuChange(value) {
        this.props.onChange(value, this.props);
    }

    onMenuFocusChange(focused) {
        if (!focused && this.state.popupVisible) {
            // NOTE(narqo@): restore DOM focus to the Menu if still opened
            this.trapMenuFocus();
        }
    }

    onPopupRequestHide(_, reason) {
        this._shouldRestoreButtonFocus = reason === 'escapeKeyPress';
        this.setState({ popupVisible: false });
    }
}

Select.contextTypes = {
    theme: React.PropTypes.string
};

Select.propTypes = {
    theme: React.PropTypes.string,
    size: React.PropTypes.string,
    mode: React.PropTypes.string,
    name: React.PropTypes.string,
    value: React.PropTypes.any,
    placeholder: React.PropTypes.string,
    disabled: React.PropTypes.bool,
    onChange: React.PropTypes.func,
};

Select.defaultProps = {
    onChange() {}
};

export default Select;
<commit_msg>select: open on arrow keys down<commit_after>import React from 'react';

import Component from '../Component';
import Button from '../Button';
import Popup from '../Popup';
import Menu from '../Menu';
import Icon from '../Icon';
import Group from '../Group';
import Item from '../Item';

class Select extends Component {
    constructor(props) {
        super(props);

        this.state = {
            popupVisible: false,
        };

        this._shouldRestoreButtonFocus = false;
        this._cachedItems = null;

        this.onButtonClick = this.onButtonClick.bind(this);
        this.onButtonKeyDown = this.onButtonKeyDown.bind(this);
        this.onMenuChange = this.onMenuChange.bind(this);
        this.onMenuFocusChange = this.onMenuFocusChange.bind(this);
        this.onMenuItemClick = this.onMenuItemClick.bind(this);
        this.onPopupRequestHide = this.onPopupRequestHide.bind(this);
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.children !== this.props.children) {
            this._cachedItems = null;
        }
    }

    componentDidUpdate() {
        if (this._shouldRestoreButtonFocus) {
            this._shouldRestoreButtonFocus = false;
        }
    }

    componentWillUnmount() {
        this._cachedItems = null;
    }

    render() {
        return (

                {this.renderInputs()}
                {this.renderButton()}
                <Popup theme={this.props.theme} size={this.props.size}
                    anchor={this.refs.button}
                    directions={['bottom-left', 'bottom-right', 'top-left', 'top-right']}
                    visible={this.state.popupVisible}
                    onRequestHide={this.onPopupRequestHide}
                >
                    {this.renderMenu()}
                </Popup>

        );
    }

    renderButton() {
        const { theme, size, disabled, mode, value } = this.props;
        const focused = (!disabled && this._shouldRestoreButtonFocus) ? true : undefined;
        const checked = (
            (mode === 'check' || mode === 'radio-check') &&
            Array.isArray(value) && value.length > 0
        );

        const text = this.getItems().reduce((res, item) => {
            if (value.indexOf(item.props.value) !== -1) {
                if (value.length === 1) {
                    res.push(Component.textValue(item));
                } else {
                    res.push(item.props.checkedText || Component.textValue(item));
                }
            }
            return res;
        }, []);
        const buttonText = text.join(', ') || this.props.placeholder || '—';

        return (
            <Button ref="button" theme={theme} size={size} className="select__button"
                disabled={disabled}
                checked={checked}
                focused={focused}
                onClick={this.onButtonClick}
                onKeyDown={this.onButtonKeyDown}
            >
                {buttonText}
                <Icon className="select__tick"/>
            </Button>
        );
    }

    renderMenu() {
        const { theme, size, disabled, mode, value } = this.props;
        const focused = this.state.popupVisible;
        const tabIndex = -1;

        return (
            <Menu ref="menu" theme={theme} size={size} className="select__menu"
                mode={mode}
                value={value}
                tabIndex={tabIndex}
                disabled={disabled}
                focused={focused}
                onItemClick={this.onMenuItemClick}
                onChange={this.onMenuChange}
                onFocusChange={this.onMenuFocusChange}
            >
                {this.props.children}
            </Menu>
        );
    }

    renderInputs() {
        if (this.props.disabled) {
            return null;
        }

        const { name } = this.props;
        return this.props.value.map(value => React.createElement('input', { type: 'hidden', name, value }));
    }

    className() {
        var className = 'select';

        const theme = this.props.theme || this.context.theme;
        if (theme) {
            className += ' select_theme_' + theme;
        }
        if (this.props.size) {
            className += ' select_size_' + this.props.size;
        }
        if (this.props.mode) {
            className += ' select_mode_' + this.props.mode;
        }
        if (this.props.disabled) {
            className += ' select_disabled';
        }
        if (this.state.popupVisible) {
            className += ' select_opened';
        }

        if (this.props.className) {
            className += ' ' + this.props.className;
        }
        return className;
    }

    getItems() {
        if (!this._cachedItems) {
            let items = [];

            React.Children.forEach(this.props.children, child => {
                if (Component.is(child, Item)) {
                    items.push(child);
                } else if (Component.is(child, Group)) {
                    //  Предполагаем, что ничего, кроме Item внутри Group уже нет.
                    items = items.concat(React.Children.toArray(child.props.children));
                }
            });

            this._cachedItems = items;
        }

        return this._cachedItems;
    }

    getMenu() {
        return this.refs.menu;
    }

    trapMenuFocus() {
        this.getMenu().componentWillGainFocus();
    }

    onButtonClick() {
        this.setState({ popupVisible: !this.state.popupVisible });
    }

    onButtonKeyDown(e) {
        if (!this.state.popupVisible &&
            ((e.key === 'ArrowDown' || e.key === 'ArrowUp') && !e.shiftKey)) {
            this.setState({ popupVisible: true });
        }
    }

    onMenuItemClick() {
        if (this.props.mode === 'radio' || this.props.mode === 'radio-check') {
            this._shouldRestoreButtonFocus = true;
            // NOTE(narqo@): select with mode radio* must be closed on click within <Menu>
            this.setState({ popupVisible: false });
        }
    }

    onMenuChange(value) {
        this.props.onChange(value, this.props);
    }

    onMenuFocusChange(focused) {
        if (!focused && this.state.popupVisible) {
            // NOTE(narqo@): restore DOM focus to the Menu if still opened
            this.trapMenuFocus();
        }
    }

    onPopupRequestHide(_, reason) {
        this._shouldRestoreButtonFocus = reason === 'escapeKeyPress';
        this.setState({ popupVisible: false });
    }
}

Select.contextTypes = {
    theme: React.PropTypes.string
};

Select.propTypes = {
    theme: React.PropTypes.string,
    size: React.PropTypes.string,
    mode: React.PropTypes.string,
    name: React.PropTypes.string,
    value: React.PropTypes.any,
    placeholder: React.PropTypes.string,
    disabled: React.PropTypes.bool,
    onChange: React.PropTypes.func,
};

Select.defaultProps = {
    onChange() {}
};

export default Select;
<|endoftext|>


<commit_before><commit_msg>Post-merge commit.<commit_after><|endoftext|>


<commit_before>const ccxt = require ('../../ccxt');

const exchange = new ccxt.huobi ({
    'apiKey': 'YOUR_API_KEY',
    'secret': 'YOUR_SECRET_KEY',
})

// Example 1: Spot : fetch balance, create order, cancel it and check canceled orders
async function example1() {
    await exchange.loadMarkets ();

    // fetch spot balance
    const balance = await exchange.fetchBalance ();
    console.log(balance)

    // create order
    const symbol = 'LTC/USDT';
    const createOrder = await exchange.createOrder (symbol, 'limit', 'buy', 50, 0.1);
    console.log('Created order Id:', createOrder['id'])

    // cancel order
    const cancelOrder = await exchange.cancelOrder (createOrder['id'], symbol);

    // Check canceled orders (bybit does not have a single endpoint to check orders
    // we have to choose whether to check open or closed orders and call fetchOpenOrders
    // or fetchClosedOrders respectively
    const canceledOrders = await exchange.fetchClosedOrders(symbol);
    console.log(canceledOrders);
}

// Example 2 :: Swap : fetch balance, open a position and close it
async function example2() {
    exchange['options']['defaultType'] = 'swap'; // very important set swap as default type
    await exchange.loadMarkets ();

    // fetch swap balance
    const balance = await exchange.fetchBalance ();
    console.log(balance)

    // create order and open position
    const symbol = 'LTC/USDT:USDT';
    const createOrder = await exchange.createOrder (symbol, 'market', 'buy', 0.1);
    console.log('Created order Id:', createOrder['id'])

    // check opened position
    const symbols = [ symbol ];
    const positions = await exchange.fetchPositions (symbols);
    console.log(positions)

    // Close position by issuing a order in the opposite direction
    const params = {
        'reduce_only': true
    }
    const closePositionOrder = await exchange.createOrder (symbol, 'market', 'sell', 0.1, undefined, params);
    console.log(closePositionOrder);
}

// Example 3 :: USDC Swap : fetch balance, open a position and close it
async function example3() {
    exchange['options']['defaultType'] = 'swap'; // very important set swap as default type
    await exchange.loadMarkets ();

    // fetch USDC swap balance
    // when no symbol is available we can show our intent
    // of using USDC endpoints by either using defaultSettle in options or
    // settle in params
    // Using Options: exchange['options']['defaultSettle'] = 'USDC';
    // Using params:
    const balanceParams = {
        'settle': 'USDC'
    }
    const balance = await exchange.fetchBalance (balanceParams);
    console.log(balance)

    // create order and open position
    // taking into consideration that USDC markets do not support
    // market orders
    const symbol = 'BTC/USD:USDC';
    const amount = 0.1;
    const price = 29940 // adjust this accordingly
    const createOrder = await exchange.createOrder (symbol, 'limit', 'buy', amount, price);
    console.log('Created order Id:', createOrder['id'])

    // check if the order was filled and the position opened
    const symbols = [ symbol ];
    const positions = await exchange.fetchPositions (symbols);
    console.log(positions)

    // close position (assuming it was already opened) by issuing a order in the opposite direction
    const params = {
        'reduce_only': true
    }
    const closePositionOrder = await exchange.createOrder (symbol, 'limit', 'sell', amount, price, params);
    console.log(closePositionOrder);
}

// Example 4 :: Future : fetch balance, create stop-order and check fetch open stop-orders
async function example4() {
    exchange['options']['defaultType'] = 'future'; // very important set future as default type
    await exchange.loadMarkets ();

    // fetch future balance
    const balance = await exchange.fetchBalance ();
    console.log(balance)

    // create stop-order
    const symbol = 'ETH/USD:ETH-220930';
    const amount = 10; // in USD for inverse futures
    const price = 1200;
    const side = 'buy';
    const type = 'limit';
    const stopOrderParams = {
        'position_idx': 0, // 0 One-Way Mode, 1 Buy-side, 2 Sell-side, default = 0
        'stopPrice': 1000, // mandatory for stop orders
        'basePrice': 1100  // mandatory for stop orders
    }
    const stopOrder = await exchange.createOrder (symbol, type, side, amount, price, stopOrderParams);
    console.log('Created order Id:', stopOrder['id'])

    // check opened stop-order
    const openOrderParams = {
        'stop': true
    }
    const openOrders = await exchange.fetchOpenOrders (symbol, undefined, undefined, openOrderParams);
    console.log(openOrders)

    // Cancell all open stop-orders
    const cancelOrder = await exchange.cancelOrder(stopOrder['id'], symbol, openOrderParams);
    console.log(cancelOrder);
}

async function main() {
    // await example1 ();
    // await example2 ();
    // await example3 ();
    await example4 ();

}

main();<commit_msg>split examples<commit_after>const ccxt = require ('../../ccxt');

const exchange = new ccxt.huobi ({
    'apiKey': 'YOUR_API_KEY',
    'secret': 'YOUR_SECRET_KEY',
})

// Example 1: Spot : fetch balance, create order, cancel it and check canceled orders
async function example1() {
    await exchange.loadMarkets ();

    // fetch spot balance
    const balance = await exchange.fetchBalance ();
    console.log(balance)

    // create order
    const symbol = 'LTC/USDT';
    const createOrder = await exchange.createOrder (symbol, 'limit', 'buy', 50, 0.1);
    console.log('Created order Id:', createOrder['id'])

    // cancel order
    const cancelOrder = await exchange.cancelOrder (createOrder['id'], symbol);

    // Check canceled orders (bybit does not have a single endpoint to check orders
    // we have to choose whether to check open or closed orders and call fetchOpenOrders
    // or fetchClosedOrders respectively
    const canceledOrders = await exchange.fetchClosedOrders(symbol);
    console.log(canceledOrders);
}

// -----------------------------------------------------------------------------------------

// Example 2 :: Swap : fetch balance, open a position and close it
async function example2() {
    exchange['options']['defaultType'] = 'swap'; // very important set swap as default type
    await exchange.loadMarkets ();

    // fetch swap balance
    const balance = await exchange.fetchBalance ();
    console.log(balance)

    // create order and open position
    const symbol = 'LTC/USDT:USDT';
    const createOrder = await exchange.createOrder (symbol, 'market', 'buy', 0.1);
    console.log('Created order Id:', createOrder['id'])

    // check opened position
    const symbols = [ symbol ];
    const positions = await exchange.fetchPositions (symbols);
    console.log(positions)

    // Close position by issuing a order in the opposite direction
    const params = {
        'reduce_only': true
    }
    const closePositionOrder = await exchange.createOrder (symbol, 'market', 'sell', 0.1, undefined, params);
    console.log(closePositionOrder);
}

// -----------------------------------------------------------------------------------------

// Example 3 :: USDC Swap : fetch balance, open a position and close it
async function example3() {
    exchange['options']['defaultType'] = 'swap'; // very important set swap as default type
    await exchange.loadMarkets ();

    // fetch USDC swap balance
    // when no symbol is available we can show our intent
    // of using USDC endpoints by either using defaultSettle in options or
    // settle in params
    // Using Options: exchange['options']['defaultSettle'] = 'USDC';
    // Using params:
    const balanceParams = {
        'settle': 'USDC'
    }
    const balance = await exchange.fetchBalance (balanceParams);
    console.log(balance)

    // create order and open position
    // taking into consideration that USDC markets do not support
    // market orders
    const symbol = 'BTC/USD:USDC';
    const amount = 0.1;
    const price = 29940 // adjust this accordingly
    const createOrder = await exchange.createOrder (symbol, 'limit', 'buy', amount, price);
    console.log('Created order Id:', createOrder['id'])

    // check if the order was filled and the position opened
    const symbols = [ symbol ];
    const positions = await exchange.fetchPositions (symbols);
    console.log(positions)

    // close position (assuming it was already opened) by issuing an order in the opposite direction
    const params = {
        'reduce_only': true
    }
    const closePositionOrder = await exchange.createOrder (symbol, 'limit', 'sell', amount, price, params);
    console.log(closePositionOrder);
}

// -----------------------------------------------------------------------------------------

// Example 4 :: Future : fetch balance, create stop-order and check fetch open stop-orders
async function example4() {
    exchange['options']['defaultType'] = 'future'; // very important set future as default type
    await exchange.loadMarkets ();

    // fetch future balance
    const balance = await exchange.fetchBalance ();
    console.log(balance)

    // create stop-order
    const symbol = 'ETH/USD:ETH-220930';
    const amount = 10; // in USD for inverse futures
    const price = 1200;
    const side = 'buy';
    const type = 'limit';
    const stopOrderParams = {
        'position_idx': 0, // 0 One-Way Mode, 1 Buy-side, 2 Sell-side, default = 0
        'stopPrice': 1000, // mandatory for stop orders
        'basePrice': 1100  // mandatory for stop orders
    }
    const stopOrder = await exchange.createOrder (symbol, type, side, amount, price, stopOrderParams);
    console.log('Created order Id:', stopOrder['id'])

    // check opened stop-order
    const openOrderParams = {
        'stop': true
    }
    const openOrders = await exchange.fetchOpenOrders (symbol, undefined, undefined, openOrderParams);
    console.log(openOrders)

    // Cancell open stop-order
    const cancelOrder = await exchange.cancelOrder(stopOrder['id'], symbol, openOrderParams);
    console.log(cancelOrder);
}

// -----------------------------------------------------------------------------------------

async function main() {
    // await example1 ();
    // await example2 ();
    // await example3 ();
    await example4 ();

}

main();<|endoftext|>


<commit_before>#! /usr/bin/env node
/*jslint node: true */

/*
 * dust-compiler.js
 * james.young@turner.com
 *
 * This is a basic dust compiler, there are many out there. This one adds support
 * for OS X 10.8.x Notification Center to bring more visiblity to compile errors
 * when developing while the terminal window that it is running in is not visible.
 *
 * Usage from terminal:
 *     node dust-compiler.js
 */

var source = "./dust/",
    destination = "./js/",
    fs = require('fs'),
    dust = require('dustjs-linkedin'),
    watch = require('watch'),
    notifier = require('terminal-notifier');

function log(message) {
    'use strict';

    if (process.platform === 'darwin') {
        notifier(message, {
            title: 'Dust Compiler',
            activate: 'com.apple.Terminal'
        });
    }

    console.log(message);
}

function compile(path, curr, prev) {
    'use strict';

    var filename = path.split('/').reverse()[0].replace('.dust', ''),
        filepath = destination + filename + '.js',
        error = false,
        data;

    fs.readFile(path, function (err, data) {
        if (err) {
            log('fs.readFile error');
            throw err;
        }

        try {
            data = dust.compile(data.toString(), filename);
        } catch (e) {
            error = true;
            log(e);
        }

        if (!error) {
            fs.writeFile(filepath, data, function (err) {
                if (err) {
                    log('fs.writeFile error: ' + err);
                    throw err;
                }
                log('Saved ' + filepath);
            });
        }
    });
}

watch.createMonitor(source, function (monitor) {
    'use strict';

    log('Watching' + source);
    monitor.files['*.dust', '*/*'];
    monitor.on('created', compile);
    monitor.on('changed', compile);
});
<commit_msg>changed default source and destination paths<commit_after>#! /usr/bin/env node
/*jslint node: true */

/*
 * dust-compiler
 * jmeyoung@gmail.com
 *
 * This is a basic dust compiler, there are many out there. This one adds support
 * for OS X 10.8.x Notification Center to bring more visiblity to compile errors
 * when developing while the terminal window that it is running in is not visible.
 *
 * Usage from terminal:
 *     ./dust-compiler
 */

var source = "src/main/dust-templates/",
    destination = "src/main/js/lib/dust-templates",
    fs = require('fs'),
    dust = require('dustjs-linkedin'),
    watch = require('watch'),
    notifier = require('terminal-notifier');

function log(message) {
    'use strict';

    if (process.platform === 'darwin') {
        notifier(message, {
            title: 'Dust Compiler',
            activate: 'com.apple.Terminal'
        });
    }

    console.log(message);
}

function compile(path, curr, prev) {
    'use strict';

    var filename = path.split('/').reverse()[0].replace('.dust', ''),
        filepath = destination + filename + '.js',
        error = false,
        data;

    fs.readFile(path, function (err, data) {
        if (err) {
            log('fs.readFile error');
            throw err;
        }

        try {
            data = dust.compile(data.toString(), filename);
        } catch (e) {
            error = true;
            log(e);
        }

        if (!error) {
            fs.writeFile(filepath, data, function (err) {
                if (err) {
                    log('fs.writeFile error: ' + err);
                    throw err;
                }
                log('Saved ' + filepath);
            });
        }
    });
}

watch.createMonitor(source, function (monitor) {
    'use strict';

    log('Watching ' + source);
    monitor.files['*.dust', '*/*'];
    monitor.on('created', compile);
    monitor.on('changed', compile);
});
<|endoftext|>


<commit_before>'use strict';

// Fluxex extra action
// you should attach a `routing()` action creator on your fluxexapp
// See routing.js for more info
module.exports = function (url) {
    // Try to route
    this.dispatch('UPDATE_URL', url).then(function () {
        // Run action to update page stores
        return this.executeAction(this.routing);
    }.bind(this)).then(function () {
        // Success, trigger page refresh
        this.getStore('page').emitChange();

        // update url to history
        /*global history*/
        history.pushState(this.toString(), undefined, url);
    }.bind(this))['catch'](function (E) {
        if (console.log) {
            console.log('Pjax failed! Failback to page loading....');
            console.log(E.stack || E);
        }
        // pjax failed, go to url...
        location.href = url;
    });
};
<commit_msg>ie8 friendly<commit_after>'use strict';

// Fluxex extra action
// you should attach a `routing()` action creator on your fluxexapp
// See routing.js for more info
module.exports = function (url) {
    // Try to route
    this.dispatch('UPDATE_URL', url).then(function () {
        // Run action to update page stores
        return this.executeAction(this.routing);
    }.bind(this)).then(function () {
        // Success, trigger page refresh
        this.getStore('page').emitChange();

        // update url to history
        /*global history*/
        history.pushState(this.toString(), undefined, url);
    }.bind(this))['catch'](function (E) {
        if (console && console.log) {
            console.log('Pjax failed! Failback to page loading....');
            console.log(E.stack || E);
        }
        // pjax failed, go to url...
        location.href = url;
    });
};
<|endoftext|>


<commit_before>var port = process.argv[2];

var userService = require('./src/userService');

var mysql = require('./src/mysql');
var dbPool = mysql.createPool();

var express = require('express');
var status = require('http-status');
var cors = require('cors');

var app = express();
app.use(cors());

app.get('/user', function(request, response) {
	var filter = request.query.filter || '';

	userService.searchUser(filter, dbPool, function(err, result){
    if (err) {
      return response.status(status.INTERNAL_SERVER_ERROR).json({ error: err });
    }
		response.json(result);
	});
});

app.get('/user/:id', function(request, response) {
  var filter = request.params.id || '';

  userService.searchUserId(filter, dbPool, function(err, result){
    if (err) {
      return response.status(status.INTERNAL_SERVER_ERROR).json({ error: err });
    }
    response.json(result);
  });
});

app.listen(port);
<commit_msg>renamed field<commit_after>var port = process.argv[2];

var userService = require('./src/userService');

var mysql = require('./src/mysql');
var dbPool = mysql.createPool();

var express = require('express');
var status = require('http-status');
var cors = require('cors');

var app = express();
app.use(cors());

app.get('/user', function(request, response) {
	var filter = request.query.filter || '';

	userService.searchUser(filter, dbPool, function(err, result){
    if (err) {
      return response.status(status.INTERNAL_SERVER_ERROR).json({ error: err });
    }
		response.json(result);
	});
});

app.get('/user/:id', function(request, response) {
  var userId = request.params.id || '';

  userService.searchUserId(userId, dbPool, function(err, result){
    if (err) {
      return response.status(status.INTERNAL_SERVER_ERROR).json({ error: err });
    }
    response.json(result);
  });
});

app.listen(port);
<|endoftext|>


<commit_before>({
    baseUrl: "src",
    out: "test-bundle.js",
    name: "patterns",

    paths: {

        // Externals
        "jquery": "bower_components/jquery/jquery",
        "logging": "bower_components/logging/src/logging",
        "jquery.form": "bower_components/jquery-form/jquery.form",
        "jquery.anythingslider": "bower_components/AnythingSlider/js/jquery.anythingslider",
        "jcrop": "bower_components/jcrop/js/jquery.Jcrop",
        "klass": "bower_components/klass/src/klass",
        "photoswipe": "legacy/photoswipe",
        "parsley": "bower_components/parsleyjs/parsley",
        "parsley.extend": "bower_components/parsleyjs/parsley.extend",
        "patternslib.slides": "bower_components/slides/src/slides",
        "modernizr": "bower_components/modernizr/modernizr",
        "less": "bower_components/less.js/dist/less-1.6.2",
        "prefixfree": "bower_components/prefixfree/prefixfree.min",
        "Markdown.Converter": "legacy/Markdown.Converter",
        "Markdown.Extra": "legacy/Markdown.Extra",
        "Markdown.Sanitizer": "legacy/Markdown.Sanitizer",
        "imagesloaded":  "bower_components/imagesloaded/imagesloaded",
        "eventEmitter/EventEmitter": "bower_components/eventEmitter/EventEmitter",
        "eventie/eventie": "bower_components/eventie/eventie",
        "select2": "bower_components/select2/select2.min",
        "jquery.chosen": "bower_components/chosen/chosen/chosen.jquery",
        "jquery.fullcalendar": "bower_components/fullcalendar/fullcalendar.min",
        "jquery.fullcalendar.dnd": "bower_components/fullcalendar/lib/jquery-ui.custom.min",
        "jquery.placeholder": "bower_components/jquery-placeholder/jquery.placeholder.min",
        "jquery.textchange": "bower_components/jquery-textchange/jquery.textchange",
        "tinymce": "bower_components/jquery.tinymce/jscripts/tiny_mce/jquery.tinymce",
        "spectrum": "bower_components/spectrum/spectrum",

        // Core
        "pat-utils": "core/utils",
        "pat-compat": "core/compat",
        "pat-jquery-ext": "core/jquery-ext",
        "pat-logger": "core/logger",
        "pat-parser": "core/parser",
        "pat-remove": "core/remove",
        "pat-url": "core/url",
        "pat-store": "core/store",
        "pat-registry": "core/registry",
        "pat-htmlparser": "lib/htmlparser",
        "pat-depends_parse": "lib/depends_parse",
        "pat-dependshandler": "lib/dependshandler",
        "pat-input-change-events": "lib/input-change-events",

        // Patterns
        "patterns": "patterns",
        "pat-ajax": "pat/ajax",
        "pat-autofocus": "pat/autofocus",
        "pat-autoscale": "pat/autoscale",
        "pat-autosubmit": "pat/autosubmit",
        "pat-autosuggest": "pat/autosuggest",
        "pat-breadcrumbs": "pat/breadcrumbs",
        "pat-bumper": "pat/bumper",
        "pat-carousel": "pat/carousel",
        "pat-checkedflag": "pat/checkedflag",
        "pat-checklist": "pat/checklist",
        "pat-chosen": "pat/chosen",
        "pat-collapsible": "pat/collapsible",
        "pat-colour-picket": "pat/colour-picker",
        "pat-depends": "pat/depends",
        "pat-edit-tinymce": "pat/edit-tinymce",
        "pat-equaliser": "pat/equaliser",
        "pat-expandable": "pat/expandable",
        "pat-focus": "pat/focus",
        "pat-formstate": "pat/form-state",
        "pat-forward": "pat/forward",
        "pat-fullcalendar": "pat/fullcalendar",
        "pat-gallery": "pat/gallery",
        "pat-image-crop": "pat/image-crop",
        "pat-inject": "pat/inject",
        "pat-legend": "pat/legend",
        "pat-markdown": "pat/markdown",
        "pat-menu": "pat/menu",
        "pat-modal": "pat/modal",
        "pat-navigation": "pat/navigation",
        "pat-notification": "pat/notification",
        "pat-placeholder": "pat/placeholder",
        "pat-selectbox": "pat/selectbox",
        "pat-skeleton": "pat/skeleton",
        "pat-slides": "pat/slides",
        "pat-slideshow-builder": "pat/slideshow-builder",
        "pat-sortable": "pat/sortable",
        "pat-stacks": "pat/stacks",
        "pat-subform": "pat/subform",
        "pat-switch": "pat/switch",
        "pat-toggle": "pat/toggle",
        "pat-tooltip": "pat/tooltip",
        "pat-validate": "pat/validate",
        "pat-zoom": "pat/zoom",

        // Calendar pattern
        "moment": "bower_components/moment/moment",
        "moment-timezone": "bower_components/moment-timezone/moment-timezone",
        "pat-calendar": "pat/calendar/calendar",
        "pat-calendar-moment-timezone-data": "pat/calendar/moment-timezone-data"
    },

    shim: {
        "jquery": {
            exports: "jQuery"
        },
        "jquery.fullcalendar.dnd": {
            depends: "jQuery",
        },
        "tinymce": {
            depends: "jquery"
        },
        "photoswipe": {
            depends: "klass",
        }
    },

    optimize: "none"
})
<commit_msg>Only formatting<commit_after>({
    baseUrl: "src",
    out: "test-bundle.js",
    name: "patterns",

    paths: {

        // Externals
        "jquery":                       "bower_components/jquery/jquery",
        "logging":                      "bower_components/logging/src/logging",
        "jquery.form":                  "bower_components/jquery-form/jquery.form",
        "jquery.anythingslider":        "bower_components/AnythingSlider/js/jquery.anythingslider",
        "jcrop":                        "bower_components/jcrop/js/jquery.Jcrop",
        "klass":                        "bower_components/klass/src/klass",
        "photoswipe":                   "legacy/photoswipe",
        "parsley":                      "bower_components/parsleyjs/parsley",
        "parsley.extend":               "bower_components/parsleyjs/parsley.extend",
        "patternslib.slides":           "bower_components/slides/src/slides",
        "modernizr":                    "bower_components/modernizr/modernizr",
        "less":                         "bower_components/less.js/dist/less-1.6.2",
        "prefixfree":                   "bower_components/prefixfree/prefixfree.min",
        "Markdown.Converter":           "legacy/Markdown.Converter",
        "Markdown.Extra":               "legacy/Markdown.Extra",
        "Markdown.Sanitizer":           "legacy/Markdown.Sanitizer",
        "imagesloaded":                 "bower_components/imagesloaded/imagesloaded",
        "eventEmitter/EventEmitter":    "bower_components/eventEmitter/EventEmitter",
        "eventie/eventie":              "bower_components/eventie/eventie",
        "select2":                      "bower_components/select2/select2.min",
        "jquery.chosen":                "bower_components/chosen/chosen/chosen.jquery",
        "jquery.fullcalendar":          "bower_components/fullcalendar/fullcalendar.min",
        "jquery.fullcalendar.dnd":      "bower_components/fullcalendar/lib/jquery-ui.custom.min",
        "jquery.placeholder":           "bower_components/jquery-placeholder/jquery.placeholder.min",
        "jquery.textchange":            "bower_components/jquery-textchange/jquery.textchange",
        "tinymce":                      "bower_components/jquery.tinymce/jscripts/tiny_mce/jquery.tinymce",
        "spectrum":                     "bower_components/spectrum/spectrum",

        // Core
        "pat-utils": "core/utils",
        "pat-compat": "core/compat",
        "pat-jquery-ext": "core/jquery-ext",
        "pat-logger": "core/logger",
        "pat-parser": "core/parser",
        "pat-remove": "core/remove",
        "pat-url": "core/url",
        "pat-store": "core/store",
        "pat-registry": "core/registry",
        "pat-htmlparser": "lib/htmlparser",
        "pat-depends_parse": "lib/depends_parse",
        "pat-dependshandler": "lib/dependshandler",
        "pat-input-change-events": "lib/input-change-events",

        // Patterns
        "patterns": "patterns",
        "pat-ajax": "pat/ajax",
        "pat-autofocus": "pat/autofocus",
        "pat-autoscale": "pat/autoscale",
        "pat-autosubmit": "pat/autosubmit",
        "pat-autosuggest": "pat/autosuggest",
        "pat-breadcrumbs": "pat/breadcrumbs",
        "pat-bumper": "pat/bumper",
        "pat-carousel": "pat/carousel",
        "pat-checkedflag": "pat/checkedflag",
        "pat-checklist": "pat/checklist",
        "pat-chosen": "pat/chosen",
        "pat-collapsible": "pat/collapsible",
        "pat-colour-picket": "pat/colour-picker",
        "pat-depends": "pat/depends",
        "pat-edit-tinymce": "pat/edit-tinymce",
        "pat-equaliser": "pat/equaliser",
        "pat-expandable": "pat/expandable",
        "pat-focus": "pat/focus",
        "pat-formstate": "pat/form-state",
        "pat-forward": "pat/forward",
        "pat-fullcalendar": "pat/fullcalendar",
        "pat-gallery": "pat/gallery",
        "pat-image-crop": "pat/image-crop",
        "pat-inject": "pat/inject",
        "pat-legend": "pat/legend",
        "pat-markdown": "pat/markdown",
        "pat-menu": "pat/menu",
        "pat-modal": "pat/modal",
        "pat-navigation": "pat/navigation",
        "pat-notification": "pat/notification",
        "pat-placeholder": "pat/placeholder",
        "pat-selectbox": "pat/selectbox",
        "pat-skeleton": "pat/skeleton",
        "pat-slides": "pat/slides",
        "pat-slideshow-builder": "pat/slideshow-builder",
        "pat-sortable": "pat/sortable",
        "pat-stacks": "pat/stacks",
        "pat-subform": "pat/subform",
        "pat-switch": "pat/switch",
        "pat-toggle": "pat/toggle",
        "pat-tooltip": "pat/tooltip",
        "pat-validate": "pat/validate",
        "pat-zoom": "pat/zoom",

        // Calendar pattern
        "moment": "bower_components/moment/moment",
        "moment-timezone": "bower_components/moment-timezone/moment-timezone",
        "pat-calendar": "pat/calendar/calendar",
        "pat-calendar-moment-timezone-data": "pat/calendar/moment-timezone-data"
    },

    shim: {
        "jquery": {
            exports: "jQuery"
        },
        "jquery.fullcalendar.dnd": {
            depends: "jQuery",
        },
        "tinymce": {
            depends: "jquery"
        },
        "photoswipe": {
            depends: "klass",
        }
    },

    optimize: "none"
})
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    less = require('gulp-less'),
    concat = require('gulp-concat'),
    rename = require('gulp-rename'),
    livereload = require('gulp-livereload'),
    uglify = require('gulp-uglify'),
    path = require("path"),
    annotate = require('gulp-ng-annotate'),
    jshint = require('gulp-jshint'),
    jshint_stylish = require('jshint-stylish'),
    bower = require('gulp-bower');

var paths = {
    bootstrap: [
        'app/js/bower_components/bootstrap/dist/js/bootstrap.js'//,
        //'app/js/bootstrap-tree.js'
    ],
    paperwork: [
        'app/js/paperwork/**/*.js'
    ],
    paperworknative: [
        'app/js/paperwork-native.js'
    ],
    angular: [
        'app/js/bower_components/angular/angular.js',
        'app/js/bower_components/angular-resource/angular-resource.js',
        'app/js/bower_components/angular-route/angular-route.js',
        //'app/js/bower_components/angular-sanitize/angular-sanitize.js',
        'app/js/bower_components/angular-animate/angular-animate.js',
        'app/js/bower_components/angular-file-upload/angular-file-upload.js',
        'app/js/bower_components/angular-utf8-base64/angular-utf8-base64.js',
        'app/js/bower_components/angular-ui-bootstrap-bower/ui-bootstrap.js',
        'app/js/bower_components/angular-ui-bootstrap-bower/ui-bootstrap-tpls.js',
        'app/js/bower_components/ngDraggable/ngDraggable.js',
        'app/js/bower_components/angular-loading-bar/src/loading-bar.js',
	'app/js/bower_components/textAngular/src/textAngular-sanitize.js'
    ],
    jQuery: [
        'app/js/bower_components/jquery/dist/jquery.js',
        'app/js/bower_components/jquery-overscroll-fixed/dist/jquery.overscroll.js',
        'app/js/bower_components/jquery.scrollTo/jquery.scrollTo.js'
    ],
    tagsinput: [
        'app/js/bower_components/bootstrap-tagsinput/dist/bootstrap-tagsinput.js',
        'app/js/bower_components/bootstrap-tagsinput/dist/bootstrap-tagsinput-angular.js',
        'app/js/bower_components/typeahead.js/dist/typeahead.bundle.js'
    ],
    libraries: [
        'app/js/freqselector.js',
        'app/js/mathquill.js',
        'app/js/bower_components/retinajs/dist/retina.js'
    ],
    ie9compat: [
        'app/js/bower_components/html5shiv/dist/html5shiv.js',
        'app/js/bower_components/respond/dest/respond.src.js',
        'app/js/bower_components/placeholders/dist/placeholders.min.js'
    ],
    ie11compat: [
        'app/js/bower_components/bootstrap3-ie10-viewport-bug-workaround/ie10-viewport-bug-workaround.js'
    ],
    output: {
        js: 'public/js',
        css: 'public/css'
    }
};

gulp.task('compileLessBootstrapTheme', function () {
    gulp
        .src('app/less/bootstrap/theme.less')
        .pipe(less({
            paths: ['app/less/bootstrap/']
        }))
        .pipe(rename({
            basename: 'bootstrap-theme.min'
        }))
        .pipe(gulp.dest(paths.output.css))
        .pipe(livereload());
});

gulp.task('compileLessPaperworkThemeV1', function () {
    gulp
        .src('app/less/paperwork-themes/paperwork-v1/paperwork-v1.less')
        .pipe(less({
            paths: ['app/less/bootstrap/', 'app/less/paperwork-themes/paperwork-v1/', 'app/less/font-awesome/']
        }))
        .pipe(rename({
            basename: 'paperwork-v1.min'
        }))
        .pipe(gulp.dest(path.join(paths.output.css, 'themes')))
        .pipe(livereload());
});

gulp.task('moveLoadingBarCSSToPublic', function() {
	gulp
		/* Move CSS file for loading-bar to CSS folder */
		.src('app/js/bower_components/angular-loading-bar/src/loading-bar.css')
		.pipe(gulp.dest(paths.output.css))
		.pipe(livereload());
});

gulp.task('compileLessFreqselector', function() {
	gulp
		.src('app/less/freqselector.less')
		.pipe(less({
			paths: ['app/less/']
		}))
		.pipe(rename({
			basename: 'freqselector.min'
		}))
		.pipe(gulp.dest(paths.output.css))
		.pipe(livereload());
});

gulp.task('compileLessTypeahead', function () {
    gulp
        .src('app/less/typeahead.less')
        .pipe(less({
            paths: ['app/less/']
        }))
        .pipe(rename({
            basename: 'typeahead.min'
        }))
        .pipe(gulp.dest(paths.output.css))
        .pipe(livereload());
});

gulp.task('compileJsBootstrap', function () {
    gulp
        .src(paths.bootstrap)
        .pipe(concat('bootstrap.min.js'))
        .pipe(gulp.dest(paths.output.js))
        .pipe(livereload());
});

gulp.task('compileJsPaperwork', function () {
    gulp
        .src(paths.paperwork)
        .pipe(concat('paperwork.min.js'))
        .pipe(annotate())
        .pipe(gulp.dest(paths.output.js))
        .pipe(livereload());
});

gulp.task('compileJsPaperworkNative', function () {
    gulp
        .src(paths.paperworknative)
        .pipe(concat('paperwork-native.min.js'))
        .pipe(annotate())
        .pipe(gulp.dest(paths.output.js))
        .pipe(livereload());
});

gulp.task('compileJsAngular', function () {
    gulp
        .src(paths.angular)
        .pipe(concat('angular.min.js'))
        .pipe(gulp.dest(paths.output.js))
        .pipe(livereload());
});

gulp.task('compileJsJquery', function () {
    gulp
        .src(paths.jQuery)
        .pipe(concat('jquery.min.js'))
        .pipe(gulp.dest(paths.output.js))
        .pipe(livereload());
});

gulp.task('compileJsTagsinput', function () {
    gulp
        .src(paths.tagsinput)
        .pipe(concat('tagsinput.min.js'))
        .pipe(gulp.dest(paths.output.js))
        .pipe(livereload());
});

gulp.task('compileJsLibraries', function () {
    gulp
        .src(paths.libraries)
        .pipe(concat('libraries.min.js'))
        .pipe(gulp.dest(paths.output.js))
        .pipe(livereload());
});

gulp.task('compileJsLtIe9Compat', function () {
    gulp
        .src(paths.ie9compat)
        .pipe(concat('ltie9compat.min.js'))
        .pipe(gulp.dest(paths.output.js))
        .pipe(livereload());
});

gulp.task('compileJsLtIe11Compat', function () {
    gulp
        .src(paths.ie11compat)
        .pipe(concat('ltie11compat.min.js'))
        .pipe(gulp.dest(paths.output.js))
        .pipe(livereload());
});

gulp.task('lint', function () {
    gulp
        .src(paths.paperwork)
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish'))
        .pipe(jshint.reporter('fail'));
});

gulp.task('minifyJs', function () {
    gulp
        .src(path.join(paths.output.js, '*.js'))
        .pipe(uglify())
        .pipe(gulp.dest(paths.output.js));
});

gulp.task('bower', function () {
    return bower().pipe(gulp.dest('js'));
});

gulp.task('bower-update', function () {
    return bower({cmd: 'update'}).pipe(gulp.dest('js'));
});

gulp.task('less', ['compileLessBootstrapTheme', 'compileLessPaperworkThemeV1', 'compileLessFreqselector', 'compileLessTypeahead']);
gulp.task('js', ['compileJsBootstrap', 'compileJsPaperwork', 'compileJsPaperworkNative', 'compileJsAngular', 'compileJsJquery', 'compileJsTagsinput', 'compileJsLibraries', 'compileJsLtIe9Compat', 'compileJsLtIe11Compat']);

gulp.task('default', ['less', 'lint', 'js', 'moveLoadingBarCSSToPublic']);
gulp.task('prod', ['default', 'minifyJs']);

gulp.task('watch', function () {
    livereload.listen();
    gulp.watch('app/less/*.less', ['less']);
    gulp.watch('app/less/bootstrap/*.less', ['less']);
    gulp.watch('app/less/font-fontawesome/*.less', ['less']);
    gulp.watch('app/less/paperwork-themes/paperwork-v1/*.less', ['less']);
    gulp.watch('app/js/**/*.js', ['js']);
    gulp.watch('app/js/bootstrap/*.js', ['compileJsBootstrap']);
    gulp.watch('app/js/paperwork/*.js', ['compileJsPaperwork']);
});
<commit_msg>Fixed path for angular-file-upload Javascript Source<commit_after>var gulp = require('gulp'),
    less = require('gulp-less'),
    concat = require('gulp-concat'),
    rename = require('gulp-rename'),
    livereload = require('gulp-livereload'),
    uglify = require('gulp-uglify'),
    path = require("path"),
    annotate = require('gulp-ng-annotate'),
    jshint = require('gulp-jshint'),
    jshint_stylish = require('jshint-stylish'),
    bower = require('gulp-bower');

var paths = {
    bootstrap: [
        'app/js/bower_components/bootstrap/dist/js/bootstrap.js'//,
        //'app/js/bootstrap-tree.js'
    ],
    paperwork: [
        'app/js/paperwork/**/*.js'
    ],
    paperworknative: [
        'app/js/paperwork-native.js'
    ],
    angular: [
        'app/js/bower_components/angular/angular.js',
        'app/js/bower_components/angular-resource/angular-resource.js',
        'app/js/bower_components/angular-route/angular-route.js',
        //'app/js/bower_components/angular-sanitize/angular-sanitize.js',
        'app/js/bower_components/angular-animate/angular-animate.js',
        'app/js/bower_components/angular-file-upload/src/module.js',
        'app/js/bower_components/angular-utf8-base64/angular-utf8-base64.js',
        'app/js/bower_components/angular-ui-bootstrap-bower/ui-bootstrap.js',
        'app/js/bower_components/angular-ui-bootstrap-bower/ui-bootstrap-tpls.js',
        'app/js/bower_components/ngDraggable/ngDraggable.js',
        'app/js/bower_components/angular-loading-bar/src/loading-bar.js',
	'app/js/bower_components/textAngular/src/textAngular-sanitize.js'
    ],
    jQuery: [
        'app/js/bower_components/jquery/dist/jquery.js',
        'app/js/bower_components/jquery-overscroll-fixed/dist/jquery.overscroll.js',
        'app/js/bower_components/jquery.scrollTo/jquery.scrollTo.js'
    ],
    tagsinput: [
        'app/js/bower_components/bootstrap-tagsinput/dist/bootstrap-tagsinput.js',
        'app/js/bower_components/bootstrap-tagsinput/dist/bootstrap-tagsinput-angular.js',
        'app/js/bower_components/typeahead.js/dist/typeahead.bundle.js'
    ],
    libraries: [
        'app/js/freqselector.js',
        'app/js/mathquill.js',
        'app/js/bower_components/retinajs/dist/retina.js'
    ],
    ie9compat: [
        'app/js/bower_components/html5shiv/dist/html5shiv.js',
        'app/js/bower_components/respond/dest/respond.src.js',
        'app/js/bower_components/placeholders/dist/placeholders.min.js'
    ],
    ie11compat: [
        'app/js/bower_components/bootstrap3-ie10-viewport-bug-workaround/ie10-viewport-bug-workaround.js'
    ],
    output: {
        js: 'public/js',
        css: 'public/css'
    }
};

gulp.task('compileLessBootstrapTheme', function () {
    gulp
        .src('app/less/bootstrap/theme.less')
        .pipe(less({
            paths: ['app/less/bootstrap/']
        }))
        .pipe(rename({
            basename: 'bootstrap-theme.min'
        }))
        .pipe(gulp.dest(paths.output.css))
        .pipe(livereload());
});

gulp.task('compileLessPaperworkThemeV1', function () {
    gulp
        .src('app/less/paperwork-themes/paperwork-v1/paperwork-v1.less')
        .pipe(less({
            paths: ['app/less/bootstrap/', 'app/less/paperwork-themes/paperwork-v1/', 'app/less/font-awesome/']
        }))
        .pipe(rename({
            basename: 'paperwork-v1.min'
        }))
        .pipe(gulp.dest(path.join(paths.output.css, 'themes')))
        .pipe(livereload());
});

gulp.task('moveLoadingBarCSSToPublic', function() {
	gulp
		/* Move CSS file for loading-bar to CSS folder */
		.src('app/js/bower_components/angular-loading-bar/src/loading-bar.css')
		.pipe(gulp.dest(paths.output.css))
		.pipe(livereload());
});

gulp.task('compileLessFreqselector', function() {
	gulp
		.src('app/less/freqselector.less')
		.pipe(less({
			paths: ['app/less/']
		}))
		.pipe(rename({
			basename: 'freqselector.min'
		}))
		.pipe(gulp.dest(paths.output.css))
		.pipe(livereload());
});

gulp.task('compileLessTypeahead', function () {
    gulp
        .src('app/less/typeahead.less')
        .pipe(less({
            paths: ['app/less/']
        }))
        .pipe(rename({
            basename: 'typeahead.min'
        }))
        .pipe(gulp.dest(paths.output.css))
        .pipe(livereload());
});

gulp.task('compileJsBootstrap', function () {
    gulp
        .src(paths.bootstrap)
        .pipe(concat('bootstrap.min.js'))
        .pipe(gulp.dest(paths.output.js))
        .pipe(livereload());
});

gulp.task('compileJsPaperwork', function () {
    gulp
        .src(paths.paperwork)
        .pipe(concat('paperwork.min.js'))
        .pipe(annotate())
        .pipe(gulp.dest(paths.output.js))
        .pipe(livereload());
});

gulp.task('compileJsPaperworkNative', function () {
    gulp
        .src(paths.paperworknative)
        .pipe(concat('paperwork-native.min.js'))
        .pipe(annotate())
        .pipe(gulp.dest(paths.output.js))
        .pipe(livereload());
});

gulp.task('compileJsAngular', function () {
    gulp
        .src(paths.angular)
        .pipe(concat('angular.min.js'))
        .pipe(gulp.dest(paths.output.js))
        .pipe(livereload());
});

gulp.task('compileJsJquery', function () {
    gulp
        .src(paths.jQuery)
        .pipe(concat('jquery.min.js'))
        .pipe(gulp.dest(paths.output.js))
        .pipe(livereload());
});

gulp.task('compileJsTagsinput', function () {
    gulp
        .src(paths.tagsinput)
        .pipe(concat('tagsinput.min.js'))
        .pipe(gulp.dest(paths.output.js))
        .pipe(livereload());
});

gulp.task('compileJsLibraries', function () {
    gulp
        .src(paths.libraries)
        .pipe(concat('libraries.min.js'))
        .pipe(gulp.dest(paths.output.js))
        .pipe(livereload());
});

gulp.task('compileJsLtIe9Compat', function () {
    gulp
        .src(paths.ie9compat)
        .pipe(concat('ltie9compat.min.js'))
        .pipe(gulp.dest(paths.output.js))
        .pipe(livereload());
});

gulp.task('compileJsLtIe11Compat', function () {
    gulp
        .src(paths.ie11compat)
        .pipe(concat('ltie11compat.min.js'))
        .pipe(gulp.dest(paths.output.js))
        .pipe(livereload());
});

gulp.task('lint', function () {
    gulp
        .src(paths.paperwork)
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish'))
        .pipe(jshint.reporter('fail'));
});

gulp.task('minifyJs', function () {
    gulp
        .src(path.join(paths.output.js, '*.js'))
        .pipe(uglify())
        .pipe(gulp.dest(paths.output.js));
});

gulp.task('bower', function () {
    return bower().pipe(gulp.dest('js'));
});

gulp.task('bower-update', function () {
    return bower({cmd: 'update'}).pipe(gulp.dest('js'));
});

gulp.task('less', ['compileLessBootstrapTheme', 'compileLessPaperworkThemeV1', 'compileLessFreqselector', 'compileLessTypeahead']);
gulp.task('js', ['compileJsBootstrap', 'compileJsPaperwork', 'compileJsPaperworkNative', 'compileJsAngular', 'compileJsJquery', 'compileJsTagsinput', 'compileJsLibraries', 'compileJsLtIe9Compat', 'compileJsLtIe11Compat']);

gulp.task('default', ['less', 'lint', 'js', 'moveLoadingBarCSSToPublic']);
gulp.task('prod', ['default', 'minifyJs']);

gulp.task('watch', function () {
    livereload.listen();
    gulp.watch('app/less/*.less', ['less']);
    gulp.watch('app/less/bootstrap/*.less', ['less']);
    gulp.watch('app/less/font-fontawesome/*.less', ['less']);
    gulp.watch('app/less/paperwork-themes/paperwork-v1/*.less', ['less']);
    gulp.watch('app/js/**/*.js', ['js']);
    gulp.watch('app/js/bootstrap/*.js', ['compileJsBootstrap']);
    gulp.watch('app/js/paperwork/*.js', ['compileJsPaperwork']);
});
<|endoftext|>


<commit_before>'use strict';

var Client = {};
Client.request = function(resource, args) {
  args = args || {};
  args.credentials = 'same-origin'
  args.headers = args.headers || {};
  args.headers['Accept'] = 'application/json';

  if( args.method && args.method === 'POST') {
    args.headers['Content-Type'] = 'application/json';

    if(args.data) {
      if( typeof(args.data) !== "string") {
        args.data = JSON.stringify(args.data)
      }
      args.body = args.data
      delete args.data
    }
  }

  return fetch(`/api/${resource}`, args)
    .then(handleRequestErrors)
    .then(parseJSON)
    .then(parseData)
}

function parseJSON(r) {
  return r.json()
}

function handleRequestErrors(r) {
    if (!r.ok) {
        throw new Error(r.statusText);
    }
    return r;
}

function parseData(d) {
  if(d.Error) {
    throw new Error(d.Error)
  }

  return d.Data
}

export default Client
<commit_msg>use status code as error message<commit_after>'use strict';

var Client = {};
Client.request = function(resource, args) {
  args = args || {};
  args.credentials = 'same-origin'
  args.headers = args.headers || {};
  args.headers['Accept'] = 'application/json';

  if( args.method && args.method === 'POST') {
    args.headers['Content-Type'] = 'application/json';

    if(args.data) {
      if( typeof(args.data) !== "string") {
        args.data = JSON.stringify(args.data)
      }
      args.body = args.data
      delete args.data
    }
  }

  return fetch(`/api/${resource}`, args)
    .then(handleRequestErrors)
    .then(parseJSON)
    .then(parseData)
}

function parseJSON(r) {
  return r.json()
}

function handleRequestErrors(r) {
    if (!r.ok) {
      throw new Error(r.status);
    }
    return r;
}

function parseData(d) {
  if(d.Error) {
    throw new Error(d.Error)
  }

  return d.Data
}

export default Client
<|endoftext|>