How to capture and store an image in django - django
I wanted to access the camera. capture an image and store in the database.
models.py :
class student(models.Model):
Img = models.ImageField(upload_to='images/')
HTML page :
<!DOCTYPE html>
<html>
<head>
<title> webcam </title>
</head>
<body>
<div class = "video-wrap">
<video id = "video" playsinline autoplay></video>
</div>
<div class = "controller">
<button id = "snap">Capture</button>
</div>
<canvas id = "canvas" width = "640" height = "480">
</canvas>
<script>
'use strict';
const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const snap = document.getElementById('snap');
const errorMsgElement = document.getElementById('span#ErrorMsg');
const constraints = {
audio:true,
video:{
width:1280,height:720
}};
async function init()
{
try
{
const stream = await navigator.mediaDevices.getUserMedia(constraints);
handleSuccess(stream);
}
catch(e)
{
errorMsgElement.innerHTML
=`navigator.getUserMedia.error:${e.toString()}`;
}
}
function handleSuccess(stream)
{
window.stream = stream;
video.srcObject = stream;
}
init();
var context = canvas.getContext('2d');
snap.addEventListener("click",function(){
context.drawImage(video, 0, 0, 640, 480);});
</script>
</body>
</html>
This HTML page can access the camera and can capture. But I don't know how to access and get that to models. can anyone pls help
To capture images in Django you can make use of the python imaging library PILLOW(https://pypi.org/project/Pillow/). It is easy to use
you can use open cv module to capture an image. By using input type=submit and using form, and by defining open cv function in view file
https://github.com/kevinam99/capturing-images-from-webcam-using-opencv-python
Related
How to integrate novnc client inside django project
I have a couple virtual machines running inside proxmox but I found out you can use the novnc client to connect to these virtual machines and use the console in a web browser. This is perfect for different clients I work with. I already have a small django project that shows the running nodes and vm's inside of them. Now I wanted to include de js library by novnc. However I can't really find a lot of information online and since my coding experience is not that high I don't really know what I am doing wrong. I used this outdated repo and tried to see if I can find out how to get it to work. https://github.com/missuor/novnc-proxy-django for now I have a view that call the api of proxmox. /api2/json/nodes/{node}/lxc/{vmid}/vncproxy to be precise. this returns a ticket, port, cert, user and upid. Now I am not sure if I just need to call the vncproxy or use these variable to open a websocket by /api2/json/nodes/{node}/lxc/{vmid}/vncwebsocket. The django view i currently have just call the vncproxy and sends the values to the rendered template. This template I used from the repo metioned above, but I just don't know why I keep ketting a Server Disconnected(code 1006 error). If you have any tips for me that would be of great help. this is the view I currently use which receives all the correct values. def vnc(request, node, vmid): vncproxy = proxmox_vnc().vncproxyVirtualMachine(node, vmid) token = vncproxy['data']['ticket'] port = vncproxy['data']['port'] host = 'Settings.vnxproxy' password = '' print(token) return render(request, 'vnc_auto.html', {'token': token, 'host': host, 'port': port, 'password': password}) And this below is the vnc.html I use to render and uses the novnc client. {% load static %} <!DOCTYPE html> <html> <head> <!-- noVNC example: simple example using default UI Copyright (C) 2012 Joel Martin Copyright (C) 2013 Samuel Mannehed for Cendio AB noVNC is licensed under the MPL 2.0 (see LICENSE.txt) This file is licensed under the 2-Clause BSD license (see LICENSE.txt). Connect parameters are provided in query string: http://example.com/?host=HOST&port=PORT&encrypt=1&true_color=1 --> <title>noVNC</title> <meta charset="utf-8"> <!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame Remove this if you use the .htaccess --> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <!-- Apple iOS Safari settings --> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" /> <!-- App Start Icon --> <link rel="apple-touch-startup-image" href="{% static 'novnc/images/screen_320x460.png' %}" /> <!-- For iOS devices set the icon to use if user bookmarks app on their homescreen --> <link rel="apple-touch-icon" href="{% static 'novnc/images/screen_57x57.png' %}"> <!-- <link rel="apple-touch-icon-precomposed" href="{% static 'novnc/images/screen_57x57.png' %}" /> --> <script>var INCLUDE_URI='/static/novnc/include/'</script> <!-- Stylesheets --> <link rel="stylesheet" href="{% static 'novnc/include/base.css' %}" title="plain"> <!-- <script type='text/javascript' src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script> --> <script src="{% static 'novnc/include/util.js' %}"></script> </head> <body style="margin: 0px;"> <div id="noVNC_screen"> <div id="noVNC_status_bar" class="noVNC_status_bar" style="margin-top: 0px;"> <table border=0 width="100%"><tr> <td><div id="noVNC_status" style="position: relative; height: auto;"> Loading </div></td> <td width="1%"><div id="noVNC_buttons"> <input type=button value="Send CtrlAltDel" id="sendCtrlAltDelButton"> <span id="noVNC_xvp_buttons"> <input type=button value="Shutdown" id="xvpShutdownButton"> <input type=button value="Reboot" id="xvpRebootButton"> <input type=button value="Reset" id="xvpResetButton"> </span> </div></td> </tr></table> </div> <canvas id="noVNC_canvas" width="640px" height="20px"> Canvas not supported. </canvas> </div> <script> /*jslint white: false */ /*global window, $, Util, RFB, */ "use strict"; // Load supporting scripts Util.load_scripts(["webutil.js", "base64.js", "websock.js", "des.js", "keysymdef.js", "keyboard.js", "input.js", "display.js", "jsunzip.js", "rfb.js", "keysym.js"]); var rfb; function passwordRequired(rfb) { var msg; msg = '<form onsubmit="return setPassword();"'; msg += ' style="margin-bottom: 0px">'; msg += 'Password Required: '; msg += '<input type=password size=10 id="password_input" class="noVNC_status">'; msg += '<\/form>'; $D('noVNC_status_bar').setAttribute("class", "noVNC_status_warn"); $D('noVNC_status').innerHTML = msg; } function setPassword() { rfb.sendPassword($D('password_input').value); return false; } function sendCtrlAltDel() { rfb.sendCtrlAltDel(); return false; } function xvpShutdown() { rfb.xvpShutdown(); return false; } function xvpReboot() { rfb.xvpReboot(); return false; } function xvpReset() { rfb.xvpReset(); return false; } function updateState(rfb, state, oldstate, msg) { var s, sb, cad, level; s = $D('noVNC_status'); sb = $D('noVNC_status_bar'); cad = $D('sendCtrlAltDelButton'); switch (state) { case 'failed': level = "error"; break; case 'fatal': level = "error"; break; case 'normal': level = "normal"; break; case 'disconnected': level = "normal"; break; case 'loaded': level = "normal"; break; default: level = "warn"; break; } if (state === "normal") { cad.disabled = false; } else { cad.disabled = true; xvpInit(0); } if (typeof(msg) !== 'undefined') { sb.setAttribute("class", "noVNC_status_" + level); s.innerHTML = msg; } } function xvpInit(ver) { var xvpbuttons; xvpbuttons = $D('noVNC_xvp_buttons'); if (ver >= 1) { xvpbuttons.style.display = 'inline'; } else { xvpbuttons.style.display = 'none'; } } window.onscriptsload = function () { var host, port, password, path, token; $D('sendCtrlAltDelButton').style.display = "inline"; $D('sendCtrlAltDelButton').onclick = sendCtrlAltDel; $D('xvpShutdownButton').onclick = xvpShutdown; $D('xvpRebootButton').onclick = xvpReboot; $D('xvpResetButton').onclick = xvpReset; WebUtil.init_logging(WebUtil.getQueryVar('logging', 'warn')); document.title = unescape(WebUtil.getQueryVar('title', 'noVNC')); // By default, use the host and port of server that served this file host = WebUtil.getQueryVar('host', '{{host}}'?'{{host}}':window.location.hostname); port = WebUtil.getQueryVar('port', {{port}}?{{port}}:window.location.port); // if port == 80 (or 443) then it won't be present and should be // set manually if (!port) { if (window.location.protocol.substring(0,5) == 'https') { port = 443; } else if (window.location.protocol.substring(0,4) == 'http') { port = 80; } } // If a token variable is passed in, set the parameter in a cookie. // This is used by nova-novncproxy. token = WebUtil.getQueryVar('token', null); if (token) { WebUtil.createCookie('token', token, 1) } password = WebUtil.getQueryVar('password', '{{password}}'?'{{password}}':''); path = WebUtil.getQueryVar('path', '{{path}}'?'{{path}}':''); path += '?token='+token; if ((!host) || (!port)) { updateState('failed', "Must specify host and port in URL"); return; } rfb = new RFB({'target': $D('noVNC_canvas'), 'encrypt': WebUtil.getQueryVar('encrypt', (window.location.protocol === "https:")), 'repeaterID': WebUtil.getQueryVar('repeaterID', ''), 'true_color': WebUtil.getQueryVar('true_color', true), 'local_cursor': WebUtil.getQueryVar('cursor', true), 'shared': WebUtil.getQueryVar('shared', true), 'view_only': WebUtil.getQueryVar('view_only', false), 'onUpdateState': updateState, 'onXvpInit': xvpInit, 'onPasswordRequired': passwordRequired}); console.log(host, port, password, path); rfb.connect(host, port, password, path); }; </script> </body> </html>
Cannot open client webcam - Flasksocketio
app.py: #app.route("/") #app.route("/login", methods=["GET", "POST"]) def login(): msg = "" if ( request.method == "POST" and "username" in request.form and "password" in request.form ): username = request.form["username"] password = request.form["password"] cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute( "SELECT * FROM accounts WHERE username = %s AND password = %s", ( username, password, ), ) account = cursor.fetchone() if account: session["loggedin"] = True session["id"] = account["id"] session["username"] = account["username"] msg = "Logged in successfully" return render_template("index.html", msg=msg) else: msg = "Incorrect username / password !" return render_template("login.html", msg=msg) #socketio.on("image") def image(data_image): sbuf = StringIO() sbuf.write(data_image) # decode and convert into image b = io.BytesIO(base64.b64decode(data_image)) pimg = Image.open(b) ## converting RGB to BGR, as opencv standards frame = cv2.cvtColor(np.array(pimg), cv2.COLOR_RGB2BGR) # Process the image frame frame = imutils.resize(frame, width=700) frame = cv2.flip(frame, 1) imgencode = cv2.imencode(".jpg", frame)[1] # base64 encode stringData = base64.b64encode(imgencode).decode("utf-8") b64_src = "data:image/jpg;base64," stringData = b64_src + stringData # emit the frame back emit("response_back", stringData) index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.4/socket.io.js" integrity="sha512-aMGMvNYu8Ue4G+fHa359jcPb1u+ytAF+P2SCb+PxrjCdO3n3ZTxJ30zuH39rimUggmTwmh2u7wvQsDTHESnmfQ==" crossorigin="anonymous"></script> <title>Document</title> </head> <body> <div id="container"> <canvas id="canvasOutput"></canvas> <video autoplay="true" id="videoElement"></video> </div> <div class='video'> <img id="image"> </div> <script> var socket = io('http://localhost:5000/login'); socket.on('connect', function () { console.log("Connected...!", socket.connected) }); const video = document.querySelector("#videoElement"); video.width = 500; video.height = 375;; if (navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({ video: true }) .then(function (stream) { video.srcObject = stream; video.play(); }) .catch(function (err0r) { console.log(err0r) console.log("Something went wrong!"); }); } let cap = new cv.VideoCapture(video); let src = new cv.Mat(video.height, video.width, cv.CV_8UC4); let dst = new cv.Mat(video.height, video.width, cv.CV_8UC1); const FPS = 22; setInterval(() => { cap.read(src); var type = "image/png" var data = document.getElementById("canvasOutput").toDataURL(type); data = data.replace('data:' + type + ';base64,', ''); //split off junk at the beginning socket.emit('image', data); }, 10000 / FPS); socket.on('response_back', function (image) { const image_id = document.getElementById('image'); image_id.src = image; }); </script> </body> </html> Error on the console: DOMException: Could not start video source I have a flask web app where when a user logs in, the web camera opens to render a live video stream on the web app. but it throws an error that it cannot open the camera and start a video stream, where am I doing wrong how can I access the camera and display in when user logs in.
Retrieve data from list in SharePoint 2013 provider hosted App
I have developed a provider hosted app in SharePoint 2013. As you already know, Visual Studio creates web application and SharePoint app. The web application gets hosted inside IIS and the SharePoint App in SharePoint site collection. I'm trying to get data from a list hosted in SharePoint using CSOM. But I get ran insecure content error. "[blocked] The page at 'https://localhost:44302/Pages/Default.aspx?SPHostUrl=http%3A%2F%2Fecontent&0319c41%2Eecontent%2Eelibrary%2Eapps%2Elocal%2FSharePointApp2%5Fsingeltest' was loaded over HTTPS, but ran insecure content from 'http://apps-892db5a0319c41.econtent.elibrary.apps.local/sharepointapp2_singeltest/_layouts/15/AppWebProxy.aspx': this content should also be loaded over HTTPS." here is my code in Default.aspx <script type="text/javascript" src="../Scripts/jquery-1.8.2.js"></script> <script type="text/javascript" src="../Scripts/MicrosoftAjax.js"></script> <script type="text/javascript" src="../Scripts/SP.Core.js"></script> <script type="text/javascript" src="../Scripts/INIT.JS"></script> <script type="text/javascript" src="../Scripts/SP.Runtime.js"></script> <script type="text/javascript" src="../Scripts/SP.js"></script> <script type="text/javascript" src="../Scripts/SP.RequestExecutor.js"></script> <script type="text/javascript" src="../Scripts/App.js"></script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <input id="Button1" type="button" value="Get title via CSOM" onclick="execCSOMTitleRequest()" /> <br /> <input id="Button2" type="button" value="Get Lists via CSOM" onclick="execCSOMListRequest()" /> </div> <p ID="lblResultTitle"></p><br /> <p ID="lblResultLists"></p> </form> </body> </html> and App.js is: var hostwebUrl; var appwebUrl; // Load the required SharePoint libraries $(document).ready(function () { //Get the URI decoded URLs. hostwebUrl = decodeURIComponent( getQueryStringParameter("SPHostUrl") ); appwebUrl = decodeURIComponent( getQueryStringParameter("SPAppWebUrl") ); // resources are in URLs in the form: // web_url/_layouts/15/resource var scriptbase = hostwebUrl + "/_layouts/15/"; // Load the js files and continue to the successHandler //$.getScript(scriptbase + "/MicrosoftAjax.js", // function () { // $.getScript(scriptbase + "SP.Core.js", // function () { // $.getScript(scriptbase + "INIT.JS", // function () { // $.getScript(scriptbase + "SP.Runtime.js", // function () { // $.getScript(scriptbase + "SP.js", // function () { $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest); } // ); // } // ); // }); // }); // }); }); function execCrossDomainRequest() { alert("scripts loaded"); } function getQueryStringParameter(paramToRetrieve) { var params = document.URL.split("?")[1].split("&"); var strParams = ""; for (var i = 0; i < params.length; i = i + 1) { var singleParam = params[i].split("="); if (singleParam[0] == paramToRetrieve) return singleParam[1]; } } function execCSOMTitleRequest() { var context; var factory; var appContextSite; var collList; //Get the client context of the AppWebUrl context = new SP.ClientContext(appwebUrl); //Get the ProxyWebRequestExecutorFactory factory = new SP.ProxyWebRequestExecutorFactory(appwebUrl); //Assign the factory to the client context. context.set_webRequestExecutorFactory(factory); //Get the app context of the Host Web using the client context of the Application. appContextSite = new SP.AppContextSite(context, hostwebUrl); //Get the Web this.web = context.get_web(); //Load Web. context.load(this.web); context.executeQueryAsync( Function.createDelegate(this, successTitleHandlerCSOM), Function.createDelegate(this, errorTitleHandlerCSOM) ); //success Title function successTitleHandlerCSOM(data) { $('#lblResultTitle').html("<b>Via CSOM the title is:</b> " + this.web.get_title()); } //Error Title function errorTitleHandlerCSOM(data, errorCode, errorMessage) { $('#lblResultLists').html("Could not complete CSOM call: " + errorMessage); } } function execCSOMListRequest() { var context; var factory; var appContextSite; var collList; //Get the client context of the AppWebUrl context = new SP.ClientContext(appwebUrl); //Get the ProxyWebRequestExecutorFactory factory = new SP.ProxyWebRequestExecutorFactory(appwebUrl); //Assign the factory to the client context. context.set_webRequestExecutorFactory(factory); //Get the app context of the Host Web using the client context of the Application. appContextSite = new SP.AppContextSite(context, hostwebUrl); //Get the Web this.web = context.get_web(); // Get the Web lists. collList = this.web.get_lists(); //Load Lists. context.load(collList); context.executeQueryAsync( Function.createDelegate(this, successListHandlerCSOM), Function.createDelegate(this, errorListHandlerCSOM) ); //Success Lists function successListHandlerCSOM() { var listEnumerator = collList.getEnumerator(); $('#lblResultLists').html("<b>Via CSOM the lists are:</b><br/>"); while (listEnumerator.moveNext()) { var oList = listEnumerator.get_current(); $('#lblResultLists').append(oList.get_title() + " (" + oList.get_itemCount() + ")<br/>"); } } //Error Lists function errorListHandlerCSOM(data, errorCode, errorMessage) { $('#lblResultLists').html("Could not complete CSOM Call: " + errorMessage); } }; Any solution is appreciated.
well first off, i can tell you your decodeURIComponent logic isnt working. Yours:https://localhost:44302/Pages/Default.aspx?SPHostUrl=http%3A%2F%2Fecontent&0319c41%2Eecontent%2Eelibrary%2Eapps%2Elocal%2FSharePointApp2%5Fsingeltest Mine: https://localhost:44302/Pages/Default.aspx?SPHostUrl=http://econtent&0319c41.econtent.elibrary.apps.local/SharePointApp2_singeltest Secondly, is the HostURL content supposed to be unsecure? If so, then you may want to change your browser settings. If not, then you need to see why your HostURL is in the Anonymous Zone but your AppURL is in the Secure Zone. In either case, verify that Everyone has at least Read Access to the location your trying to pull from. Last thing to do, is to setup a Trusted Host Location if you have access to the Admin Center. Here is a code snippet for what i used to test: $(document).ready(function () { $.getScript(qsHostUrl + "/_layouts/15/SP.RequestExecutor.js", getHostInfo); function getHostInfo() { var ctxApp = new SP.ClientContext(qsAppUrl); var factory = new SP.ProxyWebRequestExecutorFactory(qsAppUrl); ctxApp.set_webRequestExecutorFactory(factory); var ctxHost = new SP.AppContextSite(ctxApp, qsHostUrl); var web = ctxHost.get_web(); ctxApp.load(web); ctxApp.executeQueryAsync( Function.createDelegate(this, getHostInfoSuccess), Function.createDelegate(this, getHostInfoError) ); function getHostInfoSuccess(sender, args) { lblData.html( 'Title: ' + web.get_title() + '<br/>' + 'Description: ' + web.get_description() ); } function getHostInfoError(sender, args) { lblData.html( 'Request Failed: ' + args.get_message() + '\n' + 'Stacktrace: ' + args.get_stackTrace() ); } } }
d3js returning "[object%20Object]" and "Uncaught TypeError: Cannot read property: nodes of undefined"
I am new to Javascript and Django. I have to animate a svg file with D3js, so to practice and understand how it works I decided to add the miserables widget to my local Django website. I have a simple view: def miserable(request): return render_to_response('index.html') The url is: url(r'^moremiser/$','more_miserable')and I copied both index.html and miserable.json into my template folder. When I go to the url that is supposed to display the widget all I get is a blank screen. what am I doing wrong? The person who set up the local website installed tinymce and compressor, could they be causing the problem? here is the code for index.html and miserables.json. They both are in my templates folder: #index.html <!DOCTYPE html> <meta charset="utf-8"> <style> .node { stroke: #fff; stroke-width: 1.5px; } .link { stroke: #999; stroke-opacity: .6; } </style> <body> <script src="http://d3js.org/d3.v3.min.js"></script> <script> var width = 960, height = 500; var color = d3.scale.category20(); var force = d3.layout.force() .charge(-120) .linkDistance(30) .size([width, height]); var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height); d3.json("miserables.json", function(error, graph) { force .nodes(graph.nodes) .links(graph.links) .start(); var link = svg.selectAll(".link") .data(graph.links) .enter().append("line") .attr("class", "link") .style("stroke-width", function(d) { return Math.sqrt(d.value); }); var node = svg.selectAll(".node") .data(graph.nodes) .enter().append("circle") .attr("class", "node") .attr("r", 5) .style("fill", function(d) { return color(d.group); }) .call(force.drag); node.append("title") .text(function(d) { return d.name; }); force.on("tick", function() { link.attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); node.attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }); }); }); </script> #miserables.json { "nodes":[ {"name":"Myriel","group":1}, {"name":"Napoleon","group":1}, {"name":"Mlle.Baptistine","group":1}, {"name":"Mme.Magloire","group":1}, {"name":"CountessdeLo","group":1}, {"name":"Geborand","group":1}, {"name":"Champtercier","group":1}, {"name":"Cravatte","group":1}, {"name":"Count","group":1}, {"name":"OldMan","group":1}, {"name":"Labarre","group":2}, {"name":"Valjean","group":2}, {"name":"Marguerite","group":3}, {"name":"Mme.deR","group":2}, {"name":"Isabeau","group":2}, {"name":"Gervais","group":2}, {"name":"Tholomyes","group":3}, {"name":"Listolier","group":3}, {"name":"Fameuil","group":3}, {"name":"Blacheville","group":3}, {"name":"Favourite","group":3}, {"name":"Dahlia","group":3}, {"name":"Zephine","group":3}, {"name":"Fantine","group":3}, {"name":"Mme.Thenardier","group":4}, {"name":"Thenardier","group":4}, {"name":"Cosette","group":5}, {"name":"Javert","group":4}, {"name":"Fauchelevent","group":0}, {"name":"Bamatabois","group":2}, {"name":"Perpetue","group":3}, {"name":"Simplice","group":2}, {"name":"Scaufflaire","group":2}, {"name":"Woman1","group":2}, {"name":"Judge","group":2}, {"name":"Champmathieu","group":2}, {"name":"Brevet","group":2}, {"name":"Chenildieu","group":2}, {"name":"Cochepaille","group":2}, {"name":"Pontmercy","group":4}, {"name":"Boulatruelle","group":6}, {"name":"Eponine","group":4}, {"name":"Anzelma","group":4}, {"name":"Woman2","group":5}, {"name":"MotherInnocent","group":0}, {"name":"Gribier","group":0}, {"name":"Jondrette","group":7}, {"name":"Mme.Burgon","group":7}, {"name":"Gavroche","group":8}, {"name":"Gillenormand","group":5}, {"name":"Magnon","group":5}, {"name":"Mlle.Gillenormand","group":5}, {"name":"Mme.Pontmercy","group":5}, {"name":"Mlle.Vaubois","group":5}, {"name":"Lt.Gillenormand","group":5}, {"name":"Marius","group":8}, {"name":"BaronessT","group":5}, {"name":"Mabeuf","group":8}, {"name":"Enjolras","group":8}, {"name":"Combeferre","group":8}, {"name":"Prouvaire","group":8}, {"name":"Feuilly","group":8}, {"name":"Courfeyrac","group":8}, {"name":"Bahorel","group":8}, {"name":"Bossuet","group":8}, {"name":"Joly","group":8}, {"name":"Grantaire","group":8}, {"name":"MotherPlutarch","group":9}, {"name":"Gueulemer","group":4}, {"name":"Babet","group":4}, {"name":"Claquesous","group":4}, {"name":"Montparnasse","group":4}, {"name":"Toussaint","group":5}, {"name":"Child1","group":10}, {"name":"Child2","group":10}, {"name":"Brujon","group":4}, {"name":"Mme.Hucheloup","group":8} ], "links":[ {"source":1,"target":0,"value":1}, {"source":2,"target":0,"value":8}, {"source":3,"target":0,"value":10}, {"source":3,"target":2,"value":6}, {"source":4,"target":0,"value":1}, {"source":5,"target":0,"value":1}, {"source":6,"target":0,"value":1}, {"source":7,"target":0,"value":1}, {"source":8,"target":0,"value":2}, {"source":9,"target":0,"value":1}, {"source":11,"target":10,"value":1}, {"source":11,"target":3,"value":3}, {"source":11,"target":2,"value":3}, {"source":11,"target":0,"value":5}, {"source":12,"target":11,"value":1}, {"source":13,"target":11,"value":1}, {"source":14,"target":11,"value":1}, {"source":15,"target":11,"value":1}, {"source":17,"target":16,"value":4}, {"source":18,"target":16,"value":4}, {"source":18,"target":17,"value":4}, {"source":19,"target":16,"value":4}, {"source":19,"target":17,"value":4}, {"source":19,"target":18,"value":4}, {"source":20,"target":16,"value":3}, {"source":20,"target":17,"value":3}, {"source":20,"target":18,"value":3}, {"source":20,"target":19,"value":4}, {"source":21,"target":16,"value":3}, {"source":21,"target":17,"value":3}, {"source":21,"target":18,"value":3}, {"source":21,"target":19,"value":3}, {"source":21,"target":20,"value":5}, {"source":22,"target":16,"value":3}, {"source":22,"target":17,"value":3}, {"source":22,"target":18,"value":3}, {"source":22,"target":19,"value":3}, {"source":22,"target":20,"value":4}, {"source":22,"target":21,"value":4}, {"source":23,"target":16,"value":3}, {"source":23,"target":17,"value":3}, {"source":23,"target":18,"value":3}, {"source":23,"target":19,"value":3}, {"source":23,"target":20,"value":4}, {"source":23,"target":21,"value":4}, {"source":23,"target":22,"value":4}, {"source":23,"target":12,"value":2}, {"source":23,"target":11,"value":9}, {"source":24,"target":23,"value":2}, {"source":24,"target":11,"value":7}, {"source":25,"target":24,"value":13}, {"source":25,"target":23,"value":1}, {"source":25,"target":11,"value":12}, {"source":26,"target":24,"value":4}, {"source":26,"target":11,"value":31}, {"source":26,"target":16,"value":1}, {"source":26,"target":25,"value":1}, {"source":27,"target":11,"value":17}, {"source":27,"target":23,"value":5}, {"source":27,"target":25,"value":5}, {"source":27,"target":24,"value":1}, {"source":27,"target":26,"value":1}, {"source":28,"target":11,"value":8}, {"source":28,"target":27,"value":1}, {"source":29,"target":23,"value":1}, {"source":29,"target":27,"value":1}, {"source":29,"target":11,"value":2}, {"source":30,"target":23,"value":1}, {"source":31,"target":30,"value":2}, {"source":31,"target":11,"value":3}, {"source":31,"target":23,"value":2}, {"source":31,"target":27,"value":1}, {"source":32,"target":11,"value":1}, {"source":33,"target":11,"value":2}, {"source":33,"target":27,"value":1}, {"source":34,"target":11,"value":3}, {"source":34,"target":29,"value":2}, {"source":35,"target":11,"value":3}, {"source":35,"target":34,"value":3}, {"source":35,"target":29,"value":2}, {"source":36,"target":34,"value":2}, {"source":36,"target":35,"value":2}, {"source":36,"target":11,"value":2}, {"source":36,"target":29,"value":1}, {"source":37,"target":34,"value":2}, {"source":37,"target":35,"value":2}, {"source":37,"target":36,"value":2}, {"source":37,"target":11,"value":2}, {"source":37,"target":29,"value":1}, {"source":38,"target":34,"value":2}, {"source":38,"target":35,"value":2}, {"source":38,"target":36,"value":2}, {"source":38,"target":37,"value":2}, {"source":38,"target":11,"value":2}, {"source":38,"target":29,"value":1}, {"source":39,"target":25,"value":1}, {"source":40,"target":25,"value":1}, {"source":41,"target":24,"value":2}, {"source":41,"target":25,"value":3}, {"source":42,"target":41,"value":2}, {"source":42,"target":25,"value":2}, {"source":42,"target":24,"value":1}, {"source":43,"target":11,"value":3}, {"source":43,"target":26,"value":1}, {"source":43,"target":27,"value":1}, {"source":44,"target":28,"value":3}, {"source":44,"target":11,"value":1}, {"source":45,"target":28,"value":2}, {"source":47,"target":46,"value":1}, {"source":48,"target":47,"value":2}, {"source":48,"target":25,"value":1}, {"source":48,"target":27,"value":1}, {"source":48,"target":11,"value":1}, {"source":49,"target":26,"value":3}, {"source":49,"target":11,"value":2}, {"source":50,"target":49,"value":1}, {"source":50,"target":24,"value":1}, {"source":51,"target":49,"value":9}, {"source":51,"target":26,"value":2}, {"source":51,"target":11,"value":2}, {"source":52,"target":51,"value":1}, {"source":52,"target":39,"value":1}, {"source":53,"target":51,"value":1}, {"source":54,"target":51,"value":2}, {"source":54,"target":49,"value":1}, {"source":54,"target":26,"value":1}, {"source":55,"target":51,"value":6}, {"source":55,"target":49,"value":12}, {"source":55,"target":39,"value":1}, {"source":55,"target":54,"value":1}, {"source":55,"target":26,"value":21}, {"source":55,"target":11,"value":19}, {"source":55,"target":16,"value":1}, {"source":55,"target":25,"value":2}, {"source":55,"target":41,"value":5}, {"source":55,"target":48,"value":4}, {"source":56,"target":49,"value":1}, {"source":56,"target":55,"value":1}, {"source":57,"target":55,"value":1}, {"source":57,"target":41,"value":1}, {"source":57,"target":48,"value":1}, {"source":58,"target":55,"value":7}, {"source":58,"target":48,"value":7}, {"source":58,"target":27,"value":6}, {"source":58,"target":57,"value":1}, {"source":58,"target":11,"value":4}, {"source":59,"target":58,"value":15}, {"source":59,"target":55,"value":5}, {"source":59,"target":48,"value":6}, {"source":59,"target":57,"value":2}, {"source":60,"target":48,"value":1}, {"source":60,"target":58,"value":4}, {"source":60,"target":59,"value":2}, {"source":61,"target":48,"value":2}, {"source":61,"target":58,"value":6}, {"source":61,"target":60,"value":2}, {"source":61,"target":59,"value":5}, {"source":61,"target":57,"value":1}, {"source":61,"target":55,"value":1}, {"source":62,"target":55,"value":9}, {"source":62,"target":58,"value":17}, {"source":62,"target":59,"value":13}, {"source":62,"target":48,"value":7}, {"source":62,"target":57,"value":2}, {"source":62,"target":41,"value":1}, {"source":62,"target":61,"value":6}, {"source":62,"target":60,"value":3}, {"source":63,"target":59,"value":5}, {"source":63,"target":48,"value":5}, {"source":63,"target":62,"value":6}, {"source":63,"target":57,"value":2}, {"source":63,"target":58,"value":4}, {"source":63,"target":61,"value":3}, {"source":63,"target":60,"value":2}, {"source":63,"target":55,"value":1}, {"source":64,"target":55,"value":5}, {"source":64,"target":62,"value":12}, {"source":64,"target":48,"value":5}, {"source":64,"target":63,"value":4}, {"source":64,"target":58,"value":10}, {"source":64,"target":61,"value":6}, {"source":64,"target":60,"value":2}, {"source":64,"target":59,"value":9}, {"source":64,"target":57,"value":1}, {"source":64,"target":11,"value":1}, {"source":65,"target":63,"value":5}, {"source":65,"target":64,"value":7}, {"source":65,"target":48,"value":3}, {"source":65,"target":62,"value":5}, {"source":65,"target":58,"value":5}, {"source":65,"target":61,"value":5}, {"source":65,"target":60,"value":2}, {"source":65,"target":59,"value":5}, {"source":65,"target":57,"value":1}, {"source":65,"target":55,"value":2}, {"source":66,"target":64,"value":3}, {"source":66,"target":58,"value":3}, {"source":66,"target":59,"value":1}, {"source":66,"target":62,"value":2}, {"source":66,"target":65,"value":2}, {"source":66,"target":48,"value":1}, {"source":66,"target":63,"value":1}, {"source":66,"target":61,"value":1}, {"source":66,"target":60,"value":1}, {"source":67,"target":57,"value":3}, {"source":68,"target":25,"value":5}, {"source":68,"target":11,"value":1}, {"source":68,"target":24,"value":1}, {"source":68,"target":27,"value":1}, {"source":68,"target":48,"value":1}, {"source":68,"target":41,"value":1}, {"source":69,"target":25,"value":6}, {"source":69,"target":68,"value":6}, {"source":69,"target":11,"value":1}, {"source":69,"target":24,"value":1}, {"source":69,"target":27,"value":2}, {"source":69,"target":48,"value":1}, {"source":69,"target":41,"value":1}, {"source":70,"target":25,"value":4}, {"source":70,"target":69,"value":4}, {"source":70,"target":68,"value":4}, {"source":70,"target":11,"value":1}, {"source":70,"target":24,"value":1}, {"source":70,"target":27,"value":1}, {"source":70,"target":41,"value":1}, {"source":70,"target":58,"value":1}, {"source":71,"target":27,"value":1}, {"source":71,"target":69,"value":2}, {"source":71,"target":68,"value":2}, {"source":71,"target":70,"value":2}, {"source":71,"target":11,"value":1}, {"source":71,"target":48,"value":1}, {"source":71,"target":41,"value":1}, {"source":71,"target":25,"value":1}, {"source":72,"target":26,"value":2}, {"source":72,"target":27,"value":1}, {"source":72,"target":11,"value":1}, {"source":73,"target":48,"value":2}, {"source":74,"target":48,"value":2}, {"source":74,"target":73,"value":3}, {"source":75,"target":69,"value":3}, {"source":75,"target":68,"value":3}, {"source":75,"target":25,"value":3}, {"source":75,"target":48,"value":1}, {"source":75,"target":41,"value":1}, {"source":75,"target":70,"value":1}, {"source":75,"target":71,"value":1}, {"source":76,"target":64,"value":1}, {"source":76,"target":65,"value":1}, {"source":76,"target":66,"value":1}, {"source":76,"target":63,"value":1}, {"source":76,"target":62,"value":1}, {"source":76,"target":48,"value":1}, {"source":76,"target":58,"value":1} ] } When I open the Javascript debugger in Google Chrome, I see that instead of going to the url "moremiser" the server try to go to "moremiser/[object%20Object] and then the other error message appears:""Uncaught TypeError: Cannot read property: nodes of undefined". What should I modify?
Yes, I did. I think Javascript cannot locate "miserable.json" nor access the nodes in it. I say this because I have assigned the content of "miserables.json" to an object defined into "index.html" without success. Then, I created an array of nodes(without identifying them as being node), pasted the code for the array into the "index.html" file, and wrote a for loop printing as many "hello wolrd" as there are objects in the array; at first, the browser said that d3 was not defined, then it worked when I referenced the url of the online d3 library instead of the d3 folder on my computer. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>D3 Test</title> <script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script> </head> <body> <script type="text/javascript"> var dataset = [{"name":"Myriel","group":1}, {"name":"Napoleon","group":1}, {"name":"Mlle.Baptistine","group":1}, {"name":"Mme.Magloire","group":1}, {"name":"CountessdeLo","group":1}, {"name":"Geborand","group":1}, {"name":"Champtercier","group":1}, {"name":"Cravatte","group":1}, {"name":"Count","group":1}, {"name":"OldMan","group":1}, {"name":"Labarre","group":2}, {"name":"Valjean","group":2}, {"name":"Marguerite","group":3}, {"name":"Mme.deR","group":2}, {"name":"Isabeau","group":2}, {"name":"Gervais","group":2}, {"name":"Tholomyes","group":3}, {"name":"Listolier","group":3}, {"name":"Fameuil","group":3}, {"name":"Blacheville","group":3}, {"name":"Favourite","group":3}, {"name":"Dahlia","group":3}, {"name":"Zephine","group":3}, {"name":"Fantine","group":3}, {"name":"Mme.Thenardier","group":4}, {"name":"Thenardier","group":4}, {"name":"Cosette","group":5}, {"name":"Javert","group":4}, {"name":"Fauchelevent","group":0}, {"name":"Bamatabois","group":2}, {"name":"Perpetue","group":3}, {"name":"Simplice","group":2}, {"name":"Scaufflaire","group":2}, {"name":"Woman1","group":2}, {"name":"Judge","group":2}, {"name":"Champmathieu","group":2}, {"name":"Brevet","group":2}, {"name":"Chenildieu","group":2}, {"name":"Cochepaille","group":2}, {"name":"Pontmercy","group":4}, {"name":"Boulatruelle","group":6}, {"name":"Eponine","group":4}, {"name":"Anzelma","group":4}, {"name":"Woman2","group":5}, {"name":"MotherInnocent","group":0}, {"name":"Gribier","group":0}, {"name":"Jondrette","group":7}, {"name":"Mme.Burgon","group":7}, {"name":"Gavroche","group":8}, {"name":"Gillenormand","group":5}, {"name":"Magnon","group":5}, {"name":"Mlle.Gillenormand","group":5}, {"name":"Mme.Pontmercy","group":5}, {"name":"Mlle.Vaubois","group":5}, {"name":"Lt.Gillenormand","group":5}, {"name":"Marius","group":8}, {"name":"BaronessT","group":5}, {"name":"Mabeuf","group":8}, {"name":"Enjolras","group":8}, {"name":"Combeferre","group":8}, {"name":"Prouvaire","group":8}, {"name":"Feuilly","group":8}, {"name":"Courfeyrac","group":8}, {"name":"Bahorel","group":8}, {"name":"Bossuet","group":8}, {"name":"Joly","group":8}, {"name":"Grantaire","group":8}, {"name":"MotherPlutarch","group":9}, {"name":"Gueulemer","group":4}, {"name":"Babet","group":4}, {"name":"Claquesous","group":4}, {"name":"Montparnasse","group":4}, {"name":"Toussaint","group":5}, {"name":"Child1","group":10}, {"name":"Child2","group":10}, {"name":"Brujon","group":4}, {"name":"Mme.Hucheloup","group":8}]; d3.select("body").selectAll("p") .data(dataset) .enter() .append("p") .text("New paragraph!") </script> </body> </html>
Grails g:select setting selectedIndex
How do you set the selectedIndex on a <g:select> tag with a value from the list? I have a page that allows you to add a record. the page then goes to a view containing a g:select and i want the g:select to default to that item i just inserted into the database. I tried passing the new object in the flash but i can't figure out how to get it's index in the list being used to generate the g:select data.
Supposing you store a Book object in flash.book at the controller level, your second page could look like this : <html> <head> <g:javascript library="prototype" /> <g:javascript> function showLast(selectedId) { if (selectedId) { $$('#books option[value=' + selectedId + "]")[0].selected = true; } else { $('books').selectedIndex = 0; } }; Event.observe(window, 'load', init, false); function init() { showLast(${flash?.book?.id}); } </g:javascript> </head> <body> <g:select id="books" name="id" from="${Book.list()}" value="title" optionValue="title" optionKey="id" /> </body> </html>