<commit_before>function Couch(url) {
    this.url = url;
}
Couch.prototype.urlFor = function (path, query) {
    if (query) {
        path += "?" + Object.keys(query).map(function (key) {
            if (key[0] === '$') {
                return encodeURIComponent(key.slice(1)) + "=" + encodeURIComponent(JSON.stringify(query[key]));
            } else {
                return encodeURIComponent(key) + "=" + encodeURIComponent(query[key]);
            }
        }).join("&");
    }
    return this.url + "/" + path;
};
Couch.prototype.http = function (method, obj, path, query, callback) {
    var req = new XMLHttpRequest();
    req.open(method, this.urlFor(path, query));
    req.setRequestHeader("Content-Type", "application/json");
    req.send(JSON.stringify(obj));
    req.onreadystatechange = function() {
        if (req.readyState === req.DONE) {
            callback(req.status, JSON.parse(req.responseText));
        }
    }
};
Couch.prototype.get = function (path, query, callback) {
    this.http("GET", null, path, query, function (status, result) {
        callback((status === 200) ? result : null);
    });
};

var db = new Couch("http://localhost:5984/dev");

var loading = false;
var loadPending = false;
var lastImage = null;
function displayFetchedImages(viewResult) {
    viewResult.rows.forEach(function (row) {
        var img = new Image();
        img.className = "image";
        img.id = row.id;
        img.setAttribute('data-by_date-key', JSON.stringify(row.key));
        img.src = db.urlFor(row.id) + "/thumbnail/512.jpg";
        document.body.appendChild(img);
        lastImage = img;
    });
    loading = false;
    if (loadPending) {
        loadNextImages();
        loadPending = false;
    }
}
function loadNextImages() {
    if (loading) {
        loadPending = true;
        return;
    }

    var query = {reduce:false, limit:10};
    if (lastImage) {
        query.startkey = lastImage.getAttribute('data-by_date-key');
        query.startkey_docid = lastImage.id;
        query.skip = 1;
    }
    db.get("_design/shutterstem/_view/by_date", query, displayFetchedImages);
    loading = true;
}

document.addEventListener('DOMContentLoaded', function () {
    loadNextImages();
}, false);

document.addEventListener('scroll', function () {
    if ((window.pageYOffset + window.innerHeight) > (document.height - 50)) {
        loadNextImages();
    }
}, false);
<commit_msg>Couch helper urlFor now allows array paths<commit_after>function Couch(url) {
    this.url = url;
}
Couch.prototype.urlFor = function (path, query) {
    if (path.join) {
        path = path.join("/");
    }
    if (query) {
        path += "?" + Object.keys(query).map(function (key) {
            if (key[0] === '$') {
                return encodeURIComponent(key.slice(1)) + "=" + encodeURIComponent(JSON.stringify(query[key]));
            } else {
                return encodeURIComponent(key) + "=" + encodeURIComponent(query[key]);
            }
        }).join("&");
    }
    return this.url + "/" + path;
};
Couch.prototype.http = function (method, obj, path, query, callback) {
    var req = new XMLHttpRequest();
    req.open(method, this.urlFor(path, query));
    req.setRequestHeader("Content-Type", "application/json");
    req.send(JSON.stringify(obj));
    req.onreadystatechange = function() {
        if (req.readyState === req.DONE) {
            callback(req.status, JSON.parse(req.responseText));
        }
    }
};
Couch.prototype.get = function (path, query, callback) {
    this.http("GET", null, path, query, function (status, result) {
        callback((status === 200) ? result : null);
    });
};

var db = new Couch("http://localhost:5984/dev");

var loading = false;
var loadPending = false;
var lastImage = null;
function displayFetchedImages(viewResult) {
    viewResult.rows.forEach(function (row) {
        var img = new Image();
        img.className = "image";
        img.id = row.id;
        img.setAttribute('data-by_date-key', JSON.stringify(row.key));
        img.src = db.urlFor(row.id) + "/thumbnail/512.jpg";
        document.body.appendChild(img);
        lastImage = img;
    });
    loading = false;
    if (loadPending) {
        loadNextImages();
        loadPending = false;
    }
}
function loadNextImages() {
    if (loading) {
        loadPending = true;
        return;
    }

    var query = {reduce:false, limit:10};
    if (lastImage) {
        query.startkey = lastImage.getAttribute('data-by_date-key');
        query.startkey_docid = lastImage.id;
        query.skip = 1;
    }
    db.get("_design/shutterstem/_view/by_date", query, displayFetchedImages);
    loading = true;
}

document.addEventListener('DOMContentLoaded', function () {
    loadNextImages();
}, false);

document.addEventListener('scroll', function () {
    if ((window.pageYOffset + window.innerHeight) > (document.height - 50)) {
        loadNextImages();
    }
}, false);
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2010 Nils Schneider
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/* settings:
 * {
 *  generateConfirm: 120
 * }
 */
function TXList(list, app, settings) {
	function sortTX(a, b) {
		if(a.time != b.time)
			return (a.time - b.time);

		if(a.category != b.category)
			return (b.category < a.category) ? -1 : 1;

		return (b.amount - a.amount);
	}

	this.clear = function() {
		list.children().remove();
	}

	this.processRPC = function(transactions) {
		var start = new Date().getTime();

		var transactions = jQuery.grep(transactions,
				function(n, i) {
					return n.account == app.bitcoin.settings.account;
				});

		transactions.sort(this.sortTX);

		list.children('#txlistempty').remove();

		if (transactions.length == 0)
			list.append('
no transactions
');

		for (var key in transactions)
			this.processTX(transactions[key]);

		list.children('tr:not(.txinfo):odd').addClass('odd').next('.txinfo').addClass('odd');
		list.children('tr:not(.txinfo):even').removeClass('odd').next('.txinfo').removeClass('odd');

		/* adjust refresh interval of app depending processing time of txlist */
		var end = new Date().getTime();
		var time = end - start;
		app.setRefreshInterval(time * 10);
	}

	this.processTX = function(tx) {
		if (tx.time == undefined)
			tx.time = 0;

		if (tx.txid == undefined)
			tx.txid = (tx.time + tx.amount + tx.otheraccount).replace(/ /g,'');

		tx.txid += tx.category;

		var txrow = $(document.getElementById(tx.txid));

		if (txrow.length == 0) {
			txrow = $('

');
			list.prepend(txrow);
			var txdiv = $('

');
			txrow.after(txdiv);

			txrow.click( function() {
					$(this).next('tr.txinfo').children('td').children('div').slideToggle('fast');
				});
		}

		var checksum = tx.txid + tx.confirmations + tx.time;

		/* Only update TX if it differs from current one */
		if(txrow.attr('checksum') != checksum) {
			txrow.attr('checksum', checksum);
			txrow.html(this.renderRow(tx));

			txrow.next('tr.txinfo').children('td').children('div').html(this.renderInfo(tx));

			if (tx.confirmations == 0 || (tx.category == "generate" && tx.confirmations < settings.generateConfirm))
				txrow.addClass("unconfirmed");
			else
				txrow.removeClass("unconfirmed");
		}
	}

	this.renderInfo = function(tx) {
		var html = "";
		var extra = "";

		switch (tx.category) {
			case "generate":
				html += "Generated coins
";
				break;
			case "move":
				html += "Moved " + (tx.amount<0?"to":"from") + ": " + tx.otheraccount.prettyAccount() + "
";
				break;
			case "send":
				if (tx.to)
					extra = " (" + tx.to + ")";
				html += "Sent to: " + tx.address + extra + "
";
				break;
			case "receive":
				if (tx.from)
					extra = " (" + tx.from + ")";
				html += "Received on: " + tx.address + extra + "
";
				break;
			default:
				html += "Category: " + tx.category + "
";
		}

		if(tx.confirmations != undefined) html += "Confirmations: " + tx.confirmations + "
";
		if(tx.fee != undefined) html += "Fee: " + tx.fee.formatBTC() + "
";
		if(tx.comment != "" && tx.comment != undefined) html += "Comment: " + tx.comment + "
";

		return html;
	}

	this.renderRow = function(tx) {
		var confirmations = tx.confirmations<10?tx.confirmations:'✓';

		if (tx.category == "generate")
			confirmations = tx.confirmations<settings.generateConfirm?'&#x2717':'&#x2713';

		var timestamp = new Date();
		timestamp.setTime (tx.time * 1000);

		var info = tx.category.capitalize();

		if (tx.category == 'send')
			if (tx.to)
				info = tx.to;
			else
				info = tx.address;

		if (tx.category == 'receive')
			if (tx.from)
				info = tx.from;
			else
				info = tx.address;

		if (tx.comment)
			info += " (" + tx.comment + ")";

		if (tx.category == 'move')
			info = (tx.amount<0?"to ":"from ") + tx.otheraccount.prettyAccount();

		var amountClass = (tx.amount<0?'debit':'credit');

		var html = '' + confirmations + '	';
		html += '' + timestamp.format(app.dateFormat) + '	';
		html += '' + info + '	';
		html += '' + tx.amount.formatBTC(true) + '	';

		return html;
	}

	this.refresh = function() {
		app.bitcoin.listTransactions(jQuery.proxy(this, 'processRPC'));
	}
}
<commit_msg>fix sortTX function<commit_after>/*
 * Copyright (c) 2010 Nils Schneider
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/* settings:
 * {
 *  generateConfirm: 120
 * }
 */
function TXList(list, app, settings) {
	this.sortTX = function(a, b) {
		if(a.time != b.time)
			return (a.time - b.time);

		if(a.category != b.category)
			return (b.category < a.category) ? -1 : 1;

		return (b.amount - a.amount);
	}

	this.clear = function() {
		list.children().remove();
	}

	this.processRPC = function(transactions) {
		var start = new Date().getTime();

		var transactions = jQuery.grep(transactions,
				function(n, i) {
					return n.account == app.bitcoin.settings.account;
				});

		transactions.sort(this.sortTX);

		list.children('#txlistempty').remove();

		if (transactions.length == 0)
			list.append('
no transactions
');

		for (var key in transactions)
			this.processTX(transactions[key]);

		list.children('tr:not(.txinfo):odd').addClass('odd').next('.txinfo').addClass('odd');
		list.children('tr:not(.txinfo):even').removeClass('odd').next('.txinfo').removeClass('odd');

		/* adjust refresh interval of app depending processing time of txlist */
		var end = new Date().getTime();
		var time = end - start;
		app.setRefreshInterval(time * 10);
	}

	this.processTX = function(tx) {
		if (tx.time == undefined)
			tx.time = 0;

		if (tx.txid == undefined)
			tx.txid = (tx.time + tx.amount + tx.otheraccount).replace(/ /g,'');

		tx.txid += tx.category;

		var txrow = $(document.getElementById(tx.txid));

		if (txrow.length == 0) {
			txrow = $('

');
			list.prepend(txrow);
			var txdiv = $('

');
			txrow.after(txdiv);

			txrow.click( function() {
					$(this).next('tr.txinfo').children('td').children('div').slideToggle('fast');
				});
		}

		var checksum = tx.txid + tx.confirmations + tx.time;

		/* Only update TX if it differs from current one */
		if(txrow.attr('checksum') != checksum) {
			txrow.attr('checksum', checksum);
			txrow.html(this.renderRow(tx));

			txrow.next('tr.txinfo').children('td').children('div').html(this.renderInfo(tx));

			if (tx.confirmations == 0 || (tx.category == "generate" && tx.confirmations < settings.generateConfirm))
				txrow.addClass("unconfirmed");
			else
				txrow.removeClass("unconfirmed");
		}
	}

	this.renderInfo = function(tx) {
		var html = "";
		var extra = "";

		switch (tx.category) {
			case "generate":
				html += "Generated coins
";
				break;
			case "move":
				html += "Moved " + (tx.amount<0?"to":"from") + ": " + tx.otheraccount.prettyAccount() + "
";
				break;
			case "send":
				if (tx.to)
					extra = " (" + tx.to + ")";
				html += "Sent to: " + tx.address + extra + "
";
				break;
			case "receive":
				if (tx.from)
					extra = " (" + tx.from + ")";
				html += "Received on: " + tx.address + extra + "
";
				break;
			default:
				html += "Category: " + tx.category + "
";
		}

		if(tx.confirmations != undefined) html += "Confirmations: " + tx.confirmations + "
";
		if(tx.fee != undefined) html += "Fee: " + tx.fee.formatBTC() + "
";
		if(tx.comment != "" && tx.comment != undefined) html += "Comment: " + tx.comment + "
";

		return html;
	}

	this.renderRow = function(tx) {
		var confirmations = tx.confirmations<10?tx.confirmations:'✓';

		if (tx.category == "generate")
			confirmations = tx.confirmations<settings.generateConfirm?'&#x2717':'&#x2713';

		var timestamp = new Date();
		timestamp.setTime (tx.time * 1000);

		var info = tx.category.capitalize();

		if (tx.category == 'send')
			if (tx.to)
				info = tx.to;
			else
				info = tx.address;

		if (tx.category == 'receive')
			if (tx.from)
				info = tx.from;
			else
				info = tx.address;

		if (tx.comment)
			info += " (" + tx.comment + ")";

		if (tx.category == 'move')
			info = (tx.amount<0?"to ":"from ") + tx.otheraccount.prettyAccount();

		var amountClass = (tx.amount<0?'debit':'credit');

		var html = '' + confirmations + '	';
		html += '' + timestamp.format(app.dateFormat) + '	';
		html += '' + info + '	';
		html += '' + tx.amount.formatBTC(true) + '	';

		return html;
	}

	this.refresh = function() {
		app.bitcoin.listTransactions(jQuery.proxy(this, 'processRPC'));
	}
}
<|endoftext|>


<commit_before>module.exports = Cli

var defaults = require('defaults')
var minimist = require('minimist')
var stdin = require('get-stdin')

function Cli (opts) {
  var standard = require('../').linter(opts)

  opts = defaults(opts, {
    cmd: 'standard-engine',
    tagline: 'JavaScript Custom Style',
    version: require('../package.json').version,
    formatter: require('standard-format')
  })

  var typeFormatter = typeof opts.formatter

  if (typeFormatter !== 'object' || typeof opts.formatter.transform !== 'function') {
    console.error('Invalid formatter API')
    process.exit(0)
  }

  var argv = minimist(process.argv.slice(2), {
    alias: {
      help: 'h',
      verbose: 'v'
    },
    boolean: [
      'help',
      'stdin',
      'verbose',
      'version'
    ]
  })

  // flag `-` is equivalent to `--stdin`
  if (argv._[0] === '-') {
    argv.stdin = true
    argv._.shift()
  }

  if (argv.help) {
    if (opts.tagline) console.log('%s - %s', opts.cmd, opts.tagline)
    console.log(function () {
    /*

    Usage:
        %s <flags> [FILES...]

        If FILES is omitted, then all JavaScript source files (*.js, *.jsx) in the current
        working directory are checked, recursively.

        Certain paths (node_modules/, .git/, coverage/, *.min.js, bundle.js) are
        automatically excluded.

    Flags:
        -v, --verbose   Show error codes. (so you can ignore specific rules)
            --stdin     Read file text from stdin.
            --version   Show current version.
        -h, --help      Show usage information.

    */
    }.toString().split(/\n/).slice(2, -2).join('\n'), opts.cmd)

    if (opts.homepage) console.log('Readme: %s', opts.homepage)
    if (opts.bugs) console.log('Report bugs: %s\n', opts.homepage)

    process.exit(0)
  }

  if (argv.version) {
    console.log(opts.version)
    process.exit(0)
  }

  if (argv.stdin) {
    stdin(function (text) {
      standard.lintText(text, onResult)
    })
  } else {
    var lintOpts = {}
    standard.lintFiles(argv._, lintOpts, onResult)
  }

  function onResult (err, result) {
    if (err) return onError(err)
    if (result.errorCount === 0) process.exit(0)

    console.error(
      opts.cmd + ': Use %s (%s) ',
      opts.tagline,
      opts.homepage
    )

    result.results.forEach(function (result) {
      result.messages.forEach(function (message) {
        log(
          '  %s:%d:%d: %s%s',
          result.filePath, message.line || 0, message.column || 0, message.message,
          argv.verbose ? ' (' + message.ruleId + ')' : ''
        )
      })
    })

    process.exit(1)
  }

  function onError (err) {
    console.error(opts.cmd + ': Unexpected linter output:\n')
    console.error(err.stack || err.message || err)
    console.error(
      '\nIf you think this is a bug in `%s`, open an issue: %s',
      opts.cmd, opts.bugs
    )
    process.exit(1)
  }

  /**
   * Print lint errors to stdout since this is expected output from `standard-engine`.
   * Note: When formatting code from stdin (`standard --stdin --format`), the transformed
   * code is printed to stdout, so print lint errors to stderr in this case.
   */
  function log () {
    if (argv.stdin && argv.format) {
      arguments[0] = opts.cmd + ': ' + arguments[0]
      console.error.apply(console, arguments)
    } else {
      console.log.apply(console, arguments)
    }
  }
}
<commit_msg>add the whole format process inside bind/cmd<commit_after>module.exports = Cli

var defaults = require('defaults')
var minimist = require('minimist')
var stdin = require('get-stdin')
var fs = require('fs')

function Cli (opts) {
  var standard = require('../').linter(opts)

  opts = defaults(opts, {
    cmd: 'standard-engine',
    tagline: 'JavaScript Custom Style',
    version: require('../package.json').version,
    formatter: require('standard-format')
  })

  var typeFormatter = typeof opts.formatter

  if (typeFormatter !== 'object' || typeof opts.formatter.transform !== 'function') {
    console.error('Invalid formatter API')
    process.exit(0)
  }

  var argv = minimist(process.argv.slice(2), {
    alias: {
      help: 'h',
      verbose: 'v',
      format: 'F'
    },
    boolean: [
      'help',
      'stdin',
      'verbose',
      'version',
      'format'
    ]
  })

  // flag `-` is equivalent to `--stdin`
  if (argv._[0] === '-') {
    argv.stdin = true
    argv._.shift()
  }

  if (argv.help) {
    if (opts.tagline) console.log('%s - %s', opts.cmd, opts.tagline)
    console.log(function () {
    /*

    Usage:
        %s <flags> [FILES...]

        If FILES is omitted, then all JavaScript source files (*.js, *.jsx) in the current
        working directory are checked, recursively.

        Certain paths (node_modules/, .git/, coverage/, *.min.js, bundle.js) are
        automatically excluded.

    Flags:
        -v, --verbose   Show error codes. (so you can ignore specific rules)
            --stdin     Read file text from stdin.
            --version   Show current version.
        -h, --help      Show usage information.
        -F  --format    Automatically format code. (default standard-format)

    */
    }.toString().split(/\n/).slice(2, -2).join('\n'), opts.cmd)

    if (opts.homepage) console.log('Readme: %s', opts.homepage)
    if (opts.bugs) console.log('Report bugs: %s\n', opts.homepage)

    process.exit(0)
  }

  if (argv.version) {
    console.log(opts.version)
    process.exit(0)
  }

  if (argv.stdin) {
    stdin(function (text) {
      if (argv.format) {
        text = opts.formatter.transform(text)
        process.stdout.write(text)
      }
      standard.lintText(text, onResult)
    })
  } else {
    var lintOpts = {}
    if (argv.format) {
      lintOpts._onFiles = function (files) {
        files.forEach(function (file) {
          var data = fs.readFileSync(file).toString()
          fs.writeFileSync(file, opts.formatter.transform(data))
        })
      }
    }
    standard.lintFiles(argv._, lintOpts, onResult)
  }

  function onResult (err, result) {
    if (err) return onError(err)
    if (result.errorCount === 0) process.exit(0)

    console.error(
      opts.cmd + ': Use %s (%s) ',
      opts.tagline,
      opts.homepage
    )

    result.results.forEach(function (result) {
      result.messages.forEach(function (message) {
        log(
          '  %s:%d:%d: %s%s',
          result.filePath, message.line || 0, message.column || 0, message.message,
          argv.verbose ? ' (' + message.ruleId + ')' : ''
        )
      })
    })

    process.exit(1)
  }

  function onError (err) {
    console.error(opts.cmd + ': Unexpected linter output:\n')
    console.error(err.stack || err.message || err)
    console.error(
      '\nIf you think this is a bug in `%s`, open an issue: %s',
      opts.cmd, opts.bugs
    )
    process.exit(1)
  }

  /**
   * Print lint errors to stdout since this is expected output from `standard-engine`.
   * Note: When formatting code from stdin (`standard --stdin --format`), the transformed
   * code is printed to stdout, so print lint errors to stderr in this case.
   */
  function log () {
    if (argv.stdin && argv.format) {
      arguments[0] = opts.cmd + ': ' + arguments[0]
      console.error.apply(console, arguments)
    } else {
      console.log.apply(console, arguments)
    }
  }
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Container, Grid, SchemaLoader } from 'olymp-fela';
import { graphql, gql, Link } from 'olymp';
import moment from 'moment';
import { sortBy, range } from 'lodash';
import { H2, Panel, Item } from '../components';
import { Column, Content, Img } from './magazin';

const loaderSchema = [
  {
    height: 0,
  },
  {
    width: 'container',
    grid: [
      {
        medium: 7,
        children: range(9).map(() => ({
          height: 180,
          width: '100%',
        })),
      },
      {
        medium: 5,
        height: 500,
      },
    ],
  },
];

const getItems = (items, filter, title) =>
  sortBy(items.filter(filter), ['date']).reverse().slice(0, 5).map(item =>
    (<Item key={item.id}>

        {title(item)}

        {item.name}

      {item.slug &&
        <Link to={{ pathname: `/news${item.slug}` }}>
          Nähere Informationen
        </Link>}
    </Item>)
  );

const NewsItem = (props) => {
  const { art, date, name, description, org, slug } = props;

  const image = props.image || org.logo || {
    url:
    'https://res.cloudinary.com/djyenzorc/image/upload/v1499270971/kdmxe7pl54cqtdfc7ggy.jpg',
    width: 400,
    height: 300,
  };

  return (
    <Panel
      accent={org.color}
      title={name}
      subtitle={`${art} vom ${moment(date).format('DD.MM.YYYY')}`}
    >

      <Content>

          {description}

        {slug && <Link to={{ pathname: `/news${slug}` }}>Weiterlesen...</Link>}
      </Content>
    </Panel>
  );
};

@graphql(
  gql`
    query newsList {
      items: newsList(
        sort: { date: DESC }
        query: { state: { eq: PUBLISHED } }
      ) {
        id
        date
        art
        name
        description
        text
        slug
        image {
          id
          width
          height
          url
          crop
        }
        org {
          id
          name
          logo {
            id
            width
            height
            url
            crop
          }
          color
        }
        author {
          id
          name
        }
      }
    }
  `,
  {
    props: ({ ownProps, data }) => ({
      ...ownProps,
      data,
      isLoading: data.loading,
      items: data.items || [],
    }),
  }
)
class News extends Component {
  render() {
    const { attributes, items, isLoading } = this.props;

    return (
      <SchemaLoader isLoading={isLoading} schema={loaderSchema}>
        <Container {...attributes}>
          <Grid>
            <Grid.Item medium={7} paddingMedium="0 0 0 0.5rem">
              {items.map(item =>
                (<NewsItem
                  {...item}
                  onClick={() =>
                    this.setState({
                      open: open === item.id ? undefined : item.id,
                    })}
                  org={item.org || {}}
                  key={item.id}
                />)
              )}
            </Grid.Item>
            <Column
              medium={4}
              offsetMedium={1}
              offsetLarge={1}
              offsetHuge={1}
              paddingMini="1rem 1rem 0 1rem"
              paddingMedium="0 1rem"
            >

Vorträge & Veranstaltungen

              {getItems(
                items,
                item => item.art === 'VORTRAG' || item.art === 'VERANSTALTUNG',
                item =>
                  `${moment(item.date).format('DD. MMMM YYYY, HH:mm')} Uhr`
              )}

Publikationen

              {getItems(
                items,
                item => item.art === 'PUBLIKATION',
                item => moment(item.date).format('DD. MMMM YYYY')
              )}

Presse

              {getItems(
                items,
                item => item.art === 'PRESSE',
                item => moment(item.date).format('DD. MMMM YYYY')
              )}
            </Column>
          </Grid>
        </Container>
      </SchemaLoader>
    );
  }
}

export default {
  key: 'GZK.Collections.NewsBlock',
  label: 'Neuigkeiten',
  category: 'Collections',
  editable: false,
  component: News,
};
<commit_msg>fix news<commit_after>import React, { Component } from 'react';
import { Container, Grid, SchemaLoader } from 'olymp-fela';
import { graphql, gql, Link } from 'olymp';
import moment from 'moment';
import { sortBy, range } from 'lodash';
import { H2, Panel, Item } from '../components';
import { Column, Content, Img } from './magazin';

const loaderSchema = [
  {
    height: 0,
  },
  {
    width: 'container',
    grid: [
      {
        medium: 7,
        children: range(9).map(() => ({
          height: 180,
          width: '100%',
        })),
      },
      {
        medium: 5,
        height: 500,
      },
    ],
  },
];

const getItems = (items, filter, title) =>
  sortBy(items.filter(filter), ['date']).reverse().slice(0, 5).map(item =>
    (<Item key={item.id}>

        {title(item)}

        {item.name}

      {item.slug &&
        <Link to={{ pathname: `/news${item.slug}` }}>
          Nähere Informationen
        </Link>}
    </Item>)
  );

const NewsItem = (props) => {
  const { art, date, name, description, org, slug } = props;

  const image = props.image || org.logo || {
    url:
    'https://res.cloudinary.com/djyenzorc/image/upload/v1499270971/kdmxe7pl54cqtdfc7ggy.jpg',
    width: 400,
    height: 300,
  };

  return (
    <Panel
      accent={org.color}
      title={name}
      subtitle={`${art} vom ${moment(date).format('DD.MM.YYYY')}`}
    >

      <Content>

          {description}

        {slug && <Link to={{ pathname: `/news${slug}` }}>Weiterlesen...</Link>}
      </Content>
    </Panel>
  );
};

@graphql(
  gql`
    query newsList {
      news: newsList(
        sort: { date: DESC }
        query: { state: { eq: PUBLISHED } }
      ) {
        id
        date
        art
        name
        description
        text
        slug
        image {
          id
          width
          height
          url
          crop
        }
        org {
          id
          name
          logo {
            id
            width
            height
            url
            crop
          }
          color
        }
        author {
          id
          name
        }
      }
    }
  `,
  {
    props: ({ ownProps, data }) => ({
      ...ownProps,
      data,
      isLoading: data.loading,
      news: data.news || [],
    }),
  }
)
@graphql(
  gql`
    query eventList {
      events: eventList(
        sort: { date: DESC }
        query: { state: { eq: PUBLISHED } }
      ) {
        id
        date
        art
        name
        ort
        description
        text
        slug
        image {
          id
          width
          height
          url
          crop
        }
        org {
          id
          name
          logo {
            id
            width
            height
            url
            crop
          }
          color
        }
        author {
          id
          name
        }
      }
    }
  `,
  {
    props: ({ ownProps, data }) => ({
      ...ownProps,
      data,
      isLoading: data.loading,
      events: data.events || [],
    }),
  }
)
class News extends Component {
  render() {
    const { attributes, isLoading, events, news } = this.props;
    const items = sortBy([...events, ...news], 'date').reverse();
    return (
      <SchemaLoader isLoading={isLoading} schema={loaderSchema}>
        <Container {...attributes}>
          <Grid>
            <Grid.Item medium={7} paddingMedium="0 0 0 0.5rem">
              {items.map(item =>
                (<NewsItem
                  {...item}
                  onClick={() =>
                    this.setState({
                      open: open === item.id ? undefined : item.id,
                    })}
                  org={item.org || {}}
                  key={item.id}
                />)
              )}
            </Grid.Item>
            <Column
              medium={4}
              offsetMedium={1}
              offsetLarge={1}
              offsetHuge={1}
              paddingMini="1rem 1rem 0 1rem"
              paddingMedium="0 1rem"
            >

Vorträge & Veranstaltungen

              {getItems(
                events,
                item => true,
                item =>
                  `${moment(item.date).format('DD. MMMM YYYY, HH:mm')} Uhr`
              )}

Publikationen & Presse

              {getItems(
                news,
                item => true,
                item => moment(item.date).format('DD. MMMM YYYY')
              )}
            </Column>
          </Grid>
        </Container>
      </SchemaLoader>
    );
  }
}

export default {
  key: 'GZK.Collections.NewsBlock',
  label: 'Neuigkeiten',
  category: 'Collections',
  editable: false,
  component: News,
};
<|endoftext|>


<commit_before>import styled from 'styled-components';

const HiddenAction = styled.div`
  min-width: 10rem;
  max-width: 12rem;
  flex: 1;
`;

export default HiddenAction;
<commit_msg>fix hidden action width issue<commit_after>import styled from 'styled-components';
import { cellWidth } from '../Permissions/utils/constants';

const HiddenAction = styled.div`
  width: ${cellWidth};
`;

export default HiddenAction;
<|endoftext|>


<commit_before>(function() {

var MAXVALUE          = 1000000;

Dagaz.AI.AI_FRAME     = 3000;
Dagaz.AI.MIN_DEEP     = 5;
Dagaz.AI.MAX_DEEP     = 10;
Dagaz.AI.MAX_MOVES    = 100;
Dagaz.AI.WIN_EVAL     = 100;
Dagaz.AI.DRAW_EVAL    = 50;
Dagaz.AI.NOISE_FACTOR = 10;
Dagaz.AI.UCT_COEFF    = Math.sqrt(2);

function UctAi(parent) {
  this.parent = parent;
}

var findBot = Dagaz.AI.findBot;

Dagaz.AI.findBot = function(type, params, parent) {
  if ((type == "uct") || (type == "common") || (type == "1") || (type == "2")) {
      return new UctAi(parent);
  } else {
      return findBot(type, params, parent);
  }
}

Dagaz.AI.eval = function(design, params, board, player) {
  var r = 0;
  _.each(design.allPositions(), function(pos) {
      var piece = board.getPiece(pos);
      if (piece !== null) {
          var v = design.price[piece.type];
          if (piece.player != player) {
              v = -v;
          }
          r += v;
      }
  });
  return r;
}

Dagaz.AI.heuristic = function(ai, design, board, move) {
  var r = 1;
  var captured = [];
  var price = null;
  _.each(move.actions, function(a) {
      if ((a[0] !== null) && (a[1] === null)) {
          var piece = board.getPiece(a[0][0]);
          if (piece !== null) {
              r += design.price[piece.type];
          }
          captured.push(a[0][0]);
      }
  });
  _.each(move.actions, function(a) {
      if ((a[0] !== null) && (a[1] !== null)) {
          var piece = board.getPiece(a[1][0]);
          if (piece !== null) {
              r += design.price[piece.type];
          }
          piece = board.getPiece(a[0][0]);
          if (price === null) {
              price = design.price[piece.type];
          }
          if (_.indexOf(captured, a[1][0]) >= 0) {
              r -= price;
              return;
          }
          if (piece !== null) {
              r -= (design.price[piece.type] / 2) | 0;
          }
          if ((a[2] !== null) && (a[2][0].type != piece.type)) {
              r += design.price[a[2][0].type];
          }
      }
  });
  return r;
}

var uct = function(win, count, all) {
  return Math.sqrt(Math.log(all) / count) * Dagaz.AI.UCT_COEFF +
         win / count;
}

var simulate = function(design, board, player, move) {
  // TODO: Use checkGoals if there are no moves
  // TODO: Return null if it's a bad move

}

UctAi.prototype.setContext = function(ctx, board) {
  if (this.parent) {
      this.parent.setContext(ctx, board);
  }
  ctx.timestamp = Date.now();
  ctx.board = board;
  delete ctx.cache;
}

UctAi.prototype.getMove = function(ctx) {
  var moves = Dagaz.AI.generate(ctx, ctx.board);
  if (moves.length == 0) {
      return { done: true, ai: "nothing" };
  }
  if (moves.length == 1) {
      return {
           done: true,
           move: moves[0],
           time: Date.now() - ctx.timestamp,
           ai:  "once"
      };
  }
  ctx.cache = _.map(moves, function(move) {
      var weight = Dagaz.AI.heuristic(this, ctx.design, ctx.board, move);
      if (Dagaz.AI.NOISE_FACTOR > 0) {
          weight = weight * Dagaz.AI.NOISE_FACTOR;
          weight += _.random(0, Dagaz.AI.NOISE_FACTOR - 1);
      }
      return {
          m: move,
          h: weight,
          w: 0,
          c: 1
      };
  });
  if (ctx.cache.length > Dagaz.AI.MAX_MOVES) {
      ctx.cache =  _.sortBy(ctx.cache, function(n) {
          return -n.h;
      });
      while (ctx.cache.length > Dagaz.AI.MAX_MOVES) {
          ctx.cache.pop();
      }
  }
  ctx.timestamp = Date.now();
  var start = Dagaz.AI.eval(ctx.design, null, ctx.board, ctx.board.player);
  var cnt = 1;
  while (Date.now() - ctx.timestamp < Dagaz.AI.AI_FRAME) {
      var node = _.max(ctx.cache, function(n) {
          return uct(n.w, n.c, cnt);
      });
      var board  = ctx.board.apply(node.m);
      var result = simulate(ctx.design, board, ctx.board.player, node.m);
      if ((result !== null) && (result > start)) {
          result -= start;
          if (result > Dagaz.AI.WIN_EVAL) {
              result = Dagaz.AI.WIN_EVAL;
          }
          node.w += result;
          node.c += result;
      } else {
          node.c++;
          cnt++;
      }
  }
  var best = _.max(ctx.cache, function(n) {
      return n.w;
  });
  if (best !== null) {
      return {
           done: true,
           move: best.m,
           time: Date.now() - ctx.timestamp,
           ai:  "uct"
      };
  }
  if (this.parent) {
      return this.parent.getMove(ctx);
  }
}

})();
<commit_msg>uct-ai-v5 (simulate)<commit_after>(function() {

var MAXVALUE          = 1000000;

Dagaz.AI.AI_FRAME     = 3000;
Dagaz.AI.KING         = 0;
Dagaz.AI.ONE_KING     = true;
Dagaz.AI.MIN_DEEP     = 5;
Dagaz.AI.MAX_DEEP     = 10;
Dagaz.AI.MAX_MOVES    = 100;
Dagaz.AI.WIN_EVAL     = 100;
Dagaz.AI.DRAW_EVAL    = 50;
Dagaz.AI.NOISE_FACTOR = 10;
Dagaz.AI.UCT_COEFF    = Math.sqrt(2);

function UctAi(parent) {
  this.parent = parent;
}

var findBot = Dagaz.AI.findBot;

Dagaz.AI.findBot = function(type, params, parent) {
  if ((type == "uct") || (type == "common") || (type == "1") || (type == "2")) {
      return new UctAi(parent);
  } else {
      return findBot(type, params, parent);
  }
}

Dagaz.AI.eval = function(design, params, board, player) {
  var r = 0;
  // TODO: cover
  _.each(design.allPositions(), function(pos) {
      var piece = board.getPiece(pos);
      if (piece !== null) {
          var v = design.price[piece.type];
          if (piece.player != player) {
              v = -v;
          }
          r += v;
      }
  });
  return r;
}

Dagaz.AI.heuristic = function(ai, design, board, move) {
  var r = 1;
  var captured = [];
  var price = null;
  _.each(move.actions, function(a) {
      if ((a[0] !== null) && (a[1] === null)) {
          var piece = board.getPiece(a[0][0]);
          if (piece !== null) {
              r += design.price[piece.type];
          }
          captured.push(a[0][0]);
      }
  });
  _.each(move.actions, function(a) {
      if ((a[0] !== null) && (a[1] !== null)) {
          var piece = board.getPiece(a[1][0]);
          if (piece !== null) {
              r += design.price[piece.type];
          }
          piece = board.getPiece(a[0][0]);
          if (price === null) {
              price = design.price[piece.type];
          }
          if (_.indexOf(captured, a[1][0]) >= 0) {
              r -= price;
              return;
          }
          if (piece !== null) {
              r -= (design.price[piece.type] / 2) | 0;
          }
          if ((a[2] !== null) && (a[2][0].type != piece.type)) {
              r += design.price[a[2][0].type];
          }
      }
  });
  return r;
}

var uct = function(win, count, all) {
  return Math.sqrt(Math.log(all) / count) * Dagaz.AI.UCT_COEFF +
         win / count;
}

UctAi.prototype.simulate = function(ctx, board, player, move) {
  var deep = 0;
  var positions = null;
  // TODO: Return null if bad exchange

  while (deep < Dagaz.AI.MAX_DEEP) {
      var moves = Dagaz.AI.generate(ctx, board);
      if (moves.length == 0) {
          var goal = Dagaz.Model.checkGoals(ctx.design, board, player);
          if ((goal === null) && (board.player != player)) return Dagaz.AI.WIN_EVAL;
          if (goal > 0) return Dagaz.AI.WIN_EVAL;
          if (goal == 0) return Dagaz.AI.DRAW_EVAL;
          return null;
      }
      if (board.player == player) {
          deep++;
          positions = [];
          for (var pos = 0; pos < ctx.design.positions.length; pos++) {
               var piece = board.getPiece(pos);
               if ((piece !== null) && (piece.player == player) && (piece.type == Dagaz.AI.KING)) {
                   positions.push(pos);
                   if (Dagaz.AI.ONE_KING) break;
               }
          }
          // TODO: positions = null, if checks

      } else {
          if ((deep >= Dagaz.AI.MIN_DEEP) && (positions !== null)) {
               var f = true;
               for (var i = 0; i < moves.length; i++) {
                    for (var j = 0; j < moves[i].actions.length; j++) {
                         var a = moves[i].actions[j];
                         if ((a[0] !== null) && (a[1] !== null) && (_.indexOf(positions, a[1][0]) >= 0)) {
                             f = false;
                         }
                         if ((a[0] !== null) && (a[1] === null) && (_.indexOf(positions, a[0][0]) >= 0)) {
                             f = false;
                         }
                    }
               }
               if (f) break;
          }
      }
      var nodes = [];
      var all = 0;
      for (var i = 0; i < moves.length; i++) {
           var weight = Dagaz.AI.heuristic(this, ctx.design, board, moves[i]);
           if (weight > 0) {
               nodes.push({
                   m: moves[i],
                   h: weight
               });
               all += weight;
           }
      }
      var lvl = _.random(0, all - 1);
      var all = 0;
      for (var i = 0; i < nodes.length; i++) {
          all += nodes[i].h;
          if (lvl < all) {
              if ((board.player == player) && (positions !== null)) {
                  for (var j = 0; j < nodes[i].m.actions.length; j++) {
                       var a = nodes[i].m.actions[j];
                       if ((a[0] !== null) && (a[1] !== null)) {
                           positions.push(a[1][0]);
                       }
                  }
              }
              board = board.apply(nodes[i].m);
              break;
          }
      }
  }
  return Dagaz.AI.eval(ctx.design, [], board, player);
}

UctAi.prototype.setContext = function(ctx, board) {
  if (this.parent) {
      this.parent.setContext(ctx, board);
  }
  ctx.timestamp = Date.now();
  ctx.board = board;
  delete ctx.cache;
}

UctAi.prototype.getMove = function(ctx) {
  var moves = Dagaz.AI.generate(ctx, ctx.board);
  if (moves.length == 0) {
      return { done: true, ai: "nothing" };
  }
  if (moves.length == 1) {
      return {
           done: true,
           move: moves[0],
           time: Date.now() - ctx.timestamp,
           ai:  "once"
      };
  }
  ctx.cache = _.map(moves, function(move) {
      var weight = Dagaz.AI.heuristic(this, ctx.design, ctx.board, move);
      if (Dagaz.AI.NOISE_FACTOR > 0) {
          weight = weight * Dagaz.AI.NOISE_FACTOR;
          weight += _.random(0, Dagaz.AI.NOISE_FACTOR - 1);
      }
      return {
          m: move,
          h: weight,
          w: 0,
          c: 1
      };
  });
  if (ctx.cache.length > Dagaz.AI.MAX_MOVES) {
      ctx.cache =  _.sortBy(ctx.cache, function(n) {
          return -n.h;
      });
      var cache = [];
      for (var i = 0; i < Dagaz.AI.MAX_MOVES; i++) {
          cache.push(ctx.cache[i]);
      }
      ctx.cache = cache;
  }
  ctx.timestamp = Date.now();
  var start = Dagaz.AI.eval(ctx.design, [], ctx.board, ctx.board.player);
  var cnt = 1;
  while (Date.now() - ctx.timestamp < Dagaz.AI.AI_FRAME) {
      var node = _.max(ctx.cache, function(n) {
          return uct(n.w, n.c, cnt);
      });
      var board  = ctx.board.apply(node.m);
      var result = this.simulate(ctx, board, ctx.board.player, node.m);
      if ((result !== null) && (result > start)) {
          result -= start;
          if (result > Dagaz.AI.WIN_EVAL) {
              result = Dagaz.AI.WIN_EVAL;
          }
          node.w += result;
          node.c += result;
      } else {
          node.c++;
          cnt++;
      }
  }
  var best = _.max(ctx.cache, function(n) {
      return n.w;
  });
  if (best !== null) {
      return {
           done: true,
           move: best.m,
           time: Date.now() - ctx.timestamp,
           ai:  "uct"
      };
  }
  if (this.parent) {
      return this.parent.getMove(ctx);
  }
}

})();
<|endoftext|>


<commit_before>dataviva.load = function(name, url, callBack) {
    var parseAttr = function(data) {
        var attr = {};
        for (var i = 0; i < data.length; ++i) {
            attr[data[i].id] = data[i];
        }

        return attr;
    }

    var requestData = function(loadData) {
        $.ajax({
            dataType: 'json',
            method: 'GET',
            url: url,
            success: function (response) {
                localforage.setItem(url, response, loadData);
            }
        });
    }

    var loadData = function() {
        localforage.getItem(url, function(err, attr) {
            if(attr) {
                window.dataviva[name] = parseAttr(attr.data);
                if (callBack) {
                    callBack(name);
                }
            } else {
                requestData(loadData);
            }
        });
    }

    loadData();
}

dataviva.requireAttrs = function(attrs, callBack) {
    var queue = attrs;

    var ready = function(attr) {
        queue.splice(queue.indexOf(attr), 1);

        if (queue.length == 0) {
            callBack();
        }
    }

    attrs.forEach(function(attr) {
        dataviva.load(attr, '/attrs/'+attr+'/?lang='+lang, ready);
    });
}

dataviva.datatables = {
    language: {
        "loading": dataviva.dictionary['loading'] + "...",
        "emptyTable": dataviva.dictionary['emptyTable'],
        "info": dataviva.dictionary['infoResults'],
        "infoEmpty": dataviva.dictionary['infoEmpty'],
        "infoFiltered": dataviva.dictionary['infoFiltered'],
        "processing": dataviva.dictionary['processing'] + "...",
        "search": dataviva.dictionary['dataTableSearch'] + ":",
        "zeroRecords": dataviva.dictionary['zeroRecords'],
        "decimal": dataviva.language == "pt" ? "," : ".",
        "thousands": dataviva.language == "pt" ? "." : ","
    }
}

function setAlertTimeOut(time) {
    window.setTimeout(function() {
      $(".alert").fadeTo(500, 0).slideUp(500, function(){
          $(this).remove();
      });
    }, time);
}

function showMessage(message, category, timeout) {
    if (category == null) {
        category = 'info';
    }
    $('#message').append(
        '
' +
        '<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>' +
        message +
        '
'
    );
    if (timeout) {
        setAlertTimeOut(timeout);
    }
}

var lang = document.documentElement.lang

if (lang == 'pt') {
    lang_code = 'pt-BR';
} else if (lang == 'en') {
    lang_code = 'en-US';
}

var summernoteConfig = {
    lang: lang_code,
    fontNames: [
        'Arial', 'Arial Black', 'Comic Sans MS', 'Courier New',
        'Helvetica Neue', 'Helvetica', 'Impact', 'Lucida Grande',
        'Open Sans', 'Tahoma', 'Times New Roman', 'Verdana'
      ],
    toolbar: [
        ['style', ['style']],
        ['font', ['bold', 'italic', 'underline', 'clear']],
        ['fontname', ['fontname']],
        ['fontsize', ['fontsize']],
        ['color', ['color']],
        ['para', ['ul', 'ol', 'paragraph']],
        ['table', ['table']],
        ['insert', ['link', 'picture', 'video']],
        ['view', ['fullscreen', 'codeview', 'help']]
      ],
    placeholder: 'Escreva aqui o conteúdo desta publicação'
}

function selectorCallback(id, event) {
    url = window.location.origin + window.location.pathname + '?bra_id='+id;
    window.location = url;
}

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    url = url.toLowerCase();
    name = name.replace(/[\[\]]/g, "\\$&").toLowerCase();

    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

function cropInput(crop, input, callback) {
    if (window.FileReader) {
        input.change(function() {
            var fileReader = new FileReader(),
                    files = this.files,
                    file;

            if (!files.length) {
                return;
            }

            file = files[0];

            if (/^image\/\w+$/.test(file.type) && file.size <= 5242880) {
                fileReader.readAsDataURL(file);
                fileReader.onload = function () {
                    input.val("");
                    crop.cropper("reset", true).cropper("replace", this.result);
                };

                if (callback !== null) {
                    callback();
                }

            } else {
                showMessage("Por favor escolha um arquivo de imagem, com no máximo 5 MB.");
            }
        });
    } else {
        input.addClass("hide");
    }
}

// Create Filter Selector
dataviva.popover.create({
  "id": "filter_popover",
  "width": 600,
  "height": "80%",
  "close": true
})

dataviva.getAttrUrl = function(attr) {
  if (attr == "bra") return 'location';
  else if (attr == "cbo") return 'occupation';
  else if (attr == "cnae") return 'industry';
  else if (attr == "hs") return 'product';
  else if (attr == "wld") return 'trade_partner';
  else if (attr == "university") return 'university';
  else if (attr == "course_hedu") return 'major';
  else if (attr == "course_sc") return 'basic_course';
  else return '';
}

dataviva.getUrlAttr = function(attr) {
  if (attr == "Location") return 'bra';
  else if (attr == "Occupation") return 'cbo';
  else if (attr == "Industry") return 'cnae';
  else if (attr == "Product") return 'hs';
  else if (attr == "Trade_partner") return 'wld';
  else if (attr == "University") return 'university';
  else if (attr == "Major") return 'course_hedu';
  else if (attr == "Basic_course") return 'course_sc';
  else return '';
}

var selectorSearchCallback = Selector()
  .callback(function(d){
    window.location = window.location.pathname + "?" + selectorSearchCallback.type() + "_id="
    + d.id ;
  });

var selectorHrefCallback = Selector()
    .callback(function(d){
        window.location = "/" + lang + "/" + dataviva.getAttrUrl(selectorHrefCallback.type()) + "/" + d.id +
        window.location.search;
    });

var select_attr = function(id) {
  d3.select("#modal-selector-content").call(selectorHrefCallback.type(id));
  $('#modal-selector').modal('show');
}

var select_attr_search = function(id) {
  d3.select("#modal-selector-content").call(selectorSearchCallback.type(id));
  $('#modal-selector').modal('show');
}

d3.selectAll(".profile_simple").on("click", function(){
  // stop from bubbling up so selector isn't triggered
  d3.event.stopPropagation();
})

$(document).ready(function () {
    new WOW().init();
    $("[data-toggle=popover]").popover({ trigger: "hover" });
    $('.counter').counterUp();
    $.stellar();

    $( ".js-switch" ).each(function() {
        var switchery = new Switchery(this, {
            color: '#5A9DC4'
        });
    });

    (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/pt_BR/sdk.js#xfbml=1&version=v2.5&appId=222520191136295";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    $("[name='language-selector']").val(document.documentElement.lang);

    $("[name='language-selector']").change(function() {
        var path = window.location.pathname.split('/'),
            lang = path[1];

        if (lang !== this.value) {
            if (['pt','en'].indexOf(lang) > -1) {
                path.splice(1, 1, this.value);
            } else {
                path.splice(1, 0, this.value);
            }
            window.location.href = path.join('/') + window.location.search + window.location.hash;
        }
    });

    $('a[data-search]').click(function() {
        search($(this).data('search'));
    });
});

var search = function(profile) {
    $('#modal-search .modal-body').empty();
    $('#modal-search .chosen-options .question').empty();
    $('#modal-search #search-advance').prop("disabled", true);
    var search_load = new dataviva.ui.loading($('#modal-search .modal-body').get(0));
    search_load.text(dataviva.dictionary['loading']);

    $('#modal-search').modal('show');

    $.ajax({
      method: "GET",
      url: "/" + lang + "/search/profile/" + profile,
      success: function (response) {
        search_load.hide();

        $('#modal-search .modal-title').html(response.profile);
        $('#modal-search .modal-body').html(response.template);

        for (i in response.questions) {

            var question = $("

").addClass("selector-list-item");
            question.append("

").addClass("item-title").html(response.questions[i].question);

            question.click(function() {
                $('#modal-search .chosen-options .question').html($(this).html());
                $('#modal-search #search-advance').prop("disabled", false);
                $(this).siblings('.selected')   .toggleClass('selected');
                $(this).toggleClass('selected');
            });

            $('#modal-search .selector-list .list-group').append(question);
        }
      }
    })
}<commit_msg>Fixes #907<commit_after>dataviva.load = function(name, url, callBack) {
    var parseAttr = function(data) {
        var attr = {};
        for (var i = 0; i < data.length; ++i) {
            attr[data[i].id] = data[i];
        }

        return attr;
    }

    var requestData = function(loadData) {
        $.ajax({
            dataType: 'json',
            method: 'GET',
            url: url,
            success: function (response) {
                localforage.setItem(url, response, loadData);
            }
        });
    }

    var loadData = function() {
        localforage.getItem(url, function(err, attr) {
            if(attr) {
                window.dataviva[name] = parseAttr(attr.data);
                if (callBack) {
                    callBack(name);
                }
            } else {
                requestData(loadData);
            }
        });
    }

    loadData();
}

dataviva.requireAttrs = function(attrs, callBack) {
    var queue = attrs;

    var ready = function(attr) {
        queue.splice(queue.indexOf(attr), 1);

        if (queue.length == 0) {
            callBack();
        }
    }

    attrs.forEach(function(attr) {
        dataviva.load(attr, '/attrs/'+attr+'/?lang='+lang, ready);
    });
}

dataviva.datatables = {
    language: {
        "loading": dataviva.dictionary['loading'] + "...",
        "emptyTable": dataviva.dictionary['emptyTable'],
        "info": dataviva.dictionary['infoResults'],
        "infoEmpty": dataviva.dictionary['infoEmpty'],
        "infoFiltered": dataviva.dictionary['infoFiltered'],
        "processing": dataviva.dictionary['processing'] + "...",
        "search": dataviva.dictionary['dataTableSearch'] + ":",
        "zeroRecords": dataviva.dictionary['zeroRecords'],
        "decimal": dataviva.language == "pt" ? "," : ".",
        "thousands": dataviva.language == "pt" ? "." : ","
    }
}

function setAlertTimeOut(time) {
    window.setTimeout(function() {
      $(".alert").fadeTo(500, 0).slideUp(500, function(){
          $(this).remove();
      });
    }, time);
}

function showMessage(message, category, timeout) {
    if (category == null) {
        category = 'info';
    }
    $('#message').append(
        '
' +
        '<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>' +
        message +
        '
'
    );
    if (timeout) {
        setAlertTimeOut(timeout);
    }
}

var lang = document.documentElement.lang

if (lang == 'pt') {
    lang_code = 'pt-BR';
} else if (lang == 'en') {
    lang_code = 'en-US';
}

var summernoteConfig = {
    lang: lang_code,
    fontNames: [
        'Arial', 'Arial Black', 'Comic Sans MS', 'Courier New',
        'Helvetica Neue', 'Helvetica', 'Impact', 'Lucida Grande',
        'Open Sans', 'Tahoma', 'Times New Roman', 'Verdana'
      ],
    toolbar: [
        ['style', ['style']],
        ['font', ['bold', 'italic', 'underline', 'clear']],
        ['fontname', ['fontname']],
        ['fontsize', ['fontsize']],
        ['color', ['color']],
        ['para', ['ul', 'ol', 'paragraph']],
        ['table', ['table']],
        ['insert', ['link', 'picture', 'video']],
        ['view', ['fullscreen', 'codeview', 'help']]
      ],
    placeholder: 'Escreva aqui o conteúdo desta publicação'
}

function selectorCallback(id, event) {
    url = window.location.origin + window.location.pathname + '?bra_id='+id;
    window.location = url;
}

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    url = url.toLowerCase();
    name = name.replace(/[\[\]]/g, "\\$&").toLowerCase();

    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

function cropInput(crop, input, callback) {
    if (window.FileReader) {
        input.change(function() {
            var fileReader = new FileReader(),
                    files = this.files,
                    file;

            if (!files.length) {
                return;
            }

            file = files[0];

            if (/^image\/\w+$/.test(file.type) && file.size <= 5242880) {
                fileReader.readAsDataURL(file);
                fileReader.onload = function () {
                    input.val("");
                    crop.cropper("reset", true).cropper("replace", this.result);
                };

                if (callback !== null) {
                    callback();
                }

            } else {
                showMessage("Por favor escolha um arquivo de imagem, com no máximo 5 MB.");
            }
        });
    } else {
        input.addClass("hide");
    }
}

// Create Filter Selector
dataviva.popover.create({
  "id": "filter_popover",
  "width": 600,
  "height": "80%",
  "close": true
})

dataviva.getAttrUrl = function(attr) {
  if (attr == "bra") return 'location';
  else if (attr == "cbo") return 'occupation';
  else if (attr == "cnae") return 'industry';
  else if (attr == "hs") return 'product';
  else if (attr == "wld") return 'trade_partner';
  else if (attr == "university") return 'university';
  else if (attr == "course_hedu") return 'major';
  else if (attr == "course_sc") return 'basic_course';
  else return attr;
}

dataviva.getUrlAttr = function(attr) {
  if (attr == "Location") return 'bra';
  else if (attr == "Occupation") return 'cbo';
  else if (attr == "Industry") return 'cnae';
  else if (attr == "Product") return 'hs';
  else if (attr == "Trade_partner") return 'wld';
  else if (attr == "University") return 'university';
  else if (attr == "Major") return 'course_hedu';
  else if (attr == "Basic_course") return 'course_sc';
  else return attr;
}

var selectorSearchCallback = Selector()
  .callback(function(d){
    window.location = window.location.pathname + "?" + selectorSearchCallback.type() + "_id="
    + d.id ;
  });

var selectorHrefCallback = Selector()
    .callback(function(d){
        window.location = "/" + lang + "/" + dataviva.getAttrUrl(selectorHrefCallback.type()) + "/" + d.id +
        window.location.search;
    });

var select_attr = function(id) {
  d3.select("#modal-selector-content").call(selectorHrefCallback.type(id));
  $('#modal-selector').modal('show');
}

var select_attr_search = function(id) {
  d3.select("#modal-selector-content").call(selectorSearchCallback.type(id));
  $('#modal-selector').modal('show');
}

d3.selectAll(".profile_simple").on("click", function(){
  // stop from bubbling up so selector isn't triggered
  d3.event.stopPropagation();
})

$(document).ready(function () {
    new WOW().init();
    $("[data-toggle=popover]").popover({ trigger: "hover" });
    $('.counter').counterUp();
    $.stellar();

    $( ".js-switch" ).each(function() {
        var switchery = new Switchery(this, {
            color: '#5A9DC4'
        });
    });

    (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/pt_BR/sdk.js#xfbml=1&version=v2.5&appId=222520191136295";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    $("[name='language-selector']").val(document.documentElement.lang);

    $("[name='language-selector']").change(function() {
        var path = window.location.pathname.split('/'),
            lang = path[1];

        if (lang !== this.value) {
            if (['pt','en'].indexOf(lang) > -1) {
                path.splice(1, 1, this.value);
            } else {
                path.splice(1, 0, this.value);
            }
            window.location.href = path.join('/') + window.location.search + window.location.hash;
        }
    });

    $('a[data-search]').click(function() {
        search($(this).data('search'));
    });
});

var search = function(profile) {

    // Reset modal and set loading
    $('#modal-search .modal-body').empty();
    $('#modal-search .chosen-options .question').empty();
    $('#modal-search #chosen-options').val('');
    $('#modal-search #search-advance').prop("disabled", true);
    var search_load = new dataviva.ui.loading($('#modal-search .modal-body').get(0));
    search_load.text(dataviva.dictionary['loading']);

    $('#modal-search').modal('show');

    $.ajax({
      method: "GET",
      url: "/" + lang + "/search/profile/" + profile,
      success: function (response) {
        search_load.hide();

        var questions = response.questions;
        // Set modal template
        $('#modal-search .modal-title').html(response.profile);
        $('#modal-search .modal-body').html(response.template);

        var chosenOptions = $('#modal-search .chosen-options');

        $('#modal-search #search-advance').click(function() {
            var id = chosenOptions.find('#question-id').val();
            var awnser = questions[id].awnser;

            chosenOptions.find('input:not(#question-id)').each(function() {
                if (this.value == "") {
                    $('#modal-search .modal-body').empty();
                    d3.select("#modal-search-content").call(selectorHrefCallback.type(this.id));
                    return false;
                }
            });
        });

        for (id in questions) {

            var question = questions[id],
                selectors = questions[id].selectors,
                div = $('

').addClass('selector-list-item');

            // Append questions
            div.append('

')
                    .addClass('item-title')
                    .html(question.description)
                    .data('id', id)
                    .data('selectors', selectors.join(','));

            // Choose Question
            div.click(function() {
                $('#modal-search #search-advance').prop('disabled', false);
                $(this).siblings('.selected').toggleClass('selected');
                $(this).toggleClass('selected');

                chosenOptions.find('.question').html($(this).html());
                chosenOptions.find('#question-id').val($(this).data('id'));
                chosenOptions.find('input:not(#question-id)').remove()

                var selectors = $(this).data('selectors').split(',')

                for (var i = 0; i < selectors.length; i++) {
                    var selector = selectors[i];
                        selectorInput = $('<input>')
                            .attr('type', 'hidden')
                            .attr('id', selector);
                        chosenOptions.append(selectorInput);
                }
            });

            $('#modal-search .selector-list .list-group').append(div);
        }
      }
    });
}<|endoftext|>


<commit_before>"use strict";

jsns.define("htmlrest.bindingcollection", function (using) {
    var escape = using("htmlrest.escape");
    var typeId = using("htmlrest.typeidentifiers");
    var domQuery = using("htmlrest.domquery");

    //Startswith polyfill
    if (!String.prototype.startsWith) {
        String.prototype.startsWith = function (searchString, position) {
            position = position || 0;
            return this.substr(position, searchString.length) === searchString;
        };
    }

    function EventRunner(name, listener) {
        this.execute = function(evt){
            var cb = listener[name];
            if(cb){
                cb.call(this, evt);
            }
        }
    }

    function bindEvents(elements, listener) {
        for (var eIx = 0; eIx < elements.length; ++eIx) {
            var element = elements[eIx];
            var iter = document.createNodeIterator(element, NodeFilter.SHOW_ELEMENT, function (node) {
                //Look for attribute
                for (var i = 0; i < node.attributes.length; i++) {
                    var attribute = node.attributes[i];
                    if (attribute.name.startsWith('data-hr-on-')) {
                        var runner = new EventRunner(attribute.value, listener);
                        node.addEventListener(attribute.name.substr(11), runner.execute);
                    }
                }
            }, false);
            while(iter.nextNode()){} //Have to walk to get results
        }
    }

    function bindNodes(bindings, elements) {
        for (var key in bindings) {
            var query = '[data-htmlrest-binding=' + key + ']';
            for (var eIx = 0; eIx < elements.length; ++eIx) {
                var element = elements[eIx];
                var child = domQuery.first(query, element);
                if (child) {
                    var elementBindings = bindings[key];
                    for (var name in elementBindings) {
                        child.addEventListener(name, elementBindings[name]);
                    }
                }
            }
        }
    }

    function bindData(data, elements) {
        for (var key in data) {
            var query = '[data-htmlrest-binding=' + key + ']';
            for (var eIx = 0; eIx < elements.length; ++eIx) {
                var element = elements[eIx];
                var child = domQuery.first(query, element);
                if (child) {
                    child.innerHTML = escape(data[key]);
                }
            }
        }
    }

    function lookupNodeInArray(bindingName, elements) {
        var query = '[data-htmlrest-binding=' + bindingName + ']';
        for (var eIx = 0; eIx < elements.length; ++eIx) {
            var element = elements[eIx];
            var child = domQuery.first(query, element);
            if (child) {
                return child;
            }
            else {
                return null;
            }
        }
    }

    function iterateNodeArray(bindingName, elements, callback) {
        var query = '[data-htmlrest-binding=' + bindingName + ']';
        for (var eIx = 0; eIx < elements.length; ++eIx) {
            var element = elements[eIx];

            var matchingChildren = domQuery.all(query, element);
            for (var i = 0; i < matchingChildren.length; ++i) {
                callback(matchingChildren[i]);
            }
        }
    }

    function getAllElements(bindingName, elements) {
        var results = [];
        var query = '[data-htmlrest-binding=' + bindingName + ']';
        for (var eIx = 0; eIx < elements.length; ++eIx) {
            var element = elements[eIx];
            domQuery.all(query, element, results);
        }
        return results;
    }

    function OutputBindings(elements) {
        function TextNodeBinding(element, stream) {
            this.output = function (data) {
                element.innerText
            }
        }

        var textNodeBindings = [];
        for (var i = 0; i < elements.length; ++i) {
            var element = elements[i];
            var current = element.firstChild;
            while (current != null) {

            }
        }
    }

    //Constructor
    return function (elements) {
        elements = domQuery.all(elements);

        /**
         * Find the first binding that matches bindingName
         * @param {string} bindingName - The name of the binding to look up.
         * @returns {HTMLElement} - The found element
         */
        this.first = function (bindingName) {
            return lookupNodeInArray(bindingName, elements);
        }

        /**
         * Get the binding that matches input if it is a string.
         * Otherwise just returns input, ideally because you put an htmlelement in there already
         * @param {string|HTMLElement} input
         * @returns {HTMLElement}
         */
        this.firstOrInput = function (input) {
            if (typeId.isString(input)) {
                return lookupNodeInArray(input, elements);
            }
            return input;
        }

        /**
         * Get all bindings that match the given binding name.
         * @param {string} bindingName - the name of the bindings to look up
         * @returns {array} - The array of bindings that match name
         */
        this.all = function (bindingName) {
            return getAllElements(bindingName, elements);
        }

        /**
         * Call callback for each item that matches bindingName
         * @param {type} bindingName - The name of the binding to look up.
         * @param {type} callback - The callback to call for each discovered binding
         */
        this.iterate = function (bindingName, callback) {
            iterateNodeArray(bindingName, elements, callback);
        }

        /**
         * Bind events to items in an element. elements is an array of elements to bind to.
         * This is the same format they are returned from the create functions with.
         * The bindings should be in the following form
         * name is the data-htmlrest-binding name of the element
         * eventNameX is the name of the event you want to bind to (click, submit etc)
         * {
         * name:{
         * eventName: function(){},
         * eventName2: function(){},
         * etc
         * }
         * @param {type} bindings - The bindings to bind
         */
        this.bind = function (bindings) {
            bindNodes(bindings, elements);
        }

        /**
         * Set the listener for this binding collection. This listener will have its functions
         * fired when a matching event is fired.
         * @param {type} listener
         */
        this.setListener = function (listener) {
            bindEvents(elements, listener);
        }

        /**
         * Use the bindings to output data. The inner html of all the matching bindings will be replaced
         * with the values provided by data. The output will be escaped for xss.
         * @param {type} data
         */
        this.output = function (data) {
            bindData(data, elements);
        }
    };
});<commit_msg>Removed old event binding method.<commit_after>"use strict";

jsns.define("htmlrest.bindingcollection", function (using) {
    var escape = using("htmlrest.escape");
    var typeId = using("htmlrest.typeidentifiers");
    var domQuery = using("htmlrest.domquery");

    //Startswith polyfill
    if (!String.prototype.startsWith) {
        String.prototype.startsWith = function (searchString, position) {
            position = position || 0;
            return this.substr(position, searchString.length) === searchString;
        };
    }

    function EventRunner(name, listener) {
        this.execute = function(evt){
            var cb = listener[name];
            if(cb){
                cb.call(this, evt);
            }
        }
    }

    function bindEvents(elements, listener) {
        for (var eIx = 0; eIx < elements.length; ++eIx) {
            var element = elements[eIx];
            var iter = document.createNodeIterator(element, NodeFilter.SHOW_ELEMENT, function (node) {
                //Look for attribute
                for (var i = 0; i < node.attributes.length; i++) {
                    var attribute = node.attributes[i];
                    if (attribute.name.startsWith('data-hr-on-')) {
                        var runner = new EventRunner(attribute.value, listener);
                        node.addEventListener(attribute.name.substr(11), runner.execute);
                    }
                }
            }, false);
            while(iter.nextNode()){} //Have to walk to get results
        }
    }

    function bindData(data, elements) {
        for (var key in data) {
            var query = '[data-htmlrest-binding=' + key + ']';
            for (var eIx = 0; eIx < elements.length; ++eIx) {
                var element = elements[eIx];
                var child = domQuery.first(query, element);
                if (child) {
                    child.innerHTML = escape(data[key]);
                }
            }
        }
    }

    function lookupNodeInArray(bindingName, elements) {
        var query = '[data-htmlrest-binding=' + bindingName + ']';
        for (var eIx = 0; eIx < elements.length; ++eIx) {
            var element = elements[eIx];
            var child = domQuery.first(query, element);
            if (child) {
                return child;
            }
            else {
                return null;
            }
        }
    }

    function iterateNodeArray(bindingName, elements, callback) {
        var query = '[data-htmlrest-binding=' + bindingName + ']';
        for (var eIx = 0; eIx < elements.length; ++eIx) {
            var element = elements[eIx];

            var matchingChildren = domQuery.all(query, element);
            for (var i = 0; i < matchingChildren.length; ++i) {
                callback(matchingChildren[i]);
            }
        }
    }

    function getAllElements(bindingName, elements) {
        var results = [];
        var query = '[data-htmlrest-binding=' + bindingName + ']';
        for (var eIx = 0; eIx < elements.length; ++eIx) {
            var element = elements[eIx];
            domQuery.all(query, element, results);
        }
        return results;
    }

    //Constructor
    return function (elements) {
        elements = domQuery.all(elements);

        /**
         * Find the first binding that matches bindingName
         * @param {string} bindingName - The name of the binding to look up.
         * @returns {HTMLElement} - The found element
         */
        this.first = function (bindingName) {
            return lookupNodeInArray(bindingName, elements);
        }

        /**
         * Get the binding that matches input if it is a string.
         * Otherwise just returns input, ideally because you put an htmlelement in there already
         * @param {string|HTMLElement} input
         * @returns {HTMLElement}
         */
        this.firstOrInput = function (input) {
            if (typeId.isString(input)) {
                return lookupNodeInArray(input, elements);
            }
            return input;
        }

        /**
         * Get all bindings that match the given binding name.
         * @param {string} bindingName - the name of the bindings to look up
         * @returns {array} - The array of bindings that match name
         */
        this.all = function (bindingName) {
            return getAllElements(bindingName, elements);
        }

        /**
         * Call callback for each item that matches bindingName
         * @param {type} bindingName - The name of the binding to look up.
         * @param {type} callback - The callback to call for each discovered binding
         */
        this.iterate = function (bindingName, callback) {
            iterateNodeArray(bindingName, elements, callback);
        }

        /**
         * Set the listener for this binding collection. This listener will have its functions
         * fired when a matching event is fired.
         * @param {type} listener
         */
        this.setListener = function (listener) {
            bindEvents(elements, listener);
        }

        /**
         * Use the bindings to output data. The inner html of all the matching bindings will be replaced
         * with the values provided by data. The output will be escaped for xss.
         * @param {type} data
         */
        this.output = function (data) {
            bindData(data, elements);
        }
    };
});<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var App = require('app');

App.HighAvailabilityWizardStep5Controller = App.HighAvailabilityProgressPageController.extend({

  name:"highAvailabilityWizardStep5Controller",

  isHA: true,

  commands: ['stopAllServices', 'installNameNode', 'installJournalNodes', 'reconfigureHDFS', 'startJournalNodes', 'disableSNameNode'],

  hdfsSiteTag : "",
  coreSiteTag : "",

  stopAllServices: function () {
    App.ajax.send({
      name: 'admin.high_availability.stop_all_services',
      sender: this,
      success: 'startPolling',
      error: 'onTaskError'
    });
  },

  installNameNode: function () {
    var hostName = this.get('content.masterComponentHosts').findProperty('isAddNameNode').hostName;
    this.createComponent('NAMENODE', hostName);
  },

  installJournalNodes: function () {
    App.ajax.send({
      name: 'admin.high_availability.create_journalnode',
      sender: this,
      success: 'onJournalNodeCreate',
      error: 'onJournalNodeCreate'
    });
  },

  onJournalNodeCreate: function () {
    var hostNames = this.get('content.masterComponentHosts').filterProperty('component', 'JOURNALNODE').mapProperty('hostName');
    this.createComponent('JOURNALNODE', hostNames);
  },

  startJournalNodes: function () {
    var hostNames = this.get('content.masterComponentHosts').filterProperty('component', 'JOURNALNODE').mapProperty('hostName');
    this.startComponent('JOURNALNODE', hostNames);
  },

  disableSNameNode: function () {
    var hostName = this.get('content.masterComponentHosts').findProperty('component', 'SECONDARY_NAMENODE').hostName;
    App.ajax.send({
      name: 'admin.high_availability.maintenance_mode',
      sender: this,
      data: {
        hostName: hostName,
        componentName: 'SECONDARY_NAMENODE'
      },
      success: 'onTaskCompleted',
      error: 'onTaskError'
    });
  },

  reconfigureHDFS: function () {
    var data = this.get('content.serviceConfigProperties');
    var hdfsSiteProperties = data.items.findProperty('type', 'hdfs-site').properties;
    var coreSiteProperties = data.items.findProperty('type', 'core-site').properties;
    var self = this;
    App.ajax.send({
      name: 'admin.high_availability.save_configs',
      sender: this,
      data: {
        siteName: 'hdfs-site',
        properties: hdfsSiteProperties
      },
      error: 'onTaskError'
    }).done(function() {
      App.ajax.send({
        name: 'admin.high_availability.save_configs',
        sender: self,
        data: {
          siteName: 'core-site',
          properties: coreSiteProperties
        },
        error: 'onTaskError',
        success: 'installHDFSClients'
      });
    });
  },

  installHDFSClients: function () {
    var nnHostNames = this.get('content.masterComponentHosts').filterProperty('component', 'NAMENODE').mapProperty('hostName');
    var jnHostNames = this.get('content.masterComponentHosts').filterProperty('component', 'JOURNALNODE').mapProperty('hostName');
    var hostNames = $.extend([], nnHostNames, jnHostNames);
    this.createComponent('HDFS_CLIENT', hostNames);
    App.router.get(this.get('content.controllerName')).saveHdfsClientHosts(hostNames);
    App.clusterStatus.setClusterStatus({
      clusterName: this.get('content.cluster.name'),
      clusterState: 'HIGH_AVAILABILITY_DEPLOY',
      wizardControllerName: this.get('content.controllerName'),
      localdb: App.db.data
    });
  }
});

<commit_msg>AMBARI-5270. Initialize shared edits fails while enabling NameNode HA. (jaimin)<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var App = require('app');

App.HighAvailabilityWizardStep5Controller = App.HighAvailabilityProgressPageController.extend({

  name:"highAvailabilityWizardStep5Controller",

  isHA: true,

  commands: ['stopAllServices', 'installNameNode', 'installJournalNodes', 'reconfigureHDFS', 'startJournalNodes', 'disableSNameNode'],

  hdfsSiteTag : "",
  coreSiteTag : "",

  stopAllServices: function () {
    App.ajax.send({
      name: 'admin.high_availability.stop_all_services',
      sender: this,
      success: 'startPolling',
      error: 'onTaskError'
    });
  },

  installNameNode: function () {
    var hostName = this.get('content.masterComponentHosts').findProperty('isAddNameNode').hostName;
    this.createComponent('NAMENODE', hostName);
  },

  installJournalNodes: function () {
    App.ajax.send({
      name: 'admin.high_availability.create_journalnode',
      sender: this,
      success: 'onJournalNodeCreate',
      error: 'onJournalNodeCreate'
    });
  },

  onJournalNodeCreate: function () {
    var hostNames = this.get('content.masterComponentHosts').filterProperty('component', 'JOURNALNODE').mapProperty('hostName');
    this.createComponent('JOURNALNODE', hostNames);
  },

  startJournalNodes: function () {
    var hostNames = this.get('content.masterComponentHosts').filterProperty('component', 'JOURNALNODE').mapProperty('hostName');
    this.startComponent('JOURNALNODE', hostNames);
  },

  disableSNameNode: function () {
    var hostName = this.get('content.masterComponentHosts').findProperty('component', 'SECONDARY_NAMENODE').hostName;
    App.ajax.send({
      name: 'admin.high_availability.maintenance_mode',
      sender: this,
      data: {
        hostName: hostName,
        componentName: 'SECONDARY_NAMENODE'
      },
      success: 'onTaskCompleted',
      error: 'onTaskError'
    });
  },

  reconfigureHDFS: function () {
    var data = this.get('content.serviceConfigProperties');
    var hdfsSiteProperties = data.items.findProperty('type', 'hdfs-site').properties;
    var coreSiteProperties = data.items.findProperty('type', 'core-site').properties;
    var self = this;
    App.ajax.send({
      name: 'admin.high_availability.save_configs',
      sender: this,
      data: {
        siteName: 'hdfs-site',
        properties: hdfsSiteProperties
      },
      error: 'onTaskError'
    }).done(function() {
      App.ajax.send({
        name: 'admin.high_availability.save_configs',
        sender: self,
        data: {
          siteName: 'core-site',
          properties: coreSiteProperties
        },
        error: 'onTaskError',
        success: 'installHDFSClients'
      });
    });
  },

  installHDFSClients: function () {
    var nnHostNames = this.get('content.masterComponentHosts').filterProperty('component', 'NAMENODE').mapProperty('hostName');
    var jnHostNames = this.get('content.masterComponentHosts').filterProperty('component', 'JOURNALNODE').mapProperty('hostName');
    var hostNames = nnHostNames.concat(jnHostNames).uniq();
    this.createComponent('HDFS_CLIENT', hostNames);
    App.router.get(this.get('content.controllerName')).saveHdfsClientHosts(hostNames);
    App.clusterStatus.setClusterStatus({
      clusterName: this.get('content.cluster.name'),
      clusterState: 'HIGH_AVAILABILITY_DEPLOY',
      wizardControllerName: this.get('content.controllerName'),
      localdb: App.db.data
    });
  }
});

<|endoftext|>


<commit_before>#!/usr/bin/env node
var child_process = require('child_process');

function log(msg) {
	process.stdout.write(msg + '\n');
}

module.exports = function(context) {
	var async = context.requireCordovaModule('async');
	var fs = context.requireCordovaModule('fs');
	var path = context.requireCordovaModule('path');
	var deferral = context.requireCordovaModule('q').defer();
	var XmlHelpers = context.requireCordovaModule("cordova-lib/src/util/xml-helpers");
	var et = context.requireCordovaModule('elementtree');

	var byConfigXml = function(next) {
		var configFile = path.join(context.opts.projectRoot, 'config.xml');
		var xml = XmlHelpers.parseElementtreeSync(configFile);

		async.waterfall(
				[
				function(next) {
					var target;
					xml.findall('preference').forEach(function(e) {
						if (e.get('name') === 'deployment-target') target = e.get('value');
					});
					if (!target) target = "8.0";

					var podfile = path.join(context.opts.projectRoot, 'platforms', 'ios', 'Podfile');
					fs.writeFile(podfile, "platform :ios,'" + target + "'\n\n", next);
				},
				function(next) {
					var getParent = function(tag, name) {
						var list = xml.findall(tag);
						var ios;
						list.forEach(function(e) {
							if (e.get('name') === name) ios = e;
						});
						log('Found platform(name=ios): ' + ios);
						if (!ios) {
							log('Creating tag: ' + tag + '(name=' + name + ')');
							ios = et.Element(tag, {name: name});
							xml.getroot().append(ios);
						}
						return ios;
					}
					var script_path = path.join(path.dirname(context.scriptLocation), 'add-bridging_header.rb');
					var child = et.Element('hook', {type: "after_prepare", src: path.relative(context.opts.projectRoot, script_path)});
					getParent('platform', 'ios').append(child);

					fs.writeFile(configFile, xml.write({indent: 4}), 'utf-8', next);
				}
				 ], next);
	}

	var main = function() {
		async.waterfall(
				[
				byConfigXml
				 ],
				function(err, result) {
					if (err) {
						deferral.reject();
					} else {
						deferral.resolve();
					}
				});
	}
	main();
	return deferral.promise;
};
<commit_msg>async モジュールをパスで直接指定<commit_after>#!/usr/bin/env node
var child_process = require('child_process');

function log(msg) {
	process.stdout.write(msg + '\n');
}

module.exports = function(context) {
	var async = context.requireCordovaModule('cordova-lib/node_modules/request/node_modules/form-data/node_modules/async');
	var fs = context.requireCordovaModule('fs');
	var path = context.requireCordovaModule('path');
	var deferral = context.requireCordovaModule('q').defer();
	var XmlHelpers = context.requireCordovaModule("cordova-lib/src/util/xml-helpers");
	var et = context.requireCordovaModule('elementtree');

	var byConfigXml = function(next) {
		var configFile = path.join(context.opts.projectRoot, 'config.xml');
		var xml = XmlHelpers.parseElementtreeSync(configFile);

		async.waterfall(
				[
				function(next) {
					var target;
					xml.findall('preference').forEach(function(e) {
						if (e.get('name') === 'deployment-target') target = e.get('value');
					});
					if (!target) target = "8.0";

					var podfile = path.join(context.opts.projectRoot, 'platforms', 'ios', 'Podfile');
					fs.writeFile(podfile, "platform :ios,'" + target + "'\n\n", next);
				},
				function(next) {
					var getParent = function(tag, name) {
						var list = xml.findall(tag);
						var ios;
						list.forEach(function(e) {
							if (e.get('name') === name) ios = e;
						});
						log('Found platform(name=ios): ' + ios);
						if (!ios) {
							log('Creating tag: ' + tag + '(name=' + name + ')');
							ios = et.Element(tag, {name: name});
							xml.getroot().append(ios);
						}
						return ios;
					}
					var script_path = path.join(path.dirname(context.scriptLocation), 'add-bridging_header.rb');
					var child = et.Element('hook', {type: "after_prepare", src: path.relative(context.opts.projectRoot, script_path)});
					getParent('platform', 'ios').append(child);

					fs.writeFile(configFile, xml.write({indent: 4}), 'utf-8', next);
				}
				 ], next);
	}

	var main = function() {
		async.waterfall(
				[
				byConfigXml
				 ],
				function(err, result) {
					if (err) {
						deferral.reject();
					} else {
						deferral.resolve();
					}
				});
	}
	main();
	return deferral.promise;
};
<|endoftext|>


<commit_before>/**
 * ModalFooter test
 */

import React from 'react';

import { expect } from 'chai';
import { describe, beforeEach, it } from '@bigtest/mocha';
import { mount } from '../../../tests/helpers';

import ModalFooter from '../ModalFooter';
import ModalFooterInteractor from './interactor';

import buttonCss from '../../Button/Button.css';

describe('ModalFooter', () => {
  const modalFooter = new ModalFooterInteractor();
  const primaryButtonId = 'primaryButton';
  const primaryButtonLabel = 'Primary Button';
  const secondaryButtonId = 'secondaryButton';
  const secondaryButtonLabel = 'Secondary Button';

  beforeEach(async () => {
    await mount(
      <ModalFooter
        primaryButton={{
          label: primaryButtonLabel,
          id: primaryButtonId,
        }}
        secondaryButton={{
          label: secondaryButtonLabel,
          id: secondaryButtonId,
        }}
      />
    );
  });

  /**
   * "primaryButton"-prop should render a primary <Button>
   */
  it(`renders a primary button with a label of "${primaryButtonLabel}" when using the primaryButton-prop`, () => {
    const button = modalFooter.$(`#${primaryButtonId}`);
    expect(button.className).to.include(buttonCss.primary);
    expect(button.innerText.trim()).to.equal(primaryButtonLabel);
  });

  /**
   * "secondaryButton"-prop should render a secondary <Button>
   */
  it(`renders a default button with a label of "${secondaryButtonLabel}" when using the secondaryButton-prop`, () => {
    const button = modalFooter.$(`#${secondaryButtonId}`);
    expect(button.className).to.include(buttonCss.default);
    expect(button.innerText.trim()).to.equal(secondaryButtonLabel);
  });
});
<commit_msg>Updated test.<commit_after>/**
 * ModalFooter test
 */

import React from 'react';

import { expect } from 'chai';
import { describe, beforeEach, it } from '@bigtest/mocha';
import { mount } from '../../../tests/helpers';

import ModalFooter from '../ModalFooter';
import ModalFooterInteractor from './interactor';

import buttonCss from '../../Button/Button.css';

describe('ModalFooter', () => {
  const modalFooter = new ModalFooterInteractor();
  const primaryButtonId = 'primaryButton';
  const primaryButtonLabel = 'Primary Button';
  const secondaryButtonId = 'secondaryButton';
  const secondaryButtonLabel = 'Secondary Button';

  beforeEach(async () => {
    await mount(
      <ModalFooter
        primaryButton={{
          label: primaryButtonLabel,
          id: primaryButtonId,
        }}
        secondaryButton={{
          label: secondaryButtonLabel,
          id: secondaryButtonId,
        }}
      />
    );
  });

  /**
   * The "primaryButton"-prop should render a primary <Button>  with the primary button style
   */
  it('renders a primary button when using the primaryButton-prop', () => {
    const button = modalFooter.$(`#${primaryButtonId}`);
    expect(button.className).to.include(buttonCss.primary);
  });

  /**
   * The "secondaryButton"-prop should render a <Button> with the default button style
   */
  it('renders a default button when using the secondaryButton-prop', () => {
    const button = modalFooter.$(`#${secondaryButtonId}`);
    expect(button.className).to.include(buttonCss.default);
  });

  /**
   * Passing a label-key to either secondaryButton or primaryButton
   * should render a button with this label
   */
  it(`renders a button with a label of "${secondaryButtonLabel}" when passing a label-key to any of the button props`, () => {
    const button = modalFooter.$(`#${secondaryButtonId}`);
    expect(button.innerText.trim()).to.equal(secondaryButtonLabel);
  });
});
<|endoftext|>


<commit_before>/* globals girderTest, describe, expect, it, runs, waits, waitsFor  */

girderTest.addCoveredScripts([
    '/clients/web/static/built/plugins/candela/plugin.min.js'
]);

girderTest.startApp();

$(function () {
    describe('Test the candela UI.', function () {

        it('register a user', girderTest.createUser(
            'johndoe', 'john.doe@email.com', 'John', 'Doe', 'password!'
        ));

        it('uploads the data file', function () {
            runs(function () {
                expect($('#g-user-action-menu.open').length).toBe(0);
                $('.g-user-text>a:first').click();
            });
            girderTest.waitForLoad();

            runs(function () {
                expect($('#g-user-action-menu.open').length).toBe(1);
                $('a.g-my-folders').click();
            });
            girderTest.waitForLoad();

            runs(function () {
                $('a.g-folder-list-link:last').click();
            });
            girderTest.waitForLoad();

            waitsFor(function () {
                return $('ol.breadcrumb>li.active').text() === 'Public' &&
                       $('.g-empty-parent-message:visible').length === 1;
            }, 'descending into Public folder');

            girderTest.binaryUpload('clients/web/test/testFile.csv');

            runs(function () {
                $('.g-item-list-link:first').click();
            });
        });

        it('sets up candela inputs and renders the visualization', function () {
            waitsFor(function () {
                return $('.g-item-candela-component').length === 1;
            }, 'the candela component selector to appear');

            runs(function () {
                expect($('.g-item-candela-component option').length).toBeGreaterThan(18);
            });

            waitsFor(function () {
                return $('.g-candela-inputs-container').length === 1;
            }, 'the inputs container to exist');

            runs(function () {
                var inputs = $('.g-candela-inputs-container').children().eq(1).children().children();
                expect(inputs.eq(0).find('label').text()).toBe('Width');
                expect(inputs.eq(1).find('label').text()).toBe('Height');
                expect(inputs.eq(2).find('label').text()).toBe('x');
                expect(inputs.eq(2).find('option').eq(0).text()).toBe('(none)');
                expect(inputs.eq(2).find('option').eq(1).text()).toBe('a');
                expect(inputs.eq(2).find('option').eq(2).text()).toBe('b');
                expect(inputs.eq(2).find('option').eq(3).text()).toBe('c');
                expect(inputs.eq(3).find('label').text()).toBe('y');
                expect(inputs.eq(4).find('label').text()).toBe('color');
                expect(inputs.eq(5).find('label').text()).toBe('hover');
                $('.g-candela-update-vis').click();
            });

            waitsFor(function () {
                return $('.g-candela-vis').find('canvas').length === 1;
            }, 'the vis canvas to be drawn');
        });
    });
});
<commit_msg>Test column rename logic<commit_after>/* globals girderTest, describe, expect, it, runs, waits, waitsFor  */

girderTest.addCoveredScripts([
    '/clients/web/static/built/plugins/candela/plugin.min.js'
]);

girderTest.startApp();

$(function () {
    describe('Test the candela UI.', function () {

        it('register a user', girderTest.createUser(
            'johndoe', 'john.doe@email.com', 'John', 'Doe', 'password!'
        ));

        it('uploads the data file', function () {
            runs(function () {
                expect($('#g-user-action-menu.open').length).toBe(0);
                $('.g-user-text>a:first').click();
            });
            girderTest.waitForLoad();

            runs(function () {
                expect($('#g-user-action-menu.open').length).toBe(1);
                $('a.g-my-folders').click();
            });
            girderTest.waitForLoad();

            runs(function () {
                $('a.g-folder-list-link:last').click();
            });
            girderTest.waitForLoad();

            waitsFor(function () {
                return $('ol.breadcrumb>li.active').text() === 'Public' &&
                       $('.g-empty-parent-message:visible').length === 1;
            }, 'descending into Public folder');

            girderTest.binaryUpload('clients/web/test/testFile.csv');

            runs(function () {
                $('.g-item-list-link:first').click();
            });
        });

        it('sets up candela inputs and renders the visualization', function () {
            waitsFor(function () {
                return $('.g-item-candela-component').length === 1;
            }, 'the candela component selector to appear');

            runs(function () {
                expect($('.g-item-candela-component option').length).toBeGreaterThan(18);
            });

            waitsFor(function () {
                return $('.g-candela-inputs-container').length === 1;
            }, 'the inputs container to exist');

            runs(function () {
                var inputs = $('.g-candela-inputs-container').children().eq(1).children().children();
                expect(inputs.eq(0).find('label').text()).toBe('Width');
                expect(inputs.eq(1).find('label').text()).toBe('Height');
                expect(inputs.eq(2).find('label').text()).toBe('x');
                var values = [];
                for (var i = 0; i < 4; i += 1) {
                    values.push(inputs.eq(2).find('option').eq(i).text());
                }
                values.sort();
                expect(values).toEqual(['(none)', 'a_b', 'c', 'id']);
                expect(inputs.eq(3).find('label').text()).toBe('y');
                expect(inputs.eq(4).find('label').text()).toBe('color');
                expect(inputs.eq(5).find('label').text()).toBe('hover');
                $('.g-candela-update-vis').click();
            });

            waitsFor(function () {
                return $('.g-candela-vis').find('canvas').length === 1;
            }, 'the vis canvas to be drawn');
        });
    });
});
<|endoftext|>