Spyne. Set Array fixed number items - spyne

I create the model in spyne with array attribute and I need to fix number items in array.
i.e. my model looks like:
class MyModel(ComplexModel):
__namespace__ = 'myns'
string_field = String(**{'min_occurs': 1, 'max_occurs': 1, 'nillable': False})
array_field = Array(Integer(**{'max_occurs': 16, 'min_occurs': 16, 'nillable': False}),
**{'min_occurs': 1, 'max_occurs': 1, 'nillable': False})
So, it mean I need to objects with string attribute and array with 16 integer items, but this code direct to xml like:
<myns:MyModel>
<!--Optional:-->
<myns:string_field>?</myns:string_field>
<myns:array_field>
<!--Zero or more repetitions:-->
<myns:integer>?</myns:integer>
</myns:array_field>
</myns:MyModel>
There is just one integer item in myns:array_field instead 16. What's wrong in my code or is there possible set number of of array's items which I need to?
Thanks.

Two options:
You can define a constructor and set default values the usual way. i.e.
class MyModel(ComplexModel):
__namespace__ = 'myns'
string_field = String(min_occurs=1, nillable=False)
array_field = Array(Integer(max_occurs=16, min_occurs=16, nillable=False),
min_occurs=1, max_occurs=1, nillable=False)
def __init__(self):
self.array_field = [0] * 16
You can define a default value for the array. Here's a fully working script:
from lxml import etree
from spyne.model.complex import ComplexModel, Array
from spyne.model.primitive import String, Integer
class MyModel(ComplexModel):
__namespace__ = 'myns'
s = String(min_occurs=1, nillable=False)
a = Array(Integer(max_occurs=16, min_occurs=16, nillable=False),
min_occurs=1, max_occurs=1, nillable=False, default=[0]*16)
from spyne.util.xml import get_object_as_xml
print etree.tostring(get_object_as_xml(MyModel(s='some_string'), MyModel), pretty_print=True)

Related

Odoo 10 selection fields value

How can i get selection fields value in odoo 10?
def compute_default_value(self):
return self.get_value("field")
I tried this,
def compute_default_value(self):
return dict(self._fields['field'].selection).get(self.type)
Also tried this,but it is not working.
Please help me, i could not find the solution.
Thank you.
You can do this in a following manner:
self._fields['your_field']._desription_selection(self.env)
This will return the selection list of pairs (value, label).
If you just need possible values, you can use get_values method.
self._fields['your_field'].get_values(self.env)
But it's not a common way. Most of the time people define selections differently and then use those definitions. For example, I commonly use classes for those.
class BaseSelectionType(object):
""" Base abstract class """
values = None
#classmethod
def get_selection(cls):
return [(x, cls.values[x]) for x in sorted(cls.values)]
#classmethod
def get_value(cls, _id):
return cls.values.get(_id, False)
class StateType(BaseSelectionType):
""" Your selection """
NEW = 1
IN_PROGRESS = 2
FINISHED = 3
values = {
NEW: 'New',
IN_PROGRESS: 'In Progress',
FINISHED: 'Finished'
}
You can use this class wherever you want, just import it.
state = fields.Selection(StateType.get_selection(), 'State')
And it's really handy to use those in the code. For example, if you want to do something on a specific state:
if self.state == StateType.NEW:
# do your code ...
I don't get the question fully, but let me try to answer. Why not just define the selection as method and use it for both situations:
from datetime import datetime
from odoo import models, fields
class MyModel(models.Model):
_name = 'my.model'
def month_selection(self):
return [(1, 'Month1'), (2, 'Month2')]
def compute_default_value(self):
selection = self.month_selection()
# do whatever you want here
month = fields.Selection(
selection=month_selection, string='Month',
default=datetime.now().month, required=True)

declaring dynamic variable in loop Coffescript

Probably it's a noobisch question. Currently I'm fiddling with Framer.js. I've got a CoffeeScript question;
types = ["orange", "apple", "banana", "grapefruit", "pear"]
for i in types
li = new TextLayer
text: types
y: li * 60
li.parent = dropdownList
print "list-item-" + "#{i}", i
So I've got an Array and I would like to declare an dynamic variable to an object instance. Code above just generates 5 li layers (which is Framer specific > I don't want non-self-explaining layer names within Editor)
So within the for-loop;
var item-orange = new Layer...
var item-apple = new Layer...
and so on
How could I accomplish this with CoffeeScript?
I'm not sure, but I think what you're trying to do is get a reference to each created layer by name, right? You could do this by storing them in an object under the reference of their name:
types = ["orange", "apple", "banana", "grapefruit", "pear"]
# Create an empty layers object, outside of the loop
layers = {}
# Loop over the types array, storing the type in the variable named type
# And the number of the current loop in the variable index
for type, index in types
li = new Layer
html: type
y: index * 220
name: "list-item-#{type}"
# Store the layer in the layer object under the type key
layers[type] = li
print "list-item-" + "#{type}", layers[type]
# Get a specific layer out of the layers array
layers['apple'].animate
x: 300
Full example is here: http://share.framerjs.com/5owxrbz5hqse/

How to return a list of elements in Elm

I'm trying to build a list of elements from a simple array in ELM. The expected result is literally just a list of elements with 1 as the first item, 2 as the second, and so on.
import Html exposing (..)
import Html.Attributes exposing (class, id)
import List exposing (map)
theArray = [1,2,3,4,5,6]
createListItem item =
li [] [ text (toString item)]
buildList collection =
map createListItem collection
builtList = ul [] [(buildList theArray)]
main =
builtList
But I keep getting the compiler error on line thirteen. I've tried type annotating the map element to html but I don't see what I should do.
The 2nd argument to function `ul` is causing a mismatch.
*13| builtList = ul [] [(buildList theArray)]*
Function `ul` is expecting the 2nd argument to be:
List VirtualDom.Node
But it is:
List (List Html)
buildList is already returning a value of type List Html, so you don't need brackets around (buildList theArray). Change line 13 to:
builtList = ul [] (buildList theArray)

Import a dictionary into the current scope as variables

I have a .mat file in which I put data previously processed. When I perform
dict = scipy.io.loadmat('training_data.mat')
I get back a dict that is like this
{'encoders' : ......, 'decoders' : ........, 'stuff' : .....}
I want to selectively import the encoders and decoders variables into my current scope. The effect is the same as:
encoders = dict['encoders']
decoders = dict['decoders']
How do I cleanly do this without typing 10-15 lines?
You could import a dictionary d into the global scope using
globals().update(d)
The same thing is impossible for local scopes, since modifying the dictionary returned by locals() results in undefined behaviour.
A slightly hacky trick you could use in this situation is to import the names into the dictionary of an on-the-fly created type:
d = {"encoders": 1, "decoders": 2}
t = type("", (), d)
print t.encoders
print t.decoders
This will at least be slightly more convenient than using d["decoders"] etc.
Alternatively, you could use exec statements to create your variables:
d = {"encoders": 1, "decoders": 2}
for k, v in d.iteritems():
exec k + " = v"
This could also be done selectively.

Add extra field in Django QuerySet as timedelta type

I have the following model:
class UptimeManager(models.Manager):
def with_length(self):
"""Get querySet of uptimes sorted by length including the current one. """
extra_length = Uptime.objects.extra(select={'length':
"""
SELECT
IF (end is null,
timestampdiff(second,begin,now()),
timestampdiff(second,begin,end))
FROM content_uptime c
WHERE content_uptime.id = c.id
"""
})
return extra_length
class Uptime(models.Model):
begin = models.DateTimeField('beginning')
end = models.DateTimeField('end', null=True) I call
host = models.ForeignKey("Host")
objects = UptimeManager()
...
then I call Uptime.objects.with_length().order_by('-length')[:10] to get list of longest uptimes.
But the length in template is of integer type. How to modify my code as the length of object returned by manager would be accessible in template as timedelta object?
I almost could do it by returning a list and converting number of seconds to timedelta objects, but then I have to do sorting, filtering etc. in my Python code which is rather ineffective in comparison to one well done SQL query.
Add a property to the model that looks at the actual field and converts it to the appropriate type.
My solution is to create a filter that determines type of length var and returns timedelta in case it's some integer type
from django import template
import datetime
register = template.Library()
def timedelta(value):
if isinstance(value, (long,int)):
return datetime.timedelta(seconds=value)
elif isinstance(value, datetime.timedelta):
return value
else: raise UnsupportedOperation
register.filter('timedelta',timedelta)
and use in template it's trivial
{{ uptime.length|timedelta }}