In order to help for a festival where people can organize their encampments themselves, I was trying to create a very simple map where users can draw their encampment and add their name and information. My first question is: where this sharable information would be saved? Does Leaflet servers provide that option? or we need our own server? And then my second question is: how to write the code (html and jabascript and maybe more?)
This would benefit greatly many organizations as we let people organize themselves in a more decentralized way. No need of a central authority. You could discuss with your future neighbors about noise levels for example… I can see many applications
Category: javascript
Category Added in a WPeMatico Campaign
How to make a static variable in JavaScript like we do in c ? ( to avoid re-initialization of the variable)
I watched this video on https://www.youtube.com/watch?v=cjIswDCKgu0&t=429s YouTube;
I just wanted to make a simple debounce function. but this code does not work on my device as intended. Please help.
let debounceTimes = 0;
// this code does not work as intended
let timeout; // if I make it global it works just fine
// but I don't want to do that for obvious reasons
function debounce(cb, delay = 100) {
// let timeout; // this is being reinitialized
// only if I could do something like this
// static timeout;
// to avoid re-initializing the variable
// return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
cb();
}, delay);
// }
}
window.addEventListener("mousemove", () => {
// console.log("hello");
// document.getElementById("debounce").innerText++;
debounce(
() => {
debounceTimes++;
document.getElementById("debounce").innerText = String(debounceTimes);
}, 100);
});
Is there a way to avoid transcoding to save bitstream through webrtc?
I managed to port recording function into WebRTC server using RecordRTC. Now I can save the video that is conveyed. enter image description here
current structure: enter image description here
But it strikes me that i might be encoding the video stream on the screen that is actually decoded from the bitstream. If so, I want to make the data flow structure different, because the decoding process is not necessary if I just signed up for containing the bitstream into a file only. I’m struggling with finding a way around decoding process.
the structure that I aimed for: enter image description here
Please would there be a solution for this? If not, suggest me a possible alternative for this. Thank you.
React Ag-grid checkbox filter with API data
I create react ag-grid table and populate external api data to ag-grid table.
I used this code to populate api data :
function App() {
const columnDefs= [
{ headerName: "Name", field: "company_name" },
{ headerName: "Floor", field: "floor",},
{ headerName: "Group",field: "videos",},
{ headerName: "Camera", field: "camera" },
{ field: 'Name', filter: 'agMultiColumnFilter' },
]
const defaultColDef={
sortable:true,
editable:true,
flex:1,filter:true,
floatingFilter:true
}
const onGridReady=(params)=>{
console.log("grid is ready")
fetch("http://localhost:8000/get_all")
.then(resp=>resp.json())
.then(resp=>{console.log(resp.results)
params.api.applyTransaction({add:resp.results})
})
}
return (
<div className="App">
<h1 align="center"> React FastAPI Integration</h1>
<h3> API Data </h3>
<div className="ag-theme-alpine" style={ {height: '400px'} }>
<AgGridReact
columnDefs={columnDefs}
defaultColDef={defaultColDef}
onGridReady={onGridReady}>
</AgGridReact>
</div>
</div>
);
}
export default App;
After passing data i expected to add checkbox filter for API data.How can i add checkbox filter for react ag-grid table
After passing data my table like this
My expected checkbox filter like this
How to add checkbox filter for react ag-grid table using react js
Why am I getting “Property ‘wide’ does not exist on type ‘ThemedStyledProps<PressableProps & RefAttributes, DefaultTheme>’.”
I’m trying to add styled components to my project, but I’m having some trouble changing the style based on the props of the styled component. Whenever I try to do this – width: ${(props) => (props.wide ? '100%' : undefined)}; I get a Property 'wide' does not exist on type 'ThemedStyledProps<PressableProps & RefAttributes<View>, DefaultTheme>'. error.
I’m passing variant, wide and style to the styled component and I have the props type defined like this:
type StyledPressableProps = {
variant?: ButtonVariant;
wide?: boolean;
} & PressableProps;
But I’m still getting a TS error.
My code:
import React, { FunctionComponent } from 'react';
import { PressableProps, ViewStyle, StyleProp } from 'react-native';
import styled from 'styled-components/native';
import colors from '@src/core/colors';
import HeaderText from '../Text/HeaderText';
type ButtonVariant = 'primary' | 'secondary' | 'tertiary';
type Props = {
title: string;
variant?: ButtonVariant;
wide?: boolean;
style?: StyleProp<ViewStyle>;
} & Omit<PressableProps, 'style'>;
type StyledPressableProps = {
variant?: ButtonVariant;
wide?: boolean;
} & PressableProps;
const PrimaryButton: FunctionComponent<Props> = ({ title, variant = 'primary', wide = false, ...rest }) => {
const textColor = variant === 'primary' ? colors.white : colors.primary600;
return (
<StyledPressable
variant={variant}
wide={wide}
style={({ pressed: isPressed }) => [{ elevation: isPressed ? 5 : 0 }]}
{...rest}
>
<StyledHeaderText variant="h4" style={{ color: textColor }}>
{title}
</StyledHeaderText>
</StyledPressable>
);
};
const StyledPressable: FunctionComponent<StyledPressableProps> = styled.Pressable`
padding: 12px 24px;
border-radius: 100px;
border-width: 1.5px;
justify-content: center;
align-items: center;
align-self: center;
width: ${(props) => (props.wide ? '100%' : undefined)};
background-color: ${(props) => styles[props.variant].backgroundColor};
border-color: ${(props) => styles[props.variant].borderColor};
`;
const StyledHeaderText = styled(HeaderText)`
text-align: center;
`;
const styles = {
primary: {
backgroundColor: colors.primary600,
borderColor: colors.primary600,
},
secondary: {
backgroundColor: colors.white,
borderColor: colors.primary600,
},
tertiary: {
backgroundColor: 'transparent',
borderColor: 'transparent',
},
};
export default PrimaryButton;
Testing Moment in React Enzyme Jest
I am Using React, Formick and material UI
The UI functionality is working fine, I need to write test case for Formik handle Submit ,
so I wrote the formk test case as usual, but not what is happing is i am using picker and i am getting Date in Friday, February 5, 2016 at 9:00:00 pm UTC to convert the same i am using Moment and i am able to verify it in UI and is working fine but as soon as i try to test the same
it says moment is not a function can any one kindly let me know
what i am doing wrong, (I want to use moment only for conversion as it is being used in my application need a way to test it in jest ezyme)
https://codesandbox.io/s/competent-thompson-s075hi?file=/src/app.test.js
Datepicker Enable Specific Days from list
I am trying to develop an appointment system. I tried to enable available dates in a date picker, but the problem is that it enables only one day.
$('#doctor').on('change', function() {
var drId = this.value;
$('#timetable').html('');
$.ajax({
url: '{{ route('
getTimes ') }}?dr_id=' + drId,
type: 'get',
success: function(res) {
console.log(res);
$('#timetable').html('<option value="">Select Day Time</option>');
$.each(res, function(key, value) {
const weekday = [, "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Satarday"];
const d = new Date();
//Disabled by Day Name
$(document).ready(function() {
$('#datepicker').datepicker({
beforeShowDay: filterDays
});
});
// getDay() method returns the day of the week (from 0 to 6) where
// Sunday is 0, Monday is 1, and so on.
function filterDays(date) {
var day = date.getDay();
//return true only if day is Wed or Fri or Sun
return [day[value.day_name]]
}
$('#timetable').append('<option value="' + value.id + '">' + value.start_time + value.end_time + '</option>');
});
}
});
});
Here return [day[value.day_name]] shows only Sunday, but there is another 3 days had stored in the database. It’s passes only a single value.
Please help me to do this.
Can we use webpack created Javascript files offline
I have an app which uses react with webpack. I see the JS files created in chunks. My question is can I download this [x].chunk.js file and use it like a normal JS file? Also how does the app understand this webpack js file?
Print multiple texts from multiple elements with same class name
Im trying to print all the product names from an e commerce website in selenium using java but its printing only the first name of the product from the first class it finds, kindly help me to print all the product names from all the classes with same class name, This is my code :
package introduction;
import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Getproductnames {
private static int i;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "D:/Temp/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
driver.get("https://www.fipola.in/chicken");
driver.findElement(By.id("DelLocation")).sendKeys("600020");
driver.findElement(By.className("top_pincode_select")).click();
Thread.sleep(3000);
List<WebElement> products=driver.findElements(By.cssSelector("a.product-item-link"));
for(int i=0; i<products.size(); i++);
{
String[] names = new String[]{products.get(i).getText()};
System.out.println(names[i] + "");
}
}
}
How to create a file with a specific size with NodeJs
Doing several tests of files validation, I need a file with more than 250MB, but I don’t want to store it in the repo.
I’m trying to create a file with NodeJs in time execution with several functions I’ve found, but they don’t work for me.
This one creates the file, but it doesn’t have the size I’m passing.
Files have just 1 byte.
createFile(filePath, size) {
return new Promise((resolve, reject) => {
setTimeout(() => {
try {
const fd = fs.openSync(`${filePath}`, 'w');
//fs.writeSync(fd, 'ok', Math.max(0, size - 2));
fs.writeSync(fd, Buffer.alloc(1, 'ok', 'base64'), 0, 1,
//Math.max(0, size - 1)
size - 1
);
fs.closeSync(fd);
resolve(true);
} catch (error) {
reject(error);
}
}, 0);
});
}
I’ll appreciate any help
Draggable video scrubbing
I have a MP4 video of a product which shows a 360 of the product (so it looks like it’s spinning) – I have it autoplaying on the page and looks great.
I want the user to be able to click and drag on the video to basically rewind or fastforward the video, so they can kind of scroll back and forth and spin the product around as they wish.
We have used the js-cloudimage-360-view library and used images, but because we wanted this as smooth as possible each colour had 360 images and loading times weren’t great, we have MP4s which are small in size and load fast but it’s just the srubbing I can’t get right.
I’d had a look at this https://codepen.io/webandapp/pen/xEjjOJ too but it’s supper jumpy, essentially we want if the user drags to the right it fast forwards as they drag, when they stop it should play from that point (and rewinds if dragging to the left) – this should be as smooth as possible.
The video is just a HTML video element like so:
<video id="three-sixty-video" preload="auto" controls loop playsinline autoplay muted>
<source src="/video/video-1.mp4" type="video/mp4;">
</video>
Why is my test failing mocha chai javascript
Here is my code. I have tried everything I can think of and am getting conflicting information.
What is the purpose of calling done?
What is the best way to debug testing issues?
Any and all help would be greatly appreciated. Udacity Experts are not much help
describe('API tests', function () {
it('should have return version number', function (done) {
request(app)
.get('/?filename=icelandwaterfall.jpg&width=300&height=600')
.end(function (err, res) {
expect(res.statusCode).to.be.equal(200);
done();
});
});
});
Here is my router file
import * as express from 'express';
import * as path from 'path';
import * as sharp from 'sharp';
const router = express.Router();
router.use((req, res, next) => {
console.log('Time: ', Date.now());
next();
});
const dir = path.join(__dirname, '../public');
router.get('/', async (req, res) => {
try {
if (!req.query.filename && !req.query.height && !req.query.width) {
req.query.height = 200;
req.query.width = 200;
req.query.filename = 'santamonica.jpg';
res.status(400).send('Please enter filename, height and width');
return;
}
if (!req.query.height && !req.query.width) {
req.query.height = 200;
req.query.width = 200;
res.status(400).send('Please enter a height and width');
return;
}
if (!req.query.filename) {
req.query.filename = 'santamonica.jpg';
res.status(400).send('Please enter a filename');
return;
}
if (!req.query.height) {
req.query.height = 200;
res.status(400).send('Please enter a height');
return;
}
if (!req.query.width) {
req.query.width = 200;
res.status(400).send('Please enter a width');
return;
}
const height = Number(req.query.height);
const width = Number(req.query.width);
const file = dir + '\' + req.query.filename;
const output = dir + '\' + 'resized.jpeg';
await sharp(file)
.resize({ height: height, width: width })
.toFile(output).then(() => {
res.status(201).sendFile(output);
}) .catch(function(err) {
console.log('Error occured ', err);
});
} catch (error) {
console.error(error);
}
});
module.exports = router ;
Here is my app file
import * as express from 'express';
import * as imageRoutes from './routes/images';
const app = express();
app.use('/api/Images', imageRoutes);
app.listen(3000);
module.exports = app;
Here is the error message
1) API tests
should have return version number:
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (C:UserspatrickOneDriveDocumentsGitHubimage-apitestimageTests.js)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)
TypeError: Cannot read properties of undefined (reading 'filename')
Exporting multiple instances of same chart in a single file
Since we cannot have a scrollbar in our exported file so I want to break my chart into multiple instances in order to view the whole chart data. If we have 40 columns(bars) in our chart, I would like to break it into four instances each having 10 bars. The first instance should display the first 10 columns, second instance should display the next 10 columns and so on. All instances should be placed inside single exported file (like Exporting several charts demo). I am facing some problems doing that.
Below are my export, onExporting and onExported functions:
Here I am trying to display 12 columns in each instance so I have taken the length as 12, the startingPoint variable is initially set to 0 and incremented by 12 each time. I am changing the visual range in each instance but that is not happening.
I have declared a chartInstances array on which I am trying to push each chart instance but it gives the same instance each time.
(Note: I don’t want to resize anything please don’t provide useless solutions)
It’s a request kindly understand the problem first then provide any solution please. Thank you!
I have attached a sample image of what I’m trying to achieve, but here all four instance display the same data instead what I want is that the first instance should display the first 12 columns, second instance should display the next 12 columns and so on.
export() {
exportWidgets([this.chartInstances], {
fileName: 'chart',
format: 'PNG',
});
}
onExporting(e) {
e.cancel = true;
this.currentRange = e.component.getArgumentAxis().visualRange();
for (let i = 0; i < Math.ceil(this.dataSource.length / 12); i++) {
e.component.getArgumentAxis().visualRange({startValue: this.startingPoint, length: 12});
this.chartInstances.push(this.chart.instance);
if (i >= Math.ceil(this.dataSource.length / 12)) {
this.export();
}
this.startingPoint += 12;
}
}
onExported(e) {
e.component.getArgumentAxis().visualRange(this.currentRange);
}
Does the Elasticsearch bulk API JavaScript sample code work correctly?
I want to use Elasticsearch bulk index with JavaScript, and follow the official document. Basically I just used it as is, but it throws an exception saying that the bulk request must be terminated by a newline code, which seems to be JSON lines.
My question is, if so, how can I convert the JSON to JSON lines and then pass it to bulk API? or am I missing some options when calling client.bulk?
ResponseError: illegal_argument_exception: [illegal_argument_exception] Reason: The bulk request must be terminated by a newline [n]
at SniffingTransport.request
I use Elasticsearch v7.15 and Node.js v16.15 on macOS.
Remove special chars from string onchange [duplicate]
I am trying to remove special chars from a string everytime a user enters a charactor. However, they are not removed using the function below:
const onChange = (args) => {
const inputValue = args[0].nativeEvent.text;
inputValue?.replace(/[^a-zA-Z0-9 ]/g, ""); // special chars not removed
console.log(inputValue)
return inputValue;
};
<Controller
name="anotherVehicle"
defaultValue=""
control={control}
rules={{ required: enableAddingAnother, maxLength: 7 }}
onChange={onChange}
as={
<InputField
name="anotherVehicle"
error={errors?.work}
placeholder={vehicleRegistrationLabel}
errorMessage={errors?.work?.errorMessage}
inputWrapperStyle={styles.textInputWrapperStyle}
inputExternalWrapperStyle={
styles.textInputExternalWrapperStyle
}
{...AccessibilityHelper("Another vehicle input field")}
/>
}
/>


