How to check if a Gun unordered list is empty? - gun

Given the following, how would one go about determining if the machines list is empty in order to add a machine?
let gun = new Gun();
let machines = gun.get('machines');
How do I check if the machines list is empty?

This from Mark Nadal:
// machineId and location defined elsewhere
machines.val(table => {
if (Gun.obj.empty(table, '_') {
// table is empty so we can add something to it
let machine = gun.get('machine/' + machineId);
machine.put({machineId, location}};
machines.set(machine);
} else {
// table is not empty
})
table is a data node that has all the row pointers in it (not the actual sub-objects)
so if table has 0 items on it, then it is empty! Or if table is null or undefined
HOWEVER, gun has its {_: {...}} meta data it includes on every node, so you need to ignore that.
Gun.obj.empty({}) tests if an object is empty (you can use lodash or something else), the second parameter tells it to IGNORE a key, like in this case '_'. So it will still say that yes it is empty if it has 0 properties other than the metadata property.

Related

Azure Workbook parameter for resource and resource group

I've been defeated by Kusto on what I thought to be a simple query...
I'm making my first workbook and playing with parameters. I can list and select a Resource Group, but I can't make the following parameter (Virtual Machines) populate with the VMs when more than one Resource Group is selected. The ResourceGroup passes a comma delineated string of the group names as a property resourcegroup just fine. I cannot figure out how to translate that string into a usable where-statement. My query works just fine when I manually string several Resource Groups together so I assume I'm getting burned by my understanding of let and arrays in Kusto. If there is a better way of doing what I'm trying to do, please let me know.
//This will work so long as 1 Resource Group is passed from the previous parameter
resources
| where resourceGroup in ('{ResourceGroup:resourcegroup}') and type =~ microsoft.compute/virtualmachines'
| project value = id , label = name
I've figured out I can get a proper array with split('{ResourceGroup:resourcegroup}',","), but, again, I haven't been able to marry up that object with a where-statement.
Any help is much appreciated!
in https://github.com/microsoft/Application-Insights-Workbooks/blob/master/Documentation/Parameters/DropDown.md#special-casing-all
NORMALLY there is a way to do this:
let resourceGroups = dynamic([{ResourceGroup:resourcegroup}]);// turns even an empty string into a valid array
resources
| where (array_length(resourceGroups)==0 // allows 0 length array to be "all"
or resourceGroup in (resourceGroups)) // or filters to only those in the set
and type =~ microsoft.compute/virtualmachines'
| project value = id , label = name
however, i don't think Azure Resource Graph allows using let this way?
if you get an error that let isn't allowed, you'll have to do that dynamic thing inline a couple times instead:
resources
| where (array_length(dynamic([{ResourceGroup:resourcegroup}]))==0 // allows 0 length array to be "all"
or resourceGroup in (dynamic([{ResourceGroup:resourcegroup}]))) // or filters to only those in the set
and type =~ microsoft.compute/virtualmachines'
| project value = id , label = name

Using a variable content to generate a variable name

I have a script for a game server, and I'm stuck in some shit that look easy to solve
Exists a variable which receive content dynamically based on user action, so we will name this variable: example, and attrib some random value
local example = Potato
Then I have a function which sends a message to a discord webhook
SendWebhookMessage(varNAME, "Message content")
Where varname is the variable containing the link of the webhook.
I want to use the content of variable example to generate the variable name like
webhook_ds_example
So in this case it will be
webhook_ds_potato
Hope you guys could understand and help to solve
local menu = { name = "Baú" }
local cb_take = function(idname)
local citem = chest.items[idname]
local amount = vRP.prompt(source,"Quantidade:","")
amount = parseInt(amount)
if amount >= 0 and amount <= citem.amount then
local new_weight = vRP.getInventoryWeight(user_id)+vRP.getItemWeight(idname)*amount
if new_weight <= vRP.getInventoryMaxWeight(user_id) then
citem.amount = citem.amount - amount
local temp = os.date("%x %X")
vRP.logs("savedata/bau.txt","Bau: "..name.." [ID]: "..user_id.." /"..temp.." [FUNÇÃO]: Retirar / [ITEM]: "..idname.." / [QTD]: "..amount)
local webhook_bau_fac1 = ""
local webhook_bau_fac2 = ""
local webhook_bau_fac3 = ""
local webhook_bau_fac4 = ""
SendWebhookMessage(webhook_bau_..name,"```prolog\n[ID]: "..user_id.." "..identity.name.." "..identity.firstname.." \n[GUARDOU]: "..vRP.format(parseInt(amount)).." "..vRP.itemNameList(itemName).." \n[BAU]: "..chestName.." "..os.date("\n[Data]: %d/%m/%Y [Hora]: %H:%M:%S").." \r```")
You are looking for tables, which let you store lots of different named values in one variable.
local webhook_bau -- make a variable
-- create a table with 4 entries, put it in the variable
webhook_bau = {fac1="", fac2="", fac3="", fac4=""}
-- if you want to start with an empty table, use {} instead
-- change one of them based on the name
webhook_bau[name] = "something"
-- use one of the entries based on the name
SendWebhookMessage(webhook_bau[name], "whatever you want to send")
Table entries "magically" appear when you use them, you don't have to create them first. If you access an entry that doesn't exist, you will read the value nil. You can also delete an entry by putting nil in the entry.
In the example you provided, you have:
SendWebhookMessage(webhook_bau_..name,"```prolog\n[ID]: "..user_id.." "..identity.name.." "..identity.firstname.." \n[GUARDOU]: "..vRP.format(parseInt(amount)).." "..vRP.itemNameList(itemName).." \n[BAU]: "..chestName.." "..os.date("\n[Data]: %d/%m/%Y [Hora]: %H:%M:%S").." \r```")
You are missing quotes around webhook_bau_ which would result in an error trying to concatenate a nil variable.
I'm also not seeing where name is set (only menu.name), so I'm assuming you have that elsewhere in your program, if not, that will also be nil, so just make sure that is set somewhere as well.

Terraform: How Do I Setup a Resource Based on Configuration

So here is what I want as a module in Pseudo Code:
IF UseCustom, Create AWS Launch Config With One Custom EBS Device and One Generic EBS Device
ELSE Create AWS Launch Config With One Generic EBS Device
I am aware that I can use the 'count' function within a resource to decide whether it is created or not... So I currently have:
resource aws_launch_configuration "basic_launch_config" {
count = var.boolean ? 0 : 1
blah
}
resource aws_launch_configuration "custom_launch_config" {
count = var.boolean ? 1 : 0
blah
blah
}
Which is great, now it creates the right Launch configuration based on my 'boolean' variable... But in order to then create the AutoScalingGroup using that Launch Configuration, I need the Launch Configuration Name. I know what you're thinking, just output it and grab it, you moron! Well of course I'm outputting it:
output "name" {
description = "The Name of the Default Launch Configuration"
value = aws_launch_configuration.basic_launch_config.*.name
}
output "name" {
description = "The Name of the Custom Launch Configuration"
value = aws_launch_configuration.custom_launch_config.*.name
}
But how the heck do I know from the higher area that I'm calling the module that creates the Launch Configuration and Then the Auto Scaling Group which output to use for passing into the ASG???
Is there a different way to grab the value I want that I'm overlooking? I'm new to Terraform and the whole no real conditional thing is really throwing me for a loop.
Terraform: How to conditionally assign an EBS volume to an ECS Cluster
This seemed to be the cleanest way I could find, using a ternary operator:
output "name {
description = "The Name of the Launch Configuration"
value = "${(var.booleanVar) == 0 ? aws_launch_configuration.default_launch_config.*.name : aws_launch_configuration.custom_launch_config.*.name}
}
Let me know if there is a better way!
You can use the same variable you used to decide which resource to enable to select the appropriate result:
output "name" {
value = var.boolean ? aws_launch_configuration.custom_launch_config[0].name : aws_launch_configuration.basic_launch_config[0].name
}
Another option, which is a little more terse but arguably also a little less clear to a future reader, is to exploit the fact that you will always have one list of zero elements and one list with one elements, like this:
output "name" {
value = concat(
aws_launch_configuration.basic_launch_config[*].name,
aws_launch_configuration.custom_launch_config[*].name,
)[0]
}
Concatenating these two lists will always produce a single-item list due to how the count expressions are written, and so we can use [0] to take that single item and return it.

Resetting a Bacon property on value changed to empty

TL;DR
How can I reset emailProfile/aliasProfile when email/alias is cleared after having a value?
Slightly longer version
I have a form that has inputs for email and alias. Neither is mandatory. But, if you fill in the alias field, it might require the email as well, if the alias is reserved.
So far so good, I have the pipe setup from an empty form, up until checking if an alias is reserved and whether the given email matches up. This works correctly and reliably.
Where my setup falters, is when after filling in a correct e-mail I clear the email. The status of emailProfile remains status quo (last server response).
What I want to achieve, is to clear emailProfile when email has no value (or actually when validEmail is false), but in all other cases return the last server response.
The direct (and only) way to tackle the problem I can think of, would be to drop the filter and return null from the lookup function when validation fails, but there has to be a better way, right?
// Functions that can be assumed to work as they should (they do):
// form.findInput, validAlias,validEmail, compose,
// fetchProfilesByAlias, fetchProfileByEmail
var alias = Bacon.fromEventTarget(form.findInput("alias"), "change").
merge(
Bacon.fromEventTarget(form.findInput("alias"), "keyup")
).
map(".target").
map(".value").
skipDuplicates().
toProperty(form.findInput("alias").value);
var email = Bacon.fromEventTarget(form.findInput("email"), "change").
merge(
Bacon.fromEventTarget(form.findInput("email"), "keyup")
).
map(".target").
map(".value").
skipDuplicates().
toProperty(form.findInput("email").value);
var aliasProfiles = alias.
debounce(600).
filter(validAlias).
flatMapLatest(compose(Bacon.fromPromise.bind(Bacon), fetchProfilesByAlias)).
toProperty(null);
var emailProfile = email.
debounce(600).
filter(validEmail).
flatMapLatest(compose(Bacon.fromPromise.bind(Bacon), fetchProfileByEmail)).
toProperty(null);
This is the most straightforward way I can think of.
var emailProfile = email.
debounce(600).
flatMapLatest(function(email) {
if (validEmail(email)) {
return Bacon.fromPromise(fetchProfileByEmail(email))
} else {
return null
}
}).
toProperty(null)
Pretty much the same that you already discovered, except the if is not in the lookup function :)

grid filter in dojo

can any one help with filtering multiple condition in dojo grid.
im using grid.DataGrid and json data.
data1 = {items: [ {"id":1,"media":"PRINT",pt:"Yellow Directory"},
{"id":2,"media":"DIGITAL",pt:"Social Media"},{id":3,"media":"DIGITAL",pt:"Yellow Online"}
],identifier: "id"};
a=1,b=2;
grid.filter({id:a,id:b})
the above line is just displaying the record with b value.
i need the record with both the values.
can any one help me with this.???
So you want the records that have any of the specified ids?
It comes down to the capabilities of the store you're using. If you're using a Memory store with SimpleQueryEngine, then you can specify a regex or an object with a test function instead:
grid.filter({id: {
test: function(x) {
return x === 'a' || x === 'b';
}
}});
If you're using JsonRest store, then you get to choose how your queries are processed server-side so you could potentially pass in an array of interesting values and handle that in your own way on the server. (i.e. filter({id:[a,b]}))