SyntaxFix.com - Programming Questions & Answers Hub For Beginners


Some Of The Best Answers From Latest Asked Questions

How can I execute PHP code from the command line?

On the command line:

php -i | grep sourceguardian

If it's there, then you'll get some text. If not, you won't get a thing.

Why does this CSS margin-top style not work?

Not sure why what you have doesn't work, but you can add

overflow: auto;

to the outer div.

Merge Two Lists in R

Here's some code that I ended up writing, based upon @Andrei's answer but without the elegancy/simplicity. The advantage is that it allows a more complex recursive merge and also differs between elements that should be connected with rbind and those that are just connected with c:

# Decided to move this outside the mapply, not sure this is 
# that important for speed but I imagine redefining the function
# might be somewhat time-consuming
mergeLists_internal <- function(o_element, n_element){
  if (is.list(n_element)){
    # Fill in non-existant element with NA elements
    if (length(n_element) != length(o_element)){
      n_unique <- names(n_element)[! names(n_element) %in% names(o_element)]
      if (length(n_unique) > 0){
        for (n in n_unique){
          if (is.matrix(n_element[[n]])){
            o_element[[n]] <- matrix(NA, 
                                     nrow=nrow(n_element[[n]]), 
                                     ncol=ncol(n_element[[n]]))
          }else{
            o_element[[n]] <- rep(NA, 
                                  times=length(n_element[[n]]))
          }
        }
      }

      o_unique <- names(o_element)[! names(o_element) %in% names(n_element)]
      if (length(o_unique) > 0){
        for (n in o_unique){
          if (is.matrix(n_element[[n]])){
            n_element[[n]] <- matrix(NA, 
                                     nrow=nrow(o_element[[n]]), 
                                     ncol=ncol(o_element[[n]]))
          }else{
            n_element[[n]] <- rep(NA, 
                                  times=length(o_element[[n]]))
          }
        }
      }
    }  

    # Now merge the two lists
    return(mergeLists(o_element, 
                      n_element))

  }
  if(length(n_element)>1){
    new_cols <- ifelse(is.matrix(n_element), ncol(n_element), length(n_element))
    old_cols <- ifelse(is.matrix(o_element), ncol(o_element), length(o_element))
    if (new_cols != old_cols)
      stop("Your length doesn't match on the elements,",
           " new element (", new_cols , ") !=",
           " old element (", old_cols , ")")
  }

  return(rbind(o_element, 
               n_element, 
               deparse.level=0))
  return(c(o_element, 
           n_element))
}
mergeLists <- function(old, new){
  if (is.null(old))
    return (new)

  m <- mapply(mergeLists_internal, old, new, SIMPLIFY=FALSE)
  return(m)
}

Here's my example:

v1 <- list("a"=c(1,2), b="test 1", sublist=list(one=20:21, two=21:22))
v2 <- list("a"=c(3,4), b="test 2", sublist=list(one=10:11, two=11:12, three=1:2))
mergeLists(v1, v2)

This results in:

$a
     [,1] [,2]
[1,]    1    2
[2,]    3    4

$b
[1] "test 1" "test 2"

$sublist
$sublist$one
     [,1] [,2]
[1,]   20   21
[2,]   10   11

$sublist$two
     [,1] [,2]
[1,]   21   22
[2,]   11   12

$sublist$three
     [,1] [,2]
[1,]   NA   NA
[2,]    1    2

Yeah, I know - perhaps not the most logical merge but I have a complex parallel loop that I had to generate a more customized .combine function for, and therefore I wrote this monster :-)

Tree view of a directory/folder in Windows?

In the Windows command prompt you can use "tree /F" to view a tree of the current folder and all descending files & folders.

In File Explorer under Windows 8.1:

  • Select folder
  • Press Shift, right-click mouse, and select "Open command window here"
  • Type tree /f > tree.txt and press Enter
  • Use MS Word to open "tree.txt"
  • The dialog box "File Conversion - tree.txt" will open
  • For "Text encoding" tick the "MS-DOS" option

You now have an editable tree structure file.

This works for versions of Windows from Windows XP to Windows 8.1.

How to get the name of the current Windows user in JavaScript

JavaScript runs in the context of the current HTML document, so it won't be able to determine anything about a current user unless it's in the current page or you do AJAX calls to a server-side script to get more information.

JavaScript will not be able to determine your Windows user name.

How can I create an Asynchronous function in Javascript?

You can use a timer:

setTimeout( yourFn, 0 );

(where yourFn is a reference to your function)

or, with Lodash:

_.defer( yourFn );

Defers invoking the func until the current call stack has cleared. Any additional arguments are provided to func when it's invoked.

How to set a Header field on POST a form?

Here is what I did in pub/jade

extends layout
block content
    script(src="/jquery/dist/jquery.js")
    script.
      function doThePost() {
        var jqXHR = $.ajax({ 
            type:'post'
            , url:<blabla>
            , headers: { 
                'x-custom1': 'blabla'
                , 'x-custom2': 'blabla'
                , 'content-type': 'application/json'
            }
            , data: {
                'id': 123456, blabla
            }
        })
        .done(function(data, status, req) { console.log("done", data, status, req); })
        .fail(function(req, status, err) { console.log("fail", req, status, err); });
      }
    h1= title
    button(onclick='doThePost()') Click

Use a content script to access the page context variables and functions

Underlying cause:
Content scripts are executed in an "isolated world" environment.

Solution::
To access functions/variables of the page context ("main world") you have to inject the code into the page itself using DOM. Same thing if you want to expose your functions/variables to the page context (in your case it's the state() method).

  • Note in case communication with the page script is needed:
    Use DOM CustomEvent handler. Examples: one, two, and three.

  • Note in case chrome API is needed in the page script:
    Since chrome.* APIs can't be used in the page script, you have to use them in the content script and send the results to the page script via DOM messaging (see the note above).

Safety warning:
A page may redefine or augment/hook a built-in prototype so your exposed code may fail if the page did it in an incompatible fashion. If you want to make sure your exposed code runs in a safe environment then you should either a) declare your content script with "run_at": "document_start" and use Methods 2-3 not 1, or b) extract the original native built-ins via an empty iframe, example. Note that with document_start you may need to use DOMContentLoaded event inside the exposed code to wait for DOM.

Table of contents

  • Method 1: Inject another file
  • Method 2: Inject embedded code
  • Method 2b: Using a function
  • Method 3: Using an inline event
  • Dynamic values in the injected code

Method 1: Inject another file

This is the easiest/best method when you have lots of code. Include your actual JS code in a file within your extension, say script.js. Then let your content script be as follows (explained here: Google Chome “Application Shortcut” Custom Javascript):

var s = document.createElement('script');
// TODO: add "script.js" to web_accessible_resources in manifest.json
s.src = chrome.runtime.getURL('script.js');
s.onload = function() {
    this.remove();
};
(document.head || document.documentElement).appendChild(s);

Note: For security reasons, Chrome prevents loading of js files. Your file must be added as a "web_accessible_resources" item (example) :

// manifest.json must include: 
"web_accessible_resources": ["script.js"],

If not, the following error will appear in the console:

Denying load of chrome-extension://[EXTENSIONID]/script.js. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.

Method 2: Inject embedded code

This method is useful when you want to quickly run a small piece of code. (See also: How to disable facebook hotkeys with Chrome extension?).

var actualCode = `// Code here.
// If you want to use a variable, use $ and curly braces.
// For example, to use a fixed random number:
var someFixedRandomValue = ${ Math.random() };
// NOTE: Do not insert unsafe variables in this way, see below
// at "Dynamic values in the injected code"
`;

var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.remove();

Note: template literals are only supported in Chrome 41 and above. If you want the extension to work in Chrome 40-, use:

var actualCode = ['/* Code here. Example: */' + 'alert(0);',
                  '// Beware! This array have to be joined',
                  '// using a newline. Otherwise, missing semicolons',
                  '// or single-line comments (//) will mess up your',
                  '// code ----->'].join('\n');

Method 2b: Using a function

For a big chunk of code, quoting the string is not feasible. Instead of using an array, a function can be used, and stringified:

var actualCode = '(' + function() {
    // All code is executed in a local scope.
    // For example, the following does NOT overwrite the global `alert` method
    var alert = null;
    // To overwrite a global variable, prefix `window`:
    window.alert = null;
} + ')();';
var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.remove();

This method works, because the + operator on strings and a function converts all objects to a string. If you intend on using the code more than once, it's wise to create a function to avoid code repetition. An implementation might look like:

function injectScript(func) {
    var actualCode = '(' + func + ')();'
    ...
}
injectScript(function() {
   alert("Injected script");
});

Note: Since the function is serialized, the original scope, and all bound properties are lost!

var scriptToInject = function() {
    console.log(typeof scriptToInject);
};
injectScript(scriptToInject);
// Console output:  "undefined"

Method 3: Using an inline event

Sometimes, you want to run some code immediately, e.g. to run some code before the <head> element is created. This can be done by inserting a <script> tag with textContent (see method 2/2b).

An alternative, but not recommended is to use inline events. It is not recommended because if the page defines a Content Security policy that forbids inline scripts, then inline event listeners are blocked. Inline scripts injected by the extension, on the other hand, still run. If you still want to use inline events, this is how:

var actualCode = '// Some code example \n' + 
                 'console.log(document.documentElement.outerHTML);';

document.documentElement.setAttribute('onreset', actualCode);
document.documentElement.dispatchEvent(new CustomEvent('reset'));
document.documentElement.removeAttribute('onreset');

Note: This method assumes that there are no other global event listeners that handle the reset event. If there is, you can also pick one of the other global events. Just open the JavaScript console (F12), type document.documentElement.on, and pick on of the available events.

Dynamic values in the injected code

Occasionally, you need to pass an arbitrary variable to the injected function. For example:

var GREETING = "Hi, I'm ";
var NAME = "Rob";
var scriptToInject = function() {
    alert(GREETING + NAME);
};

To inject this code, you need to pass the variables as arguments to the anonymous function. Be sure to implement it correctly! The following will not work:

var scriptToInject = function (GREETING, NAME) { ... };
var actualCode = '(' + scriptToInject + ')(' + GREETING + ',' + NAME + ')';
// The previous will work for numbers and booleans, but not strings.
// To see why, have a look at the resulting string:
var actualCode = "(function(GREETING, NAME) {...})(Hi, I'm ,Rob)";
//                                                 ^^^^^^^^ ^^^ No string literals!

The solution is to use JSON.stringify before passing the argument. Example:

var actualCode = '(' + function(greeting, name) { ...
} + ')(' + JSON.stringify(GREETING) + ',' + JSON.stringify(NAME) + ')';

If you have many variables, it's worthwhile to use JSON.stringify once, to improve readability, as follows:

...
} + ')(' + JSON.stringify([arg1, arg2, arg3, arg4]) + ')';

Bypass popup blocker on window.open when JQuery event.preventDefault() is set

Popup blockers will typically only allow window.open if used during the processing of a user event (like a click). In your case, you're calling window.open later, not during the event, because $.getJSON is asynchronous.

You have two options:

  1. Do something else, rather than window.open.

  2. Make the ajax call synchronous, which is something you should normally avoid like the plague as it locks up the UI of the browser. $.getJSON is equivalent to:

    $.ajax({
      url: url,
      dataType: 'json',
      data: data,
      success: callback
    });
    

    ...and so you can make your $.getJSON call synchronous by mapping your params to the above and adding async: false:

    $.ajax({
        url:      "redirect/" + pageId,
        async:    false,
        dataType: "json",
        data:     {},
        success:  function(status) {
            if (status == null) {
                alert("Error in verifying the status.");
            } else if(!status) {
                $("#agreement").dialog("open");
            } else {
                window.open(redirectionURL);
            }
        }
    });
    

    Again, I don't advocate synchronous ajax calls if you can find any other way to achieve your goal. But if you can't, there you go.

    Here's an example of code that fails the test because of the asynchronous call:

    Live example | Live source (The live links no longer work because of changes to JSBin)

    jQuery(function($) {
      // This version doesn't work, because the window.open is
      // not during the event processing
      $("#theButton").click(function(e) {
        e.preventDefault();
        $.getJSON("http://jsbin.com/uriyip", function() {
          window.open("http://jsbin.com/ubiqev");
        });
      });
    });
    

    And here's an example that does work, using a synchronous call:

    Live example | Live source (The live links no longer work because of changes to JSBin)

    jQuery(function($) {
      // This version does work, because the window.open is
      // during the event processing. But it uses a synchronous
      // ajax call, locking up the browser UI while the call is
      // in progress.
      $("#theButton").click(function(e) {
        e.preventDefault();
        $.ajax({
          url:      "http://jsbin.com/uriyip",
          async:    false,
          dataType: "json",
          success:  function() {
            window.open("http://jsbin.com/ubiqev");
          }
        });
      });
    });
    

How to find the operating system version using JavaScript?

@Ludwig 's solution was brilliant. A couple of fixes (which didn't have to do with operating system, and I couldn't place as a comment on his original posting because this is too long):

  1. IE 11 no longer identifies itself as MS IE.
  2. Chrome on IOS spoofs itself as Safari

Here they are:

(function (window) {
    {
    /* test cases
        alert(
            'browserInfo result: OS: ' + browserInfo.os +' '+ browserInfo.osVersion + '\n'+
                'Browser: ' + browserInfo.browser +' '+ browserInfo.browserVersion + '\n' +
                'Mobile: ' + browserInfo.mobile + '\n' +
                'Cookies: ' + browserInfo.cookies + '\n' +
                'Screen Size: ' + browserInfo.screen
        );
    */
        var unknown = 'Unknown';

        // screen
        var screenSize = '';
        if (screen.width) {
            width = (screen.width) ? screen.width : '';
            height = (screen.height) ? screen.height : '';
            screenSize += '' + width + " x " + height;
        }

        //browser
        var nVer = navigator.appVersion;
        var nAgt = navigator.userAgent;
        var browser = navigator.appName;
        var version = '' + parseFloat(navigator.appVersion);
        var majorVersion = parseInt(navigator.appVersion, 10);
        var nameOffset, verOffset, ix;

        // Opera
        if ((verOffset = nAgt.indexOf('Opera')) != -1) {
            browser = 'Opera';
            version = nAgt.substring(verOffset + 6);
            if ((verOffset = nAgt.indexOf('Version')) != -1) {
                version = nAgt.substring(verOffset + 8);
            }
        }
        // MSIE
        else if ((verOffset = nAgt.indexOf('MSIE')) != -1) {
            browser = 'Microsoft Internet Explorer';
            version = nAgt.substring(verOffset + 5);
        }

        //IE 11 no longer identifies itself as MS IE, so trap it
        //http://stackoverflow.com/questions/17907445/how-to-detect-ie11
        else if ((browser == 'Netscape') && (nAgt.indexOf('Trident/') != -1)) {

            browser = 'Microsoft Internet Explorer';
            version = nAgt.substring(verOffset + 5);
            if ((verOffset = nAgt.indexOf('rv:')) != -1) {
                version = nAgt.substring(verOffset + 3);
            }

        }

        // Chrome
        else if ((verOffset = nAgt.indexOf('Chrome')) != -1) {
            browser = 'Chrome';
            version = nAgt.substring(verOffset + 7);
        }
        // Safari
        else if ((verOffset = nAgt.indexOf('Safari')) != -1) {
            browser = 'Safari';
            version = nAgt.substring(verOffset + 7);
            if ((verOffset = nAgt.indexOf('Version')) != -1) {
                version = nAgt.substring(verOffset + 8);
            }

            // Chrome on iPad identifies itself as Safari. Actual results do not match what Google claims
            //  at: https://developers.google.com/chrome/mobile/docs/user-agent?hl=ja
            //  No mention of chrome in the user agent string. However it does mention CriOS, which presumably
            //  can be keyed on to detect it.
            if (nAgt.indexOf('CriOS') != -1) {
                //Chrome on iPad spoofing Safari...correct it.
                browser = 'Chrome';
                //Don't believe there is a way to grab the accurate version number, so leaving that for now.
            }
        }
        // Firefox
        else if ((verOffset = nAgt.indexOf('Firefox')) != -1) {
            browser = 'Firefox';
            version = nAgt.substring(verOffset + 8);
        }
        // Other browsers
        else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
            browser = nAgt.substring(nameOffset, verOffset);
            version = nAgt.substring(verOffset + 1);
            if (browser.toLowerCase() == browser.toUpperCase()) {
                browser = navigator.appName;
            }
        }
        // trim the version string
        if ((ix = version.indexOf(';')) != -1) version = version.substring(0, ix);
        if ((ix = version.indexOf(' ')) != -1) version = version.substring(0, ix);
        if ((ix = version.indexOf(')')) != -1) version = version.substring(0, ix);

        majorVersion = parseInt('' + version, 10);
        if (isNaN(majorVersion)) {
            version = '' + parseFloat(navigator.appVersion);
            majorVersion = parseInt(navigator.appVersion, 10);
        }

        // mobile version
        var mobile = /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(nVer);

        // cookie
        var cookieEnabled = (navigator.cookieEnabled) ? true : false;

        if (typeof navigator.cookieEnabled == 'undefined' && !cookieEnabled) {
            document.cookie = 'testcookie';
            cookieEnabled = (document.cookie.indexOf('testcookie') != -1) ? true : false;
        }

        // system
        var os = unknown;
        var clientStrings = [
            {s:'Windows 3.11', r:/Win16/},
            {s:'Windows 95', r:/(Windows 95|Win95|Windows_95)/},
            {s:'Windows ME', r:/(Win 9x 4.90|Windows ME)/},
            {s:'Windows 98', r:/(Windows 98|Win98)/},
            {s:'Windows CE', r:/Windows CE/},
            {s:'Windows 2000', r:/(Windows NT 5.0|Windows 2000)/},
            {s:'Windows XP', r:/(Windows NT 5.1|Windows XP)/},
            {s:'Windows Server 2003', r:/Windows NT 5.2/},
            {s:'Windows Vista', r:/Windows NT 6.0/},
            {s:'Windows 7', r:/(Windows 7|Windows NT 6.1)/},
            {s:'Windows 8.1', r:/(Windows 8.1|Windows NT 6.3)/},
            {s:'Windows 8', r:/(Windows 8|Windows NT 6.2)/},
            {s:'Windows NT 4.0', r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},
            {s:'Windows ME', r:/Windows ME/},
            {s:'Android', r:/Android/},
            {s:'Open BSD', r:/OpenBSD/},
            {s:'Sun OS', r:/SunOS/},
            {s:'Linux', r:/(Linux|X11)/},
            {s:'iOS', r:/(iPhone|iPad|iPod)/},
            {s:'Mac OS X', r:/Mac OS X/},
            {s:'Mac OS', r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},
            {s:'QNX', r:/QNX/},
            {s:'UNIX', r:/UNIX/},
            {s:'BeOS', r:/BeOS/},
            {s:'OS/2', r:/OS\/2/},
            {s:'Search Bot', r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}
        ];
        for (var id in clientStrings) {
            var cs = clientStrings[id];
            if (cs.r.test(nAgt)) {
                os = cs.s;
                break;
            }
        }

        var osVersion = unknown;

        if (/Windows/.test(os)) {
            osVersion = /Windows (.*)/.exec(os)[1];
            os = 'Windows';
        }

        switch (os) {
            case 'Mac OS X':
                osVersion = /Mac OS X (10[\.\_\d]+)/.exec(nAgt)[1];
                break;

            case 'Android':
                osVersion = /Android ([\.\_\d]+)/.exec(nAgt)[1];
                break;

            case 'iOS':
                osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer);
                osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
                break;

        }
    }

    window.browserInfo = {
        screen: screenSize,
        browser: browser,
        browserVersion: version,
        mobile: mobile,
        os: os,
        osVersion: osVersion,
        cookies: cookieEnabled
    };
}(this));

How to fast-forward a branch to head?

To anyone that wants to Fast Forward they are not on to another remote branch (including itself) without checking out that branch, you can do:

git fetch origin master:other

This basically fast forwards the index of other to origin/master if you are not on other branch. You can fast forward multiple branches this way.

If you working on another branch for some time, and wanted to update stale branches from remote to their respective head:

git fetch origin master:master other:other etc:etc

Sorting by date & time in descending order?

This is one of the simplest ways to sort record by Date:

SELECT  `Article_Id` ,  `Title` ,  `Source_Link` ,  `Content` ,  `Source` , `Reg_Date`, UNIX_TIMESTAMP(  `Reg_Date` ) AS DATE
FROM article
ORDER BY DATE DESC 

java.math.BigInteger cannot be cast to java.lang.Integer

The column in the database is probably a DECIMAL. You should process it as a BigInteger, not an Integer, otherwise you are losing digits. Or else change the column to int.

Removing pip's cache?

Clear the cache directory where appropriate for your system

Linux and Unix

~/.cache/pip  # and it respects the XDG_CACHE_HOME directory.

OS X

~/Library/Caches/pip

Windows

%LocalAppData%\pip\Cache

UPDATE

With pip 20.1 or later, you can find the full path for your operating system easily by typing this in the command line:

pip cache dir

Example output on my Ubuntu installation:

? pip3 cache dir
/home/tawanda/.cache/pip

Set size of HTML page and browser window

You could use width: 100%; in your css.

Using Jasmine to spy on a function without an object

import * as saveAsFunctions from 'file-saver';
..........
....... 
let saveAs;
            beforeEach(() => {
                saveAs = jasmine.createSpy('saveAs');
            })
            it('should generate the excel on sample request details page', () => {
                spyOn(saveAsFunctions, 'saveAs').and.callFake(saveAs);
                expect(saveAsFunctions.saveAs).toHaveBeenCalled();
            })

This worked for me.

Label word wrapping

If you want some dynamic sizing in conjunction with a word-wrapping label you can do the following:

  1. Put the label inside a panel
  2. Handle the ClientSizeChanged event for the panel, making the label fill the space:

    private void Panel2_ClientSizeChanged(object sender, EventArgs e)
    {
        label1.MaximumSize = new Size((sender as Control).ClientSize.Width - label1.Left, 10000);
    }
    
  3. Set Auto-Size for the label to true

  4. Set Dock for the label to Fill

CSS transition when class removed

CSS transitions work by defining two states for the object using CSS. In your case, you define how the object looks when it has the class "saved" and you define how it looks when it doesn't have the class "saved" (it's normal look). When you remove the class "saved", it will transition to the other state according to the transition settings in place for the object without the "saved" class.

If the CSS transition settings apply to the object (without the "saved" class), then they will apply to both transitions.

We could help more specifically if you included all relevant CSS you're using to with the HTML you've provided.

My guess from looking at your HTML is that your transition CSS settings only apply to .saved and thus when you remove it, there are no controls to specify a CSS setting. You may want to add another class ".fade" that you leave on the object all the time and you can specify your CSS transition settings on that class so they are always in effect.

Dropdown select with images

Check this example .. everything has been done easily http://jsfiddle.net/GHzfD/

EDIT: Updated/working as of 2013, July 02: jsfiddle.net/GHzfD/357

#webmenu{
    width:340px;
}

<select name="webmenu" id="webmenu">
    <option value="calendar" title="http://www.abe.co.nz/edit/image_cache/Hamach_300x60c0.JPG"></option>
    <option value="shopping_cart" title="http://www.nationaldirectory.com.au/sites/itchnomore/thumbs/screenshot2013-01-23at12.05.50pm_300_60.png"></option>
    <option value="cd" title="http://www.mitenterpriseforum.co.uk/wp-content/uploads/2013/01/MIT_EF_logo_300x60.jpg"></option>
    <option value="email"  selected="selected" title="http://annualreport.tacomaartmuseum.org/sites/default/files/L_AnnualReport_300x60.png"></option>
    <option value="faq" title="http://fleetfootmarketing.com/wp-content/uploads/2013/01/Wichita-Apartment-Video-Tours-CTA60-300x50.png"></option>
    <option value="games" title="http://krishnapatrika.com/images/300x50/pellipandiri300-50.gif"></option>
</select>

$("body select").msDropDown();

.htaccess deny from all

A little alternative to @gasp´s answer is to simply put the actual domain name you are running it from. Docs: https://httpd.apache.org/docs/2.4/upgrading.html

In the following example, there is no authentication and all hosts in the example.org domain are allowed access; all other hosts are denied access.

Apache 2.2 configuration:

Order Deny,Allow
Deny from all
Allow from example.org

Apache 2.4 configuration:

Require host example.org

How do I install and use curl on Windows?

Starting with Windows 10 version 1803 (and earlier, with insider build 17063), you don't install curl anymore. Windows includes a native curl.exe (and tar.exe) in C:\Windows\System32\, which you can access right from your regular CMD.

C:\Users\vonc>C:\Windows\System32\curl.exe --version
curl 7.55.1 (Windows) libcurl/7.55.1 WinSSL
Release-Date: [unreleased]
Protocols: dict file ftp ftps http https imap imaps pop3 pop3s smtp smtps telnet tftp
Features: AsynchDNS IPv6 Largefile SSPI Kerberos SPNEGO NTLM SSL

C:\Users\vonc>C:\Windows\System32\tar.exe --version
bsdtar 3.3.2 - libarchive 3.3.2 zlib/1.2.5.f-ipp

See the initial announcement and the release announcement.

Using python PIL to turn a RGB image into a pure black and white image

A PIL only solution for creating a bi-level (black and white) image with a custom threshold:

from PIL import Image
img = Image.open('mB96s.png')
thresh = 200
fn = lambda x : 255 if x > thresh else 0
r = img.convert('L').point(fn, mode='1')
r.save('foo.png')

With just

r = img.convert('1')
r.save('foo.png')

you get a dithered image.

From left to right the input image, the black and white conversion result and the dithered result:

Input Image Black and White Result Dithered Result

You can click on the images to view the unscaled versions.

javascript /jQuery - For Loop

Use a regular for loop and format the index to be used in the selector.

var array = [];
for (var i = 0; i < 4; i++) {
    var selector = '' + i;
    if (selector.length == 1)
        selector = '0' + selector;
    selector = '#event' + selector;
    array.push($(selector, response).html());
}

Request string without GET arguments

Solution:

echoparse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);

Convert string into Date type on Python

While it seems the question was answered per the OP's request, none of the answers give a good way to get a datetime.date object instead of a datetime.datetime. So for those searching and finding this thread:

datetime.date has no .strptime method; use the one on datetime.datetime instead and then call .date() on it to receive the datetime.date object.

Like so:

>>> from datetime import datetime
>>> datetime.strptime('2014-12-04', '%Y-%m-%d').date()
datetime.date(2014, 12, 4)

How to make an introduction page with Doxygen

As of v1.8.8 there is also the option USE_MDFILE_AS_MAINPAGE. So make sure to add your index file, e.g. README.md, to INPUT and set it as this option's value:

INPUT += README.md
USE_MDFILE_AS_MAINPAGE = README.md

Change Twitter Bootstrap Tooltip content on click

Destroy any pre-existing tooltip so we can repopulate with new tooltip content

$(element).tooltip("destroy");    
$(element).tooltip({
    title: message
});

Read input stream twice

You can wrap input stream with PushbackInputStream. PushbackInputStream allows to unread ("write back") bytes which were already read, so you can do like this:

public class StreamTest {
  public static void main(String[] args) throws IOException {
    byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    InputStream originalStream = new ByteArrayInputStream(bytes);

    byte[] readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 1 2 3

    readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 4 5 6

    // now let's wrap it with PushBackInputStream

    originalStream = new ByteArrayInputStream(bytes);

    InputStream wrappedStream = new PushbackInputStream(originalStream, 10); // 10 means that maximnum 10 characters can be "written back" to the stream

    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 1 2 3

    ((PushbackInputStream) wrappedStream).unread(readBytes, 0, readBytes.length);

    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 1 2 3


  }

  private static byte[] getBytes(InputStream is, int howManyBytes) throws IOException {
    System.out.print("Reading stream: ");

    byte[] buf = new byte[howManyBytes];

    int next = 0;
    for (int i = 0; i < howManyBytes; i++) {
      next = is.read();
      if (next > 0) {
        buf[i] = (byte) next;
      }
    }
    return buf;
  }

  private static void printBytes(byte[] buffer) throws IOException {
    System.out.print("Reading stream: ");

    for (int i = 0; i < buffer.length; i++) {
      System.out.print(buffer[i] + " ");
    }
    System.out.println();
  }


}

Please note that PushbackInputStream stores internal buffer of bytes so it really creates a buffer in memory which holds bytes "written back".

Knowing this approach we can go further and combine it with FilterInputStream. FilterInputStream stores original input stream as a delegate. This allows to create new class definition which allows to "unread" original data automatically. The definition of this class is following:

public class TryReadInputStream extends FilterInputStream {
  private final int maxPushbackBufferSize;

  /**
  * Creates a <code>FilterInputStream</code>
  * by assigning the  argument <code>in</code>
  * to the field <code>this.in</code> so as
  * to remember it for later use.
  *
  * @param in the underlying input stream, or <code>null</code> if
  *           this instance is to be created without an underlying stream.
  */
  public TryReadInputStream(InputStream in, int maxPushbackBufferSize) {
    super(new PushbackInputStream(in, maxPushbackBufferSize));
    this.maxPushbackBufferSize = maxPushbackBufferSize;
  }

  /**
   * Reads from input stream the <code>length</code> of bytes to given buffer. The read bytes are still avilable
   * in the stream
   *
   * @param buffer the destination buffer to which read the data
   * @param offset  the start offset in the destination <code>buffer</code>
   * @aram length how many bytes to read from the stream to buff. Length needs to be less than
   *        <code>maxPushbackBufferSize</code> or IOException will be thrown
   *
   * @return number of bytes read
   * @throws java.io.IOException in case length is
   */
  public int tryRead(byte[] buffer, int offset, int length) throws IOException {
    validateMaxLength(length);

    // NOTE: below reading byte by byte instead of "int bytesRead = is.read(firstBytes, 0, maxBytesOfResponseToLog);"
    // because read() guarantees to read a byte

    int bytesRead = 0;

    int nextByte = 0;

    for (int i = 0; (i < length) && (nextByte >= 0); i++) {
      nextByte = read();
      if (nextByte >= 0) {
        buffer[offset + bytesRead++] = (byte) nextByte;
      }
    }

    if (bytesRead > 0) {
      ((PushbackInputStream) in).unread(buffer, offset, bytesRead);
    }

    return bytesRead;

  }

  public byte[] tryRead(int maxBytesToRead) throws IOException {
    validateMaxLength(maxBytesToRead);

    ByteArrayOutputStream baos = new ByteArrayOutputStream(); // as ByteArrayOutputStream to dynamically allocate internal bytes array instead of allocating possibly large buffer (if maxBytesToRead is large)

    // NOTE: below reading byte by byte instead of "int bytesRead = is.read(firstBytes, 0, maxBytesOfResponseToLog);"
    // because read() guarantees to read a byte

    int nextByte = 0;

    for (int i = 0; (i < maxBytesToRead) && (nextByte >= 0); i++) {
      nextByte = read();
      if (nextByte >= 0) {
        baos.write((byte) nextByte);
      }
    }

    byte[] buffer = baos.toByteArray();

    if (buffer.length > 0) {
      ((PushbackInputStream) in).unread(buffer, 0, buffer.length);
    }

    return buffer;

  }

  private void validateMaxLength(int length) throws IOException {
    if (length > maxPushbackBufferSize) {
      throw new IOException(
        "Trying to read more bytes than maxBytesToRead. Max bytes: " + maxPushbackBufferSize + ". Trying to read: " +
        length);
    }
  }

}

This class has two methods. One for reading into existing buffer (defintion is analogous to calling public int read(byte b[], int off, int len) of InputStream class). Second which returns new buffer (this may be more effective if the size of buffer to read is unknown).

Now let's see our class in action:

public class StreamTest2 {
  public static void main(String[] args) throws IOException {
    byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    InputStream originalStream = new ByteArrayInputStream(bytes);

    byte[] readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 1 2 3

    readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 4 5 6

    // now let's use our TryReadInputStream

    originalStream = new ByteArrayInputStream(bytes);

    InputStream wrappedStream = new TryReadInputStream(originalStream, 10);

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); // NOTE: no manual call to "unread"(!) because TryReadInputStream handles this internally
    printBytes(readBytes); // prints 1 2 3

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); 
    printBytes(readBytes); // prints 1 2 3

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3);
    printBytes(readBytes); // prints 1 2 3

    // we can also call normal read which will actually read the bytes without "writing them back"
    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 1 2 3

    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 4 5 6

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); // now we can try read next bytes
    printBytes(readBytes); // prints 7 8 9

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); 
    printBytes(readBytes); // prints 7 8 9


  }



}

Path of assets in CSS files in Symfony 2

I'll post what worked for me, thanks to @xavi-montero.

Put your CSS in your bundle's Resource/public/css directory, and your images in say Resource/public/img.

Change assetic paths to the form 'bundles/mybundle/css/*.css', in your layout.

In config.yml, add rule css_rewrite to assetic:

assetic:
    filters:
        cssrewrite:
            apply_to: "\.css$"

Now install assets and compile with assetic:

$ rm -r app/cache/* # just in case
$ php app/console assets:install --symlink
$ php app/console assetic:dump --env=prod

This is good enough for the development box, and --symlink is useful, so you don't have to reinstall your assets (for example, you add a new image) when you enter through app_dev.php.

For the production server, I just removed the '--symlink' option (in my deployment script), and added this command at the end:

$ rm -r web/bundles/*/css web/bundles/*/js # all this is already compiled, we don't need the originals

All is done. With this, you can use paths like this in your .css files: ../img/picture.jpeg

Single controller with multiple GET methods in ASP.NET Web API

If you have multiple Action within same file then pass the same argument e.g. Id to all Action. This is because action only can identify Id, So instead of giving any name to argument only declare Id like this.


[httpget]
[ActionName("firstAction")] firstAction(string Id)
{.....
.....
}
[httpget]
[ActionName("secondAction")] secondAction(Int Id)
{.....
.....
}
//Now go to webroute.config file under App-start folder and add following
routes.MapHttpRoute(
name: "firstAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);

routes.MapHttpRoute(
name: "secondAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);

how to compare the Java Byte[] array?

If you're trying to use the array as a generic HashMap key, that's not going to work. Consider creating a custom wrapper object that holds the array, and whose equals(...) and hashcode(...) method returns the results from the java.util.Arrays methods. For example...

import java.util.Arrays;

public class MyByteArray {
   private byte[] data;

   // ... constructors, getters methods, setter methods, etc...


   @Override
   public int hashCode() {
      return Arrays.hashCode(data);
   }

   @Override
   public boolean equals(Object obj) {
      if (this == obj)
         return true;
      if (obj == null)
         return false;
      if (getClass() != obj.getClass())
         return false;
      MyByteArray other = (MyByteArray) obj;
      if (!Arrays.equals(data, other.data))
         return false;
      return true;
   }


}

Objects of this wrapper class will work fine as a key for your HashMap<MyByteArray, OtherType> and will allow for clean use of equals(...) and hashCode(...) methods.

How is TeamViewer so fast?

would take time to route through TeamViewer's servers (TeamViewer bypasses corporate Symmetric NATs by simply proxying traffic through their servers)

You'll find that TeamViewer rarely needs to relay traffic through their own servers. TeamViewer penetrates NAT and networks complicated by NAT using NAT traversal (I think it is UDP hole-punching, like Google's libjingle).

They do use their own servers to middle-man in order to do the handshake and connection set-up, but most of the time the relationship between client and server will be P2P (best case, when the hand-shake is successful). If NAT traversal fails, then TeamViewer will indeed relay traffic through its own servers.

I've only ever seen it do this when a client has been behind double-NAT, though.

How to view the Folder and Files in GAC?

Install:

gacutil -i "path_to_the_assembly"

View:

Open in Windows Explorer folder

  • .NET 1.0 - NET 3.5: c:\windows\assembly (%systemroot%\assembly)
  • .NET 4.x: %windir%\Microsoft.NET\assembly

OR gacutil –l

When you are going to install an assembly you have to specify where gacutil can find it, so you have to provide a full path as well. But when an assembly already is in GAC - gacutil know a folder path so it just need an assembly name.

MSDN:

Export and Import all MySQL databases at one time

When you are dumping all database. Obviously it is having large data. So you can prefer below for better:

Creating Backup:

mysqldump -u [user] -p[password]--single-transaction --quick --all-databases | gzip > alldb.sql.gz

If error

-- Warning: Skipping the data of table mysql.event. Specify the --events option explicitly.

Use:

mysqldump -u [user] -p --events --single-transaction --quick --all-databases | gzip > alldb.sql.gz

Restoring Backup:

gunzip < alldb.sql.gz | mysql -u [user] -p[password]

Hope it will help :)

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

As far as I know PKCS#12 is just a certificate/public/private key store. If you extracted a public key from PKCS#12 file, OpenSSH should be able to use it as long as it was extracted in PEM format. You probably already know that you also need a corresponding private key (also in PEM) in order to use it for ssh-public-key authentication.

Get elements by attribute when querySelectorAll is not available without using libraries?

I played a bit around and ended up with this crude solution:

function getElementsByAttribute(attribute, context) {
  var nodeList = (context || document).getElementsByTagName('*');
  var nodeArray = [];
  var iterator = 0;
  var node = null;

  while (node = nodeList[iterator++]) {
    if (node.hasAttribute(attribute)) nodeArray.push(node);
  }

  return nodeArray;
}

The usage is quite simple, and works even in IE8:

getElementsByAttribute('data-foo');
// or with parentNode
getElementsByAttribute('data-foo', document);

http://fiddle.jshell.net/9xaxf6jr/

But I recommend to use querySelector / All for this (and to support older browsers use a polyfill):

document.querySelectorAll('[data-foo]');

Indenting code in Sublime text 2?

First open the sublime text.
than open preferences.
than open Key Bindings -User.
than put the below code

[{"keys": ["ctrl+shift+c"], "command": "reindent"},]

I use CtrlShiftC and you also use other short cut key.

Difference between ApiController and Controller in ASP.NET MVC

In Asp.net Core 3+ Vesrion

Controller: If wants to return anything related to IActionResult & Data also, go for Controllercontroller

ApiController: Used as attribute/notation in API controller. That inherits ControllerBase Class

ControllerBase: If wants to return data only go for ControllerBase class

Use of True, False, and None as return values in Python functions

One thing to ensure is that nothing can reassign your variable. If it is not a Boolean in the end, relying on truthiness will lead to bugs. The beauty of conditional programming in dynamically typed languages :).

The following prints "no".

x = False
if x:
    print 'yes'
else:
    print 'no'

Now let's change x.

x = 'False'

Now the statement prints "yes", because the string is truthy.

if x:
    print 'yes'
else:
    print 'no'

This statement, however, correctly outputs "no".

if x == True:
    print 'yes'
else:
    print 'no'

How to set text size of textview dynamically for different screens

float currentSize = textEdit.getTextSize(); // default size
float newSize = currentSize * 2.0F; // new size is twice bigger than default one
textEdit.setTextSize(newSize);

Is there StartsWith or Contains in t sql with variables?

StartsWith

a) left(@edition, 15) = 'Express Edition'
b) charindex('Express Edition', @edition) = 1

Contains

charindex('Express Edition', @edition) >= 1

Examples

left function

set @isExpress = case when left(@edition, 15) = 'Express Edition' then 1 else 0 end

iif function (starting with SQL Server 2012)

set @isExpress = iif(left(@edition, 15) = 'Express Edition', 1, 0);

charindex function

set @isExpress = iif(charindex('Express Edition', @edition) = 1, 1, 0);

Send multiple checkbox data to PHP via jQuery ajax()

    $.post("test.php", { 'choices[]': ["Jon", "Susan"] });

So I would just iterate over the checked boxes and build the array. Something like.

       var data = { 'user_ids[]' : []};
        $(":checked").each(function() {
       data['user_ids[]'].push($(this).val());
       });
        $.post("ajax.php", data);

Python - How do you run a .py file?

Your command should include the url parameter as stated in the script usage comments. The main function has 2 parameters, url and out (which is set to a default value) C:\python23\python "C:\PathToYourScript\SCRIPT.py" http://yoururl.com "C:\OptionalOutput\"

Rails: How does the respond_to block work?

There is one more thing you should be aware of - MIME.

If you need to use a MIME type and it isn't supported by default, you can register your own handlers in config/initializers/mime_types.rb:

Mime::Type.register "text/markdown", :markdown

Render a string in HTML and preserve spaces and linebreaks

Just style the content with white-space: pre-wrap;.

_x000D_
_x000D_
div {_x000D_
    white-space: pre-wrap;_x000D_
}
_x000D_
<div>_x000D_
This is some text   with some extra spacing    and a_x000D_
few newlines along with some trailing spaces        _x000D_
     and five leading spaces thrown in_x000D_
for                                              good_x000D_
measure                                              _x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I use Apache tomcat 7 built in Host Manager gui?

Solution for a fresh install of Tomcat 7 on Ubuntu 12.04.

Edit this file - /etc/tomcat7/tomcat-users.xml to add this xml section -

<tomcat-users>
<role rolename="admin"/>
<role rolename="admin-gui"/>
<role rolename="manager-gui"/>
<user username="tomcatadmin" password="tomcat2009" roles="admin,admin-gui,manager-gui"/>
</tomcat-users>

restart Tomcat -

service tomcat7 restart

urls to access managers -

  1. tomcat test page - http://localhost:8080/
  2. manager webapp - http://localhost:8080/manager/html
  3. host-manager webapp - http://localhost:8080/host-manager/html

just wanted to put the latest info out there.

Closing a Userform with Unload Me doesn't work

Unload Me only works when its called from userform self. If you want to close a form from another module code (or userform), you need to use the Unload function + userformtoclose name.

I hope its helps

How to change a <select> value from JavaScript

If you would like it to go back to first option try this:

   document.getElementById("select").selectedIndex = 0;

How can I get the average (mean) of selected columns

Try using rowMeans:

z$mean=rowMeans(z[,c("x", "y")], na.rm=TRUE)

  w x  y mean
1 5 1  1    1
2 6 2  2    2
3 7 3  3    3
4 8 4 NA    4

Adding 'serial' to existing column in Postgres

Look at the following commands (especially the commented block).

DROP TABLE foo;
DROP TABLE bar;

CREATE TABLE foo (a int, b text);
CREATE TABLE bar (a serial, b text);

INSERT INTO foo (a, b) SELECT i, 'foo ' || i::text FROM generate_series(1, 5) i;
INSERT INTO bar (b) SELECT 'bar ' || i::text FROM generate_series(1, 5) i;

-- blocks of commands to turn foo into bar
CREATE SEQUENCE foo_a_seq;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
ALTER TABLE foo ALTER COLUMN a SET NOT NULL;
ALTER SEQUENCE foo_a_seq OWNED BY foo.a;    -- 8.2 or later

SELECT MAX(a) FROM foo;
SELECT setval('foo_a_seq', 5);  -- replace 5 by SELECT MAX result

INSERT INTO foo (b) VALUES('teste');
INSERT INTO bar (b) VALUES('teste');

SELECT * FROM foo;
SELECT * FROM bar;

initializing a Guava ImmutableMap

Notice that your error message only contains five K, V pairs, 10 arguments total. This is by design; the ImmutableMap class provides six different of() methods, accepting between zero and five key-value pairings. There is not an of(...) overload accepting a varags parameter because K and V can be different types.

You want an ImmutableMap.Builder:

ImmutableMap<String,String> myMap = ImmutableMap.<String, String>builder()
    .put("key1", "value1") 
    .put("key2", "value2") 
    .put("key3", "value3") 
    .put("key4", "value4") 
    .put("key5", "value5") 
    .put("key6", "value6") 
    .put("key7", "value7") 
    .put("key8", "value8") 
    .put("key9", "value9")
    .build();

Gem Command not found

On CentOS 7 you can do:

yum -y install rubygems-devel

That worked for me.

npm can't find package.json

I found myself here trying to resolve the same error message:

npm ERR! message ENOENT, no such file or directory 'c:\<some_folder>\package.json'

The error could be due to two reasons:

  1. You do not have the package.json
  2. You have the package.json, but you are running npm start in the wrong folder

To troubleshoot the first cause, you need to create a package.json using:

npm init

To fix the second cause, make sure the folder you are running the npm start command is the same folder as the package.json

jQuery click not working for dynamically created items

source: this post

if you created your elements dynamically(using javascript), then this code doesn't work. Because, .click() will attach events to elements that already exists. As you are dynamically creating your elements using javascript, it doesn't work.

For this you have to use some other functions which works on dynamically created elements. This can be done in different ways..

Earlier we have .live() function

$('selector').live('click', function()
{
//your code
});

but .live() is deprecated.This can be replaced by other functions.

Delegate():

Using delegate() function you can click on dynamically generated HTML elements.

Example:

$(document).delegate('selector', 'click', function()
{
 //your code
});

EDIT: The delegate() method was deprecated in version 3.0. Use the on() method instead.

ON():

Using on() function you can click on dynamically generated HTML elements.

Example:

$(document).on('click', 'selector', function()
{
// your code
});

Is there a difference between `continue` and `pass` in a for loop in python?

Difference between pass and continue in a for loop:

So why pass in python?

If you want to create a empty class, method or block.

Examples:

class MyException(Exception):
    pass


try:
   1/0
 except:
   pass

without 'pass' in the above examples will throw IndentationError.

How to exit git log or git diff

Actually, there are three ways to do it, precisely.

Type any of the following 3 commands.

  1. :q
  2. :z or
  3. Ctrl + z

P.S.: Sometimes, for someone, one of these options doesn't seem to work and for others it works.

CSS3 background image transition

If animating opacity is not an option, you can also animate background-size.

For example, I used this CSS to set a backgound-image with a delay.

.before {
  background-size: 0;
}

.after {
  transition: background 0.1s step-end;
  background-image: $path-to-image;
  background-size: 20px 20px;
}

Set specific precision of a BigDecimal

 BigDecimal decPrec = (BigDecimal)yo.get("Avg");
 decPrec = decPrec.setScale(5, RoundingMode.CEILING);
 String value= String.valueOf(decPrec);

This way you can set specific precision of a BigDecimal.

The value of decPrec was 1.5726903423607562595809913132345426 which is rounded off to 1.57267.

Getting the IP address of the current machine using Java

Posting here tested IP ambiguity workaround code from https://issues.apache.org/jira/browse/JCS-40 (InetAddress.getLocalHost() ambiguous on Linux systems):

/**
 * Returns an <code>InetAddress</code> object encapsulating what is most likely the machine's LAN IP address.
 * <p/>
 * This method is intended for use as a replacement of JDK method <code>InetAddress.getLocalHost</code>, because
 * that method is ambiguous on Linux systems. Linux systems enumerate the loopback network interface the same
 * way as regular LAN network interfaces, but the JDK <code>InetAddress.getLocalHost</code> method does not
 * specify the algorithm used to select the address returned under such circumstances, and will often return the
 * loopback address, which is not valid for network communication. Details
 * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4665037">here</a>.
 * <p/>
 * This method will scan all IP addresses on all network interfaces on the host machine to determine the IP address
 * most likely to be the machine's LAN address. If the machine has multiple IP addresses, this method will prefer
 * a site-local IP address (e.g. 192.168.x.x or 10.10.x.x, usually IPv4) if the machine has one (and will return the
 * first site-local address if the machine has more than one), but if the machine does not hold a site-local
 * address, this method will return simply the first non-loopback address found (IPv4 or IPv6).
 * <p/>
 * If this method cannot find a non-loopback address using this selection algorithm, it will fall back to
 * calling and returning the result of JDK method <code>InetAddress.getLocalHost</code>.
 * <p/>
 *
 * @throws UnknownHostException If the LAN address of the machine cannot be found.
 */
private static InetAddress getLocalHostLANAddress() throws UnknownHostException {
    try {
        InetAddress candidateAddress = null;
        // Iterate all NICs (network interface cards)...
        for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
            NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
            // Iterate all IP addresses assigned to each card...
            for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
                InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                if (!inetAddr.isLoopbackAddress()) {

                    if (inetAddr.isSiteLocalAddress()) {
                        // Found non-loopback site-local address. Return it immediately...
                        return inetAddr;
                    }
                    else if (candidateAddress == null) {
                        // Found non-loopback address, but not necessarily site-local.
                        // Store it as a candidate to be returned if site-local address is not subsequently found...
                        candidateAddress = inetAddr;
                        // Note that we don't repeatedly assign non-loopback non-site-local addresses as candidates,
                        // only the first. For subsequent iterations, candidate will be non-null.
                    }
                }
            }
        }
        if (candidateAddress != null) {
            // We did not find a site-local address, but we found some other non-loopback address.
            // Server might have a non-site-local address assigned to its NIC (or it might be running
            // IPv6 which deprecates the "site-local" concept).
            // Return this non-loopback candidate address...
            return candidateAddress;
        }
        // At this point, we did not find a non-loopback address.
        // Fall back to returning whatever InetAddress.getLocalHost() returns...
        InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
        if (jdkSuppliedAddress == null) {
            throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
        }
        return jdkSuppliedAddress;
    }
    catch (Exception e) {
        UnknownHostException unknownHostException = new UnknownHostException("Failed to determine LAN address: " + e);
        unknownHostException.initCause(e);
        throw unknownHostException;
    }
}

HTML not loading CSS file

I have struggled with this same problem (Ubuntu 16.04, Bluefish editor, FireFox, Google Chrome.

Solution: Clear browsing data in Chrome "Settings > Advanced Settings > Clear Browsing Data", In Firefox, "Open Menu image top right tool bar 'Preferences' > Advanced ", look for this image in the menu: Cached Web Content click the button "Clear Now". Browser's cache the .css file and if it has not changed they usually won't reload it. So when you change your .css file clear this web cache and it should work unless a problem exists in your .css file. Peace, Stan

image processing to improve tesseract OCR accuracy

Java version for Sathyaraj's code above:

// Resize
public Bitmap resize(Bitmap img, int newWidth, int newHeight) {
    Bitmap bmap = img.copy(img.getConfig(), true);

    double nWidthFactor = (double) img.getWidth() / (double) newWidth;
    double nHeightFactor = (double) img.getHeight() / (double) newHeight;

    double fx, fy, nx, ny;
    int cx, cy, fr_x, fr_y;
    int color1;
    int color2;
    int color3;
    int color4;
    byte nRed, nGreen, nBlue;

    byte bp1, bp2;

    for (int x = 0; x < bmap.getWidth(); ++x) {
        for (int y = 0; y < bmap.getHeight(); ++y) {

            fr_x = (int) Math.floor(x * nWidthFactor);
            fr_y = (int) Math.floor(y * nHeightFactor);
            cx = fr_x + 1;
            if (cx >= img.getWidth())
                cx = fr_x;
            cy = fr_y + 1;
            if (cy >= img.getHeight())
                cy = fr_y;
            fx = x * nWidthFactor - fr_x;
            fy = y * nHeightFactor - fr_y;
            nx = 1.0 - fx;
            ny = 1.0 - fy;

            color1 = img.getPixel(fr_x, fr_y);
            color2 = img.getPixel(cx, fr_y);
            color3 = img.getPixel(fr_x, cy);
            color4 = img.getPixel(cx, cy);

            // Blue
            bp1 = (byte) (nx * Color.blue(color1) + fx * Color.blue(color2));
            bp2 = (byte) (nx * Color.blue(color3) + fx * Color.blue(color4));
            nBlue = (byte) (ny * (double) (bp1) + fy * (double) (bp2));

            // Green
            bp1 = (byte) (nx * Color.green(color1) + fx * Color.green(color2));
            bp2 = (byte) (nx * Color.green(color3) + fx * Color.green(color4));
            nGreen = (byte) (ny * (double) (bp1) + fy * (double) (bp2));

            // Red
            bp1 = (byte) (nx * Color.red(color1) + fx * Color.red(color2));
            bp2 = (byte) (nx * Color.red(color3) + fx * Color.red(color4));
            nRed = (byte) (ny * (double) (bp1) + fy * (double) (bp2));

            bmap.setPixel(x, y, Color.argb(255, nRed, nGreen, nBlue));
        }
    }

    bmap = setGrayscale(bmap);
    bmap = removeNoise(bmap);

    return bmap;
}

// SetGrayscale
private Bitmap setGrayscale(Bitmap img) {
    Bitmap bmap = img.copy(img.getConfig(), true);
    int c;
    for (int i = 0; i < bmap.getWidth(); i++) {
        for (int j = 0; j < bmap.getHeight(); j++) {
            c = bmap.getPixel(i, j);
            byte gray = (byte) (.299 * Color.red(c) + .587 * Color.green(c)
                    + .114 * Color.blue(c));

            bmap.setPixel(i, j, Color.argb(255, gray, gray, gray));
        }
    }
    return bmap;
}

// RemoveNoise
private Bitmap removeNoise(Bitmap bmap) {
    for (int x = 0; x < bmap.getWidth(); x++) {
        for (int y = 0; y < bmap.getHeight(); y++) {
            int pixel = bmap.getPixel(x, y);
            if (Color.red(pixel) < 162 && Color.green(pixel) < 162 && Color.blue(pixel) < 162) {
                bmap.setPixel(x, y, Color.BLACK);
            }
        }
    }
    for (int x = 0; x < bmap.getWidth(); x++) {
        for (int y = 0; y < bmap.getHeight(); y++) {
            int pixel = bmap.getPixel(x, y);
            if (Color.red(pixel) > 162 && Color.green(pixel) > 162 && Color.blue(pixel) > 162) {
                bmap.setPixel(x, y, Color.WHITE);
            }
        }
    }
    return bmap;
}

HighCharts Hide Series Name from the Legend

Set showInLegend to false.

series: [{
            showInLegend: false,
            name: 'Series',
            data: value                
        }]

Regular expression to check if password is "8 characters including 1 uppercase letter, 1 special character, alphanumeric characters"

_x000D_
_x000D_
var regex =/^(?=.*\d)(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z]).{8,64}$/;

 
function test() {

 if(regex.test(document.getElementById("txtPassword").value)===false)
 {
 alert("Min 6,Max 64,At Least One Uppercase Character,One Lowercase Character,One Numeric Value And One Special Character(!@#$%^&*) Required ");
 }
 else
 {
 alert("Success");
 }
}
_x000D_
<input type="text" id="txtPassword" />
<button id="testBtn" onclick=test()>CheckPassword</button>
_x000D_
_x000D_
_x000D_

Get the last inserted row ID (with SQL statement)

You can use:

SELECT IDENT_CURRENT('tablename')

to access the latest identity for a perticular table.

e.g. Considering following code:

INSERT INTO dbo.MyTable(columns....) VALUES(..........)

INSERT INTO dbo.YourTable(columns....) VALUES(..........)

SELECT IDENT_CURRENT('MyTable')

SELECT IDENT_CURRENT('YourTable')

This would yield to correct value for corresponding tables.

It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.

IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

How to run binary file in Linux

If it is not a typo, as pointed out earlier, it could be wrong compiler options like compiling 64 bit under 32 bit. It must not be a toolchain.

What are the differences and similarities between ffmpeg, libav, and avconv?

Confusing messages

These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".

The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.

The real ffmpeg vs the fake one

For a while both Libav and FFmpeg separately developed their own version of ffmpeg.

Libav then renamed their bizarro ffmpeg to avconv to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv instead of their counterfeit version of ffmpeg. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.

This message was removed upstream when the fake "ffmpeg" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.

In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1. Unfortunately the new "deprecated" message has caused additional user confusion.

Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg is back in the repositories again.

libav vs Libav

To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.

How to tell the difference

If you are using avconv then you are using Libav. If you are using ffmpeg you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.

Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg or avconv and viewing the console output.

If you want to use the real ffmpeg

Ubuntu 15.04 "Vivid Vervet" or newer

The real ffmpeg is in the repository, so you can install it with:

apt-get install ffmpeg

For older Ubuntu versions

Your options are:

These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.

Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg from the repository.

Also see

For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.

CSS3 animate border color

You can use a CSS3 transition for this. Have a look at this example:

http://jsfiddle.net/ujDkf/1/

Here is the main code:

#box {
  position : relative;
  width : 100px;
  height : 100px;
  background-color : gray;
  border : 5px solid black;
  -webkit-transition : border 500ms ease-out;
  -moz-transition : border 500ms ease-out;
  -o-transition : border 500ms ease-out;
  transition : border 500ms ease-out;
}

#box:hover {
   border : 10px solid red;   
}

How to change spinner text size and text color?

Simple and crisp...:

private OnItemSelectedListener OnCatSpinnerCL = new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

       ((TextView) parent.getChildAt(0)).setTextColor(Color.BLUE);
       ((TextView) parent.getChildAt(0)).setTextSize(5);

    }

    public void onNothingSelected(AdapterView<?> parent) {

    }
};

FPDF error: Some data has already been output, can't send PDF

For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:

<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

While this will not (note the leading space before the opening <? tag)

 <?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

Also, this will not work either (the echo will break it):

<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.


add ob_start (); at the top and at the end add ob_end_flush();

<?php
    ob_start();
    require('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,'Hello World!');
    $pdf->Output();
    ob_end_flush(); 
?>

give me an error as below:
FPDF error: Some data has already been output, can't send PDF

to over come this error: go to fpdf.php in that,goto line number 996

function Output($name='', $dest='')

after that make changes like this:

function Output($name='', $dest='') {   
    ob_clean();     //Output PDF to so

Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.

<?

while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);

?>

cheers :-)


In my case i had set:

ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);

When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off the display_errors option, the report was generated successfully.

Get first element in PHP stdObject

Update PHP 7.4

Curly brace access syntax is deprecated since PHP 7.4

Update 2019

Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.

Simply iterate its using {}

Example:

$videos{0}->id

This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and below use this

$videos{0}['id']

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {
  [0]=>
  object(stdClass)#20 (22) {
    ["id"]=>
    string(1) "123"
  etc...

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element
$key = key($obj);

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4


2022 Update:
After PHP 7.4, using current(), end(), etc functions on objects is deprecated.

In newer versions of PHP, use the ArrayIterator class:

$objIterator = new ArrayIterator($obj);

$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object

$key = $objIterator->key(); // and gets the key

How do you split and unsplit a window/view in Eclipse IDE?

This is possible with the menu items Window>Editor>Toggle Split Editor.

Current shortcut for splitting is:

Azerty keyboard:

  • Ctrl + _ for split horizontally, and
  • Ctrl + { for split vertically.

Qwerty US keyboard:

  • Ctrl + Shift + - (accessing _) for split horizontally, and
  • Ctrl + Shift + [ (accessing {) for split vertically.

MacOS - Qwerty US keyboard:

  • + Shift + - (accessing _) for split horizontally, and
  • + Shift + [ (accessing {) for split vertically.

On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:

  • Alt + ASCII code + Ctrl then release Alt

Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.

Example of vertical split:

https://bugs.eclipse.org/bugs/attachment.cgi?id=238285

PS:

  • The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
  • The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
  • The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.

EditText non editable

android:editable="false" should work, but it is deprecated, you should be using android:inputType="none" instead.

Alternatively, if you want to do it in the code you could do this :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);

This is also a viable alternative :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);

If you're going to make your EditText non-editable, may I suggest using the TextView widget instead of the EditText, since using a EditText seems kind of pointless in that case.

EDIT: Altered some information since I've found that android:editable is deprecated, and you should use android:inputType="none", but there is a bug about it on android code; So please check this.

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

How to request Google to re-crawl my website?

There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:

  1. Go to: https://www.google.com/webmasters/tools/ and log in
  2. If you haven't already, add and verify the site with the "Add a Site" button
  3. Click on the site name for the one you want to manage
  4. Click Crawl -> Fetch as Google
  5. Optional: if you want to do a specific page only, type in the URL
  6. Click Fetch
  7. Click Submit to Index
  8. Select either "URL" or "URL and its direct links"
  9. Click OK and you're done.

With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.

Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/

Update 2019:

  1. Login to - Google Search Console
  2. Add a site and verify it with the available methods.
  3. After verification from the console, click on URL Inspection.
  4. In the Search bar on top, enter your website URL or custom URLs for inspection and enter.
  5. After Inspection, it'll show an option to Request Indexing
  6. Click on it and GoogleBot will add your website in a Queue for crawling.

Enabling the OpenSSL in XAMPP

Yes, you must open php.ini and remove the semicolon to:

;extension=php_openssl.dll

If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext) and add this to php.ini in the "Dynamic Extensions" section:

extension=php_openssl.dll

Things have changed for PHP > 7. This is what i had to do for PHP 7.2.

Step: 1: Uncomment extension=openssl

Step: 2: Uncomment extension_dir = "ext"

Step: 3: Restart xampp.

Done.

Explanation: ( From php.ini )

If you wish to have an extension loaded automatically, use the following syntax:

extension=modulename

Note : The syntax used in previous PHP versions (extension=<ext>.so and extension='php_<ext>.dll) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>) syntax.

Special Note: Be sure to appropriately set the extension_dir directive.

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

How can you make a custom keyboard in Android?

Well Suragch gave the best answer so far but he skipped certain minor stuff that was important to getting the app compiled.

I hope to make a better answer than Suragch by improving on his answer. I will add all the missing elements he didnt put.

I compiled my apk using the android app , APK Builder 1.1.0. So let's begin.

To build an Android app we need couple files and folders that are organized in a certain format and capitalized accordingly.

res layout -> xml files depicting how app will look on phone. Similar to how html shapes how web page looks on browser. Allowing your app to fit on screens accordingly.

values -> constant data such as colors.xml, strings.xml, styles.xml. These files must be properly spelt.

drawable -> pics{jpeg, png,...}; Name them anything.

mipmap -> more pics. used for app icon?

xml -> more xml files.

src -> acts like JavaScript in html. layout files will initiate the starting view and your java file will dynamically control the tag elements and trigger events. Events can also be activated directly in the layout.xml just like in html.

AndroidManifest.xml -> This file registers what your app is about. Application name, Type of program, permissions needed, etc. This seems to make Android rather safe. Programs literally cannot do what they didnt ask for in the Manifest.

Now there are 4 types of Android programs, an activity, a service, a content provider, and a broadcast reciever. Our keyboard will be a service, which allows it to run in the background. It will not appear in the list of apps to launch; but it can be uninstalled.

To compile your app, involves gradle, and apk signing. You can research that one or use APK Builder for android. It is super easy.

Now that we understand Android development, let us create the files and folders.

  1. Create the files and folders as I discussed above. My directory wil look as follows:

    • NumPad
      • AndroidManifest.xml
      • src
        • Saragch
          • num_pad
            • MyInputMethodService.java
      • res
        • drawable
          • Suragch_NumPad_icon.png
        • layout
          • key_preview.xml
          • keyboard_view.xml
        • xml
          • method.xml
          • number_pad.xml
        • values
          • colors.xml
          • strings.xml
          • styles.xml

Remember if you are using an ide such as Android Studio it may have a project file.

  1. Write files.

A: NumPad/res/layout/key_preview.xml

<?xml version="1.0" encoding="utf-8"?>
   <TextView
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:gravity="center"
      android:background="@android:color/white"
      android:textColor="@android:color/black"
      android:textSize="30sp">
</TextView>

B: NumPad/res/layout/keyboard_view.xml

<?xml version="1.0" encoding="utf-8"?>
<android.inputmethodservice.KeyboardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/keyboard_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:keyPreviewLayout="@layout/key_preview"
    android:layout_alignParentBottom="true">

</android.inputmethodservice.KeyboardView>

C: NumPad/res/xml/method.xml

<?xml version="1.0" encoding="utf-8"?>
<input-method  xmlns:android="http://schemas.android.com/apk/res/android">
    <subtype  android:imeSubtypeMode="keyboard"/>
</input-method>

D: Numpad/res/xml/number_pad.xml

<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="20%p"
    android:horizontalGap="5dp"
    android:verticalGap="5dp"
    android:keyHeight="60dp">

    <Row>
        <Key android:codes="49" android:keyLabel="1" android:keyEdgeFlags="left"/>
        <Key android:codes="50" android:keyLabel="2"/>
        <Key android:codes="51" android:keyLabel="3"/>
        <Key android:codes="52" android:keyLabel="4"/>
        <Key android:codes="53" android:keyLabel="5" android:keyEdgeFlags="right"/>
    </Row>

    <Row>
        <Key android:codes="54" android:keyLabel="6" android:keyEdgeFlags="left"/>
        <Key android:codes="55" android:keyLabel="7"/>
        <Key android:codes="56" android:keyLabel="8"/>
        <Key android:codes="57" android:keyLabel="9"/>
        <Key android:codes="48" android:keyLabel="0" android:keyEdgeFlags="right"/>
    </Row>

    <Row>
        <Key android:codes="-5"
             android:keyLabel="DELETE"
             android:keyWidth="40%p"
             android:keyEdgeFlags="left"
             android:isRepeatable="true"/>
        <Key android:codes="10"
             android:keyLabel="ENTER"
             android:keyWidth="60%p"
             android:keyEdgeFlags="right"/>
    </Row>

</Keyboard>

Of course this can be easily edited to your liking. You can even use images instead lf words for the label.

Suragch didnt demonstrate the files in the values folder and assumed we had access to Android Studio; which automatically creates them. Good thing I have APK Builder.

E: NumPad/res/values/colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
</resources>

F: NumPad/res/values/strings.xml

<resources>
    <string name="app_name">Suragch NumPad</string>
</resources>

G: NumPad/res/values/styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="android:Theme.Material.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

</resources>

H: Numpad/AndroidManifest.xml

This is the file that was really up for contension. Here I felt I would never compile my program. sob. sob. If you check Suracgh's answer you see he leaves the first set of fields empty, and adds the activity tag in this file. As I said there are four types of Android programs. An activity is a regular app with a launcher icon. This numpad is not an activity! Further he didnt implement any activity.

My friends do not include the activity tag. Your program will compile, and when you try to launch it will crash! As for xmlns:android and uses-sdk; I cant help you there. Just try my settings if they work.

As you can see there is a service tag, which register it as a service. Also service.android:name must be name of public class extending service in our java file. It MUST be capitalized accordingly. Also package is the name of the package we declared in java file.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="Saragch.num_pad">

    <uses-sdk
        android:minSdkVersion="12"
        android:targetSdkVersion="27" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/Suragch_NumPad_icon"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <service
            android:name=".MyInputMethodService"
            android:label="Keyboard Display Name"
            android:permission="android.permission.BIND_INPUT_METHOD">

            <intent-filter>
                <action android:name="android.view.InputMethod"/>
            </intent-filter>

            <meta-data
                android:name="android.view.im"
                android:resource="@xml/method"/>

        </service>

    </application>
</manifest>

I: NumPad/src/Saragch/num_pad/MyInputMethodService.java

Note: I think java is an alternative to src.

This was another problem file but not as contentious as the manifest file. As I know Java good enough to know what is what, what is not. I barely know xml and how it ties in with Android development!

The problem here was he didnt import anything! I mean, he gave us a "complete" file which uses names that couldnt be resolved! InputMethodService, Keyboard, etc. That is bad practice Mr. Suragch. Thanks for helping me out but how did you expect the code to compile if the names cant be resolved?

Following is the correctly edited version. I just happened to pounce upon couple hints to drove me to the right place to learn what exactly to import.

package Saragch.num_pad;

import android.inputmethodservice.InputMethodService;
import android.inputmethodservice.KeyboardView;
import android.inputmethodservice.Keyboard;

import android.text.TextUtils;
import android.view.inputmethod.InputConnection;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


public class MyInputMethodService extends InputMethodService implements KeyboardView.OnKeyboardActionListener 
{
    @Override
    public View onCreateInputView() 
    {
     // get the KeyboardView and add our Keyboard layout to it
     KeyboardView keyboardView = (KeyboardView)getLayoutInflater().inflate(R.layout.keyboard_view, null);
     Keyboard keyboard = new Keyboard(this, R.xml.number_pad);
     keyboardView.setKeyboard(keyboard);
     keyboardView.setOnKeyboardActionListener(this);
     return keyboardView;
    }

    @Override
    public void onKey(int primaryCode, int[] keyCodes) 
    {

        InputConnection ic = getCurrentInputConnection();

        if (ic == null) return;

        switch (primaryCode)
        {
         case Keyboard.KEYCODE_DELETE:
            CharSequence selectedText = ic.getSelectedText(0);

            if (TextUtils.isEmpty(selectedText)) 
            {
             // no selection, so delete previous character
             ic.deleteSurroundingText(1, 0);
            }

            else 
            {
             // delete the selection
             ic.commitText("", 1);
            }

            ic.deleteSurroundingText(1, 0);
            break;

         default:
            char code = (char) primaryCode;
            ic.commitText(String.valueOf(code), 1);
        }
    }

    @Override
    public void onPress(int primaryCode) { }

    @Override
    public void onRelease(int primaryCode) { }

    @Override
    public void onText(CharSequence text) { }

    @Override
    public void swipeLeft() { }

    @Override
    public void swipeRight() { }

    @Override
    public void swipeDown() { }

    @Override
    public void swipeUp() { }
}
  1. Compile and sign your project.

    This is where I am clueless as a newby Android developer. I would like to learn it manually, as I believe real programmers can compile manually.

I think gradle is one of the tools for compiling and packaging to apk. apk seems to be like a jar file or a rar for zip file. There are then two types of signing. debug key which is not alllowed on play store and private key.

Well lets give Mr. Saragch a hand. And thank you for watching my video. Like, subscribe.