<commit_before>import fetch from 'isomorphic-fetch';

const checkStatus = (response) => {
  if (response.status >= 200 && response.status < 300) {
    return response;
  } else {
    var error = new Error(response.statusText);
    error.response = response;
    throw error;
  }
};

const failingFetch = (url) =>
  fetch(url)
    .catch(error => {
      throw new Error('Network error, check your internet connection');
    })
    .then(checkStatus)
    .then(response => response.json());

export default failingFetch;
<commit_msg>End full sentence error messages with a period, again<commit_after>import fetch from 'isomorphic-fetch';

const checkStatus = (response) => {
  if (response.status >= 200 && response.status < 300) {
    return response;
  } else {
    var error = new Error(response.statusText);
    error.response = response;
    throw error;
  }
};

const failingFetch = (url) =>
  fetch(url)
    .catch(error => {
      throw new Error('Network error, check your internet connection.');
    })
    .then(checkStatus)
    .then(response => response.json());

export default failingFetch;
<|endoftext|>


<commit_before>/* eslint-disable no-unused-vars, no-constant-condition */

import test from 'tape'
import { createStore, applyMiddleware } from 'redux'
import sagaMiddleware from '../src'
import { take, put, fork, join, call, race, cancel, actionChannel } from '../src/effects'
import { channel, buffers, END } from '../src'

test('action channel', assert => {
  assert.plan(1)

  const actual = []
  const middleware = sagaMiddleware()
  const store = applyMiddleware(middleware)(createStore)(() => {})

  function* saga() {
    const chan = yield actionChannel('ACTION')
    while (true) {
      const { payload } = yield take(chan)
      actual.push(payload)
      yield Promise.resolve() // block
    }
  }

  middleware
    .run(saga)
    .done.then(() => {
      assert.deepEqual(
        actual,
        [1, 2, 3],
        'Sagas must take consecutive actions dispatched synchronously on an action channel even if it performs blocking calls',
      )
      assert.end()
    })
    .catch(err => assert.fail(err))

  for (var i = 0; i < 3; i++) {
    store.dispatch({ type: 'ACTION', payload: i + 1 })
  }
  store.dispatch(END)
})

test('channel: watcher + max workers', assert => {
  assert.plan(1)

  const actual = []
  const middleware = sagaMiddleware()
  const store = applyMiddleware(middleware)(createStore)(() => {})

  function* saga() {
    const chan = channel()
    try {
      for (var i = 0; i < 3; i++) {
        yield fork(worker, i + 1, chan)
      }
      while (true) {
        const { payload } = yield take('ACTION')
        yield put(chan, payload)
      }
    } finally {
      chan.close()
    }
  }

  function* worker(idx, chan) {
    let count = 0
    while (true) {
      actual.push([idx, yield take(chan)])
      // 1st worker will 'sleep' after taking 2 messages on the 1st round
      if (idx === 1 && ++count === 2) {
        yield Promise.resolve()
      }
    }
  }

  middleware.run(saga).done.then(() => {
    assert.deepEqual(
      actual,
      [[1, 1], [2, 2], [3, 3], [1, 4], [2, 5], [3, 6], [2, 7], [3, 8], [2, 9], [3, 10]],
      'Saga must dispatch to free workers via channel',
    )
    assert.end()
  })

  for (var i = 0; i < 10; i++) {
    store.dispatch({ type: 'ACTION', payload: i + 1, round: 1 })
  }

  store.dispatch(END)
})
<commit_msg>Adding actionChannel generator test<commit_after>/* eslint-disable no-unused-vars, no-constant-condition */

import test from 'tape'
import { createStore, applyMiddleware } from 'redux'
import sagaMiddleware from '../src'
import { take, put, fork, join, call, race, cancel, actionChannel } from '../src/effects'
import { channel, buffers, END } from '../src'

test('action channel', assert => {
  assert.plan(1)

  const actual = []
  const middleware = sagaMiddleware()
  const store = applyMiddleware(middleware)(createStore)(() => {})

  function* saga() {
    const chan = yield actionChannel('ACTION')
    while (true) {
      const { payload } = yield take(chan)
      actual.push(payload)
      yield Promise.resolve() // block
    }
  }

  middleware
    .run(saga)
    .done.then(() => {
      assert.deepEqual(
        actual,
        [1, 2, 3],
        'Sagas must take consecutive actions dispatched synchronously on an action channel even if it performs blocking calls',
      )
      assert.end()
    })
    .catch(err => assert.fail(err))

  for (var i = 0; i < 3; i++) {
    store.dispatch({ type: 'ACTION', payload: i + 1 })
  }
  store.dispatch(END)
})

test('action channel generator', assert => {
  assert.plan(2)

  function* saga() {
    const chan = yield actionChannel('ACTION')
    while (true) {
      const { payload } = yield take(chan)
      yield Promise.resolve() // block
    }
  }

  let gen = saga()
  let chan = actionChannel('ACTION')
  assert.deepEqual(gen.next().value, chan)

  const mockChannel = channel()

  assert.deepEqual(gen.next(mockChannel).value, take(mockChannel))
})

test('channel: watcher + max workers', assert => {
  assert.plan(1)

  const actual = []
  const middleware = sagaMiddleware()
  const store = applyMiddleware(middleware)(createStore)(() => {})

  function* saga() {
    const chan = channel()
    try {
      for (var i = 0; i < 3; i++) {
        yield fork(worker, i + 1, chan)
      }
      while (true) {
        const { payload } = yield take('ACTION')
        yield put(chan, payload)
      }
    } finally {
      chan.close()
    }
  }

  function* worker(idx, chan) {
    let count = 0
    while (true) {
      actual.push([idx, yield take(chan)])
      // 1st worker will 'sleep' after taking 2 messages on the 1st round
      if (idx === 1 && ++count === 2) {
        yield Promise.resolve()
      }
    }
  }

  middleware.run(saga).done.then(() => {
    assert.deepEqual(
      actual,
      [[1, 1], [2, 2], [3, 3], [1, 4], [2, 5], [3, 6], [2, 7], [3, 8], [2, 9], [3, 10]],
      'Saga must dispatch to free workers via channel',
    )
    assert.end()
  })

  for (var i = 0; i < 10; i++) {
    store.dispatch({ type: 'ACTION', payload: i + 1, round: 1 })
  }

  store.dispatch(END)
})
<|endoftext|>


<commit_before>(function($){"usestrict";$(document).ready(function(){});}(jQuery));<commit_msg>Delete index.min.js<commit_after><|endoftext|>


<commit_before>export default {
  title: 'c-theme',
  description: ['Theme component will set the theme styling for all other components by default. You can set the theme name attribute to set a theme. Put the theme component anywhere in your page inside the body tag. We use Redux to store the theme value in a global store. The other components then subscribed to the store and will be updated for any changes.',
    'Example use:',
    '
<c-theme name="scania"></c-theme>
',
    '
Bootstrap custom events
',
    'All custom events for Bootstrap plugins are available globally in the CorporateUi.$ object. For example, this is how to trigger Bootstrap modal event:',
    '
CorporateUi.$(\'#exampleModal\').modal();
'],
};
<commit_msg>Changed double quotes to singe quote on code example<commit_after>export default {
  title: 'c-theme',
  description: ['Theme component will set the theme styling for all other components by default. You can set the theme name attribute to set a theme. Put the theme component anywhere in your page inside the body tag. We use Redux to store the theme value in a global store. The other components then subscribed to the store and will be updated for any changes.',
    'Example use:',
    '
<c-theme name=\'scania\'></c-theme>
',
    '
Bootstrap custom events
',
    'All custom events for Bootstrap plugins are available globally in the CorporateUi.$ object. For example, this is how to trigger Bootstrap modal event:',
    '
CorporateUi.$(\'#exampleModal\').modal();
'],
};
<|endoftext|>


<commit_before>var elmDebugger = {
  restart: function() {},
  pause: function() {},
  kontinue: function() {},
  getMaxSteps: function() { return 0; },
  stepTo: function(i) {},
  getPaused: function() { return false; },
  getHotSwapState: function() { return null; },
  watchTracker: { frames:[{}] }
};

var mainHandle = {};
var debuggerHandle = {};
var createdSocket = false;
var filePath;

var elmPauseState = false;
var elmPermitHotswaps = true;

var ELM_MAIN_ID = "elmMain";
var ELM_DEBUGGER_ID = "elmToolPanel";
var ELM_DARK_GREY = "#4A4A4A";
var ELM_LIGHT_GREY = "#E4E4E4";

function createMainElement() {
  var mainDiv = document.createElement("div");
  mainDiv.id = ELM_MAIN_ID;
  mainDiv.style.width = "100%";
  mainDiv.style.height = "100%";
  return mainDiv;
}

function createDebuggingElement() {
  var debuggingPanelExpanded = true;
  var debuggerWidth = 275;

  var debugTools = document.createElement("div");
  debugTools.id = ELM_DEBUGGER_ID;

  var debuggerDiv = document.createElement("div");
  debuggerDiv.id = "elmDebugger";
  debuggerDiv.style.overflow = "hidden";

  // Create and style the panel
  debugTools.style.background = ELM_DARK_GREY;
  debugTools.style.width = debuggerWidth + "px";
  debugTools.style.height = "100%";
  debugTools.style.position = "absolute";
  debugTools.style.top = "0px";
  debugTools.style.left = window.innerWidth - debuggerWidth + "px";
  debugTools.style.transitionDuration = "0.3s";
  debugTools.style.opacity = 0.97;

  // Create and style the button
  var debugTab = document.createElement("div");
  debugTab.id = "debugtoggle";
  debugTab.style.position = "absolute";
  debugTab.style.width = "15px";
  debugTab.style.height = "30px";
  debugTab.style.top = window.innerHeight / 2 + "px";
  debugTab.style.left = "-15px";
  debugTab.style.borderTopLeftRadius = "3px";
  debugTab.style.borderBottomLeftRadius = "3px";
  debugTab.style.background = ELM_DARK_GREY;

  // Wire the button
  debugTab.onclick = function() {
    var toolPanel = document.getElementById("elmToolPanel");
    if (debuggingPanelExpanded){
      toolPanel.style.left = window.innerWidth + "px";
      toolPanel.style.width = "0px";
      debuggingPanelExpanded = false;
    } else {
      toolPanel.style.left = window.innerWidth - debuggerWidth + "px";
      toolPanel.style.width = debuggerWidth + "px";
      debuggingPanelExpanded = true;
    }
  }

  debugTools.appendChild(debugTab);
  debugTools.appendChild(debuggerDiv);
  return debugTools;
}

Elm.debugFullscreen = function(module, moduleFile, hotSwapState /* =undefined */) {
  filePath = moduleFile;
  var elmMain = createMainElement();
  document.body.appendChild(elmMain);
  initDebugger();
  mainHandle = Elm.embed(Elm.debuggerAttach(module, hotSwapState), elmMain);
  return mainHandle;
}

function initDebugger() {
  function scrubber(position) {
    if (elmDebugger.getPaused()) {
      elmDebugger.stepTo(position);
      sendWatches(position);
    }
  }

  function elmPauser(doPause) {
    if (doPause) {
      elmDebugger.pause();
    } else {
      elmDebugger.kontinue();
    }
    elmPauseState = doPause;
  }

  function elmRestart() {
    elmDebugger.restart();
    sendWatches(0);
  }

  function elmHotswap(permitHotswaps) {
    elmPermitHotswaps = permitHotswaps;
  }

  var debugTools = createDebuggingElement();
  document.body.appendChild(debugTools);
  var debuggerDiv = document.getElementById("elmDebugger");

  debuggerHandle = Elm.embed(Elm.DebuggerInterface, debuggerDiv,
      { eventCounter: 0,
        watches: ""
      });
  debuggerHandle.ports.scrubTo.subscribe(scrubber);
  debuggerHandle.ports.pause.subscribe(elmPauser);
  debuggerHandle.ports.restart.subscribe(elmRestart);
  debuggerHandle.ports.permitHotswap.subscribe(elmHotswap);
}

parent.window.addEventListener("message", function(e) {
  if (e.data === "elmDebuggerInit") {
    elmDebugger = parent.Elm.Debugger;
    if (!createdSocket) {
      initSocket();
    }
  } else if (e.data === "elmNotify") {
    var currentPosition = elmDebugger.getMaxSteps();
    debuggerHandle.ports.eventCounter.send(currentPosition);
    sendWatches(currentPosition);
  }
}, false);

function sendWatches(position) {
  function censor(key, value) {
    if (key === "_") {
      return undefined;
    }
    return value;
  }

  var watchAtPoint = elmDebugger.watchTracker.frames[position];
  var jsonWatch = JSON.stringify(watchAtPoint, censor, "  ");
  // Thanks http://stackoverflow.com/questions/11233498/json-stringify-without-quotes-on-properties
  jsonWatch.replace(/\\"/g,"\uFFFF"); // U+FFFF
  jsonWatch = jsonWatch.replace(/\"([^"]+)\":/g,"$1:").replace(/\uFFFF/g,"\\\"");
  jsonWatch = jsonWatch.substr(2, jsonWatch.length - 4); // Removes outer {}
  debuggerHandle.ports.watches.send(jsonWatch);
}

function initSocket() {
  createdSocket = true;
  // "/todo.html" => "todo.elm"
  filePath = filePath || window.location.pathname.substr(1).split(".")[0] + ".elm";
  var socketLocation = "ws://" + window.location.host + "/socket?file=" + filePath;
  var serverConnection = new WebSocket(socketLocation);
  serverConnection.onmessage = function(event) {
    if (elmPermitHotswaps) {
      hotSwap(event.data);
    }
  };
}

function hotSwap(raw) {
  var debuggerDiv = document.getElementById(ELM_DEBUGGER_ID);
  var result = JSON.parse(raw);
  var js = result.success;
  var errorMessage = result.error;
  var error = document.getElementById('ErrorMessage');
  if (error) {
      error.parentNode.removeChild(error);
  }
  if (js) {
      var error = document.getElementById('ErrorMessage');
      if (error) {
          error.parentNode.removeChild(error);
      }
      window.eval(js);
      var moduleStr = js.match(/(Elm\..+)\ =\ \1/)[1];
      var module = window.eval(moduleStr);
      if (Elm.Debugger) {
          var debuggerState = Elm.Debugger.getHotSwapState();
          mainHandle.dispose();
          Elm.Debugger.dispose();

          var newMainNode = createMainElement();
          debuggerDiv.parentElement.insertBefore(newMainNode,debuggerDiv);

          var wrappedModule = Elm.debuggerAttach(module, debuggerState);
          mainHandle = Elm.embed(wrappedModule, newMainNode);
      }
      else {
          mainHandle = mainHandle.swap(module);
      }
  } else if (errorMessage) {
      var errorNode = document.createElement("pre");
      errorNode.id = "ErrorMessage";
      errorNode.innerHTML = errorMessage;
      errorNode.style.zindex = 1;
      errorNode.style.position = "absolute";
      errorNode.style.top = "0px";
      errorNode.style.background = ELM_LIGHT_GREY;

      var mainNode = document.getElementById(ELM_MAIN_ID);
      mainNode.parentElement.appendChild(errorNode);
  }
}
<commit_msg>4 space indent<commit_after>var elmDebugger = {
    restart: function() {},
    pause: function() {},
    kontinue: function() {},
    getMaxSteps: function() { return 0; },
    stepTo: function(i) {},
    getPaused: function() { return false; },
    getHotSwapState: function() { return null; },
    watchTracker: { frames:[{}] }
};

var mainHandle = {};
var debuggerHandle = {};
var createdSocket = false;
var filePath;

var elmPauseState = false;
var elmPermitHotswaps = true;

var ELM_MAIN_ID = "elmMain";
var ELM_DEBUGGER_ID = "elmToolPanel";
var ELM_DARK_GREY = "#4A4A4A";
var ELM_LIGHT_GREY = "#E4E4E4";

function createMainElement() {
    var mainDiv = document.createElement("div");
    mainDiv.id = ELM_MAIN_ID;
    mainDiv.style.width = "100%";
    mainDiv.style.height = "100%";
    return mainDiv;
}

function createDebuggingElement() {
    var debuggingPanelExpanded = true;
    var debuggerWidth = 275;

    var debugTools = document.createElement("div");
    debugTools.id = ELM_DEBUGGER_ID;

    var debuggerDiv = document.createElement("div");
    debuggerDiv.id = "elmDebugger";
    debuggerDiv.style.overflow = "hidden";

    // Create and style the panel
    debugTools.style.background = ELM_DARK_GREY;
    debugTools.style.width = debuggerWidth + "px";
    debugTools.style.height = "100%";
    debugTools.style.position = "absolute";
    debugTools.style.top = "0px";
    debugTools.style.left = window.innerWidth - debuggerWidth + "px";
    debugTools.style.transitionDuration = "0.3s";
    debugTools.style.opacity = 0.97;

    // Create and style the button
    var debugTab = document.createElement("div");
    debugTab.id = "debugtoggle";
    debugTab.style.position = "absolute";
    debugTab.style.width = "15px";
    debugTab.style.height = "30px";
    debugTab.style.top = window.innerHeight / 2 + "px";
    debugTab.style.left = "-15px";
    debugTab.style.borderTopLeftRadius = "3px";
    debugTab.style.borderBottomLeftRadius = "3px";
    debugTab.style.background = ELM_DARK_GREY;

    // Wire the button
    debugTab.onclick = function() {
        var toolPanel = document.getElementById("elmToolPanel");
        if (debuggingPanelExpanded){
            toolPanel.style.left = window.innerWidth + "px";
            toolPanel.style.width = "0px";
            debuggingPanelExpanded = false;
        } else {
            toolPanel.style.left = window.innerWidth - debuggerWidth + "px";
            toolPanel.style.width = debuggerWidth + "px";
            debuggingPanelExpanded = true;
        }
    }

    debugTools.appendChild(debugTab);
    debugTools.appendChild(debuggerDiv);
    return debugTools;
}

Elm.debugFullscreen = function(module, moduleFile, hotSwapState /* =undefined */) {
    filePath = moduleFile;
    var elmMain = createMainElement();
    document.body.appendChild(elmMain);
    initDebugger();
    mainHandle = Elm.embed(Elm.debuggerAttach(module, hotSwapState), elmMain);
    return mainHandle;
}

function initDebugger() {
    function scrubber(position) {
        if (elmDebugger.getPaused()) {
            elmDebugger.stepTo(position);
            sendWatches(position);
        }
    }

    function elmPauser(doPause) {
        if (doPause) {
          elmDebugger.pause();
        } else {
            elmDebugger.kontinue();
        }
        elmPauseState = doPause;
    }

    function elmRestart() {
        elmDebugger.restart();
        sendWatches(0);
    }

    function elmHotswap(permitHotswaps) {
        elmPermitHotswaps = permitHotswaps;
    }

    var debugTools = createDebuggingElement();
    document.body.appendChild(debugTools);
    var debuggerDiv = document.getElementById("elmDebugger");

    debuggerHandle = Elm.embed(Elm.DebuggerInterface, debuggerDiv,
        { eventCounter: 0,
          watches: ""
        });
    debuggerHandle.ports.scrubTo.subscribe(scrubber);
    debuggerHandle.ports.pause.subscribe(elmPauser);
    debuggerHandle.ports.restart.subscribe(elmRestart);
    debuggerHandle.ports.permitHotswap.subscribe(elmHotswap);
}

parent.window.addEventListener("message", function(e) {
    if (e.data === "elmDebuggerInit") {
        elmDebugger = parent.Elm.Debugger;
        if (!createdSocket) {
            initSocket();
        }
    } else if (e.data === "elmNotify") {
        var currentPosition = elmDebugger.getMaxSteps();
        debuggerHandle.ports.eventCounter.send(currentPosition);
        sendWatches(currentPosition);
    }
}, false);

function sendWatches(position) {
    function censor(key, value) {
        if (key === "_") {
            return undefined;
        }
        return value;
    }

    var watchAtPoint = elmDebugger.watchTracker.frames[position];
    var jsonWatch = JSON.stringify(watchAtPoint, censor, "  ");
    // Thanks http://stackoverflow.com/questions/11233498/json-stringify-without-quotes-on-properties
    jsonWatch.replace(/\\"/g,"\uFFFF"); // U+FFFF
    jsonWatch = jsonWatch.replace(/\"([^"]+)\":/g,"$1:").replace(/\uFFFF/g,"\\\"");
    jsonWatch = jsonWatch.substr(2, jsonWatch.length - 4); // Removes outer {}
    debuggerHandle.ports.watches.send(jsonWatch);
}

function initSocket() {
    createdSocket = true;
    // "/todo.html" => "todo.elm"
    filePath = filePath || window.location.pathname.substr(1).split(".")[0] + ".elm";
    var socketLocation = "ws://" + window.location.host + "/socket?file=" + filePath;
    var serverConnection = new WebSocket(socketLocation);
    serverConnection.onmessage = function(event) {
        if (elmPermitHotswaps) {
            hotSwap(event.data);
        }
    };
}

function hotSwap(raw) {
    var debuggerDiv = document.getElementById(ELM_DEBUGGER_ID);
    var result = JSON.parse(raw);
    var js = result.success;
    var errorMessage = result.error;
    var error = document.getElementById('ErrorMessage');
    if (error) {
        error.parentNode.removeChild(error);
    }
    if (js) {
        var error = document.getElementById('ErrorMessage');
        if (error) {
            error.parentNode.removeChild(error);
        }
        window.eval(js);
        var moduleStr = js.match(/(Elm\..+)\ =\ \1/)[1];
        var module = window.eval(moduleStr);
        if (Elm.Debugger) {
            var debuggerState = Elm.Debugger.getHotSwapState();
            mainHandle.dispose();
            Elm.Debugger.dispose();

            var newMainNode = createMainElement();
            debuggerDiv.parentElement.insertBefore(newMainNode,debuggerDiv);

            var wrappedModule = Elm.debuggerAttach(module, debuggerState);
            mainHandle = Elm.embed(wrappedModule, newMainNode);
        }
        else {
            mainHandle = mainHandle.swap(module);
        }
    } else if (errorMessage) {
        var errorNode = document.createElement("pre");
        errorNode.id = "ErrorMessage";
        errorNode.innerHTML = errorMessage;
        errorNode.style.zindex = 1;
        errorNode.style.position = "absolute";
        errorNode.style.top = "0px";
        errorNode.style.background = ELM_LIGHT_GREY;

        var mainNode = document.getElementById(ELM_MAIN_ID);
        mainNode.parentElement.appendChild(errorNode);
    }
}
<|endoftext|>


<commit_before>'use strict';

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

const Exchange = require ('./base/Exchange');
const { ExchangeError, AuthenticationError } = require ('./base/errors');

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

module.exports = class bigone extends Exchange {

    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'bigone',
            'name': 'BigONE',
            'countries': 'GB',
            'has': {
                'fetchTickers': true,
                'fetchOpenOrders': true,
                'fetchMyTrades': true,
            },
            'urls': {
                'logo': 'https://p14.zdassets.com/hc/settings_assets/2042110/115000083534/FxqlPvZoc8SvIhRfAju5Vg-BigONE.jpg',
                'api': 'https://api.big.one',
                'www': 'https://big.one/',
                'doc': 'https://developer.big.one/',
                'fees': 'https://help.big.one/hc/en-us/articles/115001933374-BigONE-Fee-Policy',
            },
            'api': {
                'public': {
                    'get': [
                        'markets',
                        'markets/{symbol}',
                        'markets/{symbol}/book',
                        'markets/{symbol}/trades',
                        'orders',
                        'orders/{id}',
                        'trades',
                    ],
                },
                'private': {
                    'get': [
                        'accounts',
                        'accounts/{currency}',
                        'withdrawals',
                        'deposits',
                    ],
                    'post': [
                        'orders',
                        'orders/cancel',
                        'withdrawals',
                    ],
                    'delete': [
                        'orders/{id}',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'maker': 0.1 / 100,
                    'taker': 0.1 / 100,
                },
                'funding': {
                    'withdraw': {
                        'BTC': 0.002,
                        'ETH': 0.01,
                        'EOS': 0.01,
                        'ZEC': 0.002,
                        'LTC': 0.01,
                        'QTUM': 0.01,
                        // 'INK': 0.01 QTUM,
                        // 'BOT': 0.01 QTUM,
                        'ETC': 0.01,
                        'GAS': 0.0,
                        'BTS': 1.0,
                        'GXS': 0.1,
                        'BITCNY': 1.0,
                    },
                },
            },
        });
    }

    async fetchMarkets () {
        let markets = await this.publicGetMarkets ();
        let result = [];
        for (let i = 0; i < markets.length; i++) {
            let market = markets[i];
            let id = market['symbol'];
            let base = this.commonCurrencyCode (market['quote']);
            let quote = this.commonCurrencyCode (market['base']);
            let symbol = base + '/' + quote;
            let precision = {
                'amount': 8,
                'price': 8,
            };
            let lot = Math.pow (10, -precision['amount']);
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'active': true,
                'lot': lot,
                'limits': {
                    'amount': {
                        'min': parseInt (market['base_min']),
                        'max': parseInt (market['base_max']),
                    },
                    'price': {
                        'min': Math.pow (10, -precision['price']),
                        'max': Math.pow (10, precision['price']),
                    },
                    'cost': {
                        'min': undefined,
                        'max': undefined,
                    },
                },
                'info': market,
            });
        }
        return result;
    }

    parseTicker (ticker, market = undefined) {
        let symbol = market['symbol'];
        let timestamp = this.milliseconds ();
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': parseFloat (ticker['high']),
            'low': parseFloat (ticker['low']),
            'bid': undefined,
            'ask': undefined,
            'vwap': undefined,
            'open': parseFloat (ticker['open']),
            'close': parseFloat (ticker['close']),
            'first': undefined,
            'last': parseFloat (ticker['price']),
            'change': undefined,
            'percentage': undefined,
            'average': undefined,
            'baseVolume': parseFloat (ticker['volume']),
            'quoteVolume': undefined,
            'info': ticker,
        };
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetMarketsSymbol (this.extend ({
            'symbol': market['id'],
        }, params));
        return this.parseTicker (response['ticker'], market);
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let tickers = await this.publicGetMarkets (params);
        let result = {};
        for (let i = 0; i < tickers.length; i++) {
            let ticker = tickers[i];
            let id = ticker['symbol'];
            let market = this.marketsById[id];
            let symbol = market['symbol'];
            result[symbol] = this.parseTicker (ticker['ticker'], market);
        }
        return result;
    }

    async fetchOrderBook (symbol, params = {}) {
        await this.loadMarkets ();
        let orderbook = await this.publicGetMarketsSymbolBook (this.extend ({
            'symbol': this.marketId (symbol),
        }, params));
        return this.parseOrderBook (orderbook, undefined, 'bids', 'asks', 'price', 'amount');
    }

    parseTrade (trade, market = undefined) {
        let timestamp = this.parse8601 (trade['created_at']);
        let price = parseFloat (trade['price']);
        let amount = parseFloat (trade['amount']);
        let symbol = market['symbol'];
        let cost = this.costToPrecision (symbol, price * amount);
        let side = trade['trade_side'] === 'ASK' ? 'sell' : 'buy';
        return {
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'id': this.safeString (trade, 'trade_id'),
            'order': undefined,
            'type': 'limit',
            'side': side,
            'price': price,
            'amount': amount,
            'cost': cost,
            'fee': undefined,
            'info': trade,
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let trades = await this.publicGetMarketsSymbolTrades (this.extend ({
            'symbol': market['id'],
        }, params));
        return this.parseTrades (trades, market, since, limit);
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let balances = await this.privateGetAccounts (params);
        let result = { 'info': balances };
        for (let i = 0; i < balances.length; i++) {
            let balance = balances[i];
            let id = balance['account_type'];
            let currency = this.commonCurrencyCode (id);
            let account = {
                'free': parseFloat (balance['active_balance']),
                'used': parseFloat (balance['frozen_balance']),
                'total': 0.0,
            };
            account['total'] = this.sum (account['free'], account['used']);
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    parseOrder (order, market = undefined) {
        let marketId = this.safeString (order, 'order_market');
        let symbol = undefined;
        if (marketId && !market && (marketId in this.marketsById)) {
            market = this.marketsById[marketId];
        }
        if (market)
            symbol = market['symbol'];
        let timestamp = this.parse8601 (order['created_at']);
        let price = parseFloat (order['price']);
        let amount = this.safeFloat (order, 'amount');
        let filled = this.safeFloat (order, 'filled_amount');
        let remaining = amount - filled;
        let status = this.safeString (order, 'order_state');
        if (status === 'filled') {
            status = 'closed';
        }
        let side = this.safeInteger (order, 'order_side');
        if (side === 'BID') {
            side = 'buy';
        } else {
            side = 'sell';
        }
        return {
            'id': this.safeString (order, 'order_id'),
            'datetime': this.iso8601 (timestamp),
            'timestamp': timestamp,
            'status': status,
            'symbol': symbol,
            'type': order['order_type'].toLowerCase (),
            'side': side,
            'price': price,
            'cost': undefined,
            'amount': amount,
            'filled': filled,
            'remaining': remaining,
            'trades': undefined,
            'fee': undefined,
            'info': order,
        };
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.privatePostOrders (this.extend ({
            'order_market': market['id'],
            'order_side': (side === 'buy' ? 'BID' : 'ASK'),
            'amount': amount,
            'price': price,
        }, params));
        // TODO: what's the response here actually
        return response;
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        let result = await this.privateDeleteOrdersId (this.extend ({
            'id': id,
        }, params));
        return result;
    }

    async fetchOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        let order = await this.privateGetOrdersId (this.extend ({
            'id': id,
        }, params));
        return this.parseOrder (order);
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        // TODO: check if it's for open orders only
        let request = {
            'market': market['id'],
        };
        if (limit)
            request['limit'] = limit;
        let orders = await this.privateGetOrders (this.extend (request, params));
        return this.parseOrders (orders, market, since, limit);
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let request = {
            'market': market['id'],
        };
        if (limit) {
            request['limit'] = limit;
        }
        let trades = await this.privateGetTrades (this.extend (request, params));
        return this.parseTrades (trades['trade_history'], market, since, limit);
    }

    async fetchDepositAddress (currencyCode, params = {}) {
        await this.loadMarkets ();
        let currency = this.currency (currencyCode);
        let response = await this.privateGetAccountsCurrency (this.extend ({
            'currency': currency['id'],
        }, params));
        let address = this.safeString (response, 'public_key');
        let status = address ? 'ok' : 'none';
        return {
            'currency': currencyCode,
            'address': address,
            'status': status,
            'info': response,
        };
    }

    async withdraw (code, amount, address, tag = undefined, params = {}) {
        await this.loadMarkets ();
        let currency = this.currency (code);
        let request = {
            'withdrawal_type': currency['id'],
            'address': address,
            'amount': amount,
            // 'fee': 0.0,
            // 'asset_pin': 'YOUR_ASSET_PIN',
        };
        if (tag) {
            // probably it's not the same
            request['label'] = tag;
        }
        let result = await this.privatePostWithdrawals (this.extend (request, params));
        return {
            'info': result,
            'id': undefined,
        };
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let query = this.omit (params, this.extractParams (path));
        let url = this.urls['api'] + '/' + this.implodeParams (path, params);
        if (api === 'public') {
            if (Object.keys (query).length)
                url += '?' + this.urlencode (query);
        } else {
            this.checkRequiredCredentials ();
            headers = {
                'Authorization': 'Bearer ' + this.secret,
                'Big-Device-Id': this.apiKey,
            };
            if (method === 'GET') {
                if (Object.keys (query).length)
                    url += '?' + this.urlencode (query);
            } else if (method === 'POST') {
                headers['Content-Type'] = 'application/json';
                body = this.json (query);
            }
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        let error = this.safeValue (response, 'error');
        let data = this.safeValue (response, 'data');
        if (error || !data) {
            let code = this.safeInteger (error, 'code');
            let errorClasses = {
                '401': AuthenticationError,
            };
            let message = this.safeString (error, 'description', 'Error');
            let ErrorClass = this.safeString (errorClasses, code, ExchangeError);
            throw new ErrorClass (message);
        }
        return data;
    }
};
<commit_msg>bigone: fix parseTrade cost<commit_after>'use strict';

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

const Exchange = require ('./base/Exchange');
const { ExchangeError, AuthenticationError } = require ('./base/errors');

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

module.exports = class bigone extends Exchange {

    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'bigone',
            'name': 'BigONE',
            'countries': 'GB',
            'has': {
                'fetchTickers': true,
                'fetchOpenOrders': true,
                'fetchMyTrades': true,
            },
            'urls': {
                'logo': 'https://p14.zdassets.com/hc/settings_assets/2042110/115000083534/FxqlPvZoc8SvIhRfAju5Vg-BigONE.jpg',
                'api': 'https://api.big.one',
                'www': 'https://big.one/',
                'doc': 'https://developer.big.one/',
                'fees': 'https://help.big.one/hc/en-us/articles/115001933374-BigONE-Fee-Policy',
            },
            'api': {
                'public': {
                    'get': [
                        'markets',
                        'markets/{symbol}',
                        'markets/{symbol}/book',
                        'markets/{symbol}/trades',
                        'orders',
                        'orders/{id}',
                        'trades',
                    ],
                },
                'private': {
                    'get': [
                        'accounts',
                        'accounts/{currency}',
                        'withdrawals',
                        'deposits',
                    ],
                    'post': [
                        'orders',
                        'orders/cancel',
                        'withdrawals',
                    ],
                    'delete': [
                        'orders/{id}',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'maker': 0.1 / 100,
                    'taker': 0.1 / 100,
                },
                'funding': {
                    'withdraw': {
                        'BTC': 0.002,
                        'ETH': 0.01,
                        'EOS': 0.01,
                        'ZEC': 0.002,
                        'LTC': 0.01,
                        'QTUM': 0.01,
                        // 'INK': 0.01 QTUM,
                        // 'BOT': 0.01 QTUM,
                        'ETC': 0.01,
                        'GAS': 0.0,
                        'BTS': 1.0,
                        'GXS': 0.1,
                        'BITCNY': 1.0,
                    },
                },
            },
        });
    }

    async fetchMarkets () {
        let markets = await this.publicGetMarkets ();
        let result = [];
        for (let i = 0; i < markets.length; i++) {
            let market = markets[i];
            let id = market['symbol'];
            let base = this.commonCurrencyCode (market['quote']);
            let quote = this.commonCurrencyCode (market['base']);
            let symbol = base + '/' + quote;
            let precision = {
                'amount': 8,
                'price': 8,
            };
            let lot = Math.pow (10, -precision['amount']);
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'active': true,
                'lot': lot,
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': parseInt (market['base_min']),
                        'max': parseInt (market['base_max']),
                    },
                    'price': {
                        'min': Math.pow (10, -precision['price']),
                        'max': Math.pow (10, precision['price']),
                    },
                    'cost': {
                        'min': undefined,
                        'max': undefined,
                    },
                },
                'info': market,
            });
        }
        return result;
    }

    parseTicker (ticker, market = undefined) {
        let symbol = market['symbol'];
        let timestamp = this.milliseconds ();
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': parseFloat (ticker['high']),
            'low': parseFloat (ticker['low']),
            'bid': undefined,
            'ask': undefined,
            'vwap': undefined,
            'open': parseFloat (ticker['open']),
            'close': parseFloat (ticker['close']),
            'first': undefined,
            'last': parseFloat (ticker['price']),
            'change': undefined,
            'percentage': undefined,
            'average': undefined,
            'baseVolume': parseFloat (ticker['volume']),
            'quoteVolume': undefined,
            'info': ticker,
        };
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetMarketsSymbol (this.extend ({
            'symbol': market['id'],
        }, params));
        return this.parseTicker (response['ticker'], market);
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let tickers = await this.publicGetMarkets (params);
        let result = {};
        for (let i = 0; i < tickers.length; i++) {
            let ticker = tickers[i];
            let id = ticker['symbol'];
            let market = this.marketsById[id];
            let symbol = market['symbol'];
            result[symbol] = this.parseTicker (ticker['ticker'], market);
        }
        return result;
    }

    async fetchOrderBook (symbol, params = {}) {
        await this.loadMarkets ();
        let orderbook = await this.publicGetMarketsSymbolBook (this.extend ({
            'symbol': this.marketId (symbol),
        }, params));
        return this.parseOrderBook (orderbook, undefined, 'bids', 'asks', 'price', 'amount');
    }

    parseTrade (trade, market = undefined) {
        let timestamp = this.parse8601 (trade['created_at']);
        let price = parseFloat (trade['price']);
        let amount = parseFloat (trade['amount']);
        let symbol = market['symbol'];
        let cost = this.costToPrecision (symbol, price * amount);
        let side = trade['trade_side'] === 'ASK' ? 'sell' : 'buy';
        return {
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'id': this.safeString (trade, 'trade_id'),
            'order': undefined,
            'type': 'limit',
            'side': side,
            'price': price,
            'amount': amount,
            'cost': parseFloat (cost),
            'fee': undefined,
            'info': trade,
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let trades = await this.publicGetMarketsSymbolTrades (this.extend ({
            'symbol': market['id'],
        }, params));
        return this.parseTrades (trades, market, since, limit);
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let balances = await this.privateGetAccounts (params);
        let result = { 'info': balances };
        for (let i = 0; i < balances.length; i++) {
            let balance = balances[i];
            let id = balance['account_type'];
            let currency = this.commonCurrencyCode (id);
            let account = {
                'free': parseFloat (balance['active_balance']),
                'used': parseFloat (balance['frozen_balance']),
                'total': 0.0,
            };
            account['total'] = this.sum (account['free'], account['used']);
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    parseOrder (order, market = undefined) {
        let marketId = this.safeString (order, 'order_market');
        let symbol = undefined;
        if (marketId && !market && (marketId in this.marketsById)) {
            market = this.marketsById[marketId];
        }
        if (market)
            symbol = market['symbol'];
        let timestamp = this.parse8601 (order['created_at']);
        let price = parseFloat (order['price']);
        let amount = this.safeFloat (order, 'amount');
        let filled = this.safeFloat (order, 'filled_amount');
        let remaining = amount - filled;
        let status = this.safeString (order, 'order_state');
        if (status === 'filled') {
            status = 'closed';
        }
        let side = this.safeInteger (order, 'order_side');
        if (side === 'BID') {
            side = 'buy';
        } else {
            side = 'sell';
        }
        return {
            'id': this.safeString (order, 'order_id'),
            'datetime': this.iso8601 (timestamp),
            'timestamp': timestamp,
            'status': status,
            'symbol': symbol,
            'type': order['order_type'].toLowerCase (),
            'side': side,
            'price': price,
            'cost': undefined,
            'amount': amount,
            'filled': filled,
            'remaining': remaining,
            'trades': undefined,
            'fee': undefined,
            'info': order,
        };
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.privatePostOrders (this.extend ({
            'order_market': market['id'],
            'order_side': (side === 'buy' ? 'BID' : 'ASK'),
            'amount': amount,
            'price': price,
        }, params));
        // TODO: what's the response here actually
        return response;
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        let result = await this.privateDeleteOrdersId (this.extend ({
            'id': id,
        }, params));
        return result;
    }

    async fetchOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        let order = await this.privateGetOrdersId (this.extend ({
            'id': id,
        }, params));
        return this.parseOrder (order);
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        // TODO: check if it's for open orders only
        let request = {
            'market': market['id'],
        };
        if (limit)
            request['limit'] = limit;
        let orders = await this.privateGetOrders (this.extend (request, params));
        return this.parseOrders (orders, market, since, limit);
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let request = {
            'market': market['id'],
        };
        if (limit) {
            request['limit'] = limit;
        }
        let trades = await this.privateGetTrades (this.extend (request, params));
        return this.parseTrades (trades['trade_history'], market, since, limit);
    }

    async fetchDepositAddress (currencyCode, params = {}) {
        await this.loadMarkets ();
        let currency = this.currency (currencyCode);
        let response = await this.privateGetAccountsCurrency (this.extend ({
            'currency': currency['id'],
        }, params));
        let address = this.safeString (response, 'public_key');
        let status = address ? 'ok' : 'none';
        return {
            'currency': currencyCode,
            'address': address,
            'status': status,
            'info': response,
        };
    }

    async withdraw (code, amount, address, tag = undefined, params = {}) {
        await this.loadMarkets ();
        let currency = this.currency (code);
        let request = {
            'withdrawal_type': currency['id'],
            'address': address,
            'amount': amount,
            // 'fee': 0.0,
            // 'asset_pin': 'YOUR_ASSET_PIN',
        };
        if (tag) {
            // probably it's not the same
            request['label'] = tag;
        }
        let result = await this.privatePostWithdrawals (this.extend (request, params));
        return {
            'info': result,
            'id': undefined,
        };
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let query = this.omit (params, this.extractParams (path));
        let url = this.urls['api'] + '/' + this.implodeParams (path, params);
        if (api === 'public') {
            if (Object.keys (query).length)
                url += '?' + this.urlencode (query);
        } else {
            this.checkRequiredCredentials ();
            headers = {
                'Authorization': 'Bearer ' + this.secret,
                'Big-Device-Id': this.apiKey,
            };
            if (method === 'GET') {
                if (Object.keys (query).length)
                    url += '?' + this.urlencode (query);
            } else if (method === 'POST') {
                headers['Content-Type'] = 'application/json';
                body = this.json (query);
            }
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        let error = this.safeValue (response, 'error');
        let data = this.safeValue (response, 'data');
        if (error || !data) {
            let code = this.safeInteger (error, 'code');
            let errorClasses = {
                '401': AuthenticationError,
            };
            let message = this.safeString (error, 'description', 'Error');
            let ErrorClass = this.safeString (errorClasses, code, ExchangeError);
            throw new ErrorClass (message);
        }
        return data;
    }
};
<|endoftext|>


<commit_before>var config  = require('./gulpconfig');
var gulp 	= require('gulp');
var fs      = require('fs');
var path    = require('path');
var glob    = require('glob');
var filter  = require('gulp-filter');
var jshint  = require('gulp-jshint');
var uglify  = require('gulp-uglify');
var cssMinify = require('gulp-clean-css');
var htmlMinify = require('gulp-htmlmin');
var md5     = require("md5");
var through = require('through2');
var cp 		= require('child_process');
var exec    = function(cmd, cb)
{
	var r = cp.exec(cmd, function (error, stdout, stderr)
	{
		cb(error, stdout, stderr);
	});

	r.stdout.pipe(process.stdout);
	r.stderr.pipe(process.stderr);
}

var spawn   = cp.spawn;

var tempPath = config.temp || "dest-temp";
var destPath = config.dest || "dest";

var IGNORES = ["!bin/**", "!node_modules/**", "!./.*", "!"+destPath+"/**", "!"+tempPath+"/**"];

var getFilePath = function(patthern)
{
	var paths = glob.sync(patthern);
	if(!paths || paths.length === 0)
	{
		return null;
	}

	return paths[0];
}

var rmdirSync = function(rmPath)
{
    var files = null;
    if(fs.existsSync(rmPath))
    {
        files = fs.readdirSync(rmPath);
        files.forEach(function(file,index)
        {

            var curPath = path.join(rmPath, file);
            if(fs.statSync(curPath).isDirectory())
            {
             	rmdirSync(curPath);
            }
            else
            {
            	fs.unlinkSync(curPath);
            }
        });

        fs.rmdirSync(rmPath);
    }
}

gulp.task('default', function()
{

});

gulp.task('build-dest', ['build-fixref-bin', 'build-lscaches'], function(cb)
{
	rmdirSync(destPath);
	return 	gulp.src(path.join(tempPath, "**"))
			.pipe(gulp.dest(destPath));
});

gulp.task('build-fixref-bin', ['build-minify-bin'], function(cb)
{
	var indexPath = path.join(tempPath, "index.html");
	var requireMainPath = path.join(tempPath, "bin/requireMain.js");
	var binPath = path.join(tempPath, "bin/bin.js");
	var partyPath = path.join(tempPath, "bin/3party.js");
	var binMD5 = md5(fs.readFileSync(binPath, 'utf-8'));
	var partyMD5 = md5(fs.readFileSync(partyPath, 'utf-8'));

	var content = fs.readFileSync(requireMainPath, 'utf-8');
	content = content.replace("bin.js", "bin-"+binMD5+".js");
	content = content.replace("3party.js", "3party-"+partyMD5+".js");
	fs.writeFileSync(requireMainPath, content, 'utf-8');

	var name2md5 = {};
	var paths =
	[
		getFilePath(path.join(tempPath, "**/require.js")),
		getFilePath(path.join(tempPath, "**/bin.css")),
		requireMainPath,
		binPath,
		partyPath
	];

	var noExtName = null;
	var extName   = null;
	var dirName   = null;
	var fileMD5   = null;
	for(var i=0,i_sz=paths.length; i<i_sz; ++i)
	{
		extName   = path.extname(paths[i]);
		noExtName = path.basename(paths[i], extName);
		dirName   = path.dirname(paths[i]);

		name2md5[path.basename(paths[i])] = fileMD5 = md5(fs.readFileSync(paths[i], 'utf-8'));
		fs.renameSync(paths[i], path.join(dirName, noExtName+"-"+fileMD5+extName));
	}

	content = fs.readFileSync(indexPath, 'utf-8');
	content = content.replace("bin.css", "bin-"+name2md5["bin.css"]+".css");
	content = content.replace("require.js", "require-"+name2md5["require.js"]+".js");
	content = content.replace("requireMain.js", "requireMain-"+name2md5["requireMain.js"]+".js");
	fs.writeFileSync(indexPath, content, 'utf-8');

	cb();
});

gulp.task('build-minify-bin', ["build-package-bin"], function(cb)
{
	var requirejsPath = getFilePath("bin/**/require.js");
	var binCSSPath    = getFilePath("bin/**/bin.css");

	var filePaths = [requirejsPath, binCSSPath, "index.html", "local-caches.json", "bin/bin.js", "bin/3party.js", "bin/requireMain.js"];

	var htmlFilter = filter("**/*.html", {restore: true});
	var cssFilter = filter("**/*.css", {restore: true});
	var jsFilter = filter(["**/*.js", "!bin/bin.js", "!bin/3party.js"], {restore: true});

	return gulp.src(["{"+filePaths.join(",")+"}"])
			.pipe(htmlFilter)
			.pipe(htmlMinify({collapseWhitespace: true, minifyCSS:true, minifyJS:true}))
			.pipe(htmlFilter.restore)
			.pipe(cssFilter)
			.pipe(cssMinify({compatibility: 'ie8'}))
			.pipe(cssFilter.restore)
			.pipe(jsFilter)
			.pipe(uglify())
			.pipe(jsFilter.restore)
			.pipe(gulp.dest(tempPath))
			.pipe(through.obj({},
			function(chunk, enc, callback)
			{
				callback(null, chunk);
			},
			function(cb)
			{
				fs.unlinkSync("bin/bin.js");
				fs.unlinkSync("bin/3party.js");
				cb();
			}));
});

gulp.task('build-package-bin', function(cb)
{
	var n = 0;
	var f = false;
	var windows = process.platform === "win32";
	var onPackaged = function()
	{
		++n;
		if(n !== 2)
		{
			return ;
		}
		if(f)
		{
			cb("build-package fail");

			return ;
		}

		cb();
	}

	exec(windows ?'r.js.cmd -o 3party-build.js' :'r.js -o 3party-build.js', function(error, stdout, stderr)
	{
		if(error)
		{
			f = true;
			console.log("3party-build fail");
		}
		else
		{
			console.log("3party-build success");
		}

		onPackaged();
	});

	exec(windows ? 'r.js.cmd -o bin-build.js' : 'r.js -o bin-build.js', function(error, stdout, stderr)
	{
		if(error)
		{
			f = true;
			console.log("bin-build fail");
		}
		else
		{
			console.log("bin-build success");
		}

		onPackaged();
	});
});

gulp.task('build-lscaches', ['build-minify'], function(cb)
{
	var versionConfig = config.lsCaches;

	var basePath        = path.resolve(tempPath);
    var nodeRequire     = require;
    var localCachesPath = path.resolve("local-caches.json");
    var oldLocalCaches  = null;
    try
    {
        oldLocalCaches = nodeRequire(localCachesPath);
    }
    catch(e)
    {
        oldLocalCaches = {version:0, files:{}};
    }
    var newLocalCaches  = {};

    var toLeftSlash = function(path)
    {
    	return path.replace(/\\/g, "/");
    }

    var pathToUrl = function(path)
    {
        var ret = path.replace(basePath, (basePath[basePath.length-1]==="/" || basePath[basePath.length-1]==="\\" ? "./" : '.'));
    	return toLeftSlash(ret);
    }

    var processDir = function(dirPath)
    {
        var files = fs.readdirSync(dirPath);
        var filePath = null;
        var fileStat = null;
        for(var i=0,i_sz=files.length; i<i_sz; ++i)
        {
            filePath = files[i];
            if(files[0] === '.')
            {
                continue;
            }
            filePath = path.join(dirPath, filePath);
            fileStat = fs.statSync(filePath);
            if(fileStat.isFile())
            {
                processFile(filePath)
            }
            else if(fileStat.isDirectory())
            {
                processDir(filePath)
            }
        }
    }

    var processFile = function(filePath)
    {
        var ext = path.extname(filePath);
        ext = ext.toLowerCase();
        if(!(ext === ".css" || ext === ".html" || ext === ".js"))
        {
            return ;
        }
        console.log("处理文件 "+filePath);

        var content = fs.readFileSync(filePath, "utf-8");
        var url     = pathToUrl(filePath);
        newLocalCaches.files[url] = md5(content);
    }

    var onLoad = function()
    {
		if (versionConfig.all) {
			newLocalCaches.all = true;
			newLocalCaches.version = oldLocalCaches.version + 1;
		} else {
			var newFiles = newLocalCaches.files;
			var oldFiles = oldLocalCaches.files;
			newLocalCaches.version = oldLocalCaches.version;
			for (var key in newFiles) {
				if (!oldFiles[key] || oldFiles[key] !== newFiles[key]) {
					newLocalCaches.version = oldLocalCaches.version + 1;
					break;
				}
			}

			for (var key in oldFiles) {
				if (!newFiles[key]) {
					newLocalCaches.version = oldLocalCaches.version + 1;
					break;
				}
			}
		}

		var content = JSON.stringify(newLocalCaches);
		fs.writeFileSync(localCachesPath, content, 'utf8');

		cb();
    }

    newLocalCaches.files = {};
    if(versionConfig.all)
	{
		onLoad();

		return;
	}

	var dirs = versionConfig.dirs;
	var dir = null;
	var dirStat = null;
	for (var i = 0, i_sz = dirs.length; i < i_sz; ++i)
	{
		dir = dirs[i];
		dir = path.resolve(path.join(tempPath, dirs[i]));
		dirStat = fs.statSync(dir);
		if (dirStat.isFile())
		{
			processFile(dir)
		}
		else if (dirStat.isDirectory())
		{
			processDir(dir)
		}
	}

	onLoad();
});

gulp.task('build-minify',  function(cb)
{
	rmdirSync(tempPath);

	var htmlFilter = filter("**/*.html", {restore: true});
	var cssFilter = filter("**/*.css", {restore: true});
	var jsFilter = filter("**/*.js", {restore: true});

	// html
	return gulp.src(["./**", "!./*.*"].concat(IGNORES))
	.pipe(htmlFilter)
	.pipe(htmlMinify({collapseWhitespace: true, minifyCSS:true, minifyJS:true}))
	.pipe(htmlFilter.restore)
	.pipe(cssFilter)
	.pipe(cssMinify({compatibility: 'ie8'}))
	.pipe(cssFilter.restore)
	.pipe(jsFilter)
	.pipe(uglify())
	.pipe(jsFilter.restore)
	.pipe(gulp.dest(tempPath));
});

gulp.task('build-jshint', function(cb)
{
	return gulp.src(["**/*.js", "!./*.js"].concat(IGNORES))
	.pipe(jshint())
	.pipe(jshint.reporter());
});

gulp.task('build', ["build-dest"], function(cb)
{
	rmdirSync(tempPath);
});
<commit_msg>自动构建BUG FIX<commit_after>var config  = require('./gulpconfig');
var gulp 	= require('gulp');
var fs      = require('fs');
var path    = require('path');
var glob    = require('glob');
var filter  = require('gulp-filter');
var jshint  = require('gulp-jshint');
var uglify  = require('gulp-uglify');
var cssMinify = require('gulp-clean-css');
var htmlMinify = require('gulp-htmlmin');
var md5     = require("md5");
var through = require('through2');
var cp 		= require('child_process');
var exec    = function(cmd, cb)
{
	var r = cp.exec(cmd, function (error, stdout, stderr)
	{
		cb(error, stdout, stderr);
	});

	r.stdout.pipe(process.stdout);
	r.stderr.pipe(process.stderr);
}

var spawn   = cp.spawn;

var tempPath = config.temp || "dest-temp";
var destPath = config.dest || "dest";

var IGNORES = ["!bin/**", "!node_modules/**", "!./.*", "!"+destPath+"/**", "!"+tempPath+"/**"];

var getFilePath = function(patthern)
{
	var paths = glob.sync(patthern);
	if(!paths || paths.length === 0)
	{
		return null;
	}

	return paths[0];
}

var rmdirSync = function(rmPath)
{
    var files = null;
    if(fs.existsSync(rmPath))
    {
        files = fs.readdirSync(rmPath);
        files.forEach(function(file,index)
        {

            var curPath = path.join(rmPath, file);
            if(fs.statSync(curPath).isDirectory())
            {
             	rmdirSync(curPath);
            }
            else
            {
            	fs.unlinkSync(curPath);
            }
        });

        fs.rmdirSync(rmPath);
    }
}

gulp.task('default', function()
{

});

gulp.task('build-dest', ['build-fixref-bin', 'build-lscaches'], function(cb)
{
	rmdirSync(destPath);
	return 	gulp.src(path.join(tempPath, "**"))
			.pipe(gulp.dest(destPath));
});

gulp.task('build-fixref-bin', ['build-minify-bin'], function(cb)
{
	var indexPath = path.join(tempPath, "index.html");
	var requireMainPath = path.join(tempPath, "bin/requireMain.js");
	var binPath = path.join(tempPath, "bin/bin.js");
	var partyPath = path.join(tempPath, "bin/3party.js");
	var binMD5 = md5(fs.readFileSync(binPath, 'utf-8'));
	var partyMD5 = md5(fs.readFileSync(partyPath, 'utf-8'));

	var content = fs.readFileSync(requireMainPath, 'utf-8');
	content = content.replace("bin.js", "bin-"+binMD5+".js");
	content = content.replace("3party.js", "3party-"+partyMD5+".js");
	fs.writeFileSync(requireMainPath, content, 'utf-8');

	var name2md5 = {};
	var paths =
	[
		getFilePath(path.join(tempPath, "**/require.js")),
		getFilePath(path.join(tempPath, "**/bin.css")),
		requireMainPath,
		binPath,
		partyPath
	];

	var noExtName = null;
	var extName   = null;
	var dirName   = null;
	var fileMD5   = null;
	for(var i=0,i_sz=paths.length; i<i_sz; ++i)
	{
		extName   = path.extname(paths[i]);
		noExtName = path.basename(paths[i], extName);
		dirName   = path.dirname(paths[i]);

		name2md5[path.basename(paths[i])] = fileMD5 = md5(fs.readFileSync(paths[i], 'utf-8'));
		fs.renameSync(paths[i], path.join(dirName, noExtName+"-"+fileMD5+extName));
	}

	content = fs.readFileSync(indexPath, 'utf-8');
	content = content.replace("bin.css", "bin-"+name2md5["bin.css"]+".css");
	content = content.replace("require.js", "require-"+name2md5["require.js"]+".js");
	content = content.replace("requireMain.js", "requireMain-"+name2md5["requireMain.js"]+".js");
	fs.writeFileSync(indexPath, content, 'utf-8');

	cb();
});

gulp.task('build-minify-bin', ["build-package-bin"], function(cb)
{
	var requirejsPath = getFilePath("bin/**/require.js");
	var binCSSPath    = getFilePath("bin/**/bin.css");

	var filePaths = ["bin/**/*.png", "bin/**/*.jpeg", "bin/**/*.jpg", requirejsPath, binCSSPath, "index.html", "local-caches.json", "bin/bin.js", "bin/3party.js", "bin/requireMain.js"];

	var htmlFilter = filter("**/*.html", {restore: true});
	var cssFilter = filter("**/*.css", {restore: true});
	var jsFilter = filter(["**/*.js", "!bin/bin.js", "!bin/3party.js"], {restore: true});

	return gulp.src(["{"+filePaths.join(",")+"}"])
			.pipe(htmlFilter)
			.pipe(htmlMinify({collapseWhitespace: true, minifyCSS:true, minifyJS:true}))
			.pipe(htmlFilter.restore)
			.pipe(cssFilter)
			.pipe(cssMinify({compatibility: 'ie8'}))
			.pipe(cssFilter.restore)
			.pipe(jsFilter)
			.pipe(uglify())
			.pipe(jsFilter.restore)
			.pipe(gulp.dest(tempPath))
			.pipe(through.obj({},
			function(chunk, enc, callback)
			{
				callback(null, chunk);
			},
			function(cb)
			{
				fs.unlinkSync("bin/bin.js");
				fs.unlinkSync("bin/3party.js");
				cb();
			}));
});

gulp.task('build-package-bin', function(cb)
{
	var n = 0;
	var f = false;
	var windows = process.platform === "win32";
	var onPackaged = function()
	{
		++n;
		if(n !== 2)
		{
			return ;
		}
		if(f)
		{
			cb("build-package fail");

			return ;
		}

		cb();
	}

	exec(windows ?'r.js.cmd -o 3party-build.js' :'r.js -o 3party-build.js', function(error, stdout, stderr)
	{
		if(error)
		{
			f = true;
			console.log("3party-build fail");
		}
		else
		{
			console.log("3party-build success");
		}

		onPackaged();
	});

	exec(windows ? 'r.js.cmd -o bin-build.js' : 'r.js -o bin-build.js', function(error, stdout, stderr)
	{
		if(error)
		{
			f = true;
			console.log("bin-build fail");
		}
		else
		{
			console.log("bin-build success");
		}

		onPackaged();
	});
});

gulp.task('build-lscaches', ['build-minify'], function(cb)
{
	var versionConfig = config.lsCaches;

	var basePath        = path.resolve(tempPath);
    var nodeRequire     = require;
    var localCachesPath = path.resolve("local-caches.json");
    var oldLocalCaches  = null;
    try
    {
        oldLocalCaches = nodeRequire(localCachesPath);
    }
    catch(e)
    {
        oldLocalCaches = {version:0, files:{}};
    }
    var newLocalCaches  = {};

    var toLeftSlash = function(path)
    {
    	return path.replace(/\\/g, "/");
    }

    var pathToUrl = function(path)
    {
        var ret = path.replace(basePath, (basePath[basePath.length-1]==="/" || basePath[basePath.length-1]==="\\" ? "./" : '.'));
    	return toLeftSlash(ret);
    }

    var processDir = function(dirPath)
    {
        var files = fs.readdirSync(dirPath);
        var filePath = null;
        var fileStat = null;
        for(var i=0,i_sz=files.length; i<i_sz; ++i)
        {
            filePath = files[i];
            if(files[0] === '.')
            {
                continue;
            }
            filePath = path.join(dirPath, filePath);
            fileStat = fs.statSync(filePath);
            if(fileStat.isFile())
            {
                processFile(filePath)
            }
            else if(fileStat.isDirectory())
            {
                processDir(filePath)
            }
        }
    }

    var processFile = function(filePath)
    {
        var ext = path.extname(filePath);
        ext = ext.toLowerCase();
        if(!(ext === ".css" || ext === ".html" || ext === ".js"))
        {
            return ;
        }
        console.log("处理文件 "+filePath);

        var content = fs.readFileSync(filePath, "utf-8");
        var url     = pathToUrl(filePath);
        newLocalCaches.files[url] = md5(content);
    }

    var onLoad = function()
    {
		if (versionConfig.all) {
			newLocalCaches.all = true;
			newLocalCaches.version = oldLocalCaches.version + 1;
		} else {
			var newFiles = newLocalCaches.files;
			var oldFiles = oldLocalCaches.files;
			newLocalCaches.version = oldLocalCaches.version;
			for (var key in newFiles) {
				if (!oldFiles[key] || oldFiles[key] !== newFiles[key]) {
					newLocalCaches.version = oldLocalCaches.version + 1;
					break;
				}
			}

			for (var key in oldFiles) {
				if (!newFiles[key]) {
					newLocalCaches.version = oldLocalCaches.version + 1;
					break;
				}
			}
		}

		var content = JSON.stringify(newLocalCaches);
		fs.writeFileSync(localCachesPath, content, 'utf8');

		cb();
    }

    newLocalCaches.files = {};
    if(versionConfig.all)
	{
		onLoad();

		return;
	}

	var dirs = versionConfig.dirs;
	var dir = null;
	var dirStat = null;
	for (var i = 0, i_sz = dirs.length; i < i_sz; ++i)
	{
		dir = dirs[i];
		dir = path.resolve(path.join(tempPath, dirs[i]));
		dirStat = fs.statSync(dir);
		if (dirStat.isFile())
		{
			processFile(dir)
		}
		else if (dirStat.isDirectory())
		{
			processDir(dir)
		}
	}

	onLoad();
});

gulp.task('build-minify',  function(cb)
{
	rmdirSync(tempPath);

	var htmlFilter = filter("**/*.html", {restore: true});
	var cssFilter = filter("**/*.css", {restore: true});
	var jsFilter = filter("**/*.js", {restore: true});

	// html
	return gulp.src(["./**", "!./*.*"].concat(IGNORES))
	.pipe(htmlFilter)
	.pipe(htmlMinify({collapseWhitespace: true, minifyCSS:true, minifyJS:true}))
	.pipe(htmlFilter.restore)
	.pipe(cssFilter)
	.pipe(cssMinify({compatibility: 'ie8'}))
	.pipe(cssFilter.restore)
	.pipe(jsFilter)
	.pipe(uglify())
	.pipe(jsFilter.restore)
	.pipe(gulp.dest(tempPath));
});

gulp.task('build-jshint', function(cb)
{
	return gulp.src(["**/*.js", "!./*.js"].concat(IGNORES))
	.pipe(jshint())
	.pipe(jshint.reporter());
});

gulp.task('build', ["build-dest"], function(cb)
{
	rmdirSync(tempPath);
});
<|endoftext|>


<commit_before>document.on('click', '.task_header .text_actions a[href$="/edit"]', function(e, link) {
  if (!e.isMiddleClick()) {
    e.stop()
    link.up('.task_header').hide().next('form.edit_task').forceShow().focusFirstElement()
  }
})

var hideEditTaskFormAndShowHeader = function(form) {
  Form.reset(form).hide().previous('.task_header').show()
}

document.on('click', '.task_header + .edit_task a[href="#cancel"]', function(e, link) {
  e.stop()
  hideEditTaskFormAndShowHeader(link.up('.edit_task'))
})

document.on('keyup', '.task_header + .edit_task', function(e, form) {
  if (e.keyCode == Event.KEY_ESC) hideEditTaskFormAndShowHeader(form)
})

document.on('ajax:failure', 'form.new_task.app_form', function(e, form) {
  var message = e.memo.responseJSON.first()[1]
  form.down('div.text_field').insertOrUpdate('p.error', message)
})

document.on('ajax:success', '.task_header + form.edit_task', function(e, form) {
  var name = form.down('input[name="task[name]"]').getValue()
  form.up('.content').select('.task_header h2, .task .thread_title a.task').invoke('update', name)

  hideEditTaskFormAndShowHeader(form)
})

// update task counter
document.on('ajax:success', 'form.edit_task', function(e, form) {
	var task_data = e.memo.headerJSON
	counter = $$('.task_counter[data-task-id='+ task_data.id +']').first()
  counter.update(parseInt(counter.innerHTML) + 1)
})

document.on('click', '.date_picker', function(e, element) {
  new CalendarDateSelect(element.down('input'), element.down('span'), {
    buttons: true,
    popup: 'force',
    time: false,
    year_range: [2008, 2020]
  })
})

Task = {

  sortableChange: function(draggable) {
    this.currentDraggable = draggable
  },

  sortableUpdate: function() {
    var taskId = this.currentDraggable.readAttribute('data-task-id'),
        taskList = this.currentDraggable.up('.task_list')
        taskListId = taskList.readAttribute('data-task-list-id')

    taskIds = taskList.select('.tasks .task').collect(
      function(task) {
          return task.readAttribute('data-task-id')
      }).join(',')

    new Ajax.Request('/projects/' + current_project + '/tasks/' + taskId + '/reorder', {
      method: 'put',
      parameters: { task_list_id: taskListId, task_ids: taskIds }
    })
  }.debounce(100),

  makeSortable: function(task_id, all_task_ids) {
    Sortable.create(task_id, {
      constraint: 'vertical',
      containment: all_task_ids,
      // format: /.*task_(\d+)_task_task/,
      handle: 'img.task_drag',
      dropOnEmpty: true,
      // that makes the task disappear when it leaves its original task list
      // only:'task',
      tag: 'div',
      onChange: Task.sortableChange.bind(Task),
      onUpdate: Task.sortableUpdate.bind(Task)
    })
  },

  make_all_sortable: function() {
    var task_div_ids = $$(".tasks.open").map(function(task_div){
      return task_div.identify();
    })
    task_div_ids.each(function(task_div_id){
      Task.makeSortable(task_div_id, task_div_ids);
    })
  },

  highlight_my_tasks: function() {
    $$(".task.user_"+my_user.id).invoke('addClassName', 'mine')
  },

  insertTask: function(task_list_id, archived, task_id, html) {
    var container = archived ? $(task_list_id + '_the_closed_tasks') : $(task_list_id + '_the_main_tasks');
    container.insert({bottom: html});
    new Effect.Highlight(task_id, { duration: 3 });
    TaskList.updateList(task_list_id);
  },

  removeTask: function(task_list_id, task_id) {
    $(task_id).remove();
    TaskList.updateList(task_list_id);
  },

  replaceTasks: function(task_list_id, archived, html) {
    var container = archived ? $(task_list_id + '_the_closed_tasks') : $(task_list_id + '_the_main_tasks');
    container.innerHTML = html;
    TaskList.updateList(task_list_id);
  },

  insertAssignableUsers: function() {
    if (typeof _people == "object") {
      $$('form.new_comment.edit_task .task_actions select#task_assigned_id').each(function(select) {
        var project_id = select.up('form').readAttribute('data-project-id')
        select.insert(new Element('option').insert(task_unassigned))
        if (typeof _people[project_id] == "object") {
          _people[project_id].each(function(person) {
            var option = new Element('option', { 'value': person[0] }).insert(person[2])
            select.insert(option)
          })
        }
      })
    }
  }

}

document.on('click', 'a.show_archived_tasks_link', function(e, el) {
  e.stop();
  var task_container_id = el.up('.task_list').id;
  var task_list_id = $(task_container_id).up().id;
  el.hide();
  el.up().down('.loading').show();
  TaskList.reloadList($(task_container_id), 'tasks', function(req){
    el.up().remove();
    new Effect.BlindDown(task_list_id + '_the_closed_tasks', {duration:0.3});
  });
});

document.on('ajax:success', '.new_task form', function(e){
  setTimeout(function(){
    Task.make_all_sortable();
    TaskList.saveColumn();
    TaskList.updatePage('column', TaskList.restoreColumn);
  }, 0);
})

document.observe('jenny:loaded:edit_task', function(evt) {
  setTimeout(function(){
    Task.make_all_sortable();
    TaskList.updatePage('column', TaskList.restoreColumn);
  }, 0);
});

document.observe('jenny:cancel:edit_task', function(evt) {
  $('show_task').down(".task_header").show();
});

// Enable task sort on load and highlight my tasks
document.observe('dom:loaded', function(e) {
  if(typeof(my_user) == "undefined") return

  if ($$('.tasks').length > 0) Task.make_all_sortable();
  Task.highlight_my_tasks();
  Filter.updateCounts(false);
  Filter.updateFilters();
  Task.insertAssignableUsers();
});
<commit_msg>never add repeated items on assigned_id select<commit_after>document.on('click', '.task_header .text_actions a[href$="/edit"]', function(e, link) {
  if (!e.isMiddleClick()) {
    e.stop()
    link.up('.task_header').hide().next('form.edit_task').forceShow().focusFirstElement()
  }
})

var hideEditTaskFormAndShowHeader = function(form) {
  Form.reset(form).hide().previous('.task_header').show()
}

document.on('click', '.task_header + .edit_task a[href="#cancel"]', function(e, link) {
  e.stop()
  hideEditTaskFormAndShowHeader(link.up('.edit_task'))
})

document.on('keyup', '.task_header + .edit_task', function(e, form) {
  if (e.keyCode == Event.KEY_ESC) hideEditTaskFormAndShowHeader(form)
})

document.on('ajax:failure', 'form.new_task.app_form', function(e, form) {
  var message = e.memo.responseJSON.first()[1]
  form.down('div.text_field').insertOrUpdate('p.error', message)
})

document.on('ajax:success', '.task_header + form.edit_task', function(e, form) {
  var name = form.down('input[name="task[name]"]').getValue()
  form.up('.content').select('.task_header h2, .task .thread_title a.task').invoke('update', name)

  hideEditTaskFormAndShowHeader(form)
})

// update task counter
document.on('ajax:success', 'form.edit_task', function(e, form) {
	var task_data = e.memo.headerJSON
	counter = $$('.task_counter[data-task-id='+ task_data.id +']').first()
  counter.update(parseInt(counter.innerHTML) + 1)
})

document.on('click', '.date_picker', function(e, element) {
  new CalendarDateSelect(element.down('input'), element.down('span'), {
    buttons: true,
    popup: 'force',
    time: false,
    year_range: [2008, 2020]
  })
})

Task = {

  sortableChange: function(draggable) {
    this.currentDraggable = draggable
  },

  sortableUpdate: function() {
    var taskId = this.currentDraggable.readAttribute('data-task-id'),
        taskList = this.currentDraggable.up('.task_list')
        taskListId = taskList.readAttribute('data-task-list-id')

    taskIds = taskList.select('.tasks .task').collect(
      function(task) {
          return task.readAttribute('data-task-id')
      }).join(',')

    new Ajax.Request('/projects/' + current_project + '/tasks/' + taskId + '/reorder', {
      method: 'put',
      parameters: { task_list_id: taskListId, task_ids: taskIds }
    })
  }.debounce(100),

  makeSortable: function(task_id, all_task_ids) {
    Sortable.create(task_id, {
      constraint: 'vertical',
      containment: all_task_ids,
      // format: /.*task_(\d+)_task_task/,
      handle: 'img.task_drag',
      dropOnEmpty: true,
      // that makes the task disappear when it leaves its original task list
      // only:'task',
      tag: 'div',
      onChange: Task.sortableChange.bind(Task),
      onUpdate: Task.sortableUpdate.bind(Task)
    })
  },

  make_all_sortable: function() {
    var task_div_ids = $$(".tasks.open").map(function(task_div){
      return task_div.identify();
    })
    task_div_ids.each(function(task_div_id){
      Task.makeSortable(task_div_id, task_div_ids);
    })
  },

  highlight_my_tasks: function() {
    $$(".task.user_"+my_user.id).invoke('addClassName', 'mine')
  },

  insertTask: function(task_list_id, archived, task_id, html) {
    var container = archived ? $(task_list_id + '_the_closed_tasks') : $(task_list_id + '_the_main_tasks');
    container.insert({bottom: html});
    new Effect.Highlight(task_id, { duration: 3 });
    TaskList.updateList(task_list_id);
  },

  removeTask: function(task_list_id, task_id) {
    $(task_id).remove();
    TaskList.updateList(task_list_id);
  },

  replaceTasks: function(task_list_id, archived, html) {
    var container = archived ? $(task_list_id + '_the_closed_tasks') : $(task_list_id + '_the_main_tasks');
    container.innerHTML = html;
    TaskList.updateList(task_list_id);
  },

  insertAssignableUsers: function() {
    if (typeof _people == "object") {
      $$('form.new_comment.edit_task .task_actions select#task_assigned_id').each(function(select) {
        var project_id = select.up('form').readAttribute('data-project-id')
        if (!select.descendants().any()) {
          select.insert(new Element('option').insert(task_unassigned))
        }
        if (typeof _people[project_id] == "object") {
          _people[project_id].each(function(person) {
            if (!select.select('[value=' + person[0] + ']').any()) {
              var option = new Element('option', { 'value': person[0] }).insert(person[2])
              select.insert(option)
            }
          })
        }
      })
    }
  }

}

document.on('click', 'a.show_archived_tasks_link', function(e, el) {
  e.stop();
  var task_container_id = el.up('.task_list').id;
  var task_list_id = $(task_container_id).up().id;
  el.hide();
  el.up().down('.loading').show();
  TaskList.reloadList($(task_container_id), 'tasks', function(req){
    el.up().remove();
    new Effect.BlindDown(task_list_id + '_the_closed_tasks', {duration:0.3});
  });
});

document.on('ajax:success', '.new_task form', function(e){
  setTimeout(function(){
    Task.make_all_sortable();
    TaskList.saveColumn();
    TaskList.updatePage('column', TaskList.restoreColumn);
  }, 0);
})

document.observe('jenny:loaded:edit_task', function(evt) {
  setTimeout(function(){
    Task.make_all_sortable();
    TaskList.updatePage('column', TaskList.restoreColumn);
  }, 0);
});

document.observe('jenny:cancel:edit_task', function(evt) {
  $('show_task').down(".task_header").show();
});

// Enable task sort on load and highlight my tasks
document.observe('dom:loaded', function(e) {
  if(typeof(my_user) == "undefined") return

  if ($$('.tasks').length > 0) Task.make_all_sortable();
  Task.highlight_my_tasks();
  Filter.updateCounts(false);
  Filter.updateFilters();
  Task.insertAssignableUsers();
});
<|endoftext|>


<commit_before>var instance
var windowWidth
var windowHeight

function shareURL(){
	browser.tabs.query({active: true},function(tabs){

		var gettingUrl = browser.storage.local.get("instance_url");
		gettingUrl.then(onGotUrl, onError);
		var gettingWidth = browser.storage.local.get("window_width");
		gettingWidth.then(onGotWidth, onError);
		var gettingHeight = browser.storage.local.get("window_height");
		gettingHeight.then(onGotHeight, onError);

		var tab = tabs[0];

		// manages Mozilla Firefox reader mode
		var rawUrl = tab.url;
		var partToRemove = partToRemove = "about:reader?url=";
		if(rawUrl.includes(partToRemove)) {
		rawUrl = rawUrl.substring(partToRemove.length);
		rawUrl = decodeURIComponent(rawUrl);
	  	}

		var url = instance + "/bookmarks.php?action=add&address=" + encodeURIComponent(rawUrl) + "&title=" + tabs[0].title;
		widthInt = Number(windowWidth);
		heightInt = Number(windowHeight);

		browser.windows.create({
			url: url,
			width: widthInt,
			height: heightInt,
			type: "popup"
		},(win)=>{
			browser.tabs.onUpdated.addListener((tabId,changeInfo) =>{
				if(tabId === win.tabs[0].id){
					if(changeInfo.url){
						var new_url
						new_url = changeInfo.url
						if((new_url.includes("action=add") == false) && (new_url.includes("edit.php") == false)){
							browser.windows.remove(win.id);
						}
					}
				}
			});
		});
	});
}

function onError(error) {
  console.log(`Error: ${error}`);
}

function onGotUrl(item) {
	if (item.instance_url) {
	    instance = item.instance_url;
	  }
}

function onGotWidth(item) {
	if (item.window_width) {
	    windowWidth = item.window_width;
	  }
}

function onGotHeight(item) {
	if (item.window_height) {
	    windowHeight = item.window_height;
	  }
}

browser.contextMenus.create({
	id: "semantic-scuttle",
	title: "Add to (Semantic)Scuttle",
	onclick: function(){
		shareURL();
	},
	contexts: ["all"]
});

browser.browserAction.onClicked.addListener(() => {
	shareURL();
});
<commit_msg>Corrected a bug when there was quotes in page title.<commit_after>var instance
var windowWidth
var windowHeight

function shareURL(){
	browser.tabs.query({active: true},function(tabs){

		var gettingUrl = browser.storage.local.get("instance_url");
		gettingUrl.then(onGotUrl, onError);
		var gettingWidth = browser.storage.local.get("window_width");
		gettingWidth.then(onGotWidth, onError);
		var gettingHeight = browser.storage.local.get("window_height");
		gettingHeight.then(onGotHeight, onError);

		var tab = tabs[0];

		// manages Mozilla Firefox reader mode
		var rawUrl = tab.url;
		var partToRemove = partToRemove = "about:reader?url=";
		if(rawUrl.includes(partToRemove)) {
		rawUrl = rawUrl.substring(partToRemove.length);
		rawUrl = decodeURIComponent(rawUrl);
	  	}

		var url = instance + "/bookmarks.php?action=add&address=" + encodeURIComponent(rawUrl) + "&title=" + encodeURIComponent(tabs[0].title);
		widthInt = Number(windowWidth);
		heightInt = Number(windowHeight);

		browser.windows.create({
			url: url,
			width: widthInt,
			height: heightInt,
			type: "popup"
		},(win)=>{
			browser.tabs.onUpdated.addListener((tabId,changeInfo) =>{
				if(tabId === win.tabs[0].id){
					if(changeInfo.url){
						var new_url
						new_url = changeInfo.url
						if((new_url.includes("action=add") == false) && (new_url.includes("edit.php") == false)){
							browser.windows.remove(win.id);
						}
					}
				}
			});
		});
	});
}

function onError(error) {
  console.log(`Error: ${error}`);
}

function onGotUrl(item) {
	if (item.instance_url) {
	    instance = item.instance_url;
	  }
}

function onGotWidth(item) {
	if (item.window_width) {
	    windowWidth = item.window_width;
	  }
}

function onGotHeight(item) {
	if (item.window_height) {
	    windowHeight = item.window_height;
	  }
}

browser.contextMenus.create({
	id: "semantic-scuttle",
	title: "Add to (Semantic)Scuttle",
	onclick: function(){
		shareURL();
	},
	contexts: ["all"]
});

browser.browserAction.onClicked.addListener(() => {
	shareURL();
});
<|endoftext|>