Skip to content

Instantly share code, notes, and snippets.

@s-kganz
Created July 20, 2020 04:41
Show Gist options
  • Save s-kganz/1ed59e07b4010dc661d7de763a733ea9 to your computer and use it in GitHub Desktop.
Save s-kganz/1ed59e07b4010dc661d7de763a733ea9 to your computer and use it in GitHub Desktop.
#: kivy 1.11.1
<MainLayout@BoxLayout>:
palindrome_label: palindrome_label
prime_label: prime_label
prime: 100000000
palindrome: 10000001
orientation: 'vertical'
BoxLayout:
orientation: 'horizontal'
Label:
id: palindrome_label
text: 'The current palindrome is {}'.format(root.palindrome)
Label:
id: prime_label
text: 'The current prime is {}'.format(root.prime)
Splitter:
sizable_from: 'top'
BoxLayout:
orientation: 'horizontal'
Button:
text: 'Get next palindrome'
on_press: app.update_palindrome()
Button:
text: 'Get next prime'
on_press: app.update_prime()
from concurrent.futures import ThreadPoolExecutor
import kivy
from kivy.app import App
from kivy.properties import ObjectProperty, NumericProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
def is_prime(n):
'''
Checks if a number is prime.
'''
for i in range(2, n):
if n % i == 0: return False
return True
def get_next_prime(n):
'''
Returns the next prime number larger than n.
'''
n += 1
while not is_prime(n): n += 1
return n
def get_next_palindrome(n):
'''
Returns the next palindromic number larger than n.
'''
n += 1
while not str(n) == str(n)[::-1]: n += 1
return n
class MainLayout(BoxLayout):
palindrome_label = ObjectProperty(None)
prime_label = ObjectProperty(None)
palindrome = NumericProperty(1)
prime = NumericProperty(1)
class AsyncApp(App):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._executor = ThreadPoolExecutor(max_workers=1)
self._future = None
self._clock_event = None
def build(self):
self.layout = MainLayout()
return self.layout
def update_palindrome(self):
current = self.layout.palindrome
self.layout.palindrome = get_next_palindrome(current)
def update_prime(self):
if self._future is None or self._future.done():
print("Starting a new thread, current prime is {}".format(self.layout.prime))
self._future = self._executor.submit(get_next_prime, self.layout.prime)
self._clock_event = Clock.schedule_interval(self.check_thread_status, 0.1)
def check_thread_status(self, *args):
if not self._future.done():
return
else:
maybe_e = self._future.exception()
if maybe_e is not None:
raise maybe_e
else:
next_prime = self._future.result()
self.layout.prime = next_prime
Clock.unschedule(self._clock_event)
if __name__ == '__main__':
AsyncApp().run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment