Change Image width Ajax, browser memory leaks - image

This is my html test page:
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<style type="text/css">
#imager img{
width: 1050px;
height:650px;
}
</style>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
var index = 0;
var max = 1;
//! get next image
function getImage(){
if (index >= max ) index = 0;
var objTest = {
"index" : index++
};
$.ajax({
type: 'POST',
url: "prova.php",
data: objTest,
success: function(response){
max = response.max;
imageToLoad = response.imageToLoad;
//! Clean div
$("#imager").html("");
//! Display new image
$("#imager").append("<img src='"+imageToLoad+"'></img>");
},
dataType: "json"
});
}
</script>
</head>
<body>
<button onclick="getImage()">get img</button>
<div id="imager"></div>
</body>
And this is my prova.php test page:
$max = 0;
$imgToLoad = null;
// Open image dir
if ($handle = opendir('img')) {
while (false !== ($entry = readdir($handle))) {
if($entry == '.' || $entry == '..' ) continue;
if($_POST['index'] == $max)
// Save next image to show
$imgToLoad =$entry;
// Image counter
$max++;
}
closedir($handle);
}
$array = array(
"max" => $max,
"imageToLoad" => "http://192.168.1.96/prove/cache/img/".$imgToLoad
);
// Return next image and max number of image the we can show
echo json_encode($array);
The problem is that every time that i call "getImage()" the memory browser incrase ( IE and Firefox tested).
My 'img' folder contains a lot of very huge images, about 4600x3000px (400kb), and after a little time the memory brower is about 1 gb and so on.
Thanks for help

Related

d3.js v5 stratify returning missing: 0

I have created a very simple test case to use the D3.JS v5 stratify method. Everything looks to be in order based on similar code but mine fails and I am not sure why. Can anyone help?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<script>
let csvdata =
`pk,firstname,lastname,email,title,city,statecode,zip,phone,latitude,longitude,fk_staff
1,Thomas,Bellmer,thomas.bellmer#gmail.com,President,Overland Park,KS,66221,9132216533,38.86182,-94.71264,
2,Xnx,Zgulx,xnx.zgulx#gmail.com,Vice President,Royal Palm Beach,FL,33421,5615120044,26.6802,-80.204984,1
3,Kjc,Duxuk,kjc.duxuk#gmail.com,Vice President,Newtown,IN,47969,7656204292,40.205844,-87.148287,1`
;
data = d3.csvParse(csvdata);
data.forEach(function(d) {
d.pk = +d.pk;
d.fk_staff = +d.fk_staff;
});
console.log(data);
let root = d3.stratify()
.id(function(d) { return d.pk; })
.parentId(function(d) { return d.fk_staff; })
(data);
console.log(root);
</script>
</body>
</html>
The issue is happening here:
data.forEach(function(d) {
d.pk = +d.pk;
d.fk_staff = +d.fk_staff;
});
Some of the data has an empty string as d.fk_staff. When the empty string is coerced to a number it becomes 0, and there is no data with d.pk equals to 0, hence the error.
A simple fix is to not coerce the empty string:
data.forEach(function(d) {
d.pk = +d.pk;
d.fk_staff = d.fk_staff === '' ? '' : +d.fk_staff;
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<script>
let csvdata =
`pk,firstname,lastname,email,title,city,statecode,zip,phone,latitude,longitude,fk_staff
1,Thomas,Bellmer,thomas.bellmer#gmail.com,President,Overland Park,KS,66221,9132216533,38.86182,-94.71264,
2,Xnx,Zgulx,xnx.zgulx#gmail.com,Vice President,Royal Palm Beach,FL,33421,5615120044,26.6802,-80.204984,1
3,Kjc,Duxuk,kjc.duxuk#gmail.com,Vice President,Newtown,IN,47969,7656204292,40.205844,-87.148287,1`
;
data = d3.csvParse(csvdata);
data.forEach(function(d) {
d.pk = +d.pk;
d.fk_staff = d.fk_staff === '' ? '' : +d.fk_staff;
});
console.log(data);
let root = d3.stratify()
.id(function(d) { return d.pk; })
.parentId(function(d) { return d.fk_staff; })
(data);
console.log(root);
</script>
</body>
</html>

How to style Kendo Scheduler's weekend

I have kendo scheduler below, is there any way to set different background style for weekends.
#(Html.Kendo().Scheduler<CalenderTaskModel>()
.Name("scheduler")
.Footer(false)
.Editable(false)
.EventTemplateId("eventTemplate")
.Timezone("Etc/UTC")
.Views(views =>
{
views.AgendaView(view => view.Title("Week"));
views.MonthView(view => view.Selected(true).EventHeight(15).Title("Month"));
})
.Resources(resource =>
{
resource.Add(m => m.ResourceID)
.DataTextField("Text")
.DataValueField("Value")
.BindTo(new[] {
new { Text = "Resource 1", Value = "Resource1"} ,
new { Text = "Resource 2", Value = "Resource2"}
});
})
.DataSource(d => d
.Read("GetCalenderSummary", "Home"))
)
<script id="eventTemplate" type="text/x-kendo-template">
# if(ResourceID === 'Resource1') { #
<a class='t-resource1'>#: title #</a>
# } else if (ResourceID === 'Resource2') { #
<a class='t-resource2'>#: title #</a>
# } #
</script>
I am not looking to set background style of the event on weekend but i want to set the background of the day (weekend) itself.
So below is the sample picture i got from telerik's demo. The highlighted portion should be in different background color
You can use dayTemplate:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.common.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.rtl.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.silver.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.mobile.all.min.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2018.1.221/js/kendo.all.min.js"></script>
<style>
.k-scheduler-content td {
padding: 0;
}
.weekend {
background-color: red;
height: 100%;
padding: 5px;
}
</style>
</head>
<body>
<div id="scheduler"></div>
<script>
$("#scheduler").kendoScheduler({
date: new Date("2013/6/6"),
views: [
{
type: "month",
dayTemplate: (e) => "<div" + (e.date.getDay() === 0 || e.date.getDay() === 6 ? " class='weekend'>" : ">") + e.date.getDate() + "</div>"
}
],
dataSource: [
{
id: 1,
start: new Date("2013/6/6 08:00 AM"),
end: new Date("2013/6/6 09:00 AM"),
title: "Interview"
}
]
});
</script>
</body>
</html>
Assuming that Sunday is always the first column and Saturday the last one, you could use the following css:
.k-scheduler-monthview .k-scheduler-table td:first-child,
.k-scheduler-monthview .k-scheduler-table td:last-child {
background-color: grey;
}
On dataBound event you can go through all days and check what kind of week day it is.
dataBound: function(e) {
var view = this.viewName();
if(view == 'week' || view == 'month'){
var days = this.view().content.find("td");
for(var i = 0; i < days.length; i++){
var slot = this.slotByElement(days[i]);
var date = new Date(slot.startDate);
var isWeekend = date.getDay() == 0 || date.getDay() == 6;
if(isWeekend){
days[i].style.background = '#4CAF50'
}
}
}
}
slotByElement method gets you a scheduler's day when you pass a Html element. From there you can check whether is weekend or not.
Working fiddle where weekends get marked for "week" and "month" views.

Google Maps current location JavaScript error

I want to get my current location using Google Maps Geolocation by Latitude and Longitude and I also want to set the origin as my current location but I'm not getting the current location. What should I do?
This is my code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Draggable directions</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
var rendererOptions = {
draggable: true
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
var lat, lon, mapOptions;
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(
function(position){
lat = position.coords.latitude;
lon = position.coords.longitude;
mapOptions = {
zoom: 7,
center: new google.maps.LatLng(lat, lon),
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directionsPanel'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
calcRoute();
},
function(error){
alert('ouch');
});
}
else {
alert("Your browser doesn't support geolocations, please consider downloading Google Chrome");
}
}
function calcRoute() {
var request = {
origin: new google.maps.LatLng(lat, lon),
destination: new google.maps.LatLng(10.5200,76.2100),
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000.0;
document.getElementById('total').innerHTML = total + ' km';
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="float:left;width:70%; height:100%"></div>
<div id="directionsPanel" style="float:right;width:30%;height 100%">
<p>Total Distance: <span id="total"></span></p>
</div>
</body>
</html>

How to save a image coded in Data-URI?

I'm trying to find a trick to save a picture coded in Data-URI like this:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA1MAAAE7CAYAAAA4gNuCAAAgAElEQ…
i/fPjJwSa8k8blB7TPIbffod14w9E/Baq03hUCXPf2/wK6K8SbNo44VwAAAABJRU5ErkJggg==
Another question: Where the picture is saved in the first time in the server? Browser?
JS: save image to user's disk using javascript,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript">
window.onload = function () {
var img = document.getElementById('embedImage');
var button = document.getElementById('saveImage');
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA'+
'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO'+
'9TXL0Y4OHwAAAABJRU5ErkJggg==';
img.onload = function () {
button.removeAttribute('disabled');
};
button.onclick = function () {
window.location.href = img.src.replace('image/png', 'image/octet-stream');
};
};
</script>
</head>
<body>
<img id="embedImage" alt="Red dot"/>
<input id="saveImage" type="button" value="save image" disabled="disabled"/>
</body>
</html>
PHP: http://j-query.blogspot.com/2011/02/save-base64-encoded-canvas-image-to-png.html
<?php
// requires php5
define('UPLOAD_DIR', 'images/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
EDIT JS solution 2 (fiddle: http://jsfiddle.net/KAdN8/):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript">
var img = document.getElementById('embedImage');
if( document.createEvent ) {
var evObj = document.createEvent('MouseEvents');
evObj.initEvent( 'click', true, false );
img.dispatchEvent(evObj);
} else if( document.createEventObject ) {
img.fireEvent('on'+evt);
}
</script>
</head>
<body>
Download
</body>
</html>

OpenLayers: Geocoding Data Google + OSM

I got this error TypeError: placemarks is undefined I use google api and openlayer api .
help me this. I am using google api v3 and openLayer map i want to give address in textbox and click button and the geocoding perform.
In my code I got this error TypeError: placemarks is undefined Here is my full code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>OpenLayers: Geocoding Data Google + OSM</title>
<link rel="stylesheet" href="../theme/default/style.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key=AIzaSyBz7CjlxpWO8HgM_ATuq3_F85wfAoupXck&language=de"></script>
<script src="OpenLayers.js"></script>
<script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js" type="text/javascript"></script>
<style type="text/css">
#map {
width: 100%;
height: 80%;
border: 1px solid black;
}
</style>
<script type="text/javascript">
var map, vectors, geocoder;
// Define marker style
// #fixme: where can we get information about these marker styles
var markerStyle = {
externalGraphic : 'img/marker.png',
pointRadius : 12
};
function init() {
// Add the map
var options = {
projection : new OpenLayers.Projection("EPSG:900913"),
displayProjection : new OpenLayers.Projection("EPSG:4326"),
units : "m",
maxResolution : 156543.0339,
maxExtent : new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34)
};
map = new OpenLayers.Map('map', options);
// Add the OpenStreetMaps Layer
var osm = new OpenLayers.Layer.OSM.Mapnik("OpenStreetMap (Mapnik)", {
displayOutsideMaxExtent : true,
wrapDateLine : true,
buffer : 0
});
map.addLayer(osm);
// Add the google maps Layer
var gmap = new OpenLayers.Layer.Google("Google", {
sphericalMercator : true
});
map.addLayer(gmap);
// Add a vector Layer which holds the markers
vectors = new OpenLayers.Layer.Vector("Vector Layer");
map.addLayer(vectors);
// Allow marker drag
var dragCtl = new OpenLayers.Control.DragFeature(vectors);
dragCtl.onComplete = function(feature, position) {
var ll = map.getLonLatFromPixel(position);
var coords = ll.transform(map.getProjectionObject(), new OpenLayers.Projection("EPSG:4326"));
alert('New coordinates: ' + coords.lon + ' ' + coords.lat);
}
map.addControl(dragCtl);
dragCtl.activate();
map.addControl(new OpenLayers.Control.LayerSwitcher());
// Center map
var centerLonLat = new OpenLayers.LonLat(10.5, 51.6).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
map.setCenter(centerLonLat, 5);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address' : address
}, gotGeocodes);
alert("hiiii");
}
function gotGeocodes(response) {
// Clear markers from vector layer
alert("hi");
vectors.destroyFeatures();
if (typeof response.location !== 'undefined') {
alert("Sorry, we were unable to geocode that address");
} else {
var placemarks = response.Placemark;
// We may get more than one result here. So you can display
// all results or just the first like here
if (placemarks.length > 0) {
var coords = placemarks[0].Point.coordinates;
var ll = new OpenLayers.LonLat(coords[0], coords[1]).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
var pointGeometry = new OpenLayers.Geometry.Point(ll.lon, ll.lat);
var point = new OpenLayers.Feature.Vector(pointGeometry, null, markerStyle);
vectors.addFeatures([point]);
map.setCenter(ll, 16);
}
}
}
</script>
</head>
<body onload="init();">
<h1 id="title">Get geocoding data from google</h1>
<p id="shortdesc">
Get geocoding data from google an show it in openstreetmap or google maps.
</p>
<form action="#" onsubmit="codeAddress(); return false;">
<strong>Enter an address:</strong>
<input type="text" id="address" name="q" value="" size="40" />
<input type="submit" name="find" value="Search" />
</form>
<div id="map"></div>
</body>
</html>

Resources