spss: rename a variable label - python

I have a list of variable labels I would like to capitalize them
(i.e.) Variable label.
L0K3V "PROBLÈME AVEC VOS ENFANTS"
PK34 "QUEL ÂGE AVIEZ-VOUS?"
ML9KL "RÉPONDANT A-T'IL DÉJA ÉTÉ LÉGALEMENT MARIÉ(E)"
...
program
BEGIN PROGRAM PYTHON.
import spss
spss.StartDataStep()
#current dataset
datasetObj = spss.Dataset()
varcount=spss.GetVariableCount()
#populate a list or all the Variable Label
varNameList= [spss.GetVariableLabel(i) for i in xrange(varcount) ]
labellist=[]
for i in xrange(varcount):
myLabel = spss.GetVariableLabel(i)
newLabel = myLabel.capitalize()
spss.Submit(r""" rename labels (%s = %s) . """ %(myLabel, newLabel))
spss.EndDataStep()
END PROGRAM.
Traceback (most recent call last):
File "<string>", line 22, in <module>
File "C:\PROGRA~1\IBM\SPSS\STATIS~1\22\Python\Lib\site-packages\spss\spss.py", line 1527, in Submit
raise SpssError,error
spss.errMsg.SpssError: [errLevel 98] Submit cannot be used from within a Datastep.

1) You have an error suggesting Submit cannot be used from within a Dataset.
2) VARIABLE LABEL is the correct command to relabel a variable.
Here is a simplified way of achieving the same:
get file="C:\Program Files\IBM\SPSS\Statistics\23\Samples\English\Employee data.sav".
begin program.
import spss, spssaux, spssdata
spss.Submit("set mprint on.")
vd=spssaux.VariableDict()
spss.Submit("VARIABLE LABEL %s." % ("\n".join(["%s '%s' " % (str(v), v.VariableLabel.capitalize()) for v in vd])))
spss.Submit("set mprint off.")
end program.

You can also set the variable label property (v.VariableLabel = "...") rather than generating a VARIABLE LABEL command. If what you want is Title Case, you could just do v.VariableLabel = v.VariableLabel.title()

Related

How to fill a column of type 'multi-select' in notion-py(Notion API)?

I am trying to create a telegram-bot that will create notes in notion, for this I use:
notion-py
pyTelegramBotAPI
then I connected my notion by adding token_v2, and then receiving data about the note that I want to save in notion, at the end I save a note on notion like this:
def make_notion_row():
collection_view = client.get_collection_view(list_url[temporary_category]) #take collection
print(temporary_category)
print(temporary_name)
print(temporary_link)
print(temporary_subcategory)
print(temporary_tag)
row = collection_view.collection.add_row() #make row
row.ssylka = temporary_link #this is link
row.nazvanie_zametki = temporary_name #this is name
if temporary_category == 0: #this is category, where do I want to save the note
row.stil = temporary_subcategory #this is subcategory
tags = temporary_tag.split(',') #temporary_tags is text that has many tags separated by commas. I want to get these tags as an array
for tag_one in tags:
**add_new_multi_select_value("Теги", tag_one): #"Теги" is "Tag column" in russian. in this situation, tag_one takes on the following values: ['my_hero_academia','midoria']**
else:
row.kategoria = temporary_subcategory
this script works, but the problem is filling in the Tags column which is of type multi-select.
Since in the readme 'notion-py', nothing was said about filling in the 'multi-select', therefore
I used the bkiac function:https://github.com/jamalex/notion-py/issues/51
here is the slightly modified by me ​function:
art_tags = ['ryuko_matoi', 'kill_la_kill']
def add_new_multi_select_value(prop, value, style=None):
​global temporary_prop_schema
​if style is None:
​style = choice(art_tags)
​collection_schema = collection_view.collection.get(["schema"])
​prop_schema = next(
​(v for k, v in collection_schema.items() if v["name"] == prop), None
​)
​if not prop_schema:
​raise ValueError(
​f'"{prop}" property does not exist on the collection!'
​)
​if prop_schema["type"] != "multi_select":
​raise ValueError(f'"{prop}" is not a multi select property!')
​dupe = next(
​(o for o in prop_schema["options"] if o["value"] == value), None
​)
​if dupe:
​raise ValueError(f'"{value}" already exists in the schema!')
​temporary_prop_schema = prop_schema
​prop_schema["options"].append(
​{"id": str(uuid1()), "value": value, "style": style}
​)
​collection.set("schema", collection_schema)`
But it turned out that this function does not work, and gives the following error:
add_new_multi_select_value("Теги","my_hero_academia)
Traceback (most recent call last):
​File "<pyshell#4>", line 1, in <module>
​add_new_multi_select_value("Теги","my_hero_academia)
​File "C:\Users\laere\OneDrive\Documents\Programming\Other\notion-bot\program\notionbot\test.py", line 53, in add_new_multi_select_value
​collection.set("schema", collection_schema)
​File "C:\Users\laere\AppData\Local\Programs\Python\Python39-32\lib\site-packages\notion\records.py", line 115, in set
​self._client.submit_transaction(
​File "C:\Users\laere\AppData\Local\Programs\Python\Python39-32\lib\site-packages\notion\client.py", line 290, in submit_transaction
​self.post("submitTransaction", data)
​File "C:\Users\laere\AppData\Local\Programs\Python\Python39-32\lib\site-packages\notion\client.py", line 260, in post
​raise HTTPError(
requests.exceptions.HTTPError: Unsaved transactions: Not allowed to edit column: schema
this is my table image: link
this is my telegram chatting to bot: link
Honestly, I don’t know how to solve this problem, the question is how to fill a column of type 'multi-select'?
I solved this problem using this command
row.set_property("Категория", temporary_subcategory)
and do not be afraid if there is an error "options ..." this can be solved by adding settings for the 'multi-select' field.

UnboundLocalError: local variable 'name_chk' referenced before assignment

I have created a Bank Management System using Tkinter and MySQL in Python.
def deposit_acc_chk():
mycursor.execute("SELECT name FROM bank_master WHERE acno = '"+deposit_entry1.get()+"'")
for x in mycursor:
name_chk = ''.join(map(str, x))
deposit_chk_entry.delete(0, "end")
deposit_chk_entry.insert(0, name_chk)
deposit_chk_entry["state"] = "disabled"
This code snippet displays the name of the Account holder depositing the money. It was working fine initially but then it showed an error.
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:\Users\HP\Desktop\BMS - GUI v1.1.2.py", line 196, in deposit_acc_chk
deposit_chk_entry.insert(0, name_chk)
UnboundLocalError: local variable 'name_chk' referenced before assignment
I tried to declare the variable name_chk, explicitly, as global and even tried referring some already answered questions of this type but it was not much helpful.
My error is still not resolved! Please help me.
P.S. - I am new here so please excuse me if I fail to correctly describe my question!
It is because there is no record returned by the SQL statement, so name_chk is not created.
You should check whether there is record returned before updating deposit_chk_entry:
def deposit_acc_chk():
mycursor.execute('SELECT name FROM bank_master WHERE acno = %s', (deposit_entry1.get(),))
rec = mycursor.fetchone()
if rec:
deposit_chk_entry['state'] = 'normal'
deposit_chk_entry.delete(0, 'end')
deposit_chk_entry.insert(0, rec[0])
deposit_chk_entry['state'] = 'disabled'
Or better show something to user if no record found:
def deposit_acc_chk():
mycursor.execute('SELECT name FROM bank_master WHERE acno = %s', (deposit_entry1.get(),))
rec = mycursor.fetchone()
name_chk = rec[0] if rec else '*** No record found ***'
deposit_chk_entry['state'] = 'normal'
deposit_chk_entry.delete(0, 'end')
deposit_chk_entry.insert(0, name_chk)
deposit_chk_entry['state'] = 'disabled'
You should
declare the name_chk variable before the line (this way, initialization occurs too)
deposit_chk_entry.insert(0, name_chk) such as
import tkinter as tk
root = tk.Tk()
name_chk = tk.StringVar()
or
call deposit_acc_chk() function between end of this function and
the line deposit_chk_entry.insert(0, name_chk) in order to incur the definition of the variable
name_chk within that function

Create automatically a certain numbers of Entrys - Tkinter/Python

I want to use Tkinter to write a code where the user can enter a number N. Depending on this number N the program automatically (i dont want to use any buttons) creates N-Entry rows.
My solution works partially:
from tkinter import *
root = Tk()
Label(root, text = "Enter Number of columns").grid(row = 0, column = 0)
N = IntVar()
e_N = Entry(root, textvariable = N).grid(row = 0, column = 1)
# Put trace callbacks on the Entry IntVar
def create_rows(name, index, mode):
rows = N.get()
for i in range(rows):
Entry(root).grid(row = i + 1, column = 0)
N.trace('w', create_rows)
# Setting the vars will trigger the trace
N.set(2)
mainloop()
When you run the code for the first time, it works fine. If you delete the number two and enter a new number, new lines are automatically created. However, an error message is displayed :
Exception in Tkinter callback
Traceback (most recent call last):
File "/home/anaconda3/lib/python3.7/tkinter/__init__.py", line 508, in get
return self._tk.getint(value)
_tkinter.TclError: expected integer but got ""
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/anaconda3/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "<ipython-input-97-2da00b5c0b50>", line 12, in create_rows
rows = N.get()
File "/home/anaconda3/lib/python3.7/tkinter/__init__.py", line 510, in get
return int(self._tk.getdouble(value))
_tkinter.TclError: expected floating-point number but got ""
This error is repeated as soon as the old number is deleted and a new one is entered.
Does someone know what is wrong and how to fix it?
Also as an extra: Only new lines can be created, i.e. if you first enter 5 and then 3, the last two lines are not deleted.
Edited code:
from tkinter import *
root = Tk()
Label(root, text = "Enter Number of columns").grid(row = 0, column = 0)
N = IntVar()
e_N = Entry(root, textvariable = N).grid(row = 0, column = 1)
# Put trace callbacks on the Entry IntVar
def create_rows(name, index, mode):
try:
rows = N.get()
except _tkinter.TclError:
""
for i in range(rows):
Entry(root).grid(row = i + 1, column = 0)
N.trace('w', create_rows)
# Setting the vars will trigger the trace
N.set(2)
mainloop()
Putting a trace on the value of N means it calls create_rows whenever it changes, including just after you deleted the original number, but before you type the new one. You could put N.get() inside a try/except, and only add new lines if the contents of the number entry are a valid integer. This will handle the deleted case when the value is an empty string, and also if someone types a non-number into the entry.

Don't understand this tkinter.TclError

I can't seem to set (update) the column which I previously created to a value from a function which is called when I click a button, it says Item not found.
curItem = tree.focus()
contents =(tree.item(curItem))
selecteditem = contents['values']
tree.get_children(curItem)
Database()
cursor.execute("SELECT SUM(PRODUCT_QTY) FROM `product` WHERE `product_id` = %d" % selecteditem[0])
fetch = cursor.fetchall()
for data in fetch:
# d = tree.item(data)
tree.set(selecteditem, 3, data)
a = data
conn.commit()
cursor.close()
conn.close()
The Error and traceback:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\.\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py",
line 1705, in __call__ return self.func(*args)
File "c:\Users\.\Desktop\Simple_Inventory PYTHON\Simple Inventory System\index.py",
line 268, in calculate tree.set(selecteditem, 2, data)
File "C:\Users\.\AppData\Local\Programs\Python\Python37-32\lib\tkinter\ttk.py",
line 1482, in set res = self.tk.call(self._w, "set", item, column, value)
_tkinter.TclError: Item 8 e 3 4 not found
NOTE: 8 is the ID of the item, e the name,3 and 4 the price and quantity (dummy values)
For those who may struggle with the same problem, simply putting the curItem instead of selectedItem[0] in the tree.set() parameters fixes it. Just put in the focused tree variable there.
You are setting selecteditem to some values. The argument to tree.set must be an identifier. Like the error says, there is nothing in the tree with an id of 8 e 3 4.
The identifier will be whatever is returned when you called tree.insert. It will either be an indentifier computed for you of the form "IXXX" (eg: I001), or whatever you specified when you called tree.insert.
Since you didn't show how you created the items in the tree it's hard to say what the value should be. It might be enough to use curItem, but from the tiny bit of code you provided it's hard to say for certain.

Understanding why this python code works randomly

I'm coding a little script that gets metadata from a sound file and creates a string with the desired values. I know I'm doing something wrong but I ain't sure why, but it's probably the way I am iterating the if's. When I run the code :
import os, mutagen
XPATH= "/home/xavier/Code/autotube/tree/def"
DPATH="/home/xavier/Code/autotube/tree/down"
def get_meta():
for dirpath, directories,files in os.walk(XPATH):
for sound_file in files :
if sound_file.endswith('.flac'):
from mutagen.flac import FLAC
metadata = mutagen.flac.Open(os.path.join(dirpath,sound_file))
for (key, value) in metadata.items():
#print (key,value)
if key.startswith('date'):
date = value
print(date[0])
if key.startswith('artist'):
artist = value
#print(artist[0])
if key.startswith('album'):
album = value
#print(album[0])
if key.startswith('title'):
title = value
#print(title[0])
build_name(artist,album,title) # UnboundLocalError gets raised here
def build_name(artist,album,title):
print(artist[0],album[0],title[0])
I get the desired result or an error, randomly :
RESULT :
1967 Ravi Shankar & Yehudi Menuhin West Meets East Raga: Puriya Kalyan
ERROR :
Traceback (most recent call last):
File "<stdin>", line 39, in <module>
File "<stdin>", line 31, in get_meta
build_name(artist,album,title)
UnboundLocalError: local variable 'album' referenced before assignment
If "title" comes before "album" in the meta data then album will never be initialised. "album" may not exist at all.
As you don't blank out the value of album for each track, if a track has previously had "album" defined then the next track which doesn't define "album" will use the previous track's value.
Give it a blank value for each track (if that's reasonable to you).
Looking at build_name the values are lists of strings, so the default should be ['']:
for sound_file in files:
artist = album = title = ['']
However, you will still not get values before calling build_name if the metadata is out of order.
You need to move build_name(artist, album, title) out of the loop:
for (key, value) in metadata.items():
... # searching metadata
build_name(artist, album, title)

Categories

Resources