Getting CSS pseudo-element properties by Javascript

You probably wonder if you can access CSS pseudo-element's (like ::before or :: after) properties by Javascript.

The answer is yes, you can, but it's tricky :)

Let's assume you have following HTML/CSS


<p id="myid">some content</p>



#myid::after {
  display:block;
  width: 100px;
  height: 40px;
  color: blue;
  content: "Hello world";
}
#myid {
  color: red;
}


Apparently, "#myid::after" is not in the DOM tree, but following trick will allow you to get its properties:


var color = window.getComputedStyle(document.querySelector('#myid'), ':after').getPropertyValue('color')
var content = window.getComputedStyle(document.querySelector('#myid'), ':after').getPropertyValue('content')
console.log(color, content) // outputs the color and content of the pseudo-element

You might find it useful in test automation or some UI interaction manipulation.

URL parsing using native JS engine approach

The snippet bellow can come in handy when you need basic URL parsing


/**
 * @description URL parsing using native JS engine approach
 * @param {string} url - URL string
 * @returns {object} parsed data
 */

function parseURL(url) {
	var parser = document.createElement('a');
	parser.href = url;
	return {
		protocol : parser.protocol, // => "http:"
		hostname : parser.hostname, // => "domain.com"
		port : parser.port, // => "8000"
		pathname : parser.pathname, // => "/path/"
		search : parser.search, // => "?search=test"
		hash : parser.hash, // => "#hash"
		host : parser.host // => "domain.com:8000"
	}
}

console.dir(parseURL("http://domain.com:8000/path/?search=test&bar=1&bar=2&key1=val1#hash"));

How to check how many threads node.js is using on Linux?

We all know Node is single threaded, however, it's single threaded for a client (to you as a programmer), but the platform itself is multi-threaded (internally). In order to check how many threads your node is using on Linux machine you have 3 different options:

1.
cat /proc/`pidof node`/status | grep Threads

2.
ls /proc/19899/task/ | wc -l

3.
ps hH p `pidof node` | wc -l


Sometimes, it come in handy when you want to automate the load monitoring for example.

What If you want to to determine whether is 64bit or 32bit node executable installed?

You can try 3 following options:

1) Run node cli and type there:
require('os').arch()

3) Or type there:
process.arch

3) Or type there:
process.env.PROCESSOR_ARCHITECTURE


One of them will work for sure! (The latest one doesn't work on my Macbook but does on Win10 machine)

Mongoose 4.0.2 doesn't create indexes

Mongoose 4.0.2 doesn't create indexes automatically for some reason despite of its docs.
So I've found if you add {autoIndex: true} as it's shown bellow, it solves the issue.


var path = require('path');

module.exports = function (mongoose) {
    var Schema = new mongoose.Schema({
        name: {type: String, trim: true, required: true},
        uuid: {type: String, required: true, unique: true, index: true},
        device: {type: mongoose.Schema.Types.Mixed},
        updated_at: {type: Date, default: Date.now}
    }, {autoIndex: true});
    return mongoose.model(path.basename(module.filename, '.js'), Schema);
};

How JSONP works

JSONP is really a simple trick to overcome the XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)

So — instead of using XMLHttpRequest we have to use script HTML tags, the ones you usually use to load js files, in order for js to get data from another domain. Sounds weird?

Thing is — turns out script tags can be used in a fashion similar to XMLHttpRequest! Check this out:
script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://www.someWebApiServer.com/some-data';


You will end up with a script segment that looks like this after it loads the data:
<script>
   {['some string 1', 'some data', 'whatever data']}
</script>


However this is a bit inconvenient, because we have to fetch this array from script tag. So JSONP creators decided that this will work better(and it is):

script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://www.someWebApiServer.com/some-data?callback=my_callback';


Notice the my_callback function over there? So — when JSONP server receives your request and finds callback parameter — instead of returning plain js array it'll return this:
my_callback({['some string 1', 'some data', 'whatever data']});


See where the profit is: now we get automatic callback (my_callback) that'll be triggered once we get the data.
That's all there is to know about JSONP: it's a callback and script tags.

NOTE: these are simple examples of JSONP usage, these are not production ready scripts.

Basic JavaScript example (simple Twitter feed using JSONP)
<html>
    <head>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
        <script>
        function myCallback(dataWeGotViaJsonp){
            var text = '';
            var len = dataWeGotViaJsonp.length;
            for(var i=0;i<len;i++){
                twitterEntry = dataWeGotViaJsonp[i];
                text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
            }
            document.getElementById('twitterFeed').innerHTML = text;
        }
        </script>
        <script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
    </body>
</html>


Basic jQuery example (simple Twitter feed using JSONP)

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $.ajax({
                    url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
                    dataType: 'jsonp',
                    success: function(dataWeGotViaJsonp){
                        var text = '';
                        var len = dataWeGotViaJsonp.length;
                        for(var i=0;i<len;i++){
                            twitterEntry = dataWeGotViaJsonp[i];
                            text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
                        }
                        $('#twitterFeed').html(text);
                    }
                });
            })
        </script>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
    </body>
</html>

JSONP stands for JSON with Padding.

© ThatGuy

The "open with" context menu shows twice the same item fix

If you get something like:



The following command could help this issue, just copy paste this whole line into your terminal

/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -all s,l,u; killall Finder

Really crazy Javascript's Fibonacci implementation

Run it in console and see it's really working :)


  var fib = function (_) {
      for(_=[+[],++[[]][+[]],+[],_],_[++[++[++[[]][+[]]][+[]]][+[]]]=(((_[++[++[++[[]][+[]]][+[]]][+[]]]-(++[[]][+[]]))&(((--[[]][+[]])>>>(++[[]][+[]]))))===(_[++[++[++[[]][+[]]][+[]]][+[]]]-(++[[]][+[]])))?(_[++[++[[]][+[]]][+[]]]=++[[]][+[]],_[++[++[++[[]][+[]]][+[]]][+[]]]-(++[[]][+[]])):+[];_[++[++[++[[]][+[]]][+[]]][+[]]]--;_[+[]]=(_[++[[]][+[]]]=_[++[++[[]][+[]]][+[]]]=_[+[]]+_[++[[]][+[]]])-_[+[]]);
      return _[++[++[[]][+[]]][+[]]];
  }

  console.assert(fib(-1) === 0);
  console.assert(fib(0) === 0);
  console.assert(fib(1) === 1);
  console.assert(fib(2) === 1);
  console.assert(fib(3) === 2);
  console.assert(fib(4) === 3);
  console.assert(fib(5) === 5);
  console.assert(fib(6) === 8);
  console.assert(fib(7) === 13);
  console.assert(fib(32) === 2178309);
  console.assert(fib(46) === 1836311903);
  console.assert(fib(47) === 2971215073);
  console.assert(fib(63) === 6557470319842);

  console.log('done!');


More could be found at: wtfsjs

Properties vs Attributes

A DOM element is an object, a thing in memory. Like most objects in OOP, it has properties. It also, separately, has a map of the attributes defined on the element (usually coming from the markup that the browser read to create the element). Some of the element's properties get their initial values from attributes with the same or similar names (value gets its initial value from the «value» attribute; href gets its initial value from the «href» attribute, but it's not exactly the same value; className from the «class» attribute). Other properties get their initial values in other ways: For instance, the parentNode property gets its value based on what its parent element is; an element always has a style property, whether it has a «style» attribute or not.

Let's consider this anchor in a page at example.com/testing.html:

<a href='foo.html' class='test one' name='fooAnchor' id='fooAnchor'>Hi</a>

Some gratuitous ASCII art (and leaving out a lot of stuff):

+-------------------------------------------+
| a                                         |
+-------------------------------------------+
| href:       "http://example.com/foo.html" |
| name:       "fooAnchor"                   |
| id:         "fooAnchor"                   |
| className:  "test one"                    |
| attributes:                               |
|    href:  "foo.html"                      |
|    name:  "fooAnchor"                     |
|    id:    "fooAnchor"                     |
|    class: "test one"                      |
+-------------------------------------------+

Note that the properties and attributes are distinct.

Now, although they are distinct, because all of this evolved rather than being designed from the ground up, a number of properties write back to the attribute they derived from if you set them. But not all do, and as you can see from href above, the mapping is not always a straight «pass the value on», sometimes there's interpretation involved.

When I talk about properties being properties of an object, I'm not speaking in the abstract. Here's some non-jQuery code:

var link = document.getElementById('fooAnchor');
alert(link.href);                 // alerts "http://example.com/foo.html"
alert(link.getAttribute("href")); // alerts "foo.html"

(Those values are as per most browsers; there's some variation.)

The link object is a real thing, and you can see there's a real distinction between accessing a property on it, and accessing an attribute.

The vast majority of the time, we want to be working with properties. Partially that's because their values (even their names) tend to be more consistent across browsers. We mostly only want to work with attributes when there is no property related to it (custom attributes), or when we know that for that particular attribute, the attribute and the property are not 1:1 (as with href and «href» above).

The standard properties are laid out in the various DOM specs:

DOM2 HTML
DOM2 Core
DOM3 Core

These specs have excellent indexes and I recommend keeping links to them handy; I use them all the time.

Custom attributes would include, for instance, any data-xyz attributes you might put on elements to provide meta-data to your code (now that that's valid as of HTML5, as long as you stick to the data- prefix). (Recent versions of jQuery give you access to data-xyz elements via the data function, but that function does more than that and if you're just dealing with a data-xyz attribute, I'd actually use the attr function to interact with it.)

The attr function used to have some convoluted logic around getting what they thought you wanted, rather than literally getting the attribute. It conflated the concepts. Moving to prop and attr is meant to de-conflate them. There will be some brief confusion, but hopefully a better understanding of what's really going on going forward.

Via (stackoverflow)

Add "Recent Applications" icon to the dock, and disable windows animation

1) To add Recent Applications icon to the dock, open Terminal and copy paste following:

defaults write com.apple.dock persistent-others -array-add '{ "tile-data" = { "list-type" = 1; }; "tile-type" = "recents-tile"; }' && killall Dock


Don't forget to check recent Items settings in System Preferences>General

2) To disable windows animation, open Terminal and copy paste following:
defaults write NSGlobalDomain NSAutomaticWindowAnimationsEnabled -bool NO