text:
"""
    -> Blackjack Statistics Simulator 1.0
    -> J Joddy Zavala Z
    -> Enero 2017 (retomando)
    -> Python 3.6

    En esta version solo se simularan rondas de juego para obtener estadisticas
    que muestren la eficiencia de seguir estrategias predefinidas

    Descubrimientos:

    *Todos las referencias creadas apuntando a empty list apuntan
    a una misma empty list D: para prevenir eso iniciar las listas a 'None' y
    al momento de usarlas verificar que no sean 'None'

    *** CORREGIDO USANDO PYTHON 3.6

    -> Abril 2017 (Actualizacion)
"""

# --> Bibliotecas

from datetime import datetime
from random import shuffle
from copy import deepcopy  # Copia un objeto, no la referencia sino su valor
from pathlib import Path  # Manejo de rutas para file I/O
from matplotlib import pyplot as plt
import os

# --> Clases

class Matriz():
    """
    Guarda una matriz de decisiones (Una tabla de estrategias para jugar BJ).
    """
    def __init__(self, matriz=None):
        """
        La matriz es un diccionario con las matrices dura, suave y los pares
        """
        self.matriz = matriz

    def get_jugada(self, puntos_dealer, puntos_jugador, tipo_matriz):
        """
        Devuelve la jugada recomendada por la matriz segun las manos del jugador y del dealer
            'P' Pedir: pedir una carta
            'Q' Plantarse: quedarse con la jugada que se tiene en mano
            'D' Doblar: pedir una carta mas y doblar la apuesta
            'S' Separar: separar las cartas de la mano en dos jugadas independientes
            'X' Se pasa: la mano se pasa de 21
        Matriz().get_jugada(self,int,int,str) --> str
        """
        matriz = self.matriz.get(tipo_matriz)
        jugada = "X"
        index = matriz[0].index(puntos_dealer)
        for fila in matriz:
            if fila[0] == puntos_jugador:
                jugada = fila[index]
                break
        return jugada

    def show_jugadas(self):
        """
        Imprime rudimentariamente los elementos de la matriz
        Matriz().show_jugadas(self) --> None
        """
        print("\n ---  Matriz  ---\n")
        for llave in iter(self.matriz):
            print("------------------------------------------------------")
            print(llave)
            for fila in self.matriz.get(llave):
                print(fila)
        print("------------------------------------------------------\n")

    def to_string(self, tipo=None):
        """
        Devuelve la representacion de la matriz como una cadena formateada, puede ser
        toda la matriz (default) o solo un tipo especifico ('suave','dura','pares')
        Matriz().to_string(self[,tipo]) --> str
        """
        if tipo is None:
            llaves = [llave for llave in iter(self.matriz)]
        else:
            llaves = [tipo]
        string = ""
        for llave in llaves:
            string += " --- " + llave + " --- \n"
            for fila in self.matriz.get(llave):
                string += str(fila) + "\n"
        string += "\n"
        return string

class Naipe():
    """
    Guarda un naipe representado por una tupla de un valor y una figura
    """
    def __init__(self, naipe=None):
        """
        El naipe es una tupla de un valor numerico y una figura
        """
        self.naipe = naipe

    def get_numero(self):
        """
        Devuelve el valor numerico del naipe, en el caso de un 'As' devuelve 11,
        se requiere verificacion externa en caso de que convenga que valga 1 (As suave)
        Naipe().get_numero(self) --> int
        """
        if self.naipe[0] in ["J", "Q", "K"]:
            return 10
        elif self.naipe[0] == "As":
            return 11
        else:
            return self.naipe[0]

    def get_palo(self):
        """
        Devuelve el palo (figura) del naipe
        Naipe().get_palo(self) --> str
        """
        return self.naipe[1]

    def show_valor(self):
        """
        Imprime en pantalla el valor y la figura del naipe
        Naipe().show_valor(self) --> None
        """
        if len(self.naipe) == 2:
            if self.naipe[0] == "J":
                print("Jack de", self.naipe[1])
            elif self.naipe[0] == "Q":
                print("Queen de", self.naipe[1])
            elif self.naipe[0] == "K":
                print("King de", self.naipe[1])
            else:
                print(self.naipe[0], "de", self.naipe[1])
        else:
            print("Naipe vacio*")

    def to_string(self):
        """
        Devuelve la representacion del naipe como una cadena formateada
        Naipe().to_string(self) --> str
        """
        string = "Naipe vacio*"
        if len(self.naipe) == 2:
            if self.naipe[0] == "J":
                string = "Jack de " + str(self.naipe[1])
            elif self.naipe[0] == "Q":
                string = "Queen de " + str(self.naipe[1])
            elif self.naipe[0] == "K":
                string = "King de " + str(self.naipe[1])
            else:
                string = str(self.naipe[0]) + " de " + str(self.naipe[1])
        return string

class Baraja():
    """
    Guarda n barajas francesas de 52 naipes representada por una lista
    """
    def __init__(self, naipes=None):
        """
        La baraja es una lista de naipes de clase Naipe(), como atributo interno se
        tiene el conteo de cartas
        """
        self.naipes = naipes
        self.cuenta = 0

    def get_naipe(self):
        """
        Devuelve un naipe sacado de la baraja si esta tiene naipes, devuelve naipe vacio en otro caso
        Baraja().get_naipe(self) --> Naipe()
        """
        if not self.naipes:
            naipe = Naipe()
        else:
            naipe = self.naipes.pop()
            valor = naipe.get_numero()
            if valor in [2, 3, 4, 5, 6]:
                self.cuenta += 1
            elif valor in [10, 11]:
                self.cuenta -= 1
        return naipe

    def get_cuenta(self):
        """
        Devuelve la cuenta que lleva la baraja al momento
        Baraja().get_cuenta(self) --> int
        """
        return self.cuenta

    def get_numero_naipes(self):
        """
        Devuelve la cantidad de naipes que contiene la baraja
        Baraja().get_numero_naipes(self) --> int
        """
        return len(self.naipes)

    def mezclar_naipes(self):
        """
        Mezcla los naipes de la baraja
        Baraja().mezclar_naipes(self) --> None
        """
        shuffle(self.naipes)

    def clonar(self):
        """
        Devuelve una copia de la baraja
        Baraja().clonar(self) --> Baraja()
        """
        return deepcopy(self)

    def show_naipes(self):
        """
        Imprime en pantalla los naipes de la baraja
        Baraja().show_naipes(self) --> None
        """
        print("\n ---  Baraja  ---\n")
        for naipe in self.naipes:
            naipe.show_valor()
        print()

class Jugador():
    """
    Guarda la informacion basica de un jugador
    """
    def __init__(self, nombre=None, dinero=300, *manos):
        """
        El jugador tiene nombre, dinero y su lista de manos
        """
        self.nombre = nombre
        self.dinero = dinero
        self.manos = list(manos)

    def get_nombre(self):
        """
        Devuelve el nombre del jugador
        Jugador().get_nombre(self) --> str
        """
        return self.nombre

    def get_dinero(self):
        """
        Devuelve la cantidad de dinero con que cuenta el jugador
        Jugador().get_dinero(self) --> float
        """
        return self.dinero

    def get_mano(self, indice=None):
        """
        Devuelve la mano o manos del jugador segun el indice (default todas las manos)
        Jugador().get_mano(self[,int]) --> [Mano()|list(Mano())]
        """
        if indice is not None:
            return self.manos[indice]
        else:
            return self.manos

    def get_cantidad_manos(self):
        """
        Devuelve el numero de manos actuales del jugador
        Jugador().get_cantidad_manos(self) --> int
        """
        return len(self.manos)

    def get_puntuacion_mano(self, indice=0, soft=False):
        """
        Devuelve la puntuacion de la mano indicada del jugador, puede ser la dura (As = 11) o la suave (As = 1)
        (defaul la mano del indice 0 y puntuacion dura)
        Jugador().get_puntuacion_mano(self[,[int,],[bool]]) --> int
        """
        return self.manos[indice].get_puntuacion(soft)

    def agregar_mano(self, mano_nueva, indice=None):
        """
        Agrega una mano extra al jugador, se puede especificar la posicion
        Jugador().agregar_mano(self,Mano()[,int]) --> None
        """
        if indice is None:
            indice = len(self.manos)
        self.manos.insert(indice, mano_nueva)

    def agregar_naipe_a_mano(self, naipe, indice=0):
        """
        Agrega un naipe a la mano del jugador (por default a la primer mano asignada)
        Jugador().agregar_naipe_a_mano(self,Naipe()[,int]) --> None
        """
        self.manos[indice].agrega_naipe(naipe)

    def agregar_dinero(self, monto):
        """
        Agrega el monto ganado al dinero del jugador
        Jugador().agregar_dinero(self,float) --> None
        """
        self.dinero += monto

    def quitar_dinero(self, monto):
        """
        Substrae dinero apostado por el jugador igual al monto indicado
        Jugador().quitar_dinero(self,float) --> None
        """
        self.dinero -= monto

    def resetear_mano(self):
        """
        Limpia la mano del jugador, devuelve lista con una mano vacia
        Jugador().resetear_mano(self) --> list(Mano())
        """
        self.manos = [Mano()]

    def show_mano(self):
        """
        Imprime el nombre del jugador y las manos que posee
        Jugador().show_mano(self) --> None
        """
        if self.get_cantidad_manos() > 1:
            msg = "Manos"
        else:
            msg = "Mano"
        print("\n", msg, "de", self.nombre, "\n")
        for mano in self.manos:
            mano.show_mano()
        print()

    def show_nombre(self):
        """
        Imprime el nombre del jugador
        Jugador().show_nombre(self) --> None
        """
        print("\n Nombre:", self.nombre)
        print()

    def show_dinero(self):
        """
        Imprime la cantidad actual de dinero con que cuenta el jugador
        Jugador().show_dinero(self) --> None
        """
        print("\n Dinero de", self.nombre, ":", self.dinero)
        print()

    def show_puntuacion_mano(self):
        """
        Imprime la puntuacion de la mano del jugador (defeult la mano con indice 0)
        Jugador().show_puntuacion_mano(self[,int]) --> None
        """
        for mano in self.manos:
            mano.show_puntuacion()
        print()

    def to_string(self):
        """
        Devuelve la representacion del jugador como una cadena formateada
        Jugador().to_string(self) --> str
        """
        string = "Nombre: " + self.nombre + "\n"
        string += "Dinero: " + str(self.dinero) + "\n"
        string += "Mano: \n"
        for mano in self.manos:
            string += mano.to_string()
            string += "-------"
        return string

class Mano():
    """
    Guarda una lista de naipes
    """
    def __init__(self, naipes=None):
        """
        La mano tiene una lista de naipes, una puntuacion y la jugada final segun la estrategia
        """
        self.naipes = naipes
        self.jugadaFinal = None
        self.puntuacion = 0

    def get_puntuacion(self, soft=False):
        """
        Devuelve la puntuacion de la mano (por default la puntuacion dura)
        Mano().get_puntuacion(self[,bool]) --> int
        """
        self._actualiza_puntuacion(soft)
        return self.puntuacion

    def get_naipes(self):
        """
        Devuelve la lista de naipes de la mano
        Mano().get_naipes(self) --> list()
        """
        return self.naipes

    def get_numero_naipes(self):
        """
        Devuelve el numero de naipes en la mano
        Mano().get_numero_naipes(self) --> int
        """
        return len(self.naipes)

    def get_jugada(self):
        """
        Devuelve el tipo de jugada final que se realizo con la mano
        Mano().get_jugada(self) --> str
        """
        return self.jugadaFinal

    def set_puntuacion(self, nueva_puntuacion):
        """
        Pone la puntuacion indicada a la mano
        Mano().set_puntuacion(self,int) --> None
        """
        self.puntuacion = nueva_puntuacion

    def set_jugada(self, jugada):
        """
        Establece manualmente la jugada final de la mano
        Mano().set_jugada(self,str) --> None
        """
        self.jugadaFinal = jugada

    def _actualiza_puntuacion(self, soft=False):
        """
        Actualiza la puntuacion de la mano, en caso de indicar 'soft' los Ases de la mano se vuelven 1
        (de ser necesario) para devolver la mejor puntuacion posible. (default calcula puntuacion dura)
        Mano()._actualiza_puntuacion(self[,bool]) --> None
        """
        puntuacion = 0
        contador_as = 0
        if self.naipes is not None:
            for carta in self.naipes:
                puntuacion += carta.get_numero()
                if carta.get_numero() == 11:
                    contador_as += 1
        if contador_as > 0 and soft and puntuacion > 21:
            for i in range(0, contador_as):
                puntuacion -= 10
                if puntuacion <= 21:
                    break
        self.puntuacion = puntuacion

    def agrega_naipe(self, naipe):
        """
        Agrega un naipe a la mano y recalcula la puntuacion
        Mano().agrega_naipe(self,Naipe()) --> None
        """
        if self.naipes is not None:
            self.naipes.append(naipe)
        else:
            self.naipes = [naipe]
        self._actualiza_puntuacion()

    def mueve_naipe_a_mano(self, mano_nueva):
        """
        Mueve un naipe de una mano a otra 'Para la jugada Separar'
        Mano().moveNaipe(self,Mano()) --> None
        """
        mano_nueva.agrega_naipe(self.naipes.pop())

    def show_puntuacion(self):
        """
        Imprime la puntuacion de la mano
        Mano().show_puntuacion(self) --> None
        """
        print("Puntuacion:", str(self.puntuacion))

    def show_mano(self):
        """
        Imprime los naipes de la mano
        Mano().get_numero_naipes(self) --> None
        """
        if self.naipes is not None:
            for n in self.naipes:
                n.show_valor()
        else:
            print("\nNo hay naipes en la mano*\n")

    def to_string(self):
        """
        Devuelve la representacion de la mano como una cadena formateada
        Mano().to_string(self) --> str
        """
        string = ""
        if self.naipes is not None:
            for n in self.naipes:
                string += "   " + n.to_string() + "\n"
            if self.get_puntuacion() > 21:
                string += "   Puntuacion -> " + str(self.get_puntuacion(soft=True)) + "\n"
            else:
                string += "   Puntuacion -> " + str(self.get_puntuacion()) + "\n"
        else:
            string += "   No hay naipes en la mano*\n"
            string += "   Puntuacion -> 0\n"
        return string

# -> Funciones

def fn_carga_matriz(archivo):
    """
    Devuelve un diccionario con las tres matrices de decision que carga de un archivo plano
    fn_carga_matriz(str) --> Matriz()
    """
    ruta_entrada = Path(archivo)
    archivo_entrada = ruta_entrada.open('r')
    lineas = archivo_entrada.readlines()
    archivo_entrada.close()
    temp_matriz, matriz = [], []
    for linea in lineas:
        linea = linea.replace("\n", "")
        linea = linea.split()
        if linea[0] == "X":  # Separadores de matrices
            matriz.append(temp_matriz)
            temp_matriz = []
            continue
        elif linea[0] == '0':  # Cabeceras de matrices
            lista = [int(j) for j in linea]
        else:  # Jugadas de matrices
            y = int(linea[0])
            lista = [y] + linea[1:len(linea)]  # Warning due to adding list(integer) + list(string), works though
        temp_matriz.append(lista)
    diccionario = {"hard": matriz[0], "soft": matriz[1], "pairs": matriz[2]}
    return Matriz(diccionario)

def fn_crea_mazo(numero_barajas=6):
    """
    Devuelve un mazo de naipes con n barajas francesas (default 6 barajas)
    fn_crea_mazo([int]) --> Baraja()
    """
    numeros = list(range(2, 11))
    figuras = ["J", "Q", "K", "As"]
    palos = ["Treboles", "Picas", "Diamantes", "Corazones"]
    temp_baraja = []
    for j in range(numero_barajas):
        temp_lista = [[n, p] for p in palos for n in numeros + figuras]
        for tupla in temp_lista:
            temp_baraja.append(Naipe(tupla))
    return Baraja(temp_baraja)

def fn_lanzar_juego(mazo, jugadores, matriz_estrategia, rondas, apuesta_minima):
    """
    Contiene la mecanica general del juego
    fn_lanzar_juego(Baraja(),list(),Matriz(),int,float) --> None
    """
    # Se copia el mazo original para no tener que crearlo en caso de jugar mas rondas
    mazo_actual = mazo.clonar()
    mazo_actual.mezclar_naipes()
    # Guardara los jugadores retirados del juego por no poder apostar mas
    jugadores_retirados = []
    # El dealer es un jugador mas (actualmente no se le resta dinero)
    dealer = Jugador("Dealer", 1000000000000, Mano())
    archivoSalida.write("-------------- Informacion inicial de los jugadores --------------\n")
    fn_imprime_info(jugadores)
    fn_imprime_info(dealer)
    for j in range(rondas):
        archivoSalida.write("----------------------------- RONDA "+str(j+1)+" -----------------------------\n")
        archivoSalida.write("****** Se reparten naipes... ******\n")
        datos[0].append(j)
        datos[1].append(mazo_actual.get_cuenta())
        # Reparto de naipes, 2 a cada jugador
        for index1 in range(2):
            for jugador in jugadores:
                if jugador.get_dinero() >= apuesta_minima:
                    # Reparte a los jugadores con dinero suficiente
                    naipe_actual = mazo_actual.get_naipe()
                    jugador.agregar_naipe_a_mano(naipe_actual)
                else:
                    # Saca los jugadores sin dinero suficiente
                    jugadores_retirados.append(jugadores.pop(jugadores.index(jugador)))
                    continue
                if index1 == 1:
                    # Mesa cobra apuesta al sacar el 2do naipe
                    jugador.quitar_dinero(apuesta_minima)
                    dealer.agregar_dinero(apuesta_minima)
        # Reparto de naipes, 1 al Dealer
        naipe_actual = mazo_actual.get_naipe()
        dealer.agregar_naipe_a_mano(naipe_actual)
        # Imprime condiciones iniciales de jugadores aun en la mesa
        """for jugador in jugadores + [dealer]:
            jugador.show_mano()
            jugador.show_puntuacion_mano()"""
        fn_imprime_info(jugadores)
        fn_imprime_info(dealer)
        # Confrontar individualmente al Dealer con cada jugador
        mano_dealer = dealer.get_mano(0)
        puntos_dealer = mano_dealer.get_puntuacion()
        archivoSalida.write("****** Comienza enfrentamiento... ******\n")
        for jugador in jugadores:
            archivoSalida.write("  Nombre: " + jugador.get_nombre() + "\n")
            mano_jugador = jugador.get_mano(0)
            fn_enfenta_al_dealer(dealer, puntos_dealer, jugador, mano_jugador, matriz_estrategia, mazo_actual, apuesta_minima)
            archivoSalida.write("  ..............\n")

        archivoSalida.write("  Dealer: \n")
        while True:
            nuevo_naipe = mazo_actual.get_naipe()
            dealer.agregar_naipe_a_mano(nuevo_naipe)
            archivoSalida.write("  ** Saca naipe **\n")
            archivoSalida.write(dealer.get_mano(0).to_string() + "\n")
            if dealer.get_puntuacion_mano(soft=True) >= 17:
                archivoSalida.write("  ** No mas cartas **\n")
                break
        archivoSalida.write("****************\n\n")
        """for jugador in jugadores + [dealer]:
            jugador.show_mano()
            jugador.show_puntuacion_mano()
        fn_imprime_info(jugadores,dealer)"""
        fn_cierre_ronda(dealer,jugadores,apuesta_minima)
        for jugador in jugadores:
            if jugador.get_dinero() < apuesta_minima:
                jugadores_retirados.append(jugadores.pop(jugadores.index(jugador)))
        cartas_restantes = mazo_actual.get_numero_naipes()
        jugadores_restantes = len(jugadores)
        archivoSalida.write(":::::::::: Cartas restantes: "+str(cartas_restantes)+"\n")
        archivoSalida.write(":::::::::: Jugadores restantes: "+str(jugadores_restantes)+"\n")
        archivoSalida.write(":::::::::: Conteo de cartas: "+str(mazo_actual.get_cuenta())+"\n")
        if (jugadores_restantes * 5) > cartas_restantes or (jugadores_restantes == 0):
            break
    archivoSalida.write(":::::::::::::::::::::::::::: TERMINA JUEGO ::::::::::::::::::::::::::\n")
    # Guardar estadisticas en archivo

def fn_separar_mano(dealer, puntosDealer, jugador, manoJugador, matrizEstrategia, mazoActual, apuestaMinima):
    """
    Enfrenta a cada jugador contra el dealer
    fn_enfenta_al_dealer(Jugador(),int,Jugador(),Mano(),Matriz(),Baraja(),float) --> None
    """
    archivoSalida.write("   --> Separando mano..\n\n")
    manoNueva = Mano()
    manoJugador.mueve_naipe_a_mano(manoNueva)
    naipeActual = mazoActual.get_naipe()
    manoJugador.agrega_naipe(naipeActual)
    naipeActual = mazoActual.get_naipe()
    manoNueva.agrega_naipe(naipeActual)
    indice = None
    naipeF = manoJugador.get_naipes()[0].get_numero()
    naipeS = manoJugador.get_naipes()[1].get_numero()
    # Si la mano nueva NO es par, metela en la posicion 0
    if naipeF == naipeS:
        indice = 0
    jugador.agregar_mano(manoNueva,indice)
    archivoSalida.write("    -> Mano A:\n")
    archivoSalida.write(manoJugador.to_string() + "\n")
    archivoSalida.write("    -> Mano B:\n")
    archivoSalida.write(manoNueva.to_string() + "\n")
    for i,mano in enumerate(jugador.get_mano()):
        if mano.get_jugada() is None:
            archivoSalida.write("   --> Jugando mano separada " + str(i+1) + ":\n")
            fn_enfenta_al_dealer(dealer,puntosDealer,jugador,mano,matrizEstrategia,mazoActual,apuestaMinima,calledFromSepara=True)

def fn_enfenta_al_dealer(dealer,puntosDealer,jugador,manoJugador,matrizEstrategia,mazoActual,apuestaMinima,calledFromSepara=False):
    """
    Enfrenta a cada jugador contra el dealer
    fn_enfenta_al_dealer(Jugador(),int,Jugador(),Mano(),Matriz(),Baraja(),float[,bool]) --> None
    """
    puntosJugador = manoJugador.get_puntuacion()
    #puntosSoftJugador = manoJugador.get_puntuacion(soft=True)
    archivoSalida.write(manoJugador.to_string() +"\n")
    banderaAs = False
    tipoEstrategia = None
    # Define la jugada de la mano segun puntos y matriz
    if manoJugador.get_numero_naipes() == 2:
        naipeF = manoJugador.get_naipes()[0].get_numero()
        naipeS = manoJugador.get_naipes()[1].get_numero()
        if naipeF == naipeS:
            tipoEstrategia = "pairs"
        elif 11 in (naipeF,naipeS):
            puntosJugador = manoJugador.get_puntuacion(soft=True)
            tipoEstrategia = "soft"
        else:
            tipoEstrategia = "hard"
    else:
        for naipe in manoJugador.get_naipes():
            if naipe.get_numero() == 11:
                banderaAs = True
                break
        if banderaAs and puntosJugador > 21:
            puntosJugador = manoJugador.get_puntuacion(soft=True)
            tipoEstrategia = "soft"
        else:
            tipoEstrategia = "hard"
    jugada = matrizEstrategia.get_jugada(puntosDealer, puntosJugador, tipoEstrategia)
    archivoSalida.write("   Jugada segun estrategia: "+jugada+"\n")
    # Solo se puede doblar apuesta para el 3er naipe
    if jugada == "D" and manoJugador.get_numero_naipes() == 2:
        if jugador.get_dinero() >= apuestaMinima:
            # Dobla si la jugada recomendada es Doblar y hay dinero
            naipeNew = mazoActual.get_naipe()
            #archivoSalida.write("  Nuevo naipe: "+naipeNew.to_string()+"\n")
            manoJugador.agrega_naipe(naipeNew)
            jugador.quitar_dinero(apuestaMinima)
            dealer.agregar_dinero(apuestaMinima)
        else:
            # Pide si la jugada recomendada es Doblar pero no hay dinero
            jugada = "P"
    elif jugada == "D":
        # Pide si la jugada recomendada es Doblar pero es el 4to naipe o mas
        jugada = "P"

    # Solo se pueden separar manos con 2 cartas
    banderaSepara = False
    if jugada == "S" and manoJugador.get_numero_naipes() == 2:
        if jugador.get_dinero() >= apuestaMinima:
            banderaSepara = True
            jugador.quitar_dinero(apuestaMinima)
            dealer.agregar_dinero(apuestaMinima)
            archivoSalida.write("   Jugada elegida: "+jugada+"\n\n")
            #print("!!!")
            fn_separar_mano(dealer,puntosDealer,jugador,manoJugador,matrizEstrategia,mazoActual,apuestaMinima)
        else:
            jugada = "P"
    elif jugada == "S":
        jugada = "P"

    if calledFromSepara is False and banderaSepara is True:
        archivoSalida.write("   ---> Termina separacion..\n\n")

    if calledFromSepara is True and banderaSepara is False:
            archivoSalida.write("   Jugada elegida: "+jugada+"\n\n")

    if calledFromSepara is False and banderaSepara is False:
            archivoSalida.write("   Jugada elegida: "+jugada+"\n\n")

    # Jugadas que terminan la reparticion de cartas a la mano
    if jugada in ("X","Q"):
        manoJugador.set_jugada(jugada)
        #puntosJugador = manoJugador.get_puntuacion()
        #puntosSoftJugador = manoJugador.get_puntuacion(soft=True)
        #archivoSalida.write(manoJugador.to_string() +"\n")
        return
    elif jugada == "D":
        manoJugador.set_jugada(jugada)
        archivoSalida.write(manoJugador.to_string() +"\n")
        return
    elif jugada == "P":
        naipeNew = mazoActual.get_naipe()
        manoJugador.agrega_naipe(naipeNew)
        #archivoSalida.write("  Nuevo naipe: "+naipeNew.to_string()+"\n")
        fn_enfenta_al_dealer(dealer,puntosDealer,jugador,manoJugador,matrizEstrategia,mazoActual,apuestaMinima)

def fn_cierre_ronda(dealer,jugadores,apuesta):
    """
    Realiza los pagos o cobros de apuestas por mano a cada jugador, segun corresponda y
    al final limpia las manos de los jugadores
    """
    manoDealer = dealer.get_mano(0)
    factorPagaBJ = 1.5
    archivoSalida.write(" ------ Resultados ------\n")
    for jugador in jugadores:
        archivoSalida.write(jugador.get_nombre()+"\n")
        for i,manoJugador in enumerate(jugador.get_mano()):
            # Si elije doblar apuesta
            factorApuesta = 1
            factorEmpate = 1
            msgDoble = ": "
            if manoJugador.get_jugada() == "D":
                factorApuesta = 3
                factorEmpate = 2
                msgDoble = " doblada!: "
            resultado,mensaje = fn_evalua_manos(manoDealer,manoJugador)
            if jugador.get_cantidad_manos() == 1:
                msgManos = " -> mano"
            else:
                msgManos = " -> mano "+str(i+1)
            archivoSalida.write(msgManos+msgDoble+mensaje+"\n")
            if resultado == "BJ":
                jugador.agregar_dinero(apuesta+(apuesta*factorPagaBJ*factorApuesta))
                dealer.quitar_dinero(apuesta+(apuesta*factorPagaBJ*factorApuesta))
            elif resultado == "G":
                jugador.agregar_dinero(apuesta+(apuesta*factorApuesta))
                dealer.quitar_dinero(apuesta+(apuesta*factorApuesta))
            elif resultado == "E":
                jugador.agregar_dinero(apuesta*factorEmpate)
                dealer.quitar_dinero(apuesta*factorEmpate)
        archivoSalida.write(" -> Dinero: "+str(jugador.get_dinero())+"\n")
    archivoSalida.write("----------------------\n\n")
    for jugador in jugadores + [dealer]:
        jugador.resetear_mano()

def fn_evalua_manos(manoDealer,manoJugador):
    """
    Compara la mano del jugador contra la del dealer para definir el resultado
    """
    puntosJugador = manoJugador.get_puntuacion(soft=True)
    puntosDealer = manoDealer.get_puntuacion(soft=True)
    jugadaFinal = manoJugador.get_jugada()
    if puntosJugador == 21 and manoJugador.get_numero_naipes() == 2:
        return("BJ"," GANA con BlackJack!!!")
    elif jugadaFinal == 'X':
        return(jugadaFinal," Se pasa con " + str(puntosJugador))
    elif puntosJugador == puntosDealer:
        return("E"," Empata con " + str(puntosJugador))
    elif puntosDealer > 21 and puntosJugador <= 21:
        return("G"," Gana con " + str(puntosJugador))
    elif puntosJugador <= 21 and puntosJugador > puntosDealer:
        return("G"," Gana con " + str(puntosJugador))
    elif puntosJugador < puntosDealer:
        return("P"," Pierde con " + str(puntosJugador))
    else:
        print("COMPARACION DE MANOS NO VERIFICADA MANDA EMPATE")
        print("jugador: ",puntosDealer," dealer: ",puntosJugador)
        return("E"," Empata por indefinicion de manos")

def fn_comenzar_proceso(numero_barajas=6, numero_jugadores=6, apuesta_minima=250, rondas=20):
    """
    Genera carga la matriz de decisiones, crea el mazo de cartas, crea los jugadores y
    manda a llamar la funcion encargada de la logica del juego
    fn_comenzar_proceso(int,int,float,int) --> None
    """
    global archivoSalida
    global datos
    rutaSalida = Path('./output/gameplay.txt')
    if not os.path.exists(rutaSalida):
        try:
            os.makedirs(os.path.dirname(rutaSalida))
        except OSError:
            print("OCURRIO UN ERROR DURANTE LA CREACION DEL ARCHIVO DE SALIDA, VERIFICAR")
            raise
    archivoSalida = rutaSalida.open('w')
    archivoSalida.write("-------------------------------------------------------------------------------------\n")
    archivoSalida.write("Test: " + datetime.now().strftime('%Y-%m-%d %H:%M:%S')+"\n\n")
    print("\nArchivo de salida ./output/gameplay.txt")
    datos = [[],[]]
    matrizEstrategia = fn_carga_matriz("./resources/matriz_1.txt")
    mazo = fn_crea_mazo(numero_barajas)
    jugadores = []
    for j in range(numero_jugadores):
        jugadores.append(Jugador("Jugador " + str(j+1),1000,Mano()))
    fn_lanzar_juego(mazo,jugadores,matrizEstrategia,rondas,apuesta_minima)
    archivoSalida.close()
    plt.plot(datos[0],datos[1],'o-')
    plt.grid()
    plt.show()

def fn_imprime_info(jugadores):
    if type(jugadores) is not list:
        jugadores = [jugadores]
    for jugador in jugadores:
        nombre = jugador.get_nombre()
        archivoSalida.write(jugador.to_string())
        archivoSalida.write("\n")

# -> Main
fn_comenzar_proceso()


text:
angular.module('weDo.landing', [])
  .controller('LandingCtrl', function () {

  })

redpajama_set_name: RedPajamaGithub


text:
{{#if flash.message}}

{{flash.message}}

{{/if}}

        No Login ?

Developer Login

        <form method="post">

                Email

                    <input type="text" name="auth_slug" class="form-control" value="{{item.auth_slug}}" />
                    {{#if errors.auth_slug}}
                    {{errors.auth_slug}}
                    {{/if}}

                Password

                    <input type="password" name="auth_password" class="form-control" value="{{item.auth_password}}" />
                    {{#if errors.auth_password}}
                    {{errors.auth_password}}
                    {{/if}}

               <button type="submit" class="btn btn-primary">Submit</button>
               Forgot Password ?

        </form>


text:
layout: project
title: Pictoid
description: Pictionary Telephone
date: Mar 2014
img: http://devchuk.github.io/devchukV1/res/img/portimg/pictoid/profile2.png
category: software
order: 6
---

![](http://devchuk.github.io/devchukV1/res/img/portimg/pictoid/pictoid2.png)

In HackBCA I teamed up with four other high school students to build a pictionary telephone web game called Pictoid. The game waits for at least four players to enter the same room before starting.

![](http://devchuk.github.io/devchukV1/res/img/portimg/pictoid/room2.png)

When the game starts, each player will be given a blank canvas to write any word they want. After each player has submitted a word, the words are then sent to the next player in line. In a situation with four players, player 1 would send a word to player 2. Player 2 would send a word to player 3. Player 3 would send a word to player 4. Then player 4 would send a word to player 1.

In short, each player would create a word and receive a word.

After the words are sent around, each player must draw a picture to represent that word within a ridiculously short time limit. Then the pictures are sent around. The players then must try to guess a word that represents the drawings they receive. Next, those words the players guessed would be sent around and the players much now draw another picture to represent the words they receive.

Over time, the ideas conveyed through the words and pictures will mutate into other ideas. When the number of passes reaches a set point, the game ends and the players would be able to see how their ideas evolved as they were passed around. What makes the game so fun is that there is video chat support with the help of TokBox: players are able to see each others' facial expressions and yell at one another for silly mistakes.

![](http://devchuk.github.io/devchukV1/res/img/portimg/pictoid/profile.png)

**Tech:** HTML, CSS, Javascript, Parse, NodeJS

[View the source code](https://github.com/devChuk/HackBCA_CSTUY)

[Challengepost](http://challengepost.com/software/pictoid)


text:
package org.spacehq.mc.protocol.data.game.values.world.effect;

public interface WorldEffect {
}


text:
#ifndef CYBER_EVENT_PERF_EVENT_CACHE_H_
#define CYBER_EVENT_PERF_EVENT_CACHE_H_

#include <chrono>
#include <fstream>
#include <memory>
#include <string>
#include <thread>

#include "cyber/base/bounded_queue.h"
#include "cyber/common/macros.h"
#include "cyber/event/perf_event.h"
#include "cyber/proto/perf_conf.pb.h"

namespace apollo {
namespace cyber {
namespace event {

class PerfEventCache {
 public:
  using EventBasePtr = std::shared_ptr<EventBase>;

  ~PerfEventCache();
  void AddSchedEvent(const SchedPerf event_id, const uint64_t cr_id,
                     const int proc_id, const int cr_state = -1);
  void AddTransportEvent(const TransPerf event_id, const uint64_t channel_id,
                         const uint64_t msg_seq, const uint64_t stamp = 0,
                         const std::string& adder = "-");

  std::string PerfFile() { return perf_file_; }

  void Shutdown();

 private:
  void Start();
  void Run();

  std::thread io_thread_;
  std::ofstream of_;

  bool enable_ = false;
  bool shutdown_ = false;

  proto::PerfConf perf_conf_;
  std::string perf_file_ = "";
  base::BoundedQueue<EventBasePtr> event_queue_;

  const int kFlushSize = 512;
  const uint64_t kEventQueueSize = 8192;

  DECLARE_SINGLETON(PerfEventCache)
};

}  // namespace event
}  // namespace cyber
}  // namespace apollo

#endif  // CYBER_EVENT_PERF_EVENT_CACHE_H_


text:
<input type="text" ng-model="acess.name">
<input type="text" ng-model="acess.password">
<button type="button" name="button" ng-click="login()"></button>


text:
package bammerbom.ultimatecore.sponge.api.command.exceptions;

import bammerbom.ultimatecore.sponge.api.language.utils.Messages;
import org.spongepowered.api.command.CommandException;

public class PlayerOnlyException extends CommandException {
    public PlayerOnlyException() {
        super(Messages.getFormatted("core.noplayer"));
    }
}


text:
package ru.stqa.pft.addressbook.tests;

import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.ContactData;

import java.util.Arrays;
import java.util.stream.Collectors;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

/**
 * Created by Zakhidat on 06.04.2017.
 */
public class ContactFullInfoTests extends TestBase {

  @Test/*(enabled=false)*/
  public void testContactFullInfo(){
    app.goTo().ContactPage();
    ContactData contact = app.contact().all().iterator().next();
    ContactData contactFullInfoFromDetailsForm = app.contact().FullInfoFromDetailsForm(contact);
    ContactData contactInfoFromEditForm = app.contact().infoFromEditForm(contact);
    String form = cleaned(contactFullInfoFromDetailsForm.getFullInfo());
    String content = mergeFullInfo(contactInfoFromEditForm);
    if (contactFullInfoFromDetailsForm.getFullInfo() != null) {
      assertThat(cleaned(contactFullInfoFromDetailsForm.getFullInfo()), equalTo(mergeFullInfo(contactInfoFromEditForm)));
    }
  }

  private String mergeFullInfo(ContactData fullInfo) {
    return Arrays.asList(fullInfo.getName(),fullInfo.getLastname(),fullInfo.getAddress(),fullInfo.getHometel(),fullInfo.getMobile(),fullInfo.getWorktel(),fullInfo.getEmail(),fullInfo.getEmail2(),fullInfo.getEmail3())
            .stream().filter((s) -> !s.equals(""))
            .map(ContactPhoneTests::cleaned)
            .collect(Collectors.joining(""));

  }

  public static String cleaned(String fullInfo) {
    return fullInfo.replaceAll("\\s","").replaceAll("[-()]","")
            .replaceAll("Memberof.*","")
            .replace("M:", "")
            .replace("H:", "")
            .replace("W:", "");
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://ws.apache.org/ns/synapse">
    <registry provider="org.wso2.carbon.mediation.registry.WSO2Registry">
        <parameter name="cachableDuration">15000</parameter>
    </registry>
    <localEntry key="response_transform.xslt">
        <xsl:stylesheet version="2.0"
                        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                        xmlns:fn="http://www.w3.org/2005/02/xpath-functions"
                        xmlns:m0="http://services.samples"
                        xmlns:ax21="http://services.samples/xsd"
                        exclude-result-prefixes="m0 ax21 fn">
            <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>

		    <xsl:template match="@* | node()">
		       <xsl:copy>
		          <xsl:apply-templates select="@* | node()"/>
		       </xsl:copy>
		    </xsl:template>

		    <xsl:template match="m0:getQuoteResponse">

		        <m:CheckPriceResponse xmlns:m="http://services.samples/xsd">
		            <m:Code>
		                <xsl:value-of select="m0:return/ax21:symbol"/>
		            </m:Code>
		            <m:Price>
		                <xsl:value-of select="m0:return/ax21:last"/>
		            </m:Price>
		        </m:CheckPriceResponse>

		    </xsl:template>

        </xsl:stylesheet>
    </localEntry>
    <localEntry key="request_transform.xslt">
        <xsl:stylesheet version="2.0"
                        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                        xmlns:fn="http://www.w3.org/2005/02/xpath-functions"
                        xmlns:m0="http://services.samples"
                        exclude-result-prefixes="m0 fn">
            <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>

	        <xsl:template match="@* | node()">
	           <xsl:copy>
	              <xsl:apply-templates select="@* | node()"/>
	           </xsl:copy>
	        </xsl:template>

            <xsl:template match="m0:CheckPriceRequest">

                <m:getQuote xmlns:m="http://services.samples">
                    <m:request>
                        <m:symbol>
                            <xsl:value-of select="m0:Code"/>
                        </m:symbol>
                    </m:request>
                </m:getQuote>

            </xsl:template>
        </xsl:stylesheet>
    </localEntry>
    <sequence name="fastXSLTMediatorSequence" onError="fault">
        <in>
            <fastXSLT xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"
                      xmlns:ns="http://org.apache.synapse/xsd"
                      key="{get-property('registry','conf:localEntries/request_transformation.txt/@resourceName')}"/>
            <send>
                <endpoint>
                    <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                </endpoint>
            </send>
        </in>
        <out>
            <fastXSLT xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"
                      xmlns:ns="http://org.apache.synapse/xsd"
                      key="{get-property('registry','gov:localEntries/response_transformation_back.txt/@resourceName')}"/>
            <send/>
        </out>
    </sequence>

    <sequence name="fault">
        <makefault>
            <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope" value="tns:Receiver"/>
            <reason xmlns:ns3="http://org.apache.synapse/xsd"
                    expression="get-property('ERROR_MESSAGE')"/>
        </makefault>
        <header name="To" expression="get-property('ReplyTo')"/>
        <send/>
    </sequence>
    <sequence name="main">
        <sequence key="fastXSLTMediatorSequence"/>
    </sequence>
</definitions>


text:
package androidx.test.services.events.internal;

import static androidx.test.services.events.internal.StackTrimmer.MAX_TRACE_SIZE;
import static com.google.common.truth.Truth.assertThat;
import static junit.framework.Assert.assertTrue;

import android.os.Environment;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runner.notification.Failure;
import org.robolectric.annotation.Config;

@RunWith(AndroidJUnit4.class)
@Config(sdk = 19)
public class StackTrimmerTest {

  @Test
  public void verifyFailureStackTraceIsTrimmed() throws Exception {

    Failure testFailure = new Failure(Description.EMPTY, new Exception());

    // ensure trace contains the current method, but not any of the junit + androidx.test framework
    // traces
    String trace = StackTrimmer.getTrimmedStackTrace(testFailure);
    assertThat(trace).contains("StackTrimmerTest.verifyFailureStackTraceIsTrimmed");
    // negative test are suspect, but just check for a few known trace elements
    assertThat(trace).doesNotContain("androidx.test.runner.AndroidJUnitRunner.onStart");
    assertThat(trace).doesNotContain("org.junit.runners.ParentRunner.run");

    Environment.getDataDirectory();
  }

  @Test
  public void verifyFailureStackTraceIsTruncated() throws Exception {
    Failure testFailure = new Failure(Description.EMPTY, new Exception(getVeryLargeString()));

    int testResultTraceLength = StackTrimmer.getTrimmedStackTrace(testFailure).length() - 1;
    assertTrue(
        String.format(
            "The stack trace length: %s, exceeds the max: %s",
            testResultTraceLength, MAX_TRACE_SIZE),
        testResultTraceLength <= MAX_TRACE_SIZE);
  }

  private static String getVeryLargeString() {
    return new String(new char[1000000]);
  }
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Трудоустройств выпускников</title>
	<link rel="stylesheet" type="text/css" href="assets/css/reset.css">
	<link rel="stylesheet" type="text/css" href="css/style.css">

					Войти
					|
					Регистрация

						С.Сейфуллин атындағы

Қазақ агротехникалық университеті

Трудоустроиства студентов КазАТУ

									Главная

									О проекте

									Выпускники

											Бакалавр

											Магистр

											Доктор

									Компании

									Контакты

						Разместить резюме
						Добавить компанию

Добро пожаловать! Выберите категорию студентов

								Бакалавриат

									Lorem ipsum dolor sit amet, consectetur adipisicing elit. Optio recusandae nesciunt officiis est obcaecati ut amet debitis? Ab autem deleniti voluptatum. Debitis modi ea nihil neque dolore tenetur hic quas.

								Магистратура

									Lorem ipsum dolor sit amet, consectetur adipisicing elit. Optio recusandae nesciunt officiis est obcaecati ut amet debitis? Ab autem deleniti voluptatum. Debitis modi ea nihil neque dolore tenetur hic quas.

								PhD докторантура

									Lorem ipsum dolor sit amet, consectetur adipisicing elit. Optio recusandae nesciunt officiis est obcaecati ut amet debitis? Ab autem deleniti voluptatum. Debitis modi ea nihil neque dolore tenetur hic quas.

Интересная статистика

						1595
						вакансии
бакалавр

						5687
						вакансии
магистр

						9861
						вакансии
доктор

						Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

						Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

						Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Новости

						Lorem Ipsum is simply dummy text

Lorem Ipsum is simply dummy text of the printing and typesetting industry....

						Lorem Ipsum is simply dummy text

Lorem Ipsum is simply dummy text of the printing and typesetting industry....

									Главная

									Выпускники

											Бакалавр

											Магистр

											Доктор

									Компании

									Контакты

© С.Сейфуллин атындағы Қазақ агротехникалық университеті, 2015

Қазақстан Республикасы, 010000, Астана қ-сы, Жеңіс даңғылы, 62

Тел.: (8-7172) 317-547, факс: (8-7172) 316-072

e-mail: agun.katu@gmail.com

	Войти
        <form method="POST" name="form1" action="form.php" >
			<input  name="name1" id="name" maxlength="200" class="modal_f" type="text" size="1"  required placeholder="Имя..."/>
			<input   name="phone1" id="user_phone" maxlength="200" class="modal_f " type="text" size="1"  required placeholder="Пароль..."/>
			<button type="submit" name="submit1" class="form_button" >Войти</button>
		</form>

	Регистрация
        <form method="POST" name="form1" action="form.php" >
			<input  name="name1" id="name" maxlength="200" class="modal_f" type="text" size="1"  required placeholder="Логин..."/>
			<input   name="phone1" id="user_phone" maxlength="200" class="modal_f " type="text" size="1"  required placeholder="mail..."/>
			<input  name="name1" id="name" maxlength="200" class="modal_f" type="text" size="1"  required placeholder="Пароль..."/>
			<input   name="phone1" id="user_phone" maxlength="200" class="modal_f " type="text" size="1"  required placeholder="повторите пароль..."/>
			<button type="submit" name="submit1" class="form_button" >Отправить</button>
		</form>


text:
using System;
using System.Collections;

namespace log4net
{
	///
	/// Implementation of Mapped Diagnostic Contexts.
	///
	/// <remarks>
	/// <note>
	/// <para>
	/// The MDC is deprecated and has been replaced by the <see cref="ThreadContext.Properties"/>.
	/// The current MDC implementation forwards to the <c>ThreadContext.Properties</c>.
	/// </para>
	/// </note>
	/// <para>
	/// The MDC class is similar to the <see cref="NDC"/> class except that it is
	/// based on a map instead of a stack. It provides mapped
	/// diagnostic contexts. A Mapped Diagnostic Context, or
	/// MDC in short, is an instrument for distinguishing interleaved log
	/// output from different sources. Log output is typically interleaved
	/// when a server handles multiple clients near-simultaneously.
	/// </para>
	/// <para>
	/// The MDC is managed on a per thread basis.
	/// </para>
	/// </remarks>
	/// <threadsafety static="true" instance="true" />
	/// <author>Nicko Cadell</author>
	/// <author>Gert Driesen</author>
	public sealed class MDC
	{
		#region Private Instance Constructors

		///
		/// Initializes a new instance of the <see cref="MDC" /> class.
		///
		/// <remarks>
		/// Uses a private access modifier to prevent instantiation of this class.
		/// </remarks>
		private MDC()
		{
		}

		#endregion Private Instance Constructors

		#region Public Static Methods

		///
		/// Gets the context value identified by the <paramref name="key" /> parameter.
		///
		/// <param name="key">The key to lookup in the MDC.</param>
		/// <returns>The string value held for the key, or a <c>null</c> reference if no corresponding value is found.</returns>
		/// <remarks>
		/// <note>
		/// <para>
		/// The MDC is deprecated and has been replaced by the <see cref="ThreadContext.Properties"/>.
		/// The current MDC implementation forwards to the <c>ThreadContext.Properties</c>.
		/// </para>
		/// </note>
		/// <para>
		/// If the <paramref name="key" /> parameter does not look up to a
		/// previously defined context then <c>null</c> will be returned.
		/// </para>
		/// </remarks>
		public static string Get(string key)
		{
			object obj = ThreadContext.Properties[key];
			if (obj == null)
			{
				return null;
			}
			return obj.ToString();
		}

		///
		/// Add an entry to the MDC
		///
		/// <param name="key">The key to store the value under.</param>
		/// <param name="value">The value to store.</param>
		/// <remarks>
		/// <note>
		/// <para>
		/// The MDC is deprecated and has been replaced by the <see cref="ThreadContext.Properties"/>.
		/// The current MDC implementation forwards to the <c>ThreadContext.Properties</c>.
		/// </para>
		/// </note>
		/// <para>
		/// Puts a context value (the <paramref name="value" /> parameter) as identified
		/// with the <paramref name="key" /> parameter into the current thread's
		/// context map.
		/// </para>
		/// <para>
		/// If a value is already defined for the <paramref name="key" />
		/// specified then the value will be replaced. If the <paramref name="value" />
		/// is specified as <c>null</c> then the key value mapping will be removed.
		/// </para>
		/// </remarks>
		public static void Set(string key, string value)
		{
			ThreadContext.Properties[key] = value;
		}

		///
		/// Removes the key value mapping for the key specified.
		///
		/// <param name="key">The key to remove.</param>
		/// <remarks>
		/// <note>
		/// <para>
		/// The MDC is deprecated and has been replaced by the <see cref="ThreadContext.Properties"/>.
		/// The current MDC implementation forwards to the <c>ThreadContext.Properties</c>.
		/// </para>
		/// </note>
		/// <para>
		/// Remove the specified entry from this thread's MDC
		/// </para>
		/// </remarks>
		public static void Remove(string key)
		{
			ThreadContext.Properties.Remove(key);
		}

		///
		/// Clear all entries in the MDC
		///
		/// <remarks>
		/// <note>
		/// <para>
		/// The MDC is deprecated and has been replaced by the <see cref="ThreadContext.Properties"/>.
		/// The current MDC implementation forwards to the <c>ThreadContext.Properties</c>.
		/// </para>
		/// </note>
		/// <para>
		/// Remove all the entries from this thread's MDC
		/// </para>
		/// </remarks>
		public static void Clear()
		{
			ThreadContext.Properties.Clear();
		}

		#endregion Public Static Methods
	}
}


text:
# Overview

CoffeeScript on the left, compiled JavaScript output on the right.

## Assignment:

- from

    number   = 42
    opposite = true

- to

    var number, opposite;

    number = 42;
    opposite = true;

## Conditions:

- from

    number = -42 if opposite

- to

    if (opposite) {
      number = -42;
    }

## Functions:

- from

    square = (x) -> x * x

- to

    square = function(x) {
      return x * x;
    };

## Arrays:

- from

    list = [1, 2, 3, 4, 5]

- to

    list = [1, 2, 3, 4, 5];

## Objects:

- from

    math =
      root:   Math.sqrt
      square: square
      cube:   (x) -> x * square x

- to

    var square;
    math = {
      root: Math.sqrt,
      square: square,
      cube: function(x) {
        return x * square(x);
      }
    };

## Splats

- from

    race = (winner, runners...) ->
      print winner, runners

- to

    var __slice = [].slice;
    race = function() {
      var runners, winner;

      winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      return print(winner, runners);
    };

## Existence

- from

    alert "I knew it!" if elvis?

- to

    if (typeof elvis !== "undefined" && elvis !== null) {
      alert("I knew it!");
    }

## Array comprehensions

- from

    cubes = (math.cube num for num in list)

- to

    var cubes;
    cubes = (function() {
      var _i, _len, _results;

      _results = [];
      for (_i = 0, _len = list.length; _i < _len; _i++) {
        num = list[_i];
        _results.push(math.cube(num));
      }
      return _results;
    })();

# Installation

The CoffeeScript compiler is itself written in CoffeeScript, using the Jison parser generator. The command-line version of coffee is available as a Node.js utility. The core compiler however, does not depend on Node, and can be run in any JavaScript environment, or in the browser (see "Try CoffeeScript", above).

To install, first make sure you have a working copy of the latest stable version of Node.js, and npm (the Node Package Manager). You can then install CoffeeScript with npm:

    npm install -g coffee-script

(Leave off the -g if you don't wish to install globally.)

If you'd prefer to install the latest master version of CoffeeScript, you can clone the CoffeeScript source repository from GitHub, or download the source directly. To install the lastest master CoffeeScript compiler with npm:

npm install -g http://github.com/jashkenas/coffee-script/tarball/master
Or, if you want to install to /usr/local, and don't want to use npm to manage it, open the coffee-script directory and run:

    sudo bin/cake install

# Usage

Once installed, you should have access to the coffee command, which can execute scripts, compile .coffee files into .js, and provide an interactive REPL. The coffee command takes the following options:

`-c, --compile`  Compile a `.coffee` script into a `.js` JavaScript file of the same name.
`-m, --map`  Generate source maps alongside the compiled JavaScript files. Adds `sourceMappingURL` directives to the JavaScript as well.
`-i, --interactive`  Launch an interactive CoffeeScript session to try short snippets. Identical to calling `coffee` with no arguments.
`-o, --output [DIR]`   Write out all compiled JavaScript files into the specified directory. Use in conjunction with `--compile` or `--watch`.
`-j, --join [FILE]`  Before compiling, concatenate all scripts together in the order they were passed, and write them into the specified file. Useful for building large projects.
`-w, --watch`  Watch files for changes, rerunning the specified command when any file is updated.
`-p, --print`  Instead of writing out the JavaScript as a file, print it directly to stdout.
`-l, --lint`   If the jsl (JavaScript Lint) command is installed, use it to check the compilation of a CoffeeScript file. (Handy in conjunction with
--watch)
`-s, --stdio`  Pipe in CoffeeScript to STDIN and get back JavaScript over STDOUT. Good for use with processes written in other languages. An example: `cat src/cake.coffee | coffee -sc`
`-e, --eval`   Compile and print a little snippet of CoffeeScript directly from the command line. For example: `coffee -e "console.log num for num in [10..1]"`
`-b, --bare`   Compile the JavaScript without the top-level function safety wrapper.
`-t, --tokens`   Instead of parsing the CoffeeScript, just lex it, and print out the token stream: [IDENTIFIER square] [ASSIGN =] [PARAM_START (] ...
`-n, --nodes`  Instead of compiling the CoffeeScript, just lex and parse it, and print out the parse tree:
Expressions
  Assign
    Value "square"
    Code "x"
      Op *
        Value "x"
        Value "x"
`--nodejs`   The node executable has some useful options you can set, such as `--debug, --debug-brk, --max-stack-size, and --expose-gc`. Use this flag to forward options directly to Node.js. To pass multiple flags, use `--nodejs` multiple times.

## Examples:

Compile a directory tree of .coffee files in src into a parallel tree of .js files in lib:

    coffee --compile --output lib/ src/

Watch a file for changes, and recompile it every time the file is saved:

    coffee --watch --compile experimental.coffee

Concatenate a list of files into a single script:

    coffee --join project.js --compile src/*.coffee

Print out the compiled JS from a one-liner:

    coffee -bpe "alert i for i in [0..10]"

All together now, watch and recompile an entire project as you work on it:

    coffee -o lib/ -cw src/

Start the CoffeeScript REPL (Ctrl-D to exit, Ctrl-Vfor multi-line):
coffee

# Functions

Functions are defined by an optional list of parameters in parentheses, an arrow, and the function body. The empty function looks like this: `->`

- from

    square = (x) -> x * x
    cube   = (x) -> square(x) * x

- to

    var cube, square;

    square = function(x) {
      return x * x;
    };

    cube = function(x) {
      return square(x) * x;
    };

Functions may also have default values for arguments. Override the default value by passing a non-null argument.

- from

    fill = (container, liquid = "coffee") ->
      "Filling the #{container} with #{liquid}..."

- to

    var fill;

    fill = function(container, liquid) {
      if (liquid == null) {
        liquid = "coffee";
      }
      return "Filling the " + container + " with " + liquid + "...";
    };

# Objects and Arrays

The CoffeeScript literals for objects and arrays look very similar to their JavaScript cousins. When each property is listed on its own line, the commas are optional. Objects may be created using indentation instead of explicit braces, similar to YAML.

- from

    song = ["do", "re", "mi", "fa", "so"]

    singers = {Jagger: "Rock", Elvis: "Roll"}

    bitlist = [
      1, 0, 1
      0, 0, 1
      1, 1, 0
    ]

    kids =
      brother:
        name: "Max"
        age:  11
      sister:
        name: "Ida"
        age:  9

- to

    var bitlist, kids, singers, song;

    song = ["do", "re", "mi", "fa", "so"];

    singers = {
      Jagger: "Rock",
      Elvis: "Roll"
    };

    bitlist = [1, 0, 1, 0, 0, 1, 1, 1, 0];

    kids = {
      brother: {
        name: "Max",
        age: 11
      },
      sister: {
        name: "Ida",
        age: 9
      }
    };

In JavaScript, you can't use reserved words, like class, as properties of an object, without quoting them as strings. CoffeeScript notices reserved words used as keys in objects and quotes them for you, so you don't have to worry about it (say, when using jQuery).

- from

    $('.account').attr class: 'active'

    log object.class

- to

    $('.account').attr({
      "class": 'active'
    });

    log(object["class"]);

# Lexical Scoping and Variable Safety

The CoffeeScript compiler takes care to make sure that all of your variables are properly declared within lexical scope — you never need to write  var yourself.

- from

    outer = 1
    changeNumbers = ->
      inner = -1
      outer = 10
    inner = changeNumbers()

- to

    var changeNumbers, inner, outer;

    outer = 1;

    changeNumbers = function() {
      var inner;

      inner = -1;
      return outer = 10;
    };

    inner = changeNumbers();

# If, Else, Unless, and Conditional Assignment

- from

    mood = greatlyImproved if singing

    if happy and knowsIt
      clapsHands()
      chaChaCha()
    else
      showIt()

    date = if friday then sue else jill

- to

    var date, mood;

    if (singing) {
      mood = greatlyImproved;
    }

    if (happy && knowsIt) {
      clapsHands();
      chaChaCha();
    } else {
      showIt();
    }

    date = friday ? sue : jill;

# Splats...

The JavaScript arguments object is a useful way to work with functions that accept variable numbers of arguments. CoffeeScript provides splats ..., both for function definition as well as invocation, making variable numbers of arguments a little bit more palatable.

- from

    gold = silver = rest = "unknown"

    awardMedals = (first, second, others...) ->
      gold   = first
      silver = second
      rest   = others

    contenders = [
      "Michael Phelps"
      "Liu Xiang"
      "Yao Ming"
      "Allyson Felix"
      "Shawn Johnson"
      "Roman Sebrle"
      "Guo Jingjing"
      "Tyson Gay"
      "Asafa Powell"
      "Usain Bolt"
    ]

    awardMedals contenders...

    alert "Gold: " + gold
    alert "Silver: " + silver
    alert "The Field: " + rest

- to

    var awardMedals, contenders, gold, rest, silver,
      __slice = [].slice;

    gold = silver = rest = "unknown";

    awardMedals = function() {
      var first, others, second;

      first = arguments[0], second = arguments[1], others = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
      gold = first;
      silver = second;
      return rest = others;
    };

    contenders = ["Michael Phelps", "Liu Xiang", "Yao Ming", "Allyson Felix", "Shawn Johnson", "Roman Sebrle", "Guo Jingjing", "Tyson Gay", "Asafa Powell", "Usain Bolt"];

    awardMedals.apply(null, contenders);

    alert("Gold: " + gold);

    alert("Silver: " + silver);

    alert("The Field: " + rest);

# Loops and Comprehensions

Most of the loops you'll write in CoffeeScript will be comprehensions over arrays, objects, and ranges. Comprehensions replace (and compile into) for loops, with optional guard clauses and the value of the current array index. Unlike for loops, array comprehensions are expressions, and can be returned and assigned.

- from

    # Eat lunch.
    eat food for food in ['toast', 'cheese', 'wine']

    # Fine five course dining.
    courses = ['greens', 'caviar', 'truffles', 'roast', 'cake']
    menu i + 1, dish for dish, i in courses

    # Health conscious meal.
    foods = ['broccoli', 'spinach', 'chocolate']
    eat food for food in foods when food isnt 'chocolate'

- to

    var courses, dish, food, foods, i, _i, _j, _k, _len, _len1, _len2, _ref;

    _ref = ['toast', 'cheese', 'wine'];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      food = _ref[_i];
      eat(food);
    }

    courses = ['greens', 'caviar', 'truffles', 'roast', 'cake'];

    for (i = _j = 0, _len1 = courses.length; _j < _len1; i = ++_j) {
      dish = courses[i];
      menu(i + 1, dish);
    }

    foods = ['broccoli', 'spinach', 'chocolate'];

    for (_k = 0, _len2 = foods.length; _k < _len2; _k++) {
      food = foods[_k];
      if (food !== 'chocolate') {
        eat(food);
      }
    }

Comprehensions should be able to handle most places where you otherwise would use a loop, each/forEach, map, or select/filter, for example: shortNames = (name for name in list when name.length < 5)
If you know the start and end of your loop, or would like to step through in fixed-size increments, you can use a range to specify the start and end of your comprehension.

- from

    countdown = (num for num in [10..1])

- to

    var countdown, num;

    countdown = (function() {
      var _i, _results;

      _results = [];
      for (num = _i = 10; _i >= 1; num = --_i) {
        _results.push(num);
      }
      return _results;
    })();

Note how because we are assigning the value of the comprehensions to a variable in the example above, CoffeeScript is collecting the result of each iteration into an array. Sometimes functions end with loops that are intended to run only for their side-effects. Be careful that you're not accidentally returning the results of the comprehension in these cases, by adding a meaningful return value — like true — or null, to the bottom of your function.

To step through a range comprehension in fixed-size chunks, use by, for example:
evens = (x for x in [0..10] by 2)

Comprehensions can also be used to iterate over the keys and values in an object. Use of to signal comprehension over the properties of an object instead of the values in an array.

- from

    yearsOld = max: 10, ida: 9, tim: 11

    ages = for child, age of yearsOld
      "#{child} is #{age}"

- to

    var age, ages, child, yearsOld;

    yearsOld = {
      max: 10,
      ida: 9,
      tim: 11
    };

    ages = (function() {
      var _results;

      _results = [];
      for (child in yearsOld) {
        age = yearsOld[child];
        _results.push("" + child + " is " + age);
      }
      return _results;
    })();

If you would like to iterate over just the keys that are defined on the object itself, by adding a hasOwnProperty check to avoid properties that may be inherited from the prototype, use
for own key, value of object

The only low-level loop that CoffeeScript provides is the while loop. The main difference from JavaScript is that the while loop can be used as an expression, returning an array containing the result of each iteration through the loop.

- from

    # Econ 101
    if this.studyingEconomics
      buy()  while supply > demand
      sell() until supply > demand

    # Nursery Rhyme
    num = 6
    lyrics = while num -= 1
      "#{num} little monkeys, jumping on the bed.
        One fell out and bumped his head."

- to

    var lyrics, num;

    if (this.studyingEconomics) {
      while (supply > demand) {
        buy();
      }
      while (!(supply > demand)) {
        sell();
      }
    }

    num = 6;

    lyrics = (function() {
      var _results;

      _results = [];
      while (num -= 1) {
        _results.push("" + num + " little monkeys, jumping on the bed.    One fell out and bumped his head.");
      }
      return _results;
    })();

For readability, the until keyword is equivalent to while not, and the loop keyword is equivalent to while true.

When using a JavaScript loop to generate functions, it's common to insert a closure wrapper in order to ensure that loop variables are closed over, and all the generated functions don't just share the final values. CoffeeScript provides the do keyword, which immediately invokes a passed function, forwarding any arguments.

- from

    for filename in list
      do (filename) ->
        fs.readFile filename, (err, contents) ->
          compile filename, contents.toString()

- to

    var filename, _fn, _i, _len;

    _fn = function(filename) {
      return fs.readFile(filename, function(err, contents) {
        return compile(filename, contents.toString());
      });
    };
    for (_i = 0, _len = list.length; _i < _len; _i++) {
      filename = list[_i];
      _fn(filename);
    }

# Array Slicing and Splicing with Ranges

Ranges can also be used to extract slices of arrays. With two dots (3..6), the range is inclusive (3, 4, 5, 6); with three dots (3...6), the range excludes the end (3, 4, 5). Slices indices have useful defaults. An omitted first index defaults to zero and an omitted second index defaults to the size of the array.

- from

    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

    start   = numbers[0..2]

    middle  = numbers[3...6]

    end     = numbers[6..]

    copy    = numbers[..]

- to

    var copy, end, middle, numbers, start;

    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

    start = numbers.slice(0, 3);

    middle = numbers.slice(3, 6);

    end = numbers.slice(6);

    copy = numbers.slice(0);

The same syntax can be used with assignment to replace a segment of an array with new values, splicing it.

- from

    numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    numbers[3..6] = [-3, -4, -5, -6]

- to

    var numbers, _ref;

    numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

    [].splice.apply(numbers, [3, 4].concat(_ref = [-3, -4, -5, -6])), _ref;

# Everything is an Expression (at least, as much as possible)

You might have noticed how even though we don't add return statements to CoffeeScript functions, they nonetheless return their final value. The CoffeeScript compiler tries to make sure that all statements in the language can be used as expressions. Watch how the return gets pushed down into each possible branch of execution in the function below.

- from

    grade = (student) ->
      if student.excellentWork
        "A+"
      else if student.okayStuff
        if student.triedHard then "B" else "B-"
      else
        "C"

    eldest = if 24 > 21 then "Liz" else "Ike"

- to

    var eldest, grade;

    grade = function(student) {
      if (student.excellentWork) {
        return "A+";
      } else if (student.okayStuff) {
        if (student.triedHard) {
          return "B";
        } else {
          return "B-";
        }
      } else {
        return "C";
      }
    };

    eldest = 24 > 21 ? "Liz" : "Ike";

Even though functions will always return their final value, it's both possible and encouraged to return early from a function body writing out the explicit return (return value), when you know that you're done.

Because variable declarations occur at the top of scope, assignment can be used within expressions, even for variables that haven't been seen before:

- from

    six = (one = 1) + (two = 2) + (three = 3)

- to

    var one, six, three, two;

    six = (one = 1) + (two = 2) + (three = 3);

Things that would otherwise be statements in JavaScript, when used as part of an expression in CoffeeScript, are converted into expressions by wrapping them in a closure. This lets you do useful things, like assign the result of a comprehension to a variable:

- from

    # The first ten global properties.
    globals = (name for name of window)[0...10]

- to

    var globals, name;

    globals = ((function() {
      var _results;

      _results = [];
      for (name in window) {
        _results.push(name);
      }
      return _results;
    })()).slice(0, 10);

As well as silly things, like passing a try/catch statement directly into a function call:

- from

    alert(
      try
        nonexistent / undefined
      catch error
        "And the error is ... #{error}"
    )

- to

    var error;

    alert((function() {
      try {
        return nonexistent / void 0;
      } catch (_error) {
        error = _error;
        return "And the error is ... " + error;
      }
    })());

There are a handful of statements in JavaScript that can't be meaningfully converted into expressions, namely break, continue, and return. If you make use of them within a block of code, CoffeeScript won't try to perform the conversion.

# Operators and Aliases

Because the `==` operator frequently causes undesirable coercion, is intransitive, and has a different meaning than in other languages, CoffeeScript compiles `==` into `===`, and `!=` into  `!==`. In addition, is compiles into `===`, and `isnt` into `!==`.

You can use `not` as an alias for `!`.

For logic, `and` compiles to `&&`, and `or` into `||`.

Instead of a newline or semicolon, then can be used to separate conditions from expressions, in while, if/else, and switch/when statements.

As in YAML, `on` and `yes` are the same as boolean `true`, while `off` and `no` are boolean `false`.

`unless` can be used as the inverse of `if`.

As a shortcut for `this.property`, you can use `@property`.

You can use `in` to test for array presence, and `of` to test for JavaScript object-key presence.

All together now:

`CoffeeScript`    `JavaScript`
     is         ===
     isnt       !==
     not        !
     and        &&
     or         ||
true, yes, on   true
false, no, off  false
@, this         this
     of         in
     in         no JS equivalent

- from

    launch() if ignition is on

    volume = 10 if band isnt SpinalTap

    letTheWildRumpusBegin() unless answer is no

    if car.speed < limit then accelerate()

    winner = yes if pick in [47, 92, 13]

    print inspect "My name is #{@name}"

- to

    var volume, winner;

    if (ignition === true) {
      launch();
    }

    if (band !== SpinalTap) {
      volume = 10;
    }

    if (answer !== false) {
      letTheWildRumpusBegin();
    }

    if (car.speed < limit) {
      accelerate();
    }

    if (pick === 47 || pick === 92 || pick === 13) {
      winner = true;
    }

    print(inspect("My name is " + this.name));

# The Existential Operator

It's a little difficult to check for the existence of a variable in JavaScript. if (variable) ... comes close, but fails for zero, the empty string, and false. CoffeeScript's existential operator ? returns true unless a variable is null or undefined, which makes it analogous to Ruby's nil?

It can also be used for safer conditional assignment than ||= provides, for cases where you may be handling numbers or strings.

- from

    solipsism = true if mind? and not world?

    speed = 0
    speed ?= 15

    footprints = yeti ? "bear"

- to

    var footprints, solipsism, speed;

    if ((typeof mind !== "undefined" && mind !== null) && (typeof world === "undefined" || world === null)) {
      solipsism = true;
    }

    speed = 0;

    if (speed == null) {
      speed = 15;
    }

    footprints = typeof yeti !== "undefined" && yeti !== null ? yeti : "bear";

The accessor variant of the existential operator ?. can be used to soak up null references in a chain of properties. Use it instead of the dot accessor . in cases where the base value may be null or undefined. If all of the properties exist then you'll get the expected result, if the chain is broken, undefined is returned instead of the TypeError that would be raised otherwise.

- from

    zip = lottery.drawWinner?().address?.zipcode

- to

    var zip, _ref;

    zip = typeof lottery.drawWinner === "function" ? (_ref = lottery.drawWinner().address) != null ? _ref.zipcode : void 0 : void 0;

Soaking up nulls is similar to Ruby's andand gem, and to the safe navigation operator in Groovy.

# Classes, Inheritance, and Super

JavaScript's prototypal inheritance has always been a bit of a brain-bender, with a whole family tree of libraries that provide a cleaner syntax for classical inheritance on top of JavaScript's prototypes: Base2, Prototype.js, JS.Class, etc. The libraries provide syntactic sugar, but the built-in inheritance would be completely usable if it weren't for a couple of small exceptions: it's awkward to call super (the prototype object's implementation of the current function), and it's awkward to correctly set the prototype chain.

Instead of repetitively attaching functions to a prototype, CoffeeScript provides a basic `class` structure that allows you to name your class, set the superclass, assign prototypal properties, and define the constructor, in a single assignable expression.

Constructor functions are named, to better support helpful stack traces. In the first class in the example below, `this.constructor.name is "Animal"`.

- from

    class Animal
      constructor: (@name) ->

      move: (meters) ->
        alert @name + " moved #{meters}m."

    class Snake extends Animal
      move: ->
        alert "Slithering..."
        super 5

    class Horse extends Animal
      move: ->
        alert "Galloping..."
        super 45

    sam = new Snake "Sammy the Python"
    tom = new Horse "Tommy the Palomino"

    sam.move()
    tom.move()

- to

    var Animal, Horse, Snake, sam, tom, _ref, _ref1,
      __hasProp = {}.hasOwnProperty,
      __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

    Animal = (function() {
      function Animal(name) {
        this.name = name;
      }

      Animal.prototype.move = function(meters) {
        return alert(this.name + (" moved " + meters + "m."));
      };

      return Animal;

    })();

    Snake = (function(_super) {
      __extends(Snake, _super);

      function Snake() {
        _ref = Snake.__super__.constructor.apply(this, arguments);
        return _ref;
      }

      Snake.prototype.move = function() {
        alert("Slithering...");
        return Snake.__super__.move.call(this, 5);
      };

      return Snake;

    })(Animal);

    Horse = (function(_super) {
      __extends(Horse, _super);

      function Horse() {
        _ref1 = Horse.__super__.constructor.apply(this, arguments);
        return _ref1;
      }

      Horse.prototype.move = function() {
        alert("Galloping...");
        return Horse.__super__.move.call(this, 45);
      };

      return Horse;

    })(Animal);

    sam = new Snake("Sammy the Python");

    tom = new Horse("Tommy the Palomino");

    sam.move();

    tom.move();

If structuring your prototypes classically isn't your cup of tea, CoffeeScript provides a couple of lower-level conveniences. The extends operator helps with proper prototype setup, and can be used to create an inheritance chain between any pair of constructor functions; :: gives you quick access to an object's prototype; and super() is converted into a call against the immediate ancestor's method of the same name.

- from

    String::dasherize = ->
      this.replace /_/g, "-"

- to

    String.prototype.dasherize = function() {
      return this.replace(/_/g, "-");
    };

Finally, class definitions are blocks of executable code, which make for interesting metaprogramming possibilities. Because in the context of a class definition,  `this` is the class object itself (the constructor function), you can assign static properties by using
`@property: value`, and call functions defined in parent classes: `@attr 'title', type: 'text'`

# Destructuring Assignment

To make extracting values from complex arrays and objects more convenient, CoffeeScript implements ECMAScript Harmony's proposed destructuring assignment syntax. When you assign an array or object literal to a value, CoffeeScript breaks up and matches both sides against each other, assigning the values on the right to the variables on the left. In the simplest case, it can be used for parallel assignment:

- from

    theBait   = 1000
    theSwitch = 0
    [theBait, theSwitch] = [theSwitch, theBait]

- to

    var theBait, theSwitch, _ref;

    theBait = 1000;

    theSwitch = 0;

    _ref = [theSwitch, theBait], theBait = _ref[0], theSwitch = _ref[1];

But it's also helpful for dealing with functions that return multiple values.

- from

    weatherReport = (location) ->
      # Make an Ajax request to fetch the weather...
      [location, 72, "Mostly Sunny"]

    [city, temp, forecast] = weatherReport "Berkeley, CA"

- to

    var city, forecast, temp, weatherReport, _ref;

    weatherReport = function(location) {
      return [location, 72, "Mostly Sunny"];
    };

    _ref = weatherReport("Berkeley, CA"), city = _ref[0], temp = _ref[1], forecast = _ref[2];

Destructuring assignment can be used with any depth of array and object nesting, to help pull out deeply nested properties.

- from

    futurists =
      sculptor: "Umberto Boccioni"
      painter:  "Vladimir Burliuk"
      poet:
        name:   "F.T. Marinetti"
        address: [
          "Via Roma 42R"
          "Bellagio, Italy 22021"
        ]

    {poet: {name, address: [street, city]}} = futurists

- to

    var city, futurists, name, street, _ref, _ref1;

    futurists = {
      sculptor: "Umberto Boccioni",
      painter: "Vladimir Burliuk",
      poet: {
        name: "F.T. Marinetti",
        address: ["Via Roma 42R", "Bellagio, Italy 22021"]
      }
    };

    _ref = futurists.poet, name = _ref.name, (_ref1 = _ref.address, street = _ref1[0], city = _ref1[1]);

Destructuring assignment can even be combined with splats.

- from

    tag = "<impossible>"

    [open, contents..., close] = tag.split("")

- to

    var close, contents, open, tag, _i, _ref,
      __slice = [].slice;

    tag = "<impossible>";

    _ref = tag.split(""), open = _ref[0], contents = 3 <= _ref.length ? __slice.call(_ref, 1, _i = _ref.length - 1) : (_i = 1, []), close = _ref[_i++];

Destructuring assignment is also useful when combined with class constructors to assign propeties to your instance from an options object passed to the constructor.

- from

    class Person
      constructor: (options) ->
        {@name, @age, @height} = options

- to

    var Person;

    Person = (function() {
      function Person(options) {
        this.name = options.name, this.age = options.age, this.height = options.height;
      }

      return Person;

    })();

# Function binding

In JavaScript, the this keyword is dynamically scoped to mean the object that the current function is attached to. If you pass a function as a callback or attach it to a different object, the original value of this will be lost. If you're not familiar with this behavior, this Digital Web article gives a good overview of the quirks.

The fat arrow => can be used to both define a function, and to bind it to the current value of this, right on the spot. This is helpful when using callback-based libraries like Prototype or jQuery, for creating iterator functions to pass to each, or event-handler functions to use with bind. Functions created with the fat arrow are able to access properties of the this where they're defined.

- from

    Account = (customer, cart) ->
      @customer = customer
      @cart = cart

      $('.shopping_cart').bind 'click', (event) =>
        @customer.purchase @cart

- to

    var Account;

    Account = function(customer, cart) {
      var _this = this;

      this.customer = customer;
      this.cart = cart;
      return $('.shopping_cart').bind('click', function(event) {
        return _this.customer.purchase(_this.cart);
      });
    };

If we had used -> in the callback above, @customer would have referred to the undefined "customer" property of the DOM element, and trying to call purchase() on it would have raised an exception.

When used in a class definition, methods declared with the fat arrow will be automatically bound to each instance of the class when the instance is constructed.

# Embedded JavaScript

Hopefully, you'll never need to use it, but if you ever need to intersperse snippets of JavaScript within your CoffeeScript, you can use backticks to pass it straight through.

- from

    hi = `function() {
      return [document.title, "Hello JavaScript"].join(": ");
    }`

- to

    var hi;

    hi = function() {
      return [document.title, "Hello JavaScript"].join(": ");
    };

# Switch/When/Else

Switch statements in JavaScript are a bit awkward. You need to remember to break at the end of every case statement to avoid accidentally falling through to the default case. CoffeeScript prevents accidental fall-through, and can convert the switch into a returnable, assignable expression. The format is: switch condition,  when clauses, else the default case.

As in Ruby, switch statements in CoffeeScript can take multiple values for each when clause. If any of the values match, the clause runs.

- from

    switch day
      when "Mon" then go work
      when "Tue" then go relax
      when "Thu" then go iceFishing
      when "Fri", "Sat"
        if day is bingoDay
          go bingo
          go dancing
      when "Sun" then go church
      else go work

- to

    switch (day) {
      case "Mon":
        go(work);
        break;
      case "Tue":
        go(relax);
        break;
      case "Thu":
        go(iceFishing);
        break;
      case "Fri":
      case "Sat":
        if (day === bingoDay) {
          go(bingo);
          go(dancing);
        }
        break;
      case "Sun":
        go(church);
        break;
      default:
        go(work);
    }

Switch statements can also be used without a control expression, turning them in to a cleaner alternative to if/else chains.

- from

    score = 76
    grade = switch
      when score < 60 then 'F'
      when score < 70 then 'D'
      when score < 80 then 'C'
      when score < 90 then 'B'
      else 'A'
    # grade == 'C'

- to

    var grade, score;

    score = 76;

    grade = (function() {
      switch (false) {
        case !(score < 60):
          return 'F';
        case !(score < 70):
          return 'D';
        case !(score < 80):
          return 'C';
        case !(score < 90):
          return 'B';
        default:
          return 'A';
      }
    })();

# Try/Catch/Finally

Try/catch statements are just about the same as JavaScript (although they work as expressions).

- from

    try
      allHellBreaksLoose()
      catsAndDogsLivingTogether()
    catch error
      print error
    finally
      cleanUp()

- to

    var error;

    try {
      allHellBreaksLoose();
      catsAndDogsLivingTogether();
    } catch (_error) {
      error = _error;
      print(error);
    } finally {
      cleanUp();
    }

# Chained Comparisons

CoffeeScript borrows chained comparisons from Python — making it easy to test if a value falls within a certain range.

- from

    cholesterol = 127

    healthy = 200 > cholesterol > 60

- to

    var cholesterol, healthy;

    cholesterol = 127;

    healthy = (200 > cholesterol && cholesterol > 60);

# String Interpolation, Block Strings, and Block Comments

Ruby-style string interpolation is included in CoffeeScript. Double-quoted strings allow for interpolated values, using #{ ... }, and single-quoted strings are literal.

- from

    author = "Wittgenstein"
    quote  = "A picture is a fact. -- #{ author }"

    sentence = "#{ 22 / 7 } is a decent approximation of π"

- to

    var author, quote, sentence;

    author = "Wittgenstein";

    quote = "A picture is a fact. -- " + author;

    sentence = "" + (22 / 7) + " is a decent approximation of π";

# Multiline strings are allowed in CoffeeScript.

- from

    mobyDick = "Call me Ishmael. Some years ago --
     never mind how long precisely -- having little
     or no money in my purse, and nothing particular
     to interest me on shore, I thought I would sail
     about a little and see the watery part of the
     world..."

- to

    var mobyDick;

    mobyDick = "Call me Ishmael. Some years ago -- never mind how long precisely -- having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world...";

Block strings can be used to hold formatted or indentation-sensitive text (or, if you just don't feel like escaping quotes and apostrophes). The indentation level that begins the block is maintained throughout, so you can keep it all aligned with the body of your code.

- from

    html = """
           <strong>
             cup of coffeescript
           </strong>
           """

- to

    var html;

    html = "<strong>\n  cup of coffeescript\n</strong>";

Double-quoted block strings, like other double-quoted strings, allow interpolation.

Sometimes you'd like to pass a block comment through to the generated JavaScript. For example, when you need to embed a licensing header at the top of a file. Block comments, which mirror the syntax for block strings, are preserved in the generated code.

- from

    ###
    SkinnyMochaHalfCaffScript Compiler v1.0
    Released under the MIT License
    ###

- to

    /*
    SkinnyMochaHalfCaffScript Compiler v1.0
    Released under the MIT License
    */

# Block Regular Expressions

Similar to block strings and comments, CoffeeScript supports block regexes — extended regular expressions that ignore internal whitespace and can contain comments and interpolation. Modeled after Perl's /x modifier, CoffeeScript's block regexes are delimited by /// and go a long way towards making complex regular expressions readable. To quote from the CoffeeScript source:

- from

    OPERATOR = /// ^ (
      ?: [-=]>             # function
       | [-+*/%<>&|^!?=]=  # compound assign / compare
       | >>>=?             # zero-fill right shift
       | ([-+:])\1         # doubles
       | ([&|<>])\2=?      # logic / shift
       | \?\.              # soak access
       | \.{2,3}           # range or splat
    ) ///

- to

    var OPERATOR;

    OPERATOR = /^(?:[-=]>|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>])\2=?|\?\.|\.{2,3})/;

# Cake, and Cakefiles

CoffeeScript includes a (very) simple build system similar to Make and Rake. Naturally, it's called Cake, and is used for the tasks that build and test the CoffeeScript language itself. Tasks are defined in a file named Cakefile, and can be invoked by running cake [task] from within the directory. To print a list of all the tasks and options, just type cake.

Task definitions are written in CoffeeScript, so you can put arbitrary code in your Cakefile. Define a task with a name, a long description, and the function to invoke when the task is run. If your task takes a command-line option, you can define the option with short and long flags, and it will be made available in the options object. Here's a task that uses the Node.js API to rebuild CoffeeScript's parser:

- from

    fs = require 'fs'

    option '-o', '--output [DIR]', 'directory for compiled code'

    task 'build:parser', 'rebuild the Jison parser', (options) ->
      require 'jison'
      code = require('./lib/grammar').parser.generate()
      dir  = options.output or 'lib'
      fs.writeFile "#{dir}/parser.js", code

- to

    var fs;

    fs = require('fs');

    option('-o', '--output [DIR]', 'directory for compiled code');

    task('build:parser', 'rebuild the Jison parser', function(options) {
      var code, dir;

      require('jison');
      code = require('./lib/grammar').parser.generate();
      dir = options.output || 'lib';
      return fs.writeFile("" + dir + "/parser.js", code);
    });

If you need to invoke one task before another — for example, running  build before test, you can use the invoke function:  invoke 'build'. Cake tasks are a minimal way to expose your CoffeeScript functions to the command line, so don't expect any fanciness built-in. If you need dependencies, or async callbacks, it's best to put them in your code itself — not the cake task.

# Source Maps

CoffeeScript 1.6.1 and above include support for generating source maps, a way to tell your JavaScript engine what part of your CoffeeScript program matches up with the code being evaluated. Browsers that support it can automatically use source maps to show your original source code in the debugger. To generate source maps alongside your JavaScript files, pass the --map or -m flag to the compiler.

For a full introduction to source maps, how they work, and how to hook them up in your browser, read the HTML5 Tutorial.

# "text/coffeescript" Script Tags

While it's not recommended for serious use, CoffeeScripts may be included directly within the browser using <script type="text/coffeescript"> tags. The source includes a compressed and minified version of the compiler (Download current version here, 39k when gzipped) as extras/coffee-script.js. Include this file on a page with inline CoffeeScript tags, and it will compile and evaluate them in order.

In fact, the little bit of glue script that runs "Try CoffeeScript" above, as well as the jQuery for the menu, is implemented in just this way. View source and look at the bottom of the page to see the example. Including the script also gives you access to CoffeeScript.compile() so you can pop open Firebug and try compiling some strings.

The usual caveats about CoffeeScript apply — your inline scripts will run within a closure wrapper, so if you want to expose global variables or functions, attach them to the window object.