Last active
October 13, 2019 17:13
-
-
Save 3m3x/fc08d700b4d0f2c99bf26cc390080ab8 to your computer and use it in GitHub Desktop.
A motley crew of useful things you might want to do (in Python)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # | |
| # Make 1024 binary numbers | |
| # | |
| import itertools | |
| binary_numbers = [''.join(digits) | |
| for digits in itertools.product(*[['0', '1'] for _ in range(10)])] | |
| print(binary_numbers) | |
| # | |
| # Use types to enforce types of values used in an LRU cache | |
| # | |
| from typing import Generic, TypeVar, Any | |
| T = TypeVar('T') | |
| class TypedLRUCache(Generic[T]): | |
| def __init__(self, max_size: int = 256) -> None: | |
| raise NotImplementedError | |
| def get(self, key: Any, default: T) -> T: | |
| raise NotImplementedError | |
| def put(self, key: Any, value: T) -> None: | |
| raise NotImplementedError | |
| example_cache = TypedLRUCache[str](max_size=10) | |
| example_cache.put("first_name", 10) # Fails because 10 is not a str | |
| # | |
| # Very simple SSL-enabled HTTP endpoint | |
| # | |
| import BaseHTTPServer | |
| import ssl | |
| class Handler(BaseHTTPServer.BaseHTTPRequestHandler): | |
| def do_GET(self): | |
| self.send_response(302) | |
| self.send_header('Location', 'http://localhost:8000/') | |
| self.end_headers() | |
| self.wfile.write('') | |
| httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), Handler) | |
| httpd.socket = ssl.wrap_socket (httpd.socket, server_side=True, | |
| certfile='yourpemfile.pem') | |
| httpd.serve_forever() | |
| # | |
| # char/number conversion stuff | |
| # | |
| '\n'.encode('hex') # python2: '0a' | |
| print('\x0a') # python2: prints a string containing a newline | |
| "7a7a7a7a".decode('hex') # python2: "zzzz" | |
| bytes.fromhex('7a7a7a7a').decode() # python3: "zzzz" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment