I wrote a kivy app, which is supposed to save a list of strings.
But when I try to append a new String to the list I get this error:
ValueError: dictionary update sequence element #0 has length 1; 2 is required
Here is the function, which is supposed to make and save the list:
def save(self, vinput):
store = JsonStore('hello.json')
self.ueberschrift = ([])
if store.exists('tito'):
self.ueberschrift = store.get('tito')
self.ueberschrift.update(vinput)
store.put('tito', list_of_cap=self.ueberschrift)
I left the rest of the app and the import commands out, because these parts are working fine.
Related
Context
I am pretty new to coding and have been learning through videos and trial and error. Though it seems to have run out of steam on this one.
I was able to download a group of youtube links using helium, a simpler version of Selenium. However, I want to loop through these lists to download the transcripts from them.
# Get the links
def Get_links():
# For the class (categories with segments of information), find them all
Lnk = find_all(S('.style-scope ytd-video-renderer'))
fin = []
# Within this class,
for l in Lnk:
# These variables exist
# The xpath that contains the links
ind_links = find_all(S('//*[#id="thumbnail"]'))
# links in this this xpath
href_list = [e.web_element.get_attribute('href') for e in ind_links]
# We want to separate the duplicates
# for every link in the href_lists variable
for i in href_list:
# within the empty list 'fin', if it is not in the empty list, then we append it.
# This makes sense because if there is nothing in the list, then there will only be one copy of the list of links
if i not in fin:
fin.append(i)
print(fin)
The output is the list of links
['https://www.youtube.com/watch?v=eHnXgh0j500', None,
'https://www.youtube.com/watch?v=wDHtXXApfbc',
'https://www.youtube.com/watch?v=CJhOGDU636k',
'https://www.youtube.com/watch?v=xIB6uNsgFb8',
'https://www.youtube.com/watch?v=u7Ckt6A6du8',
'https://www.youtube.com/watch?v=PnSC2BY4e7c',
'https://www.youtube.com/watch?v=UkIAsYWgciQ',
'https://www.youtube.com/watch?v=MqC_k2WxZro',
'https://www.youtube.com/watch?v=B0BpL20QHPU',
'https://www.youtube.com/watch?v=UujbkSBzuI0',
'https://www.youtube.com/watch?v=7Q8ZvFDyjhA',
'https://www.youtube.com/watch?v=Z8pVlfulkcw',
'https://www.youtube.com/watch?v=fy0clsby3v8',
'https://www.youtube.com/watch?v=oYJaLgJL0Ok',
'https://www.youtube.com/watch?v=rampRBuDIIQ',
'https://www.youtube.com/watch?v=BuhUXD0KH8k',
'https://www.youtube.com/watch?v=27mtHjDTgvQ',
'https://www.youtube.com/watch?v=kebonpz4bD0',
'https://www.youtube.com/watch?v=2KgH0UpiRiw',
'https://www.youtube.com/watch?v=TA-P5ilI_Vg',
'https://www.youtube.com/watch?v=TOTmOToM6zQ',
'https://www.youtube.com/watch?v=CRVYXC2OH7U',
'https://www.youtube.com/watch?v=g4TrGD2tDek',
'https://www.youtube.com/watch?v=tAO-Ff7_4CE',
'https://www.youtube.com/watch?v=fwe-PjrX23o',
'https://www.youtube.com/watch?v=Gu7-vlVFUnw',
'https://www.youtube.com/watch?v=oXOqExfdKNg',
'https://www.youtube.com/watch?v=zrh7P9fgga8',
'https://www.youtube.com/watch?v=HVdZ-ccwkj8',
'https://www.youtube.com/watch?v=vCdTLteTPtM']
Problem
Is there a way I can go into these links to open them in the browser using helium (or Selenium) to then download the transcripts without copying and pasting them manually as variables and then placing them in a list?
Example
Your list with urls:
fin = ['https://www.youtube.com/watch?v=eHnXgh0j500', None,
'https://www.youtube.com/watch?v=wDHtXXApfbc',
'https://www.youtube.com/watch?v=CJhOGDU636k'
]
Looping the list and doing something:
for url in fin:
if url: #check for the NONE values
#do something in selenium e.g. driver.get(url)
print(url) #or just print
What I'm trying to do
I'm trying to enter a list of tags in flask that should become passable as a list but I can't figure out how to do it in flask, nor can I find documentation to add lists (of strings) in flask_wtf. Has anyone have experience with this?
Ideally I would like the tags to be selectively delete-able, after you entered them. So that you could enter.
The problem
Thus far my form is static. You enter stuff, hit submit, it gets processed into a .json. The tags list is the last element I can't figure out. I don't even know if flask can do this.
A little demo of how I envisioned the entry process:
How I envisioned the entry process:
The current tags are displayed and an entry field to add new ones.
[Tag1](x) | [Tag2](x)
Enter new Tag: [______] (add)
Hit (add)
[Tag1](x) | [Tag2](x)
Enter new Tag: [Tag3__] (add)
New Tag is added
[Tag1](x) | [Tag2](x) | [Tag3](x)
Enter new Tag: [______]
How I envisioned the deletion process:
Hitting the (x) on the side of the tag should kill it.
[Tag1](x) | [Tag2](x) | [Tag3](x)
Hit (x) on Tag2. Result:
[Tag1](x) | [Tag3](x)
The deletion is kind of icing on the cake and could probably be done, once I have a list I can edit, but getting there seems quite hard.
I'm at a loss here.
I basically want to know if it's possible to enter lists in general, since there does not seem to be documentation on the topic.
Your description is not really clear (is Tag1 the key in the JSON or is it Tag the key, and 1 the index?)
But I had a similar issue recently, where I wanted to submit a basic list in JSON and let WTForms handle it properly.
For instance, this:
{
"name": "John",
"tags": ["code", "python", "flask", "wtforms"]
}
So, I had to rewrite the way FieldList works because WTForms, for some reason, wants a list as "tags-1=XXX,tags-2=xxx".
from wtforms import FieldList
class JSONFieldList(FieldList):
def process(self, formdata, data=None):
self.entries = []
if data is None or not data:
try:
data = self.default()
except TypeError:
data = self.default
self.object_data = data
if formdata:
for (index, obj_data) in enumerate(formdata.getlist(self.name)):
self._add_entry(formdata, obj_data, index=index)
else:
for obj_data in data:
self._add_entry(formdata, obj_data)
while len(self.entries) < self.min_entries:
self._add_entry(formdata)
def _add_entry(self, formdata=None, data=None, index=None):
assert not self.max_entries or len(self.entries) < self.max_entries, \
'You cannot have more than max_entries entries in this FieldList'
if index is None:
index = self.last_index + 1
self.last_index = index
name = '%s-%d' % (self.short_name, index)
id = '%s-%d' % (self.id, index)
field = self.unbound_field.bind(form=None, name=name, id=id, prefix=self._prefix, _meta=self.meta,
translations=self._translations)
field.process(formdata, data)
self.entries.append(field)
return field
On Flask's end to handle the form:
from flask import request
from werkzeug.datastructures import ImmutableMultiDict
#app.route('/add', methods=['POST'])
def add():
form = MyForm(ImmutableMultiDict(request.get_json())
# process the form, form.tags.data is a list
And the form (notice the use of JSONFieldList):
class MonitorForm(BaseForm):
name = StringField(validators=[validators.DataRequired(), validators.Length(min=3, max=5)], filters=[lambda x: x or None])
tags = JSONFieldList(StringField(validators=[validators.DataRequired(), validators.Length(min=1, max=250)], filters=[lambda x: x or None]), validators=[Optional()])
I found a viable solution in this 2015 book, where a tagging system is being build for flask as part of a blog building exercise.
It's based on Flask_SQLAlchemy.
Entering lists therefore is possible with WTForms / Flask by submitting the items to the database via, e.g. FieldList and in the usecase of a tagging system, reading them from the database back to render them in the UI.
If however you don't want to deal with O'Rielly's paywall (I'm sorry, I can't post copyrighted material here) and all you want is a solution to add tags, check out taggle.js by Sean Coker. It's not flask, but javascript, but it does the job.
Following is my intention
1. read json file with codecs and utf-8 encoding
2. load the json file into python as dictionary
3. iterate through dictionary , if 'categories' key contains value 'Restaurant' then add it to a set ; else continue to next iteration.
Issue: 'categories' key may contain values like 'Restaurant', 'Restaurant and Bristro', 'Restaurant and Bar'.
My if condition should select all these three values not only 'Restaurant'
Sample code as follows
import json
restaurant_ids = set()
# open the json file
with codecs.open(json_file.json, encoding='utf_8') as f:
# iterate through each line (json record) in the file
for b_json in f:
# convert the json record to a Python dict
business = json.loads(b_json)
# if this key is not a restaurant, skip to the next one
if u'Restaurants' not in business[u'categories']:
continue
# add the restaurant business id to our restaurant_ids set
restaurant_ids.add(business[u'business_id'])
print (len(restaurant_ids))
I am getting error at if condition, business[u'categories'] seems to be unicode object, I get following error
Argument of type 'NonType' is not iterable
Any help would be highly appreciated
One of the JSON objects is missing the catagories key.
I am trying to add multiple strings to the Include list of my Render Setup Layer Collection.
See Image Here
Here i can add 'test1' using setPattern
import maya.app.renderSetup.model.renderSetup as renderSetup
"""create render setup instance"""
rs = renderSetup.instance()
"""create the render layer"""
test = rs.createRenderLayer("fg_bty")
"""set render layer to be visible"""
rs.switchToLayer(test)
#create collection
scene_Assets = test.createCollection("scene_Assets")
# add specific items to collection
scene_Assets.getSelector().setPattern('test1')
If I try:
scene_Assets.getSelector().setPattern('test1', 'test2')
I get an error as it only accepts 2 arguments not 3 as given.
If I try:
scene_Assets.getSelector().setPattern('test1')
scene_Assets.getSelector().setPattern('test2')
It just replaces the string test1 with test2
Does anyone know how to append to the list so it doesn't replace? another way to do this? I have got a way to explicitly list the items but I wanted to keep it as an expression in case things need to be added to it later on.
you can set both patterns as a single string:
scene_Assets.getSelector().setPattern('test1, test2')
you can also retrieve a previously set pattern using:
scene_Assets.getSelector().getPattern()
retrieve and append the string, then set the new combined pattern as single string
old_pattern = scene_Assets.getSelector().getPattern()
new_pattern = ', '.join([old_pattern, 'test3', 'test4'])
scene_Assets.getSelector().setPattern(new_pattern)
result: 'test1, test2, test3, test4'
I'm reading a file outputfromextractand I want to split the contents of that file with the delimiter ',' which I have done.
When reading the contents into a list there's two 'faff' entries at the beginning that I'm just trying to remove however I find myself unable to remove the index
import json
class device:
ipaddress = None
macaddress = None
def __init__(self, ipaddress, macaddress):
self.ipaddress = ipaddress
self.macaddress = macaddress
listofItems = []
listofdevices = []
def format_the_data():
file = open("outputfromextract")
contentsofFile = file.read()
individualItem = contentsofFile.split(',')
listofItems.append(individualItem)
print(listofItems[0][0:2]) #this here displays the entries I want to remove
listofItems.remove[0[0:2]] # fails here and raises a TypeError (int object not subscriptable)
In the file I have created the first three lines are enclosed below for reference:
[u' #created by system\n', u'time at 12:05\n', u'192.168.1.1\n',...
I'm wanting to simply remove those two items from the list and the rest will be put into an constructor
I believe listofItems.remove[0[0:2]] should be listofItems.remove[0][0:2].
But, slicing will be much easier, for example:
with open("outputfromextract") as f:
contentsofFile = f.read()
individualItem = contentsofFile.split(',')[2:]