Attempting to a configurable attribute of a configurable property Issue-in turfJS? - javascript

I have an issue with #turf/turf the last version, in my react native app
"react-native": "0.58.0",
"#turf/turf": "^5.1.6"
I just followed the same example in the README.md but it's not working with me anymore.
The issue is when I import turf like this
import * as turf from '#turf/turf';
and write the function here is
handleNearby = () => {
const { region, providers } = this.state;
let currentPoint = [region.longitude, region.latitude]
let points = _.map(providers, p => {
console.log('#p', p);
const to = [p.coordinates.longitude, p.coordinates.latitude];
const distance = turf.distance(currentPoint, to, { units: 'kilometers' });
return { coords: p.coordinates, name: p.username, id: p.id, distance }
});
const sortPoints = _.sortBy(points, ['distance']);
this.setState({ sortedMarkers: sortPoints });
console.log('##points', sortPoints);
return;
}
and run the app I have this error
attempting to a configurable attribute of a configurable property
But when I run the debugger on the browser the app works well I don't know why! any help?

Related

I get the error "Unrecognized extension value in extension set ([object Object])." setting highlighting language using #codemirror/lang-javascript?

I'm trying to set a highlighting language for JavaScript in CodeMirror by importing #codemirror/lang-javascript and adding it to the extensions array, but I keep getting the error "Uncaught (in promise) Error: Unrecognized extension value in extension set ([object Object])."
I realize there is a question with a similar title here but I think the cause and solution is a different one, hence, a different question.
Here is the code that is causing the error: (Code is inspired by the docs)
CodeMirror(
`console.log('hello');
1+2`,
{
extensions: [myDefaultTheme,/*javascript() //error*/]
}
);
So because I really want to make this problem reproducible, this is a snippet that works, that can be used to reproduce the problem. This is the working code. I just want to enable syntax highlighting.
CODEMIRROR_VERSION = "^6.0.1";
esmImport = pkg => import(`https://cdn.skypack.dev/${pkg}`);
esmCodeMirror = (mod) =>
esmImport(
"#codemirror/" +
(mod.indexOf("#") >= 0 ?
mod : `${mod}#${CODEMIRROR_VERSION}`)
);
loadCodeMirrorModules = async entries => {
const repo = Object.create(null)
const loadToRepo = async key => {
const module = await esmCodeMirror(key)
repo[key] = module
}
await Promise.all(entries.map(loadToRepo))
return repo
}
loadCodeMirrorModules([
"view",
"state",
"language",
"commands",
"search",
"autocomplete",
"lang-javascript"
]).then(async cmImports => {
let myDefaultTheme = cmImports.view.EditorView.theme({
'&': {
fontFamily: 'Consolas, "Roboto Mono", monospace',
fontSize: '14px',
height: '200px',
border: '1px solid #ddd',
},
})
let CodeMirror = async (doc = "", config = {}) => {
const extensions = config.extensions ?? [];
const keymaps = config.keymaps ?? [];
const {
highlightSpecialChars,
keymap,
drawSelection,
highlightActiveLine
} =
cmImports.view;
const {
Prec
} = cmImports.state;
let state = cmImports.state.EditorState.create({
doc,
extensions: [
cmImports.view.lineNumbers(),
highlightSpecialChars(),
drawSelection(),
highlightActiveLine(),
keymap.of([
...cmImports.commands.defaultKeymap,
...cmImports.search.searchKeymap,
...keymaps
]),
...extensions
]
});
const view = new cmImports.view.EditorView({
state
});
const el = view.dom;
el.value = view.state.doc.toString();
return el;
};
let javascript = cmImports['lang-javascript'].javascript;
let d = await CodeMirror(
`console.log('hello');
1+2`, {
extensions: [myDefaultTheme]
}
);
document.body.insertBefore(d, document.body.firstChild);
})
Is there something I'm missing or doing wrong in my implementation? Any help would be greatly appreciated.

How to call a composition function from another composition in VueJS

I've been experimenting with the new composition-api in VueJS and am not sure how to solve a problem. I'm looking for some advice on how to properly implement a solution. This wasn't a problem when everything was vuex-based since you can dispatch an action to another module without a problem. However, I'm struggling to find a solution for the composition implementation.
Problem:
Component calls a CompositionA's function.
CompositionA triggers a login function.
On CompositionA's login success/failure response I would like to call a CompositionB function. (CompositionB contains data and logic for showing a snackbar that's used across the site)
The problem is that it is necessary to inject the snackbar dependency in every component rather than have it be instantiated/mounted from CompositionA. Current solution is to this effect:
Component.vue:
// template calls login(credentials) method
import { useCompositionA } from '#/compositions/compositionA'
import { useCompositionB } from '#/compositions/compositionB'
export default {
name: 'Component',
setup(props, context) {
const { login } = useCompositionA(props, context, useCompositionB(props, context))
return {
login
}
},
}
compositionA.js:
export const useAuth = (props, context, snack) => {
const login = async (credentials) => {
try {
return await loginWithEmailPassword(credentials)
snack.show({text: 'Welcome back!'})
} catch (err) {
snack.show({text: 'Failed to login'})
}
}
return { login }
}
compositionB.js:
export const useSnack = (props, context) => {
const snack = reactive({
color: 'success',
text: null,
timeout: 6000,
visible: true,
})
const snackRefs = toRefs(snack)
const show = ({ text, timeout, color }) => {
snackRefs.text.value = text
snackRefs.timeout.value = timeout || 6000
snackRefs.color.value = color || 'success'
snackRefs.visible.value = true
}
return {
...snackRefs,
show
}
}
Would be nice if something like below existed, but I'm finding that the properties aren't reactive in CompositionB if it's used from CompositionA (method gets called but snackbar doesn't show up). My understanding is that Vue isn't injecting CompositionB into the Component, so I'm just running another instance of CompositionB inside CompositionA. What am I doing something wrong? What's the proper solution here?
compositionA.js (not working):
import { useCompositionB } from '#/compositions/compositionB'
export const useAuth = (props, context) => {
const login = async (credentials) => {
const { show } = useCompositionB()
try {
return await loginWithEmailPassword(credentials)
show({text: 'Welcome back!'})
} catch (err) {
show({text: 'Failed to login'})
}
}
return { login }
}
Thanks in advance,
As expected it was due to the Component referencing its own local copy of CompositionB*. Solution is actually to bring the state of your compositions into the global scope according to:
https://vueschool.io/articles/vuejs-tutorials/state-management-with-composition-api/
Something like this:
compositionB.js:
const snack = reactive({
color: 'success',
text: null,
timeout: 6000,
visible: true,
})
export const useSnack = (props, context) => {
const snackRefs = toRefs(snack)
const show = ({ text, timeout, color }) => {
snackRefs.text.value = text
snackRefs.timeout.value = timeout || 6000
snackRefs.color.value = color || 'success'
snackRefs.visible.value = true
}
return {
...snackRefs,
show
}
}
Works like a charm.
Only caveat I found initially was a composition-api error:
Uncaught Error: [vue-composition-api] must call Vue.use(plugin) before using any function.
This was easily solved by mounting the composition-api first thing in main.js as per solution here:
Uncaught Error: [vue-composition-api] must call Vue.use(plugin) before using any function
I think this won't be a problem with vue3 comes out. Hope this helps someone.

How to write JavaScript code that allows for defaults to be overrided

I would like to use this text-highlighting library in my Vue project. Here's an example from their website of how it can be used:
import TextHighlighter from '#perlego/text-highlighter';
import { isDuplicate } from './utils';
import highlightsApi from './services/highlights-api';
class ArticleView {
constructor(data) {
this.data = data;
const pageElement = document.getElementById("article");
this.highlighter = new TextHighlighter(
pageElement,
{
version: "independencia",
onBeforeHighlight: this.onBeforeHighlight,
onAfterHighlight: this.onAfterHighlight,
preprocessDescriptors: this.preprocessDescriptors,
onRemoveHighlight: this.onRemoveHighlight
});
}
onBeforeHighlight = (range) => {
return !isDuplicate(range)
}
onRemoveHighlight = (highlightElement) => {
const proceed = window.confirm("Are you sure you want to remove this highlight?");
return proceed;
}
preprocessDescriptors = (range, descriptors, timestamp) => {
// Add an ID to the class list to identify each highlight
// (A highlight can be represented by a group of elements in the DOM).
const uniqueId = `hlt-${Math.random()
.toString(36)
.substring(2, 15) +
Math.random()
.toString(36)
.substring(2, 15)}`;
const descriptorsWithIds = descriptors.map(descriptor => {
const [wrapper, ...rest] = descriptor;
return [
wrapper.replace(
'class="highlighted"',
`class="highlighted ${uniqueId}"`
),
...rest
];
});
return { descriptors: descriptorsWithIds, meta: { id: uniqueId } };
}
onAfterHighlight = (range, descriptors, timestamp, meta) => {
highlightsApi.saveBatch(meta.id, descriptorsWithIds)
.then((result) => {
// Do something with the highlights that have been saved.
})
.catch((err) => console.error(err));
}
render = () => {
// Code that takes the data for the article and adds it to the DOM
// based on a html template here.
}
}
Using the above example, I would like to setup the highlighter (similar to the above code, but in a different file, for example ./utils/highlighter.js) with all the default options I want (onBeforeHighlight, onRemoveHighlight, etc.), and then be able to import it from there and override the options for which I don't want to use the defaults, so it looks something like this in the importing file:
import highlighter from "../utils/highlighter.js";
const overridingOptions = {
onAfterHighlight: (range, descriptors, timestamp, meta) => {
console.log(range, descriptors, timestamp, meta);
}
};
const target = document.getElementsByClassName("testme")[0];
highlighter(target, overridingOptions);
For some reason, I am not able to understand how to modify the ArticleView example to fit my needs, so I think I need to see this done once. How should the code in ./utils/highlighter.js look to make this possible?

VTK.js VR not display/showing an hand controller in Room

I try to use VTK VR, but When I test it, I cant see controller in room, I can get action from controller like press or somthing, but without its seen for user in VR mode, how I can fix it?
Online Demo From Here.
import 'vtk.js/Sources/favicon';
import vtkActor from 'vtk.js/Sources/Rendering/Core/Actor';
import vtkCalculator from 'vtk.js/Sources/Filters/General/Calculator';
import vtkConeSource from 'vtk.js/Sources/Filters/Sources/ConeSource';
import vtkFullScreenRenderWindow from 'vtk.js/Sources/Rendering/Misc/FullScreenRenderWindow';
import vtkMapper from 'vtk.js/Sources/Rendering/Core/Mapper';
import { AttributeTypes } from 'vtk.js/Sources/Common/DataModel/DataSetAttributes/Constants';
import { FieldDataTypes } from 'vtk.js/Sources/Common/DataModel/DataSet/Constants';
import controlPanel from './controller.html';
// ----------------------------------------------------------------------------
// Standard rendering code setup
// ----------------------------------------------------------------------------
const fullScreenRenderer = vtkFullScreenRenderWindow.newInstance({
background: [0, 0, 0],
});
const renderer = fullScreenRenderer.getRenderer();
const renderWindow = fullScreenRenderer.getRenderWindow();
// ----------------------------------------------------------------------------
// Example code
// ----------------------------------------------------------------------------
// create a filter on the fly, sort of cool, this is a random scalars
// filter we create inline, for a simple cone you would not need
// this
// ----------------------------------------------------------------------------
const coneSource = vtkConeSource.newInstance({ height: 100.0, radius: 50.0 });
// const coneSource = vtkConeSource.newInstance({ height: 1.0, radius: 0.5 });
const filter = vtkCalculator.newInstance();
filter.setInputConnection(coneSource.getOutputPort());
// filter.setFormulaSimple(FieldDataTypes.CELL, [], 'random', () => Math.random());
filter.setFormula({
getArrays: (inputDataSets) => ({
input: [],
output: [
{
location: FieldDataTypes.CELL,
name: 'Random',
dataType: 'Float32Array',
attribute: AttributeTypes.SCALARS,
},
],
}),
evaluate: (arraysIn, arraysOut) => {
const [scalars] = arraysOut.map((d) => d.getData());
for (let i = 0; i < scalars.length; i++) {
scalars[i] = Math.random();
}
},
});
const mapper = vtkMapper.newInstance();
mapper.setInputConnection(filter.getOutputPort());
const actor = vtkActor.newInstance();
actor.setMapper(mapper);
actor.setPosition(20.0, 0.0, 0.0);
renderer.addActor(actor);
renderer.resetCamera();
renderWindow.render();
// -----------------------------------------------------------
// UI control handling
// -----------------------------------------------------------
fullScreenRenderer.addController(controlPanel);
const representationSelector = document.querySelector('.representations');
const resolutionChange = document.querySelector('.resolution');
const vrbutton = document.querySelector('.vrbutton');
representationSelector.addEventListener('change', (e) => {
const newRepValue = Number(e.target.value);
actor.getProperty().setRepresentation(newRepValue);
renderWindow.render();
});
resolutionChange.addEventListener('input', (e) => {
const resolution = Number(e.target.value);
coneSource.setResolution(resolution);
renderWindow.render();
});
vrbutton.addEventListener('click', (e) => {
if (vrbutton.textContent === 'Send To VR') {
fullScreenRenderer.getOpenGLRenderWindow().startVR();
vrbutton.textContent = 'Return From VR';
} else {
fullScreenRenderer.getOpenGLRenderWindow().stopVR();
vrbutton.textContent = 'Send To VR';
}
});
// -----------------------------------------------------------
// Make some variables global so that you can inspect and
// modify objects in your browser's developer console:
// -----------------------------------------------------------
global.source = coneSource;
global.mapper = mapper;
global.actor = actor;
global.renderer = renderer;
global.renderWindow = renderWindow;
Note: Tested on Latest Version of Chrome & Firefox (64 bit). Controller Type is HTC Vive.
Update 1:
We found this option not development, so that I share updated link now Github Link

React JS Google Maps Distance Matrix Error: Uncaught TypeError: locations.join is not a function at formatLocations (index.js:45)

I'm not sure if this is a bug so I'm going to ask for advice first since I'm very new to ReactJS
I'm trying to implement Google Distance Matrix to get the distance.
(If there are any pre-built reactjs alternative solution, please let me know)
My Code:
import React, {Component} from 'react';
import GoogleMap from 'google-distance-matrix';
//...
class View extends Component {
state = {
//...
address:'',
dest: '',
distanceText:'',
openModal: false,
foundDistance: false,
distanceText: "",
address: "New York NY",
dest: "Montreal"
};
constructor (props){
super(props)
this.searchUpdated = this.searchUpdated.bind(this);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
}
handleFormSubmit = (event) => {
const component = this
// const { address, dest } = this.state
let address = "Toronto, ON, CA"
let dest = "Vancouver, ON, CA"
let origins = ['San Francisco CA', '40.7421,-73.9914'];
let destinations = ['New York NY', 'Montreal', '41.8337329,-87.7321554',
'Honolulu'];
event.preventDefault()
// console.log(event)
GoogleMap.matrix(address, dest, function (err, distances) {
distance.key('AIzaSyCFKLGuYz6ffYby7U-ODjFtV5TO4nDyevE');
distance.units('imperial');
console.log("address");
console.log(dest);
console.log(err);
console.log(distances);
if (err) {
return console.log(err);
}
if(!distances) {
return console.log('no distances');
}
if (distances.status == 'OK') {
if(distances.rows[0].elements[0]) {
var distance = distances.rows[0].elements[0].duration['text'];
console.log(distance);
component.setState({
foundDistance: true,
distanceText: distance
});
}
}
}).bind(this);
}
componentWillMount() {
//...
}
componentDidMount () {
// ...
}
render() {
//...
return (
<div>
<button onClick={this.handleFormSubmit}>Hello </button>
</div>
)
}
}
export default View;
I literally just want to console.log() the distance between two locations but I'm unable to do so... Right now, it's giving me this error:
Uncaught TypeError: locations.join is not a function
at formatLocations (index.js:45)
What the error gives me:
The error is emanating from your handleFormSubmit function when you call GoogleMap.matrix, it should look like this:
handleFormSubmit = (event) => {
const component = this
// const { address, dest } = this.state
let address = ["Toronto, ON, CA"];
let dest = ["Vancouver, ON, CA"];
event.preventDefault()
// console.log(event)
GoogleMap.matrix(address, dest, function (err, distances) {
Notice the brackets for Toronto and Vancouver; the package expects those two arguments to be arrays, not strings

Categories