Skip to content

Instantly share code, notes, and snippets.

View luisenriquecorona's full-sized avatar
😎
I may be slow to respond.

TextKi JS luisenriquecorona

😎
I may be slow to respond.
View GitHub Profile
@luisenriquecorona
luisenriquecorona / StrKeyDict0.py
Created December 23, 2019 19:08
Underlying the way mappings deal with missing keys is the aptly named __missing__ method. This method is not defined in the base dict class, but dict is aware of it: if you subclass dict and provide a __missing__ method, the standard dict.__getitem__will call it whenever a key is not found, instead of raising KeyError.
class StrKeyDict0(dict):
def __missing__(self, key):
if isinstance(key, str):
raise KeyError(key)
return self[str(key)]
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
@luisenriquecorona
luisenriquecorona / Index0.py
Created December 23, 2019 18:08
In line with the fail-fast philosophy, dict access with d[k] raises an error when k is not an existing key. Every Pythonista knows that d.get(k, default) is an alternative to d[k] whenever a default value is more convenient than handling KeyError.
import sys
import re
WORD_RE = re.compile('\w+')
index = {}
with open(sys.argv[1], encoding='utf-8') as fp:
for line_no, line in enumerate(fp, 1):
for match in WORD_RE.finditer(line):
word = match.group()
column_no = match.start()+1
location = (line_no, column_no)
@luisenriquecorona
luisenriquecorona / Bisect.insort.py
Created December 23, 2019 17:54
Sorting is expensive, so once you have a sorted sequence, it’s good to keep it that way. That is why bisect.insort was created.
import bisect
import random
SIZE = 7
random.seed(1729)
my_list = []
for i in range(SIZE):
new_item = random.randrange(SIZE*2)
bisect.insort(my_list, new_item)
print('%2d ->' % new_item, my_list)
@luisenriquecorona
luisenriquecorona / Graphic.py
Created December 21, 2019 03:57
bisect(haystack, needle) does a binary search for needle in haystack — which must be a sorted sequence — to locate the position where needle can be inserted while maintaining haystack in ascending order. In other words, all items appearing up to that position are less or equal to needle.
import bisect
import sys
HAYSTACK = [1, 4, 5, 6, 8, 12, 15, 20, 21, 23, 23, 26, 29, 30]
NEEDLES = [0, 1, 2, 5, 8, 10, 22, 23, 29, 30, 31]
ROW_FMT = '{0:2d} @ {1:2d} {2}{0:<2d}'
def demo(bisect_fn):
for needle in reversed(NEEDLES):
position = bisect_fn(HAYSTACK, needle)
offset = position * ' |'
print(ROW_FMT.format(needle, position, offset))
@luisenriquecorona
luisenriquecorona / Metro.py
Created December 19, 2019 05:38
The tuple to receive an expression to unpack can have nested tuples, like (a, b, (c, d)) and Python will do the right thing if the expression matches the nesting structure.
metro_areas = [
('Tokyo', 'JP', 36.933, (35.689722, 139.691667)),
('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)),
('Mexico City', 'MX', 20.142, (19.433333, -99.133333)),
('New York-Newark', 'US', 20.104, (40.808611, -74.020386)),
('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833)),
]
print('{:15} | {:^9} | {:^9}'.format('', 'lat.', 'long.'))
fmt = '{:15} | {:9.4f} | {:9.4f}'
for name, cc, pop, (latitude, longitude) in metro_areas:
Programa: rectangulo.py
Propósito: Calcula el perímetro y el área de un rectángulo a partir de su altura y anchura.
Autor: @soyluiscorona
Fecha: 1/1/2020
Petición de los datos (en metros)
altura float input
anchura float input
function longCode() {
var tStart = Number(new Date());
while( (tStart + 5000) > Number(new Date()) ) {}; }
window.onload = longCode;
@luisenriquecorona
luisenriquecorona / npm-from-git.sh
Created November 18, 2019 01:36 — forked from wmakeev/npm-from-git.sh
npm #npm #git
# https://docs.npmjs.com/cli/install
# 1
npm install <protocol>://[<user>[:<password>]@]<hostname>[:<port>][:][/]<path>[#<commit-ish>]
## Examples
npm install git+https://[email protected]/visionmedia/express.git
npm install git+https://[email protected]/visionmedia/express.git#branch
# 2
npm install <githubname>/<githubrepo>[#<commit-ish>]
@luisenriquecorona
luisenriquecorona / addHandler.js
Created November 5, 2019 21:13
The first way to eliminate work repetition in functions is through lazy loading. Lazy loading means that no work is done until the information is necessary.
function addHandler(target, eventType, handler){
//overwrite the existing function
if (target.addEventListener){ //DOM2 Events
addHandler = function(target, eventType, handler){
target.addEventListener(eventType, handler, false);
};
} else { //IE
addHandler = function(target, eventType, handler){
target.attachEvent("on" + eventType, handler);
};
@luisenriquecorona
luisenriquecorona / parseJSON.js
Created November 3, 2019 03:46
Successful parsing requires that the order of the data must be maintained. That being said, it is trivial to convert this format into one that maintains the same attribute names as the first JSON format:
function parseJSON(responseText) {
var users = [];
var usersArray = eval('(' + responseText + ')');
for (var i = 0, len = usersArray.length; i < len; i++) {
users[i] = {
id: usersArray[i][0],
username: usersArray[i][1],
realname: usersArray[i][2],
email: usersArray[i][3]
};