I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.
My question was:
I was wondering how can I match two digits but which are not the same. So, it would be fine to match 12, but not 11.
What I have till now is: I have to match strings like “P12”, and I’ve done it with this regex:
^P([1-6]{1})([1-6]{1})$
But now my problem is how to match only strings like P12 or P32 where the numbers do not repeat.
Any help or guidance to reading materials will be grateful.
edit: this is what worked:
^P([1-6]{1})(?!\1)([1-6]{1})$
The answer, by Ignacio Vazquez-Abrams, was:
Use this:
^P((1[2-6])|(2[13-6])|(3[124-6])|(4[1-356])|(5[1-46])|(6[1-5]))$
I finished the course at CodeSchool, and below are my notes from it.
Level 1
Ternary howto with SIAF
var allPacked = true; var readyToGo = true; var adventureTime; adventureTime = allPacked && readyToGo ? function( ){ return "Adventure time is now!" ; }() : function( ){ return "Adventuring has been postponed!" ; }() ; console.log(adventureTime);
Short-circuting, if the this.swords is not empty it takes it immediately, without looking at the thing after the ||
this.swords = this.swords || [];
Same goes for &&, as soon as it finds a first falsy value – it returns that. If all falsy, it returns the last one.
Level 2
If you need lengthy, repetitive access to a value nested deep within a JS Object, then cache the necessary value in a local variable.
var numCritters = location.critters.length; for(var i = 0; i < numCritters; i++){ list += location.critters[i]; } //instead of for(var i = 0; i < location.critters.length; i++){ list += location.critters[i]; } //and even better for(var i = 0, numCritters = location.critters.length; i < numCritters; i++){ list += location.critters[i]; }
Put script tag just before the ending body tag, or you can also leave them in the head section, but add async keyword. Use a list of variables after the keyword var all at once! Use function join() on the array instead of concatenation. with +=. console.time(“string”) is the opening statement to a timer method that will help us measure how long our code is taking to perform. console.timeEnd(“string”) ends it and prints how long it took. “string” has to be the same in both cases.
var now = new Date(); console.log(+now) == console.log(new Number(now));
Level 3
=== compares type and content. instanceof – userful to determine, well, the instance of some object 🙂
function Bird(){} function DatatypeBird(){} function SyntaxBird(){} DatatypeBird.prototype = Object.create(Bird.prototype); SyntaxBird.prototype = Object.create(Bird.prototype);
Runtime error catching:
try{ if(someVar === undefined) throw new ReferenceError(); } catch(err){ if(err instanceof ReferenceError) console.log("Ref err:" + err); //TypeError } finally{ //this will execute no matter what }
Avoid eval, with.
Use num.toFixed(2), parseFloat(), parseInt(num, radix). Radix can be from 2 – 36. typeof along with isNan to determine if the number is trully a number.
Level 4
Namespace is an object that groups and protects related data and methods in JavaScript files.
Say you have a code like this:
var treasureChests = 3; var openChest = function(){ treasureChests--; alert("DA DADADA DAAAAAAA!"); };
you can use namespacing like this:
var DATA = { treasureChests : 3, openChest : function(){ this.treasureChests--; alert("DA DADADA DAAAAAAA!"); } };
You then call the function like this: DATA.openChests().
Closures are a feature of JavaScript, used to cause some properties to be private, bound only to a surrounding function’s local scope, and some properties to be public, accessible by all holders of the namespace.
Private properties are created in the local scope of the function expression. Public properties are built within the object which is then returned to become the namespace. Access to private data is thus possible only because of closure within the larger module.
Say you have a code like this:
var CAVESOFCLARITY = { stalactites: 4235, stalagmites: 3924, bats: 345, SECRET: { treasureChests: 3, openChest: function(){ this.treasureChests--; alert("DA DADADA DAAAAAAA!"); } } };
You would make it into a closure like this:
var CAVESOFCLARITY = function () { var treasureChests = 3; return { stalactites: 4235, stalagmites: 3924, bats: 345, openChest: function () { treasureChests--; alert("DA DADADA DAAAAAAA!"); } }; }();
If a module references globally-scoped variables, it’s a best practice to bring them into the scope of anonymous closure through the use of a specific technique called global imports.
Say the code is like this and uses a global variable named globalAnswer:
var MySomething = function () { var a = 3; return { getA: function() {return a; }, summon: function(){ if(globalAnswer === "42"){ alert("YEP!"); } else{ alert("NOPE"); } } }; }();
You would rewrite this using global imports like this:
var MySomething = function (answer) { var a = 3; return { getA: function() {return a; }, summon: function(){ if(answer === "42"){ alert("YEP!"); } else{ alert("NOPE"); } } }; }(globalAnswer);
Your import ensures clarity of scope within a module. By using a parameter, you protect the global data that might have been overwritten. All imported data becomes locally scoped to the anonymous function, to be used in closure. Thus, when compared with searching the entire scope, import are both clearer and faster.
Augmentation is the term for adding or changing properties in a module after the module has already been built.
In simple augmentation, the module file and the augmentation file do not share their private state. Augmented module properties may only access the private data from their file’s closure. Private data from the original closure will not be lost, and will be accessible to all original properties that referenced it.
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.
My question was:
I got a request from my client that they want to add stars (★) to their email subject (They send these mails through the application we made as a part of bigger CRM for them).
I tried to send a test mail, and the email title is displayed nicely in my Gmail account, and I must agree with my client that it is eye catching, but what came to my mind is that this may be a spam magnet, so I googled about it but I can’t find the actual “don’t do this”.
Generaly, my oppinion would be not to use it, but now I have to explain to the client why. My best explanation whould be there is a probability your emails will be treated as spam
but I don’t have the background for this statement.
Do you have any suggestions about what should I do?
The rather extensive answer, by Kibbee, was:
The only information I could find is on the SpamAssassin page of how to avoid false positives. The only relevant part I found was this part.
Do not use “cute” spellings, Don’t S.P.A.C.E out your words, don’t put str@nge |etters 0r characters into your emails.
SpamAssassin is a very widely used spam filtering tool. However, simply breaking one of the rules (strange characters) alone wouldn’t get an email marked as spam. But combined with some other problems could lead to your email being considered spam. That being said, if your email is a completely legitimate business email, it’s likely that few other rules are triggered, and using the special characters wouldn’t create a huge problem. That being said, you should probably try out a couple test emails on SpamAssassin and a couple other spam filtering tools in order to come to a better conclusion on the emails you plan to send out.
Additionally, there was also a good answer from Nathan White:
Simply explain to your client as you have explained to SO: you stated that the star made it eye catching: this doesn’t directly mean that it will be treated as spam, but you could explain how that concept COULD be considered spam.
If the star is part of their branding, however, this could be quite a nice way in which your client expresses themselves.
Spam emails are becoming more and more like what one would consider ‘normal’, so I think they have trial it internally, test the concept.
Talk it over with your client – there is going to be no basis in hard fact with things like this, purely social perception.
And also by lukeA:
More and more retailers are using unicode symbols in their subject lines since a few months. Of course it’s in order to gain more attention in cluttered inboxes. Until now, there has been absolutely no evidence that such symbols increase the likelihood of failing spam filter tests. However, keep in mind that rare symbols might not render (correctly) across all mail user agents. Especially keep an eye on Android and Blackberry smartphones, but also on Outlook. In addition, due to a Hotmail bug symbols will render much bigger in subect lines and in the email body within the web front end. In fact, they are beeing replaced by images. All in all, the star shouldn’t make any problems. At least, if it’s encoded correctly in the subject line. So, go for it.
Smarterer released its API for free. Even if you’re not into programming, you can still make use of this and give your site visitors a quick skill test (in just 10 questions and 120 seconds), by using their Smarterer Widget Builder.
Simply, search for a test and optionally name it:
and embed it to your widget area (wp terminology) on your site/blog:
Here are few examples you can try:
Recently I wanted to find out how to update field only if the updated value would be new (as in – different from the current one).
After a bit of googling I managed to find the solution which I’m now presenting here for anyone that may need a solution for such an use case:
UPDATE table SET db_field=(CASE db_field WHEN NULL THEN 'new_value' ELSE db_field END);
Here are my notes from a free CodeSchool tutorial sponsored by Google:
Things I wish I were told about Angular.js.
Binding
<!DOCTYPE html> <html> <head> <title>AngularJS Tutorials</title> </head> <body> <div ng-app=""> <input type="text" ng-model="data.message"> <h1>{{data.message}}</h1> </div> <script type="text/javascript" src="angular.js"></script> </body> </html>
Controllers
<html> <body> <div ng-app=""> <div ng-controller="FirstCtrl"> <h1>{{data.message + " world"}}</h1> <div class="{{data.message}}"> Msg... </div> </div> </div> <script type="text/javascript" src="angular.js"></script> <script type="text/javascript" src="main.js"></script> </body> </html> //main.js function FirstCtrl($scope){ $scope.data = {message: "Hello"}; }
Dot
https://www.youtube.com/watch?v=DTx23w4z6Kc
The initial setup:
<div ng-app=""> <input type="text" ng-model="data.message"> <h1>{{ data.message }}</h1> <div ng-controller="FirstCtrl"> <input type="text" ng-model="data.message"> <h1>{{ data.message }}</h1> </div> <div ng-controller="SecondCtrl"> <input type="text" ng-model="data.message"> <h1>{{ data.message }}</h1> </div> </div>
function FirstCtrl($scope) { } function SecondCtrl($scope) { }
In this setup, all three instances of data.message are bound to each other through the first data.message, which is in the scope of the entire application.
If we were to replace the instances of data.message with just message,
<div ng-app=""> <input type="text" ng-model="message"> <h1>{{ message }}</h1> <div ng-controller="FirstCtrl"> <input type="text" ng-model="message"> <h1>{{ message }}</h1> </div> <div ng-controller="SecondCtrl"> <input type="text" ng-model="message"> <h1>{{ message }}</h1> </div> </div>
It breaks the scope inheritance that was binding all the data.message instances. Now, each new ng-model of message is creating a new instance of message, and so each model will be an unbound instance. So, important to note here is the data.message which will be available to all of the controllers!
Sharing data between controllers
https://www.youtube.com/watch?v=HXpHV5gWgyk
The initial setup:
<div ng-app=""> <input type="text" ng-model="data.message"> <h1>{{ data.message }}</h1> <div ng-controller="FirstCtrl"> <input type="text" ng-model="data.message"> <h1>{{ data.message }}</h1> </div> <div ng-controller="SecondCtrl"> <input type="text" ng-model="data.message"> <h1>{{ data.message }}</h1> </div> </div>
function FirstCtrl($scope) { } function SecondCtrl($scope) { }
With this setup, data.message is defined outside of either controller, scoped to the entire ng-app. The bindings within each of the controller divs both point to that ‘parent’ model. Because of this, all 3 instances of the data.message input are bound to each other because of the first instance, which is globally scoped in the application.
If one were to remove the first model that does not reside in a controller, there is no parent model for either controller to bind to, so each instance of data.message will be scoped within its respective controller. Thus, neither data.message will be bound to the other.
We’d like to share the data model between the two controllers without creating a parent scope. This requires a service within a formally defined Angular application.
<div ng-app="myApp"> <div ng-controller="FirstCtrl">
var myApp = angular.module('myApp', []); myApp.factory('Data', function () { return { message: "I'm data from a service" }; }); function FirstCtrl($scope) {
This Data service can be injected into each of the controllers as a parameter. By doing this, we are now attaching the data.model to an app service, which repairs the binding between the two controller models.
Stackoverflow thread on this.
<!DOCTYPE html> <html> <head> <title></title> </head> <body ng-app="myApp"> <div ng-controller="FirstCtrl"> <input type="text" ng-model="data.message"> <h1>{{ data.message }}</h1> </div> <div ng-controller="SecondCtrl"> <input type="text" ng-model="data.message"> <h1>{{ data.message }}</h1> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <script type="text/javascript" charset="utf-8"> angular.module('myApp', []) .factory('Data', function () { return { message: "I'm data from a service" }; }) .controller('FirstCtrl', function ($scope, Data){ $scope.data = Data; }) .controller('SecondCtrl', function ($scope, Data){ $scope.data = Data; }); </script> </body> </html>
Method on a scope
function SecondCtrl($scope, Data) { $scope.data = Data; $scope.reversedMessage = function() { return $scope.data.message.split("").reverse().join(""); }; }
Bootstraping https://docs.angularjs.org/guide/bootstrap
Changing the data in the service and then showing it again, the ultimate example which eluded me for some time (Plunkr):
<!DOCTYPE html> <html> <head> <title></title> </head> <body ng-app="myApp"> <div ng-controller="FirstCtrl"> <input type="text" ng-model="data.msg"> <h1>{{ data.msg }}</h1> <button type="" ng-click="sayItBack()"></button> </div> <div ng-controller="SecondCtrl"> <input type="text" ng-model="data.msg"> <h1>{{ data.msg }}</h1> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <script type="text/javascript" charset="utf-8"> angular.module('myApp', []) .service('Data', function () { this.data = {}; this.data.msg = "Howdy!"; this.getMsg = function() { return this.data; }; this.setMsg = function(city){ this.data.msg = city; }; }) .controller('FirstCtrl', function ($scope, Data){ $scope.data = Data.getMsg(); $scope.sayItBack = function(){ Data.setMsg("Hello to you too!"); } }) .controller('SecondCtrl', function ($scope, Data){ $scope.data = Data.getMsg(); }); </script> </body> </html>
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.
My question was:
I got the following error when running the project from GitHub: “options found in locals object. The option(s) is copied to the option object. This behavior is deprecated and will be removed in EJS 3”
I tried to update the ejs and express modules to the newest versions but the notice persists. I googled, ofc, and the only thread about it is this, but it doesn’t help.
Does anyone know more about this?
For reference, here is the whole important code:
app/views/index.ejs
<!DOCTYPE html> <html> <head> <title><%= title %></title> </head> <body> <h1><%= title %></h1> <img src="img/logo.jpg" alt="Hack Hands logo"> </body> </html>
app/controllers/index.server.controller.js
exports.render = function(req, res) { res.render('index', { title: 'MEAN MVC' }); };
app/routes/index.server.route.js
module.exports = function(app) { var index = require('../controllers/index.server.controller'); app.get('/', index.render); };
app/config/express.js
var express = require('express'); module.exports = function() { var app = express(); app.set('views', './app/views'); app.set('view engine', 'ejs'); require('../app/routes/index.server.routes.js')(app); app.use(express.static('./public')); return app; };
server.js
var port = 1337; var express = require('./config/express'); var app = express(); app.listen(port); module.exports = app; console.log('Server running at http://localhost:' + port);
The answer, by Timothy Gu, was:
tl;dr: Upgrade to the latest version of EJS. It removes all warnings about
options
andlocals
.
whoami
I’m a collaborator (or the collaborator in @micnic’s comment above) in EJS v2. I only started maintaining EJS after version 2.0.3 (or something like that) was released, so I don’t know a lot about how the API changes took place.
History
EJS v2’s
renderFile
function, used by Express.js, now has the signaturefunction(path[, options[, locals]], cb)But for compatibility with and Express.js, which calls all functions as
function(path, locals, cb)with options mixed into the
locals
object, EJS automatically picks out the locals with option-y names and treat them as options.But because the Express.js signature is also the function signature of EJS v1, we also print a warning if any option in
locals
is copied tooptions
, urging developers to use the new signature withlocals
andoptions
separated (it was actually me who added the warning).However, Express.js users do not have a choice in terms of calling convention, so the warning is always present in Express.js.
Some users did complain: #34 #36.
At first, @mde (who is the main maintainer of EJS) pushed a fix, which correctly disables warnings on Express.js, and Express.js only.
But then, the person in #36 still complained, as he was using
filename
as the name of a local, and when the optiony local is copied tooptions
a warning is printed.At last, @mde was like “f*** this shit” and removed all the deprecation warnings, including an uncontroversial and legitimate one, and released version 2.2.4 (the legitimate warning was restored by me after the release).
Future
@dougwilson (an Express.js maintainer) said he was interested in a separation of
options
andlocals
in Express.js v5, just like in EJS v2. I did volunteer to make that change, but then I got busy so yeah.
I listened to the book Time management made simple by Brian Tracy via Audible and honestly this is one of the best I’ve read/listened on this subject.
Make a decision. Every positive change in your life begins with a clear decision that you’re going to do something or stop doing something. Either fish or cut bait.
Self-discipline is the ability to make yourself do what you should do when you should do it whether you feel like it or not.
Develop a clear goals and objectives. Be clear on what is it that you want to achieve.
Plan every day in advance.
6P = prior proper planning prevents poor performance
Working from a to do list will improve your performance by 25% very first day you start practicing it. Think on paper.
ABCDE method for setting priorities.
Select your most valuable desk and then discipline yourself to work on the single task until it is complete.
Eat that frog!
If the first thing you do each morning to get up and eat to live frog, you can be sure that nothing worst will happen all day long. Your frog is the ugliest job you have to do which is most important.
Work from a clean workspace.
Used travel time effectively! Always listen to educational material.
Zero-based thinking – is there anything in my life knowing what I know now I wouldn’t get into today if I had to do it again.
Set clear posteriorities – before you start doing something new you have to stop doing something old.
Keep your life in balance! The reason why you’re working you so that you can earn enough money to enjoy your family, health and the important parts of your personal life.
In life, relationships are everything. For 85% of your success in life will come from your happy relationships with all others. Only 15% happiness will come from your achievement from your work.
It’s quantity of time at home that counts, and quality of time at work.
Everything is hard before it’s easy. Goete
Only 21 days are needed to form a habit.
One minutes spent in planning saves 10 minutes in execution.
If I didn’t read this, will there be any negative consequences? If no – throw it away. It goes the same for information which you can get it elsewhere at a later time.
Doing something extremely well, the need not be done at all is a useless waste of time.
Effectiveness is doing the right things and efficiency is doing the things right.
The person you see is the person you will be. Imagine constantly yourself as a perfect, and you will mold your mind so.
When everyone knows that there’s an award at the end of the road the people around you will be more supportive and it will be even encourage you to work on your job until finished.
Whatever you can do, or dream you can – begin it! Boldness has genius power and magic in it. Goete
Seven years spent in bathroom. Six years eating. Five years waiting in line. Four years cleaning your house. Three years in meetings. One you searching for things. Eight months opening junk mail. Six months of waiting in the red lights. 125 days brushing your teeth. Four minutes per day conversing with your spouse. 30 seconds per day conversing with your children.
Be willing to make a decision and act on it. Be willing to make a mistake if necessary other than to hesitate or delay. The others are so afraid of a mistake that they do nothing.
John C. Gardener once wrote “Mastery it is not something that strikes instantly like a thunderbolt, but the gathering forward to it moves steadily through time, like the weather.”
To earn more, you must learn more.
Read at least one hour per day in your chosen field.
All readers are leaders.
Adult brain only learns something which is immediately applicable.
We only understand something to the degree which we are able to explain it to another person.
Delegate every job that can be done by someone else with a lower hourly rate did you earn.
Would you quit your current job if you got $10 million.
It doesn’t really matter where you’re coming from, it only matters where you’re going.
More child sees you’re committed about him doing his homework, the more it becomes committed to school work.
But she’s ill – she’s not the woman you married. Yes, but I’m still the man she married.
Don’t look at how much you already put in – invest on how the cards are now.
Never given to the temptation to clear the small things first!
Article – if it’s not immediately applicable to you, throw it away.
Building blocks of Express.js on CodeSchool, notes below… If you’re interested for more in depth tutorial about Node.js and Express, make sure you check out the 2nd tutorial (free, OFC) in a MEAN series I made for HackHands named Delving into Node.js and Express web framework.
Level 1
Install Express with npm:
npm install express
Simples web server which responds with Howdy!
var express = require('express'); var app = express(); app.get('/', function(req, res){ res.json("Howdy!"); }); app.listen(1337); //tcp port btw
Test with curl (-i switch prints the headers):
curl -i http://localhost:1337
Redirecting the requests:
res.redirect(301, '/newLink');
Level 2
Static middleware to serve files from folder public.
app.use(express.static('public'));
app.use(function(req, resp, next){ ...some work, when done call Ghost buster, erm, no next(); });
Level 3
app.get('/blocks', function(request, response) { //request.query.limit //if the request was like /api?limit=10 });
app.get('/blocks/:name', function(request, response) { //request.params.name });
Level 4
//npm install body-parser var bodyParser = require('body-parser'); var parseUrlencoded = bodyParser.urlencoded({ extended: false }); //false forces the use of the native querystring Node library app.post('/api', parseUrlencoded, function(request, response) { var blocks = { ... }; var newBlock = request.body; });
Level 5
app.route('/cities') .get(function (request, response) { }) .post(parseUrlencoded, function (request, response) { });
Instead of
app.get('/apiEndpoint', function (request, response) { }); app.post('/apiEndpoint', parseUrlencoded, function (request, response) { });
Using the router to put in different file:
var router = express.Router(); router.route('/', router) .get(function (request, response) { }) .post(parseUrlencoded, function (request, response) { }); router.route('/:name', router) .get(function (request, response) { }) .delete(function (request, response) { }); app.use('/cities', router);
Recent posts
Categories
- Android (3)
- Books (114)
- Programming (22)
- CodeProject (35)
- Daily Thoughts (77)
- Go (3)
- iOS (5)
- JavaScript (127)
- Leadership (1)
- Meetups (8)
- Miscellaneou$ (77)
- Breaking News (8)
- CodeSchool (2)
- Hacker Games (3)
- Pluralsight (7)
- Projects (2)
- Sublime Text (2)
- PHP (6)
- Quick tips (40)
- Servers (8)
- Stack Overflow (81)
- Unity3D (9)
- Windows (8)
- Wordpress (2)