I am trying to create a time series graph using d3-timeseries, a d3.js based library. I am using the implementation mentioned by the author in my JSP script tag of the body but I get nothing. Any help is appreciated.
My Code:
//data :
// [{date:new Date('2013-01-01'),n:120,n3:200},...]
var chart = d3.timeseries()
.addSeries(data,{x:'date',y:'n',diff:'n3'},
{interpolate:'monotone',color:"#333"}).width(900)
chart('#chart')
To use this library you need to perform a few steps which are not very well documented anywhere.
Download ZIP.
Install bower if you don't have already
Do bower install inside this directory
Zip will contain an src folder with d3_timeseries.js and d3_timeseries.css link both of them to your html file
Sample index.html file that will work if used within the folder you unzipped library:
<html>
<head>
<script src="bower_components/d3/d3.min.js"></script>
<script src="src/d3_timeseries.js"></script>
<link href="src/d3_timeseries.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="chart" id="chart3"></div>
</body>
<script>
var data = createRandomData(80,[0,1000],0.01)
var chart3 = d3.timeseries()
.addSerie(data,{x:'date',y:'n',diff:'n3'},{interpolate:'monotone',color:"#333"})
.width(900)
chart3('#chart3')
function createRandomData(n,range,rand)
{
if(range==null)
range=[0,100]
if(rand==null)
rand=1/20
var num = range[0] + Math.floor(Math.random()*(range[1]-range[0]))
var num2 = range[0] + Math.floor(Math.random()*(range[1]-range[0]))
var num3 = num
var d= new Date('2013-01-01')
var data = []
var rgen = d3.random.normal(0,(range[1]-range[0])*rand)
for (var i = 0; i<n; i++)
{
data.push({date:d,n:num,n2:num2,n3:num3,
ci_up:num3*1.05,ci_down:num3*0.95
})
d = new Date(d.getTime() + 1000*60*60*24)
num = num+rgen()
num3 = num+rgen()/3
num = Math.min(Math.max(num,range[0]),range[1])
num2 = num2+rgen()
num2 = Math.min(Math.max(num2,range[0]),range[1])
}
return data;
}
</script>
</html>
Related
I am trying to implement the following code in which i try to read a json file in javascript. I have two files , let one be main.html which has the main javascript code let it be called main.js , and the other is imported.js
This is the main.html file
<!Doctype html>
<html>
<head>
Dwell time for workers
</head>
<script src = https://requirejs.org/docs/release/2.3.6/r.js></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script type="text/javascript" src="text.json"></script>
<script src="testing_file.js"></script>
<script type = "text/javascript"></script>
<script>
var Import = new import_file('osama'); // constructor
var out = Import.dwell_times()
console.log('out')
console.log(out[2]);
</script>
<body>
<h1> worker time : </h1>
</body>
</html>
This is the imported.js file
var that = null;
class import_file
{
constructor(title)
{
this.title = title;
that = this;
}
dwell_times()
{
console.log('osama')
var x = [5,4,3,2,1] ;
var y = x.toString();
console.log(y)
let parsed = require('./updated.json')
console.log(parsed) ;// Arham
return parsed;
}
}
var Import = new import_file('osama'); // constructor
var out = Import.dwell_times()
console.log('out')
console.log(out[2])
I am getting the following error
Uncaught Error: Module name "updated.json" has not been loaded yet for context: _. Use require([])
https://requirejs.org/docs/errors.html#notloaded
at makeError (r.js:417)
at Object.localRequire [as require] (r.js:1685)
at requirejs (r.js:2046)
at import_file.dwell_times (testing_file.js:16)
at imported.js:23
What do i do to solve this error ?
Require is unable to parse this out and automatically convert it. The solution is to convert to the callback syntax :
var moduleName = './updated.json';
require([moduleName], function(fooModule){
// do something
})
I need to load the text file data into a javascript array and define a dynamic form using html.
I tried below code for extracting data from text file and to store in a javascript array and it works as long as it is in .js file
var fs = require('fs');
var textByLine = fs.readFileSync('123.txt').toString().split("\n");
console.log(textByLine);
but when I embed it inside my html file this doesn't work.
below is my html code. for now I am just forming an array with months but i need to replace it with array taken from the text file.
<html>
<head>
<title></title>
<META NAME="DESCRIPTION" CONTENT="">
<META NAME="KEYWORDS" CONTENT="">
<script language="javascript">
var dt=new Date();
var dt_month=dt.getMonth() +1;
//alert(dt_month);
function addOption(selectbox,text,value )
{
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}
function addOption_list(){
var month = new Array("January","February","March","April","May","June","July","August",
"September","October","November","December");
for (var i=0; i < month.length;++i){
addOption(document.drop_list.Month_list, month[i], month[i]);
document.drop_list.Month_list.options[i].selected=true;
}
}
</script>
</head>
<body onLoad="addOption_list()";>
You can see the view-> Source of this page.
<br><br>
<FORM name="drop_list" action="yourpage.php" method="POST" >
<SELECT NAME="Month_list">
<Option value="" >Month list</option>
</SELECT>
</form>
</body>
</html>
I gave the 3 line code which is working independently as a .js file inside addOption_list function in above code and it doesn't work. Appreciate help on this.
Thanks in advance
The FileSytem (fs) module is for NodeJS applications so needs to be in .js file. If you want to load the file into your html you can use Ajax instead. This may work:
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this.responseText);
}
};
xhttp.open("GET", "123.txt", true);
xhttp.send();
}
function myFunction(data) {
var textByLine = data.split("\n");
console.log(textByLine);
}
loadDoc();
</script>
I have an XLS file with data in it.
The excel file has a lot of reference in one column, so I want the user to type the reference then the web page search for the reference and show the data in the line found.
I can't use a server, so I want to do it without PHP or things like that.
Is it possible ? How can I do that ?
Thanks
Here is the sample of js-xlsx, and will return all values in all worksheets as JSON object, you may need to modify by your usage.
<html>
<script src="xlsx.core.min.js"></script>
<head></head>
<body>
</body>
<script type ="text/javascript">
"use strict";
var X = XLSX;
function convertFile(b64data) {
var wb = X.read(b64data, {type: 'base64',WTF: false});
var result = {};
wb.SheetNames.forEach(function(sheetName) {
var roa = X.utils.sheet_to_row_object_array(wb.Sheets[sheetName]);
if(roa.length > 0){
result[sheetName] = roa;
}
});
return JSON.stringify(result, 2, 2);
}
</script>
</html>
More option (by upload file, drag and drop option), you can study the source code of js-xlsx example: http://oss.sheetjs.com/js-xlsx/
You don't need PHP but at least Javascript.
You can do it like this:
var excel = new ActiveXObject("Excel.Application");
var wb = excel.Workbooks.Open("Path/to/your/excel/file.xls");
var ws = wb.ActiveSheet;
var cell = ws.Cells.Find("your search input");
alert(cell.Row);
excel.Quit();
I hope i could help you;)
I have an .csv file that looks like:
oS,browName,browVer,timeCanvas,timeSvg
Windows,Firefox,25.0,0.25,1.23
Windows,Opera,12.16,0.572,1.465
And i would like to do a function that will count arithmetic mean for timeCanvas and timeSvg looking something like:
for (int i = 0; i < maxrow; i++)
{
if(oS=Windows)
{
if(browName=FireFox
{
if(browVer=25.0)
{
a=a+1;
timeC=timeC+timeCanvas
timeS=timeS+timeSvg
}
}
}
...
}
I googled my problem and only solution i could find was jquery-csv 0.7 with toObjects method (http://code.google.com/p/jquery-csv/)> I would like to know is it possible with this libaarry to do what i want?? And if there are some good examples (couldnt find myself)??
..........................................................................
Edit:
so i tryed vadim solution but it deos not working and i dont know hwat i do worng.Here is the code.
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript">
function draw(){
var a = 0,
timeC = 0,
timeS = 0,
meanCFf=0,
meanSFf= 0;
$.get('test1.csv').done(function(data) {
var i,
lines = data.split('\n'),
line = lines[0].split(','),
oS = line.indexOf('oS'),
browName = line.indexOf('browName'),
browVer = line.indexOf('browVer'),
timeCanvas = line.indexOf('timeCanvas'),
timeSvg = line.indexOf('timeSvg');
for(i=1; i<lines.length; i++) {
line = lines[i].split(',');
if(line[oS] === 'Windows') {
a++;
timeC += parseFloat(line[timeCanvas], 10);
timeS += parseFloat(line[timeSvg], 10);
}
}
});
meanCFf = timeC/a;
meanSFf = timeC/a;
var os1 = document.getElementById("osInfo1");
os1.innerHTML = "Twoja średnia to: " + meanCFf;
var os2 = document.getElementById("osInfo2");
os2.innerHTML = "Twój sytem operacyjny to: " + meanSFf;
}
</script>
</head>
<body onload="draw()">
<p id="osInfo1"></p>
<p id="osInfo2"></p>
</body>
It looks like for loop is not working coz a is zero all the time.
Using jQuery you can do something like this:
JavaScript (script.js)
$(function() {
var a = 0,
timeC = 0,
timeS = 0;
$.get('test1.csv').done(function(data) {
var i,
lines = data.split(/\r\n|\n/),
line = lines[0].split(','),
oS = line.indexOf('oS'),
browName = line.indexOf('browName'),
browVer = line.indexOf('browVer'),
timeCanvas = line.indexOf('timeCanvas'),
timeSvg = line.indexOf('timeSvg');
for(i=1; i<lines.length; i++) {
line = lines[i].split(',');
if(line[oS] === 'Windows' && line[browName] === 'Firefox' && line[browVer] === '25.0') {
a++;
timeC += parseFloat(line[timeCanvas], 10);
timeS += parseFloat(line[timeSvg], 10);
}
}
$('#osInfo1').html("Twoja średnia to: " + timeC/a);
$('#osInfo2').html("Twój sytem operacyjny to: " + timeS/a);
});
});
HTML
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<h1>CSV Test</h1>
<div id="osInfo1"></div>
<div id="osInfo2"></div>
</body>
</html>
You could get the folder manually with javascript and then attempt to manually parse it OR you could use PHP.
PHP has some great libraries for working with CSV which come standard.
Rather than go through all the effort of working with it manually every time I would personally create a simply PHP JSON service which carries out the function you require of the csv simply and delivers the data. You can then retrieve you the data using Javascript AJAX allowing you perform the code you need as usual.
Overall, I think you'll find this will mean less code for you and theres a lot more documentation on the net to support both the PHP CSV and the JSON service.
Of course, this is assuming that you have a server that has PHP.
How can I parse the value of status = 'logged-out' to the 3 tags below it, updating the value of login_status = 'logged-out'?
<script type="text/javascript">
window.ndm = window.ndm || {};
window.ndm.cam = {'status':'logged-out'};
</script>
<script src="http://foo.com/adserver/ndm/js.php?position=header-ad§ion_id=NEWS&login_status=SUBSCRIBER"></script>
<script src="http://foo.com/adserver/ndm/js.php?position=middle-ad§ion_id=NEWS&login_status=SUBSCRIBER"></script>
<script src="http://foo.com/adserver/ndm/js.php?position=footer-ad§ion_id=NEWS&login_status=SUBSCRIBER"></script>
Keep in mind, there also heaps of other script tags on the page, so to identify the relevant ones. I got this function.
function getScriptSourceName(name){
var scripts = document.getElementsByTagName('script');
for (i=0;i<scripts.length;i++){
if (scripts[i].src.indexOf(name) > -1)
return scripts[i].src;
}}
Therefore to find the relevant script tags I want, i call the function - getScriptSourceName('foo.com');
How can I then update the login_status parameter's value to use the one declare at the very top?
I think this should work (below the HTML file for testing).
Look at changeStatus method (I triggered it by button click for testing).
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<script type="text/javascript">
window.ndm = window.ndm || {};
window.ndm.cam = {'status':'logged-out'};
</script>
<script src="http://foo.com/some.php?login_status=SUBSCRIBER"></script>
<script src="http://foo.com/some.php?login_status=SUBSCRIBER"></script>
<script src="http://foofoo01.com/some.php?login_status=SUBSCRIBER"></script>
<script>
function changeStatus(name)
{
var scripts = document.getElementsByTagName('script');
var scriptsToChange = [];
for (var i = 0; i < scripts.length; i++)
{
if (scripts[i].src.indexOf(name) > -1)
{
var oldSrc = scripts[i].src;
var newSrc = oldSrc.replace(/(login_status=).*/,'$1' + 'logged-out');
scripts[i].setAttribute("src", newSrc);
scriptsToChange.push(scripts[i]);
}
}
for (var k = 0; k < scriptsToChange.length; k++)
{
document.getElementsByTagName("head")[0].appendChild(scriptsToChange[k]);
}
}
</script>
</head>
<body>
<button type="button" onclick="changeStatus('foo.com')">Change status</button>
</body>
</html>