diff --git a/htdocs/edit.js b/htdocs/edit.js index 17953b8f79..9b9d5a4699 100644 --- a/htdocs/edit.js +++ b/htdocs/edit.js @@ -6,7 +6,7 @@ function main() { } RCloud.UI.init(); - RCloud.session.init().then(function() { + RCloud.session.init(false, ['edit', 'gui']).then(function() { var opts = {}; return RCloud.UI.load_options().then(function() { if (location.search.length > 0) { diff --git a/htdocs/js/rcloud.js b/htdocs/js/rcloud.js index f4d4663ab5..20d0106c37 100644 --- a/htdocs/js/rcloud.js +++ b/htdocs/js/rcloud.js @@ -139,12 +139,16 @@ RCloud.create = function(rcloud_ocaps) { return rcloud_ocaps.version_infoAsync.apply(null, arguments); }; - rcloud.anonymous_session_init = function() { - return rcloud_ocaps.anonymous_session_initAsync(); + rcloud.set_session_type = function(session_type) { + return rcloud_ocaps.set_session_typeAsync(session_type); }; - rcloud.anonymous_compute_init = function() { - return rcloud_ocaps.anonymous_compute_initAsync(); + rcloud.anonymous_session_init = function(session_type) { + return rcloud_ocaps.anonymous_session_initAsync(session_type); + }; + + rcloud.anonymous_compute_init = function(session_type) { + return rcloud_ocaps.anonymous_compute_initAsync(session_type); }; rcloud.init_client_side_data = function() { @@ -422,12 +426,12 @@ RCloud.create = function(rcloud_ocaps) { ]; RCloud.promisify_paths(rcloud_ocaps, paths); - rcloud.session_init = function(username, token) { - return rcloud_ocaps.session_initAsync(username, token); + rcloud.session_init = function(session_type, username, token) { + return rcloud_ocaps.session_initAsync(session_type, username, token); }; - rcloud.compute_init = function(username, token) { - return rcloud_ocaps.compute_initAsync(username, token); + rcloud.compute_init = function(session_type, username, token) { + return rcloud_ocaps.compute_initAsync(session_type, username, token); }; rcloud.signal_to_compute = function(signal) { diff --git a/htdocs/js/rcloud_bundle.js b/htdocs/js/rcloud_bundle.js index 34c421660b..0e043ebe24 100644 --- a/htdocs/js/rcloud_bundle.js +++ b/htdocs/js/rcloud_bundle.js @@ -245,12 +245,16 @@ RCloud.create = function(rcloud_ocaps) { return rcloud_ocaps.version_infoAsync.apply(null, arguments); }; - rcloud.anonymous_session_init = function() { - return rcloud_ocaps.anonymous_session_initAsync(); + rcloud.set_session_type = function(session_type) { + return rcloud_ocaps.set_session_typeAsync(session_type); }; - rcloud.anonymous_compute_init = function() { - return rcloud_ocaps.anonymous_compute_initAsync(); + rcloud.anonymous_session_init = function(session_type) { + return rcloud_ocaps.anonymous_session_initAsync(session_type); + }; + + rcloud.anonymous_compute_init = function(session_type) { + return rcloud_ocaps.anonymous_compute_initAsync(session_type); }; rcloud.init_client_side_data = function() { @@ -528,12 +532,12 @@ RCloud.create = function(rcloud_ocaps) { ]; RCloud.promisify_paths(rcloud_ocaps, paths); - rcloud.session_init = function(username, token) { - return rcloud_ocaps.session_initAsync(username, token); + rcloud.session_init = function(session_type, username, token) { + return rcloud_ocaps.session_initAsync(session_type, username, token); }; - rcloud.compute_init = function(username, token) { - return rcloud_ocaps.compute_initAsync(username, token); + rcloud.compute_init = function(session_type, username, token) { + return rcloud_ocaps.compute_initAsync(session_type, username, token); }; rcloud.signal_to_compute = function(signal) { @@ -3819,16 +3823,16 @@ function could_not_initialize_error(err) { return msg; } -function on_connect_anonymous_allowed(ocaps) { +function on_connect_anonymous_allowed(ocaps, session_type) { var promise_c, promise_s; rcloud = RCloud.create(ocaps.rcloud); if (rcloud.authenticated) { - promise_c = rcloud.compute_init(rcloud.username(), rcloud.github_token()); - promise_s = rcloud.session_init(rcloud.username(), rcloud.github_token()); + promise_c = rcloud.compute_init(session_type, rcloud.username(), rcloud.github_token()); + promise_s = rcloud.session_init(session_type, rcloud.username(), rcloud.github_token()); } else { - promise_c = rcloud.anonymous_compute_init(); - promise_s = rcloud.anonymous_session_init(); + promise_c = rcloud.anonymous_compute_init(session_type); + promise_s = rcloud.anonymous_session_init(session_type); } promise_c.catch(function(e) { @@ -3845,19 +3849,19 @@ function on_connect_anonymous_allowed(ocaps) { return Promise.all([promise_c, promise_s]); } -function on_connect_anonymous_disallowed(ocaps) { +function on_connect_anonymous_disallowed(ocaps, session_type) { rcloud = RCloud.create(ocaps.rcloud); if (!rcloud.authenticated) { return Promise.reject(new Error("Authentication required")); } - var res_c = rcloud.compute_init(rcloud.username(), rcloud.github_token()); - var res_s = rcloud.session_init(rcloud.username(), rcloud.github_token()); + var res_c = rcloud.compute_init(session_type, rcloud.username(), rcloud.github_token()); + var res_s = rcloud.session_init(session_type, rcloud.username(), rcloud.github_token()); return Promise.all([res_c, res_s]); } -function rclient_promise(allow_anonymous) { +function rclient_promise(allow_anonymous, session_type) { return new Promise(function(resolve, reject) { rclient = RClient.create({ debug: false, @@ -3876,8 +3880,8 @@ function rclient_promise(allow_anonymous) { rclient.allow_anonymous_ = allow_anonymous; }).then(function(ocaps) { var promise = allow_anonymous ? - on_connect_anonymous_allowed(ocaps) : - on_connect_anonymous_disallowed(ocaps); + on_connect_anonymous_allowed(ocaps, session_type) : + on_connect_anonymous_disallowed(ocaps, session_type); return promise; }).then(function(hello) { if (!$("#output > .response").length) @@ -3942,9 +3946,9 @@ RCloud.session = { rclient.close(); return rclient_promise(anonymous); }); - }, init: function(allow_anonymous) { + }, init: function(allow_anonymous, session_type) { this.first_session_ = true; - return rclient_promise(allow_anonymous); + return rclient_promise(allow_anonymous, session_type); } }; diff --git a/htdocs/js/rcloud_bundle.min.js b/htdocs/js/rcloud_bundle.min.js index 7d83a8a3d3..1b823ecf89 100644 --- a/htdocs/js/rcloud_bundle.min.js +++ b/htdocs/js/rcloud_bundle.min.js @@ -1,6 +1,6 @@ -RClient={create:function(opts){opts=_.defaults(opts,{debug:false});function on_connect(){if(!rserve.ocap_mode){RCloud.UI.session_pane.post_error(ui_utils.disconnection_error("Expected an object-capability Rserve. Shutting Down!"));shutdown();return}var session_mode=opts.mode?opts.mode:"client";rserve.ocap([token,execToken],session_mode,function(err,ocaps){if(err)on_error(err[0],err[1]);else{ocaps=Promise.promisifyAll(ocaps);if(ocaps===null){on_error("Login failed. Shutting down!")}else if(RCloud.is_exception(ocaps)){on_error(ocaps)}else{result.running=true;opts.on_connect&&opts.on_connect.call(result,ocaps)}}})}function shutdown(){if(!clean){$("#input-div").hide()}if(!rserve.closed)rserve.close()}function on_error(msg,status_code){if(opts.debug){debugger}if(opts.on_error&&opts.on_error(msg,status_code))return;RCloud.UI.session_pane.post_error(ui_utils.disconnection_error(msg));shutdown()}function on_close(msg){if(opts.debug){debugger}if(!clean){RCloud.UI.fatal_dialog("Your session has been logged out.","Reconnect",ui_utils.relogin_uri());shutdown()}}var token=$.cookies.get().token;var execToken=$.cookies.get().execToken;var rserve=Rserve.create({host:opts.host,on_connect:on_connect,on_error:on_error,on_close:on_close,on_data:opts.on_data,on_oob_message:opts.on_oob_message});var result;var clean=false;result={_rserve:rserve,host:opts.host,running:false,post_response:function(msg){var d=$("
").html(msg);$("#output").append(d)},post_rejection:function(e){RCloud.UI.session_pane.post_error(e.message);throw e},close:function(){clean=true;shutdown()}};return result}};RCloud={};RCloud.is_exception=function(v){return _.isObject(v)&&v.r_attributes&&v.r_attributes["class"]==="OCAP-eval-error"};RCloud.exception_message=function(v){if(!RCloud.is_exception(v))throw new Error("Not an R exception value");return v["error"]};RCloud.promisify_paths=function(){function rcloud_handler(command,promise_fn){function success(result){if(result&&RCloud.is_exception(result)){var tb=result["traceback"]?result["traceback"]:"";if(tb.join)tb=tb.join("\n");throw new Error(command+": "+result.error+"R trace:\n"+tb)}return result}return function(){return promise_fn.apply(this,arguments).then(success)}}function process_paths(ocaps,paths,replace){function get(path){var v=ocaps;for(var i=0;i
");pre.append(current_result_);result_div_.append(pre)}current_result_.append(_.escape(r));break;case"error":if(!current_error_){pre=$("");current_error_=$('
');pre.append(current_error_);result_div_.append(pre)}current_error_.append(_.escape(r));break;case"selection":case"html":result_div_.append(r);break;case"deferred_result":result_div_.append(''+r+"");break;default:throw new Error("unknown result type "+type)}result_updated()},end_output:function(error){if(!has_result_){result_div_.empty();has_result_=true}this.state_changed(error?"error":running_state_==="unknown-running"?"ready":"complete");current_result_=current_error_=null},clear_result:clear_result,set_readonly:function(readonly){am_read_only_=readonly;if(ace_widget_)ui_utils.set_ace_readonly(ace_widget_,readonly);[cell_controls_,above_between_controls_,left_controls_].forEach(function(controls){if(controls)controls.set_flag("modify",!readonly)});click_to_edit(code_div_.find("pre"),!readonly);cell_status_.toggleClass("readonly",readonly)},set_show_cell_numbers:function(whether){left_controls_.set_flag("cell-numbers",whether)},click_to_edit:click_to_edit,execute_cell:function(){return cell_model.parent_model.controller.save().then(function(){cell_model.controller.enqueue_execution_snapshot()})},toggle_edit:function(){return this.edit_source(!edit_mode_)},edit_source:function(edit_mode,event){if(edit_mode===edit_mode_){if(edit_mode)ace_widget_.focus();return}if(edit_mode){if(cell_controls_)cell_controls_.controls["edit"].control.find("i").toggleClass("icon-border",true);if(RCloud.language.is_a_markdown(language))this.hide_source(false);code_div_.hide();create_edit_widget();outer_ace_div.show();ace_widget_.resize(true);set_widget_height();ace_widget_.resize(true);if(cell_controls_)cell_controls_.set_flag("edit",true);outer_ace_div.show();ace_widget_.resize();ace_widget_.focus();if(event){var scrollTopOffset=ace_widget_.getSession().getScrollTop();var screenPos=ace_widget_.renderer.pixelToScreenCoordinates(event.pageX,event.pageY-scrollTopOffset);var docPos=ace_session_.screenToDocumentPosition(Math.abs(screenPos.row),Math.abs(screenPos.column));var Range=ace.require("ace/range").Range;var row=Math.abs(docPos.row),column=Math.abs(docPos.column);var range=new Range(row,column,row,column);ace_widget_.getSelection().setSelectionRange(range)}}else{if(cell_controls_)cell_controls_.controls["edit"].control.find("i").toggleClass("icon-border",false);var new_content=update_model();if(new_content!==null)cell_model.parent_model.controller.update_cell(cell_model);source_div_.css({height:""});if(cell_controls_)cell_controls_.set_flag("edit",false);code_div_.show();outer_ace_div.hide()}edit_mode_=edit_mode;this.change_highlights(highlights_)},hide_source:function(whether){if(whether)source_div_.hide();else source_div_.show()},toggle_results:function(val){if(val===undefined)val=result_div_.is(":hidden");if(cell_controls_)cell_controls_.controls["results"].control.find("i").toggleClass("icon-border",val);if(val)result_div_.show();else result_div_.hide()},get_input:function(type,prompt,k){if(!has_result_){result_div_.empty();has_result_=true}prompt_text_=_.escape(prompt).replace(/\n/g,"");create_input_widget();input_widget_.setValue("");input_div_.show();input_div_.css("height","36px");input_widget_.renderer.$gutterLayer.gutterWidth=0;input_widget_.renderer.$changes|=input_widget_.renderer.__proto__.CHANGE_FULL;input_widget_.resize(true);input_widget_.focus();input_div_.css("border-color","#eeeeee");var dir=false;var switch_color=function(){input_div_.animate({borderColor:dir?"#ffac88":"#E34234"},{duration:1e3,easing:"easeInOutCubic",queue:false});dir=!dir};switch_color();input_anim_=window.setInterval(switch_color,1e3);ui_utils.scroll_into_view($("#rcloud-cellarea"),100,100,notebook_cell_div,input_div_);input_kont_=k},div:function(){return notebook_cell_div},update_model:function(){return update_model()},focus:function(){ace_widget_.focus();return this},get_content:function(){return cell_model.content()},reformat:function(){if(edit_mode_){ace_widget_.resize();set_widget_height();ace_widget_.resize()}return this},check_buttons:function(){if(above_between_controls_)above_between_controls_.betweenness(!!cell_model.parent_model.prior_cell(cell_model));return this},change_highlights:function(ranges){highlights_=ranges;if(edit_mode_){var markers=ace_session_.getMarkers();for(var marker in markers){if(markers[marker].type==="rcloud-select")ace_session_.removeMarker(marker)}if(ranges)ranges.forEach(function(range){var ace_range=ui_utils.ace_range_of_character_range(ace_widget_,range.begin,range.end);ace_session_.addMarker(ace_range,highlight_classes(range.kind),"rcloud-select");if(/active/.test(range.kind)){ace_widget_.scrollToLine(ace_range.start.row);window.setTimeout(function(){var hl=ace_div.find(".find-highlight."+range.kind);if(hl.size())ui_utils.scroll_into_view($("#rcloud-cellarea"),100,100,notebook_cell_div,ace_div,hl)},0)}})}else{assign_code();var $active=code_div_.find(".find-highlight.active, .find-highlight.activereplaced");if($active.size())ui_utils.scroll_into_view($("#rcloud-cellarea"),100,100,notebook_cell_div,code_div_,$active)}return this}});result.edit_source(false);return result}Notebook.Cell.create_html_view=function(cell_model){return create_cell_html_view(cell_model.language(),cell_model)}})();Notebook.Cell.create_model=function(content,language){var id_=-1;var result=Notebook.Buffer.create_model(content,language);var base_change_object=result.change_object;_.extend(result,{id:function(new_id){if(!_.isUndefined(new_id)&&new_id!=id_){id_=new_id;this.notify_views(function(view){view.id_updated()})}return id_},filename:function(){if(arguments.length)throw new Error("can't set filename of cell");return Notebook.part_name(this.id(),this.language())},get_execution_snapshot:function(){var language=this.language()||"Text";return{controller:this.controller,json_rep:this.json(),partname:Notebook.part_name(this.id(),language),language:language,version:this.parent_model.controller.current_gist().history[0].version}},json:function(){return{content:content,language:this.language()}},change_object:function(obj){obj=obj||{};if(obj.id&&obj.filename)throw new Error("must specify only id or filename");if(!obj.filename){var id=obj.id||this.id();if(id>0!==true)throw new Error("bad id for cell change object: "+id);obj.filename=Notebook.part_name(id,this.language())}if(obj.rename&&_.isNumber(obj.rename))obj.rename=Notebook.part_name(obj.rename,this.language());return base_change_object.call(this,obj)}});return result};Notebook.Cell.create_controller=function(cell_model){var execution_context_=null;var result={enqueue_execution_snapshot:function(){var that=this;if(!execution_context_){function appender(type){return that.append_result.bind(this,type)}var resulter=appender("code");execution_context_={end:this.end_output.bind(this),out:resulter,err:appender("error"),msg:resulter,html_out:appender("html"),deferred_result:appender("deferred_result"),selection_out:appender("selection"),"in":this.get_input.bind(this,"in")}}var context_id=RCloud.register_output_context(execution_context_);that.set_run_state("waiting");that.edit_source(false);var snapshot=cell_model.get_execution_snapshot();RCloud.UI.run_button.enqueue(function(){that.set_run_state("running");return cell_model.parent_model.controller.execute_cell_version(context_id,snapshot)},function(){that.set_run_state("cancelled")})},set_run_state:function(msg){cell_model.notify_views(function(view){view.state_changed(msg)})},clear_result:function(){cell_model.notify_views(function(view){view.clear_result()})},append_result:function(type,msg){cell_model.notify_views(function(view){view.add_result(type,msg)})},end_output:function(error){cell_model.notify_views(function(view){if(error&&error!==true)view.add_result("error",error);view.end_output(error)})},get_input:function(type,prompt,k){var view=_.find(cell_model.views,function(v){return v.get_input});if(!view)k("cell view does not support input",null);else view.get_input(type,prompt,k)},edit_source:function(whether){cell_model.notify_views(function(view){view.edit_source(whether)})},change_language:function(language){cell_model.language(language)}};return result};Notebook.Cell.preprocessors=RCloud.extension.create();Notebook.Cell.postprocessors=RCloud.extension.create();Notebook.Cell.postprocessors.add({device_pixel_ratio:{sort:1e3,disable:true,process:function(div){var dpr=rcloud.display.get_device_pixel_ratio();div.find("img").each(function(i,img){function update(){img.style.width=img.width/dpr}if(img.width===0){$(img).on("load",update)}else{update()}})}},deferred_results:{sort:2e3,process:function(div){var uuid=rcloud.deferred_knitr_uuid;div.find("span.deferred-result").each(function(){var that=this;var uuids=this.textContent.split("|");var ocap=[uuids[1]];ocap.r_attributes={"class":"OCref"};var f=rclient._rserve.wrap_ocap(ocap);f(function(err,future){var data;if(RCloud.is_exception(future)){data=RCloud.exception_message(future);$(that).replaceWith(function(){return ui_utils.string_error(data)})}else{data=future();$(that).replaceWith(function(){return data})}})})}},mathjax:{sort:3e3,process:function(div){if(!_.isUndefined(MathJax))MathJax.Hub.Queue(["Typeset",MathJax.Hub])}},shade_pre_r:{sort:4e3,process:function(div){div.find("pre code").filter(function(i,e){return e.classList.length>0}).parent().toggleClass("r",true)}},hide_source:{sort:5e3,process:function(div){if(!shell.notebook.controller._r_source_visible){Notebook.hide_r_source(div)}}},click_markdown_code:{sort:6e3,process:function(div,view){view.click_to_edit(div.find("pre.r"),true)}}});Notebook.Cell.preprocessors.add({quote_deferred_results:{sort:1e3,process:function(){var deferred_result_uuid_,deferred_regexp_,deferred_replacement_;function make_deferred_regexp(){deferred_result_uuid_=rcloud.deferred_knitr_uuid;deferred_regexp_=new RegExp(deferred_result_uuid_+"\\|[@a-zA-Z_0-9.]*","g");deferred_replacement_='$&'}return function(r){if(!deferred_result_uuid_!=rcloud.deferred_knitr_uuid)make_deferred_regexp();return r.replace(deferred_regexp_,deferred_replacement_)}}()}});Notebook.create_html_view=function(model,root_div){var show_cell_numbers_;function on_rearrange(){_.each(result.sub_views,function(view){view.check_buttons()})}function init_cell_view(cell_view){cell_view.set_readonly(model.read_only()||shell.is_view_mode());cell_view.set_show_cell_numbers(show_cell_numbers_)}var result={model:model,sub_views:[],asset_sub_views:[],cell_appended:function(cell_model){var cell_view=Notebook.Cell.create_html_view(cell_model);cell_model.views.push(cell_view);root_div.append(cell_view.div());this.sub_views.push(cell_view);init_cell_view(cell_view);on_rearrange();return cell_view},asset_appended:function(asset_model){var asset_view=Notebook.Asset.create_html_view(asset_model);asset_model.views.push(asset_view);$("#asset-list").append(asset_view.div());this.asset_sub_views.push(asset_view);on_rearrange();return asset_view},cell_inserted:function(cell_model,cell_index){var cell_view=Notebook.Cell.create_html_view(cell_model);cell_model.views.push(cell_view);root_div.append(cell_view.div());$(cell_view.div()).insertBefore(root_div.children(".notebook-cell")[cell_index]);this.sub_views.splice(cell_index,0,cell_view);init_cell_view(cell_view);on_rearrange();return cell_view},cell_removed:function(cell_model,cell_index){_.each(cell_model.views,function(view){view.self_removed()});this.sub_views.splice(cell_index,1);on_rearrange()},asset_removed:function(asset_model,asset_index){_.each(asset_model.views,function(view){view.self_removed()});this.asset_sub_views.splice(asset_index,1)},cell_moved:function(cell_model,pre_index,post_index){this.sub_views.splice(pre_index,1);this.sub_views.splice(post_index,0,cell_model.views[0]);on_rearrange()},set_readonly:function(readonly){_.each(this.sub_views,function(view){view.set_readonly(readonly)});_.each(this.asset_sub_views,function(view){view.set_readonly(readonly)})},set_show_cell_numbers:function(whether){show_cell_numbers_=whether;_.each(this.sub_views,function(view){view.set_show_cell_numbers(whether)})},update_urls:function(){RCloud.UI.scratchpad.update_asset_url()},update_model:function(){return _.map(this.sub_views,function(cell_view){return cell_view.update_model()})},reformat:function(){_.each(this.sub_views,function(view){view.reformat()})}};model.views.push(result);return result};Notebook.create_model=function(){var readonly_=false;var user_="";function last_id(cells){if(cells.length)return cells[cells.length-1].id();else return 0}return{cells:[],assets:[],views:[],dishers:[],execution_watchers:[],clear:function(){var cells_removed=this.remove_cell(null,last_id(this.cells));var assets_removed=this.remove_asset(null,this.assets.length);return cells_removed.concat(assets_removed)},get_asset:function(filename){return _.find(this.assets,function(asset){return asset.filename()==filename})},append_asset:function(asset_model,filename,skip_event){asset_model.parent_model=this;var changes=[];changes.push(asset_model.change_object());this.assets.push(asset_model);if(!skip_event)_.each(this.views,function(view){view.asset_appended(asset_model)});return changes},append_cell:function(cell_model,id,skip_event){cell_model.parent_model=this;cell_model.renew_content();var changes=[];var n=1;id=id||1;id=Math.max(id,last_id(this.cells)+1);while(n){cell_model.id(id);changes.push(cell_model.change_object());this.cells.push(cell_model);if(!skip_event)_.each(this.views,function(view){view.cell_appended(cell_model)});++id;--n}return changes},insert_cell:function(cell_model,id,skip_event){var that=this;cell_model.parent_model=this;cell_model.renew_content();var changes=[];var n=1,x=0;while(x"+files[i]+""}RCloud.UI.help_frame.display_content(html)},editor:function(ctx,what,content,name){append_session_info("what: "+what+"\ncontents:"+content+"\nname: "+name+"\n")},"console.out":forward_to_context("out"),"console.msg":forward_to_context("msg"),"console.err":forward_to_context("err"),"img.url.update":handle_img.bind(null,"img.url.update"),"img.url.final":handle_img.bind(null,"img.url.final"),stdout:append_session_info,stderr:append_session_info,"html.out":forward_to_context("html_out"),"deferred.result":forward_to_context("deferred_result")};var on_data=function(v){v=v.value.json();console.log("OOB send arrived: ['"+v[0]+"']"+(oob_sends[v[0]]?"":" (unhandled)"));if(oob_sends[v[0]])oob_sends[v[0]].apply(null,v.slice(1))};var oob_messages={"console.in":forward_to_context("in",true)};var on_message=function(v,k){v=v.value.json();console.log("OOB message arrived: ['"+v[0]+"']"+(oob_messages[v[0]]?"":" (unhandled)"));if(oob_messages[v[0]]){v.push(k);oob_messages[v[0]].apply(null,v.slice(1))}else k("unhandled",null)};function could_not_initialize_error(err){var msg="Could not initialize session. The GitHub backend might be down or you might have an invalid authorization token. (You could try clearing your cookies, for example).";if(err)msg+="
'+message+"
");body.append(message_,default_button);if(href)body.append(ignore_button);body.append('');default_button.click(function(e){e.preventDefault();if(href)window.location=href;else fatal_dialog_.modal("hide")});ignore_button.click(function(){fatal_dialog_.modal("hide")});fatal_dialog_=$('').append($('').append($('').append($('').append(body))));$("body").append(fatal_dialog_);fatal_dialog_.on("shown.bs.modal",function(){default_button.focus()})}else message_.text(message);fatal_dialog_.modal({keyboard:false})}})();RCloud.UI.find_replace=function(){var find_dialog_=null,regex_,find_desc_,find_input_,replace_desc_,replace_input_,replace_stuff_,find_next_,find_last_,replace_next_,replace_all_,shown_=false,replace_mode_=false,find_cycle_=null,replace_cycle_=null,matches_=[],active_match_;function toggle_find_replace(replace){if(!find_dialog_){find_dialog_=$('');var find_form=$('');find_desc_=$('');find_input_=$('');find_next_=$('');find_last_=$('');var replace_break=$("Import notebooks from another GitHub instance.
Currently import does not preserve history.
",'source repo api url: ','
notebooks:
prefix (e.g. folder/
to put notebooks in a folder): '].join("")));var cancel=$('Cancel').on("click",function(){$(dialog).modal("hide")});var go=$('Import').on("click",do_import);var footer=$('
PDF preview not supported
");else sbin.html('');sbin.show()}else{binary_mode_=false;that.widget.setReadOnly(false);$("#scratchpad-binary").hide();$("#scratchpad-editor").show();$("#scratchpad-editor > *").show();this.change_content(content);var model_cursor=asset_model.cursor_position();if(model_cursor){ui_utils.ace_set_pos(this.widget,model_cursor)}else{ui_utils.ace_set_pos(this.widget,0,0)}ui_utils.on_next_tick(function(){that.session.getUndoManager().reset()});that.language_updated();that.widget.resize();that.widget.focus()}},update_model:function(){return this.current_model&&!binary_mode_?this.current_model.content(this.widget.getSession().getValue()):null},content_updated:function(){var changed=false;changed=this.current_model.content();binary_mode_=Notebook.is_binary_content(changed);if(changed&&!binary_mode_){var range=this.widget.getSelection().getRange();this.change_content(changed);this.widget.getSelection().setSelectionRange(range)}return changed},language_updated:function(){if(!binary_mode_){var lang=this.current_model.language();var LangMode=ace.require(RCloud.language.ace_mode(lang)).Mode;this.session.setMode(new LangMode(false,this.session.doc,this.session))}},set_readonly:function(readonly){if(!shell.is_view_mode()){if(this.widget&&!binary_mode_)ui_utils.set_ace_readonly(this.widget,readonly);if(readonly)$("#new-asset").hide();else $("#new-asset").show()}},update_asset_url:function(){if(this.current_model)$("#asset-link").attr("href",make_asset_url(this.current_model))},clear:function(){if(!this.exists)return;this.change_content("");this.session.getUndoManager().reset();this.widget.resize()}}}();RCloud.UI.search=function(){var page_size_=10;var search_err_msg=['The search engine in RCloud uses Lucene for advanced search features.',"It appears you may have used one of the special characters in Lucene syntax incorrectly. ",'Please see this link to learn about Lucene syntax. ','
Or, if you mean to search for the character itself, escape it using a backslash, e.g. "foo\\:"
'];function go_to_page(page_num,incr_by){var start=parseInt(page_num)*parseInt(incr_by);var end=parseInt(start)+parseInt(incr_by);var qry=$("#input-text-search").val();var sortby=$("#sort-by option:selected").val();var orderby=$("#order-by option:selected").val();$("#input-text-search").blur();if(!($("#input-text-search").val()===""))RCloud.UI.search.exec(qry,sortby,orderby,start,end,true)}function sortby(){return $("#sort-by option:selected").val()}function orderby(){return $("#order-by option:selected").val()}function all_sources(){return $("#all-sources").is(":checked")}function order_from_sort(){var orderby;switch(sortby()){case"starcount":case"updated_at":orderby="desc";break;case"user":case"description":orderby="asc";break}$("#order-by").val(orderby)}return{body:function(){return RCloud.UI.panel_loader.load_snippet("search-snippet")},init:function(){if(!rcloud.search)$("#search-wrapper").text("Search engine not enabled on server");else{$("#search-form").submit(function(e){searchproc();return false});rcloud.get_gist_sources().then(function(sources){if(_.isString(sources))sources=[sources];if(sources.length<2){$("#all-sources").parent().hide()}else{$("#all-sources").change(function(e){var val=all_sources();rcloud.config.set_user_option("search-all-sources",val)})}});$("#sort-by").change(function(){rcloud.config.set_user_option("search-sort-by",sortby());order_from_sort();rcloud.config.set_user_option("search-order-by",orderby());searchproc()});$("#order-by").change(function(){rcloud.config.set_user_option("search-order-by",orderby());searchproc()});var searchproc=function(){var start=0;var qry=$("#input-text-search").val();$("#input-text-search").focus();if(!($("#input-text-search").val()==="")){RCloud.UI.search.exec(qry,sortby(),orderby(),start,page_size_)}else{$("#paging").html("");$("#search-results").html("");$("#search-summary").html("")}}}},load:function(){return rcloud.config.get_user_option(["search-all-sources","search-results-per-page","search-sort-by","search-order-by"]).then(function(opts){$("#all-sources").prop("checked",opts["search-all-sources"]);if(opts["search-results-per-page"])page_size_=opts["search-results-per-page"];if(!opts["search-sort-by"])opts["search-sort-by"]="starcount";$("#sort-by").val(opts["search-sort-by"]);if(opts["search-order-by"])$("#order-by").val(opts["search-order-by"]);else order_from_sort()})},panel_sizer:function(el){var padding=RCloud.UI.collapsible_column.default_padder(el);var height=24+$("#search-summary").height()+$("#search-results").height()+$("#search-results-pagination").height();height+=40;return{height:height,padding:padding}},toggle:function(id,togid){$("#"+togid+"").text(function(_,txt){var ret="";if(txt.indexOf("Show me more...")>-1){ret="Show me less...";$("#"+id+"").css("height","auto")}else{ret="Show me more...";$("#"+id+"").css("height","150px")}return ret});return false},exec:function(query,sortby,orderby,start,noofrows,pgclick){function summary(html,color){$("#search-summary").css("color",color||"black");$("#search-summary").show().html($("").append(html))}function err_msg(html,color){$("#search-summary").css("display","none");$("#search-results").css("color",color||"black");$("#search-results-row").show().animate({scrollTop:$(document).height()},"slow");$("#search-results").show().html($("").append(html))}function create_list_of_search_results(d){var i;var custom_msg="";if(d===null||d==="null"||d===""){summary("No Results Found")}else if(d[0]==="error"){d[1]=d[1].replace(/\n/g,""+content[l]+"
"+'"+d[i].user+" / "+d[i].notebook+""+image_string+" modified at "+d[i].updated_at+" | |
"+parts_table+" |
File "+filename+" exists.
");var overwrite=bootstrap_utils.button({"class":"btn-danger"}).click(overwrite_click).text("Overwrite");p.append(overwrite);var alert_box=result_alert(p);$("button.close",alert_box).click(function(){callback(new Error("Overwrite cancelled"),null)})})}}options=upload_ui_opts(options||{});if(options.$result_panel.length)RCloud.UI.right_panel.collapse(options.$result_panel,false);var file_error_handler=function(err){var message=err.message;var p,done=true;if(message==="empty"){p=$("File is empty.
")}else if(message==="Overwrite cancelled"){p=$("").append(message)}else if(message==="badname"){p=$("
Filename not allowed.
")}else{p=$("(unexpected) "+message+"
");console.log(message,err.stack)}result_alert(p);throw err};var promise=to_notebook?RCloud.upload_assets(options,asset_react(options)):RCloud.upload_files(options,file_react(options));return promise.catch(function(err){return file_error_handler(err,options)}).then(function(){if(options.$progress.length)window.setTimeout(function(){options.$progress.hide()},5e3)})}return upload_files}();RCloud.UI.upload_frame={body:function(){return RCloud.UI.panel_loader.load_snippet("file-upload-snippet")},init:function(){$("#file").change(function(){$("#progress-bar").css("width","0%")});$("#upload-submit").click(function(){if($("#file")[0].files.length===0)return;var to_notebook=$("#upload-to-notebook").is(":checked");RCloud.UI.upload_with_alerts(to_notebook).catch(function(){})});RCloud.session.listeners.push({on_reset:function(){$(".progress").hide();$("#file-upload-results").empty()}})},panel_sizer:function(el){var padding=RCloud.UI.collapsible_column.default_padder(el);var height=24+$("#file-upload-controls").height()+$("#file-upload-results").height();return{height:height,padding:padding}}};RCloud.UI.notebook_protection_logger={timeout:0,log:function(val){var that=this;$(".logging-panel").removeClass("red").removeClass("white").addClass("green");$(".logging-panel span").text(val);window.clearTimeout(this.timeout);this.timeout=setTimeout(function(){$(".logging-panel").removeClass("red").removeClass("green").addClass("white");$(".logging-panel span").html(" ")},2e4)},warn:function(val){var that=this;$(".logging-panel").removeClass("green").removeClass("white").addClass("red");$(".logging-panel span").text(val);window.clearTimeout(this.timeout);this.timeout=setTimeout(function(){$(".logging-panel").removeClass("red").removeClass("green").addClass("white");$(".logging-panel span").html(" ")},2e4)},clear:function(){$(".logging-panel").removeClass("red").removeClass("green").addClass("white");$(".logging-panel span").html(" ")}};RCloud.UI.notebook_protection=function(){this.defaultCryptogroup=null;this.defaultNotebook=null;this.userId=null;this.userLogin=null;this.appScope=null;this.appInited=false;return{init:function(state){if(!this.appInited){this.appInited=true;this.buildDom();var that=this;require(["angular","./../../js/ui/notebook_protection_app","angular-selectize"],function(angular,app,selectize){"use strict";angular.element(document).ready(function(){_.delay(function(){angular.bootstrap($("#protection-app")[0],["NotebookProtectionApp"]);angular.resumeBootstrap()},100);_.delay(function(){that.appScope=angular.element(document.getElementById("protection-app")).scope();that.launch(state);$("#notebook-protection-dialog").modal({keyboard:false})},200)})})}else{this.launch(state);$("#notebook-protection-dialog").modal({keyboard:false})}},launch:function(state){if(state==="both-tabs-enabled"){$("#protection-app #tab2").removeClass("active");$("#protection-app #tab1").removeClass("disabled").addClass("active");$("#protection-app #tab1 a").attr("href","#notebook-tab").attr("data-toggle","tab");$("#protection-app #tab2 a").tab("show");$("#protection-app #tab1 a").tab("show");this.appScope.initBoth()}else if(state==="group-tab-enabled"){$("#protection-app #tab1").removeClass("active").addClass("disabled");$("#protection-app #tab1 a").attr("href","#").removeAttr("data-toggle");$("#protection-app #tab2 a").tab("show");this.appScope.initGroups()}},buildDom:function(){var body=$('');body.append(RCloud.UI.panel_loader.load_snippet("notebook-protection-modal"));var header=$(['
");pre.append(current_result_);result_div_.append(pre)}current_result_.append(_.escape(r));break;case"error":if(!current_error_){pre=$("");current_error_=$('
');pre.append(current_error_);result_div_.append(pre)}current_error_.append(_.escape(r));break;case"selection":case"html":result_div_.append(r);break;case"deferred_result":result_div_.append(''+r+"");break;default:throw new Error("unknown result type "+type)}result_updated()},end_output:function(error){if(!has_result_){result_div_.empty();has_result_=true}this.state_changed(error?"error":running_state_==="unknown-running"?"ready":"complete");current_result_=current_error_=null},clear_result:clear_result,set_readonly:function(readonly){am_read_only_=readonly;if(ace_widget_)ui_utils.set_ace_readonly(ace_widget_,readonly);[cell_controls_,above_between_controls_,left_controls_].forEach(function(controls){if(controls)controls.set_flag("modify",!readonly)});click_to_edit(code_div_.find("pre"),!readonly);cell_status_.toggleClass("readonly",readonly)},set_show_cell_numbers:function(whether){left_controls_.set_flag("cell-numbers",whether)},click_to_edit:click_to_edit,execute_cell:function(){return cell_model.parent_model.controller.save().then(function(){cell_model.controller.enqueue_execution_snapshot()})},toggle_edit:function(){return this.edit_source(!edit_mode_)},edit_source:function(edit_mode,event){if(edit_mode===edit_mode_){if(edit_mode)ace_widget_.focus();return}if(edit_mode){if(cell_controls_)cell_controls_.controls["edit"].control.find("i").toggleClass("icon-border",true);if(RCloud.language.is_a_markdown(language))this.hide_source(false);code_div_.hide();create_edit_widget();outer_ace_div.show();ace_widget_.resize(true);set_widget_height();ace_widget_.resize(true);if(cell_controls_)cell_controls_.set_flag("edit",true);outer_ace_div.show();ace_widget_.resize();ace_widget_.focus();if(event){var scrollTopOffset=ace_widget_.getSession().getScrollTop();var screenPos=ace_widget_.renderer.pixelToScreenCoordinates(event.pageX,event.pageY-scrollTopOffset);var docPos=ace_session_.screenToDocumentPosition(Math.abs(screenPos.row),Math.abs(screenPos.column));var Range=ace.require("ace/range").Range;var row=Math.abs(docPos.row),column=Math.abs(docPos.column);var range=new Range(row,column,row,column);ace_widget_.getSelection().setSelectionRange(range)}}else{if(cell_controls_)cell_controls_.controls["edit"].control.find("i").toggleClass("icon-border",false);var new_content=update_model();if(new_content!==null)cell_model.parent_model.controller.update_cell(cell_model);source_div_.css({height:""});if(cell_controls_)cell_controls_.set_flag("edit",false);code_div_.show();outer_ace_div.hide()}edit_mode_=edit_mode;this.change_highlights(highlights_)},hide_source:function(whether){if(whether)source_div_.hide();else source_div_.show()},toggle_results:function(val){if(val===undefined)val=result_div_.is(":hidden");if(cell_controls_)cell_controls_.controls["results"].control.find("i").toggleClass("icon-border",val);if(val)result_div_.show();else result_div_.hide()},get_input:function(type,prompt,k){if(!has_result_){result_div_.empty();has_result_=true}prompt_text_=_.escape(prompt).replace(/\n/g,"");create_input_widget();input_widget_.setValue("");input_div_.show();input_div_.css("height","36px");input_widget_.renderer.$gutterLayer.gutterWidth=0;input_widget_.renderer.$changes|=input_widget_.renderer.__proto__.CHANGE_FULL;input_widget_.resize(true);input_widget_.focus();input_div_.css("border-color","#eeeeee");var dir=false;var switch_color=function(){input_div_.animate({borderColor:dir?"#ffac88":"#E34234"},{duration:1e3,easing:"easeInOutCubic",queue:false});dir=!dir};switch_color();input_anim_=window.setInterval(switch_color,1e3);ui_utils.scroll_into_view($("#rcloud-cellarea"),100,100,notebook_cell_div,input_div_);input_kont_=k},div:function(){return notebook_cell_div},update_model:function(){return update_model()},focus:function(){ace_widget_.focus();return this},get_content:function(){return cell_model.content()},reformat:function(){if(edit_mode_){ace_widget_.resize();set_widget_height();ace_widget_.resize()}return this},check_buttons:function(){if(above_between_controls_)above_between_controls_.betweenness(!!cell_model.parent_model.prior_cell(cell_model));return this},change_highlights:function(ranges){highlights_=ranges;if(edit_mode_){var markers=ace_session_.getMarkers();for(var marker in markers){if(markers[marker].type==="rcloud-select")ace_session_.removeMarker(marker)}if(ranges)ranges.forEach(function(range){var ace_range=ui_utils.ace_range_of_character_range(ace_widget_,range.begin,range.end);ace_session_.addMarker(ace_range,highlight_classes(range.kind),"rcloud-select");if(/active/.test(range.kind)){ace_widget_.scrollToLine(ace_range.start.row);window.setTimeout(function(){var hl=ace_div.find(".find-highlight."+range.kind);if(hl.size())ui_utils.scroll_into_view($("#rcloud-cellarea"),100,100,notebook_cell_div,ace_div,hl)},0)}})}else{assign_code();var $active=code_div_.find(".find-highlight.active, .find-highlight.activereplaced");if($active.size())ui_utils.scroll_into_view($("#rcloud-cellarea"),100,100,notebook_cell_div,code_div_,$active)}return this}});result.edit_source(false);return result}Notebook.Cell.create_html_view=function(cell_model){return create_cell_html_view(cell_model.language(),cell_model)}})();Notebook.Cell.create_model=function(content,language){var id_=-1;var result=Notebook.Buffer.create_model(content,language);var base_change_object=result.change_object;_.extend(result,{id:function(new_id){if(!_.isUndefined(new_id)&&new_id!=id_){id_=new_id;this.notify_views(function(view){view.id_updated()})}return id_},filename:function(){if(arguments.length)throw new Error("can't set filename of cell");return Notebook.part_name(this.id(),this.language())},get_execution_snapshot:function(){var language=this.language()||"Text";return{controller:this.controller,json_rep:this.json(),partname:Notebook.part_name(this.id(),language),language:language,version:this.parent_model.controller.current_gist().history[0].version}},json:function(){return{content:content,language:this.language()}},change_object:function(obj){obj=obj||{};if(obj.id&&obj.filename)throw new Error("must specify only id or filename");if(!obj.filename){var id=obj.id||this.id();if(id>0!==true)throw new Error("bad id for cell change object: "+id);obj.filename=Notebook.part_name(id,this.language())}if(obj.rename&&_.isNumber(obj.rename))obj.rename=Notebook.part_name(obj.rename,this.language());return base_change_object.call(this,obj)}});return result};Notebook.Cell.create_controller=function(cell_model){var execution_context_=null;var result={enqueue_execution_snapshot:function(){var that=this;if(!execution_context_){function appender(type){return that.append_result.bind(this,type)}var resulter=appender("code");execution_context_={end:this.end_output.bind(this),out:resulter,err:appender("error"),msg:resulter,html_out:appender("html"),deferred_result:appender("deferred_result"),selection_out:appender("selection"),"in":this.get_input.bind(this,"in")}}var context_id=RCloud.register_output_context(execution_context_);that.set_run_state("waiting");that.edit_source(false);var snapshot=cell_model.get_execution_snapshot();RCloud.UI.run_button.enqueue(function(){that.set_run_state("running");return cell_model.parent_model.controller.execute_cell_version(context_id,snapshot)},function(){that.set_run_state("cancelled")})},set_run_state:function(msg){cell_model.notify_views(function(view){view.state_changed(msg)})},clear_result:function(){cell_model.notify_views(function(view){view.clear_result()})},append_result:function(type,msg){cell_model.notify_views(function(view){view.add_result(type,msg)})},end_output:function(error){cell_model.notify_views(function(view){if(error&&error!==true)view.add_result("error",error);view.end_output(error)})},get_input:function(type,prompt,k){var view=_.find(cell_model.views,function(v){return v.get_input});if(!view)k("cell view does not support input",null);else view.get_input(type,prompt,k)},edit_source:function(whether){cell_model.notify_views(function(view){view.edit_source(whether)})},change_language:function(language){cell_model.language(language)}};return result};Notebook.Cell.preprocessors=RCloud.extension.create();Notebook.Cell.postprocessors=RCloud.extension.create();Notebook.Cell.postprocessors.add({device_pixel_ratio:{sort:1e3,disable:true,process:function(div){var dpr=rcloud.display.get_device_pixel_ratio();div.find("img").each(function(i,img){function update(){img.style.width=img.width/dpr}if(img.width===0){$(img).on("load",update)}else{update()}})}},deferred_results:{sort:2e3,process:function(div){var uuid=rcloud.deferred_knitr_uuid;div.find("span.deferred-result").each(function(){var that=this;var uuids=this.textContent.split("|");var ocap=[uuids[1]];ocap.r_attributes={"class":"OCref"};var f=rclient._rserve.wrap_ocap(ocap);f(function(err,future){var data;if(RCloud.is_exception(future)){data=RCloud.exception_message(future);$(that).replaceWith(function(){return ui_utils.string_error(data)})}else{data=future();$(that).replaceWith(function(){return data})}})})}},mathjax:{sort:3e3,process:function(div){if(!_.isUndefined(MathJax))MathJax.Hub.Queue(["Typeset",MathJax.Hub])}},shade_pre_r:{sort:4e3,process:function(div){div.find("pre code").filter(function(i,e){return e.classList.length>0}).parent().toggleClass("r",true)}},hide_source:{sort:5e3,process:function(div){if(!shell.notebook.controller._r_source_visible){Notebook.hide_r_source(div)}}},click_markdown_code:{sort:6e3,process:function(div,view){view.click_to_edit(div.find("pre.r"),true)}}});Notebook.Cell.preprocessors.add({quote_deferred_results:{sort:1e3,process:function(){var deferred_result_uuid_,deferred_regexp_,deferred_replacement_;function make_deferred_regexp(){deferred_result_uuid_=rcloud.deferred_knitr_uuid;deferred_regexp_=new RegExp(deferred_result_uuid_+"\\|[@a-zA-Z_0-9.]*","g");deferred_replacement_='$&'}return function(r){if(!deferred_result_uuid_!=rcloud.deferred_knitr_uuid)make_deferred_regexp();return r.replace(deferred_regexp_,deferred_replacement_)}}()}});Notebook.create_html_view=function(model,root_div){var show_cell_numbers_;function on_rearrange(){_.each(result.sub_views,function(view){view.check_buttons()})}function init_cell_view(cell_view){cell_view.set_readonly(model.read_only()||shell.is_view_mode());cell_view.set_show_cell_numbers(show_cell_numbers_)}var result={model:model,sub_views:[],asset_sub_views:[],cell_appended:function(cell_model){var cell_view=Notebook.Cell.create_html_view(cell_model);cell_model.views.push(cell_view);root_div.append(cell_view.div());this.sub_views.push(cell_view);init_cell_view(cell_view);on_rearrange();return cell_view},asset_appended:function(asset_model){var asset_view=Notebook.Asset.create_html_view(asset_model);asset_model.views.push(asset_view);$("#asset-list").append(asset_view.div());this.asset_sub_views.push(asset_view);on_rearrange();return asset_view},cell_inserted:function(cell_model,cell_index){var cell_view=Notebook.Cell.create_html_view(cell_model);cell_model.views.push(cell_view);root_div.append(cell_view.div());$(cell_view.div()).insertBefore(root_div.children(".notebook-cell")[cell_index]);this.sub_views.splice(cell_index,0,cell_view);init_cell_view(cell_view);on_rearrange();return cell_view},cell_removed:function(cell_model,cell_index){_.each(cell_model.views,function(view){view.self_removed()});this.sub_views.splice(cell_index,1);on_rearrange()},asset_removed:function(asset_model,asset_index){_.each(asset_model.views,function(view){view.self_removed()});this.asset_sub_views.splice(asset_index,1)},cell_moved:function(cell_model,pre_index,post_index){this.sub_views.splice(pre_index,1);this.sub_views.splice(post_index,0,cell_model.views[0]);on_rearrange()},set_readonly:function(readonly){_.each(this.sub_views,function(view){view.set_readonly(readonly)});_.each(this.asset_sub_views,function(view){view.set_readonly(readonly)})},set_show_cell_numbers:function(whether){show_cell_numbers_=whether;_.each(this.sub_views,function(view){view.set_show_cell_numbers(whether)})},update_urls:function(){RCloud.UI.scratchpad.update_asset_url()},update_model:function(){return _.map(this.sub_views,function(cell_view){return cell_view.update_model()})},reformat:function(){_.each(this.sub_views,function(view){view.reformat()})}};model.views.push(result);return result};Notebook.create_model=function(){var readonly_=false;var user_="";function last_id(cells){if(cells.length)return cells[cells.length-1].id();else return 0}return{cells:[],assets:[],views:[],dishers:[],execution_watchers:[],clear:function(){var cells_removed=this.remove_cell(null,last_id(this.cells));var assets_removed=this.remove_asset(null,this.assets.length);return cells_removed.concat(assets_removed)},get_asset:function(filename){return _.find(this.assets,function(asset){return asset.filename()==filename})},append_asset:function(asset_model,filename,skip_event){asset_model.parent_model=this;var changes=[];changes.push(asset_model.change_object());this.assets.push(asset_model);if(!skip_event)_.each(this.views,function(view){view.asset_appended(asset_model)});return changes},append_cell:function(cell_model,id,skip_event){cell_model.parent_model=this;cell_model.renew_content();var changes=[];var n=1;id=id||1;id=Math.max(id,last_id(this.cells)+1);while(n){cell_model.id(id);changes.push(cell_model.change_object());this.cells.push(cell_model);if(!skip_event)_.each(this.views,function(view){view.cell_appended(cell_model)});++id;--n}return changes},insert_cell:function(cell_model,id,skip_event){var that=this;cell_model.parent_model=this;cell_model.renew_content();var changes=[];var n=1,x=0;while(x"+files[i]+""}RCloud.UI.help_frame.display_content(html)},editor:function(ctx,what,content,name){append_session_info("what: "+what+"\ncontents:"+content+"\nname: "+name+"\n")},"console.out":forward_to_context("out"),"console.msg":forward_to_context("msg"),"console.err":forward_to_context("err"),"img.url.update":handle_img.bind(null,"img.url.update"),"img.url.final":handle_img.bind(null,"img.url.final"),stdout:append_session_info,stderr:append_session_info,"html.out":forward_to_context("html_out"),"deferred.result":forward_to_context("deferred_result")};var on_data=function(v){v=v.value.json();console.log("OOB send arrived: ['"+v[0]+"']"+(oob_sends[v[0]]?"":" (unhandled)"));if(oob_sends[v[0]])oob_sends[v[0]].apply(null,v.slice(1))};var oob_messages={"console.in":forward_to_context("in",true)};var on_message=function(v,k){v=v.value.json();console.log("OOB message arrived: ['"+v[0]+"']"+(oob_messages[v[0]]?"":" (unhandled)"));if(oob_messages[v[0]]){v.push(k);oob_messages[v[0]].apply(null,v.slice(1))}else k("unhandled",null)};function could_not_initialize_error(err){var msg="Could not initialize session. The GitHub backend might be down or you might have an invalid authorization token. (You could try clearing your cookies, for example).";if(err)msg+="
'+message+"
");body.append(message_,default_button);if(href)body.append(ignore_button);body.append('');default_button.click(function(e){e.preventDefault();if(href)window.location=href;else fatal_dialog_.modal("hide")});ignore_button.click(function(){fatal_dialog_.modal("hide")});fatal_dialog_=$('').append($('').append($('').append($('').append(body))));$("body").append(fatal_dialog_);fatal_dialog_.on("shown.bs.modal",function(){default_button.focus()})}else message_.text(message);fatal_dialog_.modal({keyboard:false})}})();RCloud.UI.find_replace=function(){var find_dialog_=null,regex_,find_desc_,find_input_,replace_desc_,replace_input_,replace_stuff_,find_next_,find_last_,replace_next_,replace_all_,shown_=false,replace_mode_=false,find_cycle_=null,replace_cycle_=null,matches_=[],active_match_;function toggle_find_replace(replace){if(!find_dialog_){find_dialog_=$('');var find_form=$('');find_desc_=$('');find_input_=$('');find_next_=$('');find_last_=$('');var replace_break=$("Import notebooks from another GitHub instance.
Currently import does not preserve history.
",'source repo api url: ','
notebooks:
prefix (e.g. folder/
to put notebooks in a folder): '].join("")));var cancel=$('Cancel').on("click",function(){$(dialog).modal("hide")});var go=$('Import').on("click",do_import);var footer=$('
PDF preview not supported
");else sbin.html('');sbin.show()}else{binary_mode_=false;that.widget.setReadOnly(false);$("#scratchpad-binary").hide();$("#scratchpad-editor").show();$("#scratchpad-editor > *").show();this.change_content(content);var model_cursor=asset_model.cursor_position();if(model_cursor){ui_utils.ace_set_pos(this.widget,model_cursor)}else{ui_utils.ace_set_pos(this.widget,0,0)}ui_utils.on_next_tick(function(){that.session.getUndoManager().reset()});that.language_updated();that.widget.resize();that.widget.focus()}},update_model:function(){return this.current_model&&!binary_mode_?this.current_model.content(this.widget.getSession().getValue()):null},content_updated:function(){var changed=false;changed=this.current_model.content();binary_mode_=Notebook.is_binary_content(changed);if(changed&&!binary_mode_){var range=this.widget.getSelection().getRange();this.change_content(changed);this.widget.getSelection().setSelectionRange(range)}return changed},language_updated:function(){if(!binary_mode_){var lang=this.current_model.language();var LangMode=ace.require(RCloud.language.ace_mode(lang)).Mode;this.session.setMode(new LangMode(false,this.session.doc,this.session))}},set_readonly:function(readonly){if(!shell.is_view_mode()){if(this.widget&&!binary_mode_)ui_utils.set_ace_readonly(this.widget,readonly);if(readonly)$("#new-asset").hide();else $("#new-asset").show()}},update_asset_url:function(){if(this.current_model)$("#asset-link").attr("href",make_asset_url(this.current_model))},clear:function(){if(!this.exists)return;this.change_content("");this.session.getUndoManager().reset();this.widget.resize()}}}();RCloud.UI.search=function(){var page_size_=10;var search_err_msg=['The search engine in RCloud uses Lucene for advanced search features.',"It appears you may have used one of the special characters in Lucene syntax incorrectly. ",'Please see this link to learn about Lucene syntax. ','
Or, if you mean to search for the character itself, escape it using a backslash, e.g. "foo\\:"
'];function go_to_page(page_num,incr_by){var start=parseInt(page_num)*parseInt(incr_by);var end=parseInt(start)+parseInt(incr_by);var qry=$("#input-text-search").val();var sortby=$("#sort-by option:selected").val();var orderby=$("#order-by option:selected").val();$("#input-text-search").blur();if(!($("#input-text-search").val()===""))RCloud.UI.search.exec(qry,sortby,orderby,start,end,true)}function sortby(){return $("#sort-by option:selected").val()}function orderby(){return $("#order-by option:selected").val()}function all_sources(){return $("#all-sources").is(":checked")}function order_from_sort(){var orderby;switch(sortby()){case"starcount":case"updated_at":orderby="desc";break;case"user":case"description":orderby="asc";break}$("#order-by").val(orderby)}return{body:function(){return RCloud.UI.panel_loader.load_snippet("search-snippet")},init:function(){if(!rcloud.search)$("#search-wrapper").text("Search engine not enabled on server");else{$("#search-form").submit(function(e){searchproc();return false});rcloud.get_gist_sources().then(function(sources){if(_.isString(sources))sources=[sources];if(sources.length<2){$("#all-sources").parent().hide()}else{$("#all-sources").change(function(e){var val=all_sources();rcloud.config.set_user_option("search-all-sources",val)})}});$("#sort-by").change(function(){rcloud.config.set_user_option("search-sort-by",sortby());order_from_sort();rcloud.config.set_user_option("search-order-by",orderby());searchproc()});$("#order-by").change(function(){rcloud.config.set_user_option("search-order-by",orderby());searchproc()});var searchproc=function(){var start=0;var qry=$("#input-text-search").val();$("#input-text-search").focus();if(!($("#input-text-search").val()==="")){RCloud.UI.search.exec(qry,sortby(),orderby(),start,page_size_)}else{$("#paging").html("");$("#search-results").html("");$("#search-summary").html("")}}}},load:function(){return rcloud.config.get_user_option(["search-all-sources","search-results-per-page","search-sort-by","search-order-by"]).then(function(opts){$("#all-sources").prop("checked",opts["search-all-sources"]);if(opts["search-results-per-page"])page_size_=opts["search-results-per-page"];if(!opts["search-sort-by"])opts["search-sort-by"]="starcount";$("#sort-by").val(opts["search-sort-by"]);if(opts["search-order-by"])$("#order-by").val(opts["search-order-by"]);else order_from_sort()})},panel_sizer:function(el){var padding=RCloud.UI.collapsible_column.default_padder(el);var height=24+$("#search-summary").height()+$("#search-results").height()+$("#search-results-pagination").height();height+=40;return{height:height,padding:padding}},toggle:function(id,togid){$("#"+togid+"").text(function(_,txt){var ret="";if(txt.indexOf("Show me more...")>-1){ret="Show me less...";$("#"+id+"").css("height","auto")}else{ret="Show me more...";$("#"+id+"").css("height","150px")}return ret});return false},exec:function(query,sortby,orderby,start,noofrows,pgclick){function summary(html,color){$("#search-summary").css("color",color||"black");$("#search-summary").show().html($("").append(html))}function err_msg(html,color){$("#search-summary").css("display","none");$("#search-results").css("color",color||"black");$("#search-results-row").show().animate({scrollTop:$(document).height()},"slow");$("#search-results").show().html($("").append(html))}function create_list_of_search_results(d){var i;var custom_msg="";if(d===null||d==="null"||d===""){summary("No Results Found")}else if(d[0]==="error"){d[1]=d[1].replace(/\n/g,""+content[l]+"
"+'"+d[i].user+" / "+d[i].notebook+""+image_string+" modified at "+d[i].updated_at+" | |
"+parts_table+" |
File "+filename+" exists.
");var overwrite=bootstrap_utils.button({"class":"btn-danger"}).click(overwrite_click).text("Overwrite");p.append(overwrite);var alert_box=result_alert(p);$("button.close",alert_box).click(function(){callback(new Error("Overwrite cancelled"),null)})})}}options=upload_ui_opts(options||{});if(options.$result_panel.length)RCloud.UI.right_panel.collapse(options.$result_panel,false);var file_error_handler=function(err){var message=err.message;var p,done=true;if(message==="empty"){p=$("File is empty.
")}else if(message==="Overwrite cancelled"){p=$("").append(message)}else if(message==="badname"){p=$("
Filename not allowed.
")}else{p=$("(unexpected) "+message+"
");console.log(message,err.stack)}result_alert(p);throw err};var promise=to_notebook?RCloud.upload_assets(options,asset_react(options)):RCloud.upload_files(options,file_react(options));return promise.catch(function(err){return file_error_handler(err,options)}).then(function(){if(options.$progress.length)window.setTimeout(function(){options.$progress.hide()},5e3)})}return upload_files}();RCloud.UI.upload_frame={body:function(){return RCloud.UI.panel_loader.load_snippet("file-upload-snippet")},init:function(){$("#file").change(function(){$("#progress-bar").css("width","0%")});$("#upload-submit").click(function(){if($("#file")[0].files.length===0)return;var to_notebook=$("#upload-to-notebook").is(":checked");RCloud.UI.upload_with_alerts(to_notebook).catch(function(){})});RCloud.session.listeners.push({on_reset:function(){$(".progress").hide();$("#file-upload-results").empty()}})},panel_sizer:function(el){var padding=RCloud.UI.collapsible_column.default_padder(el);var height=24+$("#file-upload-controls").height()+$("#file-upload-results").height();return{height:height,padding:padding}}};RCloud.UI.notebook_protection_logger={timeout:0,log:function(val){var that=this;$(".logging-panel").removeClass("red").removeClass("white").addClass("green");$(".logging-panel span").text(val);window.clearTimeout(this.timeout);this.timeout=setTimeout(function(){$(".logging-panel").removeClass("red").removeClass("green").addClass("white");$(".logging-panel span").html(" ")},2e4)},warn:function(val){var that=this;$(".logging-panel").removeClass("green").removeClass("white").addClass("red");$(".logging-panel span").text(val);window.clearTimeout(this.timeout);this.timeout=setTimeout(function(){$(".logging-panel").removeClass("red").removeClass("green").addClass("white");$(".logging-panel span").html(" ")},2e4)},clear:function(){$(".logging-panel").removeClass("red").removeClass("green").addClass("white");$(".logging-panel span").html(" ")}};RCloud.UI.notebook_protection=function(){this.defaultCryptogroup=null;this.defaultNotebook=null;this.userId=null;this.userLogin=null;this.appScope=null;this.appInited=false;return{init:function(state){if(!this.appInited){this.appInited=true;this.buildDom();var that=this;require(["angular","./../../js/ui/notebook_protection_app","angular-selectize"],function(angular,app,selectize){"use strict";angular.element(document).ready(function(){_.delay(function(){angular.bootstrap($("#protection-app")[0],["NotebookProtectionApp"]);angular.resumeBootstrap()},100);_.delay(function(){that.appScope=angular.element(document.getElementById("protection-app")).scope();that.launch(state);$("#notebook-protection-dialog").modal({keyboard:false})},200)})})}else{this.launch(state);$("#notebook-protection-dialog").modal({keyboard:false})}},launch:function(state){if(state==="both-tabs-enabled"){$("#protection-app #tab2").removeClass("active");$("#protection-app #tab1").removeClass("disabled").addClass("active");$("#protection-app #tab1 a").attr("href","#notebook-tab").attr("data-toggle","tab");$("#protection-app #tab2 a").tab("show");$("#protection-app #tab1 a").tab("show");this.appScope.initBoth()}else if(state==="group-tab-enabled"){$("#protection-app #tab1").removeClass("active").addClass("disabled");$("#protection-app #tab1 a").attr("href","#").removeAttr("data-toggle");$("#protection-app #tab2 a").tab("show");this.appScope.initGroups()}},buildDom:function(){var body=$('');body.append(RCloud.UI.panel_loader.load_snippet("notebook-protection-modal"));var header=$(['