ReactJS/Javascript: map function and rendering - java

The Graph component is getting data (verified in console) but for some reason the page is still blank. I am not quit sure I understand how the map function works. This is the last piece I need to figure out to render this graph but for whatever reason I can't seem to get any graphics on the screen. The state of nodes in the console is:
{data: {action: [{action: "Changed", timestamp: 1499348050,…},…]}}
data:{action: [{action: "Changed", timestamp: 1499348050,…},…]}
action:[{action: "User Assist Changed", timestamp: 1499348050,…},…]
Graph Component:
import React, {Component} from 'react';
import * as d3 from "d3";
import {graphql} from 'react-apollo';
import getObjectsQuery from './Queries';
class Graph extends React.Component {
constructor(props) {
super(props);
this.state = { startTime:this.props.startTime,
endTime:this.props.endTime,
nodes:this.props.getObjectsQuery
}
//console.log('graph data:', this.props.data)
}
componentDidMount() {
console.log('nodes:', this.props.data)
this.force = d3.forceSimulation(this.props.data)
.force("charge",
d3.forceManyBody()
.strength(this.props.forceStrength)
)
.force("x", d3.forceX(this.props.width / 2))
.force("y", d3.forceY(this.props.height / 2));
this.force.on('tick', () => this.setState({nodes: this.props.data}));
console.log('setState:', this.props.data);
}
componentWillUnmount() {
this.force.stop();
}
render() {
// console.log('graph datas:', this.props.data)
return (
<svg width={this.props.width} height={this.props.height}>
{Object.keys(this.props.data).map((action, index) =>(
<circle r={action.action} cx={action.second} cy={action.obj} fill="red" key={index}/>
))}
</svg>
);
}//render
}//Component
export default graphql(getObjectsQuery,
{ options: (ownProps) => {
console.log(ownProps.startTime);
return ({ second: { startTime: ownProps.startTime,
endTime: ownProps.endTime
} })
} } )(Graph);
Graph.defaultProps = {
width: 300,
height: 300,
forceStrength: -10
};

If this.props.data.action is an array then it can be used directly in map:
{this.props.data.action.map((action,
but this.props.data.action (and even this.props.data?) can be undefined on start, first render
use some conditions in render to prevent errors, f.e.
{!this.props.data.loading && this.props.data.action.map((action,
Check if loading is present ... structure of props passed into component can be mapped differently by fn defined in config props property in graphql() (f.e. in case of conflict props names). Search for examples.

Related

Using AnyApi with React

I am trying to use AnyApi with my react app.
The request parameters are
IMDBid:string required
IMDB ID of the movie to return
GET https://hydramovies.com/api-v2/%3Fsource=http:/hydramovies.com/api-v2/current-Movie-Data.csv&imdb_id={IMDBid}
I want to be able to type in the input box and return searches from the api in my container.
Im not getting any response from the Api, can anyone help
// importing useState so we can create states
import React, {useState, useEffect} from 'react';
// Imports style sheet for APP
import './App.css';
function App() {
// setting imdbID so we can use this as a value in the input box
const [imdbID,setimdbIDs] = useState('')
const [container,setContainer] = useState([])
useEffect(() =>{
fetchMe()
},[imdbID])
const fetchMe = () => {
fetch(`https://hydramovies.com/api-v2/%3Fsource=http:/hydramovies.com/api-v2/current-Movie-Data.csv&imdb_id={IMDBid}`, {
"method": "GET"
})
.then(response => {
return response.json();
})
.then(data => {
setContainer(data.d)
})
.catch(err => {
console.error(err);
});
}
//Every letter that is typed in the input box will then change imdbID to setimdbIDs
const onChangeHandler = (e) => {
setimdbIDs(e.target.value)
}
const submitHandler = e => {
e.preventDefault()
}
return (
<div className="App">
<form onSubmit={submitHandler}>
{/* input box value is imdbID calling onChangeHandler state*/}
<input type="text" value={imdbID} onChange={onChangeHandler}/>
{/* submit button */}
<button type="submite">SUBMIT</button>
</form>
{container.map((item) =>{
return (
<p>{item.l}</p>
)
})}
</div>
);
}
export default App;
You didnt provide the IMDBid in the url correctly
the template literal should be given like `string${expression}`
so your code would be
https://hydramovies.com/api-v2/%3Fsource=http:/hydramovies.com/api-v2/current-Movie-Data.csv&imdb_id=${IMDBid}

Amazon Location map how to enable Route calculator, tracker map in react js project

I need your help to implement the AWS map, I have created the Arn for all the required map functionality but I don't know how to enable the search box and its functionality.
Map --> implemented
Place index --> need help
Route calculator --> need help
Geofence collection --> need help
Tracker --> need help
sample code for your reference:
import React, { useEffect, useState } from "react";
import { createRequestTransformer } from "amazon-location-helpers";
import { ICredentials } from "#aws-amplify/core";
import Amplify,{ Auth } from "aws-amplify";
import ReactMapGL, { NavigationControl, ViewportProps } from "react-map-gl";
import "maplibre-gl/dist/maplibre-gl.css";
import amplifyConfig from "../aws-exports";
Amplify.configure(amplifyConfig);
// Replace with the name of the map that you created on the Amazon Location Service console: https://console.aws.amazon.com/location/maps/home
const mapName = "<MAP NAME>";
const Map = () => {
const [credentials, setCredentials] = useState<ICredentials>();
const [transformRequest, setRequestTransformer] = useState<Function>();
const [viewport, setViewport] = React.useState<Partial<ViewportProps>>({
longitude: -123.1187,
latitude: 49.2819,
zoom: 10,
});
useEffect(() => {
const fetchCredentials = async () => {
setCredentials(await Auth.currentUserCredentials());
};
fetchCredentials();
}, []);
// create a new transformRequest function whenever the credentials change
useEffect(() => {
const makeRequestTransformer = async () => {
if (credentials != null) {
const tr = await createRequestTransformer({
credentials,
region: amplifyConfig.aws_project_region,
});
// wrap the new value in an anonymous function to prevent React from recognizing it as a
// function and immediately calling it
setRequestTransformer(() => tr);
}
};
makeRequestTransformer();
}, [credentials]);
return (
<div>
{transformRequest ? (
<ReactMapGL
{...viewport}
width="100%"
height="100vh"
/** #ts-ignore */
transformRequest={transformRequest}
mapStyle={mapName}
onViewportChange={setViewport}
>
<div style={{ position: "absolute", left: 20, top: 20 }}>
<NavigationControl showCompass={false} />
</div>
</ReactMapGL>
) : (
<h1>Loading...</h1>
)}
</div>
);
};
export default Map;
reference image:
I don't know how to enable the tracker and place index functionality can I get anyone help on this. Thanks in advance.

Parse unknown XML derivate

I found a file containing xml like structure. I have no idea what it is but I need to parse it.
It looks like that:
<:openingtag>
<:openingtag2>
<:openingtag3>
text
</>
</>
</>
Does anybody has an idea how to parse it? Groovy / Java / Python are fine to implement the parser.
A naive parser using petit - but of course leaves alot to cover, since the grammatic is unknown.
#Grab("com.github.petitparser:petitparser-core:2.2.0")
import org.petitparser.tools.GrammarDefinition
import org.petitparser.tools.GrammarParser
import org.petitparser.parser.primitive.CharacterParser as CP
import org.petitparser.parser.primitive.StringParser as SP
import org.petitparser.utils.Functions as F
class FakeMLGrammerDefinition extends GrammarDefinition {
FakeMLGrammerDefinition() {
define("start",
ref("tag").trim())
define("tag",
ref("tag-start")
.seq(ref("tag").star())
.seq(ref("text").optional())
.seq(ref("tag").star())
.seq(ref("tag-end")))
define("tag-start",
SP.of('<:')
.seq(ref("keyword"))
.seq(SP.of(">"))
.trim())
define("tag-end",
SP.of("</>")
.trim())
define("text",
CP.pattern("^<").star().flatten().trim())
define("keyword",
CP.letter()
.seq(CP.pattern("^>").plus())
.star()
.flatten())
}
/** Helper for `def`, which is a keyword in groovy */
void define(s, p) { super.def(s,p) }
}
class FakeMLParserDefinition extends FakeMLGrammerDefinition {
FakeMLParserDefinition() {
action("tag", { tag, c1, t, c2, _ ->
[(tag): [children: c1+c2, text: t]]
})
action("tag-start", { it[1] })
}
}
class FakeMLParser extends GrammarParser {
FakeMLParser() {
super(new FakeMLParserDefinition())
}
}
println(new FakeMLParser().parse("""
<:openingtag>
<:openingtag2>
<:openingtag3>
text
</>
</>
</>
"""))
// Success[9:1]: {openingtag={children=[{openingtag2={children=[{openingtag3={children=[], text=text}}], text=}}], text=}}

How to make an alert Box that ask user if he wants to leave the page or not only angular?

I see every day that some app has a function that when you are on a page and you are filling, for example, a form and when you tried and click somewhere else for example in nav menu or even leave the page and you have unsafe change they ask the user if he wants to leave the page, I would really appreciate if someone can provide me an example of how can this be implemented in Angular, I am not sure if this is a front or backend job in backend I am working with java. Thanks a lot, each idea count :D.
You can use canDeactivate guard for every component,
First you have to add this service file "deactivate-guard.service.ts":
import { Injectable } from '#angular/core';
import { CanDeactivate } from '#angular/router';
import { Observable } from 'rxjs/Observable';
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
#Injectable()
export class DeactivateGuardService implements CanDeactivate<CanComponentDeactivate>{
canDeactivate(component: CanComponentDeactivate) {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
then you have to provide in the app module:
providers: [
DeactivateGuardService
]
now in the component you want to protect, add the function:
export class ExampleComponent {
loading: boolean = false;
#ViewChild('exampleForm') exampleForm: NgForm;
canDeactivate(): Observable<boolean> | boolean {
if (this.loading|| this.exampleForm.dirty) {
return this.confirmBox('Discard Unsaved Changes?');
}
return true;
}
confirmBox(message?: string): Observable<boolean> {
const confirmation = window.confirm(message || 'Are you sure?');
return of(confirmation);
};
}
Add the directive to the component in the routing module:
#NgModule({
imports: [
RouterModule.forRoot([
{
path: 'example',
canDeactivate: [DeactivateGuardService],
component: ExampleComponent
}
])
]
You can use the canDeactivate guard to check a page leave and display the warning message you wish to display something like this
import { Injectable } from '#angular/core';
import { CanDeactivate } from '#angular/router';
import { Observable } from 'rxjs/Observable';
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
#Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate>{
canDeactivate(component: CanComponentDeactivate) {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
include set the can activate guard to the route like this
{ path: 'sample-path', component: SampleComponent, canDeactivate: [CanDeactivateGuard] },
and the canDeactivate method to the component
canDeactivate() {
if (this.formIsIncomplete > 0) {
let result: boolean = window.confirm("You have unsaved Changes");
return result;
}
return true;
}
it may helpful for you to make alert
https://stackblitz.com/edit/angular-confirmation-dialog

How do I stop Jawr processing some parts of CSS files?

I am currently using Jawr to compress and bundle my css, javascript and image files.
Jawr is currently converting all of the url() links in my css files, regardless whether they are images or not. For example:
#font-face {
font-family: 'NothingYouCouldSay';
src: url('../fonts/NothingYouCouldSay.eot') format('eot');
src: local("☺"), url('../fonts/NothingYouCouldSay.woff') format('woff'), url("../fonts/NothingYouCouldSay.otf") format("opentype"), url('../fonts/NothingYouCouldSay.ttf') format('truetype'), url('../fonts/NothingYouCouldSay.svg') format('svg');
font-weight: normal;
font-style: normal;
}
Jawr is converting all of the url() values, but then the resources cannot be found when the webserver is running, as I have configured the image servlet to listen only for *.png & *.jpg.
#font-face {
font-family: 'NothingYouCouldSay';
src: url('../../../cb1130234589/resources/fonts/NothingYouCouldSay.eot') format('eot');
src: local("☺"), url('../../../cb1130234589/resources/fonts/NothingYouCouldSay.woff') format('woff'), url("../../../cb1130234589/resources/fonts/NothingYouCouldSay.otf") format("opentype"), url('../../../cb1130234589/resources/fonts/NothingYouCouldSay.ttf') format('truetype'), url('../../../cb1130234589/resources/fonts/NothingYouCouldSay.svg') format('svg');
font-weight: normal;
font-style: normal;
}
If I add *.woff to the image servlet mapping, then the servlet complains that the mime type of the file is not understood.
Is there any way I can get Jawr to not process these particular particular URLs?
So, after trying a few different ideas, I ended up writing my own custom post processor to handle this. I reuse as much of the existing Jawr code as possible, which means it may be quite brittle if Jawr changes it's underlying code.
Anyway, here's what I wrote:
package com.bullethq.jawr.postprocessor;
import net.jawr.web.resource.FileNameUtils;
import net.jawr.web.resource.bundle.factory.util.PathNormalizer;
import net.jawr.web.resource.bundle.postprocess.BundleProcessingStatus;
import net.jawr.web.resource.bundle.postprocess.impl.CSSURLPathRewriterPostProcessor;
import net.jawr.web.resource.bundle.postprocess.impl.PostProcessorCssImageUrlRewriter;
import java.io.IOException;
public class CustomCssUrlPathRewriterPostProcessor extends CSSURLPathRewriterPostProcessor {
public static final String CUSTOM_URL_PATH_REWRITER = "customcsspathrewriter";
public CustomCssUrlPathRewriterPostProcessor() {
super(CUSTOM_URL_PATH_REWRITER);
}
// ========================================================================
// ========================================================================
// ========================================================================
#Override
protected PostProcessorCssImageUrlRewriter createImageUrlRewriter(BundleProcessingStatus status) {
return new CustomPostProcessorCssImageUrlRewriter(status);
}
// ========================================================================
// ========================================================================
// ========================================================================
public class CustomPostProcessorCssImageUrlRewriter extends PostProcessorCssImageUrlRewriter {
public CustomPostProcessorCssImageUrlRewriter(BundleProcessingStatus status) {
super(status);
}
// ========================================================================
// ========================================================================
// ========================================================================
#Override
protected String getUrlPath(String match, String originalPath, String newCssPath) throws IOException {
String url = match.substring(match.indexOf('(') + 1, match.lastIndexOf(')')).trim();
// Remove any quotes if necessary.
String quoteStr = "";
if (url.startsWith("'") || url.startsWith("\"")) {
quoteStr = String.valueOf(url.charAt(0));
url = url.substring(1, url.length() - 1);
}
// We now check if the url ends in a known image file extension
// If not, the url is ignored.
if (FileNameUtils.hasImageExtension(url)) {
return super.getUrlPath(match, originalPath, newCssPath);
} else {
// We need to rewrite the path, as any relative URLs will
// not resolve correctly if Jawr has changed the CSS path.
url = PathNormalizer.concatWebPath(originalPath, url);
url = PathNormalizer.getRelativeWebPath(PathNormalizer.getParentPath(newCssPath), url);
return "url(" + quoteStr + url + quoteStr + ")";
}
}
}
}
And then, you need to configure Jawr to use this custom post processor in jawr.properties:
jawr.custom.postprocessors.customcsspathrewriter.class=com.bullethq.jawr.postprocessor.CustomCssUrlPathRewriterPostProcessor
jawr.css.bundle.factory.filepostprocessors=customcsspathrewriter

Categories

Resources