How do I switch between tab screens by swipeing - rubymotion

I have 2 tab screens,
I want to swipe right to second tab screen
and swipe left to first tab screen
But I don't know how to call open second tab screen in handle_swipe method
Any idea ? Thank you
AppDelegate
ruby
class AppDelegate
def application(application, didFinishLaunchingWithOptions:launchOptions)
#window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)
#window.makeKeyAndVisible
first_tab = FirstTabController.alloc.init
second_tab = SecondTabController.alloc.init
#tabbar = UITabBarController.alloc.init
#tabbar.viewControllers = [first_tab, second_tab]
#tabbar.wantsFullScreenLayout = true
#window.addSubview #tabbar.view
FirstTabController
```ruby
class FirstTabController < UIViewController
def init
if super
self.title = "First Tab"
self.tabBarItem.image = UIImage.imageNamed('FirstTab.png')
end
self
end
def viewDidLoad
view.backgroundColor = UIColor.whiteColor
#label = UILabel.new
#label.text = 'First Tab'
#label.frame = [[50,50],[250,50]]
view.addSubview(#label)
# right
recognizer = UISwipeGestureRecognizer.alloc.initWithTarget(self, action:'handle_swipe:')
self.view.addGestureRecognizer(recognizer)
# left
recognizer = UISwipeGestureRecognizer.alloc.initWithTarget(self, action:'handle_swipe:')
recognizer.direction = UISwipeGestureRecognizerDirectionLeft
self.view.addGestureRecognizer(recognizer)
end
def handle_swipe(sender)
if(sender.direction == UISwipeGestureRecognizerDirectionRight)
p "Swiped right"
# #secondary_controller = SecondaryController.alloc.init
#secondary_controller = SecondTabController.alloc.init
# self.navigationController.pushViewController(#secondary_controller, animated: true)
end
end
end
```

You could try adding the gesture recognizer to the UITabBarController view, in which case you would need to subclass it and move the handle_swipe method to that controller.
If you try this route, I would also move the code that creates and adds the gesture recognizers into the viewDidLoad method of the UITabBarController subclass.

Finally I finished it by setting UITabBarController as a global variable, then change its index on swipe event occurs.
Is there any better practice to achieve this ?
I thought use the global variable may not be a good idea.
But I don't know the alternative way.
```diff
--- a/ch_2/12_tabbars/app/first_tab_controller.rb
+++ b/ch_2/12_tabbars/app/first_tab_controller.rb
## -13,5 +13,22 ## class FirstTabController < UIViewController
#label.text = 'First Tab'
#label.frame = [[50,50],[250,50]]
view.addSubview(#label)
+
+ # right
+ recognizer = UISwipeGestureRecognizer.alloc.initWithTarget(self, action:'handle_swipe:')
+ self.view.addGestureRecognizer(recognizer)
+ # left
+ recognizer = UISwipeGestureRecognizer.alloc.initWithTarget(self, action:'handle_swipe:')
+ recognizer.direction = UISwipeGestureRecognizerDirectionLeft
+ self.view.addGestureRecognizer(recognizer)
+ end
+
+
+ def handle_swipe(sender)
+
+ if(sender.direction == UISwipeGestureRecognizerDirectionRight)
+ p "Swiped right"
+ $tabbar.selectedIndex =1
+ end
end
end
diff --git a/ch_2/12_tabbars/app/second_tab_controller.rb b/ch_2/12_tabbars/app/second_tab_controller.rb
index 18ce656..8e718b0 100644
--- a/ch_2/12_tabbars/app/second_tab_controller.rb
+++ b/ch_2/12_tabbars/app/second_tab_controller.rb
## -13,5 +13,24 ## class SecondTabController < UIViewController
#label.text = 'Second Tab Controller'
#label.frame = [[50,50],[250,50]]
view.addSubview(#label)
+
+ # right
+ recognizer = UISwipeGestureRecognizer.alloc.initWithTarget(self, action:'handle_swipe:')
+ self.view.addGestureRecognizer(recognizer)
+ # left
+ recognizer = UISwipeGestureRecognizer.alloc.initWithTarget(self, action:'handle_swipe:')
+ recognizer.direction = UISwipeGestureRecognizerDirectionLeft
+ self.view.addGestureRecognizer(recognizer)
+
+
end
+
+
+ def handle_swipe(sender)
+
+ if(sender.direction == UISwipeGestureRecognizerDirectionLeft)
+ p "Swiped left"
+ $tabbar.selectedIndex = 0
+ end
+ end
end
```

Related

Doesen't go to the next cycle

The problem is the btn.onclicked(callback.next) doesn't go to the next cycle and doesn't draw the points of next cycle. Please Help, I'm new in python
import matplotlib.pyplot as plt
import mdfreader
from matplotlib.widgets import Button
btn_next = plt.axes([0.78, 0.93, 0.06, 0.045])
bnext = Button(btn_next, 'Next -->', color='0.55', hovercolor='0.95')
class Index(object):
global_cycle = 0
def next(self, event):
self.global_cycle += 1
callback = Index()
# crossing on the 40 objects
for i in range(number_ohy_objects):
wExistProb = mdf_inf._getChannelData3('fus.ObjData_Qm_TC.FusObj.i' + str(i) + '.wExistProb')
dx_Ohl_Obj = mdf_inf._getChannelData3('fus.ObjData_Qm_TC.FusObj.i' + str(i) + '.dxv')
dy_Ohl_Obj = mdf_inf._getChannelData3('fus.ObjData_Qm_TC.FusObj.i' + str(i) + '.dyv')
# check the value bigger than 0.1 and add into a list
if wExistProb[global_cycle] > 0.1:
obj_index.append(i)
obj_dy.append(dy_Ohl_Obj[global_cycle])
obj_dx.append(dx_Ohl_Obj[global_cycle])
# plot the points
aux = plt.scatter(obj_dy[:], obj_dx[:], color='green')
bnext.on_clicked(callback.next)
aux = plt.scatter(obj_dy[global_cycle], obj_dx[global_cycle] color='green')
plt.show()

Pyton2.7 Dot serpenstky triangle Tkinter

For my homework I have to create a program that maps dots to a Tkinter window, and creates a serpenstky triangle out of it. I can create it easily with lines, but I dont understand how I am supposed to get the math to work with dots.
My main question is how would I create a full object with dots using math in python for Tkinter?
from Tkinter import *
from random import randint
# the 2D point class
class Point(object):
def __init__(self,x = 0.0 ,y = 0.0):
self._x = float(x)
self._y = float(y)
#property
def x(self):
return self._x
#x.setter
def x(self):
self._x = x
#property
def y(self):
return self._y
#y.setter
def y(self):
self._y = y
#parts from previous program that I left in here just in case
def __str__(self):
return '(' + str(self.x) + ',' + str(self.y) + ')'
def dist(self,other):
return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5
def midpt(self,other):
x=float((self.x + other.x)/2)
y=float((self.y + other.y)/2)
return Point(x,y)
# the coordinate system class: (0,0) is in the top-left corner
# inherits from the Canvas class of Tkinter
class chaosGame(Canvas):
def __init__(self, master):
Canvas.__init__(self, master, bg="white")
self.colors = ["black"]
self.radius = 0
self.pack(fill=BOTH, expand=1)
def plotPoints(self, n):
min_x = 10
min_y = 0
k=1
max_x = 600
max_y = 520
mid_x = (min_x + max_x)/2
mid_y = (min_y + max_y)/2
x1 = 3**k-1
y1 = 3**k-1
for i in range(n):
point = Point((x1), (y1))
self.plot(point.x, point.y)
k+= 1
def vertPoints(self, n):
topPoint = Point((300), (0))
leftPoint = Point((0), (510))
rightPoint = Point((590), (510))
self.vplot(topPoint.x, topPoint.y)
self.vplot(leftPoint.x, leftPoint.y)
self.vplot(rightPoint.x, rightPoint.y)
def vplot(self, x, y):
color = self.colors[randint(0, len(self.colors) - 1)]
self.create_oval(x, y, x + 10, y + 10, fill= "red")
def plot(self, x, y):
color = self.colors[randint(0, len(self.colors) - 1)]
self.create_oval(x, y, x + self.radius, y + self.radius, fill=color)
##########################################################
WIDTH = 600
HEIGHT = 520
# the number of points to plot
NUM_POINTS = 50000
# create the window
window = Tk()
window.geometry("{}x{}".format(WIDTH, HEIGHT))
window.title("Triangles")
# create the coordinate system as a Tkinter canvas inside the window
s = chaosGame(window)
# plot some random points
s.plotPoints(NUM_POINTS)
s.vertPoints(3)
# wait for the window to close
window.mainloop()

Mouse selection of images with Psychopy

I have created two stimuli(red and green rectangles) as stimuli in Psychopy. Also, I have enabled mouse movements to four directions. Using the function[mouse.getPressed()] in Psychopy for selecting the stimuli, I am facing some issues.
Basically, I want the mouse to move in four directions, and when the mouse reaches red/green rectangle stimuli, I need to select that stimuli and change its color to blue.
Can anyone look into the issue and help me to resolve the same?
Here is my code:
from psychopy import visual, core, event
import numpy as np
# Create a window.
# For configuring and debugging the code turn off full screen.
fullscr = False
win = visual.Window(
[1200,1000],
monitor="testMonitor",
units="deg",
fullscr=fullscr
)
#cursor = visual.Circle(win, radius=0.2)
#cursor = visual.CustomMouse(win,
# leftLimit=-10, topLimit=10, rightLimit=10, bottomLimit=-10,
# showLimitBox=True, clickOnUp=True)
pos_zero = (0, 0)
cursor = visual.Rect(
win=win,
size=400,
pos=pos_zero,
opacity=0
)
mouse = event.Mouse(visible=True)
# Sinusoidal control version.
freq_one = 0.5
freq_two = 1.5
# Colors of the rectangles.
#color_zero='black'
color_one = 'red'
color_two = 'green'
# Positions of the rectanges.
pos_one = (-10, 0)
pos_two = (10, 0)
start = core.getTime()
cnt = 0
cursor.pos = mouse.getPos()
print cursor.pos
while cnt<600:
second = core.getTime() - start
sin_val_one = 0.5+0.5*np.sin(2 * np.pi * second * float(freq_one))
sin_val_two = 0.5+0.5*np.sin(2 * np.pi * second * float(freq_two))
#while not mouse.getPressed()[0]:
# Do something if mouse moved
for key in event.getKeys():
if key == 'escape':
core.quit()
elif key == "right":
cursor.pos = cursor.pos + (2,0)
elif key =="left":
cursor.pos = cursor.pos - (2,0)
elif key =="up":
cursor.pos = cursor.pos + (0,2)
elif key =="down":
cursor.pos = cursor.pos - (0,2)
#if cursor.pos == pos_one:
# mouse.getpressed(rect_one)
#elif cursor.pos == pos_two:
# mouse.getpressed(rect_two)
mouse.setPos(cursor.pos)
mouse.lastPos = cursor.pos
rect_one = visual.Rect(
win=win,
fillColor=color_one,
lineColor=color_one,
size=15,
pos=pos_one,
opacity=sin_val_one
)
rect_two = visual.Rect(
win=win,
fillColor=color_two,
lineColor=color_two,
size=15,
pos=pos_two,
opacity=sin_val_two
)
#images = [rect_one, rect_two]
#for image in images:
# if mouse.isPressedIn(image):
# pressed_shape = shape
#
# pressed_image.fillColor = 'blue'
# pressed_image.draw()
# print pressed_image.name
rect_one.draw()
rect_two.draw()
cursor.draw()
win.flip()
cnt += 1
win.close()
Any help is greatly appreciated. Thanks!
I made several changes and post the updated code below. It's significantly shorter and simpler.
Removed everything using mouse. Since you just want something visual to move on key presses, there's no need to invoke the mouse - especially when you actually don't want subjects to use the mouse...
Create the colored shapes once, then updating the color during runtime. This is significantly faster, i.e. avoids dropping frames.
Changed the cursor size. It was 400 degrees!
Removed the line around the rectangles so that only fillColor needs to be changed on overlap.
A few other simplifications.
Here is the code:
from psychopy import visual, core, event
import numpy as np
# Settings
fullscr = False
directions = {'left': (-2,0), 'right': (2,0), 'up': (0, 2), 'down': (0, -2)}
freq_one = 0.5 # # Sinusoidal control
freq_two = 1.5
# Create a window.
win = visual.Window([1200,1000], monitor="testMonitor", units="deg", fullscr=fullscr)
# The two rectangles
rect_one = visual.Rect(win=win, fillColor='red', lineColor=None, size=15, pos=(-10, 0))
rect_two = visual.Rect(win=win, fillColor='green', lineColor=None, size=15, pos=(10, 0))
# Cursor
cursor = visual.Circle(win, fillColor='white', radius=0.2)
# Run five trials
for trial in range(5):
# Set to initial condition
rect_one.fillColor = 'red'
rect_two.fillColor = 'green'
cursor.pos = (0, 0)
# Start task
start = core.getTime()
for frame in range(600):
# Set rectangle opacities
second = core.getTime() - start
rect_one.opacity = 0.5+0.5*np.sin(2 * np.pi * second * float(freq_one))
rect_two.opacity = 0.5+0.5*np.sin(2 * np.pi * second * float(freq_two))
# Show it
rect_one.draw()
rect_two.draw()
cursor.draw()
win.flip()
# Get keyboard responses and change color if there is overlap
for key in event.getKeys():
if key == 'escape':
core.quit()
elif key in directions.keys(): # if this is a key corresponding to a direction
cursor.pos += directions[key] # Lookup the pos change in "directions" and add it to current position
if cursor.overlaps(rect_one):
rect_one.fillColor = 'blue'
if cursor.overlaps(rect_two):
rect_two.fillColor = 'blue'

Tkinter strange behavior on destroy()

I am developing an application on Tkinter, Python 2.7.
In one of my processes I build a portion of my window (root) with 26 widgets:
23 Labels, 2 Buttons and 1 Entry.
While building them I keep adding their names to a list for further destroying
when their use is finished. For that I use the press of one of the buttons ("Done")
to read the list created and destroy() them inside a "for" loop.
The widgets get destroyed erratically, not in the order on the list. And I need
several presses of the button to finish it.
I found out of frustration, not insight, that if the list is reversed() in
the "for" loop they all get "destroyed" in the first attempt.
Is this an expected behaviour? Very puzzling!
I am ready to post the portion of my application with the strange behavior
expunged of unnecessary code unless somebody already knows the reason for it.
I am still busting my chops with Python and not ready to use Classes...
Thank you!
I am including the relevant portion of my program. I edited the original to reduce it size. Tested the edited version and it has the same behavior. I commented some of my code to show where to correct.
Happy that Mr. Oakley has taken interest. I am not sure if on transcribing my code the proper indentation was not affected.
My code:
# testdestroy.py
from Tkinter import *
root = Tk()
root.title('Information container')
root.geometry('1160x900+650+50')
global todestroy, screen, font1, lbl1txt, lbl2txt
global col, row, colincr, rowincr, bxincr, entries
todestroy = []
screen = ''
col = 10
row = 10
font1 = 'verdana 12 bold '
colincr = 370
rowincr = 40
bxincr = 145
entries = {' Last updated: ' : '11/08/2016 at 11:55',
' Login id: ' : 'calfucura',
' Password: ': 'munafuca',
'card number' : '1234567890',
'check number': '445',
'expiry' : '12/06/2018',
'PIN' : '9890',
'Tel:' : '1-800-234-5678',
'emergency' : 'entry nine',
'use for' : 'gas, groceries'}
def position(col, row, what): # returns the position for the place command
colincr = 370
rowincr = 40
bxincr = 145
if what == 'down':
row += rowincr
col -= colincr
if what == 'side':
col += colincr
if what == 'button1':
row += rowincr
col += colincr - bxincr
if what == 'button':
col -= bxincr
if what == 'reset':
col = col
row = row
return col, row
def done(event): # Button "Done"
print 'Done pressed'
for name in todestroy: # DOES NOT WORK!!!!
# THIS WORKS in the previous line:
# for name in reversed(todestroy):
name.destroy()
todestroy.remove(name)
def accept(event): # Button "Accept"
print 'Name to show: ', entry1.get()
scr2d1(entries)
def scr2d(): # Name to show
lbl1txt = 'Enter name to show: '
screen = 'scr2d'
scr2(lbl1txt)
# scr2d1(entries)
def scr2(lbl1txt):
global todestroy, col, row, entry1
lbl1 = Label(root, text = lbl1txt, anchor = E, width = 25, font = font1)
entry1 = Entry(root, width = 25, show = '*', font = font1)
Accept = Button(root, text = 'Accept', font = font1, bg = 'green', width = 9)
cmd = eval('Accept'.lower())
Accept.bind('<ButtonRelease-1>', cmd)
col, row = position(200, 200, 'reset')
lbl1.place(x = col, y = row)
col, row = position(col, row, 'side')
entry1.place(x = col , y = row )
col, row = position(col, row, 'button1')
Accept.place(x = col, y = row)
todestroy = []
todestroy.extend([lbl1, entry1, Accept])
def scr2d1(entries): # show entries
global todestroy, col, row
lblup = 1
lbl = 'lbl' + str(lblup)
lbl = Label(root, text = 'Entry', font = font1, width = 20 )
row = rowincr * 7
col = 600
col, row = position(col, row, 'down')
lbl.place(x = col, y = row)
todestroy.append(lbl)
lblup += 1
lbl = 'lbl' + str(lblup)
lbl = Label(root, text = 'Contents', font = font1, width = 20)
col, row = position(col, row, 'side')
lbl.place (x = col, y = row)
todestroy.append(lbl)
for name in sorted(entries):
lblup += 1
lbl = 'lbl' + str(lblup)
lbl = Label(root, text = name, bg = 'yellow', font = font1, width = 25, anchor = E)
col, row = position(col, row, 'down')
lbl.place(x = col, y = row)
todestroy.append(lbl)
lblup += 1
lbl = 'lbl' + str(lblup)
lbl = Label(root, text = entries[name], bg = 'yellow', font = font1, width = 25, anchor = W)
col, row = position(col, row, 'side')
lbl.place(x = col , y = row)
todestroy.append(lbl)
cmd = eval('done')
Done = Button(root, text = 'Done', font = font1, bg = 'green', width = 9)
Done.bind('<ButtonRelease-1>', cmd)
col, row = position(col, row, 'button1')
Done.place(x = col, y = row)
todestroy.append(Done)
scr2d()
root.mainloop()
The problem is that you are altering the list as you iterate over it, which is not something you should do. The reason that it works with reversed is because you are iterating over a copy of the original list. You get the same result if you use for name in todestroy[:], which also iterates over a copy of the list.
The quickest solution is to not remove anything from the list,and simply reset the list after you've deleted everything:
def done(event):
global todestroy
for name in todestroy:
name.destroy()
todestroy = []
A better solution would be to put all of the widgets you plan to destroy into a Frame. You can then destroy just the frame, and it will destroy all of its child widgets.

amazon api not able to find reduced price

I am using below code snippet to get the red reduced price from amazon but simehow I am always getting the old price and not the reduced red one.
enter code here`def getSignedUrlAmazon(searchvalue):
params = {'ResponseGroup':'Medium',
'AssociateTag':'',
'Operation':'ItemSearch',
'SearchIndex':'All',
'Keywords':searchvalue}
action = 'GET'`enter code here`
server = "webservices.amazon.in"
path = "/onca/xml"
params['Version'] = '2011-08-01'
params['AWSAccessKeyId'] = AWS_ACCESS_KEY_ID
params['Service'] = 'AWSECommerceService'
params['Timestamp'] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# Now sort by keys and make the param string
key_values = [(urllib.quote(k), urllib.quote(v)) for k,v in params.items()]
key_values.sort()
# Combine key value pairs into a string.
paramstring = '&'.join(['%s=%s' % (k, v) for k, v in key_values])
urlstring = "http://" + server + path + "?" + \
('&'.join(['%s=%s' % (k, v) for k, v in key_values]))
# Add the method and path (always the same, how RESTy!) and get it ready to sign
hmac.update(action + "\n" + server + "\n" + path + "\n" + paramstring)
# Sign it up and make the url string
urlstring = urlstring + "&Signature="+\
urllib.quote(base64.encodestring(hmac.digest()).strip())
return urlstring
forgot the price grabbing part:
def getDataAmazon(searchvalue,PRICE, lock):
try:
searchvalue = removeStopWord(searchvalue)
url = getSignedUrlAmazon(searchvalue)
data = etree.parse(url)
root = objectify.fromstring(etree.tostring(data, pretty_print=True))
gd=[]
gd1=[]
counter = 0
if hasattr(root, 'Items') and hasattr(root.Items, 'Item'):
for item in root.Items.Item:
cd={}
priceCheckFlag = False
try :
if hasattr(item.ItemAttributes, 'EAN'):
cd['EAN'] = str(item.ItemAttributes.EAN)
elif hasattr(item, 'ASIN'):
cd['ASIN'] = str(item.ASIN)
cd['productName'] = str(item.ItemAttributes.Title)
if hasattr(item, 'SmallImage'):
cd['imgLink'] = str(item.SmallImage.URL)
elif hasattr(item, 'MediumImage'):
cd['imgLink'] = str(item.MediumImage.URL)
cd['numstar'] = "0"
cd['productdiv'] = '1'
cd['sellername'] = 'Amazon'
if hasattr(item, 'DetailPageURL'):
cd['visitstore'] = str(item.DetailPageURL)
if hasattr(item.ItemAttributes, 'ListPrice') and hasattr(item.ItemAttributes.ListPrice, 'Amount'):
cd['price'] = item.ItemAttributes.ListPrice.Amount/100.0
elif hasattr(item, 'OfferSummary') and hasattr(item.OfferSummary, 'LowestNewPrice'):
cd['price'] = item.OfferSummary.LowestNewPrice.Amount/100.0