<commit_before>var utils  = require('../utils');

/**
 * dimensions and resolution
 *
 * Checks dimensions and resolution for x, y, z, and time across subjects to
 * ensure they are consistent.
 *
 * The fields we are interested in are all arrays and we are only looking at
 * the first for values in those arrays. To handle single values or longer
 * arrays more arguments will need to be added to headerField.
 */

var headerFields = function headerFields(headers) {
    var issues = [];
    issues = issues.concat(headerField(headers, 'dim'));
    issues = issues.concat(headerField(headers, 'pixdim'));
    return issues;
};

/**
 * Key to headerField working is the fact that we take and array of values
 * from the nifti header and convert it to a string. This string is used to
 * compare the header field value against other header field values and is used
 * as an attribute in the object nifti_types. Nifti types refers to the
 * different types of nifti files we are comparing across subjects. Only the
 * dimensionality of similar anatomy/functional/dwi headers are being compared.
 */

var headerField = function headerField(headers, field) {
    var nifti_types = {};
    var issues = [];
    for (var header_index in headers) {
        var badField = false;
        var field_value;
        var file = headers[header_index][0];
        var filename;
        var header = headers[header_index][1];
        var match;
        var path = utils.files.relativePath(file);
        var run;
        var subject;

        if (field === 'dim') {
            if ((typeof header[field]) === 'undefined' || header[field] === null || header[field].length < header[field][0]) {
                issues.push(new utils.Issue({
                        file: file,
                        code: 40
                }));
                continue;
            }
            field_value = header[field].slice(1, header[field][0]+1).toString();
        } else if (field === 'pixdim') {
            if ((typeof header['xyzt_units']) === 'undefined' || header['xyzt_units'] === null || header['xyzt_units'].length < 4) {
                issues.push(new utils.Issue({
                        file: file,
                        code: 41
                }));
                badField = true;
            }
            if ((typeof header['pixdim']) === 'undefined' || header['pixdim'] === null || header['pixdim'].length < 4) {
                issues.push(new utils.Issue({
                        file: file,
                        code: 42
                }));
                badField = true;
            }
            if (badField === true) {
                continue;
            }
            field_value = [];
            var pix_dim = header[field].slice(1,5);
            var units = header['xyzt_units'].slice(0,4);
            for (var i = 0; i < 4; i++) {
                field_value.push('' + pix_dim[i] + units[i]);
            }
            field_value = field_value.toString();
        } else {
            console.warn("Checks against header field: " + field + " are currently unsupported.");
            return;
        }

        if (!file || (typeof window != 'undefined' && !file.webkitRelativePath)) {
            continue;
        }

        if (!utils.type.isBIDS(path)) {
            continue;
        }
        //match the subject identifier up to the '/' in the full path to a file.
        match = path.match(/sub-(.*?)(?=\/)/);
        if (match === null) {
            continue;
        } else {
            subject = match[0];
        }
        // files are prepended with subject name, the following two commands
        // remove the subject from the file name to allow filenames to be more
        // easily compared
        filename = path.substring(path.match(subject).index + subject.length);
        filename = filename.replace(subject, '<sub>');

        // generalize the run number so we can compare counts across all runs
        match = filename.match(/run-\d+/);
        if (match !== null) {
            filename = filename.replace(match[0], '<run>');
        }

        if (!nifti_types.hasOwnProperty(filename)) {
            nifti_types[filename] = {};
            nifti_types[filename][field_value] = {'count': 1, 'files': [file]};
        } else {
            if (!nifti_types[filename].hasOwnProperty(field_value)) {
                nifti_types[filename][field_value] = {'count': 1, 'files': [file]};
            } else {
                nifti_types[filename][field_value].count += 1;
                nifti_types[filename][field_value].files.push(file);
            }
        }
    }
    for (var nifti_key in nifti_types) {
        var nifti_type = nifti_types[nifti_key];
        var max_field_value = Object.keys(nifti_type)[0];
        for (var field_value_key in nifti_type) {
            field_value = nifti_type[field_value_key];
            if (field_value.count > nifti_type[max_field_value].count) {
                max_field_value = field_value_key;
            }
        }
        for (field_value_key in nifti_type) {
            field_value = nifti_type[field_value_key];
            if (max_field_value !== field_value_key && headerFieldCompare(max_field_value, field_value_key)) {
                for (var nifti_file_index in field_value.files) {
                    var nifti_file = field_value.files[nifti_file_index];
                    var evidence;
                    if (field === 'dim') {
                        evidence = " The most common set of dimensions is: " +
                                  max_field_value + "(voxels), This file has the dimensions: " +
                                  field_value_key + "(voxels)";
                    } else if (field === 'pixdim') {
                        evidence = " The most common resolution is: " +
                                  max_field_value.replace(/,/g, ' x ') + ", This file has the resolution: " +
                                  field_value_key.replace(/,/g, ' x ');
                    }
                        issues.push(new utils.Issue({
                        file: nifti_file,
                        evidence: evidence,
                        code: 39
                    }));
                }
            }
        }
    }
    return issues;
};

/**
 * if elements of the two arrays differ by less than one we won't raise a
 * warning about them. There are a large number of floating point rounding
 * errors that cause resolutions to be slightly different. Returns true if
 * the two headers are signifigantly different
 */
function headerFieldCompare(header1, header2) {
    var hdr1 = header1.split(',');
    var hdr2 = header2.split(',');
    for (var i = 0; i < hdr1.length; i++) {
        var hdr1_val = Number(hdr1[i].match(/-?\d*\.?\d*/));
        var hdr2_val  = Number(hdr2[i].match(/-?\d*\.?\d*/));
        // Matching alphas with * will return '' on headers without units
        var hdr1_unit = hdr1[i].match(/[A-Za-z]*$/)[0];
        var hdr2_unit = hdr2[i].match(/[A-Za-z]*$/)[0];
        if (Math.abs(hdr1_val - hdr2_val) > .00001) {
            return true;
        }
        if (hdr1_unit !== hdr2_unit) {
            return true;
        }
    }
    return false;
}

module.exports = headerFields;

<commit_msg>removed unused variable<commit_after>var utils  = require('../utils');

/**
 * dimensions and resolution
 *
 * Checks dimensions and resolution for x, y, z, and time across subjects to
 * ensure they are consistent.
 *
 * The fields we are interested in are all arrays and we are only looking at
 * the first for values in those arrays. To handle single values or longer
 * arrays more arguments will need to be added to headerField.
 */

var headerFields = function headerFields(headers) {
    var issues = [];
    issues = issues.concat(headerField(headers, 'dim'));
    issues = issues.concat(headerField(headers, 'pixdim'));
    return issues;
};

/**
 * Key to headerField working is the fact that we take and array of values
 * from the nifti header and convert it to a string. This string is used to
 * compare the header field value against other header field values and is used
 * as an attribute in the object nifti_types. Nifti types refers to the
 * different types of nifti files we are comparing across subjects. Only the
 * dimensionality of similar anatomy/functional/dwi headers are being compared.
 */

var headerField = function headerField(headers, field) {
    var nifti_types = {};
    var issues = [];
    for (var header_index in headers) {
        var badField = false;
        var field_value;
        var file = headers[header_index][0];
        var filename;
        var header = headers[header_index][1];
        var match;
        var path = utils.files.relativePath(file);
        var subject;

        if (field === 'dim') {
            if ((typeof header[field]) === 'undefined' || header[field] === null || header[field].length < header[field][0]) {
                issues.push(new utils.Issue({
                        file: file,
                        code: 40
                }));
                continue;
            }
            field_value = header[field].slice(1, header[field][0]+1).toString();
        } else if (field === 'pixdim') {
            if ((typeof header['xyzt_units']) === 'undefined' || header['xyzt_units'] === null || header['xyzt_units'].length < 4) {
                issues.push(new utils.Issue({
                        file: file,
                        code: 41
                }));
                badField = true;
            }
            if ((typeof header['pixdim']) === 'undefined' || header['pixdim'] === null || header['pixdim'].length < 4) {
                issues.push(new utils.Issue({
                        file: file,
                        code: 42
                }));
                badField = true;
            }
            if (badField === true) {
                continue;
            }
            field_value = [];
            var pix_dim = header[field].slice(1,5);
            var units = header['xyzt_units'].slice(0,4);
            for (var i = 0; i < 4; i++) {
                field_value.push('' + pix_dim[i] + units[i]);
            }
            field_value = field_value.toString();
        } else {
            console.warn("Checks against header field: " + field + " are currently unsupported.");
            return;
        }

        if (!file || (typeof window != 'undefined' && !file.webkitRelativePath)) {
            continue;
        }

        if (!utils.type.isBIDS(path)) {
            continue;
        }
        //match the subject identifier up to the '/' in the full path to a file.
        match = path.match(/sub-(.*?)(?=\/)/);
        if (match === null) {
            continue;
        } else {
            subject = match[0];
        }
        // files are prepended with subject name, the following two commands
        // remove the subject from the file name to allow filenames to be more
        // easily compared
        filename = path.substring(path.match(subject).index + subject.length);
        filename = filename.replace(subject, '<sub>');

        // generalize the run number so we can compare counts across all runs
        match = filename.match(/run-\d+/);
        if (match !== null) {
            filename = filename.replace(match[0], '<run>');
        }

        if (!nifti_types.hasOwnProperty(filename)) {
            nifti_types[filename] = {};
            nifti_types[filename][field_value] = {'count': 1, 'files': [file]};
        } else {
            if (!nifti_types[filename].hasOwnProperty(field_value)) {
                nifti_types[filename][field_value] = {'count': 1, 'files': [file]};
            } else {
                nifti_types[filename][field_value].count += 1;
                nifti_types[filename][field_value].files.push(file);
            }
        }
    }
    for (var nifti_key in nifti_types) {
        var nifti_type = nifti_types[nifti_key];
        var max_field_value = Object.keys(nifti_type)[0];
        for (var field_value_key in nifti_type) {
            field_value = nifti_type[field_value_key];
            if (field_value.count > nifti_type[max_field_value].count) {
                max_field_value = field_value_key;
            }
        }
        for (field_value_key in nifti_type) {
            field_value = nifti_type[field_value_key];
            if (max_field_value !== field_value_key && headerFieldCompare(max_field_value, field_value_key)) {
                for (var nifti_file_index in field_value.files) {
                    var nifti_file = field_value.files[nifti_file_index];
                    var evidence;
                    if (field === 'dim') {
                        evidence = " The most common set of dimensions is: " +
                                  max_field_value + "(voxels), This file has the dimensions: " +
                                  field_value_key + "(voxels)";
                    } else if (field === 'pixdim') {
                        evidence = " The most common resolution is: " +
                                  max_field_value.replace(/,/g, ' x ') + ", This file has the resolution: " +
                                  field_value_key.replace(/,/g, ' x ');
                    }
                        issues.push(new utils.Issue({
                        file: nifti_file,
                        evidence: evidence,
                        code: 39
                    }));
                }
            }
        }
    }
    return issues;
};

/**
 * if elements of the two arrays differ by less than one we won't raise a
 * warning about them. There are a large number of floating point rounding
 * errors that cause resolutions to be slightly different. Returns true if
 * the two headers are signifigantly different
 */
function headerFieldCompare(header1, header2) {
    var hdr1 = header1.split(',');
    var hdr2 = header2.split(',');
    for (var i = 0; i < hdr1.length; i++) {
        var hdr1_val = Number(hdr1[i].match(/-?\d*\.?\d*/));
        var hdr2_val  = Number(hdr2[i].match(/-?\d*\.?\d*/));
        // Matching alphas with * will return '' on headers without units
        var hdr1_unit = hdr1[i].match(/[A-Za-z]*$/)[0];
        var hdr2_unit = hdr2[i].match(/[A-Za-z]*$/)[0];
        if (Math.abs(hdr1_val - hdr2_val) > .00001) {
            return true;
        }
        if (hdr1_unit !== hdr2_unit) {
            return true;
        }
    }
    return false;
}

module.exports = headerFields;

<|endoftext|>


<commit_before>// ==UserScript==
// @name         MastodonTranslate
// @namespace    https://niu.moe/@tomo
// @version      1.7.2
// @description  Provides a translate toot option for Mastodon users via GoogleTranslate
// @author       tomo@uchuu.io / https://niu.moe/@tomo
// @match        *://*/web/*
// @match        *://*/settings/preferences
// @connect      translate.uchuu.io
// @grant        GM_getValue
// @grant        GM_xmlhttpRequest
// ==/UserScript==

(function() {
    'use strict';

    // Set Defaults if not set
    if(!localStorage.getItem('toggle')) {
        localStorage.setItem('toggle', GM_getValue('toggle', 'false'));
    }
    if(!localStorage.getItem('lang')) {
        localStorage.setItem('lang', GM_getValue('lang', 'en'));
    }

    function getTranslation(status, language, text) {
        text = encodeURIComponent(text);
        GM_xmlhttpRequest({
            method: 'GET',
            headers: {
                'Accept': 'application/json'
            },
            url: "https://translate.uchuu.io/"+language+'/'+text,
            onload: function(res) {
                var resJson = JSON.parse(res.responseText);
                var translatedText = resJson.text;

                var translateArea = document.createElement('p');
                translateArea.classList.add('toot__translation');
                translateArea.innerHTML = 'Translated: '+translatedText;

                status.querySelector('div.status__content').appendChild(translateArea);

                document.querySelector('li.translate__toot').remove();
                if (document.querySelector('div.dropdown-menu') !== null) {
                    status.querySelector('i.fa.fa-ellipsis-h').click();
                }
            },
            onerror: function() {
                console.log('There was an error');
            }
        });
    }

    function addTranslateLink(status) {
        var statusText = status.querySelector('div.status__content').textContent;
        setTimeout(function() {
            // var dropdown = status.querySelector('div.status__action-bar-dropdown');
            var dropdown = document.querySelector('div.dropdown-menu ul');
            var separator = dropdown.querySelector('li.dropdown-menu__separator');

            var listItem = document.createElement('li');
            listItem.classList.add('dropdown-menu__item');
            listItem.classList.add('translate__toot');

            var link = document.createElement('a');
            // link.setAttribute('href', 'https://translate.google.com/#auto/en/'+statusText);
            link.setAttribute('href', '#');
            link.setAttribute('target', '_blank');
            link.textContent = 'Translate Toot';
            link.addEventListener('click', function(e) {
                e.preventDefault();
                if (localStorage.getItem('toggle') == 'true' && status.querySelectorAll('p.toot__translation').length === 0) {
                    link.textContent = 'Loading...';
                    getTranslation(status, localStorage.getItem('lang'), statusText);
                } else if (localStorage.getItem('toggle') == 'false') {
                    window.location.href = window.location.origin + '/settings/preferences#translation_notice';
                }
            }, false);

            listItem.appendChild(link);
            dropdown.insertBefore(listItem, separator);
        }, 100);
    }

    function saveSettings(event) {
        if (event.target.tagName.toLowerCase() === 'button' && event.target.getAttribute('type') === 'submit') {
            event.preventDefault();
            var toggle = document.getElementById('user_translation_enabled');
            var selectedToggle = toggle.checked;
            localStorage.setItem('toggle', selectedToggle);

            var input = document.getElementById('translation_locale');
            var selectedLanguage = input.options[input.selectedIndex].value;
            localStorage.setItem('lang', selectedLanguage);

            setTimeout(function() {
                document.querySelector('body').removeEventListener('click', saveSettings, false);
                actions.children[0].click();
            }, 500);
        }
    }

    document.querySelector('body').addEventListener('click', function(event) {
        if (event.target.tagName.toLowerCase() === 'i' && event.target.classList.contains('fa-ellipsis-h') && document.querySelector('div.dropdown-menu') === null) {
            // Get the status for this event
            var status = event.target.parentNode.parentNode.parentNode.parentNode.parentNode;
            addTranslateLink(status);
        }
    }, false);

    if (window.location.pathname === '/settings/preferences') {
        // We're on the settings page
        var form = document.querySelector('form.simple_form');
        var actions = document.querySelector('div.actions');

        var settingsGroup = form.querySelector('div.fields-group').cloneNode(true);
        settingsGroup.children[1].remove(); // Remove the privacy element from the clone

        var notice = document.createElement('div');
        var noticeMsg = 'Translation is currently provided by Google Translate, if you\'re not happy with this please don\'t check the checkbox below or just uninstall the script. I\'m looking to offer alternatives to Google which you can track here: https://github.com/tomouchuu/mastodon-translate/issues/6';
        noticeMsg += '
If you have an issue please give me a buzz @tomo@niu.moe via mastodon or raise an issue on Github';
        notice.setAttribute('id', 'translation_notice');
        notice.innerHTML = '
Tampermonkey Translation Script

'+noticeMsg+'
';

        var toggle = document.createElement('div');
        toggle.classList.add('input');
        toggle.classList.add('boolean');
        toggle.classList.add('optional');
        toggle.classList.add('user_translation_enabled');
        toggle.innerHTML = '
<input value="0" type="hidden" name="user[translation_enabled]"><input class="boolean optional" type="checkbox" value="1" name="user[translation_enabled]" id="user_translation_enabled">I\'m happy to use Google Translate
';
        var checkbox = toggle.querySelector('input#user_translation_enabled');
        checkbox.checked = (localStorage.getItem('toggle') == 'true');

        var languageDiv = settingsGroup.children[0];
        languageDiv.classList.remove('user_locale');
        languageDiv.classList.add('translation_locale');
        var label = languageDiv.children[0].children[0];
        label.setAttribute('for', 'translation_locale');
        label.textContent = 'Translation Language';
        var input = languageDiv.children[0].children[1];
        input.setAttribute('name', 'user[translation]');
        input.setAttribute('id', 'translation_locale');
        input.value = localStorage.getItem('lang');

        settingsGroup.insertBefore(notice, languageDiv);
        settingsGroup.insertBefore(toggle, languageDiv);

        form.insertBefore(settingsGroup, actions);

        document.querySelector('body').addEventListener('click', saveSettings, false);
    }
})();<commit_msg>Fixes firefox, due to differences in event.target, closes #14<commit_after>// ==UserScript==
// @name         MastodonTranslate
// @namespace    https://niu.moe/@tomo
// @version      1.7.3
// @description  Provides a translate toot option for Mastodon users via GoogleTranslate
// @author       tomo@uchuu.io / https://niu.moe/@tomo
// @match        *://*/web/*
// @match        *://*/settings/preferences
// @connect      translate.uchuu.io
// @grant        GM_getValue
// @grant        GM_xmlhttpRequest
// ==/UserScript==

(function() {
    'use strict';

    // Set Defaults if not set
    if(!localStorage.getItem('toggle')) {
        localStorage.setItem('toggle', GM_getValue('toggle', 'false'));
    }
    if(!localStorage.getItem('lang')) {
        localStorage.setItem('lang', GM_getValue('lang', 'en'));
    }

    function getTranslation(status, language, text) {
        text = encodeURIComponent(text);
        GM_xmlhttpRequest({
            method: 'GET',
            headers: {
                'Accept': 'application/json'
            },
            url: "https://translate.uchuu.io/"+language+'/'+text,
            onload: function(res) {
                var resJson = JSON.parse(res.responseText);
                var translatedText = resJson.text;

                var translateArea = document.createElement('p');
                translateArea.classList.add('toot__translation');
                translateArea.innerHTML = 'Translated: '+translatedText;

                status.querySelector('div.status__content').appendChild(translateArea);

                document.querySelector('li.translate__toot').remove();
                if (document.querySelector('div.dropdown-menu') !== null) {
                    status.querySelector('i.fa.fa-ellipsis-h').click();
                }
            },
            onerror: function() {
                console.log('There was an error');
            }
        });
    }

    function addTranslateLink(status) {
        var statusText = status.querySelector('div.status__content').textContent;
        setTimeout(function() {
            // var dropdown = status.querySelector('div.status__action-bar-dropdown');
            var dropdown = document.querySelector('div.dropdown-menu ul');
            var separator = dropdown.querySelector('li.dropdown-menu__separator');

            var listItem = document.createElement('li');
            listItem.classList.add('dropdown-menu__item');
            listItem.classList.add('translate__toot');

            var link = document.createElement('a');
            // link.setAttribute('href', 'https://translate.google.com/#auto/en/'+statusText);
            link.setAttribute('href', '#');
            link.setAttribute('target', '_blank');
            link.textContent = 'Translate Toot';
            link.addEventListener('click', function(e) {
                e.preventDefault();
                if (localStorage.getItem('toggle') == 'true' && status.querySelectorAll('p.toot__translation').length === 0) {
                    link.textContent = 'Loading...';
                    getTranslation(status, localStorage.getItem('lang'), statusText);
                } else if (localStorage.getItem('toggle') == 'false') {
                    window.location.href = window.location.origin + '/settings/preferences#translation_notice';
                }
            }, false);

            listItem.appendChild(link);
            dropdown.insertBefore(listItem, separator);
        }, 100);
    }

    function saveSettings(event) {
        if (event.target.tagName.toLowerCase() === 'button' && event.target.getAttribute('type') === 'submit') {
            event.preventDefault();
            var toggle = document.getElementById('user_translation_enabled');
            var selectedToggle = toggle.checked;
            localStorage.setItem('toggle', selectedToggle);

            var input = document.getElementById('translation_locale');
            var selectedLanguage = input.options[input.selectedIndex].value;
            localStorage.setItem('lang', selectedLanguage);

            setTimeout(function() {
                document.querySelector('body').removeEventListener('click', saveSettings, false);
                actions.children[0].click();
            }, 500);
        }
    }

    function chromeClickChecker(event) {
        return(
            event.target.tagName.toLowerCase() === 'i' &&
            event.target.classList.contains('fa-ellipsis-h') &&
            document.querySelector('div.dropdown-menu') === null
        );
    }

    function firefoxClickChecker(event) {
        return(
            event.target.tagName.toLowerCase() === 'button' &&
            event.target.classList.contains('icon-button') &&
            document.querySelector('div.dropdown-menu') === null
        );
    }

    document.querySelector('body').addEventListener('click', function(event) {
        if (chromeClickChecker(event) || firefoxClickChecker(event)) {
            // Get the status for this event
            var status = event.target.parentNode.parentNode.parentNode.parentNode.parentNode;
            addTranslateLink(status);
        }
    }, false);

    if (window.location.pathname === '/settings/preferences') {
        // We're on the settings page
        var form = document.querySelector('form.simple_form');
        var actions = document.querySelector('div.actions');

        var settingsGroup = form.querySelector('div.fields-group').cloneNode(true);
        settingsGroup.children[1].remove(); // Remove the privacy element from the clone

        var notice = document.createElement('div');
        var noticeMsg = 'Translation is currently provided by Google Translate, if you\'re not happy with this please don\'t check the checkbox below or just uninstall the script. I\'m looking to offer alternatives to Google which you can track here: https://github.com/tomouchuu/mastodon-translate/issues/6';
        noticeMsg += '
If you have an issue please give me a buzz @tomo@niu.moe via mastodon or raise an issue on Github';
        notice.setAttribute('id', 'translation_notice');
        notice.innerHTML = '
Tampermonkey Translation Script

'+noticeMsg+'
';

        var toggle = document.createElement('div');
        toggle.classList.add('input');
        toggle.classList.add('boolean');
        toggle.classList.add('optional');
        toggle.classList.add('user_translation_enabled');
        toggle.innerHTML = '
<input value="0" type="hidden" name="user[translation_enabled]"><input class="boolean optional" type="checkbox" value="1" name="user[translation_enabled]" id="user_translation_enabled">I\'m happy to use Google Translate
';
        var checkbox = toggle.querySelector('input#user_translation_enabled');
        checkbox.checked = (localStorage.getItem('toggle') == 'true');

        var languageDiv = settingsGroup.children[0];
        languageDiv.classList.remove('user_locale');
        languageDiv.classList.add('translation_locale');
        var label = languageDiv.children[0].children[0];
        label.setAttribute('for', 'translation_locale');
        label.textContent = 'Translation Language';
        var input = languageDiv.children[0].children[1];
        input.setAttribute('name', 'user[translation]');
        input.setAttribute('id', 'translation_locale');
        input.value = localStorage.getItem('lang');

        settingsGroup.insertBefore(notice, languageDiv);
        settingsGroup.insertBefore(toggle, languageDiv);

        form.insertBefore(settingsGroup, actions);

        document.querySelector('body').addEventListener('click', saveSettings, false);
    }
})();<|endoftext|>


<commit_before>import React from 'react'
import {
  Text,
  View
} from 'react-native'
import Icon from 'react-native-vector-icons/FontAwesome'

import { color, styles } from '../styles'

export default class Home extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to Register!
        </Text>
        <Icon.Button name="facebook" backgroundColor="#3b5998" onPress={this.loginWithFacebook}>
          Register with Facebook
        </Icon.Button>
        <Icon.Button name="home" size={30} color={color.black} onPress={() => this.props.navigation.goBack()}>
          Go back home
        </Icon.Button>
      </View>
    )
  }
}
<commit_msg>update register component<commit_after>import React from 'react'
import {
  Text,
  TextInput,
  Image,
  View,
  TouchableOpacity
} from 'react-native'
import Icon from 'react-native-vector-icons/FontAwesome'

import { color, styles, styleMenu } from '../styles'

export default class Home extends React.Component {
  render() {
    return (
      <View style={styleMenu.containerLogin}>
        <View style={styleMenu.logoLoginContainer}>
          <Image
            style={styleMenu.logo}
            source={require('../../asset/logo/price-tag-percent.png')}
          />
          <Text style={styleMenu.title}>PRICE POLICE</Text>
        </View>
        <Text style={styleMenu.headerText}>REGISTER</Text>
      <View style={styleMenu.registerFrom}>
        <TextInput
          style={styleMenu.registerInput}
          placeholder="Fullname"
          placeholderTextColor="rgba(255,255,255,0.8)"
          placeholderStyle={{paddingLeft: 25}}
          underlineColorAndroid="transparent"
          returnKeyType="next"
        />
        <TextInput
          style={styleMenu.registerInput}
          placeholder="Email"
          placeholderTextColor="rgba(255,255,255,0.8)"
          underlineColorAndroid="transparent"
          returnKeyType="next"
        />
        <TextInput
          style={styleMenu.registerInput}
          placeholder="Password"
          placeholderTextColor="rgba(255,255,255,0.8)"
          underlineColorAndroid="transparent"
          secureTextEntry
          returnKeyType="next"
        />
        <TextInput
          style={styleMenu.registerInput}
          placeholder="Password (enter again)"
          placeholderTextColor="rgba(255,255,255,0.8)"
          underlineColorAndroid="transparent"
          secureTextEntry
          returnKeyType="next"
        />
      </View>
      <View style={styleMenu.registerFrom}>
        <TouchableOpacity style={styleMenu.buttonContainer}>
          <Text style={styleMenu.buttonText}>SIGN UP</Text>
        </TouchableOpacity>
        <Icon.Button name="user" size={25} backgroundColor="#3b3898" onPress={() => this.props.navigation.navigate('LittleMaps')}>Maps</Icon.Button>
      <Icon.Button name="user" size={25} backgroundColor="#3b3898" onPress={() => this.props.navigation.navigate('DetailProduct')}>Maps</Icon.Button>
      </View>
        {/* <Icon.Button name="facebook" backgroundColor="#3b5998" onPress={this.loginWithFacebook}>
          Register with Facebook
        </Icon.Button>
        <Icon.Button name="home" size={30} color={color.black} onPress={() => this.props.navigation.goBack()}>
          Go back home
        </Icon.Button>
        <Icon.Button name="user" size={25} backgroundColor="#3b3898" onPress={() => this.props.navigation.navigate('Maps')}>Maps</Icon.Button> */}
      </View>
    )
  }
}
<|endoftext|>


<commit_before>function Muppet(age, hobby) {
  this.age = age;
  this.hobby = hobby;

  this.answerNanny = function(){
	return "Everything's cool!";
  }
}

function SwedishChef(age, hobby, mood) {
  Muppet.call(this, age, hobby);
  this.mood = mood;

  this.cook = function() {
    return "Mmmm soup!";
  }
}

SwedishChef.prototype = new Muppet();

describe("About inheritance", function() {

  beforeEach(function(){
    this.muppet = new Muppet(2, "coding");
    this.swedishChef = new SwedishChef(2, "cooking", "chillin");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.swedishChef.cook()).toEqual("Mmmm soup!");
    console.log(this.muppet);
    console.log(this.swedishChef);
    debugger;
  });

  it("should be able to call a method on the base object", function() {
    expect(this.swedishChef.answerNanny()).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.swedishChef.age).toEqual(FILL_ME_IN);
    expect(this.swedishChef.hobby).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.swedishChef.mood).toEqual(FILL_ME_IN);
  });
});

/*****

// http://javascript.crockford.com/prototypal.html
Object.prototype.beget = function () {
  function F() {}
  F.prototype = this;
  return new F();
}

function Gonzo(age, hobby, trick) {
  Muppet.call(this, age, hobby);
  this.trick = trick;

  this.doTrick = function() {
    return this.trick;
  }
}

//no longer need to call the Muppet (base type) constructor
Gonzo.prototype = Muppet.prototype.beget();

describe("About Crockford's inheritance improvement", function() {
  beforeEach(function(){
  this.gonzo = new Gonzo(3, "daredevil performer", "eat a tire");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.gonzo.doTrick()).toEqual(FILL_ME_IN);
  });

  it("should be able to call a method on the base object", function() {
    expect(this.gonzo.answerNanny()).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.gonzo.age).toEqual(FILL_ME_IN);
    expect(this.gonzo.hobby).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.gonzo.trick).toEqual(FILL_ME_IN);
  });

});

********/
<commit_msg>inheritence!<commit_after>function Muppet(age, hobby) {
  this.age = age;
  this.hobby = hobby;

  this.answerNanny = function(){
	return "Everything's cool!";
  }
}

function SwedishChef(age, hobby, mood) {
  Muppet.call(this, age, hobby);
  this.mood = mood;

  this.cook = function() {
    return "Mmmm soup!";
  }
}

SwedishChef.prototype = new Muppet();

describe("About inheritance", function() {

  beforeEach(function(){
    this.muppet = new Muppet(2, "coding");
    this.swedishChef = new SwedishChef(2, "cooking", "chillin");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.swedishChef.cook()).toEqual("Mmmm soup!");
    console.log(this.muppet);
    console.log(this.swedishChef);

    console.log(this.swedishChef.age);
    console.log(this.swedishChef.hobby);
    console.log(this.muppet.age);
    console.log(this.muppet.hobby);
    debugger;
  });

  it("should be able to call a method on the base object", function() {
    expect(this.swedishChef.answerNanny()).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.swedishChef.age).toEqual(FILL_ME_IN);
    expect(this.swedishChef.hobby).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.swedishChef.mood).toEqual(FILL_ME_IN);
  });
});

/*****

// http://javascript.crockford.com/prototypal.html
Object.prototype.beget = function () {
  function F() {}
  F.prototype = this;
  return new F();
}

function Gonzo(age, hobby, trick) {
  Muppet.call(this, age, hobby);
  this.trick = trick;

  this.doTrick = function() {
    return this.trick;
  }
}

//no longer need to call the Muppet (base type) constructor
Gonzo.prototype = Muppet.prototype.beget();

describe("About Crockford's inheritance improvement", function() {
  beforeEach(function(){
  this.gonzo = new Gonzo(3, "daredevil performer", "eat a tire");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.gonzo.doTrick()).toEqual(FILL_ME_IN);
  });

  it("should be able to call a method on the base object", function() {
    expect(this.gonzo.answerNanny()).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.gonzo.age).toEqual(FILL_ME_IN);
    expect(this.gonzo.hobby).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.gonzo.trick).toEqual(FILL_ME_IN);
  });

});

********/
<|endoftext|>


<commit_before><commit_msg>fixed loop manager id management<commit_after><|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import Slider, { Handle } from 'rc-slider'
import './VolumeSlider.scss'

export default class VolumeSlider extends React.Component {
  static propTypes = {
    volume: PropTypes.number.isRequired,
    onVolumeChange: PropTypes.func.isRequired,
    className: PropTypes.string.isRequired,
  }

  state = {
    vol: this.props.volume,
    isDragging: false,
  }

  handleChange = this.handleChange.bind(this)
  handleAfterChange = this.handleAfterChange.bind(this)

  handleChange(vol) {
    this.setState({
      vol,
      isDragging: true,
    })
    this.props.onVolumeChange(vol)
    this.ignoreStatus = 0
  }

  handleAfterChange(vol) {
    this.setState({
      vol,
      isDragging: false,
    })
    this.props.onVolumeChange(vol)
    this.ignoreStatus = 2
  }

  componentDidUpdate(prevProps) {
    if (this.ignoreStatus && prevProps.volume !== this.props.volume) {
      this.ignoreStatus--
    }
  }

  render() {
    return (
      <Slider
        min={0}
        max={1}
        step={0.01}
        value={this.state.isDragging || this.ignoreStatus ? this.state.vol : this.props.volume}
        onChange={this.handleChange}
        onAfterChange={this.handleAfterChange}
        handle={handle}
        className={this.props.className}
      />
    )
  }
}

// volume slider handle/grabber
const handle = (props) => {
  const style = Object.assign({left: `${props.offset}%`}, {
    position: 'absolute',
    transform: 'translate(-50%, -50%)',
    marginTop: '6px',
    fontSize: '40px',
    opacity: .7,
    color: '#333',
    touchAction: 'pan-x',
  })

  let icon = "volume_up"
  if (props.value === 0) icon = "volume_off"
  else if (props.value < .4) icon = "volume_mute"
  else if (props.value < .7) icon = "volume_down"

  return (

      {icon}
      <Handle {...props}/>

  )
}
<commit_msg>"Unknown prop" warning workaround<commit_after>import React, { PropTypes } from 'react'
import Slider, { Handle } from 'rc-slider'
import './VolumeSlider.scss'

export default class VolumeSlider extends React.Component {
  static propTypes = {
    volume: PropTypes.number.isRequired,
    onVolumeChange: PropTypes.func.isRequired,
    className: PropTypes.string.isRequired,
  }

  state = {
    vol: this.props.volume,
    isDragging: false,
  }

  handleChange = this.handleChange.bind(this)
  handleAfterChange = this.handleAfterChange.bind(this)

  handleChange(vol) {
    this.setState({
      vol,
      isDragging: true,
    })
    this.props.onVolumeChange(vol)
    this.ignoreStatus = 0
  }

  handleAfterChange(vol) {
    this.setState({
      vol,
      isDragging: false,
    })
    this.props.onVolumeChange(vol)
    this.ignoreStatus = 2
  }

  componentDidUpdate(prevProps) {
    if (this.ignoreStatus && prevProps.volume !== this.props.volume) {
      this.ignoreStatus--
    }
  }

  render() {
    return (
      <Slider
        min={0}
        max={1}
        step={0.01}
        value={this.state.isDragging || this.ignoreStatus ? this.state.vol : this.props.volume}
        onChange={this.handleChange}
        onAfterChange={this.handleAfterChange}
        handle={handle}
        className={this.props.className}
      />
    )
  }
}

// volume slider handle/grabber
const handle = (props) => {
  const style = Object.assign({left: `${props.offset}%`}, {
    position: 'absolute',
    transform: 'translate(-50%, -50%)',
    marginTop: '6px',
    fontSize: '40px',
    opacity: .7,
    color: '#333',
    touchAction: 'pan-x',
  })

  let icon = "volume_up"
  if (props.value === 0) icon = "volume_off"
  else if (props.value < .4) icon = "volume_mute"
  else if (props.value < .7) icon = "volume_down"

  // will cause 'unknown prop' warning if passed to Handle
  delete props.dragging

  return (

      {icon}
      <Handle {...props}/>

  )
}
<|endoftext|>


<commit_before>import fs from "fs";
import path from "path";

const testCacheFilename = path.join(__dirname, ".babel");
const oldBabelDisableCacheValue = process.env.BABEL_DISABLE_CACHE;

process.env.BABEL_CACHE_PATH = testCacheFilename;
delete process.env.BABEL_DISABLE_CACHE;

function writeCache(data, mode = 0o666) {
  if (typeof data === "object") {
    data = JSON.stringify(data);
  }

  fs.writeFileSync(testCacheFilename, data, { mode });
}

function cleanCache() {
  try {
    fs.unlinkSync(testCacheFilename);
  } catch (e) {
    // It is convenient to always try to clear
  }
}

function resetCache() {
  process.env.BABEL_CACHE_PATH = null;
  process.env.BABEL_DISABLE_CACHE = oldBabelDisableCacheValue;
}

describe("@babel/register - caching", () => {
  describe("cache", () => {
    let load, get, save;

    beforeEach(() => {
      // Since lib/cache is a singleton we need to fully reload it
      jest.resetModules();
      const cache = require("../lib/cache");

      load = cache.load;
      get = cache.get;
      save = cache.save;
    });

    afterEach(cleanCache);
    afterAll(resetCache);

    it("should load and get cached data", () => {
      writeCache({ foo: "bar" });

      load();

      expect(get()).toEqual({ foo: "bar" });
    });

    it("should load and get an object with no cached data", () => {
      load();

      expect(get()).toEqual({});
    });

    it("should load and get an object with invalid cached data", () => {
      writeCache("foobar");

      load();

      expect(get()).toEqual({});
    });

    it("should create the cache on save", () => {
      save();

      expect(fs.existsSync(testCacheFilename)).toBe(true);
      expect(get()).toEqual({});
    });

    it("should create the cache after load", cb => {
      load();

      process.nextTick(() => {
        expect(fs.existsSync(testCacheFilename)).toBe(true);
        expect(get()).toEqual({});
        cb();
      });
    });

    // Only write mode is effective on Windows
    if (process.platform !== "win32") {
      it("should be disabled when CACHE_PATH is not allowed to read", () => {
        writeCache({ foo: "bar" }, 0o266);

        load();

        expect(get()).toEqual({});
      });
    }

    it("should be disabled when CACHE_PATH is not allowed to write", cb => {
      writeCache({ foo: "bar" }, 0o466);

      load();

      expect(get()).toEqual({ foo: "bar" });
      process.nextTick(() => {
        load();
        expect(get()).toEqual({});
        cb();
      });
    });
  });
});
<commit_msg>test: add console warn spy on babel-register tests (#11780)<commit_after>import fs from "fs";
import path from "path";

const testCacheFilename = path.join(__dirname, ".babel");
const oldBabelDisableCacheValue = process.env.BABEL_DISABLE_CACHE;

process.env.BABEL_CACHE_PATH = testCacheFilename;
delete process.env.BABEL_DISABLE_CACHE;

function writeCache(data, mode = 0o666) {
  if (typeof data === "object") {
    data = JSON.stringify(data);
  }

  fs.writeFileSync(testCacheFilename, data, { mode });
}

function cleanCache() {
  try {
    fs.unlinkSync(testCacheFilename);
  } catch (e) {
    // It is convenient to always try to clear
  }
}

function resetCache() {
  process.env.BABEL_CACHE_PATH = null;
  process.env.BABEL_DISABLE_CACHE = oldBabelDisableCacheValue;
}

describe("@babel/register - caching", () => {
  describe("cache", () => {
    let load, get, save;
    let consoleWarnSpy;

    beforeEach(() => {
      // Since lib/cache is a singleton we need to fully reload it
      jest.resetModules();
      const cache = require("../lib/cache");

      load = cache.load;
      get = cache.get;
      save = cache.save;

      consoleWarnSpy = jest.spyOn(console, "warn").mockImplementation(() => {});
    });

    afterEach(() => {
      cleanCache();
      consoleWarnSpy.mockRestore();
    });
    afterAll(resetCache);

    it("should load and get cached data", () => {
      writeCache({ foo: "bar" });

      load();

      expect(get()).toEqual({ foo: "bar" });
    });

    it("should load and get an object with no cached data", () => {
      load();

      expect(get()).toEqual({});
    });

    it("should load and get an object with invalid cached data", () => {
      writeCache("foobar");

      load();

      expect(get()).toEqual({});
    });

    it("should create the cache on save", () => {
      save();

      expect(fs.existsSync(testCacheFilename)).toBe(true);
      expect(get()).toEqual({});
    });

    it("should create the cache after load", cb => {
      load();

      process.nextTick(() => {
        expect(fs.existsSync(testCacheFilename)).toBe(true);
        expect(get()).toEqual({});
        cb();
      });
    });

    // Only write mode is effective on Windows
    if (process.platform !== "win32") {
      it("should be disabled when CACHE_PATH is not allowed to read", () => {
        writeCache({ foo: "bar" }, 0o266);
        load();

        expect(get()).toEqual({});
        expect(consoleWarnSpy.mock.calls[0][0]).toContain(
          "Babel could not read cache file",
        );
      });
    }

    it("should be disabled when CACHE_PATH is not allowed to write", cb => {
      writeCache({ foo: "bar" }, 0o466);

      load();

      expect(get()).toEqual({ foo: "bar" });
      process.nextTick(() => {
        load();
        expect(get()).toEqual({});
        expect(consoleWarnSpy.mock.calls[0][0]).toContain(
          "Babel could not write cache to file",
        );
        cb();
      });
    });
  });
});
<|endoftext|>


<commit_before>/**
 * Copyright 2013-2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @typechecks
 * @flow
 */

'use strict';

/**
 * TODO: Unify the two versions of `RelayNodeInterface`.
 */
module.exports = require('RelayFBNodeInterface');
<commit_msg>Relay: Use `RelayFBNodeInterface` for OSS Mock<commit_after>/**
 * Copyright 2013-2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @typechecks
 * @flow
 */

/**
 * TODO: Unify the two versions of `RelayNodeInterface`.
 */

'use strict';

import type {DataID} from 'RelayInternalTypes';
import type RelayQuery from 'RelayQuery';
import type RelayRecordStore from 'RelayRecordStore';

var forEachRootCallArg = require('forEachRootCallArg');
var generateClientID = require('generateClientID');
var invariant = require('invariant');

type PayloadResult = {
  dataID: DataID;
  result: mixed;
};

/**
 * @internal
 *
 * Defines logic relevant to the informal "Node" GraphQL interface.
 */
var RelayFBNodeInterface = {
  ID: 'id',
  NODE: 'node',
  NODE_TYPE: 'Node',
  NODES: 'nodes',

  isNodeRootCall(rootCallName: string): boolean {
    return (
      rootCallName === RelayFBNodeInterface.NODE ||
      rootCallName === RelayFBNodeInterface.NODES
    );
  },

  getResultsFromPayload(
    store: RelayRecordStore,
    query: RelayQuery.Root,
    payload: {[key: string]: mixed}
  ): Array<PayloadResult> {
    var results = [];

    var rootBatchCall = query.getBatchCall();
    if (rootBatchCall) {
      Object.keys(payload).forEach(dataID => {
        var result = payload[dataID];
        if (typeof result === 'object' && result !== null) {
          invariant(
            result[RelayFBNodeInterface.ID] === dataID,
            'RelayFBNodeInterface.getResultsFromPayload(): Expected each ' +
            'batch response for query `%s()` to have an `id`.',
            query.getName()
          );
          results.push({dataID, result});
        }
      });
    } else {
      forEachRootCallArg(query, (rootCallArg, rootCallName) => {
        var payloadKey = getPayloadKey(payload, rootCallName, rootCallArg);
        if (payloadKey == null || !payload.hasOwnProperty(payloadKey)) {
          return;
        }
        var result = payload[payloadKey];
        var dataID = store.getRootCallID(rootCallName, rootCallArg);

        if (dataID == null) {
          var payloadID = typeof result === 'object' && result ?
            result[RelayFBNodeInterface.ID] :
            null;
          if (payloadID != null) {
            // any root call where the response has an `id` field:
            // - `node(123)` with `{id: 123}`
            // - `username(joe)` with `{id: 123}`
            // - `me()` with `{id: 123}`
            dataID = payloadID;
          } else if (rootCallArg == null) {
            // argument-less root calls:
            // - `viewer()` without `id` in the response
            dataID = 'client:' + rootCallName;
          } else {
            // root calls with an argument:
            // - `foo(bar)` without `id` in the response
            dataID = generateClientID();
          }
          store.putRootCallID(rootCallName, rootCallArg, dataID);
        }
        results.push({dataID, result});
      });
    }

    return results;
  },
};

/**
 * Gets the key in `payload` that corresponds to results for the particular root
 * call argument supplied.
 */
function getPayloadKey(
  payload: {[key: string]: mixed},
  rootCallName: string,
  rootCallArg: ?string
): ?string {
  var payloadKey;
  var payloadKeys = Object.keys(payload);
  if (payloadKeys.length === 1) {
    payloadKey = payloadKeys[0];
  } else if (rootCallArg == null) {
    invariant(
      payloadKeys.length < 2,
      'writeRelayQueryPayload(): Expected payload to have at most 1 payload ' +
      'for root call `%s()`, called with %s payloads.',
      rootCallName,
      payloadKeys.length
    );
    payloadKey = payloadKeys[0];
  } else {
    payloadKey = rootCallArg;
  }
  return payloadKey;
}

module.exports = RelayFBNodeInterface;
<|endoftext|>


<commit_before>// Compares .sol files to their .sol.js counterparts,
// determines which .sol files have been updated.

var path = require("path");
var async = require("async");
var fs = require("fs");
var Parser = require("./parser");
var CompilerSupplier = require("./compilerSupplier");
var expect = require("truffle-expect");
var find_contracts = require("truffle-contract-sources");
var debug = require("debug")("compile:profiler"); // eslint-disable-line no-unused-vars

module.exports = {
  updated: function(options, callback) {
    expect.options(options, ["resolver"]);

    var contracts_directory = options.contracts_directory;
    var build_directory = options.contracts_build_directory;

    function getFiles(done) {
      if (options.files) {
        done(null, options.files);
      } else {
        find_contracts(contracts_directory, done);
      }
    }

    var sourceFilesArtifacts = {};
    var sourceFilesArtifactsUpdatedTimes = {};

    var updatedFiles = [];

    async.series(
      [
        // Get all the source files and create an object out of them.
        function(c) {
          getFiles(function(err, files) {
            if (err) return c(err);

            // Use an object for O(1) access.
            files.forEach(function(sourceFile) {
              sourceFilesArtifacts[sourceFile] = [];
            });

            c();
          });
        },
        // Get all the artifact files, and read them, parsing them as JSON
        function(c) {
          fs.readdir(build_directory, function(err, build_files) {
            if (err) {
              // The build directory may not always exist.
              if (
                err.message.indexOf("ENOENT: no such file or directory") >= 0
              ) {
                // Ignore it.
                build_files = [];
              } else {
                return c(err);
              }
            }

            build_files = build_files.filter(function(build_file) {
              return path.extname(build_file) === ".json";
            });

            async.map(
              build_files,
              function(buildFile, finished) {
                fs.readFile(
                  path.join(build_directory, buildFile),
                  "utf8",
                  function(err, body) {
                    if (err) return finished(err);
                    finished(null, body);
                  }
                );
              },
              function(err, jsonData) {
                if (err) return c(err);

                try {
                  for (var i = 0; i < jsonData.length; i++) {
                    var data = JSON.parse(jsonData[i]);

                    // In case there are artifacts from other source locations.
                    if (sourceFilesArtifacts[data.sourcePath] == null) {
                      sourceFilesArtifacts[data.sourcePath] = [];
                    }

                    sourceFilesArtifacts[data.sourcePath].push(data);
                  }
                } catch (e) {
                  return c(e);
                }

                c();
              }
            );
          });
        },
        function(c) {
          // Get the minimum updated time for all of a source file's artifacts
          // (note: one source file might have multiple artifacts).
          Object.keys(sourceFilesArtifacts).forEach(function(sourceFile) {
            var artifacts = sourceFilesArtifacts[sourceFile];

            sourceFilesArtifactsUpdatedTimes[sourceFile] = artifacts.reduce(
              function(minimum, current) {
                var updatedAt = new Date(current.updatedAt).getTime();

                if (updatedAt < minimum) {
                  return updatedAt;
                }
                return minimum;
              },
              Number.MAX_SAFE_INTEGER
            );

            // Empty array?
            if (
              sourceFilesArtifactsUpdatedTimes[sourceFile] ===
              Number.MAX_SAFE_INTEGER
            ) {
              sourceFilesArtifactsUpdatedTimes[sourceFile] = 0;
            }
          });

          c();
        },
        // Stat all the source files, getting there updated times, and comparing them to
        // the artifact updated times.
        function(c) {
          var sourceFiles = Object.keys(sourceFilesArtifacts);

          async.map(
            sourceFiles,
            function(sourceFile, finished) {
              fs.stat(sourceFile, function(err, stat) {
                if (err) {
                  // Ignore it. This means the source file was removed
                  // but the artifact file possibly exists. Return null
                  // to signfy that we should ignore it.
                  stat = null;
                }
                finished(null, stat);
              });
            },
            function(err, sourceFileStats) {
              if (err) return callback(err);

              sourceFiles.forEach(function(sourceFile, index) {
                var sourceFileStat = sourceFileStats[index];

                // Ignore updating artifacts if source file has been removed.
                if (sourceFileStat == null) {
                  return;
                }

                var artifactsUpdatedTime =
                  sourceFilesArtifactsUpdatedTimes[sourceFile] || 0;
                var sourceFileUpdatedTime = (
                  sourceFileStat.mtime || sourceFileStat.ctime
                ).getTime();

                if (sourceFileUpdatedTime > artifactsUpdatedTime) {
                  updatedFiles.push(sourceFile);
                }
              });

              c();
            }
          );
        }
      ],
      function(err) {
        callback(err, updatedFiles);
      }
    );
  },

  // Returns the minimal set of sources to pass to solc as compilations targets,
  // as well as the complete set of sources so solc can resolve the comp targets' imports.
  required_sources: function(options, callback) {
    var self = this;

    expect.options(options, ["paths", "base_path", "resolver"]);

    var resolver = options.resolver;

    // Fetch the whole contract set
    find_contracts(options.contracts_directory, (err, allPaths) => {
      if (err) return callback(err);

      // Solidity test files might have been injected. Include them in the known set.
      options.paths.forEach(_path => {
        if (!allPaths.includes(_path)) {
          allPaths.push(_path);
        }
      });

      var updates = self
        .convert_to_absolute_paths(options.paths, options.base_path)
        .sort();
      allPaths = self
        .convert_to_absolute_paths(allPaths, options.base_path)
        .sort();

      var allSources = {};
      var compilationTargets = [];

      // Load compiler
      const supplier = new CompilerSupplier(options.compilers.solc);
      supplier
        .load()
        .then(async solc => {
          // Get all the source code
          const resolved = await self.resolveAllSources(
            resolver,
            allPaths,
            solc
          );
          // Generate hash of all sources including external packages - passed to solc inputs.
          var resolvedPaths = Object.keys(resolved);
          resolvedPaths.forEach(
            file => (allSources[file] = resolved[file].body)
          );

          // Exit w/out minimizing if we've been asked to compile everything, or nothing.
          if (self.listsEqual(options.paths, allPaths)) {
            return callback(null, allSources, {});
          } else if (!options.paths.length) {
            return callback(null, {}, {});
          }

          // Seed compilationTargets with known updates
          updates.forEach(update => compilationTargets.push(update));

          // While there are updated files in the queue, we take each one
          // and search the entire file corpus to find any sources that import it.
          // Those sources are added to list of compilation targets as well as
          // the update queue because their own ancestors need to be discovered.
          async.whilst(
            () => updates.length > 0,
            updateFinished => {
              var currentUpdate = updates.shift();
              var files = allPaths.slice();

              // While files: dequeue and inspect their imports
              async.whilst(
                () => files.length > 0,
                fileFinished => {
                  var currentFile = files.shift();

                  // Ignore targets already selected.
                  if (compilationTargets.includes(currentFile)) {
                    return fileFinished();
                  }

                  var imports;
                  try {
                    imports = self.getImports(
                      currentFile,
                      resolved[currentFile],
                      solc
                    );
                  } catch (err) {
                    err.message =
                      "Error parsing " + currentFile + ": " + e.message;
                    return fileFinished(err);
                  }

                  // If file imports a compilation target, add it
                  // to list of updates and compilation targets
                  if (imports.includes(currentUpdate)) {
                    updates.push(currentFile);
                    compilationTargets.push(currentFile);
                  }

                  fileFinished();
                },
                err => updateFinished(err)
              );
            },
            err =>
              err
                ? callback(err)
                : callback(null, allSources, compilationTargets)
          );
        })
        .catch(callback);
    });
  },

  // Resolves sources in several async passes. For each resolved set it detects unknown
  // imports from external packages and adds them to the set of files to resolve.
  resolveAllSources: async function(resolver, initialPaths, solc) {
    var self = this;
    var mapping = {};
    var allPaths = initialPaths.slice();

    // Begin generateMapping
    function generateMapping(finished) {
      var promises = [];

      // Dequeue all the known paths, generating resolver promises,
      // We'll add paths if we discover external package imports.
      while (allPaths.length) {
        var file;
        var parent = null;

        var candidate = allPaths.shift();

        // Some paths will have been extracted as imports from a file
        // and have information about their parent location we need to track.
        if (typeof candidate === "object") {
          file = candidate.file;
          parent = candidate.parent;
        } else {
          file = candidate;
        }
        var promise = new Promise((accept, reject) => {
          resolver.resolve(file, parent, (err, body, absolutePath, source) => {
            err
              ? reject(err)
              : accept({ file: absolutePath, body: body, source: source });
          });
        });
        promises.push(promise);
      }

      // Resolve everything known and add it to the map, then inspect each file's
      // imports and add those to the list of paths to resolve if we don't have it.
      Promise.all(promises)
        .then(results => {
          // Generate the sources mapping
          results.forEach(
            item => (mapping[item.file] = Object.assign({}, item))
          );

          // Queue unknown imports for the next resolver cycle
          while (results.length) {
            var result = results.shift();

            // Inspect the imports
            var imports;
            try {
              imports = self.getImports(result.file, result, solc);
            } catch (err) {
              err.message = "Error parsing " + result.file + ": " + err.message;
              return finished(err);
            }

            // Detect unknown external packages / add them to the list of files to resolve
            // Keep track of location of this import because we need to report that.
            imports.forEach(item => {
              if (!mapping[item])
                allPaths.push({ file: item, parent: result.file });
            });
          }
        })
        .catch(finished)
        .then(finished);
    }
    // End generateMapping

    return new Promise((resolve, reject) => {
      async.whilst(() => allPaths.length, generateMapping, error => {
        if (error) reject(new Error(error));
        resolve(mapping);
      });
    });
  },

  getImports: function(file, resolved, solc) {
    var self = this;

    var imports = Parser.parseImports(resolved.body, solc);

    // Convert explicitly relative dependencies of modules back into module paths.
    return imports.map(dependencyPath => {
      return self.isExplicitlyRelative(dependencyPath)
        ? resolved.source.resolve_dependency_path(file, dependencyPath)
        : dependencyPath;
    });
  },

  listsEqual: function(listA, listB) {
    var a = listA.sort();
    var b = listB.sort();

    return JSON.stringify(a) === JSON.stringify(b);
  },

  convert_to_absolute_paths: function(paths, base) {
    var self = this;
    return paths.map(function(p) {
      // If it's anabsolute paths, leave it alone.
      if (path.isAbsolute(p)) return p;

      // If it's not explicitly relative, then leave it alone (i.e., it's a module).
      if (!self.isExplicitlyRelative(p)) return p;

      // Path must be explicitly releative, therefore make it absolute.
      return path.resolve(path.join(base, p));
    });
  },

  isExplicitlyRelative: function(import_path) {
    return import_path.indexOf(".") === 0;
  }
};
<commit_msg>skip parsing vyper files for imports<commit_after>// Compares .sol files to their .sol.js counterparts,
// determines which .sol files have been updated.

var path = require("path");
var async = require("async");
var fs = require("fs");
var Parser = require("./parser");
var CompilerSupplier = require("./compilerSupplier");
var expect = require("truffle-expect");
var find_contracts = require("truffle-contract-sources");
var debug = require("debug")("compile:profiler"); // eslint-disable-line no-unused-vars

module.exports = {
  updated: function(options, callback) {
    expect.options(options, ["resolver"]);

    var contracts_directory = options.contracts_directory;
    var build_directory = options.contracts_build_directory;

    function getFiles(done) {
      if (options.files) {
        done(null, options.files);
      } else {
        find_contracts(contracts_directory, done);
      }
    }

    var sourceFilesArtifacts = {};
    var sourceFilesArtifactsUpdatedTimes = {};

    var updatedFiles = [];

    async.series(
      [
        // Get all the source files and create an object out of them.
        function(c) {
          getFiles(function(err, files) {
            if (err) return c(err);

            // Use an object for O(1) access.
            files.forEach(function(sourceFile) {
              sourceFilesArtifacts[sourceFile] = [];
            });

            c();
          });
        },
        // Get all the artifact files, and read them, parsing them as JSON
        function(c) {
          fs.readdir(build_directory, function(err, build_files) {
            if (err) {
              // The build directory may not always exist.
              if (
                err.message.indexOf("ENOENT: no such file or directory") >= 0
              ) {
                // Ignore it.
                build_files = [];
              } else {
                return c(err);
              }
            }

            build_files = build_files.filter(function(build_file) {
              return path.extname(build_file) === ".json";
            });

            async.map(
              build_files,
              function(buildFile, finished) {
                fs.readFile(
                  path.join(build_directory, buildFile),
                  "utf8",
                  function(err, body) {
                    if (err) return finished(err);
                    finished(null, body);
                  }
                );
              },
              function(err, jsonData) {
                if (err) return c(err);

                try {
                  for (var i = 0; i < jsonData.length; i++) {
                    var data = JSON.parse(jsonData[i]);

                    // In case there are artifacts from other source locations.
                    if (sourceFilesArtifacts[data.sourcePath] == null) {
                      sourceFilesArtifacts[data.sourcePath] = [];
                    }

                    sourceFilesArtifacts[data.sourcePath].push(data);
                  }
                } catch (e) {
                  return c(e);
                }

                c();
              }
            );
          });
        },
        function(c) {
          // Get the minimum updated time for all of a source file's artifacts
          // (note: one source file might have multiple artifacts).
          Object.keys(sourceFilesArtifacts).forEach(function(sourceFile) {
            var artifacts = sourceFilesArtifacts[sourceFile];

            sourceFilesArtifactsUpdatedTimes[sourceFile] = artifacts.reduce(
              function(minimum, current) {
                var updatedAt = new Date(current.updatedAt).getTime();

                if (updatedAt < minimum) {
                  return updatedAt;
                }
                return minimum;
              },
              Number.MAX_SAFE_INTEGER
            );

            // Empty array?
            if (
              sourceFilesArtifactsUpdatedTimes[sourceFile] ===
              Number.MAX_SAFE_INTEGER
            ) {
              sourceFilesArtifactsUpdatedTimes[sourceFile] = 0;
            }
          });

          c();
        },
        // Stat all the source files, getting there updated times, and comparing them to
        // the artifact updated times.
        function(c) {
          var sourceFiles = Object.keys(sourceFilesArtifacts);

          async.map(
            sourceFiles,
            function(sourceFile, finished) {
              fs.stat(sourceFile, function(err, stat) {
                if (err) {
                  // Ignore it. This means the source file was removed
                  // but the artifact file possibly exists. Return null
                  // to signfy that we should ignore it.
                  stat = null;
                }
                finished(null, stat);
              });
            },
            function(err, sourceFileStats) {
              if (err) return callback(err);

              sourceFiles.forEach(function(sourceFile, index) {
                var sourceFileStat = sourceFileStats[index];

                // Ignore updating artifacts if source file has been removed.
                if (sourceFileStat == null) {
                  return;
                }

                var artifactsUpdatedTime =
                  sourceFilesArtifactsUpdatedTimes[sourceFile] || 0;
                var sourceFileUpdatedTime = (
                  sourceFileStat.mtime || sourceFileStat.ctime
                ).getTime();

                if (sourceFileUpdatedTime > artifactsUpdatedTime) {
                  updatedFiles.push(sourceFile);
                }
              });

              c();
            }
          );
        }
      ],
      function(err) {
        callback(err, updatedFiles);
      }
    );
  },

  // Returns the minimal set of sources to pass to solc as compilations targets,
  // as well as the complete set of sources so solc can resolve the comp targets' imports.
  required_sources: function(options, callback) {
    var self = this;

    expect.options(options, ["paths", "base_path", "resolver"]);

    var resolver = options.resolver;

    // Fetch the whole contract set
    find_contracts(options.contracts_directory, (err, allPaths) => {
      if (err) return callback(err);

      // Solidity test files might have been injected. Include them in the known set.
      options.paths.forEach(_path => {
        if (!allPaths.includes(_path)) {
          allPaths.push(_path);
        }
      });

      var updates = self
        .convert_to_absolute_paths(options.paths, options.base_path)
        .sort();
      allPaths = self
        .convert_to_absolute_paths(allPaths, options.base_path)
        .sort();

      var allSources = {};
      var compilationTargets = [];

      // Load compiler
      const supplier = new CompilerSupplier(options.compilers.solc);
      supplier
        .load()
        .then(async solc => {
          // Get all the source code
          const resolved = await self.resolveAllSources(
            resolver,
            allPaths,
            solc
          );
          // Generate hash of all sources including external packages - passed to solc inputs.
          var resolvedPaths = Object.keys(resolved);
          resolvedPaths.forEach(file => {
            allSources[file] = resolved[file].body;
          });

          // Exit w/out minimizing if we've been asked to compile everything, or nothing.
          if (self.listsEqual(options.paths, allPaths)) {
            return callback(null, allSources, {});
          } else if (!options.paths.length) {
            return callback(null, {}, {});
          }

          // Seed compilationTargets with known updates
          updates.forEach(update => compilationTargets.push(update));

          // While there are updated files in the queue, we take each one
          // and search the entire file corpus to find any sources that import it.
          // Those sources are added to list of compilation targets as well as
          // the update queue because their own ancestors need to be discovered.
          async.whilst(
            () => updates.length > 0,
            updateFinished => {
              var currentUpdate = updates.shift();
              var files = allPaths.slice();

              // While files: dequeue and inspect their imports
              async.whilst(
                () => files.length > 0,
                fileFinished => {
                  var currentFile = files.shift();

                  // Ignore targets already selected.
                  if (compilationTargets.includes(currentFile)) {
                    return fileFinished();
                  }

                  var imports;
                  try {
                    imports = self.getImports(
                      currentFile,
                      resolved[currentFile],
                      solc
                    );
                  } catch (err) {
                    err.message =
                      "Error parsing " + currentFile + ": " + e.message;
                    return fileFinished(err);
                  }

                  // If file imports a compilation target, add it
                  // to list of updates and compilation targets
                  if (imports.includes(currentUpdate)) {
                    updates.push(currentFile);
                    compilationTargets.push(currentFile);
                  }

                  fileFinished();
                },
                err => updateFinished(err)
              );
            },
            err =>
              err
                ? callback(err)
                : callback(null, allSources, compilationTargets)
          );
        })
        .catch(callback);
    });
  },

  // Resolves sources in several async passes. For each resolved set it detects unknown
  // imports from external packages and adds them to the set of files to resolve.
  resolveAllSources: async function(resolver, initialPaths, solc) {
    var self = this;
    var mapping = {};
    var allPaths = initialPaths.slice();

    // Begin generateMapping
    function generateMapping(finished) {
      var promises = [];

      // Dequeue all the known paths, generating resolver promises,
      // We'll add paths if we discover external package imports.
      while (allPaths.length) {
        var file;
        var parent = null;

        var candidate = allPaths.shift();

        // Some paths will have been extracted as imports from a file
        // and have information about their parent location we need to track.
        if (typeof candidate === "object") {
          file = candidate.file;
          parent = candidate.parent;
        } else {
          file = candidate;
        }
        var promise = new Promise((accept, reject) => {
          resolver.resolve(file, parent, (err, body, absolutePath, source) => {
            err
              ? reject(err)
              : accept({ file: absolutePath, body: body, source: source });
          });
        });
        promises.push(promise);
      }

      // Resolve everything known and add it to the map, then inspect each file's
      // imports and add those to the list of paths to resolve if we don't have it.
      Promise.all(promises)
        .then(results => {
          // Generate the sources mapping
          results.forEach(
            item => (mapping[item.file] = Object.assign({}, item))
          );

          // Queue unknown imports for the next resolver cycle
          while (results.length) {
            var result = results.shift();

            // Inspect the imports
            var imports;
            try {
              imports = self.getImports(result.file, result, solc);
            } catch (err) {
              err.message = "Error parsing " + result.file + ": " + err.message;
              return finished(err);
            }

            // Detect unknown external packages / add them to the list of files to resolve
            // Keep track of location of this import because we need to report that.
            imports.forEach(item => {
              if (!mapping[item])
                allPaths.push({ file: item, parent: result.file });
            });
          }
        })
        .catch(finished)
        .then(finished);
    }
    // End generateMapping

    return new Promise((resolve, reject) => {
      async.whilst(() => allPaths.length, generateMapping, error => {
        if (error) reject(new Error(error));
        resolve(mapping);
      });
    });
  },

  getImports: function(file, resolved, solc) {
    var self = this;

    // No imports in vyper!
    if (path.extname(file) === ".vy") return [];

    var imports = Parser.parseImports(resolved.body, solc);

    // Convert explicitly relative dependencies of modules back into module paths.
    return imports.map(dependencyPath => {
      return self.isExplicitlyRelative(dependencyPath)
        ? resolved.source.resolve_dependency_path(file, dependencyPath)
        : dependencyPath;
    });
  },

  listsEqual: function(listA, listB) {
    var a = listA.sort();
    var b = listB.sort();

    return JSON.stringify(a) === JSON.stringify(b);
  },

  convert_to_absolute_paths: function(paths, base) {
    var self = this;
    return paths.map(function(p) {
      // If it's anabsolute paths, leave it alone.
      if (path.isAbsolute(p)) return p;

      // If it's not explicitly relative, then leave it alone (i.e., it's a module).
      if (!self.isExplicitlyRelative(p)) return p;

      // Path must be explicitly releative, therefore make it absolute.
      return path.resolve(path.join(base, p));
    });
  },

  isExplicitlyRelative: function(import_path) {
    return import_path.indexOf(".") === 0;
  }
};
<|endoftext|>