Thursday, February 07, 2019

Classification and List of Patterns

Creational Patterns


  •  Abstract factory: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
  •  Builder: Separate the construction of a complex object from its representation allowing the same construc- tion process to create various representations.
  •  Factory method: Define an interface for creating an object, but let subclasses decide which class to instanti- ate. Factory Method lets a class defer instantiation to subclasses.
  •  Lazy initialization: Tactic of delaying the creation of an object, the calculation of a value, or some other ex- pensive process until the first time it is needed.
  •  Multiton: Ensure a class has only named instances, and provide global point of access to them.
  •  Object pool: Avoid expensive acquisition and release of resources by recycling objects that are no longer in use. Can be considered a generalization of connection pool and thread pool patterns.
  •  Prototype: Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
  •  Resource acquisition is initialization: Ensure that resources are properly released by tying them to the life-span of suitable objects.
  •  Singleton: Ensure a class has only one instance, and provide a global point of access to it.


Structural Patterns

  •  Adapter or Wrapper: Convert the interface of a class into another interface clients expect. Adapter lets classes work together that could not otherwise because of incompatible interfaces.
  •  Bridge: Decouple an abstraction from its implementation allowing the two to vary independently.
  •  Composite: Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
  •  Decorator: Attach additional responsibilities to an object dynamically keeping the same interface. Decorators provide a flexible alternative to subclassing for extending functionality.
  •  Facade: Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
  •  Front Controller: Provide a unified interface to a set of interfaces in a subsystem. Front Controller defines a higher-level interface that makes the subsystem easier to use.
  •  Flyweight: Use sharing to support large numbers of fine-grained objects efficiently.
  •  Proxy: Provide a surrogate or placeholder for another object to control access to it. 
Behavioral Patterns
  •  Blackboard: Generalized observer, which allows multiple readers and writers. Communicates information system-wide.
  •  Chain of responsibility: Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
  •  Command: Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
  •  Interpreter: Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
  •  Iterator: Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
  •  Mediator: Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
  •  Memento: Without violating encapsulation, capture and externalize an object’s internal state allowing theobject to be restored to this state later.
  •  Null object: Avoid null references by providing a default object.
  •  Observer or Publish/subscribe: Define a one-to-many dependency between objects where a state change in one object results with all its dependents being notified and updated automatically.
  •  Servant: Define common functionality for a group of classes.
  •  Specification: Recombinable business logic in a Boolean fashion.
  •  State: Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
  •  Strategy: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
  •  Template method: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
  • Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
  •  Visitor: Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
Concurrency Patterns

  •  Active Object: Decouples method execution from method invocation that reside in their own thread of con- trol. The goal is to introduce concurrency, by using asynchronous method invocation and a scheduler for handling requests.
  •  Balking: Only execute an action on an object when the object is in a particular state.
  •  Binding Properties: Combining multiple observers to force properties in different objects to be synchronized or coordinated in some way.
  •  Messaging pattern: The messaging design pattern (MDP) allows the interchange of information (i.e. messages) between components and applications.
  •  Double-checked locking: Reduce the overhead of acquiring a lock by first testing the locking criterion (the “lock hint”) in an unsafe manner; only if that succeeds does the actual lock proceed. Can be unsafe when implemented in some language/hardware combinations. It can therefore sometimes be considered an anti-pat- tern.
  •  Event-based asynchronous: Addresses problems with the Asynchronous pattern that occur in multithreaded programs.
  •  Guarded suspension: Manages operations that require both a lock to be acquired and a precondition to be satisfied before the operation can be executed.
  •  Lock: One thread puts a “lock” on a resource, preventing other threads from accessing or modifying it.
  •  Monitor object: An object whose methods are subject to mutual exclusion, thus preventing multiple objects from erroneously trying to use it at the same time.
  •  Reactor: A reactor object provides an asynchronous interface to resources that must be handled synchronously.
  •  Read-write lock: Allows concurrent read access to an object but requires exclusive access for write operations.
  •  Scheduler: Explicitly control when threads may execute single-threaded code.
  •  Thread pool: A number of threads are created to perform a number of tasks, which are usually organized in a queue. Typically, there are many more tasks than threads. Can be considered a special case of the object pool pattern.
  •  Thread-specific storage: Static or “global” memory local to a thread.

Data Access Patterns

  •  ORM Patterns: Domain Object Factory, Object/Relational Map, Update Factory.
  •  Resource Management Patterns: Resource Pool, Resource Timer, Retryer, Paging Iterator.
  •  Cache Patterns: Cache Accessor, Demand Cache, Primed Cache, Cache Collector, Cache Replicator.

Enterprise Patterns

  •  Presentation Tier Patterns: Intercepting Filter, Front Controller, View Helper, Composite View, Service to Worker, Dispatcher View.
  •  Business Tier Patterns: Business Delegate, Value Object, Session Facade, Composite Entity, Value Object Assembler, Value List Handler, Service Locator.
  •  Integration Tier Patterns: Data Access Object, Service Activator.

Real-Time Patterns

  •  Architecture Patterns: Layered Pattern, Channel Architecture Pattern, Component-Based Architecture, Recursive Containment Pattern and Hierarchical Control Pattern, Microkernel Architecture Pattern, Virtual Machine Pattern.
  •  Concurrency Patterns: Message Queuing Pattern, Interrupt Pattern, Guarded Call Pattern, Rendezvous Pattern, Cyclic Executive Pattern, Round Robin Pattern.
  •  Memory Patterns: Static Allocation Pattern, Pool Allocation Pattern, Fixed Sized Buffer Pattern, Smart Pointer Pattern, Garbage Collection Pattern, Garbage Compactor Pattern.
  •  Resource Patterns: Critical Section Pattern, Priority Inheritance Pattern, Priority Ceiling Pattern, Simultaneous Locking Pattern, Ordered Locking Pattern.
  •  Distribution Patterns: Shared Memory Pattern, Remote Method Call Pattern, Observer Pattern, Data Bus Pattern, Proxy Pattern, Broker Pattern.
  •  Safety and Reliability Patterns: Monitor-Actuator Pattern, Sanity Check Pattern, Watchdog Pattern, Safety Executive Pattern, Protected Single Channel Pattern, Homogeneous Redundancy Pattern, Triple Modular Redundancy Pattern, Heterogeneous Redundancy Pattern.

Some key figures that have influenced thinking about research


  • Plato (427–347 BC) and Aristotle (348–322 BC) – these represent the two contrasting approaches to acquiring knowledge and understanding the world (epistemology). Plato argued for deductive thinking (starting with theory to make sense of what we observe) and Aristotle for the opposite, inductive thinking (starting with observations in order to build theories).
  • René Descartes (1596–1650) – provided the starting point for modern philosophy by using a method of systematic doubt; that we cannot rely on our senses or logic, and therefore he challenged all who sought for the basis of certainty and knowledge. His famous maxim is ‘I think, therefore I am’, that is – I can only be sure of my own existence, the rest must be doubted.
  • John Locke (1632–1704) – made the distinction between bodies or objects that can be directly measured, and therefore have a physical existence, and those abstract qualities that are generated by our perceptions and feelings.
  • George Berkeley (1685–1753) – argued that all things that exist are only mental phenomena. They exist by being perceived. This is ‘our’ world.
  • David Hume (1711–1776) – made a distinction between systems of ideas that can provide certainty – e.g. maths – and those that rely on our perceptions (empirical evidence) which are not certain. He recognized the importance of inductive thinking in the advancement of scientific knowledge, but highlighted its restrictions in finding the truth.
  • Immanuel Kant (1724–1804) – held that our minds organize our experiences to make sense of the world. Therefore ‘facts’ are not independent of the way we see things and interpret them.
  • Karl Popper (1902–1994) – formulated a combination of deductive and inductive thinking in the hypothetico-deductive method, commonly known as scientific method. This method aims to refine theories to get closer to the truth.
  • Auguste Compte (1789–1857) – maintained that society can be analysed empirically just like any other subjects of scientific enquiry. Social laws and theories are based on psychology and biology.
  • Karl Marx (1818–1883) – defined moral and social aspects of humanity in terms of material forces.
  • Emil Durkheim (1858–1917) – argued that society develops its own
  • system of collectively shared norms and beliefs – these were ‘social facts’.
  • Max Weber (1864–1920) – insisted that we need to understand the values and meanings of subjects without making judgements – ‘verstehen’ was the term he coined for this which is German for ‘understanding’.
  • Thomas Kuhn (1922–1995) – revealed that scientific research cannot be separated from human influences and is subject to social norms.
  • Michel Foucault (1926–1984) – argued that there was no progress in science, only changing perspectives, as the practice of science is shown to control what is permitted to count as knowledge. He demonstrated how discourse is used to make social regulation and control appear natural.
  • Jacques Derrida (1930–2004) – stated that there is no external or fixed meaning to text, nor is there a subject who exists prior to language and to particular experiences. You cannot get outside or beyond the structure. This approach led to the movement called Deconstruction.

Friday, January 11, 2019

How did you learn math?


Nove níveis de consciência

  • Primeiro – Sobrevivência
     
  • Segundo – Condicionamento
     
  • Terceiro – Desejo de ser importante
     
  • Quarto – Claridade
     
  • Quinto – Realização
     
  • Sexto – Apoiar uns aos outros
     
  • Sétimo – Fluir com a vida
     
  • Oitavo – Conexão
     
  • Nono – Unidade

Eneagrama - Tipo Cinco - Refletindo sobre a avareza

No Eneagrama o Tipo Cinco está sempre em busca de conhecimento. São pessoas discretas e que não costumam falar muito. O pecado de raiz que os aprsiona é a avareza. Neste artigo refletimos sobre alguns comportamentos dessa gente tão interessante no dia a dia.

Acaso não houvesse no mundo gente do Tipo Cinco ele seria por demais enfadonho, acomodado e estável. O conhecimento nos chegaria muito mais lentamente e as mudanças não custariam bem mais a acontecer. É esta gente que presenteia a humanidade com a sabedoria.

Os Cinco estão sempre pesquisando, jamais deixam de estudar para tornar o mundo melhor. São eles os grandes inventores, os criadores das novas teorias, aqueles que fazem com que a humanidade possa dar saltos quantitativos e qualitativos de crescimento.

Enquanto aqui vou escrevendo, gosto de imaginar quantos e quantos Cincos não estão absortos em bibliotecas e laboratórios, mundo afora, trabalhando duro para nos gerar ciência, tecnologia e conhecimento especializado, que possa ser transformado em ferramentas práticas para facilitar a vida de nós todos.

Mas será que é sempre assim? A dura realidade nos mostra que não. Há muito Cinco por aí que se aprofunda em temas inócuos, absolutamente irrelevantes. Eles, podem ficar obcecados pelo foco e perderem a visão do todo, ou mesmo como poderão encaixar aquilo no que estão estudando, na vida prática. Sim, o Tipo Cinco corre o risco da “super especialização”. A verdade é que como costuma separar (veremos isto mais adiante) seus sentimentos daquilo que vive pensando, há que tomar cuidados para não ficar estudando algo que nada tenha a ver com a realidade circunstante.

O Cinco vive a tentação de proteger a vida, guardá-la e assim não vivenciá-la. A vida é experimentar, fruir das vivências que se nos apresentam. Viver bem é escolher aquilo que nos faça melhores e desprezar as demais que não nos ajudam no crescimento. Só que o Tipo Cinco entra aqui num grande conflito. A dificuldade é que quando se encontra no “modo automático” da existência, acredita que existir é pensar. Acha então que está vivendo, quando em realidade se encontra apenas observando a realidade circunstante.

É preciso mostrar ao Cinco que viver é descer da torre de observação onde se esconde e partir na direção das pessoas. Ah, como ele sente medo disto. É que ele tem a impressão de que irão exigir demais dele. Ou então que são rasas e cansativas. As pessoas, é o que relatam vários Cincos, são “sugadoras de energia” e como consideram que a tem no nível básico, que a possuem em nível apenas suficiente para sobreviver, agirão com bastante parcimônia em relação à sua disponibilização.

Esta dificuldade em se relacionar fará com que crie espaços estanques de amizade. Criará então cenários bem definidos e protegidos, para que não corram o risco de se misturar. Assim, é bastante usual que o Cinco tenha amigos do esporte, do grupo de estudos, da Igreja, do trabalho... Normal até aqui, eis que todos os tipos também o possuam.

O que há de diferente com o Cinco é que estas pessoas não costumam se conhecer num cenário comum. Desse jeito não terá maiores dificuldades em se relacionar com elas, eis que saberá bem o que esperam dele. É comum, depois de muitos anos, que um amigo de um cinco, oriundo de uma dessas plataformas, descubra (as proteções também falham) que possui um amigo comum com ele e que jamais havia se dado conta disto.

O seu pecado, a usura, explica bem esta situação de economia de vida na qual costuma estar metido. A avareza vital não se manifestará somente na questão do dinheiro. Você poderá encontrar vários Cinco bastante abertos à questão financeira. Ela se dará bem mais na segurança em relação aos sentimentos. Fato é que a sua mesquinhez ficará ainda mais patente em aspectos relacionais.

Ele sofre receios de se relacionar. É necessário se lembrar de que o Cinco faz parte do Centro da Razão e este é regido pelo medo. Por isto suas relações, quando ainda está numa fase inconsciente e conformista, ou normal, tenderá a se dar de maneira superficial. O cônjuge, sentindo falta de mais afeto e emoção, poderá lhe cobrar maior profundidade, ou doação à relação. Nesta hora ele poderá se retrair e será capaz, inclusive, de elaborar uma bela explicação sobre o que é na verdade um sentimento.

Definir ou explicar algo jamais será prova de que se esteja vivendo aquilo que se teoriza, mas o Cinco, nessa sua separação entre sentir e pensar, acabará ponderando, ilusoriamente, que por conseguir explicar o que acha que seja o sentimento pertinente para a situação, ele o estará realmente experimentando.

O Cinco é observador nato. Está sempre atento a reparar tudo em volta. A vida foi lhe ensinando a fazer isto sem ser notado. Quando presente num grupo saberá bastante de todo mundo. Saberá dos outros, mas esses, não necessariamente, conhecerão dele, eis que é sempre discreto e fala bem pouco. Seu método de observar é “na moita”. É especialista no que se chama voyeurismo. Consegue ver tudo sem que se note que esteja olhando.

Ao fazer desta forma se sente confortável. Afinal, olhando de longe e mais ainda, sem ser reparado, não será necessário comprometer-se com o que esteja acontecendo. Permanecerá em sua torre protegida, alienado das relações e das dificuldades inerentes a ela. Sair dessa posição de mero expectador da vida e partir para vivenciar a existência desde dentro, é crescimento para o Cinco. Viver, ele desconhece, é agir, é se emocionar, é se relacionar e não apenas observar ou analisar sistematicamente a realidade.

Ao sair da posição de observador e partir para a ação, o Cinco estará se dando conta de sua vulnerabilidade emocional e enfrentando-a. Mas não conseguirá fazer isto sozinho. O acompanhante espiritual, coaching, amigo, ou cônjuge, precisará estar bem perto dele nesta hora, dando-lhe a mão e conduzindo-o em direção aos sentimentos. Ele os acha perigosos. Uma caixa a ser guardada bem fechada e escondida. Seu auxílio fará com que não os racionalizem, mas os vivenciem, mesmo que lhes provoquem incômodo e até mesmo o coloquem em contato com a dor.

Deixando a proteção dos altos muros do seu castelo mental e se colocando disponível a viver mais dentro do coração e da ação, o Cinco passará a se fazer atento a, mais do que perceber, viver os pensamentos. Tal passo o levará a entrar na maravilhosa dinâmica da compaixão: sentir aquilo que o outro esteja experimentando, independente do sinal de positivo (consolação) ou negativo, (desolação) que a experiência irá lhe trazer.

Será crescimento para o Cinco tomar consciência de que ao se disponibilizar para o mundo, não estará perdendo algo, mas sim ganhando. Claro que poderão se machucar. Faz parte das regras do jogo da vida. Agindo diferente estará tão preservado que não se machucará, mas também não experimentará o que seja realmente viver. Passará pela existência como mero e frio observador dos acontecimentos.

Os tempos Pós-modernos oferecem algo que o Cinco considera como uma tremenda maravilha. Trata-se da Internet. Esta pode se tornar o manjar dos deuses deles. Propicia-lhes o controle dos contatos, deixa-os no comando da situação, podendo assim escapar das surpresas, que lhes são tão incômodas e desagradáveis.

Ao menor sinal de aflição, de que a emoção ameaça chegar, ou de que pretendem conhecer mais dele, a um rápido clique se retirará e tudo estará de volta à fria normalidade. Aliviado então poderá, cansado do fato vivenciado, desligar o computador, ou partir para algum outro grupo, ou pessoa que não vá lhe exigir nada além da razão e do conhecimento externo.

Quando o Cinco inicia a subida desenvolvendo-se no Eneagrama, toma consciência de que a vida vai muito além daquilo que observa e vê. A existência é para ser gasta e isto significa que será preciso aprender a lidar com os conflitos e relações de maneira mais profunda. Saber que os desejos não poderão ser, vida afora, sublimados, mas exigem ser experimentados nos relacionamentos. Ao sentir-se assim o Cinco, que tinha tanto receio de contatos, surpreenderá seu/sua parceiro(a), mostrando o quanto consegue mergulhar na experiência corporal.

O Cinco tem com os vizinhos Quatro uma semelhança. Compartilham de semelhante sentimento de perda. O Quatro vivencia tal perda de maneira intensa e constante. O Cinco acha que perde algo ao se relacionar e se doar a outrem. Será  preciso convencê-lo de que se entregar não é perder algo, mas sim ganhar vida. Ganhar a amizade, cumplicidade e Amor do outro.

É bem provável que tenha se tornado assim, frio e mental, porque na infância se sentiu rechaçado. Ou porque via nos pais, ou figuras de autoridade, gente invasora de privacidade. Para que não soubessem então o que na realidade estava pensando, criou muros de proteção e lá do outro lado fica a nos olhar.

A oração do Tipo Cinco tende a ser mental e estruturada por ele mesmo. Gostam de se retirar para rezar. Quanto mais distante dos outros, esta é uma tentação que  costumam viver, melhor será para orar. Esquecem-se de que a oração se faz, principalmente, onde se vive a comunidade.

Sem questionar verdadeiras vocações monásticas, há que se tomarem cuidados com pessoas Cinco que resolvem seguir a vida contemplativa. Poderá bem ser que a decisão por este caminho, se dê mais para fugir do contato das pessoas e das suas emoções pessoais, do que para um real encontro com a misericórdia e o Amor de Deus.

Sem dúvida que será muito difícil para uma pessoa do Tipo Cinco, experimentar o Amor de Deus quando não consegue tomar consciência de seus sentimentos, ou mesmo não os esteja experimentando através de uma relação afetiva. Viver a experiência do Amor humano (uma faceta do Amor de Deus), o auxiliará a que se deixe inebriar pelo sentimento profundo de Deus dentro dele.

Quando integrados eles se tornam seres socializados, não fogem do contato e nem sentem que os outros estão querendo lhes roubar energia. Sabem interagir e se preocupam com as questões da justiça e das relações humanas. A calma e sabedoria que têm ajudarão a encontrar soluções para situações de injustiça. Ajudará também na resolução de conflitos às suas voltas.

O respeito à individualidade. O cuidado com o espaço de cada um e o guardar para as horas de crise e necessidade são aspectos fundamentais à vida, são presentes do Amor de Deus para nós. Não houvesse os celeiros do Egito como poderiam José e seus irmãos ter sobrevivido? Guardar sem levar em conta os outros, sem a partilha é que é a usura e essa nos leva para distante de Deus.

Integrado consigo mesmo, com os outros e com Deus o Cinco sente que ser profundo, implica em estar unido àqueles que fazem parte da sua vida. Que é impossível viver realmente sendo uma ilha estanque e autossuficiente. A sua razão será posta em apoio à emoção e atitudes de vida, que irá tomando com toda a sua sabedoria.

Ser sábio é tomar uma das faces mais belas e profundas de Deus. A sabedoria é dom da Trindade Santa e faz com que o Cinco possa nos ajudar na aplicação da ferramenta do discernimento. Esta consiste em escolher, entre vários caminhos bons, aquele que melhor me conduzirá à realização e felicidade. Para Deus, enfim.

Unidos pelo círculo a todos os demais Tipos temos, de alguma forma, a avareza em nossa vida. Não somente o Cinco que a possui como paixão fundamental precisa se preocupar com ela. Ninguém está livre. De uma forma ou de outra, todos nos abrigamos debaixo da sombra sorrateira da usura. Todos queremos defender, ou guardar algo. Nenhum de nós é indiferente em relação às coisas que nos rodeiam. Leia e releia o texto observando-se mais no intuito de verificar, com abertura de coração, como a avareza se manifesta dentro do tipo do qual sou parte.

Para auxiliar na reflexão e apoiar as descobertas e ênfases, há algumas perguntas postas em seguida. Use-as tanto quanto possam ajudar na caminhada e deixe-as de lado, caso sinta não serem pertinentes para o conhecimento de si e seu crescimento pessoal e espiritual.

- Minha avareza se manifesta de que maneira?

- - Como me sinto quando avarento(a)?

- Como me relaciono com a sabedoria e o conhecimento?

- Como me relaciono com as pessoas?

- Deus para mim é sabedoria?

Anoto minhas observações no caderno do Eneagrama.

Faço o NER.

Resumo:

Pecado de raiz: Avareza

Armadilha: Ganância (juntar)

Mecanismo de defesa: Retirada

Autoimagem: Vejo através

Convite: Sabedoria

Fruto do Espírito: Desapego

http://www.genteplena.com.br/cms/artigoFull.php?id_artigo=64&cat=3&titulo=Eneagrama%20-%20Tipo%20Cinco%20-%20Refletindo%20sobre%20a%20avareza

Eneagrama


Thursday, January 10, 2019

Knapsack problem in R

Problem definition

You are going to spend a month in the wilderness. You’re taking a backpack with you, however, the maximum weight it can carry is 20 kilograms. You have a number of survival items available, each with its own number of “survival points”. You’re objective is to maximize the number of survival points.

Code

library(genalg)
library(ggplot2)

dataset <- bag="" beans="" br="" compass="" data.frame="" item="c(" pocketknife="" potatoes="" rope="" sleeping="" unions="">                      survivalpoints = c(10, 20, 15, 2, 30, 10, 30),
                      weight = c(1, 5, 10, 1, 7, 5, 1))
weightlimit <- 10="" br="">
chromosome = c(1, 0, 0, 1, 1, 0, 0)
dataset[chromosome == 1, ]

evalFunc <- br="" function="" x="">  current_solution_survivalpoints <- br="" dataset="" survivalpoints="" x="">  current_solution_weight <- br="" dataset="" weight="" x=""> 
  if (current_solution_weight > weightlimit)
    return(0) else return(-current_solution_survivalpoints)
}

iter = 100
GAmodel <- br="" iters="iter," mutationchance="0.01," popsize="200," rbga.bin="" size="7,">                    elitism = T, evalFunc = evalFunc)

cat(summary(GAmodel))
plot(GAmodel)

solution = c(1, 1, 0, 1, 1, 1, 1)
dataset[solution == 1, ]

# solution vs available
cat(paste(solution %*% dataset$survivalpoints, "/", sum(dataset$survivalpoints)))

animate_plot <- br="" function="" x="">  for (i in seq(1, iter)) {
    temp <- br="" data.frame="" eneration="c(seq(1," i="" mean="" seq="" variable="c(rep(">                                                                              i), rep("best", i)), Survivalpoints = c(-GAmodel$mean[1:i], -GAmodel$best[1:i]))
   
    pl <- aes="" br="" ggplot="" group="Variable," temp="" x="Generation," y="Survivalpoints,">                           colour = Variable)) + geom_line() + scale_x_continuous(limits = c(0,
                                                                                             iter)) + scale_y_continuous(limits = c(0, 110)) + geom_hline(y = max(temp$Survivalpoints),
                                                                                                                                                          lty = 2) + annotate("text", x = 1, y = max(temp$Survivalpoints) +
                                                                                                                                                                                2, hjust = 0, size = 3, color = "black", label = paste("Best solution:",
                                                                                                                                                                                                                                       max(temp$Survivalpoints))) + scale_colour_brewer(palette = "Set1") +
      opts(title = "Evolution Knapsack optimization model")
   
    print(pl)
  }
}

# in order to save the animation
install.packages("animation")
library(animation)
saveMovie(animate_plot(), interval = 0.1, outdir = getwd())


 

Sunday, December 23, 2018

Um dia a Verdade e a Mentira se encontram

Um dia a Verdade e a Mentira se encontram. A Mentira diz à Verdade: “Hoje está um dia maravilhoso!” A Verdade olha para o céu, desconfiada, e suspira, pois o dia estava realmente lindo. Elas passam algum tempo juntas, chegando finalmente a um poço. A Mentira diz à Verdade: “A água está muito boa, vamos tomar um banho juntas!” A Verdade, mais uma vez desconfiada, testa a água e descobre que realmente está muito gostosa. Elas se despem e começam a tomar banho. De repente, a Mentira sai da água, veste as roupas da Verdade e foge. A Verdade, furiosa, sai do poço e corre para encontrar a Mentira e pegar suas roupas de volta.

O mundo, vendo a Verdade nua, desvia o olhar, com desprezo e raiva. A pobre Verdade volta ao poço e desaparece para sempre, escondendo nele sua vergonha. Desde então, a Mentira viaja ao redor do mundo vestida como a Verdade, satisfazendo as necessidades da sociedade. Porque o mundo não nutre o menor desejo de encontrar a Verdade nua.

Parábola judaica

S.O.L.I.D: The First 5 Principles of Object Oriented Design

S.O.L.I.D is an acronym for the first five object-oriented design(OOD)** principles** by Robert C. Martin, popularly known as Uncle Bob.
These principles, when combined together, make it easy for a programmer to develop software that are easy to maintain and extend. They also make it easy for developers to avoid code smells, easily refactor code, and are also a part of the agile or adaptive software development.
Note: this is just a simple "welcome to _S.O.L.I.D" article, it simply sheds light on what S.O.L.I.D is_.

S.O.L.I.D stands for:

When expanded the acronyms might seem complicated, but they are pretty simple to grasp.
  • S - Single-responsiblity principle
  • O - Open-closed principle
  • L - Liskov substitution principle
  • I - Interface segregation principle
  • D - Dependency Inversion Principle
Let's look at each principle individually to understand why S.O.L.I.D can help make us better developers.

Single-responsibility Principle

S.R.P for short - this principle states that:
A class should have one and only one reason to change, meaning that a class should have only one job.
For example, say we have some shapes and we wanted to sum all the areas of the shapes. Well this is pretty simple right?
class Circle {
    public $radius;

    public function construct($radius) {
        $this->radius = $radius;
    }
}

class Square {
    public $length;

    public function construct($length) {
        $this->length = $length;
    }
}
First, we create our shapes classes and have the constructors setup the required parameters. Next, we move on by creating the AreaCalculator class and then write up our logic to sum up the areas of all provided shapes.
class AreaCalculator {

    protected $shapes;

    public function __construct($shapes = array()) {
        $this->shapes = $shapes;
    }

    public function sum() {
        
    }

    public function output() {
        return implode('', array(
            "",
                "Sum of the areas of provided shapes: ",
                $this->sum(),
            ""
        ));
    }
}
To use the AreaCalculator class, we simply instantiate the class and pass in an array of shapes, and display the output at the bottom of the page.
$shapes = array(
    new Circle(2),
    new Square(5),
    new Square(6)
);

$areas = new AreaCalculator($shapes);

echo $areas->output();
The problem with the output method is that the AreaCalculator handles the logic to output the data. Therefore, what if the user wanted to output the data as json or something else?
All of that logic would be handled by the AreaCalculator class, this is what SRP frowns against; the AreaCalculator class should only sum the areas of provided shapes, it should not care whether the user wants json or HTML.
So, to fix this you can create an SumCalculatorOutputter class and use this to handle whatever logic you need to handle how the sum areas of all provided shapes are displayed.
The SumCalculatorOutputter class would work like this:
$shapes = array(
    new Circle(2),
    new Square(5),
    new Square(6)
);

$areas = new AreaCalculator($shapes);
$output = new SumCalculatorOutputter($areas);

echo $output->JSON();
echo $output->HAML();
echo $output->HTML();
echo $output->JADE();
Now, whatever logic you need to output the data to the user is now handled by the SumCalculatorOutputter class.

Open-closed Principle

Objects or entities should be open for extension, but closed for modification.
This simply means that a class should be easily extendable without modifying the class itself. Let's take a look at the AreaCalculator class, especially it's sum method.
public function sum() {
    foreach($this->shapes as $shape) {
        if(is_a($shape, 'Square')) {
            $area[] = pow($shape->length, 2);
        } else if(is_a($shape, 'Circle')) {
            $area[] = pi() * pow($shape->radius, 2);
        }
    }

    return array_sum($area);
}
If we wanted the sum method to be able to sum the areas of more shapes, we would have to add more if/else blocks and that goes against the Open-closed principle.
A way we can make this sum method better is to remove the logic to calculate the area of each shape out of the sum method and attach it to the shape's class.
class Square {
    public $length;

    public function __construct($length) {
        $this->length = $length;
    }

    public function area() {
        return pow($this->length, 2);
    }
}
The same thing should be done for the Circle class, an area method should be added. Now, to calculate the sum of any shape provided should be as simple as:
public function sum() {
    foreach($this->shapes as $shape) {
        $area[] = $shape->area();
    }

    return array_sum($area);
}
Now we can create another shape class and pass it in when calculating the sum without breaking our code. However, now another problem arises, how do we know that the object passed into the AreaCalculator is actually a shape or if the shape has a method named area?
Coding to an interface is an integral part of S.O.L.I.D, a quick example is we create an interface, that every shape implements:
interface ShapeInterface {
    public function area();
}

class Circle implements ShapeInterface {
    public $radius;

    public function __construct($radius) {
        $this->radius = $radius;
    }

    public function area() {
        return pi() * pow($this->radius, 2);
    }
}
In our AreaCalculator sum method we can check if the shapes provided are actually instances of the ShapeInterface, otherwise we throw an exception:
public function sum() {
    foreach($this->shapes as $shape) {
        if(is_a($shape, 'ShapeInterface')) {
            $area[] = $shape->area();
            continue;
        }

        throw new AreaCalculatorInvalidShapeException;
    }

    return array_sum($area);
}

Liskov substitution principle

Let q(x) be a property provable about objects of x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.
All this is stating is that every subclass/derived class should be substitutable for their base/parent class.
Still making use of out AreaCalculator class, say we have a VolumeCalculator class that extends the AreaCalculator class:
class VolumeCalculator extends AreaCalulator {
    public function construct($shapes = array()) {
        parent::construct($shapes);
    }

    public function sum() {
        
        return array($summedData);
    }
}
In the SumCalculatorOutputter class:
class SumCalculatorOutputter {
    protected $calculator;

    public function __constructor(AreaCalculator $calculator) {
        $this->calculator = $calculator;
    }

    public function JSON() {
        $data = array(
            'sum' => $this->calculator->sum();
        );

        return json_encode($data);
    }

    public function HTML() {
        return implode('', array(
            '',
                'Sum of the areas of provided shapes: ',
                $this->calculator->sum(),
            ''
        ));
    }
}
If we tried to run an example like this:
$areas = new AreaCalculator($shapes);
$volumes = new AreaCalculator($solidShapes);

$output = new SumCalculatorOutputter($areas);
$output2 = new SumCalculatorOutputter($volumes);
The program does not squawk, but when we call the HTML method on the $output2 object we get an E_NOTICE error informing us of an array to string conversion.
To fix this, instead of returning an array from the VolumeCalculator class sum method, you should simply:
public function sum() {
    
    return $summedData;
}
The summed data as a float, double or integer.

Interface segregation principle

A client should never be forced to implement an interface that it doesn't use or clients shouldn't be forced to depend on methods they do not use.
Still using our shapes example, we know that we also have solid shapes, so since we would also want to calculate the volume of the shape, we can add another contract to the ShapeInterface:
interface ShapeInterface {
    public function area();
    public function volume();
}
Any shape we create must implement the volume method, but we know that squares are flat shapes and that they do not have volumes, so this interface would force the Square class to implement a method that it has no use of.
ISP says no to this, instead you could create another interface called SolidShapeInterface that has the volume contract and solid shapes like cubes e.t.c can implement this interface:
interface ShapeInterface {
    public function area();
}

interface SolidShapeInterface {
    public function volume();
}

class Cuboid implements ShapeInterface, SolidShapeInterface {
    public function area() {
        
    }

    public function volume() {
        
    }
}
This is a much better approach, but a pitfall to watch out for is when type-hinting these interfaces, instead of using a ShapeInterface or a SolidShapeInterface.
You can create another interface, maybe ManageShapeInterface, and implement it on both the flat and solid shapes, this way you can easily see that it has a single API for managing the shapes. For example:
interface ManageShapeInterface {
    public function calculate();
}

class Square implements ShapeInterface, ManageShapeInterface {
    public function area() { /Do stuff here/ }

    public function calculate() {
        return $this->area();
    }
}

class Cuboid implements ShapeInterface, SolidShapeInterface, ManageShapeInterface {
    public function area() { /Do stuff here/ }
    public function volume() { /Do stuff here/ }

    public function calculate() {
        return $this->area() + $this->volume();
    }
}
Now in AreaCalculator class, we can easily replace the call to the area method with calculate and also check if the object is an instance of the ManageShapeInterface and not the ShapeInterface.

Dependency Inversion principle

The last, but definitely not the least states that:
Entities must depend on abstractions not on concretions. It states that the high level module must not depend on the low level module, but they should depend on abstractions.
This might sound bloated, but it is really easy to understand. This principle allows for decoupling, an example that seems like the best way to explain this principle:
class PasswordReminder {
    private $dbConnection;

    public function __construct(MySQLConnection $dbConnection) {
        $this->dbConnection = $dbConnection;
    }
}
First the MySQLConnection is the low level module while the PasswordReminder is high level, but according to the definition of D in S.O.L.I.D. which states that Depend on Abstraction not on concretions, this snippet above violates this principle as the PasswordReminder class is being forced to depend on the MySQLConnection class.
Later if you were to change the database engine, you would also have to edit the PasswordReminder class and thus violates Open-close principle.
The PasswordReminder class should not care what database your application uses, to fix this again we "code to an interface", since high level and low level modules should depend on abstraction, we can create an interface:
interface DBConnectionInterface {
    public function connect();
}
The interface has a connect method and the MySQLConnection class implements this interface, also instead of directly type-hinting MySQLConnection class in the constructor of the PasswordReminder, we instead type-hint the interface and no matter the type of database your application uses, the PasswordReminder class can easily connect to the database without any problems and OCP is not violated.
class MySQLConnection implements DBConnectionInterface {
    public function connect() {
        return "Database connection";
    }
}

class PasswordReminder {
    private $dbConnection;

    public function __construct(DBConnectionInterface $dbConnection) {
        $this->dbConnection = $dbConnection;
    }
}
According to the little snippet above, you can now see that both the high level and low level modules depend on abstraction.

Conclusion

Honestly, S.O.L.I.D might seem to be a handful at first, but with continuous usage and adherence to its guidelines, it becomes a part of you and your code which can easily be extended, modified, tested, and refactored without any problems.

Thursday, December 13, 2018

Steps in CSE research


Types of Research


Some key figures that have influenced thinking about research


  • Plato (427–347 BC) and Aristotle (348–322 BC) – these represent the two contrasting approaches to acquiring knowledge and understanding the world (epistemology). Plato argued for deductive thinking (starting with theory to make sense of what we observe) and Aristotle for the opposite, inductive thinking (starting with observations in order to build theories).
  • René Descartes (1596–1650) – provided the starting point for modern philosophy by using a method of systematic doubt; that we cannot rely on our senses or logic, and therefore he challenged all who sought for the basis of certainty and knowledge. His famous maxim is ‘I think, therefore I am’, that is – I can only be sure of my own existence, the rest must be doubted.
  • John Locke (1632–1704) – made the distinction between bodies or objects that can be directly measured, and therefore have a physical existence, and those abstract qualities that are generated by our perceptions and feelings.
  • George Berkeley (1685–1753) – argued that all things that exist are only mental phenomena. They exist by being perceived. This is ‘our’ world.
  • David Hume (1711–1776) – made a distinction between systems of ideas that can provide certainty – e.g. maths – and those that rely on our perceptions (empirical evidence) which are not certain. He recognized the importance of inductive thinking in the advancement of scientific knowledge, but highlighted its restrictions in finding the truth.
  • Immanuel Kant (1724–1804) – held that our minds organize our experiences to make sense of the world. Therefore ‘facts’ are not independent of the way we see things and interpret them.
  • Karl Popper (1902–1994) – formulated a combination of deductive and inductive thinking in the hypothetico-deductive method, commonly known as scientific method. This method aims to refine theories to get closer to the truth.
  • Auguste Compte (1789–1857) – maintained that society can be analysed empirically just like any other subjects of scientific enquiry. Social laws and theories are based on psychology and biology.
  • Karl Marx (1818–1883) – defined moral and social aspects of humanity in terms of material forces.
  • Emil Durkheim (1858–1917) – argued that society develops its own
  • system of collectively shared norms and beliefs – these were ‘social facts’.
  • Max Weber (1864–1920) – insisted that we need to understand the values and meanings of subjects without making judgements – ‘verstehen’ was the term he coined for this which is German for ‘understanding’.
  • Thomas Kuhn (1922–1995) – revealed that scientific research cannot be separated from human influences and is subject to social norms.
  • Michel Foucault (1926–1984) – argued that there was no progress in science, only changing perspectives, as the practice of science is shown to control what is permitted to count as knowledge. He demonstrated how discourse is used to make social regulation and control appear natural.
  • Jacques Derrida (1930–2004) – stated that there is no external or fixed meaning to text, nor is there a subject who exists prior to language and to particular experiences. You cannot get outside or beyond the structure. This approach led to the movement called Deconstruction.

Scientific Method


Sunday, December 09, 2018

Os 12 Arquétipos Comuns

post-08-31-2
O termo “arquétipo” tem suas origens na Grécia antiga, as palavras raiz são archein que significa “original ou velho” e typos que significa “padrão, modelo ou tipo”, o significado combinado é “padrão original” do qual todas as outras pessoas similares, objetos ou conceitos são derivados, copiados, modelados, ou emulados.
O psicólogo Carl Gustav Jung usou o conceito de arquétipo em sua teoria da psique humana, ele acreditava que arquétipos de míticos personagens universais residiam no interior do inconsciente coletivo das pessoas em todo o mundo, arquétipos representam motivos humanos fundamentais de nossa experiência como nós evoluímos consequentemente eles evocam emoções profundas.
Embora existam muitos diferentes arquétipos, Jung definiu doze tipos principais que simbolizam as motivações humanas básicas, cada tipo tem seu próprio conjunto de valores, significados e traços de personalidade, além disso, os doze tipos são divididos em três grupos de quatro, ou seja, Ego, Alma e Eu, os tipos em cada conjunto compartilha uma fonte de condução comum, por exemplo, tipos dentro do conjunto Ego são levados a cumprir agendas definidas pelo ego.
A maioria se não todas as pessoas têm vários arquétipos em jogo na construção da sua personalidade, no entanto, um arquétipo tende a dominar a personalidade em geral, ele pode ser útil para saber quais arquétipos estão em jogo em si e nos outros, especialmente nos entes queridos, amigos e colegas de trabalho a fim de obter uma visão pessoal sobre comportamentos e motivações.

Os Tipos de Ego

1. O Inocente
post-08-31-3 
Lema: Livre para ser você e eu
Desejo principal: Chegar ao paraíso
Objetivo: ser feliz
Maior medo: Ser punido por ter feito algo de ruim ou errado
Estratégia: Fazer as coisas certas
Fraqueza: Chato por toda a sua inocência ingênua
Talento: Fé e otimismo
O Inocente também é conhecido como: utópico, tradicionalista, ingênuo, místico, santo, romântico, sonhador.

2. O Cara Comum, o Órfão
post-08-31-4 
Lema: Todos os homens e mulheres são iguais
Desejo central: Ligação com os outros
Objetivo: Fazer parte
Maior medo: Ficar de fora ou se destacar da multidão
Estratégia: Desenvolver sólidas virtudes comuns, seja para a Terra ou o contato comum
Fraqueza: Perder o próprio Eu em um esforço para se misturar ou por uma questão de relações superficiais
Talento: O realismo, a empatia, a falta de pretensão
A pessoa normal também é conhecida como: O bom menino velho, o homem comum, a pessoa da porta ao lado, o realista, o cidadão sólido, o trabalhador rígido, o bom vizinho, a maioria silenciosa.

3. O Herói
post-08-31-5 
Lema: Onde há uma vontade, há um caminho
Desejo central: Provar o valor para alguém através de atos corajosos
Objetivo: Especialista em domínio de um modo que melhore o mundo
Maior medo: Fraqueza, vulnerabilidade, ser um “covarde”
Estratégia: Ser tão forte e competente quanto possível
Fraqueza: Arrogância, sempre precisando de mais uma batalha para lutar
Talento: Competência e coragem
O herói também é conhecido como: O guerreiro, o salvador, o super-herói, o soldado, o matador de dragão, o vencedor e o jogador da equipe.

4. O Cuidador
post-08-31-6 
Lema: Ame o seu próximo como a si mesmo
Desejo central: Proteger e cuidar dos outros
Objetivo: Ajudar os outros
Maior medo: Egoísmo e ingratidão
Estratégia: Fazer coisas para os outros
Fraqueza: Martírio e ser explorado
Talento: Compaixão e generosidade
O cuidador também é conhecido como: O santo, o altruísta, o pai, o ajudante, o torcedor.

Os Tipos de Alma

5. O Explorador
post-08-31-7 
Lema: Não me cerque
Desejo central: A liberdade de descobrir quem é através da exploração do mundo
Objetivo: A experiência de um mundo melhor, mais autêntico, mais gratificante na vida
Maior medo: Ficar preso, conformidade e vazio interior
Estratégia: Viajar, procurar e experimentar coisas novas, fugir do tédio
Fraqueza: Perambular sem destino tornando-se um desajustado
Talento: Autonomia, ambição, ser fiel a sua alma
O explorador também é conhecido como: O candidato, o iconoclasta, o andarilho, o individualista, o peregrino.

6. O Rebelde
post-08-31-8 
Lema: As regras são feitas para serem quebradas
Desejo central: Vingança ou revolução
Objetivo: Derrubar o que não está funcionando
Maior medo: Ser impotente ou ineficaz
Estratégia: Interromper, destruir ou chocar
Fraqueza: Cruzar para o lado negro do crime
Talento: Ousadia, liberdade radical
O rebelde também é conhecido como: O ilegal, o revolucionário, o homem selvagem, o desajustado, o iconoclasta.

7 O Amante
post-08-31-9 
Lema: Você é único
Desejo central: Intimidade e experiência
Objetivo: Estar em um relacionamento com as pessoas no trabalho e no ambiente que eles amam
Maior medo: Ficar sozinho, ser um invisível, se indesejado, ser mal amado
Estratégia: Tornar-se cada vez mais atraente fisicamente e emocionalmente
Fraqueza: Com o desejo de agradar aos outros corre o risco de perder sua identidade externa
Talento: Paixão, gratidão, valorização e compromisso
O amante também é conhecido como: O parceiro, o amigo íntimo, o entusiasta, o sensualista, o cônjuge, o construtor de equipe.

8. O Criador
post-08-31-10 
Lema: Se você pode imaginar algo, isso pode ser feito
Desejo central: Criar coisas de valor duradouro
Objetivo: Realizar uma visão
Maior medo: A visão ou a execução medíocre
Estratégia: Desenvolver a habilidade e o controle artístico
Tarefa: Criar cultura, expressar a própria visão
Fraqueza: Perfeccionismo, soluções ruins
Talento: Criatividade e imaginação
O Criador também é conhecido como: O artista, o inventor, o inovador, o músico, o escritor, o sonhador.

Os tipos de Eu

9. O Tolo
post-08-31-11 
Lema: Só se vive uma vez
Desejo central: Viver para o momento com pleno gozo
Objetivo: Ter um grande momento e iluminar o mundo
Maior medo: Se aborrecer ou chatear os outros
Estratégia: Jogar, fazer piadas, ser engraçado
Fraqueza: Frivolidade, desperdício de tempo
Talento: Alegria
O tolo também é conhecido como: O bobo da corte, o malandro, o palhaço, o brincalhão, o comediante.

10. O Sábio
post-08-31-12 
Lema: A verdade vos libertará
Desejo central: Encontrar a verdade
Objetivo: Usar a inteligência e a análise para compreender o mundo
Maior medo: Ser enganado, iludido, ou ser ignorante
Estratégia: Buscar informação e conhecimento, auto reflexão e compreensão dos processos de pensamento
Fraqueza: Pode estudar detalhes para sempre e nunca agir
Talento: Sabedoria, inteligência
O Sábio também é conhecido como: O perito, o erudito, o detetive, o conselheiro, o pensador, o filósofo, o acadêmico, o pesquisador, o pensador, o planejador, o profissional, o mentor, o professor, o contemplador.

11. O mágico
post-08-31-13 
Lema: Eu faço as coisas acontecerem.
Desejo central: Compreensão das leis fundamentais do universo
Objetivo: Realizar sonhos
Maior medo: Consequências negativas não intencionais
Estratégia: Desenvolver uma visão e viver por ela
Fraqueza: Se tornar manipulador
Talento: Encontrar soluções ganha-ganha
O mágico também é conhecido como: O visionário, o catalisador, o inventor, o líder carismático, o xamã, o curandeiro, o feiticeiro.

12. O Governante
CENTURY COLLECTION HITLER 
Lema: O poder não é qualquer coisa, é a única coisa
Desejo central: Controle e poder
Objetivo: Criar uma família ou uma comunidade bem sucedida e próspera
Estratégia: Exercer o poder
Maior medo: O caos, ser destituído
Fraqueza: Ser autoritário, incapaz de delegar
Talento: Responsabilidade, liderança
O Governante é também conhecido como: O chefe, o líder, o ditador, o aristocrata, o rei, a rainha, o político, o gerente, o administrador.

As quatro Orientações cardeais 

post-08-31-15
As quatro orientações cardeais definem quatro grupos, com cada grupo contendo três tipos (como a roda de arquétipos acima ilustra), cada grupo é motivado por seu respectivo foco orientador: satisfação do ego, liberdade, socialidade e ordem, esta é uma variação nos grupos dos três tipos anteriormente mencionados, no entanto, todos os tipos dentro do Ego, Alma e Eu compartilham da mesma fonte de condução, os tipos que compõem a orientação dos quatro grupos têm diferentes unidades de origem, mas a mesma orientação de motivação, por exemplo, o cuidador é impulsionado pela necessidade de cumprir agendas do ego através do atendimento das necessidades dos outros que é uma orientação social, considerando que o herói também é impulsionado pela necessidade de cumprir agendas do ego o faz através de ação corajosa que comprova a autoestima, compreender os agrupamentos ajudará na compreensão da dinâmica de motivação e autopercepção de cada tipo.
Carl Golden

Friday, October 26, 2018

Rules-based systems

In many cases, it is more practical to use a simple but uncertain rule rather than a complex but certain one, even if the true rule is deterministic and our modelling system has the fidelity to accommodate a complex rule. For example, thesimple rule “Most birds fly” is cheap to develop and is broadly useful, while a ruleof the form, “Birds fly, except for very young birds that have not yet learned tofly, sick or injured birds that have lost the ability to fly, flightless species of birdsincluding the cassowary, ostrich and kiwi. . .” is expensive to develop, maintainand communicate and, after all this effort, is still brittle and prone to failure.