i dont know why i get => duplicate key value violates unique constraint “data_inventorytoko_pkey”
Category: javascript
Category Added in a WPeMatico Campaign
How to pass specific item to another page HTML JavaScript Jquery
I want to pass specific items(paragraphs) to another page with button. I’m currently beginner in web development. Is there any way to do that? also I need to add those “like” buttons to every paragraph in my page. There’s a lot of them… So is there any way to add those “like” buttons(with same ids) to every paragraph and when I click “like” button it likes this specific paragraphs that’s next to it.
I made “like” button next to one of the paragraph. So far I’ve managed to save like buttons toggle state. Now I need to pass this specific “liked” paragraphitem to another page. Here’s my first page:
<!--Name of that file is "page1.html"-->
<p>A<span id="heart"><i class="fa fa-heart-o" aria-hidden="true" ></i></span></p>
<p>B</p>
<p>C</p>
<p>D</p>
<p>E</p>
<p>F</p>
<p>G</p>
<script>
$(window).on('load',function(){
if(localStorage.toggled != "with_toggle"){
$("#heart").html('<i class="fa fa-heart" aria-hidden="true"></i>');
}else{
$("#heart").html('<i class="fa fa-heart-o" aria-hidden="true"></i>');
}
});
$('#heart').toggleClass(localStorage.toggled);
$('#heart').on('click',function(){
if (localStorage.toggled != "with_toggle") {
$("#heart").html('<i class="fa fa-heart-o" aria-hidden="true"></i>');
$('#heart').toggleClass("with_toggle", true);
localStorage.toggled = "with_toggle";
} else {
$("#heart").html('<i class="fa fa-heart" aria-hidden="true"></i>');
$('#heart').toggleClass("with_toggle", false);
localStorage.toggled = "";
}
});
</script>
And here’s my second page:
<!--Name of that file is "page2.html"-->
<body>
<div>
<!--SAVED PARAGRAPHS/ITEMS--->
</div>
</body>
Get the 2nd Friday of a month with MomentJS
I am trying to get the nth Friday of a month with momentjs
where n is in the range [1,4]
So if a user supplies n as 2. Then I need to get the date for the second Friday of the month.
Here is what I tried with no sucess
let startingFrom = new Date("StartDateStringGoesHere");
let n=2;
let nthFriday = moment(startDate).isoWeekday(n); //I can't figure out how to resolve it here
Any ideas will be truly appreciated.
Add an opacity slider to a leaflet map generated in r
I would like to add an opacity slider to a leaflet map generated in r. It should change the opacity of the uppermost visible or all visible layers (either of the two, I don’t mind).
I found helpful advice in this thread:
Add opacity slider in R leaflet
This blog:
https://bookdown.org/nicohahn/making_maps_with_r5/docs/leaflet.html
and tried the following two packages, but none of the two seems to work:
So I figured out, this should be possible with htmltools. However, I struggle with the following
-
Dragging the slider moves the map too (while changing the opacity of the labels), as pointed out in Laurens comment here: Add opacity slider in R leaflet
-
I would like to change the opacity of the selected overlay layers. However I neither manage to get those values nor to change their opacity value.
Not helpful in this cause is, that I have almost no command of Javascript. Here is an example on how far I got. Would appreciate anyone pointing me into the right direction. I don’t even know how the access variables filled by htmltools javascript commands.
library(leaflet)
library(mapview) #to get the franconia dataset
library(htmltools)
colors <- colorFactor(palette = c("Red", "Green", "Blue"),
levels = c("Oberfranken","Mittelfranken", "Unterfranken"))
franconia %>% leaflet() %>%
addProviderTiles("CartoDB.Positron", group = "CartoDB.Positron") %>%
addPolygons(fillColor = ~colors(district),weight = 1, group = "Districts") %>%
addPolygons(label = ~NAME_ASCI,weight = 1, group = "Names", fillColor = "Grey") %>%
addLayersControl(baseGroups = "CartoDB.Positron",overlayGroups = c("Districts", "Names"),position = "topleft") %>%
addControl(html = "<input id="slide" type="range" min="0" max="1" step="0.1" value="0.5">") %>% # Add Slider
htmlwidgets::onRender("function(el,x,data){
var map = this;
var evthandler = function(e){
var layers = map.layerManager.getVisibleGroups();
Object.keys(layer).forEach(function(el){
layer[el]._container.style.opacity = +e.target.value;
});
};
$('#slide').on('mousemove',L.DomEvent.stopPropagation);
$('#slide').on('input', evthandler)}
")
How to Disable a Button after 1 click?
i am making an app of react-native and i need someone’s help with my stack of code
i need to disable the button after just one click. can someone help? the problem is, i am using props and because of that i am unable to disable property.
`
import React from "react";
import { View, Text, StyleSheet , Button, Image ,TouchableOpacity} from 'react-native'
import colors from "../../constants/colors";
const DoctorItem = props => {
return(
<TouchableOpacity onPress={props.onViewDetail}>
<View style={styles.dr}>
<Image style={styles.img} source={{uri:props.image}}/>
<Text style= {styles.title}>{props.title}</Text>
<Text style= {styles.price}>{props.price} RS </Text>
<View style = {styles.actions}>
<Button style={styles.btn} color={colors.primary} title="View Details " onPress={props.onViewDetail} />
<Button style = {styles.btn} color={colors.primary} title="To Registration" onPress={props.onRegistration} />
</View>
</View>
</TouchableOpacity>
);
}
const styles= StyleSheet.create({
dr:{
shadowColor: 'black',
shadowOpacity: 0.26,
shadowOffset: { width: 0, height: 2 },
shadowRadius: 8,
elevation: 5,
borderRadius: 10,
backgroundColor: 'white',
height: 300,
margin: 20,
},
img:{
width: '100%',
height: '60%'
},
title:{
fontSize: 18,
marginVertical : 4,
textAlign:'center',
fontFamily:'opsb'
},
price:{
fontSize : 14,
color:'#888',
textAlign:'center',
fontFamily:'ops'
},
actions:{
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
height: '25%',
paddingHorizontal: 20
},
btn : {
padding:5,
color:colors.primary
}
});
export default DoctorItem;
`
import React from 'react';
import { FlatList, Text } from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import dr from '../../store/reducers/dr';
import DoctorItem from '../../components/Doctor/DoctorItem';
import DrDetail from '../shop/DrDetail';
import * as appointActions from '../../store/actions/appoint';
import {HeaderButtons,Item} from 'react-navigation-header-buttons';
import CustomHeaderButton from '../../components/UI/headerButton';
import colors from '../../constants/colors';
const drscreen = props => {
const dr = useSelector(state => state.dr.availableDr);
const dispatch = useDispatch()
return (
<FlatList
data={dr}
keyExtractor={item => item.id}
renderItem={itemData => <DoctorItem
image= {itemData.item.imageUrl}
title={itemData.item.title}
price={itemData.item.price}
onViewDetail={()=>{
props.navigation.navigate('DoctorDetails',{
doctorId:itemData.item.id,
doctorTitle:itemData.item.title
});
}}
onRegistration={()=>{
dispatch(appointActions.appointDoc(itemData.item))
}}
/>}
/>
);
};
drscreen.navigationOptions = navData => {
return{
headerTitle: 'All Doctors',
headerRight: (
<HeaderButtons HeaderButtonComponent={CustomHeaderButton}>
<Item
title="Appoint"
iconName={"ios-checkmark-done-outline"}
onPress={() => {
navData.navigation.navigate ("Register")
}}
/>
</HeaderButtons>
)
}
};
export default drscreen;
`
Have tried using the disable function, but probably incorrectly. if anybody is familiar with this coding format, please help.
p5js // Change LIVE capture animation to a gif/moving animation
So lately I have done some exploration on the camera delay sort of effect on P5.js, and I just couldn’t wrap my head around something— When I try to replace the img source from “createCapture(VIDEO)” to “loadImage(“XXXX.gif”)” the moving GIF just stopped and became a static image and did not make the same performance as how a live camera-capturing would (to delay from centre out).
Does anyone have a better idea to run this code with GIF that achieves the same effect?
let cap;
let num =40;
let imgs = [];
let tileNum = 10;
function setup() {
createCanvas(windowWidth, windowHeight);
cap = createCapture(VIDEO);
cap.hide();
frameRate(24);
imageMode(CENTER);
}
function draw() {
background(255);
let size = min(cap.width,cap.height);
let img = createImage(size,size);
img.copy(cap,(cap.width-size),(cap.height-size)*6.5,size,size,0,0,img.width,img.height);
imgs.unshift(img);
if(imgs.length >num){
imgs.pop();
}
let stepX = width/tileNum;
let stepY = stepX * img.height /img.width;
let maxDist = dist(width/2,height/2,-10,-10);
if(imgs.length == num){
for(let y = 0; y< height+10; y += stepY){
for(let x =0; x < width+10; x+= stepX){
let dis = dist(width/2,height/2,x,y);
let index = Math.floor(dis/maxDist*num);
image(imgs[index%num],x,y,stepX,stepY);
}
}
}
}
Redux Invoke function linked to onClick in a different file
I have a code written in React+Redux for a table. The mapping of the table goes as follows:-
ListTemp.js
//editTemp function invoked in the mapping below
editTemp = (e, temp_id, temp_name, action_url, duration) => {
e.preventDefault();
this.props.getTemp(temp_id)
this.setState({
isEdit: true,
temp_id : temp_id
});
}
<table className = "table_style">
<thead>
<tr className = "table_style" >
<th className = "table_style">TempID</th>
<th className = "table_style">Name</th>
<th className = "table_style">CreatedOn</th>
<th className = "table_style">Action</th>
</tr>
</thead>
<tbody>
{
this.props.temp_list.map((temp,index)=>
<tr className = "table_style">
<th className = "table_style">{temp.temp_id}</th>
<td className = "table_style">{temp.temp_name}</td>
<td className = "table_style">{temp.created_on}</td>
<td>
<button className="btn btn-info" type = "submit" onClick = {(e) => this.editTemp(e, temp.temp_id, temp.temp_name, temp.action_url, temp.duration)}>
EDIT
</button>
</td>
</tr>
)
}
</tbody>
</table>
Because of the table having a lot of data, I paginated it and the mapping was moved to a different file changing the code as follows:-
ListTemp.js
showTemp = (temp) => {
var result = null;
if (temp.length > 0) {
result = temp.map((temp, index) => {
return <ListMapp key={index} temp={temp} index={index} />;
});
}
return result;
};
editTemp = (e, temp_id, temp_name, action_url, duration) => {
e.preventDefault();
this.props.getTemp(temp_id)
this.setState({
isEdit: true,
temp_id : temp_id
});
}
<table className = "table table-bordered table-hover">
<thead>
<tr className = "table_style" >
<th className = "table_style">TempID</th>
<th className = "table_style">Name</th>
<th className = "table_style">CreatedOn</th>
<th className = "table_style">Action</th>
</tr>
</thead>
<tbody>
{
this.showTemp(rowsPerPage)
}
</tbody>
</table>
And the mapping in this.showTemp comes from:-
ListMapp.js
class ListMapp extends Component {
render() {
var { template, index } = this.props;
return (
<tr className = "table_style">
<th className = "table_style">{temp.temp_id}</th>
<td className = "table_style">{temp.temp_name}</td>
<td className = "table_style">{temp.created_on}</td>
<td>
<td>
<button className="btn btn-info" type = "submit" onClick = {(e) => this.editTemp(e, temp.temp_id, temp.temp_name, temp.action_url, temp.duration)}>
EDIT
</button>
</td>
</tr>
);
}
}
export default ListMapp;
What is the simplest way in this situation to link/call/map the editTemp function in ListTemp.js from ListMapp.js? Also, please clarify what the return type(s) and payload will be here for invoking of the function if applicable.
Execute synchronously MessageBox show function in ExtJs-5
I want to execute a Ext.Msg.show() function synchronously in ExtJs-5
onButtonClick : function() {
1. some code...
2. Ext.Msg.show({
title : 'Confirm Please',
msg : 'Please be informed that record will only save when click ok.',
buttons : Ext.Msg.OKCANCEL,
icon : Ext.Msg.QUESTION,
fn : function(btn) {
if ('cancel' === btn) {
return;
}
}
});
3. other message box ...
4. other code ...
}
The above function execute synchronously each step 1, 2, 3 & 4 but doesn’t wait for user interaction on step 2. It directly move to step 3 and after that to step 4. But I want to execute step 3 only when user click on ok else terminate other below steps.
Can anybody check and let me know the possible code that I need to add to make it possible? Thanks
Vue unit testing with file dependency
I tried to adapt the vue unit testing guide but got stuck at file dependency.
I have a basic component something like that;
<template>
<div class="promoted-job-item-image">
<img :src="companyLogo" :alt="job.companyName">
</div>
</template>
<script>
import { ImagePaths } from '~/configs/imagePaths'
export default {
name: 'PromotedJobItem',
props: {
job: {
type: Object,
required: true
}
},
data () {
return {
logoPath: ImagePaths.LOGO_PATH
defaultLogo: ImagePaths.DEFAULT_LOGO
}
},
computed: {
companyLogo () {
if (!this.job?.imageName && !this.job?.fullPathImage) {
return this.defaultLogo
}
if (!this.job?.fullPathImage) {
return this.logoPath + this.job?.imageName
}
return this.job?.fullPathImage
}
}
}
</script>
configs/imagePaths.js
export const ImagePaths = Object.freeze({
LOGO_PATH: 'url/',
DEFAULT_LOGO: 'url/no-image.jpg'
})
and this my test;
import { mount } from '@vue/test-utils'
import PromotedJobItem from './index.vue'
test('should do a partial mock', () => {
const wrapper = mount(PromotedJobItem, {
propsData: {
job: {
id: 1,
companyName: 'Test',
fullPathImage: '',
imageName: 'test.jpg'
}
}
})
const image = wrapper.find('img')
expect(image.src).toBe('url/test.jpg')
})
this test gives me this error:
TypeError: Cannot read properties of undefined (reading ‘LOGO_PATH’)
I tried to use jest.mock but got same error. How can i mock ImagePaths.js file?
Uncaught TypeError: r.current.contains is not a function in kendo DriopDownList
While working with Kendo React, I wanted to add a Kendo DropDownList. I tried to fill the list with data like this:
Array(8) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…} ]
0: Object { id: -1, name: null }
1: Object { id: 1, name: "A" }
2: Object { id: 2, name: "B" }
3: Object { id: 3, name: "C" }
4: Object { id: 4, name: "D" }
5: Object { id: 5, name: "E" }
6: Object { id: 6, name: "F" }
7: Object { id: 77, name: "G" }
The data is fetched with axios and put inside useState in UseEffect:
const[sektor, setSektor] = useState([]);
...
...
useEffect(() => {
(async() =>{
try{
const resSektor = await services.getSektor();
console.log(resSektor.data.rlista); //JSON above is this console log
setSektor(resSektor.data.rlista);
}
catch(e){
console.log(e);
}
})();
}, []);
So, ‘sektor’ is used as an array of objects that will fill the Kendo dropdown:
<DropDownList data={sektor} value={sektorV} style={{marginTop:'2%'}} onChange={handleChangeSektor} textField="name" dataItemKey="id"/>
...
...
const handleChangeSektor = (event) => {
setSektorV(event.target.value);
};
‘sektorV’ is a state that saves the object that is picked from the KendoDropDown and is defined like this:
const[sektorV, setSektorV] = useState({id: -1, name: "All"});
Everything seems to be correct, but when I click on the DropDown the screen goes white and this is console logged:
Uncaught TypeError: r.current.contains is not a function
...
Uncaught TypeError: _utils__WEBPACK_IMPORTED_MODULE_2__.getItemValue(...) is null
I had a bunch of dropdowns in my current project and they all worked fine. Can anybody see the problem?
how to delete any array values from array on button click in each row
I want to delete row as well as delete that value from array but I want delete button on each row and need to delete any index value on button click
How can I insert delete button on each row and delete row as well as value from same array ?
var users = []
$(document).ready(loadTable);
function loadTable() {
for(var i = 0; i < users.length; i++){
for(var j = 0; j < users[i].length; j++){
//console.log(users[i][j])
}
{continue;}
}
}
$("#submit").on('click', function() {
var temp = [document.getElementById("id").value, document.getElementById("name").value]
users.push(temp)
loadTable ($("tbody").append("<tr>" +
"<td>" + $("#id").val() + "</td>" +
"<td>" + $("#name").val() + "</td>" +
//"<td>"+<button href="javascript:void(0);" class="remCF1 btn btn-small btn-danger">Remove</button>+"</td>"+
"</tr>"));
console.log(users)
});
table, th, td {
border: 1px solid black;
}
<html>
<head>
<title>Hello</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<input type="text" name="id" id="id">
<input type="text" name="name" id="name">
<button type="button" id="submit">Add</button>
<table id="demo">
<tbody>
</tbody>
</table>
</body>
</html>
Add separate button action for Bootstrap 3 collapse panel
In the following example when I click Add button the panel started collapsing along with panel.
But I want the panel should not collapse when I click add button. Because I have to write different action for button.
1. The panel should collapse when I click the title bar
2. When I click add button it should not collapse
Kindly drop a comment for further clarifications.

a.addinput {
background: #138eff;
padding: 5px;
margin: 0 0 0 15px;
color: #fff !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
<h4 class="panel-title">
<a role="button">
<span>Collapse Panel<a class="addinput" href="#">Add</a></span>
</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
<div class="panel-body">
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon
tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice
lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
</div>
</div>
</div>
</div>
selectize.js: Fetch all selected values from selectized dropdown
I hope everyone of you is in good health.
I have multiple select options have different classes and names and I am using selectize library to allow the user to search. I want to get the selected values on click of a button. Right now, I have tried the following code ……
$(window).bind("load", function()
{
var selectize_search_1 = $('.selectize_search_1').selectize(
{
sortField: 'text'
});
var selectize_search_2 = $('.selectize_search_2').selectize(
{
sortField: 'text'
});
});
function fetch_cars()
{
var cars_value = $('.selectize_search_1')[0].selectize.items;
alert (cars_value);
}
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.13.3/css/selectize.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.13.3/js/standalone/selectize.min.js"></script>
<select class="selectize_search_1" name="cars[]" required>
<option value="">Select Car</option>
<option value="C1">Car 1</option>
<option value="C2">Car 2</option>
<option value="C3">Car 3</option>
</select>
<br />
<select class="selectize_search_1" name="cars[]" required>
<option value="">Select Car</option>
<option value="C1">Car 1</option>
<option value="C2">Car 2</option>
<option value="C3">Car 3</option>
</select>
<hr />
<button type="button" onclick="fetch_cars();">Fetch Cars</button>
So, lets suppose i select car 1 and car 2 from the dropdowns, but using the above code, it only return me the selected value in the first dropdown but not both selected values. Kindly help.
NFT Marketplace cards using ReactJS
enter image description hereI am new to blockchain and trying to learn,I have created NFT marketplace application where the functionalities like minting, selling and buying is working fine. But, in the UI after putting it for sale the price of NFT is showing same for all the minted NFTs. I have used {Web3.utils.fromWei(String(price), “ether”)}.120000 in the code to display the price of NFT but it is not reflecting the price from blockchain.
<CardContent className={classes.content}>
<div className={classes.title}>
<Typography
className={"MuiTypography--heading"}
variant={"h5"}
gutterBottom
>
{name}
</Typography>
<Chip
size="small"
disabled={true}
label="Selling"
className={classes.badge}
/>
</div>
<Typography variant="h6" className={classes.price}>
<SvgIcon
component={EthereumLogo}
viewBox="0 0 400 426.6"
titleAccess="ETH"
/>
<span{Web3.utils.fromWei(String(price), "ether")}.120000</span>
</Typography>
Not able to register and bind addEventListener in Dom element
if((documentStatus == "Draft" || documentStatus == "Published") || this.context.pageContext.user.email == event.listItem["_values"].get("Author")[0].email){
var btnID = "btnClick" + itemID;
event.domElement.innerHTML = `<button class='btn' type='button' id='${btnID}'><span class='buttonIcon'></span></button>`;
let clickEvent= document.querySelector(`#${btnID}`);
category="button";
clickEvent.addEventListener('click', (e: Event) => this.btn1ClickEvent(itemID,commiteePolicyApprover,documentType,category,authers,reviewers,approvers,revisionPeriod,keyvaluepair));
}
if(documentStatus == "Published" || this.context.pageContext.user.email == event.listItem["_values"].get("Author")[0].email){
var buttonID = "AttestationIconbtnClick" + itemID;
event.domElement.innerHTML += `<button class='btn' type='button' id='${buttonID}'><span class='AttestationIcon'></span></button>`;
let clickEvent= document.querySelector(`#${buttonID}`);
category="attest"
clickEvent.addEventListener('click', (e: Event) => this.btnClickEvent(itemID,commiteePolicyApprover,documentType,category,authers,reviewers,approvers,revisionPeriod,keyvaluepair));
}
Second button is working find but first button event not triggred
