You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

870 lines
16 KiB

6 years ago
7 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
  1. Comprehensive Python Cheatsheet
  2. ===============================
  3. ![Monty Python](web/image_888.jpeg)
  4. Main
  5. ----
  6. ```python
  7. if __name__ == '__main__':
  8. main()
  9. ```
  10. List
  11. ----
  12. ```python
  13. <list>[from_inclusive : to_exclusive : step_size]
  14. <list>.append(<el>)
  15. <list>.extend(<list>)
  16. <list>.sort()
  17. <list>.reverse()
  18. <list> = sorted(<list>)
  19. <list> = reversed(<list>)
  20. ```
  21. ```python
  22. sum_of_elements = sum(<list>)
  23. sorted_by_second = sorted(<list>, key=lambda el: el[1])
  24. flattened_list = [item for sublist in <list> for item in sublist]
  25. list_of_chars = list(<str>)
  26. ```
  27. Dictionary
  28. ----------
  29. ```python
  30. <dict>.items()
  31. <dict>.get(key, default)
  32. <dict>.setdefault(key, default)
  33. <dict>.update(<dict>)
  34. ```
  35. ```python
  36. collections.defaultdict(<type>) # Creates a dictionary with default values.
  37. dict(<list>) # Initiates a dict from list of key/value pairs.
  38. dict(zip(keys, values)) # Initiates a dict from two lists.
  39. {k: v for k, v in <dict>.items() if k in <list>} # Filters a dict by keys.
  40. ```
  41. ### Counter
  42. ```python
  43. >>> from collections import Counter
  44. >>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
  45. >>> Counter(z)
  46. Counter({'blue': 3, 'red': 2, 'yellow': 1})
  47. ```
  48. Set
  49. ---
  50. ```python
  51. <set> = set()
  52. <set>.add(<el>)
  53. <set>.update(<set>)
  54. <set>.union(<set>)
  55. <set>.intersection(<set>)
  56. <set>.difference(<set>)
  57. <set>.issubset(<set>)
  58. <set>.issuperset(<set>)
  59. ```
  60. ### Frozenset
  61. #### Is hashable and can be used as a key in dictionary:
  62. ```python
  63. <frozenset> = frozenset()
  64. ```
  65. Range
  66. -----
  67. ```python
  68. range(to_exclusive)
  69. range(from_inclusive, to_exclusive)
  70. range(from_inclusive, to_exclusive, step_size)
  71. range(from_inclusive, to_exclusive, -step_size)
  72. ```
  73. Enumerate
  74. ---------
  75. ```python
  76. for i, <el> in enumerate(<collection> [, i_start])
  77. ```
  78. Named Tuple
  79. -----------
  80. ```python
  81. >>> Point = collections.namedtuple('Point', ['x', 'y'])
  82. >>> a = Point(1, y=2)
  83. Point(x=1, y=2)
  84. >>> a.x
  85. 1
  86. >>> getattr(a, 'y')
  87. 2
  88. ```
  89. Iterator
  90. --------
  91. #### Skips first element:
  92. ```python
  93. next(<iter>)
  94. for element in <iter>:
  95. ...
  96. ```
  97. #### Reads input until it reaches an empty line:
  98. ```python
  99. for line in iter(input, ''):
  100. ...
  101. ```
  102. #### Same, but prints a message every time:
  103. ```python
  104. from functools import partial
  105. for line in iter(partial(input, 'Please enter value'), ''):
  106. ...
  107. ```
  108. Generator
  109. ---------
  110. ```python
  111. def step(start, step):
  112. while True:
  113. yield start
  114. start += step
  115. ```
  116. ```python
  117. stepper = step(10, 2)
  118. next(stepper) # 10 (, 12, 14, ...)
  119. ```
  120. Type
  121. ----
  122. ```python
  123. type(<el>) # <class 'int'> / <class 'str'> / ...
  124. ```
  125. ```python
  126. import numbers
  127. isinstance(<el>, numbers.Number) # Integral, Real, Rational, Complex
  128. ```
  129. String
  130. ------
  131. ```python
  132. str.replace(text, old, new)
  133. <str>.split(sep=None, maxsplit=-1)
  134. <str>.strip()
  135. <str>.join(<list>)
  136. <str>.startswith(<str>)
  137. <str>.isnumeric()
  138. ```
  139. ### Print
  140. ```python
  141. print(<el> [, <el>, end='', sep='', file=<file>])
  142. ```
  143. ### Regex
  144. ```python
  145. import re
  146. re.sub(<regex>, new, text, count=0)
  147. re.search(<regex>, text) # Searches for first occurrence of pattern.
  148. re.match(<regex>, text) # Searches only at the beginning of the string.
  149. re.findall(<regex>, text)
  150. re.split(<regex>, text, maxsplit=0) # Use brackets in regex to keep the matches.
  151. ```
  152. **'Search' and 'match' functions return a 'Match' object. Use '.group()' method on it to get the whole match, or '.group(1)' to get the part in first bracket.**
  153. **Parameter 'flags=re.IGNORECASE' can be used with all functions. Parameter 'flags=re.DOTALL' makes dot also accept newline.**
  154. **Use '\\\\1' or r'\1' for backreference.**
  155. #### Special Sequences:
  156. ```python
  157. # Use capital letter for negation.
  158. '\d' == '[0-9]' # Digit
  159. '\s' == '[ \t\n\r\f\v]' # Whitespace
  160. '\w' == '[a-zA-Z0-9_]' # Alphanumeric
  161. ```
  162. ### Format
  163. ```python
  164. '{}'.format(<el> [, <el>, ...])
  165. ```
  166. ```python
  167. {:min_width} # '<el> '
  168. {:>min_width} # ' <el>'
  169. {:^min_width} # ' <el> '
  170. {:_<min_width} # '<el>____'
  171. {:.max_width} # '<e>'
  172. {:max_width.min_width} # ' <e>'
  173. {:max_width.no_of_decimalsf} # ' 3.14'
  174. ```
  175. ```python
  176. >>> person = {'name': 'Jean-Luc', 'height': 187.1}
  177. >>> '{p[height]:.0f}'.format(p=person)
  178. '187'
  179. >>> f"{person['height']:.0f}"
  180. '187'
  181. ```
  182. ```python
  183. >>> f'{123:020b}'
  184. '00000000000001111011'
  185. ```
  186. #### Integer presentation types:
  187. * 'b' - Binary
  188. * 'c' - Character
  189. * 'o' - Octal
  190. * 'x' - Hex
  191. * 'X' - HEX
  192. ### Text Wrap
  193. ```python
  194. import textwrap
  195. textwrap.wrap(text, width)
  196. ```
  197. Random
  198. ------
  199. ```python
  200. import random
  201. random.random()
  202. random.randint(from_inclusive, to_inclusive)
  203. random.shuffle(<list>)
  204. random.choice(<list>)
  205. ```
  206. Infinity
  207. --------
  208. ```python
  209. float('inf')
  210. ```
  211. Datetime
  212. --------
  213. ```python
  214. import datetime
  215. now = datetime.datetime.now()
  216. now.month # 3
  217. now.strftime('%Y%m%d') # 20180315
  218. now.strftime('%Y%m%d%H%M%S') # 20180315002834
  219. ```
  220. Arguments
  221. ---------
  222. **"*" is the splat operator, that takes a list as input, and expands it into actual positional arguments in the function call:**
  223. ```python
  224. args = (1, 2)
  225. kwargs = {'x': 3, 'y': 4, 'z': 5}
  226. func(*args, **kwargs)
  227. ```
  228. #### Is the same as:
  229. ```python
  230. func(1, 2, x=3, y=4, z=5)
  231. ```
  232. Inline
  233. ------
  234. ### Lambda
  235. ```python
  236. lambda: <return_value>
  237. lambda <argument1>, <argument2>: <return_value>
  238. ```
  239. ### Comprehension
  240. ```python
  241. [i+1 for i in range(10)] # [1, 2, ..., 10]
  242. [i for i in range(10) if i>5] # [6, 7, ..., 9]
  243. {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18}
  244. (x+5 for x in range(0, 10)) # (5, 6, ..., 14) -> Generator
  245. ```
  246. ```python
  247. [i+j for i in range(10) for j in range(10)]
  248. ```
  249. #### Is the same as:
  250. ```python
  251. out = []
  252. for i in range(10):
  253. for j in range(10):
  254. out.append(i+j)
  255. ```
  256. ### Map, Filter, Reduce
  257. ```python
  258. map(lambda x: x+1, range(10)) # [1, 2, ..., 10]
  259. filter(lambda x: x>5, range(10)) # [6, 7, ..., 9]
  260. functools.reduce(lambda sum, x: sum+x, range(10)) # 45
  261. ```
  262. ### Any, All
  263. ```python
  264. any(el[1] for el in <collection>)
  265. ```
  266. ### If - Else
  267. ```python
  268. <expression_if_true> if <condition> else <expression_if_false>
  269. ```
  270. Closure
  271. -------
  272. ```python
  273. def multiply_closure(x):
  274. def wrapped(y):
  275. return x * y
  276. return wrapped
  277. multiply_by_3 = multiply_closure(3)
  278. ```
  279. #### Or:
  280. ```python
  281. from functools import partial
  282. partial(<function>, <argument>)
  283. ```
  284. Decorator
  285. ---------
  286. ```python
  287. @closure_name
  288. def function_that_gets_passed_to_closure():
  289. pass
  290. ```
  291. #### Debugger example:
  292. ```python
  293. from functools import wraps
  294. def debug(func):
  295. @wraps(func) # Needed for metadata copying (func name, ...).
  296. def wrapper(*args, **kwargs):
  297. print(func.__name__)
  298. return func(*args, **kwargs)
  299. return wrapper
  300. @debug
  301. def add(x, y):
  302. return x + y
  303. ```
  304. Class
  305. -----
  306. ```python
  307. class <name>:
  308. def __init__(self, a):
  309. self.a = a
  310. def __repr__(self):
  311. return str({'a': self.a})
  312. def __str__(self):
  313. return str(self.a)
  314. ```
  315. ### Enum
  316. ```python
  317. import enum
  318. class <enum_name>(enum.Enum):
  319. <name1> = <value1>
  320. <name2> = <value2>
  321. <name3> = enum.auto() # Can be used for automatic indexing.
  322. ...
  323. ```
  324. ```python
  325. <enum_name>.<name> # == <enum>
  326. <enum_name>(value) # == <enum>
  327. <enum>.name # == <name>
  328. <enum>.value # == <value>
  329. ```
  330. ```python
  331. Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon'])
  332. list(<enum_name>) # == [<enum1>, <enum2>, ...]
  333. random.choice(list(<enum_name>)) # == random <enum>
  334. ```
  335. ### Copy
  336. ```python
  337. import copy
  338. copy.copy(<object>)
  339. copy.deepcopy(<object>)
  340. ```
  341. System
  342. ------
  343. ### Arguments
  344. ```python
  345. import sys
  346. sys.argv
  347. ```
  348. ### Read File
  349. ```python
  350. def read_file(filename):
  351. with open(filename, encoding='utf-8') as file:
  352. return file.readlines()
  353. ```
  354. ### Write to File
  355. ```python
  356. def write_to_file(filename, text):
  357. with open(filename, 'w', encoding='utf-8') as file:
  358. file.write(text)
  359. ```
  360. ### Path
  361. ```python
  362. import os
  363. os.path.exists(<path>)
  364. os.path.isfile(<path>)
  365. os.path.isdir(<path>)
  366. os.listdir(<path>)
  367. ```
  368. ### Execute Command
  369. ```python
  370. import os
  371. os.popen(<command>).read()
  372. ```
  373. #### Or:
  374. ```python
  375. >>> import subprocess
  376. >>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE)
  377. >>> a.stdout
  378. b'.\n..\nfile1.txt\nfile2.txt\n'
  379. >>> a.returncode
  380. 0
  381. ```
  382. ### Input
  383. ```python
  384. filename = input('Enter a file name: ')
  385. ```
  386. #### Prints lines until EOF:
  387. ```python
  388. while True:
  389. try:
  390. print(input())
  391. except EOFError:
  392. break
  393. ```
  394. JSON
  395. ----
  396. ```python
  397. import json
  398. ```
  399. ### Serialization
  400. ```python
  401. <str> = json.dumps(<object>, ensure_ascii=True, indent=None)
  402. <object> = json.loads(<str>)
  403. ```
  404. ### Read File
  405. ```python
  406. def read_json_file(filename):
  407. with open(filename, encoding='utf-8') as file:
  408. return json.load(file)
  409. ```
  410. ### Write to File
  411. ```python
  412. def write_to_json_file(filename, an_object):
  413. with open(filename, 'w', encoding='utf-8') as file:
  414. json.dump(an_object, file, ensure_ascii=False, indent=2)
  415. ```
  416. SQLite
  417. ------
  418. ```python
  419. import sqlite3
  420. db = sqlite3.connect(filename)
  421. ```
  422. ### Read
  423. ```python
  424. cursor = db.execute(<query>)
  425. if cursor:
  426. cursor.fetchall() # Or cursor.fetchone()
  427. db.close()
  428. ```
  429. ### Write
  430. ```python
  431. db.execute(<query>)
  432. db.commit()
  433. ```
  434. Exceptions
  435. ----------
  436. ```python
  437. while True:
  438. try:
  439. x = int(input("Please enter a number: "))
  440. except ValueError:
  441. print("Oops! That was no valid number. Try again...")
  442. else:
  443. print("Thank you.")
  444. break
  445. ```
  446. Threading
  447. ---------
  448. ```python
  449. import threading
  450. ```
  451. ### Thread
  452. ```python
  453. thread = threading.Thread(target=<function>, args=(<first_arg>, ))
  454. thread.start()
  455. thread.join()
  456. ```
  457. ### Lock
  458. ```python
  459. lock = threading.Rlock()
  460. lock.acquire()
  461. lock.release()
  462. ```
  463. Itertools
  464. ---------
  465. **Every function returns a generator and can accept any collection. If you want to print an output of generator, as in examples, you need to pass it to the list() function.**
  466. ```python
  467. from itertools import *
  468. ```
  469. ### Chain
  470. ```python
  471. >>> chain([1, 2], range(3, 5))
  472. [1, 2, 3, 4]
  473. ```
  474. ### Combinations
  475. ```python
  476. >>> combinations("abc", 2)
  477. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  478. ```
  479. ### Permutations
  480. ```python
  481. >>> permutations("abc", 2)
  482. [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
  483. ```
  484. ### Product
  485. ```python
  486. >>> list(product('ab', [1, 2]))
  487. [('a', 1), ('a', 2), ('b', 1), ('b', 2)]
  488. ```
  489. ### Compress
  490. ```python
  491. >>> compress("abc", [True, 0, 23])
  492. ['a', 'c']
  493. ```
  494. ### Count
  495. ```python
  496. >>> a = count(5, 2)
  497. >>> next(a), next(a)
  498. (5, 7)
  499. ```
  500. ### Cycle
  501. ```python
  502. >>> a = cycle("abc")
  503. >>> [next(a) for _ in range(10)]
  504. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
  505. ```
  506. ### Groupby
  507. ```python
  508. >>> a = [{"id": 1, "name": "bob"},
  509. {"id": 2, "name": "bob"},
  510. {"id": 3, "name": "peter"}]
  511. >>> {k: list(v) for k, v in groupby(a, key=lambda x: x["name"])}
  512. {'bob': [{'id': 1, 'name': 'bob'},
  513. {'id': 2, 'name': 'bob'}],
  514. 'peter': [{'id': 3, 'name': 'peter'}]}
  515. ```
  516. ### Islice
  517. ```python
  518. islice([1, 2, 3], 1, None)
  519. [2, 3]
  520. ```
  521. ### Ifilter, imap and izip
  522. #### Filter, map and zip functions that return generators instead of iterators.
  523. Introspection and Metaprograming
  524. --------------------------------
  525. **Inspecting code at runtime and code that generates code. You can:**
  526. * **Look at the attributes**
  527. * **Set new attributes**
  528. * **Create functions dynamically**
  529. * **Traverse the parent classes**
  530. * **Change values in the class**
  531. ```python
  532. >>> class B:
  533. ... def __init__(self):
  534. ... self.a= 'sdfsd'
  535. ... self.b = 123324
  536. >>> b = B()
  537. ```
  538. ### Getattr
  539. ```python
  540. >>> getattr(b, 'a')
  541. 'sdfsd'
  542. ```
  543. #### Is the same as:
  544. ```python
  545. B.__getattribute__(b, 'a')
  546. ```
  547. ### Hasattr
  548. ```python
  549. >>> hasattr(b, 'c')
  550. False
  551. ```
  552. ### Setattr
  553. ```python
  554. >>> setattr(b, 'c', 10)
  555. ```
  556. ### Type
  557. **Type is the root class. If only passed the object it returns it's type. Otherwise it creates a new class (and not the instance!):**
  558. ```python
  559. type(class_name, parents<tuple>, attributes<dict>)
  560. ```
  561. ```python
  562. >>> BB = type('B', (), {'a': 'sdfsd', 'b': 123324}
  563. >>> b = BB()
  564. ```
  565. ### MetaClass
  566. #### Class that creates class:
  567. ```python
  568. def my_meta_class(name, parents, attrs):
  569. ...
  570. return type(name, parents, attrs)
  571. ```
  572. #### Or:
  573. ```python
  574. class MyMetaClass(type):
  575. def __new__(klass, name, parents, attrs):
  576. ...
  577. return type.__new__(klass, name, parents, attrs)
  578. ```
  579. ### Metaclass Attr
  580. **When class is created it checks if it has metaclass defined. If not, it recursively checks if any of his parents has it defined, and eventually comes to type:**
  581. ```python
  582. class BlaBla:
  583. __metaclass__ = Bla
  584. ```
  585. Eval
  586. ----
  587. ```python
  588. import ast
  589. import operator as op
  590. # Supported operators
  591. operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
  592. ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
  593. ast.USub: op.neg}
  594. def eval_expr(expr):
  595. return eval_(ast.parse(expr, mode='eval').body)
  596. def eval_(node):
  597. if isinstance(node, ast.Num): # <number>
  598. return node.n
  599. elif isinstance(node, ast.BinOp): # <left> <operator> <right>
  600. return operators[type(node.op)](eval_(node.left), eval_(node.right))
  601. elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
  602. return operators[type(node.op)](eval_(node.operand))
  603. else:
  604. raise TypeError(node)
  605. ```
  606. ```python
  607. >>> eval_expr('2^6')
  608. 4
  609. >>> eval_expr('2**6')
  610. 64
  611. >>> eval_expr('1 + 2*3**(4^5) / (6 + -7)')
  612. -5.0
  613. ```
  614. Libraries
  615. =========
  616. Plot
  617. ----
  618. ```python
  619. from matplotlib import pyplot
  620. pyplot.plot(<data> [, <data>])
  621. pyplot.show()
  622. pyplot.savefig(filename)
  623. ```
  624. Web
  625. ---
  626. ```python
  627. import bottle
  628. import urllib
  629. ```
  630. ### Run
  631. ```python
  632. bottle.run(host='localhost', port=8080)
  633. bottle.run(host='0.0.0.0', port=80, server='cherrypy')
  634. ```
  635. ### Static request
  636. ```python
  637. @route('/img/<image>')
  638. def send_image(image):
  639. return static_file(image, 'images/', mimetype='image/png')
  640. ```
  641. ### Dynamic request
  642. ```python
  643. @route('/<sport>')
  644. def send_page(sport):
  645. sport = urllib.parse.unquote(sport).lower()
  646. page = read_file(sport)
  647. return template(page)
  648. ```
  649. ### REST request
  650. ```python
  651. @post('/p/<sport>')
  652. def p_handler(sport):
  653. team = request.forms.get('team')
  654. team = urllib.parse.unquote(team).lower()
  655. db = sqlite3.connect(conf.DB_PATH)
  656. p_h, p_a = get_p(db, sport, team)
  657. db.close()
  658. response.headers['Content-Type'] = 'application/json'
  659. response.headers['Cache-Control'] = 'no-cache'
  660. return json.dumps([p_h, p_a])
  661. ```
  662. Curses
  663. ------
  664. ```python
  665. import curses
  666. def main():
  667. curses.wrapper(draw)
  668. def draw(screen):
  669. screen.clear()
  670. screen.addstr(0, 0, "Press ESC to quit.")
  671. while screen.getch() != 27:
  672. pass
  673. def get_border(screen):
  674. Coords = collections.namedtuple('Coords', ['x', 'y'])
  675. height, width = screen.getmaxyx()
  676. return Coords(width - 1, height - 1)
  677. ```
  678. #### Gets char from int:
  679. ```python
  680. chr(<int>)
  681. ```
  682. Profile
  683. -------
  684. #### Basic:
  685. ```python
  686. from time import time
  687. start_time = time()
  688. <code>
  689. duration = time() - start_time
  690. ```
  691. #### Times execution of the passed code:
  692. ```python
  693. from timeit import timeit
  694. timeit('"-".join(str(n) for n in range(100))', number=10000)
  695. ```
  696. #### Generates a PNG image of call graph and highlights the bottlenecks:
  697. ```python
  698. import pycallgraph
  699. graph = pycallgraph.output.GraphvizOutput()
  700. graph.output_file = get_filename()
  701. with pycallgraph.PyCallGraph(output=graph):
  702. <code_to_be_profiled>
  703. ```
  704. #### Utility code for unique PNG filenames:
  705. ```python
  706. def get_filename():
  707. return "{}-{}.png".format("profile", get_current_datetime_string())
  708. def get_current_datetime_string():
  709. now = datetime.datetime.now()
  710. return get_datetime_string(now)
  711. def get_datetime_string(a_datetime):
  712. return a_datetime.strftime('%Y%m%d%H%M%S')
  713. ```
  714. Audio
  715. -----
  716. #### Saves list of floats of size 0 to 1 to a WAV file:
  717. ```python
  718. import wave, struct
  719. frames = [struct.pack("%dh"%(1), int((a-0.5)*60000)) for a in <list>]
  720. wf = wave.open(filename, 'wb')
  721. wf.setnchannels(1)
  722. wf.setsampwidth(4)
  723. wf.setframerate(44100)
  724. wf.writeframes(b''.join(frames))
  725. wf.close()
  726. ```