OrderedDictionary inside the init consisting of list of dictionaries gives the error for the state of transitions module for the state maching - state

In a class ABCD inside the init method I have variable state consisting of OrderedDict containing list of dictionaries. Basically the state is of module 'transitions' which are imported from class 'machine' and inside state I have orderedDict consisting of list of dictionaries.
class ABCD(Machine)
def __init__(self,args):
self.a=opts['a']
self.a=opts['b']
self.states=orderedDict([{'name':'start'},{'name':'connection','on_enter':'go'}])
Error is:
Argument of type "list[dict[str, str]]" cannot be assigned to parameter "__iterable" of type "Iterable[list[str]]" in function "init"
If I donot use the OrderedDict and use the dictionary instead of it, then I face the below error:
Cannot assign member "states" for type "ABCD"
"list[dict[str, str]]" is incompatible with "OrderedDict[str, State]"

Related

Dart/Flutter: Method 'foldIndexed' isn't defined for the type 'List'

I am trying to use the foldIndexed() method on a List in Flutter/Dart, like so:
// should only compute the combined character length of the first two fruits
['apple', 'banana', 'cherry'].foldIndexed(
0,
(index, previousElement, element) =>
index < 2 ? previousElement + element.length : previousElement);
For some reason it shows the following syntax error: The method 'foldIndexed' isn't defined for the type 'List'.
From this documentation I understand that foldIndexed() is part of Flutter and that it should be possible to use it on a List as List is an implementation of the Iterable abstract class.
Any ideas why Flutter casts the above mentioned error or won't let me use it? Or is there another way of getting access to the iteration index when using the fold() method on a List?
My problem was that I had forgotten to import collection.dart as pointed out by #pskink.

Kotlin make constructor of data class accept both List and MutableList but store a mutable instance of them

I want to make a data class which can accept both list and mutable-list and if the list is instance of MutableList then directly make it a property else if it is a List then convert it into a MutableList and then store it.
data class SidebarCategory(val title: String, val groups: MutableList<SidebarGroup>) {
constructor(title: String, groups: List<SidebarGroup>) :
this(title, if (groups is MutableList<SidebarGroup>) groups else groups.toMutableList())
}
In the above code Platform declaration clash: The following declarations have the same JVM signature error is thrown by the secondary constructor of the class (2nd line).
How should I approach this? Should I use a so called fake constructor (Companion.invoke()) or is there any better work-around?
List and MutableList are mapped to the same java.util.List class (mapped-types), so from JMV it will look like SidebarCategory has two identical constructors.
Instead of List, you can use Collection in the second constructor.
Use Collection instead of List, and then make an init block that sets it equal to a mutable list, as so:
data class SidebarCategory(val title: String, groups: Collection<SidebarGroup>) {
val groups = mutableListOf<>(groups)
}

pass kwargs and default values to ordered list

Using python 2.7, I have been researching into using keyword arguments to pass a function that inserts a new tuple into a list.
My goal: have a function that takes one required argument, and n number of arguments that then get inserted into a tuple at specific positions and have a default value if nothing was passed.
Here is what I have so far:
def add_tagging_log_row(key, **time_stamp):
tagging_log_rows.insert(len(tagging_log_rows), (key, time_stamp.get('is_processed'), time_stamp.get('is_processed')))
add_tagging_log_row('zzz', is_processed=datetime.datetime.now(), is_audited=datetime.datetime.now())
Here is a sample of tagging_low_rows list I am building with all values in the tuple populated:
[('key1', datetime.datetime.now(), datetime.datetime.now(), datetime.datetime.now(), datetime.datetime.now()), ('key2', datetime.datetime.now(), datetime.datetime.now(), datetime.datetime.now(), datetime.datetime.now())]
here is the order of the items in each tuple in the list:
key | is_processed | is_archived | is_error | is_audited
The problem is when calling the function add_tagging_log_row(), I will always pass a 'key' but might or might not pass the other timestamp fields to the tuple when it is inserted into the list. I need these fields to be empty strings ('').
Is using **kwargs the right way to approach this problem?
Yes, using kwargs works. You would need some exception handling inside your function though. kwargs passed in as a dictionary. You can check if a given timestamp exists in the dictionary and use an empty string if it doesn't. Try doing something like this inside the function:
timestamps_order = ['is_processed', 'is_archived', 'is_error', 'is_audited']
required_tuple = tuple([key] + [time_stamp[k] if k in time_stamp else "" for k in timestamps_order])
On a side note - please consider switching to Python 3. Python 2.7 is at the end of life and won't receive any future support. Most libraries have stopped supporting it.

Set attribute of type "Class" to define it as Int32, String, Float64

I have a class Container, which has an attribute type which stores the type of element stored in it:
class Container
def initialize(#type = Class)
end
end
And I want to use it like this:
array = Container.new(Int32)
# or
array = Container.new(String)
However, when running this I get: can't use Class as the type of instance variable #dtype of Crystalla::Ndarray, use a more specific type
How can I achieve this ?
If I look at other languages and librairies like numpy, they do store a type in their ndarrays:
np.ndarray(shape=(2,2), dtype=float)
How can I achieve something similar in crystal ?
EDIT: dtype is a class itself in python, but it still seems to hold a type/class like I'm trying to achieve
I think you should use generics for that.
class Container(T)
#type : T.class
#array : Array(T)
def initialize
#array = Array(T).new
#type = T
puts "Container elements type is #{#type}"
end
end
array = Container(Int32).new
Of course instance variable #type can be removed because you can always refer to T type in class definition.

grails controller: access to parameter that has a list of elements

I need to access to items stored in a parameter that represents selected elements in a multiselect. I pass selected items from gsp to controller with the following code into the remoteFunction:
params: '\'receiptItemsSelected=\' + jQuery(this).val()'
Now, following the code found in discussion here, I use the closure to get each value, but if I perform a multiselect, the size of receiptItemsSelected is always 1, but value is, for example, 1,2. To get values as a list I've done the following in the controller
params.list("receiptItemsSelected")
but it does not give me two elements if I select two items in the multiselect, but always one element.
The question is: if I select two elements, how can I get each element and use it in the controller? And how can I have that elemnts as Long and not as String?
Thanks
If you're parameters are being passed with string representation of a list, e.g.:
http://yoursite.com/?receiptItemsSelected=1,2,3
You have to split the value using normal Groovy string manipulation and perform the type conversion yourself:
def receiptsAsLongs = params.receiptItemsSelected.split(',')*.toLong()
If your parameters are passed with the convention of repeated parameters makes a list, e.g.:
http://yoursite.com/?receiptItemsSelected=1&receiptItemsSelected=2
Then grails can convert this to a list for you using params.list(), but you must do the final String to Long conversion:
def receiptsAsLongs = params.list('receiptItemsSelected')*.toLong()
params.list() is intended for multi-valued parameters, i.e. it will work if you have
receiptItemsSelected=1&receiptItemsSelected=2
You may have more luck using serialize() rather than val() to build the request body.