tv show ed with tom cavanaugh - Extensions
When will the TV Series 'Ed' with Tom Cavanaugh and Julie Bowen ... They are close for season 1 but are still working on the music rights which can take time. "ED" was also produced by two different companies so that . http://askville.amazon.com/TV-Series-Ed-Tom-Cavanaugh-Julie-Bowen-purchase/AnswerViewer.do?requestId=5253114
You can develop your own extensions
using the negative reactions to control mechanisms.
Syntax-Highlighting Addons
Ed (TV Series 20002004) - IMDb With Tom Cavanagh, Julie Bowen, Josh Randall, Jana Marie Hupp. Ed Stevens is a . TV Shows I have watched at least an episode in my lifetime. a list of 806 . http://www.imdb.com/title/tt0247091/
tom cavanaugh | Tumblr So umm, i feel like I'm the only one in the world who's heard of the show Ed. . Michael Ian Black (The State, Stella, Viva Variety) and Tom Cavanaugh (Ed) eat . http://www.tumblr.com/tagged/tom%20cavanaugh in one installer (526 kb).
Amazon.com: Ed: The Complete First Season: Tom Cavanagh, Julie ... Amazon.com: Ed: The Complete First Season: Tom Cavanagh, Julie Bowen, . Its been like forever and other TV shows are coming out before Ed. Ed was a . http://www.amazon.com/Ed-The-Complete-First-Season/dp/B00005JNS4
Project Free TV :: Ed Ed Links and Full Online Videos. . mid-logo-free-tv-show-series-movies-online- . Tom Cavanagh plays Ed Stevens, a hot shot New York City lawyer, who, . http://www.free-tv-video-online.me/internet/ed/
Stuckeyville's Journal If anyone is interested, I made a finetune playlist of music from Ed. It is . My Exclusive Advance Review of the New TNT Show Trust Me (Starring Eric McCormack, Tom Cavanagh, Monica Potter
) My Q&A Session with Eric McCormack and Tom Cavanagh (We're Totally BFFS . https://www.dvdavenue. tv/products.php? http://stuckeyville.livejournal.com/
A simple JavaScript Formatter (47kb)Ed (TV series) - Wikipedia, the free encyclopedia For the MSNBC show hosted by Ed Schultz, see The Ed Show. . Tom Cavanagh received a Golden Globe nomination and a TV Guide Award for his work on . http://en.wikipedia.org/wiki/Ed_(TV_series)
Tom Cavanagh - Wikipedia, the free encyclopedia . in the NBC television program Providence, Cavanagh was . title character in the NBC program Ed. Cavanagh received a . http://en.wikipedia.org/wiki/Tom_Cavanagh CertMaker for iOS and Android
Tom Cavanagh - IMDb Tom Cavanagh, Actor: Ed. Thomas Cavanagh was born on October 26th, 1963 in Ottawa, Ontario, . 2008 The Capture of the Green River Killer (TV mini-series) . http://www.imdb.com/name/nm0146915/
Windows 8 AppContainer Loopback Utility
Pilot Intel: Tom Cavanagh is Ed(gar) again! | Inside TV | EW.com Mar 8, 2010 . Tom Cavanagh has landed the title role in the highly regarded ABC pilot Edgar Floats, . This is up to, what, four failed series on his watch? http://insidetv.ew.com/2010/03/08/tom-cavanagh-is-edgar-floats/ Download
Now (60kb) or
rocky mounatin flatline prices
Traffic Differ
Ed DVD news: Status report for Ed on DVD | TVShowsOnDVD.com Feb 11, 2009 . Tom Cavanagh has a new series airing on TNT these days: Trust Me, . for a pair of the actor's previous television series: Ed and Love Monkey. http://www.tvshowsondvd.com/news/Ed-DVD-Status/11295 Download now (47kb).
SAZ Clipboard
Ed 102 - The World of Possibility - Part 1 of 5 - YouTube Aug 21, 2008 . Season 1 Episode 2 of the NBC show "Ed," starring Tom Cavanagh . his secrets; Nancy becomes threatened by the baby's nanny." ~tv.com . http://www.youtube.com/watch?v=BGKagbyqcMw
Gallery
The Gallery extension (50kb) Cast of Ed TV Show, Cast Includes Tom Cavanagh and Justin Long Cast of Ed TV Show. Learn more about the Ed TV cast, including Tom Cavanagh, Julie Bowen Justin Long and Michael Ian Black. http://www.ed-cast.org/default.aspx
'Ed' Cast: Where Are They Now? - TV Oct 11, 2010 . Last week marked the 10th anniversary of 'Ed,' which certainly has a plum . charming and adorkable Tom Cavanagh as the titular Ed Stevens, 'Ed' . as Ed, hasn't had much luck in getting another TV show to stick around, . http://www.aoltv.com/2010/10/11/ed-cast-where-are-they-now/
AnyWHERE (sample)
The AnyWHERE extension (40kb) Thomas Cavanagh - TV.com Tom Cavanagh, Thomas Cavanaugh, Tom Cavanaugh . Prior to his work on Ed, Tom appeared in several theatrical and movie productions in New York, Los Angeles, . 2001 - TV Guide Award Actor of the Year in a New Series for Ed ( won) . http://www.tv.com/people/thomas-cavanagh/
RulesTab (sample)
Tom Cavanagh - TV Guide Get the latest Tom Cavanagh News, Bio, Photos, Credits and More for Tom Cavanagh . "When that comes to a head, it takes the show into an epic and darker . In the new TNT dramedy Trust Me, TV's former Ed Stevens and Will Truman play . http://www.tvguide.com/celebrities/tom-cavanagh/191036
Privacy Scanner
The Privacy Scanner
(41kb) Please Release Ed on DVD and Blu-ray #2 | SweetPaul ... Mar 3, 2013 . Produced by Worldwide Pants, this show features Tom Cavanagh as . for a pair of the actor's previous television series: Ed and Love Monkey. http://www.sweetpaul.com/please-release-ed-on-dvd-and-blu-ray-2/
Content-Blocking (sample)
The Content Blocker
sample (11kb) EDtheTVshow Everything about the TV show "Ed" that ran for four seasons before being cancelled. . Tom Cavanaugh [Ed Stevens]; Julie Bowen [Carol Vessey]; Josh Randall . http://stuckeyville.tumblr.com/
Image-Flipper (sample)
The Image
Flipper sample (6kb) Tom Cavanagh | TV shows, credits and biography - Yahoo! TV Find the complete TV career of Tom Cavanagh on Yahoo! TV. . A memorable role in a popular show would help Cavanagh to launch "Ed", a quirky . http://tv.yahoo.com/person/tom-cavanagh/
3rd-Party Extensions
Tom Cavanagh Filmography | List of Movies and TV Shows Tom Cavanagh filmography including movies from released projects, in theatres, in production and upcoming . As Ed Stevens in TV series "Ed" (2000-2004) . http://www.aceshowbiz.com/celebrity/tom_cavanagh/filmography.html
Tom Cavanagh Movies Your online source for Tom Cavanagh movies, biography and filmography. . title largely thanks to his assignment headlining the popular prime-time series Ed ( 2000). . Cavanagh returned to regular television work with the 2006 prime-time . http://www.blockbuster.com/browse/catalog/personDetails/265939
neXpert Performance Report Generator
Watch Ed Online | Season 1, 2, 3 & 4 Video ... - Web TV Wire Dec 15, 2009 . Ed Synopsis Ed is a comedy drama television series produced by NBC . It follows the story of Ed Stevens (played by Tom Cavanagh), young . http://www.webtvwire.com/watch-ed-online-season-1-2-3-4-video-streaming-torrent-search/
StresStimulus
Five off-the-air TV shows that don't get enough Internet love ... Aug 31, 2012 . The core cast of TV's Ed. (NBC) Certain TV shows benefit from an . home and becomes a bowling alley lawyer: Tom Cavanagh, Julie Bowen, . http://www.washingtonpost.com/blogs/celebritology/post/five-off-the-air-tv-shows-that-dont-get-enough-internet-love/2012/08/31/d2c98cb4-f387-11e1-a612-3cfc842a6d89_blog.html
Watcher - Passive Security Auditor
Ed | Facebook Ed. 29 likes · 1 talking about this. TV Show. NBC's Ed. About · Photos . with Ed, the wonderful 2000-2004 NBC comedy-drama starring Tom Cavanagh as Ed, . http://www.facebook.com/NBC.Ed
Ed Episodes - Ed Season 4 2004 Episode Guides ... - TV Guide Critic's Guide to Tuesday TV: New Girl Talks Turkey, Sons Explodes, and More! . to avoid spoiling our Thanksgiving digestion with another results show). read full article . Tom Cavanagh (Love Monkey, Ed) has landed a lead role in the CBS . http://www.tvguide.com/tvshows/ed/100135
Ammonite - Security Scanner
ED the Complete DVD Collection : iDVD Shop Ed is an NBC television program produced by David Letterman's Worldwide Pants . The hour-long comedy-drama starred Tom Cavanagh as Edward Jeremy . http://www.idvdshop.com/Drama/ED_THE_COMPLETE_DVD_COLLECTION/
help me make a flyer
x5s - Automated XSS Security Testing AssistantEd 103 - Just Friends - Part 1 of 5 - YouTube Aug 24, 2008 . Season 1 Episode 3 of the NBC show "Ed," starring Tom Cavanagh . Nancy and Mike fuss over who takes care of the baby at night." ~tv.com . http://www.youtube.com/watch?v=LKDgMEcLoHE
- Detecting where safe encodings were not applied to emitted
user-inputs
- Detecting where Unicode character transformations might bypass
security filters
- Detecting where non-shortest UTF-8 encodings might bypass security
filters
catholic church middle ages
intruder21
"Ed" (2000) - Full cast and crew Ed on IMDb: Movies, TV, Celebs, and more... http://www.imdb.com/title/tt0247091/fullcredits
just lay off mp3
HTML Inspector
CNN.com - Entertainment - Tom Cavanagh of 'Ed' - November 15 ... Nov 15, 2000 . Tom Cavanagh beat out hundreds of actors vying for the role in "Ed," a series . they didn't have television or film -- a really good existence, I would say. CNN: You were cast in this show for CBS more than two years ago. http://archives.cnn.com/2000/SHOWBIZ/TV/11/15/sbtst.cavanagh/
Stories from the Vaults - Smithsonian Channel Find out as host Tom Cavanagh ("Ed") takes you on an entertaining insider's tour of the private rooms, high-tech vaults, and cutting edge labs of the Smithsonian . http://www.smithsonianchannel.com/site/sn/show.do?series=435
WCF Binary-Encoded Message Inspector
Tom Cavanagh, ED Cast Tom Cavanagh is a Canadian actor better known for the title role on the ED tv . Born as Thomas Cavanagh, he is best known for his role on the TV show ED, . http://www.ed-cast.org/tom-cavanagh.aspx
Chad Sowald's Request-To-Code
Ed - TV Show, Episode Guide & Schedule | LocateTV Never miss Ed! Find out where and when you can watch the show on TV or . American comedy, starring Thomas Cavanagh . Cast. Tom Cavanagh Ed Stevens . http://www.locatetv.com/tv/ed
Eyal's Extensions
- falloutboy from under the cork tree has written two extensions:
Thomas Deml's Export WCAT Script extension
Ed - Season 1 Reviews - Metacritic Metacritic TV Reviews, Ed - Season 1, Ed Stevens is a contracts lawyer at a high- profile . Show Type: Ended; Season 1 premiere date: Oct 8, 2000; Episode Length: 60 . Tom Cavanaugh is brilliant and Julie Bowen shines in a role that far . http://www.metacritic.com/tv/ed
Per-Response Latency Extension
ED - A Celebration | Facebook TV Show. Welcome to the ED-Celebration site. This site was originally created to mark . Tom Cavanagh and Judd Hirsch rehearse in NY for the play they'll be . http://www.facebook.com/pages/ED-A-Celebration/315186749199
WPAD Server
Ed (TV series) - Wikiquote Ed (2000-2004) was a comedy-drama television show about a hotshot New York lawyer who on the same day is both fired from his job (for a misplaced comma . http://en.wikiquote.org/wiki/Ed_(TV_series)
XML Request InspectorDaryl Mitchell Is Part of the Family on NBC's Ed | Profiles in Excellence The ensemble cast features Tom Cavanagh as Ed Stevens, the lawyer who . Michaels on TV's Veronica's Closet , Dexter Walker on The John Larroquette Show . http://disability-marketing.com/profiles/daryl-mitchell.php4 XML DataSet InspectorQ and A: Smithsonian Channel Host Tom Cavanagh | Arts & Culture ... Actor Tom Cavanagh discusses what it is like to go behind the scenes of the . Cavanagh, best known for his role in the TV series, Ed, spoke to Beth . http://www.smithsonianmag.com/arts-culture/Q-and-A-Smithsonian-Channel-Host-Tom-Cavanagh.html
©2013 Telerik
|


Get Score, live match info and much more about Cricket
Get Score, live match info and much more about Football
Get Score, live match info and much more about Basketball


Create Account
Email Address
Please enter an Email Address
Password
Password must be atleast 8 characters.
I will be a
Rider
Driver
Log in
{{errorMessage}}
Start


Tropical Storm Ramon brings rain around 2 days ahead of landfall
The eastern parts of Cagayan and of Isabela, as well as the northern part of Aurora, are under Signal No. 1 as of Friday morning, November 15
by Acor ArceoSubscribe
Email Address
Newsletters
- Glenda Gloria's Take this Tuesday
- Huddle by Miriam Grace Go
- The Newsbreak Agenda by Chay Hofileña
- Sometimes, all you need is video by Lilibeth Frondoso


This is an application that can make you write script with the Go language.
It is NOT an interpreter but the pure Go. The preprocessor tranforms the script into a Go program, instantly compiles and runs. So it is almost same as the standard Go with the same efficiency.
Benefits
#!/bin/gosl
import "encoding/json"
toJson := func(lines []string) string {
res, _ := json.Marshal(struct {
Lines []string `json:"lines"`
}{
Lines: lines,
})
return string(res)
}
files := BashEval("ls -l %s", "/tmp/")
Println(toJson(Split(files, "\n")))
Go Search is now operating with gosl. So you can find some good examples at: https://github.com/daviddengcn/gcse/tree/master/scripts
go-diff also provides scripts in gosl: https://github.com/daviddengcn/go-diff/tree/master/scripts
go get github.com/daviddengcn/gosl
go install github.com/daviddengcn/gosl
/bin
sudo ln -s $GOPATH/bin/gosl /bin/gosl
If you don’t want to do this, the interpreter line can be like this, assuming $GOPATH/bin
is in your $PATH
:
#!/usr/bin/env gosl
If a script starts with the bash interpreter line: #!/bin/gosl
. You can run it like this
chmod a+x example.go
./example.go [params...]
Or you can explictly call gosl
to run it:
gosl example.go [params...]
The following packages are pre-imported with .
, i.e. you can directly use the methods exported by them. No complain of the compiler if you don’t use them.
fmt
, os
, strings
, strconv
, math
, time
, and github.com/daviddengcn/gosl/builtin
builtin
Functions| Method | Description | Example |
|---|---|---|
S |
Convert anything to a string |
S(1234) == "123" |
I |
Convert anything to an int |
I("1234") == 1234 |
BashEval |
Similar to bash backtick substitution. | lsstr := BashEval("ls -l") |
Exec |
Execute an command with arguments | err, code := Exec("rm", "-rf" "tmp") |
Bash |
Execute a bash line | err, code := Bash("rm -rf tmp") |
ScriptDir |
Returns the directory of the script | file := ScriptDir() + "/" + fn |
More functions are defined in package daviddengcn/gosl/builtin/ (godoc)
Apache License V2


Bacon ipsum dolor amet capicola sirloin bacon corned beef tri-tip ham cow rump brisket ribeye boudin. Pancetta drumstick
kevin, cupim sausage leberkas fatback chuck. Meatball fatback cow, prosciutto venison alcatra ball tip shankle.
Bacon shoulder filet mignon chicken. Beef ribs kielbasa chicken ribeye beef, flank turkey pork loin. Cow bacon strip steak,
tri-tip rump tenderloin pork jowl kevin. Kielbasa corned beef tenderloin bacon meatloaf picanha.  Flank ground round shoulder
cow, pastrami ball tip sausage jowl boudin hamburger meatball.
Ribeye sirloin drumstick t-bone porchetta chicken. Turducken pork belly shankle ball tip landjaeger tri-tip drumstick
spare ribs swine ham hock. Strip steak beef meatball meatloaf t-bone biltong hamburger pastrami tongue pork chop.
Strip steak hamburger kevin meatloaf, short ribs andouille brisket. Cupim meatball bacon shankle andouille ball tip. Cupim
pastrami shankle swine short ribs, sirloin turkey prosciutto. Tri-tip capicola tongue salami beef, landjaeger bacon.
Turkey short loin pig, beef ball tip fatback porchetta pork belly chuck bresaola boudin hamburger tongue ribeye.
T-bone pork belly meatball, bacon jowl venison turducken. Brisket ham beef ribs drumstick, chicken pastrami capicola jowl.
Pork belly pork loin salami ham. Pork belly doner kevin cow, ball tip biltong salami kielbasa sirloin flank meatloaf
turkey tongue frankfurter. Pancetta pork loin capicola chicken doner pork strip steak. Tail shoulder meatball, meatloaf
alcatra jowl pancetta shankle tongue swine.
© Andrew Duncan


Survey
Survey - All Survey
Search:
Add Survey
Delete Selected
User Name
Profile Pic
Title
Description
{{survey.user_name}}
{{survey.Title}}
{{survey.Description}}
Statistics
Participate
Participants
View My Answers
Delete


Toggle navigation
Dong
Archive
Categories
Pages
Reading
Tags
Submit
Normal Equation
Normal Equation VS Gradient Descent
Gradient Descent
need to choose .
need many iterations.
works well even when is large.
Normal Equation
no need to choose choose .
do not need to iterate.
slow is is very large.


Hi Everyone :-)
What a great system the OpenEnergyMonitor and also the community !
I created
I Used this brilliant 30$ WIFI enabled microcomputer http://www.adafruit.com/product/1129
The simple code is here... and only the pulse counting and JSON push to EmonCMS is working.
https://github.com/dkcsn/EnergyMeter
I made this simple configuration in EmonCMS (Look at attached pictures)
Data
10.000 pulse is equal 1Kwh
The count is uploaded each 60 seconds. And its typical between 15 - 200 Pulses.
My configuration is not working - counting very wrong.
So any help would be appreciated.
Best Regards
The Eletronic geek, and newbie to EmonCMS
Christian Søgaard Nielsen
Pluse Power Logging in Emoncms
Submitted by dkcsn on Fri, 06/06/2014 - 12:28Hi Everyone :-)
What a great system the OpenEnergyMonitor and also the community !
I created
I Used this brilliant 30$ WIFI enabled microcomputer http://www.adafruit.com/product/1129
The simple code is here... and only the pulse counting and JSON push to EmonCMS is working.
https://github.com/dkcsn/EnergyMeter
I made this simple configuration in EmonCMS (Look at attached pictures)
Data
10.000 pulse is equal 1Kwh
The count is uploaded each 60 seconds. And its typical between 15 - 200 Pulses.
My configuration is not working - counting very wrong.
So any help would be appreciated.
Best Regards
The Eletronic geek, and newbie to EmonCMS
Christian Søgaard Nielsen


Minnesota Case Information Minnesota Case Information
Not all cases of COVID-19 are tested, so it is not a representative of the total number of people in Minnesota who have or had COVID-19. Number of positive cases is the cases that were tested and returned positive. All data are preliminary and may change as cases are investigated. Not all cases of COVID-19 are tested, so it is not a representative of the total number of people in Minnesota who have or had COVID-19. Number of positive cases is the cases that were tested and returned positive. All data are preliminary and may change as cases are investigated.
Total cases requiring hospitalization: Total cases requiring hospitalization: 21 21
County of residence is confirmed during the case interview. At the time of this posting not all interviews have been completed. The data on this map may not equal the total number of reported positive cases. County of residence is confirmed during the case interview. At the time of this posting not all interviews have been completed. The data on this map may not equal the total number of reported positive cases.
Choosing a county on the interactive map above will provide the case count, the legend is located in the upper left. This map will not work if your browser is in compatibility mode. Choosing a county on the interactive map above will provide the case count, the legend is located in the upper left. This map will not work if your browser is in compatibility mode.
Cumulative total and daily confirmed cases in Minnesota Cumulative total and daily confirmed cases in Minnesota
| kind | link | text |
| link | /index.html | |
| link | /index.html | HOME |
| link | /data/index.html | Data, Statistics and Legislation |
| link | /diseases/index.html | Diseases and Conditions |
| link | /facilities/index.html | Health Care Facilities, Providers, and Insurance |
| link | /communities/index.html | Healthy Communities, Environment and Workplaces |
| link | /people/index.html | Individual and Family Health |
| link | /about/index.html | ABOUT US |
| link | /diseases/coronavirus/index.html | COVID-19 Home |
| link | /diseases/coronavirus/action.html | Strategies to Slow the Spread |
| link | /diseases/coronavirus/situation.html | Situation Update |
| link | /diseases/coronavirus/basics.html | About COVID-19 |
| link | /diseases/coronavirus/prevention.html | Protecting Yourself and Family |
| link | /diseases/coronavirus/communities.html | Community Settings |
| link | /diseases/coronavirus/travel.html | Travelers |
| link | /diseases/coronavirus/hcp/index.html | Health Care |
| link | /diseases/coronavirus/schools.html | Schools and Child Care |
| link | /diseases/coronavirus/businesses.html | Businesses and Employers |
| link | /diseases/coronavirus/responders.html | First Responders |
| link | /diseases/coronavirus/mdh.html | What MDH is Doing |
| link | /diseases/coronavirus/materials/index.html | Materials and Resources |
| link | /communities/ep/behavioral/index.html | Behavioral Health and Emergency Preparedness |
| link | /diseases/respiratory/index.html | Infectious Respiratory Illness |
| link | /diseases/coronavirus/hcp/eval.html | Evaluating and Testing for Coronavirus Disease 2019 (COVID-19) |
| link | /news/pressrel/index.html | 2020 News Releases |
| link | https://www.cdc.gov/coronavirus/2019-ncov/index.html | CDC: Coronavirus Disease 2019 (COVID-19) |
| link | http://www.addthis.com/bookmark.php?v=250&pub=mnhealth | Share This |
| link | javascript:window.open('http://service.govdelivery.com/service/subscribe.html?code=MNMDH_486',%20'Popup','width=700,height=440,toolbar=no,scrollbars=yes,resizable=yes');%20void(''); | Subscribe: COVID-19 updates |
| link | /diseases/coronavirus/materials/hmong.html | 2019 Novel Coronavirus |
| link | /diseases/coronavirus/materials/somali.html | Koronafayraska Cusub ee 2019 |
| link | /diseases/coronavirus/materials/spanish.html | Enfermedad del Coronavirus 2019 (COVID-19) |
| link | /diseases/coronavirus/materials/index.html#asl | COVID-19 PSA in American Sign Language (ASL) |
| link | https://survey.vovici.com/se/56206EE321296199 | IDEPC Comment Form or call<PHONE_NUMBER> for the MDH |
| link | /about/org/idepc/index.html | Infectious Disease Epidemiology, Prevention and Control Division |
| link | /people/index.html | Individual & Family Health |
| link | /facilities/index.html | Health Care Facilities, Providers |
| link | /data/index.html | Data, Statistics and Legislation |
| link | /diseases/index.html | Diseases & Conditions |
| link | /communities/index.html | Healthy Communities, Environment |
| link | /about/index.html | About MDH |
| link | /about/locations/index.html | Locations & Directions |
| link | /forms/feedback/mail.html | Comments & Questions |
| link | /about/privacy.html | Privacy Statement & Disclaimer |
| link | /about/equalopp.html | Equal Opportunity |
| link | https://mn.gov/portal/ | |
| link | https://www.phaboard.org/ | |


Updated:
Avviso News
The site tutorial : avviso.news
The twitter : avviso_news
Part 1: The Beginnings
This is a project I have been working on for months. It actually started a few years back during the Israel and Gaza conflict. Watching the news, I noticed how the story only mentioned the fact that the Israeli missles killed civilians but did nothing to tell about the weapons harbored in those buildings. It made me think, there should be a news source that is non partisan, where the user not only gets the facts, but can learn different views, therefore being able to choose their own. The site started as a place for all news, but after realizing that approach was too broad, I switched to covering just the 2016 election.
This became the message of the site and as the site was being developed, it became a site where users post the news. I summarize this idea with the phrase, “News for the people, by the people”.
Part 2: The Creation
This site, like every one I have made before used Ruby on Rails. This site tied together skills I have been learning for years and included learning some new ones as well.
- Database Relationships
- Web Scraping-(Searches sources posted for the best image possible)
- Regular Expressions
- Devise and user authentication
- Heroku
- Ajax
Skills I Used Already Known
- Nested Comments / Ancestery
- Reputation / Voting System
- Log functions to rank items-(time since created versus votes)
- DNS Setting
- Automatic color contrasting
New Skills Learned
Making the site took a few months of on and off working, and is still getting better every day.
Part 3: The Plan
I already started the twitter account and have 11 followers as of now. This may not seem like a lot, but these are people who are actively engaging with the account and will probably become users. The user count for the website at the moment is 14 with all users being people I know. The goal for now is to make all the posts and comments myself until people begin doing it. No one wants to go to a blank website. I am going after users who are politically active who will hopefully become active users on the site. The idea is to create a community that will use the site often and then to go after site readers who may occasionally post something. It will take time for the site to grow, but I am ready for the journey.


--- layout: post title: A Helpful Guide To Lifestyle Experiments | Break the Twitch date: '2020-01-10T19:13:00.000+05:30' author: Sahil Rajput tags: modified_time: '2020-01-10T19:14:01.427+05:30' blogger_id: tag:blogger.com,1999:blog-5250005448924290719.post-2735636696097671941 blogger_orig_url: https://www.jaadujinn.ml/2020/01/a-helpful-guide-to-lifestyle.html ---


Header Files in C
Standard header files contains Prototypes of the library functions.
For example, math.h contains prototypes for mathematical operations.
some standard header files are:
stdio.h printf, scanf, getchar, putchat etc.
stdlib.h utility functions; number conversions, memory allocation, exit and system , Quick Sort
float.h system limits for floating point types
math.h mathematical functions
string.h string functions
assert.h assertions
ctype.h character class tests
time.h date and time functions
limits.h system limits for integral types
setjmp.h non-local jumps
signal.h signals and error handling
stdarg.h variable length parameter lists
Use the #include (preprocessor directive) and give angle brackets around the name of the file to include these standard header files in your program


__construct()
__construct() : \BarcodeValidator
Constructor.
A PHP class for validating EAN, IMEI, ISBN, GTIN, SSCC, GSIN, UPC and other similar codes.
__construct() : \BarcodeValidator
Constructor.
IsValidISBN(string $code = '') : boolean
Determine whether an ISBN code is valid (either ISBN 10 or 13 digits). It also validates whether the code has the right length.
For ISBN-10 each of the first nine digits of the ten-digit ISBN (excluding the check digit itself) is multiplied by a number in a sequence from 10 to 2 and the remainder of the sum with (respect to 11) is computed. The resulting remainder, plus the check digit, must equal a multiple of 11 (either 0 or 11). For ISBN-13 the check-digit is calculated using the BarcodeValidator::validateEANCheckDigit() function, making it compatible with EAN codes.
| string | $code | the code to validate |
IsValidEAN8(string $code = '') : boolean
Determine whether a EAN-8 (GTIN-8) code is valid
EAN 8 is the short form of EAN-13. This code is only used if the article is too small for an EAN-13 code.
EAN-8 codes are common throughout the world, and companies may also use them to encode RCN-8s (8-digit Restricted Circulation Numbers) used to identify own-brand products sold only in their stores. These are formatted as 02xx xxxx, 04xx xxxx or 2xxx xxxx.
An EAN-8 always has 8 digits:
| string | $code | the code to validate |
IsValidEAN13(string $code = '') : boolean
Determine whether a EAN-13 (GTIN-13) code is valid
The EAN barcode is primarily used in supermarkets to identify product at the point of sales. The products contain the EAN number or GTIN (Global Trade Item Number) to identify itself.
An EAN-13 always has 13 digits:
| string | $code | the code to validate |
IsValidEAN14(string $code = '') : boolean
Determine whether a EAN-14 code is valid
The EAN 14 code is used for traded goods.
An EAN-14 always has 14 digits:
| string | $code | the code to validate |
IsValidUPCA(string $code = '') : boolean
Determine whether a UPC-A code is valid
The UPC-A code is the standard version of the UPC code and has 12 digits. The UPC code is a numeric code which is able to display digits from 0-9. It is also called UPC-12 and is very similar to the EAN code.
The structure of the UPC-A code is as follows:
| string | $code | the code to validate |
IsValidUPCE(string $code = '') : boolean
Determine whether a UPC-E code is valid
The UPC-E code is a short, 8-digit version of the UPC-A code, always starting with a zero. It is often used for small retail items. The UPC code is a numeric code which is able to display digits from 0-9.
The structure of the full-length UPC-E code is as follows:
| string | $code | the code to validate |
IsValidGSIN(string $code = '') : boolean
Determine whether a GSIN code is valid.
The Global Shipment Identification Number (GSIN) is a globally unique number which is used to identify a grouping of logistic units which are part of the same shipment.
The logistic units keep the same GSIN during all transport stages, from origin to final destination. The GSIN identifies the logical grouping of one or several logistic units, each identified with a separate SSCC (Serial Shipping Container Code).
GSIN also meets the requirements for UCR (Unique Consignment Reference) according to the World Customs Organisation, WCO.
| string | $code | the code to validate |
IsValidSSCC(string $code = '') : boolean
Determine whether a SSCC code is valid.
An SSCC (Serial Shipping Container Code) is used to provide a number logistic units. An SSCC enables manufacturers, suppliers, carriers and buyers to track a logistic unit from production to end customer. The can be used for tracing goods, warehouse management and efficient handling in transport.
The same SSCC may not be used on two different logistic units, neither during transport or when they are handled in the warehouse of the transport buyer or goods recipient. This means that the life span of an SSCC, that is the period until the unit is unpacked or repacked, can be from a few to many years.
The transport industry recommends that an SSCC should be available for re-use after 18 months, but only if it is certain that the SSCC is no longer in use. To estimate how many SSCCs your company needs you can, for example, use the number of logistic units handled in the most recent one or two year period.
| string | $code | the code to validate |
IsValidGLN(string $code = '') : boolean
Determine whether a GLN code is valid
A GLN (Global Location Number) is used to uniquely identify a company or organisation.
A GLN can also be used to number delivery places, invoicing addresses, workplaces, branches as well as functions or roles, such as goods recipient or authorised purchaser.
| string | $code | the code to validate |
IsValidIMEI(string $code = '') : boolean
Determine whether an IMEI number is valid or IMEISV
The International Mobile Equipment Identity (IMEI) is a number, to identify 3GPP (i.e., GSM, UMTS and LTE) and iDEN mobile phones, as well as some satellite phones.
It is usually found printed inside the battery compartment of the phone, but can also be displayed on-screen on most phones by entering *#06# on the dialpad, or alongside other system information in the settings menu on smartphone operating systems.
The IMEI (15 decimal digits: 14 digits plus a check digit) or IMEISV (16 digits) includes information on the origin, model, and serial number of the device.
The structure of the IMEI/SV is specified in 3GPP TS 23.003. The model and origin comprise the initial 8-digit portion of the IMEI/SV, known as the Type Allocation Code (TAC). The remainder of the IMEI is manufacturer-defined, with a Luhn check digit at the end. The IMEISV drops the Luhn check digit in favor of an additional two digits for the Software Version Number (SVN)
| string | $code | the code to validate |
validateEANCheckDigit(string $code, integer $length) : boolean
Determine whether a code is valid using the check-digit algorithm. It also validates whether the code has the right length and that it's composed of only digits.
A check digit is a form of redundancy check used for error detection on identification numbers, such as bank account numbers, which are used in an application where they will at least sometimes be input manually.
It is analogous to a binary parity bit used to check for errors in computer-generated data. It consists of one or more digits computed by an algorithm from the other digits (or letters) in the sequence input.
| string | $code | the code to validate |
| integer | $length | the code's length (e.g. 13 for EAN13, 12 for UPC-A, etc.) |
sumAllDigits(integer $number, integer $index) : array
Replace a number by the sum of all its digits.
This funtion is used by BarcodeValidator::calculateLuhnCheckDigit() to add all the single digits of each number
| integer | $number | the number to get the sum of digits from |
| integer | $index | the array index |
calculateLuhnCheckDigit(string $code) : integer
Calculate a check digit using the Luhn Modulo-10 algorithm used for IMEI, Credit Card validation and others.
The check digit (x) is obtained by computing the sum of the rest of the digits then subtracting the units digit from 10. In algorithm form:
For instance
| Digits | 4 | 9 | 0 | 1 | 5 | 4 | 2 | 0 | 3 | 2 | 3 | 7 | 5 | 1 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Double every other | 4 | 18 | 0 | 2 | 5 | 8 | 2 | 0 | 3 | 4 | 3 | 14 | 5 | 2 | |
| Sum all digits | 4 | + (1+8) | + 0 | + 2 | + 5 | + 8 | + 2 | + 0 | + 3 | + 4 | + 3 | + (1+4) | + 5 | + 2 | = 52 |
Check digit is: 10 - 2 = 8.
| string | $code | the code to calculate the Luhn check digit for |
validateLuhnCheckDigit(string $code, integer $length) : boolean
Determine whether a code is valid using the Luhn algorithm. It also validates whether the code has the right length and that it's composed of only digits.
The Luhn algorithm or Luhn formula, also known as the "modulus 10" or "mod 10" algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers and National Provider Identifier numbers in US and Canadian Social Insurance Numbers.
| string | $code | the code to validate |
| integer | $length | the code's length (e.g. 15 for IMEI numbers, 16 for credit cards, etc.) |
calculateISBNCheckDigit(string $code) : mixed
Calculate a check digit using the ISBN algorithm. The ISBN is error-detecting, but not error-correcting (unless it is known that only a single digit is erroneous). The ISBN detects any single-digit error, as well as most two-digit error resulting from transposing two digits.
The ISBN (International Standard Book Number) is a unique numeric commercial book identifier. An ISBN is assigned to each edition and variation (except reprintings) of a book. For example, an e-book, a paperback and a hardcover edition of the same book would each have a different ISBN. ISBNs are 13 digits long if assigned on or after 1 January 2007, and 10 digits long if assigned before 2007. The method of assigning an ISBN is nation-based and varies from country to country, often depending on how large the publishing industry is within a country.
The initial ISBN configuration of recognition was generated in 1967 based upon the 9-digit Standard Book Numbering (SBN) created in 1966. The 10-digit ISBN format was developed by the International Organization for Standardization (ISO) and was published in 1970 as international standard ISO 2108 (the SBN code can be converted to a ten digit ISBN by prefixing it with a zero). The last digit is a check digit which may be in the range 0-9 or X (where X is the Roman numeral for 10) for an ISBN-10, or 0-9 for an ISBN-13.
For ISBN-10 each of the first nine digits of the ten-digit ISBN (excluding the check digit itself) is multiplied by a number in a sequence from 10 to 2 and the remainder of the sum with (respect to 11) is computed. The resulting remainder, plus the check digit, must equal a multiple of 11 (either 0 or 11).
For ISBN-13 the check-digit is calculated using the BarcodeValidator::calculateEANCheckDigit() function, making it compatible with EAN codes.
Therefore, the check digit is (11 minus the remainder of the sum of the products modulo 11) modulo 11. Taking the remainder modulo 11 a second time accounts for the possibility that the first remainder is 0 (without the second modulo operation the calculation could end up with 11-0 = 11 which is invalid).
| ISBN | 1 | 8 | 4 | 1 | 4 | 6 | 2 | 0 | 1 | Total |
|---|---|---|---|---|---|---|---|---|---|---|
| Weight | 10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | |
| Result | 10 | 72 | 32 | 7 | 24 | 30 | 8 | 0 | 2 | 185 |
Calculate (11 - (185 mod 11)) mod 11 = 2 which is the last digit from the original ISBN. Hence, the ISBN is valid.
| string | $code | The code to calculate the check digit for |
(integer or X)
validateISBNCheckDigit(string $code) : boolean
Determine whether a code is valid using the ISBN algorithm (either ISBN 10). It also validates whether the code has the right length.
For ISBN-10 each of the first nine digits of the ten-digit ISBN (excluding the check digit itself) is multiplied by a number in a sequence from 10 to 2 and the remainder of the sum with (respect to 11) is computed. The resulting remainder, plus the check digit, must equal a multiple of 11 (either 0 or 11).
| string | $code | the code to validate |


1. Purpose
This code standard is designed to help organizations:
-
Facilitate team communication.
-
Encourage documentation and reuse.
-
Avoid common mistakes and dead code.
-
Recognize and use the strengths of JavaScript.
2. Do you know?
- How does a code standard improve products?
-
Answer:
- What are the current version of JavaScript?
-
Answer:
- Why is indicating variable type especially useful for JavaScript?
-
Answer:
- Should one avoid plurals in most variable names?
-
Answer:
- What are the dangers of imprecise comparators like
==
or!=
? -
Answer:
- Which is better,
setInterval
orsetTimeout
? -
Answer:
3. The code base audience
Code is read by at least two audiences: the machines that execute the instructions and the humans who write, maintain, or extend it. Code written for human comprehension tends to result in carefully constructed and well documented assets that are inexpensive to maintain, extend, or reuse. This is often called Living Code.
Code that cannot be understood by humans after it is written is often called Dead Code[1]. This code becomes prohibitively difficult and expensive to maintain, extend, or reuse and it is a technical debt[2] that stifles innovation.
A good standard helps us create well documented Living Code that can grow with our product and organization. A comprehensive standard is arguably more valuable for JavaScript than with other stricter languages. JavaScript’s flexibility can open a Pandora’s Box of syntax and practice. Stricter languages have a good deal of structure and consistency built-in. Developers must actively apply convention to attain the same results with JavaScript.
This standard has continuously evolved over many years and is used in many open source and commercial projects. Appendix Y provides a three-page quick-reference guide which dispenses with any explanations. However, if you want to know why we recommend a convention, keep reading.
4. JavaScript versions
Let’s review how JavaScript versions are named and why this standard considers ES5.1 the latest usable version.
4.1. ECMA, ECMAScript, and ES
Development on the JavaScript language has accelerated over the past decade as vendors have stopped competing and started collaborating on making the lanugage better all centered around the ECMAScript specifications. All these acronymns can be confusing so let’s clear things up.
ECMA International is a standards organization that changed its name from European Computer Manufacturers Association in 1994 to reflect its broader ambitions. ECMA is no longer considered an acronymn but is apparently retained for the pleasant sounds that occur when one tries to pronounce it.
ECMAScript is a language standard created by ECMA International. ES is contraction of ECMAScript. Thus the ES6 and ECMAScript 6 are the same thing. Clever, eh?
4.2. Current ES Versions and supported platforms
Table X.1 shows the major JavaScript versions that have been released. Later specifications have been mostly backward-compatible.
Year |
Pref. Name |
Alternate |
Highlights |
1997 |
ES1 |
ECMAScript 1 |
You gotta start somewhere |
1998 |
ES2 |
ECMAScript 2 |
Compatible with ISO 16262 |
1999 |
ES3 |
ECMAScript 3 |
Regular expressions |
---- |
ES4 |
---- |
Abandoned |
2009 |
ES5 |
ECMAScript 5 |
Strict mode, JSON |
2011 |
ES5.1 |
ECMASCript 5.1 |
Compatible with ISO 16262:2011 |
2015 |
ES2015 |
ES6, ECMAScript 6 |
ES6 Harmony, for/of, promises |
2016 |
ES2016 |
ES7, ECMAScript 7 |
ES7 Harmony, Exponent, Array includes |
2017 |
ES2017 |
ES8, ECMAScript 8 |
SIMD types, await/sync |
--- |
ESNext |
---- |
Cool stuff |
As of 2015, ECMA discourages the use of a single version numbers in favor of the year of release. Thus while using ES5.1 is fine, they prefer we use ES2015, ES2016, ES2017 instead of ES6, ES7, or ES8. Thanks to Codeburst.io for help sorting this out!
At the time of writing (fall 2017) IE 11 held around 11% market share and the highest level of JavaScript it supports well is ES5.1. This is the feature level that most public sites should and is the basis for this standard. Kanagax has provided a very helpful chart so we can keep an eye on popularity. Once IE 11 use drop below 1% we will will go all-in on ES2015.
5. Variables
Variables can contain array, functions, numbers, object, strings,
null
, or undefined
. Some JavaScript implementations may make
internal distinctions between integers, 32-bit signed, and 64-bit
double-precision floating point numbers but there is no formal means to
enforce this.
Provide variables with meaningful names as shown in Listing X.1 so we won’t have to insert a clumsy time-and-focus-sapping description every time a variable is used.
// == Avoid ===
var x = 'Fred';
function p () { console.log( 'Hello ' + x ); }
p();
// == Prefer ==
var person_name = 'Fred';
function sayHelloFn () { console.log( 'Hello ' + person_name ); }
sayHelloFn();
Minimize the effort required to understand why a variable exists and what it contains. This frees the mind to focus more important areas such as application structure and logic.
5.1. Abbreviate smartly
-
Do not abbreviate short words.
-
Remove most articles, adjectives, and prepositions from names.
-
Use standard abbreviations and acronyms where they exist.
-
Prefer truncated names to contractions.
// == Avoid ===
var dgClrStr = 'brown';
function walkWithTheBrownDog () {...}
for ( var q = 0; q < 9; q++ ) ...
var denormalizationMap = {...};
var dnmlztnMap = {...};
// == Prefer ==
var dogColorStr = 'brown'; (1)
function walkDogFn () {...} (2)
for ( var i = 0; i < 9; i++ ) ... (3)
var denormMap = {...}; (4)
-
Do not abbreviate short words
-
Discard articles and prepositions
-
Use standard i, j, k for integers
-
Truncate instead of contract
5.2. Replace comments with meaningful names
Name variables to describe why they needed and what data type we expected them to contain. The first consideration is important in any language; the second is useful for loosely-type languages like JavaScript. Listing X.3 shows variables named by purpose and type.
// == Avoid ===
// 'creators' is an object constructor we get by
// calling 'makers'. The first positional argument
// of 'makers' must be a string, and it directs
// the type of object constructor to be returned.
// 'makers' uses a closure to remember the type
// of object the returned function is to
// meant to create.
//
var creators = makers( 'house' );
// == Prefer ==
var make_house_fn = curry_build_fn({ _item_type_ : 'house' });
Figure X.1 illustrates how we convey all the meaning of the comments in Listing X.3 using variable names.
Precise variable names are not only more concise but they help avoid inaccurate comments. Consider, for example, what can happen when a teammate updates a few names. It is all too easy to make a mistake when updating the comments as shown in Listing X.4. If we instead rely on variable names this problem goes away.
// == Avoid ===
// 'creators' is an object constructor we get by (1)
// calling 'makers'. The first positional argument (2) (3)
// of 'makers' must be a string, and it directs
// the type of object constructor to be returned.
// 'makers' uses a closure to remember the type (4)
// of object the returned function is to
// meant to create.
//
var makers = builders( null, 'house' );
// == Prefer ==
var make_abode = curry_make_fn({ _item_type_ : 'abode' });
-
Mistake:
creators
is nowmakers
-
Mistake:
makers
is nowbuilders
-
Mistake: The string is now the second positional parameter
-
Mistake:
makers
is nowbuilders
The changes to the preferred code are far shorter and guaranteed correct. Good editors can apply variable-name changes throughout a project in second whereas comment management is the developer’s responsibility.
5.3. Use common characters
-
Use the characters
a-z
,A-Z
,0-9
, underscore, and$
, for variable names and all other symbols such as labels or property keys. -
Don’t begin a name with a number.
// == Avoid ===
my_obj[ '00-x__®__' ] = 'hello';
// == Prefer ==
my_obj._greet_str_ = 'hello';
Limit variable names to characters available on most of the world’s keyboards. Apply the same character limits to object property names since all variables are object properties of their functional scope.
5.4. Communicate variable scope
-
Place each module in its own file
-
Use
camelCase
when the variable is module scope. -
Use
snake_case
when the variable is local to a function nested inside the module. -
Use two or more syllables for module-scope variables.
// == Avoid ===
var stateMap = {}; (1)
function initModuleFn () {
var
localInt = 1, (2)
localStr = 'Module initialized. Our number is '
;
console.log( localStr + localInt );
}
return { _initModuleFn_ : initModuleFn };
// == Prefer ==
var stateMap = {}; (1)
function initModuleFn () {
var
local_int = 1, (3)
local_str = 'Module initialized. Our number is '
;
console.log( local_str + local_int );
}
return { _initModuleFn_ : initModuleFn };
-
Module scope
-
Avoid: Local scope variables use camelCase
-
Prefer: Local scope variables use snake_case
5.5. Communicate variable type
Add a suffix or prefix to a variable name to identify its intended data type. Avoid changing a variable type after declaration because it causes confusion and rarely provides any benefit. When in doubt use an “unknown type” indicator.
// == Avoid ===
var
places = 10,
users = '02',
calc = places + users;
console.log ( calc ); (1)
// == Prefer ===
var
place_count = 10,
user_id = '02',
calc_num = place_count + Number( user_id );
console.log ( calc_num ); (2)
-
Displays the string '1002'
-
Displays the number '12'
5.5.1. Booleans
Name boolean variables using <noun>_<type>
or <type>_<noun>
.
Recommended <type>
indicators are shown in Table X.1. Boolean
<type>
indicators are often prefixes because they read better in English.
Most other <type>
indicators are suffixes.
Indicator |
Local scope |
Module scope |
_bool [generic] |
return_bool |
returnBool |
do_ (requests action) |
do_retract |
doRetract |
has_ (inclusion) |
has_whiskers |
hasWhiskers |
is_ (state) |
is_retracted |
IsRetracted |
5.5.2. Functions
Name functions and function variables using <verb>-<noun>-<type>
.
Recommended type
indicators are shown in Table X.2. Recommended
verbs for are shown in tables X.3-5.
Indicator |
Local scope |
Module scope |
<verb><noun><type>_fn |
bound_fn curry_get_list_fn get_car_list_fn fetch_car_list_fn remove_car_list_fn store_car_list_fn send_car_list_fn |
boundFn curryGetListFn getCarListFn fetchCarListFn removeCarListFn storeCarListFn sendCarListFn curryGetListFn getCarListFn |
Verb |
Example |
Meaning |
bound |
boundFn |
A function with a bound context |
curry |
curryMakeUserFn |
Return a function as specified by argument(s) |
delete |
deleteUserObjFn |
Remove data structure from memory |
destroy, remove |
destroyUserObjFn |
Same as delete, but implies references will be cleaned up as well |
empty |
emptyUserListFn |
Remove all members of a data structure without removing the container |
get |
getUserObjFn |
Get data structure from memory |
make |
makeUserObjFn |
Create a new data structure using input parameters |
store |
storeUserListFn |
Store data structure in memory |
update |
updateUserListFn |
Change memory data structure in-place |
Verb |
Example |
Meaning |
fetch |
fetchUserListFn |
Fetch data from external source like AJAX, local storage, or cookie |
put |
putUserChangeFn |
Send data to external source for update |
send |
sendUserListFn |
Send data to external source |
Verb |
Example |
Meaning |
on |
onMouseoverFn onClickHeaderFn |
An event handler. Use <on><event-name><modifier> |
5.5.3. Integers
Name integer variables using <noun>-<type>
. Recommended <type>
indicators are shown in Table X.6.
Indicator |
Local scope |
Module scope |
_int [generic] |
size_int |
sizeInt |
_count |
user_count |
userCount |
_idx |
user_idx |
userIdx |
_ms (milliseconds) |
click_delay_ms |
clickDelayMs |
i, j, k (convention) |
i |
— |
_toid, _intid |
show_popup_toid |
showPopUpToid |
JavaScript requires an integer value for a number of purposes such as an
index for an array, or as an argument for indexOf
, or
subStr
. Consider, for example, what happens if we try to use a
float for an array index as shown in Listing X.8.
// == Avoid ===
const color_list = [ 'red', 'green', 'blue' ];
color_list[1.5] = 'chartreuse';
console.log( color_list.pop() ); // 'blue'
console.log( color_list.pop() ); // 'green'
console.log( color_list.pop() ); // 'red'
console.log( color_list.pop() ); // *undefined???*
console.log( color_list[1.5] ); // *oh, there it is*
console.log( color_list ); // *["1.5":"chartreuse"]*
5.5.4. Lists
Name array variables using <noun>-<type>
. Recommended <type>
indicators are shown in Table X.7. Please use only singular nouns
as the suffix indicates plurality. We recommend using the <table>
suffix for complex data structures such as a list-of-lists or
a list-of-objects.
Indicator |
Local scope |
Module scope |
_list [generic] |
timestamp_list, color_list |
timestampList, colorList |
_table [complex lists] |
user_table |
userTable |
5.5.5. Numbers
Name floating-point number variables using <noun>-<type>
. Recommended
<type>
indicators are shown in Table X.8. Please use only singular nouns
as the suffix indicates plurality.
Indicator |
Local scope |
Module scope |
_num [generic] |
size_num |
SizeNum |
_coord |
x_coord |
xCoord |
_px (fractional unit) |
x_px, y_px |
xPx |
_ratio |
sale_ratio |
saleRatio |
x,y,z |
x |
— |
5.5.6. Maps
Name variables used as maps using <noun>-<type>
. Recommended <type>
indicators are shown in Table X.9. Please use only singular nouns as the
suffix indicates plurality. We recommend using the <matrix>
suffix for complex data structures such as a map-of-lists or a map-of-maps.
Indicator |
Local scope |
Module scope |
_map [generic] _matrix [complex maps] |
employee_map receipt_map user_matrix |
employeeMap receiptMap userMatrix |
Maps are simple objects used to store key-value pairs[3]. This is similar to a map
in Java,
a dict
in Python, an associative array
in PHP, or a hash
in Perl.
5.5.7. Objects
Name full-featured object variables using <noun>-<type>. Recommended
`<type>
indicators are shown in Table X.10.
Indicator |
Local scope |
Module scope |
_obj [generic] |
employee_obj receipt_obj error_obj |
employeeObj receiptObj errorObj |
$ (jQuery object) |
$header $area_tabs |
$Header $areaTabs |
_proto (prototype) |
user_proto |
userProto |
5.5.8. Regular expression objects
Name regular expression object variables using <noun>-<type>
. The
recommended <type>
indicator is shown in Table X.11.
Indicator |
Local scope |
Module scope |
_rx |
match_rx |
matchRx |
5.5.9. Strings
Name strings variables using '<noun-type>'. Recommended <type>
indicators are shown in Table X.12.
Indicator |
Local scope |
Module scope |
_str [generic] |
direction_str |
directionStr |
_date |
email_date |
emailDate |
_dirname, _filename, _linkname, _socketname, _pathname |
config_filename test_dirname source_pathname |
configFilename testDirname sourcePathname |
_html |
body_html |
bodyHtml |
_id, _code (identifier) |
email_id |
emailId |
_msg (message) |
employee_msg |
employeeMsg |
_name |
employee_name |
employeeName |
_text |
email_text |
emailText |
_type |
item_type |
itemType |
5.5.10. Unknown types
Name variable of an unknown type using <noun>-<type>
. The recommended
<type>
indicator is shown in Table X.13.
Indicator |
Local scope |
Module scope |
_data |
http_data socket_data arg_data data |
httpData, socketData |
Variables with unknown types are encountered in polymorphic functions where an argument may have one of many types. One such function might concatenate strings, numbers, arrays, or maps. We also encounter unknown data types when receiving data from an external source such as an AJAX response.
5.6. Avoid plurals
Avoid plurals in any variable name. A plural noun implies an indeterminate group of data. Instead use a variable name that more precisely identifies the type of data that contains the group.
// == Avoid ===
var
cats = [ 'callico', 'tabby' ],
colors = { blue : '#00f', green : '#0f0', red : '#00f' },
persons = [ { name : 'Fred' }, [ name : 'Wilma' } ],
retracts = true,
users = 'Betty,Bamm-Bamm,Fred,Pebbles,Wilma'
;
// == Prefer ==
var
cat_list = [ 'callico', 'tabby' ],
color_map = { blue : '#00f', green : '#0f0', red : '#00f' },
do_retract = true,
person_table = [ { name : 'fred' }, [ name : 'wilma' } ],
user_csv_list = 'Betty,Bamm-Bamm,Fred,Pebbles,Wilma'
;
5.7. Sort declarations and assignments
Sort declarations and assignment of variables, lists, and maps in alphabetical order unless there is a precedence requirement or another obvious reason for a different order. Use an editor like Vim, Sublime, or WebStorm which support in-line sorting.
// == Avoid ===
var
do_retract = true,
color_map = { green : '#0f0', red : '#00f', blue : '#00f' },
person_table = [ { name : 'Wilma' }, { name : 'Fred' } ],
user_csv_list = 'Pebbles,Wilma,Betty,Bamm-Bamm,Fred',
cat_list = [ 'tabby', 'callico' ]
;
// == Prefer ==
var
cat_list = [ 'callico', 'tabby', ],
color_map = { blue : '#00f', green : '#0f0', red : '#00f' },
do_retract = true,
person_table = [ { name : 'fred' }, [ name : 'wilma' } ],
user_csv_list = 'Betty,Bamm-Bamm,Fred,Pebbles,Wilma';
;
5.8. Object property names
Name object properties using the same convention as other variables. Properties we intend to have compressed should be wrapped with underscores so they can be identified during the build process.
Type |
Local scope |
Module scope |
Array |
local_map._person_list_ |
spa._03_model_._personList_ |
Boolean |
local_map._is_enabled_ |
spa._03_model_._isReady_ |
Function |
local_map._init_fn_ |
spa._03_model_.initModuleFn_ spa._07_shell_.initModuleFn |
Integer |
local_map.leg_count |
spa._03_model_._callbackCount_ |
Map |
local_map._user_map_ |
spa._06_slider_._instanceMap_ |
Number |
local_map._mix_ratio_ |
spa._06_sound_._mixRatio_ |
String |
local_map._username_ |
spa._03_model_._userMap_ |
Regex |
local_map._match_rx_ |
spa.\01_util_.matchRx |
6. Functions
Functions are a first-class data type in JavaScript. They can be used as with any other type. We can, for example, create a map or array with them as values, or use them as arguments in other functions.
6.1. Use namespaces
When running JavaScript in a browser we need to protect our code from
conflict. Create a single global namespace map inside of which all our other
variables are scoped[4].
Use an Immediately Invoked Function Expression (IIFE
) to create the
namespace as shown in Listing X.11. When declaring an IIFE
always wrap
the outer function in parenthesis so that it’s clear obvious the value
produced is the result of the function and not the function itself.
Always use the 'use strict'
pragma for module-scope IIFEs
.
IIFE
// == Avoid ==
var greetStr = 'Hi there!';
console.log( window.greetStr ); // prints 'Hi there!'
// == Prefer ==
var spa = (function () {
'use strict';
var greetStr = 'Hi there!';
function initModuleFn () { console.log( greetStr ); }
return { _initModuleFn_ : initModuleFn };
}());
spa._initModuleFn_();
We can break a namespace into manageable subdivisions. For example, we
can add spa._06_slider_
and spa._07_shell_
to our spa
namespace as shown in Listing X.12.
// == Prefer ==
// In the file spa.slider.js:
spa._06_slider_ = (function () {
'use strict';
return { (1)
_initModuleFn_ : initModuleFn,
_extendSliderFn_ : extendSliderFn,
_retractSliderFn_ : retractSliderFn
};
}());
// In the file spa.shell.js:
spa._07_shell_ = (function () {
'use strict';
return { (1)
_initModuleFn_ : initModuleFn,
_resetDisplayFn_ : resetDisplayFn
};
}());
// In the file spa._08_app.js:
spa._07_shell_._initModuleFn();
-
Return private variables and methods
The numbers in the modules show inclusion precedence as shown in Diagram X.1 and Figure X.2.
spa # Root, also referred to as _00_root_
spa._01_util_ # Core utility
_02_data_ # Data management (AJAX, Websockets)
_03_model_ # Core logic
_04_utilb_ # Browser utilities
_05_css_lb_ # Feature support
_06_lb_ # Feature modules
_07_shell_ # Browser interface
_08_app_ # Application bundle
Name CSS selectors in parallel with the JavaScript namespaces. For
example, any classes used by spa._07_shell_
should have an
spa-_07_shell_
prefix.
6.2. Minimize module-scope variables
Do not use global variables except when namespacing as above.
It is also wise to minimize module-scope variables otherwise one can lose
track of module state. We recommend grouping state and configuration data
into stateMap
and configMap
respectively as shown in Listing X.13.
// == Avoid ===
var
doBigThings = true,
userMaxCount = 5,
isSliderActive = true,
isSliderOpen = false
;
// == Prefer ==
var
configMap = {
_do_big_things_ : true,
_user_max_count_ : 5
},
stateMap = {
_is_slider_active_ : true,
_is_slider_open_ : false
};
6.3. Use named functions
Named functions are easier to debug than anonymous functions. For most purposes the declarations in Listing X.14 are equivalent. However, we will see a difference when debugging. When we declare functions with an explicit names, legible stack traces can be computed prior to run-time.
// == Avoid ===
getMapCopy = function ( arg_map ) { ... }; (1)
// == Prefer ==
function getMapCopy( arg_map ) { ... }; (2)
-
This is an anonymous function assigned to a variable.
-
This is a named function.
6.4. Use named arguments for complex functions
Positional argument, while convenient for simple function, are not self documenting and become unwieldy when the list grows longer than two. Use named arguments instead as shown in Listing X.15.
// == Good ====
hypotenuse_num = sqrt( 25 ); (1)
// == Avoid ===
coor_map = refactorCoords( 22, 28, 32, 48); (2)
// == Prefer ==
coord_map = refactorCoords({
x1 : 22, y1 : 28, x2 : 32, y2 : 48 (3)
});
-
Positional arguments are fine for simple functions.
-
But they can get confusing when the list grows.
-
The purpose of these named arguments is clearer.
6.5. Use a single var statement per function
Declare all variables at the top of a function using a
single var
keyword first as shown in Listing X.16.
// == Avoid ===
function copyMapKeysFn( arg_map ) {
var solve_map = {};
var key_list = Object.keys( arg_map );
var key_count = key_list.length;
for ( var idx = 0; idx < key_count; idx++ ) {
var key_name = key_list[ idx ];
var val_data = arg_map[ key_name ];
if ( val_data !== undefined ) {
solve_map[ key_name ] = val_data;
}
}
return solve_map;
}
// == Prefer ==
function copyMapKeysFn( arg_map ) {
var
solve_map = {},
key_list = Object.keys( arg_map ),
key_count = key_list.length,
idx, key_name, val_data
;
for ( idx = 0; idx < key_count; idx++ ) {
key_name = key_list[ idx ];
val_data = arg_map[ key_name ];
if ( val_data !== undefined ) {
solve_map[ key_name ] = val_data;
}
}
return solve_map;
}
If we declare a variable anywhere within a function using var
,
it will be initialized with a value of undefined
immediately
on invocation. Declaring a variable is not the same as assigning a value to it.
When a variable is declared, the JS engine know which it exists within
a functional scope and this is processed at compile-time. A value can be
assigned to a variable only at run-time[5]. As a convenience
we may combine declaration and assignment with the var
statement
but internally the JavaScript engine will always process both
stages at different times.
As of ES5.1 let
is preferred over var
in most cases. But there
is one glaring problem: not all tool chains support it.
We’ve discovered this the hard way. So despite all the benefits of let
,
we’re going to allow its use catch up with its promise before we join the
party.
The const
keyword is also preferred over var
. Just like with let
there
are tool-chain issues. Listing X.17 shows how a const
symbol is not as
immutable as one might think.
const
'use strict';
const foo_table = [ {}, {} ];
foo_table[ 0 ]._brand_str_ = 'billy'; (1)
foo_table[ 1 ]._type_ = 'beer'; (1)
console.warn( JSON.stringify( foo_table ) );
// [ { _brand_str_: 'billy' }, { _type_: 'beer' } ]
-
So much for immutability.
6.6. Distinguish function declaration and invocation
-
Declare a function with a single space between the name and opening left parenthesis.
-
Invoke a function with no space between the name and the opening left parenthesis.
function processMap( arg_map ){ ... } // == Avoid ===
function processMap ( arg_map ) { ... } // == Prefer ==
result_map = processMap ( example_map ); // == Avoid ===
result_map = processMap( example_map ); // == Prefer ==
6.7. Compare with precision
Use the precise ===
and !==
comparators instead of ==
and !=
.
The latter operators apply type coercion which is inconsistent
and confusing as shown Listing X.19.
var count_list = [ 1 + 1 ];
== Avoid ===
if ( count_list == 2 ) { console.warn( 'Confusing match' ); } (1)
== Prefer ===
if ( count_list === 2 ) { console.warn( 'No match' ); } (2)
-
Both the array and number are coerced into the string '2'.
-
No type coercion occurs.
6.8. Catch exceptions
Exceptions should be caught using a try-catch block. Avoid nested blocks as shown in Listing X.20 and use a linear search instead as shown in Listing X.21.
// == Avoid ===
var fs_obj, lib_key;
try {
lib_key = 'fancyFs';
console.log( 'attempt ' + lib_key );
fs_obj = require( lib_key );
}
catch ( error0_data ) {
console.warn( String( error0_data ) );
try {
lib_key = 'coolFs';
console.log( 'attempt ' + lib_key );
fs_obj = require( lib_key );
}
catch ( error1_data ) {
console.warn( String( error1_data ) );
try {
lib_key = 'neatFs';
console.log( 'attempt ' + lib_key );
fs_obj = require( lib_key );
}
catch( error2_data ) {
console.warn( String( error2_data ) );
try {
lib_key = 'fs';
console.log( 'attempt ' + lib_key );
fs_obj = require( lib_key );
}
catch ( error3_data ) {
console.warn( String( error3_data ) );
}
}
}
}
if ( fs_obj ) {
console.log( 'Found library ' + lib_key );
}
// == Prefer == var lib_list = [ 'fancyFs','coolFs', 'neatFs', 'fs' ], lib_count = lib_list.length, fs_idx, lib_key, fs_obj, error_data; for ( fs_idx = 0; fs_idx < lib_count; fs_idx++ ) { lib_key = lib_list[ fs_idx ]; error_data = undefined; try { fs_obj = require( lib_key ); break; } catch ( catch_data ) { console.warn( String( catch_data ) ); } } if ( fs_obj ) { console.log( 'Found library ' + lib_key ); }
6.9. Prefer factory objects
Use {}
or []
instead of new Object()
or new Array()
to
create a new object or array. If you require object inheritance, use
Object.create( obj_proto )
and use the factory pattern for object
constructors shown in Listing X.22. This emphasizes the prototype object
inheritance in JavaScript.
// == Avoid ===
var dog = new Dog();
// == Prefer ==
var dog_obj = makeDogObjFn();
6.10. Use labels for clarity
Labels may be used with while
, do
, for
, or switch
blocks.
They clarify the purpose of a continue
or break
statement and make the
logic more resistant to nesting errors as shown in Listing X.23.
// == Prefer ==
var
horse_list = [ 'Anglo-Arabian', 'Clydsedale' ],
horse_count = horseList.length,
solve_list = [],
breed_name, idx, idj
;
_HORSE_: for ( idx = 0; idx < horse_count; idx++ ) {
breed_name = horse_list[ idx ];
_LEG_ : for ( idj = 0; idj < 4; idj++ ) {
if ( Math.random() < 0.5 ) { continue _LEG_; } (1)
if ( Math.random() < 0.1 && breed_name === 'Clydesdale' ) {
break _HORSE_; (2)
}
solve_list.push( breed_name + ' ' + String( idj ) );
}
}
console.log( JSON.stringify( solve_list ) );
-
Skip iteration of inner loop
-
Break out of outer loop
6.11. Return the intended value
The return value must start on the same line as the return
keyword to avoid semicolon insertion as shown in Listing X.24.
// == Avoid ===
return
( { _make_house_fn_ : make_house_fn } );
// == Prefer ==
return { _make_house_fn_ : make_house_fn };
6.12. Copy with care
The values in complex variables such as arrays and objects are not copied when they are assigned. Instead, the pointer to the data is copied as shown in Listing X.25. We highly recommend the use of deep copy routines to avoid data corruption.
var age_map, copy_map; // == Avoid === age_map = { 'Bob' : 36 }; copy_map = age_map; (1) copy_map.Amanda = 54; console.log( age_map ); // == Prefer == function cloneData ( data ) { try { return JSON.parse( JSON.stringify( data ) ); } catch ( error_data ) { return; } } age_map = { 'Bob' : 36 }; copy_map = cloneData( age_map ); (2) copy_map.Amanda = 54; console.log( age_map );
-
age_map and copy_map are pointers to the same map
-
copy_map is a deep copy of age map
6.13. Break after each case block
Every case
block inside a switch
closure — with the exception
of default
— should end with break
, return
, or throw
as shown in Listing X.26.
// == Avoid ==
switch ( <expression> ) {
case <value1>:
case <value2>:
// statements
case <value3>:
// statements
default:
// statements (1)
}
// == Prefer ==
switch ( <expression> ) {
case <value1>:
case <value2>:
// statements
break;
case <value3>:
// statements
break;
default:
// statements (2)
}
-
All case blocks will execute
-
Only one matching case block will execute
One may safely nest switch
statements by using labeled breaks
.
6.14. Don’t use these features
6.14.1. The comma operator
Avoid the use of the comma operator found in some for
loop
constructs. This doesn’t apply to the comma separator, which is used in
object literals, array literals, variable declarations, and parameter
lists.
6.14.2. Assignment expressions
Avoid using an assignment as as test condition as it is unexpected and confusing.
// == Avoid ===
var
random_int = Math.floor( Math.random() * 2 ),
set_int
;
if ( set_int = random_int ) {
console.warn( 'random int is not 0' );
}
// == Prefer ==
var
random_int = Math.floor( Math.random() * 2 ),
set_int = random_int
;
if ( random_int !== 0 ) {
console.warn( 'random int is not 0' );
}
6.14.3. Endless loops
Avoid the do
, while
and setInterval
statements as they are all prone
to endless loop conditions by default. Instead, prefer the self limiting
for
and setTimeout
statements, as shown in Listing X.28.
// == Avoid ===
totalCount = 0;
function bumpFn () { totalCount++ };
setInterval( bumpFn, 1000 ); (1)
// == Prefer
totalCount = 0;
function bumpFn () {
totalCount++;
if ( totalCount < 10 ) { (2)
setTimeout( bumpFn, 1000 );
}
}
bumpFn();
-
This will continue as long as the application is loaded
-
This is limited to 10 repetitions
6.15. The with statement
Avoid the with
statement. Instead use the object.call()
family
of methods adjust the value of this
during function
invocation.
6.16. Confusing plus and minus operators
Be careful to not follow a + with a + or a ++. This pattern can be confusing. Insert parentheses between them to make your intention clear as shown in Listing X.29.
// == Avoid ===
total = total_count + +arg_map._cost_int_;
// == Prefer ==
total = total_count + ( +arg_map._cost_int_);
This prevents the + +
from being misread as ++
. The same
guideline applies for the minus sign.
6.17. eval
JavaScript will attempt to eval
(evaluate and execute) a string
variable in numerous situations. Avoid them all to enhance security
and performance.
-
Don’t use the
Function
constructor with a string as this performs aneval
. -
Don’t pass strings to
setTimeout
orsetInterval
as this performs aneval
. -
Don’t use
eval
to processJSON
data. UseJSON.parse( <string> )
to convert JSON string into a data structure andJSON.stringify( <data> )
to convert a data structure into a string.
7. Format and documentation
7.1. Format for 80 column displays
-
Use a document width of 80 characters.
-
Indent two spaces per code level.
-
Don’t use tab characters.
-
Place white space between operators and variables.
-
Place white space after every comma.
-
Use only one statement or variable assignment per line.
-
Place a semicolon at the end of every statement.
Listing X.30 shows these rules in practice.
// == Avoid ===
function makePctStr(arg_ratio,arg_count,arg_sigil_str){
var ratio=castNum(arg_ratio,0),
count=castNum(arg_count,0),
sigil_str=castStr(arg_sigil_str,'%'),
count=count<0?0:Math.floor(count);
return (1)
{ pct_str:(ratio*100).toFixed(count)+sigil_str };
}
// == Prefer ==
function makePctStr ( arg_ratio, arg_count, arg_sigil_str ) {
var
count = castNum( arg_count, 0 ),
ratio = castNum( arg_ratio, 0 ),
sigil_str = castStr( arg_sigil_str, '%' ),
count = count < 0 ? 0 : Math.floor( count )
;
return {
pct_str : ( ratio * __100 ).toFixed( count ) + sigil_str
};
}
-
This results in a semicolon insertion bug where the return value is undefined.
Keep the document width below 80 characters so that it fits within a standard terminal window and reads well on constrained displays such as those found on mobile devices and is easy to comprehend[6]. Indent two spaces per level to avoid exceeding the document width when code is nested. Use spaces for indentation not tabs as they display consistently on all devices.
Place white space around operators, variables, and commas to assist with legibility. This has no effect on application performance as it will be concatenated, minified, and compressed before it reaches end users.
Place only one statement or assignment per line. One may, however, declare multiple variables on a single line to save space. Explicitly terminate every statement with a semicolon to avoid semicolon insertion bugs.
7.2. Use Stroustrup-style bracketing
-
Place the opening parenthesis, brace, or bracket at the end of the line.
-
Indent the code inside the delimiters (parenthesis, brace, or bracket) one level.
-
Place the closing parenthesis, brace or bracket on its own line with
-
same indentation as the opening line.
-
Do not omit braces on any single-line statement.
Listing X.31 shows these rules in practice.
// == Avoid ===
function getSign(arg_data)
{
var
arg_num = arg_data + 0,
solve_int = 0;
if (arg_num < 0) solve_int = -1
else if (arg_num === 0)
{
solve_int = 0;
} else {
solve_int = 1;
}
return solve_int;
}
// == Prefer ==
function getSign( arg_data ) {
var
arg_num = arg_data + 0,
solve_int = 0;
if ( arg_num < 0 ) {
solve_int = -1;
}
else if ( arg_num === 0 ) {
solve_int = 0;
}
else {
solve_int = 1;
}
return solve_int;
}
Stroustrup style is a one-true-brace variant of K&R-style that does not cuddle else clauses. Many feel it nicely balances brevity, clarity, and safety.
7.3. Organize and comment by paragraphs
-
Group code in logical paragraphs and place blank lines between each.
-
Vertically align operators within paragraphs.
-
Indent comments the same amount as the code they explain.
-
Comment once per paragraph.
Listing X.32 shows how cluttered and noisy comments can get. Listing X.33 shows comments applied by paragraph.
// == Avoid ===
function shuffle( items ) {
// Items should be an array.
// Return false if argument is not an array
if ( ! Array.isArray( items ) ) { return false; }
// Get the length of the items array. Size is an integer.
var size = items.length;
// Decrement i from the size of the list to 1
for ( var i = size; i > 0; i-- ) {
// x is the int element index at the end of the section.
var x = i - 1;
// y is a random integer index within the section.
var y = Math.floor( Math.random() * i );
// Get random element value. Swap could be any data type.
var swap = items[ y ];
// Set random element value to same as end of section
items[ y ] = items[ x ];
// Set end of section value to random element value
items[ x ] = swap;
}
return true;
}
// == Prefer ==
// BEGIN public method /shuffleListFn/
// Purpose : Shuffle elements in a list
// Example : shuffleListFn( [1,2,3,4] ) returns [ 3,1,4,2 ]
// Arguments : ( positional )
// 0. arg_list - The list to shuffle
// Returns : boolean true on success
// Throws : none
// Technique :
// 1. Count down from end of array with last_idx
// 2. Randomly pick element from between 0 and last_idx
// 3. Swap pick element with last_idx element
//
function shuffleListFn ( arg_list ) {
var
list = castList( arg_list ),
count = list ? list.length : 0,
idx, last_idx, pick_idx
;
if ( ! list ) { return false; }
for ( idx = count; idx > 0; idx-- ) {
last_idx = idx - 1;
pick_idx = Math.floor( Math.random() * idx );
swap_data = list[ last_idx ];
list[ last_idx ] = list[ pick_idx ];
list[ pick_idx ] = swap_data;
}
return true;
}
Rely on the name convention to explain variable content and purpose. Use a capable editor like Vim, Sublime, or WebStorm which support vertical selection and alignment. WebStorm can be configured align map values and assignments within paragraphs.
7.4. Document APIs in-line
Document any nontrivial function API inline. A template is provided in Listing X.34. Place architecture plans in documents separate from the code.
// == Avoid ===
function shuffle( items ) { ... }
// == Prefer ==
// BEGIN public method /<method_name>/
// Purpose : <what does this do in a short sentence>
// Example : <example call and results>
// Arguments : ( positional )
// <arg_name or number> : <value description>
// Returns : <return value on success and failure>
// Throws : <any exceptions, or 'none'>
// Technique : <overview of algorithm>
//
function shuffleListFn( arg_list ) { ... }
// . END public method /shuffleListFn/
7.5. Mark future tasks with TODOs
Create TODO
comments for tasks that can not be complete immediately
as shown in Listing X.35. These have become standard enough that WebStorm,
ESLint, Vim, and many other tools recognize them.
// TODO <date> <username> <urgency>: <notes>
// TODO 2019-05-01 bubba alert : Disabled while testing alternate
The <date>
field conveys the freshness of the comment and should be
expressed in ISO YYYY-MM-DD format, for example, 2019-05-01.
The <username>
field should be the identification of the author.
The <urgency>
field explains how critical the task is. We recommend using
syslog levels as these are well known [7]. We can check a list of all TODOs in a project
as shown in Listing X.36.
grep TODO $(find ./ -type f -name '*.js' \
| grep -v node_modules |grep -v /vendor/) |sort -u
7.6. Annotate disabled code
It is wise to disable a code block and only delete it when we are
certain it will no longer be useful. This prevents team members from
solving the same problem multiple times. Disabled code should be
identified by a TODO
comment as shown in Listing X.37.
// == Avoid ===
// while ( k > 0 ) { … }
// == Prefer ==
// BEGIN TODO 2019-05-01 bubba warn: Disabled for testing
// while ( k > 0 ) { … }
// ...
// . END TODO 2019-05-01 bubba warn
Search and resolve TODOs
regularly — once a week is good — by
recording them in the organization’s issue tracking database. Convert
each comment as each issue is entered as shown in Listing X.38
// == Prefer == (issue ID used to explain disabled code)
// Issue #96785: Disabled while testing alternative
// while ( k > 0 ) { ... }
7.7. Break lines on operators
-
Prefer single lines when possible.
-
Break lines before operators or after comma separators.
-
Indent subsequent lines of the statement one level.
-
Optionally place the terminating semicolon on its own line to end multi-line statements.
// == Avoid ===
var full_address_str = first_name + ' ' + last_name +
'\n' + street1_str + '\n' + street2_str + '\n' +
city_str + ',' + state_code + ' ' + zip_code;
// == Prefer ==
var full_address_str
= first_name + ' ' + last_name + '\n'
+ street1_str + '\n'
+ street2_str + '\n'
+ city_str + ','
+ state_code + ' ' + zip_code
;
Place all statements and declarations within our document width on a single line. Break any statement or declaration that exceeds our document width into multiple lines. Break before operators so they are aligned on the left column. This highlights the action taking place on the data. Indent all continuation lines one level.
7.8. Delimit literals with single quotes
Prefer single quotes ('
) over double quotes ("
) when delimiting string
literals. This communicates that JavaScript does not expand embedded
variables name just with single-quoted strings in many other popular
languages. Quoting HTML is also much easier as shown in Listing X.40.
// == Avoid ===
link_str = "<a href=\"/wiki/fish\" title=\"fish\">fish</a>";
// == Prefer ==
link_str = '<a href="/wiki/fish" title="fish">fish</a>';
ECMA2015 introduced template literals where grave accent delimiters (`
)
work much like double quotes ("
) in many other languages. As of late
2017, only Firefox supports template literals fully.
7.9. Prefer C-style ‘for’ syntax
Use the C-style form of the for
statement. Avoid the
for-in
form as this iterates over inherited object properties which
are unreliable. Instead use Object.keys()
to get a list of property
names and iterate over that as shown in Listing X.41.
// == Avoid ===
for ( key in cat_obj ) {
if ( cat_obj.hasOwnProperty( key ) ) {
// process key
}
}
// == Prefer ==
key_list = Object.keys( cat_obj );
key_count = key_list.length;
for ( idx = 0; idx < key_count; idx++ ) {
key = obj_list[ idx ];
// process key
}
7.10. Before and after
Listings X.42 and X.43 compare the readability of an object prototype before and after applying the recommended formatting.
// == Avoid ===
doggy = {
temperature : 36.5,
name : 'Guido',
greeting : 'Grrrr',
speech : 'I am a dog',
height : 1.0,
legs : 4,
ok : check,
remove : release,
greet_people : greet_people,
say_something : say_something,
speak_to_us : speak,
colorify : flash,
show : render
};
// == Prefer ==
dogProto = {
_greet_str : 'Grrrr',
_height_m_num_ : 1.0,
_leg_count_ : 4,
_name : 'Guido',
_speak_str_ : 'I am a dog',
_temp_c_num_ : 36.5,
_check_exist_fn_ : checkExistFn,
_print_greet_fn_ : printGreetFn,
_print_name_fn_ : printNameFn,
_print_speak_fn_ : printSpeakFn,
_redraw_dog_fn_ : redrawDogFn,
_remove_dog_fn_ : removeDogFn,
_show_flash_fn_ : showFlashFn
};
8. Layout JS and CSS files by namespace
-
Place JavaScript files used by the web application under a directory called
js.
-
Name JavaScript files according to the namespace they provide, one namespace per file. All files should have the
.js
suffix as shown in Listing X.44. -
Use the template to start any JavaScript module file. This is found in the
hi_score
project atjs/xhi/xhi-module-template.js
. -
Place all CSS files used by the web application in a directory called
css
. -
Maintain a parallel structure between JavaScript and CSS files and class names. Create a CSS file for each JavaScript file that generates HTML. All files should have the
.css
suffix as shown below. -
Prefix CSS selectors according to the name of the module they support. This practice helps greatly to avoid unintended interaction with classes from third-party modules as shown in Listing X.44.
-
Use
<namespace>_x_<descriptor>_
for state-indicator selectors and other shared class names. Examples includespa-_x_select_
andspa-_x_disabled_
. Place these in the root namespace stylesheet, for examplespa.css
. -
When using PowerCSS, keep the same parallel structure, replacing CSS files with JS files as shown in Listing X.44.
-
Include third-party JavaScript files first in HTML so their functions may be evaluated and made ready for our application.
-
Include custom JavaScript files next, in order of namespace. We can’t load namespace
spa.shell
, for example, if the root namespace,spa
, has not yet been loaded.
// == Prefer == JS files
js/spa.js (1)
js/spa.shell.js (2)
js/spa.slider.js (3)
// == Prefer == CSS files
css/spa.css (1) (4)
css/spa.shell.css (2) (5)
css/spa.slider.css (3) (6)
// == Alternate CSS generator files
js/spa.css.js (1) (4)
js/spa.css_shell.js (2) (5)
js/spa.css_slider.js (3) (6)
-
Claims spa JavaScript namespace
-
Claims spa._shell_ JavaScript namespace
-
Claims spa._slider_ JavaScript namespace
-
Defines #spa, .spa-_x_clearall_.
-
Defines spa-_shell_, spa-_shell_header_, .spa-_shell_footer_, and .spa-_shell_main_
-
Defines .spa-_slider_open_, .spa-_slider_closed_
These conventions make the interplay between CSS and JavaScript easier to manage and debug.
9. Code Validation
ESLint is a popular JavaScript validation tool that is more configurable than the venerable JSLint. Use it to identify errors and ensure best practice.
9.1. Install ESLint
We may install ESLint globally as shown in Listing X.45.
sudo npm install -g eslint
9.2. Configure ESLint
Our settings for are shown in Listing X.46. These are
added to the package.json
file at the root of the project.
{
...,
"eslintConfig": {
"extends" : [
"eslint:recommended"
],
"globals" : {
"$" : true,
"clearTimeout" : true,
"console" : true,
"document" : true,
"global" : true,
"Image" : true,
"localStorage" : true,
"jQuery" : true,
"module" : true,
"process" : true,
"require" : true,
"setTimeout" : true,
"window" : true
},
"parserOptions": {
"ecmaVersion": 6
},
"plugins": [
"json"
],
"rules": {
"continue" : "off",
"indent" : "off",
"no-console" : "off",
"one-var": [
"error",
{
"var": "always",
"let": "always",
"const": "always"
}
],
"no-plusplus" : "off"
}
},
...
}
9.3. Verify JavaScript
Check JavaScript validity as shown in Listing x.47.
node_modules/.bin/eslint $( \
find -type f -name '*.js' \
| grep -v vendor |grep -v node_modules |grep -v build \
)
9.4. Share IDE configuration
WebStorm has excellent code inspection tools (see Tools
> Inspect code
).
The hi_score
project has code inspection settings available at
config/webstorm_settings.jar
which may be imported using File
> Import
settings
.
10. Choose libraries wisely
See "The Fog of SPA" on how too many libraries can result in greater complexity when developing a JavaScript application.
11. Exercises
- How does a code standard improve products?
-
A standard provides team members a common dialect and practices so they may better understand and collaborate with each other. A good standard will encourage documentation, code reuse, and empahsize the benefits of the language. It also helps developers avoid common mistakes, and techical debt[2].
- Why is indicating variable type especially useful for JavaScript?
-
Because JavaScript variables can contain any type without any indication whatsoever. Directly naming variables by expected type can remove the constant need for expensive manual or automated introspection.
- Should one avoid plurals in variable names?
-
Yes, plurals imply a collection of items. At worst this is simply wrong, when, for example, a developer users
runs
as a boolean. At best there are far more exact ways to indicate a collection of items. For example, instead ofusers
, consideruser_list
,user_map
, orpeople_obj
. - What are the dangers of imprecise comparators like
==
or!=
? -
Imprecise comparators will convert values in complex and unpredictable ways. Using a a precise comparison forces the developer to fully understand the comparison and avoid subtle bugs.
- Which is better:
setTimeout
instead ofsetInterval
? -
The
setInterval
method will invoke a function indefinitely unless actively stopped. This is easy to get wrong. Alternately we can use thesetTimeout
method to invoke a function once and then have it call itself if it needs to run again. This approach is self-limiting and hard to get wrong. - Why are labels useful with
break
orcontinue
? -
A
break <label>
orcontinue <label>
statement explicitly declares which loop is effected. This illustrates logic and helps prevent errors.
12. End
Original author: Michael Mikowski for SPAr2


Apache FOP: Graphics Formats
Introduction
Some noteworthy features of the image handling subsystem are:
- The image libraries Jimi and JAI are not supported. Instead, Apache FOP uses the Image I/O API that was introduced with Java 1.4 for all bitmap codecs.
- Some bitmap images are not converted to a standardized 24 bit RGB image but are instead handled in their native format.
- A plug-in mechanism offers a possibility to add support for new formats without changing the FOP's source code.
The actual image loading framework does not reside in Apache FOP, but in XML Graphics Commons.
Overview of Graphics Support
The table below summarizes the theoretical support for graphical formats within FOP. In other words, within the constraints of the limitations listed here, these formats should work. However, many of them have not been tested, and there may be limitations that have not yet been discovered or documented. The packages needed to support some formats are not included in the FOP distribution and must be installed separately. Follow the links in the "Support Through" columns for more details.
| Format | Type | Support Through | ||
|---|---|---|---|---|
| Apache FOP (native) | Apache Batik | Image I/O | ||
| BMP (Microsoft Windows Bitmap) | bitmap | X [1] | ||
| EMF (Windows Enhanced Metafile) | vector (with embedded bitmaps) | (X) | ||
| EPS (Encapsulated PostScript) | metafile (both bitmap and vector), most frequently used for vector drawings | (X) | ||
| GIF (Graphics Interchange Format) | bitmap | X | ||
| JPEG (Joint Photographic Experts Group) | bitmap | (X) | X | |
| PNG (Portable Network Graphic) | bitmap | X | ||
| SVG (Scalable Vector Graphics) | vector (with embedded bitmaps) | X | ||
| TIFF (Tag Image Format File) | bitmap | (X) | X [1] | |
| WMF (Windows Metafile) | vector (with embedded bitmaps) | (X) |
Legend:
- "(X)" means restricted support. Please see the details below.
- [1]: Requires the presence of JAI Image I/O Tools (or an equivalent Image I/O compatible codec) in the classpath. JAI Image I/O Tools also adds support for JPEG 2000, WBMP, RAW and PNM. Other Image I/O codecs may provide support for additional formats.
Map of supported image formats by output format
Not all image formats are supported for all output formats! For example, while you can use EPS (Encapsulated PostScript) files when you generate PostScript output, this format will not be supported by any other output format. Here's an overview of which image formats are supported by which output format:
| Image Format | PostScript | Java2D, PNG, TIFF, AWT | PCL | AFP | RTF | |
|---|---|---|---|---|---|---|
| BMP (Microsoft Windows Bitmap) | X | X | X | X | X | X |
| EMF (Windows Enhanced Metafile) | X [1] | |||||
| EPS (Encapsulated PostScript) | X [1] | |||||
| GIF (Graphics Interchange Format) | X | X | X | X | X | X |
| JPEG (Joint Photographic Experts Group) | X [1] | X [1] | X | X | X [1] | X |
| PNG (Portable Network Graphic) | X | X | X | X | X | X |
| SVG (Scalable Vector Graphics) | X | X | X | X | X | X |
| TIFF (Tag Image Format File) | X [2] | X [2] | X | X | X [2] | X |
| WMF (Windows Metafile) | X | X | X | X | X | X |
Legend:
- [1]: Supported without the need to decode the image.
- [2]: Supported without the need to decode the image, but only for certain subtypes.
Graphics Packages
XML Graphics Commons Native
XML Graphics Commons supports a number of graphic file formats natively as basic functionality: all bitmap formats for which there are Image I/O codecs available (JPEG, PNG, GIF, TIFF, etc.), EPS and EMF.
FOP Native
FOP has no native image plug-ins for the image loading framework of its own but currently hosts the Batik-dependent SVG and WMF plug-ins until they can be moved to Apache Batik.
Apache Batik
Apache Batik will later receive the SVG and WMF plug-ins for the image loading framework that are currently hosted inside FOP.
Current FOP distributions include a distribution of the Apache Batik. Because Batik's API changes frequently, it is highly recommended that you use the version that ships with FOP, at least when running FOP.
Batik must be run in a graphical environment. It uses AWT classes for rendering SVG, which in turn require an X server on Unixish systems. If you run a server without X, or if you can't connect to the X server due to security restrictions or policies (a so-called "headless" environment), SVG rendering will fail.
Here are some workarounds:
- Start Java with the -Djava.awt.headless=true command line option.
- Install an X server which provides an in-memory framebuffer without actually using a screen device or any display hardware. One example is Xvfb.
- Install a toolkit which emulates AWT without the need for an underlying X server. One example is the PJA toolkit, which is free and comes with detailed installation instructions.
Image I/O
The image loading framework in XML Graphics Commons provides a wrapper to load images through the JDK's Image I/O API (JSR 015). Image I/O allows to dynamically add additional image codecs. An example of such an add-on library are the JAI Image I/O Tools available from Sun.
Details on image formats
BMP
BMP images are supported through an Image I/O codec. There may be limitations of the codec which are outside the control of Apache FOP.
EMF
Windows Enhanced Metafiles (EMF) are only supported in RTF output where they are embedded without decoding.
EPS
Apache FOP allows to use EPS files when generating PostScript output only.
Other output targets can't be supported at the moment because FOP lacks a PostScript interpreter. Furthermore, FOP is currently not able to parse the preview bitmaps sometimes contained in EPS files.
 Transparency is supported but not guaranteed to work with every output format.
JPEG
FOP native support (i.e. the handling of undecoded images) of JPEG does not include all variants, especially those containing unusual color lookup tables and color profiles. If you have trouble with a JPEG image in FOP, try opening it with an image processing program (such as Photoshop or Gimp) and then saving it. Specifying 24-bit color output may also help. For the PDF and PostScript renderers most JPEG images can be passed through without decompression. User reports indicate that grayscale, RGB, and CMYK color spaces are all rendered properly. However, for other output formats, the JPEG images have to be decompressed. Tests have shown that there are some limitation in some Image I/O codecs concerning images in the CMYK color space. Work-arounds are in place but may not always work as expected.
PNG
PNG images are supported through an Image I/O codec. Transparency is supported but not guaranteed to work with every output format.
SVG
Introduction
FOP uses Apache Batik for SVG support. This format can be handled as an fo:instream-foreign-object or in a separate file referenced with fo:external-graphic.
Placing SVG Graphics into PDF
The SVG is rendered into PDF by using PDF commands to draw and fill lines and curves. This means that the graphical objects created with this remain as vector graphics. The same applies to PostScript output. For other output formats the SVG graphic may be converted to a bitmap image.
There are a number of SVG things that cannot be converted directly into PDF. Parts of the graphic such as effects, patterns and images are inserted into the PDF as a raster graphic. The resolution of these raster images can be controlled through the "target resolution" setting in the configuration.
Currently transparency is limited in PDF so some SVG images that contain effects or graphics with transparent areas may not be displayed correctly.
Placing SVG Text into PDF and PostScript
If possible, Batik will use normal PDF or PostScript text when inserting text. It does this by checking if the text can be drawn normally and the font is supported. This example svg text.svg / text.pdf / text.png shows how various types and effects with text are handled. Note that SVG font support is not yet implemented. Furthermore, text handling in PostScript output is inferior to PDF output - more text will be painted as shapes in PS than in PDF.
When there's no support to paint text using native text operations, text is converted and drawn as a set of shapes by Batik, using the stroking text painter. This means that a typical character will have about 10 curves (each curve consists of at least 20 characters). This can make the output files large and when it is viewed the viewer may not normally draw those fine curves very well (In Adobe Acrobat, turning on "Smooth Line Art" in the preferences will fix this). Copy/paste functionality will not be supported in this case. If the text is inserted into the output file using the inbuilt text commands it will use a single character.
Note that because SVG text can be rendered as either text or a vector graphic, you may need to consider settings in your viewer for both. The Acrobat viewer has both "smooth line art" and "smooth text" settings that may need to be set for SVG images to be displayed nicely on your screen (see Edit / Preferences / Display). This setting will not affect the printing of your document, which should be OK in any case, but will only affect the quality of the screen display.
Font selection notes
Apache Batik uses the AWT/Java2D subsystem as font source while FOP has its own font subsystem. Great care has been taken that font selection does the best possible choices. But it must be noted when creating PDF or PostScript that a font used in SVG graphics needs to be registered with the operating system as well as in FOP's configuration. By using FOP's font auto-detection, you simply have to install the font in the operating system and not care about anything else. This is less of an issue if you create formats like TIFFs, PNGs or PCL because in these cases SVG graphics are usually rendered to bitmaps which means that on both sides (Batik and FOP), AWT/Java2D is used as the single font source.
Whenever an SVG is converted into a PDF or PostScript file, the font that has been used inside Batik has to be mapped to a font used by the actual output format. Features like font substitution in FOP may need to be taken into account but can also be an advantage when working around font mapping issues. Like for XSL-FO content, you'll get a warning if a particular font could not be found and had to be substituted, or if a particular glyph is missing in a font.
Scaling
Currently, SVG images are rendered with the dimensions specified in the SVG file, within the viewport specified in the fo:external-graphic element. For everything to work properly, the two should be equal. The SVG standard leaves this issue as an implementation detail. Additional scaling options are available through XSL-FO means.
If you use pixels to specify the size of an SVG graphic the "source resolution" setting in the configuration will be used to determine the size of a pixel. The use of pixels to specify sizes is discouraged as they may be interpreted differently in different environments.
Known Problems
- Soft mask transparency is combined with white so that it looks better on PDF 1.3 viewers but this causes the soft mask to be slightly lighter or darker on PDF 1.4 viewers.
- There is some problem with a gradient inside a pattern which may cause a PDF error when viewed in Acrobat 5.
- Text is not always handled correctly, it may select the wrong font especially if characters have multiple fonts in the font list.
- Uniform transparency for images and other SVG elements that are converted into a raster graphic are not drawn properly in PDF. The image is opaque.
TIFF
FOP can embed TIFF images without decompression into PDF, PostScript and AFP if they have either CCITT T.4, CCITT T.6, or JPEG compression. Otherwise, a TIFF-capable Image I/O codec is necessary for decoding the image.
There may be some limitation concerning images in the CMYK color space.
WMF
Windows Metafiles (WMF) are supported through classes in Apache Batik. At the moment, support for this format is experimental and may not always work as expected.
Graphics Resolution
Some bitmapped image file formats store a dots-per-inch (dpi) or other resolution values. FOP tries to use this resolution information whenever possible to determine the image's intrinsic size. This size is used during the layout process when it is not superseded by an explicit size on fo:external-graphic (content-width and content-height properties).
Please note that not all images contain resolution information. If it's not available the source resolution set on the FopFactory (or through the user configuration XML) is used. The default here is 72 dpi.
Bitmap images are generally embedded into the output format at their original resolution (as is). No resampling of the image is performed. Explicit resampling is on our wishlist, but hasn't been implemented, yet. Bitmaps included in SVG graphics may be resampled to the resolution specified in the "target resolution" setting in the configuration if SVG filters are applied. This can be used as a work-around to resample images in FO documents.
Page selection for multi-page formats
Some image formats such as TIFF support multiple pages/sub-images per file. You can select a particular page using a special URI fragment in the form: <uri>#page=<nr> (for example: http://localhost/images/myimage.tiff#page=3)
Image caching
FOP caches images between runs. There is one cache per FopFactory instance. The URI is used as a key to identify images which means that when a particular URI appears again, the image is taken from the cache. If you have a servlet that generates a different image each time it is called with the same URI you need to use a constantly changing dummy parameter on the URI to avoid caching.
The image cache has been improved considerably in the redesigned code. Therefore, resetting the image cache should be a thing of the past. If you still experience OutOfMemoryErrors, please notify us.
If all else fails, the image cache can be cleared like this: fopFactory.getImageManager().getCache().clearCache();


Drake booed off stage at Tyler the Creator's music festival
by Christy Somos, CTVNews.ca WriterTORONTO -- Attendees of rapper Tyler the Creator’s Camp Flog Gnaw music festival appeared to boo rapper Drake off stage after he was brought on as a surprise performer.
Drake was revealed as a surprise headliner after other acts including ASAP Rocky and Lil Uzi Vert had already performed, but fans seemed to think that crooner Frank Ocean would be taking the stage – and took their disappointment out on Drake, according to music site Genius.
Video of the fans reacting to Drake onstage trended on Twitter, as users reacted in disbelief at the crowd’s apparent rejection of the artist.