Why it gives me Type error in that code? - database

Why he gives me (Type error) in that statment
" address = cur.fetchone()[2] last = cur.fetchone()[4] no = cur.fetchone()[5] , while it accept "name = cur.fetchone()[1]" in the code : "
import sqlite3
conn = sqlite3.connect('myproject.sqlite')
cur = conn.cursor()
print "Welcome Mr/Hefnawy"
cur.execute('SELECT phone FROM participants')
b = cur.fetchone()[0]
while True:
a = raw_input("Enter Phone number here : ")
if a == b :
cur.execute('SELECT name,address,last_order,no_of_orders FROM participants WHERE phone = ?',(b, ))
name = cur.fetchone()[1]
address = cur.fetchone()[2]
last = cur.fetchone()[4]
no = cur.fetchone()[5]
print "The Costumer is already exist in Paricipants "
print "To edit the costumer data press (1)", "\n" , "to delet the costumer press (2)", "\n" , "add new order to the costumer press (3) "
c = raw_input("Enter your choice here : ")
if c == "1":
print "What do you want to edit ? , to edit name press 1 , to edit address press 2 , to edit phone press 3"
d = raw_input("Enter your choice here : ")
if d == "1" :
e = raw_input("New costumer name please ")
cur.execute('UPDATE participants SET name = ? WHERE phone = ?' , (e , a))
print "Costumer name has been updated to :", e
print ""
conn.commit()
else:
print "The costumer is not exist"
print b
print a , type(a)

When you are fetching something from a cursor say for example
t = cur.fetchone()
you can access the data from t using
print t[0],t[1],t[2] but In your case you are using multiple cur.fetchone() which allows you to use name = cur.fetchone()[1] that ends the data in the cursor. The second line address = cur.fetchone()[2] and the lines that follow it do not have a sql query executed for them to fetch, hence giving you the error. If you want to access the whole row just assign it to a variable and use the variable to get the data.

Related

How to display array values in Shopify Script Editor?

With the holidays coming up, my team is working on developing a script for our Shopify store that prevents our customers from using discount codes if they have one of the following in their cart : Donations, Items already on sale, and items that qualify for a F30 335i giveaway. Here is the code I currently have :
##disable discount codes##
error_message = 'Cannot use Discount. Reason(s) : '
marzano_donation_id = 6723597598805
marzano_donation = false
Input.cart.line_items.each do |line_item|
product = line_item.variant.product
puts product.id
if Input.cart.discount_code != nil
# only runs if customer has discount code
if product.id == marzano_donation_id
# marzano_donation = true
marzano_error = "Marzano's Donation in cart, "
error_message.concat(marzano_error)
# Input.cart.discount_code.reject({message: "1"})
end
end
end
list_of_invalid_vendors = []
vendor_message = "Invalid vendors in cart : #{list_of_invalid_vendors}"
contains_vendor = false
vendor_list = ["Evolution Racewerks", "Kies Giveaway Items", "Precision Raceworks"]
Input.cart.line_items.each do |line_item|
vendor = line_item.variant.product.vendor
if vendor_list.include? vendor
list_of_invalid_vendors.append(vendor)
if Input.cart.discount_code != nil
error_message.concat(vendor_message)
puts list_of_invalid_vendors
puts vendor_message
end
puts list_of_invalid_vendors
end
end
puts contains_vendor
contains_giveaway = false
Input.cart.line_items.each do |line_item|
product = line_item.variant.product
next unless product.tags.include?('Kies Giveaway Items')
# Input.cart.discount_code.reject({message: "3"})
# contains_giveaway = true
giveaway_error = " Cannot use discount code on Kies Giveaway Items, "
error_message.concat(giveaway_error)
end
puts contains_giveaway
puts "123"
if Input.cart.discount_code != nil
Input.cart.discount_code.reject({message: "#{error_message}"})
end
Output.cart = Input.cart
Currently with this output, I can get the error message I want -- but only when it is a string.
The last piece to my puzzle is needed to be able to display the invalid vendors that the customer has in their cart, shown here :
list_of_invalid_vendors = []
vendor_message = "Invalid vendors in cart : #{list_of_invalid_vendors}"
contains_vendor = false
vendor_list = ["Evolution Racewerks", "Kies Giveaway Items", "Precision Raceworks"]
Input.cart.line_items.each do |line_item|
vendor = line_item.variant.product.vendor
if vendor_list.include? vendor
list_of_invalid_vendors.append(vendor)
if Input.cart.discount_code != nil
error_message.concat(vendor_message)
puts list_of_invalid_vendors
puts vendor_message
end
puts list_of_invalid_vendors
end
end
What I would like to have is code that outputs : "Cannot use discount, Invalid vendors in cart : Evolution racewerks, Precision Raceworks"
But instead what I keep on getting is :
Cannot use Discount. Reason(s) : Invalid vendors in cart : []
So to clarify -- my initial issue was that the output I was receiving was the following : Cannot use Discount. Reason(s) : Invalid vendors in cart : [] -- when in reality what I needed to be displayed in the cart was : "Invalid vendors in cart : Evolution racewerks, Precision raceworks..." What I also wanted to avoid was the content of the array being displayed, as in -- Invalid vendors in cart : ["evolution racewerks', ...] -- SO upon further research, what I discovered was that my issue was in this line here :
vendor_message = "Invalid vendors in cart : #{list_of_invalid_vendors}"
Im not entirely sure why this wouldn't work, but when I printed out "list_of_invalid_vendors", it didn't return null, but when I printed out vendor_message, it did.
So for me to be able to take an array, append values to it, and create a clean looking sentence that was easy to read for my user, i wrote the following :
invalid_vendors = invalid_vendors.join(', ')
vendor_message = "Black Friday Vendors in Cart : #{invalid_vendors}, "
error_message.concat(vendor_message)

how do I insert values while using Hash.Lib while using while loop?

I have the following code... How would I be able to insert values in the array list with different indexes while its looping inside of a while loop? from the 2nd function(HashMine(CarID1))
local function HistoryHash() -- This function is to print out the Hashes "Mined" using Hash.Lib
for Hashindex = 1, #HashHistory do
print("Hash "..Hashindex..":", HashHistory[Hashindex])
end
end
--Mines the BTC pending transaction
local function HashMine(CarID1)
while stringtohash:sub(1,2) ~= "00" do
STRINGTOHASH = stringtohash..HASHNUMBER
stringtohash = HASHLIBRARY.sha256(STRINGTOHASH)
HASHNUMBER = HASHNUMBER + 1
wait(1)
table.insert()
end
HashGUI.Text = stringtohash
PendingTextGui.Text = ""
local CarID1 = CarBought
if CarID1 == 1 then
ConfirmedText.Text = ("Car1 ".. game.Workspace.Cars.Car1Buy.Car1.Value .. "BTC To Malta Car Dealer from " .. Players:GetChildren()[1].Name)
AfterCarPurchase()
elseif CarID1 == 2 then
ConfirmedText.Text = ("Car2 ".. game.Workspace.Cars.Car2Buy.Car2.Value.. "BTC To Malta Car Dealer from " .. Players:GetChildren()[1].Name)
AfterCarPurchase()
elseif CarID1 == 3 then
ConfirmedText.Text = ("Car3 ".. game.Workspace.Cars.Car3Buy.Car3.Value .. "BTC To Malta Car Dealer from " .. Players:GetChildren()[1].Name)
end
AfterCarPurchase()
end
table.insert() will cause the error message
bad argument #1 to 'insert' (table expected, got no value)
According to the Lua 5.4 Reference Manual - table.insert, it is mandatory to provide the table you want to insert to and the value you want to to insert into that table.
table.insert (list, [pos,] value)
Inserts element value at position pos in list, shifting up the
elements list[pos], list[pos+1], ···, list[#list]. The default value
for pos is #list+1, so that a call table.insert(t,x) inserts x at the
end of the list t.
If you want to assign a value to a specific table index you need to use indexing assignmet t[key] = value

ruby class method unable to push additional user input to array

It stores the first employee, but when I try to add another employee I am unable to view the additional employees entered. Below is the method for viewing employee record. Thanks for any help!
Employee Class
class Employee
attr_accessor :employee, :role, :location
def initialize(employee, role, location)
#employee = employee
#role = role
#location = location
end
def employee_change(new_emp)
#employee = new_emp
end
def role_change(new_role)
#role = new_role
end.
def location_change(new_loc)
#location = new_loc
end
end
Main Menu
def main_menu
puts "Welcome to the Employee Portal"
puts "Please select an option below: "
puts "---------------------"
puts "1. Create New Employee Record."
puts "2. View an existing record."
puts "3. Modify an existing record."
puts "4. Exit Portal"
option = gets.chomp.to_i
if option == 1
create_record
main_menu
elsif option == 2
view_record
elsif option == 3
modify
elsif option == 4
puts "Thank you for using the Employee Portal"
exit
else
puts "Not a valid option. Please try again."
main_menu
system("clear")
end
end
Create New Employee (Option 1 from Main Menu)
def create_record
puts "Create New Employee Record, click 'Enter' to begin"
puts "Enter Employee Information: "
employee = gets.chomp.capitalize
puts "Enter Employee's Role: "
role = gets.chomp.capitalize
puts "Enter Employee's Current Work Location: "
location = gets.chomp.capitalize
puts "\n"
new_record = Employee.new(employee, role, location)
#record.push(new_record)
puts "New Employee Record has been created."
puts "Name: #{employee}"
puts "Role: #{role}"
puts "Location: #{location}"
system("clear")
main_menu
end
View Employee (Option 2 from Main Menu)
def view_record
puts "Enter Employee Name to view record: "
name = gets.chomp.capitalize
system("clear")
#record.each do |a|
if a.employee == name
puts "\n"
puts "Employee Information "
puts "--------------------"
puts " Name : #{a.employee}"
puts " Role(s) : #{a.role}"
puts " Location(s) : #{a.location}"
puts " Type 'Exit' to return to the Main Menu "
else
puts "That is not a valid entry, please try again."
view_record
main_menu
end
end
end
Modify Employee (Option 3 from Main Menu)
def modify
system("clear")
puts "Enter employee name to modify existing record: "
name = gets.chomp.capitalize
#record.each do |r|
if r.employee == name
puts "Employee found."
puts "Select an option to modify."
puts "-----------------------------------"
puts "1.) Modify employee's name."
puts "2.) Modify employee's role."
puts "3.) Modify employee's location."
puts "4.) Return to Main Menu"
puts "\n"
option = gets.chomp.to_i
if option == 1
change_employee
elsif option == 2
change_role
elsif option == 3
change_location
elsif option == 4
main_menu
else
puts "Invalid selection. Please try again."
modify
end
end
end
end
Change Employee (Option 1 from Modify)
def change_employee
puts "Enter new employee name: "
new_emp = gets.chomp.capitalize
#record.each do |r|
if r.employee == employee
r.employee_change(new_emp)
puts "#{r.employee} has been updated to #{r.employee}"
end
end
end
Change Employee Role (Option 2 from Modify)
def change_role
puts "What is #{r.employee}\'s new role?: "
new_role = gets.chomp.capitalize
#record.each do |r|
if r.employee == employee
r.role_change(new_role)
puts "#{r.employee}\'s new role is #{r.role}"
end
end
end
Change Employee Location (Option 3 from Modify)
def change_location
puts "What is #{r.employee}\'s new location?: "
new_loc = gets.chomp.capitalize
#record.each do |r|
if r.employee == employee
r.location_change(new_loc)
puts "#{r.employee} has been transfer to new location, #{r.location}."
end
end
end
Run the Program
#record = []
system("clear")
main_menu
The problem is with your view_record method. If you change it to look something like:
def view_record
puts "Enter Employee Name to view record: "
name = gets.chomp.capitalize
system("clear")
if a = #record.detect { |rec| rec.employee == name }
puts "\n"
puts "Employee Information "
puts "--------------------"
puts " Name : #{a.employee}"
puts " Role(s) : #{a.role}"
puts " Location(s) : #{a.location}"
puts " Type 'Exit' to return to the Main Menu "
else
puts "That is not a valid entry, please try again."
view_record
end
end
It works properly.
The problem was that you were calling the if...else statement on every record in #record. So if you create 2 Employees the first one named "John" and the second named "Jane". When you go to view "Jane", you call the else portion for "John", since he's the first record and then once he finishes the else you call the if portion for "Jane". The else for "John", however, never returns because after you finally finish a [possibly lengthy] stack of view_record calls, with the same issue, you then go back to main_menu which never returns (due to the final else condition in that method that re-calls main_menu)
Hope that helps and makes sense.
Notes:
The modify seems to have the same issue and the change_x methods will loop through and check each employee against the if statement, but since no else no problem (I'd still change them personally, to use the detect on these as well).
The change_x methods don't look like they would run, because employee isn't defined in them
If more than 1 employee can have the same name, you can use select instead of detect and then check for empty? or iterate through only those returned by select and call only the if portion on them.

array of objects in genie

I have 2 classes: one with 2 properties and one with an array. I want to make an array of objects of the first class.
The example compiles, but gives a wrong answer. Why?
[indent=4]
class data
prop first_name : string = " "
prop last_name : string = " "
class Arr : Object
person : data
dataset : array of data[]
init
person = new data()
dataset = new array of data[3]
def date_input()
print "\n data input \n"
person.first_name = "Egon"
person.last_name = "Meier"
dataset[0] = person
print dataset[0].first_name + " " + dataset[0].last_name
person.first_name = "John"
person.last_name = "Schneider"
dataset[1] = person
print dataset[1].first_name + " " + dataset[1].last_name
person.first_name = "Erwin"
person.last_name = "Müller"
dataset[2] = person
print dataset[2].first_name + " " + dataset[2].last_name
def date_output()
print "\n data output \n"
for i : int = 0 to 2
print dataset[i].first_name + " " + dataset[i].last_name
init
Intl.setlocale()
var a = new Arr()
a.date_input()
a.date_output()
The fundamental problem is you are referring to the same person three times, but changing their name each time. In Genie there are both value types and reference types. Value types are simpler and automatically copied on assignment. For example:
[indent=4]
init
a:int = 2
b:int = a
b = 3
print( "a is still %i", a )
A reference type has the advantage that it can be easily copied, Genie simply keeps a count of the references made. So to copy a reference type the reference count is increased by one, but this means that changes to the underlying object will affect all variables that refer to it:
[indent=4]
init
a:ReferenceTypeExample = new ReferenceTypeExample()
a.field = 2
b:ReferenceTypeExample = a
b.field = 3
print( "a.field is not 2, but %i", a.field )
class ReferenceTypeExample
field:int = 0
In the working example below I have made Person a value object by using readonly properties:
[indent=4]
init
Intl.setlocale()
var group = new Group()
print "\n data input \n"
try
group.add_person( new Person( "Egon", "Meier" ))
group.add_person( new Person( "John", "Schneider" ))
group.add_person( new Person( "Erwin", "Müller" ))
except err:GroupError
print( err.message )
print( #"$group" )
class Person
prop readonly first_name:string = ""
prop readonly last_name:string = ""
construct( first:string, last:string )
_first_name = first
_last_name = last
exception GroupError
GROUP_FULL
class Group
_people_count:int = -1
_group:new array of Person
_max_size:int = 2
construct()
_group = new array of Person[ _max_size ]
def add_person( person:Person ) raises GroupError
_people_count ++
if _people_count > _max_size
_people_count = _max_size
raise new GroupError.GROUP_FULL(
"Group is full. Maximum is %i members",
_max_size + 1
)
_group[ _people_count ] = person
print( " " + _group[ _people_count ].first_name +
" " + _group[ _people_count ].last_name
)
def to_string():string
result:string = "\n data output \n\n"
if _people_count < 0
result += " empty group"
return result
for i:int = 0 to _people_count
result += " " + _group[i].first_name + \
" " + _group[i].last_name + "\n"
return result
Some details about the code:
By changing the properties to be readonly an error will be given when you compile the program if it tries to change a detail of Person. In your example, if you change the properties of data to be readonly then the Vala compiler will warn you are trying to re-write the current object
Person has its data values set in the constructor and then any attempt after that to change them is an error
For a simple property Genie generates an automatic backing field that starts with an underscore. For example in Person the property first_name has the backing field _first_name and it is that field that is set in the constructor
Instead of including the people's names in the method itself, a method called add_person() is used that takes a Person as a parameter. This separates the concrete data from the abstract class
Checks have been added to the add_person() method to make sure the array doesn't go beyond its limits. If more people are added to the group than are allowed then an exception is raised
The add_person() calls in the init block create the Person as part of the method call. This means a reference to a Person object is not kept in the init block

Text file over written and not appended

So far I have this program doing what i want. However when running through it will overwrite the last employee record instead of just adding to the file. I'm new to prgramming and have been staring at this for hours and i can't get it yet. Just need a little nudge in the right direction.
# Define Employee Class
# Common Base Class for all Employees
class EmployeeClass:
def Employee(fullName, age, salary):
fullName = fullName
age = age
salary = salary
def displayEmployee():
print("\n")
print("Name: " + fullName)
print("Age: " + age)
print("Salary: " + salary)
print("\n")
EmployeeArray = []
Continue = True
print ("Employee Information V2.0")
while Continue == True:
print ("Welcome to Employee Information")
print ("1: Add New Record")
print ("2: List Records")
print ("3: Quit")
choice = input("Pick an option: ")
if choice == "1":
fullName = input ("Enter Full Name: ")
if fullName == "":
blankName = input ("Please enter a name or quit: ")
if blankName == "quit":
print ("Goodbye!")
print ("Hope to see you again.")
Continue = False
break
age = input ("Enter Age: ")
salary = input ("Enter Salary: ")
EmployeeRecords = open ('EmployeeRecords.txt' , 'w')
EmployeeRecords.write("Full Name: " + fullName + '\n')
EmployeeRecords.write("Age: " + age + '\n')
EmployeeRecords.write("Salary: " + salary + '\n')
EmployeeRecords.close()
elif choice == "2":
EmployeeRecords = open ('EmployeeRecords.txt', 'r')
data = EmployeeRecords.read()
print ("\n")
print (data)
EmployeeRecords.close
elif choice == "3":
answer = input ("Are you sure you want to quit? " "yes/no: ")
if answer == "yes" or "y":
print ("Bye!")
Continue = False
else:
Continue
else:
print ("Please choose a valid option")
print ("\n")
You are opening the file to be rewritten each time, based on the control string passed to open. Change open ('EmployeeRecords.txt, 'w')to open ('EmployeeRecords.txt', 'a+'). and the records will be appended to the end of the file.
Append mode should work.
EmployeeRecords = open('EmployeeRecords.txt', 'a')

Resources