# informacion que el usuario ingreso se guarda en userInput que es un diccionario!
# https://www.w3schools.com/python/python_dictionaries.asp
# esta variable permite la comunicación entre distintos Frames

userInput = dict.fromkeys(['order', 'type', 'frequency', 'frequency2', 'gain', 'epsilon', 'inputFunction',
                          'inputAmplitude', 'inputFreq', 'transf', 'p1', 'p2', 'z1', 'z2'])

#THINGS INSIDE userInput

#"order" : 1, 2             Describes order of chosen filter
#"type": "low", "high", "band", "all", "notch", "guess"           Describes filter type
#"frequency"                List of key frequencies
#"poles"
#"zeros"
#"epsilon"
#'inputFunction'            "Bode", "Distribution", "Sine", "Step"
#'transf'                   Transfer function H
#
#


#!/usr/bin/python
# import cython
import numpy as np
import pyximport; pyximport.install(setup_args={
                              "include_dirs":np.get_include()},
                            reload_support=True)

import XOR

X = np.random.randint(2, size=(10000,2), dtype=np.int32)
Y = np.ones([10000]).astype(dtype=np.int32)

for i in range(10000):
    if X[i,0] == X[i,1]:
        Y[i] = 0
# Parameters for the Tsetlin Machine
T = 1
s = 3.9
number_of_clauses = 2
states = 100
Th = 1

# Parameters of the pattern recognition problem
number_of_features = 2

# Training configuration
epochs = 200

# Loading of training and test data
NoOfTrainingSamples = len(X)*80//100
NoOfTestingSamples = len(X) - NoOfTrainingSamples

X_training = X[0:NoOfTrainingSamples,:] # Input features
y_training = Y[0:NoOfTrainingSamples] # Target value

X_test = X[NoOfTrainingSamples:NoOfTrainingSamples+NoOfTestingSamples,:] # Input features
y_test = Y[NoOfTrainingSamples:NoOfTrainingSamples+NoOfTestingSamples] # Target value

# This is a multiclass variant of the Tsetlin Machine, capable of distinguishing between multiple classes
tsetlin_machine = XOR.TsetlinMachine(number_of_clauses, number_of_features, states, s, T, Th)

# Training of the Tsetlin Machine in batch mode. The Tsetlin Machine can also be trained online
tsetlin_machine.fit(X_training, y_training, y_training.shape[0], epochs=epochs)

# Some performacne statistics

print ("Accuracy on test data (no noise):", tsetlin_machine.evaluate(X_test, y_test, y_test.shape[0]))

for clause in range(number_of_clauses):
    print('Clause', clause+1),
    for feature in range(number_of_features):
        for tatype in range(2):
            State = tsetlin_machine.get_state(clause,feature,tatype)
            if State >= 101:
                Decision = 'In'
            else:
                Decision = 'Ex'
            print('feature %d TA %d State %d' % (feature, tatype+1, State)),
    print('/n')


##########################################################
##       CONFIGURATION FOR HZZ4L TREES                  ##
##########################################################
import PhysicsTools.HeppyCore.framework.config as cfg

#Load all analyzers
from CMGTools.HToZZ4L.analyzers.hzz4lCore_modules_cff import *
from CMGTools.HToZZ4L.analyzers.hzz4lExtra_modules_cff import *
from CMGTools.HToZZ4L.tools.configTools import *
from CMGTools.RootTools.samples.autoAAAconfig import *

#-------- SEQUENCE
sequence = cfg.Sequence(hzz4lPreSequence +  [ fastSkim2L ] + hzz4lObjSequence + [
    trigMatcher1Mu, trigMatcher1El,
    twoLeptonAnalyzerTnP,
    twoLeptonEventSkimmerTnP,
    twoLeptonTreeProducerTnP
])

#run = "Both"
#run = "Mu"
run = "El"

#-------- SAMPLES AND TRIGGERS -----------
from CMGTools.HToZZ4L.samples.samples_13TeV_Fall15 import *
if   run == "Mu": dataSamples = [ d for d in dataSamples if "SingleM" in d.name ]
elif run == "El": dataSamples = [ d for d in dataSamples if "SingleE" in d.name ]
else            : dataSamples = [ d for d in dataSamples if "Single"  in d.name ]
for d in dataSamples:
    d.triggers = triggers_1mu if 'Muon' in d.name else triggers_1e
    d.vetoTriggers = []
    d.splitFactor = max((len(d.files)+4)/7,1)
configureSplittingFromTime([d for d in dataSamples if "Silver" not in d.name], 10.0, 2)

mcSamples = [ DYJetsToLL_LO_M50 ] # , DYJetsToLL_M50 ]
for d in mcSamples:
    d.triggers = triggers_1mu + triggers_1e
    d.vetoTriggers = []
configureSplittingFromTime(mcSamples, 25.0, 2)

if True:
    prescaleComponents(mcSamples, 10)
    dataSamples = [ d for d in dataSamples if 'Run2015D' in d.name ]
    redefineRunRange(dataSamples,[258214,258214])

selectedComponents = dataSamples + mcSamples
if run == "Mu":
    doKalmanMuonCorrections(smear="basic")
    fastSkim2L.eleCut = lambda ele : False
    lepAna.loose_electron_isoCut = lambda ele : False
elif run == "El":
    doECalCorrections(era="25ns")
    fastSkim2L.muCut = lambda mu : False
    lepAna.loose_muon_isoCut = lambda mu : False
    configureSplittingFromTime(dataSamples, 4.0, 1)
    configureSplittingFromTime(mcSamples, 10.0, 1)
else:
    doECalCorrections(era="25ns")
    doKalmanMuonCorrections(smear="basic")

printSummary(selectedComponents)
if True: autoAAA(selectedComponents)
#doECalCorrections(era="25ns")
doKalmanMuonCorrections(smear="basic")

from PhysicsTools.HeppyCore.framework.heppy_loop import getHeppyOption
test = getHeppyOption('test')
lepAna.do_mc_match_photons = False
if test in ("1","1M","1E"):
    trigMatcher1Mu.verbose = True
    trigMatcher1El.verbose = True
    component = { "1":DYJetsToLL_LO_M50, "1M":SingleMuon_Run2015D_16Dec2015_25ns, "1E":SingleElectron_Run2015D_16Dec2015_25ns }[test]
    if not component.isMC: redefineRunRange([component],[258214,258214])
    selectedComponents = doTest1( component, sequence=sequence )
elif test == "1M":
    selectedComponents = doTest1( DYJetsToLL_LO_M50 , sequence=sequence )
elif test in ('2','3','5'):
    doTestN(test,selectedComponents)

config = autoConfig(selectedComponents, sequence)


import re
class Solution:

    def myAtoi(self, s: str) -> int:
        # Initialize empty string to store numbers in
        strTemp = ""

        #Loop over chars in string
        for i in s:
            # Condition if there is a whitespace and it is still in the begining of the string
            # This is assumed when there are no elements added yet to the string
            if i == " " and len(strTemp) == 0:
                continue
            #if we meet a + or a - before any numbers
            elif (i == "-" or i == "+") and len(strTemp) == 0:
                strTemp += i
            # if we meet a digit then we append it to the string
            elif i.isdigit() :
                strTemp += i
            # If non of those coditions are met then we stop the loop
            else:
                break

        if not re.search("[0-9]", strTemp[0:]):
            return 0
        if int(strTemp) <= pow(-2, 31):
            return pow(-2, 31)
        if int(strTemp) >= pow(2, 31)-1:
            return pow(2, 31)-1
        else:
            return int(strTemp)


"""
Author of Code: Enrique Boswell Nueve IV.
Email: enriquenueve9@gmail.com
Written: June 2019

Description: Python-3.7 implementation of the paper "A General Reflex Fuzzy Min-Max Neural Network."
The General Reflex Fuzzy Min-Max Neural Network is a supervised clustering algorithim.

I DO NOT CLAIM TO BE THE CREATOR OF THIS ALGORITHIM! I have no affilation
with the creation of the paper this code is based on.
For information about the creators of this algorithim and the paper that it is based on,
please refer to the citation below.

@article{Nandedkar2007AGR,
  title={A General Reflex Fuzzy Min-Max Neural Network},
  author={Abhijeet V. Nandedkar and Prabir Kumar Biswas},
  journal={Engineering Letters},
  year={2007},
  volume={14},
  pages={195-205}
}
"""

# --- Import Modules --- #
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from GRMMFN import ReflexFuzzyNeuroNetwork

def main():
    # --- Import Iris data and split --- #
    data = pd.read_csv('iris_data_norm.csv')
    data = data.iloc[:,1:]
    X = data.iloc[:,:-1]
    y = data.iloc[:,-1]

    scaler_min_max = MinMaxScaler(feature_range=(0.01, .99))
    X = scaler_min_max.fit_transform(X)

    X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.33, random_state=42)
    y_train, y_test = y_train.values, y_test.values
    X_train, X_test = X_train.T, X_test.T

    # --- Declare network --- #
    nn = ReflexFuzzyNeuroNetwork(gamma=2, theta=.1)

    # --- Run network --- #
    nn.train(X_train, y_train)

    # --- Test Network --- #
    nn.test(X_test,y_test)

main()


#Author: stone
import os

def read_ad():
    lines = open("../tmp/avazu_ad_quantify",'r').readlines()
    dic = {}
    for line in lines:
        inf = line.strip().split("@")
        key = inf[0]
        if key not in dic:
            dic[key] = inf

    return dic

def join():
    lines = open("../tmp/avazu_sample_user",'r').readlines()
    fptr = open("../tmp/avazu_ad_user_original",'w')
    dic = read_ad()
    for line in lines:
        inf = line.strip().split(",")
        key = inf[0]
        if key in dic:
            fptr.write("{}@".format("@".join(dic[key])))
            fptr.write("{}\n".format("@".join(inf[1:])))

if __name__ == "__main__":
    join()


# Python Program to blur image

# Importing cv2 module
import cv2

# importing os module
import os

# Image path
image_path = r'C:\blurndeblur\1.jpg'

# Image directory
directory = r'C:\blurndeblur\images\savedBlurImg'

# bat.jpg is the batman image.
img = cv2.imread(image_path)

# Change the current directory
# to specified directory
os.chdir(directory)

#List files and directories
# in 'C:/Users/Rajnish/Desktop/GeeksforGeeks'
print("Before saving image:")
print(os.listdir(directory))

# Filename
filename = 'blurred.jpg'

# Gaussian Blurring
# Again, you can change the kernel size
gausBlur = cv2.GaussianBlur(img, (25,25),0)
cv2.imshow('Gaussian Blurring', gausBlur)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Using cv2.imwrite() method
# Saving the image
cv2.imwrite(filename, gausBlur)

# List files and directories
# in 'C:/Users / Rajnish / Desktop / GeeksforGeeks'
print("After saving image:")
print(os.listdir(directory))

print('Successfully saved')


# DFS
N = int(input())
Lines = int(input())

graph = [[] for _ in range(N+1)]
visited = [False] * (N+1)

for i in range(Lines):
    node_1, node_2 = list(map(int, (input().split())))
    graph[node_1].append(node_2)
    graph[node_2].append(node_1)

def dfs(graph, v, visited):
    visited[v] = True

    visited_list = []
    visited_list.append(v)

    for i in graph[v]:
        if not visited[i]:
            visited_list = visited_list + dfs(graph, i, visited)

    return visited_list

result = list(set(dfs(graph, 1, visited)))
print(len(result)-1)


import torch
from torch import nn as nn
from torch.nn import functional as F

from basicsr.utils.registry import ARCH_REGISTRY
from .arch_util import ResidualBlockNoBN, make_layer
from .tmpalign_util import TMPAlign

@ARCH_REGISTRY.register()
class TMP(nn.Module):

    def __init__(self,
                 num_in_ch=3,
                 num_out_ch=3,
                 num_feat=64,
                 num_frame=5,
                 num_extract_block=5,
                 num_reconstruct_block=10,
                 center_frame_idx=None,
                 hr_in=False):

        super().__init__()
        if center_frame_idx is None:
            self.center_frame_idx = num_frame // 2
        else:
            self.center_frame_idx = center_frame_idx

        self.hr_in = hr_in

        # extract features for each frame
        self.conv_first = nn.Conv2d(num_in_ch, num_feat, 3, padding=1)
        self.feature_extraction = make_layer(ResidualBlockNoBN, num_extract_block, num_feat=num_feat)

        # align
        self.align = TMPAlign(num_feat=num_feat)

        # upsample
        self.upconv1 = nn.Conv2d(num_feat, 48, 3, 1, 1)
        self.pixel_shuffle = nn.PixelShuffle(4)

        # activation function
        self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True)

    def forward(self, x, hidden_states=None, return_hs=False):
        b, t, c, h, w = x.size()
        if self.hr_in:
            assert h % 16 == 0 and w % 16 == 0, ('The height and width must be multiple of 16.')
        else:
            assert h % 4 == 0 and w % 4 == 0, ('The height and width must be multiple of 4.')

        # extract features for each frame
        feat_origin = self.lrelu(self.conv_first(x.view(-1, c, h, w)))
        feat_l1 = self.feature_extraction(feat_origin)

        # align
        feat, hidden_states = self.align(feat_l1.view(b, t, -1, h, w), x, hidden_states)
        feat = feat.view(b*t, -1, h, w)

        # upsample
        out = feat
        out = self.pixel_shuffle(self.upconv1(out)).view(b, t, c, 4*h, 4*w)
        if self.hr_in:
            base = x
        else:
            base = F.interpolate(x.view(-1, c, h, w), scale_factor=4, mode='bilinear', align_corners=False).view(b, t, c, 4*h, 4*w)
        out += base

        if return_hs is True:
            return out, hidden_states
        else:
            return out


# 3x 마을 사람들은 3을 저주의 숫자라고 생각하기 때문에 3의 배수와 숫자 3을 사용하지 않습니다.
# 10진법	3x 마을에서 쓰는 숫자	10진법	3x 마을에서 쓰는 숫자
# 1	1	6	8
# 2	2	7	10
# 3	4	8	11
# 4	5	9	14
# 5	7	10	16
# 정수 n이 매개변수로 주어질 때, n을 3x 마을에서 사용하는 숫자로 바꿔 return하도록 solution 함수를 완성해주세요.
# 못 푼 문제

# 풀이 1

def solution(n):
    n_list = [i for i in range(1,230)]
    n_list2 = []
    for i in n_list:
        if i%3 != 0 and i%10 != 3 and (i<30 or i >=40) and (i<130 or i >=140):
            n_list2.append(i)

    return n_list2[n-1]

# 풀이 2 (나도 첨엔 이런 방향..)

def solution(n):
    answer = 0
    for _ in range(n):
        answer += 1
        while answer % 3 == 0 or '3' in str(answer):
            answer += 1
    return answer


from openerp.osv import fields, osv
from openerp.tools.translate import _
import time

import logging

_logger = logging.getLogger(__name__)

class grp_set_def_cur_rate_type(osv.osv):
    _inherit = "res.currency.rate"

    _columns = {
        'rate_presupuesto': fields.float('Tipo cambio presupuesto', digits=(12, 6), help='Tipo de cambio para enviar al SIIF'),
        'rate_arbitraje': fields.float('Arbitraje', digits=(12, 6), help='Tipo de cambio arbitraje'), #001 Arbitraje
    }

    _defaults = {
        'rate_presupuesto': 1,
        'rate_arbitraje': 1,
    }

grp_set_def_cur_rate_type()

class grp_calcular_arbitraje(osv.osv):
    _inherit = "res.currency"

    def _current_rate_presupuesto(self, cr, uid, ids, name, arg, context=None):
        raise_on_no_rate= False
        if context is None:
            context = {}
        res = {}

        if 'date' in context:
            date = context.get('date')
        else:
            date = time.strftime('%Y-%m-%d')
        date = date or time.strftime('%Y-%m-%d')

        for id in ids:
            cr.execute('SELECT rate_presupuesto FROM res_currency_rate '
                       'WHERE currency_id = %s '
                         'AND name::date <= %s '
                       'ORDER BY name desc LIMIT 1',
                       (id, date))
            if cr.rowcount:
                res[id] = cr.fetchone()[0]
            elif not raise_on_no_rate:
                res[id] = 0
            else:
                currency = self.browse(cr, uid, id, context=context)
                raise osv.except_osv(_('Error!'),_("No currency rate associated for currency %d for the given period" % (id)))
        return res

    #001 Arbitraje
    def _current_rate_arbitraje(self, cr, uid, ids, name, arg, context=None):

        raise_on_no_rate= False
        if context is None:
            context = {}
        res = {}

        if 'date' in context:
            date = context.get('date')
        else:
            date = time.strftime('%Y-%m-%d')
        date = date or time.strftime('%Y-%m-%d')

        for id in ids:
            cr.execute('SELECT rate_arbitraje FROM res_currency_rate '
                       'WHERE currency_id = %s '
                         'AND name::date <= %s '
                       'ORDER BY name desc LIMIT 1',
                       (id, date))
            if cr.rowcount:
                res[id] = cr.fetchone()[0]
            elif not raise_on_no_rate:
                res[id] = 0
            else:
                currency = self.browse(cr, uid, id, context=context)
                raise osv.except_osv(_('Error!'),_("No currency rate associated for currency %d for the given period" % (id)))
        return res
    #001 Fin arbitraje

    def _get_conversion_rate(self, cr, uid, from_currency, to_currency, context=None):
        if context is None:
            context = {}
        ctx = context.copy()
        from_currency = self.browse(cr, uid, from_currency.id, context=ctx)
        to_currency = self.browse(cr, uid, to_currency.id, context=ctx)

        pricelist_type = context.get('pricelist_type', False) or 'sale'  # pricelist_type default to 'sale' and use buying rate
        to_currency_rate = 0.0
        from_currency_rate = 0.0
        # kittiu: Buying rate
        if pricelist_type == 'sale':
            if from_currency.rate == 0 or to_currency.rate == 0:
                date = context.get('date', time.strftime('%Y-%m-%d'))
                if from_currency.rate == 0:
                    currency_symbol = from_currency.symbol
                else:
                    currency_symbol = to_currency.symbol
                raise osv.except_osv(_('Error'), _('No buying rate found \n' \
                        'for the currency: %s \n' \
                        'at the date: %s') % (currency_symbol, date))
            to_currency_rate = to_currency.rate
            from_currency_rate = from_currency.rate
        # kittiu: Selling rate
        if pricelist_type == 'purchase':
            if from_currency.rate_sell == 0 or to_currency.rate_sell == 0:
                date = context.get('date', time.strftime('%Y-%m-%d'))
                if from_currency.rate == 0:
                    currency_symbol = from_currency.symbol
                else:
                    currency_symbol = to_currency.symbol
                raise osv.except_osv(_('Error'), _('No selling rate found \n' \
                        'for the currency: %s \n' \
                        'at the date: %s') % (currency_symbol, date))
            to_currency_rate = to_currency.rate_sell
            from_currency_rate = from_currency.rate_sell
        if pricelist_type == 'presupuesto':
            if from_currency.rate_presupuesto == 0 or to_currency.rate_presupuesto == 0:
                date = context.get('date', time.strftime('%Y-%m-%d'))
                if from_currency.rate == 0:
                    currency_symbol = from_currency.symbol
                else:
                    currency_symbol = to_currency.symbol
                raise osv.except_osv(_('Error'), _(u'No se encontró tipo de cambio de presupuesto '
                                                   u'para la moneda: %s '
                                                   u'en la fecha: %s') % (currency_symbol, date))
            to_currency_rate = to_currency.rate_presupuesto
            from_currency_rate = from_currency.rate_presupuesto
        if pricelist_type == 'arbitraje':
            if from_currency.rate_arbitraje == 0 or to_currency.rate_arbitraje == 0:
                date = context.get('date', time.strftime('%Y-%m-%d'))
                if from_currency.rate == 0:
                    currency_symbol = from_currency.symbol
                else:
                    currency_symbol = to_currency.symbol
                raise osv.except_osv(_('Error'), _(u'No se encontró tipo de cambio de arbitraje '
                                                   u'para la moneda: %s '
                                                   u'en la fecha: %s') % (currency_symbol, date))
            to_currency_rate = to_currency.rate_arbitraje
            from_currency_rate = from_currency.rate_arbitraje
        # kittiu: check Smaller/Bigger currency
        to_rate = to_currency.type_ref_base == 'bigger' and (1 / to_currency_rate) or to_currency_rate
        from_rate = from_currency.type_ref_base == 'bigger' and (1 / from_currency_rate) or from_currency_rate
        return to_rate / from_rate

    _columns = {
        'rate_presupuesto': fields.function(_current_rate_presupuesto, string='Tipo cambio presupuesto', digits=(12, 6),
            help='El tipo de cambio para presupuesto.'),
        'rate_arbitraje': fields.function(_current_rate_arbitraje, string='Arbitraje', digits=(12, 6),
            help='El tipo de cambio arbitraje.'), #001 Arbitraje
    }
grp_calcular_arbitraje()


#!/usr/bin/env python3
# coding: utf-8

"""
Replace invalid characters from a filename
"""

import os
import argparse
from pathlib import Path
from utils import common

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("input", type=Path, help="Path to directory or single file")
    args = parser.parse_args()

    # Sanity check
    if args.input is None:
        common.abort(parser.format_help())

    # If path is a directory, get a list of files
    files = common.list_directory(args.input.resolve(), None, True)

    for f in files:
        a = str(f).encode('utf-8', "ignore")
        os.rename(str(f), a)


#!/usr/bin/env python3
import argparse

def get_args():
    parser = argparse.ArgumentParser(usage="%(prog)s\n\t./106bombyx n [k | i0 i1]")
    parser.add_argument("n", type=int, help="number of the first genration individuals")
    parser.add_argument("k", type=float, help="growth rate 1 to 4")
    parser.add_argument("i0", type=int, help="initial generation (included)")
    parser.add_argument("i1", type=int, help="final generation (included)")

    try:
        args = parser.parse_args(None, None)
    except SystemExit:
        exit(84)
    return args

def logistic_increment(x_prev, k):
    return k * x_prev * (1000 - x_prev) / 1000

def population(n, k, i0, i1):
    x1 = n
    x_next = x1
    res = []
    res.append([1, k, x1])

    for i in range(1, i1):
        x_next = logistic_increment(x_next, k)
        res.append([i + 1, k, x_next])
    return res[i0:i1 + 1]

def test_k(n, k, i0, i1):
    res = []
    while(k <= 4):
        res += population(n, k, i0, i1)
        k += 0.01
    return res

def with_rate(n, k):
    res = population(n, k, 0, 100)
    for elt in res:
        print(elt[0], elt[2])
    return

def with_borne(n, i0, i1):
    res = test_k(n, 1, i0, i1)
    for elt in res:
        print(elt[1], elt[2])
    return

args = get_args()
if (len(args) == 2):
    print("3")
if (len(args) == 3):
    print("4")

with_rate(10, 3.3)
# with_borne(10, 10000, 10010)


import sys
import numpy as np

def makeColorwheel():

	#  color encoding scheme

	#   adapted from the color circle idea described at
	#   http://members.shaw.ca/quadibloc/other/colint.htm

	RY = 15
	YG = 6
	GC = 4
	CB = 11
	BM = 13
	MR = 6

	ncols = RY + YG + GC + CB + BM + MR

	colorwheel = np.zeros([ncols, 3]) # r g b

	col = 0
	#RY
	colorwheel[0:RY, 0] = 255
	colorwheel[0:RY, 1] = np.floor(255*np.arange(0, RY, 1)/RY)
	col += RY

	#YG
	colorwheel[col:YG+col, 0]= 255 - np.floor(255*np.arange(0, YG, 1)/YG)
	colorwheel[col:YG+col, 1] = 255;
	col += YG;

	#GC
	colorwheel[col:GC+col, 1]= 255
	colorwheel[col:GC+col, 2] = np.floor(255*np.arange(0, GC, 1)/GC)
	col += GC;

	#CB
	colorwheel[col:CB+col, 1]= 255 - np.floor(255*np.arange(0, CB, 1)/CB)
	colorwheel[col:CB+col, 2] = 255
	col += CB;

	#BM
	colorwheel[col:BM+col, 2]= 255
	colorwheel[col:BM+col, 0] = np.floor(255*np.arange(0, BM, 1)/BM)
	col += BM;

	#MR
	colorwheel[col:MR+col, 2]= 255 - np.floor(255*np.arange(0, MR, 1)/MR)
	colorwheel[col:MR+col, 0] = 255
	return 	colorwheel

def computeColor(u, v):

	colorwheel = makeColorwheel();
	nan_u = np.isnan(u)
	nan_v = np.isnan(v)
	nan_u = np.where(nan_u)
	nan_v = np.where(nan_v)

	u[nan_u] = 0
	u[nan_v] = 0
	v[nan_u] = 0
	v[nan_v] = 0

	ncols = colorwheel.shape[0]
	radius = np.sqrt(u**2 + v**2)
	a = np.arctan2(-v, -u) / np.pi
	fk = (a+1) /2 * (ncols-1) # -1~1 maped to 1~ncols
	k0 = fk.astype(np.uint8)	 # 1, 2, ..., ncols
	k1 = k0+1;
	k1[k1 == ncols] = 0
	f = fk - k0

	img = np.empty([k1.shape[0], k1.shape[1],3])
	ncolors = colorwheel.shape[1]
	for i in range(ncolors):
		tmp = colorwheel[:,i]
		col0 = tmp[k0]/255
		col1 = tmp[k1]/255
		col = (1-f)*col0 + f*col1
		idx = radius <= 1
		col[idx] = 1 - radius[idx]*(1-col[idx]) # increase saturation with radius
		col[~idx] *= 0.75 # out of range
		img[:,:,2-i] = np.floor(255*col).astype(np.uint8)

	return img.astype(np.uint8)

def computeImg(flow):

	eps = sys.float_info.epsilon
	UNKNOWN_FLOW_THRESH = 1e9
	UNKNOWN_FLOW = 1e10

	u = flow[: , : , 0]
	v = flow[: , : , 1]

	maxu = -999
	maxv = -999

	minu = 999
	minv = 999

	maxrad = -1
	#fix unknown flow
	greater_u = np.where(u > UNKNOWN_FLOW_THRESH)
	greater_v = np.where(v > UNKNOWN_FLOW_THRESH)
	u[greater_u] = 0
	u[greater_v] = 0
	v[greater_u] = 0
	v[greater_v] = 0

	maxu = max([maxu, np.amax(u)])
	minu = min([minu, np.amin(u)])

	maxv = max([maxv, np.amax(v)])
	minv = min([minv, np.amin(v)])
	rad = np.sqrt(np.multiply(u,u)+np.multiply(v,v))
	maxrad = max([maxrad, np.amax(rad)])

	u = u/(maxrad+eps)
	v = v/(maxrad+eps)
	img = computeColor(u, v)
	return img


from decimal import Decimal
from dateutil.relativedelta import relativedelta

from trytond.model import ModelView, fields
from trytond.wizard import Wizard, StateView, StateReport, Button
from trytond.report import Report
from trytond.pool import Pool
from trytond.pyson import Eval, If
from trytond.transaction import Transaction

MAX_COLS = 24

class PrintCashFlowReportStart(ModelView):
    'Print Cash-Flow'
    __name__ = 'cooperative_ar.print_cashflow.start'

    company = fields.Many2One('company.company', 'Company', required=True)
    analytic_account = fields.Many2One('analytic_account.account',
        'Analytic Account', required=True,
        domain=[
            ('company', '=', Eval('company', -1)),
            ('type', '=', 'root'),
            ],
        depends=['company'])
    from_date = fields.Date('From Date', required=True,
        domain=[
            If(Eval('to_date') & Eval('from_date'),
                ('from_date', '<=', Eval('to_date')),
                ()),
            ],
        depends=['to_date'])
    to_date = fields.Date('To Date', required=True,
        domain=[
            If(Eval('from_date') & Eval('to_date'),
                ('to_date', '>=', Eval('from_date')),
                ()),
            ],
        depends=['from_date'])

    @classmethod
    def default_company(cls):
        return Transaction().context.get('company')

class PrintCashFlowReport(Wizard):
    'Print Cash-Flow'
    __name__ = 'cooperative_ar.print_cashflow'

    start = StateView('cooperative_ar.print_cashflow.start',
        'cooperative_cashflow_ar.print_cashflow_report_start_view', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Print', 'print_', 'tryton-print', True),
            ])
    print_ = StateReport('cooperative_ar.cashflow')

    def do_print_(self, action):
        data = {
            'company': self.start.company.id,
            'analytic_account': self.start.analytic_account.id,
            'from_date': self.start.from_date,
            'to_date': self.start.to_date,
            }
        return action, data

class CashFlowReport(Report):
    'Cash-Flow'
    __name__ = 'cooperative_ar.cashflow'

    @classmethod
    def get_context(cls, records, header, data):
        pool = Pool()
        Company = pool.get('company.company')

        report_context = super().get_context(records, header, data)

        report_context['company'] = Company(data['company'])
        report_context['from_date'] = data['from_date']
        report_context['to_date'] = data['to_date']

        columns = cls._get_date_columns(data['from_date'], data['to_date'])
        report_context['columns'] = [x['lbl']
            for x in columns.values()] + ['Total']
        if len(report_context['columns']) < MAX_COLS:
            for idx in range(MAX_COLS - len(report_context['columns'])):
                report_context['columns'].append('')

        # Sales
        sales_raw = cls._get_sale_records(data)
        report_context['sales_raw'] = sales_raw.values()

        sales_summary = cls._get_sale_summary(columns, sales_raw)
        report_context['sales_summary'] = sales_summary.values()

        # Expenses
        expenses_raw = cls._get_expense_records(data)
        report_context['expenses_raw'] = expenses_raw.values()

        expenses_summary = cls._get_expense_summary(columns, expenses_raw)
        report_context['expenses_summary'] = expenses_summary.values()

        # Cooperative Receipts
        receipts_raw = cls._get_receipt_records(data)
        report_context['receipts_raw'] = receipts_raw.values()

        receipts_summary = cls._get_receipt_summary(columns, receipts_raw)
        report_context['receipts_summary'] = receipts_summary.values()

        # Synthesis
        synthesis = cls._get_synthesis(columns,
            sales_summary, expenses_summary, receipts_summary)
        report_context['synthesis'] = synthesis.values()

        return report_context

    @classmethod
    def _get_date_columns(cls, from_date, to_date):
        res = {}
        date = from_date
        idx = 0
        while date < to_date and idx < MAX_COLS:
            year, month = date.year, date.month
            res[(year, month)] = {'idx': idx, 'lbl': '%s/%s' % (month, year)}
            date = date + relativedelta(months=1)
            idx += 1
        return res

    @classmethod
    def _get_sale_records(cls, data):
        pool = Pool()
        Company = pool.get('company.company')
        Currency = pool.get('currency.currency')
        SaleLine = pool.get('sale.line')
        AnalyticAccount = pool.get('analytic_account.account')

        records = {}
        company = Company(data['company'])

        clause = [
            ('sale.company', '=', data['company']),
            ('sale.state', 'in',
                ['projected', 'confirmed', 'processing', 'done']),
            ('type', '=', 'line'),
            ('manual_delivery_date', '>=', data['from_date']),
            ('manual_delivery_date', '<=', data['to_date']),
            ]
        sale_lines = SaleLine.search(clause,
            order=[('manual_delivery_date', 'ASC')])
        if not sale_lines:
            return records

        for line in sale_lines:
            year = line.manual_delivery_date.year
            month = line.manual_delivery_date.month
            category_id = None
            for analytic_line in line.analytic_accounts:
                if (analytic_line.root.id == data['analytic_account'] and
                        analytic_line.account):
                    category_id = analytic_line.account.id
            key = (year, month, category_id)
            if key not in records:
                records[key] = {
                    'year': year,
                    'month': month,
                    'category': (category_id and
                        AnalyticAccount(category_id).name or ''),
                    'amount': Decimal(0),
                    }
            with Transaction().set_context(date=line.manual_delivery_date):
                records[key]['amount'] += Currency.compute(
                    company.currency, line.amount, line.currency)
        return records

    @classmethod
    def _get_sale_summary(cls, columns, sales_raw):
        records = {}
        for key, line in sales_raw.items():
            category_id = key[2]
            if category_id not in records:
                records[category_id] = {
                    'category': line['category'],
                    'columns': dict((idx, None) for idx in range(MAX_COLS)),
                    'total': Decimal(0),
                    }
            date = key[:2]
            if date not in columns:
                continue
            records[category_id]['columns'][columns[date]['idx']] = line[
                'amount']
            records[category_id]['total'] += line['amount']

        total_idx = len(columns)
        for k, v in records.items():
            v['columns'][total_idx] = v['total']
        return records

    @classmethod
    def _get_purchase_records(cls):
        return []

    @classmethod
    def _get_expense_records(cls, data):
        pool = Pool()
        MoveLine = pool.get('account.move.line')
        AnalyticAccount = pool.get('analytic_account.account')

        records = {}

        clause = [
            ('move.company', '=', data['company']),
            ('account.cashflow_report', '=', True),
            ('move.state', '=', 'posted'),
            ('move.date', '>=', data['from_date']),
            ('move.date', '<=', data['to_date']),
            ]
        move_lines = MoveLine.search(clause,
            order=[('move.date', 'ASC')])
        if not move_lines:
            return records

        for line in move_lines:
            year = line.move.date.year
            month = line.move.date.month
            category_id = None
            for analytic_line in line.analytic_lines:
                if (analytic_line.account.root.id ==
                        data['analytic_account'] and
                        analytic_line.account):
                    category_id = analytic_line.account.id
            key = (year, month, category_id)
            if key not in records:
                records[key] = {
                    'year': year,
                    'month': month,
                    'category': (category_id and
                        AnalyticAccount(category_id).name or ''),
                    'amount': Decimal(0),
                    }
            with Transaction().set_context(date=line.move.date):
                records[key]['amount'] += abs(line.debit - line.credit)
        return records

    @classmethod
    def _get_expense_summary(cls, columns, expenses_raw):
        records = {}
        for key, line in expenses_raw.items():
            category_id = key[2]
            if category_id not in records:
                records[category_id] = {
                    'category': line['category'],
                    'columns': dict((idx, None) for idx in range(MAX_COLS)),
                    'total': Decimal(0),
                    }
            date = key[:2]
            if date not in columns:
                continue
            records[category_id]['columns'][columns[date]['idx']] = line[
                'amount']
            records[category_id]['total'] += line['amount']

        total_idx = len(columns)
        for k, v in records.items():
            v['columns'][total_idx] = v['total']
        return records

    @classmethod
    def _get_receipt_records(cls, data):
        pool = Pool()
        Company = pool.get('company.company')
        Currency = pool.get('currency.currency')
        Recibo = pool.get('cooperative.partner.recibo')
        AnalyticAccount = pool.get('analytic_account.account')

        records = {}
        company = Company(data['company'])

        clause = [
            ('company', '=', data['company']),
            ('state', 'in', ['projected', 'confirmed']),
            ('date', '>=', data['from_date']),
            ('date', '<=', data['to_date']),
            ]
        receipts = Recibo.search(clause,
            order=[('date', 'ASC')])
        if not receipts:
            return records

        for line in receipts:
            year = line.date.year
            month = line.date.month
            category_id = None
            #for analytic_line in line.analytic_accounts:
                #if (analytic_line.root.id == data['analytic_account'] and
                        #analytic_line.account):
                    #category_id = analytic_line.account.id
            key = (year, month, line.partner.id, category_id)
            if key not in records:
                records[key] = {
                    'year': year,
                    'month': month,
                    'partner': line.partner.rec_name,
                    'category': (category_id and
                        AnalyticAccount(category_id).name or ''),
                    'amount': Decimal(0),
                    }
            with Transaction().set_context(date=line.date):
                records[key]['amount'] += Currency.compute(
                    company.currency, line.amount, line.currency)
        return records

    @classmethod
    def _get_receipt_summary(cls, columns, receipts_raw):
        records = {}
        for key, line in receipts_raw.items():
            partner_id = key[2]
            if partner_id not in records:
                records[partner_id] = {
                    'partner': line['partner'],
                    'columns': dict((idx, None) for idx in range(MAX_COLS)),
                    'total': Decimal(0),
                    }
            date = key[:2]
            if date not in columns:
                continue
            records[partner_id]['columns'][columns[date]['idx']] = line[
                'amount']
            records[partner_id]['total'] += line['amount']

        total_idx = len(columns)
        for k, v in records.items():
            v['columns'][total_idx] = v['total']
        return records

    @classmethod
    def _get_synthesis(cls, columns,
            sales_summary, expenses_summary, receipts_summary):
        records = {}
        result_columns = dict((idx, None) for idx in range(MAX_COLS))

        # Sales
        records[1] = {
            'name': 'Ventas',
            'columns': dict((idx, None) for idx in range(MAX_COLS)),
            }
        for record in sales_summary.values():
            for idx, value in record['columns'].items():
                if value is None:
                    continue
                if records[1]['columns'][idx] is None:
                    records[1]['columns'][idx] = Decimal(0)
                records[1]['columns'][idx] += value
                if result_columns[idx] is None:
                    result_columns[idx] = Decimal(0)
                result_columns[idx] += value

        # Expenses
        records[2] = {
            'name': 'Gastos',
            'columns': dict((idx, None) for idx in range(MAX_COLS)),
            }
        for record in expenses_summary.values():
            for idx, value in record['columns'].items():
                if value is None:
                    continue
                if records[2]['columns'][idx] is None:
                    records[2]['columns'][idx] = Decimal(0)
                records[2]['columns'][idx] += value
                if result_columns[idx] is None:
                    result_columns[idx] = Decimal(0)
                result_columns[idx] -= value

        # Cooperative Receipts
        records[3] = {
            'name': 'Retiros',
            'columns': dict((idx, None) for idx in range(MAX_COLS)),
            }
        for record in receipts_summary.values():
            for idx, value in record['columns'].items():
                if value is None:
                    continue
                if records[3]['columns'][idx] is None:
                    records[3]['columns'][idx] = Decimal(0)
                records[3]['columns'][idx] += value
                if result_columns[idx] is None:
                    result_columns[idx] = Decimal(0)
                result_columns[idx] -= value

        # Result
        records[9] = {
            'name': 'Resultado',
            'columns': result_columns,
            }

        return records


from cmath import isnan
import boto3
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/ec2')
# ‘/’ URL is bound with hello_world() function.
def hello_world():

    ec2client = boto3.client(
        'ec2',
        aws_access_key_id='<access-key>',
        aws_secret_access_key='<secret-key>',
        region_name='us-west-2'
    )

    ec2detailsDict=dict()

    response = ec2client.describe_instances()

    for reservation in response["Reservations"]:
        for instance in reservation["Instances"]:
            print(instance)
            ec2detailsList=list()
            ec2detailsList.append(instance["InstanceId"])
            ec2detailsList.append(instance["PrivateIpAddress"])
            ec2detailsList.append(instance["Tags"])
            ec2detailsDict[instance["InstanceId"]]=[]
            ec2detailsDict[instance["InstanceId"]].extend(ec2detailsList)
    return jsonify(ec2detailsDict)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000)


from flask import Flask, render_template, request
from dotenv import load_dotenv
import os
import requests

load_dotenv()

app = Flask(__name__)

API_KEY = os.getenv("ETHERSCAN_API")

electricity_per_transaction = 8.4
kilowat_to_co2 = 0.85
co2_to_tree = 21

@app.route("/")
def home():
    return render_template("index.html")

@app.route("/calculate", methods=["POST"])
def calculate():
    my_address = request.form["public_key"]
    response = requests.get(
        f"https://api.etherscan.io/api?module=proxy&action=eth_getTransactionCount&address={my_address}&tag=latest&apikey={API_KEY}")
    raw_data = response.json()
    print(raw_data)
    tx = raw_data["result"]
    tx_count = float.fromhex(tx)
    print(tx_count)
    electricity_consumption = tx_count * electricity_per_transaction
    co2 = electricity_consumption * kilowat_to_co2
    formatted_co2 = "{:.2f}".format(co2)
    tree = co2 / co2_to_tree
    formatted_tree = "{:.2f}".format(tree)
    return render_template("result.html", formatted_co2=formatted_co2, formatted_tree=formatted_tree)

if __name__ == "__main__":
    app.run(debug=True)


from inputFiles import file_path as fp
from fastapi import APIRouter

# APIRouter creates path operations for item module
router = APIRouter(
    prefix="/AdventOfCode",
    tags=["Day 5"],
    responses={404: {"description": "Not found"}},
)

file = open(fp.file_path + 'day_05.txt', "r")
parts = file.read()[:-1].split('\n\n')

cratesStack = parts[0].split('\n')
moves = parts[1].split('\n')

# prepare stacks
numberOfStacks = int(cratesStack[len(cratesStack) - 1][-2])
maxHeightOfStack = len(cratesStack) - 1
stacks = [[] for _ in range(numberOfStacks)]
for i in range(maxHeightOfStack):
    line = cratesStack[i]
    crates = line[1::4]
    for s in range(len(crates)):
        if crates[s] != " ":
            stacks[s].append(crates[s])
stacks = [stack[::-1] for stack in stacks]

@router.get("/day5/part1")
async def Solve_Part_One():
    return [
        {"result": solvePart1()}
    ]

@router.get("/day5/part2")
async def Solve_Part_Two():
    return [
        {"result": solvePart2()}
    ]

def solvePart1():
    for move in moves:
        moveSplit = move.split(" ")
        number = int(moveSplit[1])
        stackFrom = int(moveSplit[3])
        stackTo = int(moveSplit[5])

        for n in range(number):
            elem = stacks[stackFrom - 1].pop()
            stacks[stackTo - 1].append(elem)
    res = [stack[-1] for stack in stacks]
    result = ""
    for stack in stacks:
        result += stack[-1]
    return result

def solvePart2():
    for move in moves:
        moveSplit = move.split(" ")
        number = int(moveSplit[1])
        stackFrom = int(moveSplit[3])
        stackTo = int(moveSplit[5])
        temp = []
        for n in range(number):
            temp.append(stacks[stackFrom - 1].pop())
        for x in temp[::-1]:
            stacks[stackTo - 1].append(x)
    result = ""
    for stack in stacks:
        result += stack[-1]

    return result


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Functions for creating matrices and accessing submatrices.
"""

import numpy
import theano

def random_normal_matrix(shape, scale=None):
    """Generates a random matrix from “standard normal” distribution.

    :type shape: tuple of ints
    :param shape: size of each dimension (typically there are two dimensions,
                  input and output)

    :type scale: float
    :param scale: if other than None, the random numbers will be scaled by this
                  factor

    :rtype: numpy.ndarray
    :returns: the generated weight matrix
    """

    result = numpy.random.randn(*shape)
    if scale is not None:
        result = scale * result
    return result.astype(theano.config.floatX)

def random_orthogonal_matrix(size):
    """Generates a random orthogonal matrix from “standard normal” distribution.

    :type size: int
    :param size: size of both dimensions of the weight

    :rtype: numpy.ndarray
    :returns: the generated weight matrix
    """

    nonorthogonal_matrix = numpy.random.randn(size, size)
    result, _, _ = numpy.linalg.svd(nonorthogonal_matrix)
    return result.astype(theano.config.floatX)

def random_matrix(shape, scale=None, count=1):
    """Generates a random matrix from “standard normal” distribution.

    If ``shape`` contains two dimensions that match, generates an orthogonal
    matrix. In that case scale is ignored.

    If ``count`` is specified, creates a concatenation of several similar
    matrices (same shape but different content).

    :type shape: tuple of ints
    :param shape: size of each dimension (typically there are two dimensions,
                  input and output)

    :type scale: float
    :param scale: if other than None, the random numbers will be scaled by this
                  factor

    :type count: int
    :param count: concatenate this many weight matrices with the same shape

    :rtype: numpy.ndarray
    :returns: the generated weight matrix
    """

    if (len(shape) == 2) and (shape[0] == shape[1]):
        return numpy.concatenate(
            [random_orthogonal_matrix(shape[0]) for _ in range(count)],
            axis=-1)
    else:
        return numpy.concatenate(
            [random_normal_matrix(shape, scale) for _ in range(count)],
            axis=-1)

def matrix_from_value(shape, value=None):
    """Creates a matrix with given value.

    If ``value`` is not given, initializes the vector with zero value. If
    ``value`` is a list, creates a concatenation of as many vectors as there are
    elements in the list.

    :type shape: int or tuple of ints
    :param shape: size of the vector, or a tuple of the sizes of each dimension
                  (in case ``value`` is a list, each part will have this size)

    :type value: float, numpy.ndarray or list
    :param value: the value or array to initialize the elements to, or a list of
                  values or arrays to create a concatenation of vectors
    """

    values = value if isinstance(value, (list, tuple)) else [value]
    parts = []
    for part_value in values:
        if part_value is None:
            part = numpy.zeros(shape).astype(theano.config.floatX)
        elif isinstance(value, numpy.ndarray):
            part = value.astype(theano.config.floatX)
        else:
            part = numpy.empty(shape).astype(theano.config.floatX)
            part.fill(part_value)
        parts.append(part)
    return numpy.concatenate(parts, axis=-1)

def get_submatrix(matrices, index, size, end_index=None):
    """Returns a submatrix of a concatenation of 2 or 3 dimensional
    matrices.

    :type matrices: Variable
    :param matrices: symbolic 2 or 3 dimensional matrix formed by
                     concatenating matrices of length size

    :type index: int
    :param index: index of the matrix to be returned

    :type size: Variable
    :param size: size of the last dimension of one submatrix

    :type end_index: int
    :param end_index: if set to other than None, returns a concatenation of all
                      the submatrices from ``index`` to ``end_index``
    """

    if end_index is None:
        end_index = index
    start = index * size
    end = (end_index + 1) * size
    if matrices.ndim == 3:
        return matrices[:, :, start:end]
    elif matrices.ndim == 2:
        return matrices[:, start:end]
    else:
        raise ValueError("get_submatrix() requires a 2 or 3 dimensional matrix.")


class Employe:
    tarif_horaire = 25
    #INITIALISATION
    def __init__(self, nom, heure_hebdo=38):
        if heure_hebdo < 1:
            raise ValueError("Erreur : nombre d'heure de travail hebdomadaire trop petit (>=1)")

        if heure_hebdo > 168:
            raise ValueError("Erreur : nombre d'heure de travail hebdomadaire trop grand (<=168)")
        self.nom = nom
        self.heure_hebdo = heure_hebdo

    #METHODES
    def get_salaire(self):
        salaire = self.heure_hebdo * Employe.tarif_horaire
        return "EMPLOYE || nom : {} | heure hebdomadaire : {} | salaire : {}".\
            format(self.nom, self.heure_hebdo, salaire)

    def __str__(self):
        return "{} de classe Employe est de type : {}".format(self.nom, type(self))

if __name__ == "__main__":

    liste = [
                Employe('Freddy'),
                Employe('Anna', 50)
    ]

    for employe in liste:
        print(employe.get_salaire())

    for employe in liste:
        print(employe)


# ----------------------------------------------------------
# Lab #5: Cryptarithmetic with CSP
# General cryptarithmetic puzzle solver.
#
# Date: 13-Oct-2023
# Authors:
#           A01747327 Jorge Rea
#           A01753911 Oswaldo Hernández
# ----------------------------------------------------------

from csp import Constraint, CSP
from typing import Dict, List, Optional

class CryptarithmeticConstraint(Constraint[str, int]):
    def __init__(self, unique_letters: List[str], words: List[str], answer: str, max_word_length: int) -> None:
        super().__init__(unique_letters)
        self.unique_letters: List[str] = unique_letters
        self.words: List[str] = words
        self.answer: str = answer
        self.max_word_length: int = max_word_length

    def satisfied(self, assignment: Dict[str, int]) -> bool:
        # Check for duplicate assignments
        if len(set(assignment.values())) < len(assignment):
            return False

        if len(assignment) != len(self.unique_letters):
            return True

        total_word_sum = 0
        for i in range(self.max_word_length):
            for word in self.words:
                if i < len(word):
                    index = len(word) - 1 - i
                    total_word_sum += assignment[word[index]] * 10 ** i

        total_answer_sum = 0
        for i in range(len(self.answer)):
            index = len(self.answer) - 1 - i
            total_answer_sum += assignment[self.answer[index]] * 10 ** i

        return total_word_sum == total_answer_sum

def solve_cryptarithmetic_puzzle(addends: List[str], answer: str) -> Optional[Dict[str, int]]:
    unique_letters = list(set("".join(addends + [answer])))
    unique_letters.sort()

    possible_digits = {letter: list(range(10)) for letter in unique_letters}

    csp = CSP(unique_letters, possible_digits)
    csp.add_constraint(CryptarithmeticConstraint(
        unique_letters, addends, answer, max(map(len, addends))))

    solution = csp.backtracking_search()

    if solution is None:
        return None
    else:
        upper_solution = {key.upper(): value for key,
                          value in solution.items()}
        return upper_solution

if __name__ == "__main__":
    print(solve_cryptarithmetic_puzzle(['SEND', 'MORE'], 'MONEY'))


from functools import reduce

# declaracio de funcions
def comptar(l):
   p = {}
   for x in l:
      p.setdefault(x, 0)
      p[x] += 1
   return p

def comptar2(l, k):
   p = {}
   for i in range(len(l)):
      p.setdefault(k[i], {})
      p[k[i]].setdefault(l[i], 0)
      p[k[i]][l[i]] += 1
   return p

def Pxik(atr, N, k):
   if atr in N[k]:
      return N[k][atr] / Nk[k]
   else:
      return Nk[k] / n ** 2

def classify(t):
   l = [(k , Nk[k] / n *
        reduce(lambda x, y: x * y,
               map(Pxik, t, Nxik,
                   [k for a in range(len(t))])))
        for k in Nk.keys()]
   return max(l, key=lambda x: x[1])[0]

# carrega de l'arxiu
l = list(map(lambda l: (l.strip()).split(','),
             open('mushroom.data.txt', 'r').readlines()))

# construccio del training: 2 de cada 3
train = list(map(lambda x: x[1],
                 filter(lambda v: v[0] % 3 != 0, enumerate(l))))
n = len(train)

# construccio del test: 1 de cada 3
test = list(map(lambda x: x[1],
                filter(lambda v: v[0] % 3 == 0, enumerate(l))))

# transposta del training
m = list(zip(*train))

# Numerador de P(k)
Nk = comptar(m[0])

# Numerador de P(xi|k)
Nxik = [ comptar2 (m[ i ] , m[ 0 ] ) for i in range (1 , len (m) ) ]

# Classificacio
classes = list(map(lambda x: x.pop(0), test))
prediccions = list(map(classify, test))

# Nombre de correctes
print('Prec.:', len(list(filter(lambda x: x[0] == x[1],
                                zip(*[prediccions, classes]))))
                / len(test) * 100, '%')


import sys
import socket

ipAddress = sys.argv[1]

for portas in range (1,65535):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    if s.connect_ex((ipAddress, portas)) == 0:
        print(f"Portas {portas} estão abertas")
        s.close()


# Imported libraries
import numpy as npy
import matplotlib.pyplot as plt
import tensorflow as tf
from tqdm import tqdm
import time as tm
import timeit as ti
from keras.models import Model
from tensorflow.keras.optimizers import Adam, SGD

# This class loads the CIFAR10 dataset to feed it to the GAN.
class dataset_load:
    ver = tf.__version__
    msg_0_0 = f"\nWorking with a Generative Adversarial Network Using TensorFlow and Keras version: {ver}\n"
    print(msg_0_0)
    tm.sleep(1)
    # Progress bar.
    for progress in tqdm(range(101), desc="Loading..", ascii=False, ncols=75):
        tm.sleep(0.01)

    print("\nStarting----->\n")
    tm.sleep(1)

    # Loads the CIFAR10 dataset
    (X, y), (_, _) = tf.keras.datasets.cifar10.load_data()

    X = X[y.flatten() == 8]

    # Loads, reads, and split the dataset.
    msg_0 = X.shape, y.shape, _.shape, _.shape

    # Input shape.
    image_shape = (32, 32, 3)
    latent_dims = 100

    # Dataset progress bar.
    for progress_2 in tqdm(range(101), desc="Loading Dataset", ascii=False, ncols=75):
        tm.sleep(0.01)

    msg_1 = f"\nCIFAR10 dataset--------------------------------------->>\n{msg_0}\n\n"
    print(msg_1)
    tm.sleep(1)

# This class houses the generator conv network.
class build_generator:
    generator_net = tf.keras.Sequential()

    generator_net.add(tf.keras.layers.Dense(128 * 8 * 8, activation='relu', input_dim=dataset_load.latent_dims))
    generator_net.add(tf.keras.layers.Reshape((8, 8, 128)))
    generator_net.add(tf.keras.layers.UpSampling2D())

    generator_net.add(tf.keras.layers.Conv2D(128, kernel_size=3, padding="same"))
    generator_net.add(tf.keras.layers.BatchNormalization(momentum=0.78))
    generator_net.add(tf.keras.layers.Activation("relu"))
    generator_net.add(tf.keras.layers.UpSampling2D())

    generator_net.add(tf.keras.layers.Conv2D(64, kernel_size=3, padding="same"))
    generator_net.add(tf.keras.layers.BatchNormalization(momentum=0.78))
    generator_net.add(tf.keras.layers.Activation("relu"))

    generator_net.add(tf.keras.layers.Conv2D(3, kernel_size=3, padding="same"))
    generator_net.add(tf.keras.layers.Activation("tanh"))

    noise = tf.keras.Input(shape=(dataset_load.latent_dims,))
    image = generator_net(noise)

    generator_net.summary()

    sent1 = Model(noise, image)

# This class houses the discriminator network.
class build_discriminator:
    discriminator_net = tf.keras.Sequential()

    discriminator_net.add(tf.keras.layers.Conv2D(32, kernel_size=3, strides=2, input_shape=dataset_load.image_shape,
                                                 padding="same"))
    discriminator_net.add(tf.keras.layers.LeakyReLU(alpha=0.2))
    discriminator_net.add(tf.keras.layers.Dropout(0.25))

    discriminator_net.add(tf.keras.layers.Conv2D(64, kernel_size=3, strides=2, padding="same"))
    discriminator_net.add(tf.keras.layers.ZeroPadding2D(padding=((0, 1), (0, 1))))
    discriminator_net.add(tf.keras.layers.BatchNormalization(momentum=0.82))
    discriminator_net.add(tf.keras.layers.LeakyReLU(alpha=0.2))
    discriminator_net.add(tf.keras.layers.Dropout(0.25))

    discriminator_net.add(tf.keras.layers.Conv2D(128, kernel_size=3, strides=2, padding="same"))
    discriminator_net.add(tf.keras.layers.BatchNormalization(momentum=0.82))
    discriminator_net.add(tf.keras.layers.LeakyReLU(alpha=0.2))
    discriminator_net.add(tf.keras.layers.Dropout(0.25))

    discriminator_net.add(tf.keras.layers.Conv2D(256, kernel_size=3, strides=1, padding="same"))
    discriminator_net.add(tf.keras.layers.BatchNormalization(momentum=0.8))
    discriminator_net.add(tf.keras.layers.LeakyReLU(alpha=0.25))
    discriminator_net.add(tf.keras.layers.Dropout(0.25))

    discriminator_net.add(tf.keras.layers.Flatten())
    discriminator_net.add(tf.keras.layers.Dense(1, activation='sigmoid'))

    image = tf.keras.Input(shape=dataset_load.image_shape)
    validity = discriminator_net(image)

    discriminator_net.summary()

    sent2 = Model(image, validity)

# this function displays the generated images.
# every 2500 epochs.
def image_plotter():
    r, c = 4, 4

    noise = npy.random.normal(0, 1, (r * c, dataset_load.latent_dims))
    generated_image = GAN.generator.predict(noise)

    generated_image = 0.5 * generated_image + 0.5

    fig, axs = plt.subplots(r, c)
    count = 0

    for i in range(r):
        for j in range(c):
            axs[i, j].imshow(generated_image[count])
            axs[i, j].axis('off')
            count += 1

    plt.show()
    plt.close()

# This class builds the GAN by combining the networks.
class GAN:
    discriminator = build_discriminator.discriminator_net

    discriminator.compile(loss='binary_crossentropy', optimizer=Adam(0.0002, 0.5),
                          metrics=['Accuracy'])

    build_discriminator.discriminator_net.trainable = False

    generator = build_generator.generator_net
    z = tf.keras.Input(shape=(dataset_load.latent_dims,))
    image = generator(z)

    validity = build_discriminator.discriminator_net(image)

    combined_network = Model(z, validity)
    combined_network.compile(loss='binary_crossentropy', optimizer=Adam(0.0002, 0.5))

# this class starts the training process on the generator and the discriminator.
class Net_training:
    num_epochs = 15000
    batch_size = 32
    display_interval = 2500
    losses = []

    X = (dataset_load.X / 127.5) - 1

    valid = npy.ones((batch_size, 1))

    valid += 0.05 * npy.random.random(valid.shape)

    fake = npy.zeros((batch_size, 1))
    fake += 0.05 * npy.random.random(fake.shape)

    for epoch in range(num_epochs):
        index = npy.random.randint(0, X.shape[0], batch_size)
        images = X[index]

        noise = npy.random.normal(0, 1, (batch_size, dataset_load.latent_dims))

        generated_images = GAN.generator.predict(noise)

        discm_loss_real = GAN.discriminator.train_on_batch(images, valid)
        discm_loss_fake = GAN.discriminator.train_on_batch(generated_images, fake)
        discm_loss = 0.5 * npy.add(discm_loss_real, discm_loss_fake)

        genr_loss = GAN.combined_network.train_on_batch(noise, valid)

        if epoch % display_interval == 0:
            image_plotter()

        # displays the respective number of losses per epochs.
        tqdm.write(f"\nEpoch: {epoch} | \nGAN Loss: {genr_loss} "
                   f"| \nReal Loss: {discm_loss_real} | \nFake Loss: {discm_loss_fake}\n")

    # plots the images from the last epoch.
    noise = npy.random.normal(size=(40, dataset_load.latent_dims))

    generated_images = GAN.generator.predict(noise)
    generated_images = 0.5 * generated_images + 0.5

    f, ax = plt.subplots(5, 8, figsize=(16, 10))
    for img_data_2, image in enumerate(generated_images):
        ax[img_data_2 // 8, img_data_2 % 8].imshow(image)
        ax[img_data_2 // 8, img_data_2 % 8].axis('off')

    plt.show()
    plt.savefig(f"Image generates from the last epoch.jpg")
    plt.close()

# runtime evaluation
class model_eval:
    runtime_duration = ti.timeit(build_generator, number=1)
    runtime_duration_2 = ti.timeit(build_discriminator, number=2)
    GAN_Runtime = {'Generator_runtime': f"\nGenerator: {runtime_duration}",
                   'Discriminator_runtime': f"\nDiscriminator: {runtime_duration_2}"}

    print(GAN_Runtime['Generator_runtime'] + GAN_Runtime['Discriminator_runtime'])

if __name__ == "__main__":
    dataset_load()
    model_eval()

Applying Machine Learning and Neural Networks/Generative Adversarial Network/GAN_V1.py


#default function
def sum(a, b):
    result = a + b
    return result

a = sum(3, 4)
print(a)

print("\n")

#Functions without input values
def say():
    return 'Hi'

a = say()
print(a)

print("\n")

#Functions without result values
def sum(a, b):
    print("%d, %d의 합은 %d입니다." %(a, b, a+b))

sum(3, 4)       #3, 4의 합은 7입니다.

print("\n")

a = sum(3, 4)   #3, 4의 합은 7입니다.

print("\n")

print(a)        #None

print("\n")

#Functions without input and output
def say():
    print('Hi')

say()

print("\n")

#Create a function that accepts multiple input values
def sum_many(*args):
        sum = 0
        for i in args:
            sum = sum + i
        return sum

result = sum_many(1, 2, 3)
print(result)
result = sum_many(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print(result)

print("\n")

def sum_mul(choice, *args):
    if choice =="sum":
        result = 0
        for i in args:
            result = result + i
    elif choice == "mul":
        result = 1
        for i in args:
            result = result * i
    return result

result = sum_mul('sum', 1, 2, 3, 4, 5)
print(result)
result = sum_mul('mul', 1, 2, 3, 4, 5)
print(result)

print("\n")

#kwargs
def func(**kwargs):
    print(kwargs)

func(a=1)
func(name="HDW", age="20")

print("\n")

def func(*args, **kwargs):
    print(kwargs)
    print(args)

func(1, 2, 3, name="HDW", age=20)

print("\n")

def nick_n(nick):
     if nick == "바보":
         return                         #return을 만나면 빠져나간다.
     print("나의 별명은 %s 입니다." %nick)

nick_n("HHH")
nick_n("바보")

print("\n")

def me(name, old, man=0):               #입력 인수에 초깃값 미리 설정하기
    print("My anme is %s" %name)
    print("I am %d years old" %old)
    if man:
        print("I am a man")
    else:
        print("I am a women")

me("HDW", 20)

print("\n")

#함수안에서 선언된 변수의 범위
a = 1
def range(a):
    a = a + 1

range(a)                                #함수안에서 선언된 변수는 함수 안에서만 사용된다.
print(a)

#함수 안에서 밖의 함수를 변경하는 방법
a = 1
def in_out(a):
    a = a + 1
    return a                            #return

a = in_out(a)
print(a)

a = 1
def in_out():
    global a                            #global
    a = a + 1

in_out()
print(a)


import numpy as np
import scipy.io as sio
import torch
from sklearn import preprocessing

def weights_init(m):
    classname = m.__class__.__name__
    if classname.find('Linear') != -1:
        m.weight.data.normal_(0.0, 0.02)
        m.bias.data.fill_(0)
    elif classname.find('BatchNorm') != -1:
        m.weight.data.normal_(1.0, 0.02)
        m.bias.data.fill_(0)

def map_label(label, classes):
    mapped_label = torch.LongTensor(label.size())
    for i in range(classes.size(0)):
        mapped_label[label==classes[i]] = i
    return mapped_label
class Logger(object):
    def __init__(self, filename):
        self.filename = filename
        f = open(self.filename+'.log', "a")
        f.close()

    def write(self, message):
        f = open(self.filename+'.log', "a")
        f.write(message)
        f.close()

class DATA_LOADER(object):
    def __init__(self, opt):
        if opt.matdataset:
            if opt.dataset == 'imageNet1K':
                self.read_matimagenet(opt)
            else:
                self.read_matdataset(opt)
        self.index_in_epoch = 0
        self.epochs_completed = 0

    def read_matdataset(self, opt):
        matcontent = sio.loadmat(opt.dataroot + "/" + opt.dataset + "/" + opt.image_embedding + ".mat")
        feature = matcontent['features'].T
        label = matcontent['labels'].astype(int).squeeze() - 1
        matcontent = sio.loadmat(opt.dataroot + "/" + opt.dataset + "/" + opt.class_embedding + "_splits.mat")
        # numpy array index starts from 0, matlab starts from 1
        trainval_loc = matcontent['trainval_loc'].squeeze() - 1
        # train_loc = matcontent['train_loc'].squeeze() - 1
        # val_unseen_loc = matcontent['val_loc'].squeeze() - 1
        test_seen_loc = matcontent['test_seen_loc'].squeeze() - 1
        test_unseen_loc = matcontent['test_unseen_loc'].squeeze() - 1
        self.attribute = torch.from_numpy(matcontent['att'].T).float()

        if not opt.validation:
            if opt.preprocessing:
                if opt.standardization:
                    print('standardization...')
                    scaler = preprocessing.StandardScaler()
                else:
                    scaler = preprocessing.MinMaxScaler()

                _train_feature = scaler.fit_transform(feature[trainval_loc])
                _test_seen_feature = scaler.transform(feature[test_seen_loc])
                _test_unseen_feature = scaler.transform(feature[test_unseen_loc])
                self.train_feature = torch.from_numpy(_train_feature).float()
                mx = self.train_feature.max()
                self.train_feature.mul_(1/mx)
                self.train_label = torch.from_numpy(label[trainval_loc]).long()
                self.test_unseen_feature = torch.from_numpy(_test_unseen_feature).float()
                self.test_unseen_feature.mul_(1/mx)
                self.test_unseen_label = torch.from_numpy(label[test_unseen_loc]).long()
                self.test_seen_feature = torch.from_numpy(_test_seen_feature).float()
                self.test_seen_feature.mul_(1/mx)
                self.test_seen_label = torch.from_numpy(label[test_seen_loc]).long()
            else:
                self.train_feature = torch.from_numpy(feature[trainval_loc]).float()
                self.train_label = torch.from_numpy(label[trainval_loc]).long()
                self.test_unseen_feature = torch.from_numpy(feature[test_unseen_loc]).float()
                self.test_unseen_label = torch.from_numpy(label[test_unseen_loc]).long()
                self.test_seen_feature = torch.from_numpy(feature[test_seen_loc]).float()
                self.test_seen_label = torch.from_numpy(label[test_seen_loc]).long()
        else:
            self.train_feature = torch.from_numpy(feature[train_loc]).float()
            self.train_label = torch.from_numpy(label[train_loc]).long()
            self.test_unseen_feature = torch.from_numpy(feature[val_unseen_loc]).float()
            self.test_unseen_label = torch.from_numpy(label[val_unseen_loc]).long()

        self.seenclasses = torch.from_numpy(np.unique(self.train_label.numpy()))
        self.unseenclasses = torch.from_numpy(np.unique(self.test_unseen_label.numpy()))
        self.ntrain = self.train_feature.size()[0]
        self.ntrain_class = self.seenclasses.size(0)
        self.ntest_class = self.unseenclasses.size(0)
        self.train_class = self.seenclasses.clone()
        self.allclasses = torch.arange(0, self.ntrain_class+self.ntest_class).long()

        self.train_mapped_label = map_label(self.train_label, self.seenclasses)

    def next_batch_one_class(self, batch_size):
        if self.index_in_epoch == self.ntrain_class:
            self.index_in_epoch = 0
            perm = torch.randperm(self.ntrain_class)
            self.train_class[perm] = self.train_class[perm]

        iclass = self.train_class[self.index_in_epoch]
        idx = self.train_label.eq(iclass).nonzero().squeeze()
        perm = torch.randperm(idx.size(0))
        idx = idx[perm]
        iclass_feature = self.train_feature[idx]
        iclass_label = self.train_label[idx]
        self.index_in_epoch += 1
        return iclass_feature[0:batch_size], iclass_label[0:batch_size], self.attribute[iclass_label[0:batch_size]]

    def next_batch(self, batch_size):
        idx = torch.randperm(self.ntrain)[0:batch_size]
        batch_feature = self.train_feature[idx]
        batch_label = self.train_label[idx]
        return batch_feature, batch_label
    # select batch samples by randomly drawing batch_size classes
    def next_batch_uniform_class(self, batch_size):
        batch_class = torch.LongTensor(batch_size)
        for i in range(batch_size):
            idx = torch.randperm(self.ntrain_class)[0]
            batch_class[i] = self.train_class[idx]

        batch_feature = torch.FloatTensor(batch_size, self.train_feature.size(1))
        batch_label = torch.LongTensor(batch_size)
        batch_att = torch.FloatTensor(batch_size, self.attribute.size(1))
        for i in range(batch_size):
            iclass = batch_class[i]
            idx_iclass = self.train_label.eq(iclass).nonzero().squeeze()
            idx_in_iclass = torch.randperm(idx_iclass.size(0))[0]
            idx_file = idx_iclass[idx_in_iclass]
            batch_feature[i] = self.train_feature[idx_file]
            batch_label[i] = self.train_label[idx_file]
            batch_att[i] = self.attribute[batch_label[i]]
        return batch_feature, batch_label, batch_att


from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('doors/', views.DoorListView.as_view(), name='doors'),
    path('doors/requests/', views.RequestListView.as_view(), name='requested-doors'),

    path('doors/request/<int:pk>/update/<str:status>/', views.RequestUpdate.as_view(), name='request-update'),

    path('door/<int:pk>', views.DoorDetailView.as_view(), name='door-detail'),
    path('door/<int:pk>/request/', views.RequestDoorView.as_view(), name='door-request'),
    path('users/', views.UserListView.as_view(), name='users'),

    path('user/<int:pk>', views.UserDetailView.as_view(), name='user-detail'),
]


from __future__ import (absolute_import, print_function, unicode_literals)

import errno
import logging
import os
import os.path
import select
import socket
import threading

import conveyor.log
import conveyor.stoppable

class Connection(conveyor.stoppable.StoppableInterface):
    """ Base class for all conveyor connection objects """

    def __init__(self):
        conveyor.stoppable.StoppableInterface.__init__(self)
        self._log = conveyor.log.getlogger(self)

    def read(self):
        "Template read function, not implemented."
        raise NotImplementedError

    def write(self, data):
        "Template write function, not implemented."
        raise NotImplementedError

    def close(self):
        raise NotImplementedError

class ConnectionWriteException(Exception):
    """ Default connection exception class."""
    pass

class _AbstractSocketConnection(Connection):
    """ Base Socket Connection class. Contains tools to
    read/write from generic json sockets. """

    def __init__(self, socket, address):
        """
        @param socket a socket object
        @param address
        """
        Connection.__init__(self)
        self._condition = threading.Condition()
        self._stopped = False
        self._socket = socket
        self._address = address

    def getaddress(self):
        return self._address

    def stop(self):
        """ Sets stop flag to true, which will case the  write loop. """
        self._stopped = True
        # ^ threading.Condition lock unneeded, boolean write is atomic

    def write(self, data):
        """ writes data over a socket. Loops until either .stop() is set or
        data has been sent successfully. Exceptions for flow are handled in
        this functions, others are throw upwards.
        @param data The data you want to send
        """
        with self._condition:
            i = 0
            while not self._stopped and i < len(data):
                try:
                    sent = self._socket.send(data[i:])
                except IOError as e:
                    if e.args[0] in (errno.EINTR, errno.EAGAIN, errno.EWOULDBLOCK):
                        # NOTE: debug too spammy
                        # self._log.debug('handled exception', exc_info=True)
                        continue
                    elif e.args[0] in (errno.EBADF, errno.EPIPE):
                        self._log.debug('handled exception', exc_info=True)
                        if self._stopped:
                            break
                        else:
                            raise ConnectionWriteException
                    else:
                        raise
                else:
                    i += sent

    def close(self):
        self._socket.close()

if 'nt' != os.name:
# TRICKY: Due to windows issues installing pywintypes, we wrote our own
# lower level socket classes. This is the posix section of those

    class _PosixSocketConnection(_AbstractSocketConnection):
        """ A Posix socket connection.
        Major functionality is via 'read','write','stop'.
        """
        def stop(self):
            _AbstractSocketConnection.stop(self)
            # NOTE: use SHUT_RD instead of SHUT_RDWR or you will get annoying
            # 'Connection reset by peer' errors.
            try:
                self._socket.shutdown(socket.SHUT_RD)
                self._socket.close()
            except IOError as e:
                # NOTE: the Python socket implementation throws EBADF when you
                # invoke methods on a closed socket.
                if errno.EBADF != e.args[0]:
                    raise
                else:
                    self._log.debug('handled exception', exc_info=True)

        def read(self):
            while True:
                if self._stopped:
                    return ''
                else:
                    try:
                        data = self._socket.recv(4096)
                    except IOError as e:
                        if e.args[0] in (errno.EINTR, errno.EAGAIN, errno.EWOULDBLOCK):
                            # NOTE: too spammy
                            # self._log.debug('handled exception', exc_info=True)
                            continue
                        elif errno.ECONNRESET == e.args[0]:
                            self._log.debug('handled exception', exc_info=True)
                            return ''
                        else:
                            raise
                    else:
                        return data
    # Custom posix classes as 'PipeConnection' and 'SocketConnection
    PipeConnection = _PosixSocketConnection
    SocketConnection = _PosixSocketConnection

else: # case for os == 'nt' (ie, windows machines')
# TRICKY: Due to windows issues installing pywintypes, we wrote our own
# ctypes based based socket class.
    import ctypes
    import ctypes.wintypes
    import conveyor.platform.win32 as win32

    # The size of the read buffer.
    _SIZE = 4096

    # The read polling timeout.
    _TIMEOUT = 1000

    class _Win32PipeConnection(Connection):

        @staticmethod
        def create(handle):
            buffer = ctypes.create_string_buffer(_SIZE)
            overlapped_read = _Win32PipeConnection.createoverlapped()
            overlapped_write = _Win32PipeConnection.createoverlapped()
            connection = conveyor.connection.PipeConnection(
                handle, buffer, overlapped_read, overlapped_write)
            return connection

        @staticmethod
        def createoverlapped():
            overlapped = win32.OVERLAPPED()
            overlapped.hEvent = win32.CreateEventW(None, False, False, None)
            return overlapped

        def __init__(self, handle, buffer, overlapped_read, overlapped_write):
            Connection.__init__(self)
            self._condition = threading.Condition()
            self._stopped = False
            self._handle = handle
            self._buffer = buffer
            self._overlapped_read = overlapped_read
            self._overlapped_write = overlapped_write

        def stop(self):
            self._stopped = True

        def read(self):
            count = ctypes.wintypes.DWORD()
            result = win32.ReadFile(
                self._handle, self._buffer, _SIZE, ctypes.byref(count),
                ctypes.byref(self._overlapped_read))
            if result:
                s = str(self._buffer[:count.value])
                return s
            else:
                error = win32.GetLastError()
                if win32.ERROR_BROKEN_PIPE == error:
                    return ''
                elif win32.ERROR_MORE_DATA == error:
                    s = str(self._buffer[:count.value])
                    return s
                elif win32.ERROR_IO_PENDING == error:
                    s = self._read_pending(count)
                    return s
                else:
                    raise win32.create_WindowsError(error)

        def _read_pending(self, count):
            while True:
                if self._stopped:
                    return ''
                else:
                    result = win32.WaitForSingleObject(
                        self._overlapped_read.hEvent, _TIMEOUT)
                    if win32.WAIT_TIMEOUT == result:
                        continue
                    elif win32.WAIT_OBJECT_0 == result:
                        result = win32.GetOverlappedResult(
                            self._handle, ctypes.byref(self._overlapped_read),
                            ctypes.byref(count), True)
                        if result:
                            s = str(self._buffer[:count.value])
                            return s
                        else:
                            error = win32.GetLastError()
                            if win32.ERROR_BROKEN_PIPE == error:
                                return ''
                            elif win32.ERROR_MORE_DATA == error:
                                s = str(self._buffer[:count.value])
                                return s
                            else:
                                raise win32.create_WindowsError(error)
                    else:
                        raise ValueError(result)

        def write(self, data):
            """ writes data over a socket. Loops until either .stop() is set or
            data has been sent successfully. Exceptions for flow are handled in
            this functions, others are throw upwards.
            @param data The data you want to send
            """
            with self._condition:
                s = str(data)
                result = win32.WriteFile(
                    self._handle, s, len(s), None, self._overlapped_write)
                if not result:
                    error = win32.GetLastError()
                    if win32.ERROR_BROKEN_PIPE == error:
                        raise ConnectionWriteException
                    elif win32.ERROR_IO_PENDING == error:
                        count = ctypes.wintypes.DWORD()
                        result = win32.GetOverlappedResult(
                            self._handle, ctypes.byref(self._overlapped_write),
                            ctypes.byref(count), True)
                        if not result:
                            error = win32.GetLastError()
                            if win32.ERROR_BROKEN_PIPE == error:
                                raise ConnectionWriteException
                            else:
                                raise win32.create_WindowsError(error)
                    else:
                        raise win32.create_WindowsError(error)

    class _Win32SocketConnection(_AbstractSocketConnection):
        def read(self):
            while True:
                if self._stopped:
                    return ''
                else:
                    rlist, wlist, xlist = select.select([self._socket], [], [], 1.0)
                    if 0 != len(rlist):
                        try:
                            data = self._socket.recv(4096)
                        except IOError as e:
                            if errno.EINTR != e.args[0] and not self._stopped:
                                raise
                            else:
                                # NOTE: too spammy
                                # self._log.debug('handled exception', exc_info=True)
                                continue
                        else:
                            return data

    # use custom windowns socket classes as 'PipeConnection' and 'SocketConnection
    PipeConnection = _Win32PipeConnection
    SocketConnection = _Win32SocketConnection