How do I create an attribute dynamically while using yattag? - html

This is the part of 'data' in the code below:
{'element': 'background', 'x': 0, 'y': 0, 'width': 800, 'height': 898, 'properties': {'background-color': '#ffffff'}}
The code:
for i in data:
print(i)
if i['element'] in comp:
ta = i['element']
if i['properties']:
prop_keys = list(i['properties'].keys())
background = "green"
for j in range(len(prop_keys)):
attri = prop_keys[j]
print(type(attri))
val = i['properties'][prop_keys[j]]
print(type(val))
doc, tag, text = Doc().tagtext()
exec('with tag(ta, %s = %s)'%(attri,val))
break
The error that I am getting:
Traceback (most recent call last):
File "/home/harsh/.virtualenvs/py3/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3418, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-78-69185a93c0dd>", line 19, in <module>
exec('with tag(ta, %s = %s)'%(attri,val))
File "<string>", line 1
with tag(ta, background-color = #ffffff)
^
SyntaxError: unexpected EOF while parsing
I basically want to use value of 'attri' as the name of attribute in the yattag to make it dynamic.
I tried using 'exec' function to put in the values to convert the json data into html using yattag but the yattag library doesn't allow to use expression in place of variable name to make it dynamic.

Related

Getting an AttributeError when I try to create a Oracle BMC SecurityList

I am trying to automate the creation of resources in Oracle BMC. I have this python code:
import oraclebmc
config = oraclebmc.config.from_file()
network = oraclebmc.core.virtual_network_client.VirtualNetworkClient(config)
compartment_id = ...
vcn_id = ....
details = oraclebmc.core.models.CreateSecurityListDetails()
details.compartment_id = compartment_id
details.display_name = "baseline"
details.ingress_security_rules = ()
details.egress_security_rules = ()
details.vcn_id = vcn_id
network.create_security_list(details)
But when I run this code I get:
Traceback (most recent call last):
File "deploy/cloudresources/foo.py", line 16, in <module>
network.create_security_list(details)
File "/Users/jwmcclai/bmcs_env/lib/python2.7/site-packages/oraclebmc/core/virtual_network_client.py", line 668, in create_security_list
response_type="SecurityList")
File "/lib/python2.7/site-packages/oraclebmc/base_client.py", line 124, in call_api
body = self.sanitize_for_serialization(body)
File "/lib/python2.7/site-packages/oraclebmc/base_client.py", line 230, in sanitize_for_serialization
for key, val in obj_dict.items()}
File "/lib/python2.7/site-packages/oraclebmc/base_client.py", line 230, in <dictcomp>
for key, val in obj_dict.items()}
File "/lib/python2.7/site-packages/oraclebmc/base_client.py", line 226, in sanitize_for_serialization
for attr, _ in obj.swagger_types.items()
AttributeError: 'tuple' object has no attribute 'swagger_types'
I can create security lists through console and I can create other resources (VCN, instances, etc.) using the Python API. Any ideas?
Thanks
This is because you are defining the security rules fields as tuples, not as lists.
Your code:
details.ingress_security_rules = ()
details.egress_security_rules = ()
Should be:
details.ingress_security_rules = []
details.egress_security_rules = []
As the docs mention, these fields should be of type list, not type tuple.

Python Return a list in Bottle

I have a list from an mysql query that I'm trying to return in my bottle website. Is this possible? Here's what I have:
def create_new_location():
kitchen_locations = select_location()
return template('''
% for kitchen_location in {{kitchen_locations}}:
{{kitchen_location}} Kitchen
<br/>
% end''',kitchen_locations=kitchen_locations)
This is the error that I get.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 862, in _handle
return route.call(**args)
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 1732, in wrapper
rv = callback(*a, **ka)
File "index.py", line 32, in create_new_location
</form>''',kitchen_locations=kitchen_locations)
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 3609, in template
return TEMPLATES[tplid].render(kwargs)
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 3399, in render
self.execute(stdout, env)
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 3386, in execute
eval(self.co, env)
File "<string>", line 6, in <module>
TypeError: unhashable type: 'set'
Got It (took me a while...)
% for kitchen_location in {{kitchen_locations}}:
Should be
% for kitchen_location in kitchen_locations:
When using the % at the beginning you don't need the {{}}.
This error:
TypeError: unhashable type: 'set'
is trying to use a set literal {{kitchen_locations}} ==>
kitchen_locations in a set in another set. since set is not hash-able you got the error

can you modify this theano code for fft-convolution available?

I'm searching for the way to use fft-convolution in theano.
I wrote simple convolution code with theano.
But this code doesn't work if i set "fft_conv = 1" though simple convolution works with "fft_conv = 0"
Please tell me what is wrong with this code?
import numpy as np
import theano.sandbox.cuda.fftconv
from theano.tensor.nnet import conv
import theano.tensor as T
xdata_test = np.random.uniform(low=-1, high=1, size=(100,76,76),)
xdata_test = np.asarray(xdata_test,dtype='float32')
CONVfilter = np.random.uniform(low=-1,high=1,size=(10,1,6,6))
CONVfilter = np.asarray(CONVfilter,dtype='float32')
x = T.tensor3('x') # the data is presented as rasterized images
layer0_input = x.reshape((100, 1, 76, 76))
fft_flag = 1
if fft_flag == 1 :
##### FFT-CONVOLUTION VERSION
conv_out = theano.sandbox.cuda.fftconv.conv2d_fft(
input=layer0_input,
filters=CONVfilter,
filter_shape=(10, 1, 6, 6),
image_shape=(100,1,76,76),
border_mode='valid',
pad_last_dim=False
)
elif fft_flag == 0 :
###### CONVENTIONAL CONVOLUTION VERSION
conv_out = conv.conv2d(
input=layer0_input,
filters=CONVfilter,
filter_shape=(10, 1, 6, 6),
image_shape=(100,1,76,76),
)
test_conv = theano.function([x],conv_out)
result = test_conv(xdata_test)
The error message is like below:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 580, in runfile
execfile(filename, namespace)
File "C:/Users/user/Documents/Python Scripts/ffttest.py", line 38, in <module>
result = test_conv(xdata_test)
File "C:\Anaconda\lib\site-packages\theano\compile\function_module.py", line 606, in __call__
storage_map=self.fn.storage_map)
File "C:\Anaconda\lib\site-packages\theano\gof\link.py", line 205, in raise_with_op
'\n' + '\n'.join(hints))
TypeError: __init__() takes at least 3 arguments (2 given)

web2py: module function that behaves normally in shell fails browser mode

I have a very simple helper function that helps creates column definitions for a javascript framework I"m using.
def tocol(fields,title=None,width=None,attributes=None):
cols = dict((name,eval(name)) for name in ['title','width','attributes'] if eval(name) is not None)
cols["field"] = fields
return cols
when I try this in a web2py shell the result is as I'd expect:
In [15]: col = tocol(attr.columns.tolist())
In [16]: col
Out[16]: {'field': ['l1', 'pw', 'bw', 'tilt']}
but when I try the same thing in a view I get the following traceback:
Traceback (most recent call last):
File "/home/tahnoon/web2py/gluon/restricted.py", line 224, in restricted
exec ccode in environment
File "/home/tahnoon/web2py/applications/apollo/controllers/performance.py", line 788, in <module>
File "/home/tahnoon/web2py/gluon/globals.py", line 392, in <lambda>
self._caller = lambda f: f()
File "/home/tahnoon/web2py/applications/apollo/controllers/performance.py", line 561, in pa_equity
cols = tocol(attr.columns.tolist())
File "applications/apollo/modules/helpers.py", line 33, in tocol
cols = dict((name,eval(name)) for name in ['title','width','attributes'] if eval(name) is not None)
File "applications/apollo/modules/helpers.py", line 33, in <genexpr>
cols = dict((name,eval(name)) for name in ['title','width','attributes'] if eval(name) is not None)
File "<string>", line 1, in <module>
NameError: name 'title' is not defined
Might anyone have any idea what is going wrong here? Pretty mystified.
Thanks
It looks like you're just trying to remove None values from a dictionary, so instead, why not just create a function to do that:
def remove_none(d):
[d.pop(key) for key in d.keys() if d[key] is None]
Then you can do:
col = remove_none(dict(field=attr.columns.tolist(),
title=None, width=None, attributes=None))
Or if you want to enter the arguments directly::
def remove_none_dict(**d):
[d.pop(key) for key in d.keys() if d[key] is None]
return d
col = remove_none_dict(field=attr.columns.tolist(),
title=None, width=None, attributes=None))

error loading json using topsy

When i load single record json is created just fine when i try to load multiple records i get this error. Sorry i am new to python http://tny.cz/ce1baaba
Traceback (most recent call last):
File "TweetGraber.py", line 26, in <module>
get_tweets_by_query(topic)
File "TweetGraber.py", line 15, in get_tweets_by_query
json_tree = json.loads(source)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 368, in decode
raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 2 column 1 - line 11 column 1 (char 2380 - 46974)
Here is my code
def get_tweets_by_query(query, count=10):
"""A function that gets the tweets by a query."""
Tweets=[]
queryEncoded=urllib.quote(query)
api_key = "xxxxx"
source=urllib.urlopen("http://api.topsy.com/v2/content/bulktweets.json?q=%s&type=tweet&offset=0&perpage=%s&window=realtime&apikey=%s" % (queryEncoded, count, api_key)).read()
json_tree = json.loads(source)
pprint(json_tree)
topic = raw_input("Please enter a topic: ")
get_tweets_by_query(topic)
Thanks Timusan I was able to correct my json The problem with the original it was missing the root element "[" which showed we are expecting array and there "," was missing after end of each object. So here is fixed code.
So here is the code
def get_tweets_by_query(query, count=10):
"""A function that gets the tweets by a query."""
Tweets=[]
queryEncoded=urllib.quote(query)
api_key = "xx"
source=urllib.urlopen("http://api.topsy.com/v2/content/bulktweets.json?q=%s&type=tweet&offset=0&perpage=%s&window=realtime&apikey=%s" % (queryEncoded, count, api_key)).read()
source="["+source+"]"
source=source.replace("}\n{","},{")
json_tree = json.loads(source)
pprint(json_tree)