Scala. foreach in one element Lists of Dates - list

I want to create a function that works on a single date or over a period of time. For that I make a list of strings like this:
import com.github.nscala_time.time.Imports._
val fromDate = "2015-10-15".toLocalDate
val toDate = "2015-10-15".toLocalDate
val days = Iterator.iterate(fromDate)(_ + 1.day).takeWhile(_ <= toDate).map(_.toString)
Now I want to access days content:
scala> days.foreach(println)
2015-10-15
scala> days.foreach(day => println(day))
With the first foreach I get the only element in days list, but with the second I get nothing. This is just a sample, but I need to use the 2nd form, because I need to use day value inside the function.
If I use a range both methods work like they are supposed to...
Anyone knows why this behaviour?
Thanks in advance!
P.D. I don't want to use another method to create the list of strings (unless I can't find a solution for this)

Second function works in same way as first.
You've created Iterator object, which you can iterate only once.
To be able use it any amount of times just convert you iterator to list.
val daysL = days.toList

Related

Check an Array for latest timestamp

[["a","some_variable_data","01.02.2021"]
["a","some_variable_data","01.03.2021"]
["a","some_variable_data","01.04.2021"]
["a","some_variable_data","11.02.2021"]
["b","some_variable_data","01.02.2020"]
["b","some_variable_data","01.03.2020"]
["b","some_variable_data","01.04.2020"]
["b","some_variable_data","11.02.2020"]]
i have to check the latest timestamp for each first array field and add this to the rows. so the result should look like:
[["a","some_variable_data","01.02.2021"]
["a","some_variable_data","01.03.2021"]
["a","some_variable_data","01.04.2021","latest"]
["a","some_variable_data","11.02.2021"]
["b","some_variable_data","01.02.2020"]
["b","some_variable_data","01.03.2020"]
["b","some_variable_data","01.04.2020","latest"]
["b","some_variable_data","11.02.2020"]]
i need some help/hint how to realize this. can anybody help me? i have to use python 2.7
I'm not sure if sorted([ that array ]) works, but you can try that.
Lets say: array = [ that bigger array you shared ].
We know the location of the dates: the 3rd element (index 2). It's also sorted on the first element of the list: "a" or "b"
A possible option is to split the array into two arrays: one starting with "a" and one with "b".
Next, you can sort on the array_a[2] element in the list. Depending on the date and month, you can see if it was before, or after.
At the end, you simply merge the big arrays together:
print([1,2,3]+[4,5,6]) # [1,2,3,4,5,6]
def latest(n):
n = list(filter(None, n)) #delete_empty
n.sort(key = lambda date: datetime.strptime(date, '%d.%m.%Y')) #sort date
n=n[::-1] #reverse list
#print(n)
latest=""
for lp in n:
latest=lp
break
return latest
found a way:
build list for each first key and sort them as datetime, then pick latest and rebuild the initial list

How to show which values of one list are in other list?

Having 2 lists, I want check which values of List1 are in List2. I'm trying as below but I get error
List1 = {3,2,8,7,5}
List2 = {1,3,4,2,6,7,9}
= List.Transform(List1, each Text.Contains(List2, _))
Expression.Error: We cannot convert a value of type List to type Text.
Details:
Value=[List]
Type=[Type]
My expected output would be 3,2,7.
How can I do this?
See List.Intersect Documentation
Intersect = List.Intersect({List1,List2})
#horseyride has probably the best answer but using your original logic, you could also write the intersection like this:
List.Select(List1, each List.Contains(List2, _))
This uses Select instead of Transform since you are trying to select/filter instead of changing the elements and uses the appropriate List type instead of Text for the Contains part.

Compare a portion of String value present in 2 Lists

Below code extract a particular value from List srchlist and check for a particular value in List rplzlist. The contents of list srchlist and rplzlist looks like below.
srchlist = ["DD='A'\n", "SOUT='*'\n", 'PGM=FTP\n', 'PGM=EMAIL']
rplzlist = ['A=ZZ.VVMSSB\n', 'SOUT=*\n', 'SALEDB=TEST12']
I am extracting the characters after the '='(equal) sign and within the single quotes using a combination of strip and translate function.
Of the elements in the srchlist only the 'SOUT' matches with the rplzlist.
Do let me know why the below code does not work, also suggest me a better approach to compare a part of string present in the list.
for ele in srchlist:
sYmls = ele.split('=')
vAlue = sYmls[1].translate(None,'\'')
for elem in rplzlist:
rPls = elem.split('=')
if vAlue in rPls:
print("vAlue")
Here is the more pythonic approach for what you wanted to do:
>>> list(set([(i.split('='))[1].translate(None,'\'') for i in srchlist]) & set([j.split('=')[1] for j in rplzlist]))
['*\n']
I used set() and then get the whole output as list, you may use .join().
Inside set(), list comprehension is given which is faster than the normal for loops.
Another Solution Using join(), and replace() in place of translate():
>>> "".join(set([(i.split('='))[1].replace('\'','') for i in srchlist]) & set([j.split('=')[1] for j in rplzlist]))
'*\n'

Applying regexp and finding the highest number in a list

I have got a list of different names. I have a script that prints out the names from the list.
req=urllib2.Request('http://some.api.com/')
req.add_header('AUTHORIZATION', 'Token token=hash')
response = urllib2.urlopen(req).read()
json_content = json.loads(response)
for name in json_content:
print name['name']
Output:
Thomas001
Thomas002
Alice001
Ben001
Thomas120
I need to find the max number that comes with the name Thomas. Is there a simple way to to apply regexp for all the elements that contain "Thomas" and then apply max(list) to them? The only way that I have came up with is to go through each element in the list, match regexp for Thomas, then strip the letters and put the remaining numbers to a new list, but this seems pretty bulky.
You don't need regular expressions, and you don't need sorting. As you said, max() is fine. To be safe in case the list contains names like "Thomasson123", you can use:
names = ((x['name'][:6], x['name'][6:]) for x in json_content)
max(int(b) for a, b in names if a == 'Thomas' and b.isdigit())
The first assignment creates a generator expression, so there will be only one pass over the sequence to find the maximum.
You don't need to go for regex. Just store the results in a list and then apply sorted function on that.
>>> l = ['Thomas001',
'homas002',
'Alice001',
'Ben001',
'Thomas120']
>>> [i for i in sorted(l) if i.startswith('Thomas')][-1]
'Thomas120'

Scala and JPA Results Lists

Scala noob i'm afraid:
I have the following declared class variable which will the objects I read from the database:
val options = mutable.LinkedList[DivisionSelectOption]()
I then use JPA to get a List of all rows from a table:
val divisionOptions = em.createNamedQuery("SelectOption.all", classOf[SelectOption]) getResultList
/* Wrap java List in Scala List */
val wrappedOptions = JListWrapper.apply(divisionOptions)
/* Store the wrappedOptions in the class variable */
options += wrappedOptions
However, the last line has an error:
Type Expected: String, actual JListWrapper[SelectOption]
Can anyone help with what I am doing wrong? I'm just trying to populate the options object with the result of the DB call.
Thanks
What (probably) is happening is that a JlistWrapper[SelectOption] isn't a DivisionSelectOption, so the method += isn't applicable to it. That being the case, it is trying other stuff, and giving a final error on this:
options = options + wrappedOptions
That is a rewriting Scala can do to make things like x += 1 work for var x. The + method is present on all objects, but it takes a String as parameter -- that's so one can write stuff like options + ":" and have that work as in Java. But since wrappedOptions isn't a String, it complains.
Roundabout and confusing, I know, and even Odersky regrets his decision with regards to +. Let that be a lesson: if you thing of adding a method to Any, think really hard before doing it.