Search vs List all in Angular 2

Handling search and the List of all items in Angular 2 in the same Component

Using the tutorial of Angular 2 for hero search was the base for this, although I wanted that the same table to show the All the items when the search was inactive without having to do a new component (one for searching and another one for listing all products).

On the template I setup the call of the enableSearch and disableSearch events

<input id=”search-box” (keyup)=”enableSearch()” [(ngModel)]=”searchValue” />
<button (click)=”disableSearch()”>clear search</button>

the enableSearch is fired on keyup meaning someone is starting to search for a name or keyword.

the disableSearch is fired on click of the button “clear search”

I used the two way binding of searchValue so I can clear the searched text when I disable the search

In the component method enableSearch I set a flag searchEnable = true and setup the Observable relation to this.products this way if the search is Enabled I wont set it up again and kill the observable with this new call.

products: Observable<Product[]>;
private searchTerms = new Subject<string>();

parents : Product[];

selectedCategory: Product;

db: Product[];

searchValue : string = ”;

private searchEnabled:boolean = false;

Initially I make the call for the full items list using getProducts

ngOnInit() :void {
this.products = this.productService.getProducts();

When the search is enabled by the keyup event this is executed

    enableSearch() {
if (!this.searchEnabled) {
this.products = this.searchTerms
.debounceTime(500)        // wait for n ms pause in events
.distinctUntilChanged()   // ignore if next search term is same as previous
.switchMap( term => term   // switch to new observable each time
// return the http search observable
// or the observable of empty products if no search term
: this.productService.getProducts()
.catch(error => {
// TODO: real error handling
return Observable.of<Product[]>([]);

this.searchEnabled = true;

// Push a search term into the observable stream.
search(term: string): void {;


if the search wasn’t enable I set up the observable and put the search term into the observable stream 😡 . The ternary operator would only fire the list if I had the search typed so to get always a result list I had to make these changes, so the table would be filled when a search was on and when there was no search.

And the code bellow disables the search and displays all the products available

disableSearch() {
this.searchValue = ”;
this.searchEnabled = false;
this.products = this.productService.getProducts();

I set the searchValue to an empty string and disable the searchEnabled value and getProducts from the Service.



Select ComboBox two way binding in Angular 2

This is a note for me or anyone that needs it…

providers: [CategoryService],
template: `
Add uma Category


Parent Category

*ngFor=”let p of categories” [value]=””[attr.selected]=” == category.parent_id”>

<button (click)=”add()”>Save</button>
<button (click)=”goBack()”>Back</button>

Basically this makes the item from a parent category select onclick and onchange and when rendered the selected attribute will equal the value of category.parent_id

attr accesses all the attributes of the Element and it has a property binding so the value of the resulting evaluation of == category.parent_id will set it’s selected attribute value.

category: Category = {id:0, name: “”, description: “”, parent_id:0};

Also on the component I have

getCategories() : void {
this.categoryService.getCategories().then( res => this.categories = res);

To show all categories on the category select combobox

ngOnInit pulls the categories

ngOnInit() : void {
this.getCategories(); // <–
// (+) converts string ‘id’ to a number
.switchMap((params: Params) => this.categoryService.getCategory(+params[‘id’]))
.subscribe((category: Category) => this.category = category);





Acreditar que um país deva ter medidas proteccionistas na importação e reclamar dos preços altos não é maluquice é exigir um mercado que se ajuste à necessidade dos consumidores. Se não houver ajuste o produtor continuará a criar desculpas e a aumentar preços sem melhorar métodos de produção e controlo de qualidade beneficiando de um monopólio.
O tipo de ajustes a que me refiro pode ser visto como a ordem do presidente Temer em 2016 de permitir a importação do feijão para terminar com a alta do preço do mesmo.
Claro que ter barreiras à importação e depois ter toda a classe alta a se beneficiar de suas viagens para contornar essas barreiras é a permissão para uma sociedade menos igual e a criação/preservação de um sistema de castas.

Scala Playframework connect to mysql

I’m writting this because I had issues following the documentation that comes with playframework
the docs are wrong or at least for me it gave me an error.

The docs states that to connect to a mysql database server you have to do the following:

If you need to connect to another JDBC-compliant database, first add the corresponding driver library to your application dependencies in build.sbt e.g.:

libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.18"

This above works ok, I had no problems.

Then add the corresponding JDBC configuration to the conf/application.conf file:


This above now has problems namely the db.driver section it returned me an error
java.lang.ClassNotFoundException: org.mysql.Driver

Searching the internet I found this answer

So the correct working version is:



Maybe for others this is easy to spot but for me it wasn’t.

PHP: Autentication and Access Control in a modular web application


This example is about the access control and authentication on a modular web application, developed in Symfony2 using the EventDispatcher, the logic of implementation can be used in different projects, that don’t necessarily use these tools. The basis of this access control is the usage of a main event dispatcher and listener (EventDriven) to detect destination request address and intercept it before it reaches that destination (controller + method ).

I first became aware of the idea of using Events to control access, I believe it was by on his blog a long time ago.

Anyway here I describe the usage of a Symfony2  custom EventListener to listen to a onKernelRequest

This usually happens this way:

Client -[call]-> Webserver -[dispatch event request]-> triggers onKernelRequest witch does validation -[Validates]-> if passes code continues normally inside symfony2  … Get the idea? I hope so.

First I implemented the interface in the AccessControl Class no other code will interact with this that’s the beauty of using a event for access control, you can have the event manage the control access of all modules without having to interact directly with them. The code is commented for easier reading…

Class AccessControl implements EventSubscriberInterface

public function __construct($em, $dispatcher, $security, $router)
$this->em = $em; // the EntityManager not used in this demo
$this->dispatcher = $dispatcher; // The SF2 EventDispatcher
$this->security = $security; // security.context
$this->router = $router; // router to know where the request is going to

And of course I will be listening to onKernelRequest events

public static function getSubscribedEvents()
return array(
KernelEvents::REQUEST => [‘onKernelRequest’, 0],

Here follows an example on access control without any dynamic database support

This is a basic decision path based on the destination route using the symfony name and the request from the client.

public function onKernelRequest($event)
if ($event->getRequestType() != HttpKernelInterface::MASTER_REQUEST) {
return null; // will only be handled if it’s from a external request else returns null

$user = $this->security->getToken()->getUser();  // get the current user information
$request = $event->getRequest(); // get the current request
$requested_uri = $request->getRequestUri(); // get the requested URI
$internal_route = $request->get(‘_route’); // this what is used to validate access

// $internal_route has the route name used by symfony witch I use to compare since it’s simpler

if ($internal_route == ‘fos_user_registration_register’) {
return true; // by default I allow the call to the registering of a new user

if ($user == ‘anon.’) {
$mainrequest = $event->getRequest();
// Matched route
$_route = $mainrequest->attributes->get(‘_route’);
// Matched controller
$_controller = $mainrequest->attributes->get(‘_controller’);
// All route parameters including the `_controller`
$params = $mainrequest->attributes->get(‘_route_params’);

if ($_route != ‘fos_user_security_login’) {

// if anonymous is not trying to login
// send him to login
$url = $this->router->generate(‘fos_user_security_login’);
$response = new RedirectResponse($url);

if ($user->hasGroup(“Admin”)) {
return true; // if the user has a group admin allow him to everywhere

$request = $event->getRequest();
$requested_uri = $request->getRequestUri();
$internal_route = $request->get(‘_route’); // this is what is used to validate access

if (mb_substr($internal_route, 0, mb_strlen(“lab_”)) == “lab_”) {
if ($user->hasGroup(“Laboratorio”)) {

// allow user to space _lab if he’s from the Group Laboratorio
return true;
} else {
// monolog here
throw new \Exception(“Unauthorized access. $internal_route”);

if (mb_substr($internal_route, 0, mb_strlen(“stock”)) == “stock”) {
if ($user->hasGroup(“Stock”)) {

// allow the user to access stock route names if he his in the stock Group
return true;
} else {
// monolog here
throw new \Exception(“Unauthorized access. $internal_route”);

if (mb_substr($internal_route, 0, mb_strlen(“user”)) == “user”) {
if ($user->hasGroup(“Admin”)) {

  // if the user is admin allow him to manage users
return true;
} else {
// monolog here
throw new \Exception(“Unauthorized access. $internal_route”);


After this, configure the services.xml file in Resources/config/  this will allow for the dependencies to be loaded in the object.

security.context provides information about the user logged (or not), router allow’s to generate a different destination route for the Event

In this gist you can see all the code used.

Best regards,

PHP Taking advantage of Traits and Doctrine2 for less lines of code

I did this app a time ago (~1 year) with Doctrine2+Symfony2 with simple Entities basically I was mimicking an excel sheet copying the values from the sheet to the database and setting all up for web usage.

The main Class was Item, this had Sub Entities Location, Protocol, State, etc…

These named here Location, Protocol, State had the same properties (fields), they also had to have a incrementable “Code” field witch, this was a basic copy paste to fill the tables and increment the number. Didn’t want to write the code to the different Entities so I used a Trait in a very lazy way I declared


namespace Far\AssetManagerBundle\Entity;

trait TautoFill {

    public function getAndInsert($val)

        $valtmp = strtoupper(str_replace(' ','',trim($val)));
        $Res = $this->findBy(['code' => $valtmp]);
        if (count($Res) > 0 && $Res[0] != null) {
            $obj = $Res[0];


        } else {
            $tmp = $this->getClassName();
            $obj = new $tmp();
            // persist

        return $obj;

So in a easy use TautoFill I got the data auto inserted and related to the main Item, without much work. Using a trait made the code more dynamic and easier to reimplement in the different situations without compromising hierarchy of the Entities.

An old Afgan story/Velha história Afegã (EN/PT)

“A man a women had a son, they decided to move to greener fields
, and eventually found a place where it was very beautiful
there a man rented a house to them. They lived well until one day
during the night a wolf went into their house and stole their son.
They wept, but eventually recovered and tried again, giving birth to a second son.
Soon after the child was born the renter visited them and congratulated
them. Bought were happy, until one day the wolf returned and stole their second
Devastated they changed place, left that house and never returned, eventually had a third
child and although they weren’t in that green field they were safe has the wolf never returned.”

This is my remembering of a old story of writer Ayaan Hirsi Ali, that her
grandmother told her during her childhood. The lesson here is that greener
fields aren’t always the safest. The renter was the wolf. If you buy her
biography it will give you a better read.

“Um dia um homem e uma mulher tiveram o seu primeiro filho, felizes resolveram
mudar-se para um local mais belo, encontraram um local e um homem alugou-lhes
uma casa. Mais tarde enquanto dormiam um lobo entrou na casa e roubou-lhes o filho,
choraram e lamentaram-se mas eventualmente recuperaram. Tiveram o seu segundo
filho, felizes congratularam-se, o arrendatário visitou-os e congratulou-os pela
boa nova… Após algum tempo o lobo regressou, roubou o segundo filho,
lamentaram-se, choraram e resolveram mudar-se dali.
Em novo local que apesar de não ser tão belo encontraram segurança.O lobo não

Este é um trecho da auto-biografia de Ayaan Hirsi Ali em que ela narra uma
história que lhe fora contada por sua avó. A lição a tirar daqui é que os
locais que parecem ser os mais belos nem sempre são os mais seguros. O
arrendatário era o lobo. Se comprarem a auto-biografia terão uma melhor leitura
desta história.