<commit_before>Imcms.define("imcms-access-tab-builder",
    [
        "imcms-bem-builder", "imcms-components-builder", "imcms-roles-rest-api", "imcms-page-info-tab-form-builder",
        "imcms-uuid-generator", "jquery", "imcms-i18n-texts"
    ],
    function (BEM, components, rolesRestApi, tabContentBuilder, uuidGenerator, $, texts) {

        texts = texts.pageInfo.access;

        var storedRoleIdsPerRoles;
        var storedRoles;

        var rolesBEM = new BEM({
            block: "imcms-access-role",
            elements: {
                "head": "",
                "title": "imcms-title",
                "body": "",
                "row": "",
                "column-title": "imcms-title",
                "column": "imcms-radio",
                "button": "imcms-button"
            }
        });

        function storeRoles(roles) {
            storedRoles = roles;
            storedRoleIdsPerRoles = {};

            roles.forEach(function (role) {
                storedRoleIdsPerRoles[role.id] = role;
            });
        }

        function mapRoleOnSelectOption(role) {
            return {
                text: role.name,
                "data-value": role.id
            }
        }

        function generateRoleRow(role, $addRoleSelect) {
            function buildRole(roleName, role, radioName) {
                return rolesBEM.makeBlockElement("column", components.radios.imcmsRadio("<div>", {
                    name: radioName,
                    value: roleName,
                    checked: roleName === role.permission ? "checked" : undefined
                }));
            }

            function displayAddRoleSelectAndBtn($addRoleSelect) {
                $addRoleSelect.css("display", "block");
                var $addRoleBtn = $addRoleSelect.next();
                $addRoleBtn.css("display", "block");
            }

            function hideRolesField($rolesBody) {
                var $rolesField = $rolesBody.parent().parent();
                $rolesField.css("display", "none");
            }

            var $roleTitle = rolesBEM.buildBlockElement("column-title", "<div>", mapRoleOnSelectOption(role)),
                radioName = uuidGenerator.generateUUID(),
                $roleView = buildRole("VIEW", role, radioName),
                $roleEdit = buildRole("EDIT", role, radioName),
                $roleRestricted1 = buildRole("RESTRICTED_1", role, radioName),
                $roleRestricted2 = buildRole("RESTRICTED_2", role, radioName),
                $row = rolesBEM.buildBlockElement("row", "<div>", {"data-role-id": role.id}),
                onDeleteRoleClick = function () {
                    components.selects.addOptionsToSelect([mapRoleOnSelectOption(role)], $addRoleSelect);

                    if ($addRoleSelect.hasOptions()) {
                        displayAddRoleSelectAndBtn($addRoleSelect);
                    }

                    var $rolesBody = $row.parent();

                    $row.detach();

                    var tableContainsRows = $rolesBody.find("[data-role-id]").length;
                    if (!tableContainsRows) {
                        hideRolesField($rolesBody);
                    }
                },
                $deleteRoleButton = rolesBEM.makeBlockElement(
                    "button", components.buttons.closeButton({click: onDeleteRoleClick})
                )
            ;

            return $row.append([
                $roleTitle,
                $roleView,
                $roleEdit,
                $roleRestricted1,
                $roleRestricted2,
                $deleteRoleButton
            ]);
        }

        var tabData = {};

        return {
            name: texts.name,
            tabIndex: null,
            isDocumentTypeSupported: function () {
                return true; // all supported
            },
            showTab: function () {
                tabContentBuilder.showTab(this.tabIndex);
            },
            hideTab: function () {
                tabContentBuilder.hideTab(this.tabIndex);
            },
            buildTab: function (index, docId) {
                this.tabIndex = index;
                var $addRoleSelect = components.selects.imcmsSelect("<div>");

                if (!docId) {
                    function mapRoles(roles) {
                        var rolesDataMapped = roles.map(mapRoleOnSelectOption);
                        components.selects.addOptionsToSelect(rolesDataMapped, $addRoleSelect);
                    }

                    storedRoles ? mapRoles(storedRoles) : rolesRestApi.read(null).done(function (roles) {
                        storeRoles(roles);
                        mapRoles(roles);
                    });
                }

                var $titleRole = rolesBEM.buildBlockElement("title", "<div>", {text: texts.role}),
                    $titleView = rolesBEM.buildBlockElement("title", "<div>", {text: texts.view}),
                    $titleEdit = rolesBEM.buildBlockElement("title", "<div>", {text: texts.edit}),
                    $titleRestricted1 = rolesBEM.buildBlockElement("title", "<div>", {text: texts.restricted_1}),
                    $titleRestricted2 = rolesBEM.buildBlockElement("title", "<div>", {text: texts.restricted_2}),
                    $rolesHead = $("<div>", {
                        html: [$titleRole, $titleView, $titleEdit, $titleRestricted1, $titleRestricted2]
                    }),
                    $rolesBody = $("<div>"),
                    $rolesTable = rolesBEM.buildBlock("<div>", [
                        {"head": $rolesHead},
                        {"body": $rolesBody}
                    ]),
                    $rolesField = new BEM({
                        block: "imcms-field",
                        elements: {
                            "access-role": $rolesTable
                        }
                    }).buildBlockStructure("<div>")
                ;

                tabData.$addRoleSelect = $addRoleSelect;
                tabData.$rolesBody = $rolesBody;
                tabData.$rolesField = $rolesField.css("display", "none");

                var $addRoleButton = components.buttons.neutralButton({
                        text: texts.addRole,
                        click: function () {
                            var id = $addRoleSelect.getSelectedValue();
                            var role = {
                                id: id,
                                name: $addRoleSelect.selectedText()
                            };

                            var $row = generateRoleRow(role, $addRoleSelect);
                            $row.find(":radio")
                                .first()
                                .prop("checked", "checked");

                            $rolesBody.append($row);
                            $addRoleSelect.deleteOption(id);

                            if (!$addRoleSelect.hasOptions()) {
                                $addRoleSelect.css("display", "none");
                                $addRoleButton.css("display", "none");
                            } else {
                                $addRoleSelect.selectFirst();
                            }

                            $rolesField.css("display", "block");
                        }
                    }),

                    $addRoleInnerBlock = new BEM({
                        block: "imcms-access-addrole",
                        elements: {
                            "select": $addRoleSelect,
                            "button": $addRoleButton
                        }
                    }).buildBlockStructure("<div>"),

                    $addRoleContainer = new BEM({
                        block: "imcms-field",
                        elements: {
                            "access-role": $addRoleInnerBlock
                        }
                    }).buildBlockStructure("<div>")
                ;

                return tabContentBuilder.buildFormBlock([$rolesField, $addRoleContainer], index);
            },

            fillTabDataFromDocument: function (document) {
                function documentContainsRole(document, role) {
                    return document.roleIdToPermission[role.id];
                }

                function buildRolesRows(roles) {
                    var rolesDataMapped = roles.filter(function (role) {
                        return !documentContainsRole(document, role);
                    }).map(mapRoleOnSelectOption);

                    tabData.$addRoleSelect.clearSelect();

                    var addRoleDisplay = "none",
                        $addRoleBtn = tabData.$addRoleSelect.next();

                    if (rolesDataMapped.length) {
                        addRoleDisplay = "block";
                        components.selects.addOptionsToSelect(rolesDataMapped, tabData.$addRoleSelect);
                    }

                    tabData.$addRoleSelect.css("display", addRoleDisplay);
                    $addRoleBtn.css("display", addRoleDisplay);

                    var $roles = Object.keys(document.roleIdToPermission).map(function (roleId) {
                        var role = storedRoleIdsPerRoles[roleId];
                        role.permission = document.roleIdToPermission[roleId];

                        return generateRoleRow(role, tabData.$addRoleSelect);
                    });

                    if ($roles.length) {
                        tabData.$rolesBody.prepend($roles);
                        tabData.$rolesField.css("display", "block");
                    }
                }

                (storedRoles) ? buildRolesRows(storedRoles) : rolesRestApi.read(null).done(function (roles) {
                    storeRoles(roles);
                    buildRolesRows(roles);
                });
            },

            saveData: function (documentDTO) {
                documentDTO.roleIdToPermission = {};

                tabData.$rolesBody.find("[data-role-id]")
                    .toArray()
                    .forEach(function (roleRow) {
                        var $roleRow = $(roleRow);
                        var radios$ = $roleRow.find(".imcms-radio")
                            .map(function () {
                                return $(this);
                            })
                            .toArray();

                        var permission = components.radios.group.apply(components.radios, radios$).getCheckedValue();
                        var id = $roleRow.data("roleId");

                        documentDTO.roleIdToPermission[id] = permission;
                    });

                return documentDTO;
            },

            clearTabData: function () {
                tabData.$rolesBody.empty();
                tabData.$rolesField.css("display", "none");
            }
        };
    }
);
<commit_msg>IMCMS-300 - New design to superadmin-pages: - Build process of access tab refactored.<commit_after>Imcms.define("imcms-access-tab-builder",
    [
        "imcms-bem-builder", "imcms-components-builder", "imcms-roles-rest-api", "imcms-uuid-generator", "jquery",
        "imcms-i18n-texts", "imcms-window-tab"
    ],
    function (BEM, components, rolesRestApi, uuidGenerator, $, texts, WindowTab) {

        texts = texts.pageInfo.access;

        var storedRoleIdsPerRoles;
        var storedRoles;

        var rolesBEM = new BEM({
            block: "imcms-access-role",
            elements: {
                "head": "",
                "title": "imcms-title",
                "body": "",
                "row": "",
                "column-title": "imcms-title",
                "column": "imcms-radio",
                "button": "imcms-button"
            }
        });

        function storeRoles(roles) {
            storedRoles = roles;
            storedRoleIdsPerRoles = {};

            roles.forEach(function (role) {
                storedRoleIdsPerRoles[role.id] = role;
            });
        }

        function mapRoleOnSelectOption(role) {
            return {
                text: role.name,
                "data-value": role.id
            }
        }

        function generateRoleRow(role, $addRoleSelect) {
            function buildRole(roleName, role, radioName) {
                return rolesBEM.makeBlockElement("column", components.radios.imcmsRadio("<div>", {
                    name: radioName,
                    value: roleName,
                    checked: roleName === role.permission ? "checked" : undefined
                }));
            }

            function displayAddRoleSelectAndBtn($addRoleSelect) {
                $addRoleSelect.css("display", "block");
                var $addRoleBtn = $addRoleSelect.next();
                $addRoleBtn.css("display", "block");
            }

            function hideRolesField($rolesBody) {
                var $rolesField = $rolesBody.parent().parent();
                $rolesField.css("display", "none");
            }

            var $roleTitle = rolesBEM.buildBlockElement("column-title", "<div>", mapRoleOnSelectOption(role)),
                radioName = uuidGenerator.generateUUID(),
                $roleView = buildRole("VIEW", role, radioName),
                $roleEdit = buildRole("EDIT", role, radioName),
                $roleRestricted1 = buildRole("RESTRICTED_1", role, radioName),
                $roleRestricted2 = buildRole("RESTRICTED_2", role, radioName),
                $row = rolesBEM.buildBlockElement("row", "<div>", {"data-role-id": role.id}),
                onDeleteRoleClick = function () {
                    components.selects.addOptionsToSelect([mapRoleOnSelectOption(role)], $addRoleSelect);

                    if ($addRoleSelect.hasOptions()) {
                        displayAddRoleSelectAndBtn($addRoleSelect);
                    }

                    var $rolesBody = $row.parent();

                    $row.detach();

                    var tableContainsRows = $rolesBody.find("[data-role-id]").length;
                    if (!tableContainsRows) {
                        hideRolesField($rolesBody);
                    }
                },
                $deleteRoleButton = rolesBEM.makeBlockElement(
                    "button", components.buttons.closeButton({click: onDeleteRoleClick})
                )
            ;

            return $row.append([
                $roleTitle,
                $roleView,
                $roleEdit,
                $roleRestricted1,
                $roleRestricted2,
                $deleteRoleButton
            ]);
        }

        var tabData = {};

        var AccessTab = function (name) {
            WindowTab.call(this, name);
        };

        AccessTab.prototype = Object.create(WindowTab.prototype);

        AccessTab.prototype.isDocumentTypeSupported = function () {
            return true; // all supported
        };
        AccessTab.prototype.buildTab = function (index, docId) {
            this.tabIndex = index;
            var $addRoleSelect = components.selects.imcmsSelect("<div>");

            if (!docId) {
                function mapRoles(roles) {
                    var rolesDataMapped = roles.map(mapRoleOnSelectOption);
                    components.selects.addOptionsToSelect(rolesDataMapped, $addRoleSelect);
                }

                storedRoles ? mapRoles(storedRoles) : rolesRestApi.read(null).done(function (roles) {
                    storeRoles(roles);
                    mapRoles(roles);
                });
            }

            var $titleRole = rolesBEM.buildBlockElement("title", "<div>", {text: texts.role}),
                $titleView = rolesBEM.buildBlockElement("title", "<div>", {text: texts.view}),
                $titleEdit = rolesBEM.buildBlockElement("title", "<div>", {text: texts.edit}),
                $titleRestricted1 = rolesBEM.buildBlockElement("title", "<div>", {text: texts.restricted_1}),
                $titleRestricted2 = rolesBEM.buildBlockElement("title", "<div>", {text: texts.restricted_2}),
                $rolesHead = $("<div>", {
                    html: [$titleRole, $titleView, $titleEdit, $titleRestricted1, $titleRestricted2]
                }),
                $rolesBody = $("<div>"),
                $rolesTable = rolesBEM.buildBlock("<div>", [
                    {"head": $rolesHead},
                    {"body": $rolesBody}
                ]),
                $rolesField = new BEM({
                    block: "imcms-field",
                    elements: {
                        "access-role": $rolesTable
                    }
                }).buildBlockStructure("<div>")
            ;

            tabData.$addRoleSelect = $addRoleSelect;
            tabData.$rolesBody = $rolesBody;
            tabData.$rolesField = $rolesField.css("display", "none");

            var $addRoleButton = components.buttons.neutralButton({
                    text: texts.addRole,
                    click: function () {
                        var id = $addRoleSelect.getSelectedValue();
                        var role = {
                            id: id,
                            name: $addRoleSelect.selectedText()
                        };

                        var $row = generateRoleRow(role, $addRoleSelect);
                        $row.find(":radio")
                            .first()
                            .prop("checked", "checked");

                        $rolesBody.append($row);
                        $addRoleSelect.deleteOption(id);

                        if (!$addRoleSelect.hasOptions()) {
                            $addRoleSelect.css("display", "none");
                            $addRoleButton.css("display", "none");
                        } else {
                            $addRoleSelect.selectFirst();
                        }

                        $rolesField.css("display", "block");
                    }
                }),

                $addRoleInnerBlock = new BEM({
                    block: "imcms-access-addrole",
                    elements: {
                        "select": $addRoleSelect,
                        "button": $addRoleButton
                    }
                }).buildBlockStructure("<div>"),

                $addRoleContainer = new BEM({
                    block: "imcms-field",
                    elements: {
                        "access-role": $addRoleInnerBlock
                    }
                }).buildBlockStructure("<div>")
            ;

            return this.tabFormBuilder.buildFormBlock([$rolesField, $addRoleContainer], index);
        };
        AccessTab.prototype.fillTabDataFromDocument = function (document) {
            function documentContainsRole(document, role) {
                return document.roleIdToPermission[role.id];
            }

            function buildRolesRows(roles) {
                var rolesDataMapped = roles.filter(function (role) {
                    return !documentContainsRole(document, role);
                }).map(mapRoleOnSelectOption);

                tabData.$addRoleSelect.clearSelect();

                var addRoleDisplay = "none",
                    $addRoleBtn = tabData.$addRoleSelect.next();

                if (rolesDataMapped.length) {
                    addRoleDisplay = "block";
                    components.selects.addOptionsToSelect(rolesDataMapped, tabData.$addRoleSelect);
                }

                tabData.$addRoleSelect.css("display", addRoleDisplay);
                $addRoleBtn.css("display", addRoleDisplay);

                var $roles = Object.keys(document.roleIdToPermission).map(function (roleId) {
                    var role = storedRoleIdsPerRoles[roleId];
                    role.permission = document.roleIdToPermission[roleId];

                    return generateRoleRow(role, tabData.$addRoleSelect);
                });

                if ($roles.length) {
                    tabData.$rolesBody.prepend($roles);
                    tabData.$rolesField.css("display", "block");
                }
            }

            (storedRoles) ? buildRolesRows(storedRoles) : rolesRestApi.read(null).done(function (roles) {
                storeRoles(roles);
                buildRolesRows(roles);
            });
        };
        AccessTab.prototype.saveData = function (documentDTO) {
            documentDTO.roleIdToPermission = {};

            tabData.$rolesBody.find("[data-role-id]")
                .toArray()
                .forEach(function (roleRow) {
                    var $roleRow = $(roleRow);
                    var radios$ = $roleRow.find(".imcms-radio")
                        .map(function () {
                            return $(this);
                        })
                        .toArray();

                    var permission = components.radios.group.apply(components.radios, radios$).getCheckedValue();
                    var id = $roleRow.data("roleId");

                    documentDTO.roleIdToPermission[id] = permission;
                });

            return documentDTO;
        };
        AccessTab.prototype.clearTabData = function () {
            tabData.$rolesBody.empty();
            tabData.$rolesField.css("display", "none");
        };

        return new AccessTab(texts.name);
    }
);
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import ImmutablePropTypes from 'react-immutable-proptypes'
import { FormattedMessage } from 'react-intl'
import { lightGreen400} from 'material-ui/styles/colors'
import jp from 'jsonpath'
import Chip from 'material-ui/Chip'
import FlatButton from 'material-ui/FlatButton'
import { Link } from 'react-router'
// import ImmutablePropTypes from 'react-immutable-proptypes'
import H3 from 'components/H3'
import P from 'components/P'
import Divider from 'material-ui/Divider'
import  messages from './messages'

const styles = {
  chip: {
    margin: '4px'
  }
}
export default class PictogramCategories extends Component {
  static propTypes = {
    categories: PropTypes.object.isRequired,
    pictoCategories: PropTypes.array.isRequired,
    tags: ImmutablePropTypes.list.isRequired,
  }

  render() {
    const { categories, pictoCategories,  tags } = this.props
    const tree = categories.toJSON()
    const nodes = jp.nodes(tree, '$..text')
    const nodesKeywords = jp.nodes(tree, '$..keywords')
    const categoryPaths = nodes
      .filter(node => {
        const lastCategoryCount = node.path.length - 1
        const lastCategory = node.path[lastCategoryCount - 1]
        return pictoCategories.indexOf(lastCategory) !== -1
      })
      .sort((a, b) => {
        const aLastCategoryCount = a.path.length - 1
        const aLastCategory = a.path[aLastCategoryCount - 1]
        const bLastCategoryCount = b.path.length - 1
        const bLastCategory = b.path[bLastCategoryCount - 1]
        return pictoCategories.indexOf(aLastCategory) - pictoCategories.indexOf(bLastCategory)
      })
      .map(node=>node.path)
      .map(path => {
        const categoryPath = []
        path.forEach((category)  => {
          if (['$', 'children', 'text'].indexOf(category)=== -1)
            categoryPath.push(category)

          })
        return categoryPath
      }).map(path =>path.map((category) => {
          const text = nodes.filter(node => {
            const lastCategoryCount = node.path.length - 1
            const lastCategory = node.path[lastCategoryCount - 1]
            return lastCategory===category
          })
          const keywords = nodesKeywords.filter(node => {
            const lastCategoryCount = node.path.length - 1
            const lastCategory = node.path[lastCategoryCount - 1]
            return lastCategory===category
          })
          return {text: text[0].value, keyword: keywords[0].value[0] }
        })
      )
    const renderPaths = categoryPaths
      .map((categoryPath,  index) =>

          { categoryPath.map((item, index) => {
            if  (!index) {
              return !item.keyword ?
                <FlatButton key={item.text} label={item.text} disabled={true}/>
              : <Link to={`/pictograms/search/${item.keyword}`}>
                  <FlatButton key={item.text} label={item.text} />
              </Link>

            }
            else {
              return item.keyword ?

 /

                  <Link to={`/pictograms/search/${item.keyword}`}>
                    <FlatButton key={item.text} label={item.text} />
                  </Link>

              :

 /

                  <FlatButton label={item.text}  disabled={true}/>

            }
          })}

    )
    return  (

{<FormattedMessage {...messages.taxonomy} />}

        <Divider />

{<FormattedMessage {...messages.pictoBelongs} />}

        {renderPaths.map(path =>

            {path}

        )}

{<FormattedMessage {...messages.pictoLabels} />}

        { tags &&

            {tags.map(tag =>
              <Chip  key={tag} style={styles.chip}>
                {tag}
              {/* {<FormattedMessage {...messages[tag]} />} */}
              </Chip>
            )}

        }

    )
  }
}
<commit_msg>fix tags translations<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import ImmutablePropTypes from 'react-immutable-proptypes'
import { FormattedMessage } from 'react-intl'
import jp from 'jsonpath'
import Chip from 'material-ui/Chip'
import FlatButton from 'material-ui/FlatButton'
import { Link } from 'react-router'
// import ImmutablePropTypes from 'react-immutable-proptypes'
import H3 from 'components/H3'
import P from 'components/P'
import Divider from 'material-ui/Divider'
import tagMessages from 'components/PictogramTags/messages'
import  messages from './messages'

const styles = {
  chip: {
    margin: '4px'
  }
}
export default class PictogramCategories extends Component {
  static propTypes = {
    categories: PropTypes.object.isRequired,
    pictoCategories: PropTypes.array.isRequired,
    tags: ImmutablePropTypes.list.isRequired,
  }

  render() {
    const { categories, pictoCategories,  tags } = this.props
    const tree = categories.toJSON()
    const nodes = jp.nodes(tree, '$..text')
    const nodesKeywords = jp.nodes(tree, '$..keywords')
    const categoryPaths = nodes
      .filter(node => {
        const lastCategoryCount = node.path.length - 1
        const lastCategory = node.path[lastCategoryCount - 1]
        return pictoCategories.indexOf(lastCategory) !== -1
      })
      .sort((a, b) => {
        const aLastCategoryCount = a.path.length - 1
        const aLastCategory = a.path[aLastCategoryCount - 1]
        const bLastCategoryCount = b.path.length - 1
        const bLastCategory = b.path[bLastCategoryCount - 1]
        return pictoCategories.indexOf(aLastCategory) - pictoCategories.indexOf(bLastCategory)
      })
      .map(node=>node.path)
      .map(path => {
        const categoryPath = []
        path.forEach((category)  => {
          if (['$', 'children', 'text'].indexOf(category)=== -1)
            categoryPath.push(category)

          })
        return categoryPath
      }).map(path =>path.map((category) => {
          const text = nodes.filter(node => {
            const lastCategoryCount = node.path.length - 1
            const lastCategory = node.path[lastCategoryCount - 1]
            return lastCategory===category
          })
          const keywords = nodesKeywords.filter(node => {
            const lastCategoryCount = node.path.length - 1
            const lastCategory = node.path[lastCategoryCount - 1]
            return lastCategory===category
          })
          return {text: text[0].value, keyword: keywords[0].value[0] }
        })
      )
    const renderPaths = categoryPaths
      .map((categoryPath,  index) =>

          { categoryPath.map((item, index) => {
            if  (!index) {
              return !item.keyword ?
                <FlatButton key={item.text} label={item.text} disabled={true}/>
              : <Link to={`/pictograms/search/${item.keyword}`}>
                  <FlatButton key={item.text} label={item.text} />
              </Link>

            }
            else {
              return item.keyword ?

 /

                  <Link to={`/pictograms/search/${item.keyword}`}>
                    <FlatButton key={item.text} label={item.text} />
                  </Link>

              :

 /

                  <FlatButton label={item.text}  disabled={true}/>

            }
          })}

    )
    return  (

{<FormattedMessage {...messages.taxonomy} />}

        <Divider />

{<FormattedMessage {...messages.pictoBelongs} />}

        {renderPaths.map(path =>

            {path}

        )}

{<FormattedMessage {...messages.pictoLabels} />}

        { tags &&

            {tags.map(tag =>
              <Chip  key={tag} style={styles.chip}>
              {<FormattedMessage {...tagMessages[tag]} />}
              </Chip>
            )}

        }

    )
  }
}
<|endoftext|>


<commit_before>
function Apt() {
    this.name = "APT";
    this.description = "Atom Probe Tomography";
    this._type = "APT";
    this.input_files = [];
    this.output_files = [];
    this.input_samples = [];
    this.output_samples = [];
    this.transformed_samples = [];
    this.project_id = "";
    this.what = "";
    this.why = "";
    this.who = "";
    this.settings = [
        {
            property: {
                name: "Mode",
                attribute: "mode",
                description: "",
                value: null,
                units: [],
                unit: null,
                _type: "selection",
                required: true,
                choices: [
                    {
                        name: "FIM",
                        value: "fim"
                    },
                    {
                        name: "Voltage",
                        value: "voltage"
                    },
                    {
                        name: "Laser",
                        value: "laser"
                    }
                ]
            },
            validators: [],
            valid: false,
            errorMessage: ""
        },
        {
            property:{
                name: "Specimen Temperature",
                attribute: "specimen_temperature",
                description: "",
                value: null,
                units: [],
                unit: "K",
                _type: "number",
                required: true,
                choices: []
            },
            validators: [],
            valid: false,
            errorMessage: ""
        },
        {
            property:{
                name: "Voltage Pulse Fraction",
                attribute: "voltage_pulse_fraction",
                description: "",
                value: null,
                units: [],
                unit:"percentage",
                _type: "number",
                required: false,
                choices: []
            },
            validators: [],
            valid: false,
            errorMessage: ""
        },
        {
            property:{
                name: "Laser Pulse Energy",
                attribute: "laser_pulse_energy",
                description: "",
                value: null,
                units: ["pJ", "nJ"],
                unit: null,
                _type: "number",
                required: false,
                choices: []
            },
            validators: [],
            valid: false,
            errorMessage: ""
        },
        {
            property:{
                name: "Laser Wavelength",
                attribute: "laser_wavelength",
                description: "",
                value: null,
                units: [],
                unit: "nm",
                _type: "number",
                required: false,
                choices: []
            },
            validators: [],
            valid: false,
            errorMessage: ""
        },
        {
            property:{
                name: "Pulse Frequency",
                attribute: "pulse_frequency",
                description: "",
                value: null,
                units: [],
                unit: "kHz",
                _type: "number",
                required: false,
                choices: []
            },
            validators: [],
            valid: false,
            errorMessage: ""
        },
        {
            property:{
                name: "Evaporation Control",
                attribute: "evaporation_control",
                description: "",
                value: null,
                units: [],
                unit: null,
                _type: "selection",
                required: false,
                choices: [
                    {
                        "name": "Constant Detector Rate",
                        "value" : "constant_detector_rate"
                    },
                    {
                        "name": "Constant Evaporation Rate",
                        "value" : "constant_evaporation_rate"
                    },
                    {
                        "name": "Constant Charge Rate Ratio",
                        "value" : "constant_charge_rate_ratio"
                    },
                    {
                        "name": "Other",
                        "value" : "other"
                    }
                ]
            },
            validators: [],
            valid: false,
            errorMessage: ""
        },
        {
            property:{
                name: "Evaporation Rate",
                attribute: "evaporation_rate",
                description: "",
                value: null,
                units: [],
                unit: "Atom/Pulse",
                required: false,
                _type: "number",
                choices: []
            },
            validators: [],
            valid: false,
            errorMessage: ""
        },
        {
            property:{
                name: "Imaging Gas",
                attribute: "imaging_gas",
                description: "",
                value: null,
                units: [],
                unit: null,
                required: false,
                _type: "selection",
                choices: [
                    {
                        "name": "He",
                        "value" : "He"
                    },
                    {
                        "name": "Ar",
                        "value" : "Ar"
                    },
                    {
                        "name": "Ne",
                        "value" : "Ne"
                    },
                    {
                        "name": "Other",
                        "value" : "other"
                    },
                    {
                        "name": "None",
                        "value" : "none"
                    }
                ]
            },
            validators: [],
            valid: false,
            errorMessage: ""
        },
        {
            property:{
                name: "Pressure",
                attribute: "pressure",
                description: "",
                value: null,
                units: ["atm", "Pa", "torr"],
                unit: null,
                required: false,
                _type: "number",
                choices: []
            },
            validators: [],
            valid: false,
            errorMessage: ""
        }
    ];
}
<commit_msg>Change who to owner.<commit_after>
function Apt() {
    this.name = "APT";
    this.description = "Atom Probe Tomography";
    this._type = "APT";
    this.input_files = [];
    this.output_files = [];
    this.input_samples = [];
    this.output_samples = [];
    this.transformed_samples = [];
    this.project_id = "";
    this.what = "";
    this.why = "";
    this.owner = "";
    this.settings = [
        {
            property: {
                name: "Mode",
                attribute: "mode",
                description: "",
                value: null,
                units: [],
                unit: null,
                _type: "selection",
                required: true,
                choices: [
                    {
                        name: "FIM",
                        value: "fim"
                    },
                    {
                        name: "Voltage",
                        value: "voltage"
                    },
                    {
                        name: "Laser",
                        value: "laser"
                    }
                ]
            },
            validators: [],
            valid: false,
            errorMessage: ""
        },
        {
            property:{
                name: "Specimen Temperature",
                attribute: "specimen_temperature",
                description: "",
                value: null,
                units: [],
                unit: "K",
                _type: "number",
                required: true,
                choices: []
            },
            validators: [],
            valid: false,
            errorMessage: ""
        },
        {
            property:{
                name: "Voltage Pulse Fraction",
                attribute: "voltage_pulse_fraction",
                description: "",
                value: null,
                units: [],
                unit:"percentage",
                _type: "number",
                required: false,
                choices: []
            },
            validators: [],
            valid: false,
            errorMessage: ""
        },
        {
            property:{
                name: "Laser Pulse Energy",
                attribute: "laser_pulse_energy",
                description: "",
                value: null,
                units: ["pJ", "nJ"],
                unit: null,
                _type: "number",
                required: false,
                choices: []
            },
            validators: [],
            valid: false,
            errorMessage: ""
        },
        {
            property:{
                name: "Laser Wavelength",
                attribute: "laser_wavelength",
                description: "",
                value: null,
                units: [],
                unit: "nm",
                _type: "number",
                required: false,
                choices: []
            },
            validators: [],
            valid: false,
            errorMessage: ""
        },
        {
            property:{
                name: "Pulse Frequency",
                attribute: "pulse_frequency",
                description: "",
                value: null,
                units: [],
                unit: "kHz",
                _type: "number",
                required: false,
                choices: []
            },
            validators: [],
            valid: false,
            errorMessage: ""
        },
        {
            property:{
                name: "Evaporation Control",
                attribute: "evaporation_control",
                description: "",
                value: null,
                units: [],
                unit: null,
                _type: "selection",
                required: false,
                choices: [
                    {
                        "name": "Constant Detector Rate",
                        "value" : "constant_detector_rate"
                    },
                    {
                        "name": "Constant Evaporation Rate",
                        "value" : "constant_evaporation_rate"
                    },
                    {
                        "name": "Constant Charge Rate Ratio",
                        "value" : "constant_charge_rate_ratio"
                    },
                    {
                        "name": "Other",
                        "value" : "other"
                    }
                ]
            },
            validators: [],
            valid: false,
            errorMessage: ""
        },
        {
            property:{
                name: "Evaporation Rate",
                attribute: "evaporation_rate",
                description: "",
                value: null,
                units: [],
                unit: "Atom/Pulse",
                required: false,
                _type: "number",
                choices: []
            },
            validators: [],
            valid: false,
            errorMessage: ""
        },
        {
            property:{
                name: "Imaging Gas",
                attribute: "imaging_gas",
                description: "",
                value: null,
                units: [],
                unit: null,
                required: false,
                _type: "selection",
                choices: [
                    {
                        "name": "He",
                        "value" : "He"
                    },
                    {
                        "name": "Ar",
                        "value" : "Ar"
                    },
                    {
                        "name": "Ne",
                        "value" : "Ne"
                    },
                    {
                        "name": "Other",
                        "value" : "other"
                    },
                    {
                        "name": "None",
                        "value" : "none"
                    }
                ]
            },
            validators: [],
            valid: false,
            errorMessage: ""
        },
        {
            property:{
                name: "Pressure",
                attribute: "pressure",
                description: "",
                value: null,
                units: ["atm", "Pa", "torr"],
                unit: null,
                required: false,
                _type: "number",
                choices: []
            },
            validators: [],
            valid: false,
            errorMessage: ""
        }
    ];
}
<|endoftext|>


<commit_before>    angular.module('container', [])
    .controller('ContainerController', ['$scope', '$routeParams', '$location', 'Container', 'ContainerCommit', 'Image', 'Messages', 'ViewSpinner', '$timeout',
        function ($scope, $routeParams, $location, Container, ContainerCommit, Image, Messages, ViewSpinner, $timeout) {
            $scope.changes = [];
            $scope.editEnv = false;
            $scope.editPorts = false;
            $scope.editBinds = false;
            $scope.newCfg = {
                Env: [],
                Ports: {}
            };

            var update = function () {
                ViewSpinner.spin();
                Container.get({id: $routeParams.id}, function (d) {
                    $scope.container = d;
                    $scope.container.edit = false;
                    $scope.container.newContainerName = d.Name;

                    // fill up env
                    if (d.Config.Env) {
                        $scope.newCfg.Env = d.Config.Env.map(function (entry) {
                            return {name: entry.split('=')[0], value: entry.split('=')[1]};
                        });
                    }

                    // fill up ports
                    $scope.newCfg.Ports = {};
                    angular.forEach(d.Config.ExposedPorts, function(i, port) {
                        if (d.HostConfig.PortBindings && port in d.HostConfig.PortBindings)
                            $scope.newCfg.Ports[port] = d.HostConfig.PortBindings[port];
                        else
                            $scope.newCfg.Ports[port] = [];
                    });

                    // fill up bindings
                    $scope.newCfg.Binds = [];
                    var defaultBinds = {};
                    angular.forEach(d.Config.Volumes, function(value, vol) {
                        defaultBinds[vol] = { ContPath: vol, HostPath: '', ReadOnly: false, DefaultBind: true };
                    });
                    angular.forEach(d.HostConfig.Binds, function(binding, i) {
                        var mountpoint = binding.split(':')[0];
                        var vol = binding.split(':')[1] || '';
                        var ro = binding.split(':').length > 2 && binding.split(':')[2] == 'ro';
                        var defaultBind = false;
                        if (vol == '') {
                            vol = mountpoint;
                            mountpoint = '';
                        }

                        if (vol in defaultBinds) {
                            delete defaultBinds[vol];
                            defaultBind = true;
                        }
                        $scope.newCfg.Binds.push({ ContPath: vol, HostPath: mountpoint, ReadOnly: ro, DefaultBind: defaultBind });
                    });
                    angular.forEach(defaultBinds, function(bind) {
                        $scope.newCfg.Binds.push(bind);
                    });

                    console.log($scope.newCfg);

                    ViewSpinner.stop();
                }, function (e) {
                    if (e.status === 404) {
                        $('.detail').hide();
                        Messages.error("Not found", "Container not found.");
                    } else {
                        Messages.error("Failure", e.data);
                    }
                    ViewSpinner.stop();
                });

            };

            $scope.start = function () {
                ViewSpinner.spin();
                Container.start({
                    id: $scope.container.Id,
                    HostConfig: $scope.container.HostConfig
                }, function (d) {
                    update();
                    Messages.send("Container started", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to start." + e.data);
                });
            };

            $scope.stop = function () {
                ViewSpinner.spin();
                Container.stop({id: $routeParams.id}, function (d) {
                    update();
                    Messages.send("Container stopped", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to stop." + e.data);
                });
            };

            $scope.kill = function () {
                ViewSpinner.spin();
                Container.kill({id: $routeParams.id}, function (d) {
                    update();
                    Messages.send("Container killed", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to die." + e.data);
                });
            };

            $scope.restartEnv = function () {
                var config = angular.copy($scope.container.Config);

                config.Env = $scope.newCfg.Env.map(function(entry) {
                    return entry.name+"="+entry.value;
                });

                var portBindings = angular.copy($scope.newCfg.Ports);

                var binds = [];
                angular.forEach($scope.newCfg.Binds, function(b) {
                    if (b.ContPath != '') {
                        var bindLine = '';
                        if (b.HostPath != '') {
                            bindLine = b.HostPath + ':';
                        }
                        bindLine += b.ContPath;
                        if (b.ReadOnly) {
                            bindLine += ':ro';
                        }
                        binds.push(bindLine);
                    }
                });

                ViewSpinner.spin();
                ContainerCommit.commit({id: $routeParams.id, tag: $scope.container.Config.Image, config: config }, function (d) {
                    if ('Id' in d) {
                        var imageId = d.Id;
                        Image.inspect({id: imageId}, function(imageData) {
                            // Append current host config to image with new port bindings
                            imageData.Config.HostConfig = angular.copy($scope.container.HostConfig);
                            imageData.Config.HostConfig.PortBindings = portBindings;
                            imageData.Config.HostConfig.Binds = binds;

                            Container.create(imageData.Config, function(containerData) {
                                // Stop current if running
                                if ($scope.container.State.Running) {
                                    Container.stop({id: $routeParams.id}, function (d) {
                                        Messages.send("Container stopped", $routeParams.id);
                                        // start new
                                        Container.start({
                                            id: containerData.Id
                                            // HostConfig: $scope.container.HostConfig we really need this?
                                        }, function (d) {
                                            $location.url('/containers/' + containerData.Id + '/');
                                            Messages.send("Container started", $routeParams.id);
                                        }, function (e) {
                                            update();
                                            Messages.error("Failure", "Container failed to start." + e.data);
                                        });
                                    }, function (e) {
                                        update();
                                        Messages.error("Failure", "Container failed to stop." + e.data);
                                    });
                                } else {
                                    // start new
                                    Container.start({
                                        id: containerData.Id
                                        // HostConfig: $scope.container.HostConfig we really need this?
                                    }, function (d) {
                                        $location.url('/containers/'+containerData.Id+'/');
                                        Messages.send("Container started", $routeParams.id);
                                    }, function (e) {
                                        update();
                                        Messages.error("Failure", "Container failed to start." + e.data);
                                    });
                                }

                            }, function(e) {
                                update();
                                Messages.error("Failure", "Image failed to get." + e.data);
                            });
                        }, function (e) {
                            update();
                            Messages.error("Failure", "Image failed to get." + e.data);
                        })

                    } else {
                        update();
                        Messages.send("Container commit failed", $routeParams.id);
                    }

                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to commit." + e.data);
                });
            };

            $scope.commit = function () {
                ViewSpinner.spin();
                ContainerCommit.commit({id: $routeParams.id, repo: $scope.container.Config.Image}, function (d) {
                    update();
                    Messages.send("Container commited", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to commit." + e.data);
                });
            };
            $scope.pause = function () {
                ViewSpinner.spin();
                Container.pause({id: $routeParams.id}, function (d) {
                    update();
                    Messages.send("Container paused", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to pause." + e.data);
                });
            };

            $scope.unpause = function () {
                ViewSpinner.spin();
                Container.unpause({id: $routeParams.id}, function (d) {
                    update();
                    Messages.send("Container unpaused", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to unpause." + e.data);
                });
            };

            $scope.remove = function () {
                ViewSpinner.spin();
                Container.remove({id: $routeParams.id}, function (d) {
                    update();
                    $location.path('/containers');
                    Messages.send("Container removed", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to remove." + e.data);
                });
            };

            $scope.restart = function () {
                ViewSpinner.spin();
                Container.restart({id: $routeParams.id}, function (d) {
                    update();
                    Messages.send("Container restarted", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to restart." + e.data);
                });
            };

            $scope.hasContent = function (data) {
                return data !== null && data !== undefined;
            };

            $scope.getChanges = function () {
                ViewSpinner.spin();
                Container.changes({id: $routeParams.id}, function (d) {
                    $scope.changes = d;
                    ViewSpinner.stop();
                });
            };

            $scope.renameContainer = function () {
                // #FIXME fix me later to handle http status to show the correct error message
                Container.rename({id: $routeParams.id, 'name': $scope.container.newContainerName}, function (data) {
                    if (data.name) {
                        $scope.container.Name = data.name;
                        Messages.send("Container renamed", $routeParams.id);
                    } else {
                        $scope.container.newContainerName = $scope.container.Name;
                        Messages.error("Failure", "Container failed to rename.");
                    }
                });
                $scope.container.edit = false;
            };

            $scope.addEntry = function (array, entry) {
                array.push(entry);
            };
            $scope.rmEntry = function (array, entry) {
                var idx = array.indexOf(entry);
                array.splice(idx, 1);
            };

            $scope.toggleEdit = function() {
                $scope.edit = !$scope.edit;
            };

            update();
            $scope.getChanges();
        }]);

<commit_msg>Null vars fix<commit_after>    angular.module('container', [])
    .controller('ContainerController', ['$scope', '$routeParams', '$location', 'Container', 'ContainerCommit', 'Image', 'Messages', 'ViewSpinner', '$timeout',
        function ($scope, $routeParams, $location, Container, ContainerCommit, Image, Messages, ViewSpinner, $timeout) {
            $scope.changes = [];
            $scope.editEnv = false;
            $scope.editPorts = false;
            $scope.editBinds = false;
            $scope.newCfg = {
                Env: [],
                Ports: {}
            };

            var update = function () {
                ViewSpinner.spin();
                Container.get({id: $routeParams.id}, function (d) {
                    $scope.container = d;
                    $scope.container.edit = false;
                    $scope.container.newContainerName = d.Name;

                    // fill up env
                    if (d.Config.Env) {
                        $scope.newCfg.Env = d.Config.Env.map(function (entry) {
                            return {name: entry.split('=')[0], value: entry.split('=')[1]};
                        });
                    }

                    // fill up ports
                    $scope.newCfg.Ports = {};
                    angular.forEach(d.Config.ExposedPorts, function(i, port) {
                        if (d.HostConfig.PortBindings && port in d.HostConfig.PortBindings)
                            $scope.newCfg.Ports[port] = d.HostConfig.PortBindings[port];
                        else
                            $scope.newCfg.Ports[port] = [];
                    });

                    // fill up bindings
                    $scope.newCfg.Binds = [];
                    var defaultBinds = {};
                    angular.forEach(d.Config.Volumes, function(value, vol) {
                        defaultBinds[vol] = { ContPath: vol, HostPath: '', ReadOnly: false, DefaultBind: true };
                    });
                    angular.forEach(d.HostConfig.Binds, function(binding, i) {
                        var mountpoint = binding.split(':')[0];
                        var vol = binding.split(':')[1] || '';
                        var ro = binding.split(':').length > 2 && binding.split(':')[2] == 'ro';
                        var defaultBind = false;
                        if (vol == '') {
                            vol = mountpoint;
                            mountpoint = '';
                        }

                        if (vol in defaultBinds) {
                            delete defaultBinds[vol];
                            defaultBind = true;
                        }
                        $scope.newCfg.Binds.push({ ContPath: vol, HostPath: mountpoint, ReadOnly: ro, DefaultBind: defaultBind });
                    });
                    angular.forEach(defaultBinds, function(bind) {
                        $scope.newCfg.Binds.push(bind);
                    });

                    ViewSpinner.stop();
                }, function (e) {
                    if (e.status === 404) {
                        $('.detail').hide();
                        Messages.error("Not found", "Container not found.");
                    } else {
                        Messages.error("Failure", e.data);
                    }
                    ViewSpinner.stop();
                });

            };

            $scope.start = function () {
                ViewSpinner.spin();
                Container.start({
                    id: $scope.container.Id,
                    HostConfig: $scope.container.HostConfig
                }, function (d) {
                    update();
                    Messages.send("Container started", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to start." + e.data);
                });
            };

            $scope.stop = function () {
                ViewSpinner.spin();
                Container.stop({id: $routeParams.id}, function (d) {
                    update();
                    Messages.send("Container stopped", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to stop." + e.data);
                });
            };

            $scope.kill = function () {
                ViewSpinner.spin();
                Container.kill({id: $routeParams.id}, function (d) {
                    update();
                    Messages.send("Container killed", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to die." + e.data);
                });
            };

            $scope.restartEnv = function () {
                var config = angular.copy($scope.container.Config);

                config.Env = $scope.newCfg.Env.map(function(entry) {
                    return entry.name+"="+entry.value;
                });

                var portBindings = angular.copy($scope.newCfg.Ports);

                var binds = [];
                angular.forEach($scope.newCfg.Binds, function(b) {
                    if (b.ContPath != '') {
                        var bindLine = '';
                        if (b.HostPath != '') {
                            bindLine = b.HostPath + ':';
                        }
                        bindLine += b.ContPath;
                        if (b.ReadOnly) {
                            bindLine += ':ro';
                        }
                        if (b.HostPath != '' || !b.DefaultBind) {
                            binds.push(bindLine);
                        }
                    }
                });

                ViewSpinner.spin();
                ContainerCommit.commit({id: $routeParams.id, tag: $scope.container.Config.Image, config: config }, function (d) {
                    if ('Id' in d) {
                        var imageId = d.Id;
                        Image.inspect({id: imageId}, function(imageData) {
                            // Append current host config to image with new port bindings
                            imageData.Config.HostConfig = angular.copy($scope.container.HostConfig);
                            imageData.Config.HostConfig.PortBindings = portBindings;
                            imageData.Config.HostConfig.Binds = binds;

                            Container.create(imageData.Config, function(containerData) {
                                // Stop current if running
                                if ($scope.container.State.Running) {
                                    Container.stop({id: $routeParams.id}, function (d) {
                                        Messages.send("Container stopped", $routeParams.id);
                                        // start new
                                        Container.start({
                                            id: containerData.Id
                                            // HostConfig: $scope.container.HostConfig we really need this?
                                        }, function (d) {
                                            $location.url('/containers/' + containerData.Id + '/');
                                            Messages.send("Container started", $routeParams.id);
                                        }, function (e) {
                                            update();
                                            Messages.error("Failure", "Container failed to start." + e.data);
                                        });
                                    }, function (e) {
                                        update();
                                        Messages.error("Failure", "Container failed to stop." + e.data);
                                    });
                                } else {
                                    // start new
                                    Container.start({
                                        id: containerData.Id
                                        // HostConfig: $scope.container.HostConfig we really need this?
                                    }, function (d) {
                                        $location.url('/containers/'+containerData.Id+'/');
                                        Messages.send("Container started", $routeParams.id);
                                    }, function (e) {
                                        update();
                                        Messages.error("Failure", "Container failed to start." + e.data);
                                    });
                                }

                            }, function(e) {
                                update();
                                Messages.error("Failure", "Image failed to get." + e.data);
                            });
                        }, function (e) {
                            update();
                            Messages.error("Failure", "Image failed to get." + e.data);
                        })

                    } else {
                        update();
                        Messages.send("Container commit failed", $routeParams.id);
                    }

                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to commit." + e.data);
                });
            };

            $scope.commit = function () {
                ViewSpinner.spin();
                ContainerCommit.commit({id: $routeParams.id, repo: $scope.container.Config.Image}, function (d) {
                    update();
                    Messages.send("Container commited", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to commit." + e.data);
                });
            };
            $scope.pause = function () {
                ViewSpinner.spin();
                Container.pause({id: $routeParams.id}, function (d) {
                    update();
                    Messages.send("Container paused", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to pause." + e.data);
                });
            };

            $scope.unpause = function () {
                ViewSpinner.spin();
                Container.unpause({id: $routeParams.id}, function (d) {
                    update();
                    Messages.send("Container unpaused", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to unpause." + e.data);
                });
            };

            $scope.remove = function () {
                ViewSpinner.spin();
                Container.remove({id: $routeParams.id}, function (d) {
                    update();
                    $location.path('/containers');
                    Messages.send("Container removed", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to remove." + e.data);
                });
            };

            $scope.restart = function () {
                ViewSpinner.spin();
                Container.restart({id: $routeParams.id}, function (d) {
                    update();
                    Messages.send("Container restarted", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to restart." + e.data);
                });
            };

            $scope.hasContent = function (data) {
                return data !== null && data !== undefined;
            };

            $scope.getChanges = function () {
                ViewSpinner.spin();
                Container.changes({id: $routeParams.id}, function (d) {
                    $scope.changes = d;
                    ViewSpinner.stop();
                });
            };

            $scope.renameContainer = function () {
                // #FIXME fix me later to handle http status to show the correct error message
                Container.rename({id: $routeParams.id, 'name': $scope.container.newContainerName}, function (data) {
                    if (data.name) {
                        $scope.container.Name = data.name;
                        Messages.send("Container renamed", $routeParams.id);
                    } else {
                        $scope.container.newContainerName = $scope.container.Name;
                        Messages.error("Failure", "Container failed to rename.");
                    }
                });
                $scope.container.edit = false;
            };

            $scope.addEntry = function (array, entry) {
                array.push(entry);
            };
            $scope.rmEntry = function (array, entry) {
                var idx = array.indexOf(entry);
                array.splice(idx, 1);
            };

            $scope.toggleEdit = function() {
                $scope.edit = !$scope.edit;
            };

            update();
            $scope.getChanges();
        }]);

<|endoftext|>


<commit_before>// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// @ts-nocheck
// TODO(crbug.com/1011811): Enable TypeScript compiler checks

import * as Common from '../common/common.js';
import * as SDK from '../sdk/sdk.js';
import * as UI from '../ui/ui.js';

import {NetworkGroupNode} from './NetworkDataGridNode.js';
import {GroupLookupInterface, NetworkLogView} from './NetworkLogView.js';  // eslint-disable-line no-unused-vars

/**
 * @implements {GroupLookupInterface}
 */
export class NetworkFrameGrouper {
  /**
   * @param {!NetworkLogView} parentView
   */
  constructor(parentView) {
    this._parentView = parentView;
    /** @type {!Map<!SDK.ResourceTreeModel.ResourceTreeFrame, !FrameGroupNode>} */
    this._activeGroups = new Map();
  }

  /**
   * @override
   * @param {!SDK.NetworkRequest.NetworkRequest} request
   * @return {?NetworkGroupNode}
   */
  groupNodeForRequest(request) {
    const frame = SDK.ResourceTreeModel.ResourceTreeModel.frameForRequest(request);
    if (!frame || frame.isTopFrame()) {
      return null;
    }
    let groupNode = this._activeGroups.get(frame);
    if (groupNode) {
      return groupNode;
    }
    groupNode = new FrameGroupNode(this._parentView, frame);
    this._activeGroups.set(frame, groupNode);
    return groupNode;
  }

  /**
   * @override
   */
  reset() {
    this._activeGroups.clear();
  }
}

export class FrameGroupNode extends NetworkGroupNode {
  /**
   * @param {!NetworkLogView} parentView
   * @param {!SDK.ResourceTreeModel.ResourceTreeFrame} frame
   */
  constructor(parentView, frame) {
    super(parentView);
    this._frame = frame;
  }

  /**
   * @override
   */
  displayName() {
    return new Common.ParsedURL.ParsedURL(this._frame.url).domain() || this._frame.name || '<iframe>';
  }

  /**
   * @override
   * @param {!Element} cell
   * @param {string} columnId
   */
  renderCell(cell, columnId) {
    super.renderCell(cell, columnId);
    const columnIndex = this.dataGrid.indexOfVisibleColumn(columnId);
    if (columnIndex === 0) {
      const name = this.displayName();
      cell.appendChild(UI.Icon.Icon.create('largeicon-navigator-frame', 'network-frame-group-icon'));
      cell.createTextChild(name);
      cell.title = name;
      this.setCellAccessibleName(cell.textContent, cell, columnId);
    }
  }
}
<commit_msg>[ts] Type-check network/NetworkFrameGrouper.js with TypeScript<commit_after>// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import * as Common from '../common/common.js';
import * as DataGrid from '../data_grid/data_grid.js';  // eslint-disable-line no-unused-vars
import * as SDK from '../sdk/sdk.js';
import * as UI from '../ui/ui.js';

import {NetworkGroupNode} from './NetworkDataGridNode.js';
import {GroupLookupInterface, NetworkLogView} from './NetworkLogView.js';  // eslint-disable-line no-unused-vars

/**
 * @implements {GroupLookupInterface}
 */
export class NetworkFrameGrouper {
  /**
   * @param {!NetworkLogView} parentView
   */
  constructor(parentView) {
    this._parentView = parentView;
    /** @type {!Map<!SDK.ResourceTreeModel.ResourceTreeFrame, !FrameGroupNode>} */
    this._activeGroups = new Map();
  }

  /**
   * @override
   * @param {!SDK.NetworkRequest.NetworkRequest} request
   * @return {?NetworkGroupNode}
   */
  groupNodeForRequest(request) {
    const frame = SDK.ResourceTreeModel.ResourceTreeModel.frameForRequest(request);
    if (!frame || frame.isTopFrame()) {
      return null;
    }
    let groupNode = this._activeGroups.get(frame);
    if (groupNode) {
      return groupNode;
    }
    groupNode = new FrameGroupNode(this._parentView, frame);
    this._activeGroups.set(frame, groupNode);
    return groupNode;
  }

  /**
   * @override
   */
  reset() {
    this._activeGroups.clear();
  }
}

export class FrameGroupNode extends NetworkGroupNode {
  /**
   * @param {!NetworkLogView} parentView
   * @param {!SDK.ResourceTreeModel.ResourceTreeFrame} frame
   */
  constructor(parentView, frame) {
    super(parentView);
    this._frame = frame;
  }

  /**
   * @override
   */
  displayName() {
    return new Common.ParsedURL.ParsedURL(this._frame.url).domain() || this._frame.name || '<iframe>';
  }

  /**
   * @override
   * @param {!Element} cell
   * @param {string} columnId
   */
  renderCell(/** @type {!HTMLElement} */ cell, columnId) {
    super.renderCell(cell, columnId);
    const columnIndex =
        /** @type {!DataGrid.DataGrid.DataGridImpl<?>} */ (this.dataGrid).indexOfVisibleColumn(columnId);
    if (columnIndex === 0) {
      const name = this.displayName();
      cell.appendChild(UI.Icon.Icon.create('largeicon-navigator-frame', 'network-frame-group-icon'));
      cell.createTextChild(name);
      cell.title = name;
      this.setCellAccessibleName(cell.textContent || '', cell, columnId);
    }
  }
}
<|endoftext|>


<commit_before>angular.module('uiForDocker')
  .controller('DashCtrl', DashCtrl);

DashCtrl.$inject = ['$scope', '$http', '$route', '$location', 'containerApi', 'imageApi', 'networkApi', 'volumeApi', 'dockerApi'];

function DashCtrl($scope, $http, $route, $location, containerApi, imageApi, networkApi, volumeApi, dockerApi) {
  $scope.imagesSize = 0;
  $scope.imageLabels = ["Used", "Available"];
  $scope.imageData = [];
  $scope.height_chart = window.innerHeight * 0.3;
  $scope.options = {
    legend: {
      display: true,
      position: "bottom"
    }
  };
  $scope.containerColours = ['#42B185', '#6BC3ED', '#ED956B'];
  $scope.imageColours = ['#ED956B', '#42B185'];

  $scope.netLabels = [];

  $scope.netData = [];

  dockerApi.getInfo().then(function(res) {
    $scope.running = res.data.info.ContainersRunning;
    $scope.stopped = res.data.info.ContainersStopped;
    $scope.paused = res.data.info.ContainersPaused;
    $scope.images = res.data.info.Images;
    $scope.cpus = res.data.info.NCPU;
    $scope.architecture = res.data.info.Architecture;
    $scope.os = res.data.info.OSType;
    $scope.memTotal = (res.data.info.MemTotal.toFixed(1) / 1000000000).toString().substring(0, 6);
    $scope.serverVersion = res.data.info.ServerVersion;

    $scope.containerLabels = ["Running", "Paused", "Stopped"];
    $scope.containerData = [$scope.running, $scope.paused, $scope.stopped];
    $scope.imageData[1] = $scope.memTotal;

  }, function(error) {});

  imageApi.getAll().then(function(response) {
    var size = 0;
    response.data.images.forEach(function(image) {
      var size = image.VirtualSize;
      var sizeMegabytes = size;
      $scope.imagesSize += Math.round(sizeMegabytes.toString());
    });
    $scope.imagesSize = ($scope.imagesSize.toFixed(1) / 1000000000).toString().substring(0, 6);
    $scope.imageData[0] = $scope.imagesSize;
  }, function(error) {});

  networkApi.getAll().then(function(res) {
    $scope.networks = res.data.networks;
    for (var i = 0; i < $scope.networks.length; i++) {
      $scope.networks[i].Name = $scope.networks[i].Name.substring(0, 12);
      $scope.netLabels.push($scope.networks[i].Name);
      let size = parseInt(Object.keys($scope.networks[i].Containers).length);
      $scope.netData.push(size);
    }
  }, function(error) {});

  volumeApi.getAll().then(function(res) {
    $scope.volumes = res.data.volumes.Volumes;
  }, function(error) {});
}
<commit_msg>fixed free space bug<commit_after>angular.module('uiForDocker')
  .controller('DashCtrl', DashCtrl);

DashCtrl.$inject = ['$scope', '$http', '$route', '$location', 'containerApi', 'imageApi', 'networkApi', 'volumeApi', 'dockerApi'];

function DashCtrl($scope, $http, $route, $location, containerApi, imageApi, networkApi, volumeApi, dockerApi) {
  $scope.imagesSize = 0;
  $scope.imageLabels = ["Used", "Available"];
  $scope.imageData = [];
  $scope.height_chart = window.innerHeight * 0.3;
  $scope.options = {
    legend: {
      display: true,
      position: "bottom"
    }
  };
  $scope.containerColours = ['#42B185', '#6BC3ED', '#ED956B'];
  $scope.imageColours = ['#ED956B', '#42B185'];

  $scope.netLabels = [];

  $scope.netData = [];

  dockerApi.getInfo().then(function(res) {
    $scope.running = res.data.info.ContainersRunning;
    $scope.stopped = res.data.info.ContainersStopped;
    $scope.paused = res.data.info.ContainersPaused;
    $scope.images = res.data.info.Images;
    $scope.cpus = res.data.info.NCPU;
    $scope.architecture = res.data.info.Architecture;
    $scope.os = res.data.info.OSType;
    $scope.memTotal = (res.data.info.MemTotal.toFixed(1) / 1000000000).toString().substring(0, 6);
    $scope.serverVersion = res.data.info.ServerVersion;

    $scope.containerLabels = ["Running", "Paused", "Stopped"];
    $scope.containerData = [$scope.running, $scope.paused, $scope.stopped];
    $scope.imageData[1] = ($scope.memTotal - $scope.imageData[0]).toFixed(1);

  }, function(error) {});

  imageApi.getAll().then(function(response) {
    var size = 0;
    response.data.images.forEach(function(image) {
      var size = image.VirtualSize;
      var sizeMegabytes = size;
      $scope.imagesSize += Math.round(sizeMegabytes.toString());
    });
    $scope.imagesSize = ($scope.imagesSize.toFixed(1) / 1000000000).toString().substring(0, 6);
    $scope.imageData[0] = $scope.imagesSize;
  }, function(error) {});

  networkApi.getAll().then(function(res) {
    $scope.networks = res.data.networks;
    for (var i = 0; i < $scope.networks.length; i++) {
      $scope.networks[i].Name = $scope.networks[i].Name.substring(0, 12);
      $scope.netLabels.push($scope.networks[i].Name);
      let size = parseInt(Object.keys($scope.networks[i].Containers).length);
      $scope.netData.push(size);
    }
  }, function(error) {});

  volumeApi.getAll().then(function(res) {
    $scope.volumes = res.data.volumes.Volumes;
  }, function(error) {});
}
<|endoftext|>


<commit_before>
const util = require('util')

function ChatServiceError (code, ...args) {
  this.name = 'ChatServiceError'
  this.code = code
  this.args = args
}

util.inherits(ChatServiceError, Error)

/**
 * @constant
 * @default
 * @memberof rpc.datatypes
 */
const codesToFormat = {
  badArgument: 'Bad argument at position %d, value %j',
  invalidName: 'String %s contains invalid characters',
  invalidSocket: 'Socket %s is not connected',
  noCommand: 'No such command %s',
  noList: 'No such list %s',
  noLogin: 'No login provided',
  noRoom: 'No such room %s',
  noSocket: 'Command %s requires a valid socket',
  noUser: 'No such user %s',
  noUserOnline: 'No such user online %s',
  notAllowed: 'Action is not allowed',
  notJoined: 'Not joined to room %s',
  roomExists: 'Room %s already exists',
  timeout: 'Server operation timeout',
  userExists: 'User %s already exists',
  userOnline: 'User %s is online',
  wrongArgumentsCount: 'Expected %s arguments, got %s'
}

ChatServiceError.prototype.codesToFormat = codesToFormat

ChatServiceError.prototype.toString = function () {
  let str = this.codesToFormat[this.code]
  if (str) {
    return util.format(`ChatServiceError: ${str}`, ...this.args)
  } else {
    return Error.prototype.toString.call(this)
  }
}

module.exports = ChatServiceError
<commit_msg>style: variable name<commit_after>
const util = require('util')

function ChatServiceError (code, ...args) {
  this.name = 'ChatServiceError'
  this.code = code
  this.args = args
}

util.inherits(ChatServiceError, Error)

/**
 * @constant
 * @default
 * @memberof rpc.datatypes
 */
const codeToFormat = {
  badArgument: 'Bad argument at position %d, value %j',
  invalidName: 'String %s contains invalid characters',
  invalidSocket: 'Socket %s is not connected',
  noCommand: 'No such command %s',
  noList: 'No such list %s',
  noLogin: 'No login provided',
  noRoom: 'No such room %s',
  noSocket: 'Command %s requires a valid socket',
  noUser: 'No such user %s',
  noUserOnline: 'No such user online %s',
  notAllowed: 'Action is not allowed',
  notJoined: 'Not joined to room %s',
  roomExists: 'Room %s already exists',
  timeout: 'Server operation timeout',
  userExists: 'User %s already exists',
  userOnline: 'User %s is online',
  wrongArgumentsCount: 'Expected %s arguments, got %s'
}

ChatServiceError.prototype.codeToFormat = codeToFormat

ChatServiceError.prototype.toString = function () {
  let str = this.codeToFormat[this.code]
  if (str) {
    return util.format(`ChatServiceError: ${str}`, ...this.args)
  } else {
    return Error.prototype.toString.call(this)
  }
}

module.exports = ChatServiceError
<|endoftext|>


<commit_before>import React from 'react'
import Modal from 'app/components/modal'
import i18n from 'app/utils/i18n'

const Add = React.createClass({
  handleAdd(){
    const title=this.refs.title.value
    const description=this.refs.description.value
    this.props.onAdd(title, description)
  },
  render(){
    const props = this.props

    return (
      <Modal>

{i18n("Add Issue")}

              {i18n("Title")}
              <input type="text" ref="title" placeholder={i18n("Short issue description")}/>

              {i18n("Description")}
              <textarea ref="description" placeholder={i18n("Short issue description")}></textarea>

            <button className="ui button yellow" onClick={this.handleAdd}>
            {i18n("Add Issue")}
            </button>

      </Modal>
    )
  }
})

export default Add
<commit_msg>Fix #106. Fix modal consistency at issues add.<commit_after>import React from 'react'
import Modal from 'app/components/modal'
import i18n from 'app/utils/i18n'

const Add = React.createClass({
  handleAdd(){
    const title=this.refs.title.value
    const description=this.refs.description.value
    this.props.onAdd(title, description)
  },
  render(){
    const props = this.props

    return (
      <Modal className="wide">

{i18n("Add Issue")}

              {i18n("Title")}
              <input type="text" ref="title" placeholder={i18n("Short issue description")}/>

              {i18n("Description")}
              <textarea ref="description" placeholder={i18n("Short issue description")}></textarea>

            <button className="ui button yellow" onClick={this.handleAdd}>
            {i18n("Add Issue")}
            </button>

      </Modal>
    )
  }
})

export default Add
<|endoftext|>


<commit_before>
/**
 * Copyright (c) 2016, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 */

import React, { Component } from 'react'

import logoSrc from './images/T-logo-dark-512x512.png';

export default class UploaderButton extends Component {
  static propTypes = {
    buttonUrl: React.PropTypes.string.isRequired,
    onClick: React.PropTypes.func,
    buttonText: React.PropTypes.string.isRequired
  };

  constructor(props) {
    super(props);
  }

  render() {
    return (

            {this.props.buttonText}

    );
  }
}
<commit_msg>Convert UploaderButton to functional component<commit_after>
/**
 * Copyright (c) 2016, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 */

import React, { Component } from 'react'

import logoSrc from './images/T-logo-dark-512x512.png';

const UploaderButton = (props) => {
  return (

          {props.buttonText}

  );
}

UploaderButton.propTypes = {
  buttonUrl: React.PropTypes.string.isRequired,
  onClick: React.PropTypes.func,
  buttonText: React.PropTypes.string.isRequired
};

export default UploaderButton;
<|endoftext|>