Using where method with List<Map> Dart - list

I have a problem in flutter I want to do a search bar and I have a response to an api and I want to show data from server that contains a text from search bar my problem is where method doesn't work with List any ideas ?

Looking at your comment, there is no where method on String types. Instead of the for loop, you want something along these lines:
// Remove the for loop
// for(var i = 0; i <map.length; i++) { _results = jsonDecode(map[i]['address']).where((p)=>p.startsWith(query)).toList(); }
// Do this instead
_results = map.where((item) => item['address'].startsWith(query)).toList();
You should now be able to ditch the for loop.

Related

In POSTMAN how do i get substring of response header item?

I am using postman to get response header value like below:
var data = postman.getResponseHeader("Location") . //value is "http://aaa/bbb" for example
I can print the value via console.log(data) easily.
However, what I really want is "bbb". So I need some substring() type of function. And apparently 'data' is not a javascript string type, because data.substring(10) for example always return null.
Does anyone what i need to do in this case?
If any postman API doc existing that explains this?
You can set an environment variable in postman. try something like
var data = JSON.parse(postman.getResponseHeader("Location"));
postman.setEnvironmentVariable("dataObj", data.href.substring(10));
You have the full flexibility of JavaScript at your fingertips here, so just split the String and use the part after the last /:
var data = pm.response.headers.get("Location").split("/").pop());
See W3 school's documentation of split and pop if you need more in depth examples of JavaScript internals.
Some initial thought - I needed a specific part of the "Location" header like the OP, but I had to also get a specific value from that specific part.
My header would look something like this
https://example.com?code_challenge_method=S256&redirect_uri=https://localhost:8080&response_type=code&state=vi8qPxcvv7I&nonce=uq95j99qBCGgJvrHjGoFtJiBoo
And I need the "state" value to pass on to the next request as a variable
var location_header = pm.response.headers.get("Location");
var attributes = location_header.split('&');
console.log(attributes);
var len = attributes.length;
var state_attribute_value = ""
var j = 0;
for (var i = 0; i < len; i++) {
attribute_key = attributes[i].split('=')[0];
if (attribute_key == "state") {
state_attribute_value = attributes[i].split('=')[1];
}
j = j + 1;
}
console.log(state_attribute_value);
pm.environment.set("state", state_attribute_value);
Might you get the point here, "split" is the choice to give you some array of values.
If the text you are splitting is always giving the same array length it should be easy to catch the correct number

Regex replacement within a partial text element in google apps script

Below is Google's example for emboldening a partial text element. This is used for selected text that is not an entire element (e.g. just a sentence fragment is selected). I need to replace the action of emboldening with that of performing a regex replacement. The replaceText() function does not accept integers to tell it where to start and end (unlike the setBold() function).
This is a very similar (unanswered) question, but I believe Google Scripts has changed some of the commands, so I thought it worth posting again.
The Google example is:
// Bold all selected text.
var selection = DocumentApp.getActiveDocument().getSelection();
if (selection) {
var elements = selection.getRangeElements();
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
// Only modify elements that can be edited as text; skip images and other non-text elements.
if (element.getElement().editAsText) {
var text = element.getElement().editAsText();
// Bold the selected part of the element, or the full element if it's completely selected.
if (element.isPartial()) {
text.setBold(element.getStartOffset(), element.getEndOffsetInclusive(), true);
} else {
text.setBold(true);
}
}
}
}
The regex implementation of replaceText method does not support lookarounds or capture groups, which makes it impossible to perform such partial replacement with it.
A workaround is to use a JavaScript replacement to prepare new substring, and then put it in place with replaceText. This preserves the formatting of text, even if, say, italicized part overlaps the selection where replacement happens. A potential drawback is that if the element contains a piece of text identical to the selection, replacement will happen there as well.
var text = element.getElement().editAsText();
if (element.isPartial()) {
var start = element.getStartOffset();
var finish = element.getEndOffsetInclusive() + 1;
var oldText = text.getText().slice(start, finish);
var newText = oldText.replace(/a/g, "b");
text.replaceText(oldText, newText);
}

Unable to get data from list control

I am working with list control in MFC. I have written code to insert elements into list control present in a dialog box as follows:
int nIndex = 0;
for (int count = 0; count < arrResults.GetSize(); count++)
{
nIndex = m_cListCtrl.InsertItem(count, _T(arrResults[count].ElementAt(0)));
m_cListCtrl.SetItemText(nIndex, 1, _T(arrResults[count].ElementAt(1)));
}
However, when I try to retrieve data from m_cListCtrl, it always returns blank. Also, the GetItemCount() method also returns 0 items. Any suggestions are appreciated.
Following is the data retrieve code that I have written:
arrResults.SetSize(1);
arrResults[0].Add("Header1");
arrResults[0].Add("Header2");
TestDialog testDlg;
testDlg.FillControlList(arrResults); // This function has above code to add data to control list
EXPECT_EQ("Header1", queryDlg.m_cListCtrl.GetItemText(0, 0));
EXPECT_EQ("Header2", queryDlg.m_cListCtrl.GetItemText(0, 1));
The GetItemText function is returning blank string.
When you call FillControlList(), you are using testDlg object. But when you call GetItemText() you're using queryDlg object. You have inserted the items in one dialog and you're trying to get data from different object. Please check with that.

Select a record where value is max in CouchDB

I have a couchdb database with 156 json documents. I want to find the max of a certain value in the documents and then emit the whole document that contains that maximun value. I used this code but it doesnt seem to work. This may help you understand what i mean.
function(doc) {
var i,m;
for (i = 0; i < doc.watchers.length; i++)
m = Math.max(m,doc.watchers[i]);
for (i = 0; i < doc.watchers.length; i++)
if (m = doc.watchers[i])
emit(doc.watchers[i], doc.watchers);
}
I would also like to select the 2 top documents, that have the max value.
Just using a map function won't work because the way map/reduce works doesn't make available the complete set of keys and values to the map function at the same time.
I would use a reduce function for that. Something like this:
Map function
function(doc) {
var i,m;
for (i = 0; i < doc.watchers.length; i++) {
emit([doc._id, doc.watchers[i]], doc.watchers);
}
}
Reduce function
function(keys, values) {
var top=0;
var index=0;
for (i=0;i<keys.length;i++) {
if (keys[i][1] > top) {
top = keys[i][1];
index = i;
}
}
return({keys[index], values[index]})
}
For this strategy to work you need to query using group_level=1, so that couch passes the results grouped by document id to the map function.
I haven't tested this solution and it doesn't solve your second question yet. I can refine it if you think it goes the right way.

Fetch items from array using regex

I'm using action script and I have an array with more than 400.000 strings and now i'm using a loop and apply a regex to each item of the array to check if it's valid or not. In case it's valid, i put such item in a result array.
this process take too long, so it's a nuisance because all the process must executed many times.
I've been thinking about if there is any other way (faster) i could use for applying the regex to all items without using a loop.
Anyone could give me an idea?
EDIT
Here I attach the code used:
var list:Array;
var list_total:Array = new Array;
var pattern:String = '^['+some_letters+']{'+n+'}$';
var cleanRegExp:RegExp = new RegExp(pattern, 'gi');
for (var i:int=0; i<_words.length; i++) {
list = _words[i].match(cleanRegExp);
if (list != null)
for (var j:int=0; j < list.length; j++)
list_total.push(list[j]);
}
Thanks.
This is not a complete answer, but may help you optimize your code.
Try to do operations in your loop that are as efficient as possible. Time them using the global getTimer() function so you can compare which methods are the most efficient. When measuring/comparing, you may want to trigger your code many times, so that these differences are noticeable.
// before test
var startTime:Number = getTimer();
// do the expensive operation
var endTime:Number = getTimer();
trace("operation took ", endTime - startTime, " milliseconds.");
For example, one improvement is inside a for loop, is to not query the array for it's length each time:
for (var i:int = 0; i < myArray.length; i++)
Instead, store the length in a local variable outside of the array and use that:
var length:int = myArray.length;
for (var i:int = 0; i < length; i++)
The difference is subtle, but accessing the length from the local variable will be faster than getting it from the Array.
Another thing you can test is the regular expression itself. Try to come up with alternate expressions, or use alternate functions. I don't recall the specifics, but in one project we determined (in our case) that using the RegEx.test() method was the fastest way to do a comparison like this. It's likely that this may be as quick as String.match() -- but you won't know unless you measure these things.
Grant Skinner has some awesome resources available on his site. They are worth reading. This slide show/presentation on performance is worth looking at. Use the arrow keys to change slides.
Edit
Without hearing Grant's presentation, the initial slides may not seem that interesting. However, it does get very interesting (with concrete code examples) around slide #43: http://gskinner.com/talks/quick/#43
I do not think there is any good way to avoid using a loop.
The loop could be optimized further though.
Like someone already suggested read the array length to a var so the loop doesn't have to check length each iteration.
Instead of the nested loop use concat to join the list array to the lists_total. I'm not sure if this is actually faster. I guess it depends on how many matches the regexp gets.
Here is the modified code.
var list:Array;
var list_total:Array = new Array;
var pattern:String = '^['+some_letters+']{'+n+'}$';
var cleanRegExp:RegExp = new RegExp(pattern, 'gi');
var wordsLength:int = _words.length;
for (var i:int=0; i<wordsLength; i++) {
list = _words[i].match(cleanRegExp);
if (list != null)
lists_total = lists_total.concat(list);
}