Monday, September 10, 2018

How do I convert to/from 24-hour time and AM/PM time in PHP?

In databases, times and datetimes may be stored as "13:30:00" or "1984-05-01 15:45:59".

But you may want to convert this to something that displays with AM/PM, or maybe you want to collect a time that is AM/PM and store it according to your DB schema.

You can display 24-hour time in AM/PM with...

print date('G:ia', strtotime("13:30:00"));

And a 24-hour datetime with in AM/PM with...

print date('Y-m-d G:ia', strtotime("1984-05-11 13:30:00"));

If you wanted to go in the opposite direction, and display an AM/PM time with 24-hour time...

print date('H:i:s', strtotime("1:30 AM"));

And if you want to display AM/PM datetime in 24-hour datetime format...

print date('Y-m-d H:i:s', strtotime("1:30 AM"));

Sunday, September 9, 2018

How do I evaluate a Mathematical Expression or Formula in Java?

You may have an expression like "1900 + 84" that you want to be evaluated, to something like "1984." You can do that easily in Java.

Make sure to import the correct packages...

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

In main(), you will need to instantiante the evaluators with...

ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");

And then you can use this engine by means of this...

System.out.println(engine.eval("1900+84"));

Note that this is a script-evaluator, so "100;1900+84" will result is just 1984. Additionally, you will want to cleanse any input that may be placed into engine.eval(), especially if you are working on a web-server.

Saturday, September 8, 2018

What are the Best Practices for Database DateTime Storage?

Dates are datetimes are common values that coders are going to want to save. But what is the ideal format?

With MySQL, you have the options of Date (default "0000-00-00"), DateTime (default "0000-00-00 00:00:00"), and even Year ("default "0000").

Any of these should fit your purposes for storing recent data. The only limits are that Date and DateTime cannot store years older than 1000, and Year has even smaller range of valid values.

There are advantages to storing dates this way: timezones are built-in to MySQL which can be applied or unapplied easily, the data is fit into as few bits as possible to get you the best storage, you can always sort by using the "greater than" or "lesser than" operators, etc..

Some people store this value as a string. But that is quite a bit more data to hold into the system, and it will accept invalid date/datetime values. This should be avoided.

Some people store this value as an integer, using the epoch time schema. But epoch time is timezone-less, and there will be no way for MySQL to be able to adjust or unadjust this time for timezones. This should be avoided.

Use MySQL's Date or DateTime.

Friday, September 7, 2018

How do I change an Element's Class in JavaScript?

You can manipulate an element in jQuery by selecting it by its class, like so...

$(".SomeElementClass").SomeAction(...)

The period here indicates that "SomeElementClass" will match on elements like this...

<element class="SomeElementClass">

If you want to change the class, things can become a bit more tricky, but it is very possible...

const element = $('.SomeElementClass');
element.classList.remove('SomeElementClass');
element.classList.add('BrandNewClass');

Now, when looking at the DOM, your element will now be...

<element class="BrandNewClass">

The same approach can be used to change an element's id attribute, as well.

Thursday, September 6, 2018

Why Custom-Delimited Data Sets are Bad and Should Be Avoided

With MySQL and other database options, you can store data to fields for tables. And sometimes, people are tempted to store a list to a field, like this: "1,2,3,4,5".

When the coder of this needs to go over the list, they retrieve it from the database, break it up by the commas using explode() or split(), depending on the language, and then iterate over the list.

There are a number of reasons why this is a problematic approach to whatever you're trying to solve.

The problem is that you need the whole list every time you want to do something with it.

Want to count how many 1's or 2's or 3's in the list? You must loop over the entire list.

Want to get only numbers when they are 4 or 5? You must loop over the entire list.

Want to delete just one value? Want to delete values greater than 5? Loop the list, loop the list, loop the list, and that's a lot of looping.

Besides performance issues, there are technical limitations.

How do you guarantee that something like "skyscraper" doesn't show up in your list of numbers? How do you escape characters like your delimiter (a comma in this case), which may appear in words, like this list: "barn", "skyscraper", "appartments, condos, etc."?

These performance and technical issues mean that few programmers actually implemented delimited lists. So, if you're going to use it in your project, it's going to be something that new people need to stress over and re-learn, when there are many more commonly accepted practices that solve this problem.

Wednesday, September 5, 2018

Importing or Including Other JavaScript Files from Your JavaScript Code

You may have multiple JavaScript files, and you want them all to be included within one page. Normally, that would be several script tags at the head of the document, like so...

<html>
<head>
<script src="MyScript.js"></script>
</head>
<body>
</body>
</html>

But, you may need to determine the name of the JavaScript file you need using JavaScript ocde itself. For instance, you may not be certain that you need MyScript.js, unless the user is logging in through a certain service.

With jQuery, you can include the file very cleanly and with high browser-compatibility. From your JavaScript source library, run this command...

$.getScript("MyScript.js", function() {
console.log("Script loaded!);
});

If you just want to use JavaScript, and nothing else, then you can get away with adding an element of the script type...

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "MyScript.js";
document.appendChild(script);

Then MyScript.js will have been loaded and is then available for use in the local, calling script.

There are a number of other options for handling this: ES6 options, AJAX query options, Node.JS packages, etc., but these are the simplest approaches.

Tuesday, September 4, 2018

What is a stacktrace? How do I use a stacktrace to debug my code?

A stacktrace is a list of all the functions and all the files called at a particular point in a piece of code. It may be generated by a programming exception (a runtime error), a break-point, or simply by developer-triggered logging.

If your code crashes, this is useful because it will tell you everywhere that code executed in order to produce the error. Generally, these are good places to start looking for finding a solution to the bug.

Take a look at this PHP error stacktrace...

Stack trace:
#0 /home/anarchocommie/classes/Format/HTML.php(181): users->viewuser()
#1 /home/anarchocommie/classes/Networking/Handler.php(536): HTML->Display()
#2 /home/anarchocommie/classes/Networking/Handler.php(520): Handler->HandleRequest_Content_Format()
#3 /home/anarchocommie/classes/Networking/Handler.php(458): Handler->HandleRequest_Content()
#4 /home/anarchocommie/revoltlib.com/index.php(9): Handler->HandleRequest()
#5 {main}

In this particular stacktrace, index.php was first called (at line 9 in index.php), which then called Handler->HandleRequest(), then Handler->HandleRequest() called Handler->HandleRequest_Content(), and then Handler->HandleRequest_Content() called Handler->HandleRequest_Content_Format(), and then Handler->HandleRequest_Content_Format() called HTML->Display() -- and so on.

Using a stack trace like this, you can find out how and why your errors occurred.

Monday, September 3, 2018

Why is document.write() a bad coding decision in JavaScript?

If you want to send content to a browser, there are many options. But one of them that you should avoid is document.write(), which may appear as...

document.write("<html><body>Hello!</body></html>");

This is considered poor form for a number of reasons.

First, it completely overwrites all content on the page with whatever is given to the write() function. So, if you have any other HTML on the page, it will disappear.

That means that all future coding and development needs to be done with this document.write("") function, and that's just an unnecessary complication.

The real problem is that it's difficult to work with. A coder using document.write()'s all over their script will take much longer to finish than one who is using proper DOM manipulations (like using element.innerHTML(), jQuery's append(), etc.).

There are also technical problems: XHTML does work with document.write("").

There are also security problems: Google Chrome will refuse to run document.write("") if it contains anything in the write("") which was from a POST or GET query, or if it suspects that any cross-site scripting injection is taking place.

There are also performance problems: Google Chrome itself will give the warning that document.write("") may slow down your webpage by "tens of seconds," according to the Google Developers blog (https://developers.google.com/web/updates/2016/08/removing-document-write).

Sunday, September 2, 2018

What is the maximum length of a URL in a browser?

Since the web runs on links, it is worth while to know the max length of a link : there is no limit at all in the specification. But, browsers will have limits.

The exact specification reads :

Servers MUST be able to handle the URI of any resource they serve, and SHOULD be able to handle URIs of unbounded length if they provide GET-based forms that could generate such URIs.

(Source: http://www.faqs.org/rfcs/rfc2616.html)

However, Microsoft Internet Explorer only can handle around 2,000 characters. (Source: https://support.microsoft.com/en-us/help/208427/maximum-url-length-is-2-083-characters-in-internet-explorer)

More than that, a webpage whose url is 2,000 characters will take longer to load than one whose length is 20 characters. At the very least, because your computer needs to download 1,980 characters less.

In terms of networking, domain lookup times, or file lookup times, longer names similarly slow things down. Additionally, search engines dislike overly long URLs, so, if SEO is important, try to keep to a limit of 100 or fewer characters.

Saturday, September 1, 2018

Difference between Single-Quoted and Double-Quoted Strings in PHP

There are two types of quoted strings in PHP: single-quoted and double-quoted.

With a single quoted string, characters using by PHP to define a string must be escaped, like so...

$stringa = 'hello, \'friend\', how are you?'; // string: hello, 'friend', how are you?
$stringb = "\\file\\directory\\location.php"; // string: \file\directory\location.php

But you may also have a double-quoted string, which means that the content is more dynamic, like so...

$stringc = "hello, $friend"; // string: hello joe, ann, tom, etc..
$stringd = "where are all the ${type}s?" // string: where are all the friends? books? beers?

Single-quoted strings always execute much faster than double-quoted strings. But there are things in double-quoted strings that cannot be done by single-quoted strings alone. They will need concatenation, like so...

$stringe = "hello, " . $friend; // string: hello joe, ann, tom, etc..
$stringf = "where are all the " . $type . "s?"; // string: where are all the friends? books? beers?

If you are using single-quoted strings, you only get this performance boost by using apostrophes ("static strings", AKA: Single Quoted Strings), and not by using the quotes ("interpolated strings", AKA: Double-Quoted Strings).