I am working on a small project. I have a textarea and a button(Send). I am trying to compare the text of a textarea which already written last time. If I update this time it compares and find any change in textarea it will change the text of button(save changes)
Category: javascript
Category Added in a WPeMatico Campaign
Cursor and content doesn’t update when using Yjs et Sandpack
I’m using Yjs and Sandpack to build a simple Collaborative code editor.
I doesn’t receive any error on console and I see other people cursor but when I update content, nothing happen on the other side. the curosor doesn’t seems to update.
import * as Y from "yjs";
import { yCollab } from "y-codemirror.next";
import { WebrtcProvider } from "y-webrtc";
const ydoc = new Y.Doc();
const provider = new WebrtcProvider("codemirror6-demo-room", ydoc, {
signaling: ["ws://localhost:4444"]
});
const ytext = ydoc.getText("codemirror");
const undoManager = new Y.UndoManager(ytext);
export default function Code({ template, theme, language, roomId = "pipi" }: ICode) {
const codemirrorInstance = useRef(null);
useEffect(() => {
const cmInstance = codemirrorInstance.current?.getCodemirror();
if (!cmInstance) return;
const txt = cmInstance.state.update({
doc: ytext.toString()
});
cmInstance.update([txt]);
return () => {
provider.disconnect();
provider.destroy();
};
},[]);
return (
<SandpackProvider template={template} theme={theme}>
<SandpackLayout>
<SandpackFileExplorer />
<SandpackCodeEditor
ref={codemirrorInstance}
showTabs
showLineNumbers
showInlineErrors
wrapContent
closableTabs
extensions={[yCollab(ytext, provider.awareness, { undoManager })]}
/>
<SandpackPreview
showNavigator={true}
showRefreshButton={true}
showOpenInCodeSandbox={false}
showOpenNewtab={true}
showRestartButton={true}
/>
</SandpackLayout>
</SandpackProvider>
);
}
What could be causing react-three-drei elements to fail when rendering code online?
I hope you are well
so I just started with three.js and react-three-fiber and I’m doing pretty well when I work locally, the tutorials found on the internet are quite detailed I must say.
However, since the final goal is to be able to put a functional site online, I’m facing a big problem.
After several attempts I manage to put online and to render some elements with react-three-fiber. However when I import react-three-drei I can get some elements to work like useGLTF but others seem not to be recognized by the browser like “float” and even “orbitcontrols”
When I integrate these elements my program does not work anymore. Could someone help me?
I would like to be able to put what I do locally online from the CDN
Here is an example of what I am trying to do by giving you an outline of the code
Here is how I import react-three-drei from the browser
`import { useGLTF, Float, MeshReflectorMaterial } from ‘https://cdn.jsdelivr.net/npm/@react-three/[email protected]/+esm’
…
<mesh rotation-x={-Math.PI * .5} castShadow receiveShadow>
<planeGeometry args={[30, 30]} />
<MeshReflectorMaterial envMapIntensity={0} normalScale={[0.15, 0.15]} dithering={true} color={[0.015, 0.015, 0.015]} roughness={0.7} blur={[1000, 400]} />
`
I can render locally but online “MeshReflectorMaterial” is not recognized
How to fix ‘bodyParser’ is declared but its value is never read.ts(6133) error on Axios and Body-Parser?
I’m taking a course on web development and this is something I know nothing about. I started to write my js code just like on the lesson and I’ve done these steps before but as installing request I got an error with “request has been deprecated”. So I search about it and installed axios. After that, when I write the code on my js file, on axios and body parser shows this error “bodyParser’ is declared but its value is never read.ts(6133)”. I have no idea what could be.
This is the code:
const express = require("express");
const bodyParser = require("body-parser");
const axios = require("axios");
app.listen(3000,function(){
console.log("Server is runing on port 3000");
});
when I try the load the server it shows
“Usage: nodemon [nodemon options] [script.js] [args]
See “nodemon –help” for more.”
Populating a data set with retrieved values from a separate API in Redux
So I want to know what the best practice is in redux for taking the information retrieved from one API and applying it as new key value pair to a hardcoded array of objects.
Effectively what I ultimately want to achieve is to create multiple filter fields but the data required from the hardcoded array doesn’t already come with these two filtering metrics.
So to expand I have an array of sporting venues with a field for location. Based on this location I want to know the current temperature and weather condition as provided from the weatherAPI. I already have the slice set up for the weatherAPI and wanted to know if I should setup another slice for the stadium array and populate it with the necessary data from the weatherSlice in the stadiumSlice or should i commit all this logic within the filter components?
Set up a slice for the stadium array which is initialised by spread syntax of the stadiums array and setting the new additional parameters to null. just a bit lost on where to take it from there or at what point I combine it with the weatherSlice
How can I navigate to specific div with an ID in React
I have a React Application with multiple routes. What I want to do is travel to a div with a specific ID inside one of these routes from another one. Just like you would do in HTML with href="#id".Is there any related topic that you can please link for me to see? Or have you got any idea on how to solve this? Thank you.
How can I add columns to a feature collection in Google Earth Engine?
I am trying to calculate the average nighttime radiance of forested areas in South Asia and Southeast Asia, broken up by country and year, then export the results as a single table where each row is a different country and each column is a different year. I have a program that will make a separate feature collection for each year, but I need some way to combine them all together as different columns of one table.
var asia = ["Sri Lanka","Bangladesh","India","Afghanistan",
"Pakistan","Bhutan","Nepal","Cambodia","Indonesia", "Burma",
"Laos","Malaysia","Philippines","Singapore","Thailand","Vietnam"];
var countries = ee.FeatureCollection("USDOS/LSIB/2017");
var asiafeatures = asia.map(function(element){ // feature collection of country names
return ee.Feature(null, {'country': element});
})
// initialize table
var table = ee.FeatureCollection(asiafeatures);
var years = ee.List.sequence(2014, 2021); // list of numbers 2014 to 2021
var fields = years.map(function (number) {
return ee.String(number).slice(0, 4); // count only pixels with values of 0, 1, 2, or 3
})
var size = years.length()
var covers = ee.ImageCollection.fromImages( // assemble an image collection from images
years.map(function (y) { // for each year
return ee.ImageCollection("MODIS/061/MCD12Q1") // from the modis land cover image
.select('LC_Type1') // select this field
.filter(ee.Filter.calendarRange(y, y, 'year')) // filter it by the desired timespan
.median() // find the median
.set('year',y); // and set the value of the year field?
}).flatten()); // flatten the MODIS collection to 1 image
var rads = ee.ImageCollection.fromImages( // assemble an image collection from images
years.map(function (y) { // for each year
return ee.ImageCollection("NOAA/VIIRS/DNB/MONTHLY_V1/VCMSLCFG") // from the nightlight image
.select('avg_rad') // select this field
.filter(ee.Filter.calendarRange(y, y, 'year')) // filter by the desired timespan
.median() // find the median
.set('year',y);
}).flatten());
var coverslist = covers.toList(size); // turn the land cover image collection into a list of images, 1 per year
var radslist = rads.toList(size); // turn the nightlights image into a list of images, 1 per year
var sequence = ee.List.sequence(0, ee.Number(size).subtract(1)); // list of numbers from 0 to 7
var stats = sequence.map(function(seq){ // for each number in the sequence (each year)
return ee.FeatureCollection(asia.map(function(c){ // for each country in asia
var country = countries.filter(ee.Filter.eq('COUNTRY_NA', c)); // one country at a time
// country is a feature collection with 1 feature
var coverclipped = ee.Image(coverslist.get(seq)).clip(country); // grab an image from the list, serve it, clip
// you can't print this one because it's server-side, but it's an image
var coverclippedmasked = coverclipped.updateMask(coverclipped.lte(6)); // clip it to forest areas?
// still an image, still server-side
var binarymask = coverclippedmasked.selfMask().mask().clip(country).toInt(); // simplify to forest and not?
// yep
var vectors = binarymask.reduceToVectors({ // turn the mask into a polygon
geometry: country, // separated by country?
scale: 500,
maxPixels: 1e18
});
// vectors is a feature collection
var forestRadianceMed = ee.Image(radslist.get(seq)).reduceRegions({ // reduce the clipped nightlights by region
collection: vectors.filter(ee.Filter.eq('label', 1)), // forested polygons only
reducer: ee.Reducer.median(),
scale: 500
});
// forestRadianceMed is a feature collection
return ee.Feature(null, {}).set(ee.String(fields.get(seq)), forestRadianceMed.aggregate_mean('median'))
// this is a feature
}));
});
// this iterates through the list of computed objects and exports each collection individually
for(var i = 0; i < size.getInfo(); i++) {
Export.table.toDrive({
collection: stats.get(i),
description: years.get(i).getInfo() + '_forestRadianceMed',
selectors: [years.get(i).getInfo()]
})
}
// Well, it does the calculations, but they're still not all in one table.
CALL_EXCEPTION when calling contract
I have a very big smart contract, and i deployed it to mainnet (ethereum mainnet). I encountered some problem with gas but i managed to solve them. I tried to execute one of the function in the contract but got this error:
Error: transaction failed [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ]
Full Contract:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "hardhat/console.sol";
contract Arbitrage is DyDxFlashLoan {
IUniswapV2Router02 public immutable uRouter;
IUniswapV2Router02 public immutable sRouter;
address public owner;
constructor(address _uRouter, address _sRouter) {
uRouter = IUniswapV2Router02(_uRouter);
sRouter = IUniswapV2Router02(_sRouter);
owner = msg.sender;
}
function executeTrade(
address _tokenA,
address _tokenB,
uint256 _flashAmount,
bool _startOnUniswap
) external {
console.log("Balance before", IERC20(_tokenA).balanceOf(address(this)));
uint balanceBefore = IERC20(_tokenA).balanceOf(address(this));
bytes memory data = abi.encode(
_startOnUniswap,
_tokenA,
_tokenB,
_flashAmount,
balanceBefore
);
flashloan(_tokenA, _flashAmount, data);
}
function callFunction(
address,
Info calldata,
bytes calldata data
) external onlyPool {
(
bool _startOnUniswap,
address _tokenA,
address _tokenB,
uint256 flashAmount,
uint256 balanceBefore
) = abi.decode(data, (bool, address, address, uint256, uint256));
console.log("Balance after:", IERC20(_tokenA).balanceOf(address(this)));
uint balanceAfter = IERC20(_tokenA).balanceOf(address(this));
require(
balanceAfter - balanceBefore == flashAmount,
"Didn't receive flash loan"
);
address[] memory tokens = new address[](2);
tokens[0] = _tokenA;
tokens[1] = _tokenB;
if (_startOnUniswap == true) {
swapOnUniswap(flashAmount, 0, tokens);
tokens[0] = _tokenB;
tokens[1] = _tokenA;
swapOnSushiswap(
IERC20(tokens[0]).balanceOf(address(this)),
0,
tokens
);
} else {
// console.log("Ho 10 WETH e li swappo per x COMPOUND");
console.log(
"Balance of WETH before swap:",
IERC20(tokens[0]).balanceOf(address(this))
);
swapOnSushiswap(flashAmount, 0, tokens);
tokens[0] = _tokenB;
tokens[1] = _tokenA;
// console.log("Ho x COMPOUND e li swappo per >10 WETH");
swapOnUniswap(
IERC20(tokens[0]).balanceOf(address(this)),
0,
tokens
);
console.log(
"Balance of WETH after swap:",
IERC20(tokens[1]).balanceOf(address(this))
);
}
}
function swapOnUniswap(
uint _amountIn,
uint _amountOut,
address[] memory _path
) internal {
require(
IERC20(_path[0]).approve(address(uRouter), _amountIn),
"Uniswap failed the approval"
);
uint[] memory amounts = uRouter.swapExactTokensForTokens(
_amountIn,
_amountOut,
_path,
address(this),
(block.timestamp + 1200)
);
console.log(
"UNISWAP: Input tokens (COMP):",
amounts[0],
"Output tokens (ETH):",
amounts[1]
);
}
function swapOnSushiswap(
uint _amountIn,
uint _amountOut,
address[] memory _path
) internal {
require(
IERC20(_path[0]).approve(address(sRouter), _amountIn),
"Sushiswap failed the approval"
);
uint[] memory amounts = sRouter.swapExactTokensForTokens(
_amountIn,
_amountOut,
_path,
address(this),
(block.timestamp + 1200)
);
console.log(
"SUSHISWAP: Input tokens (ETH):",
amounts[0],
"Output tokens (COMP):",
amounts[1]
);
}
function withdraw(address _tokenAddress) external {
console.log("Owner balance:", IERC20(_tokenAddress).balanceOf(owner));
require(owner == msg.sender, "Only owner can withdraw");
ERC20(_tokenAddress).transfer(
owner,
IERC20(_tokenAddress).balanceOf(address(this))
);
console.log("Owner balance", IERC20(_tokenAddress).balanceOf(owner));
}
}
The code that executes the transaction:
const address = new ethers.Wallet(process.env.PRIVATE_KEY, mainnetProvider);
if (process.env.IS_DEPLOYED === true) {
const options = {
gasLimit: 2500000,
maxFeePerGas: 40000000000,
};
const trade = await arbitrageContract
.connect(address)
.executeTrade(
process.env.TOKEN_WETH_MAINNET,
process.env.TOKEN_COMPOUND_MAINNET,
ethers.BigNumber.from("10000000000000000000"),
startOnUniswap,
options
);
receipt = await trade.wait();
console.log("sending eth to contract...");
const withdraw = await arbitrageContract
.connect(address)
.withdraw(process.env.TOKEN_WETH_MAINNET);
await withdraw.wait();
console.log("sent eth to owner successfully");
} else {
console.log("CURRENTLY ON TEST MODE");
}
i clicked the link that brought me to the ethers.js documentation (Because I’m using ethersJS) and i checked everything that the documentation says about this error:
-
The code exists on chain (ethereum mainnet) but its not verified (address: 0x7221a612Fc346fa218F9f64B4B4283782F639ea0)
-
I’m accessing the right code
-
The code doesn’t reverts during a require statement
-
I’m not using the wrong ABI
I’m very confused why the error is showing up and if somebody had any suggestion that would be very useful.
How can i do a filter for an image in vanilla JavaScript canvas?
I’m working inside a canvas and I want to make a color filter for an image, so when I “apply” this filter, the image’s color blends with the filter color. I also need it to be in vanilla JS.
I’ve been looking around and found a JQuery plugin, but I need this in vanilla JS (assignment for the college).
Is there any way I can do this, only for a single call of context.drawImage(), so it only affects the element that i want to use the filter on?
Adding more Angular standalone components to the default Stackblitz App component?
I created a second standalone AppNavComponent component on Stackblitz.
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
@Component({
standalone: true,
selector: 'app-nav',
imports: [CommonModule, RouterOutlet],
template: `<router-outlet>`,
})
export class AppNavComponent {
name = 'Angular';
}
It’s imported it the main one like this:
@Component({
selector: 'my-app',
standalone: true,
imports: [CommonModule, AppNavComponent],
template: `
<h1>Hello from {{name}}!</h1>
<a target="_blank" href="https://angular.io/start">
Learn more about Angular
</a>
`,
})
And it produces the error:
Cannot find module 'app-nav.component' or its corresponding type declarations.
Thoughts?
React Script Tag not working for Amazon Native Search Ads
I’m attempting to integrate Amazon native search ads into my React-based website. The website features dynamically changing product types, such as sailing books, sailing jackets, and swimming shorts. My goal is to display a few products from Amazon for each product type by implementing Amazon native search ads. Amazon provides two script tags for this purpose, but despite my efforts, I haven’t been able to successfully render them on my application.
Although the script tags work fine when directly added to the index.html file (or on a sandbox environment), I’m encountering difficulties in getting the script tag to function properly within a React element. I’m seeking suggestions or solutions from anyone who might have encountered a similar issue or has any insights on how to resolve it.
Additionally, I’ve explored the option of using the product advertising API 5.0. However, it imposes a limit of one product request per second, which is not suitable for my requirements as I need to fetch products for 20 different types simultaneously.
Below are my script tags:
<script type="text/javascript">
amzn_assoc_placement = "adunit0";
amzn_assoc_search_bar = "false";
amzn_assoc_tracking_id = "noid";
amzn_assoc_ad_mode = "search";
amzn_assoc_ad_type = "smart";
amzn_assoc_marketplace = "amazon";
amzn_assoc_region = "US";
amzn_assoc_title = "Sailing Books";
amzn_assoc_default_search_phrase = "sailing books";
amzn_assoc_default_category = "All";
amzn_assoc_linkid = "2e96d3d63ba4fe9f01c60204e5abe75e";
amzn_assoc_search_bar_position = "bottom";
</script>
<script src="//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US"></script>
I tried Helmet and dangerously set inner HTML but couldn’t make it work.
Why is my AJAX loading not updating data in real-time on button click? [closed]
AJAX LOADING
Hello guys
I’m trying to create real time updating of data for my website.
The website uses buttons clicked to determine where to get it’s data from.
I expected the code to update on real time once i started clicking buttons but that wasn’t what happened.
I’ve dropped some pictures of some of the HTML and the Javascript. [enter image description here](https://i.stack.imgur.com/PLCeC.png)
I tried using jquery to make it easier instead of xmlHttpRequest but this time it didn’t give any output or even any errors on either the console or the section I expected the data to be updated.
I was expecting to have the data updated in real time.
When `instanceof` is acting up
I recently filed an issue on GitHub but the project doesn’t seem to be very active so I am unsure if it will reach many fellow developers.
Here is the link to the issue: https://github.com/Urigo/graphql-modules/issues/2337.
TL;DR
I am currently working on a GraphQL API written in TypeScript and using the graphql-modules library calling instanceof within one of its functions.
Here is the code of the said function (altered to add some logging):
function isScalarResolver(obj) {
console.log('obj:', obj, 'nisScalarResolver(obj):', obj instanceof GraphQLScalarType, 'n');
return obj instanceof GraphQLScalarType;
}
After running pnpm run test, here is the output displayed in the terminal:
obj: { now: [Function: now] }
isScalarResolver(obj): false
obj: GraphQLScalarType {
name: 'DateTime',
description: 'DateTime scalar type',
specifiedByURL: undefined,
serialize: [Function: serialize],
parseValue: [Function: parseValue],
parseLiteral: [Function: parseLiteral],
extensions: [Object: null prototype] {},
astNode: undefined,
extensionASTNodes: []
}
isScalarResolver(obj): false
It does appear to me that obj is an instance of GraphQLScalarType so obj instanceof GraphQLScalarType should return true (which is actually the case when running pnpm run dev).
For those who would want to look into the issue, there is a reproduction on StackBlitz: https://stackblitz.com/github/devatina11yb/graphql-modules. Reproduction instructions are available in the GitHub issue previously mentioned.
Javascript date/time sequence conversion
I’m dealing with a set of time data that is an array of durations.
For instance:
00:00:51
00:10:00
00:18:50
24:00:00
00:16:11
24:00:00
00:00:51
00:00:01
00:18:50
00:10:01
The sum of these tells me the entire process execution time. Now, my javascript isn’t that strong. But as I understand it, javascript doesn’t deal with time, just date and time.
So, I’ve sent this data from the backend through to the browser, and converted it a full date/time object in a series of durations:
Thu Jan 01 1970 00:00:00 GMT-0500 (Eastern Standard Time)
Thu Jan 01 1970 00:00:51 GMT-0500 (Eastern Standard Time)
Thu Jan 01 1970 00:10:51 GMT-0500 (Eastern Standard Time)
Thu Jan 01 1970 00:29:41 GMT-0500 (Eastern Standard Time)
Fri Jan 02 1970 00:29:41 GMT-0500 (Eastern Standard Time)
Fri Jan 02 1970 00:45:52 GMT-0500 (Eastern Standard Time)
Sat Jan 03 1970 00:45:52 GMT-0500 (Eastern Standard Time)
Sat Jan 03 1970 00:46:43 GMT-0500 (Eastern Standard Time)
Sat Jan 03 1970 00:46:44 GMT-0500 (Eastern Standard Time)
Sat Jan 03 1970 01:05:34 GMT-0500 (Eastern Standard Time)
Sat Jan 03 1970 01:15:35 GMT-0500 (Eastern Standard Time)
Now, ideally for graphing purposes, I want to display this as a sequential time series, like so:
I am really unsure of how to accomplish this. I’ve done some reading and searching but I am not even sure what to call this type of time series.
Any help is appreciated.
Set Iframe src with string html variable Javascript
I have a function that receives a parameter html string query, I would like to set this parameter as source of the Iframe something like this src : @Html.Raw(result) to then display on the view. Is there a way to do it?
View
<div id="DisplayHTML"></div>
Function
function GetValues(result) {
$("#DisplayHTML").html(
$('<iframe>', {
src:// Here is where I would like to add the result parameter,
width: '600px',
height: "800px"
})
);
}
