<commit_before>import {BibFieldTypes, BibTypes} from "biblatex-csl-converter"
import {BibFieldTitles, BibTypeTitles, BibFieldHelp} from "./strings"
import {bibDialog} from "./templates"
import {addAlert, noSpaceTmp} from "../../common"
import {EntryCatForm} from "./entry_cat"
import {DateFieldForm} from "./fields/date"
import {LiteralFieldForm} from "./fields/literal"
import {LiteralLongFieldForm} from "./fields/literal_long"
import {LiteralListForm} from "./fields/literal_list"
import {TitleFieldForm} from "./fields/title"
import {NameListForm} from "./fields/name_list"
import {RangeListForm} from "./fields/range_list"
import {URIFieldForm} from "./fields/uri"
import {VerbatimFieldForm} from "./fields/verbatim"
import {TagListForm} from "./fields/tag_list"
import {KeyFieldForm} from "./fields/key"
import {KeyListForm} from "./fields/key_list"
import {nameToText} from "../tools"

const FIELD_FORMS = {
    'f_date': DateFieldForm,
    'f_integer': LiteralFieldForm,
    'f_literal': LiteralFieldForm,
    'l_literal': LiteralListForm,
    'f_long_literal': LiteralLongFieldForm,
    'f_key': KeyFieldForm,
    'l_key': KeyListForm,
    'l_name': NameListForm,
    'l_range': RangeListForm,
    'l_tag': TagListForm,
    'f_title': TitleFieldForm,
    'f_uri': URIFieldForm,
    'f_verbatim': VerbatimFieldForm
}

export class BibEntryForm {
    constructor(bibDB, itemId = false) {
        this.bibDB = bibDB
        this.itemId = itemId
        this.fields = {}
        this.currentValues = {}
    }

    init() {
        if (this.itemId) {
            this.dialogHeader = gettext('Edit Source')
            let bibEntry = this.bibDB.db[this.itemId]
            this.currentValues = JSON.parse(JSON.stringify(bibEntry)) // copy current values
        } else {
            this.dialogHeader = gettext('Register New Source')
            this.currentValues = {
                bib_type: false,
                entry_cat: [],
                entry_key: 'FidusWriter',
                fields: {}
            }
        }
        return this.createForm()
    }

    addDialogToDOM() {
        let that = this
        // Add form to DOM
        let dialogEl = bibDialog({
            'dialogHeader': this.dialogHeader,
            'bib_type': this.currentValues.bib_type,
            BibTypes,
            BibTypeTitles
        })
        document.body.insertAdjacentHTML('beforeend', bibDialog)

        let diaButtons = {
            cancel: {
                class: "fw-button fw-orange",
                text: gettext('Cancel'),
                click: function() {
                    jQuery(this).dialog('close')
                }
            },
            strong: {
                class: "fw-button fw-small fw-green fw-left fw-strong fw-edit disabled",
                text: gettext('Strong'),
                click: () => {}
            },
            em: {
                class: "fw-button fw-small fw-green fw-left fw-em fw-edit disabled",
                text: gettext('Emphasis'),
                click: () => {}
            },
            smallcaps: {
                class: "fw-button fw-small fw-green fw-left fw-smallcaps fw-edit disabled",
                text: gettext('Small caps'),
                click: () => {}
            },
            sub: {
                class: "fw-button fw-small fw-green fw-left fw-sub fw-edit disabled",
                text: gettext('Subscript₊'),
                click: () => {}
            },
            sup: {
                class: "fw-button fw-small fw-green fw-left fw-sup fw-edit disabled",
                text: gettext('Supscript²'),
                click: () => {}
            },
            nocase: {
                class: "fw-button fw-small fw-green fw-left fw-nocase fw-edit disabled",
                text: gettext('CasE ProTecT'),
                click: () => {}
            }
        }

        return new Promise(resolve => {
            diaButtons.submit = {
                class: "fw-button fw-dark",
                text: gettext('Submit'),
                click: function() {
                    if (that.check()) {
                        let returnValue = that.save()
                        jQuery("#bib-dialog").dialog('close')
                        resolve(returnValue)
                    }
                }
            }

            jQuery("#bib-dialog").dialog({
                draggable: false,
                resizable: false,
                width: 940,
                height: 700,
                modal: true,
                buttons: diaButtons,
                close: () => jQuery("#bib-dialog").dialog('destroy').remove()
            })
            // init ui tabs
            jQuery('#bib-dialog-tabs').tabs()

            document.getElementById('select-bibtype').addEventListener(
                'change',
                () => resolve(this.changeBibType())
            )
        })
    }

    addField(fieldName, dom) {
        let fieldType = BibFieldTypes[fieldName]
        let fieldTitle
        if (BibFieldHelp[fieldName]) {
            fieldTitle = noSpaceTmp`

                    ${BibFieldTitles[fieldName]}
                    ${BibFieldHelp[fieldName]}

            `
        } else {
            fieldTitle = noSpaceTmp`

                    ${BibFieldTitles[fieldName]}

            `
        }

        dom.insertAdjacentHTML(
            'beforeend',
            noSpaceTmp`

                    ${fieldTitle}

`
        )
        let fieldDOM = dom.lastChild.lastChild
        let FieldClass = FIELD_FORMS[fieldType.type]
        if (FieldClass) {
            let fieldHandler = new FieldClass(fieldDOM, this.currentValues.fields[fieldName], undefined, fieldType)
            fieldHandler.init()
            this.fields[fieldName] = fieldHandler
        } else {
            console.warn(`Unknown fieldtype: ${fieldType.type}`)
        }
    }

    createForm() {
        let dialogPromise = this.addDialogToDOM()
        if (this.currentValues.bib_type !== false) {
            let eitherOrFields = document.getElementById('eo-fields')
            BibTypes[this.currentValues.bib_type].eitheror.forEach(fieldName => {
                this.addField(fieldName, eitherOrFields)
            })
            let reqFields = document.getElementById('req-fields')
            BibTypes[this.currentValues.bib_type].required.forEach(fieldName => {
                this.addField(fieldName, reqFields)
            })
            let optFields = document.getElementById('opt-fields')
            BibTypes[this.currentValues.bib_type].optional.forEach(fieldName => {
                this.addField(fieldName, optFields)
            })
            let entryCatField = document.getElementById('categories-field')
            this.entryCatForm = new EntryCatForm(entryCatField, this.currentValues.entry_cat, this.bibDB.cats)
            this.entryCatForm.init()

            if (!this.bibDB.cats.length) {
                // There are no ctaegories to select from, so remove the categories tab.
                [].slice.call(document.querySelectorAll('#categories-tab, #categories-link')).forEach(
                    el => el.parentElement.removeChild(el)
                )
            }
        }
        return dialogPromise
    }

    changeBibType() {
        // Add all current values into temporary currentValues, in case the
        // user still wants them.
        let formValue = this.value
        Object.assign(this.currentValues.fields, formValue.fields)
        this.currentValues.entry_cat = formValue.entry_cat
        this.currentValues.bib_type = formValue.bib_type
        // Reset fields and close dialog.
        this.fields = {}
        jQuery('#bib-dialog').dialog('close')
        return this.createForm()
    }

    createEntryKey(bibItem) {
        // We attempt to create a biblatex compatible entry key if there is no entry
        // key so far.
        let entryKey = ''
        if (bibItem.fields.author) {
            entryKey += nameToText(bibItem.fields.author).replace(/\s|,|=|;|:|{|}/g,'')
        } else if (bibItem.fields.editor) {
            entryKey += nameToText(bibItem.fields.editor).replace(/\s|,|=|;|:|{|}/g,'')
        }
        if (bibItem.fields.date) {
            entryKey += bibItem.fields.date.split('/')[0].replace(/\?|\*|u|\~|-/g,'')
        }
        if (entryKey.length) {
            bibItem.entry_key = entryKey
        }
    }

    get value() {
        let that = this
        let returnObj = {
            bib_type: document.querySelector('#select-bibtype').value,
            entry_cat: this.entryCatForm ? this.entryCatForm.value : [],
            entry_key: this.currentValues.entry_key, // is never updated.
            fields: {}
        }
        Object.keys(this.fields).forEach(fieldName=>{
            let fieldValue = that.fields[fieldName].value
            if (fieldValue !== false) {
                returnObj['fields'][fieldName] = fieldValue
            }
        })
        return returnObj
    }

    save() {
        let isNew = this.itemId===false ? true : false
        let itemId = this.itemId===false ? 0 : this.itemId
        let saveObj = {}
        saveObj[itemId] = this.value

        if (saveObj[itemId].entry_key==='FidusWriter') {
            this.createEntryKey(saveObj[itemId])
        }
        return this.bibDB.saveBibEntries(
            saveObj,
            isNew
        )
    }

    check() {
        let that = this, passed = true
        if (!this.currentValues.bib_type) {
            return false
        }
        Object.keys(this.fields).forEach(fieldName=>{
            if(that.fields[fieldName].check() !== true) {
                passed = false
            }
        })
        if (!passed) {
            addAlert('error', gettext('Error in form, check highlighted values!'))
        }
        return passed
    }

}
<commit_msg>fix citationdialog display<commit_after>import {BibFieldTypes, BibTypes} from "biblatex-csl-converter"
import {BibFieldTitles, BibTypeTitles, BibFieldHelp} from "./strings"
import {bibDialog} from "./templates"
import {addAlert, noSpaceTmp} from "../../common"
import {EntryCatForm} from "./entry_cat"
import {DateFieldForm} from "./fields/date"
import {LiteralFieldForm} from "./fields/literal"
import {LiteralLongFieldForm} from "./fields/literal_long"
import {LiteralListForm} from "./fields/literal_list"
import {TitleFieldForm} from "./fields/title"
import {NameListForm} from "./fields/name_list"
import {RangeListForm} from "./fields/range_list"
import {URIFieldForm} from "./fields/uri"
import {VerbatimFieldForm} from "./fields/verbatim"
import {TagListForm} from "./fields/tag_list"
import {KeyFieldForm} from "./fields/key"
import {KeyListForm} from "./fields/key_list"
import {nameToText} from "../tools"

const FIELD_FORMS = {
    'f_date': DateFieldForm,
    'f_integer': LiteralFieldForm,
    'f_literal': LiteralFieldForm,
    'l_literal': LiteralListForm,
    'f_long_literal': LiteralLongFieldForm,
    'f_key': KeyFieldForm,
    'l_key': KeyListForm,
    'l_name': NameListForm,
    'l_range': RangeListForm,
    'l_tag': TagListForm,
    'f_title': TitleFieldForm,
    'f_uri': URIFieldForm,
    'f_verbatim': VerbatimFieldForm
}

export class BibEntryForm {
    constructor(bibDB, itemId = false) {
        this.bibDB = bibDB
        this.itemId = itemId
        this.fields = {}
        this.currentValues = {}
    }

    init() {
        if (this.itemId) {
            this.dialogHeader = gettext('Edit Source')
            let bibEntry = this.bibDB.db[this.itemId]
            this.currentValues = JSON.parse(JSON.stringify(bibEntry)) // copy current values
        } else {
            this.dialogHeader = gettext('Register New Source')
            this.currentValues = {
                bib_type: false,
                entry_cat: [],
                entry_key: 'FidusWriter',
                fields: {}
            }
        }
        return this.createForm()
    }

    addDialogToDOM() {
        let that = this
        // Add form to DOM
        let dialogHTML = bibDialog({
            'dialogHeader': this.dialogHeader,
            'bib_type': this.currentValues.bib_type,
            BibTypes,
            BibTypeTitles
        })

        document.body.insertAdjacentHTML('beforeend', dialogHTML)

        let diaButtons = {
            cancel: {
                class: "fw-button fw-orange",
                text: gettext('Cancel'),
                click: function() {
                    jQuery(this).dialog('close')
                }
            },
            strong: {
                class: "fw-button fw-small fw-green fw-left fw-strong fw-edit disabled",
                text: gettext('Strong'),
                click: () => {}
            },
            em: {
                class: "fw-button fw-small fw-green fw-left fw-em fw-edit disabled",
                text: gettext('Emphasis'),
                click: () => {}
            },
            smallcaps: {
                class: "fw-button fw-small fw-green fw-left fw-smallcaps fw-edit disabled",
                text: gettext('Small caps'),
                click: () => {}
            },
            sub: {
                class: "fw-button fw-small fw-green fw-left fw-sub fw-edit disabled",
                text: gettext('Subscript₊'),
                click: () => {}
            },
            sup: {
                class: "fw-button fw-small fw-green fw-left fw-sup fw-edit disabled",
                text: gettext('Supscript²'),
                click: () => {}
            },
            nocase: {
                class: "fw-button fw-small fw-green fw-left fw-nocase fw-edit disabled",
                text: gettext('CasE ProTecT'),
                click: () => {}
            }
        }

        return new Promise(resolve => {
            diaButtons.submit = {
                class: "fw-button fw-dark",
                text: gettext('Submit'),
                click: function() {
                    if (that.check()) {
                        let returnValue = that.save()
                        jQuery("#bib-dialog").dialog('close')
                        resolve(returnValue)
                    }
                }
            }

            jQuery("#bib-dialog").dialog({
                draggable: false,
                resizable: false,
                width: 940,
                height: 700,
                modal: true,
                buttons: diaButtons,
                close: () => jQuery("#bib-dialog").dialog('destroy').remove()
            })
            // init ui tabs
            jQuery('#bib-dialog-tabs').tabs()

            document.getElementById('select-bibtype').addEventListener(
                'change',
                () => resolve(this.changeBibType())
            )
        })
    }

    addField(fieldName, dom) {
        let fieldType = BibFieldTypes[fieldName]
        let fieldTitle
        if (BibFieldHelp[fieldName]) {
            fieldTitle = noSpaceTmp`

                    ${BibFieldTitles[fieldName]}
                    ${BibFieldHelp[fieldName]}

            `
        } else {
            fieldTitle = noSpaceTmp`

                    ${BibFieldTitles[fieldName]}

            `
        }

        dom.insertAdjacentHTML(
            'beforeend',
            noSpaceTmp`

                    ${fieldTitle}

`
        )
        let fieldDOM = dom.lastChild.lastChild
        let FieldClass = FIELD_FORMS[fieldType.type]
        if (FieldClass) {
            let fieldHandler = new FieldClass(fieldDOM, this.currentValues.fields[fieldName], undefined, fieldType)
            fieldHandler.init()
            this.fields[fieldName] = fieldHandler
        } else {
            console.warn(`Unknown fieldtype: ${fieldType.type}`)
        }
    }

    createForm() {
        let dialogPromise = this.addDialogToDOM()
        if (this.currentValues.bib_type !== false) {
            let eitherOrFields = document.getElementById('eo-fields')
            BibTypes[this.currentValues.bib_type].eitheror.forEach(fieldName => {
                this.addField(fieldName, eitherOrFields)
            })
            let reqFields = document.getElementById('req-fields')
            BibTypes[this.currentValues.bib_type].required.forEach(fieldName => {
                this.addField(fieldName, reqFields)
            })
            let optFields = document.getElementById('opt-fields')
            BibTypes[this.currentValues.bib_type].optional.forEach(fieldName => {
                this.addField(fieldName, optFields)
            })
            let entryCatField = document.getElementById('categories-field')
            this.entryCatForm = new EntryCatForm(entryCatField, this.currentValues.entry_cat, this.bibDB.cats)
            this.entryCatForm.init()

            if (!this.bibDB.cats.length) {
                // There are no ctaegories to select from, so remove the categories tab.
                [].slice.call(document.querySelectorAll('#categories-tab, #categories-link')).forEach(
                    el => el.parentElement.removeChild(el)
                )
            }
        }
        return dialogPromise
    }

    changeBibType() {
        // Add all current values into temporary currentValues, in case the
        // user still wants them.
        let formValue = this.value
        Object.assign(this.currentValues.fields, formValue.fields)
        this.currentValues.entry_cat = formValue.entry_cat
        this.currentValues.bib_type = formValue.bib_type
        // Reset fields and close dialog.
        this.fields = {}
        jQuery('#bib-dialog').dialog('close')
        return this.createForm()
    }

    createEntryKey(bibItem) {
        // We attempt to create a biblatex compatible entry key if there is no entry
        // key so far.
        let entryKey = ''
        if (bibItem.fields.author) {
            entryKey += nameToText(bibItem.fields.author).replace(/\s|,|=|;|:|{|}/g,'')
        } else if (bibItem.fields.editor) {
            entryKey += nameToText(bibItem.fields.editor).replace(/\s|,|=|;|:|{|}/g,'')
        }
        if (bibItem.fields.date) {
            entryKey += bibItem.fields.date.split('/')[0].replace(/\?|\*|u|\~|-/g,'')
        }
        if (entryKey.length) {
            bibItem.entry_key = entryKey
        }
    }

    get value() {
        let that = this
        let returnObj = {
            bib_type: document.querySelector('#select-bibtype').value,
            entry_cat: this.entryCatForm ? this.entryCatForm.value : [],
            entry_key: this.currentValues.entry_key, // is never updated.
            fields: {}
        }
        Object.keys(this.fields).forEach(fieldName=>{
            let fieldValue = that.fields[fieldName].value
            if (fieldValue !== false) {
                returnObj['fields'][fieldName] = fieldValue
            }
        })
        return returnObj
    }

    save() {
        let isNew = this.itemId===false ? true : false
        let itemId = this.itemId===false ? 0 : this.itemId
        let saveObj = {}
        saveObj[itemId] = this.value

        if (saveObj[itemId].entry_key==='FidusWriter') {
            this.createEntryKey(saveObj[itemId])
        }
        return this.bibDB.saveBibEntries(
            saveObj,
            isNew
        )
    }

    check() {
        let that = this, passed = true
        if (!this.currentValues.bib_type) {
            return false
        }
        Object.keys(this.fields).forEach(fieldName=>{
            if(that.fields[fieldName].check() !== true) {
                passed = false
            }
        })
        if (!passed) {
            addAlert('error', gettext('Error in form, check highlighted values!'))
        }
        return passed
    }

}
<|endoftext|>


<commit_before>var TabPaneItem = require('../../../../../javascripts/cartodb/components-3.0/tab-pane/item/view');
var TabPaneModel = require('../../../../../javascripts/cartodb/components-3.0/tab-pane/model');
var cdb = require('cartodb.js');

describe('components-3.0/model', function() {
  beforeEach(function() {
  });
});
<commit_msg>removes unused spec<commit_after><|endoftext|>


<commit_before>import React from "react";
import logo from "./logo.svg";
import "./App.css";
import pptxgen from "./pptxgen.es.js"; // LOCAL DEV TESTING src=`PptxGenJS/dist`
//import pptxgen from "pptxgenjs"; // react-app webpack will use package.json `"module": "dist/pptxgen.es.js"` value

function App() {
	const demoCode = `import pptxgen from "pptxgenjs";
let pptx = new pptxgen();

let slide = pptx.addSlide();
slide.addText("React Demo!", { x:1, y:1, w:'80%', h:1, fontSize:36, fill:'eeeeee', align:'center' });

pptx.writeFile("react-demo.pptx");`;

	function runDemo() {
		let pptx = new pptxgen();
		let slide = pptx.addSlide();
		slide.addText("React Demo!", { x: 1, y: 1, w: "80%", h: 1, fontSize: 36, fill: "eeeeee", align: "center" });
		pptx.writeFile("react-demo.pptx");

		console.log(`pptx.version = ${pptx.version}`);
	}

	return (

					PptxGenJS

				<button
					className="navbar-toggler"
					type="button"
					data-toggle="collapse"
					data-target="#navbarColor01"
					aria-controls="navbarColor01"
					aria-expanded="false"
					aria-label="Toggle navigation"
				>

				</button>

								Home (current)

					<form className="form-inline my-2 my-lg-0">
						<button
							type="button"
							className="btn btn-outline-info mx-3 my-2 my-sm-0"
							onClick={ev => {
								window.open("https://gitbrent.github.io/PptxGenJS/demo/", true);
							}}
						>
							Demo Page
						</button>
						<button
							type="button"
							className="btn btn-outline-info mx-3 my-2 my-sm-0"
							onClick={ev => {
								window.open("https://github.com/gitbrent/PptxGenJS", true);
							}}
						>
							GitHub Project
						</button>

						<button
							type="button"
							className="btn btn-outline-info mx-3 my-2 my-sm-0"
							onClick={ev => {
								window.open("https://gitbrent.github.io/PptxGenJS/docs/installation.html", true);
							}}
						>
							API Docs
						</button>
					</form>

React Demo

Sample React application to demonstrate using the PptxGenJS library as a module.

Demo Code

						{demoCode}

					<button type="button" className="btn btn-success w-25" onClick={ev => runDemo()}>
						Run Demo
					</button>

	);
}

export default App;
<commit_msg>updated export file name<commit_after>import React from "react";
import logo from "./logo.svg";
import "./App.css";
import pptxgen from "./pptxgen.es.js"; // LOCAL DEV TESTING src=`PptxGenJS/dist`
//import pptxgen from "pptxgenjs"; // react-app webpack will use package.json `"module": "dist/pptxgen.es.js"` value

function App() {
	const demoCode = `import pptxgen from "pptxgenjs";
let pptx = new pptxgen();

let slide = pptx.addSlide();
slide.addText("React Demo!", { x:1, y:1, w:'80%', h:1, fontSize:36, fill:'eeeeee', align:'center' });

pptx.writeFile("react-demo.pptx");`;

	function runDemo() {
		let pptx = new pptxgen();
		let slide = pptx.addSlide();
		slide.addText("React Demo!", { x: 1, y: 1, w: "80%", h: 1, fontSize: 36, fill: "eeeeee", align: "center" });
		pptx.writeFile("pptxgenjs-demo-react.pptx");

		console.log(`pptx.version = ${pptx.version}`);
	}

	return (

					PptxGenJS

				<button
					className="navbar-toggler"
					type="button"
					data-toggle="collapse"
					data-target="#navbarColor01"
					aria-controls="navbarColor01"
					aria-expanded="false"
					aria-label="Toggle navigation"
				>

				</button>

								Home (current)

					<form className="form-inline my-2 my-lg-0">
						<button
							type="button"
							className="btn btn-outline-info mx-3 my-2 my-sm-0"
							onClick={ev => {
								window.open("https://gitbrent.github.io/PptxGenJS/demo/", true);
							}}
						>
							Demo Page
						</button>
						<button
							type="button"
							className="btn btn-outline-info mx-3 my-2 my-sm-0"
							onClick={ev => {
								window.open("https://github.com/gitbrent/PptxGenJS", true);
							}}
						>
							GitHub Project
						</button>

						<button
							type="button"
							className="btn btn-outline-info mx-3 my-2 my-sm-0"
							onClick={ev => {
								window.open("https://gitbrent.github.io/PptxGenJS/docs/installation.html", true);
							}}
						>
							API Docs
						</button>
					</form>

React Demo

Sample React application to demonstrate using the PptxGenJS library as a module.

Demo Code

						{demoCode}

					<button type="button" className="btn btn-success w-25" onClick={ev => runDemo()}>
						Run Demo
					</button>

	);
}

export default App;
<|endoftext|>


<commit_before>(new function($R){

 var files = {};

 function makeSourceURL (url, type) {
   var s = '';
   if (DEBUG && url) {
     s = !!type ? ('/*# sourceURL='+url+' */') : ('//# sourceURL='+url+' ');
   }
   return s;
 }

 function once (url, callback, loader)
  {
   if(files[url] == null || !files[url].status)
    {
     loader(url, function(err, resp){
      if (err) files[url].status = 0;
      else
       {
        files[url].content = resp || null;
        files[url].status = 2;
        while(files[url].callbacks.length)
         {
          files[url].callbacks.pop()(files[url].content);
         }
       }
     });
    }
   if(files[url] == null)
    {
     files[url] = {
      status: 1,
      content: null,
      callbacks: []
     };
    }
   if(typeof callback == FUNCTION)
    {
     if(files[url].status == 2) callback(files[url].content);
     else files[url].callbacks.push(callback);
    }
  }

 function makeQueryString (o)
  {
   var a = arguments, r = [];
   var n = (typeof a[1] == STRING) ? (a[1] + '[%s]') : '%s';
   for (var i in o)
    {
     if (typeof o[i] == OBJECT && o[i] != null) r.push(makeQueryString(o[i], n.replace('%s', i)));
     else r.push(n.replace('%s', i) + '=' + encodeURIComponent(o[i]));
    }
   return r.join('&');
  }

 function makeXHR(o)
  {
   var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

   xhr.hadError = !1;
   xhr.error = null;

   function getRequest () {return o;}
   xhr.getRequest = function () { return getRequest(); };

   function getResponse ()
    {
     var ok = !!(xhr.status >= 200 && xhr.status <= 399);
     var r = xhr.responseText || '';
     var type = o.url.match(/\.(js|css)$/i);
     if (type) type = type[1].toLowerCase();
     if (DEBUG && !!type)
      {
       var url = o.url;
       if (o.type == 'GET' && o.data != null)
        {
         url += (url.indexOf('?') >= 0) ? '&' : '?';
         url += makeQueryString(o.data);
        }
       r = makeSourceURL(url, type=="css") + '\n' + r;
      }
     if (!ok)
      {
       $R.log('HTTP Error '+xhr.status+': '+(xhr.statusText || xhr.error), {
        message: xhr.statusText || xhr.error,
        location: o.url,
        code: xhr.status,
        request: o
       });
       return r;
      }
     var t = xhr.getResponseHeader('Content-Type'),
         u = (o.url!=null) ? o.url : null,
         m = 'Responce transferred with Content-Type "'+t+'" but interpreted as other type';
     try { if (t.match(/json/i)) r = new Function('return ' + r)(); }
     catch (e)
      {
       $R.log('XHR responce parsing error', {
        details: m,
        message: e.message,
        location: u,
        stack: (typeof e.stack != UNDEFINED) ? e.stack : e,
        data: r,
        request: o
       });
       e.message = '['+u+'] ' + e.message + ' (' + m + ')';
       throw e;
      };
     return r;
    }
   xhr.getResponse = function () { return getResponse(); };
   return xhr;
  }

 function xhr (/* [url,] options|callback */)
  {
   var o = null, a = arguments;
   if (a[0] != null && typeof a[0] == OBJECT) o = a[0]; // (o)
   else if (a[1] != null && typeof a[1] == OBJECT) o = a[1]; // (url, o)
   else if (typeof a[0] == STRING && typeof a[1] == FUNCTION) o = {url:a[0], complete:a[1]}; // (url, callback)
   if (o == null) return false;

   var q = {};
   q.url = (typeof o.url == STRING) ? o.url : (typeof a[0] == STRING ? a[0] : location.href.replace(/#.*$/, ''));
   q.type = (typeof o.type == STRING) ? o.type : 'GET';
   q.async = (typeof o.async == BOOLEAN) ? o.async : true;
   q.contentType = (typeof o.contentType == STRING) ? o.contentType : null; // application/x-www-form-urlencoded | multipart/form-data
   q.xRequestedWith = (typeof o.xRequestedWith == STRING) ? o.xRequestedWith : null; // XMLHttpRequest
   q.data = (typeof o.data == OBJECT && o.data != null) ? o.data : null;
   q.cache = (typeof o.cache == BOOLEAN) ? o.cache : true;
   q.headers = (typeof o.headers == OBJECT && o.headers != null) ? o.headers : {};
   q.timeout = (typeof o.timeout == NUMBER) ? o.timeout : 30 * 1000;
   q.error = (typeof o.error == FUNCTION) ? o.error : function(){};
   q.success = (typeof o.success == FUNCTION) ? o.success : function(){};
   q.complete = (typeof o.complete == FUNCTION) ? o.complete : function(){};

   if (q.cache && function(){
     var query = q.data ? makeQueryString(q.data) : '',
         id = q.url + (!query ? '' : (q.url.indexOf('?') >= 0 ? '&' : '?') + query);
     var cache = getTemplate(id);
     if (typeof cache == STRING) {
       var xhr = {
         status: 302,
         statusText: 'Found',
         responseText: cache
       };
       setTimeout(function(){
         try {
           var r = q.url.match(/.+\.json$/i) ? new Function('return ' + cache)() : cache;
           q.success(r, xhr);
           q.complete(r, xhr);
         }
         catch(e) {
           $R.log('Javascript exception in cached XHR request callback execution process', {
             message: e.message,
             stack: (typeof e.stack != UNDEFINED) ? e.stack : e,
             request: q
            });
         };
       }, 0);
       return true;
     }
     return;
   }()) return;

   var xhr = makeXHR(q);

   setTimeout(function(){
    var url = q.url;
    var data = null;
    if (q.data != null && typeof q.data == OBJECT)
     {
      if (q.contentType == null)
       {
        q.contentType = 'application/x-www-form-urlencoded';
        if (q.type.toUpperCase() == 'POST') data = makeQueryString(q.data);
        else if (q.type.toUpperCase() == 'GET')
         {
          url += (url.indexOf('?') >= 0) ? '&' : '?';
          url += makeQueryString(q.data);
         }
       }
      else data = q.data;
     }

    function onError (e, fn)
     {
      xhr.hadError = !0;
      xhr.error = 'error';
      if (e != null && e.message != null) xhr.error = e.message;
      else if (e != null && e.type != null) xhr.error = e.type;
      else if (!(xhr.status >= 200 && xhr.status <= 399) && xhr.status > 0) xhr.error = xhr.statusText;
      if (typeof fn == FUNCTION) fn(xhr);
     }

    var _executed = !1;
    function execCallbacks ()
     {
      if (_executed) return;
      _executed = !0;
      try {
       var request = xhr.getRequest(), response = xhr.getResponse();
       if (!xhr.hadError && xhr.status >= 200 && xhr.status <= 399) request.success(response, xhr);
       if (xhr.hadError) request.error(response, xhr);
       request.complete(response, xhr);
      }
      catch(e) {
       $R.log('Javascript exception in XHR request callback execution process', {
        message: e.message,
        stack: (typeof e.stack != UNDEFINED) ? e.stack : e,
        request: xhr
       });
       throw e;
      };
     }
    try{xhr.open(q.type, url, q.async);}
    catch(e){onError(e, execCallbacks);};
    xhr.timeout = q.timeout;
    if (q.contentType != null) xhr.setRequestHeader('Content-type', q.contentType);
    if (q.xRequestedWith != null) xhr.setRequestHeader('X-Requested-With', q.xRequestedWith);
    for (var i in q.headers) xhr.setRequestHeader(String(i), String(q.headers[i]));

    xhr.ontimeout = function(e){onError(e, execCallbacks);};
    xhr.onerror = function(e){onError(e, execCallbacks);};
    xhr.onreadystatechange = function(e)
     {
      if (xhr.readyState == 4)
       {
        if (xhr.status >= 200 && xhr.status <= 399) execCallbacks();
        else if (xhr.status > 0) onError(null, execCallbacks);
       }
     };
    try{xhr.send(data);}
    catch(e){onError(e, execCallbacks);};
   }, 0);

   return xhr;
  }

 function include (type, url, callback, skipErrors)
  {
   if (type == 'css')
    {
     var o = document.createElement('link');
     o.rel   = 'stylesheet';
     o.type  = 'text/css';
     o.media = 'all';
     o.href  = url;
    }
   else if (type == 'js')
    {
     var o  = document.createElement('script');
     o.type = 'text/javascript';
     o.src  = url;
    }
   if (typeof o != UNDEFINED)
    {
     var procCallback = function()
      {
       if(typeof callback == FUNCTION)
        {
         setTimeout(function(){
          callback();
         },0);
        }
      };
     var handler = function(e)
      {
       if(e.type == 'error' && !skipErrors)
        {
         $R.log('HTTP request error', {
          message: 'Location unavailable',
          location: url,
          source: e.target.outerHTML
         });
         //TODO: throw error
        }
       procCallback();
      };
     o.onload = handler;
     o.onerror = handler;
     setTimeout(function(){
      document.getElementsByTagName('head')[0].appendChild(o);
     }, 0);
    }
  }

 function include_once (type, url, callback, skipErrors)
  {
   once(url, callback, function(url, processor){
    include (type, url, processor, skipErrors);
   });
  }

 function require (url, callback, complete)
  {
   xhr(url, {
    success: callback,
    complete: function (r, xhr) {
      if(typeof complete == FUNCTION)
      {
       complete(!(xhr.status>=200 && xhr.status<=399), r);
      }
    }
   });
  }

 function require_once (url, callback)
  {
   once(url, callback, function(url, processor){
    require(url, null, processor);
   });
  }

 function inject (url, callback)
  {
   require_once(url, function(str){
    try
     {
      var js = new Function('$R', str);
      js($R);
      if(typeof callback == FUNCTION)
       {
        setTimeout(function(){ callback(); },0);
       }
     }
    catch(e)
     {
      $R.log('Javascript exception', {
       message: e.message,
       location: url,
       stack: (typeof e.stack != UNDEFINED) ? e.stack : e,
       source: str
      });
      e.message = '['+url+'] ' + e.message;
      throw e;
     };
   });
  }

 $R.xhr = xhr;
 $R.include = include; // Simple way for insert CSS or JS file (such as jQuery) to document
 $R.include_once = include_once;
 $R.require = require; // Require any content from same domain
 $R.require_once = require_once; // Require any content once from same domain
 $R.inject = inject; // Inject any JS file from same domain to the private $R namespace
 $R.makeSourceURL = makeSourceURL;
}($R));<commit_msg>InvalidAccessError exception<commit_after>(new function($R){

 var files = {};

 function makeSourceURL (url, type) {
   var s = '';
   if (DEBUG && url) {
     s = !!type ? ('/*# sourceURL='+url+' */') : ('//# sourceURL='+url+' ');
   }
   return s;
 }

 function once (url, callback, loader)
  {
   if(files[url] == null || !files[url].status)
    {
     loader(url, function(err, resp){
      if (err) files[url].status = 0;
      else
       {
        files[url].content = resp || null;
        files[url].status = 2;
        while(files[url].callbacks.length)
         {
          files[url].callbacks.pop()(files[url].content);
         }
       }
     });
    }
   if(files[url] == null)
    {
     files[url] = {
      status: 1,
      content: null,
      callbacks: []
     };
    }
   if(typeof callback == FUNCTION)
    {
     if(files[url].status == 2) callback(files[url].content);
     else files[url].callbacks.push(callback);
    }
  }

 function makeQueryString (o)
  {
   var a = arguments, r = [];
   var n = (typeof a[1] == STRING) ? (a[1] + '[%s]') : '%s';
   for (var i in o)
    {
     if (typeof o[i] == OBJECT && o[i] != null) r.push(makeQueryString(o[i], n.replace('%s', i)));
     else r.push(n.replace('%s', i) + '=' + encodeURIComponent(o[i]));
    }
   return r.join('&');
  }

 function makeXHR(o)
  {
   var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

   xhr.hadError = !1;
   xhr.error = null;

   function getRequest () {return o;}
   xhr.getRequest = function () { return getRequest(); };

   function getResponse ()
    {
     var ok = !!(xhr.status >= 200 && xhr.status <= 399);
     var r = xhr.responseText || '';
     var type = o.url.match(/\.(js|css)$/i);
     if (type) type = type[1].toLowerCase();
     if (DEBUG && !!type)
      {
       var url = o.url;
       if (o.type == 'GET' && o.data != null)
        {
         url += (url.indexOf('?') >= 0) ? '&' : '?';
         url += makeQueryString(o.data);
        }
       r = makeSourceURL(url, type=="css") + '\n' + r;
      }
     if (!ok)
      {
       $R.log('HTTP Error '+xhr.status+': '+(xhr.statusText || xhr.error), {
        message: xhr.statusText || xhr.error,
        location: o.url,
        code: xhr.status,
        request: o
       });
       return r;
      }
     var t = xhr.getResponseHeader('Content-Type'),
         u = (o.url!=null) ? o.url : null,
         m = 'Responce transferred with Content-Type "'+t+'" but interpreted as other type';
     try { if (t.match(/json/i)) r = new Function('return ' + r)(); }
     catch (e)
      {
       $R.log('XHR responce parsing error', {
        details: m,
        message: e.message,
        location: u,
        stack: (typeof e.stack != UNDEFINED) ? e.stack : e,
        data: r,
        request: o
       });
       e.message = '['+u+'] ' + e.message + ' (' + m + ')';
       throw e;
      };
     return r;
    }
   xhr.getResponse = function () { return getResponse(); };
   return xhr;
  }

 function xhr (/* [url,] options|callback */)
  {
   var o = null, a = arguments;
   if (a[0] != null && typeof a[0] == OBJECT) o = a[0]; // (o)
   else if (a[1] != null && typeof a[1] == OBJECT) o = a[1]; // (url, o)
   else if (typeof a[0] == STRING && typeof a[1] == FUNCTION) o = {url:a[0], complete:a[1]}; // (url, callback)
   if (o == null) return false;

   var q = {};
   q.url = (typeof o.url == STRING) ? o.url : (typeof a[0] == STRING ? a[0] : location.href.replace(/#.*$/, ''));
   q.type = (typeof o.type == STRING) ? o.type : 'GET';
   q.async = (typeof o.async == BOOLEAN) ? o.async : true;
   q.contentType = (typeof o.contentType == STRING) ? o.contentType : null; // application/x-www-form-urlencoded | multipart/form-data
   q.xRequestedWith = (typeof o.xRequestedWith == STRING) ? o.xRequestedWith : null; // XMLHttpRequest
   q.data = (typeof o.data == OBJECT && o.data != null) ? o.data : null;
   q.cache = (typeof o.cache == BOOLEAN) ? o.cache : true;
   q.headers = (typeof o.headers == OBJECT && o.headers != null) ? o.headers : {};
   q.timeout = (typeof o.timeout == NUMBER) ? o.timeout : 30 * 1000;
   q.error = (typeof o.error == FUNCTION) ? o.error : function(){};
   q.success = (typeof o.success == FUNCTION) ? o.success : function(){};
   q.complete = (typeof o.complete == FUNCTION) ? o.complete : function(){};

   if (q.cache && function(){
     var query = q.data ? makeQueryString(q.data) : '',
         id = q.url + (!query ? '' : (q.url.indexOf('?') >= 0 ? '&' : '?') + query);
     var cache = getTemplate(id);
     if (typeof cache == STRING) {
       var xhr = {
         status: 302,
         statusText: 'Found',
         responseText: cache
       };
       setTimeout(function(){
         try {
           var r = q.url.match(/.+\.json$/i) ? new Function('return ' + cache)() : cache;
           q.success(r, xhr);
           q.complete(r, xhr);
         }
         catch(e) {
           $R.log('Javascript exception in cached XHR request callback execution process', {
             message: e.message,
             stack: (typeof e.stack != UNDEFINED) ? e.stack : e,
             request: q
            });
         };
       }, 0);
       return true;
     }
     return;
   }()) return;

   var xhr = makeXHR(q);

   setTimeout(function(){
    var url = q.url;
    var data = null;
    if (q.data != null && typeof q.data == OBJECT)
     {
      if (q.contentType == null)
       {
        q.contentType = 'application/x-www-form-urlencoded';
        if (q.type.toUpperCase() == 'POST') data = makeQueryString(q.data);
        else if (q.type.toUpperCase() == 'GET')
         {
          url += (url.indexOf('?') >= 0) ? '&' : '?';
          url += makeQueryString(q.data);
         }
       }
      else data = q.data;
     }

    function onError (e, fn)
     {
      xhr.hadError = !0;
      xhr.error = 'error';
      if (e != null && e.message != null) xhr.error = e.message;
      else if (e != null && e.type != null) xhr.error = e.type;
      else if (!(xhr.status >= 200 && xhr.status <= 399) && xhr.status > 0) xhr.error = xhr.statusText;
      if (typeof fn == FUNCTION) fn(xhr);
     }

    var _executed = !1;
    function execCallbacks ()
     {
      if (_executed) return;
      _executed = !0;
      try {
       var request = xhr.getRequest(), response = xhr.getResponse();
       if (!xhr.hadError && xhr.status >= 200 && xhr.status <= 399) request.success(response, xhr);
       if (xhr.hadError) request.error(response, xhr);
       request.complete(response, xhr);
      }
      catch(e) {
       $R.log('Javascript exception in XHR request callback execution process', {
        message: e.message,
        stack: (typeof e.stack != UNDEFINED) ? e.stack : e,
        request: xhr
       });
       throw e;
      };
     }
    try{xhr.open(q.type, url, q.async);}
    catch(e){onError(e, execCallbacks);};
    if (q.async) xhr.timeout = q.timeout;
    if (q.contentType != null) xhr.setRequestHeader('Content-type', q.contentType);
    if (q.xRequestedWith != null) xhr.setRequestHeader('X-Requested-With', q.xRequestedWith);
    for (var i in q.headers) xhr.setRequestHeader(String(i), String(q.headers[i]));

    xhr.ontimeout = function(e){onError(e, execCallbacks);};
    xhr.onerror = function(e){onError(e, execCallbacks);};
    xhr.onreadystatechange = function(e)
     {
      if (xhr.readyState == 4)
       {
        if (xhr.status >= 200 && xhr.status <= 399) execCallbacks();
        else if (xhr.status > 0) onError(null, execCallbacks);
       }
     };
    try{xhr.send(data);}
    catch(e){onError(e, execCallbacks);};
   }, 0);

   return xhr;
  }

 function include (type, url, callback, skipErrors)
  {
   if (type == 'css')
    {
     var o = document.createElement('link');
     o.rel   = 'stylesheet';
     o.type  = 'text/css';
     o.media = 'all';
     o.href  = url;
    }
   else if (type == 'js')
    {
     var o  = document.createElement('script');
     o.type = 'text/javascript';
     o.src  = url;
    }
   if (typeof o != UNDEFINED)
    {
     var procCallback = function()
      {
       if(typeof callback == FUNCTION)
        {
         setTimeout(function(){
          callback();
         },0);
        }
      };
     var handler = function(e)
      {
       if(e.type == 'error' && !skipErrors)
        {
         $R.log('HTTP request error', {
          message: 'Location unavailable',
          location: url,
          source: e.target.outerHTML
         });
         //TODO: throw error
        }
       procCallback();
      };
     o.onload = handler;
     o.onerror = handler;
     setTimeout(function(){
      document.getElementsByTagName('head')[0].appendChild(o);
     }, 0);
    }
  }

 function include_once (type, url, callback, skipErrors)
  {
   once(url, callback, function(url, processor){
    include (type, url, processor, skipErrors);
   });
  }

 function require (url, callback, complete)
  {
   xhr(url, {
    success: callback,
    complete: function (r, xhr) {
      if(typeof complete == FUNCTION)
      {
       complete(!(xhr.status>=200 && xhr.status<=399), r);
      }
    }
   });
  }

 function require_once (url, callback)
  {
   once(url, callback, function(url, processor){
    require(url, null, processor);
   });
  }

 function inject (url, callback)
  {
   require_once(url, function(str){
    try
     {
      var js = new Function('$R', str);
      js($R);
      if(typeof callback == FUNCTION)
       {
        setTimeout(function(){ callback(); },0);
       }
     }
    catch(e)
     {
      $R.log('Javascript exception', {
       message: e.message,
       location: url,
       stack: (typeof e.stack != UNDEFINED) ? e.stack : e,
       source: str
      });
      e.message = '['+url+'] ' + e.message;
      throw e;
     };
   });
  }

 $R.xhr = xhr;
 $R.include = include; // Simple way for insert CSS or JS file (such as jQuery) to document
 $R.include_once = include_once;
 $R.require = require; // Require any content from same domain
 $R.require_once = require_once; // Require any content once from same domain
 $R.inject = inject; // Inject any JS file from same domain to the private $R namespace
 $R.makeSourceURL = makeSourceURL;
}($R));
<|endoftext|>


<commit_before>// @flow
import * as React from 'react';
import ThemeContext from './ThemeContext';
import type { Theme as ThemeType } from '../../themes/types';

export type Theme = ThemeType;

const withTheme = <Props: {}>(
  Component: React.ComponentType<Props>,
): React.ComponentType<$Diff<Props, { theme: Theme | void }>> => {
  class WithTheme extends React.PureComponent<Props> {
    render() {
      // $FlowFixMe Should be added?
      const { forwardedRef, ...rest } = this.props;
      return (
        <ThemeContext.Consumer>
          {theme => <Component {...rest} theme={theme} ref={forwardedRef} />}
        </ThemeContext.Consumer>
      );
    }
  }
  // $FlowFixMe Missing React.forwardRef definition in Flow.
  return React.forwardRef((props, ref) => {
    return <WithTheme {...props} forwardedRef={ref} />;
  });
};

export default withTheme;
<commit_msg>Delete withTheme.js<commit_after><|endoftext|>


<commit_before>var WNPRC = require("wnprc_ehr/WNPRC").WNPRC;
require("ehr/triggers").initScript(this);

function onInsert(helper, scriptErrors, row, oldRow){
    if (row && row.Id){
        WNPRC.Utils.getJavaHelper().updateUltrasoundFollowup(row.Id, row.date);

        row.QCState = EHR.Server.Security.getQCStateByLabel('Completed').RowId;
        row.QCStateLabel = EHR.Server.Security.getQCStateByLabel('Completed').Label;
    }
}

function onUpsert(helper, scriptErrors, row, oldRow){
    if (row && row.Id){
        row.followup_required = !!row.followup_required;
        row.fetal_heartbeat = !!row.fetal_heartbeat;

        let gestation_fields = ['gest_sac_mm', 'crown_rump_mm', 'biparietal_diameter_mm', 'femur_length_mm'];

        EHR.Server.Utils.findDemographics({
            participant: row.Id,
            helper: helper,
            scope: this,
            callback: function (demographics) {
                if (demographics) {
                    if (demographics['species']) {
                        let species = demographics['species'];

                        gestation_fields.forEach(function(gestationField) {
                            LABKEY.Query.selectRows({
                                schemaName: 'wnprc',
                                queryName: 'getGestationalDay',
                                parameters: {
                                    SPECIES: species,
                                    SEARCH_COLUMN_NAME: gestationField,
                                    SEARCH_VALUE: row[gestationField]
                                },
                                success: function(data){
                                    let gestationDayField = gestationField.slice(0, -3) + '_gest_day';
                                    if(data && data.rows && data.rows.length){
                                        row[gestationDayField] = data.rows[0].gestational_day;
                                    } else {
                                        row[gestationDayField] = null;
                                    }
                                },
                                failure: EHR.Server.Utils.onFailure
                            });
                        });
                    }
                }
            }
        });
    }
}<commit_msg>add description field to ultrasounds<commit_after>var WNPRC = require("wnprc_ehr/WNPRC").WNPRC;
require("ehr/triggers").initScript(this);

function onInsert(helper, scriptErrors, row, oldRow){
    if (row && row.Id){
        WNPRC.Utils.getJavaHelper().updateUltrasoundFollowup(row.Id, row.date);

        row.QCState = EHR.Server.Security.getQCStateByLabel('Completed').RowId;
        row.QCStateLabel = EHR.Server.Security.getQCStateByLabel('Completed').Label;
    }
}

function onUpsert(helper, scriptErrors, row, oldRow){
    if (row && row.Id){
        row.followup_required = !!row.followup_required;
        row.fetal_heartbeat = !!row.fetal_heartbeat;

        let gestation_fields = ['gest_sac_mm', 'crown_rump_mm', 'biparietal_diameter_mm', 'femur_length_mm'];

        EHR.Server.Utils.findDemographics({
            participant: row.Id,
            helper: helper,
            scope: this,
            callback: function (demographics) {
                if (demographics) {
                    if (demographics['species']) {
                        let species = demographics['species'];

                        gestation_fields.forEach(function(gestationField) {
                            LABKEY.Query.selectRows({
                                schemaName: 'wnprc',
                                queryName: 'getGestationalDay',
                                parameters: {
                                    SPECIES: species,
                                    SEARCH_COLUMN_NAME: gestationField,
                                    SEARCH_VALUE: row[gestationField]
                                },
                                success: function(data){
                                    let gestationDayField = gestationField.slice(0, -3) + '_gest_day';
                                    if(data && data.rows && data.rows.length){
                                        row[gestationDayField] = data.rows[0].gestational_day;
                                    } else {
                                        row[gestationDayField] = null;
                                    }
                                },
                                failure: EHR.Server.Utils.onFailure
                            });
                        });
                    }
                }
            }
        });
    }
}

function setDescription(row, helper){
    var description = [];

    if(row.reason) {
        description.push('Date: ' + row.date);
    }
    if(row.fetal_heartbeat) {
        description.push('Fetal HB: ' + (!!row.beats_per_minute ? row.beats_per_minute : 'true'));
    } else {
        description.push('Fetal HB: false');
    }
    if (row.gest_sac_mm) {
        description.push('Gestational Sac (mm): ' + row.gest_sac_mm);
    }
    if(row.crown_rump_mm) {
        description.push('Crown Rump (mm): ' + row.crown_rump_mm);
    }
    if (row.biparietal_diameter_mm) {
        description.push('Biparietal Diameter (mm): ' + row.biparietal_diameter_mm);
    }
    if (row.femur_length_mm) {
        description.push('Femur Length (mm): ' + row.femur_length_mm);
    }
    if (row.yolk_sac_diameter_mm) {
        description.push('Yolk Sac Diameter (mm): ' + row.yolk_sac_diameter_mm);
    }
    if (row.head_circumference_mm) {
        description.push('Head Circumference (mm): ' + row.head_circumference_mm);
    }
    if (row.followup_required) {
        description.push('Followup Required: ' + row.followup_required);
    }

    return description;
}<|endoftext|>


<commit_before>import Component from '@ember/component';
import { computed } from '@ember/object';

export default Component.extend({
  classNames  : ['ui', 'fluid', 'card'],
  roleType    : 'accepted',
  roleInvites : computed('data.roleInvites.@each', 'roleType', function() {
    return this.get('data.roleInvites').filterBy('status', this.get('roleType'));
  }),
  actions: {
    openAddUserRoleModal(invite) {
      if (invite) {
        this.set('currentInvite', invite);
        this.set('isNewInvite', false);
      } else {
        const currentInvite = this.get('data.roleInvites').createRecord({});
        this.set('currentInvite', currentInvite);
        this.set('isNewInvite', true);
      }
      this.set('isAddUserRoleModalOpen', true);
    },
    updateUserRoles() {
      this.set('isLoading', true);
      const currentInvite = this.get('currentInvite');
      currentInvite.set('roleName', currentInvite.get('role.name'));
      this.get('currentInvite').save()
        .then(() => {
          if (this.get('isNewInvite')) {
            this.get('data.roleInvites').addObject(currentInvite);
          }
          this.set('isAddUserRoleModalOpen', false);
          this.get('notify').success(this.get('isNewInvite') ? this.get('l10n').t('Role Invite sent successfully') : this.get('l10n').t('Role Invite updated successfully'));
        })
        .catch(() => {
          this.get('notify').error(this.get('l10n').t('Oops something went wrong. Please try again'));
        })
        .finally(() => {
          this.set('isLoading', false);
        });
    },
    deleteUserRole(invite) {
      this.set('isLoading', true);
      invite.destroyRecord()
        .then(() => {
          this.get('notify').success(this.get('l10n').t('Role Invite deleted successfully'));
          this.get('data.roleInvites').removeObject(invite);
        })
        .catch(() => {
          this.get('notify').error(this.get('l10n').t('Oops something went wrong. Please try again'));
        })
        .finally(() => {
          this.set('isLoading', false);
        });
    },

    filter(type) {
      this.set('roleType', type);
    }
  }
});
<commit_msg>fix: 'Add People' button stops working after a few clicks (#1513)<commit_after>import Component from '@ember/component';
import { computed } from '@ember/object';

export default Component.extend({
  classNames  : ['ui', 'fluid', 'card'],
  roleType    : 'accepted',
  roleInvites : computed('data.roleInvites.@each', 'roleType', function() {
    return this.get('data.roleInvites').filterBy('status', this.get('roleType'));
  }),
  actions: {
    openAddUserRoleModal(invite) {
      if (invite) {
        this.set('currentInvite', invite);
        this.set('isNewInvite', false);
      } else {
        const currentInvite = this.get('data').roleInvites.createRecord({});
        this.set('currentInvite', currentInvite);
        this.set('isNewInvite', true);
      }
      this.set('isAddUserRoleModalOpen', true);
    },
    updateUserRoles() {
      this.set('isLoading', true);
      const currentInvite = this.get('currentInvite');
      currentInvite.set('roleName', currentInvite.get('role.name'));
      this.get('currentInvite').save()
        .then(() => {
          if (this.get('isNewInvite')) {
            this.get('data.roleInvites').addObject(currentInvite);
          }
          this.set('isAddUserRoleModalOpen', false);
          this.get('notify').success(this.get('isNewInvite') ? this.get('l10n').t('Role Invite sent successfully') : this.get('l10n').t('Role Invite updated successfully'));
        })
        .catch(() => {
          this.get('notify').error(this.get('l10n').t('Oops something went wrong. Please try again'));
        })
        .finally(() => {
          this.set('isLoading', false);
        });
    },
    deleteUserRole(invite) {
      this.set('isLoading', true);
      invite.destroyRecord()
        .then(() => {
          this.get('notify').success(this.get('l10n').t('Role Invite deleted successfully'));
          this.get('data.roleInvites').removeObject(invite);
        })
        .catch(() => {
          this.get('notify').error(this.get('l10n').t('Oops something went wrong. Please try again'));
        })
        .finally(() => {
          this.set('isLoading', false);
        });
    },

    filter(type) {
      this.set('roleType', type);
    }
  }
});
<|endoftext|>


<commit_before>var _playlist_jplayer;
var _idToPostionLookUp;

/**
 *When the page loads the ready function will get all the data it can from the hidden span elements
 *and call one of three functions depending on weather the window was open to play an audio file,
 *or a playlist or a show.
 */
$(document).ready(function(){

    _playlist_jplayer = new jPlayerPlaylist({
        jPlayer: "#jquery_jplayer_1",
        cssSelectorAncestor: "#jp_container_1"
    },[], //array of songs will be filled with below's json call
    {
        swfPath: "/js/jplayer",
        supplied:"oga, mp3, m4v",
        size: {
            width: "0px",
            height: "0px",
            cssClass: "jp-video-270p"
        },
        playlistOptions: {
            autoPlay: false,
            loopOnPrevious: false,
            shuffleOnLoop: true,
            enableRemoveControls: false,
            displayTime: 0,
            addTime: 0,
            removeTime: 0,
            shuffleTime: 0
        }
    });

    $.jPlayer.timeFormat.showHour = true;

    var audioFileID = $('.audioFileID').text();
    var playlistID = $('.playlistID').text();
    var playlistIndex = $('.playlistIndex').text();
    var showID = $('.showID').text();
    var showIndex = $('.showIndex').text();

    var numOfItems = 0;

    if (playlistID != "" && playlistID !== ""){
        playAllPlaylist(playlistID, playlistIndex);
    }else if (audioFileID != "") {
        playOne(audioFileID);
    }else if (showID != "") {
        playAllShow(showID, showIndex);
    }

    $("#jp_container_1").on("mouseenter", "ul.jp-controls li", function(ev) {
    	$(this).addClass("ui-state-hover");
    });

    $("#jp_container_1").on("mouseleave", "ul.jp-controls li", function(ev) {
    	$(this).removeClass("ui-state-hover");
    });
});

/**
 * Sets up the jPlayerPlaylist to play.
 *  - Get the playlist info based on the playlistID give.
 *  - Update the playlistIndex to the position in the pllist to start playing.
 *  - Select the element played from and start playing. If playlist is null then start at index 0.
**/
function playAllPlaylist(p_playlistID, p_playlistIndex) {
    var viewsPlaylistID = $('.playlistID').text();

    if ( _idToPostionLookUp !== undefined && viewsPlaylistID == p_playlistID ) {
        play(p_playlistIndex);
    }else {
        buildplaylist("/audiopreview/get-playlist/playlistID/"+p_playlistID, p_playlistIndex);
    }
}

/**
 * Sets up the show to play.
 *  checks with the show id given to the show id on the page/view
 *      if the show id and the page or views show id are the same it means the user clicked another
 *          file in the same show, so don't refresh the show content tust play the track from the preloaded show.
 *      if the the ids are different they we'll need to get the show's context so create the uri
 *      and call the controller.
**/
function playAllShow(p_showID, p_index) {

    var viewsShowID = $('.showID').text();
    if ( _idToPostionLookUp !== undefined && viewsShowID == p_showID ) {
        play(p_index);
    }else {
        buildplaylist("/audiopreview/get-show/showID/"+p_showID, p_index);
    }
}

/**
 * This function will call the AudiopreviewController to get the contents of either a show or playlist
 * Looping throught the returned contents and creating media for each track.
 *
 * Then trigger the jplayer to play the list.
 */
function buildplaylist(p_url, p_playIndex) {
    _idToPostionLookUp = Array();
    $.getJSON(p_url, function(data){  // get the JSON array produced by my PHP
        var myPlaylist = new Array();
        var media;
        var index;
        var total = 0;
        for(index in data){

            if (data[index]['element_mp3'] != undefined){
                media = {title: data[index]['element_title'],
                        artist: data[index]['element_artist'],
                        mp3:"/api/get-media/file/"+data[index]['element_mp3']
                };
            }else if (data[index]['element_oga'] != undefined) {
                media = {title: data[index]['element_title'],
                        artist: data[index]['element_artist'],
                        oga:"/api/get-media/file/"+data[index]['element_oga']
                };
            }
            myPlaylist[index] = media;

            // we should create a map according to the new position in the player itself
            // total is the index on the player
            _idToPostionLookUp[data[index]['element_id']] = total;
            total++;
        }

        _playlist_jplayer.setPlaylist(myPlaylist);
        _playlist_jplayer.option("autoPlay", true);
        play(p_playIndex);

        var height = Math.min(90 + (26 * total), 400);
        window.innerWidth = 500;
        window.innerHeight = height;
        window.scrollbars = true;
    });
}

/**
 *Function simply plays the given index, for playlists index can be different so need to look up the
 *right index.
 */
function play(p_playlistIndex){
    playlistIndex = _idToPostionLookUp[p_playlistIndex];
    if(playlistIndex == undefined){
        playlistIndex = 0
    }
    //_playlist_jplayer.select(playlistIndex);
    _playlist_jplayer.play(playlistIndex);
}

/**
 * Playing one audio track occurs from the library. This function will create the media, setup
 * jplayer and play the track.
 */
function playOne(p_audioFileID) {
    var playlist = new Array();
    var fileExtensioin = p_audioFileID.split('.').pop();
    console.log(p_audioFileID);
    if (fileExtensioin === 'mp3') {
        media = {title: $('.audioFileTitle').text() !== 'null' ?$('.audioFileTitle').text():"",
            artist: $('.audioFileArtist').text() !== 'null' ?$('.audioFileArtist').text():"",
            mp3:"/api/get-media/file/"+p_audioFileID
        };
    }else if (fileExtensioin === 'ogg' ) {
        media = {title: $('.audioFileTitle').text() != 'null' ?$('.audioFileTitle').text():"",
            artist: $('.audioFileArtist').text() != 'null' ?$('.audioFileArtist').text():"",
            oga:"/api/get-media/file/"+p_audioFileID
        };
    }
    _playlist_jplayer.option("autoPlay", true);
    console.log(media);
    playlist[0] = media;
    //_playlist_jplayer.setPlaylist(playlist); --if I use this the player will call _init on the setPlaylist and on the ready
    _playlist_jplayer._initPlaylist(playlist);
    _playlist_jplayer.play(0);

    window.innerWidth = 490;
    window.innerHeight = 120;
}<commit_msg>CC-3851 : Preview Player: does not expand on Chrome, too big on Firefox<commit_after>var _playlist_jplayer;
var _idToPostionLookUp;

/**
 *When the page loads the ready function will get all the data it can from the hidden span elements
 *and call one of three functions depending on weather the window was open to play an audio file,
 *or a playlist or a show.
 */
$(document).ready(function(){

    _playlist_jplayer = new jPlayerPlaylist({
        jPlayer: "#jquery_jplayer_1",
        cssSelectorAncestor: "#jp_container_1"
    },[], //array of songs will be filled with below's json call
    {
        swfPath: "/js/jplayer",
        supplied:"oga, mp3, m4v",
        size: {
            width: "0px",
            height: "0px",
            cssClass: "jp-video-270p"
        },
        playlistOptions: {
            autoPlay: false,
            loopOnPrevious: false,
            shuffleOnLoop: true,
            enableRemoveControls: false,
            displayTime: 0,
            addTime: 0,
            removeTime: 0,
            shuffleTime: 0
        }
    });

    $.jPlayer.timeFormat.showHour = true;

    var audioFileID = $('.audioFileID').text();
    var playlistID = $('.playlistID').text();
    var playlistIndex = $('.playlistIndex').text();
    var showID = $('.showID').text();
    var showIndex = $('.showIndex').text();

    var numOfItems = 0;

    if (playlistID != "" && playlistID !== ""){
        playAllPlaylist(playlistID, playlistIndex);
    }else if (audioFileID != "") {
        playOne(audioFileID);
    }else if (showID != "") {
        playAllShow(showID, showIndex);
    }

    $("#jp_container_1").on("mouseenter", "ul.jp-controls li", function(ev) {
    	$(this).addClass("ui-state-hover");
    });

    $("#jp_container_1").on("mouseleave", "ul.jp-controls li", function(ev) {
    	$(this).removeClass("ui-state-hover");
    });
});

/**
 * Sets up the jPlayerPlaylist to play.
 *  - Get the playlist info based on the playlistID give.
 *  - Update the playlistIndex to the position in the pllist to start playing.
 *  - Select the element played from and start playing. If playlist is null then start at index 0.
**/
function playAllPlaylist(p_playlistID, p_playlistIndex) {
    var viewsPlaylistID = $('.playlistID').text();

    if ( _idToPostionLookUp !== undefined && viewsPlaylistID == p_playlistID ) {
        play(p_playlistIndex);
    }else {
        buildplaylist("/audiopreview/get-playlist/playlistID/"+p_playlistID, p_playlistIndex);
    }
}

/**
 * Sets up the show to play.
 *  checks with the show id given to the show id on the page/view
 *      if the show id and the page or views show id are the same it means the user clicked another
 *          file in the same show, so don't refresh the show content tust play the track from the preloaded show.
 *      if the the ids are different they we'll need to get the show's context so create the uri
 *      and call the controller.
**/
function playAllShow(p_showID, p_index) {

    var viewsShowID = $('.showID').text();
    if ( _idToPostionLookUp !== undefined && viewsShowID == p_showID ) {
        play(p_index);
    }else {
        buildplaylist("/audiopreview/get-show/showID/"+p_showID, p_index);
    }
}

/**
 * This function will call the AudiopreviewController to get the contents of either a show or playlist
 * Looping throught the returned contents and creating media for each track.
 *
 * Then trigger the jplayer to play the list.
 */
function buildplaylist(p_url, p_playIndex) {
    _idToPostionLookUp = Array();
    $.getJSON(p_url, function(data){  // get the JSON array produced by my PHP
        var myPlaylist = new Array();
        var media;
        var index;
        var total = 0;
        for(index in data){

            if (data[index]['element_mp3'] != undefined){
                media = {title: data[index]['element_title'],
                        artist: data[index]['element_artist'],
                        mp3:"/api/get-media/file/"+data[index]['element_mp3']
                };
            }else if (data[index]['element_oga'] != undefined) {
                media = {title: data[index]['element_title'],
                        artist: data[index]['element_artist'],
                        oga:"/api/get-media/file/"+data[index]['element_oga']
                };
            }
            myPlaylist[index] = media;

            // we should create a map according to the new position in the player itself
            // total is the index on the player
            _idToPostionLookUp[data[index]['element_id']] = total;
            total++;
        }

        _playlist_jplayer.setPlaylist(myPlaylist);
        _playlist_jplayer.option("autoPlay", true);
        play(p_playIndex);

        var height = Math.min(143 + (26 * total), 400);
        var width = 505;

        if (height === 400) {
        	window.scrollbars = true;
        }
        else {
        	//there's no scrollbars so we don't need the window to be as wide.
        	width = 490;
        }

        window.resizeTo(width, height);
    });
}

/**
 *Function simply plays the given index, for playlists index can be different so need to look up the
 *right index.
 */
function play(p_playlistIndex){
    playlistIndex = _idToPostionLookUp[p_playlistIndex];
    if(playlistIndex == undefined){
        playlistIndex = 0
    }
    //_playlist_jplayer.select(playlistIndex);
    _playlist_jplayer.play(playlistIndex);
}

/**
 * Playing one audio track occurs from the library. This function will create the media, setup
 * jplayer and play the track.
 */
function playOne(p_audioFileID) {
    var playlist = new Array();
    var fileExtensioin = p_audioFileID.split('.').pop();
    console.log(p_audioFileID);
    if (fileExtensioin === 'mp3') {
        media = {title: $('.audioFileTitle').text() !== 'null' ?$('.audioFileTitle').text():"",
            artist: $('.audioFileArtist').text() !== 'null' ?$('.audioFileArtist').text():"",
            mp3:"/api/get-media/file/"+p_audioFileID
        };
    }else if (fileExtensioin === 'ogg' ) {
        media = {title: $('.audioFileTitle').text() != 'null' ?$('.audioFileTitle').text():"",
            artist: $('.audioFileArtist').text() != 'null' ?$('.audioFileArtist').text():"",
            oga:"/api/get-media/file/"+p_audioFileID
        };
    }
    _playlist_jplayer.option("autoPlay", true);
    console.log(media);
    playlist[0] = media;
    //_playlist_jplayer.setPlaylist(playlist); --if I use this the player will call _init on the setPlaylist and on the ready
    _playlist_jplayer._initPlaylist(playlist);
    _playlist_jplayer.play(0);

    window.resizeTo(490, 167);
}<|endoftext|>


<commit_before>var directives = angular.module('opal.directives', []);

directives.directive("freezePanes", function () {
    return function (scope, element, attrs) {
        scope.$watch("assignments", function () {
            $('table').stickyTableHeaders({fixedOffset: 114});
                //$('table').stickyTableHeaders()
        });
    };
});

directives.directive('loadingbar', function($rootScope) {
	return {
		link: function(scope, element, attrs) {
			element.addClass('hide');

			$rootScope.$on('$routeChangeStart', function() {
				element.removeClass('hide');
			});

			$rootScope.$on('$routeChangeSuccess', function() {
				element.addClass('hide');
			});
		}
	};
});

directives.directive('placeholder', function($timeout){
	if ($.support.placeholder) {
		return {};
	}
	return {
		link: function(scope, elm, attrs){
			if (attrs.type === 'password') {
				return;
			}
			$timeout(function(){
				elm.val(attrs.placeholder).focus(function(){
					if ($(this).val() == $(this).attr('placeholder')) {
						$(this).val('');
					}
				}).blur(function(){
					if ($(this).val() == '') {
						$(this).val($(this).attr('placeholder'));
					}
				});
			});
		}
	}
});

directives.directive('markdown', function () {
	return function postLink (scope, element, attrs) {
		scope.$watch('item.' + attrs.markdown, function(){
			if(!_.isUndefined(scope.item[attrs.markdown])){
				var converter = new Showdown.converter({extensions: [OpalDown]});
				element.html(converter.makeHtml(scope.item[attrs.markdown]));
			}
		})
	}
});

directives.directive('focusOnThis', function($timeout){
    return {
        link: function(scope, elem, attr){
            $timeout(function(){
                elem[0].focus();
            });
        }
    }
});
<commit_msg>Merging master<commit_after>var directives = angular.module('opal.directives', []);

directives.directive("freezePanes", function () {
    return function (scope, element, attrs) {
        scope.$watch("assignments", function () {
            $('table').stickyTableHeaders({fixedOffset: 114});
                //$('table').stickyTableHeaders()
        });
    };
});

directives.directive('loadingbar', function($rootScope) {
	return {
		link: function(scope, element, attrs) {
			element.addClass('hide');

			$rootScope.$on('$routeChangeStart', function() {
				element.removeClass('hide');
			});

			$rootScope.$on('$routeChangeSuccess', function() {
				element.addClass('hide');
			});
		}
	};
});

directives.directive('placeholder', function($timeout){
	if ($.support.placeholder) {
		return {};
	}
	return {
		link: function(scope, elm, attrs){
			if (attrs.type === 'password') {
				return;
			}
			$timeout(function(){
				elm.val(attrs.placeholder).focus(function(){
					if ($(this).val() == $(this).attr('placeholder')) {
						$(this).val('');
					}
				}).blur(function(){
					if ($(this).val() == '') {
						$(this).val($(this).attr('placeholder'));
					}
				});
			});
		}
	}
});

directives.directive('markdown', function () {
	return function postLink (scope, element, attrs) {

	    var prefix = 'item';
	    if( _.isUndefined(scope['item']) ){
		if(! _.isUndefined(scope['editing']) )
		    {
			prefix = 'editing';
		    }
		else
		    {
			return;
		    }
	    }
	    scope.$watch(prefix + '.' + attrs.markdown, function(){
		    var converter = new Showdown.converter({extensions: [OpalDown]});
		    element.html(converter.makeHtml(scope[prefix][attrs.markdown]));
		}
		);
	}
});

directives.directive('focusOnThis', function($timeout){
    return {
        link: function(scope, elem, attr){
            $timeout(function(){
                elem[0].focus();
            });
        }
    }
});
<|endoftext|>


<commit_before>let helper = {
  clean: function () {
    var toReturn = false;
    // Always place this memory cleaning code at the very top of your main loop!
    for (var name in Memory.creeps) {
      if (!Game.creeps[name]) {
        delete Memory.creeps[name];
        console.log('Clearing non-existing creep memory:', name);
        toReturn = true;
      }
    }
    return toReturn;
  },

  getTarget: function (creep, type, ressource) {
    if (creep === undefined || type == undefined) {
      return false;
    }
    var object = null;
    switch (type) {
      case 'spawner': {
        object = creep.pos.findClosestByPath(FIND_STRUCTURES, {
          filter: (structure) => {
            return (structure.structureType == STRUCTURE_EXTENSION || structure.structureType == STRUCTURE_SPAWN) && structure.energy < structure.energyCapacity;
          }
        });
        if (object === null) {
          return false;
        }
        return { target: object, path: creep.pos.findPathTo(object.pos) }
        break;
      }
      case 'tower': {
        object = creep.pos.findClosestByPath(FIND_STRUCTURES, {
          filter: (structure) => {
            return (structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
          }
        });
        if (object === null) {
          return false;
        }
        return { target: object, path: creep.pos.findPathTo(object.pos) }
        break;
      }
      case 'construction': {
        object = creep.pos.findClosestByPath(FIND_CONSTRUCTION_SITES);
        if (object === null) {
          return false;
        }
        return { target: object, path: creep.pos.findPathTo(object.pos) }
        break;
      }
      case 'repair': {
        object = creep.pos.findClosestByRange(FIND_STRUCTURES, {
          filter: function (object) {
            if ((object.structureType === STRUCTURE_ROAD || object.structureType === STRUCTURE_STORAGE || object.structureType === STRUCTURE_CONTAINER) && object.hits < object.hitsMax * 0.95) {
              return true
            }

            return false;
          }
        });
        if (object === null) {
          return false;
        }
        return { target: object, path: creep.pos.findPathTo(object.pos) }
        break;
      }
      case 'controller':
        {
          var controller = creep.room.controller;
          return { target: object, path: creep.pos.findPathTo(object.pos) }
          break;
        }
    }

    return false;
  }
};

function CreepObject(creep) {
  this.c = creep
}

CreepObject.prototype.move = function () {
  switch (this.c.moveByPath(this.c.memory.target.path)) {
    case OK: {
      this.c.memory.target.range = this.c.memory.target.range - 1
      break
    }
    default: {
      this.recalcPath()
      break
    }
  }

  if (this.c.memory.target.time < Game.time) {
    this.recalcPath()
  }
}

CreepObject.prototype.getTarget = function () {
  let targetObj = false

  try {
    targetObj = Game.getObjectById(this.c.memory.target.obj)
  } catch (err) { }

  return targetObj
}

CreepObject.prototype.setTarget = function (obj, path, task) {
  if (!path) path = this.c.pos.findPathTo(obj);

  let target = {
    obj: obj.id,
    path: Room.serializePath(path),
    range: path.length,
    time: Game.time + 3 + Math.round(Math.random(0, 1) * 5)
  }

  if (task) target.task = task;

  this.c.memory.target = target

  return true
}

CreepObject.prototype.clearTarget = function () {
  delete this.c.memory.target
}

CreepObject.prototype.getRange = function () {
  return this.c.memory.target.range
}

CreepObject.prototype.getTask = function () {
  try {
    return this.c.memory.target.task
  } catch (err) {
    return ''
  }
}

CreepObject.prototype.recalcPath = function () {
  let target = this.getTarget()
  if (!target) {
    delete this.c.memory.target
    return false
  }

  let path = this.c.pos.findPathTo(target)
  this.c.memory.target.path = Room.serializePath(path)
  this.c.memory.target.range = path.length
  this.c.memory.target.time = Game.time + 3 + Math.round(Math.random(0, 1) * 5)

  return true
}

CreepObject.prototype.getCurrentRole = function () {
  return this.c.memory.c
}

CreepObject.prototype.setCurrentRole = function (role) {
  if (_.intersection([role], this.c.memory.r).length == 1) {
    this.c.memory.c = role
    return true
  }

  return false
}

CreepObject.prototype.getRoles = function () {
  return this.c.memory.r
}

CreepObject.prototype.getMainRole = function () {
  return this.c.memory.type
}

helper.CreepObject = CreepObject

module.exports = helper<commit_msg>removed cleanup hint<commit_after>let helper = {
  clean: function () {
    var toReturn = false;
    // Always place this memory cleaning code at the very top of your main loop!
    for (var name in Memory.creeps) {
      if (!Game.creeps[name]) {
        delete Memory.creeps[name];
        toReturn = true;
      }
    }
    return toReturn;
  },

  getTarget: function (creep, type, ressource) {
    if (creep === undefined || type == undefined) {
      return false;
    }
    var object = null;
    switch (type) {
      case 'spawner': {
        object = creep.pos.findClosestByPath(FIND_STRUCTURES, {
          filter: (structure) => {
            return (structure.structureType == STRUCTURE_EXTENSION || structure.structureType == STRUCTURE_SPAWN) && structure.energy < structure.energyCapacity;
          }
        });
        if (object === null) {
          return false;
        }
        return { target: object, path: creep.pos.findPathTo(object.pos) }
        break;
      }
      case 'tower': {
        object = creep.pos.findClosestByPath(FIND_STRUCTURES, {
          filter: (structure) => {
            return (structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
          }
        });
        if (object === null) {
          return false;
        }
        return { target: object, path: creep.pos.findPathTo(object.pos) }
        break;
      }
      case 'construction': {
        object = creep.pos.findClosestByPath(FIND_CONSTRUCTION_SITES);
        if (object === null) {
          return false;
        }
        return { target: object, path: creep.pos.findPathTo(object.pos) }
        break;
      }
      case 'repair': {
        object = creep.pos.findClosestByRange(FIND_STRUCTURES, {
          filter: function (object) {
            if ((object.structureType === STRUCTURE_ROAD || object.structureType === STRUCTURE_STORAGE || object.structureType === STRUCTURE_CONTAINER) && object.hits < object.hitsMax * 0.95) {
              return true
            }

            return false;
          }
        });
        if (object === null) {
          return false;
        }
        return { target: object, path: creep.pos.findPathTo(object.pos) }
        break;
      }
      case 'controller':
        {
          var controller = creep.room.controller;
          return { target: object, path: creep.pos.findPathTo(object.pos) }
          break;
        }
    }

    return false;
  }
};

function CreepObject(creep) {
  this.c = creep
}

CreepObject.prototype.move = function () {
  switch (this.c.moveByPath(this.c.memory.target.path)) {
    case OK: {
      this.c.memory.target.range = this.c.memory.target.range - 1
      break
    }
    default: {
      this.recalcPath()
      break
    }
  }

  if (this.c.memory.target.time < Game.time) {
    this.recalcPath()
  }
}

CreepObject.prototype.getTarget = function () {
  let targetObj = false

  try {
    targetObj = Game.getObjectById(this.c.memory.target.obj)
  } catch (err) { }

  return targetObj
}

CreepObject.prototype.setTarget = function (obj, path, task) {
  if (!path) path = this.c.pos.findPathTo(obj);

  let target = {
    obj: obj.id,
    path: Room.serializePath(path),
    range: path.length,
    time: Game.time + 3 + Math.round(Math.random(0, 1) * 5)
  }

  if (task) target.task = task;

  this.c.memory.target = target

  return true
}

CreepObject.prototype.clearTarget = function () {
  delete this.c.memory.target
}

CreepObject.prototype.getRange = function () {
  return this.c.memory.target.range
}

CreepObject.prototype.getTask = function () {
  try {
    return this.c.memory.target.task
  } catch (err) {
    return ''
  }
}

CreepObject.prototype.recalcPath = function () {
  let target = this.getTarget()
  if (!target) {
    delete this.c.memory.target
    return false
  }

  let path = this.c.pos.findPathTo(target)
  this.c.memory.target.path = Room.serializePath(path)
  this.c.memory.target.range = path.length
  this.c.memory.target.time = Game.time + 3 + Math.round(Math.random(0, 1) * 5)

  return true
}

CreepObject.prototype.getCurrentRole = function () {
  return this.c.memory.c
}

CreepObject.prototype.setCurrentRole = function (role) {
  if (_.intersection([role], this.c.memory.r).length == 1) {
    this.c.memory.c = role
    return true
  }

  return false
}

CreepObject.prototype.getRoles = function () {
  return this.c.memory.r
}

CreepObject.prototype.getMainRole = function () {
  return this.c.memory.type
}

helper.CreepObject = CreepObject

module.exports = helper<|endoftext|>


<commit_before>import logger from '../lib/logger';
import emitter from '../lib/emitter';
import {
    evalCss,
    Url,
    now,
    safeStorage,
    each,
    isStr,
    startWith,
    has,
    $,
    isErudaEl,
    upperFirst,
    loadJs
} from '../lib/util';

let style = null;

export default [
    {
        name: 'Border All',
        fn()
        {
            if (style)
            {
                evalCss.remove(style);
                style = null;
                return;
            }

            style = evalCss(borderCss);
        },
        desc: 'Add color borders to all elements'
    },
    {
        name: 'Refresh Page',
        fn()
        {
            let url = new Url();
            url.setQuery('timestamp', now());

            window.location.replace(url.toString());
        },
        desc: 'Add timestamp to url and refresh'
    },
    {
        name: 'Search Text',
        fn()
        {
            let keyword = prompt('Enter the text');

            search(keyword);
        },
        desc: 'Highlight given text on page'
    },
    {
        name: 'Edit Page',
        fn()
        {
            let body = document.body;

            body.contentEditable = body.contentEditable !== 'true';
        },
        desc: 'Toggle body contentEditable'
    },
    {
        name: 'Load Fps Plugin',
        fn()
        {
            loadPlugin('fps');
        },
        desc: 'Display page fps'
    },
    {
        name: 'Load Features Plugin',
        fn()
        {
            loadPlugin('features');
        },
        desc: 'Browser feature detections'
    },
    {
        name: 'Load Timing Plugin',
        fn()
        {
            loadPlugin('timing');
        },
        desc: 'Show performance and resource timing'
    },
    {
        name: 'Load Memory Plugin',
        fn()
        {
            loadPlugin('memory');
        },
        desc: 'Display memory'
    },
    {
        name: 'Load Code Plugin',
        fn()
        {
            loadPlugin('code');
        },
        desc: 'Edit and Run JavaScript'
    },
    {
        name: 'Restore Settings',
        fn()
        {
            let store = safeStorage('local');

            let data = JSON.parse(JSON.stringify(store));

            each(data, (val, key) =>
            {
                if (!isStr(val)) return;

                if (startWith(key, 'eruda')) store.removeItem(key);
            });

            window.location.reload();
        },
        desc: 'Restore defaults and reload'
    }
];

let borderCss = '',
    styleName = has(document.documentElement.style, 'outline') ? 'outline' : 'border',
    selector = 'html',
    colors = ['f5f5f5', 'dabb3a', 'abc1c7', '472936', 'c84941', '296dd1', '67adb4', '1ea061'];

each(colors, (color, idx) =>
{
    selector += (idx === 0) ? '>*:not([class^="eruda-"])' : '>*';

    borderCss += selector + `{${styleName}: 2px solid #${color} !important}`;
});

function search(text)
{
    let root = document.documentElement,
        regText = new RegExp(text, 'ig');

    traverse(root, node =>
    {
        let $node = $(node);

        if (!$node.hasClass('eruda-search-highlight-block')) return;

        return document.createTextNode($node.text());
    });

    traverse(root, node =>
    {
        if (node.nodeType !== 3) return;

        let val = node.nodeValue;
        val = val.replace(regText, match => `<span class="eruda-keyword">${match}</span>`);
        if (val === node.nodeValue) return;

        let $ret = $(document.createElement('div'));

        $ret.html(val);
        $ret.addClass('eruda-search-highlight-block');

        return $ret.get(0);
    });
}

function traverse(root, processor)
{
    let childNodes = root.childNodes;

    if (isErudaEl(root)) return;

    for (let i = 0, len = childNodes.length; i < len; i++)
    {
        let newNode = traverse(childNodes[i], processor);
        if (newNode) root.replaceChild(newNode, childNodes[i]);
    }

    return processor(root);
}

function loadPlugin(name)
{
    let globalName = 'eruda' + upperFirst(name);
    if (window[globalName]) return;

    loadJs(`//cdn.jsdelivr.net/npm/eruda-${name}@${pluginVersion[name]}`, isLoaded =>
    {
        if (!isLoaded || !window[globalName]) return logger.error('Fail to load plugin ' + name);

        emitter.emit(emitter.ADD, window[globalName]);
        emitter.emit(emitter.SHOW, name);
    });
}

let pluginVersion = {
    fps: '1.0.2',
    features: '1.0.2',
    timing: '1.1.0',
    memory: '1.0.1',
    code: '1.0.0'
};
<commit_msg>Dev: Update timing plugin version<commit_after>import logger from '../lib/logger';
import emitter from '../lib/emitter';
import {
    evalCss,
    Url,
    now,
    safeStorage,
    each,
    isStr,
    startWith,
    has,
    $,
    isErudaEl,
    upperFirst,
    loadJs
} from '../lib/util';

let style = null;

export default [
    {
        name: 'Border All',
        fn()
        {
            if (style)
            {
                evalCss.remove(style);
                style = null;
                return;
            }

            style = evalCss(borderCss);
        },
        desc: 'Add color borders to all elements'
    },
    {
        name: 'Refresh Page',
        fn()
        {
            let url = new Url();
            url.setQuery('timestamp', now());

            window.location.replace(url.toString());
        },
        desc: 'Add timestamp to url and refresh'
    },
    {
        name: 'Search Text',
        fn()
        {
            let keyword = prompt('Enter the text');

            search(keyword);
        },
        desc: 'Highlight given text on page'
    },
    {
        name: 'Edit Page',
        fn()
        {
            let body = document.body;

            body.contentEditable = body.contentEditable !== 'true';
        },
        desc: 'Toggle body contentEditable'
    },
    {
        name: 'Load Fps Plugin',
        fn()
        {
            loadPlugin('fps');
        },
        desc: 'Display page fps'
    },
    {
        name: 'Load Features Plugin',
        fn()
        {
            loadPlugin('features');
        },
        desc: 'Browser feature detections'
    },
    {
        name: 'Load Timing Plugin',
        fn()
        {
            loadPlugin('timing');
        },
        desc: 'Show performance and resource timing'
    },
    {
        name: 'Load Memory Plugin',
        fn()
        {
            loadPlugin('memory');
        },
        desc: 'Display memory'
    },
    {
        name: 'Load Code Plugin',
        fn()
        {
            loadPlugin('code');
        },
        desc: 'Edit and Run JavaScript'
    },
    {
        name: 'Restore Settings',
        fn()
        {
            let store = safeStorage('local');

            let data = JSON.parse(JSON.stringify(store));

            each(data, (val, key) =>
            {
                if (!isStr(val)) return;

                if (startWith(key, 'eruda')) store.removeItem(key);
            });

            window.location.reload();
        },
        desc: 'Restore defaults and reload'
    }
];

let borderCss = '',
    styleName = has(document.documentElement.style, 'outline') ? 'outline' : 'border',
    selector = 'html',
    colors = ['f5f5f5', 'dabb3a', 'abc1c7', '472936', 'c84941', '296dd1', '67adb4', '1ea061'];

each(colors, (color, idx) =>
{
    selector += (idx === 0) ? '>*:not([class^="eruda-"])' : '>*';

    borderCss += selector + `{${styleName}: 2px solid #${color} !important}`;
});

function search(text)
{
    let root = document.documentElement,
        regText = new RegExp(text, 'ig');

    traverse(root, node =>
    {
        let $node = $(node);

        if (!$node.hasClass('eruda-search-highlight-block')) return;

        return document.createTextNode($node.text());
    });

    traverse(root, node =>
    {
        if (node.nodeType !== 3) return;

        let val = node.nodeValue;
        val = val.replace(regText, match => `<span class="eruda-keyword">${match}</span>`);
        if (val === node.nodeValue) return;

        let $ret = $(document.createElement('div'));

        $ret.html(val);
        $ret.addClass('eruda-search-highlight-block');

        return $ret.get(0);
    });
}

function traverse(root, processor)
{
    let childNodes = root.childNodes;

    if (isErudaEl(root)) return;

    for (let i = 0, len = childNodes.length; i < len; i++)
    {
        let newNode = traverse(childNodes[i], processor);
        if (newNode) root.replaceChild(newNode, childNodes[i]);
    }

    return processor(root);
}

function loadPlugin(name)
{
    let globalName = 'eruda' + upperFirst(name);
    if (window[globalName]) return;

    loadJs(`//cdn.jsdelivr.net/npm/eruda-${name}@${pluginVersion[name]}`, isLoaded =>
    {
        if (!isLoaded || !window[globalName]) return logger.error('Fail to load plugin ' + name);

        emitter.emit(emitter.ADD, window[globalName]);
        emitter.emit(emitter.SHOW, name);
    });
}

let pluginVersion = {
    fps: '1.0.2',
    features: '1.0.2',
    timing: '1.1.1',
    memory: '1.0.1',
    code: '1.0.0'
};
<|endoftext|>


<commit_before>import 'regenerator-runtime';

import { transformSource } from '@nuclear/core';
import { app, ipcMain } from 'electron';
import logger from 'electron-timber';
import installExtension, {
  REACT_DEVELOPER_TOOLS,
  REDUX_DEVTOOLS
} from 'electron-devtools-installer';
import getPort from 'get-port';
import url from 'url';

import DownloadIpcCtrl from './ipc/download';
import LocalLibraryIpcCtrl from './ipc/localLibrary';
import PlayerIpcCtrl from './ipc/player';
import SettingsIpcCtrl from './ipc/settings';

import { trackSearch } from '../app/rest/youtube-search';
import AcousticId from './services/acousticId';
import Download from './services/download';
import HttpApi from './services/http';
import LocalLibrary from './services/localLibrary';
import Mpris from './services/mpris';
import Store from './services/store';
import Window from './services/window';
import * as platform from './services/platform';
import Container from './helpers/container';

let container;
const services = [
  { provide: 'acousticId', useClass: AcousticId },
  { provide: 'download', useClass: Download },
  { provide: 'httpApi', useClass: HttpApi },
  { provide: 'localLibrary', useClass: LocalLibrary },
  { provide: 'store', useClass: Store },
  { provide: 'window', useClass: Window },
  { provide: 'platform', useValue: platform },
  { provide: 'youtubeSearch', useValue: trackSearch },
  { provide: 'logger', useValue: logger },
  { provide: 'ipcLogger', useValue: logger.create({ name: 'ipc api' }) },
  { provide: 'httpLogger', useValue: logger.create({ name: 'http api' }) },
  { provide: 'mprisLogger', useValue: logger.create({ name: 'mpris' }) },
  { provide: 'mpris', useClass: platform.isLinux() ? Mpris : class EmptyClass{} }
];

const ipcControllers = [
  DownloadIpcCtrl,
  LocalLibraryIpcCtrl,
  PlayerIpcCtrl,
  SettingsIpcCtrl
];

app.on('ready', async () => {
  try {
    await Promise.all([
      installExtension(REACT_DEVELOPER_TOOLS),
      installExtension(REDUX_DEVTOOLS)
    ]);
    logger.log('devtools installed');
  } catch (err) {
    logger.warn('something fails while trying to install devtools');
  }

  app.transformSource = transformSource;

  try {
    const container = new Container({ ipcControllers, services }, { ipc: ipcMain });
    const store = container.resolve('store');
    const window = container.resolve('window');

    container.ipcListen();

    window.loadURL(
      url.format({
        pathname: 'localhost:8080',
        protocol: 'http:',
        slashes: true
      })
    );

    window.once('ready-to-show', () => {
      window.show();
      window.webContents.openDevTools();
    });

    const availablePort = await getPort({ port: getPort.makeRange(3000, 3100) });
    store.setOption('api.port', availablePort);
  } catch (err) {
    logger.error('something fail during app bootstrap');
    logger.error(err);

    return app.quit();
  }
});

app.on('window-all-closed', async () => {
  try {
    logger.log('All windows closed, quitting');
    const httpApi = container.resolve('httpApi');
    await httpApi.close();

    app.quit();
  } catch (err) {
    logger.error('something fail during app close');
    logger.error(err);
  }
});
<commit_msg>fix(dev): fix close event<commit_after>import 'regenerator-runtime';

import { transformSource } from '@nuclear/core';
import { app, ipcMain } from 'electron';
import logger from 'electron-timber';
import installExtension, {
  REACT_DEVELOPER_TOOLS,
  REDUX_DEVTOOLS
} from 'electron-devtools-installer';
import getPort from 'get-port';
import url from 'url';

import DownloadIpcCtrl from './ipc/download';
import LocalLibraryIpcCtrl from './ipc/localLibrary';
import PlayerIpcCtrl from './ipc/player';
import SettingsIpcCtrl from './ipc/settings';

import { trackSearch } from '../app/rest/youtube-search';
import AcousticId from './services/acousticId';
import Download from './services/download';
import HttpApi from './services/http';
import LocalLibrary from './services/localLibrary';
import Mpris from './services/mpris';
import Store from './services/store';
import Window from './services/window';
import * as platform from './services/platform';
import Container from './helpers/container';

let container;
const services = [
  { provide: 'acousticId', useClass: AcousticId },
  { provide: 'download', useClass: Download },
  { provide: 'httpApi', useClass: HttpApi },
  { provide: 'localLibrary', useClass: LocalLibrary },
  { provide: 'store', useClass: Store },
  { provide: 'window', useClass: Window },
  { provide: 'platform', useValue: platform },
  { provide: 'youtubeSearch', useValue: trackSearch },
  { provide: 'logger', useValue: logger },
  { provide: 'ipcLogger', useValue: logger.create({ name: 'ipc api' }) },
  { provide: 'httpLogger', useValue: logger.create({ name: 'http api' }) },
  { provide: 'mprisLogger', useValue: logger.create({ name: 'mpris' }) },
  { provide: 'mpris', useClass: platform.isLinux() ? Mpris : class EmptyClass{} }
];

const ipcControllers = [
  DownloadIpcCtrl,
  LocalLibraryIpcCtrl,
  PlayerIpcCtrl,
  SettingsIpcCtrl
];

app.on('ready', async () => {
  try {
    await Promise.all([
      installExtension(REACT_DEVELOPER_TOOLS),
      installExtension(REDUX_DEVTOOLS)
    ]);
    logger.log('devtools installed');
  } catch (err) {
    logger.warn('something fails while trying to install devtools');
  }

  app.transformSource = transformSource;

  try {
    container = new Container({ ipcControllers, services }, { ipc: ipcMain });
    const store = container.resolve('store');
    const window = container.resolve('window');

    container.ipcListen();

    window.loadURL(
      url.format({
        pathname: 'localhost:8080',
        protocol: 'http:',
        slashes: true
      })
    );

    window.once('ready-to-show', () => {
      window.show();
      window.webContents.openDevTools();
    });

    const availablePort = await getPort({ port: getPort.makeRange(3000, 3100) });
    store.setOption('api.port', availablePort);
  } catch (err) {
    logger.error('something fail during app bootstrap');
    logger.error(err);

    return app.quit();
  }
});

app.on('window-all-closed', async () => {
  try {
    logger.log('All windows closed, quitting');
    const httpApi = container.resolve('httpApi');
    await httpApi.close();

    app.quit();
  } catch (err) {
    logger.error('something fail during app close');
    logger.error(err);
  }
});
<|endoftext|>


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

function hbsHelpers(hbs) {
  return hbs.create({
    defaultLayout:'layout',
    helpers: {
      section: function(name, options){
        if(!this._sections) this._sections = {};
        this._sections[name] = options.fn(this);
        return null;
      },
      dizNome: function() {
        return moment().format('YYYY-MM-DD hh:mm:ss:SSS')
      },
      json: function(obj) {
        return JSON.stringify(obj)
      },
      inc: function(value) {
        return value + 1
      },
      setSelected: function(value, unitList) {
        return (value === unitList) ? 'selected' : ''
      },
      convBoolToHuman: function(value) {
        //console.log('convBoolToHuman' + value);
        return (parseInt(value) === 1) ? 'Sim/Yes' : 'Nāo/No'
      }
    }
  });
}

module.exports = hbsHelpers;
<commit_msg>Add 2 function, pad and totitlecase<commit_after>const moment = require('moment')

function hbsHelpers(hbs) {
  return hbs.create({
    defaultLayout:'layout',
    helpers: {
      section: function(name, options){
        if(!this._sections) this._sections = {};
        this._sections[name] = options.fn(this);
        return null;
      },
      dizNome: function() {
        return moment().format('YYYY-MM-DD hh:mm:ss:SSS')
      },
      json: function(obj) {
        return JSON.stringify(obj)
      },
      inc: function(value) {
        return value + 1
      },
      setSelected: function(value, unitList) {
        return (value === unitList) ? 'selected' : ''
      },
      convBoolToHuman: function(value) {
        //console.log('convBoolToHuman' + value);
        return (parseInt(value) === 1) ? 'Sim/Yes' : 'Nāo/No'
      },
      pad: function(n, width, z) {
        z = z || '0';
        n = n + '';
        return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
      },
      toTitleCase: function(n, width, z) {
        return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
      }
    }
  });
}

module.exports = hbsHelpers;
<|endoftext|>