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 / Enhanced date validation function.js
Last active May 20, 2020 16:46
In a high-volume data-entry environment, where productivity is measured in opera- tors’ keystrokes and time spent per form, you want to build more intelligence in a form. For example, you want to allow two-digit year entries, but code the validation routine so that it fills the field with the expanded version of the date because the backend data…
function checkDate(fld) {
var mo, day, yr;
var entry = fld.value;
var reLong = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/;
var reShort = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{2}\b/;
var valid = (reLong.test(entry)) || (reShort.test(entry));
if (valid) {
var delimChar = (entry.indexOf("/") != -1) ? "/" : "-";
var delim1 = entry.indexOf(delimChar);
var delim2 = entry.lastIndexOf(delimChar);
@luisenriquecorona
luisenriquecorona / checkDate().js
Created May 20, 2020 16:02
The checkDate( ) validation function in Example 2-3 assumes that users will enter dates in either mm/dd/yyyy or mm-dd-yyyy formats (in that order only), and that the validation must test for the entry of a true date. There is no boundary checking here, so practically any year is accepted. As a form-validation function, this one takes a ref- eren…
function checkDate(fld) {
var mo, day, yr;
var entry = fld.value;
var re = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/;
if (re.test(entry)) {
var delimChar = (entry.indexOf("/") != -1) ? "/" : "-";
var delim1 = entry.indexOf(delimChar);
var delim2 = entry.lastIndexOf(delimChar);
mo = parseInt(entry.substring(0, delim1), 10);
day = parseInt(entry.substring(delim1+1, delim2), 10);
@luisenriquecorona
luisenriquecorona / MacroCommand.py
Created March 25, 2020 18:59
Building a list from the commands arguments ensures that it is iterable and keeps a local copy of the command references in each MacroCommand instance.
class MacroCommand:
"""A command that executes a list of commands"""
def __init__(self, commands):
self.commands = list(commands) #
def __call__(self):
for command in self.commands: #
command()
@luisenriquecorona
luisenriquecorona / Best_Promo.py
Last active March 11, 2020 07:21
Is straightforward: promos is a list of functions. Once you get used to the idea that functions are first class objects, it naturally follows that building data structures holding functions often makes sense.
>>> Order(joe, long_order, best_promo)
<Order total: 10.00 due: 9.30>
>>> Order(joe, banana_cart, best_promo)
<Order total: 30.00 due: 28.50>
>>> Order(ann, cart, best_promo)
<Order total: 42.00 due: 39.90>
@luisenriquecorona
luisenriquecorona / Candidate.java
Created February 26, 2020 01:08
The function is a bit too long and the variables are used throughout. To split the func- tion into smaller pieces we need to create a GuessStatisticsMessage class and make the three variables fields of this class. This provides a clear context for the three variables. They are definitively part of the GuessStatisticsMessage.
private void printGuessStatistics(char candidate, int count) {
String number;
String verb;
String pluralModifier;
if (count == 0) {
number = "no";
verb = "are";
pluralModifier = "s";
} else if (count == 1) {
number = "1";
@luisenriquecorona
luisenriquecorona / ABC.py
Created February 25, 2020 21:52
In our example, before instantiating an order, the system would somehow select a promotional discount strategy and pass it to the Order constructor.
from abc import ABC, abstractmethod
from collections import namedtuple
Customer = namedtuple('Customer', 'name fidelity')
class LineItem:
def __init__(self, product, quantity, price):
self.product = product
self.quantity = quantity
self.price = price
def total(self):
return self.price * self.quantity
@luisenriquecorona
luisenriquecorona / Attrgetter.py
Created February 25, 2020 21:36
Demo of attrgetter to process a previously defined list of namedtuple called metro_data
>>> from collections import namedtuple
>>> LatLong = namedtuple('LatLong', 'lat long') #
>>> Metropolis = namedtuple('Metropolis', 'name cc pop coord') #
>>> metro_areas = [Metropolis(name, cc, pop, LatLong(lat, long)) #
... for name, cc, pop, (lat, long) in metro_data]
>>> metro_areas[0]
Metropolis(name='Tokyo', cc='JP', pop=36.933, coord=LatLong(lat=35.689722, long=139.691667))
>>> metro_areas[0].coord.lat #
35.689722
>>> from operator import attrgetter
@luisenriquecorona
luisenriquecorona / Annoted clip function.py
Created February 25, 2020 21:28
Function annotations. Python 3 provides syntax to attach metadata to the parameters of a function declaration and its return value.
def clip(text:str, max_len:'int > 0'=80) -> str:
"""Return text clipped at the last space before or after max_len
"""
end = None
if len(text) > max_len:
space_before = text.rfind(' ', 0, max_len)
if space_before >= 0:
end = space_before
else:
space_after = text.rfind(' ', max_len)
@luisenriquecorona
luisenriquecorona / Bob Age.py
Last active February 25, 2020 21:06
JSON is a newer and emerging data interchange format, which is both programming-language-neutral and supported by a variety of systems.
>>> json.dump(rec, fp=open('testjson.txt', 'w'), indent=4)
>>> print(open('testjson.txt').read())
{
"job": [
"dev",
"mgr"
],
"name": {
"last": "Smith",
"first": "Bob"
@luisenriquecorona
luisenriquecorona / Age.py
Created February 25, 2020 20:54
As a more advanced extension, string formatting also allows conversion targets on the left to refer to the keys in a dictionary coded on the right and fetch the corresponding values.
>>> # Template with substitution targets
>>> reply = """
Greetings...
Hello %(name)s!
Your age is %(age)s
"""
>>> values = {'name': 'Bob', 'age': 40} # Build up values to substitute
>>> print(reply % values) # Perform substitutions