summary refs log tree commit diff stats
diff options
context:
space:
mode:
-rw-r--r--python/code/01_math_functions.py (renamed from python/code/1/2.txt)0
-rw-r--r--python/code/02_num_ops.py (renamed from python/code/1/4.py)0
-rw-r--r--python/code/03_flt_ops.py (renamed from python/code/1/6.py)0
-rw-r--r--python/code/04_gsum.py (renamed from python/code/2/1.py)0
-rw-r--r--python/code/05_lam_key.py (renamed from python/code/2/3.py)0
-rw-r--r--python/code/06_cal.py (renamed from python/code/2/5.py)0
-rw-r--r--python/code/07_hstarpat.py (renamed from python/code/2/7.py)0
-rw-r--r--python/code/09_str_count.py (renamed from python/code/3/4.py)0
-rw-r--r--python/code/1/1.txt17
-rw-r--r--python/code/1/3.txt17
-rw-r--r--python/code/1/7.py5
-rw-r--r--python/code/10_caeser_cipher.py (renamed from python/code/3/6.py)0
-rw-r--r--python/code/2/2.py12
-rw-r--r--python/code/2/4.py27
-rw-r--r--python/code/2/6.py11
-rw-r--r--python/code/3/3.py11
-rw-r--r--python/code/3/5.py5
-rw-r--r--python/code/3/7.py9
-rw-r--r--python/output/03_flt_ops.typ (renamed from python/output/1/6.txt)0
-rw-r--r--python/output/04_gsum.typ (renamed from python/output/2/1.txt)0
-rw-r--r--python/output/06_cal.typ (renamed from python/output/2/5.txt)0
-rw-r--r--python/output/07_hstarpat.typ (renamed from python/output/2/7.txt)0
-rw-r--r--python/output/10_caeser_cipher.typ (renamed from python/output/3/6.txt)0
-rw-r--r--python/output/2/2.txt4
-rw-r--r--python/output/2/4.txt24
-rw-r--r--python/output/2/6.txt7
-rw-r--r--python/output/3/3.txt9
-rw-r--r--python/output/3/5.txt4
-rw-r--r--python/output/3/7.txt9
29 files changed, 0 insertions, 171 deletions
diff --git a/python/code/1/2.txt b/python/code/01_math_functions.py
index 08c95b5..08c95b5 100644
--- a/python/code/1/2.txt
+++ b/python/code/01_math_functions.py
diff --git a/python/code/1/4.py b/python/code/02_num_ops.py
index 7579373..7579373 100644
--- a/python/code/1/4.py
+++ b/python/code/02_num_ops.py
diff --git a/python/code/1/6.py b/python/code/03_flt_ops.py
index e3a3cd0..e3a3cd0 100644
--- a/python/code/1/6.py
+++ b/python/code/03_flt_ops.py
diff --git a/python/code/2/1.py b/python/code/04_gsum.py
index 7ccd78f..7ccd78f 100644
--- a/python/code/2/1.py
+++ b/python/code/04_gsum.py
diff --git a/python/code/2/3.py b/python/code/05_lam_key.py
index 2a8dd10..2a8dd10 100644
--- a/python/code/2/3.py
+++ b/python/code/05_lam_key.py
diff --git a/python/code/2/5.py b/python/code/06_cal.py
index ba78eec..ba78eec 100644
--- a/python/code/2/5.py
+++ b/python/code/06_cal.py
diff --git a/python/code/2/7.py b/python/code/07_hstarpat.py
index 3212851..3212851 100644
--- a/python/code/2/7.py
+++ b/python/code/07_hstarpat.py
diff --git a/python/code/3/4.py b/python/code/09_str_count.py
index 3c0a566..3c0a566 100644
--- a/python/code/3/4.py
+++ b/python/code/09_str_count.py
diff --git a/python/code/1/1.txt b/python/code/1/1.txt
deleted file mode 100644
index 827a09a..0000000
--- a/python/code/1/1.txt
+++ /dev/null
@@ -1,17 +0,0 @@
->>> 2 + 3
-5
->>> 1 + 2 * 3 - 4
-3
->>> 12 * 5 / 3 * 2
-40.0
->>> 5 / 8
-0.625
->>> 23 // 7
-3
->>> 17 % 5 - 1
-1
->>> 3 * (4 + 5) + 5
-32
->>> (2 + (7 + 2) / 3 - 4) / (-2 / 7 + (19 - 3 * 4) / 8)
-1.696969696969697
-
diff --git a/python/code/1/3.txt b/python/code/1/3.txt
deleted file mode 100644
index 90ebdbe..0000000
--- a/python/code/1/3.txt
+++ /dev/null
@@ -1,17 +0,0 @@
->>> a, b = 3 + 2j, 4 - 3j
->>> a + b, a - b, a * b, a / b
-((7-1j), (-1+5j), (18-1j), (0.24+0.68j))
->>> -a, -b
-((-3-2j), (-4+3j))
->>> (a + b) / (a - b)
-(-0.4615384615384615-1.3076923076923077j)
->>> abs(a), abs(b)
-(3.605551275463989, 5.0)
->>> a.imag, a.real
-(2.0, 3.0)
->>> a.conjugate(), b.conjugate()
-((3-2j), (4+3j))
->>> from cmath import phase
->>> phase(a), phase(b)
-(0.5880026035475675, -0.6435011087932844)
-
diff --git a/python/code/1/7.py b/python/code/1/7.py
deleted file mode 100644
index 37ecfa3..0000000
--- a/python/code/1/7.py
+++ /dev/null
@@ -1,5 +0,0 @@
-a = int(input('Enter first number: '))
-b = int(input('Enter second number: '))
-q, r = a // b, a % b
-q1d, r1d = q % 10, r % 10
-print(f'The one’s place digits of quotient and remainder are {"" if q1d == r1d else "not"} equal.')
diff --git a/python/code/3/6.py b/python/code/10_caeser_cipher.py
index 64b1a60..64b1a60 100644
--- a/python/code/3/6.py
+++ b/python/code/10_caeser_cipher.py
diff --git a/python/code/2/2.py b/python/code/2/2.py
deleted file mode 100644
index bb3e9d2..0000000
--- a/python/code/2/2.py
+++ /dev/null
@@ -1,12 +0,0 @@
-def is_prime(n):
-    if n < 2: return False
-    for i in range(2, n):
-        if n % i == 0: return False
-    return True
-
-def filter_prime(numbers):
-    return [number for number in numbers if is_prime(number)]
-
-numbers = [int(n) for n in input('Enter a list of numbers: ').split()]
-primes = [number for number in numbers if is_prime(number)]
-print('List of primes:', primes)
diff --git a/python/code/2/4.py b/python/code/2/4.py
deleted file mode 100644
index 21b1bf4..0000000
--- a/python/code/2/4.py
+++ /dev/null
@@ -1,27 +0,0 @@
-from random import randrange
-
-def game():
-    secret = randrange(1, 11)
-    for i in range(3):
-        guess = int(input('Enter a guess: '))
-        if guess != secret:
-            print('Wrong guess!', end=' ')
-        else:
-            print(f'Correct guess in {i + 1} {"try" if i == 0 else "tries"}!')
-            return
-        if i != 2:
-            print('Try again.')
-        else:
-            print('Game over!')
-            print(f'Secret value was {secret}')
-
-while True:
-    print('Welcome to number guessing game')
-    print('Try to guess the secret random number between 1 to 10 correctly in 3 tries')
-    game()
-    choice = input('Do you want to try playing again (y/n, default n): ')
-    if choice == '' or choice == 'n':
-        print('Thanks for playing. Bye!')
-        break
-    else:
-        print('Enjoy your next play\n')
diff --git a/python/code/2/6.py b/python/code/2/6.py
deleted file mode 100644
index 8013ae4..0000000
--- a/python/code/2/6.py
+++ /dev/null
@@ -1,11 +0,0 @@
-line = input('Enter a string: ')
-uppercase_count, lowercase_count, digit_count = 0, 0, 0
-for c in line:
-    if c.isupper(): uppercase_count += 1
-    elif c.islower(): lowercase_count += 1
-    elif c.isdigit(): digit_count += 1
-
-print('Number of')
-print('  Uppercase characters:', uppercase_count)
-print('  Lowercase characters:', lowercase_count)
-print('  Digits:', digit_count)
diff --git a/python/code/3/3.py b/python/code/3/3.py
deleted file mode 100644
index 7f9a98f..0000000
--- a/python/code/3/3.py
+++ /dev/null
@@ -1,11 +0,0 @@
-full_name = input("Enter your full name: ")
-space_index = full_name.rfind(' ')
-
-if space_index == -1:
-  print(f"Your name in reverse: {full_name}")
-else:
-  first_name = full_name[:full_name.index(' ')]
-  last_name = full_name[space_index + 1:]
-  print(f"Your name in reverse: {last_name}, {first_name}")
-
-
diff --git a/python/code/3/5.py b/python/code/3/5.py
deleted file mode 100644
index 7db13a0..0000000
--- a/python/code/3/5.py
+++ /dev/null
@@ -1,5 +0,0 @@
-text = input('Enter a line of text: ')
-vowels = set('aeiouAEIOU')
-ctext = ''.join(c for c in text if c not in vowels)
-print('Given text with all vowels removed:', ctext)
-
diff --git a/python/code/3/7.py b/python/code/3/7.py
deleted file mode 100644
index 7a17f08..0000000
--- a/python/code/3/7.py
+++ /dev/null
@@ -1,9 +0,0 @@
-import sys
-address = input('Enter an E-mail address: ')
-if '@' not in address:
-    print(address, 'is not a valid E-mail address')
-    sys.exit(1)
-at_position = address.rindex('@')
-username, domain = address[:at_position], address[at_position+1:]
-print('Username:', username)
-print('Domain:', domain)
diff --git a/python/output/1/6.txt b/python/output/03_flt_ops.typ
index b238b5f..b238b5f 100644
--- a/python/output/1/6.txt
+++ b/python/output/03_flt_ops.typ
diff --git a/python/output/2/1.txt b/python/output/04_gsum.typ
index 81480d1..81480d1 100644
--- a/python/output/2/1.txt
+++ b/python/output/04_gsum.typ
diff --git a/python/output/2/5.txt b/python/output/06_cal.typ
index 35b538d..35b538d 100644
--- a/python/output/2/5.txt
+++ b/python/output/06_cal.typ
diff --git a/python/output/2/7.txt b/python/output/07_hstarpat.typ
index abb9c92..abb9c92 100644
--- a/python/output/2/7.txt
+++ b/python/output/07_hstarpat.typ
diff --git a/python/output/3/6.txt b/python/output/10_caeser_cipher.typ
index ba5b336..ba5b336 100644
--- a/python/output/3/6.txt
+++ b/python/output/10_caeser_cipher.typ
diff --git a/python/output/2/2.txt b/python/output/2/2.txt
deleted file mode 100644
index 4c06a26..0000000
--- a/python/output/2/2.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-```
-Enter a list of numbers: 1 42 73 23 13 15 17 9 65 48 37 11 4
-List of primes: [73, 23, 13, 17, 37, 11]
-```
diff --git a/python/output/2/4.txt b/python/output/2/4.txt
deleted file mode 100644
index 8188169..0000000
--- a/python/output/2/4.txt
+++ /dev/null
@@ -1,24 +0,0 @@
-```
-Welcome to number guessing game
-Try to guess the secret random number between 1 to 10 correctly in 3 tries
-Enter a guess: 10
-Wrong guess! Try again.
-Enter a guess: 8
-Wrong guess! Try again.
-Enter a guess: 3
-Wrong guess! Game over!
-Secret value was 5
-Do you want to try playing again (y/n, default n): y
-Enjoy your next play
-
-Welcome to number guessing game
-Try to guess the secret random number between 1 to 10 correctly in 3 tries
-Enter a guess: 8
-Wrong guess! Try again.
-Enter a guess: 3
-Wrong guess! Try again.
-Enter a guess: 4
-Correct guess in 3 tries!
-Do you want to try playing again (y/n, default n): 
-Thanks for playing. Bye!
-```
diff --git a/python/output/2/6.txt b/python/output/2/6.txt
deleted file mode 100644
index 32f6729..0000000
--- a/python/output/2/6.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-```
-Enter a string: Hello World ABCDE 123456
-Number of
-  Uppercase characters: 7
-  Lowercase characters: 8
-  Digits: 6
-```
\ No newline at end of file
diff --git a/python/output/3/3.txt b/python/output/3/3.txt
deleted file mode 100644
index e2163f7..0000000
--- a/python/output/3/3.txt
+++ /dev/null
@@ -1,9 +0,0 @@
-```
-Enter your full name: Sudipto Mallick
-Your name in reverse: Mallick, Sudipto
-```
-```
-Enter your full name: Ayush Kumar Shukla
-Your name in reverse: Shukla, Ayush
-```
-
diff --git a/python/output/3/5.txt b/python/output/3/5.txt
deleted file mode 100644
index 11fdc1d..0000000
--- a/python/output/3/5.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-```
-Enter a line of text: The trend towards remote work has accelerated in recent years, with many companies adopting a hybrid or fully remote model. It offers employees more flexibility and can lead to increased productivity and job satisfaction.
-Given text with all vowels removed: Th trnd twrds rmt wrk hs cclrtd n rcnt yrs, wth mny cmpns dptng  hybrd r flly rmt mdl. t ffrs mplys mr flxblty nd cn ld t ncrsd prdctvty nd jb stsfctn.
-```
diff --git a/python/output/3/7.txt b/python/output/3/7.txt
deleted file mode 100644
index 23b872f..0000000
--- a/python/output/3/7.txt
+++ /dev/null
@@ -1,9 +0,0 @@
-```
-Enter an E-mail address: user@example.net
-Username: user
-Domain: example.net
-```
-```
-Enter an E-mail address: abcdefghi
-abcdefghi is not a valid E-mail address
-```
e/test/tc_newkeys.py?h=v1.1.1&id=2feb26dea6e9e55cf6bc0933baefd9fad99f5507'>^
d8cd2b75 ^



cfe081ec ^
d8cd2b75 ^






8d56a585 ^
d8cd2b75 ^


cfe081ec ^
d8cd2b75 ^
















e5c44775 ^



d8cd2b75 ^










d8cd2b75 ^
ca909b9a ^

39db95d9 ^








95e3dfb1 ^
39db95d9 ^


ca909b9a ^














cfe081ec ^































d8cd2b75 ^
ca909b9a ^
cfe081ec ^
d8cd2b75 ^









cfe081ec ^

d8cd2b75 ^
e5c44775 ^






95e3dfb1 ^

cfe081ec ^
95e3dfb1 ^

d8cd2b75 ^

cfe081ec ^

d8cd2b75 ^


e5c44775 ^





cfe081ec ^
d8cd2b75 ^

39db95d9 ^
d8cd2b75 ^
ca909b9a ^
95e3dfb1 ^
8d56a585 ^


95e3dfb1 ^

8d56a585 ^
95e3dfb1 ^
8d56a585 ^
d8cd2b75 ^
cfe081ec ^
d8cd2b75 ^

8d56a585 ^

d8cd2b75 ^
8d56a585 ^
ca909b9a ^




d8cd2b75 ^
39db95d9 ^
cfe081ec ^

39db95d9 ^



cfe081ec ^
e5c44775 ^
39db95d9 ^

2feb26de ^
39db95d9 ^
cfe081ec ^


39db95d9 ^







e5c44775 ^


cfe081ec ^
39db95d9 ^



e5c44775 ^
39db95d9 ^


d8cd2b75 ^
4ba2112b ^
cfe081ec ^

4ba2112b ^









cfe081ec ^

4ba2112b ^








ca909b9a ^
cfe081ec ^

ca909b9a ^








cfe081ec ^
ca909b9a ^






cfe081ec ^

ca909b9a ^

e5c44775 ^
cfe081ec ^

e5c44775 ^







cfe081ec ^
e5c44775 ^










cfe081ec ^
e5c44775 ^



d8cd2b75 ^
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
              




                                                            

                                  



                              


                       
              

             



























                                                    
                          






                                                                     


                                                                                         
                                          
                                                
                                                













                                                        


                                                                          
 
                                      

                                                                    
 
                                                                         


                                                                          
                                                               
                                         


                                                    





                                                                         
                    
                                                                      





                                                                          
                                                                 




                                                                                       












                                                                                 
                                   
                           
 

                                        
                                                                  









                                                                             
                                                                                     

                                                                                 
                                                        
                                                                             
                                                                                     






                                                     
                                 
                                                                     
                                                           

                                                        



                                    
                                 
                                 
                                   

                                           

                                                     



                                                                 












                                                                   















































                                                                                 
















                                                                      

                                                
                                             


                                  
                                                          


                                                             




                                           


                                                                 
                                        


                                                    



                                   
                                                






                                                                                       
                                   


                                                                               
                      
















                                                                              



                                                             










                                             
 

                                                     








                                                                                    
                                                                    


                                                  














                                                                                    































                                                                                        
                           
                                      
                            









                                                             

                                     
                                              






                                                                

                                             
                                               

                                                      

                                 

                                     


                                                           





                                                                           
                                    

                                                           
                                             
 
                                                   
                                                  


                                                    

                                                                                 
                                                   
                                                     
                                                  
 
                                    

                                                             

                                                                   
 
                                                  




                                                                       
 
                               

                                     



                                                           
                                                                
 

                                                        
                                                                       
 


                                                       







                                                                


                                                                                    
                                                   



                                                              
                                                      


                                                        
 
                                           

                                     









                                                           

                                                            








                                                                       
                                   

                                     








                                                           
                                                  






                                                    

                                                                                   

                          
                                               

                                     







                                                           
                                          










                                                    
                                                         



                                                     
                                 
# coding=utf-8
if __name__ == '__main__': from __init__ import init; init()
from unittest import TestCase, main

from inspect import isfunction, getargspec
import inspect
import sys
from string import ascii_lowercase
try:
	from sys import intern
except:
	pass

FUNC = 'func'
DIRECTION = 'direction'
DIRARG = 'dir'
DIRKEY = 9001
ANYKEY = 9002

def to_string(i):
	"""convert a ord'd integer to a string"""
	try:
		return chr(i)
	except ValueError:
		return '?'

def is_ascii_digit(n):
	return n >= 48 and n <= 57

class Direction(object):
	"""An object with a down and right method"""
	def __init__(self, down=0, right=0):
		self.down = down
		self.right = right

	def copy(self):
		new = type(self)()
		new.__dict__.update(self.__dict__)
		return new

	def __mul__(self, other):
		copy = self.copy()
		if other is not None:
			copy.down *= other
			copy.right *= other
		return copy
	__rmul__ = __mul__

class CommandArgs(object):
	"""The arguments which are passed to a keybinding function"""
	def __init__(self, fm, widget, keybuffer):
		self.fm = fm
		self.wdg = widget
		self.keybuffer = keybuffer
		self.n = keybuffer.quant
		self.direction = keybuffer.directions and keybuffer.directions[0] or None
		self.directions = keybuffer.directions
		self.keys = str(keybuffer)
		self.matches = keybuffer.matches
		self.binding = keybuffer.command

class KeyBuffer(object):
	"""The evaluator and storage for pressed keys"""
	def __init__(self, keymap, direction_keys):
		self.keymap = keymap
		self.direction_keys = direction_keys
		self.clear()

	def add(self, key):
		if self.failure:
			return None
		assert isinstance(key, int)
		assert key >= 0

		# evaluate quantifiers
		if self.eval_quantifier and self._do_eval_quantifier(key):
			return

		# evaluate the command
		if self.eval_command and self._do_eval_command(key):
			return

		# evaluate (the first number of) the direction-quantifier
		if self.eval_quantifier and self._do_eval_quantifier(key):
			return

		# evaluate direction keys {j,k,gg,pagedown,...}
		if not self.eval_command:
			self._do_eval_direction(key)

	def _do_eval_direction(self, key):
		# swap quant and direction_quant in bindings like '<dir>'
		if self.quant is not None and self.command is None \
		and self.direction_quant is None:
			self.direction_quant = self.quant
			self.quant = None

		try:
			assert isinstance(self.dir_tree_pointer, dict)
			self.dir_tree_pointer = self.dir_tree_pointer[key]
		except KeyError:
			self.failure = True
		else:
			if not isinstance(self.dir_tree_pointer, dict):
				match = self.dir_tree_pointer
				assert isinstance(match, Binding)
				direction = match.actions['dir'] * self.direction_quant
				self.directions.append(direction)
				self.direction_quant = None
				self.eval_command = True
				self._try_to_finish()

	def _do_eval_quantifier(self, key):
		if self.eval_command:
			tree = self.tree_pointer
		else:
			tree = self.dir_tree_pointer
		if is_ascii_digit(key) and ANYKEY not in tree:
			attr = self.eval_command and 'quant' or 'direction_quant'
			if getattr(self, attr) is None:
				setattr(self, attr, 0)
			setattr(self, attr, getattr(self, attr) * 10 + key - 48)
		else:
			self.eval_quantifier = False
			return None
		return True

	def _do_eval_command(self, key):
		try:
			assert isinstance(self.tree_pointer, dict)
			self.tree_pointer = self.tree_pointer[key]
		except TypeError:
			print(self.tree_pointer)
			self.failure = True
			return None
		except KeyError:
			if DIRKEY in self.tree_pointer:
				self.eval_command = False
				self.eval_quantifier = True
				self.tree_pointer = self.tree_pointer[DIRKEY]
				assert isinstance(self.tree_pointer, (Binding, dict))
				self.dir_tree_pointer = self.direction_keys._tree
			elif ANYKEY in self.tree_pointer:
				self.matches.append(key)
				self.tree_pointer = self.tree_pointer[ANYKEY]
				assert isinstance(self.tree_pointer, (Binding, dict))
				self._try_to_finish()
			else:
				self.failure = True
				return None
		else:
			self._try_to_finish()

	def _try_to_finish(self):
		assert isinstance(self.tree_pointer, (Binding, dict))
		if not isinstance(self.tree_pointer, dict):
			self.command = self.tree_pointer
			self.done = True

	def clear(self):
		self.failure = False
		self.done = False
		self.quant = None
		self.matches = []
		self.command = None
		self.direction_quant = None
		self.directions = []
		self.all_keys = []
		self.tree_pointer = self.keymap._tree
		self.dir_tree_pointer = self.direction_keys._tree

		self.eval_quantifier = True
		self.eval_command = True

	def __str__(self):
		"""returns a concatenation of all characters"""
		return "".join(to_string(c) for c in self.all_keys)

	def simulate_press(self, string):
		for char in string:
			self.add(ord(char))
			if self.done:
				return self.command
			if self.failure:
				break

key_map = {
	'dir': DIRKEY,
	'any': ANYKEY,
	'cr': ord("\n"),
	'enter': ord("\n"),
	'space': ord(" "),
	'space': ord(" "),
	'tab': ord('\t'),
}
for char in ascii_lowercase:
	key_map['c-' + char] = ord(char) - 96

def translate_keys(obj):
	assert isinstance(obj, (tuple, int, str))
	if isinstance(obj, tuple):
		for char in obj:
			yield char
	elif isinstance(obj, int):
		yield obj
	elif isinstance(obj, str):
		in_brackets = False
		bracket_content = None
		for char in obj:
			if in_brackets:
				if char == '>':
					in_brackets = False
					string = ''.join(bracket_content).lower()
					try:
						yield key_map[string]
					except KeyError:
						yield ord('<')
						for c in bracket_content:
							yield ord(c)
						yield ord('>')
				else:
					bracket_content.append(char)
			else:
				if char == '<':
					in_brackets = True
					bracket_content = []
				else:
					yield ord(char)
		if in_brackets:
			yield ord('<')
			for c in bracket_content:
				yield ord(c)

class KeyMap(object):
	"""Contains a tree with all the keybindings"""
	def __init__(self):
		self._tree = dict()

	def add(self, *args, **keywords):
		if keywords:
			return self.add_binding(*args, **keywords)
		firstarg = args[0]
		if isfunction(firstarg):
			keywords[FUNC] = firstarg
			return self.add_binding(*args[1:], **keywords)
		def decorator_function(func):
			keywords = {FUNC:func}
			self.add(*args, **keywords)
			return func
		return decorator_function

	def add_binding(self, *keys, **actions):
		assert keys
		bind = Binding(keys, actions)

		for key in keys:
			assert key
			chars = tuple(translate_keys(key))
			tree = self.traverse_tree(chars[:-1])
			if isinstance(tree, dict):
				tree[chars[-1]] = bind

	def traverse_tree(self, generator):
		tree = self._tree
		for char in generator:
			try:
				newtree = tree[char]
				if not isinstance(newtree, dict):
					raise KeyError()
			except KeyError:
				newtree = dict()
				tree[char] = newtree
			tree = newtree
		return tree

	def __getitem__(self, key):
		tree = self._tree
		for char in translate_keys(key):
			try:
				tree = tree[char]
			except TypeError:
				raise KeyError("trying to enter leaf")
			except KeyError:
				raise KeyError(str(char) + " not in tree " + str(tree))
		try:
			return tree
		except KeyError:
			raise KeyError(str(char) + " not in tree " + str(tree))

class Binding(object):
	"""The keybinding object"""
	def __init__(self, keys, actions):
		assert hasattr(keys, '__iter__')
		assert isinstance(actions, dict)
		self.keys = set(keys)
		self.actions = actions
		try:
			self.function = self.actions[FUNC]
		except KeyError:
			self.function = None
			self.has_direction = False
		else:
			argnames = getargspec(self.function)[0]
			try:
				self.has_direction = actions['with_direction']
			except KeyError:
				self.has_direction = DIRECTION in argnames
		try:
			self.direction = self.actions[DIRARG]
		except KeyError:
			self.direction = None

	def add_keys(self, keys):
		assert isinstance(keys, set)
		self.keys |= keys

	def has(self, action):
		return action in self.actions

	def action(self, key):
		return self.actions[key]


class PressTestCase(TestCase):
	"""Some useful methods for the actual test"""
	def _mkpress(self, keybuffer, keymap):
		def press(keys):
			keybuffer.clear()
			match = keybuffer.simulate_press(keys)
			self.assertFalse(keybuffer.failure,
					"parsing keys '"+keys+"' did fail!")
			self.assertTrue(keybuffer.done,
					"parsing keys '"+keys+"' did not complete!")
			arg = CommandArgs(None, None, keybuffer)
			self.assert_(match.function, match.__dict__)
			return match.function(arg)
		return press

	def assertPressFails(self, kb, keys):
		kb.clear()
		kb.simulate_press(keys)
		self.assertTrue(kb.failure, "Keypress did not fail as expected")
		kb.clear()

	def assertPressIncomplete(self, kb, keys):
		kb.clear()
		kb.simulate_press(keys)
		self.assertFalse(kb.failure, "Keypress failed, expected incomplete")
		self.assertFalse(kb.done, "Keypress done which was unexpected")
		kb.clear()

class Test(PressTestCase):
	"""The test cases"""
	def test_translate_keys(self):
		def test(string, *args):
			if not args:
				args = (string, )
			self.assertEqual(ordtuple(*args), tuple(translate_keys(string)))

		def ordtuple(*args):
			lst = []
			for arg in args:
				if isinstance(arg, str):
					lst.extend(ord(c) for c in arg)
				else:
					lst.append(arg)
			return tuple(lst)

		test('k')
		test('kj')
		test('k<dir>', 'k', DIRKEY)
		test('k<ANY>z<any>', 'k', ANYKEY, 'z', ANYKEY)
		test('k<anY>z<dir>', 'k', ANYKEY, 'z', DIRKEY)
		test('<cr>', "\n")
		test('<tab><tab><cr>', "\t\t\n")
		test('<')
		test('>')
		test('<C-a>', 1)
		test('k<a')
		test('k<anz>')
		test('k<a<nz>')
		test('k<a<nz>')
		test('k<a<>nz>')
		test('>nz>')

	def test_add(self):
		# depends on internals
		c = KeyMap()
		c.add(lambda *_: 'lolz', 'aa', 'b')
		self.assert_(c['aa'].actions[FUNC](), 'lolz')
		@c.add('a', 'c')
		def test():
			return 5
		self.assert_(c['b'].actions[FUNC](), 'lolz')
		self.assert_(c['c'].actions[FUNC](), 5)
		self.assert_(c['a'].actions[FUNC](), 5)

	def test_quantifier(self):
		km = KeyMap()
		directions = KeyMap()
		kb = KeyBuffer(km, directions)
		def n(value):
			"""return n or value"""
			def fnc(arg=None):
				if arg is None or arg.n is None:
					return value
				return arg.n
			return fnc
		km.add(n(5), 'p')
		press = self._mkpress(kb, km)
		self.assertEqual(5, press('p'))
		self.assertEqual(3, press('3p'))
		self.assertEqual(6223, press('6223p'))

	def test_direction(self):
		km = KeyMap()
		directions = KeyMap()
		kb = KeyBuffer(km, directions)
		directions.add('j', dir=Direction(down=1))
		directions.add('k', dir=Direction(down=-1))
		def nd(arg):
			""" n * direction """
			n = arg.n is None and 1 or arg.n
			dir = arg.direction is None and Direction(down=1) \
					or arg.direction
			return n * dir.down
		km.add(nd, 'd<dir>')
		km.add('dd', func=nd, with_direction=False)

		press = self._mkpress(kb, km)

		self.assertPressIncomplete(kb, 'd')
		self.assertEqual(  1, press('dj'))
		self.assertEqual(  3, press('3ddj'))
		self.assertEqual( 15, press('3d5j'))
		self.assertEqual(-15, press('3d5k'))
		# supporting this kind of key combination would be too confusing:
		# self.assertEqual( 15, press('3d5d'))
		self.assertEqual(  3, press('3dd'))
		self.assertEqual(  33, press('33dd'))
		self.assertEqual(  1, press('dd'))

		km.add(nd, 'x<dir>')
		km.add('xxxx', func=nd, with_direction=False)

		self.assertEqual(1, press('xxxxj'))
		self.assertEqual(1, press('xxxxjsomeinvalitchars'))

		# these combinations should break:
		self.assertPressFails(kb, 'xxxj')
		self.assertPressFails(kb, 'xxj')
		self.assertPressFails(kb, 'xxkldfjalksdjklsfsldkj')
		self.assertPressFails(kb, 'xyj')
		self.assertPressIncomplete(kb, 'x') # direction missing

	def test_any_key(self):
		km = KeyMap()
		directions = KeyMap()
		kb = KeyBuffer(km, directions)
		directions.add('j', dir=Direction(down=1))
		directions.add('k', dir=Direction(down=-1))

		directions.add('g<any>', dir=Direction(down=-1))

		def cat(arg):
			n = arg.n is None and 1 or arg.n
			return ''.join(chr(c) for c in arg.matches) * n

		km.add(cat, 'return<any>')
		km.add(cat, 'cat4<any><any><any><any>')
		km.add(cat, 'foo<dir><any>')

		press = self._mkpress(kb, km)

		self.assertEqual('x', press('returnx'))
		self.assertEqual('abcd', press('cat4abcd'))
		self.assertEqual('abcdabcd', press('2cat4abcd'))
		self.assertEqual('55555', press('5return5'))

		self.assertEqual('x', press('foojx'))
		self.assertPressFails(kb, 'fooggx')  # ANYKEY forbidden in DIRECTION

		km.add(lambda _: Ellipsis, '<any>')
		self.assertEqual('x', press('returnx'))
		self.assertEqual('abcd', press('cat4abcd'))
		self.assertEqual(Ellipsis, press('2cat4abcd'))
		self.assertEqual(Ellipsis, press('5return5'))
		self.assertEqual(Ellipsis, press('g'))
		self.assertEqual(Ellipsis, press('ß'))
		self.assertEqual(Ellipsis, press('ア'))
		self.assertEqual(Ellipsis, press('9'))

	def test_multiple_directions(self):
		km = KeyMap()
		directions = KeyMap()
		kb = KeyBuffer(km, directions)
		directions.add('j', dir=Direction(down=1))
		directions.add('k', dir=Direction(down=-1))

		def add_dirs(arg):
			n = 0
			for dir in arg.directions:
				n += dir.down
			return n

		km.add(add_dirs, 'x<dir>y<dir>')
		km.add(add_dirs, 'four<dir><dir><dir><dir>')

		press = self._mkpress(kb, km)

		self.assertEqual(2, press('xjyj'))
		self.assertEqual(0, press('fourjkkj'))
		self.assertEqual(2, press('four2j4k2j2j'))
		self.assertEqual(10, press('four1j2j3j4j'))
		self.assertEqual(10, press('four1j2j3j4jafslkdfjkldj'))

	def test_corruptions(self):
		km = KeyMap()
		directions = KeyMap()
		kb = KeyBuffer(km, directions)
		press = self._mkpress(kb, km)
		directions.add('j', dir=Direction(down=1))
		directions.add('k', dir=Direction(down=-1))
		km.add('xxx', func=lambda _: 1)

		self.assertEqual(1, press('xxx'))

		# corrupt the tree
		tup = tuple(translate_keys('xxx'))
		subtree = km.traverse_tree(tup[:-1])
		subtree[tup[-1]] = "Boo"

		self.assertPressFails(kb, 'xxy')
		self.assertPressFails(kb, 'xzy')
		self.assertPressIncomplete(kb, 'xx')
		self.assertPressIncomplete(kb, 'x')
		if not sys.flags.optimize:
			self.assertRaises(AssertionError, kb.simulate_press, 'xxx')
		kb.clear()

	def test_directions_as_functions(self):
		km = KeyMap()
		directions = KeyMap()
		kb = KeyBuffer(km, directions)
		press = self._mkpress(kb, km)

		def move(arg):
			return arg.direction.down

		directions.add('j', dir=Direction(down=1))
		directions.add('k', dir=Direction(down=-1))
		km.add('<dir>', func=move)

		self.assertEqual(1, press('j'))
		self.assertEqual(-1, press('k'))

		km.add('k', func=lambda _: 'love')

		self.assertEqual(1, press('j'))
		self.assertEqual('love', press('k'))

		self.assertEqual(40, press('40j'))

		km.add('<dir><dir><any><any>', func=move)

		self.assertEqual(40, press('40jkhl'))


if __name__ == '__main__': main()