Categorias
Tropeçando

Tropeçando 85

Good Engineering Practices while Working Solo

How Much maintenance_work_mem Do I Need?

While I generally like PostgreSQL's documentation quite a bit, there are some areas where it is not nearly specific enough for users to understand what they need to do. The documentation for maintenance_work_mem is one of those places. It says, and I quote, "Larger settings might improve performance for vacuuming and for restoring database dumps," but that isn't really very much help, because if it might improve performance, it also might not improve performance, and you might like to know which is the case before deciding to raise the value, so that you don't waste memory. TL;DR: Try maintenance_work_mem = 1GB. Read on for more specific advice.

JSONPlaceholder

Fake Online REST API for Testing and Prototyping

A Beginner’s Guide to the True Order of SQL Operations

The SQL language is very intuitive. Until it isn’t. A guide to understanding the order of a SELECT operation.

The state of open source security - 2019

Snyk is an incredible tool for package security. And they released a state of open source security, talking about open source adoption and package, images and code vulnerabilites. We are talking about maven, npm, pypi, docker, etc.

Categorias
PHP

High-performance Fibonacci numbers generator in PHP

Based on the article High-performance Fibonacci numbers generator in Go I wrote my version using PHP. Despite the differences between PHP and Go architectures reflected in response times, we can face a huge performance difference when using an optimized function. We may notice that we can have the same results, but the quality of the written code can change lots of things.

Recursive approach

function fibonacci(int $n):int {
  if ($n <= 1) {
    return $n;
  }

  return fibonacci($n-1) + fibonacci($n-2);
}

Benchmark and test

function test_fibonacci() {
  $data = [
    [0,0], [1,1], [2,1], [3,2], [4,3], [5,5], [6,8], [10,55], [42,267914296]
  ];

  foreach($data as $test) {
    $result = fibonacci($test[0]);
    if ($result !== $test[1]) {
      throw new \UnexpectedValueException("Error Processing Request. N: {$test[0]}, got: {$result}, expected: {$test[1]}", 1);
    }
  }

  echo "Tests - Success.".PHP_EOL;
}

/**
  * From https://gist.github.com/blongden/2352583
  */
function benchmark($x)
{
    $start = $t = microtime(true);
    $total = $c = $loop = 0;
    while (true) {
        $x();
        $c++;
        $now = microtime(true);
        if ($now - $t > 1) {
            $loop++;
            $total += $c;
            list($t, $c) = array(microtime(true), 0);
        }
        if ($now - $start > 2) {
            return round($total / $loop);
        }
    }
}
Benchmark 10 run: 163,754/sec or 0.0061067210571955ms/op
Benchmark 20 run: 1,351/sec or 0.74019245003701ms/op

As we can see, calculations of 20 Fibonacci numbers takes 123 times longer than 10 Fibonacci numbers. Not well performed at all! The explanation can be found in the linked article.

Sequential approach

function fibonacci_tuned(int $n):float {
  if ($n <= 1) {
    return $n;
  }

  $n2 = 0;
  $n1 = 1;

  for ($i = 2; $i < $n; $i++) {
    $n2_ = $n2;
    $n2 = $n1;
    $n1 = ($n1 + $n2_);
  }

  return $n2 + $n1;
}

function test_fibonacci_tuned() {
  $data = [
    [0,0], [1,1], [2,1], [3,2], [4,3], [5,5], [6,8], [10,55], [42,267914296]
  ];

  foreach($data as $test) {
    $result = fibonacci_tuned($test[0]);
    $float_test_value = (float) $test[1];
    if ($result !== $float_test_value) {
      throw new \UnexpectedValueException("Error Processing Request. N: {$test[0]}, got: {$result}, expected: {$float_test_value}", 1);
    }
  }

  echo "Tests - Success.".PHP_EOL;
}

Results:

Benchmark 10 tuned run: 3,345,999/sec or 0.00029886440492062ms/op
Benchmark 20 tuned run: 2,069,100/sec or 0.00048330191870862ms/op

As a much better scenario, calculate 20 numbers takes almost 2 times longer than 10 numbers. Makes sense. And performs well!

Considering the two approaches, the recursive approach runs 10 Fibonacci numbers operations 20 times longer than sequential one and 1,824 times longer for 20 Fibonacci numbers.

Fibonacci implementation in PHP can be found at https://github.com/rafaelbernard/php-fibonacci.

Categorias
Tropeçando

Tropeçando 84

Cloud Computing without Containers

Cloudflare has a cloud computing platform called Workers. Unlike essentially every other cloud computing platform I know of, it doesn’t use containers or virtual machines. We believe that is the future of Serverless and cloud computing in general, and I’ll try to convince you why.

HTTP-over-QUIC will officially become HTTP/3

The protocol that's been called HTTP-over-QUIC for quite some time has now changed name and will officially become HTTP/3. This was triggered by this original suggestion by Mark Nottingham.

The QUIC Working Group in the IETF works on creating the QUIC transport protocol. QUIC is a TCP replacement done over UDP. Originally, QUIC was started as an effort by Google and then more of a "HTTP/2-encrypted-over-UDP" protocol.

Announcing SSH Access through Cloudflare

A way to replace the old (clunky) VPN by SSH access. Leverage access without losing security.

The Memory Resource Triad

Some more information about the three resources that affect query performance: cpu, memory, and storage.

psql: A New Edit

Have you ever found yourself in the middle of a long statement in psql and wanted to pull up your favorite editor? Now, you can, using the same shortcut of control-x control-e that you would in bash!

Categorias
Internet Segurança Spam

Um convincente e-mail fraudulento do Bitcoin extorquindo você

Esta publicação foi originalmente publicada em The convincing Bitcoin scam e-mail extorting you, por Mattias Geniar, em inglês. Mas o alerta vale ser traduzido para o português, tendo você assistido ou não do que a acusação se trata.

Mais uma vez vemos a criatividade de aplicadores de golpe. Fique atento. Fique alerta. A internet é uma terra tão selvagem quando as ruas em que andamos.


Há alguns meses recebi um e-mail que me deixou preocupado por alguns segundos. Parecia assim, e é bem provável que você tenha visto também.

From: Kalie Paci 
Subject: mattias - UqtX7m

It seems that, UqtX7m, is your pass word. You do not know me and you are probably thinking
why you are getting this mail, correct?

Well, I actually placed a malware on the adult video clips (porn) web-site and guess what,
you visited this site to have fun (you know what I mean). While you were watching videos,
your browser started operating as a RDP (Remote control Desktop) that has a keylogger which
gave me access to your display and also web camera. Immediately after that, my software
program collected your entire contacts from your Messenger, FB, and email.

What exactly did I do?

I created a double-screen video. First part displays the video you were viewing (you have
a nice taste lol), and second part displays the recording of your web camera.

What should you do?

Well, in my opinion, $1900 is a fair price for our little secret. You’ll make the payment
through Bitcoin (if you do not know this, search “how to buy bitcoin” in Google).

BTC Address: 1MQNUSnquwPM9eQgs7KtjDcQZBfaW7iVge
(It is cAsE sensitive, so copy and paste it)

Important:
You now have one day to make the payment. (I’ve a unique pixel in this message, and right
now I know that you have read this email message). If I don’t get the BitCoins, I will
send your video recording to all of your contacts including members of your family,
colleagues, and many others. Having said that, if I do get paid, I will destroy the video
immidiately. If you need evidence, reply with “Yes!” and I definitely will send your video
recording to your 11 friends. This is a non-negotiable offer, and so please don’t waste
my personal time and yours by responding to this mail.

Se você lê, parece spam - não é?

Bem, o que me preocupou por alguns segundos foi que a linha de assunto e o corpo continham uma senha real que eu usei um tempo atrás: UqtX7m.

Para receber um email com um - o que parece ser - segredo pessoal no assunto, chama a atenção. É inteligente no sentido de que você se sente violado e envergonhado pelas consequências. Parece legítimo.

Deixe-me dizer claramente: é uma farsa e você não precisa pagar ninguém.

Mencionei pela primeira vez no meu Twitter descrevendo o que parece ser a parte brilhante desse golpe:

  • E-mail + senhas, fáceis de obter (muitos vazamentos on-line)
  • Todo mundo assiste pornô
  • Ninguém quer que esta informação vaze
  • O mesmo e-mail genérico pode ser usado para todas as vítimas

Quem quer que esteja executando esse esquema pensou sobre a psicologia do golpe e encontrou o ponto ideal: ele chama sua atenção e deixa você preocupado.

Bem jogado. Mas não se apegue a isso e, mais importante: não pague nada.


Quanto à Combate à pornografia conheça Just1ClickAway. Busque se livrar deste mal.

Categorias
Tropeçando

Tropeçando 82

docz

It has never been so easy to document your things!

usql

A universal command-line interface for PostgreSQL, MySQL, Oracle Database, SQLite3, Microsoft SQL Server, and many other databases including NoSQL and non-relational databases!

Agendando tarefas com o Cron para Node

O Cron para Node é um pacote npm que nos permite fazer o agendamento de tarefas baseado em uma regra de tempo. Ele é baseado no Cron do Linux e seu funcionamento segue a mesma linha. Com ele é possível definir uma função para ser executada de tempos em tempos, ou seja, ela será agendada para ser executada dentro do Node. É uma maneira bastante eficaz para tarefas repetitivas que precisam rodar em segundo plano, como o envio de notificação, backup de banco de dados, entre outras.

Howto: use one VCL per domain

The Varnish Configuration Language (VCL), I'm sure you know already, is the source of Varnish versatility: by only enforcing the protocol flow and leaving the business logic to the user, Varnish can be easily configured to do things far beyond caching.

However, because the logic of websites is generally focused around hosts, and the VCL thinks in terms of processing steps, configuration may sometimes a bit odd, with the need to place safeguards around your code to ensure that logic for one host isn't applied to another one.

It works, but it can be tedious and unwieldy, so today we are going to have a look at how we can silo our VCL per website to achieve better maintainability.

Understanding the 8 Fallacies of Distributed Systems

Are you working on a distributed system? Microservices, Web APIs, SOA, web server, application server, database server, cache server, load balancer - if these describe components in your system's design, then the answer is yes. Distributed systems are comprised of many computers that coordinate to achieve a common goal.

More than 20 years ago Peter Deutsch and James Gosling defined the 8 fallacies of distributed computing. These are false assumptions that many developers make about distributed systems. These are usually proven wrong in the long run, leading to hard to fix bugs.

PostgreSQL Tuning: Key Things to Drive Performance

Performance is one of the key requirements in software architecture design, and has been the focus of PostgreSQL developers since its beginnings

Illuminate your career

If you are a developer, this article is for you.

5 Things You Have Never Done with a REST Specification

How to to Backup Linux with Snapshots

While working on different web projects I have accumulated a large pool of tools and services to facilitate the work of developers, system administrators and DevOps
One of the first challenges, that every developer faces at the end of each project is backup configuration and maintenance of media files, UGC, databases, application and servers' data (e.g. configuration files).

Awesome PHP

A curated list of amazingly awesome PHP libraries, resources and shiny things.

Categorias
Tropeçando

Tropeçando 81

ACME Support in Apache HTTP Server Project

We’re excited that support for getting and managing TLS certificates via the ACME protocol is coming to the Apache HTTP Server Project (httpd). ACME is the protocol used by Let’s Encrypt, and hopefully other Certificate Authorities in the future. We anticipate this feature will significantly aid the adoption of HTTPS for new and existing websites.

Postgres Hidden Gems

Postgres has a rich set of features, even when working everyday with it you may not discover all it has to offer. In hopes of learning some new features that I didn’t know about myself as well as seeing what small gems people found joy in I tweeted out to see what people came back from. The response was impressive, and rather than have it lost into ether of twitter I’m capturing some of the responses here along with some resources many of the features.

Why upgrade PostgreSQL?

Usage should be simple – pick from which version you want to upgrade, to which version you want to upgrade, and press gives me… button.

Introducing DNS Resolver, 1.1.1.1 (not a joke)

Cloudflare’s mission is to help build a better Internet and today we are releasing our DNS resolver, 1.1.1.1 - a recursive DNS service. With this offering, we’re fixing the foundation of the Internet by building a faster, more secure and privacy-centric public DNS resolver. The DNS resolver, 1.1.1.1, is available publicly for everyone to use - it is the first consumer-focused service Cloudflare has ever released.

My Favorite PostgreSQL Queries and Why They Matter

Below, I present a combination of 8 differing queries or types of queries I have found interesting and engaging to explore, study, learn, or otherwise manipulate data sets.

Categorias
Tropeçando

Tropeçando 80

MVCC and VACUUM

Experienced PostgreSQL users and developers rattle off the terms “MVCC” and “VACUUM” as if everyone should know what they are and how they work, but in fact many people don’t. This blog post is my attempt to explain what MVCC is and why PostgreSQL uses it, what VACUUM is and how it works, and why we need VACUUM to implement MVCC. In addition, I’ll include a few useful links for further reading for those who may want to know more.

Setting up psql, the PostgreSQL CLI

PostgreSQL ships with an interactive console with the command line tool named psql. It can be used both for scripting and interactive usage and is moreover quite a powerful tool. Interactive features includes autocompletion, readline support (history searches, modern keyboard movements, etc), input and output redirection, formatted output, and more.

A Replication Cheat-Sheet

New flexbox guides on MDN

In preparation for CSS Grid shipping in browsers in March 2017, I worked on a number of guides and reference materials for the CSS Grid specification, which were published on MDN. With that material updated, we thought it would be nice to complete the documentation with similar guides for Flexbox, and so I updated the existing material to reflect the core use cases of Flexbox.

introduction to pgBackRest

pgBackRest (http://pgbackrest.org/) aims to be a simple, reliable backup and restore system that can seamlessly scale up to the largest databases and workloads.

Instead of relying on traditional backup tools like tar and rsync, pgBackRest implements all backup features internally and uses a custom protocol for communicating with remote systems. Removing reliance on tar and rsync allows for better solutions to database-specific backup challenges. The custom remote protocol allows for more flexibility and limits the types of connections that are required to perform a backup which increases security.

Categorias
Tropeçando

Tropeçando 79

Plan for the unexpected: install diagnostic tools on your PostgreSQL servers

There’s a lot of information out there on how to configure PostgreSQL, on the importance of backups and testing them, etc.

But what about the server you run PostgreSQL on? We tend to pay a lot less attention to tools that you won’t need unless something breaks. But it’s worth taking some time to do so now, because that’s time you won’t have when your server is down and you’re in a rush.

SQL Feature Comparison

This comparison focuses on SQL features that can be used in SQL statements or self-contained SQL scripts that don't require additional software (e.g. a compiler) to be usable. Features for database administration or deployment are also not the focus of this comparison.

Building the DOM faster: speculative parsing, async, defer and preload

In 2017, the toolbox for making sure your web page loads fast includes everything from minification and asset optimization to caching, CDNs, code splitting and tree shaking. However, you can get big performance boosts with just a few keywords and mindful code structuring, even if you’re not yet familiar with the concepts above and you’re not sure how to get started.

How we tweaked Postgres upsert performance to be 2-3* faster than MongoDB

As we all know, relational databases are fine if you’re dealing with small amounts of data but for web-scale high performance high inserts speed and masses of queries per second, NoSQL is what you need. At least, that’s the conventional wisdom/hype surrounding NoSQL databases such as MongoDB. However as we’ve recently discovered this is very wrong indeed.

Painful Varnish mistakes

This post was initially titled "Top 6 Varnish mistakes", to echo Espen's blog. Even though his material is three years old, the content is still relevant. Plus, there's a healthy colleague competition going on here, and I can't just mimic Espen if I hope to beat him, so I had to do something different.

NULL in SQL: Indicating the Absence of Data

Categorias
Tropeçando

Tropeçando 78

Replicação: o que mudou

Detalhes das mudanças na replicação do PostgreSQL desde a versão 9.0 até a 9.6.

What the hell are Generics and would I want them in PHP?

So everyone is talking about this hip “new” kid on the block for PHP: Generics. The RFC is on the table and a lot of people are getting all excited about it, but you don’t fully see the excitement? Let’s explore what it’s all about!

The Easy Way to Setup PostgreSQL 10 Logical Replication

PostgreSQL workings in one picture

With the below illustration I attempted to capture key processes that encompass Postgres workflow. Here is a quick overview.

Speeding up Application Development with Bootstrap

Bootstrap is one of the best and most used HTML/CSS/JS front-end frameworks. Almost any web developer who has made a website or two has heard of this popular framework. It offers so many ready-made components and resources, Bootstrap can significantly speed up your application development.

Categorias
Tropeçando

Tropeçando 77

How to Measure Execution Time in Node.js

Design Pattern Workshop

Recently on the pgsql-performance mailing list, a question popped up regarding Postgres RAM usage. In this instance Pietro wondered why Postgres wasn’t using more RAM, and why his process was taking so long. There were a few insightful replies, and they’re each interesting for reasons that aren’t immediately obvious. Let’s see what is really going on here, and perhaps answer a question while we’re at it.

Ativando o Optimus NVIDIA GPU no Dell XPS 15 com Linux, mesmo na bateria

New Features Coming in PostgreSQL 10

Postgres 10 highlight - SCRAM authentication