Category: javascript
Category Added in a WPeMatico Campaign
javascript zigzag problem hacker rank solution showing wrong , though answer is right
i am doing zigzag problem of hacker rank day 3, even though my output is the same as the expected output, still it is showing an error
function processData(input) {
//Enter your code here
var lines = input.split(/[nr]+/);
let arr= lines[2].split(" ");
let sorted = arr.sort((a, b) => a - b);
let mid = sorted[sorted.length - 1];
let k = (arr.length + 1) / 2;
let midl = [];
let midh = [];
arr.forEach((num) => {
if (midl.length < k - 1) {
if (num < mid) {
midl.push(num);
}
} else if (midh.length < k - 1) {
if (num < mid) {
midh.unshift(num);
}
}
});
let midd = [mid];
let res = [...midl, ...midd, ...midh];
let resStr = res.toString();
let result = resStr.replace(/,/g, " ");
console.log(result);
}
i also tried other methods of console log, like mapping over the array, adding a string and then doing a console.log, but it did not work
kindly let me know where i am going wrong
Debug react-project
type here
Hi! folks as I’m a new learner of react and after learning all basics concepts i decided to practice the new concepts inside a project using react-redux, react-router and the idea of project is to display to the nurses there round inside a hospital in the week-end days and other normal days so in the NursesTour component i retrieve nurses data from nursesSlice and i check the current day if is a saturday, sunday or a normal day and in every check i mad a new list of sorted nurses by there days of round and the problem is i got the same names of nurses, and i will take a snapshot code of NursesTour component
import { useDispatch, useSelector } from "react-redux";
import { useEffect, useState } from "react";
import {
updateSaturdayRound,
updateSundayRound,
updateNormalRound,
} from "./nursesSlice";
const NursesTour = (props) => {
const nurses = useSelector((state) => state.nurses.nurses);
const dispatch = useDispatch();
const [cutSundayNurse, setCutSundayNurse] = useState({});
const [cutSaturdayNurse, setCutSaturdayNurse] = useState({});
const [cutNormalNurse, setCutNormalNurse] = useState({});
const { day, date } = props;
const isWeekend = day === "Saturday" || day === "Sunday";
const isSaturday = day === "Saturday";
const isSunday = day === "Sunday";
useEffect(() => {
if (isWeekend) {
if (isSaturday) {
const sortedNursesBySaturday = [...nurses].sort(
(a, b) =>
new Date(a["saturdayRoundDate"]) - new Date(b["saturdayRoundDate"])
);
setCutSaturdayNurse(sortedNursesBySaturday[0]);
} else if (isSunday) {
const sortedNursesBySunday = [...nurses].sort(
(a, b) =>
new Date(a["sundayRoundDate"]) - new Date(b["sundayRoundDate"])
);
// console.log(sortedNursesBySunday);
setCutSundayNurse(sortedNursesBySunday[0]);
}
} else {
const sortedNursesByNormal = [...nurses].sort(
(a, b) =>
new Date(a["normalRoundDate"]) - new Date(b["normalRoundDate"])
);
setCutNormalNurse(sortedNursesByNormal[0]);
}
}, [isWeekend, isSaturday, isSunday, nurses]);
useEffect(() => {
if (isWeekend) {
if (isSaturday) {
dispatch(updateSaturdayRound({ nurseId: cutSaturdayNurse.Mle, date }));
} else if (isSunday) {
dispatch(updateSundayRound({ nurseId: cutSundayNurse.Mle, date }));
}
} else {
dispatch(updateNormalRound({ nurseId: cutNormalNurse.Mle, date }));
}
}, [
dispatch,
isSaturday,
isSunday,
isWeekend,
cutNormalNurse.Mle,
cutSaturdayNurse.Mle,
cutSundayNurse.Mle,
date,
]);
// console.log(cutNormalNurse, cutSaturdayNurse, cutSundayNurse);
let content;
if (isWeekend) {
if (isSaturday) {
content = (
<tr>
<td>
<strong>{day}</strong>
</td>
<td>{cutSaturdayNurse.fullName}</td>
<td>{cutSaturdayNurse.rank}</td>
<td>{cutSaturdayNurse.Mle}</td>
</tr>
);
} else if (isSunday) {
content = (
<tr>
<td>
<strong>{day}</strong>
</td>
<td>{cutSundayNurse.fullName}</td>
<td>{cutSundayNurse.rank}</td>
<td>{cutSundayNurse.Mle}</td>
</tr>
);
}
} else {
content = (
<tr>
<td>{day}</td>
<td>{cutNormalNurse.fullName}</td>
<td>{cutNormalNurse.rank}</td>
<td>{cutNormalNurse.Mle}</td>
</tr>
);
}
return content;
};
export default NursesTour;
NursesTour sub component
import { getNextDate, getNextDays } from "../helpers/helper";
import NursesTour from "../features/nurses-garde/NursesTour";
const NursesGarde = () => {
console.log("nurses garde component");
const days = getNextDays(13);
const nextDate = getNextDate(13);
return (
<div className="table">
<h2>the following table show nurses round of garde</h2>
<table>
<thead>
<tr>
<th>Day</th>
<th>Full Name</th>
<th>Rank</th>
<th>MLE</th>
</tr>
</thead>
<tbody>
{days.map((day, i) => (
<NursesTour index={i} day={day} key={i} date={nextDate[i]} />
))}
</tbody>
</table>
</div>
);
};
export default NursesGarde;
parent component of Nurses tour
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
nurses: [
{
fullName: "Mourad Mhani",
rank: "SM",
Mle: "9200/15",
normalRoundDate: "12/04/2023",
saturdayRoundDate: "10/07/2023",
sundayRoundDate: "10/08/2023",
status: "idle",
},
{
fullName: "Said ghanouch",
rank: "SM",
Mle: "9102/15",
normalRoundDate: "12/05/2023",
saturdayRoundDate: "11/25/2023",
sundayRoundDate: "11/26/2023",
status: "idle",
},
{
fullName: "Mohammed Gharghari",
rank: "SM1",
Mle: "1301/12",
normalRoundDate: "12/06/2023",
saturdayRoundDate: "09/30/2023",
sundayRoundDate: "10/1/2023",
status: "idle",
},
{
fullName: "Ayoub Ghizlani",
rank: "SM",
Mle: "1203/17",
normalRoundDate: "12/07/2023",
saturdayRoundDate: "07/11/2023",
sundayRoundDate: "07/12/2023",
status: "idle",
},
{
fullName: "Naoufel Kechach",
rank: "SM",
Mle: "1203/16",
normalRoundDate: "12/08/2023",
saturdayRoundDate: "11/04/2023",
sundayRoundDate: "11/05/2023",
status: "idle",
},
{
fullName: "Anas Cherif",
rank: "SM",
Mle: "1103/16",
normalRoundDate: "12/01/2023",
saturdayRoundDate: "10/28/2023",
sundayRoundDate: "10/29/2023",
status: "idle",
},
{
fullName: "Hamza Taysee",
rank: "SM",
Mle: "1153/16",
normalRoundDate: "11/30/2023",
saturdayRoundDate: "12/21/2023",
sundayRoundDate: "12/22/2023",
status: "idle",
},
{
fullName: "Anouar Ghaydouni",
rank: "SM",
Mle: "1303/02",
normalRoundDate: "11/29/2023",
saturdayRoundDate: "10/14/2023",
sundayRoundDate: "10/15/2023",
status: "idle",
},
],
};
const nursesSlice = createSlice({
name: "nurses",
initialState,
reducers: {
addNurse(state, action) {
state.nurses.push(action.payload);
},
deleteNurse(state, action) {
const namesToRemove = action.payload;
// const newItems = state.items.filter(item => !idsToRemove.includes(item.id));
state.nurses = state.nurses.filter(
(nurse) => !namesToRemove.includes(nurse.fullName)
);
},
updateSaturdayRound(state, action) {
const { nurseId, date } = action.payload;
// Find the index of the nurse to be updated
const nurseIndex = state.nurses.findIndex(
(nurse) => nurse.Mle === nurseId
);
if (nurseIndex === -1) {
console.log("Nurse not found");
return;
}
// Create a copy of the nurse to update
const updatedNurse = {
...state.nurses[nurseIndex],
saturdayRoundDate: date,
};
// Update the nurse in the array immutably
state.nurses = [
...state.nurses.slice(0, nurseIndex),
updatedNurse,
...state.nurses.slice(nurseIndex + 1),
];
},
updateSundayRound(state, action) {
console.log(action.payload);
const { nurseId, date } = action.payload;
// find index of the nurse to be updated
const nurseIndex = state.nurses.findIndex(
(nurse) => nurse.Mle === nurseId
);
if (nurseIndex === -1) {
console.log(`the nurse with ${nurseId} id couldn't found`);
return;
}
// create a copy of nurse to be updated
const updatedNurse = {
...state.nurses[nurseIndex],
sundayRoundDate: date,
};
state.nurses = [
...state.nurses.slice(0, nurseIndex),
updatedNurse,
...state.nurses.slice(nurseIndex + 1),
];
},
updateNormalRound(state, action) {
const { nurseId, date } = action.payload;
// find index of nurse to be updated
const nurseIndex = state.nurses.findIndex(
(nurse) => nurse.Mle === nurseId
);
if (nurseIndex === -1) {
console.log(`the nurse with ${nurseId} id couldn't found`);
return;
}
// create a copy of nurse to be updated
const updatedNurse = {
...state.nurses[nurseIndex],
normalRoundDate: date,
};
state.nurses = [
...state.nurses.slice(0, nurseIndex),
updatedNurse,
...state.nurses.slice(nurseIndex + 1),
];
},
sortNursesByNormalRound(state) {
state.nurses = [...state.nurses].sort(
(a, b) => new Date(a.normalRoundDate) - new Date(b.normalRoundDate)
);
},
sortNursesBySaturdayRound(state) {
state.nurses = [...state.nurses].sort(
(a, b) => new Date(a.saturdayRoundDate) - new Date(b.saturdayRoundDate)
);
},
sortNursesBySundayRound(state) {
state.nurses = [...state.nurses].sort(
(a, b) => new Date(a.sundayRoundDate) - new Date(b.sundayRoundDate)
);
},
},
});
export const {
addNurse,
deleteNurse,
updateSaturdayRound,
updateSundayRound,
updateNormalRound,
sortNursesByNormalRound,
sortNursesBySaturdayRound,
sortNursesBySundayRound,
} = nursesSlice.actions;
export const getNurses = (state) => state.nurses.nurses;
export default nursesSlice.reducer;
nursesSlice.js
i want to keep the state always updated when dispatching actions
Differences in Line Height and Position When Rendering Text with Canvas Across Browsers and Platforms
I’ve encountered a subtle issue while rendering text using Canvas on different browsers (Cairo (Node-Canvas), WebKit, Chromium) and operating systems (Windows, Mac, Linux). The line height and text positioning seem to vary slightly. Even within the same browser, like Chrome, there are minor differences across these platforms.
To illustrate the issue, I’ve used Konva.js to draw grids and text, allowing for an easier comparison of the rendering differences across environments.
Code Example:
Sample on CodeSandbox demonstrating the issue.
I was hoping to find a way to render text using Canvas that would look consistent across all browsers and platforms. If this is currently not possible, are there alternative solutions? For instance, would using WebGL or OpenGL + WASM help?
Smooth Transition on ScrollToIndex upon clicking(React Native)
So what I am trying to do here is to scrollToIndex but currently right now what is happening is it just snap directly to the categories that I have it doesn’t do the normal transition like this
https://snack.expo.dev/G4WZxKGdD
Categories : “All”, “Category1”, “Category2”, “Category3”, “Category4”
I have 3 tsx files okay so the first one is the categorylist.
interface Item {
id: string;
title: string;
}
const getItemMargin = (isFirstIndex: boolean, isLastIndex: boolean) => {
return {
marginLeft: isFirstIndex ? 24 : 0,
marginRight: isLastIndex ? 24 : 8,
};
};
interface CSProps<T extends Item> extends ViewProps {
items: T[];
onSelectItem: (id: T['id']) => void;
selectedId: string;
categoryIndex: number;
}
const CategoryList = <T extends Item>({
style,
items,
onSelectItem,
selectedId,
categoryIndex,
...rest
}: CSProps<T>): JSX.Element => {
const {t} = useTranslation();
const flatList = useRef<FlatList>(null);
useEffect(() => {
flatList.current?.scrollToIndex({
index: categoryIndex,
animated: true,
});
console.log('Check if being called here');
}, [categoryIndex]);
const renderItem = ({item, index}: {item: T; index: Number}) => {
const backgroundColor =
item.id === selectedId
? Colors.PRIMARY_01_BLUE_4
: Colors.PRIMARY_03_WHITE;
const color =
item.id === selectedId
? Colors.PRIMARY_03_WHITE
: Colors.PRIMARY_01_BLUE_4;
const borderWidth = item.id === selectedId ? 0 : 1;
const isFirstIndex = index === 0;
const isLastIndex = index === items.length - 1;
return (
<TouchableOpacity
testID={item.title.replace(/[A-Z]/g, c => c.toLowerCase())}
onPress={() => onSelectItem(item.id)}
style={[
styles.item,
{backgroundColor},
{borderWidth},
getItemMargin(isFirstIndex, isLastIndex),
]}>
<Text style={[styles.title, {color}]}>{t(item.title)}</Text>
</TouchableOpacity>
);
};
return (
<View style={style} {...rest}>
<FlatList
ref={flatList}
horizontal
initialScrollIndex={categoryIndex}
data={items}
renderItem={renderItem}
keyExtractor={({id}) => String(id)}
extraData={selectedId}
showsHorizontalScrollIndicator={false}
onScrollToIndexFailed={info =>
setTimeout(() => {
flatList.current?.scrollToIndex({
index: info.index,
animated: false,
});
}, 500)
}
/>
</View>
);
};
const styles = StyleSheet.create({
input: {
...Typography.BODY_2_16_BOOK,
borderBottomColor: Colors.PRIMARY_03_GREY_3,
borderBottomWidth: 0.7,
paddingVertical: 12,
},
inputActive: {
borderBottomColor: Colors.PRIMARY_01_BLUE_4,
},
item: {
borderRadius: 16,
borderStyle: 'solid',
borderColor: Colors.PRIMARY_03_GREY_3,
paddingHorizontal: 16,
height: 28,
justifyContent: 'center',
alignItems: 'flex-start',
},
title: {
...Typography.REMARK_1_13_MEDIUM,
},
});
export default CategoryList;
the second one is the tabitem where in I call the CategoryList which is in the component of RecentActivitiesTabItem
<CategoryList
style={styles.categoryContainer}
items={categories}
selectedId={categoryId}
onSelectItem={setCategoryId}
categoryIndex={categoryIndex}
/>
and the last one is RecentActivities where in I call the RecentActivitiesTabItem
const getTabComponent = useCallback(
(statusType: RecentActivityStatusType, tabIndex: number) => {
const items =
recentActivities?.filter(i => i.statusType === statusType) ?? [];
const categoryId = categoryIds[tabIndex];
const index = categories.findIndex(x => x.id === categoryId);
const categoryIndex =
index < categories.length / 2 ? 0 : categories.length - 3;
return () => (
<RecentActivitiesTabItem
navigation={navigation}
categoryId={categoryId}
setCategoryId={newCategoryId => {
const newCategoryIds = clone(categoryIds);
newCategoryIds[tabIndex] = newCategoryId;
setCategoryIds(newCategoryIds);
}}
onErrorRetry={onErrorRetry}
onRefresh={fetchData}
items={!reload ? (recentActivities ? items : null) : null}
statusType={statusType}
categoryIndex={categoryIndex}
categories={categories}
/>
);
},
[
categories,
categoryIds,
fetchData,
navigation,
onErrorRetry,
recentActivities,
reload,
],
);
Django template next item show with infinite scroll
I have some code wrong and run next item show with infinite scroll, How to resolve? TKs
I made a countdown on the template
var eventBox = document.getElementById('event-box')
console.log(eventBox.textContent)
var countdownBox = document.getElementById('countdown-box')
console.log(countdownBox.textContent)
var eventDate = Date.parse(eventBox.textContent)
setInterval(()=>{
var now = new Date().getTime()
var diff = eventDate - now
var d = Math.floor(eventDate / (1000 * 60 * 60 * 24) - (now / (1000 * 60 * 60 * 24)))
var h = Math.floor((eventDate / (1000 * 60 * 60 ) - (now / (1000 * 60 * 60 ))) % 24 )
var m = Math.floor((eventDate / (1000 * 60 ) - (now / (1000 * 60 ))) % 60 )
var s = Math.floor((eventDate / (1000) - (now / (1000))) % 60 )
if (diff>0) {
countdownBox.innerHTML = d + " 天, " + h + " 時, " + m + "分, " + s + "秒"
} else {
}
}, 1000)
def all_emp(request):
emps = Employee.objects.filter(end_date__gt=Now()).all()
context = {
'emps': emps
}
print(context)
return render(request, 'view_all_emp.html', context)
v8 c++ code to feed infinite async for loop or infinite blocking for loop
Here is the Javascript code that I want to use
(async () => {
for await(const message of listen()) {
console.debug(message);
}
});
Here is an example that works for a blocking for loop but of course ends after the array is fully iterated.
for(const message = listen()) {
console.debug(message);
}
Here is the c++ code that feeds the Javascript ‘listen()’ function. I want this to work with either an async for loop or a blocking for loop but continuously feed data that is brought in by some kind of input structure. e.i. network requests.
void listen(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::Local<v8::Object> object = v8::Object::New(isolate);
object->DefineOwnProperty(
isolate->GetCurrentContext(),
slim::utilities::StringToName(isolate, "message"),
slim::utilities::StringToValue(isolate, "listening...")
);
v8::Local<v8::Array> array = v8::Array::New(isolate);
array->Set(isolate->GetCurrentContext(), 0, object);
array->Set(isolate->GetCurrentContext(), 1, object);
array->Set(isolate->GetCurrentContext(), 2, object);
args.GetReturnValue().Set(array);
}
Using d3 dependency to embed an interactive plotly object in Quarto
I am trying to host a large interactive plotly graph using Quarto. The graph is an interactive PCA plot which shows images on hover. I have written the code in R and had to call the d3 dependency separately.
When I run the code chunk in Quarto the graph shows, however, when I render the page I get the following error:
Error in FUN(X[[i]], …) : Dependency d3 7.3 is not disk-based
Calls: .main … dependencies_from_render -> html_dependencies_as_string -> lapply -> FUN
Execution halted
I have tried having the d3 file locally on my computer, however, I get the same issue. I was wondering how to fix this? I will show my code below.
{r, echo = FALSE, message=FALSE}
# -----------------------------------------------------------------------------
# LOAD LIBRARIES --------------------------------------------------------------
# -----------------------------------------------------------------------------
library(adegenet)
library(dartR)
library(ggplot2)
library(tidyverse)
library(htmlwidgets)
library(plotly)
library(readxl)
library(magick) ## for resizing images
library(plotly) ## adding images
# -----------------------------------------------------------------------------
# LOAD DATA -------------------------------------------------------------------
# -----------------------------------------------------------------------------
all <- read_xlsx("~/Documents/RA_EcoRRAP/Spis/4_PCA/1_interactive_plot/Spis_interactive_plot_quarto.xlsx")
# -----------------------------------------------------------------------------
# CREATE PLOT -----------------------------------------------------------------
# -----------------------------------------------------------------------------
# dependency code
# Create HTML dependency for the D3 library (version 7.3)
d3 <- htmltools::htmlDependency(
"d3", "7.3",
src = c(href = "https://cdnjs.cloudflare.com/ajax/libs/d3/7.3.0/"), # Specify the source URL for D3 library
script = "d3.min.js" # Specify the JavaScript file to load
)
# javascript code
js <- 'function(el) {
// Create a tooltip div and assign it the "my-custom-tooltip" class
var tooltip = d3.select("#" + el.id + " .svg-container")
.append("div")
.attr("class", "my-custom-tooltip");
// Add an event listener for the "plotly_hover" event
el.on("plotly_hover", function(d) {
var pt = d.points[0]; // Get the first point of the hover event
// Set the desired x and y coordinates for the tooltip
var xPixel = 20; // Change this to 15
var yPixel = 4; // Change this to 6
// Create an image tag with a custom data source and width
var img = "<img src=\"" + pt.customdata + "\" width=400>";
tooltip.html(img)
.style("position", "absolute")
.style("right", xPixel + "px")
.style("top", yPixel + "px");
// Apply a transition to the tooltip (so that it fades in)
tooltip.transition()
.duration(300)
.style("opacity", 1);
});
// Add an event listener for the "plotly_unhover" event
el.on("plotly_unhover", function(d) {
// Apply a transition to hide the tooltip
tooltip.transition()
.duration(500)
.style("opacity", 0);
});
}'
# create uris (this locates the images so they can be used in the plot)
uris <- purrr::map_chr(
all$New_sample_name, ~base64enc::dataURI(file = sprintf("~/Documents/RA_EcoRRAP/Spis/4_PCA/1_interactive_plot/Spis_images/resize/%s.JPG", .x))
)
# plot figure
fig <- plot_ly(
data = all,
x = ~PC1,
y = ~PC2,
color = ~Cluster,
colors = c("#834177", "#d23359", "#17697c", "#ba4b05", "#00652e", "#b99a2d"),
customdata = ~uris,
text = ~paste("Sample Name: ", all$New_sample_name, "<br>",
"Locality: ", all$locality, "<br>",
"Site: ", all$EcoLocationID_short, "<br>",
"Taxa: ", all$Cluster),
hovertemplate = paste0(
"<span style='fill:white;font-size:1em;'>%{text}</span><extra></extra>")
)
# add dependencies
fig$dependencies <- c(fig$dependencies, list(d3))
# plot figure
fig
TomTom traffic api integration in ESRI js api
I’m facing issues displaying results from the TomTom API in my ArcGIS JavaScript application. Despite configuring a Vector Tile Layer with TomTom traffic data, the results are not showing up on the map. I’m seeking assistance in identifying and resolving the problem.
Code Snippet:
javascript
this does not show anything on the map but it makes requests for the traffic data and returns the data as .pbf file
let vectorTileLayer = new VectorTileLayer({
title: 'TomTom Traffic',
style: {
version: 8,
sources: {
tomtom: {
type: 'vector',
tileCompression: "gzip",
tiles: ["https://c.api.tomtom.com/traffic/map/4/tile/flow/absolute/{z}/{x}/{y}.pbf?key=hCsMmqZyJdl2R0HmgbL02FmpQVGmAMnT"],
minzoom: 0,
maxzoom: 22,
},
},
layers: [
{
id: 'Traffic flow',
type: 'fill',
source: 'tomtom',
'source-layer': 'public',
paint: {
'fill-color': 'red',
'fill-opacity': 0.2,
'fill-outline-color': 'blue',
},
},
],
},
});
this works but it is an image tiles
let tileLayer = new WebTileLayer({
title: 'TomTom Traffic',
urlTemplate: "https://c.api.tomtom.com/traffic/map/4/tile/flow/relative/{z}/{x}/{y}.png?key=hCsMmqZyJdl2R0HmgbL02FmpQVGmAMnT&thickness=8&tileSize=512",
minZoom: 0,
maxZoom: 22,
});
Issue Details:
I have set up a Vector Tile Layer with TomTom traffic data using the ArcGIS API for JavaScript.
The TomTom API URL and parameters have been configured correctly.
There are no console errors or warnings, but the results are not visible on the map.
Additional Information:
What steps should I take to troubleshoot and identify the reason why results from the TomTom API are not displaying?
Are there common challenges or considerations when integrating TomTom API results with the ArcGIS JavaScript API?
Are there specific debugging techniques or tools I can use to inspect the TomTom API response and understand why it’s not rendering on the map?
I have verified the TomTom API key and ensured that it is valid.
Other layers, such as WebTileLayer, are displaying correctly.
I’m using version [insert version] of the ArcGIS API for JavaScript.
Complicated regex to find && that is not in a nested bracket
I’ve created this regex (?![^()]*([^()]*))&&(?![^()]*)) for javascript to pick up any && in the following statement
a == ‘v’ && a ==’x’ && be ==’gg’ && ((hh == ‘x’ && bppint == true) && (kk == ‘welp’ && pro == true))
It works but when it came to this following statement
(hh == ‘x’ && bppint == true) && (kk == ‘welp’ && pro == true)
It doesnt pick up the && in between the brackets. Am stuck at this part for a long time and would really appreciate any help that comes my way…
For context the reason why im doing this is avoid using any external libraries to help do the detection of && or || tokens and I find regex to be interesting and quite powerful in doing this kinda things
How to make parse-server detect I’m using ESM now?
I want to use ESM instead of CommonJS in my Node.js server is used to run ParseServer (version 6.4.0). I adapt my code. However, Parse-Server doesn’t detect that I’m using ECM now and is throwing the following error:
require() of ES Module ../main.js from ../node_modules/parse-server/lib/ParseServer.js not supported.
Instead change the require of main.js in ../node_modules/parse-server/lib/ParseServer.js to a dynamic import() which is available in all CommonJS modules.
I found a solution by forcing the use of ESM via my npm start command : npm_package_type=module node app.js
But that’s not a viable solution, as it should work from scratch.
To switch to ESM, I change theses line in my package.json :
"type": "module",
"engines": {
"node": ">=16"
},
I also use import/export in all my files. What should I also do to make parse-server aware I’m now in ECM?
Looking into parseServer code, it crashes here:
if (process.env.npm_package_type === 'module' || ((_json = json) === null || _json === void 0 ? void 0 : _json.type) === 'module') {
await import(path.resolve(process.cwd(), cloud));
} else {
require(path.resolve(process.cwd(), cloud));
}
It crashes because it goes into the require part which is not allow for ESM instead of the require. It only works when I change my npm start command and force it.
selectQuery javascript
I have the following code:
HTML
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>testHtml</title>
<link rel="stylesheet" href="test.css">
<script src="testCode.js" defer></script>
</head>
<body>
<button>butt1</button>
</body>
</html>
CSS
. red {background-color:red;}
JS
let butt1 = document.querySelector("button");
butt1. classList. add("red");
This code produces an error:
Uncaught TypeError: Cannot read properties of null (reading ‘classList’)
I understand that querySelector in this returns a null or undefined object therefore it does not have any properties. But button element is clearly on the page. What may cause such behavior?
How to move words from the textAraea to each in the ‘ol’ element, JavaScript
The first word in the textarea should enter class “word1” with append tag ‘li’, then the second word should enter class “word2” with tag ‘li’ and the other words in the same order
if no more word from textarea class ol should be emtty
<!DOCTYPE html>
<head>
</head>
<textarea class="rebaz"rows=4 cols=50>hello my name is rebaz</textarea>
<button onclick="show();">Show content</button>
<ol class = "word1"></ol>
<ol class = "word2"></ol>
<ol class = "word3"></ol>
<ol class = "word4"></ol>
<ol class = "word5"></ol>
<ol class = "word6"></ol>
</body>
</html>
after click button
<ol class = "word1"><li>hello</li></ol>
<ol class = "word2"><li>my</li></ol>
<ol class = "word3"><li>name</li></ol>
<ol class = "word4"><li>is</li></ol>
<ol class = "word5"><li>rebaz</li></ol>
<ol class = "word6"></ol>
How to download excel file using storage disk(‘s3’)
recently i am having problem in downloading file using storage disk(‘s3’) in laravel .
I can download file using export.php but i need to convert it to use s3, for which i can’t find help on chrome .Here is my code
if ($request->download && !is_null($data)) {
$array = json_decode( json_encode($data), true);
$final_array = [];
foreach($array as $key){
unset($key['id']);
array_push($final_array,$key);
}
$keys = array_keys(($final_array[0]));
$file_name = 'Today_Delivery_'.$request->user()->id.'_'.Carbon::now()->format('d_M_Y_His').'.xlsx';
(new GenDataExport(collect(json_decode(json_encode($final_array), true)), $keys ))->store($file_name);
// $s3 = Storage::disk('s3');
// $filePath = '/users/signatures'.'/'.$user_id.'/post-'.$customer_id.'_'.$imageFileName;
// $s3->put($filePath, file_get_contents($image), 'public');
// $url = config('filesystems.disks.s3.arn_url');
}
As you can see the file is downloading by export.php file and i want to use the commented code to download it , but can’t think where to use that code .Any help will be appreciated ,Thanks.
i tried but got this error
file_get_contents() expects parameter 1 to be a valid path, array given
when i gave $final_array to file_get_contents
Here is my $final_array value
[0] => Array
(
[customer_name] => doodh walah
[area] => no area
[product_name] => milk bill
[address] =>
[qty] => 1
)
[1] => Array
(
[customer_name] => doodh walah
[area] => no area
[product_name] => milk
[address] =>
[qty] => 1
)
Why does Postman allow Body in GET requests?
I am using axios to interact with the backend server, and in the process, I found something interesting. In Postman, it is possible to attach data in the request Body and receive responses with the status 200. However, this seems not to be the case when implementing in the frontend. For example:
axios.get('[target_url]', {
// would result in "ERROR_CODE_INTERNAL_SERVER_ERROR" (status `500`)
'data': {
'data1': 'value1',
'data2': 'value2'
// ...etc.
}
}).then(response => console.log(response));
Many StackOverflow questions mention why GET requests do not allow request Body. Let me include some of them as references:
- HTTP GET with request body
- REST API HTTP GET with Body
- axios get request with body and header
- React JS – How to pass body request in GET of fetch
And it appears the suggested ways to do so, are to either, change it to a POST request, or transform data in request Body to params: Sending GET request parameters in body
Thus, I would genuinely like to take a step further and know the reasons why Postman allows request body for GET requests.
Thank you for your kind attention and all the help.

