Archive for the 'Programming' Category

Using Javascript to add elements to a page with class or ID

Wednesday, April 11th, 2018

There are times you might want to dynamically generate elements on a page and add classes to style them. You can create elements with ids and/or classes with plain Javascript with the following commands:

var newElement = document.createElement(“div”);
//to add a class:
newElement.setAttribute(“class”, “card”);
//to add an id
newElement.setAttribute(“id”, “id_name”);
//to add it to the body:
document.body.appendChild(newElement);
// or to add it to some element:
document.getElementById(“card-box”).appendChild(newElement);

You could also create the string for an element and attach it to the content of a div.

var newElement = '<div id="id_name" class="card">Some Content</div>';
 // This will replace the contents with your new element. 
document.body.innerHTML = newElement;

Sprite Starter Tutorial

Saturday, April 15th, 2017

There are times that you are going to want to add some imagery to your site. This would normally mean using many different image files which will increase the load time for your site. What if you could use a single image and display portions of that image throughout your site.

You could use use a single image called a sprite sheet. This single image file can hold many different images in different tiles for use through out your website. This allows you to load a single file to your page and adjust the viewport in different locations throughtout your site to display the images or icons you are using. Many major websites use this technique.

Let’s use an image like the following:
smiley_sad

The size of this image is 220px x 110px. Each tile of the grid is then a 110px x 110px image. So we need to allow for a viewport to this image that is the size of the tile.

The method we are going to use is a simple div element with the class of “sprite”.

<div class="sprite >
</div>

The CSS for this element will use height and width to define the size of the div. You could also create a placeholder image of the size you want your image to be that is a transparent png and place that inside the div, but that is not necessary.

This snippet is the CSS that we require to show the first image with the smiley face in the div. We specify a height and width for the div to create a viewport into a segment of the image. Next set the background of the div to the image url. The last step is to make sure that the image does not repeat.

.sprite {
width: 110px;
height: 110px;
background: url("http://etechtips.com/wp-content/uploads/2017/04/smiley_sad.png");
background-repeat: no-repeat;
}

In order to display the next image in the sequence you need to use the position properties of the background property. Using the hover pseudo class will allow us to demonstrate the change image update. In the hover property we only need to override the background property with a position offset of -110px in the x direction. Notice that we have used a negative to move the image to the left. The origin of this image is considered 0,0.

.sprite:hover {
  background: url("http://etechtips.com/wp-content/uploads/2017/04/smiley_sad.png") -110px 0;
}

If you used a larger image with more tiles you could scale in both horizontal and vertical directions to show more images.

Example:

If the example doesn’t show in the article, either visit the single page post or checkout this codepen: Smiley Sample

Due to a minor adjustment, I used an offset of -109px for this image or I got a slight shift of the image when I hovered. You should only see the shift of smile to frown when you mouse over the image.

The tiles can be uniformly the same size or you could try packing in many images of different sizes and shapes. Just make sure that you allow for the viewport to not display overlapping images.

Tags: ,

Useful Git Aliases

Thursday, March 9th, 2017

When you use git often, it is helpful to implement some aliases for frequent commands. Git has config options to allow for shortening commands or allowing you to use a simple command instead of a line of text that is difficult to remember.

Some simple shortcuts:
To make checkout shorter

git config --global alias.co checkout

This will allow you to just type:

git co

To make status shorter:

 
git config --global alias.st status

This will let you see the log with branch indicators and a graph of the branches:

git config --global alias.mylog "log --pretty=format:'%h %s [%an]' --graph"

This is similar to the mylog alias but is useful on a color terminal as it will highlight useful items in the comments:

git config --global alias.lol "log --graph --decorate --pretty=oneline --abbrev-commit ==all"

The results will be the following lines in your .gitconfig file:

[alias]
        st = status
        co = checkout
        mylog = log --pretty=format:'%h %s [%an]' --graph
        lol = log --graph --decorate --pretty=oneline --abbrev-commit --all

Tags:

MySQL: Connect from remote host

Monday, December 28th, 2015

I have been working on some projects and using my home server to complete some initial testing. I continually have issues connecting from my pc to the database. The remote IP on my VPN changes and I have the server pretty well locked down so need to add the current IP address to the access list.

The database name, user, remotehost ip address, and password are required to use the following command. One note, that you should probably not use the ‘root’ user or admin user when setting this command and insure that you do not leave the access on servers where there could be issues with security.

GRANT ALL PRIVILEGES
ON database.*
TO 'user'@'remotehost'
IDENTIFIED BY 'password';

This command has made it possible to connect using DB Visualizer which makes accessing the database very easy.

Learning Web Development with The Odin Project

Tuesday, July 14th, 2015

I have been working to up my skills in the web development arena and have to say that The Odin Project is a great place to get started. The lesson plan directs you to not just learn the different languages required to create for the web, but also what is going on in the computer when you do things. It also gives you information about how to connect with other developers and how to progress your skills.

Some of the projects teach you to create images with a group of divs and pure CSS like this example of the Dancing Android character.

Also learning to re-create the basic display of the Google Home Page helps to learn styling techniques, using sprites and how to position objects.

Some of the best ways to learn HTML design are to take a web page that you like and try to re-create it without looking at the styling. Once you have a good approximation, see where you differed from the original.

SQL: Shorten string to length

Tuesday, August 26th, 2014

I had a project the other day that required me to shorten a description down to a certain length and add an elipsis. The problem I encountered was making sure that the truncation did not happen in the middle of a word.

So using a Postgres database, I used the following query to return the shortened description without ending in a partial word.

select 
    case when length(long_description)>= 100
    then reverse(substring(reverse(left(long_description,100)),position(' ' in reverse(left(long_description,100))))) || '...'
    else long_description
    end
    from data_feed

The steps involved were to

  1.  Check if the field is over 100 characters,  if >100, then continue to step 2
  2.  Use left function to get 100 characters of the string
  3.  Reverse the string returned from left
  4.  Get a substring of the reversed truncated string from the first space (‘ ‘) to the end of the reversed truncated string
  5. Reverse the final string (So it is back to the correct direction of text)
  6. Append the ellipsis to the string ( or add a link or leave off if no extra chars are required)

 

Tags: ,

Install Python modules to a different directory

Saturday, February 22nd, 2014

There are times that I have wanted to install some Python module on a system where I did not have access to do so.
When you do not have permission to write into the standard library directories you
may need to run the “python setup.py install” command with the additional option of

 --home=<Some other directory>

make sure that this base directory has a lib/python directory within it and that you have
exported the PYTHONPATH variable to contain this directory.

Then simply run the command “python setup.py install –home=<Some other directory>” and your libs will
be installed.

Then you will need to make sure that your PYTHONPATH environment variable is always available
to whatever runs your scripts.

As an alternative to the PYTHONPATH, you can use the following within your scripts to target a non-standard python module directory:

import sys
sys.path.append("/path/to/the/module/directory")
## import any modules you have in your own directory

Using the method in the script allows you to make the scripts available to other users that may not have the PYTHONPATH setup.

Tags:

Counting lines, words and characters with wc

Thursday, February 13th, 2014

There is a simple Linux utility for counting characters, lines and words in files called wc. This allows you to give a file as an argument or a stream and get the counts of the aforementioned items.

wc <filename>

or

cat <filename> | wc

The options that wc accepts

-c,–bytes print the byte counts
-m,–chars print the character counts
-l,–lines print the line counts
-L,–max-line-length print the length of the longest line
-w,–words print the word counts

The ouput with no arguments will be three numbers (words,lines,characters. Otherwise the the number will reflect the argument you have passed.

And if you pass multiple filenames the output displays counts for all files and totals.

 >wc -l HelloWorld.java sample.txt
    8 HelloWorld.java
   25 sample.txt
   33 total

Tags: ,

HTML: Basic HTML5 page

Wednesday, October 23rd, 2013

This is where I start coding my web pages. This is a simple framework for an HTML5 web page. The DOCTYPE has been simplified and is supported by all major browsers even if they do not fully support the current HTML5 tags.

<!DOCTYPE html>
<html>
<head>
<title>My Sample HTML5 web page</title>
</head>
<body>
This is my sample web page.
</body>
</html>

Tags: ,

Postgres: Get table and field names from a given schema

Friday, February 8th, 2013

I work with a large Postgres install that has many hundreds of schemas. there are times that I need to find a list of tables and fields from a specific schema for a web application that I am developing.

This will return the list of table names within the giving schema:

select relname 
from pg_stat_user_tables 
WHERE schemaname='schema1';

Then to get the given field names from the table that I have chosen:

select column_name 
from information_schema.columns 
where table_name='mytable';

Tags: