<commit_before>/* globals jasmineRequire, phantom */
// Verify arguments
var system = require('system');
var args;

if(phantom.args) {
    args = phantom.args;
} else {
    args = system.args.slice(1);//use system args for phantom 2.0+
}

if (args.length === 0) {
    console.log("Simple JasmineBDD test runner for phantom.js");
    console.log("Usage: phantomjs-testrunner.js url_to_runner.html");
    console.log("Accepts http:// and file:// urls");
    console.log("");
    console.log("NOTE: This script depends on jasmine.HtmlReporter being used\non the page, for the DOM elements it creates.\n");
    phantom.exit(2);
}
else {
    var fs = require("fs"),
        pages = [],
        page, address, resultsKey, i, l;

    var setupPageFn = function(p, k) {
        return function() {
            overloadPageEvaluate(p);
            setupWriteFileFunction(p, k, fs.separator);
        };
    };

    for (i = 0, l = args.length; i < l; i++) {
        address = args[i];
        console.log("Loading " + address);

        // if provided a url without a protocol, try to use file://
        address = address.indexOf("://") === -1 ? "file://" + address : address;

        // create a WebPage object to work with
        page = require("webpage").create();
        page.url = address;

        // When initialized, inject the reporting functions before the page is loaded
        // (and thus before it will try to utilize the functions)
        resultsKey = "__jr" + Math.ceil(Math.random() * 1000000);
        page.onInitialized = setupPageFn(page, resultsKey);
        page.open(address, processPage(null, page, resultsKey));
        pages.push(page);

        page.onConsoleMessage = logAndWorkAroundDefaultLineBreaking;
    }

    // bail when all pages have been processed
    setInterval(function(){
        var exit_code = 0;
        for (i = 0, l = pages.length; i < l; i++) {
            page = pages[i];
            if (page.__exit_code === null) {
                // wait until later
                return;
            }
            exit_code |= page.__exit_code;
        }
        phantom.exit(exit_code);
    }, 100);
}

// Thanks to hoisting, these helpers are still available when needed above
/**
 * Logs a message. Does not add a line-break for single characters '.' and 'F' or lines ending in ' ...'
 *
 * @param msg
 */
function logAndWorkAroundDefaultLineBreaking(msg) {
    var interpretAsWithoutNewline = /(^(\033\[\d+m)*[\.F](\033\[\d+m)*$)|( \.\.\.$)/;
    if (navigator.userAgent.indexOf("Windows") < 0 && interpretAsWithoutNewline.test(msg)) {
        try {
            system.stdout.write(msg);
        } catch (e) {
            var fs = require('fs');
            fs.write('/dev/stdout', msg, 'w');
        }
    } else {
        console.log(msg);
    }
}

/**
 * Stringifies the function, replacing any %placeholders% with mapped values.
 *
 * @param {function} fn The function to replace occurrences within.
 * @param {object} replacements Key => Value object of string replacements.
 */
function replaceFunctionPlaceholders(fn, replacements) {
    if (replacements && typeof replacements === "object") {
        fn = fn.toString();
        for (var p in replacements) {
            if (replacements.hasOwnProperty(p)) {
                var match = new RegExp("%" + p + "%", "g");
                do {
                    fn = fn.replace(match, replacements[p]);
                } while(fn.indexOf(match) !== -1);
            }
        }
    }
    return fn;
}

/**
 * Replaces the "evaluate" method with one we can easily do substitution with.
 *
 * @param {phantomjs.WebPage} page The WebPage object to overload
 */
function overloadPageEvaluate(page) {
    page._evaluate = page.evaluate;
    page.evaluate = function(fn, replacements) { return page._evaluate(replaceFunctionPlaceholders(fn, replacements)); };
    return page;
}

/** Stubs a fake writeFile function into the test runner.
 *
 * @param {phantomjs.WebPage} page The WebPage object to inject functions into.
 * @param {string} key The name of the global object in which file data should
 *                     be stored for later retrieval.
 */
// TODO: not bothering with error checking for now (closed environment)
function setupWriteFileFunction(page, key, path_separator) {
    page.evaluate(function(){
        window["%resultsObj%"] = {};
        window.fs_path_separator = "%fs_path_separator%";
        window.__phantom_writeFile = function(filename, text) {
            window["%resultsObj%"][filename] = text;
        };
    }, {resultsObj: key, fs_path_separator: path_separator.replace("\\", "\\\\")});
}

/**
 * Returns the loaded page's filename => output object.
 *
 * @param {phantomjs.WebPage} page The WebPage object to retrieve data from.
 * @param {string} key The name of the global object to be returned. Should
 *                     be the same key provided to setupWriteFileFunction.
 */
function getXmlResults(page, key) {
    return page.evaluate(function(){
        return window["%resultsObj%"] || {};
    }, {resultsObj: key});
}

/**
 * Processes a page.
 *
 * @param {string} status The status from opening the page via WebPage#open.
 * @param {phantomjs.WebPage} page The WebPage to be processed.
 */
function processPage(status, page, resultsKey) {
    if (status === null && page) {
        page.__exit_code = null;
        return function(stat){
            processPage(stat, page, resultsKey);
        };
    }
    if (status !== "success") {
        console.error("Unable to load resource: " + address);
        page.__exit_code = 2;
    }
    else {
        var isFinished = function() {
            return page.evaluate(function(){
                // if there's a JUnitXmlReporter, return a boolean indicating if it is finished
                if (window.jasmineReporters && window.jasmineReporters.startTime) {
                    return !!window.jasmineReporters.endTime;
                }
                // otherwise, scrape the DOM for the HtmlReporter "finished in ..." output
                var durElem = document.querySelector(".html-reporter .duration");
                if (!durElem) {
                    durElem = document.querySelector(".jasmine_html-reporter .duration");
                }
                return durElem && durElem.textContent && durElem.textContent.toLowerCase().indexOf("finished in") === 0;
            });
        };
        var getResultsFromHtmlRunner = function() {
            return page.evaluate(function(){
                var resultElem = document.querySelector(".html-reporter .alert .bar");
                if (!resultElem) {
                    resultElem = document.querySelector(".jasmine_html-reporter .alert .bar");
                }
                return resultElem && resultElem.textContent &&
                    resultElem.textContent.match(/(\d+) spec.* (\d+) failure.*/) ||
                   ["Unable to determine success or failure."];
            });
        };
        var timeout = 60000;
        var loopInterval = 100;
        var ival = setInterval(function(){
            if (isFinished()) {
                // get the results that need to be written to disk
                var fs = require("fs"),
                    xml_results = getXmlResults(page, resultsKey),
                    output;
                for (var filename in xml_results) {
                    if (xml_results.hasOwnProperty(filename) && (output = xml_results[filename]) && typeof(output) === "string") {
                        fs.write(filename, output, "w");
                    }
                }

                // print out a success / failure message of the results
                var results = getResultsFromHtmlRunner();
                var failures = Number(results[2]);
                if (failures > 0) {
                    page.__exit_code = 1;
                    clearInterval(ival);
                }
                else {
                    page.__exit_code = 0;
                    clearInterval(ival);
                }
            }
            else {
                timeout -= loopInterval;
                if (timeout <= 0) {
                    console.log('Page has timed out; aborting.');
                    page.__exit_code = 2;
                    clearInterval(ival);
                }
            }
        }, loopInterval);
    }
}
<commit_msg>Don't overload page.evaluate, just call it with the correct page instance<commit_after>/* globals jasmineRequire, phantom */
// Verify arguments
var system = require('system');
var args;

if(phantom.args) {
    args = phantom.args;
} else {
    args = system.args.slice(1);//use system args for phantom 2.0+
}

if (args.length === 0) {
    console.log("Simple JasmineBDD test runner for phantom.js");
    console.log("Usage: phantomjs-testrunner.js url_to_runner.html");
    console.log("Accepts http:// and file:// urls");
    console.log("");
    console.log("NOTE: This script depends on jasmine.HtmlReporter being used\non the page, for the DOM elements it creates.\n");
    phantom.exit(2);
}
else {
    var fs = require("fs"),
        pages = [],
        page, address, resultsKey, i, l;

    var setupPageFn = function(p, k) {
        return function() {
            setupWriteFileFunction(p, k, fs.separator);
        };
    };

    for (i = 0, l = args.length; i < l; i++) {
        address = args[i];
        console.log("Loading " + address);

        // if provided a url without a protocol, try to use file://
        address = address.indexOf("://") === -1 ? "file://" + address : address;

        // create a WebPage object to work with
        page = require("webpage").create();
        page.url = address;

        // When initialized, inject the reporting functions before the page is loaded
        // (and thus before it will try to utilize the functions)
        resultsKey = "__jr" + Math.ceil(Math.random() * 1000000);
        page.onInitialized = setupPageFn(page, resultsKey);
        page.open(address, processPage(null, page, resultsKey));
        pages.push(page);

        page.onConsoleMessage = logAndWorkAroundDefaultLineBreaking;
    }

    // bail when all pages have been processed
    setInterval(function(){
        var exit_code = 0;
        for (i = 0, l = pages.length; i < l; i++) {
            page = pages[i];
            if (page.__exit_code === null) {
                // wait until later
                return;
            }
            exit_code |= page.__exit_code;
        }
        phantom.exit(exit_code);
    }, 100);
}

// Thanks to hoisting, these helpers are still available when needed above
/**
 * Logs a message. Does not add a line-break for single characters '.' and 'F' or lines ending in ' ...'
 *
 * @param msg
 */
function logAndWorkAroundDefaultLineBreaking(msg) {
    var interpretAsWithoutNewline = /(^(\033\[\d+m)*[\.F](\033\[\d+m)*$)|( \.\.\.$)/;
    if (navigator.userAgent.indexOf("Windows") < 0 && interpretAsWithoutNewline.test(msg)) {
        try {
            system.stdout.write(msg);
        } catch (e) {
            var fs = require('fs');
            fs.write('/dev/stdout', msg, 'w');
        }
    } else {
        console.log(msg);
    }
}

/**
 * Stringifies the function, replacing any %placeholders% with mapped values.
 *
 * @param {function} fn The function to replace occurrences within.
 * @param {object} replacements Key => Value object of string replacements.
 */
function replaceFunctionPlaceholders(fn, replacements) {
    if (replacements && typeof replacements === "object") {
        fn = fn.toString();
        for (var p in replacements) {
            if (replacements.hasOwnProperty(p)) {
                var match = new RegExp("%" + p + "%", "g");
                do {
                    fn = fn.replace(match, replacements[p]);
                } while(fn.indexOf(match) !== -1);
            }
        }
    }
    return fn;
}

/**
 * Custom "evaluate" method which we can easily do substitution with.
 *
 * @param {phantomjs.WebPage} page The WebPage object to overload
 * @param {function} fn The function to replace occurrences within.
 * @param {object} replacements Key => Value object of string replacements.
 */
function evaluate(page, fn, replacements) {
    return page.evaluate(replaceFunctionPlaceholders(fn, replacements));
}

/** Stubs a fake writeFile function into the test runner.
 *
 * @param {phantomjs.WebPage} page The WebPage object to inject functions into.
 * @param {string} key The name of the global object in which file data should
 *                     be stored for later retrieval.
 */
// TODO: not bothering with error checking for now (closed environment)
function setupWriteFileFunction(page, key, path_separator) {
    evaluate(page, function(){
        window["%resultsObj%"] = {};
        window.fs_path_separator = "%fs_path_separator%";
        window.__phantom_writeFile = function(filename, text) {
            window["%resultsObj%"][filename] = text;
        };
    }, {resultsObj: key, fs_path_separator: path_separator.replace("\\", "\\\\")});
}

/**
 * Returns the loaded page's filename => output object.
 *
 * @param {phantomjs.WebPage} page The WebPage object to retrieve data from.
 * @param {string} key The name of the global object to be returned. Should
 *                     be the same key provided to setupWriteFileFunction.
 */
function getXmlResults(page, key) {
    return evaluate(page, function(){
        return window["%resultsObj%"] || {};
    }, {resultsObj: key});
}

/**
 * Processes a page.
 *
 * @param {string} status The status from opening the page via WebPage#open.
 * @param {phantomjs.WebPage} page The WebPage to be processed.
 */
function processPage(status, page, resultsKey) {
    if (status === null && page) {
        page.__exit_code = null;
        return function(stat){
            processPage(stat, page, resultsKey);
        };
    }
    if (status !== "success") {
        console.error("Unable to load resource: " + address);
        page.__exit_code = 2;
    }
    else {
        var isFinished = function() {
            return evaluate(page, function(){
                // if there's a JUnitXmlReporter, return a boolean indicating if it is finished
                if (window.jasmineReporters && window.jasmineReporters.startTime) {
                    return !!window.jasmineReporters.endTime;
                }
                // otherwise, scrape the DOM for the HtmlReporter "finished in ..." output
                var durElem = document.querySelector(".html-reporter .duration");
                if (!durElem) {
                    durElem = document.querySelector(".jasmine_html-reporter .duration");
                }
                return durElem && durElem.textContent && durElem.textContent.toLowerCase().indexOf("finished in") === 0;
            });
        };
        var getResultsFromHtmlRunner = function() {
            return evaluate(page, function(){
                var resultElem = document.querySelector(".html-reporter .alert .bar");
                if (!resultElem) {
                    resultElem = document.querySelector(".jasmine_html-reporter .alert .bar");
                }
                return resultElem && resultElem.textContent &&
                    resultElem.textContent.match(/(\d+) spec.* (\d+) failure.*/) ||
                   ["Unable to determine success or failure."];
            });
        };
        var timeout = 60000;
        var loopInterval = 100;
        var ival = setInterval(function(){
            if (isFinished()) {
                // get the results that need to be written to disk
                var fs = require("fs"),
                    xml_results = getXmlResults(page, resultsKey),
                    output;
                for (var filename in xml_results) {
                    if (xml_results.hasOwnProperty(filename) && (output = xml_results[filename]) && typeof(output) === "string") {
                        fs.write(filename, output, "w");
                    }
                }

                // print out a success / failure message of the results
                var results = getResultsFromHtmlRunner();
                var failures = Number(results[2]);
                if (failures > 0) {
                    page.__exit_code = 1;
                    clearInterval(ival);
                }
                else {
                    page.__exit_code = 0;
                    clearInterval(ival);
                }
            }
            else {
                timeout -= loopInterval;
                if (timeout <= 0) {
                    console.log('Page has timed out; aborting.');
                    page.__exit_code = 2;
                    clearInterval(ival);
                }
            }
        }, loopInterval);
    }
}
<|endoftext|>


<commit_before>/*
 * Appcelerator Titanium Mobile
 * Copyright (c) 2015-2016 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

var should = require('./utilities/assertions'),
	utilities = require('./utilities/utilities');

describe('Titanium.UI.AttributedString', function () {
	it('Ti.UI.AttributedString', function () {
		should(Ti.UI.AttributedString).not.be.undefined;
	});

	it('apiName', function () {
		var attributedString = Ti.UI.createAttributedString({text : 'abc'});
		should(attributedString).have.readOnlyProperty('apiName').which.is.a.String;
		should(attributedString.apiName).be.eql('Ti.UI.AttributedString');
	});

	it('createAttributedString', function () {
		should(Ti.UI.createAttributedString).not.be.undefined;
		should(Ti.UI.createAttributedString).be.a.Function;

		var attributedString = Ti.UI.createAttributedString({text : 'abc'});
		should(attributedString).be.a.Object;
		should(attributedString.apiName).be.a.String;
		should(attributedString.apiName).be.eql('Ti.UI.AttributedString');
		should(attributedString.text).be.a.String;
	});

	it('attributes', function() {
		var str = 'Lorem ipsum dolor sit amet.';
		var attributedString = Ti.UI.createAttributedString({
			text : str,
			attributes: [{
				type: Ti.UI.ATTRIBUTE_PARAGRAPH_STYLE,
				value: {
					alignment: Ti.UI.ATTRIBUTE_TEXT_ALIGNMENT_JUSTIFIED,
					minimumLineHeight: 40,
					headIndent: 5,
					lineSpacing: 5,
				},
				range: [0, str.length]
			}]
		});

		should(attributedString.text).be.eql(str);
		should(attributedString.attributes.length).be.eql(1);

		attributedString.addAttribute({
			type : Ti.UI.ATTRIBUTE_FONT,
			value: {fontSize : 16},
			range: [0, str.length]
        });

        should(attributedString.attributes.length).be.eql(2);
	});
});
<commit_msg>[TIMOB-24080] : Linting issue fixed.<commit_after>/*
 * Appcelerator Titanium Mobile
 * Copyright (c) 2015-2016 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

var should = require('./utilities/assertions'),
	utilities = require('./utilities/utilities');

describe('Titanium.UI.AttributedString', function () {
	it('Ti.UI.AttributedString', function () {
		should(Ti.UI.AttributedString).not.be.undefined;
	});

	it('apiName', function () {
		var attributedString = Ti.UI.createAttributedString({text : 'abc'});
		should(attributedString).have.readOnlyProperty('apiName').which.is.a.String;
		should(attributedString.apiName).be.eql('Ti.UI.AttributedString');
	});

	it('createAttributedString', function () {
		should(Ti.UI.createAttributedString).not.be.undefined;
		should(Ti.UI.createAttributedString).be.a.Function;

		var attributedString = Ti.UI.createAttributedString({text : 'abc'});
		should(attributedString).be.a.Object;
		should(attributedString.apiName).be.a.String;
		should(attributedString.apiName).be.eql('Ti.UI.AttributedString');
		should(attributedString.text).be.a.String;
	});

	it('attributes', function() {
		var str = 'Lorem ipsum dolor sit amet.';
		var attributedString = Ti.UI.createAttributedString({
			text: str,
			attributes: [{
				type: Ti.UI.ATTRIBUTE_PARAGRAPH_STYLE,
				value: {
					alignment: Ti.UI.ATTRIBUTE_TEXT_ALIGNMENT_JUSTIFIED,
					minimumLineHeight: 40,
					headIndent: 5,
					lineSpacing: 5
				},
				range: [0, str.length]
			}]
		});

		should(attributedString.text).be.eql(str);
		should(attributedString.attributes.length).be.eql(1);

		attributedString.addAttribute({
			type: Ti.UI.ATTRIBUTE_FONT,
			value: {fontSize : 16},
			range: [0, str.length]
		});
		should(attributedString.attributes.length).be.eql(2);
	});
});
<|endoftext|>


<commit_before>define([
	'backbone',
    'views/currentUserView'
	'controllers/sessionsController'
	], function (Backbone, CurrentUserView, SessionsController) {

	var router = new (Backbone.Router.extend({
            start: function(){
                Backbone.history.start({pushState: true})
            },
            routes:{
                        "/": "checkUser",
                        "sign_in": "loadSignIn",
                        "nav": "loadNav",
                        "logout": "logout"
            },
            checkUser: SessionsController.checkUser(),
            loadSignIn: function(){
            	SessionsController.loggedIn();
                $('body').children().remove();
                $('body').html($('#signIn').html());
            },
            loadNav: function(){
            		//SessionsController.navLoggedIn();
                    //$('.container').children().remove();
                    $('header').html($('#signedInHeaderTemplate').html());
                    var currentUserView = new CurrentUserView({model: currentUser});

                    $('.container').html($('#navTemplate').html());
            },
            logout: function(){
                    SessionsController.logout();
                    this.navigate('/api/logout');
            }
    }));
	return router;
});<commit_msg>fix comma typo<commit_after>define([
	'backbone',
    'views/currentUserView',
	'controllers/sessionsController'
	], function (Backbone, CurrentUserView, SessionsController) {

	var router = new (Backbone.Router.extend({
            start: function(){
                Backbone.history.start({pushState: true})
            },
            routes:{
                        "/": "checkUser",
                        "sign_in": "loadSignIn",
                        "nav": "loadNav",
                        "logout": "logout"
            },
            checkUser: SessionsController.checkUser(),
            loadSignIn: function(){
            	SessionsController.loggedIn();
                $('body').children().remove();
                $('body').html($('#signIn').html());
            },
            loadNav: function(){
            		//SessionsController.navLoggedIn();
                    //$('.container').children().remove();
                    $('header').html($('#signedInHeaderTemplate').html());
                    var currentUserView = new CurrentUserView({model: currentUser});

                    $('.container').html($('#navTemplate').html());
            },
            logout: function(){
                    SessionsController.logout();
                    this.navigate('/api/logout');
            }
    }));
	return router;
});<|endoftext|>


<commit_before>const fs = require('fs');
const indexIn = `${__dirname}/../index.html`;
const indexOut = `${__dirname}/../.tmp/index.html`;
let indexHtml;

try {
  indexHtml = fs.readFileSync(indexIn);
} catch (e) {
  throw new Error(`Unable to read ${indexIn}. ${e}`);
}

try {
  const content = String(indexHtml)
    .replace('<!-- BROWSER_SYNC_PLACEHOLDER (DO NOT REMOVE OR ALTER!) -->', '')
    .replace('// install babel hooks in the renderer process', '')
    .replace('require(\'babel-register\');', '');
  fs.writeFileSync(indexOut, content);
} catch (e) {
  throw new Error(`Unable to write to ${indexOut}. ${e}`);
}
<commit_msg>Require from prod folder<commit_after>const fs = require('fs');
const indexIn = `${__dirname}/../index.html`;
const indexOut = `${__dirname}/../.tmp/index.html`;
let indexHtml;

try {
  indexHtml = fs.readFileSync(indexIn);
} catch (e) {
  throw new Error(`Unable to read ${indexIn}. ${e}`);
}

try {
  const content = String(indexHtml)
    .replace('<!-- BROWSER_SYNC_PLACEHOLDER (DO NOT REMOVE OR ALTER!) -->', '')
    .replace('// install babel hooks in the renderer process', '')
    .replace('require(\'babel-register\');', '')
    .replace('require(\'../js/start\')', 'require(\'../prod/start\')');
  fs.writeFileSync(indexOut, content);
} catch (e) {
  throw new Error(`Unable to write to ${indexOut}. ${e}`);
}
<|endoftext|>


<commit_before>// Adds a helper for django's i18n js api
Handlebars.registerHelper("trans", function() {
    switch(arguments.length) {
        case 1:
            // No text to translate
            return no_trans_key(arguments[0]);
        case 2:
            // A single translation key
            return single(arguments[0], arguments[1]);
        case 3:
            // An invalid plural - treat it like it's single
            return single(arguments[0], arguments[2]);
        case 4:
            // Proper plural
            return plural(arguments[0], arguments[1], arguments[2], arguments[3]);
        default:
            // Something else - just return something empty.
            return no_trans_key({});
    };

    function no_trans_key() {
        return "";
    }

    function single(key, obj) {
        if (undefined === key) {
            console.log("Undefined value for trans - is your msgid in quotes?");
            return "";
        }
        var base = gettext(key);
        return interpolate(base, obj.data, true);
    }

    function plural(key1, key2, count, obj) {
        if (undefined === key) {
            console.log("Undefined value for trans - is your msgid in quotes?");
            return "";
        }
        var base = ngettext(key1, key2, count);
        return interpolate(base, obj.data, true);
    }

});
<commit_msg>Fixes #1<commit_after>// Adds a helper for django's i18n js api
Handlebars.registerHelper("trans", function() {
    switch(arguments.length) {
        case 1:
            // No text to translate
            return no_trans_key(arguments[0]);
        case 2:
            // A single translation key
            return single(arguments[0], arguments[1]);
        case 3:
            // An invalid plural - treat it like it's single
            return single(arguments[0], arguments[2]);
        case 4:
            // Proper plural
            return plural(arguments[0], arguments[1], arguments[2], arguments[3]);
        default:
            // Something else - just return something empty.
            return no_trans_key({});
    };

    function no_trans_key() {
        return "";
    }

    function single(key, obj) {
        if (undefined === key) {
            console.log("Undefined value for trans - is your msgid in quotes?");
            return "";
        }
        var base = gettext(key);
        return interpolate(base, obj.data, true);
    }

    function plural(key1, key2, count, obj) {
        if (undefined === key1) {
            console.log("Undefined value for trans - is your msgid in quotes?");
            return "";
        }
        var base = ngettext(key1, key2, count);
        return interpolate(base, obj.data, true);
    }

});
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { injectIntl } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import Markdown from 'react-markdown';
import Isvg from 'react-inlinesvg';
import styled, {ThemeProvider} from 'styled-components';

import LanguageThemeProvider from 'components/LanguageThemeProvider';
import ContentBlock from 'components/ContentBlock';

import {
  Caption, Container,
  Content, ContentViewport,
  Title, ToolType,
  Viewport,
} from 'components/ToolPage/Header';

import { BR_IMAGE_PREFIX } from 'containers/Tools/constants';
import { RouterLink } from 'utils/markdown';
import ShareIcon from 'assets/images/icons/share-small.svg';
import ShareButton from 'containers/ShareButton';
import TypeFlag from 'components/TypeFlag';
import TypeOverlay from 'components/TypeOverlay';

import TranslatableStaticText from 'containers/TranslatableStaticText';
import staticText from '../staticText';

import InteractiveArea from './InteractiveArea';
import MobileInteractiveArea from './MobileInteractiveArea';
import WhereWhen from 'components/ToolPage/Header/WhereWhen';

const MobileWhenWhereContainer = styled.div`
  position: absolute;
  left: 0;
  top: -15px;
`;
export class Header extends React.PureComponent {
  constructor() {
    super();
  }

  isType(type, key) {
    return this.props.type === type ||
      (this.props[key] && this.props[key].length > 0);
  }

  getBanner() {
    if(this.props['module-type-effective'] === 'snapshot') {
      return (<TypeOverlay type={this.props.type} />);
    } else if ( ['full', 'gallery'].includes(this.props['module-type-effective'])) {
      return (
      <TypeFlag type={this.props.type}
        isPrinciple={this.isType('principle', 'key-principles')}
        isMethodology={this.isType('methodology', 'key-methodologies')}
        isTactic={this.isType('tactic', 'key-tactics')}
        isTheory={this.isType('theory', 'key-theories')}
      />);
    }
  }

  render() {

    return (
      <Container id="XX" backgroundImage={BR_IMAGE_PREFIX+this.props.image}>
        <Viewport showOverflow={this.props['module-type-effective'] !== 'snapshot'}>
          <LanguageThemeProvider>
            <InteractiveArea {...this.props}/>
            <Content id="Content">
              <ContentViewport>
                <MobileWhenWhereContainer>
                  <WhereWhen {...this.props} />
                </MobileWhenWhereContainer>
                <ToolType type={this.props.type}>
                  <Link to={`/type/${this.props.type}`}>
                    <TranslatableStaticText {...staticText[this.props.type]} />
                  </Link>
                </ToolType>
                <Title color={'white'}>
                  {this.props.title}
                </Title>
                <MobileInteractiveArea {...this.props} />
                <Caption
                  show={
                      this.props['image-caption'] !== undefined
                      && this.props.showIfUntranslated('image-caption')
                  }>
                  <Markdown
                    source={'/ ' + this.props['image-caption']}
                    renderers={{Link: RouterLink }} />
                </Caption>
              </ContentViewport>
            </Content>
            { this.getBanner() }
          </LanguageThemeProvider>
        </Viewport>
      </Container>
    );
  }
}

Header.propTypes = {
  dispatch: PropTypes.func.isRequired,
};

function mapDispatchToProps(dispatch) {
  return {
    dispatch
  }
}

export default connect(null, mapDispatchToProps)(injectIntl(Header));
<commit_msg>Fix header area<commit_after>import React, { PropTypes } from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { injectIntl } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import Markdown from 'react-markdown';
import Isvg from 'react-inlinesvg';
import styled, {ThemeProvider} from 'styled-components';

import LanguageThemeProvider from 'components/LanguageThemeProvider';
import ContentBlock from 'components/ContentBlock';

import {
  Caption, Container,
  Content, ContentViewport,
  Title, ToolType,
  Viewport,
} from 'components/ToolPage/Header';

import { BR_IMAGE_PREFIX } from 'containers/Tools/constants';
import { RouterLink } from 'utils/markdown';
import ShareIcon from 'assets/images/icons/share-small.svg';
import ShareButton from 'containers/ShareButton';
import TypeFlag from 'components/TypeFlag';
import TypeOverlay from 'components/TypeOverlay';

import TranslatableStaticText from 'containers/TranslatableStaticText';
import staticText from '../staticText';

import InteractiveArea from './InteractiveArea';
import MobileInteractiveArea from './MobileInteractiveArea';
import WhereWhen from 'components/ToolPage/Header/WhereWhen';

const MobileWhenWhereContainer = styled.div`
  position: absolute;
  left: 0;
  top: -15px;
  display: none;

  @media(max-width: 700px) {
    display: block;
  }
`;
export class Header extends React.PureComponent {
  constructor() {
    super();
  }

  isType(type, key) {
    return this.props.type === type ||
      (this.props[key] && this.props[key].length > 0);
  }

  getBanner() {
    if(this.props['module-type-effective'] === 'snapshot') {
      return (<TypeOverlay type={this.props.type} />);
    } else if ( ['full', 'gallery'].includes(this.props['module-type-effective'])) {
      return (
      <TypeFlag type={this.props.type}
        isPrinciple={this.isType('principle', 'key-principles')}
        isMethodology={this.isType('methodology', 'key-methodologies')}
        isTactic={this.isType('tactic', 'key-tactics')}
        isTheory={this.isType('theory', 'key-theories')}
      />);
    }
  }

  render() {

    return (
      <Container id="XX" backgroundImage={BR_IMAGE_PREFIX+this.props.image}>
        <Viewport showOverflow={this.props['module-type-effective'] !== 'snapshot'}>
          <LanguageThemeProvider>
            <InteractiveArea {...this.props}/>
            <Content id="Content">
              <ContentViewport>
                <MobileWhenWhereContainer>
                  <WhereWhen {...this.props} />
                </MobileWhenWhereContainer>
                <ToolType type={this.props.type}>
                  <Link to={`/type/${this.props.type}`}>
                    <TranslatableStaticText {...staticText[this.props.type]} />
                  </Link>
                </ToolType>
                <Title color={'white'}>
                  {this.props.title}
                </Title>
                <MobileInteractiveArea {...this.props} />
                <Caption
                  show={
                      this.props['image-caption'] !== undefined
                      && this.props.showIfUntranslated('image-caption')
                  }>
                  <Markdown
                    source={'/ ' + this.props['image-caption']}
                    renderers={{Link: RouterLink }} />
                </Caption>
              </ContentViewport>
            </Content>
            { this.getBanner() }
          </LanguageThemeProvider>
        </Viewport>
      </Container>
    );
  }
}

Header.propTypes = {
  dispatch: PropTypes.func.isRequired,
};

function mapDispatchToProps(dispatch) {
  return {
    dispatch
  }
}

export default connect(null, mapDispatchToProps)(injectIntl(Header));
<|endoftext|>


<commit_before>var url = window.location.protocol + '//' + window.location.host;

var stackUrl = 'https://api.stackexchange.com';
var version = '/2.2';

var apiKey = 'LatL0Qaw3)dPKFoK6Y1yiQ((';

var noLoginTemplate = '<button class="btn btn-primary">Log in</button>';
var loginTemplate = '';
var selectorOptionTemplate = '<option value="__VALUE__">__TITLE__</option>';

var accessToken = undefined;
var sites = undefined;

var targetSiteUrl = undefined;

var fromDate = undefined;
var toDate = undefined;

var reputationObjects = {};

$(document).ready(function(){
	$('#login-container').html(noLoginTemplate);

	datePickerInit();

	SE.init({
		clientId: 6388,
		key: apiKey,
		channelUrl: url + '/blank',
		complete: function(data){
			console.log(data);
		}
	});

	$('#login-container button').click(function(event){
		SE.authenticate({
			success: onLoginSuccess,
			error: function(data){
				alert('Something went wrong. Unable to log in');
				console.log(data);
			},
			scope: ['private_info'],
			networkUsers: true
		});
	});

	$('#calculate-button').click(function(event){
		buildReputationObjects();
		doReputationCalculation(reputationObjects);
	});

	$('#site-selector-container select').change(function(event){
		var idx = $(this).val();

		if(idx === ''){
			$(this).parent().addClass('has-error');
			$('#site-selector-container .help-block').removeClass('hidden');
			$('#calculate-btn').addClass('disabled');
		} else{
			$(this).parent().removeClass('has-error');
			$('#site-selector-container .help-block').addClass('hidden');

			console.log(idx);
			setTargetSite(idx);
			$('#calculate-button').removeClass('disabled');
		}
	});
});

var datePickerInit = function(){
	var formatString = 'MMMM D, YYYY';
	var start = moment().subtract(6, 'days');
	var end = moment();

	function cb(start, end) {
		fromDate = start.hour(0).minute(0).second(0).utc().unix();
		toDate = end.hour(23).minute(59).second(59).utc().unix();
		console.log(fromDate);
		console.log(toDate);
		$('#date-range-picker span').html(start.format(formatString) + ' - ' + end.format(formatString));
	}

	$('#date-range-picker').daterangepicker({
		startDate: start,
		endDate: end,
		locale: {
			format: formatString
		},
		ranges: {
			'Today': [moment(), moment()],
			'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
			'Last 7 Days': [moment().subtract(6, 'days'), moment()],
			'Last 30 Days': [moment().subtract(29, 'days'), moment()],
			'This Month': [moment().startOf('month'), moment().endOf('month')],
			'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
		}
	}, cb);

	cb(start, end);
}

var onLoginSuccess = function(data){
	console.log(data);
	accessToken = data.accessToken;
	sites = data.networkUsers;

	$('#login-container').html(loginTemplate.replace('__SEID__', sites[0].account_id));

	buildSiteSelector();
}

var buildSiteSelector = function(){
	var options = selectorOptionTemplate.replace('__VALUE__', '').replace('__TITLE__', 'Please choose a site');

	$.each(sites, function(idx, val){
		options += selectorOptionTemplate.replace('__VALUE__', idx)
										 .replace('__TITLE__', val.site_name);
	});

	$('#site-selector-container select').append(options);
	$('#site-selector-container select').prop('disabled', false);
}

var setTargetSite = function(idx){
	if(idx < 0 || idx >= sites.length) {
		alert('Could not select site with index ' + idx);
		return;
	}

	targetSiteUrl = sites[idx].site_url.replace('http://', '');
	targetUserId = sites[idx].user_id;
}

var buildRepQueryString = function(page){
	return stackUrl + version + '/me/reputation-history-full?' + $.param({
		key: apiKey,
		site: targetSiteUrl,
		access_token: accessToken,
		fromdate: fromDate,
		toDate: toDate,
		page: page
	});
}

var buildReputationObjects = function(page){
	page = page || 1;
	var queryString = buildRepQueryString(page);

	$.ajax(queryString)
	.done(function(data, status, xhr){
		console.log(data);
		$.each(data.items, function(idx, elem){
			if(!(elem.post_id in reputationObjects)){
				reputationObjects[elem.post_id] = [];
			}
			reputationObjects[elem.post_id].push(elem);
		});

		if(data.has_more){
			buildReputationObjects(page++);
		}
	})
	.fail(function(xhr, status, err){
		alert('Something went wrong: ' + err);
	});
}

var POST_TYPE_DEPENDENT = ['voter_downvotes', 'voter_undownvotes', 'post_upvoted', 'post_unupvoted'];
var idsToCheck = {};

var doReputationCalculation = function(postRepChanges){
	var earnedRep = 0;
	var actualRep = 0;

	for(var postId in postRepChanges){
		for(var i = 0; i < postRepChanges[postId].length; i++){
			var repObject = postRepChanges[postId][i];
			actualRep += repObject.reputation_change;

			if($.inArray(repObject.reputation_history_type, POST_TYPE_DEPENDENT)){
				if(!(postId in idsToCheck)){
					idsToCheck[postId] = [];
				}
				idsToCheck[postId].push(repObject.reputation_history_type);
			} else{
				earnedRep += repObject.reputation_change;
			}
		}
	}

	earnedRep += doCalculateRepForPostTypes(idsToCheck);
	alert("Earned: " + earnedRep + "; actual: " + actualRep);
}

var buildPostsQueryString = function(postIds){
	var vectorizedPostIds = postIds.join(';');
	return stackUrl + version + '/posts/' + vectorizedPostIds + '?' + $.param({
		key: apiKey,
		site: targetSiteUrl,
		pagesize=100
}

var POST_DEPENDENT_REP_CHANGES = {
	'question': {
		'voter_downvotes': 0,
		'voter_undownvotes': 0,
		'post_upvoted': 5,
		'post_unupvoted': -5
	},
	'answer': {
		'voter_downvotes': -1,
		'voter_undownvotes': 1,
		'post_upvoted': 10,
		'post_unupvoted': -10
	}
};

var doCalculateRepForPostTypes = function(repForPostIds){
	total = 0;
	postIds = repForPostIds.keys();

	for(var i = 0; i < postIds.length; i += 100){
		var end = Math.min(postIds.length, i+100);
		var queryIds = postIds.slice(i, end);

		var queryString = buildPostsQueryString(queryIds);
		$.ajax(queryString)
		.done(function(data, status, xhr){
			$.each(data.items, function(idx, elem){
				var postType = elem.post_type;
				for(var j = 0; j < repForPostIds[elem.post_id]; j++){
					var repChangeType = repForPostIds[elem.post_id][j];
					total += POST_DEPENDENT_REP_CHANGES[postType][repChangeType];
				}
			})
		})
		.fail(function(xhr, status, err){
			alert('Something went wrong: ' + err);
		});
	}
}<commit_msg>Syntax fail<commit_after>var url = window.location.protocol + '//' + window.location.host;

var stackUrl = 'https://api.stackexchange.com';
var version = '/2.2';

var apiKey = 'LatL0Qaw3)dPKFoK6Y1yiQ((';

var noLoginTemplate = '<button class="btn btn-primary">Log in</button>';
var loginTemplate = '';
var selectorOptionTemplate = '<option value="__VALUE__">__TITLE__</option>';

var accessToken = undefined;
var sites = undefined;

var targetSiteUrl = undefined;

var fromDate = undefined;
var toDate = undefined;

var reputationObjects = {};

$(document).ready(function(){
	$('#login-container').html(noLoginTemplate);

	datePickerInit();

	SE.init({
		clientId: 6388,
		key: apiKey,
		channelUrl: url + '/blank',
		complete: function(data){
			console.log(data);
		}
	});

	$('#login-container button').click(function(event){
		SE.authenticate({
			success: onLoginSuccess,
			error: function(data){
				alert('Something went wrong. Unable to log in');
				console.log(data);
			},
			scope: ['private_info'],
			networkUsers: true
		});
	});

	$('#calculate-button').click(function(event){
		buildReputationObjects();
		doReputationCalculation(reputationObjects);
	});

	$('#site-selector-container select').change(function(event){
		var idx = $(this).val();

		if(idx === ''){
			$(this).parent().addClass('has-error');
			$('#site-selector-container .help-block').removeClass('hidden');
			$('#calculate-btn').addClass('disabled');
		} else{
			$(this).parent().removeClass('has-error');
			$('#site-selector-container .help-block').addClass('hidden');

			console.log(idx);
			setTargetSite(idx);
			$('#calculate-button').removeClass('disabled');
		}
	});
});

var datePickerInit = function(){
	var formatString = 'MMMM D, YYYY';
	var start = moment().subtract(6, 'days');
	var end = moment();

	function cb(start, end) {
		fromDate = start.hour(0).minute(0).second(0).utc().unix();
		toDate = end.hour(23).minute(59).second(59).utc().unix();
		console.log(fromDate);
		console.log(toDate);
		$('#date-range-picker span').html(start.format(formatString) + ' - ' + end.format(formatString));
	}

	$('#date-range-picker').daterangepicker({
		startDate: start,
		endDate: end,
		locale: {
			format: formatString
		},
		ranges: {
			'Today': [moment(), moment()],
			'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
			'Last 7 Days': [moment().subtract(6, 'days'), moment()],
			'Last 30 Days': [moment().subtract(29, 'days'), moment()],
			'This Month': [moment().startOf('month'), moment().endOf('month')],
			'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
		}
	}, cb);

	cb(start, end);
}

var onLoginSuccess = function(data){
	console.log(data);
	accessToken = data.accessToken;
	sites = data.networkUsers;

	$('#login-container').html(loginTemplate.replace('__SEID__', sites[0].account_id));

	buildSiteSelector();
}

var buildSiteSelector = function(){
	var options = selectorOptionTemplate.replace('__VALUE__', '').replace('__TITLE__', 'Please choose a site');

	$.each(sites, function(idx, val){
		options += selectorOptionTemplate.replace('__VALUE__', idx)
										 .replace('__TITLE__', val.site_name);
	});

	$('#site-selector-container select').append(options);
	$('#site-selector-container select').prop('disabled', false);
}

var setTargetSite = function(idx){
	if(idx < 0 || idx >= sites.length) {
		alert('Could not select site with index ' + idx);
		return;
	}

	targetSiteUrl = sites[idx].site_url.replace('http://', '');
	targetUserId = sites[idx].user_id;
}

var buildRepQueryString = function(page){
	return stackUrl + version + '/me/reputation-history-full?' + $.param({
		key: apiKey,
		site: targetSiteUrl,
		access_token: accessToken,
		fromdate: fromDate,
		toDate: toDate,
		page: page
	});
}

var buildReputationObjects = function(page){
	page = page || 1;
	var queryString = buildRepQueryString(page);

	$.ajax(queryString)
	.done(function(data, status, xhr){
		console.log(data);
		$.each(data.items, function(idx, elem){
			if(!(elem.post_id in reputationObjects)){
				reputationObjects[elem.post_id] = [];
			}
			reputationObjects[elem.post_id].push(elem);
		});

		if(data.has_more){
			buildReputationObjects(page++);
		}
	})
	.fail(function(xhr, status, err){
		alert('Something went wrong: ' + err);
	});
}

var POST_TYPE_DEPENDENT = ['voter_downvotes', 'voter_undownvotes', 'post_upvoted', 'post_unupvoted'];
var idsToCheck = {};

var doReputationCalculation = function(postRepChanges){
	var earnedRep = 0;
	var actualRep = 0;

	for(var postId in postRepChanges){
		for(var i = 0; i < postRepChanges[postId].length; i++){
			var repObject = postRepChanges[postId][i];
			actualRep += repObject.reputation_change;

			if($.inArray(repObject.reputation_history_type, POST_TYPE_DEPENDENT)){
				if(!(postId in idsToCheck)){
					idsToCheck[postId] = [];
				}
				idsToCheck[postId].push(repObject.reputation_history_type);
			} else{
				earnedRep += repObject.reputation_change;
			}
		}
	}

	earnedRep += doCalculateRepForPostTypes(idsToCheck);
	alert("Earned: " + earnedRep + "; actual: " + actualRep);
}

var buildPostsQueryString = function(postIds){
	var vectorizedPostIds = postIds.join(';');
	return stackUrl + version + '/posts/' + vectorizedPostIds + '?' + $.param({
		key: apiKey,
		site: targetSiteUrl,
		pagesize: 100
	});
}

var POST_DEPENDENT_REP_CHANGES = {
	'question': {
		'voter_downvotes': 0,
		'voter_undownvotes': 0,
		'post_upvoted': 5,
		'post_unupvoted': -5
	},
	'answer': {
		'voter_downvotes': -1,
		'voter_undownvotes': 1,
		'post_upvoted': 10,
		'post_unupvoted': -10
	}
};

var doCalculateRepForPostTypes = function(repForPostIds){
	total = 0;
	postIds = repForPostIds.keys();

	for(var i = 0; i < postIds.length; i += 100){
		var end = Math.min(postIds.length, i+100);
		var queryIds = postIds.slice(i, end);

		var queryString = buildPostsQueryString(queryIds);
		$.ajax(queryString)
		.done(function(data, status, xhr){
			$.each(data.items, function(idx, elem){
				var postType = elem.post_type;
				for(var j = 0; j < repForPostIds[elem.post_id]; j++){
					var repChangeType = repForPostIds[elem.post_id][j];
					total += POST_DEPENDENT_REP_CHANGES[postType][repChangeType];
				}
			})
		})
		.fail(function(xhr, status, err){
			alert('Something went wrong: ' + err);
		});
	}
}<|endoftext|>


<commit_before>// @flow
import React, { Component, PropTypes } from 'react';
import { observer, inject, PropTypes as MobxPropTypes } from 'mobx-react';
import { defineMessages, intlShape } from 'react-intl';
import WalletTransactionsList from '../../components/wallet/home/WalletTransactionsList';
import WalletTransactionsSearch from '../../components/wallet/home/WalletTransactionsSearch';
import WalletNoTransactions from '../../components/wallet/home/WalletNoTransactions';
import CachedRequest from '../../stores/lib/CachedRequest';

const messages = defineMessages({
  noTransactions: {
    id: 'wallet.transactions.no.transactions',
    defaultMessage: '!!!No transactions',
    description: 'Message shown when wallet has no transactions yet.'
  },
  noTransactionsFound: {
    id: 'wallet.transactions.no.transactions.found',
    defaultMessage: '!!!No transactions found',
    description: 'Message shown when wallet transaction search returns zero results.'
  }
});

@inject('stores', 'actions') @observer
export default class WalletHomePage extends Component {

  static propTypes = {
    stores: PropTypes.shape({
      transactions: PropTypes.shape({
        searchOptions: PropTypes.shape({
          searchTerm: PropTypes.string.isRequired,
          searchLimit: PropTypes.number.isRequired,
        }),
        searchRequest: PropTypes.instanceOf(CachedRequest),
        filtered: MobxPropTypes.arrayOrObservableArray.isRequired,
        hasAny: PropTypes.bool.isRequired,
        totalAvailable: PropTypes.number.isRequired,
      }),
    }).isRequired,
    actions: PropTypes.shape({
      filterTransactions: PropTypes.func.isRequired
    }).isRequired
  };

  static contextTypes = {
    intl: intlShape.isRequired,
  };

  _handleSearchInputChange = (value: string, event: Object) => {
    this.props.actions.filterTransactions({ searchTerm: event.target.value });
  };

  render() {
    const { intl } = this.context;
    const actions = this.props.actions;
    const {
      searchOptions,
      searchRequest,
      hasAny,
      totalAvailable,
      filtered,
    } = this.props.stores.transactions;
    const { searchLimit, searchTerm } = searchOptions;

    let walletTransactions = null;
    let transactionSearch = null;
    const noTransactionsLabel = intl.formatMessage(messages.noTransactions);
    const noTransactionsFoundLabel = intl.formatMessage(messages.noTransactionsFound);

    if (hasAny) {
      transactionSearch = (

          <WalletTransactionsSearch
            searchTerm={searchTerm}
            onChange={this._handleSearchInputChange}
          />

      );
    }

    if (searchRequest.isExecuting || hasAny) {
      walletTransactions = (
        <WalletTransactionsList
          transactions={filtered}
          isLoadingTransactions={searchRequest.isExecuting}
          hasMoreToLoad={totalAvailable > searchLimit}
          onLoadMore={actions.loadMoreTransactions}
        />
      );
    } else if (!hasAny) {
      walletTransactions = <WalletNoTransactions label={noTransactionsLabel} />;
    } else {
      walletTransactions = <WalletNoTransactions label={noTransactionsFoundLabel} />;
    }

    return (

        {transactionSearch}
        {walletTransactions}

    );
  }

}
<commit_msg>make 'no transactions found' message work correctly<commit_after>// @flow
import React, { Component, PropTypes } from 'react';
import { observer, inject, PropTypes as MobxPropTypes } from 'mobx-react';
import { defineMessages, intlShape } from 'react-intl';
import WalletTransactionsList from '../../components/wallet/home/WalletTransactionsList';
import WalletTransactionsSearch from '../../components/wallet/home/WalletTransactionsSearch';
import WalletNoTransactions from '../../components/wallet/home/WalletNoTransactions';
import CachedRequest from '../../stores/lib/CachedRequest';

const messages = defineMessages({
  noTransactions: {
    id: 'wallet.transactions.no.transactions',
    defaultMessage: '!!!No transactions',
    description: 'Message shown when wallet has no transactions yet.'
  },
  noTransactionsFound: {
    id: 'wallet.transactions.no.transactions.found',
    defaultMessage: '!!!No transactions found',
    description: 'Message shown when wallet transaction search returns zero results.'
  }
});

@inject('stores', 'actions') @observer
export default class WalletHomePage extends Component {

  static propTypes = {
    stores: PropTypes.shape({
      transactions: PropTypes.shape({
        searchOptions: PropTypes.shape({
          searchTerm: PropTypes.string.isRequired,
          searchLimit: PropTypes.number.isRequired,
        }),
        searchRequest: PropTypes.instanceOf(CachedRequest),
        filtered: MobxPropTypes.arrayOrObservableArray.isRequired,
        hasAny: PropTypes.bool.isRequired,
        totalAvailable: PropTypes.number.isRequired,
      }),
    }).isRequired,
    actions: PropTypes.shape({
      filterTransactions: PropTypes.func.isRequired
    }).isRequired
  };

  static contextTypes = {
    intl: intlShape.isRequired,
  };

  _handleSearchInputChange = (value: string, event: Object) => {
    this.props.actions.filterTransactions({ searchTerm: event.target.value });
  };

  render() {
    const { intl } = this.context;
    const actions = this.props.actions;
    const {
      searchOptions,
      searchRequest,
      hasAny,
      totalAvailable,
      filtered,
    } = this.props.stores.transactions;
    const { searchLimit, searchTerm } = searchOptions;
    const wasSearched = searchTerm !== '';
    let walletTransactions = null;
    let transactionSearch = null;
    const noTransactionsLabel = intl.formatMessage(messages.noTransactions);
    const noTransactionsFoundLabel = intl.formatMessage(messages.noTransactionsFound);

    if (wasSearched || hasAny) {
      transactionSearch = (

          <WalletTransactionsSearch
            searchTerm={searchTerm}
            onChange={this._handleSearchInputChange}
          />

      );
    }

    if (searchRequest.isExecuting || hasAny) {
      walletTransactions = (
        <WalletTransactionsList
          transactions={filtered}
          isLoadingTransactions={searchRequest.isExecuting}
          hasMoreToLoad={totalAvailable > searchLimit}
          onLoadMore={actions.loadMoreTransactions}
        />
      );
    } else if (wasSearched && !hasAny) {
      walletTransactions = <WalletNoTransactions label={noTransactionsFoundLabel} />;
    } else if (!hasAny) {
      walletTransactions = <WalletNoTransactions label={noTransactionsLabel} />;
    }

    return (

        {transactionSearch}
        {walletTransactions}

    );
  }

}
<|endoftext|>


<commit_before>var dmsString = function(o) {//S 01°56'06.30"
  return o.pole + ' ' + o.deg + '°' + o.min + "'" + o.sec + '"';
};
var degDms = function(val) {
  var n = Math.abs(val);
  var deg = parseInt(n); n=(n-deg)*60;
  var min = parseInt(n); n=(n-min)*60;
  var sec = Math.round(n * 100)/100;
  return {deg:deg, min:min, sec:sec};
};
var dmsDeg = function(o) {
  var maxDeg = (s.public.type === 'lat') ? 90 : 180;
  if (o.deg >= maxDeg) return null;
  if (o.min >= 60) return null;
  if (o.sec >= 60) return null;
  if (o.deg<0 || o.min<0 || o.sec<0) return null;
  var res = o.deg + o.min/60 + o.sec/3600;
  if (o.pole === "S" || o.pole === "W") res *= -1;
  return Math.round(res * 1000000) / 1000000;
};
var dmsDegStr = function(str, type) {
  if (str === '') return null;
  var patt = (type === 'lat') ? /^([NS])\s(\d{1,3})°(\d{1,2})'(\d{1,2}\.*\d*)"$/ : /^([WE])\s(\d{1,3})°(\d{1,2})'(\d{1,2}\.*\d*)"$/;
  var match = str.match(patt);
  if (match === null) { return null; }
  var o = {pole:match[1],deg:parseInt(match[2]),min:parseInt(match[3]),sec:parseFloat(match[4])};
  s.deg = dmsDeg(o);
};
<commit_msg>degdms js Bugfix: remove scope dependant variable<commit_after>var dmsString = function(o) {//S 01°56'06.30"
  return o.pole + ' ' + o.deg + '°' + o.min + "'" + o.sec + '"';
};
var degDms = function(val) {
  var n = Math.abs(val);
  var deg = parseInt(n); n=(n-deg)*60;
  var min = parseInt(n); n=(n-min)*60;
  var sec = Math.round(n * 100)/100;
  return {deg:deg, min:min, sec:sec};
};
var dmsDeg = function(o,type) {
  var maxDeg = (type === 'lat') ? 90 : 180;
  if (o.deg >= maxDeg) return null;
  if (o.min >= 60) return null;
  if (o.sec >= 60) return null;
  if (o.deg<0 || o.min<0 || o.sec<0) return null;
  var res = o.deg + o.min/60 + o.sec/3600;
  if (o.pole === "S" || o.pole === "W") res *= -1;
  return Math.round(res * 1000000) / 1000000;
};
var dmsDegStr = function(str, type) {
  if (str === '') return null;
  var patt = (type === 'lat') ? /^([NS])\s(\d{1,3})°(\d{1,2})'(\d{1,2}\.*\d*)"$/ : /^([WE])\s(\d{1,3})°(\d{1,2})'(\d{1,2}\.*\d*)"$/;
  var match = str.match(patt);
  if (match === null) { return null; }
  var o = {pole:match[1],deg:parseInt(match[2]),min:parseInt(match[3]),sec:parseFloat(match[4])};
  return dmsDeg(o,type);
};
<|endoftext|>


<commit_before>import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent( 'sl-radio-group', 'Integration | Component | sl radio group', {
    integration: true
});

test( 'The disabled state applies the disabled attribute and class', function( assert ) {
    this.render( hbs`
        {{#sl-radio-group disabled=true name="testName"}}
        {{/sl-radio-group}}
    ` );

    assert.equal(
        this.$( '.sl-radio-group' ).attr( 'disabled' ),
        'disabled',
        'has "disabled" attribute'
    );

    assert.ok(
        this.$( '.sl-radio-group' ).hasClass( 'disabled' ),
        'has "disabled" class'
    );
});

test( 'The disabled state applies to sl-radio children', function( assert ) {
    this.render( hbs`
        {{#sl-radio-group disabled=true name="testName"}}
            {{#sl-radio label="One" value="one"}}
            {{/sl-radio}}
            {{#sl-radio label="Two" value="two"}}
            {{/sl-radio}}
            {{#sl-radio label="Three" value="three"}}
            {{/sl-radio}}
        {{/sl-radio-group}}
    ` );

    assert.equal(
        this.$( 'input[disabled]' ).length,
        3,
        'Rendered component has three disabled inputs'
    );
});

test( 'The readonly state applies to sl-radio children', function( assert ) {
    this.render( hbs`
        {{#sl-radio-group readonly=true name="testName"}}
            {{#sl-radio label="One" value="one"}}
            {{/sl-radio}}
            {{#sl-radio label="Two" value="two"}}
            {{/sl-radio}}
            {{#sl-radio label="Three" value="three"}}
            {{/sl-radio}}
        {{/sl-radio-group}}
    ` );

    assert.equal(
        this.$( 'input[readonly]' ).length,
        3,
        'Rendered component has three readonly inputs'
    );
});

test( "Inline true sets sl-radio children's inline property to true", function( assert ) {
    this.render( hbs`
        {{#sl-radio-group inline=true name="testName"}}
            {{#sl-radio label="One" value="one"}}
            {{/sl-radio}}
            {{#sl-radio label="Two" value="two"}}
            {{/sl-radio}}
            {{#sl-radio label="Three" value="three"}}
            {{/sl-radio}}
        {{/sl-radio-group}}
    ` );

    assert.equal(
        this.$( '.sl-radio.radio' ).length,
        0,
        'Rendered component children buttons are not inline'
    );

    assert.equal(
        this.$( '.sl-radio.radio-inline' ).length,
        3,
        'Rendered component children buttons are inline'
    );
});

test( "Inline false sets sl-radio children's inline property to false", function( assert ) {
    this.render( hbs`
        {{#sl-radio-group inline=false name="testName"}}
            {{#sl-radio label="One" value="one"}}
            {{/sl-radio}}
            {{#sl-radio label="Two" value="two"}}
            {{/sl-radio}}
            {{#sl-radio label="Three" value="three"}}
            {{/sl-radio}}
        {{/sl-radio-group}}
    ` );

    assert.equal(
        this.$( '.sl-radio.radio-inline' ).length,
        0,
        'Rendered component has zero inline radio buttons'
    );

    assert.equal(
        this.$( '.sl-radio.radio' ).length,
        3,
        'Rendered component has three default (non-inline) radio buttons'
    );
});

test( 'Value changes when sl-radio child selected', function( assert ) {
    this.set( 'value', 'jeremy' );
    this.render( hbs`
        {{#sl-radio-group value=value name="testName"}}
            {{#sl-radio label="One" value="eric"}}
            {{/sl-radio}}
            {{#sl-radio label="Two" value="josh"}}
            {{/sl-radio}}
            {{#sl-radio label="Three" value="michael"}}
            {{/sl-radio}}
        {{/sl-radio-group}}
    ` );

    Ember.run( () => {
        const $radioButton = this.$( 'input[value="eric"]' );
        $radioButton.click();
    });

    assert.equal(
        this.get( 'value' ),
        'eric',
        '"eric" value is selected'
    );

    Ember.run( () => {
        const $radioButton = this.$( 'input[value="josh"]' );
        $radioButton.click();
    });

    assert.equal(
        this.get( 'value' ),
        'josh',
        '"josh" value is selected'
    );
});

test( 'default Value gets selected by default', function( assert ) {
    this.set( 'value', 'eric' );
    this.render( hbs`
        {{#sl-radio-group value=value name="testName"}}
            {{#sl-radio label="One" value="eric"}}
            {{/sl-radio}}
            {{#sl-radio label="Two" value="josh"}}
            {{/sl-radio}}
            {{#sl-radio label="Three" value="michael"}}
            {{/sl-radio}}
        {{/sl-radio-group}}
    ` );

    assert.equal(
        this.$( 'input[name="testName"]:checked' ).val(),
        'eric',
        'The value "eric" that is set is selected by default'
    );
});<commit_msg>fixed unit test checking for the default selected radio button value, fixed grammer in test as well<commit_after>import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent( 'sl-radio-group', 'Integration | Component | sl radio group', {
    integration: true
});

test( 'The disabled state applies the disabled attribute and class', function( assert ) {
    this.render( hbs`
        {{#sl-radio-group disabled=true name="testName"}}
        {{/sl-radio-group}}
    ` );

    assert.equal(
        this.$( '.sl-radio-group' ).attr( 'disabled' ),
        'disabled',
        'has "disabled" attribute'
    );

    assert.ok(
        this.$( '.sl-radio-group' ).hasClass( 'disabled' ),
        'has "disabled" class'
    );
});

test( 'The disabled state applies to sl-radio children', function( assert ) {
    this.render( hbs`
        {{#sl-radio-group disabled=true name="testName"}}
            {{#sl-radio label="One" value="one"}}
            {{/sl-radio}}
            {{#sl-radio label="Two" value="two"}}
            {{/sl-radio}}
            {{#sl-radio label="Three" value="three"}}
            {{/sl-radio}}
        {{/sl-radio-group}}
    ` );

    assert.equal(
        this.$( 'input[disabled]' ).length,
        3,
        'Rendered component has three disabled inputs'
    );
});

test( 'The readonly state applies to sl-radio children', function( assert ) {
    this.render( hbs`
        {{#sl-radio-group readonly=true name="testName"}}
            {{#sl-radio label="One" value="one"}}
            {{/sl-radio}}
            {{#sl-radio label="Two" value="two"}}
            {{/sl-radio}}
            {{#sl-radio label="Three" value="three"}}
            {{/sl-radio}}
        {{/sl-radio-group}}
    ` );

    assert.equal(
        this.$( 'input[readonly]' ).length,
        3,
        'Rendered component has three readonly inputs'
    );
});

test( "Inline true sets sl-radio children's inline property to true", function( assert ) {
    this.render( hbs`
        {{#sl-radio-group inline=true name="testName"}}
            {{#sl-radio label="One" value="one"}}
            {{/sl-radio}}
            {{#sl-radio label="Two" value="two"}}
            {{/sl-radio}}
            {{#sl-radio label="Three" value="three"}}
            {{/sl-radio}}
        {{/sl-radio-group}}
    ` );

    assert.equal(
        this.$( '.sl-radio.radio' ).length,
        0,
        'Rendered component children buttons are not inline'
    );

    assert.equal(
        this.$( '.sl-radio.radio-inline' ).length,
        3,
        'Rendered component children buttons are inline'
    );
});

test( "Inline false sets sl-radio children's inline property to false", function( assert ) {
    this.render( hbs`
        {{#sl-radio-group inline=false name="testName"}}
            {{#sl-radio label="One" value="one"}}
            {{/sl-radio}}
            {{#sl-radio label="Two" value="two"}}
            {{/sl-radio}}
            {{#sl-radio label="Three" value="three"}}
            {{/sl-radio}}
        {{/sl-radio-group}}
    ` );

    assert.equal(
        this.$( '.sl-radio.radio-inline' ).length,
        0,
        'Rendered component has zero inline radio buttons'
    );

    assert.equal(
        this.$( '.sl-radio.radio' ).length,
        3,
        'Rendered component has three default (non-inline) radio buttons'
    );
});

test( 'Value changes when sl-radio child selected', function( assert ) {
    this.set( 'value', 'jeremy' );
    this.render( hbs`
        {{#sl-radio-group value=value name="testName"}}
            {{#sl-radio label="One" value="eric"}}
            {{/sl-radio}}
            {{#sl-radio label="Two" value="josh"}}
            {{/sl-radio}}
            {{#sl-radio label="Three" value="michael"}}
            {{/sl-radio}}
        {{/sl-radio-group}}
    ` );

    Ember.run( () => {
        const $radioButton = this.$( 'input[value="eric"]' );
        $radioButton.click();
    });

    assert.equal(
        this.get( 'value' ),
        'eric',
        '"eric" value is selected'
    );

    Ember.run( () => {
        const $radioButton = this.$( 'input[value="josh"]' );
        $radioButton.click();
    });

    assert.equal(
        this.get( 'value' ),
        'josh',
        '"josh" value is selected'
    );
});

test( 'Default Value gets selected by default', function( assert ) {
    this.set( 'value', 'josh' );
    this.render( hbs`
        {{#sl-radio-group value=value name="testName"}}
            {{#sl-radio label="One" value="eric"}}
            {{/sl-radio}}
            {{#sl-radio label="Two" value="josh"}}
            {{/sl-radio}}
            {{#sl-radio label="Three" value="michael"}}
            {{/sl-radio}}
        {{/sl-radio-group}}
    ` );

    assert.equal(
        this.$( 'input[name="testName"]:checked' ).val(),
        'josh',
        'The value "josh" that is set is selected by default'
    );
});<|endoftext|>


<commit_before>/* document.getElementsBySelector(selector)
   - returns an array of element objects from the current document
     matching the CSS selector. Selectors can contain element names,
     class names and ids and can be nested. For example:

       elements = document.getElementsBySelect('div#main p a.external')

     Will return an array of all 'a' elements with 'external' in their
     class attribute that are contained inside 'p' elements that are
     contained inside the 'div' element which has id="main"

   New in version 0.4: Support for CSS2 and CSS3 attribute selectors:
   See http://www.w3.org/TR/css3-selectors/#attribute-selectors

   Version 0.4 - Simon Willison, March 25th 2003
   -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
   -- Opera 7 fails
*/

function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (tagName && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            try {
                elements = currentContext[h].getElementsByTagName(tagName);
            }
            catch(e) {
                elements = [];
            }
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }
    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}

/* That revolting regular expression explained
/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
  \---/  \---/\-------------/    \-------/
    |      |         |               |
    |      |         |           The value
    |      |    ~,|,^,$,* or =
    |   Attribute
   Tag
*/
<commit_msg>Fixed #10783 -- Fixed Javascript error when adding a new object in admin.<commit_after>/* document.getElementsBySelector(selector)
   - returns an array of element objects from the current document
     matching the CSS selector. Selectors can contain element names,
     class names and ids and can be nested. For example:

       elements = document.getElementsBySelect('div#main p a.external')

     Will return an array of all 'a' elements with 'external' in their
     class attribute that are contained inside 'p' elements that are
     contained inside the 'div' element which has id="main"

   New in version 0.4: Support for CSS2 and CSS3 attribute selectors:
   See http://www.w3.org/TR/css3-selectors/#attribute-selectors

   Version 0.4 - Simon Willison, March 25th 2003
   -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
   -- Opera 7 fails
*/

function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (!element || (tagName && element.nodeName.toLowerCase() != tagName)) {
        // ID not found or tag with that ID not found, return false.
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            try {
                elements = currentContext[h].getElementsByTagName(tagName);
            }
            catch(e) {
                elements = [];
            }
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }
    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}

/* That revolting regular expression explained
/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
  \---/  \---/\-------------/    \-------/
    |      |         |               |
    |      |         |           The value
    |      |    ~,|,^,$,* or =
    |   Attribute
   Tag
*/
<|endoftext|>


<commit_before>
$(document).ready(function() {

    var $form = $('#report-form');
    var $map = $('#map');

    function markerMoved (point) {
        $('#id_report-x').val(point.x);
        $('#id_report-y').val(point.y);

        window.location.assign('#x=' + point.x + '&y=' + point.y);

        retrieveAddress();

    }

    $map.one('markerdrag click movestart zoomend',function(evt,point){
        $('#cursor-instructions').fadeOut();
    });

    //On page load: The report overview needs to be hidden
    $('#report_overview_table_div').hide();
    $map.bind('markermoved',function(evt,point) {
        markerMoved(point);
    });

    $(fms.currentMap).bind('reportselected', function(evt, point, report){
        window.location.assign('/reports/' + report.id);
    });

    retrieveAddress();

    function retrieveAddress() {
        var languages = ['fr', 'nl'],
        currLang = fms.currentMap.options.apiLang;

        $form.find('button, :submit').prop('disabled', true);
        $('#address-text').addClass('loading');

        fms.currentMap.getSelectedAddress(currLang, function(lang, response) {
            var address = response.result.address;
            $('#address-text').removeClass('loading');
            $form.find('.text-error').remove();

            if (!(address.street.postCode in zipcodes) || !zipcodes[String(address.street.postCode)].participation) {

                fillAdressField(lang, address);
                //This commune does not participate to fixmystreet until now.
                $form.prepend('
' + zipcodes[String(address.street.postCode)].msg + '
');

            } else if(response.status == 'success') {

                $form.find('button, :submit').prop('disabled', false);

                fillAdressField(currLang, address);
                fillI18nAdressField(currLang, address);

                //Search if the address is on a regional road or not.
                var pointX = $('#id_report-x').val();
                var pointY = $('#id_report-y').val();

                //Default False
                $('#id_report-address_regional').val('False');

                $.ajax({
                    url: "http://gis.irisnet.be/geoserver/wfs?service=WFS&version=1.0.0&request=GetFeature&typeName=urbis:URB_A_SS&maxFeatures=1&outputFormat=json&bbox="+(pointX-30)+","+(pointY-30)+","+(pointX+30)+","+(pointY+30),
                    dataType: "json",
                    type: "POST",
                    success: function(responseData, textStatus, jqXHR) {
                        if (responseData.features[0].properties.ADMINISTRATOR != null) {
                            //ROUTE REGIONALE
                            $('#id_report-address_regional').val('True');
                        }
                    }
                });

                //Does not work. Fill in the wrong input zone
                for (var i in languages) {
                    console.log(i);
                    if (languages[i] != currLang) {
                        console.log(languages[i]);
                        fms.currentMap.getSelectedAddress(languages[i], function(langSecond, response) {
                            var address = response.result.address;
                            console.log('callback='+langSecond);
                            if(response.status == 'success') {
                                fillI18nAdressField(langSecond, address);
                            }
                        });
                    }
                }

            } else {
                var msg = 'Error: ' + response.status;
                if(response.status == 'error') {
                    msg = 'Unable to locate this address';
                }
                $('#address-text').removeClass('loading');
                $form.prepend('
' + msg + '
');
            }
        });
    }
});

function fillAdressField(lang, address) {
    $('#address-text').html(address.number + ' ' + address.street.name+ ' ' + address.street.postCode); // urbis must return the full text municipality
    $('#id_report-postalcode').val(address.street.postCode);
    $('#id_report-address_number').val(address.number);
}

function fillI18nAdressField(lang, address) {
    $('#id_report-address_' + lang).val(address.street.name);
}

function checkFileFieldValue(){
    if($("#id_file").val() == ""){
        alert("Please select a file to add.");
        return false;
    }
}

<commit_msg>remove console.log<commit_after>
$(document).ready(function() {

    var $form = $('#report-form');
    var $map = $('#map');

    function markerMoved (point) {
        $('#id_report-x').val(point.x);
        $('#id_report-y').val(point.y);

        window.location.assign('#x=' + point.x + '&y=' + point.y);

        retrieveAddress();

    }

    $map.one('markerdrag click movestart zoomend',function(evt,point){
        $('#cursor-instructions').fadeOut();
    });

    //On page load: The report overview needs to be hidden
    $('#report_overview_table_div').hide();
    $map.bind('markermoved',function(evt,point) {
        markerMoved(point);
    });

    $(fms.currentMap).bind('reportselected', function(evt, point, report){
        window.location.assign('/reports/' + report.id);
    });

    retrieveAddress();

    function retrieveAddress() {
        var languages = ['fr', 'nl'],
        currLang = fms.currentMap.options.apiLang;

        $form.find('button, :submit').prop('disabled', true);
        $('#address-text').addClass('loading');

        fms.currentMap.getSelectedAddress(currLang, function(lang, response) {
            var address = response.result.address;
            $('#address-text').removeClass('loading');
            $form.find('.text-error').remove();

            if (!(address.street.postCode in zipcodes) || !zipcodes[String(address.street.postCode)].participation) {

                fillAdressField(lang, address);
                //This commune does not participate to fixmystreet until now.
                $form.prepend('
' + zipcodes[String(address.street.postCode)].msg + '
');

            } else if(response.status == 'success') {

                $form.find('button, :submit').prop('disabled', false);

                fillAdressField(currLang, address);
                fillI18nAdressField(currLang, address);

                //Search if the address is on a regional road or not.
                var pointX = $('#id_report-x').val();
                var pointY = $('#id_report-y').val();

                //Default False
                $('#id_report-address_regional').val('False');

                $.ajax({
                    url: "http://gis.irisnet.be/geoserver/wfs?service=WFS&version=1.0.0&request=GetFeature&typeName=urbis:URB_A_SS&maxFeatures=1&outputFormat=json&bbox="+(pointX-30)+","+(pointY-30)+","+(pointX+30)+","+(pointY+30),
                    dataType: "json",
                    type: "POST",
                    success: function(responseData, textStatus, jqXHR) {
                        if (responseData.features[0].properties.ADMINISTRATOR != null) {
                            //ROUTE REGIONALE
                            $('#id_report-address_regional').val('True');
                        }
                    }
                });

                //Does not work. Fill in the wrong input zone
                for (var i in languages) {
                    console.log(i);
                    if (languages[i] != currLang) {
                        fms.currentMap.getSelectedAddress(languages[i], function(langSecond, response) {
                            var address = response.result.address;
                            console.log('callback='+langSecond);
                            if(response.status == 'success') {
                                fillI18nAdressField(langSecond, address);
                            }
                        });
                    }
                }

            } else {
                var msg = 'Error: ' + response.status;
                if(response.status == 'error') {
                    msg = 'Unable to locate this address';
                }
                $('#address-text').removeClass('loading');
                $form.prepend('
' + msg + '
');
            }
        });
    }
});

function fillAdressField(lang, address) {
    $('#address-text').html(address.number + ' ' + address.street.name+ ' ' + address.street.postCode); // urbis must return the full text municipality
    $('#id_report-postalcode').val(address.street.postCode);
    $('#id_report-address_number').val(address.number);
}

function fillI18nAdressField(lang, address) {
    $('#id_report-address_' + lang).val(address.street.name);
}

function checkFileFieldValue(){
    if($("#id_file").val() == ""){
        alert("Please select a file to add.");
        return false;
    }
}

<|endoftext|>


<commit_before>/* eslint-disable react/forbid-prop-types */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2020
 */

import React, { useMemo, useState } from 'react';
import { View, StyleSheet, FlatList, Text } from 'react-native';
import PropTypes from 'prop-types';

import { FormControl } from '../FormControl';

import { getFormInputConfig } from '../../utilities/formInputConfigs';

import { APP_FONT_FAMILY, DARK_GREY } from '../../globalStyles';
import { TouchableOpacity } from 'react-native-gesture-handler';
import { queryPatientApi, queryPrescriberApi } from '../../utilities/network/lookupApi';

const RECORD_TYPES = {
    PATIENT: 'patient',
    PRESCRIBER: 'prescriber',
}

const FORM_CONFIGS = {
    [RECORD_TYPES.PATIENT]: 'searchPatient',
    [RECORD_TYPES.PRESCRIBER]: 'searchPrescriber',
}

const LIST_CONFIGS = {
    [RECORD_TYPES.PATIENT]: [ 'firstName', 'lastName', 'dateOfBirth' ],
    [RECORD_TYPES.PRESCRIBER]: [ 'firstName', 'lastName', 'registrationCode' ],
}

const SearchListItemColumn = ({ value, type }) => (
    <View style={localStyles.columnContainer}>
        <Text style={localStyles.text}>
            {type === 'date' ? value.toDateString() : value}
        </Text>
    </View>
);

const SearchListItem = ({ listItem, listConfig }) => {
    const onPress = item => console.log(item);
    const columns = listConfig.map(({ key, type}) => {
        const value = listItem[key];
        return <SearchListItemColumn key={key} value={value} type={type}/>;
    });
    return (
        <TouchableOpacity onPress={onPress} style={localStyles.rowContainer}>
            {columns}
        </TouchableOpacity>
    );
}

export const SearchForm = ({dataSource}) => {
    const [data, setData] = useState([]);

    if (!RECORD_TYPES.includes(dataSource)) return null;

    const configKey = useMemo(() => FORM_CONFIGS[dataSource], [dataSource]);
    const formConfig = useMemo(() => getFormInputConfig(configKey), [configKey]);

    const listConfig = useMemo(() => {
        const keys = LIST_CONFIGS[dataSource];
        const keyTypes = keys.reduce((acc, key) => ({ ...acc, [key]: formConfig.find(config => config.key === key)?.type }), {});
        return keys.map(key => ({ key, type: keyTypes[key] }));
    }, [formConfig]);

    const renderItem = useMemo(() => ({item}) => <SearchListItem key={item.id} listItem={item} listConfig={listConfig}/>, [listConfig]);

    const lookupRecords = useMemo(() => params => {
        switch (dataSource) {
            case RECORD_TYPES.PATIENT: {
                queryPatientApi(params).then(patientData => setData(patientData));
                break;
            }
            case RECORD_TYPES.PRESCRIBER: {
                queryPrescriberApi(params).then(prescriberData => setData(prescriberData));
                break;
            }
            default: queryPatientApi(params);
        }
    }, []);

    return (
        <View style={localStyles.container}>
            <View style={localStyles.formContainer}>
                <FormControl
                    isDisabled={false}
                    isSearchForm={true}
                    onSave={lookupRecords}
                    onCancel={() => null}
                    inputConfig={formConfig}
                />
            </View>
            <View style={localStyles.verticalSeparator}></View>
            <View style={localStyles.listContainer}>
                <FlatList
                    data={data}
                    keyExtractor={record => record.id}
                    renderItem={renderItem}
                />
            </View>
        </View>
    );
  };

SearchForm.propTypes = {
    dataSource: PropTypes.string.isRequired,
};

SearchListItem.propTypes = {
    listItem: PropTypes.object.isRequired,
    listConfig: PropTypes.array.isRequired,
}

SearchListItemColumn.propTypes = {
    value: PropTypes.oneOfType([PropTypes.string, PropTypes.instanceOf(Date)]).isRequired,
    type: PropTypes.string.isRequired,
}

const localStyles = StyleSheet.create({
    container: {
        height: 720,
        marginVertical: 20,
        flexDirection: 'row',
        justifyContent: 'space-between',
        backgroundColor: 'white',
    },
    formContainer: {
      flex: 1,
      flexDirection: 'row',
      backgroundColor: 'white',
      alignItems: 'stretch',
    },
    verticalSeparator: {
        width: 10,
        backgroundColor: DARK_GREY,
    },
    listContainer: {
      flex: 3,
      flexDirection: 'row',
      backgroundColor: 'white',

    },
    rowContainer: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        marginVertical: 10,
    },
    columnContainer: {
        marginHorizontal: 10,
    },
    text: {
        fontSize: 20,
        fontFamily: APP_FONT_FAMILY,
      },
  });<commit_msg>Tidy up search form component formatting<commit_after>/* eslint-disable react/forbid-prop-types */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2020
 */

import React, { useMemo, useState } from 'react';
import { View, StyleSheet, FlatList, Text } from 'react-native';
import PropTypes from 'prop-types';

import { FormControl } from '../FormControl';

import { getFormInputConfig } from '../../utilities/formInputConfigs';

import { APP_FONT_FAMILY, DARK_GREY } from '../../globalStyles';
import { TouchableOpacity } from 'react-native-gesture-handler';
import { queryPatientApi, queryPrescriberApi } from '../../utilities/network/lookupApi';

const RECORD_TYPES = {
  PATIENT: 'patient',
  PRESCRIBER: 'prescriber',
};

const FORM_CONFIGS = {
  [RECORD_TYPES.PATIENT]: 'searchPatient',
  [RECORD_TYPES.PRESCRIBER]: 'searchPrescriber',
};

const LIST_CONFIGS = {
  [RECORD_TYPES.PATIENT]: ['firstName', 'lastName', 'dateOfBirth'],
  [RECORD_TYPES.PRESCRIBER]: ['firstName', 'lastName', 'registrationCode'],
};

const SearchListItemColumn = ({ value, type }) => (
  <View style={localStyles.columnContainer}>
    <Text style={localStyles.text}>{type === 'date' ? value.toDateString() : value}</Text>
  </View>
);

const SearchListItem = ({ listItem, listConfig }) => {
  const onPress = item => console.log(item);
  const columns = listConfig.map(({ key, type }) => {
    const value = listItem[key];
    return <SearchListItemColumn key={key} value={value} type={type} />;
  });
  return (
    <TouchableOpacity onPress={onPress} style={localStyles.rowContainer}>
      {columns}
    </TouchableOpacity>
  );
};

export const SearchForm = ({ dataSource }) => {
  const [data, setData] = useState([]);

  if (!RECORD_TYPES.includes(dataSource)) return null;

  const configKey = useMemo(() => FORM_CONFIGS[dataSource], [dataSource]);
  const formConfig = useMemo(() => getFormInputConfig(configKey), [configKey]);

  const listConfig = useMemo(() => {
    const keys = LIST_CONFIGS[dataSource];
    const keyTypes = keys.reduce(
      (acc, key) => ({ ...acc, [key]: formConfig.find(config => config.key === key)?.type }),
      {}
    );
    return keys.map(key => ({ key, type: keyTypes[key] }));
  }, [formConfig]);

  const renderItem = useMemo(
    () => ({ item }) => <SearchListItem key={item.id} listItem={item} listConfig={listConfig} />,
    [listConfig]
  );

  const lookupRecords = useMemo(
    () => params => {
      switch (dataSource) {
        case RECORD_TYPES.PATIENT: {
          queryPatientApi(params).then(patientData => setData(patientData));
          break;
        }
        case RECORD_TYPES.PRESCRIBER: {
          queryPrescriberApi(params).then(prescriberData => setData(prescriberData));
          break;
        }
        default:
          break;
      }
    },
    []
  );

  return (
    <View style={localStyles.container}>
      <View style={localStyles.formContainer}>
        <FormControl
          isDisabled={false}
          isSearchForm={true}
          onSave={lookupRecords}
          onCancel={() => null}
          inputConfig={formConfig}
        />
      </View>
      <View style={localStyles.verticalSeparator}></View>
      <View style={localStyles.listContainer}>
        <FlatList data={data} keyExtractor={record => record.id} renderItem={renderItem} />
      </View>
    </View>
  );
};

SearchForm.propTypes = {
  dataSource: PropTypes.string.isRequired,
};

SearchListItem.propTypes = {
  listItem: PropTypes.object.isRequired,
  listConfig: PropTypes.array.isRequired,
};

SearchListItemColumn.propTypes = {
  value: PropTypes.oneOfType([PropTypes.string, PropTypes.instanceOf(Date)]).isRequired,
  type: PropTypes.string.isRequired,
};

const localStyles = StyleSheet.create({
  container: {
    height: 720,
    marginVertical: 20,
    flexDirection: 'row',
    justifyContent: 'space-between',
    backgroundColor: 'white',
  },
  formContainer: {
    flex: 1,
    flexDirection: 'row',
    backgroundColor: 'white',
    alignItems: 'stretch',
  },
  verticalSeparator: {
    width: 10,
    backgroundColor: DARK_GREY,
  },
  listContainer: {
    flex: 3,
    flexDirection: 'row',
    backgroundColor: 'white',
  },
  rowContainer: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginVertical: 10,
  },
  columnContainer: {
    marginHorizontal: 10,
  },
  text: {
    fontSize: 20,
    fontFamily: APP_FONT_FAMILY,
  },
});
<|endoftext|>