How to write Key Value Pairs in Map in a Loop without overwriting them? - dictionary

the following is my problem:
I do a select on my database and want to write the values of every record i get in a map. When i do this, i only have the values of one record in my map, because the put() function overwrites the entries everytime the loop starts again. Since I have to transfer the Key:Value pairs via JSON into my Javascript and write something into a field for every Key:Value pair, an ArrayList is not an option.
I've already tried to convert a ArrayList, which contains the Map, to a Map or to a String and then to Map, but i failed.
EDIT:
Here´s my Code
def valueArray = new ArrayList();
def recordValues = [:]
while (rs.next())
{
fremdlKorr = rs.getFloatValue(1)
leistungKorr = rs.getFloatValue(2)
materialKorr = rs.getFloatValue(3)
strid = rs.getStringValue(4)
recordValues.put("strid", strid);
recordValues.put("material", materialKorr);
recordValues.put("fremdl", fremdlKorr);
recordValues.put("leistung", leistungKorr);
valueArray.add(korrekturWerte);
}
The ArrayList was just a test, i dont want to have an ArrayList, i need a Map.

The code as written, will give you a list of maps, but the maps will all contain the values of the last row. The reaons is the def recordValues = [:] that is outside of the while loop. So you basically add always the same map to the list and the map values get overwritten each loop.
While moving the code, would fix the problem, I'd use Sql instead. That all boils down to:
def valueArray = sql.rows("select strid, material, fremdl, leistung from ...")

Related

Populating an Apex Map from a SOQL query

// I have a custom metadata object named boatNames__mdt and I'm using two methods to get a list of picklist values in a String[];
First Method
Map<String, boatNames__mdt> mapEd = boatNames__mdt.getAll();
string boatTypes = (string) mapEd.values()[0].BoatPick__c;
// BoatPick__c is a textarea field (Eg: 'Yacht, Sailboat')
string[] btWRAP = new string[]{};
**btWRAP**.addAll(boatTypes.normalizeSpace().split(','));
Second Method
string[] strL = new string[]{};
Schema.DescribeFieldResult dfr = Schema.SObjectType.boatNames__mdt.fields.BoatTypesPicklist__c;
// BoatTypesPicklist__c is a picklist field (Picklist Values: 'Yacht, Sailboat')
PicklistEntry[] picklistValues = dfr.getPicklistValues();
for (PicklistEntry pick : picklistValues){
**strl**.add((string) pick.getLabel());
}
Map with SOQL query
Map<Id, BoatType__c> boatMap = new Map<Id, BoatType__c>
([Select Id, Name from BoatType__c Where Name in :btWRAP]);
When I run the above Map with SOQL query(btWRAP[]) no records show up.
But when I used it using the strl[] records do show up.
I'm stunned!
Can you please explain why two identical String[] when used in exact SOQL queries behave so different?
You are comparing different things so you get different results. Multiple fails here.
mapEd.values()[0].BoatPick__c - this takes 1st element. At random. Are you sure you have only 1 element in there? You might be getting random results, good luck debugging.
normalizeSpace() and trim() - you trim the string but after splitting you don't trim the components. You don't have Sailboat, you have {space}Sailboat
String s = 'Yacht, Sailboat';
List<String> tokens = s.normalizeSpace().split(',');
System.debug(tokens.size()); // "2"
System.debug(tokens); // "(Yacht, Sailboat)", note the extra space
System.debug(tokens[1].charAt(0)); // "32", space's ASCII number
Try splitting by "comma, optionally followed by space/tab/newline/any other whitespace symbol": s.split(',\\s*'); or call normalize in a loop over the split's results?
pick.getLabel() - in code never compare using picklist labels unless you really know what you're doing. Somebody will translate the org to German, French etc and your code will break. Compare to getValue()

Changing values to combobox from an array

I need to load values from an array to a combobox, with this code it loads only the last value of the array? Can anyone help me please.
for(int i =0; i<lines.size(); i++) {
resultArray[i] = lines.get(i).split("\t");
Laptops[i] = resultArray[i][0];
ObservableList<String> option = FXCollections.observableArrayList(Laptops[i].toString());
cbx1.setValue("");
cbx1.setItems(option);
cbx2.setValue("");
cbx2.setItems(option);
cbx3.setValue("");
cbx3.setItems(option);
}
In your loop, you are creating a brand new List on each iteration. So when you call setItems() on your ComboBox, the option list only has that one item in it.
There are several other issues with your loop, but once you have a valid array, populating a ComboBox with it is quite simple using the Arrays.asList() method:
ObservableList<String> option = FXCollections.observableList(Arrays.asList(resultArray));
cbx1.setItems(option);
That being said, I doubt you're getting a proper array with your line:
resultArray[i] = lines.get(i).split("\t");
Without knowing what lines actually is in your code, it's difficult to address this specifically, but it looks like you could skip the whole resultArray altogether and just use lines.
Calling the split() method returns an array of Strings anyway. Perhaps you could remove the loop altogether and just try:
ObservableList<String> options =
FXCollections.observableArrayList(Arrays.asList(lines.split("\t"));

Unable to extract List elements as integers using `getInfo`

I'm using reduceRegion to sum the number of water pixels determined by an NDWI. I want to do this on a collection of images to see change in water area over a period time.
The values are returned from the reduceRegion in the console and appear to be integers, but I am unable to extract them as such. This seems to be a common problem, but the solution is typically using getInfo function to bring these values over to client side. Unfortunately getInfo returns a null in this case.
The code below is for a collection of images OR a single image. The single image(image1) returns an image with an extra property(waterArea), and the mapped algorithm blows up(because the function is returning nulls).
I've also tried using getInfo on waterAg to potentially bring that list over to client side, however that returns the same List of objects that I don't want.
var image1 = ee.Image(leastcloud.first()).select(['B11','B8','B3'])
var stackarea = function(image){
var watermask = ee.Image(0)
var MNDWI = image.normalizedDifference(['B3','B11'])
watermask = watermask.where(MNDWI.gt(.31),1);
//sum of water pixels in an area
var sum = ee.Number(watermask.reduceRegion({
reducer: ee.Reducer.sum(),
geometry: geometry,
scale: 20,
maxPixels: 1e9
}));
var clientSide = sum.getInfo()
var setArea = image.set('waterArea', clientSide)
return setArea
};
var single = stackarea(image1)
print(single)
var watermapped = filterSpot.map(stackarea)
var waterAg = watermapped.aggregate_array('waterArea')
print(waterAg)
I'm really not sure how to extract these values as numbers...
I'm hoping to get a list of numbers so that I can concatenate that array to other arrays(date of image, cloud pixel %, etc.)
reduceRegion returns a dictionary object, not a number-like object. Therefore, in your stackarea function, clientSide variable is a dictionary (i.e. an object), not a number.
The number that you're after is stored in the dictionary returned by the reduceRegion function. You can get your hand on that number by using a get function on this dictionary object:
var sum = watermask.reduceRegion({
reducer: ee.Reducer.sum(),
geometry: geometry,
scale: 20,
maxPixels: 1e9
}).get('nd');
In this way, sum will be a server-side number that store the value you're after (There's no need to use ee.Number here as it does not help much).
In case you wonder about why using get('nd') but not get('somethingelse'), well it's the name of the band in your watermask image, and this name is the default band name given to the result of the normalizedDifference function.
And in my opinion, you don't even need to use the getInfo function which takes much more time to execute. Just delete the line var clientSide = sum.getInfo() and modify the next line into var setArea = image.set('waterArea', sum).
Hope this help.

How do I get a value from a dictionary when the key is a value in another dictionary in Lua?

I am writing some code where I have multiple dictionaries for my data. The reason being, I have multiple core objects and multiple smaller assets and the user must be able to choose a smaller asset and have some function off in the distance run the code with the parent noted.
An example of one of the dictionaries: (I'm working in ROBLOX Lua 5.1 but the syntax for the problem should be identical)
local data = {
character = workspace.Stores.NPCs.Thom,
name = "Thom", npcId = 9,
npcDialog = workspace.Stores.NPCs.Thom.Dialog
}
local items = {
item1 = {
model = workspace.Stores.Items.Item1.Main,
npcName = "Thom",
}
}
This is my function:
local function function1(item)
if not items[item] and data[items[item[npcName]]] then return false end
end
As you can see, I try to index the dictionary using a key from another dictionary. Usually this is no problem.
local thisIsAVariable = item[item1[npcName]]
but the method I use above tries to index the data dictionary for data that is in the items dictionary.
Without a ton of local variables and clutter, is there a way to do this? I had an idea to wrap the conflicting dictionary reference in a tostring() function to separate them - would that work?
Thank you.
As I see it, your issue is that:
data[items[item[npcName]]]
is looking for data[“Thom”] ... but you do not have such a key in the data table. You have a “name” key that has a “Thom” value. You could reverse the name key and value in the data table. “Thom” = name

How to modify the avro key/value schema in a RDD map transformation

I'm trying to migrate some Hadoop Map Reduce code to Spark and I have doubts about how to manage map and reduce transformations when the schema of either the key or value change from input to output.
I have avro files with Indicator records that I want to process somehow. I already have this code that works:
val myAvroJob = new Job()
myAvroJob.setInputFormatClass(classOf[AvroKeyInputFormat[Indicator]])
myAvroJob.setOutputFormatClass(classOf[AvroKeyOutputFormat[Indicator]])
myAvroJob.setOutputValueClass(classOf[NullWritable])
AvroJob.setInputValueSchema(myAvroJob, Schema.create(Schema.Type.NULL))
AvroJob.setInputKeySchema(myAvroJob, Indicator.SCHEMA$)
AvroJob.setOutputKeySchema(myAvroJob, Indicator.SCHEMA$)
val indicatorsRdd = sc.newAPIHadoopRDD(myAvroJob.getConfiguration,
classOf[AvroKeyInputFormat[Indicator]],
classOf[AvroKey[Indicator]],
classOf[NullWritable])
val myRecordOnlyRdd = indicatorsRdd.map(x => (doSomethingWith(x._1), NullWritable.get)
val indicatorPairRDD = new PairRDDFunctions(myRecordOnlyRdd)
indicatorPairRDD.saveAsNewAPIHadoopDataset(myAvroJob.getConfiguration)
But this code works since the schema of the input and ouput keys does not change, is always Indicator. In hadoop Map Reduce you can define a map or reduce functions and modify the schema from input to output. In fact, I have map functions which process every Indicator record and generates a new record SoporteCartera. How can I do this in spark? It is possible from the same RDD or I have to define 2 different RDDs and pass from one to another somehow?
Thanks for your help.
To answer my own question... the problem was that you cannot change the RDD type, you must define a different RDD, so I solved it with the above code:
val myAvroJob = new Job()
myAvroJob.setInputFormatClass(classOf[AvroKeyInputFormat[SoporteCartera]])
myAvroJob.setOutputFormatClass(classOf[AvroKeyOutputFormat[Indicator]])
myAvroJob.setOutputValueClass(classOf[NullWritable])
AvroJob.setInputValueSchema(myAvroJob, Schema.create(Schema.Type.NULL))
AvroJob.setInputKeySchema(myAvroJob, SoporteCartera.SCHEMA$)
AvroJob.setOutputKeySchema(myAvroJob, Indicator.SCHEMA$)
val soporteCarteraRdd = sc.newAPIHadoopRDD(myAvroJob.getConfiguration,
classOf[AvroKeyInputFormat[SoporteCartera]],
classOf[AvroKey[SoporteCartera]],
classOf[NullWritable])
val indicatorsRdd = soporteCarteraRdd.map(x => (fromSoporteCarteraToIndicator(x._1), NullWritable.get))
val indicatorPairRDD = new PairRDDFunctions(indicatorsRdd)
indicatorPairRDD.saveAsNewAPIHadoopDataset(myAvroJob.getConfiguration)

Resources