SyntaxError: private fields are not currently supported - html-lists

Problem to enable 3d map of openlayers. 2D map works great. Using parcel and all dependencies are added.
Once importing cesium on js file i got SyntaxError: private fields are not currently supported.
In package json file added "cesium": "^1.62.0".
<html>
<head></head>
<body>
<div id="map" style="height: 400px;"></div>
<script src="index.js"></script>
</body>
</html>
import 'ol/ol.css';
import Cesium from 'cesium'; // --> THIS LINE MAKES ERROR
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import {defaults as defaultControls} from 'ol/control';
import ZoomSlider from 'ol/control/ZoomSlider';
import OLCesium from 'olcs/OLCesium.js';
var view = new View({
center: [328627.563458, 5921296.662223],
zoom: 8,
extent: [-572513.341856, 5211017.966314,
916327.095083, 6636950.728974]
});
new Map({
layers: [
new TileLayer({
source: new OSM()
})
],
keyboardEventTarget: document,
target: 'map',
view: view,
controls: defaultControls().extend([new ZoomSlider()])
});
const ol3d = new OLCesium({map: map}); // ol2dMap is the ol.Map instance
ol3d.setEnabled(true);

I received this error when I forgot quotes around ID. $(#fail) $("#works")

I received this error for mis-matching opening and closing signs for a string in JavaScript:
(!!(v)) ? $('#is_err_" + j + "_ALARM").show() : $('#is_err_" + j + "_ALARM").hide();
(some of these strings are opened with ' sign, but closed with " sign)

you are mixing up " and '. Try this:
(!!(v)) ? $("#is_err_" + j + "_ALARM").show() : $("#is_err_" + j + "_ALARM").hide();

Related

Using vue2-google-maps with Laravel 9: The map is empty

My Laravel 9 project uses Vue 2.6 and Vuetify.
As I need to display a Google map, I decided to use vue2-google-maps package. My Google Maps is displaying as blank (though it does take the proper width and height on the page)
This is my app.js file:
import Vue from 'vue'
import vuetify from './plugins/vuetify' // path to vuetify export
import * as VueGoogleMaps from 'vue2-google-maps'
Vue.use(VueGoogleMaps,{
key:'My_GOOGLE_API_KEY',
libraries: 'places',
})
new Vue({
vuetify,
}).$mount('#app')
The is my blade file
<template>
<div class="map">
<p>Google Map</p>
<gmap-map
:center="{
lat: 47.2736,
lng: 16.0843
}"
:zoom = "7"
style="width:100%; height: 280px;"
>
</gmap-map>
</div>
</template>
Am I doing something wrong? Please advise how to fix the issue or if there is any suggestion to use some-other package.
Thanks.

CkEditor5 insertContent Function not working

I am trying to use insertContent method but getting some error.
Here is my implementation
<div id="editor">
<p>This is the editor content.</p>
</div>
<button onclick="update()">update</button>
<script src="./node_modules/#ckeditor/ckeditor5-build-classic/build/ckeditor.js"></script>
<script>
var editorInstance;
ClassicEditor
.create(document.querySelector('#editor'))
.then(editor => {
editorInstance = editor;
})
.catch(error => {
console.error(error);
});
function update() {
editorInstance.model.insertContent("<p><b>Test</b> Content</p>")
}
</script>
update method should update the editor source with given content, but I am getting an error
Error on the console:
Uncaught TypeError: e.is is not a function
at xc.Nm (converters.js:777)
at xc.fire (emittermixin.js:209)
at xc. [as insertContent] (observablemixin.js:259)
at update (ck5.html:19)
at HTMLButtonElement.onclick (ck5.html:4)
Can anyone please help in sorting out this issue?
This error appears to be caused by trying to use the insertContent method to insert HTML - this method seems to expect a plain text string by default, although we can make it accept HTML with a few extra steps.
First of all, you'll need to grab the HTML Data Processor:
const htmlDP = editorInstance.data.processor;
Next you need to convert your HTML string into a viewFragment using the HTML Data Processor that we just obtained:
const viewFragment = htmlDP.toView("<p><b>Test</b> Content</p>");
Last of all, we need to convert the viewFragment to a modelFragment:
const modelFragment = editorInstance.data.toModel( viewFragment );
Now we can pass the modelFragment to the insertContent method:
editorInstance.model.insertContent(modelFragment);
This should remove the error and allow the mark-up string to be inserted into the editor

react not receiving prop from html

I have a react component in a file named ts.js:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
export default class Ts extends React.Component {
constructor(props) {
super(props);
var expected = {
lowercase:'Onlylowercase',
snakeCase:'justSnakeCase',
ProperCase: 'AndProperCase'
};
console.log("expected:",expected);
console.log("props:",props);
console.log("this.props",this.props);
console.log("props.lowercase",props.lowercase);
this.state={'lowercase':this.props.lowercase};
};
render() {
return NULL;
}
}
if (document.getElementById('ts')) {
ReactDOM.render(<Ts />, document.getElementById('ts'));
}
I also have a html page from where this is called:
<html>
<head>
<title>My TS</title>
</head>
<body>
<Ts lowercase="onlylowercase" id="ts" snakeCase="justSnakeCase" ProperCase="AndProperCase">
</Ts>
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
My issue is I can't get the values lowercase="onlylowercase" id="ts" snakeCase="justSnakeCase" ProperCase="AndProperCase" recognised as props in the constructor. I need to pass in some stuff from the html to populate the initial state of the component.
When I open the HTML with Chrome console open I get:
expected: {lowercase: "Onlylowercase", snakeCase: "justSnakeCase", ProperCase: "AndProperCase"}
props: {}
__proto__: Object
or it is this.props?: {}
__proto__: Object
props.lowercase undefined
this.props.lowercase undefined
undefined
undefined
I am expecting props to be a javascript object with properties of lowercase, snakeCase and ProperCase, like the var expected.
I don't think I need to use componentWillReceiveProps - as I am trying to follow the pattern describe in the documentation here:
https://reactjs.org/docs/react-component.html#constructor
and pass in props as html attributes as described here:
https://reactjs.org/docs/components-and-props.html
I have excluded from this post the detail of the node modules and javascript includes - as the Ts component's constructor is being called which demonstrates the Ts class is "there" and my npm config is OK - it is including react and other required modules. The {{ asset() }} function is a Laravel function. The html is part of a blade template in a Laravel app.
Can anyone see what I am doing wrongly?
Your syntax is wrong. React doesn't creat a new html tag like "". You only can use tag in react component. So the right syntax is in html replace
<Ts lowercase="onlylowercase" id="ts" snakeCase="justSnakeCase" ProperCase="AndProperCase">
</Ts>
To <div id="ts"></div>
and go add to before
<script>
var lowercase="whatever";
var snakeCase="snakeCase";
...
</script>
And change to
if (document.getElementById('ts')) {
ReactDOM.render(<Ts lowercase={lowercase} snakeCase={snakeCase} />, document.getElementById('ts'));
}
ReactDOM will find a dom with id is "ts" and replace it by your ts component.

Scraping framework with xpath support

I'm looking for a web scraping framework that lets me
Hit a given endpoint and load the html response
Search for elements by some css selector
Recover the xpath for that element
Any suggestions? I've seen many that let me search by xpath, but none that actually generate the xpath for an element.
It seems to be true that not many people search by CSS selector yet want a result as an XPath instead, but there are some options to get there.
First I wound up doing this with JQuery plus an additional function. This is because JQuery has pretty nice selection and is easy to find support for. You can use JQuery in Node.js, so you should be able to implement my code in that domain (on a server) instead of on the client (as shown in my simple example). If that's not an option, you can look below for my other potential solution using Python or at the bottom for a C# starter.
For the JQuery approach, the pure JavaScript function is pretty simple for returning the XPath. In the following example (also on JSFiddle) I retrieved the example anchor element with the JQuery selector, got the stripped DOM element, and sent it to my getXPath function:
<html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function getXPath( element )
{
var xpath = '';
for ( ; element && element.nodeType == 1; element = element.parentNode )
{
var id = $(element.parentNode).children(element.tagName).index(element) + 1;
id > 1 ? (id = '[' + id + ']') : (id = '');
xpath = '/' + element.tagName.toLowerCase() + id + xpath;
}
return xpath;
}
$(document).ready(function() {
$("#example").click(function() {
alert("Link Xpath: " + getXPath($("#example")[0]));
});
});
</script>
</head>
<body>
<p id="p1">This is an example paragraph.</p>
<p id="p2">This is an example paragraph with a <a id="example" href="#">link inside.</a></p>
</body>
</html>
There is a full library for more robust CSS selector to XPath conversions called css2xpath if you need more complexity than what I provided.
Python (lxml):
For Python you'll want to use lxml's CSS selector class (see link for full tutorial and docs) to get the xml node.
The CSSSelector class
The most important class in the lxml.cssselect module is CSSSelector.
It provides the same interface as the XPath class, but accepts a CSS
selector expression as input:
>>> from lxml.cssselect import CSSSelector
>>> sel = CSSSelector('div.content')
>>> sel #doctest: +ELLIPSIS <CSSSelector ... for 'div.content'>
>>> sel.css
'div.content'
The selector actually compiles to XPath, and you can see the
expression by inspecting the object:
>>> sel.path
"descendant-or-self::div[#class and contains(concat(' ', normalize-space(#class), ' '), ' content ')]"
To use the selector, simply call it with a document or element object:
>>> from lxml.etree import fromstring
>>> h = fromstring('''<div id="outer">
... <div id="inner" class="content body">
... text
... </div></div>''')
>>> [e.get('id') for e in sel(h)]
['inner']
Using CSSSelector is equivalent to translating with cssselect and
using the XPath class:
>>> from cssselect import GenericTranslator
>>> from lxml.etree import XPath
>>> sel = XPath(GenericTranslator().css_to_xpath('div.content'))
CSSSelector takes a translator parameter to let you choose which
translator to use. It can be 'xml' (the default), 'xhtml', 'html' or a
Translator object.
If you're looking to load from a url, you can do that directly when building the etree: root = etree.fromstring(xml, base_url="http://where.it/is/from.xml")
C#
There is a library called css2xpath-reloaded which does nothing but CSS to XPath conversion.
String css = "div#test .note span:first-child";
String xpath = css2xpath.Transform(css);
// 'xpath' will contain:
// //div[#id='test']//*[contains(concat(' ',normalize-space(#class),' '),' note ')]*[1]/self::span
Of course, getting a string from the url is very easy with C# utility classes and needs little discussion:
using(WebClient client = new WebClient()) {
string s = client.DownloadString(url);
}
As for the selection with CSS Selectors, you could try Fizzler, which is pretty powerful. Here's the front page example, though you can do much more:
// Load the document using HTMLAgilityPack as normal
var html = new HtmlDocument();
html.LoadHtml(#"
<html>
<head></head>
<body>
<div>
<p class='content'>Fizzler</p>
<p>CSS Selector Engine</p></div>
</body>
</html>");
// Fizzler for HtmlAgilityPack is implemented as the
// QuerySelectorAll extension method on HtmlNode
var document = html.DocumentNode;
// yields: [<p class="content">Fizzler</p>]
document.QuerySelectorAll(".content");
// yields: [<p class="content">Fizzler</p>,<p>CSS Selector Engine</p>]
document.QuerySelectorAll("p");
// yields empty sequence
document.QuerySelectorAll("body>p");
// yields [<p class="content">Fizzler</p>,<p>CSS Selector Engine</p>]
document.QuerySelectorAll("body p");
// yields [<p class="content">Fizzler</p>]
document.QuerySelectorAll("p:first-child");

Spring - download response as a file

I am writing application using AngularJS and Spring. I would like to send request to the server and download response returned from controller as a file. In controller I have content of csv file (as string) i.e. 1;2;3;4 (1 row, 4 columns). What is the simplest way to download this response as a file?
Below, I posted my simplified code.
In Spring controller:
#RequestMapping(value = "/csv", method = GET)
#ResponseBody
public String getCsvFile() {
return getCsvContent();
}
In javascript (AngularJS)
return $http({method: 'GET', url: 'csv/'});
I was trying to write to the response stream also (below), setting headers, but on client side I always get this content as a string - not as a file to download.
#RequestMapping(value = "/csv", method = GET)
#ResponseBody
public void getCsvFile(HttpServletResponse response) {
response.setContentType("application/csv");
response.setHeader("Content-Disposition", "attachment; filename=file.csv");
response.setContentLength(getCsvContent().getBytes().length);
ServletOutputStream out = response.getOutputStream();
out.write(getCsvContent());
out.flush();
out.close();
}
Does anyone knows how to write controller's method correctly in order to download response as a file on client side?
You can't download a file through an XHR request (which is how Angular makes it's requests). See Why threre is no way to download file using ajax request? You either need to go to the URL via $window.open or do the iframe trick shown here: JavaScript/jQuery to download file via POST with JSON data
I've wrestled with this myself, trying to make it work from the server. Couldn't. Instead...
To clarify on #dnc253's answer, $window.open(URL) is a method for having an Angular application open a given URL in another window. (It's really just a testable angular proxy for the universal window.open().) This is a great solution, preserves your history, and gets the file downloaded and possibly renders it in that fresh browser window if that's supported. But it often runs into popup blockers, which is a huge problem for reliability. Users often simply don't understand what's going on with them. So, if you don't mind immediately downloading the file with the current window, you can simply use the equally effective universal javascript method: location.href = "uriString", which works like a charm for me. Angular doesn't even realize anything has happened. I call it in a promise handler for once my POST/PUT operation has completed. If need be, have the POST/PUT return the URL to call, if you can't already infer it. You'll get the same behavior for the user as if it had downloaded in response to the PUT/POST. For example:
$http.post(url, payload).then(function(returnData){
var uriString = parseReturn(returnData);
location.href="uriString"
})
You can, in fact, download something directly from an XHR request, but it requires full support for the HTML5 file API and is usually more trouble than it's worth unless you need to perform local transformations upon the file before you make it available to the user. (Sadly, I lack the time to provide details on that but there are other SO posts about using it.)
It is possible to download a file using XHR request. You can use angular $http to load the file and then use Blob feature of HTML5 to make browser save it. There is a library that can help you with saving: FileSaver.js.
Just in case you guys need it,
Here a couple of links that can help you:
download csv file from web api in angular js
Export javascript data to CSV file without server interaction
Cheers
I have written comments below to understand code sample. Some one if using, they can follow it , as I named the files accordingly.
IF server is sending blob in the response, then our client should be able to produce it.
As my purpose is solved by using these. I can able to download files, as I have used type: 'application/*' for all files.
Created "downloadLink" variable is just technique used in response so that, it would fill like some clicked on link, then response comes and then its href would be triggered.
controller.js
//this function is in controller, which will be trigered on download button hit.
$scope.downloadSampleFile = function() {
//create sample hidden link in document, to accept Blob returned in the response from back end
var downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
downloadLink.style = "display: none";
//This service is written Below how does it work, by aceepting necessary params
downloadFile.downloadfile(data).then(function (result) {
var fName = result.filename;
var file = new Blob([result.data], {type: 'application/*'});
var fileURL = (window.URL || window.webkitURL).createObjectURL(file);
//Blob, client side object created to with holding browser specific download popup, on the URL created with the help of window obj.
downloadLink.href = fileURL;
downloadLink.download = fName;
downloadLink.click();
});
};
services.js
.factory('downloadFile', ["$http", function ($http) {
return {
downloadfile : function () {
return $http.get(//here server endpoint to which you want to hit the request
, {
responseType: 'arraybuffer',
params: {
//Required params
},
}).then(function (response, status, headers, config) {
return response;
});
},
};
}])
It's working for me :
Spring controller : DownloadController.java
package com.mycompany.myapp.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.mycompany.myapp.exception.TechnicalException;
#RestController
public class DownloadController {
private final Logger log = LoggerFactory.getLogger(DownloadController.class);
#RequestMapping(value = "/download", method = RequestMethod.GET)
public void download(#RequestParam ("name") String name, final HttpServletRequest request, final HttpServletResponse response) throws TechnicalException {
log.trace("name : {}", name);
File file = new File ("src/main/resources/" + name);
log.trace("Write response...");
try (InputStream fileInputStream = new FileInputStream(file);
OutputStream output = response.getOutputStream();) {
response.reset();
response.setContentType("application/octet-stream");
response.setContentLength((int) (file.length()));
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
IOUtils.copyLarge(fileInputStream, output);
output.flush();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
AngularJs Service : download.service.js
(function() {
'use strict';
var downloadModule = angular.module('components.donwload', []);
downloadModule.factory('downloadService', ['$q', '$timeout', '$window',
function($q, $timeout, $window) {
return {
download: function(name) {
var defer = $q.defer();
$timeout(function() {
$window.location = 'download?name=' + name;
}, 1000)
.then(function() {
defer.resolve('success');
}, function() {
defer.reject('error');
});
return defer.promise;
}
};
}
]);
})();
AngularJs config : app.js
(function() {
'use strict';
var myApp = angular.module('myApp', ['components.donwload']);
/* myApp.config([function () {
}]);
myApp.run([function () {
}]);*/
})();
AngularJs controller : download.controller.js
(function() {
'use strict';
angular.module('myApp')
.controller('DownloadSampleCtrl', ['downloadService', function(downloadService) {
this.download = function(fileName) {
downloadService.download(fileName)
.then(function(success) {
console.log('success : ' + success);
}, function(error) {
console.log('error : ' + error);
});
};
}]);
})();
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>My App</title>
<link rel="stylesheet" href="bower_components/normalize.css/normalize.css" />
<link rel="stylesheet" href="assets/styles/main.css" />
<link rel="icon" href="favicon.ico">
</head>
<body>
<div ng-controller="DownloadSampleCtrl as ctrl">
<button ng-click="ctrl.download('fileName.txt')">Download</button>
</div>
<script src="bower_components/angular/angular.min.js"></script>
<!-- App config -->
<script src="scripts/app/app.js"></script>
<!-- Download Feature -->
<script src="scripts/app/download/download.controller.js"></script>
<!-- Components -->
<script src="scripts/components/download/download.service.js"></script>
</body>
</html>
//JAVA PART
#RequestMapping(value = "/report-excel", method = RequestMethod.GET)
public ResponseEntity<byte[]> getReportExcel(#RequestParam("bookingStatusType") String bookingStatusType,
#RequestParam("endDate") String endDate, #RequestParam("product") String product, #RequestParam("startDate") String startDate)throws IOException, ParseException {
//Generate Excel from DTO using any logic after that do the following
byte[] body = wb.getBytes();
HttpHeaders header = new HttpHeaders();
header.setContentType(new MediaType("application", "xlsx"));
header.set("Content-Disposition", "inline; filename=" + fileName);
header.setCacheControl("must-revalidate, post-check=0, pre-check=0");
header.setContentLength(body.length);
return new ResponseEntity<byte[]>(body, header, HttpStatus.OK);
}
//HTML PART
<html>
<head>
<title>Test</title>
<meta http-equiv="content-type" content="application/x-www-form-urlencoded; charset=UTF-8">
</head>
<body>
<form name="downloadXLS" method="get" action="http://localhost:8080/rest/report-excel" enctype="multipart/form-data">
<input type="text" name="bookingStatusType" value="SALES"></input>
<input type="text" name="endDate" value="abcd"></input>
<input type="text" name="product" value="FLIGHT"></input>
<input type="text" name="startDate" value="abcd"></input>
<input onclick="document.downloadXLS.submit()" value="Submit"></input>
</form>
</body>
</html>

Resources