java streams - how to filter list of list based on the value in the inner list - java-stream

I got an input List<list < Health>> e.g.
[[Health{key='day', value='mon'}, Health{key='bp', value='ok'}, Health{key='temp', value='ok'}],
[Health{key='day', value='tues'}, Health{key='bp', value='notok'}, Health{key='temp', value='ok'}]
...]
I want to filter the input such that, output should be a List<list < Health >> whose 'bp'is 'notok' && 'temp' is 'ok'.
e.g output should be
[[Health{key='day', value='tues'}, Health{key='bp', value='notok'}, Health{key='temp', value='ok'}]]
I have taken filter inner and outer list in java using streams as reference but not sure how to filter on the Health which is a dict.

I'll use a pair instead of Health but should look something like this:
List<List<Pair<String,String>>> healthList = new ArrayList<>();
List<List<Pair<String,String>>> filterdList = healthList.stream()
.filter(m -> m.stream()
.anyMatch(l -> l.getKey().equals("bp") && l.getValue().equals("notOk")))
.filter(m -> m.stream()
.anyMatch(l -> l.getKey().equals("temp") && l.getValue().equals("ok")))
.collect(Collectors.toList());

Related

After converting field to tag, no query result

I am using Telegraf with Telemetry, I want to see traffic level on interface based on their description, "/interfaces/interface/subinterfaces/subinterface/state/description". Unfortunately the interface description was as field key, which I converted using the processors.converter. Since I needed to rewrite the data after this, I just dropped the whole measurement so the new tag can take place.
I do see the descriptions as tag fields and I do see the interface description as a tag key.
Unfortunately I am still getting blank results on any query when I try with querying by interface description.
### Relevant telegraf.conf:
# Convert values to another metric value type
[[processors.converter]]
# Fields to convert
[processors.converter.fields]
tag = ["/interfaces/interface/subinterfaces/subinterface/state/description"]
System info:
Telegraf 1.14.5
Debian
Steps to reproduce:
> select "/interfaces/interface/subinterfaces/subinterface/state/description" from "/interfaces/"
(empty result) this is expected since now its a tag
> show tag keys
name: /interfaces/
tagKey
------
/interfaces/interface/subinterfaces/subinterface/state/description
we can see here that now it's as a tag key
> show tag values with key = "/interfaces/interface/subinterfaces/subinterface/state/description"
(gives all descriptions)
> SELECT "/interfaces/interface/subinterfaces/subinterface/state/counters/out-pkts" from /interfaces/ where "/interfaces/interface/subinterfaces/subinterface/state/description" = 'some_description'
(empty result) Where I would like to have some result based on the interface description
Expected behavior:
SELECT "/interfaces/interface/subinterfaces/subinterface/state/counters/out-pkts" from /interfaces/ where "/interfaces/interface/subinterfaces/subinterface/state/description" = 'some_description'
to give some a result for the interface with that description
Actual behavior:
SELECT "/interfaces/interface/subinterfaces/subinterface/state/counters/out-pkts" from /interfaces/ where "/interfaces/interface/subinterfaces/subinterface/state/description" = 'some_description'
(is not returning any result)
Additional information
I am also using Chronograph which gives no results too.
You cannot just select just a tag from a measurement. For influx to return results it needs atleast one field in the select clause.

Traversing the linked list using pretty printers in GDB

I have a linked list pretty printer which takes the input from command prompt.
E.g., print xyz
My code is something like below:
class Randomcalss:
def __init__(self, val):
self.val = int(val)
def to_string(self):
return "printing linked list:"
def children(self):
for field in self.val.type.fields():
key = field.name
val = self.val[key]
yield key,val.dereference()
It does work as expected, and prints:
printing linked list:= {head = {next = 0x625590, prev = 0x623c70}}
But if I want to traverse the linked list and proceed further what do I do.
Because every time I try to access head['next'] it says head is a string and string indices must be integers.
Cant I do something like self.val[key] to access next node of head too?
You can do val.dereference()['next'] and this will give you address of next member of the list. You can cast the value obtained(if required) and traverse further.

Efficient way to get a huge number of records sorted via Linq. Also some help regarding editing an existing DB entry

The fist part of my question is
suppose I have a poco class
public class shop{
public virtual string fruitName {get;set;}
public virtual double numberOfFruitsLeftToConsume {get;set;}
public virtual double numberOfFruitsLeftForStorage {get;set;}
public virtual List<Locations> shopLocations {get;set;}
}
I add new fruits in the db by creating a new object of shop and then add it via my context then save it.
Now to retrieve the data
will it be more efficient for me to first filter by fruit name get a List then in that collection should I run my query to sort by the number of fruits to consume , or should I just put it all into one query. Supposing that the site has more than 1000 hits/sec and a massive DB, which method will be efficient.
List<shop> sh = context.shopDB.Where(p => p.fruitName == "mango" &&
p.fruitName == "apple").ToList();
List<shop> sh = sh.Where(f => f.numberOfFruitsLeftToConsume >= 100 &&
f.numberOfFruitsLeftForStorage <= 100).ToList();
The example has no meaning , I just wanted to show the type of query I am using.
The second part of my question is, when I initialize the class shop I do not initialize the List within it. Later on when I try to add it it does not get saved, the shop is connected to the user.
ApplicationUser user = await usemanager.FindByEmailAsync("email");
if(user.shops.shopLocations == null){
user.shops.shopLocation = new List<Location>();
uset.shops.shopLocation.Add(someLocation);
await context.shopDB.SaveChangesAsync();
}
////already tried
//List<Location> loc = new List<Location>();
//loc.Add(someLocation);
//user.shops.shopLocation = loc;
//await context.shopDB.SaveChangesAsync();
I tried both the methods in a try catch block and no exception is thrown.
If you need any more details or if something is not clear to you please ask.
Thank you.
If I add Location and LocationId properties to shop, and then save, I can only view the LocationId , but the Location property still remains null.
To clear any question , If I save a location Individually it saves. So I don't think I'm providing wrong data.
Now to retrieve the data will it be more efficient for me to first filter by fruit name get a List then in that collection should I run my query to sort by the number of fruits to consume , or should I just put it all into one query. Supposing that the site has more than 1000 hits/sec and a massive DB, which method will be efficient.
You are the only one who can answer that question by measuring the query performance. Only as a general rule I can say that putting all into one query and let the database do the most of the job (eventually tuning it by creating appropriate indexes) is usually preferable.
What about the second part of the question (which basically is a different question), this block
if (user.shops.shopLocations == null)
{
user.shops.shopLocation = new List<Location>();
user.shops.shopLocation.Add(someLocation);
await context.shopDB.SaveChangesAsync();
}
looks suspicious. Your shopLocations member is declared as virtual, which means it's intended to use lazy loading, hence most probably will never be null. And even if it is null, you need to keep only the new part inside the if and do the rest outside, like this
if (user.shops.shopLocations == null)
user.shops.shopLocation = new List<Location>();
user.shops.shopLocation.Add(someLocation);
await context.shopDB.SaveChangesAsync();
1st Question
Because you are calling .ToList() at the end of your queries it will have to fetch all the rows from the db each time, so it will be much faster to do all your filtering in one LINQ .Where() call like this:
List<shop> sh = context.shopDB.Where(p => p.fruitName == "mango" && p.fruitName == "apple" && f.numberOfFruitsLeftToConsume >= 100 && f.numberOfFruitsLeftForStorage <= 100).ToList();
but if you don't call .ToList() at the end of first Linq query, spliting your query into two calls will be tottally fine and will yield the same performance as the previous approach like this:
var sh = context.shopDB.Where(p => p.fruitName == "mango" &&
p.fruitName == "apple");
List<shop> shList = sh.Where(f => f.numberOfFruitsLeftToConsume >= 100 &&
f.numberOfFruitsLeftForStorage <= 100).ToList();
2nd Question
when you initialize the Location for the shop, you must set the shopId property and then it should work, if not the problem might be with your database relationships.

Using python list as node properties in py2neo

I have a list of urls:
urls = ['http://url1', 'http://url2', 'http://url3']
Mind you the list can have any number of entries including 0 (none). I want to create new node property for each url (list entry).
Example how the node will look like
(label{name='something', url1='http://url1', url2='http://url2'}, etc...)
It is possible to expand a dictionary with ** with the same effect I need but is there any way to do this with a list?
You can put your list in a dictionary and use this to create a node:
from py2neo import Node
urls = ['http://1', 'http://2']
props = {}
for i, url in enumerate(urls):
# get a key like 'url1'
prop_key = 'url' + str(i)
props[prop_key] = url
my_node = Node('Person', **props)
graph.create(my_node)

Default django-admin list filter

My question is just an extension of this thread [Question]http://stackoverflow.com/questions/851636/default-filter-in-django-admin .
from myproject.myapp.mymodels import fieldC
class Poll(models.Model):
fieldA = models.CharField(max_length=80, choices=CHOICES.MyCHOICES)
fieldB = models.ForeignKey(fieldC)
admin.py
list_display = ('fieldB__fieldc1')
Now my list filter shows four criteria All, A ,B ,C .
What I want is if the superuser is logged in ,the filter should show all four criteria All,A,B,C and if the user is other than superuser filter should only show All, A, B.
How can i acheive this ?
Here is my actual piece of admin.py
def changelist_view(self, request, extra_context=None):
referer = request.META.get('HTTP_REFERER', '')
test = referer.split(request.META['PATH_INFO'])
if test[-1] and not test[-1].startswith('?'):
if not request.GET.has_key('patient__patient_type__exact'):
q = request.GET.copy()
q['patient__patient_type__exact'] = 'Real'
request.GET = q
request.META['QUERY_STRING'] = request.GET.urlencode()
if not request.user.is_superuser:
q['patient__patient_type__exact'] = 'Real'
return super(VisitAdmin, self).changelist_view(request, extra_context)
Thanks in advance
I think the new FilterSpec API in Django 1.4 gives you exactly what you need here. Check out the docs on list_filter. In 1.4 you can now make custom list filters that subclass django.contrib.admin.SimpleListFilter and give you the power to write custom lookup and queryset code, and since the request is passed in you can do a simple conditional with is_superuser.
if request.user.is_superuser:
# pass one set of lookups
else:
# pass a different set
read the example code in the docs carefully and I think it will all be clear.

Resources