Notes by Welling Guzmánhttp://wellingguzman.comNotes about code and among other things.Thu, 23 Aug 2018 10:53:13 +0000en-USUpgrading nodejs/npm on Ubuntu 14.04I was updating my site and everything was working correctly on my local machine, but as soon as it was deployed, the new code crashed the http server.

I noticed that the server has an outdated version of nodejs. Running a 0.x nodejs version while everything was created under 8.x.

After trying to update to a new version can be tricky as there's a tons of way documented on how to install it and easier on windows and mac systems.

How to install or update nodejs can be found on the package manager section of nodejs's downloads page.

This method also works for any Debian and ubuntu based distributions.

Update Source List

First, You would need to update your system package source list. Depending on the version you want to upgrade, there's different script that will try to update your source list.

NOTE: Be carefully, these are bash scripts and can execute dangerous code, if you are a little bit skeptical you can see the content first before you use it or you can read the manual installation

# Node.js v4
curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -

# Node.js v5
curl -sL https://deb.nodesource.com/setup_5.x | sudo -E bash -

# Node.js v6
curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -

# Node.js v7
curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -

# Node.js v8
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -

# Node.js v9
curl -sL https://deb.nodesource.com/setup_9.x | sudo -E bash -

# Node.js v10
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -

Install package

After the source list has been updated, the next step is installing the new nodejs version.

sudo apt-get install -y nodejs

Confirm

The last step will be to confirm the version installed are correct, or pointing to the right path as multiple nodejs can be installed in the same system.

Try running:

$ node -v
$ which node
$ npm -v
$ which npm

In conclusion you may want to have node and npm point to the right path. For example, you can look into /usr/bin or /usr/local/bin to make sure which node and which npm points to the right version.

]]>
Thu, 23 Aug 2018 10:53:13 +0000/notes/upgrading-nodejs-npm-on-ubuntu-14-04
Manipulating Pixels Using CanvasModern browsers support playing video via the <video> element. Most browsers also have access to webcams via the MediaDevices.getUserMedia() API. But even with those two things combined, we can’t really access and manipulate those pixels directly.

Fortunately, browsers have a Canvas API that allows us to draw graphics using JavaScript. We can actually draw images to the <canvas> from the video itself, which gives us the ability to manipulate and play with those pixels.

Everything you learn here about how to manipulate pixels will give you a foundation to work with images and videos of any kind or any source, not just canvas.

Read full article.

]]>
Sat, 21 Jul 2018 13:55:13 +0000https://css-tricks.com/manipulating-pixels-using-canvas
#100DaysOfEnglishAlong side with #100DaysOfCode I have decided I should practice my English for the next 100 days.

I learned english almost by myself. I was taught english at school, but the same thing for a decade, nothing useful at the long run. about 5 years ago I put myself into a intensive english course for grammar and allow myself to speak with people in english, since then I have not talk much.

I would say I am good at listening and reading, I read and listen english every day, but I write from time to time, and speak not very often (almost zero time).

My goals is to get used to speak and write english more often. The way I want to accomplish this is by writing every day or record myself talking or both.

I hope by the end of the 100 days I've improved my skill of communicate.

This will count as the first day.

Follow my progress on Twitter.

]]>
Thu, 10 May 2018 10:55:03 +0000/notes/hashtag-100-days-of-english
#100DaysOfCodeI found old codes I wrote more than a decade ago and realized how much I have learned so far, still there is a lot more to learn.

I feel bad when I have to search for a simple task, such as, how substring minus start position works? I have used it a lot of times and still forget how it works.

I used to create a lot of things, even useless app because I like to make things. Lately it has been different as I was believing I should act more "Pro" and just build things that matter and useful to at least a group of people.

I realized I should go back to my roots and create things just for fun. I don't have to worry about whether or not is perfect or useful just make things works and learn something new.

I have been thinking on challenging myself on coding a project each week or code something everyday for a n period of time, but I did not find any strong motivation until today.

Today I came across a tweet and a video that looked like it was directly written to me, these put the cherry on top and I decided to make the #100DaysOfCode challenge.

The rules are basically:

  • Code minimum an hour every day for the next 100 days.
  • Publish your progress

The goals will be create around 20 mini projects in the next 100 days.

Follow my progress on Twitter and GitHub.

]]>
Thu, 10 May 2018 10:33:22 +0000/notes/hashtag-100-days-of-code
Guzzle HTTP: Upgrade mocking from version 5 to 6Testing a http response with guzzle 5 was done using the Subscriber/Mock class, but on version 6, this class doesn't exists.

The way this mock response works is by attaching fake response objects to the http client, and on every request it will pick the result from the queue instead of making a real request to the server.

Guzzle HTTP 5

Let's take a look how mocking was done on version 5 in the example below:

// Guzzle http client
$client = new \GuzzleHttp\Client([
    'base_url' => 'http://localhost'
]);

// Create Mock
$mock = new \GuzzleHttp\Subscriber\Mock();

// Attach mocking subscriber to the client
$client->getEmitter()->attach($mock);

// Add response to a queue
$mockPath = '/path/to/raw/response.txt';
$mockContent = file_get_contents($mockPath);
$mock->addResponse($mockContent);

The content of /path/to/raw/response.txt is a raw http response.

HTTP/1.1 200 OK
Date: Wed, 15 Jun 2016 17:02:51 GMT
Server: nginx
Content-Length: 86
Content-Type: application/json; charset=utf-8

{"id":1,"active":1,"title":"Article 1","body":"Content","tags":"tags,tugs","author":1}

The next request the client makes it will pick the first response on the queue as the result.

You can add more responses to the queue, and make sure you the queue is not empty before you send a new request.

$mockPath = '/path/to/raw/http/response/file.txt';
$mockContent = file_get_contents($mockPath);
$mock->addResponse($mockContent);

Guzzle HTTP 6

On version 6 they removed the Mock class and introduce a new MockHandler class. docs.

We now need to create a http client and attach the MockHandler object as the client handler

// Guzzle http client
$handler = new \GuzzleHttp\Handler\MockHandler();
$client = new \GuzzleHttp\Client(['handler' => $handler]);

There is not way to access the handler, so you have to keep a reference somewhere.

Now all the response needs to be added to the mock handler using the append method.

// Add response to a queue
$mockPath = '/path/to/raw/http/response/file.txt';
$mockContent = file_get_contents($mockPath);
// Convert the raw http response into a Response Object
$response = \GuzzleHttp\Psr7\parse_response($mockContent);
$handler->append($response);

Same as previous version each request pull the first response from the queue on each request.

]]>
Sat, 31 Mar 2018 19:08:19 +0000/notes/guzzle-http-upgrade-mocking-from-version-5-to-6
Cocoa: Set the nib name on a view controllerWhen you create NSViewController and makes it the owner of a view nib, the controller and the nib has to have the same name otherwise the controller will fails loading the nib.

From NSViewController source file:

On 10.10 and higher, a nil nibName can be used, and NSViewController will automatically attempt to load a view with the same class name.

It is important to notice that even this comment states that will attempt to load a view with the same class name, it seems to be attempting the file name instead.

NSViewController -loadView comment:

Prior to 10.10, -loadView would not have well defined behavior if [self nibName] returned nil. On 10.10 and later, if nibName is nil, NSViewController will automatically try to load a nib with the same name as the classname. This allows a convenience of doing [[MyViewController alloc] init] (which has a nil nibName) and having it automatically load a nib with the name "MyViewController".

Having a controller with the name MyViewController and a view with the name MyView wouldn't work because the controller will attempt to load a nib with the name MyViewController. Naming a view MyViewController doesn't make sense because it is not a controller.

What should we do here? use the method -nibName to set the default nib name.

In your controller implementation file add the following method:

- (NSNibName)nibName
{
    return @"MyView";
}

NSNibName is an alias for NSString.

Now the controller will attempt to load MyView nib instead of a MyViewController.

]]>
Sat, 31 Mar 2018 1:06:32 +0000/notes/cocoa-set-the-nib-name-on-a-view-controller
Github: Re-authentication on Mac OSXTrying to interact with github, pushing mainly as it requires write permission from the user to perform such task, I was getting a 403 error, which means I am not authorized to push to that repository.

remote: Permission to directus/directus.git denied to WellingGuzman.
fatal: unable to access 'https://github.com/directus/directus.git/': The requested URL returned error: 403

For some reason this started to happen after I installed Github Desktop Application.

I don't know the reason why it got invalid or corrupted, but I did find a way to re-authenticate myself.

On Mac OSX Git uses the Keychain Access to store credentials information, you can either update or remove the credentials from the keychain.

Removing this information the next time you try to push it will ask you to enter your username and password

$ git push origin master
Username for 'https://github.com': wellingguzman
Password for 'https://wellingguzman@github.com':
remote: Invalid username or password.

Terminal

git credential-osxkeychain erase

Application

  1. Using the method of your preferences, Finder search, manually search the application directory or CMD (⌘) + Spacebar look for "Keychain Access".
  2. Search for "Github.com"
  3. Find and edit/remove the one that says to be "Internet password" kind, to make sure this is the one, open this entry and on the access control tab should says credentials-osxkeychain.
  4. After you are sure about this, edit or delete to get back your git access control.

Hope it helps, hope I can remember this next time.

]]>
Sat, 10 Mar 2018 16:25:06 +0000/notes/github-reauthentication-on-mac-osx
MySQL fetch table name with original caseMySQL provides a database with metadata and information about the server, such as list of all the tables in a database and columns data type.

Fetching a table information can be done with the following query:

SELECT TABLE_NAME, ENGINE, TABLE_COLLATION
FROM INFORMATION_SCHEMA.TABLES
WHERE
  TABLE_SCHEMA = "mydatabase"
  AND TABLE_NAME = "Products"

Result:

+------------+--------+-----------------+
| TABLE_NAME | ENGINE | TABLE_COLLATION |
+------------+--------+-----------------+
| products   | InnoDB | utf8_general_ci |
+------------+--------+-----------------+

This result is what we expected, the name, the engine and the collation. The problem comes when the table have uppercase letter, as the result always seems to be in lowercase.

I can't tell if this is a configuration issue or a mysql bug.

Making a the condition for table name twice solves the issue.

SELECT TABLE_NAME, ENGINE, TABLE_COLLATION
FROM INFORMATION_SCHEMA.TABLES
WHERE
  TABLE_SCHEMA = "mydatabase"
  AND (
    TABLE_NAME = "Products"
    OR TABLE_NAME = "Products"
  )

The query above will result with the table name in the original case it was created.

+------------+--------+-----------------+
| TABLE_NAME | ENGINE | TABLE_COLLATION |
+------------+--------+-----------------+
| Products   | InnoDB | utf8_general_ci |
+------------+--------+-----------------+
]]>
Wed, 14 Feb 2018 20:22:34 +0000/notes/mysql-fetch-table-name-with-original-case
MySQL string columns key lengthAfter changing the default charset from utf8 to utf8mb4 to support emojis on Directus, we started to received errors that the key was too long.

How can be too long if we only change the charset? one may ask.

First these are the errors I'm talking about:

#1071 - Specified key was too long; max key length is 767 bytes
#1071 - Specified key was too long; max key length is 1000 bytes
#1071 - Specified key was too long; max key length is 3072 bytes

It can be any of those errors depending on whether the table's storage engine is: MySIAM, InnoDb or InnoDb with innodb_large_prefix enabled.

TL;DR

utf8 charset requires only 3 bytes per character, while utf8mb4 requires 4 bytes. This means when you use utf8mb4 charset you have to use at most 191 characters in a string column.

191 characters x 4 bytes = 764 bytes which is less than the maximum length of 767 bytes.


String Storage

String storage size vary depends on whether the column is fixed-length or variable-length. It also depends on the charset, it takes more bytes to storage a japanese character than an ASCII/Latin letter.

As an example, CHAR is a fixed-length while VARCHAR and TEXT are variable-length.

All fixed-length data types uses all the bytes they were declared. For example CHAR(16), no matter what's its value, it's right padded with spaces to fill up to the specific length. On the other hand VARCHAR only uses 1 byte + the content size.

VARCHAR requires a prefix value of 1 byte to store the length of the string if the size is less than 256, otherwise it will uses 2 bytes.

One tip is not to use CHAR if you are not going to use all the characters almost all the time, because the size can pile up with empty strings column.

Character Set

The UTF8 character set uses a maximum of 3 bytes per character and only contains Basic Multilingual Plane (BMP) characters, which is the home of 65,536 characters (16 bits) from U+0000 to U+FFFF.

The UTF8mb4 character set uses a maximum of 4 bytes per character including all of BMP characters and Supplementary Multilingual Plane (SMP) which include another possibility of 65,536 new characters from U+10000 to U+1FFFF.

Emojis (Unicode characters)

UTF8 can support emojis, but not all of them. All of the new emojis are part of the SMP, so in other to support both basic and supplementary multilingual plane UTF8mb4 must be used.

The sparkle emoji (✨ U+2728) value is between U+0000 and U+FFFF then it can be used on utf8 charset, but the Woman Health Worker (👩 U+1F469) value which is not between U+0000 and U+FFFF, must use the utf8mb4 charset that range between U+10000 and U+1FFFF.

Index length

Now all the characters use 4 bytes instead of 3, so all columns that has more than 191 characters now uses more than 767 bytes, because 192 x 4 bytes is 768 bytes.

The options are removing the index, keep using utf8, add a length to the index key or reduce the length of the column.

Removing the index wasn't a good option, neither keep using the utf8. Reducing the length was possible because the columns will probably never met the actual length which is 255 characters, reducing it to 191 was optimal and in no way will harm the system.

Conclusion

Changing all string columns with length greater than 191 characters to 191.

If changing the length was not possible or desired option, changing the column index to only a chunk of x characters.

CREATE INDEX `index_name` ON `posts` (title(191));
]]>
Sun, 28 May 2017 20:06:14 +0000/notes/mysql-key-limit
Ubuntu missing package sourcesWhile trying to install Directus in an ubuntu server I got an error from a composer dependency that php5-mcrypt is not installed.

php5-mcrypt : Depends: libmcrypt4 but it is not installable

Running apt-get install php5-mcrypt didn't work.

Running apt-get update first didn't work either.

After some time figuring out what was the problem, I end up noticing that the source.list file was missing.

The next question would be where do I find the official ubuntu repositories? Luckily I found this generator where you can select a ubuntu release and all the repositories you need and it generates a source.list file.

Copying and pasting the new generate content to source.list file, and then running apt-get update, will updates the ubuntu package repositories.

Now apt-get install php5-mcrypt works.

]]>
Tue, 20 Sep 2016 4:22:34 +0000/notes/ubuntu-missing-package-sources
Zend DB select from a different databaseUsing Zend DB to select data from or use a table that doesn't belong to the adapter selected database, can be done by using TableIdentifier instead of a string as it shows below:

<?php
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\TableIdentifier;

$sql = new Sql($adapter);
$select = $sql->select();
$select->from(new TableIdentifier('table', 'database'));
$select->where(array('id' => 1));

$statement = $sql->prepareStatementForSqlObject($select);
$results = $statement->execute();
]]>
Mon, 09 May 2016 0:56:13 +0000/notes/zend-db-select-from-different-database
Run node app in background (Linux)Running a script in the background in linux can be done using nohup, using nohup we can run node application in the background.

$ nohup node /nodeapp/index.js &

Forever is another solution for Node scripts.

Installation

$ npm install forever -g

Usage

$ forever start /nodeapp/index.js
$ forever restart /nodeapp/index.js
$ forever stop /nodeapp/index.js
$ forever list

Kill Process

You can stop the process using the kill command as well:

First you need to know which process ID to kill, list all the process running node by running:

ps axl | grep node

The second column of your result is probably the PID, take that number and run the command below:

kill -9 [PID]
]]>
Thu, 28 Apr 2016 7:01:59 +0000/notes/run-node-app-in-background-linux
PHP - call_user_func referencePHP function call_user_func() does not pass parameter variable as reference. the code below won't work as expected.

From PHP documentation:

Note that the parameters for call_user_func() are not passed by reference.

<?php

function increment(&$var)
{
    $var++;
}

$a = 0;
call_user_func('increment', $a);
echo $a."\n"; // $a is equals to 0

In order to solve this problem call_user_func_array() must be used instead.

<?php
function increment(&$var)
{
    $var++;
}

$a = 0;

call_user_func_array('increment', array(&$a));
echo $a."\n"; // $a is equals to 1
]]>
Fri, 01 Apr 2016 10:49:12 +0000/notes/php-call-user-func-reference
Disable nginx basic_auth for one locationIf you protected your website with nginx basic_auth, and want to disable it for just one (or maybe some specific locations), you can use basic_auth off for that location and the authorization won't be required.

Example:

server {
  auth_basic "Restricted content";
  auth_basic_user_file /etc/nginx/.htpasswd;

  location /public/ {
    auth_basic off;
  }
}
]]>
Thu, 18 Feb 2016 2:19:21 +0000/notes/disable-nginx-basic-auth-for-one-location
sudo and redirect outputConcatenating two files in unix-like operative system can be done with a single line like these:

$ cat file1.txt file2.txt > newfile.txt

If permission is needed to create and write into new files in the specified path you must use sudo, so you do this:

$ sudo cat file1.txt file2.txt > newfile.txt

But that doesn't work because the output is handle by the shell and not sudo, and by that it means it won't let you create the new file returning something like this: -bash: newfile.txt: Permission denied. Note: This only happen when the current user doesn't have permission to create/write on the new file.

There's several solutions to this but a one-liner solution is to run a shell command inline:

sudo sh -c 'sudo cat file1.txt file2.txt > newfile.txt'
]]>
Tue, 16 Feb 2016 21:20:21 +0000/notes/sudo-and-redirect-output
"JavaScript" is as related to "Java" as ...Some people mix JavaScript with Java, thinking they are the same thing or one are based on the other.

There is a comparison that start with "Javascript is related to java as something is to some" is a clever and funny comparison to me.

So this would be a list of this comparison phrases:

  • JavaScript is related to Java as Hamburger is to Ham.
  • JavaScript is related to Java as Hamster is to Ham.
  • JavaScript is related to Java as Rocket is to Rock.
  • JavaScript is related to Java as Carnival is to Car. From YDKJS Books
  • More to come...
]]>
Mon, 25 Jan 2016 23:58:02 +0000/notes/javascript-is-as-related-to-java-as
Writing on the momentThis is probably has been said a lot out there, but I wanted to tell you this again, if you like to express an idea, a experience or simply want to share your thoughts, write it down while you got the momentum going.

If you love something and want to say how much you love it, say it while you love it, and when you stop loving it, you can share it again and compare saying why you stop loving it.

If you want to share something today, and if you are like me, there's a high chance that tomorrow you won't feel that spark that make you feel you need it to share something.

I want to share so much, but then I end up thinking, who wants to read this anyway, who will find this anyway. Don't be that person.

Don't be me and share your thoughts, it doesn't matter that you think it's worthless, someone will find it worth it.

I'm saying this not because I do it, because I don't, but because I've been on the other side as a reader, reading comments about how they hate the post AND the author, while I'm sitting here thinking why do they hate them, they are awesome and this content is great. The author probably is thinking is all true, because people who liked the content are not expressing their love to them and their content, but rather they just stare at how other people hate (or don't like) them.

Please, share your thoughts and let people know if you liked their content or not, but do not offend them, they can talk, if not, move along.

I'll take my own advice and do the same. Let's

]]>
Sun, 29 Nov 2015 0:51:55 +0000/notes/writing-on-the-moment
Twenty years of PHPYesterday 9 days ago it was PHP 20th birthday. Twenty years ago Rasmus Lerdorf released PHP 1.0, but it wasn’t until 8 years later when I had my first encounter with this language.

In 2003, I found out that anyone were able to make websites, that it wasn’t something just for big company to show their product and information. So started digging and searching on Altavista and Yahoo (Remember those search engine?), “where” and “how” do I start making websites.

I found Geocities, it was a great service from Yahoo. but as far as I remember it was only HTML, CSS, images and glitter, then I found Lycos, here I could upload PHP code and MySQL databases, it was all about CuteFTP and PHPMyAdmin. I uploaded CMS, forums, blogs (I think it were called news back then, don’t recall), and thousands of PHP scripts for any purpose, such as PHPNuke and PHPBB.

I didn’t know programming at all, but I loved how easy it was, you didn’t need to know OOP, just open a text editor and write some basic c-style code instruction and you are all set, no framework, no nothing.

I really learned how to program in PHP (or build websites) by analyzing for hours a pagination script, and since then I’ve been using and learning more and more PHP.

I’ve built so many sites, for different type of clients, I buy my first PC by selling my first website, a well-configured and customized PHP-Nuke script.

Until last year I thought PHP was death, but I realized that I was around different people, because I was surprised how many people still using php, so it makes go back to PHP.

I don’t mind the people who hate PHP and PHP Developers, the most common thing question I get after I say I’m a PHP developer is: “why?”.

PHP Comic

Thanks to PHP I got into Web Development, and I love it.

I would like to thanks: Rasmus Lerdorf, PHP core developers and the whole PHP community and web folks.

]]>
Wed, 17 Jun 2015 10:39:55 +0000/notes/twenty-years-of-php
Prevent line-break with hyphenated wordsWhen you got a paragraph in HTML and in there you have a word hyphenated and you want to treat it as a whole as one word, but then there's not much space and it gets broken in the middle.

This is what you should probably be getting:

This hotel is all-
inclusive

But you want this instead:

This hotel is 
all-inclusive

There is something you probably don't know is that there's a lot of differents hyphen- or dash‑like characters in Unicode. The hyphen we need here it's the non‑breaking hyphen (U+2011 or &#8209;).

Instead of using the regular hyphen (or minus hyphen) use the non‑breaking hyphen and you should be getting the correct result of treating the hyphenated word as a single word.

]]>
Wed, 25 Feb 2015 4:06:18 +0000/notes/prevent-line-break-with-hyphenated-words
GitHub: long diff problemThis is not something that would happen frequently, but when there a big change with lots of files and lines of code involved, GitHub will display a messages that says: "Sorry, we could not display the entire diff because too many files changed." and it will be hard to check all the files that were affected by that commit.

It would be nice if there was a option where you can hide the lines of code and only show the file names, so that way wouldn't slow down the browser performance, and we can see the files name quickly.

Because this still not a option available, we have Dev Tools and DOM Selectors, and when this happen I open the console and run this line of code:

// hides the content
$('.data.blob-wrapper').hide()

Here it's what it would ends up looking like this:

GitHub Diff

]]>
Sat, 07 Feb 2015 1:47:22 +0000/notes/github-long-diff-problem
Learn the proper namesSomeone asked me if I knew what Lambdas was, and quickly I answered: “I’ve heard that word before, but really don’t know what it is”.

It turned out that I do knew what it was, just didn’t know it was called Lambdas, for me Lambdas was a shiny Ruby only feature or something. But Lambdas are Anonymous functions, I use it everyday without knowing it was also called Lambdas.

]]>
Tue, 02 Sep 2014 3:35:24 +0000/notes/learn-proper-names
How to type ß (Eszett) on Mac OSHow to type this ß (Eszett) or weird-looking "B" as I knew it before in Mac and iPhone.

Mac OS

The "s" needs to be lowercase

alt/option/⌥ + s

iOS

Using the German Keyboard: here is how to add new keyboards

hold down "s" and choose it from the list

This is how it's going to look if you hold down the key on a uppercase "S"

Here is if you hold down lowercase "s"

Why is this weird-looking "B" under "s" instead of "B", well in fact it is because is an actual "long s" sound, also called sharp s.

What am I doing with this?

I started to seriously learn German, well, using Duolingo, Duolingo-serious, and while I have been using the app it never gave me a wrong answer using "u" instead of "ü" or "b/B" instead of "ß", but it started to giving me this as a wrong answer.

Notice the lowercase "s" in Schokolade.

]]>
Mon, 01 Sep 2014 21:35:07 +0000/notes/type-s-eszett-mac-os
Custom Post Slug collapse with Page Slug in WordPressChanging permalink on WordPress it's never, well at least it never gave me any headache, but when I change /blog/%postname%/ to just /%postname%/ some pages fell apart, and I was blaming the .htaccess, deleting it, recreating, let WordPress rebuild it, did a flush_rewrite_rules(); and nothing was fixed. Then I notice it was all the custom post slug that matches the page slug.

The site had three custom post, Films, Stories, Galleries, also for each custom post there is a page with the same name and slug which had a custom template, but I enter to thesite.com/films, thesite.com/stories or thesite.com/galleries it did not serve the right template, so I change thesite.com/films to thesite.com/filmz and it did work and serve the right template.

By seeing this behavior it has to be the custom post and his rewrite fault, this is part of the custom post:

<?php
'public' => true,
'show_ui' => true,
'has_archive' => true,
'publicly_queryable' => true,
'show_in_nav_menus' => false,
'exclude_from_search' => false,
'hierarchical' => false,
'menu_position' => 20,
'rewrite' => array('slug'=>'films'),
'supports' => array('title', 'thumbnail'),
'show_in_nav_menus' => true

There is three solution to this:

Solution #1

Change the slug, but this is a wrong solution if you already had theses indexed.

Solution #2

Change 'has_archive'=> true to false and the /films would be ignore by the custom post.

Solution #3

Do not use the custom page, and customize the archive-{$post_type}.php file and forget about the specific page for each one.

]]>
Fri, 01 Aug 2014 3:37:32 +0000/notes/custom-post-slug-collapse-page-slug-wordpress
MAMP MySQL ProblemUsing the library node-mysql I found myself with an error that refused my node app to connect to an MySQL Database or in fact the server itself. At first I blame the library, searching and searching and I didn't find any solution that leads me to fix error. Every time I tried a connection I always get the error : Error: connect ECONNREFUSED.


var mysql = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '123'
});

connection.connect(function(err) {
  if (err) {
    console.error('error connecting: ' + err.stack);
    return;
  }

  console.log('connected as id ' + connection.threadId);
});

So I wrote and issue and it was not a library issue, it was MAMP's MySQL bad configuration. There is two thing that can resolve this problem:

Solution #1

On MAMP disable Allow local access only.

Solution #2

run mysql_config --socket in the terminal and use the output as socketPath value


$ mysql_config --socket
/tmp/mysql.sock

Probably when you run mysql_config it would says:

-bash: mysql_config: command not found

In MAMP is located in: /Applications/MAMP/Library/bin/mysql_config so it would be:


$ /Applications/MAMP/Library/bin/mysql_config --socket
/tmp/mysql.sock

You can use alias or export to make this long path short.


var connection = mysql.createConnection({
  socketPath : '/tmp/mysql.sock',
  host     : 'localhost',
  user       : 'root',
  password   : '123'
});

Hope it helps in any way.

]]>
Sat, 19 Jul 2014 15:47:19 +0000/notes/mamp-mysql-problem
WordPress functionality in another PHP ProjectI'm working on a Project using Laravel and I need to pull all the blog post from a WordPress site that is already on the same server.

To do this and have the power of WordPress into another project, add the WordPress wp-load.php file.

<?php
$wordPressPath = '/wordpress/path/wp-load.php';
require $wordPressPath;

$args = array(
        'posts_per_page'   => 5,
        'orderby'          => 'post_date',
        'order'            => 'DESC',
        'post_type'        => 'post',
        'post_status'      => 'publish'
      );

$posts = get_posts( $args );

Something that could happen is that you have a function/class with the same name as WordPress has and this would thrown a function/class redeclaration error.

But aside from this, works perfect.

]]>
Tue, 13 May 2014 12:58:01 +0000/notes/wordpress-functionality-another-php-project
Subdomain on a different serverI want to develop my first Node.js applications and host it as subdomain, but this server (shared on hostgator) does not support Node.js applications, and for a second I thought if I need to change server only for this?. But nope, there is a solution for this.

What I want

  • Host a Nodejs application in subdomain (subdomain.wellingguzman.com) on a server that does not support nodejs.

  • Keep it like if it was hosted on the same server.

Solution

  1. Go to your hosting provider, and look for DNS Zone, on hostgator is under domains tab.

    zonadns

  2. Add a Record, put the Name of the host, or subdomain (subdomain.wellingguzman.com), there is possible two types you would need, type A or CNAME. If you want to point to an IP you need a type A, but if you want to point to a domain/subdomain you need CNAME.

    On Address/CNAME put the server's IP or subdomain, in my case the app is hosted on OpenShift and the CNAME would be something like nodejs-welling.rhcloud.com.

    TTL is Time to Live, amount of seconds the record cache would last.

    dnszone-filled

This would do the trick, and every time subdomain.wellingguzman.com is typed it would request nodejs-welling.rhcloud.com.

]]>
Mon, 12 May 2014 22:31:30 +0000/notes/subdomain-different-server
Control WordPress 404 ErrorI have site built with Wordpress and I wanted to catch all 404 page that Wordpress try to display and make my own custom 404 page depending on the requested page, or in fact I just wanted to whether or not show a 404 page.

If the user, let's say, go to http://mysite.com/someword on mysite, and if that is not a post/page it would probably display a 404 page, but I didn't want that behavior I wanted to search if someword is a category slug or a tag and display posts in that category or tag, otherwise would show the normal 404 page.

So, this is what I did, I added a action to template_redirect hook, that is executed before WordPress determine which page is going to be loaded.

<?php
add_action('template_redirect', '_custom_redirect');
function _custom_redirect()
{
  global $wp_query;

  if ( $wp_query->is_404() )
  {
    // Here I take over 404 page
  }
}

So now, I know when it's a 404 page, I need to get the string it was passed on the url, in this case someword, so I can check if the string match a category or a tag name with that name.

This string is stored in a array named query_vars with the key name. query_vars is a variable member of WP_Query which WordPress uses to execute the main query.

<?php
add_action('template_redirect', '_custom_redirect');
function _custom_redirect()
{
  global $wp_query;

  if ( $wp_query->is_404() )
  {
    $page_name = $wp_query->query_vars['name'];

    if ( ! $page_name )
      return;

    if ( ($category =  get_category_by_slug( $page_name )) )
    {
      // Here it found a category
    }
    elseif ( ($tag = get_term_by('slug', $page_name, 'post_tag') ) )
    {
      // Here it found a tag
    }
    else
    {
      // Is not a category or a tag
      return;
    }
  }
}

After this code WordPress would still "believe" it's a 404 page, I needed to add some more lines to changed this.

<?php
add_action('template_redirect', '_custom_redirect');
function _custom_redirect()
{
  global $wp_query;

  if ( $wp_query->is_404() )
  {
    $page_name = $wp_query->query_vars['name'];

    if ( ! $page_name )
      return;

    if ( ($category =  get_category_by_slug( $page_name )) )
    {
      // Here it found a category
      $wp_query->is_category = true;
    }
    elseif ( ($tag = get_term_by('slug', $page_name, 'post_tag') ) )
    {
      // Here it found a tag
      $wp_query->is_tag = true;
    }
    else
    {
      // Is not a category or a tag
      return;
    }

    $wp_query->is_404 = false;
    status_header( 200 );
  }
}

This is pretty much what I wanted to do, now I can get a tag or a category object if one exists, otherwise WordPress will keep its own process and will display its normal 404 page.

If I actually got a tag or category object, I need to query all posts under it.

<?php
add_action('template_redirect', '_custom_redirect');
function _custom_redirect()
{
  global $wp_query;

  if ( $wp_query->is_404() )
  {
    $page_name = $wp_query->query_vars['name'];

    if ( ! $page_name )
      return;

    $query_args = '';
    if ( ($category =  get_category_by_slug( $page_name )) )
    {
      // Here we found a category
      $wp_query->is_category = true;
      $query_args = 'category_name=' . $category->slug;
    }
    elseif ( ($tag = get_term_by('slug', $page_name, 'post_tag') ) )
    {
      // Here we found a tag
      $wp_query->is_tag = true;
      $query_args = 'tag=' . $tag->slug;
    }
    else
    {
      // Is not a category or a tag
      return;
    }

    $wp_query->is_404 = false;
    $wp_query->is_archive = true;
    status_header( 200 );

    query_posts( $query_args );
  }
}

If status_header( 200 ); isn't added the HTTP status will always be a 404, so this line change the status code from 404 to 200.

This is about it, but I want a little bit more, I want if is_category(); or is_tag(); functions are used, it has to return true. In order to make this to happen I needed to set a couple of variables more.

<?php
$wp_query->set('category_name', $category->slug);
$wp_query->set('cat', $category->term_id);

$wp_query->set('tag', $tag->slug);
$wp_query->set('tag_id', $tag->term_id);

$wp_query->set() will set a variable to query_vars array, which as I mentioned before is used by WordPress main query. With this variables set, when WordPress executes is_category(); or is_tag(); would have category or tag specific variable values to check if is a category/tag or not.

Final code

<?php
add_action('template_redirect', '_custom_redirect');
function _custom_redirect()
{
  global $wp_query;

  if ( $wp_query->is_404() )
  {
    $page_name = $wp_query->query_vars['name'];

    if ( ! $page_name )
      return;

    $query_args = '';
    if ( ($category =  get_category_by_slug( $page_name )) )
    {
      // Here we found a category
      $wp_query->is_category = true;
      $wp_query->set('category_name', $category->slug);
      $wp_query->set('cat', $category->term_id);

      $query_args = 'category_name=' . $category->slug;
    }
    elseif ( ($tag = get_term_by('slug', $page_name, 'post_tag') ) )
    {
      // Here we found a tag
      $wp_query->is_tag = true;
      $wp_query->set('tag', $tag->slug);
      $wp_query->set('tag_id', $tag->term_id);

      $query_args = 'tag=' . $tag->slug;
    }
    else
    {
      // Is not a category or a tag
      return;
    }

    $wp_query->is_404 = false;
    $wp_query->is_archive = true;
    status_header( 200 );

    query_posts( $query_args );
  }
}

This would be helpful too if you want to log/register/email requested pages that ends up being a 404 page.

NOTE: if you don't have any category or tag template page will returns a 404 page template, just take that in mind.

]]>
Tue, 21 Jan 2014 0:56:04 +0000/notes/control-wordpress-404-error
2014 GoalsLate Happy New year to everybody who is not reading this and won't be reading this until whoever knows how they get in here.

This year I am going to propose myself a list of goals that I want to or would like to have done by the end of year 2014 at lease.

This are the things I would want to do, but I probably won't

Examples/Portfolio

The thing I want the most is example of the things I've done or I capable to do. I hate myself when someone ask me: 'Do you know X?' and I say: 'yes, I do', and then they said: 'Ok, cool send me some examples of work you have done in X', I just draw a blank and start looking at old Hard Drives, Flash Memories, Old Mails, Dropbox, Google Drive and olds computer to find something and start to think: he/she won't believe me if I said I don't have anything to show, they will think I am lying. I don't blame them, I understand, I won't believe it either if someone tells me it knows something and doesn't have anything to prove that, for me it just BS. So, I'm telling BS too.

That's why I'm going to create a portfolio, a collection of examples to show my potencial and what I am capable of.

Write more

I like to write but I don't do it well, so I would like to write more in order to improve my writing skills (english and spanish by the way).

I'm going to write more, about everything it won't matter what, sometimes I don't write something because it was already been wrote, or it's a simple thing that everyone (I believe) knows.

I would turn this blog into a possible log of thing I'm working on or I've worked on and share my experiences.

Work on a Big Project

One thing that I would like to do, it's been on a BIG project, where I am not the "expert" or "the master of universe of that project", I just want to be part and learn from other leader and how to approach things, not the I want to be the one dude that doesn't contribute to anything just code, but learn how other people with more experiencies handle things on a big project.

By a big project I mean a project who involves Back-end, front-end, tons of users and/or page request, fully web-based app and everything is created In house.

Take JavaScript to another level

So this mean I want to use JavaScript more and not just query some element and changed its style, so this could change if I got a change to work on a Big Project.

Stay up to day on Web

I spent couple of months outside the 'Staying up to day' World due to work that had me busy and I was way behind already, the web is growing fast and I need to keep me updated.

I don't know how am I going to mesure this, but anyways.

Attend Conferences

Yup, that. I want to attend to more conferences In order to learn and help me to stay up to day.

By the way I went to The Ultimate Developer Event Boston 2013 it was an amazing Event, hope I can go next time.

Make a game

I am probably make the game Snake, but anyways I just want to do a complete game that can be play well, with menues and stuff.

Contribute to Open Source Projects

I would love to contribute or create open source projects.

Use CodePen

I've been looking at demos there since I don't know, it's been a while, and there some amazing example there that will blow your mind, anyways, so I am going to use CodePen to publish anything, whatever cross my mind, it's just to share some code and awesome example or weird stuff.

Publish on GitHub

When is something that is too big for CodePen or whatever, I will post it here, in GitHub

I would like to create some library or some code that would be useful for developer, so I hope I could write at least 2 cool new Repositories that would be helpful for many people.

]]>
Wed, 08 Jan 2014 17:58:30 +0000/notes/2014-goals
All I use as Web DeveloperI recently did a Mac OS X clean install, now I'm just going to install only application I need and commonly use, I always say that and end up doing it again installing and downloading bunch of things I don't need or even use, and full my computer of useless files that slow my machine down.

This post will also make me keep track of all I need/use.

Browsers

I always download all my browsers first.

Safari

Safari comes by default on Mac OS X.

Google Chrome

This is (by now) my favorite/default browser, is the first thing I downloaded on every new or new install machine, in other words if there not chrome installed, I install it right away. Go and download Google Chrome, just give it a try. If you are under linux you might want to check Chromium

So as a Web Developer I mostly use Chrome because of its DevTools. Chrome DevTools is an amazing tool for debugging web applications. Give Chrome Dev Tools a try.

Google Chrome Canary

Is Google Chrome but from the future.

As a Web Developer this is a good thing because you can test new features before it came to the official Chrome Release (Stable), sometimes this features come on Chrome stable version as experimental but some are not.

Firefox

The next browser is Firefox and as a Web Developer I use Firefox to check if the web app works on it, and playing around with 3D View.

Opera

I open up opera only for testing, so that as a Web Developer I use opera. Download Opera you need it if you are going to bet for the web.

Internet Explorer

Wut?

Text Editors/IDE

Well we need something to edit all our source code files, I use the following:

Sublime Text

Sublime Text, is a multiplatform text editor and can be customizable, has a lot of plugins, themes and color schema and support a lot of programming languages.

Coda

Coda, is a great IDE with a lot of built-in features including Full File Browser (FTP, SFTP, WebDAV, and S3) and MySQL Editor.

I used to Install TextWrangler, but sublime text fits all my needs.

Tools

iTerm2

iTerm is an alternative to Terminal, it supports split view that why love it the most.

Git

I use Git to control and manage all my source code. Read more and download Git, also check GitHub.

NodeJS

I do not really use NodeJS, but I need to install NodeJS in order to install some awesome tools like grunt.

GruntJS

Grunt is a javascript task runner that helps us to automate task, like copying files, concatenating files, adding css prefixes, compiling sass and much much more.

Bower

Bower is a frontend package manager, as its name stated, manage all our frontend packages, one command and Bower will install all dependecies for us automatically.

Yeoman

I've just used Yeoman couple of times, but this is a great tool/workflow that help us out creating new application boilerplates, Yeoman uses Grunt and Bower.

CodeKit

CodeKit is an amazing tool for Mac OS X that make Web Developer lives a lot easier, it compiles everything sass, less, halm, stylus, coffeescript, compass and more, combine and minify files, optimizes images, live page reloads and much much more.

Local Environment

MAMP PRO

This is a quick and easy way (click-next install) to set up on a Mac, Apache, MySQL and PHP. I need this to use/create/test PHP/MySQL locally on my machine.

phpMyAdmin

Yup, this is the tool I used for MySQL Database Management. It's written in PHP and comes with MAMP PRO.

Collaboration/Comunication

Skype

Skype, if you work with remote clients/team-mate, you need something to talk to them, Google Hangout is an option.

Wunderlist

Wunderlist, here is where I keep all my todo task, even outside Developing, like run out of Dr. Pepper. It also syncs in all my devices.

Oh have you not heard? It was my understanding that everyone had heard.

]]>
Mon, 07 Oct 2013 14:30:27 +0000/notes/all-i-use-as-web-developer
Getting my hands dirty on Chrome CanaryIf you want to have the newest features from Google Chrome, you must need to use Chrome Canary. Chrome Canary is updated almost everyday, it's mean would be fresh builds. It can run side by side with Google Chrome stable version, so you don't have to choose one of the two, one thing to know is that you can't use Canary as your default browser.

Although this is designed for Developers and early adopters, you should be aware this could crash sometimes even has more chances to if you are using experimental features.

This is a quick view of canary I did in a couple of hours to get my hands dirty, if you want to be ahead and test features that would be available later on Google Chrome check this out.

I have been seeing this Chrome gold icon for a while, wondering what it is, I just thought it was just kind a cool icon for Chrome and nothing else, but HEY! it's not, is your Google Chrome Browser from the FUTURE!, so now let's see what bring us.

First of all this is Version 31.0.1632.0 canary.

Visually Stuff

Now the first we notice when we open up Developer Tools is that now it organizes by tabs rather than grouped list-item, I do like this new way to handle this section now, you don't have to scroll all the way down looking for an specific section, it's worst when you have thousands of CSS declarations. Also metrics section was merged with styles section. We can see its difference in the image below.

In sources panel the paused exceptions buttons was moved from bottom bar to sidebar as you can see in the next image.

They removed Collect CSS Selector Profile from Profile panel.

DevTools Settings are now neat, it has smaller font size and more organized than before.

Features

Enough of visually things, now let's see what features I found:

Inspect DOM Element

The first thing I check was the popup menu from DOM Inspector.

Inspect DOM Element is a new option that come in handy when you want a quick access to a DOM element properties, this save us time because we don't need to go to console and query that element using jQuery or querySelector or any of those anymore, now it's just a click ahead.

EventTarget

In the properties tab of DOM inspector now included EventTarget which can tell us if the element can receive DOM events, even though the most common events targets are window, Element, and document which are the ones we commonly use.

Image0

Working with CSS Preprocessor

Now in canary we have CSS and Javascript source maps enabled by default, we don't need to enable Enable Developer Tools experiments to enabled this on the experiments tab.

This all I got, most of the features I was testing I later notice that it was already available to the current Google Chrome stable version, so all the new stuff on Canary or already available (on stable) I'm going to keep posting here.

Go and Download it here, it's only available for Mac and Windows, but if you are on linux you can check Chromium Dev Channel and have weekly updates.

Useful Links:

]]>
Wed, 18 Sep 2013 17:13:30 +0000/notes/getting-hands-dirty-chrome-canary