How will the view code part based on Class-based view will look like if i have for example this 2 models
Class Student with two columns name and last_name
Class City name and street
The form will be in a html file, in this case it will have the 4 inputs,
Category: javascript
Category Added in a WPeMatico Campaign
Highlight country once selected with dropdown D3
I have a map of Africa which I loaded using D3 which features several columns including a column named ADMIN which features each country’s name. I’m trying to highlight the country on my map that is selected in my dropdown. For example if I select Algeria in my drop down, Algeria will highlight on my map. The map itself loads fine as well as the dropdown. I’m just having trouble coordinating the interaction between the dropdown function and the highlight function so that the selected country actually highlights.
//begin script when window loads
window.onload = setMap();
var attrArray = ["Algeria","Angola","Benin"];
var expressed = attrArray[0];
//set up map
function setMap(){
//map frame dimensions
var width = 1200,
height = 1000;
//create new svg container for the map
var map = d3.select("body")
.append("svg")
.attr("class", "map")
.attr("width", width)
.attr("height", height);
//create Albers equal area conic projection centered on France
var projection = d3.geoOrthographic()
.scale(600)
.translate([width / 2, height / 2.7])
.clipAngle(85)
.precision(.1);
var path = d3.geoPath()
.projection(projection)
var graticule = d3.geoGraticule()
.step([5, 5]); //place graticule lines every 5 degrees of longitude and latitude
//create graticule background
var gratBackground = map.append("path")
.datum(graticule.outline()) //bind graticule background
.attr("class", "gratBackground") //assign class for styling
.attr("d", path) //project graticule
var gratLines = map.selectAll(".gratLines")
.data(graticule.lines()) //bind graticule lines to each element to be created
.enter() //create an element for each datum
.append("path") //append each element to the svg as a path element
.attr("class", "gratLines") //assign class for styling
.attr("d", path); //project graticule lines
//use queue to parallelize asynchronous data loading
d3.queue()
.defer(d3.csv, "data/AfricaCountries.csv") //load attributes from csv
.defer(d3.json, "data/world.topojson") //load background spatial data
.defer(d3.json, "data/Africa.topojson")
.await(callback);
function callback(error, csvData, world, africa){
//translate europe TopoJSON
var basemapCountries = topojson.feature(world, world.objects.ne_10m_admin_0_countries),
africaCountries= topojson.feature(africa, africa.objects.ne_10m_admin_0_countries).features;
//select graticule elements that will be created
//add Europe countries to map
var countries = map.append("path")
.datum(basemapCountries)
.attr("class", "countries")
.attr("d", path);
//add Africa countries to map
var regions = map.selectAll(".regions")
.data(africaCountries)
.enter()
.append("path")
.attr("class", function(d){
return "regions " + d.properties.ADMIN;
})
.attr("d", path);
createDropdown(csvData);
};
function createDropdown(csvData){
//add select element
var dropdown = d3.select("body")
.append("select")
.attr("class", "dropdown")
.on("change", function(){
highlight(d.properties);
});
//add initial option
var titleOption = dropdown.append("option")
.attr("class", "titleOption")
.attr("disabled", "true")
.text("Select Country");
//add attribute name options
var attrOptions = dropdown.selectAll("attrOptions")
.data(attrArray)
.enter()
.append("option")
.attr("value", function(d){ return d })
.text(function(d){ return d });
};
//function to highlight enumeration units and bars
function highlight(props){
//change stroke
var selected = d3.selectAll("." + props.ADMIN)
.style("stroke", "blue")
.style("stroke-width", "2");
};
};
How to add dynamic or changable files as assets in pkg nodejs
I have added folders as assets to pkg for creating exe file.
The jsonfiles folder contains json files and I want to change the values of these json files and when changed should reflect in frontend.
The jsonfiles folder always displays the value which was present during compilation, I want to make these assets dynamic(i.e,json file changes should reflect on frontend)
"pkg": {
"assets": [ "public/**/*", "jsonfiles/**/*" ],
"targets": ["node14-win-x64" ]
},
SwiperJS breakpoint pagination issue
I’m creating a swiper slider using the SwiperJS library. On Desktop, I’d like to show custom pagination and on mobile, I’d like to set the pagination type to “bullets”. The issue is that the pagination type doesn’t change when I resize my browser until I manually refresh the page. Any help would be greatly appreciated. Here’s the code:
HTML:
<div class="swiper">
<div class="swiper-wrapper">
<div class="swiper-slide">
<p>slide 1</p>
</div>
<div class="swiper-slide">
<p>slide 2</p>
</div>
</div>
<div class="swiper-pagination"></div>
</div>
JS:
let mySlider = new Swiper('.swiper', {
slidesPerView: 1.1,
spaceBetween: 10,
observer: true,
observeParents: true,
pagination: {
el: '.swiper-pagination',
clickable: true,
type: 'bullets'
},
breakpoints: {
768: {
pagination: {
type: 'custom',
renderCustom: function (swiper, current, total) {
return current + ' - ' + total
}
}
}
},
on: {
breakpoint: function (swiper) {
swiper.update()
// Also tried swiper.destroy(), swiper.pagination.init() and swiper.init()
}
},
})
convert php array to a javascript array in this particular case: component is a string, recipes is also a string in the format “”recipe1″,”recipe2″”
this is what I did. The following code creates a php arrray with component as id ajnd recipes as values. An example is at component “vodka”(string) we have recipes(“”recipe1″,”recipe2″”recipe3″”) the recipes are also in a format of a string. The array is $menuThings
How to fix This page can’t load Google Maps correctly. Do you own this website?
I am creating an web app with ReactJS & there I have to use Google Map to show some data from NASA API
Project Info
- I have created
no billingfreeAPI Keyon Google Developer - I have created
.envon my React project & use with `process.env.REACT_APP_API_KEY - I have installed & imported
google-map-react
API Info
- I have enable
JavaScript Map API - App restriction selected `HTTP referrers(web sites)
- Website restriction set
*localhost:3000
http://localhost:3000
- API restriction
- Restrict Key -> Map JavaScript API
Problem
- I have clear
cached & cookies&restartserver many times but it show me
This page can’t load Google Maps correctly. Do you own this website? For development purposes only
Code
import GoogleMapReact from 'google-map-react'
import '../style/index.css'
const Map = ({ center, zoom }) => {
return (
<div className='map'>
<GoogleMapReact
bootstrapURLKeys={{
key: process.env.REACT_APP_API_KEY
}}
defaultCenter={center}
defaultZoom={zoom}
>
</GoogleMapReact>
</div>
)
}
Map.defaultProps = {
center: {
lat: 42.3265,
lng: -122.8756
},
zoom: 3
}
export default Map
CORS Request to S3 Accepted for File Display but Not for Load by Javascript Library
I’m developing a small javascript browser script that retrieve files from S3.
I can display the images without any issue after requesting a SignedUrl to S3. I also updated the CORS policy on S3:
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"GET",
"HEAD",
"PUT",
"POST",
"DELETE"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": []
}
]
However when I want to use the same URL to extract the EXIF data (using ExifReader), I get an error message about CORS policy:
Access to fetch at '*SIGNEDURL*' from origin 'null' has been blocked
by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to
'no-cors' to fetch the resource with CORS disabled.
I don’t understand the difference in the behaviour of both. Can someone help?
Thank you
How to disable button while form is being created and to prevent duplicate form
I am trying to make it so that a “Submit” button is disabled when submitting and forwarding data from a form. This is to prevent the user from create multiple copies of the form when rapidly clicking the button when the initial data that was inputted is being saved.
One approach I tried was adding a debouncer to the JavaScript function that handles the submit button operations. However if the user continues to click the button after 5 seconds, the duplicate is still created.
I think a better approach would be to disable the button while the data is being submitted and give an indication to the user that the data is in the state of being saved, and after completion, reenable the button.
Here is the javascript code for context:
setupFormIO: function(submissionFunction) {
var $this = this;
var submitFunc = submissionFunction;
var labelText = "Submit";
if ($this.projectData && !this.readonly) {
labelText = "Save";
}
var submits = FormioUtils.searchComponents($this.template.components,
{
"type": "button"
}
);
if (submits) {
_.each(submits, function (component) {
component.label = labelText;
//
var timer;
if (timer) {
clearTimeout(timer);
}
//
if ($this.readonly) {
$("#" + component.id + " > button").on("click", function(evt) {
evt.stopPropagation();
location.assign("/project/ProjectHome.aspx");
timer = setTimeout(process, 5000); //
});
}
});
}
Close popup by Esc if there are many of them on the page
I have been searching through the web, but could not find the answer to the question, which seems to have a trivial solution.
I have three popups on my page, which user can open and the functionality to open and close them looks usual:
const popupPicture = document.querySelector(".popup_pic");
const popupProfile = document.querySelector(".popup_profile");
const profileName = document.querySelector(".profile__name");
function openPopup(popup) {
popup.classList.add("popup_opened");
}
function closePopup(popup) {
popup.classList.remove("popup_opened");
}
and I pass one of the popup variables to closePopup or to openPopup as a variable.
For instance
closePopupButton.addEventListener("click", () => closePopup(popupProfile));
closePopupImageButton.addEventListener("click", () => closePopup(popupImage));
closePopupPictureButton.addEventListener("click", () => closePopup(popupPicture));
The same with opening popups. I need now closing functionality by Escape button. I understand that it is easy to achieve if there is just one popup by the following code:
document.addEventListener("keydown", function (evt) {
if (evt.key === "Escape") {
// and close popup here
}
});
But there are three popups in my case and I do not know, which I should close. Of course I can do it by this ugly way:
document.addEventListener("keydown", function (evt) {
if (evt.key === "Escape") {
closePopup(popupProfile);
closePopup(popupImage);
closePopup(popupPicture);
}
});
And it solves my case, but I wonder if there is more elegant solution, which does not require calling two functions that should not be called.
Hopefully I stated my issue clear.
Thank you very much in advance!
Slatejs – Set type as inline
I’ve got a question regarding Slatejs.
I’m trying to implement an option to set a text to a type “url” and display this type as hyperlink.
This works fine, but actually the complete line is being marked as type “url” and not only the selected text. I want the selected text marked as type “url” and to be added inline.
This is my current code to mark the selected text as type “url”
function onFormatTextUrlButtonClick(editor) {
const isActive = isTypeActive(editor,'url')
Transforms.setNodes(
editor,
{
type: isActive ? 'paragraph' : 'url',
url: isActive ? undefined : Editor.string(editor, editor.selection)
},
{
match: n => Editor.isBlock(editor, n)
}
);
}
I’m sure it is no big issue, but I can’t figure it out actually. Many thanks for any hint in advance!
How to change the json request format when input is captured via a form
We have the following form.
const MyForm = ({
myFormRef,
}) => (
<form id="myForm" ref={myFormRef} method="POST">
<input name="request_token" type="hidden" />
<input name="id" type="hidden" />
<input name="versionId" type="hidden" />
<input name="additionalId" type="hidden" />
</form>
);
export default MyForm;
We are using useRef hook to reference this form and calling it within another Component as follows.
const myFormRef = useRef();
<MyForm
myFormRef={myFormRef}
/>
The postData function at the end is in a js file.
Question is on this postData function.
This is triggered when a form is submitted via a button click.
It is all working fine where I am capturing correct details and able to submit the form.
The issue:
It is the format of how I am sending the data over which is the issue.
I am sending over details in following format in this form.
{
token,
id,
versionId,
additionalId
}
Instead I want to send it as:
{
token,
overallData: {
id,
versionId,
additionalId
}
}
How can I modify the request format to wrap inside overallData for the 3 fields (token is still outside) before submitting?
export const postData = (
myFormRef,
token,
myLink,
id,
versionId,
additionalId
) => {
const fields = {
request_token: token,
id,
versionId,
additionalId,
};
// checking if data exists for a key (example id or token) and remove if no value against the key.
[...myFormRef.current.children].forEach((child) => {
child.value = fields[child.name];
if (!child.value) {
myFormRef.current.removeChild(child);
}
});
// then submit
myFormRef.current.action = myLink;
myFormRef.current.submit();
};
Note: I have to stick with this style to use the form and useRef() due to other dependencies.
Thus looking for a way to possibly modify postData. Else advise other options. Thanks.
How would i get the amount of a something in a .json file?
I didn’t know how to put it, but I have a file named cookies.json it has 5k+ cookies in it, I need to know how to get the amount of cookies inside of it.
Path: ./pregenned/cookies.json
Inside of cookies.json:
{"codes":["cookies blah blah."]}
I would like to get the amount of cookies inside of codes!
Discord.js V13
How to convert Luxon DateTime format into string or numbers?
I am using the following code to set up a Luxon clock for my project use.
import { DateTime } from 'luxon';
import React, { useEffect, useState } from 'react';
interface IProps {
timezone: string;
format: string;
calendar?: string;
daysOffset?: number;
}
const LiveDateTime: React.FC<IProps> = ({
timezone,
daysOffset,
format,
calendar,
}) => {
const [timeLive, setTimeLive] = useState<DateTime>(DateTime.local());
useEffect(() => {
const interval = setInterval(() => {
setTimeLive(
DateTime.local()
.setZone(timezone)
.reconfigure({ outputCalendar: calendar })
.plus({ days: daysOffset })
);
}, 1000);
return () => clearInterval(interval);
}, [timezone]);
return <span>{timeLive?.toFormat(format)}</span>;
};
export default LiveDateTime;
Now, I am using this component in another place to define the month# of the current date.
const month = <LiveDateTime timezone={place?.timezone} format="M" />; // This returns '12' as a number in the UI (for December)
console.log(month)
getData(month); //this functions is supposed to return some data based on the given month.
//I get an error instead on this line that says, 'Argument of type 'Element' is not assignable to parameter of type 'number'.
When I print this in the console, I get an entire react.element object. I need to be able to use ’12’ as a number (for December) in getData()for the month variable. How can I covert this object into a number type or string type if necessary?
P.S. I tried using pareInt(). doesn’t work.
Html2Pdf JS – Rendering PDF while using a dark mode
I’m using the library Html2Pdf which works really well to allow my app’s users to download as PDF their invoices displayed in HTML. The problem encountered is when anyone need to download his/her invoice while using dark mode.
Switching from light to dark mode and reverse works by adding/removing a “disabled” attribute to the link tag :
<link href="path/to/css/app.css" rel="stylesheet" type="text/css" id="light" />
<link href="path/to/css/app-dark.css" rel="stylesheet" type="text/css" id="dark" disabled="disabled" />
Both files have the same css rules, only colours change.
If someone is using dark mode and need to download a PDF, html2pdf.js will print it exactly as it shown based on current css rules, therefore with black/gray backgrounds/fonts which isn’t really ideal for an invoice !
I already tried to change styles dynamically in the function which render the PDF after click, but of course the change is clearly visible to the user since it affects the whole page.
Therefore, my question is the following : How could I tell the function html2pdf() which css rules using without affecting the page itself ?
Is there a way to trim an array without creating a new array? [closed]
I want to use trim() to remove the white spaces from an array but I dont want to create a new array nor do I want to use map().
I have multiple random arrays that I want to iterate through and modify the existing array.
I have arrays that look like this.
var arr = [
{
"title": "sally",
"animals": {
"type":
[
[" dog"],
[" cat "]
]
}
},
{
"title": "bob",
"animals": {
"type":
[
[" cow "],
[" bald eagle "]
]
}
}
]
but I want them to look like this:
var arr = [
{
"title": "sally",
"animals": {
"type":
[
["dog"],
["cat"]
]
}
},
{
"title": "bob",
"animals": {
"type":
[
["cow"],
["bald eagle"]
]
}
}
]
I am using the split() function which is causing the values to add a space.
