text:
///import core
///commands 全屏
///commandsName FullScreen
///commandsTitle  全屏
(function () {
    var utils = baidu.editor.utils,
        uiUtils = baidu.editor.ui.uiUtils,
        UIBase = baidu.editor.ui.UIBase,
        domUtils = baidu.editor.dom.domUtils;
    var nodeStack = [];

    function EditorUI(options) {
        this.initOptions(options);
        this.initEditorUI();
    }

    EditorUI.prototype = {
        uiName:'editor',
        initEditorUI:function () {
            this.editor.ui = this;
            this._dialogs = {};
            this.initUIBase();
            this._initToolbars();
            var editor = this.editor,
                me = this;

            editor.addListener('ready', function () {
                //提供getDialog方法
                editor.getDialog = function (name) {
                    return editor.ui._dialogs[name + "Dialog"];
                };
                domUtils.on(editor.window, 'scroll', function (evt) {
                    baidu.editor.ui.Popup.postHide(evt);
                });
                //提供编辑器实时宽高(全屏时宽高不变化)
                editor.ui._actualFrameWidth = editor.options.initialFrameWidth;

                UE.browser.ie && UE.browser.version === 6 && editor.container.ownerDocument.execCommand("BackgroundImageCache", false, true);

                //display bottom-bar label based on config
                if (editor.options.elementPathEnabled) {
                    editor.ui.getDom('elementpath').innerHTML = '
' + editor.getLang("elementPathTip") + ':
';
                }
                if (editor.options.wordCount) {
                    function countFn() {
                        setCount(editor,me);
                        domUtils.un(editor.document, "click", arguments.callee);
                    }
                    domUtils.on(editor.document, "click", countFn);
                    editor.ui.getDom('wordcount').innerHTML = editor.getLang("wordCountTip");
                }
                editor.ui._scale();
                if (editor.options.scaleEnabled) {
                    if (editor.autoHeightEnabled) {
                        editor.disableAutoHeight();
                    }
                    me.enableScale();
                } else {
                    me.disableScale();
                }
                if (!editor.options.elementPathEnabled && !editor.options.wordCount && !editor.options.scaleEnabled) {
                    editor.ui.getDom('elementpath').style.display = "none";
                    editor.ui.getDom('wordcount').style.display = "none";
                    editor.ui.getDom('scale').style.display = "none";
                }

                if (!editor.selection.isFocus())return;
                editor.fireEvent('selectionchange', false, true);

            });

            editor.addListener('mousedown', function (t, evt) {
                var el = evt.target || evt.srcElement;
                baidu.editor.ui.Popup.postHide(evt, el);
                baidu.editor.ui.ShortCutMenu.postHide(evt);

            });
            editor.addListener("delcells", function () {
                if (UE.ui['edittip']) {
                    new UE.ui['edittip'](editor);
                }
                editor.getDialog('edittip').open();
            });

            var pastePop, isPaste = false, timer;
            editor.addListener("afterpaste", function () {
                if(editor.queryCommandState('pasteplain'))
                    return;
                if(baidu.editor.ui.PastePicker){
                    pastePop = new baidu.editor.ui.Popup({
                        content:new baidu.editor.ui.PastePicker({editor:editor}),
                        editor:editor,
                        className:'edui-wordpastepop'
                    });
                    pastePop.render();
                }
                isPaste = true;
            });

            editor.addListener("afterinserthtml", function () {
                clearTimeout(timer);
                timer = setTimeout(function () {
                    if (pastePop && (isPaste || editor.ui._isTransfer)) {
                        if(pastePop.isHidden()){
                            var span = domUtils.createElement(editor.document, 'span', {
                                    'style':"line-height:0px;",
                                    'innerHTML':'\ufeff'
                                }),
                                range = editor.selection.getRange();
                            range.insertNode(span);
                            var tmp= getDomNode(span, 'firstChild', 'previousSibling');
                            tmp && pastePop.showAnchor(tmp.nodeType == 3 ? tmp.parentNode : tmp);
                            domUtils.remove(span);
                        }else{
                            pastePop.show();
                        }
                        delete editor.ui._isTransfer;
                        isPaste = false;
                    }
                }, 200)
            });
            editor.addListener('contextmenu', function (t, evt) {
                baidu.editor.ui.Popup.postHide(evt);
            });
            editor.addListener('keydown', function (t, evt) {
                if (pastePop)    pastePop.dispose(evt);
                var keyCode = evt.keyCode || evt.which;
                if(evt.altKey&&keyCode==90){
                    UE.ui.buttons['fullscreen'].onclick();
                }
            });
            editor.addListener('wordcount', function (type) {
                setCount(this,me);
            });
            function setCount(editor,ui) {
                editor.setOpt({
                    wordCount:true,
                    maximumWords:10000,
                    wordCountMsg:editor.options.wordCountMsg || editor.getLang("wordCountMsg"),
                    wordOverFlowMsg:editor.options.wordOverFlowMsg || editor.getLang("wordOverFlowMsg")
                });
                var opt = editor.options,
                    max = opt.maximumWords,
                    msg = opt.wordCountMsg ,
                    errMsg = opt.wordOverFlowMsg,
                    countDom = ui.getDom('wordcount');
                if (!opt.wordCount) {
                    return;
                }
                var count = editor.getContentLength(true);
                if (count > max) {
                    countDom.innerHTML = errMsg;
                    editor.fireEvent("wordcountoverflow");
                } else {
                    countDom.innerHTML = msg.replace("{#leave}", max - count).replace("{#count}", count);
                }
            }

            editor.addListener('selectionchange', function () {
                if (editor.options.elementPathEnabled) {
                    me[(editor.queryCommandState('elementpath') == -1 ? 'dis' : 'en') + 'ableElementPath']()
                }
                if (editor.options.scaleEnabled) {
                    me[(editor.queryCommandState('scale') == -1 ? 'dis' : 'en') + 'ableScale']();

                }
            });
            var popup = new baidu.editor.ui.Popup({
                editor:editor,
                content:'',
                className:'edui-bubble',
                _onEditButtonClick:function () {
                    this.hide();
                    editor.ui._dialogs.linkDialog.open();
                },
                _onImgEditButtonClick:function (name) {
                    this.hide();
                    editor.ui._dialogs[name] && editor.ui._dialogs[name].open();

                },
                _onImgSetFloat:function (value) {
                    this.hide();
                    editor.execCommand("imagefloat", value);

                },
                _setIframeAlign:function (value) {
                    var frame = popup.anchorEl;
                    var newFrame = frame.cloneNode(true);
                    switch (value) {
                        case -2:
                            newFrame.setAttribute("align", "");
                            break;
                        case -1:
                            newFrame.setAttribute("align", "left");
                            break;
                        case 1:
                            newFrame.setAttribute("align", "right");
                            break;
                    }
                    frame.parentNode.insertBefore(newFrame, frame);
                    domUtils.remove(frame);
                    popup.anchorEl = newFrame;
                    popup.showAnchor(popup.anchorEl);
                },
                _updateIframe:function () {
                    var frame = editor._iframe = popup.anchorEl;
                    if(domUtils.hasClass(frame, 'ueditor_baidumap')) {
                        editor.selection.getRange().selectNode(frame).select();
                        editor.ui._dialogs.mapDialog.open();
                        popup.hide();
                    } else {
                        editor.ui._dialogs.insertframeDialog.open();
                        popup.hide();
                    }
                },
                _onRemoveButtonClick:function (cmdName) {
                    editor.execCommand(cmdName);
                    this.hide();
                },
                queryAutoHide:function (el) {
                    if (el && el.ownerDocument == editor.document) {
                        if (el.tagName.toLowerCase() == 'img' || domUtils.findParentByTagName(el, 'a', true)) {
                            return el !== popup.anchorEl;
                        }
                    }
                    return baidu.editor.ui.Popup.prototype.queryAutoHide.call(this, el);
                }
            });
            popup.render();
            if (editor.options.imagePopup) {
                editor.addListener('mouseover', function (t, evt) {
                    evt = evt || window.event;
                    var el = evt.target || evt.srcElement;
                    if (editor.ui._dialogs.insertframeDialog && /iframe/ig.test(el.tagName)) {
                        var html = popup.formatHtml(
                            '<nobr>' + editor.getLang("property") + ': ' + editor.getLang("default") + '  ' + editor.getLang("justifyleft") + '  ' + editor.getLang("justifyright") + '  ' +
                                ' ' + editor.getLang("modify") + '</nobr>');
                        if (html) {
                            popup.getDom('content').innerHTML = html;
                            popup.anchorEl = el;
                            popup.showAnchor(popup.anchorEl);
                        } else {
                            popup.hide();
                        }
                    }
                });
                editor.addListener('selectionchange', function (t, causeByUi) {
                    if (!causeByUi) return;
                    var html = '', str = "",
                        img = editor.selection.getRange().getClosedNode(),
                        dialogs = editor.ui._dialogs;
                    if (img && img.tagName == 'IMG') {
                        var dialogName = 'insertimageDialog';
                        if (img.className.indexOf("edui-faked-video") != -1 || img.className.indexOf("edui-upload-video") != -1) {
                            dialogName = "insertvideoDialog"
                        }
                        if (img.className.indexOf("edui-faked-webapp") != -1) {
                            dialogName = "webappDialog"
                        }
                        if (img.src.indexOf("http://api.map.baidu.com") != -1) {
                            dialogName = "mapDialog"
                        }
                        if (img.className.indexOf("edui-faked-music") != -1) {
                            dialogName = "musicDialog"
                        }
                        if (img.src.indexOf("http://maps.google.com/maps/api/staticmap") != -1) {
                            dialogName = "gmapDialog"
                        }
                        if (img.getAttribute("anchorname")) {
                            dialogName = "anchorDialog";
                            html = popup.formatHtml(
                                '<nobr>' + editor.getLang("property") + ': ' + editor.getLang("modify") + '  ' +
                                    '' + editor.getLang("delete") + '</nobr>');
                        }
                        if (img.getAttribute("word_img")) {
                            //todo 放到dialog去做查询
                            editor.word_img = [img.getAttribute("word_img")];
                            dialogName = "wordimageDialog"
                        }
                        if(domUtils.hasClass(img, 'loadingclass') || domUtils.hasClass(img, 'loaderrorclass')) {
                            dialogName = "";
                        }
                        if (!dialogs[dialogName]) {
                            return;
                        }
                        str = '<nobr>' + editor.getLang("property") + ': '+
                            '' + editor.getLang("default") + '  ' +
                            '' + editor.getLang("justifyleft") + '  ' +
                            '' + editor.getLang("justifyright") + '  ' +
                            '' + editor.getLang("justifycenter") + '  '+
                            '' + editor.getLang("modify") + '</nobr>';

                        !html && (html = popup.formatHtml(str))

                    }
                    if (editor.ui._dialogs.linkDialog) {
                        var link = editor.queryCommandValue('link');
                        var url;
                        if (link && (url = (link.getAttribute('_href') || link.getAttribute('href', 2)))) {
                            var txt = url;
                            if (url.length > 30) {
                                txt = url.substring(0, 20) + "...";
                            }
                            if (html) {
                                html += '

'
                            }
                            html += popup.formatHtml(
                                '<nobr>' + editor.getLang("anthorMsg") + ': ' + txt + '' +
                                    ' ' + editor.getLang("modify") + '' +
                                    '  ' + editor.getLang("clear") + '</nobr>');
                            popup.showAnchor(link);
                        }
                    }

                    if (html) {
                        popup.getDom('content').innerHTML = html;
                        popup.anchorEl = img || link;
                        popup.showAnchor(popup.anchorEl);
                    } else {
                        popup.hide();
                    }
                });
            }

        },
        _initToolbars:function () {
            var editor = this.editor;
            var toolbars = this.toolbars || [];
            var toolbarUis = [];
            for (var i = 0; i < toolbars.length; i++) {
                var toolbar = toolbars[i];
                var toolbarUi = new baidu.editor.ui.Toolbar({theme:editor.options.theme});
                for (var j = 0; j < toolbar.length; j++) {
                    var toolbarItem = toolbar[j];
                    var toolbarItemUi = null;
                    if (typeof toolbarItem == 'string') {
                        toolbarItem = toolbarItem.toLowerCase();
                        if (toolbarItem == '|') {
                            toolbarItem = 'Separator';
                        }
                        if(toolbarItem == '||'){
                            toolbarItem = 'Breakline';
                        }
                        if (baidu.editor.ui[toolbarItem]) {
                            toolbarItemUi = new baidu.editor.ui[toolbarItem](editor);
                        }

                        //fullscreen这里单独处理一下,放到首行去
                        if (toolbarItem == 'fullscreen') {
                            if (toolbarUis && toolbarUis[0]) {
                                toolbarUis[0].items.splice(0, 0, toolbarItemUi);
                            } else {
                                toolbarItemUi && toolbarUi.items.splice(0, 0, toolbarItemUi);
                            }

                            continue;

                        }
                    } else {
                        toolbarItemUi = toolbarItem;
                    }
                    if (toolbarItemUi && toolbarItemUi.id) {

                        toolbarUi.add(toolbarItemUi);
                    }
                }
                toolbarUis[i] = toolbarUi;
            }

            //接受外部定制的UI

            utils.each(UE._customizeUI,function(obj,key){
                var itemUI,index;
                if(obj.id && obj.id != editor.key){
                   return false;
                }
                itemUI = obj.execFn.call(editor,editor,key);
                if(itemUI){
                    index = obj.index;
                    if(index === undefined){
                        index = toolbarUi.items.length;
                    }
                    toolbarUi.add(itemUI,index)
                }
            });

            this.toolbars = toolbarUis;
        },
        getHtmlTpl:function () {
            return '
' +
                '
' +
                (this.toolbars.length ?
                    '

' +
                        this.renderToolbarBoxHtml() +
                        '

' : '') +
                '
' +
                '
' + this.editor.getLang("clickToUpload") + '
' +
                '
x
' +
                '

' +
                '

' +
                '
' +
                '

' +
                '
' +
                '
' +
                '
' +
                //modify wdcount by matao
                '

' +
                '	' +
                '	' +
                '

	' +
                '

' +
                '

' +
                '
';
        },
        showWordImageDialog:function () {
            this._dialogs['wordimageDialog'].open();
        },
        renderToolbarBoxHtml:function () {
            var buff = [];
            for (var i = 0; i < this.toolbars.length; i++) {
                buff.push(this.toolbars[i].renderHtml());
            }
            return buff.join('');
        },
        setFullScreen:function (fullscreen) {

            var editor = this.editor,
                container = editor.container.parentNode.parentNode;
            if (this._fullscreen != fullscreen) {
                this._fullscreen = fullscreen;
                this.editor.fireEvent('beforefullscreenchange', fullscreen);
                if (baidu.editor.browser.gecko) {
                    var bk = editor.selection.getRange().createBookmark();
                }
                if (fullscreen) {
                    while (container.tagName != "BODY") {
                        var position = baidu.editor.dom.domUtils.getComputedStyle(container, "position");
                        nodeStack.push(position);
                        container.style.position = "static";
                        container = container.parentNode;
                    }
                    this._bakHtmlOverflow = document.documentElement.style.overflow;
                    this._bakBodyOverflow = document.body.style.overflow;
                    this._bakAutoHeight = this.editor.autoHeightEnabled;
                    this._bakScrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);

                    this._bakEditorContaninerWidth = editor.iframe.parentNode.offsetWidth;
                    if (this._bakAutoHeight) {
                        //当全屏时不能执行自动长高
                        editor.autoHeightEnabled = false;
                        this.editor.disableAutoHeight();
                    }

                    document.documentElement.style.overflow = 'hidden';
                    //修复,滚动条不收起的问题

                    window.scrollTo(0,window.scrollY);
                    this._bakCssText = this.getDom().style.cssText;
                    this._bakCssText1 = this.getDom('iframeholder').style.cssText;
                    editor.iframe.parentNode.style.width = '';
                    this._updateFullScreen();
                } else {
                    while (container.tagName != "BODY") {
                        container.style.position = nodeStack.shift();
                        container = container.parentNode;
                    }
                    this.getDom().style.cssText = this._bakCssText;
                    this.getDom('iframeholder').style.cssText = this._bakCssText1;
                    if (this._bakAutoHeight) {
                        editor.autoHeightEnabled = true;
                        this.editor.enableAutoHeight();
                    }

                    document.documentElement.style.overflow = this._bakHtmlOverflow;
                    document.body.style.overflow = this._bakBodyOverflow;
                    editor.iframe.parentNode.style.width = this._bakEditorContaninerWidth + 'px';
                    window.scrollTo(0, this._bakScrollTop);
                }
                if (browser.gecko && editor.body.contentEditable === 'true') {
                    var input = document.createElement('input');
                    document.body.appendChild(input);
                    editor.body.contentEditable = false;
                    setTimeout(function () {
                        input.focus();
                        setTimeout(function () {
                            editor.body.contentEditable = true;
                            editor.fireEvent('fullscreenchanged', fullscreen);
                            editor.selection.getRange().moveToBookmark(bk).select(true);
                            baidu.editor.dom.domUtils.remove(input);
                            fullscreen && window.scroll(0, 0);
                        }, 0)
                    }, 0)
                }

                if(editor.body.contentEditable === 'true'){
                    this.editor.fireEvent('fullscreenchanged', fullscreen);
                    this.triggerLayout();
                }

            }
        },
        _updateFullScreen:function () {
            if (this._fullscreen) {
                var vpRect = uiUtils.getViewportRect();
                this.getDom().style.cssText = 'border:0;position:absolute;left:0;top:' + (this.editor.options.topOffset || 0) + 'px;width:' + vpRect.width + 'px;height:' + vpRect.height + 'px;z-index:' + (this.getDom().style.zIndex * 1 + 100);
                uiUtils.setViewportOffset(this.getDom(), { left:0, top:this.editor.options.topOffset || 0 });
                this.editor.setHeight(vpRect.height - this.getDom('toolbarbox').offsetHeight - this.getDom('bottombar').offsetHeight - (this.editor.options.topOffset || 0),true);
                //不手动调一下,会导致全屏失效
                if(browser.gecko){
                    try{
                        window.onresize();
                    }catch(e){

                    }

                }
            }
        },
        _updateElementPath:function () {
            var bottom = this.getDom('elementpath'), list;
            if (this.elementPathEnabled && (list = this.editor.queryCommandValue('elementpath'))) {

                var buff = [];
                for (var i = 0, ci; ci = list[i]; i++) {
                    buff[i] = this.formatHtml('' + ci + '');
                }
                bottom.innerHTML = '
' + this.editor.getLang("elementPathTip") + ': ' + buff.join(' > ') + '
';

            } else {
                bottom.style.display = 'none'
            }
        },
        disableElementPath:function () {
            var bottom = this.getDom('elementpath');
            bottom.innerHTML = '';
            bottom.style.display = 'none';
            this.elementPathEnabled = false;

        },
        enableElementPath:function () {
            var bottom = this.getDom('elementpath');
            bottom.style.display = '';
            this.elementPathEnabled = true;
            this._updateElementPath();
        },
        _scale:function () {
            var doc = document,
                editor = this.editor,
                editorHolder = editor.container,
                editorDocument = editor.document,
                toolbarBox = this.getDom("toolbarbox"),
                bottombar = this.getDom("bottombar"),
                scale = this.getDom("scale"),
                scalelayer = this.getDom("scalelayer");

            var isMouseMove = false,
                position = null,
                minEditorHeight = 0,
                minEditorWidth = editor.options.minFrameWidth,
                pageX = 0,
                pageY = 0,
                scaleWidth = 0,
                scaleHeight = 0;

            function down() {
                position = domUtils.getXY(editorHolder);

                if (!minEditorHeight) {
                    minEditorHeight = editor.options.minFrameHeight + toolbarBox.offsetHeight + bottombar.offsetHeight;
                }

                scalelayer.style.cssText = "position:absolute;left:0;display:;top:0;background-color:#41ABFF;opacity:0.4;filter: Alpha(opacity=40);width:" + editorHolder.offsetWidth + "px;height:"
                    + editorHolder.offsetHeight + "px;z-index:" + (editor.options.zIndex + 1);

                domUtils.on(doc, "mousemove", move);
                domUtils.on(editorDocument, "mouseup", up);
                domUtils.on(doc, "mouseup", up);
            }

            var me = this;
            //by xuheng 全屏时关掉缩放
            this.editor.addListener('fullscreenchanged', function (e, fullScreen) {
                if (fullScreen) {
                    me.disableScale();

                } else {
                    if (me.editor.options.scaleEnabled) {
                        me.enableScale();
                        var tmpNode = me.editor.document.createElement('span');
                        me.editor.body.appendChild(tmpNode);
                        me.editor.body.style.height = Math.max(domUtils.getXY(tmpNode).y, me.editor.iframe.offsetHeight - 20) + 'px';
                        domUtils.remove(tmpNode)
                    }
                }
            });
            function move(event) {
                clearSelection();
                var e = event || window.event;
                pageX = e.pageX || (doc.documentElement.scrollLeft + e.clientX);
                pageY = e.pageY || (doc.documentElement.scrollTop + e.clientY);
                scaleWidth = pageX - position.x;
                scaleHeight = pageY - position.y;

                if (scaleWidth >= minEditorWidth) {
                    isMouseMove = true;
                    scalelayer.style.width = scaleWidth + 'px';
                }
                if (scaleHeight >= minEditorHeight) {
                    isMouseMove = true;
                    scalelayer.style.height = scaleHeight + "px";
                }
            }

            function up() {
                if (isMouseMove) {
                    isMouseMove = false;
                    editor.ui._actualFrameWidth = scalelayer.offsetWidth - 2;
                    editorHolder.style.width = editor.ui._actualFrameWidth + 'px';

                    editor.setHeight(scalelayer.offsetHeight - bottombar.offsetHeight - toolbarBox.offsetHeight - 2,true);
                }
                if (scalelayer) {
                    scalelayer.style.display = "none";
                }
                clearSelection();
                domUtils.un(doc, "mousemove", move);
                domUtils.un(editorDocument, "mouseup", up);
                domUtils.un(doc, "mouseup", up);
            }

            function clearSelection() {
                if (browser.ie)
                    doc.selection.clear();
                else
                    window.getSelection().removeAllRanges();
            }

            this.enableScale = function () {
                //trace:2868
                if (editor.queryCommandState("source") == 1)    return;
                scale.style.display = "";
                this.scaleEnabled = true;
                domUtils.on(scale, "mousedown", down);
            };
            this.disableScale = function () {
                scale.style.display = "none";
                this.scaleEnabled = false;
                domUtils.un(scale, "mousedown", down);
            };
        },
        isFullScreen:function () {
            return this._fullscreen;
        },
        postRender:function () {
            UIBase.prototype.postRender.call(this);
            for (var i = 0; i < this.toolbars.length; i++) {
                this.toolbars[i].postRender();
            }
            var me = this;
            var timerId,
                domUtils = baidu.editor.dom.domUtils,
                updateFullScreenTime = function () {
                    clearTimeout(timerId);
                    timerId = setTimeout(function () {
                        me._updateFullScreen();
                    });
                };
            domUtils.on(window, 'resize', updateFullScreenTime);

            me.addListener('destroy', function () {
                domUtils.un(window, 'resize', updateFullScreenTime);
                clearTimeout(timerId);
            })
        },
        showToolbarMsg:function (msg, flag) {
            this.getDom('toolbarmsg_label').innerHTML = msg;
            this.getDom('toolbarmsg').style.display = '';
            //
            if (!flag) {
                var w = this.getDom('upload_dialog');
                w.style.display = 'none';
            }
        },
        hideToolbarMsg:function () {
            this.getDom('toolbarmsg').style.display = 'none';
        },
        mapUrl:function (url) {
            return url ? url.replace('~/', this.editor.options.UEDITOR_HOME_URL || '') : ''
        },
        triggerLayout:function () {
            var dom = this.getDom();
            if (dom.style.zoom == '1') {
                dom.style.zoom = '100%';
            } else {
                dom.style.zoom = '1';
            }
        }
    };
    utils.inherits(EditorUI, baidu.editor.ui.UIBase);

    var instances = {};

    UE.ui.Editor = function (options) {
        var editor = new UE.Editor(options);
        editor.options.editor = editor;
        utils.loadFile(document, {
            href:editor.options.themePath + editor.options.theme + "/_css/ueditor.css",
            tag:"link",
            type:"text/css",
            rel:"stylesheet"
        });

        var oldRender = editor.render;
        editor.render = function (holder) {
            if (holder.constructor === String) {
                editor.key = holder;
                instances[holder] = editor;
            }
            utils.domReady(function () {
                editor.langIsReady ? renderUI() : editor.addListener("langReady", renderUI);
                function renderUI() {
                    editor.setOpt({
                        labelMap:editor.options.labelMap || editor.getLang('labelMap')
                    });
                    new EditorUI(editor.options);
                    if (holder) {
                        if (holder.constructor === String) {
                            holder = document.getElementById(holder);
                        }
                        holder && holder.getAttribute('name') && ( editor.options.textarea = holder.getAttribute('name'));
                        if (holder && /script|textarea/ig.test(holder.tagName)) {
                            var newDiv = document.createElement('div');
                            holder.parentNode.insertBefore(newDiv, holder);
                            var cont = holder.value || holder.innerHTML;
                            editor.options.initialContent = /^[\t\r\n ]*$/.test(cont) ? editor.options.initialContent :
                                cont.replace(/>[\n\r\t]+([ ]{4})+/g, '>')
                                    .replace(/[\n\r\t]+([ ]{4})+</g, '<')
                                    .replace(/>[\n\r\t]+</g, '><');
                            holder.className && (newDiv.className = holder.className);
                            holder.style.cssText && (newDiv.style.cssText = holder.style.cssText);
                            if (/textarea/i.test(holder.tagName)) {
                                editor.textarea = holder;
                                editor.textarea.style.display = 'none';

                            } else {
                                holder.parentNode.removeChild(holder);

                            }
                            if(holder.id){
                                newDiv.id = holder.id;
                                domUtils.removeAttributes(holder,'id');
                            }
                            holder = newDiv;
                            holder.innerHTML = '';
                        }

                    }
                    domUtils.addClass(holder, "edui-" + editor.options.theme);
                    editor.ui.render(holder);
                    var opt = editor.options;
                    //给实例添加一个编辑器的容器引用
                    editor.container = editor.ui.getDom();
                    var parents = domUtils.findParents(holder,true);
                    var displays = [];
                    for(var i = 0 ,ci;ci=parents[i];i++){
                        displays[i] = ci.style.display;
                        ci.style.display = 'block'
                    }
                    if (opt.initialFrameWidth) {
                        opt.minFrameWidth = opt.initialFrameWidth;
                    } else {
                        opt.minFrameWidth = opt.initialFrameWidth = holder.offsetWidth;
                        var styleWidth = holder.style.width;
                        if(/%$/.test(styleWidth)) {
                            opt.initialFrameWidth = styleWidth;
                        }
                    }
                    if (opt.initialFrameHeight) {
                        opt.minFrameHeight = opt.initialFrameHeight;
                    } else {
                        opt.initialFrameHeight = opt.minFrameHeight = holder.offsetHeight;
                    }
                    for(var i = 0 ,ci;ci=parents[i];i++){
                        ci.style.display =  displays[i]
                    }
                    //编辑器最外容器设置了高度,会导致,编辑器不占位
                    //todo 先去掉,没有找到原因
                    if(holder.style.height){
                        holder.style.height = ''
                    }
                    editor.container.style.width = opt.initialFrameWidth + (/%$/.test(opt.initialFrameWidth) ? '' : 'px');
                    editor.container.style.zIndex = opt.zIndex;
                    oldRender.call(editor, editor.ui.getDom('iframeholder'));
                    editor.fireEvent("afteruiready");
                }
            })
        };
        return editor;
    };

    /**
     * @file
     * @name UE
     * @short UE
     * @desc UEditor的顶部命名空间
     */
    /**
     * @name getEditor
     * @since 1.2.4+
     * @grammar UE.getEditor(id,[opt])  =>  Editor实例
     * @desc 提供一个全局的方法得到编辑器实例
     *
     * * ''id''  放置编辑器的容器id, 如果容器下的编辑器已经存在,就直接返回
     * * ''opt'' 编辑器的可选参数
     * @example
     *  UE.getEditor('containerId',{onready:function(){//创建一个编辑器实例
     *      this.setContent('hello')
     *  }});
     *  UE.getEditor('containerId'); //返回刚创建的实例
     *
     */
    UE.getEditor = function (id, opt) {
        var editor = instances[id];
        if (!editor) {
            editor = instances[id] = new UE.ui.Editor(opt);
            editor.render(id);
        }
        return editor;
    };

    UE.delEditor = function (id) {
        var editor;
        if (editor = instances[id]) {
            editor.key && editor.destroy();
            delete instances[id]
        }
    };

    UE.registerUI = function(uiName,fn,index,editorId){
        utils.each(uiName.split(/\s+/), function (name) {
            UE._customizeUI[name] = {
                id : editorId,
                execFn:fn,
                index:index
            };
        })

    }

})();


text:
'''
(Time) delays to location conversion functions

Long Le <longle1@illinois.edu>
University of Illinois
'''
import numpy as np
import matplotlib.pyplot as plt
import multiprocessing
from joblib import Parallel, delayed

cSound = 340 # speed of sound m/s

def delay2loc_grad(micsloc,meas_delayMat,mu=1.,debug=False):
    # from delays to location using gradient descent
    #
    # micsloc: Mx3, 3-D locations of M mics
    # meas_delayMat: MxM, measured delay matrix
    # mu: gradient step size
    #
    # loc: 1x3, output location of the sound source

    M,N = np.shape(micsloc)
    nIter = 0

    locNow = np.mean(micsloc,axis=0)
    errNow = errEst(locNow,micsloc,meas_delayMat)
    grad = gradEst(locNow,errNow,micsloc,meas_delayMat)
    while True:
        # backtrack line search
        # TODO: fixed/optimized this gradient descent line search
        while True:
            # gradient descent update
            locNext = locNow-mu*grad
            #print('===== locNext = %s, locNow = %s, mu = %s, grad = %s' % (locNext,locNow,mu,grad))
            errNext = errEst(locNext,micsloc,meas_delayMat)
            if errNext <= errNow:
                locNow = locNext
                errNow = errNext
                grad = gradEst(locNow,errNow,micsloc,meas_delayMat)
                break
            else:
                mu = mu/2
                if mu == 0.:
                    break

        # check terminal condition
        nIter += 1
        if debug:
            print('nIter = %s, mu = %s, grad = %s, loc = %s, err = %s' % \
                    (nIter,mu,grad,locNow,errNow))
        if nIter >= 1e3:
            if debug:
                print('Done! Max # of iterations reached')
            break
        if np.linalg.norm(grad) < 1e-6:
            if debug:
                print('Done! Gradient is sufficiently small')
            break
        if mu < 1e-6:
            if debug:
                print('Done! Stepsize is sufficiently small')
            break

    return locNow,errNow,grad

def gradEst(loc,err,micsloc,meas_delayMat,lam=[.5,.25,.25]):
    # interior-point optimization
    # gradient of the ojective and the logarithmic barrier functions
    # of the following constraints
    # |loc-micsCen| <= 100,
    # i.e. the solution should be within the 100 m radius
    # z >= 0
    # i.e. the height must be positive
    gradStep = .1 # meter
    N = len(loc)
    grad = np.zeros(N)
    micsCen = np.mean(micsloc,axis=0) # micArray centroid

    for k in range(N):
        locNext = np.array(loc); locNext[k] += gradStep
        errNext = errEst(locNext,micsloc,meas_delayMat)

        d = np.linalg.norm(loc-micsCen)
        dNext = np.linalg.norm(locNext-micsCen)

        z = loc[-1]
        zNext = locNext[-1]

        grad[k] = (errNext-err)/gradStep\
                +lam[0]/(100-d)*(dNext-d)/gradStep\
                -lam[1]/z*(zNext-z)/gradStep\
                +lam[2]/(100-z)*(zNext-z)/gradStep

    return grad

def errEst(loc,micsloc,meas_delayMat):
    # estimate error at a location
    # given measured delays and locations of array's mics

    delays,_ = estDelay(micsloc,loc)
    delayMat = toMat(delays)
    err = 0.5*np.sum(np.abs(delayMat-meas_delayMat)) # total error in delay is the metric to minimize

    return err

def toMat(delays):
    # convert from delays vector to matrix
    M = len(delays)
    delayMat = np.dot(np.ones((M,1)),np.expand_dims(delays,axis=0))-\
            np.dot(np.expand_dims(delays,axis=1),np.ones((1,M)))

    return delayMat

def estDelay(micsloc,srcloc):
    # estimate theoretical delays given a
    # source location and an array
    #
    # micsloc: Mx3, 3-D locations of M mics in an array
    # srcloc: 1x3, 3-D location of source
    #
    # delays: Mx1, delays from srcloc to the array
    # gains: Mx1, gains from srcloc to the array

    M = len(micsloc)
    delays = [None]*M
    gains = [None]*M
    for k in range(M):
        dist = np.sqrt(np.sum((micsloc[k,:]-srcloc)**2))
        delays[k] = dist/cSound
        gains[k] = 1/dist

    # normalize
    delays = delays-np.mean(delays)
    gains = gains/np.linalg.norm(gains)

    return delays,gains

redpajama_set_name: RedPajamaGithub


text:
@class DBGViewDebugger, DVTObservingToken;

@interface DBGViewDebuggerDocument : IDEEditorDocument
{
    DVTObservingToken *_controlStateObserver;
    DVTObservingToken *_coalescedStateObserver;
    DBGViewDebugger *_viewDebugger;
}

@property(retain) DBGViewDebugger *viewDebugger; // @synthesize viewDebugger=_viewDebugger;
- (void).cxx_destruct;
- (id)_viewDebuggerForURL:(id)arg1 inWorkspace:(id)arg2;
- (id)_viewDebuggerForURL:(id)arg1;
- (id)viewObjectForLocation:(id)arg1;
- (id)displayName;
- (int)readOnlyStatus;
- (void)editorDocumentDidClose;
- (BOOL)readFromURL:(id)arg1 ofType:(id)arg2 error:(id *)arg3;
- (void)_closeDocumentIfNecessary;
- (id)initForURL:(id)arg1 withContentsOfURL:(id)arg2 ofType:(id)arg3 error:(id *)arg4;

@end


text:
#launchpadContent	{ width:100%; padding:0;}

#launchpad {width:100%; overflow:hidden; height:600px; padding-top:12px;}
#launchpad:hover	{overflow:auto;}
#launchpadInner	{position:relative; left:0; width:10000px; }

.launchpad_tiles { list-style-type: none; margin: 0 24px; padding: 0; width: 500px; float:left; }

.launchpad_tiles > li {
	margin: 6px; padding: 0px; float: left;
	text-align:left;
	overflow:hidden;
	font-size: .9em;
	background:#efefef;
	position:relative;
	-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
	-moz-box-sizing: border-box;    /* Firefox, other Gecko */
	box-sizing: border-box;         /* Opera/IE 8+ */
	-webkit-border-radius: 25px 0px 25px 0px;
	border-radius: 25px 0px 25px 0px;
	}

.launchpad_tiles li.tile_1x1	{width: 150px; height: 150px;}
.launchpad_tiles li.tile_2x1	{width:312px; height:150px;}
.launchpad_tiles li.tile_2x2	{width:312px; height:312px;}

.launchpad_tiles li .tilename {position:absolute; bottom:6px; left:6px;}
.launchpad_tiles li:hover	{
/*	cursor: move; -> re-enable when dran and drop is supported. */
	-webkit-box-shadow:  3px 3px 4px 3px rgba(0, 0, 0, .2);
	box-shadow:  3px 3px 4px 3px rgba(0, 0, 0, .2);
	}

.launchpad_tiles span.icon	{font-size:5em; line-height:2em;}

.launchpad_tiles li, .launchpad_tiles li a {color:#ffffff;}

.launchpad_tiles li.green {background-color: #64ab23;}
.launchpad_tiles li.orange {background-color: #df8500;}
.launchpad_tiles li.purple {background-color: #68468f;}
.launchpad_tiles li.teal {background-color: #60bae3;}

.launchpad_tiles li.blue1 {background-color: #a6cbf0;}
.launchpad_tiles li.blue2 {background-color: #5a98cd;}
.launchpad_tiles li.blue3 {background-color: #4978a9;}
.launchpad_tiles li.blue4 {background-color: #91afdc;}
.launchpad_tiles li.blue5 {background-color: #6784b3;}
.launchpad_tiles li.blue6 {background-color: #2c4e86;}
.launchpad_tiles li.blue7 {background-color: #006596;}
.launchpad_tiles li.blue8 {background-color: #004b67;}

.launchpad_tiles li.grey1 {background-color: #9ab0b6;}
.launchpad_tiles li.grey2 {background-color: #7a8491;}
.launchpad_tiles li.grey3 {background-color: #2d3c4d;}

.launchpad_tiles li.white	{color:#666666;}

#tileRecentNews .recentNewsTileContainer	{
	width:100%; overflow:auto; padding:12px; height:312px;
	-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
	-moz-box-sizing: border-box;    /* Firefox, other Gecko */
	box-sizing: border-box;         /* Opera/IE 8+ */
	}
/*
.launchpad_tiles li, .launchpad_tiles li a {color:#666666;}
.launchpad_tiles li.blue {background-color: #9fadba;}
.launchpad_tiles li.blueLight {background-color: #aca0a0;}
.launchpad_tiles li.blueDark {background-color: #8f98bf;}
.launchpad_tiles li.green  {background-color: #b1c3d7;}
.launchpad_tiles li.greenLight {background-color: #d0b29a;}
.launchpad_tiles li.greenDark {background-color: #bbad93;}
.launchpad_tiles li.red {background-color: #d6c29f;}
.launchpad_tiles li.redLight {background-color: #e1d3a2;}
.launchpad_tiles li.yellow {background-color: #c5c899;}
.launchpad_tiles li.orange {background-color: #faffe1;}
.launchpad_tiles li.orangeDark {background-color: #fdefd2;}
.launchpad_tiles li.pink {background-color: #f5e4dd;}
.launchpad_tiles li.pinkDark {background-color: #dbe8f9;}
.launchpad_tiles li.purple {background-color: #d9daec;}
.launchpad_tiles li.white {background-color: #ffffff;}
.launchpad_tiles li.grayLight {background-color: #efefef;}
.launchpad_tiles li.grayDark {background-color: #cccccc;}
.launchpad_tiles li.magenta {background-color: #d8e4d0;}
.launchpad_tiles li.teal {background-color: #b1c3d7;}
.launchpad_tiles li.white,
.launchpad_tiles li.grayLight,
.launchpad_tiles li.grayLight span.icon,
.launchpad_tiles li.white span.icon	{color:#666666;}
*/

#launchpad .icon	{
	font-family: "iconFont";
	font-weight: normal;
	font-style: normal;
	padding-right:6px;
	}


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.Sql.Models;

namespace Azure.ResourceManager.Sql
{
    /// <summary> The JobTargetGroups service client. </summary>
    public partial class JobTargetGroupsOperations
    {
        private readonly ClientDiagnostics _clientDiagnostics;
        private readonly HttpPipeline _pipeline;
        internal JobTargetGroupsRestOperations RestClient { get; }
        /// <summary> Initializes a new instance of JobTargetGroupsOperations for mocking. </summary>
        protected JobTargetGroupsOperations()
        {
        }
        /// <summary> Initializes a new instance of JobTargetGroupsOperations. </summary>
        /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
        /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
        /// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param>
        /// <param name="endpoint"> server parameter. </param>
        internal JobTargetGroupsOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string subscriptionId, Uri endpoint = null)
        {
            RestClient = new JobTargetGroupsRestOperations(clientDiagnostics, pipeline, subscriptionId, endpoint);
            _clientDiagnostics = clientDiagnostics;
            _pipeline = pipeline;
        }

        /// <summary> Gets a target group. </summary>
        /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
        /// <param name="serverName"> The name of the server. </param>
        /// <param name="jobAgentName"> The name of the job agent. </param>
        /// <param name="targetGroupName"> The name of the target group. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response<JobTargetGroup>> GetAsync(string resourceGroupName, string serverName, string jobAgentName, string targetGroupName, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("JobTargetGroupsOperations.Get");
            scope.Start();
            try
            {
                return await RestClient.GetAsync(resourceGroupName, serverName, jobAgentName, targetGroupName, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Gets a target group. </summary>
        /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
        /// <param name="serverName"> The name of the server. </param>
        /// <param name="jobAgentName"> The name of the job agent. </param>
        /// <param name="targetGroupName"> The name of the target group. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response<JobTargetGroup> Get(string resourceGroupName, string serverName, string jobAgentName, string targetGroupName, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("JobTargetGroupsOperations.Get");
            scope.Start();
            try
            {
                return RestClient.Get(resourceGroupName, serverName, jobAgentName, targetGroupName, cancellationToken);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Creates or updates a target group. </summary>
        /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
        /// <param name="serverName"> The name of the server. </param>
        /// <param name="jobAgentName"> The name of the job agent. </param>
        /// <param name="targetGroupName"> The name of the target group. </param>
        /// <param name="parameters"> The requested state of the target group. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response<JobTargetGroup>> CreateOrUpdateAsync(string resourceGroupName, string serverName, string jobAgentName, string targetGroupName, JobTargetGroup parameters, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("JobTargetGroupsOperations.CreateOrUpdate");
            scope.Start();
            try
            {
                return await RestClient.CreateOrUpdateAsync(resourceGroupName, serverName, jobAgentName, targetGroupName, parameters, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Creates or updates a target group. </summary>
        /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
        /// <param name="serverName"> The name of the server. </param>
        /// <param name="jobAgentName"> The name of the job agent. </param>
        /// <param name="targetGroupName"> The name of the target group. </param>
        /// <param name="parameters"> The requested state of the target group. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response<JobTargetGroup> CreateOrUpdate(string resourceGroupName, string serverName, string jobAgentName, string targetGroupName, JobTargetGroup parameters, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("JobTargetGroupsOperations.CreateOrUpdate");
            scope.Start();
            try
            {
                return RestClient.CreateOrUpdate(resourceGroupName, serverName, jobAgentName, targetGroupName, parameters, cancellationToken);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Deletes a target group. </summary>
        /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
        /// <param name="serverName"> The name of the server. </param>
        /// <param name="jobAgentName"> The name of the job agent. </param>
        /// <param name="targetGroupName"> The name of the target group. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response> DeleteAsync(string resourceGroupName, string serverName, string jobAgentName, string targetGroupName, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("JobTargetGroupsOperations.Delete");
            scope.Start();
            try
            {
                return await RestClient.DeleteAsync(resourceGroupName, serverName, jobAgentName, targetGroupName, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Deletes a target group. </summary>
        /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
        /// <param name="serverName"> The name of the server. </param>
        /// <param name="jobAgentName"> The name of the job agent. </param>
        /// <param name="targetGroupName"> The name of the target group. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response Delete(string resourceGroupName, string serverName, string jobAgentName, string targetGroupName, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("JobTargetGroupsOperations.Delete");
            scope.Start();
            try
            {
                return RestClient.Delete(resourceGroupName, serverName, jobAgentName, targetGroupName, cancellationToken);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Gets all target groups in an agent. </summary>
        /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
        /// <param name="serverName"> The name of the server. </param>
        /// <param name="jobAgentName"> The name of the job agent. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, or <paramref name="jobAgentName"/> is null. </exception>
        public virtual AsyncPageable<JobTargetGroup> ListByAgentAsync(string resourceGroupName, string serverName, string jobAgentName, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (serverName == null)
            {
                throw new ArgumentNullException(nameof(serverName));
            }
            if (jobAgentName == null)
            {
                throw new ArgumentNullException(nameof(jobAgentName));
            }

            async Task<Page<JobTargetGroup>> FirstPageFunc(int? pageSizeHint)
            {
                using var scope = _clientDiagnostics.CreateScope("JobTargetGroupsOperations.ListByAgent");
                scope.Start();
                try
                {
                    var response = await RestClient.ListByAgentAsync(resourceGroupName, serverName, jobAgentName, cancellationToken).ConfigureAwait(false);
                    return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            async Task<Page<JobTargetGroup>> NextPageFunc(string nextLink, int? pageSizeHint)
            {
                using var scope = _clientDiagnostics.CreateScope("JobTargetGroupsOperations.ListByAgent");
                scope.Start();
                try
                {
                    var response = await RestClient.ListByAgentNextPageAsync(nextLink, resourceGroupName, serverName, jobAgentName, cancellationToken).ConfigureAwait(false);
                    return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
        }

        /// <summary> Gets all target groups in an agent. </summary>
        /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
        /// <param name="serverName"> The name of the server. </param>
        /// <param name="jobAgentName"> The name of the job agent. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, or <paramref name="jobAgentName"/> is null. </exception>
        public virtual Pageable<JobTargetGroup> ListByAgent(string resourceGroupName, string serverName, string jobAgentName, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (serverName == null)
            {
                throw new ArgumentNullException(nameof(serverName));
            }
            if (jobAgentName == null)
            {
                throw new ArgumentNullException(nameof(jobAgentName));
            }

            Page<JobTargetGroup> FirstPageFunc(int? pageSizeHint)
            {
                using var scope = _clientDiagnostics.CreateScope("JobTargetGroupsOperations.ListByAgent");
                scope.Start();
                try
                {
                    var response = RestClient.ListByAgent(resourceGroupName, serverName, jobAgentName, cancellationToken);
                    return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            Page<JobTargetGroup> NextPageFunc(string nextLink, int? pageSizeHint)
            {
                using var scope = _clientDiagnostics.CreateScope("JobTargetGroupsOperations.ListByAgent");
                scope.Start();
                try
                {
                    var response = RestClient.ListByAgentNextPage(nextLink, resourceGroupName, serverName, jobAgentName, cancellationToken);
                    return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
        }
    }
}


text:
from django.contrib import admin
from stickynotes.models import Stickynote

admin.site.register(Stickynote)


text:
module LotteryPicker
	class Drawing
		def draw
			# This value used to be 5
			6.times.map { single_draw }
		end

		private
		def single_draw
			rand(0...60)
		end
	end
end


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using DarkMultiPlayerCommon;

namespace DarkMultiPlayer
{
    public class ModWorker
    {
        public ModControlMode modControl = ModControlMode.ENABLED_STOP_INVALID_PART_SYNC;
        //Accessed from ModWindow
        private List<string> allowedParts;
        private string lastModFileData = "";
        //Services
        private ModWindow modWindow;

        public ModWorker(ModWindow modWindow)
        {
            this.modWindow = modWindow;
        }

        public string failText
        {
            private set;
            get;
        }

        private bool CheckFile(string relativeFileName, string referencefileHash)
        {
            string fullFileName = Path.Combine(Client.dmpClient.gameDataDir, relativeFileName);
            string fileHash = Common.CalculateSHA256Hash(fullFileName);
            if (fileHash != referencefileHash)
            {
                DarkLog.Debug(relativeFileName + " hash mismatch");
                return false;
            }
            return true;
        }

        public bool ParseModFile(string modFileData)
        {
            if (modControl == ModControlMode.DISABLED)
            {
                return true;
            }
            bool modCheckOk = true;

            //Save mod file so we can recheck it.
            lastModFileData = modFileData;
            string tempModFilePath = Path.Combine(Client.dmpClient.dmpDataDir, "mod-control.txt");
            using (StreamWriter sw = new StreamWriter(tempModFilePath))
            {
                sw.WriteLine("#This file is downloaded from the server during connection. It is saved here for convenience.");
                sw.WriteLine(lastModFileData);
            }

            //Parse
            Dictionary<string, string> parseRequired = new Dictionary<string, string>();
            Dictionary<string, string> parseOptional = new Dictionary<string, string>();
            List<string> parseWhiteBlackList = new List<string>();
            List<string> parsePartsList = new List<string>();
            bool isWhiteList = false;
            string readMode = "";
            using (StringReader sr = new StringReader(modFileData))
            {
                while (true)
                {
                    string currentLine = sr.ReadLine();
                    if (currentLine == null)
                    {
                        //Done reading
                        break;
                    }
                    //Remove tabs/spaces from the start & end.
                    string trimmedLine = currentLine.Trim();
                    if (trimmedLine.StartsWith("#", StringComparison.Ordinal) || String.IsNullOrEmpty(trimmedLine))
                    {
                        //Skip comments or empty lines.
                        continue;
                    }
                    if (trimmedLine.StartsWith("!", StringComparison.Ordinal))
                    {
                        //New section
                        switch (trimmedLine.Substring(1))
                        {
                            case "required-files":
                            case "optional-files":
                            case "partslist":
                                readMode = trimmedLine.Substring(1);
                                break;
                            case "resource-blacklist":
                                readMode = trimmedLine.Substring(1);
                                isWhiteList = false;
                                break;
                            case "resource-whitelist":
                                readMode = trimmedLine.Substring(1);
                                isWhiteList = true;
                                break;
                            default:
                                break;
                        }
                    }
                    else
                    {
                        switch (readMode)
                        {
                            case "required-files":
                                {
                                    string lowerFixedLine = trimmedLine.ToLowerInvariant().Replace('\\', '/');
                                    if (lowerFixedLine.Contains("="))
                                    {
                                        string[] splitLine = lowerFixedLine.Split('=');
                                        if (splitLine.Length == 2)
                                        {
                                            if (!parseRequired.ContainsKey(splitLine[0]))
                                            {
                                                parseRequired.Add(splitLine[0], splitLine[1].ToLowerInvariant());
                                            }
                                        }
                                        else
                                        {
                                            if (splitLine.Length == 1)
                                            {
                                                if (!parseRequired.ContainsKey(splitLine[0]))
                                                {
                                                    parseRequired.Add(splitLine[0], "");
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (!parseRequired.ContainsKey(lowerFixedLine))
                                        {
                                            parseRequired.Add(lowerFixedLine, "");
                                        }
                                    }
                                }
                                break;
                            case "optional-files":
                                {
                                    string lowerFixedLine = trimmedLine.ToLowerInvariant().Replace('\\', '/');
                                    if (lowerFixedLine.Contains("="))
                                    {
                                        string[] splitLine = lowerFixedLine.Split('=');
                                        if (splitLine.Length == 2)
                                        {
                                            if (!parseOptional.ContainsKey(splitLine[0]))
                                            {
                                                parseOptional.Add(splitLine[0], splitLine[1]);
                                            }
                                        }
                                        else
                                        {
                                            if (splitLine.Length == 1)
                                            {
                                                if (!parseOptional.ContainsKey(splitLine[0]))
                                                {
                                                    parseOptional.Add(splitLine[0], "");
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (!parseOptional.ContainsKey(lowerFixedLine))
                                        {
                                            parseOptional.Add(lowerFixedLine, "");
                                        }
                                    }
                                }
                                break;
                            case "resource-whitelist":
                            case "resource-blacklist":
                                {
                                    string lowerFixedLine = trimmedLine.ToLowerInvariant().Replace('\\', '/');
                                    //Resource is dll's only.
                                    if (lowerFixedLine.ToLowerInvariant().EndsWith(".dll", StringComparison.Ordinal))
                                    {
                                        if (parseWhiteBlackList.Contains(lowerFixedLine))
                                        {
                                            parseWhiteBlackList.Add(lowerFixedLine);
                                        }
                                    }
                                }
                                break;
                            case "partslist":
                                if (!parsePartsList.Contains(trimmedLine))
                                {
                                    parsePartsList.Add(trimmedLine);
                                }
                                break;
                            default:
                                break;
                        }
                    }
                }
            }

            string[] currentGameDataFiles = Directory.GetFiles(Client.dmpClient.gameDataDir, "*", SearchOption.AllDirectories);
            List<string> currentGameDataFilesNormal = new List<string>();
            List<string> currentGameDataFilesLower = new List<string>();
            foreach (string currentFile in currentGameDataFiles)
            {
                string relativeFilePath = currentFile.Substring(currentFile.ToLowerInvariant().IndexOf("gamedata", StringComparison.Ordinal) + 9).Replace('\\', '/');
                currentGameDataFilesNormal.Add(relativeFilePath);
                currentGameDataFilesLower.Add(relativeFilePath.ToLowerInvariant());
            }
            //Check
            StringBuilder sb = new StringBuilder();
            //Check Required
            foreach (KeyValuePair<string, string> requiredEntry in parseRequired)
            {
                //Protect against windows-style entries in mod-control.txt. Also use case insensitive matching.
                if (!currentGameDataFilesLower.Contains(requiredEntry.Key))
                {
                    modCheckOk = false;
                    DarkLog.Debug("Required file " + requiredEntry.Key + " is missing!");
                    sb.AppendLine("Required file " + requiredEntry.Key + " is missing!");
                    continue;
                }
                //If the entry has a SHA sum, we need to check it.
                if (requiredEntry.Value != "")
                {

                    string normalCaseFileName = currentGameDataFilesNormal[currentGameDataFilesLower.IndexOf(requiredEntry.Key)];
                    string fullFileName = Path.Combine(Client.dmpClient.gameDataDir, normalCaseFileName);
                    if (!CheckFile(fullFileName, requiredEntry.Value))
                    {
                        modCheckOk = false;
                        DarkLog.Debug("Required file " + requiredEntry.Key + " does not match hash " + requiredEntry.Value + "!");
                        sb.AppendLine("Required file " + requiredEntry.Key + " does not match hash " + requiredEntry.Value + "!");
                        continue;
                    }
                }
            }

            //Check Optional
            foreach (KeyValuePair<string, string> optionalEntry in parseOptional)
            {
                //Protect against windows-style entries in mod-control.txt. Also use case insensitive matching.
                if (!currentGameDataFilesLower.Contains(optionalEntry.Key))
                {
                    //File is optional, nothing to check if it doesn't exist.
                    continue;
                }
                //If the entry has a SHA sum, we need to check it.
                if (optionalEntry.Value != "")
                {

                    string normalCaseFileName = currentGameDataFilesNormal[currentGameDataFilesLower.IndexOf(optionalEntry.Key)];
                    string fullFileName = Path.Combine(Client.dmpClient.gameDataDir, normalCaseFileName);
                    if (!CheckFile(fullFileName, optionalEntry.Value))
                    {
                        modCheckOk = false;
                        DarkLog.Debug("Optional file " + optionalEntry.Key + " does not match hash " + optionalEntry.Value + "!");
                        sb.AppendLine("Optional file " + optionalEntry.Key + " does not match hash " + optionalEntry.Value + "!");
                        continue;
                    }
                }

            }
            if (isWhiteList)
            {
                //Check Resource whitelist
                List<string> autoAllowed = new List<string>();
                autoAllowed.Add("darkmultiplayer/plugins/darkmultiplayer.dll");
                autoAllowed.Add("darkmultiplayer/plugins/darkmultiplayer-common.dll");
                autoAllowed.Add("darkmultiplayer/plugins/messagewriter2.dll");
                autoAllowed.Add("darkmultiplayer/plugins/udpmeshlib.dll");
                foreach (string fileName in Directory.GetFiles(Client.dmpClient.gameDataDir))
                {
                    string fileNameLower = fileName.ToLower();
                    if (!fileNameLower.Contains("gamedata"))
                    {
                        //This case is hit when directories are symlinked, for developing DarkMultiPlayer.
                        continue;
                    }
                    string croppedFileName = fileNameLower.Substring(fileNameLower.IndexOf("gamedata", StringComparison.Ordinal) + 9).Replace('\\', '/');
                    //Ignore non DLL files
                    if (!croppedFileName.EndsWith(".dll", StringComparison.Ordinal))
                    {
                        continue;
                    }
                    if (croppedFileName.StartsWith("ModuleManager", StringComparison.Ordinal))
                    {
                        continue;
                    }
                    //Allow DMP files
                    if (autoAllowed.Contains(croppedFileName))
                    {
                        continue;
                    }
                    //Ignore squad plugins
                    if (croppedFileName.StartsWith("squad/plugins", StringComparison.Ordinal))
                    {
                        continue;
                    }
                    //Check required (Required implies whitelist)
                    if (parseRequired.ContainsKey(croppedFileName))
                    {
                        continue;
                    }
                    //Check optional (Optional implies whitelist)
                    if (parseOptional.ContainsKey(croppedFileName))
                    {
                        continue;
                    }
                    //Check whitelist
                    if (parseWhiteBlackList.Contains(croppedFileName))
                    {
                        continue;
                    }
                    modCheckOk = false;
                    DarkLog.Debug("Non-whitelisted resource " + croppedFileName + " exists on client!");
                    sb.AppendLine("Non-whitelisted resource " + croppedFileName + " exists on client!");
                }
            }
            else
            {
                HashSet<string> dllFileList = new HashSet<string>();
                foreach (string fileName in Directory.GetFiles(Client.dmpClient.gameDataDir))
                {
                    string fileNameLower = fileName.ToLower();
                    dllFileList.Add(fileNameLower);
                }

                //Check Resource blacklist
                foreach (string blacklistEntry in parseWhiteBlackList)
                {
                    if (dllFileList.Contains(blacklistEntry.ToLower()))
                    {
                        modCheckOk = false;
                        DarkLog.Debug("Banned resource " + blacklistEntry + " exists on client!");
                        sb.AppendLine("Banned resource " + blacklistEntry + " exists on client!");
                    }
                }
            }

            //Ignores old missing stock parts
            List<string> installedPartsList = Common.GetStockParts();
            foreach (AvailablePart part in PartLoader.LoadedPartsList)
            {
                if (!installedPartsList.Contains(part.name))
                {
                    installedPartsList.Add(part.name);
                }
            }

            foreach (string partName in parsePartsList)
            {
                DarkLog.Debug("Checking " + partName);
                if (!installedPartsList.Contains(partName))
                {
                    modCheckOk = false;
                    DarkLog.Debug("Required part " + partName + " is missing!");
                    sb.AppendLine("Required part " + partName + " is missing!");
                }
            }

            if (!modCheckOk)
            {
                failText = sb.ToString();
                modWindow.display = true;
                return false;
            }
            allowedParts = parsePartsList;
            DarkLog.Debug("Mod check passed!");
            return true;
        }

        public List<string> GetAllowedPartsList()
        {
            //Return a copy
            if (modControl == ModControlMode.DISABLED)
            {
                return null;
            }
            return new List<string>(allowedParts);
        }

        public void GenerateModControlFile(bool whitelistMode, bool displayMessage)
        {
            string gameDataDir = Client.dmpClient.gameDataDir;
            string[] allFiles = Directory.GetFiles(gameDataDir, "*", SearchOption.AllDirectories);

            List<string> requiredFiles = new List<string>();
            List<string> optionalFiles = new List<string>();
            List<string> partsList = Common.GetStockParts();

            if (whitelistMode)
            {
                foreach (string fileName in allFiles)
                {
                    string fileNameLower = fileName.ToLower();
                    string croppedFileName = fileNameLower.Substring(fileNameLower.IndexOf("gamedata", StringComparison.Ordinal) + 9).Replace('\\', '/');
                    if (croppedFileName.EndsWith(".dll", StringComparison.Ordinal))
                    {
                        optionalFiles.Add(croppedFileName);
                    }
                }
            }

            foreach (AvailablePart part in PartLoader.LoadedPartsList)
            {
                if (!partsList.Contains(part.name))
                {
                    partsList.Add(part.name);
                }
            }

            string modFileData = Common.GenerateModFileStringData(requiredFiles.ToArray(), optionalFiles.ToArray(), whitelistMode, new string[0], partsList.ToArray());
            string saveModFile = Path.Combine(Client.dmpClient.kspRootPath, "mod-control.txt");
            using (StreamWriter sw = new StreamWriter(saveModFile, false))
            {
                sw.Write(modFileData);
            }
            if (displayMessage)
            {
                ScreenMessages.PostScreenMessage("mod-control.txt file generated in your KSP folder\nMove it to DMPServer/Config/", 5f, ScreenMessageStyle.UPPER_CENTER);
            }
        }

        public void CheckCommonStockParts()
        {
            int totalParts = 0;
            int missingParts = 0;
            List<string> stockParts = Common.GetStockParts();
            DarkLog.Debug("Missing parts start");
            foreach (AvailablePart part in PartLoader.LoadedPartsList)
            {
                totalParts++;
                if (!stockParts.Contains(part.name))
                {
                    missingParts++;
                    DarkLog.Debug("Missing '" + part.name + "'");
                }
            }
            DarkLog.Debug("Missing parts end");
            if (missingParts != 0)
            {
                ScreenMessages.PostScreenMessage(missingParts + " missing part(s) from Common.dll printed to debug log (" + totalParts + " total)", 5f, ScreenMessageStyle.UPPER_CENTER);
            }
            else
            {
                ScreenMessages.PostScreenMessage("No missing parts out of from Common.dll (" + totalParts + " total)", 5f, ScreenMessageStyle.UPPER_CENTER);
            }
        }
    }
}


text:
package com.amazonaws.services.rds.model;

/**
 *

 * Contains the result of a successful invocation of the
 * DescribeEngineDefaultParameters action.
 *

 */
public class EngineDefaults {

    /**
     * Specifies the name of the DB Parameter Group Family which the engine
     * default parameters apply to.
     */
    private String dBParameterGroupFamily;

    /**
     * Provides an identifier to allow retrieval of paginated results.
     */
    private String marker;

    /**
     * Contains a list of engine default parameters.
     */
    private java.util.List<Parameter> parameters;

    /**
     * Specifies the name of the DB Parameter Group Family which the engine
     * default parameters apply to.
     *
     * @return Specifies the name of the DB Parameter Group Family which the engine
     *         default parameters apply to.
     */
    public String getDBParameterGroupFamily() {
        return dBParameterGroupFamily;
    }

    /**
     * Specifies the name of the DB Parameter Group Family which the engine
     * default parameters apply to.
     *
     * @param dBParameterGroupFamily Specifies the name of the DB Parameter Group Family which the engine
     *         default parameters apply to.
     */
    public void setDBParameterGroupFamily(String dBParameterGroupFamily) {
        this.dBParameterGroupFamily = dBParameterGroupFamily;
    }

    /**
     * Specifies the name of the DB Parameter Group Family which the engine
     * default parameters apply to.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param dBParameterGroupFamily Specifies the name of the DB Parameter Group Family which the engine
     *         default parameters apply to.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public EngineDefaults withDBParameterGroupFamily(String dBParameterGroupFamily) {
        this.dBParameterGroupFamily = dBParameterGroupFamily;
        return this;
    }

    /**
     * Provides an identifier to allow retrieval of paginated results.
     *
     * @return Provides an identifier to allow retrieval of paginated results.
     */
    public String getMarker() {
        return marker;
    }

    /**
     * Provides an identifier to allow retrieval of paginated results.
     *
     * @param marker Provides an identifier to allow retrieval of paginated results.
     */
    public void setMarker(String marker) {
        this.marker = marker;
    }

    /**
     * Provides an identifier to allow retrieval of paginated results.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param marker Provides an identifier to allow retrieval of paginated results.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public EngineDefaults withMarker(String marker) {
        this.marker = marker;
        return this;
    }

    /**
     * Contains a list of engine default parameters.
     *
     * @return Contains a list of engine default parameters.
     */
    public java.util.List<Parameter> getParameters() {
        if (parameters == null) {
            parameters = new java.util.ArrayList<Parameter>();
        }
        return parameters;
    }

    /**
     * Contains a list of engine default parameters.
     *
     * @param parameters Contains a list of engine default parameters.
     */
    public void setParameters(java.util.Collection<Parameter> parameters) {
        java.util.List<Parameter> parametersCopy = new java.util.ArrayList<Parameter>();
        if (parameters != null) {
            parametersCopy.addAll(parameters);
        }
        this.parameters = parametersCopy;
    }

    /**
     * Contains a list of engine default parameters.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param parameters Contains a list of engine default parameters.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public EngineDefaults withParameters(Parameter... parameters) {
        for (Parameter value : parameters) {
            getParameters().add(value);
        }
        return this;
    }

    /**
     * Contains a list of engine default parameters.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param parameters Contains a list of engine default parameters.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public EngineDefaults withParameters(java.util.Collection<Parameter> parameters) {
        java.util.List<Parameter> parametersCopy = new java.util.ArrayList<Parameter>();
        if (parameters != null) {
            parametersCopy.addAll(parameters);
        }
        this.parameters = parametersCopy;

        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("DBParameterGroupFamily: " + dBParameterGroupFamily + ", ");
        sb.append("Marker: " + marker + ", ");
        sb.append("Parameters: " + parameters + ", ");
        sb.append("}");
        return sb.toString();
    }

}


text:
"""Algorithms to adapt the mass matrix used by algorithms in the Hamiltonian
Monte Carlo family to the current geometry.

The Stan Manual [1]_ is a very good reference on automatic tuning of
parameters used in Hamiltonian Monte Carlo.

.. [1]: "HMC Algorithm Parameters", Stan Manual
        https://mc-stan.org/docs/2_20/reference-manual/hmc-algorithm-parameters.html
"""
from typing import Callable, NamedTuple, Tuple

import jax
import jax.numpy as jnp

from blackjax.types import Array

__all__ = ["mass_matrix_adaptation", "welford_algorithm"]

class WelfordAlgorithmState(NamedTuple):
    """State carried through the Welford algorithm.

    mean
        The running sample mean.
    m2
        The running value of the sum of difference of squares. See documentation
        of the `welford_algorithm` function for an explanation.
    sample_size
        The number of successive states the previous values have been computed on;
        also the current number of iterations of the algorithm.
    """

    mean: Array
    m2: Array
    sample_size: int

class MassMatrixAdaptationState(NamedTuple):
    """State carried through the mass matrix adaptation.

    inverse_mass_matrix
        The curent value of the inverse mass matrix.
    wc_state
        The current state of the Welford Algorithm.
    """

    inverse_mass_matrix: Array
    wc_state: WelfordAlgorithmState

def mass_matrix_adaptation(
    is_diagonal_matrix: bool = True,
) -> Tuple[Callable, Callable, Callable]:
    """Adapts the values in the mass matrix by computing the covariance
    between parameters.

    Parameters
    ----------
    is_diagonal_matrix
        When True the algorithm adapts and returns a diagonal mass matrix
        (default), otherwise adaps and returns a dense mass matrix.

    Returns
    -------
    init
        A function that initializes the step of the mass matrix adaptation.
    update
        A function that updates the state of the mass matrix.
    final
        A function that computes the inverse mass matrix based on the current
        state.
    """
    wc_init, wc_update, wc_final = welford_algorithm(is_diagonal_matrix)

    def init(n_dims: int) -> MassMatrixAdaptationState:
        """Initialize the matrix adaptation.

        Parameters
        ----------
        ndims
            The number of dimensions of the mass matrix, which corresponds to
            the number of dimensions of the chain position.
        """
        if is_diagonal_matrix:
            inverse_mass_matrix = jnp.ones(n_dims)
        else:
            inverse_mass_matrix = jnp.identity(n_dims)

        wc_state = wc_init(n_dims)

        return MassMatrixAdaptationState(inverse_mass_matrix, wc_state)

    def update(
        mm_state: MassMatrixAdaptationState, position: Array
    ) -> MassMatrixAdaptationState:
        """Update the algorithm's state.

        Parameters
        ----------
        state:
            The current state of the mass matrix adapation.
        position:
            The current position of the chain.
        """
        inverse_mass_matrix, wc_state = mm_state
        position, _ = jax.flatten_util.ravel_pytree(position)
        wc_state = wc_update(wc_state, position)
        return MassMatrixAdaptationState(inverse_mass_matrix, wc_state)

    def final(mm_state: MassMatrixAdaptationState) -> MassMatrixAdaptationState:
        """Final iteration of the mass matrix adaptation.

        In this step we compute the mass matrix from the covariance matrix computed
        by the Welford algorithm, and re-initialize the later.
        """
        _, wc_state = mm_state
        covariance, count, mean = wc_final(wc_state)

        # Regularize the covariance matrix, see Stan
        scaled_covariance = (count / (count + 5)) * covariance
        shrinkage = 1e-3 * (5 / (count + 5))
        if is_diagonal_matrix:
            inverse_mass_matrix = scaled_covariance + shrinkage
        else:
            inverse_mass_matrix = scaled_covariance + shrinkage * jnp.identity(
                mean.shape[0]
            )

        ndims = jnp.shape(inverse_mass_matrix)[-1]
        new_mm_state = MassMatrixAdaptationState(inverse_mass_matrix, wc_init(ndims))

        return new_mm_state

    return init, update, final

def welford_algorithm(is_diagonal_matrix: bool) -> Tuple[Callable, Callable, Callable]:
    """Welford's online estimator of covariance.

    It is possible to compute the variance of a population of values in an
    on-line fashion to avoid storing intermediate results. The naive recurrence
    relations between the sample mean and variance at a step and the next are
    however not numerically stable.

    Welford's algorithm uses the sum of square of differences
    :math:`M_{2,n} = \\sum_{i=1}^n \\left(x_i-\\overline{x_n}\right)^2`
    for updating where :math:`x_n` is the current mean and the following
    recurrence relationships

    Parameters
    ----------
    is_diagonal_matrix
        When True the algorithm adapts and returns a diagonal mass matrix
        (default), otherwise adaps and returns a dense mass matrix.

    Note
    ----
    It might seem pedantic to separate the Welford algorithm from mass adaptation,
    but this covariance estimator is used in other parts of the library.

    .. math:
        M_{2,n} = M_{2, n-1} + (x_n-\\overline{x}_{n-1})(x_n-\\overline{x}_n)
        \\sigma_n^2 = \\frac{M_{2,n}}{n}
    """

    def init(n_dims: int) -> WelfordAlgorithmState:
        """Initialize the covariance estimation.

        When the matrix is diagonal it is sufficient to work with an array that contains
        the diagonal value. Otherwise we need to work with the matrix in full.

        Parameters
        ----------
        n_dims: int
            The number of dimensions of the problem, which corresponds to the size
            of the corresponding square mass matrix.
        """
        sample_size = 0
        mean = jnp.zeros((n_dims,))
        if is_diagonal_matrix:
            m2 = jnp.zeros((n_dims,))
        else:
            m2 = jnp.zeros((n_dims, n_dims))
        return WelfordAlgorithmState(mean, m2, sample_size)

    def update(wa_state: WelfordAlgorithmState, value: Array) -> WelfordAlgorithmState:
        """Update the M2 matrix using the new value.

        Parameters
        ----------
        state:
            The current state of the Welford Algorithm
        position: Array, shape (1,)
            The new sample (typically position of the chain) used to update m2
        """
        mean, m2, sample_size = wa_state
        sample_size = sample_size + 1

        delta = value - mean
        mean = mean + delta / sample_size
        updated_delta = value - mean
        if is_diagonal_matrix:
            new_m2 = m2 + delta * updated_delta
        else:
            new_m2 = m2 + jnp.outer(updated_delta, delta)

        return WelfordAlgorithmState(mean, new_m2, sample_size)

    def final(
        wa_state: WelfordAlgorithmState,
    ) -> Tuple[Array, int, Array]:
        mean, m2, sample_size = wa_state
        covariance = m2 / (sample_size - 1)
        return covariance, sample_size, mean

    return init, update, final


text:
// flow-typed signature: 22f054bfd3a1e0c08e773d28df429788
// flow-typed version: <<STUB>>/@material/linear-progress_v0.1.3/flow_v0.49.1

/**
 * This is an autogenerated libdef stub for:
 *
 *   '@material/linear-progress'
 *
 * Fill this stub out by replacing all the `any` types.
 *
 * Once filled out, we encourage you to share your work with the
 * community by sending a pull request to:
 * https://github.com/flowtype/flow-typed
 */

declare module '@material/linear-progress' {
  declare module.exports: any;
}

/**
 * We include stubs for each file inside this npm package in case you need to
 * require those files directly. Feel free to delete any files that aren't
 * needed.
 */
declare module '@material/linear-progress/constants' {
  declare module.exports: any;
}

declare module '@material/linear-progress/dist/mdc.linearProgress' {
  declare module.exports: any;
}

declare module '@material/linear-progress/dist/mdc.linearProgress.min' {
  declare module.exports: any;
}

declare module '@material/linear-progress/foundation' {
  declare module.exports: any;
}

// Filename aliases
declare module '@material/linear-progress/constants.js' {
  declare module.exports: $Exports<'@material/linear-progress/constants'>;
}
declare module '@material/linear-progress/dist/mdc.linearProgress.js' {
  declare module.exports: $Exports<'@material/linear-progress/dist/mdc.linearProgress'>;
}
declare module '@material/linear-progress/dist/mdc.linearProgress.min.js' {
  declare module.exports: $Exports<'@material/linear-progress/dist/mdc.linearProgress.min'>;
}
declare module '@material/linear-progress/foundation.js' {
  declare module.exports: $Exports<'@material/linear-progress/foundation'>;
}
declare module '@material/linear-progress/index' {
  declare module.exports: $Exports<'@material/linear-progress'>;
}
declare module '@material/linear-progress/index.js' {
  declare module.exports: $Exports<'@material/linear-progress'>;
}


text:
package ui;
import java.awt.Dimension;
import java.awt.Graphics;

public interface View
{
	public Dimension getPreferredSize();
	public void paint(Graphics g);
	public void update();
	public void stop();
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Unity Buy SDK: Shopify.Unity.SDK.DefaultQueriesCheckout Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Unity Buy SDK

Shopify

Unity

SDK

DefaultQueriesCheckout

Public Member Functions |
List of all members

Shopify.Unity.SDK.DefaultQueriesCheckout Class Reference

Public Member Functions

void 	Create (MutationQuery query, List< CheckoutLineItemInput > lineItems)

void 	CheckoutCompleteWithTokenizedPayment (MutationQuery query, string checkoutId, TokenizedPaymentInput tokenizedPaymentInput)

void 	Poll (QueryRootQuery query, string checkoutId)

void 	PaymentPoll (QueryRootQuery query, string paymentId)

void 	AvailableShippingRatesPoll (QueryRootQuery query, string checkoutId)

void 	LineItemsRemove (MutationQuery query, string checkoutId, List< string > lineItemIds)

void 	LineItemsAdd (MutationQuery query, string checkoutId, List< CheckoutLineItemInput > lineItems)

void 	CheckoutLineItemsPage (QueryRootQuery query, string checkoutId, int first=250, string after=null)

void 	ShippingAddressUpdate (MutationQuery query, string checkoutId, MailingAddressInput shippingAddress)

void 	EmailUpdate (MutationQuery query, string checkoutId, String email)

void 	ShippingLineUpdate (MutationQuery query, string checkoutId, String shippingRateHandle)

The documentation for this class was generated from the following file:

Assets/Shopify/Unity/SDK/DefaultQueriesCheckout.cs

<address class="footer">

</address>