How to change all hidden values to false in each state object? - redux

I am a little bit stumped on completing this without my solution looking hacky. Any recommendations? Is this easier to do in the reducer or should I keep this strictly in the action?
Surely this is easier than what I am attempting.
const initialState = {
unlockWebsite: {
hidden: false,
state: 'accepted',
completedCount: 60,
completedIds: ['priceYourHome', 'websiteInformation'],
totalTasks: 6,
},
prepareHome: {
hidden: true,
state: 'default',
completedCount: 0,
completedIds: [],
totalTasks: 6,
},
findingBuyers: {
hidden: true,
state: 'default',
completedCount: 0,
completedIds: [],
totalTasks: 6,
},
negotiateOffers: {
hidden: true,
state: 'default',
completedCount: 0,
completedIds: [],
totalTasks: 6,
},
closeHome: {
hidden: true,
state: 'default',
completedCount: 0,
completedIds: [],
totalTasks: 6,
},
};

Take an example where the initial state is
const initState = {"a":{no_change:"hi",change:"ha"},"b":{no_change:"hi",change:"ha"},"c":{no_change:"hi",change:"ha"}}
Say we want to update all of the change properties in all of a, b and c from "ha" to something else.
I can just create an action type in my reducer called CHANGE_TO_FALSE.
case 'CHANGE_TO_FALSE':
const falsifier = Object.keys(state).map((key,index) =>({[key]:{...state[key],change:"hoo"}}))
return Object.assign({}, ...falsifier )
Now, instead of "ha", the change property will hold "hoo".
State after change:
{"a":{"no_change":"hi","change":"hoo"},"b":{"no_change":"hi","change":"hoo"},"c":{"no_change":"hi","change":"hoo"}}
I'm not sure there's a simpler way to achieve this. This looks clean to me.

Related

Cypress- How can we list key names under certain key (not values of these keys)

I want to store key names under a certain key. Here is an example:
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
}
}}
There is no problem to reach end values like "sun1". I want to reach the key names under "image" as "src", "name" ...; and store them as an array. I don't need their values. How can I do that? I'm parsing response in "then" structure; so this type of answer would be great!
Thanks
The image tag is deeply nested in the outer object.
This is how I would approach it
cy.request(...)
.then(data => {
const imageKeys = Cypress._.keys(data.widget.image)
expect(imageKeys).to.deep.eq(['src', 'name', 'hOffset', 'vOffset', 'alignment'])
})
You can also chain commands,
cy.request(...)
.its('widget.image')
.then(Cypress._.keys)
.should(imageKeys => {
expect(imageKeys).to.deep.eq(['src', 'name', 'hOffset', 'vOffset', 'alignment'])
})
JavaScript has Object.keys(), which will return an array containing the keys in that object.
const myObj = {
foo: true,
bar: false,
baz: 'string'
}
cy.then(() => {
const keys = Object.keys(myObj);
console.log(keys) // ['foo', 'bar', 'baz']
});
If you needed both keys and values, you can use Object.entries().

React spring loop won't run with delay

I'm using these styles with react spring, and after it runs one time, it won't run anymore, if I remove the delay it works fine, why is that?
const styles = useSpring({
loop: true,
to: [
{ opacity: 0, color: '#53317e' },
{ opacity: 1, color: 'white' },
],
from: { opacity: 1, color: 'white' },
delay: 1000,
})
lot of time gone but I had same issue.
To fix it, instead of using
const styles = useSpring({
loop: true,
delay: 2000,
from: {...},
to: [{...}, {...}, ...]
});
I used syntax with passing function instead of object
const [styles, api] = useSpring(() => ({ ... }) )
And then delay prop stops disabling my loop

configuration to discover peers using mdns

I am trying to make this example work. It is supposed to create two nodes with mdns support. Mdns is supposed to announce the peer every second, each peer is setup to print a statement once a peer is found.
When running it, the console output is merely empty. It prints out some garbage error in my concern: (node:51841) ExperimentalWarning: Readable[Symbol.asyncIterator] is an experimental feature. This feature could change at any time
How do i enable debugging log so that i can try to understand what is going on under the hood ?
I would like to verify the mdns announce packets are issued, and possibly received, or not.
Alternatively, i am trying to use the bootstrap module to begin over wan peers, though expect it to be much slower, thus i would prefer to use mdns.
I tried to add various configuration and modules without much success, it is not clear to me if i am required to use the gossip module if i only want to announce some data on the dht. stuff like that.
any help is appreciated.
const Libp2p = require('libp2p')
const MulticastDNS = require('libp2p-mdns')
const KadDHT = require('libp2p-kad-dht')
const Bootstrap = require('libp2p-bootstrap')
const TCP = require('libp2p-tcp')
const Mplex = require('libp2p-mplex')
const { NOISE } = require('libp2p-noise')
const GossipSub = require('libp2p-gossipsub')
const { FaultTolerance } = require('libp2p/src/transport-manager')
const CID = require('cids')
const all = require('it-all')
const delay = require('delay')
const bootstrapers = [
'/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ',
'/ip4/104.236.176.52/tcp/4001/p2p/QmSoLnSGccFuZQJzRadHn95W2CrSFmZuTdDWP8HXaHca9z',
'/ip4/104.236.179.241/tcp/4001/p2p/QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM',
'/ip4/162.243.248.213/tcp/4001/p2p/QmSoLueR4xBeUbY9WZ9xGUUxunbKWcrNFTDAadQJmocnWm',
'/ip4/128.199.219.111/tcp/4001/p2p/QmSoLSafTMBsPKadTEgaXctDQVcqN88CNLHXMkTNwMKPnu',
'/ip4/104.236.76.40/tcp/4001/p2p/QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64',
'/ip4/178.62.158.247/tcp/4001/p2p/QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd',
'/ip4/178.62.61.185/tcp/4001/p2p/QmSoLMeWqB7YGVLJN3pNLQpmmEk35v6wYtsMGLzSr5QBU3',
'/ip4/104.236.151.122/tcp/4001/p2p/QmSoLju6m7xTh3DuokvT3886QRYqxAzb1kShaanJgW36yx'
]
const createNode = () => {
return Libp2p.create({
addresses: {
listen: ['/ip4/0.0.0.0/tcp/0']
},
modules: {
transport: [ TCP ],
streamMuxer: [ Mplex ],
connEncryption: [ NOISE ],
// peerDiscovery: [ MulticastDNS ],
// peerDiscovery: [ MulticastDNS ],
peerDiscovery: [ Bootstrap, MulticastDNS ],
dht: KadDHT,
pubsub: GossipSub
},
transportManager: {
faultTolerance: FaultTolerance.NO_FATAL
},
config: {
peerDiscovery: {
autoDial: true,
[MulticastDNS.tag]: {
broadcast: true,
interval: 1000,
enabled: true
},
[Bootstrap.tag]: {
interval: 1000,
enabled: true,
list: bootstrapers
},
[GossipSub.tag]: {
enabled: true,
emitSelf: true,
signMessages: true,
strictSigning: true
},
mdns: {
broadcast: true,
interval: 1000,
enabled: true
},
bootstrap: {
interval: 1000,
enabled: true,
list: bootstrapers
},
pubsub: {
enabled: true,
emitSelf: true,
signMessages: true,
strictSigning: true
},
},
dht: {
enabled: true
}
}
})
}
( async () => {
const [node1, node2] = await Promise.all([
createNode(),
createNode()
])
node1.on('peer:discovery', (peer) => console.log('Discovered:', peer.id.toB58String()))
node2.on('peer:discovery', (peer) => console.log('Discovered:', peer.id.toB58String()))
await Promise.all([
node1.start(),
node2.start()
])
// const cid = new CID('QmTp9VkYvnHyrqKQuFPiuZkiX9gPcqj6x5LJ1rmWuSySnL')
// await node1.contentRouting.provide(cid)
// await delay(3000)
// console.log("looking for providers...")
// const providers = await all(node2.contentRouting.findProviders(cid, { timeout: 5000 }))
// console.log('Found provider:', providers[0].id.toB58String())
})()
edit: found out i could use DEBUG environment variable to print debug statements, thouhg i still have problems with event system.
Logging
To enable debugging, configure the DEBUG environment variable. Start with DEBUG=*, it prints log lines like:
mss:select select: read "/noise" +1ms
libp2p:upgrader encrypting outbound connection to {"id":"QmRiNVP5NSGJPHLo256vNMTYW9VzsTKYm4dRG3GoJj37ah"} +12ms
libp2p:noise Stage 0 - Initiator starting to send first message. +14ms
Select stuff you want to print out using DEBUG=*noise ...
events
The probleme in OP code is that the peer:discovery event has an argument of type PeerID, not Peer. Thus the statements console.log('Discovered:', peer.id.toB58String()) is incorrect and should be replaced with console.log('Discovered:', peer.toB58String())
But one may have noticed the OP did not provide any error messages related to that. That happens because those event handlers are handled with an error silencer.
I am unsure what is going on, though, runnning below code will not trigger the exception with the "yo" message.
node1.on('peer:discovery', (peerID) => {
console.log(node1.peerId.toB58String(), "discovered:", peerID.toB58String())
throw "yo"
})
Related source code
const Libp2p = require('libp2p')
const MulticastDNS = require('libp2p-mdns')
const KadDHT = require('libp2p-kad-dht')
const Bootstrap = require('libp2p-bootstrap')
const TCP = require('libp2p-tcp')
const Mplex = require('libp2p-mplex')
const { NOISE } = require('libp2p-noise')
const CID = require('cids')
const all = require('it-all')
const delay = require('delay')
const bootstrapers = [
'/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ',
'/ip4/104.236.176.52/tcp/4001/p2p/QmSoLnSGccFuZQJzRadHn95W2CrSFmZuTdDWP8HXaHca9z',
'/ip4/104.236.179.241/tcp/4001/p2p/QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM',
'/ip4/162.243.248.213/tcp/4001/p2p/QmSoLueR4xBeUbY9WZ9xGUUxunbKWcrNFTDAadQJmocnWm',
'/ip4/128.199.219.111/tcp/4001/p2p/QmSoLSafTMBsPKadTEgaXctDQVcqN88CNLHXMkTNwMKPnu',
'/ip4/104.236.76.40/tcp/4001/p2p/QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64',
'/ip4/178.62.158.247/tcp/4001/p2p/QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd',
'/ip4/178.62.61.185/tcp/4001/p2p/QmSoLMeWqB7YGVLJN3pNLQpmmEk35v6wYtsMGLzSr5QBU3',
'/ip4/104.236.151.122/tcp/4001/p2p/QmSoLju6m7xTh3DuokvT3886QRYqxAzb1kShaanJgW36yx'
]
const createNode = () => {
return Libp2p.create({
addresses: {
listen: ['/ip4/0.0.0.0/tcp/0']
},
modules: {
transport: [ TCP ],
streamMuxer: [ Mplex ],
connEncryption: [ NOISE ],
// peerDiscovery: [ MulticastDNS ],
peerDiscovery: [ MulticastDNS ],
// peerDiscovery: [ Bootstrap, MulticastDNS ],
dht: KadDHT,
// pubsub: GossipSub
},
// transportManager: {
// faultTolerance: FaultTolerance.NO_FATAL
// },
config: {
peerDiscovery: {
autoDial: true,
[MulticastDNS.tag]: {
broadcast: true,
interval: 1000,
enabled: true
},
[Bootstrap.tag]: {
interval: 1000,
enabled: true,
list: bootstrapers
},
},
dht: {
enabled: true
}
}
})
}
( async () => {
const [node1, node2] = await Promise.all([
createNode(),
createNode()
])
node1.on('peer:discovery', (peerID) => {
console.log(node1.peerId.toB58String(), "discovered:", peerID.toB58String())
})
node2.on('peer:discovery', (peerID) => {
console.log(node2.peerId.toB58String(), "discovered:", peerID.toB58String())
})
node1.on('error', console.error)
node2.on('error', console.error)
await Promise.all([
node1.start(),
node2.start()
])
})()

highstock strange behavior scrollbar

i made a chart, with highstock, that contains the enabled scrollbar but when i focus the mouse on it, it happens a strange behavoir: the chart goes down and covers the scrollbar.
the options that i used are:
var options = {
chart: {
title: {
text: ''
},
renderTo: 'containerGrafico'
},
yAxis: {
title: '',
tickPixelInterval: 30,
labels: {
formatter: function () {
return '€ ' + Highcharts.numberFormat(this.value, 0);
}
}
},
xAxis: {
categories: seriesMesi,
labels: {
formatter: function () {
return arrayMesi[this.value.substring(4, 6)] + " " + this.value.substring(0, 4);
}
},
max: 6
},
scrollbar: {
enabled: true,
barBackgroundColor: 'transparent',
barBorderRadius: 7,
barBorderWidth: 0,
buttonBackgroundColor: 'gray',
buttonBorderWidth: 0,
buttonArrowColor: 'yellow',
buttonBorderRadius: 7,
rifleColor: 'transparent',
trackBackgroundColor: 'white',
trackBorderWidth: 1,
trackBorderColor: 'silver',
trackBorderRadius: 7
},
series: [
{
name: 'Totale Versato',
color: '#96B7D8',
type: 'column'
},
{
name: 'Prelievi',
color: '#D1D1D1',
type: 'column'
}]
};
anybody can tell me where i'm wrong?
thank you very much
Cinzia
In general, categorized axis for Highstock isn't supported.
Anyway, for me it works properly, see: http://jsfiddle.net/3bQne/1004/
Try to update to latest (1.3.10) version and remove categories. Or use Highcharts with categorized axis.
If none of above will help - recreate issue on jsFiddle.

How to design search bar?

I have a search bar on the top of a page where user can type any word. I want to display the names of the songs which contain the word typed by user. How to design this using enyo.js?
Made a little fiddle with comments especialy for you :)
http://jsfiddle.net/joopmicroop/NEYQC/
enyo.kind({
name: 'App',
kind: enyo.Control,
components: [
{kind: 'FittableRows', components:[
{name: 'footer', kind: 'onyx.Toolbar', components: [
{kind: "onyx.InputDecorator", components: [
{kind: "onyx.Input", name:"inputfield", placeholder: "Search number"},
]},
{kind: "onyx.Button", content: "Search", ontap: "search"},
]},
{kind: "List", fit: true, name:'list', classes:'list', count: 20, fixedHeight: true, onSetupItem: "setupItem", components: [
{name: "item", classes:'listitem', ontap: "itemTap", components: [
{tag:'span', name: "name", content:"song name"},
{tag:'span', name: "index", content:"", style:'float:right;'}
]},
]},
]}
],
searchstring:'',
search: function(inSender, inEvent) {
console.log('search tapped');
console.log('inputfield value: ', this.$.inputfield.getValue());
console.log('list: ', this.$.item);
console.log('searchstring: ',this.searchstring);
this.searchstring = this.$.inputfield.getValue();
this.$.list.refresh();
},
setupItem: function(inSender, inEvent) {
// just to have something to fill in
var data = ['alibaba', 'alibobo', 'alibibi'];
this.$.index.setContent(inEvent.index);
this.$.name.setContent(data[inEvent.index %3]);
// if searchstring isn't emty get to work
if(this.searchstring != ''){
var regex = new RegExp(this.searchstring); // = /searchstrin/g
if(this.$.name.getContent().search(regex) != -1){ // -1 = not found
this.$.list.select(inEvent.index, true); // set state selected true
}
// if selected = true change add css class
this.$.item.addRemoveClass("listitemselected", inSender.isSelected(inEvent.index));
}
},
itemTap: function(inSender, inEvent) {
alert("You tapped on row: " + inEvent.index);
},
});​
i got a sample posted here as part of my enyojs tutorial, but it uses a third party library called taffyDB here

Resources