Skip to main content

Posts

Showing posts from July, 2015

PHP: Recording Page Hits

Wanted to create something that was easy to use, maintain and grow. It's extremely basic as it is. It stores the page visited and if the user is logged in, their id; if the user is not logged in, it currently stores "0" as the user id.

Later, this class might expand to store the user's browsing history by recording their IP address and the pages that they visit.

You'll first need to create 2 tables within your database: pages and statistics. You'll need 3 but I'll show you how to create two. The third one is users that you should probably already have if your users are logging in at all. Note: I'll show you how to create the ReportError class in my next post.

The pages stores the URI for each page. You don't want to store the page within the statistics table, just the id. This is for optimization and to minimize repetitiveness.


The next table is the statistics table. This table contains the id's referencing other tables and the times the p…

PHP: Main Controller Tweaks

I wrote about the main controller a few days ago. Looking at it now, I've decided to make one tweak that was necessary and one that's purely for performance (and to keep consistent).
To review the previous version, visit: http://dinocajic.blogspot.com/2015/07/php-main-controller.html
The main change done is to the processHeaders() method. When logging in or out, it's required that the SESSION and COOKIE creation and deletion is done before any information is submitted.

This is what the processHeaders() method looked like before:


And this is what the modified processHeaders() method looks like. As you can clearly see, the logout, the SESSION based login and the COOKIE based login are all processed through this method.


My thoughts on Climate Change

There have been so many studies done on humans' effect on climate change that the burden of proof shifts from the people trying to prove that it's real to the people that negate it.

For accurate information regarding climate change, visit:
http://climate.nasa.gov

Some stats for you:

Carbon dioxide levels in the air are at their highest in 650,000 yearsCarbon dioxide (CO2) is an important heat-trapping (greenhouse) gas, which is released through human activities such as deforestation and burning fossil fuels, as well as natural processes such as respiration and volcanic eruptions. As of June 2015, we're at 400.47 ppm (concentration of mid-tropospheric carbon dioxide in parts per million).The 10 warmest years in the 134-year record all have occurred since 2000, with the exception of 1998. The year 2014 ranks as the warmest on record.Sea level rise is caused primarily by two factors related to global warming: the added water from melting land ice and the expansion of sea water …

Breaking down Stress: How it forms and what it does

You might have noticed by now that I like to break down everything to it's simplest forms. Today, I'm tackling stress. The following document contains a series of paragraphs that I believe best helps explain the phenomenon.

"Stress is simply a reaction to a stimulus that disturbs our physical or mental equilibrium. In other words, it's an omnipresent part of life. A stressful event can trigger the “fight-or-flight” response, causing hormones such as adrenaline and cortisol to surge through the body. A little bit of stress, known as “acute stress,” can be exciting—it keeps us active and alert. But long-term, or “chronic stress,” can have detrimental effects on health. You may not be able to control the stressors in your world, but you can alter your reaction to them. Cortisol is a steroid hormone, belonging to a broader class of steroids called glucocorticoids, produced by the adrenal gland and secreted during a stress response. Its primary function is to redistribute …

Microsoft Word Mail Merge

Mail Merge is extremely simple in Word 2010 however it seems that because I don't use it as often, I always have to dig around and find out how to use it. Here are the step-by-step instructions on how to easily do mail merge.
1. Create an Excel Sheet with headers in the top row (i.e. Name | Address | Street | ST | Zip) 2. Populate the Excel sheet with the content. Save upon completion.

3. Open Word 2010 4. Click the Mailings tab.

5. Click Start Mail Merge and select Labels.

6. Select Label Vendor (i.e. Avery) and select Product Number (i.e. 5160 Easy Peel Address Labels). Click OK.

7. Click on the Select Recipients and select Use Existing List.

8. Browse and find your Excel Sheet and Click OK. Make sure that First row of data contains column headers is checked.

9. Make sure that your cursor is in the first label (the one that is empty and doesn't contain the <<Next Record>> tag).

10. Click Insert Merge Field and select the Labels that you want (i.e. Name, …

PHP: The Main Controller

Last time I wrote about using the index.php page as the gateway to the main controller:
http://dinocajic.blogspot.com/2015/07/php-using-indexphp-as-your-main.html

Since it's a secure habit to place all of your code outside of the visible directory (outside of the www or public_html folder), I've created a class that index.php directs all of the information to and that class is the one that actually processes everything.

Breakdown of the Main class
All files included in the beginningAll required classes instantiatedIn the __construct(), the redirect is called to push all domains to a specific domain nameDue to the amount of times certain hacks are attempted on the server, I've decided to place some of the common ones in the preventHack() method and prevent them before any other code is called.The available pages that the website contains are populated into an arrayHeaders are processed. i.e. Logs the user in if $_COOKIE's are setPrevious page is recordedCurrent page is st…

PHP: Using index.php as your main controller

For a normal sized website you can use one page as your point of entry and retrieval of all of your pages. In the following example, I've created a class called IndexController that tests whether we're on a test server or not (to display errors or not) and then calls the class that will process the ?page $_GET variable.

PHP Pagination

The Pagination class is one that always gives me trouble when using someone else's code. I've created this class and hopefully have documented it enough for you to jump right into it.
All you'll need to do is add the following code to the class that you're using: Instantiate the Pagination classAdd the $per_page variable and set it to how-many you want to display per pag.i.e. $per_pag = 20;Call the getStartAt() method to create the int from where the sql query will begin. This is the query that calls your items to be displayed to the page and really has nothing more to do with the rest of the pagination: $start_at = $this->_pagination_obj->getStartAt($per_page);$sql = "SELECT vehicle, image FROM customer_rides WHERE approved = '1'";$sql .= " AND brand = 'XX'";$sql .= " LIMIT $start_at, $per_page";At the end of the code, you'll need to call the createPageNumbers() method and pass the sql code to select the number of…

JavaScript Redirect

When I need to redirect the user after the headers have been sent in PHP, I use JavaScript. I have a frequent code class that stores methods like this.

The following method, redirect(), contains 3 parameters:

$timeTime to stay on current page before redirecting. i.e. if you want to display a message and redirect in 5 seconds$locationThe page where you're going to be redirecting the user toi.e. index.php$folder_one_upIn case you want to use this from a folder within the directoryi.e. somewebsite.com/admin/Note. You can create an additional parameter, such as $level to indicate how many folders deep your script isi.e. somewebsite.com/admin/manager/

Beginner Java Exercise: Check Palindrome

A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. Allowances may be made for adjustments to capital letters, punctuation, and word dividers.

In this simple exercise, we're going to be checking for palindromes.

Examples of palindromes:

noon
moon noom
14455441

The program prompts the user to enter a sentence or a word. It then calls the isPalindrome() method to check whether the word is actually a palindrome. It sets two variables, low and high to 0 and the length of the string - 1 respectively (remember that the string starts at 0; that's why you need the -1).

It compares the two characters at low and high locations. If at any point through the iteration the characters at the low and high locations do not equal each other the isPalindrome() method will return false.

Fear

The definition of fear is as follows: "an unpleasant emotion caused by the belief that someone or something is dangerous, likely to cause pain, or a threat."

It's definitely a strange feeling to know that something doesn't exist yet your FEAR takes over. I'm here to break it down into chemical terms on what exactly occurs when you watch that scary movie and are afraid to take a shower afterwards. I'll also explain the different types of fear.

"In humans and animals, fear is modulated by the process of cognition and learning. Thus fear is judged as rational or appropriate and irrational or inappropriate. An irrational fear is called a phobia.

Fear is closely related to, but should be distinguished from, the emotion "anxiety", which occurs as the result of threats that are perceived to be uncontrollable or unavoidable. The fear response serves survival by generating appropriate behavioral responses, so it has been preserved throughout evolution.

A Simple PHP Class

Not all PHP classes have to be complex. Below is an example of a simple PHP class depicting the About Us page. I'm not going to list the other parts that are needed to make the class work, just the class itself to demonstrate that with enough planning certain classes can look exactly the same way.


Looking at the code, you'll notice that the displayBreadcrumb() method can be separated into it's own individual class as well (or frequently used code class) and an array of crumbs can be passed as the parameter with the key set to the name of the page and the value as the link to that page.

The return of Confederacy in Modern Times

It seems like most wars end the same way: as a cease-fire, but the hatred continues. Recently there has been quite a significant amount news-coverage on bringing down the Confederate flags and eradicating the nation of any symbols related to the Confederacy; I couldn't agree more.

Most people need a refresher on the Civil War that occurred here.

"The American Civil War, known in the United States as simply the Civil War as well as by other sectional names, was a civil war fought from 1861 to 1865 to determine the survival of the Union or independence for the Confederacy. Of the 34 states that existed in January 1861, seven Southern slave states individually declared their secession from the United States and went on to form the Confederate States of America. The Confederacy, often simply called the South, grew to include eleven states, although they claimed thirteen states and additional western territories. The Confederacy was never recognized diplomatically by a foreign cou…

Blood Oxygenation Process

One of my favorite topics when I was studying pre-med was the oxygenation process.

The purpose of this article is to see if I still remember it. The picture will be added after I finish writing it.

De-oxygenated blood would come in from the body to the Superior and Inferior Vena Cavas. It would enter the right atrium, flow through the tricuspid valve into the right ventricle, up through the pulminary valve into the and into the pulminary arteries going to the lungs. Once oxygenated, it would flow back through the pulminary veins and into the left atrium, through the mitral valve, into the left ventricle, up through the aortic valve, into the aorta and to the body where it oxygenates the cells.


PHP User Authorization

In the previous post regarding Authorization, I wrote about the portion that deals with returning users.

To reference that post visit:
http://dinocajic.blogspot.com/2015/07/php-user-authorization-returning-users.html

This one completes it.
Start with main()It double checks to make sure that the username $_SESSION is not set. If so, it redirects the user to the main page. By redirecting, the script that was written in the previous post is called to log the user in..It checks for form submission.If not, call form() methodChecks form fields and sanitizes the contentIf there were errors, display form() method with errorsIf everything is good, log the user in through the logUserIn() methodIf not successful, display error message and call the form() methodIf it made it to this point, the cookie and session are setUser is redirected to the main page

Beginner Java Exercise: Accessing Private Data Fields

To prevent tampering, sometimes it's necessary for data fields to be declared as private in a class. If you attempt to access a private data field from a client, a compile error will occur. In the following example, we have a two classes: CircleWithPrivateDataFields.java and TestCircleWithPrivateDataFields.java.

In CircleWithPrivateDataFields.java, the radius and numberOfObjects are private data fields. To access them you do so with a get method (getter or accessor). You'll just append get to the property name and finish it off with () to create a method: i.e. getNumberOfObject().

If the data field is a boolean type, you'll need to use "is" instead of "get."

To modify the private data field, you'll need a set method. Same concept as above except you replace get with set: i.e. setRadius().

In the following example we also use the keyword "static." All that means is that the value is accessible without instantiating the class, is not bound t…

LHC Discoveries

While most websites are reporting on the latest celebrities news, I was pleased to see that a few news agencies were reporting on the newest LHC discovery. The LHC has just discovered the pentaquark particle, a particle whose existence was theorized 50 years ago.













"A quark (/ˈkwɔrk/ or /ˈkwɑrk/) is an elementary particle and a fundamental constituent of matter. Quarks combine to form composite particles called hadrons, the most stable of which are protons and neutrons, the components of atomic nuclei. Due to a phenomenon known as color confinement, quarks are never directly observed or found in isolation; they can be found only within hadrons, such as baryons (of which protons and neutrons are examples), and mesons. For this reason, much of what is known about quarks has been drawn from observations of the hadrons themselves."

"A pentaquark is a subatomic particle consisting of four quarks and one antiquark bound together. As quarks have a baryon number of +1⁄3, and antiq…

Beginner Java Exercise: GUI Components

An easy transition into creating more visual programs that we're so accustomed too. The following code contains a few form-type fields. We'll first create the form fields, then add them to the panel and then add the panel to the frame.

The code is really simple and extremely easy to follow. Reference the notes for an explanation.


An individual's dream

I'm writing this one exclusively for myself. I enjoy re-reading my views and opinions; I want to see how much they change. I hope this one doesn't.
What should be an individual's dream? There are some common responses such as good health and a strong family structure. I'm dedicating this article to money. Why are people so obsessed with it? Why do people that achieve it strive for more? Why do countless celebrities commit suicide when they have everything that we strive for?
The key to happiness then is not an endless amount of money. For me, it's simply having enough that you don't have to think about it. Every person will feel differently about how much is enough depending on where they live, what kind of dreams they have, etc. The more you think about what you would like to have, the more you realize that most of those things are pure over-kill and will not bring you any additional joy. 
All I strive for is to be able to provide for my family, make their drea…

My favorite God Arguments

As I was writing my last article, I included so many God arguments that I later decided to remove them and post them in a separate article.

Without delay, here are some of my favorite God Arguments.

1. I know God exists. If you disagree, prove otherwise. Oh you say you can't prove God doesn't exist? That's because you know he does!

Extraordinary claims require extraordinary evidence. This is the way the real world and science work. When you say God exists, you are making an extraordinary claim; therefore, the burden of proof is on you to back up your claim. A position that God doesn't exist is not a "belief," it's the standard position we all start out with until we're indoctrinated into religious schools of thought. People aren't born believing in Jesus. They start out atheist: lacking belief. There is no counter-claim necessary. Nobody has to prove the tooth fairy doesn't exist either.

2. The vast majority of the world believes in God. This su…

Religion in Schools

I'm going to start off by stating some facts. If you've read my previous blogs, you may think that I'm committing the "Appealing to Authority" fallacy, however, it's simply stats that I believe to be necessary to continue.

Just a reminder,
APPEAL TO AUTHORITY: (ipse dixit also called ad verecundiam sometimes) attempts to justify an argument by citing a highly admired or well-known (but not necessarily qualified) figure who supports the conclusion being offered.

I recently watched a presentation by Neil deGrasse Tyson. He states the following:
"Ninety percent of uneducated American are religious. The amount of educated religious people: 60%. These are people with Graduate Degrees.  How many scientists in America are religious? About 40%. A graduate degree in any subject, gets you half-way there. Science is an increment from the overall educated people. Now you go to the Elite Scientist, 7% are religious. Here's my concern, when you're educated and…

Beginner Java Exercise: Objects and Classes

I like to define a class as a collection of common items that make-up an object's functionality. You'll also hear definitions like, "a class is the blueprint from which individual objects are created."
We'll create a class called TV. The TV class will have regular TV operations such as Turn On, Turn Off, Volume Up, Volume Down, Channel Up, Channel Down, Set Channel and even Set Volume.

We'll then instantiate that class from the TestTV class.

You may notice that in order to instantiate the TV class, we set the data-type as the class name:
TV tv1 = new TV();

"A class is essentially a programmer-defined type."

Fun Fact: Arrays in Java are treated as objects.

The code should be pretty straightforward.

Overview of TV.java:
Initialize the channel variable and set it to 1Initialize the volumeLevel variable and set it to 1Set the on variable to false so that the TV is in the default off position.turnOn() method to turn the TV onturnOff() method to turn the …

Ad Hominem

One of my favorite fallacies: the ad hominem attack. "An ad hominem (Latin for 'to the man' or 'to the person'), short for argumentum ad hominem, means responding to arguments by attacking a person's character, rather than to the content of their arguments."

Types of ad hominem

abusiveattack the person instead of the argument ("Only a cold-hearted Scrooge would cut this program!")circumstantialattacking the circumstances of the person ("How can you be against relaxing immigration policies. Your grandparents came over from Italy!")tu quoque ("you, too")AKA "practice what you preach." ("Why should I follow this Java style guide? You write pretty sloppy code yourself!") You'll notice this tactic used by politicians constantly. It diverts the attention from what the person can do and focuses on his or her personal characteristics. And that's why I can't listen to political debates.
"The worst th…

Pascal's Wager

The following lists a few of my favorite Pascal's Wager arguments. It states that all humans bet their lives that God either exists or doesn't.

"Blaise Pascal is a seventeenth-century French philosopher, mathematician and physicist. Pascal formulated the wager within a Christian framework. The wager was set out in section 233 of Pascal's posthumously published Pensées ("Thoughts"). These previously unpublished notes were assembled to form an incomplete treatise on Christian apologetics.

The wager uses the following logic:

God is, or God is not. Reason cannot decide between the two alternatives.A Game is being played... where heads or tails will turn up.You must wager (it is not optional).Let us weigh the gain and the loss in wagering that God is. Let us estimate these two chances. If you gain, you gain all; if you lose, you lose nothing.Wager, then, without hesitation that He is. (...) There is here an infinity of an infinitely happy life to gain, a chance of…