Programs & Examples On #Browser

A web browser or Internet browser is a software application for retrieving, presenting, and traversing information resources on the World Wide Web.

How can I resize an image dynamically with CSS as the browser width/height changes?

This can be done with pure CSS and does not even require media queries.

To make the images flexible, simply add max-width:100% and height:auto. Image max-width:100% and height:auto works in IE7, but not in IE8 (yes, another weird IE bug). To fix this, you need to add width:auto\9 for IE8.

source: http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries

CSS:

img {
    max-width: 100%;
    height: auto;
    width: auto\9; /* ie8 */
}

And if you want to enforce a fixed max width of the image, just place it inside a container, for example:

<div style="max-width:500px;">
    <img src="..." />
</div>

JSFiddle example here. No JavaScript required. Works in latest versions of Chrome, Firefox and IE (which is all I've tested).

Onclick javascript to make browser go back to previous page?

<input name="action" type="submit" value="Cancel" onclick="window.history.back();"/> 

How do I hide javascript code in a webpage?

I'm not sure there's a way to hide that information. No matter what you do to obfuscate or hide whatever you're doing in JavaScript, it still comes down to the fact that your browser needs to load it in order to use it. Modern browsers have web debugging/analysis tools out of the box that make extracting and viewing scripts trivial (just hit F12 in Chrome, for example).

If you're worried about exposing some kind of trade secret or algorithm, then your only recourse is to encapsulate that logic in a web service call and have your page invoke that functionality via AJAX.

How to detect page zoom level in all modern browsers?

This answer is based on comments about devicePixelRatio coming back incorrectly on user1080381's answer.

I found that this command was coming back incorrectly in some instances too when working with a desktop, Surface Pro 3, and Surface Pro 4.

What I found is that it worked on my desktop, but the SP3 and SP4 were giving different numbers from each other and the desktop.

I noticed though that the SP3 was coming back as 1 and a half times the zoom level I was expecting. When I took a look at the display settings, the SP3 was actually set to 150% instead of the 100% I had on my desktop.

So, the solution to the comments should be to divide the returned zoom level by the scale of the machine you are currently on.

I was able to get the scale in the Windows settings by doing the following:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DesktopMonitor");
double deviceScale = Convert.ToDouble(searcher.Get().OfType<ManagementObject>().FirstOrDefault()["PixelsPerXLogicalInch"]);
int standardPixelPerInch = 96;
return deviceScale / standardPixelPerInch;

So in the case of my SP3, this is how this code looks at 100% zoom:

devicePixelRatio = 1.5
deviceScale = 144
deviceScale / standardPixelPerInch = 1.5
devicePixelRatio / (deviceScale / standardPixelPerInch) = 1

Multiplying by the 100 in user1080381's original answer then would give you a zoom of 100 (%).

How to force reloading a page when using browser back button?

Just use jquery :

jQuery( document ).ready(function( $ ) {

   //Use this inside your document ready jQuery 
   $(window).on('popstate', function() {
      location.reload(true);
   });

});

The above will work 100% when back or forward button has been clicked using ajax as well.

if it doesn't, there must be a misconfiguration in a different part of the script.

For example it might not reload if something like one of the example in the previous post is used window.history.pushState('', null, './');

so when you do use history.pushState(); make sure you use it properly.

Suggestion in most cases you will just need:

history.pushState(url, '', url); 

No window.history... and make sure url is defined.

Hope that helps..

Detect if device is iOS

A simplified, easy to extend version.

var iOS = ['iPad', 'iPhone', 'iPod'].indexOf(navigator.platform) >= 0;

how to install multiple versions of IE on the same system?

I would use VMs. Create an XP (or whatever) VM using VMware Workstation or similar product, and snapshot it. That is your oldest version. Then perform the upgrades one at a time, and snapshot each time. Then you can switch to any snapshot you need later, or clone independent VMs based on all the snapshots so you can run them all at once. You probably want to test on different operating systems as well as different versions, so VMs generalize that solution as well rather than some one-off solution of hacking multiple IEs to coexist on a single instance of Windows.

How to disable CSS in Browser for testing purposes

you can block any request (even for a single css file) from inspector with the following:
    Right click > block request URL
without disabling other css files > https://umaar.com/dev-tips/68-block-requests/ It's a standard inspector feature, no plugins or tricks needed

Check if Internet Connection Exists with jQuery?

5 years later-version:

Today, there are JS libraries for you, if you don't want to get into the nitty gritty of the different methods described on this page.

On of these is https://github.com/hubspot/offline. It checks for the connectivity of a pre-defined URI, by default your favicon. It automatically detects when the user's connectivity has been reestablished and provides neat events like up and down, which you can bind to in order to update your UI.

Where can I find the default timeout settings for all browsers?

I managed to find network.http.connect.timeout for much older versions of Mozilla:

This preference was one of several added to allow low-level tweaking of the HTTP networking code. After a portion of the same code was significantly rewritten in 2001, the preference ceased to have any effect (as noted in all.js as early as September 2001).

Currently, the timeout is determined by the system-level connection establishment timeout. Adding a way to configure this value is considered low-priority.

It would seem that network.http.connect.timeout hasn't done anything for some time.

I also saw references to network.http.request.timeout, so I did a Google search. The results include lots of links to people recommending that others include it in about:config in what appears to be a mistaken belief that it actually does something, since the same search turns up this about:config entries article:

Pref removed (unused). Previously: HTTP-specific network timeout. Default value is 120.

The same page includes additional information about network.http.connect.timeout:

Pref removed (unused). Previously: determines how long to wait for a response until registering a timeout. Default value is 30.

Disclaimer: The information on the MozillaZine Knowledge Base may be incorrect, incomplete or out-of-date.

How do I open a URL from C++?

Here's an example in windows code using winsock.

#include <winsock2.h>
#include <windows.h>
#include <iostream>
#include <string>
#include <locale>
#pragma comment(lib,"ws2_32.lib")
using namespace std;

string website_HTML;
locale local;


void get_Website(char *url );

int main ()
{
    //open website
    get_Website("www.google.com" );

    //format website HTML
    for (size_t i=0; i<website_HTML.length(); ++i) 
        website_HTML[i]= tolower(website_HTML[i],local);

    //display HTML
    cout <<website_HTML;

    cout<<"\n\n";



    return 0;
}



//***************************
void get_Website(char *url )
{
    WSADATA wsaData;
    SOCKET Socket;
    SOCKADDR_IN SockAddr;


    int lineCount=0;
    int rowCount=0;

    struct hostent *host;
    char *get_http= new char[256];

        memset(get_http,' ', sizeof(get_http) );
        strcpy(get_http,"GET / HTTP/1.1\r\nHost: ");
        strcat(get_http,url);
        strcat(get_http,"\r\nConnection: close\r\n\r\n");

        if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) 
        {
            cout << "WSAStartup failed.\n";
            system("pause");
            //return 1;
        }

        Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
        host = gethostbyname(url);

        SockAddr.sin_port=htons(80);
        SockAddr.sin_family=AF_INET;
        SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);

        cout << "Connecting to "<< url<<" ...\n";

        if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0)
        {
            cout << "Could not connect";
            system("pause");
            //return 1;
        }

        cout << "Connected.\n";     
        send(Socket,get_http, strlen(get_http),0 );

        char buffer[10000];

        int nDataLength;
            while ((nDataLength = recv(Socket,buffer,10000,0)) > 0)
            {       
                int i = 0;

                while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') 
                {                    
                    website_HTML+=buffer[i];                     
                    i += 1;
                }               
            }
        closesocket(Socket);
        WSACleanup();

            delete[] get_http;
}

Javascript communication between browser tabs/windows

You can communicate between windows (tabbed or not) if they have a child-parent relationship.

Create and update a child window:

<html>
<head>
<title>Cross window test script</title>
<script>
var i = 0;
function open_and_run() {
    var w2 = window.open("", "winCounter"); 
    var myVar=setInterval(function(){myTimer(w2)},1000);
}

function myTimer(w2) {
    i++;
    w2.document.body.innerHTML="<center><h1>" + i + "</h1><p></center>";
}
</script>
</head>
<body>
Click to open a new window 
<button onclick="open_and_run();">Test This!</button>    
</body>
</html>

Child windows can use the parent object to communicate with the parent that spawned it, so you could control the music player from either window.

See it in action here: https://jsbin.com/cokipotajo/edit?html,js,output

Best way to check for IE less than 9 in JavaScript without library

var ie = !-[1,]; // true if IE less than 9

This hack is supported in ie5,6,7,8. It is fixed in ie9+ (so it suits demands of this question). This hack works in all IE compatibility modes.

How it works: ie engine treat array with empty element (like this [,1]) as array with two elements, instead other browsers think that there is only one element. So when we convert this array to number with + operator we do something like that: (',1' in ie / '1' in others)*1 and we get NaN in ie and 1 in others. Than we transform it to boolean and reverse value with !. Simple. By the way we can use shorter version without ! sign, but value will be reversed.

This is the shortest hack by now. And I am the author ;)

Changing the browser zoom level

_x000D_
_x000D_
<html>_x000D_
  <head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
        <script>_x000D_
        var currFFZoom = 1;_x000D_
        var currIEZoom = 100;_x000D_
_x000D_
        function plus(){_x000D_
            //alert('sad');_x000D_
                var step = 0.02;_x000D_
                currFFZoom += step;_x000D_
                $('body').css('MozTransform','scale(' + currFFZoom + ')');_x000D_
                var stepie = 2;_x000D_
                currIEZoom += stepie;_x000D_
                $('body').css('zoom', ' ' + currIEZoom + '%');_x000D_
_x000D_
        };_x000D_
        function minus(){_x000D_
            //alert('sad');_x000D_
                var step = 0.02;_x000D_
                currFFZoom -= step;_x000D_
                $('body').css('MozTransform','scale(' + currFFZoom + ')');_x000D_
                var stepie = 2;_x000D_
                currIEZoom -= stepie;_x000D_
                $('body').css('zoom', ' ' + currIEZoom + '%');_x000D_
        };_x000D_
    </script>_x000D_
    </head>_x000D_
<body>_x000D_
<!--zoom controls-->_x000D_
                        <a id="minusBtn" onclick="minus()">------</a>_x000D_
                        <a id="plusBtn" onclick="plus()">++++++</a>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

in Firefox will not change the zoom only change scale!!!

Lightweight XML Viewer that can handle large files

TextPad has a free xmltidy plugin that pretty-prints your XML. Nice and fast, although TextPad is shareware.

Preventing iframe caching in browser

Make the URL of the iframe point to a page on your site which acts as a proxy to retrieve and return the actual contents of the iframe. Now you are no longer bound by the same-origin policy (EDIT: does not prevent the iframe caching issue).

Difference between F5, Ctrl + F5 and click on refresh button?

I did small research regarding this topic and found different behavior for the browsers:

enter image description here

See my blog post "Behind refresh button" for more details.

Browser back button handling

Warn/confirm User if Back button is Pressed is as below.

window.onbeforeunload = function() { return "Your work will be lost."; };

You can get more information using below mentioned links.

Disable Back Button in Browser using JavaScript

I hope this will help to you.

Javascript - How to extract filename from a file input control

var pieces = str.split('\\');
var filename = pieces[pieces.length-1];

How to encode the filename parameter of Content-Disposition header in HTTP?

There is a simple and very robust alternative: use a URL that contains the filename you want.

When the name after the last slash is the one you want, you don't need any extra headers!

This trick works:

/real_script.php/fake_filename.doc

And if your server supports URL rewriting (e.g. mod_rewrite in Apache) then you can fully hide the script part.

Characters in URLs should be in UTF-8, urlencoded byte-by-byte:

/mot%C3%B6rhead   # motörhead

What is the maximum possible length of a query string?

Different web stacks do support different lengths of http-requests. I know from experience that the early stacks of Safari only supported 4000 characters and thus had difficulty handling ASP.net pages because of the USER-STATE. This is even for POST, so you would have to check the browser and see what the stack limit is. I think that you may reach a limit even on newer browsers. I cannot remember but one of them (IE6, I think) had a limit of 16-bit limit, 32,768 or something.

How to copy text to the client's clipboard using jQuery?

Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.

Here's how to do it for Internet Explorer:

function copy (str)
{
    //for IE ONLY!
    window.clipboardData.setData('Text',str);
}

Open an html page in default browser with VBA?

I find the most simple is

shell "explorer.exe URL"

This also works to open local folders.

Correct MIME Type for favicon.ico?

I have noticed that when using type="image/vnd.microsoft.icon", the favicon fails to appear when the browser is not connected to the internet. But type="image/x-icon" works whether the browser can connect to the internet, or not. When developing, at times I am not connected to the internet.

Make browser window blink in task Bar

function blinkTab() {
        const browserTitle = document.title;
        let timeoutId;
        let message = 'My New Title';

        const stopBlinking = () => {
            document.title = browserTitle;
            clearInterval(timeoutId);
        };

        const startBlinking = () => {
            document.title = document.title  === message ? browserTitle : message;
        };

        function registerEvents() {
            window.addEventListener("focus", function(event) { 
                stopBlinking();
            });

            window.addEventListener("blur", function(event) {
                const timeoutId = setInterval(startBlinking, 500);
            });
        };

        registerEvents();
    };


    blinkTab();

What is JavaScript's highest integer value that a number can go to without losing precision?

>= ES6:

Number.MIN_SAFE_INTEGER;
Number.MAX_SAFE_INTEGER;

<= ES5

From the reference:

Number.MAX_VALUE;
Number.MIN_VALUE;

_x000D_
_x000D_
console.log('MIN_VALUE', Number.MIN_VALUE);
console.log('MAX_VALUE', Number.MAX_VALUE);

console.log('MIN_SAFE_INTEGER', Number.MIN_SAFE_INTEGER); //ES6
console.log('MAX_SAFE_INTEGER', Number.MAX_SAFE_INTEGER); //ES6
_x000D_
_x000D_
_x000D_

How does cookie based authentication work?

I realize this is years late, but I thought I could expand on Conor's answer and add a little bit more to the discussion.

Can someone give me a step by step description of how cookie based authentication works? I've never done anything involving either authentication or cookies. What does the browser need to do? What does the server need to do? In what order? How do we keep things secure?

Step 1: Client > Signing up

Before anything else, the user has to sign up. The client posts a HTTP request to the server containing his/her username and password.

Step 2: Server > Handling sign up

The server receives this request and hashes the password before storing the username and password in your database. This way, if someone gains access to your database they won't see your users' actual passwords.

Step 3: Client > User login

Now your user logs in. He/she provides their username/password and again, this is posted as a HTTP request to the server.

Step 4: Server > Validating login

The server looks up the username in the database, hashes the supplied login password, and compares it to the previously hashed password in the database. If it doesn't check out, we may deny them access by sending a 401 status code and ending the request.

Step 5: Server > Generating access token

If everything checks out, we're going to create an access token, which uniquely identifies the user's session. Still in the server, we do two things with the access token:

  1. Store it in the database associated with that user
  2. Attach it to a response cookie to be returned to the client. Be sure to set an expiration date/time to limit the user's session

Henceforth, the cookies will be attached to every request (and response) made between the client and server.

Step 6: Client > Making page requests

Back on the client side, we are now logged in. Every time the client makes a request for a page that requires authorization (i.e. they need to be logged in), the server obtains the access token from the cookie and checks it against the one in the database associated with that user. If it checks out, access is granted.

This should get you started. Be sure to clear the cookies upon logout!

How can you detect the version of a browser?

This is an improvement on Kennebec's answer.

_x000D_
_x000D_
function get_browser() {_x000D_
    var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; _x000D_
    if(/trident/i.test(M[1])){_x000D_
        tem=/\brv[ :]+(\d+)/g.exec(ua) || []; _x000D_
        return {name:'IE',version:(tem[1]||'')};_x000D_
        }   _x000D_
    if(M[1]==='Chrome'){_x000D_
        tem=ua.match(/\bOPR|Edge\/(\d+)/)_x000D_
        if(tem!=null)   {return {name:'Opera', version:tem[1]};}_x000D_
        }   _x000D_
    M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];_x000D_
    if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);}_x000D_
    return {_x000D_
      name: M[0],_x000D_
      version: M[1]_x000D_
    };_x000D_
 }_x000D_
_x000D_
var browser=get_browser(); // browser.name = 'Chrome'_x000D_
                           // browser.version = '40'_x000D_
_x000D_
console.log(browser);
_x000D_
_x000D_
_x000D_

This way you can shield yourself from the obscurity of the code.

Disable browser 'Save Password' functionality

The simplest way to solve this problem is to place INPUT fields outside the FORM tag and add two hidden fields inside the FORM tag. Then in a submit event listener before the form data gets submitted to server copy values from visible input to the invisible ones.

Here's an example (you can't run it here, since the form action is not set to a real login script):

_x000D_
_x000D_
<!doctype html>_x000D_
<html>_x000D_
<head>_x000D_
  <title>Login & Save password test</title>_x000D_
  <meta charset="utf-8">_x000D_
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>_x000D_
</head>_x000D_
_x000D_
  <body>_x000D_
      <!-- the following fields will show on page, but are not part of the form -->_x000D_
      <input class="username" type="text" placeholder="Username" />_x000D_
      <input class="password" type="password" placeholder="Password" />_x000D_
_x000D_
      <form id="loginForm" action="login.aspx" method="post">_x000D_
        <!-- thw following two fields are part of the form, but are not visible -->_x000D_
        <input name="username" id="username" type="hidden" />_x000D_
        <input name="password" id="password" type="hidden" />_x000D_
        <!-- standard submit button -->_x000D_
        <button type="submit">Login</button>_x000D_
      </form>_x000D_
_x000D_
    <script>_x000D_
      // attache a event listener which will get called just before the form data is sent to server_x000D_
      $('form').submit(function(ev) {_x000D_
        console.log('xxx');_x000D_
        // read the value from the visible INPUT and save it to invisible one_x000D_
        // ... so that it gets sent to the server_x000D_
        $('#username').val($('.username').val());_x000D_
        $('#password').val($('.password').val());_x000D_
      });_x000D_
    </script>_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Disabling Chrome cache for website development

Using Ctrl+Shift+R to refresh was nice but didn't get everything I needed. still some things wouldn't refresh, such as data stored in js and css. found a solution: a toolbar of google for chrome web developers. After you install the toolbar select options and "reset page".

How to clear browser cache with php?

With recent browser support of "Clear-Site-Data" headers, you can clear different types of data: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data

header('Clear-Site-Data: "cache", "cookies", "storage", "executionContexts"');

Disabling browser print options (headers, footers, margins) from page?

Try this code, works 100% for me:
FOR Landscape:

<head>
<style type="text/css">

@page{
  size: auto A4 landscape;
  margin: 3mm;
}

</style>
</head>

FOR Portait:

<head>
<style type="text/css">

@page{
  size: auto;
  margin: 3mm;
}

</style>
</head>

How to deal with certificates using Selenium?

    ChromeOptions options = new ChromeOptions().addArguments("--proxy-server=http://" + proxy);
    options.setAcceptInsecureCerts(true);

How to launch an application from a browser?

The correct method is to register your custom URL Protocol in windows registry as follows:

[HKEY_CLASSES_ROOT\customurl]
@="Description here"
"URL Protocol"=""

[HKEY_CLASSES_ROOT\customurl\shell]

[HKEY_CLASSES_ROOT\customurl\shell\open]

[HKEY_CLASSES_ROOT\customurl\shell\open\command]
@="\"C:\\Path To Your EXE\\ExeName.exe\" \"%1\""

Once the above keys and values are added, from the web page, just call "customurl:\\parameter1=xxx&parameter2=xxx" . You will receive the entire url as the argument in exe, which you need to process inside your exe. Change 'customurl' with the text of your choice.

How to get scrollbar position with Javascript?

it's like this :)

window.addEventListener("scroll", (event) => {
    let scroll = this.scrollY;
    console.log(scroll)
});

Open a webpage in the default browser

Dim URL As String 
Dim browser As String = TextBox1.Text
URL = TextBox1.Text
Try
    If Not (browser = TextBox1.Text) Then
        Try
            Process.Start(browser, URL)
        Catch ex As Exception
            Process.Start(URL)
        End Try
    Else
        Process.Start(URL)
    End If

Catch ex As Exception
    MsgBox("There's something wrong!")
End Try

Display PDF within web browser

The simple solution is to put it in an iframe and hope that the user has a plug-in that supports it.

(I don't, the Acrobat plugin has been such a resource hog and source of instability that I make a point to remove it from any browser that it touches).

The complicated, but relative popular solution is to display it in a flash applet.

How do I render a Word document (.doc, .docx) in the browser using JavaScript?

There seem to be some js libraries that can handle .docx (not .doc) to html conversion client-side (in no particular order):

Note: If you are looking for the best way to convert a doc/docx file on the client side, then probably the answer is don't do it. If you really need to do it then do it server-side, i.e. with libreoffice in headless mode, apache-poi (java), pandoc or whatever other library works best for you.

What is the maximum size of a web browser's cookie's key?

Actually, RFC 2965, the document that defines how cookies work, specifies that there should be no maximum length of a cookie's key or value size, and encourages implementations to support arbitrarily large cookies. Each browser's implementation maximum will necessarily be different, so consult individual browser documentation.

See section 5.3, "Implementation Limits", in the RFC.

VB.NET - Click Submit Button on Webbrowser page

This seems to work easily.


Public Function LoginAsTech(ByVal UserID As String, ByVal Pass As String) As Boolean
        Dim MyDoc As New mshtml.HTMLDocument
        Dim DocElements As mshtml.IHTMLElementCollection = Nothing
        Dim LoginForm As mshtml.HTMLFormElement = Nothing

        ASPComplete = 0
        WB.Navigate(VitecLoginURI)
        BrowserLoop()

        MyDoc = WB.Document.DomDocument
        DocElements = MyDoc.getElementsByTagName("input")
        For Each i As mshtml.IHTMLElement In DocElements

            Select Case i.name
                Case "seLogin$UserName"
                    i.value = UserID
                Case "seLogin$Password"
                    i.value = Pass
                Case Else
                    Exit Select
            End Select

            frmServiceCalls.txtOut.Text &= i.name & " : " & i.value & " : " & i.type & vbCrLf
        Next i

        'Old Method for Clicking submit
        'WB.Document.Forms("form1").InvokeMember("submit")


        'Better Method to click submit
        LoginForm = MyDoc.forms.item("form1")
        LoginForm.item("seLogin$LoginButton").click()
        ASPComplete = 0
        BrowserLoop()



        MyDoc= WB.Document.DomDocument
        DocElements = MyDoc.getElementsByTagName("input")
        For Each j As mshtml.IHTMLElement In DocElements
            frmServiceCalls.txtOut.Text &= j.name & " : " & j.value & " : " & j.type & vbCrLf

        Next j

        frmServiceCalls.txtOut.Text &= vbCrLf & vbCrLf & WB.Url.AbsoluteUri & vbCrLf
        Return 1
End Function

What is the maximum length of a URL in different browsers?

The URI RFC (of which URLs are a subset) doesn't define a maximum length, however, it does recommend that the hostname part of the URI (if applicable) not exceed 255 characters in length:

URI producers should use names that conform to the DNS syntax, even when use of DNS is not immediately apparent, and should limit these names to no more than 255 characters in length.

As noted in other posts though, some browsers have a practical limitation on the length of a URL.

Load local javascript file in chrome for testing?

Here's what I did by creating 2 files in the /sandbox directory:

  • First file: sandbox.js
  • Second file: index.html

_x000D_
_x000D_
const name = 'Karl'_x000D_
_x000D_
console.log('This is the name: ' + name)
_x000D_
<html>_x000D_
  <head>_x000D_
    <script type = "text/javascript" src = "file:///Users/karl/Downloads/sandbox/sandbox.js"></script>_x000D_
  </head>_x000D_
</html>
_x000D_
_x000D_
_x000D_

You can then use Chrome or any browser to inspect and debug/console your code!

Force browser to refresh css, javascript, etc

Try clearing your browsers cache.

How can I get browser to prompt to save password?

Not every browser (e.g. IE 6) has options to remember credentials.

One thing you can do is to (once the user successfully logs in) store the user information via cookie and have a "Remember Me on this machine" option. That way, when the user comes again (even if he's logged off), your web application can retrieve the cookie and get the user information (user ID + Session ID) and allow him/her to carry on working.

Hope this can be suggestive. :-)

Print directly from browser without print popup window

IE9 no longer supports triggering the Print() VBScript by calling window.print() like IE7 and IE8 do, and thus window.print() will now always trigger the print dialog in IE9.

The fix is pretty simple. You just need to call Print() itself, instead of window.print() in the onclick event.

I've described the fix in more detail in an answer to another question, with a working code example sporting slightly updated HTML syntax (as much as possible while still tested as working code).

You can find that sample code here:

Bypass Printdialog in IE9

How can I tell if a DOM element is visible in the current viewport?

The most accepted answers don't work when zooming in Google Chrome on Android. In combination with Dan's answer, to account for Chrome on Android, visualViewport must be used. The following example only takes the vertical check into account and uses jQuery for the window height:

var Rect = YOUR_ELEMENT.getBoundingClientRect();
var ElTop = Rect.top, ElBottom = Rect.bottom;
var WindowHeight = $(window).height();
if(window.visualViewport) {
    ElTop -= window.visualViewport.offsetTop;
    ElBottom -= window.visualViewport.offsetTop;
    WindowHeight = window.visualViewport.height;
}
var WithinScreen = (ElTop >= 0 && ElBottom <= WindowHeight);

How to open in default browser in C#

This opened the default for me:

System.Diagnostics.Process.Start(e.LinkText.ToString());

Dynamic require in RequireJS, getting "Module name has not been loaded yet for context" error?

Answering to myself. From the RequireJS website:

//THIS WILL FAIL
define(['require'], function (require) {
    var namedModule = require('name');
});

This fails because requirejs needs to be sure to load and execute all dependencies before calling the factory function above. [...] So, either do not pass in the dependency array, or if using the dependency array, list all the dependencies in it.

My solution:

// Modules configuration (modules that will be used as Jade helpers)
define(function () {
    return {
        'moment':   'path/to/moment',
        'filesize': 'path/to/filesize',
        '_':        'path/to/lodash',
        '_s':       'path/to/underscore.string'
    };
});

The loader:

define(['jade', 'lodash', 'config'], function (Jade, _, Config) {
    var deps;

    // Dynamic require
    require(_.values(Config), function () {
        deps = _.object(_.keys(Config), arguments);

        // Use deps...
    });
});

Trying to detect browser close event

Referring to various articles and doing some trial and error testing, finally I developed this idea which works perfectly for me.

The idea was to detect the unload event that is triggered by closing the browser. In that case, the mouse will be out of the window, pointing out at the close button ('X').

$(window).on('mouseover', (function () {
    window.onbeforeunload = null;
}));
$(window).on('mouseout', (function () {
    window.onbeforeunload = ConfirmLeave;
}));
function ConfirmLeave() {
    return "";
}
var prevKey="";
$(document).keydown(function (e) {            
    if (e.key=="F5") {
        window.onbeforeunload = ConfirmLeave;
    }
    else if (e.key.toUpperCase() == "W" && prevKey == "CONTROL") {                
        window.onbeforeunload = ConfirmLeave;   
    }
    else if (e.key.toUpperCase() == "R" && prevKey == "CONTROL") {
        window.onbeforeunload = ConfirmLeave;
    }
    else if (e.key.toUpperCase() == "F4" && (prevKey == "ALT" || prevKey == "CONTROL")) {
        window.onbeforeunload = ConfirmLeave;
    }
    prevKey = e.key.toUpperCase();
});

The ConfirmLeave function will give the pop up default message, in case there is any need to customize the message, then return the text to be displayed instead of an empty string in function ConfirmLeave().

HTML 5 Favicon - Support?

No, not all browsers support the sizes attribute:

Note that some platforms define specific sizes:

Caching a jquery ajax response in javascript/browser

If I understood your question, here is the solution :

    $.ajaxSetup({ cache: true});

and for specific calls

 $.ajax({
        url: ...,
        type: "GET",
        cache: false,           
        ...
    });

If you want opposite (cache for specific calls) you can set false at the beginning and true for specific calls.

Edit and replay XHR chrome/firefox etc?

Microsoft Chromium-based Edge supports "Edit and Replay" requests in the Network Tab as an experimental feature:

enter image description here

More details about the feature and how to enable it can be found here

How can I detect browser type using jQuery?

My solution for ie detection:

if (navigator.userAgent.match(/msie/i) || navigator.userAgent.match(/trident/i) ){
    $("html").addClass("ie");
}

Jquery needed.

How to manually send HTTP POST requests from Firefox or Chrome browser?

I think that @Benny Neugebauer comment on the OP question about the Fetch API should be presented here as an answer since the OP was looking for a functionality in Chrome to manually create HTTP POST requests and that exactly what the fetch command do.

There is a nice simple example of the Fetch API here

// Make sure you run it from the domain 'https://jsonplaceholder.typicode.com/'. (cross-origin-policy)
fetch('https://jsonplaceholder.typicode.com/posts',{method: 'POST', headers: {'test': 'TestPost'} })
  .then(response => response.json())
  .then(json => console.log(json))

Some of the advantages of the fetch command are really precious: Its simple, short, fast, available and even as a console command it stored on your chrome console and can be used later.

The simplicity of pressing F12, write the command in the console tab (or press the up key if you used it before) then press enter, see it pending and returning the response is what making it really useful for simple post requests tests.

Of course, The main disadvantage here is that unlike Postman, This wont pass the cross-origin-policy but still I find it very useful for testing in local environment or other environments where I can enable CORS manually.

How does HTTP_USER_AGENT work?

http://www.useragentstring.com/

Visit that page, it'll give you a good explanation of each element of your user agent.

Mozilla:

MozillaProductSlice. Claims to be a Mozilla based user agent, which is only true for Gecko browsers like Firefox and Netscape. For all other user agents it means 'Mozilla-compatible'. In modern browsers, this is only used for historical reasons. It has no real meaning anymore

How to always show the vertical scrollbar in a browser?

jQuery shouldn't be required. You could try adding the CSS:

body    {overflow-y:scroll;}

This works across the latest browsers, even IE6.

WebSockets vs. Server-Sent events/EventSource

Websockets and SSE (Server Sent Events) are both capable of pushing data to browsers, however they are not competing technologies.

Websockets connections can both send data to the browser and receive data from the browser. A good example of an application that could use websockets is a chat application.

SSE connections can only push data to the browser. Online stock quotes, or twitters updating timeline or feed are good examples of an application that could benefit from SSE.

In practice since everything that can be done with SSE can also be done with Websockets, Websockets is getting a lot more attention and love, and many more browsers support Websockets than SSE.

However, it can be overkill for some types of application, and the backend could be easier to implement with a protocol such as SSE.

Furthermore SSE can be polyfilled into older browsers that do not support it natively using just JavaScript. Some implementations of SSE polyfills can be found on the Modernizr github page.

Gotchas:

  • SSE suffers from a limitation to the maximum number of open connections, which can be specially painful when opening various tabs as the limit is per browser and set to a very low number (6). The issue has been marked as "Won't fix" in Chrome and Firefox. This limit is per browser + domain, so that means that you can open 6 SSE connections across all of the tabs to www.example1.com and another 6 SSE connections to www.example2.com (thanks Phate).
  • Only WS can transmit both binary data and UTF-8, SSE is limited to UTF-8. (Thanks to Chado Nihi).
  • Some enterprise firewalls with packet inspection have trouble dealing with WebSockets (Sophos XG Firewall, WatchGuard, McAfee Web Gateway).

HTML5Rocks has some good information on SSE. From that page:

Server-Sent Events vs. WebSockets

Why would you choose Server-Sent Events over WebSockets? Good question.

One reason SSEs have been kept in the shadow is because later APIs like WebSockets provide a richer protocol to perform bi-directional, full-duplex communication. Having a two-way channel is more attractive for things like games, messaging apps, and for cases where you need near real-time updates in both directions. However, in some scenarios data doesn't need to be sent from the client. You simply need updates from some server action. A few examples would be friends' status updates, stock tickers, news feeds, or other automated data push mechanisms (e.g. updating a client-side Web SQL Database or IndexedDB object store). If you'll need to send data to a server, XMLHttpRequest is always a friend.

SSEs are sent over traditional HTTP. That means they do not require a special protocol or server implementation to get working. WebSockets on the other hand, require full-duplex connections and new Web Socket servers to handle the protocol. In addition, Server-Sent Events have a variety of features that WebSockets lack by design such as automatic reconnection, event IDs, and the ability to send arbitrary events.


TLDR summary:

Advantages of SSE over Websockets:

  • Transported over simple HTTP instead of a custom protocol
  • Can be poly-filled with javascript to "backport" SSE to browsers that do not support it yet.
  • Built in support for re-connection and event-id
  • Simpler protocol
  • No trouble with corporate firewalls doing packet inspection

Advantages of Websockets over SSE:

  • Real time, two directional communication.
  • Native support in more browsers

Ideal use cases of SSE:

  • Stock ticker streaming
  • twitter feed updating
  • Notifications to browser

SSE gotchas:

  • No binary support
  • Maximum open connections limit

Is there a way to detect if a browser window is not currently active?

A slightly more complicated way would be to use setInterval() to check mouse position and compare to last check. If the mouse hasn't moved in a set amount of time, the user is probably idle.

This has the added advantage of telling if the user is idle, instead of just checking if the window is not active.

As many people have pointed out, this is not always a good way to check whether the user or browser window is idle, as the user might not even be using the mouse or is watching a video, or similar. I am just suggesting one possible way to check for idle-ness.

window.history.pushState refreshing the browser

The short answer is that history.pushState (not History.pushState, which would throw an exception, the window part is optional) will never do what you suggest.

If pages are refreshing, then it is caused by other things that you are doing (for example, you might have code running that goes to a new location in the case of the address bar changing).

history.pushState({urlPath:'/page2.php'},"",'/page2.php') works exactly like it is supposed to in the latest versions of Chrome, IE and Firefox for me and my colleagues.

In fact you can put whatever you like into the function: history.pushState({}, '', 'So long and thanks for all the fish.not a real file').

If you post some more code (with special attention for code nearby the history.pushState and anywhere document.location is used), then we'll be more than happy to help you figure out where exactly this issue is coming from.

If you post more code, I'll update this answer (I have your question favourited) :).

Linux: command to open URL in default browser

on ubuntu you can try gnome-open.

$ gnome-open http://www.google.com

what happens when you type in a URL in browser

Attention: this is an extremely rough and oversimplified sketch, assuming the simplest possible HTTP request (no HTTPS, no HTTP2, no extras), simplest possible DNS, no proxies, single-stack IPv4, one HTTP request only, a simple HTTP server on the other end, and no problems in any step. This is, for most contemporary intents and purposes, an unrealistic scenario; all of these are far more complex in actual use, and the tech stack has become an order of magnitude more complicated since this was written. With this in mind, the following timeline is still somewhat valid:

  1. browser checks cache; if requested object is in cache and is fresh, skip to #9
  2. browser asks OS for server's IP address
  3. OS makes a DNS lookup and replies the IP address to the browser
  4. browser opens a TCP connection to server (this step is much more complex with HTTPS)
  5. browser sends the HTTP request through TCP connection
  6. browser receives HTTP response and may close the TCP connection, or reuse it for another request
  7. browser checks if the response is a redirect or a conditional response (3xx result status codes), authorization request (401), error (4xx and 5xx), etc.; these are handled differently from normal responses (2xx)
  8. if cacheable, response is stored in cache
  9. browser decodes response (e.g. if it's gzipped)
  10. browser determines what to do with response (e.g. is it a HTML page, is it an image, is it a sound clip?)
  11. browser renders response, or offers a download dialog for unrecognized types

Again, discussion of each of these points have filled countless pages; take this only as a summary, abridged for the sake of clarity. Also, there are many other things happening in parallel to this (processing typed-in address, speculative prefetching, adding page to browser history, displaying progress to user, notifying plugins and extensions, rendering the page while it's downloading, pipelining, connection tracking for keep-alive, cookie management, checking for malicious content etc.) - and the whole operation gets an order of magnitude more complex with HTTPS (certificates and ciphers and pinning, oh my!).

How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?

With IE6 / IE7 one can tweak the number of concurrent requests in the registry. Here's how to set it to four each.

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings]
"MaxConnectionsPerServer"=dword:00000004
"MaxConnectionsPer1_0Server"=dword:00000004

Appending HTML string to the DOM

Use insertAdjacentHTML if it's available, otherwise use some sort of fallback. insertAdjacentHTML is supported in all current browsers.

div.insertAdjacentHTML( 'beforeend', str );

Live demo: http://jsfiddle.net/euQ5n/

Do I need Content-Type: application/octet-stream for file download?

No.

The content-type should be whatever it is known to be, if you know it. application/octet-stream is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.

You can combine the use of Content-Disposition with other content-types, such as image/png or even text/html to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).

RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.

Hence:

Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"

Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"

Means "This is a PNG image. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: inline; filename="picture.png"

Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".

Of those browsers that recognise inline some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).

get client time zone from browser

I used an approach similar to the one taken by Josh Fraser, which determines the browser time offset from UTC and whether it recognizes DST or not (but somewhat simplified from his code):

var ClientTZ = {
    UTCoffset:  0,          // Browser time offset from UTC in minutes
    UTCoffsetT: '+0000S',   // Browser time offset from UTC in '±hhmmD' form
    hasDST:     false,      // Browser time observes DST

    // Determine browser's timezone and DST
    getBrowserTZ: function () {
        var self = ClientTZ;

        // Determine UTC time offset
        var now = new Date();
        var date1 = new Date(now.getFullYear(), 1-1, 1, 0, 0, 0, 0);    // Jan
        var diff1 = -date1.getTimezoneOffset();
        self.UTCoffset = diff1;

        // Determine DST use
        var date2 = new Date(now.getFullYear(), 6-1, 1, 0, 0, 0, 0);    // Jun
        var diff2 = -date2.getTimezoneOffset();
        if (diff1 != diff2) {
            self.hasDST = true;
            if (diff1 - diff2 >= 0)
                self.UTCoffset = diff2;     // East of GMT
        }

        // Convert UTC offset to ±hhmmD form
        diff2 = (diff1 < 0 ? -diff1 : diff1) / 60;
        var hr = Math.floor(diff2);
        var min = diff2 - hr;
        diff2 = hr * 100 + min * 60;
        self.UTCoffsetT = (diff1 < 0 ? '-' : '+') + (hr < 10 ? '0' : '') + diff2.toString() + (self.hasDST ? 'D' : 'S');

        return self.UTCoffset;
    }
};

// Onload
ClientTZ.getBrowserTZ();

Upon loading, the ClientTZ.getBrowserTZ() function is executed, which sets:

  • ClientTZ.UTCoffset to the browser time offset from UTC in minutes (e.g., CST is -360 minutes, which is -6.0 hours from UTC);
  • ClientTZ.UTCoffsetT to the offset in the form '±hhmmD' (e.g., '-0600D'), where the suffix is D for DST and S for standard (non-DST);
  • ClientTZ.hasDST (to true or false).

The ClientTZ.UTCoffset is provided in minutes instead of hours, because some timezones have fractional hourly offsets (e.g., +0415).

The intent behind ClientTZ.UTCoffsetT is to use it as a key into a table of timezones (not provided here), such as for a drop-down <select> list.

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

I would still recommend Firebug. Not only it can debug JS within your JSP files, it can enhance debugging experience with addons like JS Deminifier (if your production JS is minified), FireQuery, FireRainbow and more.

There is also Firebug lite which is nothing but a bookmarklet. It lets you do limited things but still is useful.

Chrome as a developer console built-in that would let you modify javascript.

Using these tools, you should be able to inject your own JS too.

How to display a PDF via Android web browser without "downloading" first

You can use this

webView.loadUrl("https://docs.google.com/viewer?url=" + "url of pdf file"); 

Getting the text from a drop-down box

var selectoption = document.getElementById("dropdown");
var optionText = selectoption.options[selectoption.selectedIndex].text;

Disabling browser caching for all browsers from ASP.NET

For what it's worth, I just had to handle this in my ASP.NET MVC 3 application. Here is the code block I used in the Global.asax file to handle this for all requests.

    protected void Application_BeginRequest()
    {
        //NOTE: Stopping IE from being a caching whore
        HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(false);
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.Cache.SetNoStore();
        Response.Cache.SetExpires(DateTime.Now);
        Response.Cache.SetValidUntilExpires(true);
    }

Is jQuery $.browser Deprecated?

Updated! 3/24/2015 (scroll below hr)

lonesomeday's answer is absolutely correct, I just thought I would add this tidbit. I had made a method a while back for getting browser in Vanilla JS and eventually curved it to replace jQuery.browser in later versions of jQuery. It does not interfere with any part of the new jQuery lib, but provides the same functionality of the traditional jQuery.browser object, as well as some other little features.


New Extended Version!

Is much more thorough for newer browser. Also, 90+% accuracy on mobile testing! I won't say 100%, as I haven't tested on every mobile browser, but new feature adds $.browser.mobile boolean/string. It's false if not mobile, else it will be a String name for the mobile device or browser (Best Guesss like: Android, RIM Tablet, iPod, etc...).

One possible caveat, may not work with some older (unsupported) browsers as it is completely reliant on userAgent string.

JS Minified

/* quick & easy cut & paste */
;;(function($){if(!$.browser&&1.9<=parseFloat($.fn.jquery)){var a={browser:void 0,version:void 0,mobile:!1};navigator&&navigator.userAgent&&(a.ua=navigator.userAgent,a.webkit=/WebKit/i.test(a.ua),a.browserArray="MSIE Chrome Opera Kindle Silk BlackBerry PlayBook Android Safari Mozilla Nokia".split(" "),/Sony[^ ]*/i.test(a.ua)?a.mobile="Sony":/RIM Tablet/i.test(a.ua)?a.mobile="RIM Tablet":/BlackBerry/i.test(a.ua)?a.mobile="BlackBerry":/iPhone/i.test(a.ua)?a.mobile="iPhone":/iPad/i.test(a.ua)?a.mobile="iPad":/iPod/i.test(a.ua)?a.mobile="iPod":/Opera Mini/i.test(a.ua)?a.mobile="Opera Mini":/IEMobile/i.test(a.ua)?a.mobile="IEMobile":/BB[0-9]{1,}; Touch/i.test(a.ua)?a.mobile="BlackBerry":/Nokia/i.test(a.ua)?a.mobile="Nokia":/Android/i.test(a.ua)&&(a.mobile="Android"),/MSIE|Trident/i.test(a.ua)?(a.browser="MSIE",a.version=/MSIE/i.test(navigator.userAgent)&&0<parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,""))?parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,"")):"Edge",/Trident/i.test(a.ua)&&/rv:([0-9]{1,}[\.0-9]{0,})/.test(a.ua)&&(a.version=parseFloat(a.ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].replace(/[^0-9\.]/g,"")))):/Chrome/.test(a.ua)?(a.browser="Chrome",a.version=parseFloat(a.ua.split("Chrome/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Opera/.test(a.ua)?(a.browser="Opera",a.version=parseFloat(a.ua.split("Version/")[1].replace(/[^0-9\.]/g,""))):/Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(a.ua)?(a.mobile="Kindle",/Silk/i.test(a.ua)?(a.browser="Silk",a.version=parseFloat(a.ua.split("Silk/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Kindle/i.test(a.ua)&&/Version/i.test(a.ua)&&(a.browser="Kindle",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,"")))):/BlackBerry/.test(a.ua)?(a.browser="BlackBerry",a.version=parseFloat(a.ua.split("/")[1].replace(/[^0-9\.]/g,""))):/PlayBook/.test(a.ua)?(a.browser="PlayBook",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/BB[0-9]{1,}; Touch/.test(a.ua)?(a.browser="Blackberry",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Android/.test(a.ua)?(a.browser="Android",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Safari/.test(a.ua)?(a.browser="Safari",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Firefox/.test(a.ua)?(a.browser="Mozilla",a.version=parseFloat(a.ua.split("Firefox/")[1].replace(/[^0-9\.]/g,""))):/Nokia/.test(a.ua)&&(a.browser="Nokia",a.version=parseFloat(a.ua.split("Browser")[1].replace(/[^0-9\.]/g,""))));if(a.browser)for(var b in a.browserArray)a[a.browserArray[b].toLowerCase()]=a.browser==a.browserArray[b];$.extend(!0,$.browser={},a)}})(jQuery);
/* quick & easy cut & paste */

jsFiddle "jQuery Plugin: Get Browser (Extended Alt Edition)"

_x000D_
_x000D_
/** jQuery.browser_x000D_
 * @author J.D. McKinstry (2014)_x000D_
 * @description Made to replicate older jQuery.browser command in jQuery versions 1.9+_x000D_
 * @see http://jsfiddle.net/SpYk3/wsqfbe4s/_x000D_
 *_x000D_
 * @extends jQuery_x000D_
 * @namespace jQuery.browser_x000D_
 * @example jQuery.browser.browser == 'browserNameInLowerCase'_x000D_
 * @example jQuery.browser.version_x000D_
 * @example jQuery.browser.mobile @returns BOOLEAN_x000D_
 * @example jQuery.browser['browserNameInLowerCase']_x000D_
 * @example jQuery.browser.chrome @returns BOOLEAN_x000D_
 * @example jQuery.browser.safari @returns BOOLEAN_x000D_
 * @example jQuery.browser.opera @returns BOOLEAN_x000D_
 * @example jQuery.browser.msie @returns BOOLEAN_x000D_
 * @example jQuery.browser.mozilla @returns BOOLEAN_x000D_
 * @example jQuery.browser.webkit @returns BOOLEAN_x000D_
 * @example jQuery.browser.ua @returns navigator.userAgent String_x000D_
 */_x000D_
;;(function($){if(!$.browser&&1.9<=parseFloat($.fn.jquery)){var a={browser:void 0,version:void 0,mobile:!1};navigator&&navigator.userAgent&&(a.ua=navigator.userAgent,a.webkit=/WebKit/i.test(a.ua),a.browserArray="MSIE Chrome Opera Kindle Silk BlackBerry PlayBook Android Safari Mozilla Nokia".split(" "),/Sony[^ ]*/i.test(a.ua)?a.mobile="Sony":/RIM Tablet/i.test(a.ua)?a.mobile="RIM Tablet":/BlackBerry/i.test(a.ua)?a.mobile="BlackBerry":/iPhone/i.test(a.ua)?a.mobile="iPhone":/iPad/i.test(a.ua)?a.mobile="iPad":/iPod/i.test(a.ua)?a.mobile="iPod":/Opera Mini/i.test(a.ua)?a.mobile="Opera Mini":/IEMobile/i.test(a.ua)?a.mobile="IEMobile":/BB[0-9]{1,}; Touch/i.test(a.ua)?a.mobile="BlackBerry":/Nokia/i.test(a.ua)?a.mobile="Nokia":/Android/i.test(a.ua)&&(a.mobile="Android"),/MSIE|Trident/i.test(a.ua)?(a.browser="MSIE",a.version=/MSIE/i.test(navigator.userAgent)&&0<parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,""))?parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,"")):"Edge",/Trident/i.test(a.ua)&&/rv:([0-9]{1,}[\.0-9]{0,})/.test(a.ua)&&(a.version=parseFloat(a.ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].replace(/[^0-9\.]/g,"")))):/Chrome/.test(a.ua)?(a.browser="Chrome",a.version=parseFloat(a.ua.split("Chrome/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Opera/.test(a.ua)?(a.browser="Opera",a.version=parseFloat(a.ua.split("Version/")[1].replace(/[^0-9\.]/g,""))):/Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(a.ua)?(a.mobile="Kindle",/Silk/i.test(a.ua)?(a.browser="Silk",a.version=parseFloat(a.ua.split("Silk/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Kindle/i.test(a.ua)&&/Version/i.test(a.ua)&&(a.browser="Kindle",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,"")))):/BlackBerry/.test(a.ua)?(a.browser="BlackBerry",a.version=parseFloat(a.ua.split("/")[1].replace(/[^0-9\.]/g,""))):/PlayBook/.test(a.ua)?(a.browser="PlayBook",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/BB[0-9]{1,}; Touch/.test(a.ua)?(a.browser="Blackberry",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Android/.test(a.ua)?(a.browser="Android",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Safari/.test(a.ua)?(a.browser="Safari",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Firefox/.test(a.ua)?(a.browser="Mozilla",a.version=parseFloat(a.ua.split("Firefox/")[1].replace(/[^0-9\.]/g,""))):/Nokia/.test(a.ua)&&(a.browser="Nokia",a.version=parseFloat(a.ua.split("Browser")[1].replace(/[^0-9\.]/g,""))));if(a.browser)for(var b in a.browserArray)a[a.browserArray[b].toLowerCase()]=a.browser==a.browserArray[b];$.extend(!0,$.browser={},a)}})(jQuery);_x000D_
/* - - - - - - - - - - - - - - - - - - - */_x000D_
_x000D_
var b = $.browser;_x000D_
console.log($.browser);    //    see console, working example of jQuery Plugin_x000D_
console.log($.browser.chrome);_x000D_
_x000D_
for (var x in b) {_x000D_
    if (x != 'init')_x000D_
        $('<tr />').append(_x000D_
            $('<th />', { text: x }),_x000D_
            $('<td />', { text: b[x] })_x000D_
        ).appendTo($('table'));_x000D_
}
_x000D_
table { border-collapse: collapse; }_x000D_
th, td { border: 1px solid; padding: .25em .5em; vertical-align: top; }_x000D_
th { text-align: right; }_x000D_
_x000D_
textarea { height: 500px; width: 100%; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<table></table>
_x000D_
_x000D_
_x000D_

Hiding the scroll bar on an HTML page

Yes, sort of..

When you ask the question, "Can the scroll-bars of a browser be removed in some way, rather than simply hidden or camouflaged", everyone will say "Not possible" because it is not possible to remove the scrollbars from all browsers in a compliant and cross-compatible way, and then there's the whole argument of usability.

However, it is possible to prevent the browser from ever having the need to generate and display scrollbars if you do not allow your webpage to overflow.

This just means that we have to proactively substitute the same behavior that the browser would typically do for us and tell the browser thanks but no thanks buddy. Rather than try to remove scrollbars (which we all know is not possible) we can avoid scrolling (perfectly feasible) and scroll within the elements that we make and have more control over.

Create a div with overflow hidden. Detect when the user attempts to scroll, but is unable to because we've disabled the browsers ability to scroll with overflow: hidden.. and instead move the content up using JavaScript when this occurs. Thereby creating our own scrolling without the browsers default scrolling or use a plugin like iScroll.

---

For the sake of being thorough; all the vendor specific ways of manipulating scroll-bars:

Internet Explorer 5.5+

*These properties were never part of the CSS specification, nor were they ever approved or vendor prefixed, but they work in Internet Explorer and Konqueror. These can also be set locally in the user style sheet for each application. In Internet Explorer you find it under the "Accessibility" tab, in Konqueror under the "Stylesheets" tab.

body, html { /* These are defaults and can be replaced by hexadecimal color values */
    scrollbar-base-color: aqua;
    scrollbar-face-color: ThreeDFace;
    scrollbar-highlight-color: ThreeDHighlight;
    scrollbar-3dlight-color: ThreeDLightShadow;
    scrollbar-shadow-color: ThreeDDarkShadow;
    scrollbar-darkshadow-color: ThreeDDarkShadow;
    scrollbar-track-color: Scrollbar;
    scrollbar-arrow-color: ButtonText;
}

As of Internet Explorer 8 these properties were vendor prefixed by Microsoft, but they were still never approved by W3C.

-ms-scrollbar-base-color
-ms-scrollbar-face-color
-ms-scrollbar-highlight-color
-ms-scrollbar-3dlight-color
-ms-scrollbar-shadow-color
-ms-scrollbar-darkshadow-color
-ms-scrollbar-base-color
-ms-scrollbar-track-color

Further details about Internet Explorer

Internet Explorer makes scroll available which sets whether or not to disable or enable scroll bars; it can also be used to get the value of the position of the scroll bars.

With Microsoft Internet Explorer 6 and later, when you use the !DOCTYPE declaration to specify standards-compliant mode, this attribute applies to the HTML element. When standards-compliant mode is not specified, as with earlier versions of Internet Explorer, this attribute applies to the BODY element, NOT the HTML element.

It's also worth noting that when working with .NET the ScrollBar class in System.Windows.Controls.Primitives in the Presentation framework is responsible for rendering the scrollbars.

http://msdn.microsoft.com/en-us/library/ie/ms534393(v=vs.85).aspx


WebKit

WebKit extensions related to scroll-bar customization are:

::-webkit-scrollbar {}             /* 1 */
::-webkit-scrollbar-button {}      /* 2 */
::-webkit-scrollbar-track {}       /* 3 */
::-webkit-scrollbar-track-piece {} /* 4 */
::-webkit-scrollbar-thumb {}       /* 5 */
::-webkit-scrollbar-corner {}      /* 6 */
::-webkit-resizer {}               /* 7 */

Enter image description here

These can each be combined with additional pseudo-selectors:

  • :horizontal – The horizontal pseudo-class applies to any scrollbar pieces that have a horizontal orientation.
  • :vertical – The vertical pseudo-class applies to any scrollbar pieces that have a vertical orientation.
  • :decrement – The decrement pseudo-class applies to buttons and track pieces. It indicates whether or not the button or track piece will decrement the view’s position when used (e.g., up on a vertical scrollbar, left on a horizontal scrollbar).
  • :increment – The increment pseudo-class applies to buttons and track pieces. It indicates whether or not a button or track piece will increment the view’s position when used (e.g., down on a vertical scrollbar, right on a horizontal scrollbar).
  • :start – The start pseudo-class applies to buttons and track pieces. It indicates whether the object is placed before the thumb.
  • :end – The end pseudo-class applies to buttons and track pieces. It indicates whether the object is placed after the thumb.
  • :double-button – The double-button pseudo-class applies to buttons and track pieces. It is used to detect whether a button is part of a pair of buttons that are together at the same end of a scrollbar. For track pieces it indicates whether the track piece abuts a pair of buttons.
  • :single-button – The single-button pseudo-class applies to buttons and track pieces. It is used to detect whether a button is by itself at the end of a scrollbar. For track pieces it indicates whether the track piece abuts a singleton button.
  • :no-button – Applies to track pieces and indicates whether or not the track piece runs to the edge of the scrollbar, i.e., there is no button at that end of the track.
  • :corner-present – Applies to all scrollbar pieces and indicates whether or not a scrollbar corner is present.
  • :window-inactive – Applies to all scrollbar pieces and indicates whether or not the window containing the scrollbar is currently active. (In recent nightlies, this pseudo-class now applies to ::selection as well. We plan to extend it to work with any content and to propose it as a new standard pseudo-class.)

Examples of these combinations

::-webkit-scrollbar-track-piece:start { /* Select the top half (or left half) or scrollbar track individually */ }
::-webkit-scrollbar-thumb:window-inactive { /* Select the thumb when the browser window isn't in focus */ }
::-webkit-scrollbar-button:horizontal:decrement:hover { /* Select the down or left scroll button when it's being hovered by the mouse */ }

Further details about Chrome

addWindowScrollHandler public static HandlerRegistration addWindowScrollHandler(Window.ScrollHandler handler)

  Adds a Window.ScrollEvent handler Parameters:   handler - the handler Returns:   returns the handler registration [source](http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/Window.html#addWindowScrollHandler(com.google.gwt.user.client.Window.ScrollHandler) )


Mozilla

Mozilla does have some extensions for manipulating the scroll-bars, but they are all recommended not to be used.

  • -moz-scrollbars-none They recommend using overflow:hidden in place of this.
  • -moz-scrollbars-horizontal Similar to overflow-x
  • -moz-scrollbars-vertical Similar to overflow-y
  • -moz-hidden-unscrollable Only works internally within a users profile settings. Disables scrolling XML root elements and disables using arrow keys and mouse wheel to scroll web pages.

  • Mozilla Developer Docs on 'Overflow'

Further details about Mozilla

This is not really useful as far as I know, but it's worth noting that the attribute which controls whether or not scrollbars are displayed in Firefox is (reference link):

  • Attribute:       scrollbars
  • Type:              nsIDOMBarProp
  • Description:  The object that controls whether or not scrollbars are shown in the window. This attribute is "replaceable" in JavaScript. Read only

Last but not least, padding is like magic.

As has been previously mentioned in some other answers, here is an illustration which is sufficiently self-explanatory.

Enter image description here


History lesson

Scroll bars

Just because I'm curious, I wanted to learn about the origin of scrollbars, and these are the best references I found.

Miscellaneous

In an HTML5 specification draft, the seamless attribute was defined to prevent scroll-bars from appearing in iFrames so that they could be blended with surrounding content on a page. Though this element does not appear in the latest revision.

The scrollbar BarProp object is a child of the window object and represents the user interface element that contains a scrolling mechanism, or some similar interface concept. window.scrollbars.visible will return true if the scroll bars are visible.

interface Window {
  // The current browsing context
  readonly attribute WindowProxy window;
  readonly attribute WindowProxy self;
           attribute DOMString name;
  [PutForwards=href] readonly attribute Location location;
  readonly attribute History history;
  readonly attribute UndoManager undoManager;
  Selection getSelection();
  [Replaceable] readonly attribute BarProp locationbar;
  [Replaceable] readonly attribute BarProp menubar;
  [Replaceable] readonly attribute BarProp personalbar;
  [Replaceable] readonly attribute BarProp scrollbars;
  [Replaceable] readonly attribute BarProp statusbar;
  [Replaceable] readonly attribute BarProp toolbar;
  void close();
  void focus();
  void blur();
  // Truncated

The History API also includes features for scroll restoration on page navigation to persist the scroll position on page load.

window.history.scrollRestoration can be used to check the status of scrollrestoration or change its status (appending ="auto"/"manual". Auto is the default value. Changing it to manual means that you as the developer will take ownership of any scroll changes that may be required when a user traverses the app's history. If you need to, you can keep track of the scroll position as you push history entries with history.pushState().

---

Further reading:

Examples

PHP: If internet explorer 6, 7, 8 , or 9

This is what I ended up using a variation of, which checks for IE8 and below:

if (preg_match('/MSIE\s(?P<v>\d+)/i', @$_SERVER['HTTP_USER_AGENT'], $B) && $B['v'] <= 8) {
    // Browsers IE 8 and below
} else {
    // All other browsers
}

How to debug Angular JavaScript Code

1. Chrome

For debugging AngularJS in Chrome you can use AngularJS Batarang. (From recent reviews on the plugin it seems like AngularJS Batarang is no longer being maintained. Tested in various versions of Chrome and it does not work.)

Here is the the link for a description and demo: Introduction of Angular JS Batarang

Download Chrome plugin from here: Chrome plugin for debugging AngularJS

You can also use ng-inspect for debugging angular.

2. Firefox

For Firefox with the help of Firebug you can debug the code.

Also use this Firefox Add-Ons: AngScope: Add-ons for Firefox (Not official extension by AngularJS Team)

3. Debugging AngularJS

Check the Link: Debugging AngularJS

How to get exact browser name and version?

I would like to suggest you this amazing class. This worked very well for me.

http://chrisschuld.com/projects/browser-php-detecting-a-users-browser-from-php.html/

I am publishing the code I used with the copyright notice of original author. You can get latest code from the link above.

<?php
/**
 * File: Browser.php
 * Author: Chris Schuld (http://chrisschuld.com/)
 *
 * Copyright (C) 2008-2010 Chris Schuld  ([email protected])
 *
 * Typical Usage:
 *
 *   $browser = new Browser();
 *   if( $browser->getBrowser() == Browser::BROWSER_FIREFOX && $browser->getVersion() >= 2 ) {
 *      echo 'You have FireFox version 2 or greater';
 *   }
 *
*/

class Browser {
    private $_agent = '';
    private $_browser_name = '';
    private $_version = '';
    private $_platform = '';
    private $_os = '';
    private $_is_aol = false;
    private $_is_mobile = false;
    private $_is_robot = false;
    private $_aol_version = '';

    const BROWSER_UNKNOWN = 'unknown';
    const VERSION_UNKNOWN = 'unknown';

    const BROWSER_OPERA = 'Opera'; 
    const BROWSER_OPERA_MINI = 'Opera Mini';
    const BROWSER_WEBTV = 'WebTV';
    const BROWSER_IE = 'Internet Explorer'; 
    const BROWSER_POCKET_IE = 'Pocket Internet Explorer';
    const BROWSER_KONQUEROR = 'Konqueror';
    const BROWSER_ICAB = 'iCab';
    const BROWSER_OMNIWEB = 'OmniWeb';
    const BROWSER_FIREBIRD = 'Firebird';
    const BROWSER_FIREFOX = 'Firefox';
    const BROWSER_ICEWEASEL = 'Iceweasel';
    const BROWSER_SHIRETOKO = 'Shiretoko';
    const BROWSER_MOZILLA = 'Mozilla';
    const BROWSER_AMAYA = 'Amaya';
    const BROWSER_LYNX = 'Lynx';
    const BROWSER_SAFARI = 'Safari';
    const BROWSER_IPHONE = 'iPhone';
    const BROWSER_IPOD = 'iPod';
    const BROWSER_IPAD = 'iPad';
    const BROWSER_CHROME = 'Chrome';
    const BROWSER_ANDROID = 'Android';
    const BROWSER_GOOGLEBOT = 'GoogleBot';
    const BROWSER_SLURP = 'Yahoo! Slurp';
    const BROWSER_W3CVALIDATOR = 'W3C Validator';
    const BROWSER_BLACKBERRY = 'BlackBerry';
    const BROWSER_ICECAT = 'IceCat';
    const BROWSER_NOKIA_S60 = 'Nokia S60 OSS Browser';
    const BROWSER_NOKIA = 'Nokia Browser';
    const BROWSER_MSN = 'MSN Browser';
    const BROWSER_MSNBOT = 'MSN Bot';

    const BROWSER_NETSCAPE_NAVIGATOR = 'Netscape Navigator';
    const BROWSER_GALEON = 'Galeon';
    const BROWSER_NETPOSITIVE = 'NetPositive';
    const BROWSER_PHOENIX = 'Phoenix';

    const PLATFORM_UNKNOWN = 'unknown';
    const PLATFORM_WINDOWS = 'Windows';
    const PLATFORM_WINDOWS_CE = 'Windows CE';
    const PLATFORM_APPLE = 'Apple';
    const PLATFORM_LINUX = 'Linux';
    const PLATFORM_OS2 = 'OS/2';
    const PLATFORM_BEOS = 'BeOS';
    const PLATFORM_IPHONE = 'iPhone';
    const PLATFORM_IPOD = 'iPod';
    const PLATFORM_IPAD = 'iPad';
    const PLATFORM_BLACKBERRY = 'BlackBerry';
    const PLATFORM_NOKIA = 'Nokia';
    const PLATFORM_FREEBSD = 'FreeBSD';
    const PLATFORM_OPENBSD = 'OpenBSD';
    const PLATFORM_NETBSD = 'NetBSD';
    const PLATFORM_SUNOS = 'SunOS';
    const PLATFORM_OPENSOLARIS = 'OpenSolaris';
    const PLATFORM_ANDROID = 'Android';

    const OPERATING_SYSTEM_UNKNOWN = 'unknown';

    public function Browser($useragent="") {
        $this->reset();
        if( $useragent != "" ) {
            $this->setUserAgent($useragent);
        }
        else {
            $this->determine();
        }
    }

    /**
    * Reset all properties
    */
    public function reset() {
        $this->_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "";
        $this->_browser_name = self::BROWSER_UNKNOWN;
        $this->_version = self::VERSION_UNKNOWN;
        $this->_platform = self::PLATFORM_UNKNOWN;
        $this->_os = self::OPERATING_SYSTEM_UNKNOWN;
        $this->_is_aol = false;
        $this->_is_mobile = false;
        $this->_is_robot = false;
        $this->_aol_version = self::VERSION_UNKNOWN;
    }

    /**
    * Check to see if the specific browser is valid
    * @param string $browserName
    * @return boolean
    */
    function isBrowser($browserName) { return( 0 == strcasecmp($this->_browser_name, trim($browserName))); }

    /**
    * The name of the browser.  All return types are from the class contants
    * @return string Name of the browser
    */
    public function getBrowser() { return $this->_browser_name; }
    /**
    * Set the name of the browser
    * @param $browser The name of the Browser
    */
    public function setBrowser($browser) { return $this->_browser_name = $browser; }
    /**
    * The name of the platform.  All return types are from the class contants
    * @return string Name of the browser
    */
    public function getPlatform() { return $this->_platform; }
    /**
    * Set the name of the platform
    * @param $platform The name of the Platform
    */
    public function setPlatform($platform) { return $this->_platform = $platform; }
    /**
    * The version of the browser.
    * @return string Version of the browser (will only contain alpha-numeric characters and a period)
    */
    public function getVersion() { return $this->_version; }
    /**
    * Set the version of the browser
    * @param $version The version of the Browser
    */
    public function setVersion($version) { $this->_version = preg_replace('/[^0-9,.,a-z,A-Z-]/','',$version); }
    /**
    * The version of AOL.
    * @return string Version of AOL (will only contain alpha-numeric characters and a period)
    */
    public function getAolVersion() { return $this->_aol_version; }
    /**
    * Set the version of AOL
    * @param $version The version of AOL
    */
    public function setAolVersion($version) { $this->_aol_version = preg_replace('/[^0-9,.,a-z,A-Z]/','',$version); }
    /**
    * Is the browser from AOL?
    * @return boolean
    */
    public function isAol() { return $this->_is_aol; }
    /**
    * Is the browser from a mobile device?
    * @return boolean
    */
    public function isMobile() { return $this->_is_mobile; }
    /**
    * Is the browser from a robot (ex Slurp,GoogleBot)?
    * @return boolean
    */
    public function isRobot() { return $this->_is_robot; }
    /**
    * Set the browser to be from AOL
    * @param $isAol
    */
    public function setAol($isAol) { $this->_is_aol = $isAol; }
    /**
     * Set the Browser to be mobile
     * @param boolean
     */
    protected function setMobile($value=true) { $this->_is_mobile = $value; }
    /**
     * Set the Browser to be a robot
     * @param boolean
     */
    protected function setRobot($value=true) { $this->_is_robot = $value; }
    /**
    * Get the user agent value in use to determine the browser
    * @return string The user agent from the HTTP header
    */
    public function getUserAgent() { return $this->_agent; }
    /**
    * Set the user agent value (the construction will use the HTTP header value - this will overwrite it)
    * @param $agent_string The value for the User Agent
    */
    public function setUserAgent($agent_string) {
        $this->reset();
        $this->_agent = $agent_string;
        $this->determine();
    }
    /**
     * Used to determine if the browser is actually "chromeframe"
     * @return boolean
     */
    public function isChromeFrame() {
        return( strpos($this->_agent,"chromeframe") !== false );
    }
    /**
    * Returns a formatted string with a summary of the details of the browser.
    * @return string formatted string with a summary of the browser
    */
    public function __toString() {
        return "<strong>Browser Name:</strong>{$this->getBrowser()}<br/>\n" .
               "<strong>Browser Version:</strong>{$this->getVersion()}<br/>\n" .
               "<strong>Browser User Agent String:</strong>{$this->getUserAgent()}<br/>\n" .
               "<strong>Platform:</strong>{$this->getPlatform()}<br/>";
    }
    /**
     * Protected routine to calculate and determine what the browser is in use (including platform)
     */
    protected function determine() {
        $this->checkPlatform();
        $this->checkBrowsers();
        $this->checkForAol();
    }
    /**
     * Protected routine to determine the browser type
     * @return boolean
     */
     protected function checkBrowsers() {
        return (
            $this->checkBrowserWebTv() ||
            $this->checkBrowserInternetExplorer() ||
            $this->checkBrowserOpera() ||
            $this->checkBrowserGaleon() ||
            $this->checkBrowserNetscapeNavigator9Plus() ||
            $this->checkBrowserFirefox() ||
            $this->checkBrowserChrome() ||
            $this->checkBrowserOmniWeb() ||

            // common mobile
            $this->checkBrowserAndroid() ||
            $this->checkBrowseriPad() ||
            $this->checkBrowseriPod() ||
            $this->checkBrowseriPhone() ||
            $this->checkBrowserBlackBerry() ||
            $this->checkBrowserNokia() ||

            // common bots
            $this->checkBrowserGoogleBot() ||
            $this->checkBrowserMSNBot() ||
            $this->checkBrowserSlurp() ||

            // WebKit base check (post mobile and others)
            $this->checkBrowserSafari() ||

            // everyone else
            $this->checkBrowserNetPositive() ||
            $this->checkBrowserFirebird() ||
            $this->checkBrowserKonqueror() ||
            $this->checkBrowserIcab() ||
            $this->checkBrowserPhoenix() ||
            $this->checkBrowserAmaya() ||
            $this->checkBrowserLynx() ||
            $this->checkBrowserShiretoko() ||
            $this->checkBrowserIceCat() ||
            $this->checkBrowserW3CValidator() ||
            $this->checkBrowserMozilla() /* Mozilla is such an open standard that you must check it last */
        );
    }

    protected function checkBrowserBlackBerry() {
        if( stripos($this->_agent,'blackberry') !== false ) {
            $aresult = explode("/",stristr($this->_agent,"BlackBerry"));
            $aversion = explode(' ',$aresult[1]);
            $this->setVersion($aversion[0]);
            $this->_browser_name = self::BROWSER_BLACKBERRY;
            $this->setMobile(true);
            return true;
        }
        return false;
    }

    protected function checkForAol() {
        $this->setAol(false);
        $this->setAolVersion(self::VERSION_UNKNOWN);

        if( stripos($this->_agent,'aol') !== false ) {
            $aversion = explode(' ',stristr($this->_agent, 'AOL'));
            $this->setAol(true);
            $this->setAolVersion(preg_replace('/[^0-9\.a-z]/i', '', $aversion[1]));
            return true;
        }
        return false;
    }


    protected function checkBrowserGoogleBot() {
        if( stripos($this->_agent,'googlebot') !== false ) {
            $aresult = explode('/',stristr($this->_agent,'googlebot'));
            $aversion = explode(' ',$aresult[1]);
            $this->setVersion(str_replace(';','',$aversion[0]));
            $this->_browser_name = self::BROWSER_GOOGLEBOT;
            $this->setRobot(true);
            return true;
        }
        return false;
    }

    protected function checkBrowserMSNBot() {
        if( stripos($this->_agent,"msnbot") !== false ) {
            $aresult = explode("/",stristr($this->_agent,"msnbot"));
            $aversion = explode(" ",$aresult[1]);
            $this->setVersion(str_replace(";","",$aversion[0]));
            $this->_browser_name = self::BROWSER_MSNBOT;
            $this->setRobot(true);
            return true;
        }
        return false;
    }       

    protected function checkBrowserW3CValidator() {
        if( stripos($this->_agent,'W3C-checklink') !== false ) {
            $aresult = explode('/',stristr($this->_agent,'W3C-checklink'));
            $aversion = explode(' ',$aresult[1]);
            $this->setVersion($aversion[0]);
            $this->_browser_name = self::BROWSER_W3CVALIDATOR;
            return true;
        }
        else if( stripos($this->_agent,'W3C_Validator') !== false ) {
            // Some of the Validator versions do not delineate w/ a slash - add it back in
            $ua = str_replace("W3C_Validator ", "W3C_Validator/", $this->_agent);
            $aresult = explode('/',stristr($ua,'W3C_Validator'));
            $aversion = explode(' ',$aresult[1]);
            $this->setVersion($aversion[0]);
            $this->_browser_name = self::BROWSER_W3CVALIDATOR;
            return true;
        }
        return false;
    }

    protected function checkBrowserSlurp() {
        if( stripos($this->_agent,'slurp') !== false ) {
            $aresult = explode('/',stristr($this->_agent,'Slurp'));
            $aversion = explode(' ',$aresult[1]);
            $this->setVersion($aversion[0]);
            $this->_browser_name = self::BROWSER_SLURP;
            $this->setRobot(true);
            $this->setMobile(false);
            return true;
        }
        return false;
    }

    protected function checkBrowserInternetExplorer() {

        // Test for v1 - v1.5 IE
        if( stripos($this->_agent,'microsoft internet explorer') !== false ) {
            $this->setBrowser(self::BROWSER_IE);
            $this->setVersion('1.0');
            $aresult = stristr($this->_agent, '/');
            if( preg_match('/308|425|426|474|0b1/i', $aresult) ) {
                $this->setVersion('1.5');
            }
            return true;
        }
        // Test for versions > 1.5
        else if( stripos($this->_agent,'msie') !== false && stripos($this->_agent,'opera') === false ) {
            // See if the browser is the odd MSN Explorer
            if( stripos($this->_agent,'msnb') !== false ) {
                $aresult = explode(' ',stristr(str_replace(';','; ',$this->_agent),'MSN'));
                $this->setBrowser( self::BROWSER_MSN );
                $this->setVersion(str_replace(array('(',')',';'),'',$aresult[1]));
                return true;
            }
            $aresult = explode(' ',stristr(str_replace(';','; ',$this->_agent),'msie'));
            $this->setBrowser( self::BROWSER_IE );
            $this->setVersion(str_replace(array('(',')',';'),'',$aresult[1]));
            return true;
        }
        // Test for Pocket IE
        else if( stripos($this->_agent,'mspie') !== false || stripos($this->_agent,'pocket') !== false ) {
            $aresult = explode(' ',stristr($this->_agent,'mspie'));
            $this->setPlatform( self::PLATFORM_WINDOWS_CE );
            $this->setBrowser( self::BROWSER_POCKET_IE );
            $this->setMobile(true);

            if( stripos($this->_agent,'mspie') !== false ) {
                $this->setVersion($aresult[1]);
            }
            else {
                $aversion = explode('/',$this->_agent);
                $this->setVersion($aversion[1]);
            }
            return true;
        }
        return false;
    }

    protected function checkBrowserOpera() {
        if( stripos($this->_agent,'opera mini') !== false ) {
            $resultant = stristr($this->_agent, 'opera mini');
            if( preg_match('/\//',$resultant) ) {
                $aresult = explode('/',$resultant);
                $aversion = explode(' ',$aresult[1]);
                $this->setVersion($aversion[0]);
            }
            else {
                $aversion = explode(' ',stristr($resultant,'opera mini'));
                $this->setVersion($aversion[1]);
            }
            $this->_browser_name = self::BROWSER_OPERA_MINI;
            $this->setMobile(true);
            return true;
        }
        else if( stripos($this->_agent,'opera') !== false ) {
            $resultant = stristr($this->_agent, 'opera');
            if( preg_match('/Version\/(10.*)$/',$resultant,$matches) ) {
                $this->setVersion($matches[1]);
            }
            else if( preg_match('/\//',$resultant) ) {
                $aresult = explode('/',str_replace("("," ",$resultant));
                $aversion = explode(' ',$aresult[1]);
                $this->setVersion($aversion[0]);
            }
            else {
                $aversion = explode(' ',stristr($resultant,'opera'));
                $this->setVersion(isset($aversion[1])?$aversion[1]:"");
            }
            $this->_browser_name = self::BROWSER_OPERA;
            return true;
        }
        return false;
    }


    protected function checkBrowserChrome() {
        if( stripos($this->_agent,'Chrome') !== false ) {
            $aresult = explode('/',stristr($this->_agent,'Chrome'));
            $aversion = explode(' ',$aresult[1]);
            $this->setVersion($aversion[0]);
            $this->setBrowser(self::BROWSER_CHROME);
            return true;
        }
        return false;
    }

    protected function checkBrowserWebTv() {
        if( stripos($this->_agent,'webtv') !== false ) {
            $aresult = explode('/',stristr($this->_agent,'webtv'));
            $aversion = explode(' ',$aresult[1]);
            $this->setVersion($aversion[0]);
            $this->setBrowser(self::BROWSER_WEBTV);
            return true;
        }
        return false;
    }

    protected function checkBrowserNetPositive() {
        if( stripos($this->_agent,'NetPositive') !== false ) {
            $aresult = explode('/',stristr($this->_agent,'NetPositive'));
            $aversion = explode(' ',$aresult[1]);
            $this->setVersion(str_replace(array('(',')',';'),'',$aversion[0]));
            $this->setBrowser(self::BROWSER_NETPOSITIVE);
            return true;
        }
        return false;
    }

    protected function checkBrowserGaleon() {
        if( stripos($this->_agent,'galeon') !== false ) {
            $aresult = explode(' ',stristr($this->_agent,'galeon'));
            $aversion = explode('/',$aresult[0]);
            $this->setVersion($aversion[1]);
            $this->setBrowser(self::BROWSER_GALEON);
            return true;
        }
        return false;
    }

    protected function checkBrowserKonqueror() {
        if( stripos($this->_agent,'Konqueror') !== false ) {
            $aresult = explode(' ',stristr($this->_agent,'Konqueror'));
            $aversion = explode('/',$aresult[0]);
            $this->setVersion($aversion[1]);
            $this->setBrowser(self::BROWSER_KONQUEROR);
            return true;
        }
        return false;
    }

    protected function checkBrowserIcab() {
        if( stripos($this->_agent,'icab') !== false ) {
            $aversion = explode(' ',stristr(str_replace('/',' ',$this->_agent),'icab'));
            $this->setVersion($aversion[1]);
            $this->setBrowser(self::BROWSER_ICAB);
            return true;
        }
        return false;
    }

    protected function checkBrowserOmniWeb() {
        if( stripos($this->_agent,'omniweb') !== false ) {
            $aresult = explode('/',stristr($this->_agent,'omniweb'));
            $aversion = explode(' ',isset($aresult[1])?$aresult[1]:"");
            $this->setVersion($aversion[0]);
            $this->setBrowser(self::BROWSER_OMNIWEB);
            return true;
        }
        return false;
    }

    protected function checkBrowserPhoenix() {
        if( stripos($this->_agent,'Phoenix') !== false ) {
            $aversion = explode('/',stristr($this->_agent,'Phoenix'));
            $this->setVersion($aversion[1]);
            $this->setBrowser(self::BROWSER_PHOENIX);
            return true;
        }
        return false;
    }

    protected function checkBrowserFirebird() {
        if( stripos($this->_agent,'Firebird') !== false ) {
            $aversion = explode('/',stristr($this->_agent,'Firebird'));
            $this->setVersion($aversion[1]);
            $this->setBrowser(self::BROWSER_FIREBIRD);
            return true;
        }
        return false;
    }

    protected function checkBrowserNetscapeNavigator9Plus() {
        if( stripos($this->_agent,'Firefox') !== false && preg_match('/Navigator\/([^ ]*)/i',$this->_agent,$matches) ) {
            $this->setVersion($matches[1]);
            $this->setBrowser(self::BROWSER_NETSCAPE_NAVIGATOR);
            return true;
        }
        else if( stripos($this->_agent,'Firefox') === false && preg_match('/Netscape6?\/([^ ]*)/i',$this->_agent,$matches) ) {
            $this->setVersion($matches[1]);
            $this->setBrowser(self::BROWSER_NETSCAPE_NAVIGATOR);
            return true;
        }
        return false;
    }

    protected function checkBrowserShiretoko() {
        if( stripos($this->_agent,'Mozilla') !== false && preg_match('/Shiretoko\/([^ ]*)/i',$this->_agent,$matches) ) {
            $this->setVersion($matches[1]);
            $this->setBrowser(self::BROWSER_SHIRETOKO);
            return true;
        }
        return false;
    }

    protected function checkBrowserIceCat() {
        if( stripos($this->_agent,'Mozilla') !== false && preg_match('/IceCat\/([^ ]*)/i',$this->_agent,$matches) ) {
            $this->setVersion($matches[1]);
            $this->setBrowser(self::BROWSER_ICECAT);
            return true;
        }
        return false;
    }

    protected function checkBrowserNokia() {
        if( preg_match("/Nokia([^\/]+)\/([^ SP]+)/i",$this->_agent,$matches) ) {
            $this->setVersion($matches[2]);
            if( stripos($this->_agent,'Series60') !== false || strpos($this->_agent,'S60') !== false ) {
                $this->setBrowser(self::BROWSER_NOKIA_S60);
            }
            else {
                $this->setBrowser( self::BROWSER_NOKIA );
            }
            $this->setMobile(true);
            return true;
        }
        return false;
    }

    protected function checkBrowserFirefox() {
        if( stripos($this->_agent,'safari') === false ) {
            if( preg_match("/Firefox[\/ \(]([^ ;\)]+)/i",$this->_agent,$matches) ) {
                $this->setVersion($matches[1]);
                $this->setBrowser(self::BROWSER_FIREFOX);
                return true;
            }
            else if( preg_match("/Firefox$/i",$this->_agent,$matches) ) {
                $this->setVersion("");
                $this->setBrowser(self::BROWSER_FIREFOX);
                return true;
            }
        }
        return false;
    }

    protected function checkBrowserIceweasel() {
        if( stripos($this->_agent,'Iceweasel') !== false ) {
            $aresult = explode('/',stristr($this->_agent,'Iceweasel'));
            $aversion = explode(' ',$aresult[1]);
            $this->setVersion($aversion[0]);
            $this->setBrowser(self::BROWSER_ICEWEASEL);
            return true;
        }
        return false;
    }

    protected function checkBrowserMozilla() {
        if( stripos($this->_agent,'mozilla') !== false  && preg_match('/rv:[0-9].[0-9][a-b]?/i',$this->_agent) && stripos($this->_agent,'netscape') === false) {
            $aversion = explode(' ',stristr($this->_agent,'rv:'));
            preg_match('/rv:[0-9].[0-9][a-b]?/i',$this->_agent,$aversion);
            $this->setVersion(str_replace('rv:','',$aversion[0]));
            $this->setBrowser(self::BROWSER_MOZILLA);
            return true;
        }
        else if( stripos($this->_agent,'mozilla') !== false && preg_match('/rv:[0-9]\.[0-9]/i',$this->_agent) && stripos($this->_agent,'netscape') === false ) {
            $aversion = explode('',stristr($this->_agent,'rv:'));
            $this->setVersion(str_replace('rv:','',$aversion[0]));
            $this->setBrowser(self::BROWSER_MOZILLA);
            return true;
        }
        else if( stripos($this->_agent,'mozilla') !== false  && preg_match('/mozilla\/([^ ]*)/i',$this->_agent,$matches) && stripos($this->_agent,'netscape') === false ) {
            $this->setVersion($matches[1]);
            $this->setBrowser(self::BROWSER_MOZILLA);
            return true;
        }
        return false;
    }

    protected function checkBrowserLynx() {
        if( stripos($this->_agent,'lynx') !== false ) {
            $aresult = explode('/',stristr($this->_agent,'Lynx'));
            $aversion = explode(' ',(isset($aresult[1])?$aresult[1]:""));
            $this->setVersion($aversion[0]);
            $this->setBrowser(self::BROWSER_LYNX);
            return true;
        }
        return false;
    }

    protected function checkBrowserAmaya() {
        if( stripos($this->_agent,'amaya') !== false ) {
            $aresult = explode('/',stristr($this->_agent,'Amaya'));
            $aversion = explode(' ',$aresult[1]);
            $this->setVersion($aversion[0]);
            $this->setBrowser(self::BROWSER_AMAYA);
            return true;
        }
        return false;
    }

    protected function checkBrowserSafari() {
        if( stripos($this->_agent,'Safari') !== false && stripos($this->_agent,'iPhone') === false && stripos($this->_agent,'iPod') === false ) {
            $aresult = explode('/',stristr($this->_agent,'Version'));
            if( isset($aresult[1]) ) {
                $aversion = explode(' ',$aresult[1]);
                $this->setVersion($aversion[0]);
            }
            else {
                $this->setVersion(self::VERSION_UNKNOWN);
            }
            $this->setBrowser(self::BROWSER_SAFARI);
            return true;
        }
        return false;
    }

    protected function checkBrowseriPhone() {
        if( stripos($this->_agent,'iPhone') !== false ) {
            $aresult = explode('/',stristr($this->_agent,'Version'));
            if( isset($aresult[1]) ) {
                $aversion = explode(' ',$aresult[1]);
                $this->setVersion($aversion[0]);
            }
            else {
                $this->setVersion(self::VERSION_UNKNOWN);
            }
            $this->setMobile(true);
            $this->setBrowser(self::BROWSER_IPHONE);
            return true;
        }
        return false;
    }

    protected function checkBrowseriPad() {
        if( stripos($this->_agent,'iPad') !== false ) {
            $aresult = explode('/',stristr($this->_agent,'Version'));
            if( isset($aresult[1]) ) {
                $aversion = explode(' ',$aresult[1]);
                $this->setVersion($aversion[0]);
            }
            else {
                $this->setVersion(self::VERSION_UNKNOWN);
            }
            $this->setMobile(true);
            $this->setBrowser(self::BROWSER_IPAD);
            return true;
        }
        return false;
    }

    protected function checkBrowseriPod() {
        if( stripos($this->_agent,'iPod') !== false ) {
            $aresult = explode('/',stristr($this->_agent,'Version'));
            if( isset($aresult[1]) ) {
                $aversion = explode(' ',$aresult[1]);
                $this->setVersion($aversion[0]);
            }
            else {
                $this->setVersion(self::VERSION_UNKNOWN);
            }
            $this->setMobile(true);
            $this->setBrowser(self::BROWSER_IPOD);
            return true;
        }
        return false;
    }

    protected function checkBrowserAndroid() {
        if( stripos($this->_agent,'Android') !== false ) {
            $aresult = explode(' ',stristr($this->_agent,'Android'));
            if( isset($aresult[1]) ) {
                $aversion = explode(' ',$aresult[1]);
                $this->setVersion($aversion[0]);
            }
            else {
                $this->setVersion(self::VERSION_UNKNOWN);
            }
            $this->setMobile(true);
            $this->setBrowser(self::BROWSER_ANDROID);
            return true;
        }
        return false;
    }

    /**
     * Determine the user's platform
     */
    protected function checkPlatform() {
        if( stripos($this->_agent, 'windows') !== false ) {
            $this->_platform = self::PLATFORM_WINDOWS;
        }
        else if( stripos($this->_agent, 'iPad') !== false ) {
            $this->_platform = self::PLATFORM_IPAD;
        }
        else if( stripos($this->_agent, 'iPod') !== false ) {
            $this->_platform = self::PLATFORM_IPOD;
        }
        else if( stripos($this->_agent, 'iPhone') !== false ) {
            $this->_platform = self::PLATFORM_IPHONE;
        }
        elseif( stripos($this->_agent, 'mac') !== false ) {
            $this->_platform = self::PLATFORM_APPLE;
        }
        elseif( stripos($this->_agent, 'android') !== false ) {
            $this->_platform = self::PLATFORM_ANDROID;
        }
        elseif( stripos($this->_agent, 'linux') !== false ) {
            $this->_platform = self::PLATFORM_LINUX;
        }
        else if( stripos($this->_agent, 'Nokia') !== false ) {
            $this->_platform = self::PLATFORM_NOKIA;
        }
        else if( stripos($this->_agent, 'BlackBerry') !== false ) {
            $this->_platform = self::PLATFORM_BLACKBERRY;
        }
        elseif( stripos($this->_agent,'FreeBSD') !== false ) {
            $this->_platform = self::PLATFORM_FREEBSD;
        }
        elseif( stripos($this->_agent,'OpenBSD') !== false ) {
            $this->_platform = self::PLATFORM_OPENBSD;
        }
        elseif( stripos($this->_agent,'NetBSD') !== false ) {
            $this->_platform = self::PLATFORM_NETBSD;
        }
        elseif( stripos($this->_agent, 'OpenSolaris') !== false ) {
            $this->_platform = self::PLATFORM_OPENSOLARIS;
        }
        elseif( stripos($this->_agent, 'SunOS') !== false ) {
            $this->_platform = self::PLATFORM_SUNOS;
        }
        elseif( stripos($this->_agent, 'OS\/2') !== false ) {
            $this->_platform = self::PLATFORM_OS2;
        }
        elseif( stripos($this->_agent, 'BeOS') !== false ) {
            $this->_platform = self::PLATFORM_BEOS;
        }
        elseif( stripos($this->_agent, 'win') !== false ) {
            $this->_platform = self::PLATFORM_WINDOWS;
        }

    }
}
?>

display HTML page after loading complete

try using javascript for this! Seems like its the best and easiest way to do this. You'll get inbuilt funcn to execute a html code only after HTML page loads completely.

or else you may use state based programming where an event occurs at a particular state of the browser..

How do we download a blob url video

If the blob is instantiated with data from an F4M manifest (check the Network Tab in Chrome's Developer Tools), you can download the video file using the php script posted here: https://n1njahacks.wordpress.com/2015/01/29/how-to-save-hds-flash-streams-from-any-web-page/

By putting:

  if ($manifest == '')
    $manifest = $_GET['manifest'];

before:

  if ($manifest)

you could even run it on a webserver, using requests with the query string: ?manifest=[manifest url].

Note that you'll probably want to use an FTP client to retrieve the downloaded video file and clean up after the script (it leaves all the downloaded video parts).

How to know whether refresh button or browser back button is clicked in Firefox

Use 'event.currentTarget.performance.navigation.type' to determine the type of navigation. This is working in IE, FF and Chrome.

function CallbackFunction(event) {
    if(window.event) {
        if (window.event.clientX < 40 && window.event.clientY < 0) {
            alert("back button is clicked");
        }else{
            alert("refresh button is clicked");
        }
    }else{
        if (event.currentTarget.performance.navigation.type == 2) {
            alert("back button is clicked");
        }
        if (event.currentTarget.performance.navigation.type == 1) {
            alert("refresh button is clicked");
        }           
    }
}

CORS Access-Control-Allow-Headers wildcard being ignored?

I found that Access-Control-Allow-Headers: * should be set ONLY for OPTIONS request. If you return it for POST request then browser cancel the request (at least for chrome)

The following PHP code works for me

// Allow CORS
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');    
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); 
}   
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    header("Access-Control-Allow-Headers: *");
}

I found similar questions with some misleading response:

  • Server thread says that this is 2 years bug of chrome: Access-Control-Allow-Headers does not match with localhost. It's wrong: I can use CORS to my local server with Post normally
  • Access-Control-Allow-Headers does accept wildcards. It's also wrong, wildcard works for me (I tested only with Chrome)

This take me half day to figure out the issue.

Happy coding

Why doesn't JavaScript support multithreading?

JavaScript does not support multi-threading because the JavaScript interpreter in the browser is a single thread (AFAIK). Even Google Chrome will not let a single web page’s JavaScript run concurrently because this would cause massive concurrency issues in existing web pages. All Chrome does is separate multiple components (different tabs, plug-ins, etcetera) into separate processes, but I can’t imagine a single page having more than one JavaScript thread.

You can however use, as was suggested, setTimeout to allow some sort of scheduling and “fake” concurrency. This causes the browser to regain control of the rendering thread, and start the JavaScript code supplied to setTimeout after the given number of milliseconds. This is very useful if you want to allow the viewport (what you see) to refresh while performing operations on it. Just looping through e.g. coordinates and updating an element accordingly will just let you see the start and end positions, and nothing in between.

We use an abstraction library in JavaScript that allows us to create processes and threads which are all managed by the same JavaScript interpreter. This allows us to run actions in the following manner:

  • Process A, Thread 1
  • Process A, Thread 2
  • Process B, Thread 1
  • Process A, Thread 3
  • Process A, Thread 4
  • Process B, Thread 2
  • Pause Process A
  • Process B, Thread 3
  • Process B, Thread 4
  • Process B, Thread 5
  • Start Process A
  • Process A, Thread 5

This allows some form of scheduling and fakes parallelism, starting and stopping of threads, etcetera, but it will not be true multi-threading. I don’t think it will ever be implemented in the language itself, since true multi-threading is only useful if the browser can run a single page multi-threaded (or even more than one core), and the difficulties there are way larger than the extra possibilities.

For the future of JavaScript, check this out: https://developer.mozilla.org/presentations/xtech2006/javascript/

Form/JavaScript not working on IE 11 with error DOM7011

I got the same console warning, when an ajax request was firing, so my form was also not working properly.

I disabled caching on the server's ajax call with the following response headers:

Cache-Control: no-cache, no-store, must-revalidate
Expires: -1
Pragma: no-cache

After this, the form was working. Refer to the server language (c#, php, java etc) you are using on how to add these response headers.

Chrome extension id - how to find it

Extension IDs can be found in:

chrome://extensions (Chrome_Hotdog >> More_tools >> Extensions) Developer mode.

For Linux: $HOME/.config/google-chrome/Default/Preferences (json file) under ["extensions"].

Disabled form inputs do not appear in the request

Simple workaround - just use hidden field as placeholder for select, checkbox and radio.

From this code to -

<form action="/Media/Add">
    <input type="hidden" name="Id" value="123" />

    <!-- this does not appear in request -->
    <input type="textbox" name="Percentage" value="100" disabled="disabled" /> 
    <select name="gender" disabled="disabled">
          <option value="male">Male</option>
          <option value="female" selected>Female</option>
    </select>

</form>

that code -

<form action="/Media/Add">
    <input type="hidden" name="Id" value="123" />

    <input type="textbox" value="100" readonly /> 

    <input type="hidden" name="gender" value="female" />
    <select name="gender" disabled="disabled">
          <option value="male">Male</option>
          <option value="female" selected>Female</option>
    </select>
</form>

How to set up Android emulator proxy settings

nothin of that worked i am using eclipse on windows 64-bit: do the folllowing steps... it worked for me: Window -> Preferences -> Android -> Launch -> Default Emulator Options -http-proxy="http://10.1.8.30:8080"

in your eclipse window

How to programmatically empty browser cache?

Initially I tried various programmatic approach in my html, JS to clear browser cache. Nothing works on latest Chrome.

Finally, I ended up with .htaccess:

<IfModule mod_headers.c>
    Header set Cache-Control "no-cache, no-store, must-revalidate"
    Header set Pragma "no-cache"
    Header set Expires 0
</IfModule>

Tested in Chrome, Firefox, Opera

Reference: https://wp-mix.com/disable-caching-htaccess/

What is a MIME type?

It is useful to think of MIME in the context of the client-server model. Clients and servers communicate over what is known as the HTTP protocol. In a http request or response, we can have a body. The Content-type or MIME type specifies what is the type of the body, like text/javascript or something else like audio, video, etc.

However, MIME types are not limited just to HTTP.

As the name suggests, MIME stands for Multipurpose Internet Mail Extensions. Originally, SMTP only supported ascii-encodings. However, there as a need for more. We could use MIME to slap a label on the content being transmitted or received.

Open a link in browser with java button?

Use the Desktop#browse(URI) method. It opens a URI in the user's default browser.

public static boolean openWebpage(URI uri) {
    Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
    if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
        try {
            desktop.browse(uri);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return false;
}

public static boolean openWebpage(URL url) {
    try {
        return openWebpage(url.toURI());
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return false;
}

Browser Caching of CSS files

It does depend on the HTTP headers sent with the CSS files as both of the previous answers state - as long as you don't append any cachebusting stuff to the href. e.g.

<link href="/stylesheets/mycss.css?some_var_to_bust_cache=24312345" rel="stylesheet" type="text/css" />

Some frameworks (e.g. rails) put these in by default.

However If you get something like firebug or fiddler, you can see exactly what your browser is downloading on each request - which is expecially useful for finding out what your browser is doing, as opposed to just what it should be doing.

All browsers should respect the cache headers in the same way, unless configured to ignore them (but there are bound to be exceptions)

Force IE9 to emulate IE8. Possible?

You can use the document compatibility mode to do this, which is what you were trying.. However, thing to note is: It must appear in the Web page's header (the HEAD section) before all other elements, except for the title element and other meta elements Hope that was the issue.. Also, The X-UA-compatible header is not case sensitive Refer: http://msdn.microsoft.com/en-us/library/cc288325%28v=vs.85%29.aspx#SetMode

Edit: in case something happens to kill the msdn link, here is the content:

Specifying Document Compatibility Modes

You can use document modes to control the way Internet Explorer interprets and displays your webpage. To specify a specific document mode for your webpage, use the meta element to include an X-UA-Compatible header in your webpage, as shown in the following example.

<html>
<head>
  <!-- Enable IE9 Standards mode -->
  <meta http-equiv="X-UA-Compatible" content="IE=9" >
  <title>My webpage</title>
</head>
<body>
  <p>Content goes here.</p>
</body>
</html> 

If you view this webpage in Internet Explorer 9, it will be displayed in IE9 mode.

The following example specifies EmulateIE7 mode.

<html>
<head>
  <!-- Mimic Internet Explorer 7 -->
  <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" >
  <title>My webpage</title>
</head>
<body>
  <p>Content goes here.</p>
</body>
</html> 

In this example, the X-UA-Compatible header directs Internet Explorer to mimic the behavior of Internet Explorer 7 when determining how to display the webpage. This means that Internet Explorer will use the directive (or lack thereof) to choose the appropriate document type. Because this page does not contain a directive, the example would be displayed in IE5 (Quirks) mode.

How do I make JavaScript beep?

function Sound(url, vol, autoplay, loop)
{
    var that = this;

    that.url = (url === undefined) ? "" : url;
    that.vol = (vol === undefined) ? 1.0 : vol;
    that.autoplay = (autoplay === undefined) ? true : autoplay;
    that.loop = (loop === undefined) ? false : loop;
    that.sample = null;

    if(that.url !== "")
    {
        that.sync = function(){
            that.sample.volume = that.vol;
            that.sample.loop = that.loop;
            that.sample.autoplay = that.autoplay;
            setTimeout(function(){ that.sync(); }, 60);
        };

        that.sample = document.createElement("audio");
        that.sample.src = that.url;
        that.sync();

        that.play = function(){
            if(that.sample)
            {
                that.sample.play();
            }
        };

        that.pause = function(){
            if(that.sample)
            {
                that.sample.pause();
            }
        };
    }
}

var test = new Sound("http://mad-hatter.fr/Assets/projects/FreedomWings/Assets/musiques/freedomwings.mp3");
test.play();

http://jsfiddle.net/sv9j638j/

How to force open links in Chrome not download them?

I think the question was about to open a local file directly instead of downloading a local file to the download folder and open the file in the download folder, which seems not possible in Chrome, except some add-on mentioned above.

My workaround would be to right click -> Copy the link location Windows + R and paste the link there and Enter It will go to the file directly.

Stop Visual Studio from launching a new browser window when starting debug?

I looked over the answers and didn't see the solution I found mentioned. If it was, my apologies. In my case, currently using Visual Studio 2015. In the solution explorer, right click on the Project file and click properties. Go to the Debug tab and this should have info for how you're launching "IIS Express or Web(DNX)" for the first two drop downs, and then there should be a checkmark box for "Launch URL:". Uncheck this option and your browser won't be automatically launched everytime you go to debug your application. Hope this helps someone out.

How to prevent a browser from storing passwords

This is not possible in modern browsers, and for good reason. Modern browsers offer password managers, which enable users to use stronger passwords than they would usually.

As explained by MDN: How to Turn Off Form Autocompletion:

Modern browsers implement integrated password management: when the user enters a username and password for a site, the browser offers to remember it for the user. When the user visits the site again, the browser autofills the login fields with the stored values.

Additionally, the browser enables the user to choose a master password that the browser will use to encrypt stored login details.

Even without a master password, in-browser password management is generally seen as a net gain for security. Since users do not have to remember passwords that the browser stores for them, they are able to choose stronger passwords than they would otherwise.

For this reason, many modern browsers do not support autocomplete="off" for login fields:

  • If a site sets autocomplete="off" for a form, and the form includes username and password input fields, then the browser will still offer to remember this login, and if the user agrees, the browser will autofill those fields the next time the user visits the page.

  • If a site sets autocomplete="off" for username and password input fields, then the browser will still offer to remember this login, and if the user agrees, the browser will autofill those fields the next time the user visits the page.

This is the behavior in Firefox (since version 38), Google Chrome (since 34), and Internet Explorer (since version 11).

If an author would like to prevent the autofilling of password fields in user management pages where a user can specify a new password for someone other than themself, autocomplete="new-password" should be specified, though support for this has not been implemented in all browsers yet.

css 'pointer-events' property alternative for IE

Best solution:

.disabled{filter: alpha(opacity=50);opacity: 0.5;z-index: 1;pointer-events: none;}

Runs perfectly on all browsers

How to Identify Microsoft Edge browser via CSS?

More accurate for Edge (do not include latest IE 15) is:

@supports (display:-ms-grid) { ... }

@supports (-ms-ime-align:auto) { ... } works for all Edge versions (currently up to IE15).

Can I pass a JavaScript variable to another browser window?

You can use window.name as a data transport between windows - and it works cross domain as well. Not officially supported, but from my understanding, actually works very well cross browser.

More info here on this Stackoverflow Post

How to force IE10 to render page in IE9 document mode

Do you mean you want to tell your copy of IE 10 to render the pages it views in IE 9 mode?

Or do you mean you want your website to force IE 10 to render it in IE 9 mode?

For the former:

To force a webpage you are viewing in Internet Explorer 10 into a particular document compatibility mode, first open F12 Tools by pressing the F12 key. Then, on the Browser Mode menu, click Internet Explorer 10, and on the Document Mode menu, click Standards.

http://msdn.microsoft.com/en-gb/library/ie/hh920756(v=vs.85).aspx

For the latter, the other answers are correct, but I wouldn't advise doing that. IE 10 is more standards-compliant (i.e. more similar to other browsers) than IE 9.

How to detect the device orientation using CSS media queries?

@media all and (orientation:portrait) {
/* Style adjustments for portrait mode goes here */
}

@media all and (orientation:landscape) {
  /* Style adjustments for landscape mode goes here */
}

but it still looks like you have to experiment

How to change the default browser to debug with in Visual Studio 2008?

If you are using MVC 2 you do not need to create another project, just add component -> webform to the project then:

* Right click the webform  
* Select Browse With...  
* Choose your browser  
* Click Set as Default  
* Delete the webform

How to open a PDF file in an <iframe>?

This is the code to link an HTTP(S) accessible PDF from an <iframe>:

<iframe src="https://research.google.com/pubs/archive/44678.pdf"
   width="800" height="600">

Fiddle: http://jsfiddle.net/cEuZ3/1545/

EDIT: and you can use Javascript, from the <a> tag (onclick event) to set iFrame' SRC attribute at run-time...

EDIT 2: Apparently, it is a bug (but there are workarounds):

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

Pandas sort by group aggregate and column

One way to do this is to insert a dummy column with the sums in order to sort:

In [10]: sum_B_over_A = df.groupby('A').sum().B

In [11]: sum_B_over_A
Out[11]: 
A
bar    0.253652
baz   -2.829711
foo    0.551376
Name: B

in [12]: df['sum_B_over_A'] = df.A.apply(sum_B_over_A.get_value)

In [13]: df
Out[13]: 
     A         B      C  sum_B_over_A
0  foo  1.624345  False      0.551376
1  bar -0.611756   True      0.253652
2  baz -0.528172  False     -2.829711
3  foo -1.072969   True      0.551376
4  bar  0.865408  False      0.253652
5  baz -2.301539   True     -2.829711

In [14]: df.sort(['sum_B_over_A', 'A', 'B'])
Out[14]: 
     A         B      C   sum_B_over_A
5  baz -2.301539   True      -2.829711
2  baz -0.528172  False      -2.829711
1  bar -0.611756   True       0.253652
4  bar  0.865408  False       0.253652
3  foo -1.072969   True       0.551376
0  foo  1.624345  False       0.551376

and maybe you would drop the dummy row:

In [15]: df.sort(['sum_B_over_A', 'A', 'B']).drop('sum_B_over_A', axis=1)
Out[15]: 
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

Add context path to Spring Boot application

The correct properties are

server.servlet.path

to configure the path of the DispatcherServlet

and

server.servlet.context-path

to configure the path of the applications context below that.

AWS S3 CLI - Could not connect to the endpoint URL

first you use 'aws configure' then input the access key, and secret key, and the region. the region you input would be important for this problem. try to input something like 's3.us-east-1', not 's3.us-east-1a'. it will solve the issue.

How to access Winform textbox control from another class?

I used this method for updating a label but you could easily change it to a textbox:

Class:

public Class1
{
    public Form_Class formToOutput;

    public Class1(Form_Class f){
        formToOutput = f;
    }

    // Then call this method and pass whatever string
    private void Write(string s)
    {
        formToOutput.MethodToBeCalledByClass(s);
    }
}

Form methods that will do the updating:

public Form_Class{

    // Methods that will do the updating
    public void MethodToBeCalledByClass(string messageToSend)
    {
       if (InvokeRequired) { 
           Invoke(new OutputDelegate(UpdateText),messageToSend); 
       }
    }

    public delegate void OutputDelegate(string messageToSend);
    public void UpdateText(string messageToSend)
    {
       label1.Text = messageToSend;
    }
}

Finally

Just pass the form through the constructor:

Class1 c = new Class1(this);

No shadow by default on Toolbar?

In my situation elevation doesn't work well because I haven't given any background to the toolbar. Try giving background color to the toolbar then set elevation and it will work well.

How do I get only directories using Get-ChildItem?

A cleaner approach:

Get-ChildItem "<name_of_directory>" | where {$_.Attributes -match'Directory'}

I wonder if PowerShell 3.0 has a switch that only returns directories; it seems like a logical thing to add.

Git: Permission denied (publickey) fatal - Could not read from remote repository. while cloning Git repository

I also faced the same issue. I did the following and it worked for me:

  1. Generate Keys from the GIT GUI client on Windows. Copy this key to the clipboard.
  2. Open up your account on bitBucket/ git website, and add this key to your profile. This way, the server knows that you are a legitimate user accessing from a legitimate system.
  3. That's it. All push commands worked for me henceforth.

POSTing JSON to URL via WebClient in C#

The question is already answered but I think I've found the solution that is simpler and more relevant to the question title, here it is:

var cli = new WebClient();
cli.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = cli.UploadString("http://some/address", "{some:\"json data\"}");

PS: In the most of .net implementations, but not in all WebClient is IDisposable, so of cource it is better to do 'using' or 'Dispose' on it. However in this particular case it is not really necessary.

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

You have to add options also in allowed headers. browser sends a preflight request before original request is sent. See below

 res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');

From source https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS

In CORS, a preflight request with the OPTIONS method is sent, so that the server can respond whether it is acceptable to send the request with these parameters. The Access-Control-Request-Method header notifies the server as part of a preflight request that when the actual request is sent, it will be sent with a POST request method. The Access-Control-Request-Headers header notifies the server that when the actual request is sent, it will be sent with a X-PINGOTHER and Content-Type custom headers. The server now has an opportunity to determine whether it wishes to accept a request under these circumstances.

EDITED

You can avoid this manual configuration by using npmjs.com/package/cors npm package.I have used this method also, it is clear and easy.

When to use self over $this?

self:: keyword used for the current class and basically it is used to access static members, methods, and constants. But in case of $this you cannot call the static member, method and functions.

You can use the self:: keyword in another class and access the static members, method and constants. When it will be extends from parent class and same in case of $this keyword. You can access the non static members, method and function in another class when it will be extends from parent class.

The code given below is a example of self:: and $this keyword. Just copy and paste the code in your code file and see the output.

class cars{
    var $doors=4;   
    static $car_wheel=4;

  public function car_features(){
    echo $this->doors." Doors <br>";
    echo self::$car_wheel." Wheels <br>"; 
  }
}

class spec extends cars{
    function car_spec(){
        print(self::$car_wheel." Doors <br>");
        print($this->doors." Wheels <br>");
    }
}

/********Parent class output*********/

$car = new cars;
print_r($car->car_features());

echo "------------------------<br>";

/********Extend class from another class output**********/


$car_spec_show=new spec;

print($car_spec_show->car_spec());

How do you get total amount of RAM the computer has?

Nobody has mentioned GetPerformanceInfo yet. PInvoke signatures are available.

This function makes the following system-wide information available:

  • CommitTotal
  • CommitLimit
  • CommitPeak
  • PhysicalTotal
  • PhysicalAvailable
  • SystemCache
  • KernelTotal
  • KernelPaged
  • KernelNonpaged
  • PageSize
  • HandleCount
  • ProcessCount
  • ThreadCount

PhysicalTotal is what the OP is looking for, although the value is the number of pages, so to convert to bytes, multiply by the PageSize value returned.

Get value of a merged cell of an excel from its cell address in vba

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).

Hence, you can get the value of merged cells in range B4:B11 in several ways:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty.

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array.

Zoom to fit all markers in Mapbox or Leaflet

You have an array of L.Marker:

let markers = [marker1, marker2, marker3]

let latlngs = markers.map(marker => marker.getLatLng())

let latlngBounds = L.latLngBounds(latlngs)

map.fitBounds(latlngBounds)
// OR with a smooth animation
// map.flyToBounds(latlngBounds)

How to know whether refresh button or browser back button is clicked in Firefox

For Back Button in jquery // http://code.jquery.com/jquery-latest.js

 jQuery(window).bind("unload", function() { //

and in html5 there is an event The event is called 'popstate'

window.onpopstate = function(event) {
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};

and for refresh please check Check if page gets reloaded or refreshed in Javascript

In Mozilla Client-x and client-y is inside document area https://developer.mozilla.org/en-US/docs/Web/API/event.clientX

How to draw an overlay on a SurfaceView used by Camera on Android?

Try calling setWillNotDraw(false) from surfaceCreated:

public void surfaceCreated(SurfaceHolder holder) {
    try {
        setWillNotDraw(false); 
        mycam.setPreviewDisplay(holder);
        mycam.startPreview();
    } catch (Exception e) {
        e.printStackTrace();
        Log.d(TAG,"Surface not created");
    }
}

@Override
protected void onDraw(Canvas canvas) {

    canvas.drawRect(area, rectanglePaint);
    Log.w(this.getClass().getName(), "On Draw Called");
}

and calling invalidate from onTouchEvent:

public boolean onTouch(View v, MotionEvent event) {

    invalidate();
    return true;
}

How do I resize an image using PIL and maintain its aspect ratio?

Based in @tomvon, I finished using the following (pick your case):

a) Resizing height (I know the new width, so I need the new height)

new_width  = 680
new_height = new_width * height / width 

b) Resizing width (I know the new height, so I need the new width)

new_height = 680
new_width  = new_height * width / height

Then just:

img = img.resize((new_width, new_height), Image.ANTIALIAS)

What is class="mb-0" in Bootstrap 4?

Bootstrap has predefined classes that we use for styling. If you are familiar with CSS, you'd know what padding, margin and spacing etc. are.

mb-0 = margin-bottom:0;

OK now moving a little further in knowledge, bootstrap has more classes for margin including:

mt- = margin-top
mb- = margin-bottom
ml- = margin-left
mr- = margin-right
my- = it sets margin-left and margin-right at the same time on y axes
mX- = it sets margin-bottom and margin-top at the same time on X axes

This and much more is explained here https://getbootstrap.com/docs/5.0/utilities/spacing/ The best way to learn is through https://getbootstrap.com site itself. It explains a lot obout its built in classes.

Update GCC on OSX

You can install your GCC manually

either through

sudo port install gcc46

or your download the source code from one of the mirrors from here for example here

tar xzvf gcc-4.6.0.tar.gz cd gcc-4.6.0 ./configure make

well if you have multiple version, then through you can choose one

port select --list gcc

remember port on mac is called macport https://www.macports.org/install.php and add add the bin into your path export PATH=$PATH:/opt/local/bin

How to convert an OrderedDict into a regular dict in python3

Even though this is a year old question, I would like to say that using dict will not help if you have an ordered dict within the ordered dict. The simplest way that could convert those recursive ordered dict will be

import json
from collections import OrderedDict
input_dict = OrderedDict([('method', 'constant'), ('recursive', OrderedDict([('m', 'c')]))])
output_dict = json.loads(json.dumps(input_dict))
print output_dict

Nginx: Job for nginx.service failed because the control process exited

  • use these command to

    1. sudo service apache2 stop

    2. sudo apt-get purge apache2

    3. sudo apt-get update

    4. sudo apt-get install nginx

    5. sudo service nginx restart

How can we dynamically allocate and grow an array

Visual Basic has a nice function : ReDim Preserve.

Someone has kindly written an equivalent function - you can find it here. I think it does exactly what you are asking for (and you're not re-inventing the wheel - you're copying someone else's)...

Get form data in ReactJS

Adding on to Michael Schock's answer:

class MyForm extends React.Component {
  constructor() {
    super();
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();
    const data = new FormData(event.target);

    console.log(data.get('email')); // reference by form input's `name` tag

    fetch('/api/form-submit-url', {
      method: 'POST',
      body: data,
    });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label htmlFor="username">Enter username</label>
        <input id="username" name="username" type="text" />

        <label htmlFor="email">Enter your email</label>
        <input id="email" name="email" type="email" />

        <label htmlFor="birthdate">Enter your birth date</label>
        <input id="birthdate" name="birthdate" type="text" />

        <button>Send data!</button>
      </form>
    );
  }
}

See this Medium article: How to Handle Forms with Just React

This method gets form data only when Submit button is pressed. Much cleaner IMO!

JavaScript operator similar to SQL "like"

You can use regular expressions in Javascript to do pattern matching of strings.

For example:

var s = "hello world!";
if (s.match(/hello.*/)) {
  // do something
}

The match() test is much like WHERE s LIKE 'hello%' in SQL.

How to use sed to remove all double quotes within a file

Try prepending the doublequote with a backslash in your expresssion:

sed 's/\"//g' [file name]

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

This can also happen when the log file is restricted in size.

Right click database in Object Explorer

Select Properties

Select Files

On the log line, click the ellipsis in the Autogrowth / Maxsize column

Change/verify Maximum File Size is Unlimited.

enter image description here

After chaning to unlimited, database came back to life.

How can I "disable" zoom on a mobile web page?

document.addEventListener('dblclick', (event) => {
    event.preventDefault()
}, { passive: false });

Can I position an element fixed relative to parent?

I know this is an older post, but I think a good example of what Jiew Meng was trying to do can already be found on this site. Check out the side menu located here: https://stackoverflow.com/faq#questions. Looking at it without getting into it too deep, I can tell javascript attaches a fixed position once the scrolling hits below the anchor tag and removes the fixed positioning if the scrolling goes above that same anchor tag. Hopefully, that will get someone started in the right direction.

How to convert object array to string array in Java

If you want to get a String representation of the objects in your array, then yes, there is no other way to do it.

If you know your Object array contains Strings only, you may also do (instread of calling toString()):

for (int i=0;i<String_Array.length;i++) String_Array[i]= (String) Object_Array[i];

The only case when you could use the cast to String[] of the Object_Array would be if the array it references would actually be defined as String[] , e.g. this would work:

    Object[] o = new String[10];
    String[] s = (String[]) o;

Check that a variable is a number in UNIX shell

Shell variables have no type, so the simplest way is to use the return type test command:

if [ $var -eq $var 2> /dev/null ]; then ...

(Or else parse it with a regexp)

installing apache: no VCRUNTIME140.dll

I was gone through same problem & I resolved it by following steps.

  1. Uninstall earlier version of wamp server, which you are trying to install.
  2. Install which ever file supports to your configuration (64, 86) from en this link
  3. Restart your computer.
  4. Install wampserver now.

comparing 2 strings alphabetically for sorting purposes

Lets look at some test cases - try running the following expressions in your JS console:

"a" < "b"

"aa" < "ab"

"aaa" < "aab"

All return true.

JavaScript compares strings character by character and "a" comes before "b" in the alphabet - hence less than.

In your case it works like so -

1 . "a?aaa" < "?a?b"

compares the first two "a" characters - all equal, lets move to the next character.

2 . "a?a??aa" < "a?b??"

compares the second characters "a" against "b" - whoop! "a" comes before "b". Returns true.

Convert integer to hexadecimal and back again

int valInt = 12;
Console.WriteLine(valInt.ToString("X"));  // C  ~ possibly single-digit output 
Console.WriteLine(valInt.ToString("X2")); // 0C ~ always double-digit output

html "data-" attribute as javascript parameter

JS:

function fun(obj) {
    var uid= $(obj).data('uid');
    var name= $(obj).data('name');
    var value= $(obj).data('value');
}

PHP array() to javascript array()

<?php 
            $ConvertDateBack = Zend_Controller_Action_HelperBroker::getStaticHelper('ConvertDate');
            $disabledDaysRange = array();
            foreach($this->reservedDates as $dates) {
                 $date = $ConvertDateBack->ConvertDateBack($dates->reservation_date);
                 $disabledDaysRange[] = $date;
                 array_push($disabledDaysRange, $date);
            }

            $finalArr = json_encode($disabledDaysRange);
?>
<script>
var disabledDaysRange = <?=$finalArr?>;

</script>

Python constructors and __init__

There is no notion of method overloading in Python. But you can achieve a similar effect by specifying optional and keyword arguments

Concatenating elements in an array to a string

For those who develop in Android, use TextUtils.

String items = TextUtils.join("", arr);

Assuming arr is of type String[] arr= {"1","2","3"};

The output would be 123

How to submit a form with JavaScript by clicking a link?

You could give the form and the link some ids and then subscribe for the onclick event of the link and submit the form:

<form id="myform" action="" method="POST">
    <a href="#" id="mylink"> submit </a>
</form>

and then:

window.onload = function() {
    document.getElementById('mylink').onclick = function() {
        document.getElementById('myform').submit();
        return false;
    };
};

I would recommend you using a submit button for submitting forms as it respects the markup semantics and it will work even for users with javascript disabled.

Oracle - how to remove white spaces?

If you would like to replace white spaces in a particular column value, you can use the following script to do the job for you,

UPDATE TableName TN
   SET TN.Column_Name   = TRIM (TN.Column_Name);

how to check if List<T> element contains an item with a Particular Property Value

var item = pricePublicList.FirstOrDefault(x => x.Size == 200);
if (item != null) {
   // There exists one with size 200 and is stored in item now
}
else {
  // There is no PricePublicModel with size 200
}

What is the purpose of meshgrid in Python / NumPy?

Short answer

The purpose of meshgrid is to help remplace Python loops (slow interpreted code) by vectorized operations within C NumPy library.

Borrowed from this site.

enter image description here

x = np.arange(-4, 4, 0.25)
y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(x, y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

meshgrid is used to create pairs of coordinates between -4 and +4 with .25 increments in each direction X and Y. Each pair is then used to find R, and Z from it. This way of preparing "a grid" of coordinates is frequently used in plotting 3D surfaces, or coloring 2D surfaces.


Details: Python for-loop vs NumPy vector operation

To take a more simple example, let's say we have two sequences of values,

a = [2,7,9,20]    
b = [1,6,7,9]    ?

and we want to perform an operation on each possible pair of values, one taken from the first list, one taken from the second list. We also want to store the result. For example, let's say we want to get the sum of the values for each possible pair.

Slow and laborious method

c = []    
for i in range(len(b)):    
    row = []    
    for j in range(len(a)):    
        row.append (a[j] + b[i])
    c.append (row)    
print (c)

Result:

[[3, 8, 10, 21],
 [8, 13, 15, 26],
 [9, 14, 16, 27],
 [11, 16, 18, 29]]

Python is interpreted, these loops are relatively slow to execute.

Fast and easy method

meshgrid is intended to remove the loops from the code. It returns two arrays (i and j below) which can be combined to scan all the existing pairs like this:

i,j = np.meshgrid (a,b)    
c = i + j    
print (c)

Result:

[[ 3  8 10 21]
 [ 8 13 15 26]
 [ 9 14 16 27]
 [11 16 18 29]]

Meshgrid under the hood

The two arrays prepared by meshgrid are:

(array([[ 2,  7,  9, 20],
        [ 2,  7,  9, 20],
        [ 2,  7,  9, 20],
        [ 2,  7,  9, 20]]),

 array([[1, 1, 1, 1],
        [6, 6, 6, 6],
        [7, 7, 7, 7],
        [9, 9, 9, 9]]))

These arrays are created by repeating the values provided. One contains the values in identical rows, the other contains the other values in identical columns. The number of rows and column is determined by the number of elements in the other sequence.

The two arrays created by meshgrid are therefore shape compatible for a vector operation. Imagine x and y sequences in the code at the top of page having a different number of elements, X and Y resulting arrays will be shape compatible anyway, not requiring any broadcast.

Origin

numpy.meshgrid comes from MATLAB, like many other NumPy functions. So you can also study the examples from MATLAB to see meshgrid in use, the code for the 3D plotting looks the same in MATLAB.

jquery function val() is not equivalent to "$(this).value="?

$(this).value is attempting to call the 'value' property of a jQuery object, which does not exist. Native JavaScript does have a 'value' property on certain HTML objects, but if you are operating on a jQuery object you must access the value by calling $(this).val().

The most efficient way to remove first N elements in a list?

Python lists were not made to operate on the beginning of the list and are very ineffective at this operation.

While you can write

mylist = [1, 2 ,3 ,4]
mylist.pop(0)

It's very inefficient.


If you only want to delete items from your list, you can do this with del:

del mylist[:n]

Which is also really fast:

In [34]: %%timeit
help=range(10000)
while help:
    del help[:1000]
   ....:
10000 loops, best of 3: 161 µs per loop

If you need to obtain elements from the beginning of the list, you should use collections.deque by Raymond Hettinger and its popleft() method.

from collections import deque

deque(['f', 'g', 'h', 'i', 'j'])

>>> d.pop()                          # return and remove the rightmost item
'j'
>>> d.popleft()                      # return and remove the leftmost item
'f'

A comparison:

list + pop(0)

In [30]: %%timeit
   ....: help=range(10000)
   ....: while help:
   ....:     help.pop(0)
   ....:
100 loops, best of 3: 17.9 ms per loop

deque + popleft()

In [33]: %%timeit
help=deque(range(10000))
while help:
    help.popleft()
   ....:
1000 loops, best of 3: 812 µs per loop

Retrieving parameters from a URL

In pure Python:

def get_param_from_url(url, param_name):
    return [i.split("=")[-1] for i in url.split("?", 1)[-1].split("&") if i.startswith(param_name + "=")][0]

Post parameter is always null

I was looking for a solution to this problem for some minutes now, so I'll share my solution.

If you post a model your model needs to have an empty/default constructor, otherwise the model can't be created, obviously. Be careful while refactoring. ;)

What is the best way to do a substring in a batch file?

As an additional info to Joey's answer, which isn't described in the help of set /? nor for /?.

%~0 expands to the name of the own batch, exactly as it was typed.
So if you start your batch it will be expanded as

%~0   - mYbAtCh
%~n0  - mybatch
%~nx0 - mybatch.bat

But there is one exception, expanding in a subroutine could fail

echo main- %~0
call :myFunction
exit /b

:myFunction
echo func - %~0
echo func - %~n0
exit /b

This results to

main - myBatch
Func - :myFunction
func - mybatch

In a function %~0 expands always to the name of the function, not of the batch file.
But if you use at least one modifier it will show the filename again!

Pass table as parameter into sql server UDF

To obtain the column count on a table, use this:

select count(id) from syscolumns where id = object_id('tablename')

and to pass a table to a function, try XML as show here:

create function dbo.ReadXml (@xmlMatrix xml)
returns table
as
return
( select
t.value('./@Salary', 'integer') as Salary,
t.value('./@Age', 'integer') as Age
from @xmlMatrix.nodes('//row') x(t)
)
go

declare @source table
( Salary integer,
age tinyint
)
insert into @source
select 10000, 25 union all
select 15000, 27 union all
select 12000, 18 union all
select 15000, 36 union all
select 16000, 57 union all
select 17000, 44 union all
select 18000, 32 union all
select 19000, 56 union all
select 25000, 34 union all
select 7500, 29
--select * from @source

declare @functionArgument xml

select @functionArgument =
( select
Salary as [row/@Salary],
Age as [row/@Age]
from @source
for xml path('')
)
--select @functionArgument as [@functionArgument]

select * from readXml(@functionArgument)

/* -------- Sample Output: --------
Salary Age
----------- -----------
10000 25
15000 27
12000 18
15000 36
16000 57
17000 44
18000 32
19000 56
25000 34
7500 29
*/

Adding days to a date in Python

Sometimes we need to use searching by from date & to date. If we use date__range then we need to add 1 day to to_date otherwise queryset will be empty.

Example:

from datetime import timedelta  

from_date  = parse_date(request.POST['from_date'])

to_date    = parse_date(request.POST['to_date']) + timedelta(days=1)

attendance_list = models.DailyAttendance.objects.filter(attdate__range = [from_date, to_date])

Android: Force EditText to remove focus?

Add these two properties to your parent layout (ex: Linear Layout, Relative Layout)

android:focusable="true"
android:focusableInTouchMode="true" 

It will do the trick :)

Changing factor levels with dplyr mutate

Can't comment because I don't have enough reputation points, but recode only works on a vector, so the above code in @Stefano's answer should be

df <- iris %>%
  mutate(Species = recode(Species, 
     setosa = "SETOSA",
     versicolor = "VERSICOLOR",
     virginica = "VIRGINICA")
  )

how to view the contents of a .pem certificate

An alternative to using keytool, you can use the command

openssl x509 -in certificate.pem -text

This should work for any x509 .pem file provided you have openssl installed.

Hunk #1 FAILED at 1. What's that mean?

Follow the instructions here, it solved my problem.

you have to run the command like as follow; patch -p0 --dry-run < path/to/your/patchFile/yourPatch.patch

Hibernate HQL Query : How to set a Collection as a named parameter of a Query?

Use Query.setParameterList(), Javadoc here.

There are four variants to pick from.

Yarn: How to upgrade yarn version using terminal?

On Linux, just run below command at terminal:

$ curl --compressed -o- -L https://yarnpkg.com/install.sh | bash

After do this, close the current terminal and open it again. And then, run below command to check yarn current version:

$ yarn --version

Json.NET serialize object with root name

Writing a custom JsonConverter is another approach mentioned in similar questions. However, due to nature of how JsonConverter is designed, using that approach for this question is tricky, as you need to be careful with the WriteJson implementation to avoid getting into infinite recursion: JSON.Net throws StackOverflowException when using [JsonConvert()].

One possible implementation:

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
    //JToken t = JToken.FromObject(value); // do not use this! leads to stack overflow
    JsonObjectContract contract = (JsonObjectContract)serializer.ContractResolver.ResolveContract(value.GetType());

    writer.WriteStartObject();
    writer.WritePropertyName(value.GetType().Name);
    writer.WriteStartObject();
    foreach (var property in contract.Properties)
    {
        // this removes any property with null value
        var propertyValue = property.ValueProvider.GetValue(value);
        if (propertyValue == null) continue;

        writer.WritePropertyName(property.PropertyName);
        serializer.Serialize(writer, propertyValue);
        //writer.WriteValue(JsonConvert.SerializeObject(property.ValueProvider.GetValue(value))); // this adds escaped quotes
    }
    writer.WriteEndObject();
    writer.WriteEndObject();
}

Convert Iterable to Stream using Java 8 JDK

There's a much better answer than using spliteratorUnknownSize directly, which is both easier and gets a better result. Iterable has a spliterator() method, so you should just use that to get your spliterator. In the worst case, it's the same code (the default implementation uses spliteratorUnknownSize), but in the more common case, where your Iterable is already a collection, you'll get a better spliterator, and therefore better stream performance (maybe even good parallelism). It's also less code:

StreamSupport.stream(iterable.spliterator(), false)
             .filter(...)
             .moreStreamOps(...);

As you can see, getting a stream from an Iterable (see also this question) is not very painful.

Inserting an image with PHP and FPDF

You can't treat a PDF like an HTML document. Images can't "float" within a document and have things flow around them, or flow with surrounding text. FPDF allows you to embed html in a text block, but only because it parses the tags and replaces <i> and <b> and so on with Postscript equivalent commands. It's not smart enough to dynamically place an image.

In other words, you have to specify coordinates (and if you don't, the current location's coordinates will be used anyways).

Global variables in R

What about .GlobalEnv$a <- "new" ? I saw this explicit way of creating a variable in a certain environment here: http://adv-r.had.co.nz/Environments.html. It seems shorter than using the assign() function.

Assign static IP to Docker container

You can access other containers' service by their name(ping apachewill get the ip or curl http://apache would access the http service) And this can be a alternative of a static ip.

Passing a variable to a powershell script via command line

Declare the parameter in test.ps1:

 Param(
                [Parameter(Mandatory=$True,Position=1)]
                [string]$input_dir,
                [Parameter(Mandatory=$True)]
                [string]$output_dir,
                [switch]$force = $false
                )

Run the script from Run OR Windows Task Scheduler:

powershell.exe -command "& C:\FTP_DATA\test.ps1 -input_dir C:\FTP_DATA\IN -output_dir C:\FTP_DATA\OUT"

or,

 powershell.exe -command "& 'C:\FTP DATA\test.ps1' -input_dir 'C:\FTP DATA\IN' -output_dir 'C:\FTP DATA\OUT'"

Function pointer as a member of a C struct

Maybe I am missing something here, but did you allocate any memory for that PString before you accessed it?

PString * initializeString() {
    PString *str;
    str = (PString *) malloc(sizeof(PString));
    str->length = &length;
    return str;
}

Laravel Controller Subfolder routing

For ** Laravel 5 or Laravel 5.1 LTS both **, if you have multiple Controllers in Admin folder, Route::group will be really helpful for you. For example:

Update: Works with Laravel 5.4

My folder Structure:

Http
----Controllers
    ----Api
          ----V1
                 PostsApiController.php
                 CommentsApiController.php
    PostsController.php

PostAPIController:

<?php namespace App\Http\Controllers\Api\V1;

use App\Http\Requests;
use App\Http\Controllers\Controller;   
use Illuminate\Http\Request;

class PostApiController extends Controller {  
...

In My Route.php, I set namespace group to Api\V1 and overall it looks like:

Route::group(
        [           
            'namespace' => 'Api\V1',
            'prefix' => 'v1',
        ], function(){

            Route::get('posts', ['uses'=>'PostsApiController@index']);
            Route::get('posts/{id}', ['uses'=>'PostssAPIController@show']);

    });

For move details to create sub-folder visit this link.

How to order events bound with jQuery

Dowski's method is good if all of your callbacks are always going to be present and you are happy with them being dependant on each other.

If you want the callbacks to be independent of each other, though, you could be to take advantage of bubbling and attach subsequent events as delegates to parent elements. The handlers on a parent elements will be triggered after the handlers on the element, continuing right up to the document. This is quite good as you can use event.stopPropagation(), event.preventDefault(), etc to skip handlers and cancel or un-cancel the action.

$( '#mybutton' ).click( function(e) { 
    // Do stuff first
} );

$( '#mybutton' ).click( function(e) { 
    // Do other stuff first
} );

$( document ).delegate( '#mybutton', 'click', function(e) {
    // Do stuff last
} );

Or, if you don't like this, you could use Nick Leaches bindLast plugin to force an event to be bound last: https://github.com/nickyleach/jQuery.bindLast.

Or, if you are using jQuery 1.5, you could also potentially do something clever with the new Deferred object.

What are good ways to prevent SQL injection?

By using the SqlCommand and its child collection of parameters all the pain of checking for sql injection is taken away from you and will be handled by these classes.

Here is an example, taken from one of the articles above:

private static void UpdateDemographics(Int32 customerID,
    string demoXml, string connectionString)
{
    // Update the demographics for a store, which is stored  
    // in an xml column.  
    string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
        + "WHERE CustomerID = @ID;";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@ID", SqlDbType.Int);
        command.Parameters["@ID"].Value = customerID;

        // Use AddWithValue to assign Demographics. 
        // SQL Server will implicitly convert strings into XML.
        command.Parameters.AddWithValue("@demographics", demoXml);

        try
        {
            connection.Open();
            Int32 rowsAffected = command.ExecuteNonQuery();
            Console.WriteLine("RowsAffected: {0}", rowsAffected);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

How to install MinGW-w64 and MSYS2?

Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).

Anyways, if you're already planning on using MSYS2, there's no need for that installer.

  1. Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).

  2. After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit or MSYS2 32-bit in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).

  3. Install a toolchain

    a) for 32-bit:

    pacman -S mingw-w64-i686-gcc
    

    b) for 64-bit:

    pacman -S mingw-w64-x86_64-gcc
    
  4. install any libraries/tools you may need. You can search the repositories by doing

    pacman -Ss name_of_something_i_want_to_install
    

    e.g.

    pacman -Ss gsl
    

    and install using

    pacman -S package_name_of_something_i_want_to_install
    

    e.g.

    pacman -S mingw-w64-x86_64-gsl
    

    and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!

  5. Open a MinGW-w64 shell:

    a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"

    b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"

  6. Verify that the compiler is working by doing

    gcc -v
    

If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin or <MSYS2 root>/mingw64/bin to your PATH.

JavaScript - Use variable in string match

xxx.match(yyy, 'g').length

ASP.NET - How to write some html in the page? With Response.Write?

You can also use pageMethods in asp.net. So that you can call javascript functions from asp.net functions. E.g.

_x000D_
_x000D_
 [WebMethod]_x000D_
    public static string showTxtbox(string name)_x000D_
    {_x000D_
         return showResult(name);_x000D_
    }_x000D_
      _x000D_
    public static string showResult(string name)_x000D_
    {_x000D_
        Database databaseObj = new Database();_x000D_
        DataTable dtObj = databaseObj.getMatches(name);_x000D_
_x000D_
        string result = "<table  border='1' cellspacing='2' cellpadding='2' >" +_x000D_
                                            "<tr>" +_x000D_
                                                "<td><b>Name</b></td>" +_x000D_
                                                "<td><b>Company Name</b></td>" +_x000D_
                                                "<td><b>Phone</b></td>"+_x000D_
                                             "</tr>";_x000D_
_x000D_
        for (int i = 0; i < dtObj.Rows.Count; i++)_x000D_
        {_x000D_
            result += "<tr> <td><a href=\"javascript:link('" + dtObj.Rows[i][0].ToString().Trim() + "','" +_x000D_
             dtObj.Rows[i][1].ToString().Trim() +"','"+dtObj.Rows[i][2]+ "');\">" + Convert.ToString(dtObj.Rows[i]["name"]) + "</td>" +_x000D_
                "<td>" + Convert.ToString(dtObj.Rows[i]["customerCompany"]) + "</td>" +_x000D_
                "<td>"+Convert.ToString(dtObj.Rows[i]["Phone"])+"</td>"+_x000D_
             "</tr>";_x000D_
        }_x000D_
_x000D_
        result += "</table>";_x000D_
        return result;_x000D_
    }
_x000D_
_x000D_
_x000D_

Here above code is written in .aspx.cs page. Database is another class. In showResult() function I've called javascript's link() function. Result is displayed in the form of table.

How can I get the current stack trace in Java?

I have a utility method that returns a string with the stacktrace:

static String getStackTrace(Throwable t) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw, true);
    t.printStackTrace(pw);
    pw.flush();
    sw.flush();
    return sw.toString();
}

And just logit like...

... 
catch (FileNotFoundException e) {
    logger.config(getStackTrace(e));
}

How to represent empty char in Java Character class

this is how I do it.

char[] myEmptyCharArray = "".toCharArray();

SQL Server error on update command - "A severe error occurred on the current command"

in my case, the method: context.Database.CreateIfNotExists(); called up multiple times before create database and crashed an error A severe error occurred on the current command. The results, if any, should be discarded.

Get The Current Domain Name With Javascript (Not the path, etc.)

I figure it ought to be as simple as this:

url.split("/")[2]

NPM doesn't install module dependencies

Also check that your package name is correctly accepted:

WRONG:

{
    "name":"My Awesome Package"
}


CORRECT

{
    "name": "my-awesome-package-name"
}

How do I get the last character of a string?

The other answers contain a lot of needless text and code. Here are two ways to get the last character of a String:

char

char lastChar = myString.charAt(myString.length() - 1);

String

String lastChar = myString.substring(myString.length() - 1);

Can someone explain how to append an element to an array in C programming?

Short answer is: You don't have any choice other than:

arr[4] = 5;

Max retries exceeded with URL in requests

Just use requests' features:

import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry


session = requests.Session()
retry = Retry(connect=3, backoff_factor=0.5)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)

session.get(url)

This will GET the URL and retry 3 times in case of requests.exceptions.ConnectionError. backoff_factor will help to apply delays between attempts to avoid to fail again in case of periodic request quota.

Take a look at requests.packages.urllib3.util.retry.Retry, it has many options to simplify retries.

Visual studio - getting error "Metadata file 'XYZ' could not be found" after edit continue

The only thing that worked for me was to delete the Solution User Options (.suo) file. Note that, this is a hidden file.

To locate this file, close your Virsual studio and search for .suo from the file explorer within your project.

Delete the .suo file

PS: a new .suo file will be created again when you rebuild your project and hopefully this newly created one wont give you issues.

I hope that helps someone get rid of this anoying error :).

For-loop vs while loop in R

Because 1 is numeric, but not integer (i.e. it's a floating point number), and 1:6000 is numeric and integer.

> print(class(1))
[1] "numeric"
> print(class(1:60000))
[1] "integer"

60000 squared is 3.6 billion, which is NOT representable in signed 32-bit integer, hence you get an overflow error:

> as.integer(60000)*as.integer(60000)
[1] NA
Warning message:
In as.integer(60000) * as.integer(60000) : NAs produced by integer overflow

3.6 billion is easily representable in floating point, however:

> as.single(60000)*as.single(60000)
[1] 3.6e+09

To fix your for code, convert to a floating point representation:

function (N)
{
    for(i in as.single(1:N)) {
        y <- i*i
    }
}

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

getElementsByClassName not working

If you want to do it by ClassName you could do:

<script type="text/javascript">
function hideTd(className){
    var elements;

    if (document.getElementsByClassName)
    {
        elements = document.getElementsByClassName(className);
    }
    else
    {
        var elArray = [];
        var tmp = document.getElementsByTagName(elements);  
        var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
        for ( var i = 0; i < tmp.length; i++ ) {

            if ( regex.test(tmp[i].className) ) {
                elArray.push(tmp[i]);
            }
        }

        elements = elArray;
    }

    for(var i = 0, i < elements.length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>

How can I render HTML from another file in a React component?

If your template.html file is just HTML and not a React component, then you can't require it in the same way you would do with a JS file.

However, if you are using Browserify — there is a transform called stringify which will allow you to require non-js files as strings. Once you have added the transform, you will be able to require HTML files and they will export as though they were just strings.

Once you have required the HTML file, you'll have to inject the HTML string into your component, using the dangerouslySetInnerHTML prop.

var __html = require('./template.html');
var template = { __html: __html };

React.module.exports = React.createClass({
  render: function() {
    return(
      <div dangerouslySetInnerHTML={template} />
    );
  }
});

This goes against a lot of what React is about though. It would be more natural to create your templates as React components with JSX, rather than as regular HTML files.

The JSX syntax makes it trivially easy to express structured data, like HTML, especially when you use stateless function components.

If your template.html file looked something like this

<div class='foo'>
  <h1>Hello</h1>
  <p>Some paragraph text</p>
  <button>Click</button>
</div>

Then you could convert it instead to a JSX file that looked like this.

module.exports = function(props) {
  return (
    <div className='foo'>
      <h1>Hello</h1>
      <p>Some paragraph text</p>
      <button>Click</button>
    </div>
  );
};

Then you can require and use it without needing stringify.

var Template = require('./template');

module.exports = React.createClass({
  render: function() {
    var bar = 'baz';
    return(
      <Template foo={bar}/>
    );
  }
});

It maintains all of the structure of the original file, but leverages the flexibility of React's props model and allows for compile time syntax checking, unlike a regular HTML file.

Making Python loggers output all messages to stdout in addition to log file

For more detailed explanations - great documentation at that link. For example: It's easy, you only need to set up two loggers.

import sys
import logging

logger = logging.getLogger('')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('my_log_info.log')
sh = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('[%(asctime)s] %(levelname)s [%(filename)s.%(funcName)s:%(lineno)d] %(message)s', datefmt='%a, %d %b %Y %H:%M:%S')
fh.setFormatter(formatter)
sh.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(sh)

def hello_logger():
    logger.info("Hello info")
    logger.critical("Hello critical")
    logger.warning("Hello warning")
    logger.debug("Hello debug")

if __name__ == "__main__":
    print(hello_logger())

Output - terminal:

[Mon, 10 Aug 2020 12:44:25] INFO [TestLoger.py.hello_logger:15] Hello info
[Mon, 10 Aug 2020 12:44:25] CRITICAL [TestLoger.py.hello_logger:16] Hello critical
[Mon, 10 Aug 2020 12:44:25] WARNING [TestLoger.py.hello_logger:17] Hello warning
[Mon, 10 Aug 2020 12:44:25] DEBUG [TestLoger.py.hello_logger:18] Hello debug
None

Output - in file:

log in file


UPDATE: color terminal

Package:

pip install colorlog

Code:

import sys
import logging
import colorlog

logger = logging.getLogger('')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('my_log_info.log')
sh = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('[%(asctime)s] %(levelname)s [%(filename)s.%(funcName)s:%(lineno)d] %(message)s', datefmt='%a, %d %b %Y %H:%M:%S')
fh.setFormatter(formatter)
sh.setFormatter(colorlog.ColoredFormatter('%(log_color)s [%(asctime)s] %(levelname)s [%(filename)s.%(funcName)s:%(lineno)d] %(message)s', datefmt='%a, %d %b %Y %H:%M:%S'))
logger.addHandler(fh)
logger.addHandler(sh)

def hello_logger():
    logger.info("Hello info")
    logger.critical("Hello critical")
    logger.warning("Hello warning")
    logger.debug("Hello debug")
    logger.error("Error message")

if __name__ == "__main__":
    hello_logger()

output: enter image description here

Recommendation:

Complete logger configuration from INI file, which also includes setup for stdout and debug.log:

  • handler_file
    • level=WARNING
  • handler_screen
    • level=DEBUG

Understanding PIVOT function in T-SQL

These are the very basic pivot example kindly go through that.

SQL SERVER – PIVOT and UNPIVOT Table Examples

Example from above link for the product table:

SELECT PRODUCT, FRED, KATE
FROM (
SELECT CUST, PRODUCT, QTY
FROM Product) up
 PIVOT (SUM(QTY) FOR CUST IN (FRED, KATE)) AS pvt
ORDER BY PRODUCT

renders:

 PRODUCT FRED  KATE
 --------------------
 BEER     24    12
 MILK      3     1
 SODA   NULL     6
 VEG    NULL     5

Similar examples can be found in the blog post Pivot tables in SQL Server. A simple sample

How can I convert this one line of ActionScript to C#?

There is collection of Func<...> classes - Func that is probably what you are looking for:

 void MyMethod(Func<int> param1 = null) 

This defines method that have parameter param1 with default value null (similar to AS), and a function that returns int. Unlike AS in C# you need to specify type of the function's arguments.

So if you AS usage was

MyMethod(function(intArg, stringArg) { return true; }) 

Than in C# it would require param1 to be of type Func<int, siring, bool> and usage like

MyMethod( (intArg, stringArg) => { return true;} ); 

How to find duplicate records in PostgreSQL

The basic idea will be using a nested query with count aggregation:

select * from yourTable ou
where (select count(*) from yourTable inr
where inr.sid = ou.sid) > 1

You can adjust the where clause in the inner query to narrow the search.


There is another good solution for that mentioned in the comments, (but not everyone reads them):

select Column1, Column2, count(*)
from yourTable
group by Column1, Column2
HAVING count(*) > 1

Or shorter:

SELECT (yourTable.*)::text, count(*)
FROM yourTable
GROUP BY yourTable.*
HAVING count(*) > 1

How to save DataFrame directly to Hive?

Here is PySpark version to create Hive table from parquet file. You may have generated Parquet files using inferred schema and now want to push definition to Hive metastore. You can also push definition to the system like AWS Glue or AWS Athena and not just to Hive metastore. Here I am using spark.sql to push/create permanent table.

   # Location where my parquet files are present.
    df = spark.read.parquet("s3://my-location/data/")
    cols = df.dtypes
    buf = []
    buf.append('CREATE EXTERNAL TABLE test123 (')
    keyanddatatypes =  df.dtypes
    sizeof = len(df.dtypes)
    print ("size----------",sizeof)
    count=1;
    for eachvalue in keyanddatatypes:
        print count,sizeof,eachvalue
        if count == sizeof:
            total = str(eachvalue[0])+str(' ')+str(eachvalue[1])
        else:
            total = str(eachvalue[0]) + str(' ') + str(eachvalue[1]) + str(',')
        buf.append(total)
        count = count + 1

    buf.append(' )')
    buf.append(' STORED as parquet ')
    buf.append("LOCATION")
    buf.append("'")
    buf.append('s3://my-location/data/')
    buf.append("'")
    buf.append("'")
    ##partition by pt
    tabledef = ''.join(buf)

    print "---------print definition ---------"
    print tabledef
    ## create a table using spark.sql. Assuming you are using spark 2.1+
    spark.sql(tabledef);

UTF-8 problems while reading CSV file with fgetcsv

Now I got it working (after removing the header command). I think the problem was that the encoding of the php file was in ISO-8859-1. I set it to UTF-8 without BOM. I thought I already have done that, but perhaps I made an additional undo.

Furthermore, I used SET NAMES 'utf8' for the database. Now it is also correct in the database.

How to pass values across the pages in ASP.net without using Session

You can pass values from one page to another by followings..

Response.Redirect
Cookies
Application Variables
HttpContext

Response.Redirect

SET :

Response.Redirect("Defaultaspx?Name=Pandian");

GET :

string Name = Request.QueryString["Name"];

Cookies

SET :

HttpCookie cookName = new HttpCookie("Name");
cookName.Value = "Pandian"; 

GET :

string name = Request.Cookies["Name"].Value;

Application Variables

SET :

Application["Name"] = "pandian";

GET :

string Name = Application["Name"].ToString();

Refer the full content here : Pass values from one to another

AngularJS sorting rows by table header

Use a third-party JavaScript library. It will give you that and much more. A good example is datatables (if you are also using jQuery): https://datatables.net

Or just order your bound array in $scope.results when the header is clicked.

PowerShell: how to grep command output?

Your problem is that alias emits a stream of AliasInfo objects, rather than a stream of strings. This does what I think you want.

alias | out-string -stream | select-string Alias

or as a function

function grep {
  $input | out-string -stream | select-string $args
}

alias | grep Alias

When you don't handle things that are in the pipeline (like when you just ran 'alias'), the shell knows to use the ToString() method on each object (or use the output formats specified in the ETS info).

How to tell which row number is clicked in a table?

$('tr').click(function(){
 alert( $('tr').index(this) );
});

For first tr, it alerts 0. If you want to alert 1, you can add 1 to index.

How does MySQL CASE work?

I wanted a simple example of the use of case that I could play with, this doesn't even need a table. This returns odd or even depending whether seconds is odd or even

SELECT CASE MOD(SECOND(NOW()),2) WHEN 0 THEN 'odd' WHEN 1 THEN 'even' END;

How can I protect my .NET assemblies from decompilation?

One thing to keep in mind is that you want to do this in a way that makes business sense. To do that, you need to define your goals. So, exactly what are your goals?

Preventing piracy? That goal is not achievable. Even native code can be decompiled or cracked; the multitude of warez available online (even for products like Windows and Photoshop) is proof a determined hacker can always gain access.

If you can't prevent piracy, then how about merely reducing it? This, too, is misguided. It only takes one person cracking your code for it to be available to everyone. You have to be lucky every time. The pirates only have to be lucky once.

I put it to you the goal should be to maximize profits. You appear to believe that stopping piracy is necessary to this endeavor. It is not. Profit is simply revenue minus costs. Stopping piracy increases costs. It takes effort, which means adding cost somewhere in the process, and so reduces that side of the equation. Protecting your product also fails to increase your revenue. I know you look at all those pirates and see all the money you could make if only they would pay your license fees instead, but the reality is this will never happen. There is some hyperbole here, but it generally holds that pirates who are unable to crack your security will either find a similar product they can crack or do without. They will never buy it instead, and therefore they do not represent lost sales.

Additionally, securing your product actually reduces revenue. There are two reasons for this. One is the small percentage of customers who have trouble with your activation or security, and therefore decide not to buy again or ask for their money back. The other is the small percentage of people who actually try a pirated version of software to make sure it works before buying. Limiting the pirated distribution of your product (if you are somehow able to succeed at this) prevents these people from ever trying your product, and so they will never buy it. Moreover, piracy can also help your product spread to a wider audience, thus reaching more people who will be willing to pay for it.

A better strategy is to assume that your product will be pirated, and think about ways to take advantage of the situation. A couple more links on the topic:
How do i prevent my code from being stolen?
Securing a .NET Application

install cx_oracle for python

This worked for me

python -m pip install cx_Oracle --upgrade

For details refer to the oracle quick start guide

https://cx-oracle.readthedocs.io/en/latest/installation.html#quick-start-cx-oracle-installation

How to remove trailing and leading whitespace for user-provided input in a batch file?

I had to create a Function.

Use it as:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION


set "TextString=    Purple Cows are flying in the Air Tonight         "
echo REM ^^Notice there is whitespace at the start and end of the TextString
echo "!TextString!"
CALL:trimWhiteSpace "!TextString!" OutPutString
echo Resulting Trimmed Text: "!OutPutString!"
echo REM ^^Now there should be no White space at the start or end.

Exit /B

Add this to the bottom of your batch file:

:FUNCTIONS
@REM FUNCTIONS AREA
GOTO:EOF
EXIT /B


::TRIM FUNCTIONS AREA::
:: USAGE:
:: trimWhiteSpace "!InputText!" OutputText
:: Remember to use the "! on the input text, but NOT on the Output text.
:: The Following is Wrong: trimWhiteSpace "!InputText!" !OutputText!
:: ^^Because it has a ! around the OutPutText
:: Make Sure to add " around the InputText when running the call.
:: If you don't add the " then it will only accept the first word before a space.
::Example:
::  set "TextString=    Purple Cows are flying in the Air Tonight         "
::  echo REM ^^Notice there is whitespace at the start and end of the TextString
::  echo "!TextString!"
::  CALL:trimWhiteSpace "!TextString!" OutPutString
::  echo Resulting Trimmed Text: "!OutPutString!"
::  echo REM ^^Now there should be no White space at the start or end.

:trimWhiteSpace
set textToTrim=%~1
CALL:trimWhiteSpaceOnTheRight "!textToTrim!" OutPutString
SET textToTrim=!OutPutString!
CALL:trimWhiteSpaceOnTheLeft "!textToTrim!" OutPutString
SET %2=!OutPutString!
GOTO:EOF

:trimWhiteSpaceOnTheRight
set str=%~1
for /l %%a in (1,1,31) do if "!str:~-1!"==" " set str=!str:~0,-1!
SET %2=%str%
GOTO:EOF

:trimWhiteSpaceOnTheLeft
set str=%~1
for /f "tokens=* delims= " %%a in ("%str%") do set str=%%a
SET %2=%str%
GOTO:EOF

And remember you MUST add "SETLOCAL ENABLEDELAYEDEXPANSION" to the top of your batch file or else none of this will work properly.

SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.

Remove Unnamed columns in pandas dataframe

The pandas.DataFrame.dropna function removes missing values (e.g. NaN, NaT).

For example the following code would remove any columns from your dataframe, where all of the elements of that column are missing.

df.dropna(how='all', axis='columns')

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

By default, Tomcat container doesn’t contain any jstl library. To fix it, declares jstl.jar in your Maven pom.xml file if you are working in Maven project or add it to your application's classpath

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
  </dependency>

Read binary file as string in Ruby

You can probably encode the tar file in Base64. Base 64 will give you a pure ASCII representation of the file that you can store in a plain text file. Then you can retrieve the tar file by decoding the text back.

You do something like:

require 'base64'

file_contents = Base64.encode64(tar_file_data)

Have look at the Base64 Rubydocs to get a better idea.

How do I find what Java version Tomcat6 is using?

/usr/local/tomcat6/bin/catalina.sh version

Getting an object array from an Angular service

Take a look at your code :

 getUsers(): Observable<User[]> {
        return Observable.create(observer => {
            this.http.get('http://users.org').map(response => response.json();
        })
    }

and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)

 getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
  }

The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:

   return Observable.create(observer => {
        this.http.get('http://users.org').map(response => response.json()

Try to follow the guide in link that I provided. You should be just fine when you study it carefully.

---EDIT----

First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!

Try to do it like this:

  getUsers(): void {
        this.userService.getUsers()
            .then(users => {
               this.users = users
               console.log('this.users=' + this.users);
            });


    }

See where the console.log(...) is!

Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.

Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.

What is a stored procedure?

Think of a situation like this,

  • You have a database with data.
  • There are a number of different applications needed to access that central database, and in the future some new applications too.
  • If you are going to insert the inline database queries to access the central database, inside each application's code individually, then probably you have to duplicate the same query again and again inside different applications' code.
  • In that kind of a situation, you can use stored procedures (SPs). With stored procedures, you are writing number of common queries (procedures) and store them with the central database.
  • Now the duplication of work will never happen as before and the data access and the maintenance will be done centrally.

NOTE:

  • In the above situation, you may wonder "Why cannot we introduce a central data access server to interact with all the applications? Yes. That will be a possible alternative. But,
  • The main advantage with SPs over that approach is, unlike your data-access-code with inline queries, SPs are pre-compiled statements, so they will execute faster. And communication costs (over networks) will be at a minimum.
  • Opposite to that, SPs will add some more load to the database server. If that would be a concern according to the situation, a centralized data access server with inline queries will be a better choice.

Make an image responsive - the simplest way

Instead of adding CSS to make the image responsive, adding different resolution images w.r.t. different screen resolution would make the application more efficient.

Mobile browsers don't need to have the same high resolution image that the desktop browsers need.

Using SASS it's easy to use different versions of the image for different resolutions using a media query.

Can Flask have optional URL parameters?

Since Flask 0.10 you can`t add multiple routes to one endpoint. But you can add fake endpoint

@user.route('/<userId>')
def show(userId):
   return show_with_username(userId)

@user.route('/<userId>/<username>')
def show_with_username(userId,username=None):
   pass

Java method to swap primitives

AFAIS, no one mentions of atomic reference.

Integer

public void swap(AtomicInteger a, AtomicInteger b){
    a.set(b.getAndSet(a.get()));
}

String

public void swap(AtomicReference<String> a, AtomicReference<String> b){
    a.set(b.getAndSet(a.get()));
}

How do I improve ASP.NET MVC application performance?

A compiled list of possible sources of improvement are below:

General

  • Make use of a profiler to discover memory leaks and performance problems in your application. personally I suggest dotTrace
  • Run your site in Release mode, not Debug mode, when in production, and also during performance profiling. Release mode is much faster. Debug mode can hide performance problems in your own code.

Caching

  • Use CompiledQuery.Compile() recursively avoiding recompilation of your query expressions
  • Cache not-prone-to-change content using OutputCacheAttribute to save unnecessary and action executions
  • Use cookies for frequently accessed non sensitive information
  • Utilize ETags and expiration - Write your custom ActionResult methods if necessary
  • Consider using the RouteName to organize your routes and then use it to generate your links, and try not to use the expression tree based ActionLink method.
  • Consider implementing a route resolution caching strategy
  • Put repetitive code inside your PartialViews, avoid render it xxxx times: if you end up calling the same partial 300 times in the same view, probably there is something wrong with that. Explanation And Benchmarks

Routing

Security

  • Use Forms Authentication, Keep your frequently accessed sensitive data in the authentication ticket

DAL

Load balancing

  • Utilize reverse proxies, to spread the client load across your app instance. (Stack Overflow uses HAProxy (MSDN).

  • Use Asynchronous Controllers to implement actions that depend on external resources processing.

Client side

  • Optimize your client side, use a tool like YSlow for suggestions to improve performance
  • Use AJAX to update components of your UI, avoid a whole page update when possible.
  • Consider implement a pub-sub architecture -i.e. Comet- for content delivery against reload based in timeouts.
  • Move charting and graph generation logic to the client side if possible. Graph generation is a expensive activity. Deferring to the client side your server from an unnecessary burden, and allows you to work with graphs locally without make a new request (i.e. Flex charting, jqbargraph, MoreJqueryCharts).
  • Use CDN's for scripts and media content to improve loading on the client side (i.e. Google CDN)
  • Minify -Compile- your JavaScript in order to improve your script size
  • Keep cookie size small, since cookies are sent to the server on every request.
  • Consider using DNS and Link Prefetching when possible.

Global configuration

  • If you use Razor, add the following code in your global.asax.cs, by default, Asp.Net MVC renders with an aspx engine and a razor engine. This only uses the RazorViewEngine.

    ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine());

  • Add gzip (HTTP compression) and static cache (images, css, ...) in your web.config <system.webServer> <urlCompression doDynamicCompression="true" doStaticCompression="true" dynamicCompressionBeforeCache="true"/> </system.webServer>

  • Remove unused HTTP Modules
  • Flush your HTML as soon as it is generated (in your web.config) and disable viewstate if you are not using it <pages buffer="true" enableViewState="false">

How to find the Git commit that introduced a string in any branch?

While this doesn't directly answer you question, I think it might be a good solution for you in the future. I saw a part of my code, which was bad. Didn't know who wrote it or when. I could see all changes from the file, but it was clear that the code had been moved from some other file to this one. I wanted to find who actually added it in the first place.

To do this, I used Git bisect, which quickly let me find the sinner.

I ran git bisect start and then git bisect bad, because the revision checked out had the issue. Since I didn't know when the problem occured, I targetted the first commit for the "good", git bisect good <initial sha>.

Then I just kept searching the repo for the bad code. When I found it, I ran git bisect bad, and when it wasn't there: git bisect good.

In ~11 steps, I had covered ~1000 commits and found the exact commit, where the issue was introduced. Pretty great.

How do you push a Git tag to a branch using a refspec?

It is probably failing because 1.0.0 is an annotated tag. Perhaps you saw the following error message:

error: Trying to write non-commit object to branch refs/heads/master

Annotated tags have their own distinct type of object that points to the tagged commit object. Branches can not usefully point to tag objects, only commit objects. You need to “peel” the annotated tag back to commit object and push that instead.

git push production +1.0.0^{commit}:master
git push production +1.0.0~0:master          # shorthand

There is another syntax that would also work in this case, but it means something slightly different if the tag object points to something other than a commit (or a tag object that points to (a tag object that points to a …) a commit).

git push production +1.0.0^{}:master

These tag peeling syntaxes are described in git-rev-parse(1) under Specifying Revisions.

How to Git stash pop specific stash in 1.8.3?

If none of the above work, quotation marks around the stash itself might work for you:

git stash pop "stash@{0}"

Is there a way to pass optional parameters to a function?

The Python 2 documentation, 7.6. Function definitions gives you a couple of ways to detect whether a caller supplied an optional parameter.

First, you can use special formal parameter syntax *. If the function definition has a formal parameter preceded by a single *, then Python populates that parameter with any positional parameters that aren't matched by preceding formal parameters (as a tuple). If the function definition has a formal parameter preceded by **, then Python populates that parameter with any keyword parameters that aren't matched by preceding formal parameters (as a dict). The function's implementation can check the contents of these parameters for any "optional parameters" of the sort you want.

For instance, here's a function opt_fun which takes two positional parameters x1 and x2, and looks for another keyword parameter named "optional".

>>> def opt_fun(x1, x2, *positional_parameters, **keyword_parameters):
...     if ('optional' in keyword_parameters):
...         print 'optional parameter found, it is ', keyword_parameters['optional']
...     else:
...         print 'no optional parameter, sorry'
... 
>>> opt_fun(1, 2)
no optional parameter, sorry
>>> opt_fun(1,2, optional="yes")
optional parameter found, it is  yes
>>> opt_fun(1,2, another="yes")
no optional parameter, sorry

Second, you can supply a default parameter value of some value like None which a caller would never use. If the parameter has this default value, you know the caller did not specify the parameter. If the parameter has a non-default value, you know it came from the caller.

How to force a script reload and re-execute?

I know that is to late, but I want to share my answer. What I did it's save de script's tags in a HTML file, locking up the scripts on my Index file in a div with an id, something like this.

<div id="ScriptsReload"><script src="js/script.js"></script></div>

and when I wanted to refresh I just used.

$("#ScriptsReload").load("html_with_scripts_tags.html", "", function(
    response,
    status,
    request
  ) {

  });

How to dynamically add elements to String array?

when using String array, you have to give size of array while initializing

eg

String[] str = new String[10];

you can use index 0-9 to store values

str[0] = "value1"
str[1] = "value2"
str[2] = "value3"
str[3] = "value4"
str[4] = "value5"
str[5] = "value6"
str[6] = "value7"
str[7] = "value8"
str[8] = "value9"
str[9] = "value10"

if you are using ArrayList instread of string array, you can use it without initializing size of array ArrayList str = new ArrayList();

you can add value by using add method of Arraylist

str.add("Value1");

get retrieve a value from arraylist, you can use get method

String s = str.get(0);

find total number of items by size method

int nCount = str.size();

read more from here

How do I keep a label centered in WinForms?

If you don't want to dock label in whole available area, just set SizeChanged event instead of TextChanged. Changing each letter will change the width property of label as well as its text when autosize property set to True. So, by the way you can use any formula to keep label centered in form.

private void lblReport_SizeChanged(object sender, EventArgs e)
{
    lblReport.Left = (this.ClientSize.Width - lblReport.Size.Width) / 2;
}

3-dimensional array in numpy

No need to go in such deep technicalities, and get yourself blasted. Let me explain it in the most easiest way. We all have studied "Sets" during our school-age in Mathematics. Just consider 3D numpy array as the formation of "sets".

x = np.zeros((2,3,4)) 

Simply Means:

2 Sets, 3 Rows per Set, 4 Columns

Example:

Input

x = np.zeros((2,3,4))

Output

Set # 1 ---- [[[ 0.,  0.,  0.,  0.],  ---- Row 1
               [ 0.,  0.,  0.,  0.],  ---- Row 2
               [ 0.,  0.,  0.,  0.]], ---- Row 3 
    
Set # 2 ----  [[ 0.,  0.,  0.,  0.],  ---- Row 1
               [ 0.,  0.,  0.,  0.],  ---- Row 2
               [ 0.,  0.,  0.,  0.]]] ---- Row 3

Explanation: See? we have 2 Sets, 3 Rows per Set, and 4 Columns.

Note: Whenever you see a "Set of numbers" closed in double brackets from both ends. Consider it as a "set". And 3D and 3D+ arrays are always built on these "sets".

VBA array sort function?

I posted some code in answer to a related question on StackOverflow:

Sorting a multidimensionnal array in VBA

The code samples in that thread include:

  1. A vector array Quicksort;
  2. A multi-column array QuickSort;
  3. A BubbleSort.

Alain's optimised Quicksort is very shiny: I just did a basic split-and-recurse, but the code sample above has a 'gating' function that cuts down on redundant comparisons of duplicated values. On the other hand, I code for Excel, and there's a bit more in the way of defensive coding - be warned, you'll need it if your array contains the pernicious 'Empty()' variant, which will break your While... Wend comparison operators and trap your code in an infinite loop.

Note that quicksort algorthms - and any recursive algorithm - can fill the stack and crash Excel. If your array has fewer than 1024 members, I'd use a rudimentary BubbleSort.

Public Sub QuickSortArray(ByRef SortArray As Variant, _
                                Optional lngMin As Long = -1, _ 
                                Optional lngMax As Long = -1, _ 
                                Optional lngColumn As Long = 0)
On Error Resume Next
'Sort a 2-Dimensional array
' Sample Usage: sort arrData by the contents of column 3 ' ' QuickSortArray arrData, , , 3
' 'Posted by Jim Rech 10/20/98 Excel.Programming
'Modifications, Nigel Heffernan:
' ' Escape failed comparison with empty variant ' ' Defensive coding: check inputs
Dim i As Long Dim j As Long Dim varMid As Variant Dim arrRowTemp As Variant Dim lngColTemp As Long

If IsEmpty(SortArray) Then Exit Sub End If
If InStr(TypeName(SortArray), "()") < 1 Then 'IsArray() is somewhat broken: Look for brackets in the type name Exit Sub End If
If lngMin = -1 Then lngMin = LBound(SortArray, 1) End If
If lngMax = -1 Then lngMax = UBound(SortArray, 1) End If
If lngMin >= lngMax Then ' no sorting required Exit Sub End If

i = lngMin j = lngMax
varMid = Empty varMid = SortArray((lngMin + lngMax) \ 2, lngColumn)
' We send 'Empty' and invalid data items to the end of the list: If IsObject(varMid) Then ' note that we don't check isObject(SortArray(n)) - varMid might pick up a valid default member or property i = lngMax j = lngMin ElseIf IsEmpty(varMid) Then i = lngMax j = lngMin ElseIf IsNull(varMid) Then i = lngMax j = lngMin ElseIf varMid = "" Then i = lngMax j = lngMin ElseIf varType(varMid) = vbError Then i = lngMax j = lngMin ElseIf varType(varMid) > 17 Then i = lngMax j = lngMin End If

While i <= j
While SortArray(i, lngColumn) < varMid And i < lngMax i = i + 1 Wend
While varMid < SortArray(j, lngColumn) And j > lngMin j = j - 1 Wend

If i <= j Then
' Swap the rows ReDim arrRowTemp(LBound(SortArray, 2) To UBound(SortArray, 2)) For lngColTemp = LBound(SortArray, 2) To UBound(SortArray, 2) arrRowTemp(lngColTemp) = SortArray(i, lngColTemp) SortArray(i, lngColTemp) = SortArray(j, lngColTemp) SortArray(j, lngColTemp) = arrRowTemp(lngColTemp) Next lngColTemp Erase arrRowTemp
i = i + 1 j = j - 1
End If

Wend
If (lngMin < j) Then Call QuickSortArray(SortArray, lngMin, j, lngColumn) If (i < lngMax) Then Call QuickSortArray(SortArray, i, lngMax, lngColumn)

End Sub

How can I update my ADT in Eclipse?

I had this problem. Since I already had the ADT address I could not follow the suggested fix. The reason why the update was not working in my case is that the ADT address was not checked in the list of "Available updates".

1) Go to eclipse > help > Install new software

2) Click on "Available Software site"

3) Check that you have the ADT address

4) If not add it following the Murtuza Kabul's steps

5) if yes check that the address is checked (checkbox on the left of the address)

I run the update after having launched Eclipse as administrator to be sure that it was not going to have problems accessing the system folders

Static Vs. Dynamic Binding in Java

From Javarevisited blog post:

Here are a few important differences between static and dynamic binding:

  1. Static binding in Java occurs during compile time while dynamic binding occurs during runtime.
  2. private, final and static methods and variables use static binding and are bonded by compiler while virtual methods are bonded during runtime based upon runtime object.
  3. Static binding uses Type (class in Java) information for binding while dynamic binding uses object to resolve binding.
  4. Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.

Here is an example which will help you to understand both static and dynamic binding in Java.

Static Binding Example in Java

public class StaticBindingTest {  
    public static void main(String args[]) {
        Collection c = new HashSet();
        StaticBindingTest et = new StaticBindingTest();
        et.sort(c);
    }
    //overloaded method takes Collection argument
    public Collection sort(Collection c) {
        System.out.println("Inside Collection sort method");
        return c;
    }
    //another overloaded method which takes HashSet argument which is sub class
    public Collection sort(HashSet hs) {
        System.out.println("Inside HashSet sort method");
        return hs;
    }
}

Output: Inside Collection sort method

Example of Dynamic Binding in Java

public class DynamicBindingTest {   
    public static void main(String args[]) {
        Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car
        vehicle.start(); //Car's start called because start() is overridden method
    }
}

class Vehicle {
    public void start() {
        System.out.println("Inside start method of Vehicle");
    }
}

class Car extends Vehicle {
    @Override
    public void start() {
        System.out.println("Inside start method of Car");
    }
}

Output: Inside start method of Car

jQuery check if attr = value

Just remove the .val(). Like:

if ( $('html').attr('lang') == 'fr-FR' ) {
    // do this
} else {
    // do that
}

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

/**
 * If $header is an array of headers
 * It will format and return the correct $header
 * $header = [
 *  'Accept' => 'application/json',
 *  'Content-Type' => 'application/x-www-form-urlencoded'
 * ];
 */
$i_header = $header;
if(is_array($i_header) === true){
    $header = [];
    foreach ($i_header as $param => $value) {
        $header[] = "$param: $value";
    }
}

How can I build XML in C#?

For simple things, I just use the XmlDocument/XmlNode/XmlAttribute classes and XmlDocument DOM found in System.XML.

It generates the XML for me, I just need to link a few items together.

However, on larger things, I use XML serialization.

Vagrant ssh authentication failure

Between all of the responses here, there are lots of good things to try. For completeness, if you

ssh vagrant@localhost -p 2222

as @Bizmate suggests, and it fails, be sure you have

AllowUsers vagrant

in the /etc/ssh/sshd_config of your guest/vagrant machine.

HTML checkbox - allow to check only one checkbox

The unique name identifier applies to radio buttons:

<input type="radio" />

change your checkboxes to radio and everything should be working

Run Function After Delay

You can add timeout function in jQuery (Show alert after 3 seconds):

$(document).ready(function($) {
    setTimeout(function() {
     alert("Hello");
    }, 3000);
});

Is there an operator to calculate percentage in Python?

use of %

def percent(expression):
    if "%" in expression:
        expression = expression.replace("%","/100")
    return eval(expression)

>>> percent("1500*20%")
300.0

Somthing simple

>>> p = lambda x: x/100
>>> p(20)
0.2
>>> 100*p(20)
20.0
>>>

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

In my case ; what solved my issue was.....

You may had json like this, the keys without " double quotations....

{ name: "test", phone: "2324234" }

So try any online Json Validator to make sure you have right syntax...

Json Validator Online

Check Whether a User Exists

There's no need to check the exit code explicitly. Try

if getent passwd $1 > /dev/null 2>&1; then
    echo "yes the user exists"
else
    echo "No, the user does not exist"
fi

If that doesn't work, there is something wrong with your getent, or you have more users defined than you think.

Writing an mp4 video using python opencv

For someone whoe still struggle with the problem. According this article I used this sample and it works for me:

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'X264')
out = cv2.VideoWriter('output.mp4',fourcc, 20.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,0)

        # write the flipped frame
        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

So I had to use cv2.VideoWriter_fourcc(*'X264') codec. Tested with OpenCV 3.4.3 compiled from sources.

How to parse a CSV in a Bash script?

A sed or awk solution would probably be shorter, but here's one for Perl:

perl -F/,/ -ane 'print if $F[<INDEX>] eq "<VALUE>"`

where <INDEX> is 0-based (0 for first column, 1 for 2nd column, etc.)

Asynchronous vs synchronous execution, what does it really mean?

Simply said asynchronous execution is doing stuff in the background.

For example if you want to download a file from the internet you might use a synchronous function to do that but it will block your thread until the file finished downloading. This can make your application unresponsive to any user input.

Instead you could download the file in the background using asynchronous method. In this case the download function returns immediately and program execution continues normally. All the download operations are done in the background and your program will be notified when it's finished.

How to insert strings containing slashes with sed?

A simplier alternative is using AWK as on this answer:

awk '$0="prefix"$0' file > new_file

How to remove multiple deleted files in Git repository

The built in clean function can also be helpful...

git clean -fd

What do multiple arrow functions mean in javascript?

That is a curried function

First, examine this function with two parameters …

const add = (x, y) => x + y
add(2, 3) //=> 5

Here it is again in curried form …

const add = x => y => x + y

Here is the same1 code without arrow functions …

const add = function (x) {
  return function (y) {
    return x + y
  }
}

Focus on return

It might help to visualize it another way. We know that arrow functions work like this – let's pay particular attention to the return value.

const f = someParam => returnValue

So our add function returns a function – we can use parentheses for added clarity. The bolded text is the return value of our function add

const add = x => (y => x + y)

In other words add of some number returns a function

add(2) // returns (y => 2 + y)

Calling curried functions

So in order to use our curried function, we have to call it a bit differently …

add(2)(3)  // returns 5

This is because the first (outer) function call returns a second (inner) function. Only after we call the second function do we actually get the result. This is more evident if we separate the calls on two lines …

const add2 = add(2) // returns function(y) { return 2 + y }
add2(3)             // returns 5

Applying our new understanding to your code

related: ”What’s the difference between binding, partial application, and currying?”

OK, now that we understand how that works, let's look at your code

handleChange = field => e => {
  e.preventDefault()
  /// Do something here
}

We'll start by representing it without using arrow functions …

handleChange = function(field) {
  return function(e) {
    e.preventDefault()
    // Do something here
    // return ...
  };
};

However, because arrow functions lexically bind this, it would actually look more like this …

handleChange = function(field) {
  return function(e) {
    e.preventDefault()
    // Do something here
    // return ...
  }.bind(this)
}.bind(this)

Maybe now we can see what this is doing more clearly. The handleChange function is creating a function for a specified field. This is a handy React technique because you're required to setup your own listeners on each input in order to update your applications state. By using the handleChange function, we can eliminate all the duplicated code that would result in setting up change listeners for each field. Cool!

1 Here I did not have to lexically bind this because the original add function does not use any context, so it is not important to preserve it in this case.


Even more arrows

More than two arrow functions can be sequenced, if necessary -

const three = a => b => c =>
  a + b + c

const four = a => b => c => d =>
  a + b + c + d

three (1) (2) (3) // 6

four (1) (2) (3) (4) // 10

Curried functions are capable of surprising things. Below we see $ defined as a curried function with two parameters, yet at the call site, it appears as though we can supply any number of arguments. Currying is the abstraction of arity -

_x000D_
_x000D_
const $ = x => k =>_x000D_
  $ (k (x))_x000D_
  _x000D_
const add = x => y =>_x000D_
  x + y_x000D_
_x000D_
const mult = x => y =>_x000D_
  x * y_x000D_
  _x000D_
$ (1)           // 1_x000D_
  (add (2))     // + 2 = 3_x000D_
  (mult (6))    // * 6 = 18_x000D_
  (console.log) // 18_x000D_
  _x000D_
$ (7)            // 7_x000D_
  (add (1))      // + 1 = 8_x000D_
  (mult (8))     // * 8 = 64_x000D_
  (mult (2))     // * 2 = 128_x000D_
  (mult (2))     // * 2 = 256_x000D_
  (console.log)  // 256
_x000D_
_x000D_
_x000D_

Partial application

Partial application is a related concept. It allows us to partially apply functions, similar to currying, except the function does not have to be defined in curried form -

const partial = (f, ...a) => (...b) =>
  f (...a, ...b)

const add3 = (x, y, z) =>
  x + y + z

partial (add3) (1, 2, 3)   // 6

partial (add3, 1) (2, 3)   // 6

partial (add3, 1, 2) (3)   // 6

partial (add3, 1, 2, 3) () // 6

partial (add3, 1, 1, 1, 1) (1, 1, 1, 1, 1) // 3

Here's a working demo of partial you can play with in your own browser -

_x000D_
_x000D_
const partial = (f, ...a) => (...b) =>_x000D_
  f (...a, ...b)_x000D_
  _x000D_
const preventDefault = (f, event) =>_x000D_
  ( event .preventDefault ()_x000D_
  , f (event)_x000D_
  )_x000D_
  _x000D_
const logKeypress = event =>_x000D_
  console .log (event.which)_x000D_
  _x000D_
document_x000D_
  .querySelector ('input[name=foo]')_x000D_
  .addEventListener ('keydown', partial (preventDefault, logKeypress))
_x000D_
<input name="foo" placeholder="type here to see ascii codes" size="50">
_x000D_
_x000D_
_x000D_

Scala: join an iterable of strings

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

How can I convert a stack trace to a string?

private String getCurrentStackTraceString() {
    StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
    return Arrays.stream(stackTrace).map(StackTraceElement::toString)
            .collect(Collectors.joining("\n"));
}

How to check String in response body with mockMvc

@Sotirios Delimanolis answer do the job however I was looking for comparing strings within this mockMvc assertion

So here it is

.andExpect(content().string("\"Username already taken - please try with different username\""));

Of course my assertion fail:

java.lang.AssertionError: Response content expected:
<"Username already taken - please try with different username"> but was:<"Something gone wrong">

because:

  MockHttpServletResponse:
            Body = "Something gone wrong"

So this is proof that it works!

How do I split an int into its digits?

I don't necessarily recommend this (it's more efficient to work with the number rather than converting it to a string), but it's easy and it works :)

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>

#include <boost/lexical_cast.hpp>

int main()
{
    int n = 23984;
    std::string s = boost::lexical_cast<std::string>(n);
    std::copy(s.begin(), s.end(), std::ostream_iterator<char>(std::cout, "\n"));
    return 0;
}

Send JavaScript variable to PHP variable

PHP runs on the server and Javascript runs on the client, so you can't set a PHP variable to equal a Javascript variable without sending the value to the server. You can, however, set a Javascript variable to equal a PHP variable:

<script type="text/javascript">
  var foo = '<?php echo $foo ?>';
</script>

To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):

var variableToSend = 'foo';
$.post('file.php', {variable: variableToSend});

On your server, you would need to receive the variable sent in the post:

$variable = $_POST['variable'];

How to Ignore "Duplicate Key" error in T-SQL (SQL Server)

If by "Ignore Duplicate Error statments", to abort the current statement and continue to the next statement without aborting the trnsaction then just put BEGIN TRY.. END TRY around each statement:

BEGIN TRY
    INSERT ...
END TRY
BEGIN CATCH /*required, but you dont have to do anything */ END CATCH
...

Safe navigation operator (?.) or (!.) and null property paths

Since TypeScript 3.7 was released you can use optional chaining now.

Property example:

let x = foo?.bar.baz();

This is equvalent to:

let x = (foo === null || foo === undefined) ?
    undefined :
    foo.bar.baz();

Moreover you can call:

Optional Call

function(otherFn: (par: string) => void) {
   otherFn?.("some value");
}

otherFn will be called only if otherFn won't be equal to null or undefined

Usage optional chaining in IF statement

This:

if (someObj && someObj.someProperty) {
    // ...
}

can be replaced now with this

if (someObj?.someProperty) {
    // ...
}

Ref. https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html

How to quickly form groups (quartiles, deciles, etc) by ordering column(s) in a data frame

temp$quartile <- ceiling(sapply(temp$value,function(x) sum(x-temp$value>=0))/(length(temp$value)/4))

Making WPF applications look Metro-styled, even in Windows 7? (Window Chrome / Theming / Theme)

If you are willing to pay I strongly recommend you Telerik Components for WPF. They offer great styles/themes and there have specific themes for both, Office 2013 and Windows 8 (EDIT: and also a Visual Studio 2013 themed style). However there offering much more than just styles in fact you will get a whole bunch of controls which are really useful.

Here is how it looks in action (Screenshots taken from telerik samples):

Telerik Dashboard Sample

Telerik CRM Dashboard Sample

Here are the links to the telerik executive dashboard sample (first screenshot) and here for the CRM Dashboard (second screenshot).

They offer a 30 day trial, just give it a shot!

How best to read a File into List<string>

List<string> lines = new List<string>();
 using (var sr = new StreamReader("file.txt"))
 {
      while (sr.Peek() >= 0)
          lines.Add(sr.ReadLine());
 }

i would suggest this... of Groo's answer.

Javascript - remove an array item by value

Here are some helper functions I use:

Array.contains = function (arr, key) {
    for (var i = arr.length; i--;) {
        if (arr[i] === key) return true;
    }
    return false;
};

Array.add = function (arr, key, value) {
    for (var i = arr.length; i--;) {
        if (arr[i] === key) return arr[key] = value;
    }
    this.push(key);
};

Array.remove = function (arr, key) {
    for (var i = arr.length; i--;) {
        if (arr[i] === key) return arr.splice(i, 1);
    }
};

Can I nest a <button> element inside an <a> using HTML5?

It would be really weird if that was valid, and I would expect it to be invalid. What should it mean to have one clickable element inside of another clickable element? Which is it -- a button, or a link?

How does Google reCAPTCHA v2 work behind the scenes?

This is speculation, but based on Google's reference to the "risk analysis engine" they use (http://googleonlinesecurity.blogspot.com/2014/12/are-you-robot-introducing-no-captcha.html)

I would assume it looks at how you behaved prior to clicking, how your cursor moved on its way to the check (organic path/acceleration), which part of the checkbox was clicked (random places, or dead on center every time), browser fingerprint, Google cookies & contents, click location history tied to your fingerprint or account if it detects one etc.

It's fairly difficult to fake "organic" behavior in such a way that it would fool a continuously learning pattern detection engine. In the cases where it's not sure, it still prompts you to match an actual CAPTCHA string.

How can I reorder a list?

>>> a=["a","b","c","d","e"]
>>> a[0],a[3] = a[3],a[0]
>>> a
['d', 'b', 'c', 'a', 'e']

Find files containing a given text

find them and grep for the string:

This will find all files of your 3 types in /starting/path and grep for the regular expression '(document\.cookie|setcookie)'. Split over 2 lines with the backslash just for readability...

find /starting/path -type f -name "*.php" -o -name "*.html" -o -name "*.js" | \
 xargs egrep -i '(document\.cookie|setcookie)'

How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?

Copy the diff file to the root of your repository, and then do:

git apply yourcoworkers.diff

More information about the apply command is available on its man page.

By the way: A better way to exchange whole commits by file is the combination of the commands git format-patch on the sender and then git am on the receiver, because it also transfers the authorship info and the commit message.

If the patch application fails and if the commits the diff was generated from are actually in your repo, you can use the -3 option of apply that tries to merge in the changes.

It also works with Unix pipe as follows:

git diff d892531 815a3b5 | git apply

Name attribute in @Entity and @Table

@Entity(name = "someThing") => this name will be used to identify the domain ..this name will only be identified by hql queries ..ie ..name of the domain object

@Table(name = "someThing") => this name will be used to which table referred by domain object..ie ..name of the table

How do I remove a library from the arduino environment?

In Elegoo Super Starter Kit, Part 2, Lesson 2.12, IR Receiver Module, I hit the problem that the lesson's IRremote library has a hard conflict with the built-in Arduino RobotIRremote library. I am using the Win10 IDE App, and it was non-trivial to "move the RobotIRremote" folder like the pre-Win10 instructions said. The built-in Libraries are saved at a path like: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries You won't be able to see WindowsApps unless you show hidden files, and you can't do anything in that folder structure until you are the owner. Carefully follow these directions to make that happen: https://www.youtube.com/watch?v=PmrOzBDZTzw
After hours of frustration, the process above finally resulted in success for me. Elegoo gets an F+ for modern instructions on this lesson.

How do I programmatically determine operating system in Java?

Below code shows the values that you can get from System API, these all things you can get through this API.

public class App {
    public static void main( String[] args ) {
        //Operating system name
        System.out.println(System.getProperty("os.name"));

        //Operating system version
        System.out.println(System.getProperty("os.version"));

        //Path separator character used in java.class.path
        System.out.println(System.getProperty("path.separator"));

        //User working directory
        System.out.println(System.getProperty("user.dir"));

        //User home directory
        System.out.println(System.getProperty("user.home"));

        //User account name
        System.out.println(System.getProperty("user.name"));

        //Operating system architecture
        System.out.println(System.getProperty("os.arch"));

        //Sequence used by operating system to separate lines in text files
        System.out.println(System.getProperty("line.separator"));

        System.out.println(System.getProperty("java.version")); //JRE version number

        System.out.println(System.getProperty("java.vendor.url")); //JRE vendor URL

        System.out.println(System.getProperty("java.vendor")); //JRE vendor name

        System.out.println(System.getProperty("java.home")); //Installation directory for Java Runtime Environment (JRE)

        System.out.println(System.getProperty("java.class.path"));

        System.out.println(System.getProperty("file.separator"));
    }
}

Answers:-

Windows 7
6.1
;
C:\Users\user\Documents\workspace-eclipse\JavaExample
C:\Users\user
user
amd64


1.7.0_71
http://java.oracle.com/
Oracle Corporation
C:\Program Files\Java\jre7
C:\Users\user\Documents\workspace-Eclipse\JavaExample\target\classes
\

Number of elements in a javascript object

AFAIK, there is no way to do this reliably, unless you switch to an array. Which honestly, doesn't seem strange - it's seems pretty straight forward to me that arrays are countable, and objects aren't.

Probably the closest you'll get is something like this

// Monkey patching on purpose to make a point
Object.prototype.length = function()
{
  var i = 0;
  for ( var p in this ) i++;
  return i;
}

alert( {foo:"bar", bar: "baz"}.length() ); // alerts 3

But this creates problems, or at least questions. All user-created properties are counted, including the _length function itself! And while in this simple example you could avoid it by just using a normal function, that doesn't mean you can stop other scripts from doing this. so what do you do? Ignore function properties?

Object.prototype.length = function()
{
  var i = 0;
  for ( var p in this )
  {
      if ( 'function' == typeof this[p] ) continue;
      i++;
  }
  return i;
}

alert( {foo:"bar", bar: "baz"}.length() ); // alerts 2

In the end, I think you should probably ditch the idea of making your objects countable and figure out another way to do whatever it is you're doing.

How can I count the number of characters in a Bash variable

jcomeau@intrepid:~$ mystring="one two three four five"
jcomeau@intrepid:~$ echo "string length: ${#mystring}"
string length: 23

link Couting characters, words, lenght of the words and total lenght in a sentence

Using C++ base class constructors?

You'll need to declare constructors in each of the derived classes, and then call the base class constructor from the initializer list:

class D : public A
{
public:
    D(const string &val) : A(0) {}
    D( int val ) : A( val ) {}
};

D variable1( "Hello" );
D variable2( 10 );

C++11 allows you to use the using A::A syntax you use in your decleration of D, but C++11 features aren't supported by all compilers just now, so best to stick with the older C++ methods until this feature is implemented in all the compilers your code will be used with.

How can I delete an item from an array in VB.NET?

You can't. I would suggest that you put the array elements into a List, at least then you can remove items. An array can be extended, for example using ReDim but you cannot remove array elements once they have been created. You would have to rebuild the array from scratch to do that.

If you can avoid it, don't use arrays here, use a List.

How do I set up Vim autoindentation properly for editing Python files?

Combining the solutions proposed by Daren and Thanos we have a good .vimrc file.

_x000D_
_x000D_
-----_x000D_
" configure expanding of tabs for various file types_x000D_
au BufRead,BufNewFile *.py set expandtab_x000D_
au BufRead,BufNewFile *.c set noexpandtab_x000D_
au BufRead,BufNewFile *.h set noexpandtab_x000D_
au BufRead,BufNewFile Makefile* set noexpandtab_x000D_
_x000D_
" --------------------------------------------------------------------------------_x000D_
" configure editor with tabs and nice stuff..._x000D_
" --------------------------------------------------------------------------------_x000D_
set expandtab           " enter spaces when tab is pressed_x000D_
set textwidth=120       " break lines when line length increases_x000D_
set tabstop=4           " use 4 spaces to represent tab_x000D_
set softtabstop=4_x000D_
set shiftwidth=4        " number of spaces to use for auto indent_x000D_
set autoindent          " copy indent from current line when starting a new line_x000D_
set smartindent_x000D_
set smarttab_x000D_
set expandtab_x000D_
set number_x000D_
_x000D_
" make backspaces more powerfull_x000D_
set backspace=indent,eol,start_x000D_
_x000D_
set ruler                           " show line and column number_x000D_
syntax on               " syntax highlighting_x000D_
set showcmd             " show (partial) command in status line
_x000D_
_x000D_
_x000D_

how much memory can be accessed by a 32 bit machine?

basically 32bit architecture can address 4GB as you expected. There are some techniques which allows processor to address more data like AWE or PAE.

Generic Interface

I'd stay with two different interfaces.

You said that 'I want to group my service executors under a common interface... It also seems overkill creating two separate interfaces for the two different service calls... A class will only implement one of these interfaces'

It's not clear what is the reason to have a single interface then. If you want to use it as a marker, you can just exploit annotations instead.

Another point is that there is a possible case that your requirements change and method(s) with another signature appears at the interface. Of course it's possible to use Adapter pattern then but it would be rather strange to see that particular class implements interface with, say, three methods where two of them trow UnsupportedOperationException. It's possible that the forth method appears etc.

Reverse Contents in Array

I would try to using pointers to solve this problem:

#include <iostream>

void displayArray(int table[], int size);

void rev(int table[], int size);


int main(int argc, char** argv) {

    int a[10] = { 1,2,3,4,5,6,7,8,9,10 };

    rev(a, 10);
    displayArray(a, 10);

    return 0;
}

void displayArray(int table[], int size) {
    for (int i = 0; i < size; i++) {
        std::cout << table[i] << " ";
    }
    std::cout << std::endl;
}

void rev(int table[], int size) {

    int *start = table;
    int *end = table + (size - 1);

    for (int i = 0; i < size; i++) {

        if (start < end) {
            int temp = *end;
            *end = *start;
            *start = temp;
        }

        start++;
        end--;
    }
}

Formatting DataBinder.Eval data

Why not use the simpler syntax?

<asp:Label id="lblNewsDate" runat="server" Text='<%# Eval("publishedDate", "{0:dddd d MMMM}") %>'</label>

This is the template control "Eval" that takes in the expression and the string format:

protected internal string Eval(
string expression,
string format

)

http://msdn.microsoft.com/en-us/library/3d2sz789.aspx

How do I decode a string with escaped unicode?

I don't have enough rep to put this under comments to the existing answers:

unescape is only deprecated for working with URIs (or any encoded utf-8) which is probably the case for most people's needs. encodeURIComponent converts a js string to escaped UTF-8 and decodeURIComponent only works on escaped UTF-8 bytes. It throws an error for something like decodeURIComponent('%a9'); // error because extended ascii isn't valid utf-8 (even though that's still a unicode value), whereas unescape('%a9'); // © So you need to know your data when using decodeURIComponent.

decodeURIComponent won't work on "%C2" or any lone byte over 0x7f because in utf-8 that indicates part of a surrogate. However decodeURIComponent("%C2%A9") //gives you © Unescape wouldn't work properly on that // © AND it wouldn't throw an error, so unescape can lead to buggy code if you don't know your data.

Usage of MySQL's "IF EXISTS"

You cannot use IF control block OUTSIDE of functions. So that affects both of your queries.

Turn the EXISTS clause into a subquery instead within an IF function

SELECT IF( EXISTS(
             SELECT *
             FROM gdata_calendars
             WHERE `group` =  ? AND id = ?), 1, 0)

In fact, booleans are returned as 1 or 0

SELECT EXISTS(
         SELECT *
         FROM gdata_calendars
         WHERE `group` =  ? AND id = ?)

How to submit a form using PhantomJS

Sending raw POST requests can be sometimes more convenient. Below you can see post.js original example from PhantomJS

// Example using HTTP POST operation

var page = require('webpage').create(),
    server = 'http://posttestserver.com/post.php?dump',
    data = 'universe=expanding&answer=42';

page.open(server, 'post', data, function (status) {
    if (status !== 'success') {
        console.log('Unable to post!');
    } else {
        console.log(page.content);
    }
    phantom.exit();
});

What is the size of ActionBar in pixels?

If you're using the compatibility ActionBar from the recent v7 appcompat support package, you can get the height using

@dimen/abc_action_bar_default_height

Documentation

Simplest way to throw an error/exception with a custom message in Swift 2?

I like @Alexander-Borisenko's answer, but the localized description was not returned when caught as an Error. It seems that you need to use LocalizedError instead:

struct RuntimeError: LocalizedError
{
    let message: String

    init(_ message: String)
    {
        self.message = message
    }

    public var errorDescription: String?
    {
        return message
    }
}

See this answer for more details.

Java FileOutputStream Create File if not exists

new FileOutputStream(f) will create a file in most cases, but unfortunately you will get a FileNotFoundException

if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason

from Javadoc

I other word there might be plenty of cases where you would get FileNotFoundException meaning "Could not create your file", but you would not be able to find the reason of why the file creation failed.

A solution is to remove any call to the File API and use the Files API instead as it provides much better error handling. Typically replace any new FileOutputStream(f) with Files.newOutputStream(p).

In cases where you do need to use the File API (because you use an external interface using File for example), using Files.createFile(p) is a good way to make sure your file is created properly and if not you would know why it didn't work. Some people commented above that this is redundant. It is true, but you get better error handling which might be necessary in some cases.

What exactly is Apache Camel?

In short:

When there is a requirement to connect / integrate systems, you will probably need to connect to some data source and then process this data to match your business requirements.

In order to do that:

1) You could develop custom program that would do it (might be time consuming and hard to understand, maintain for other developer)

2) Alternatively, you could use Apache Camel to do it in standardised way (it has most of the connectors already developed for you, you just need to set it up and plug your logic - called Process):

Camel will help you to:

  1. Consume data from any source/format
  2. Process this data
  3. Output data to any source/format

By using Apache Camel you will make it easy to understand / maintain / extend your system to another developer.

Apache Camel is developed with Enterprise Integration Patterns. The patterns help you to integrate systems in a good way :-)

Sqlite or MySql? How to decide?

My few cents to previous excellent replies. the site www.sqlite.org works on a sqlite database. Here is the link when the author (Richard Hipp) replies to a similar question.

How can I create a "Please Wait, Loading..." animation using jQuery?

If you are using Turbolinks With Rails this is my solution:

This is the CoffeeScript

$(window).on 'page:fetch', ->
  $('body').append("<div class='modal'></div>")
  $('body').addClass("loading")

$(window).on 'page:change', ->
  $('body').removeClass("loading")

This is the SASS CSS based on the first excellent answer from Jonathan Sampson

# loader.css.scss

.modal {
    display:    none;
    position:   fixed;
    z-index:    1000;
    top:        0;
    left:       0;
    height:     100%;
    width:      100%;
    background: rgba( 255, 255, 255, 0.4)
            asset-url('ajax-loader.gif', image)
            50% 50% 
            no-repeat;
}
body.loading {
    overflow: hidden;   
}

body.loading .modal {
    display: block;
}

Path of currently executing powershell script

Split-Path $MyInvocation.MyCommand.Path -Parent

How can I enter latitude and longitude in Google Maps?

You don't need to convert to decimal; you can also enter 46 23S, 115 22E. You can add seconds after the minutes, also separated by a space.

How to find foreign key dependencies in SQL Server?

You can Use INFORMATION_SCHEMA.KEY_COLUMN_USAGE and sys.foreign_key_columns in order to get the foreign key metadata for a table i.e. Constraint name, Reference table and Reference column etc.

Below is the query:

SELECT  CONSTRAINT_NAME, COLUMN_NAME, ParentTableName, RefTableName,RefColName FROM 
    (SELECT CONSTRAINT_NAME,COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = '<tableName>') constraint_details
    INNER JOIN  
    (SELECT ParentTableName, RefTableName,name ,COL_NAME(fc.referenced_object_id,fc.referenced_column_id) RefColName  FROM (SELECT object_name(parent_object_id) ParentTableName,object_name(referenced_object_id) RefTableName,name,OBJECT_ID  FROM sys.foreign_keys WHERE parent_object_id = object_id('<tableName>') ) f 
    INNER JOIN   
    sys.foreign_key_columns AS fc  ON  f.OBJECT_ID = fc.constraint_object_id ) foreign_key_detail 
    on foreign_key_detail.name = constraint_details.CONSTRAINT_NAME

Inserting the same value multiple times when formatting a string

incoming = 'arbit'
result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming}

You may like to have a read of this to get an understanding: String Formatting Operations.

Best way to do multi-row insert in Oracle?

This works in Oracle:

insert into pager (PAG_ID,PAG_PARENT,PAG_NAME,PAG_ACTIVE)
          select 8000,0,'Multi 8000',1 from dual
union all select 8001,0,'Multi 8001',1 from dual

The thing to remember here is to use the from dual statement.

How to revert a merge commit that's already pushed to remote branch?

I found good explanation for How To Revert The Merge from this link and I copy pasted the explanation below and it would be helpful just in case if below link doesn't work.

How to revert a faulty merge Alan([email protected]) said:

I have a master branch. We have a branch off of that that some developers are doing work on. They claim it is ready. We merge it into the master branch. It breaks something so we revert the merge. They make changes to the code. they get it to a point where they say it is ok and we merge again. When examined, we find that code changes made before the revert are not in the master branch, but code changes after are in the master branch. and asked for help recovering from this situation.

The history immediately after the "revert of the merge" would look like this:

---o---o---o---M---x---x---W
              /
      ---A---B

where A and B are on the side development that was not so good, M is the merge that brings these premature changes into the mainline, x are changes unrelated to what the side branch did and already made on the mainline, and W is the "revert of the merge M" (doesn’t W look M upside down?). IOW, "diff W^..W" is similar to "diff -R M^..M".

Such a "revert" of a merge can be made with:

$ git revert -m 1 M After the developers of the side branch fix their mistakes, the history may look like this:

---o---o---o---M---x---x---W---x
              /
      ---A---B-------------------C---D

where C and D are to fix what was broken in A and B, and you may already have some other changes on the mainline after W.

If you merge the updated side branch (with D at its tip), none of the changes made in A or B will be in the result, because they were reverted by W. That is what Alan saw.

Linus explains the situation:

Reverting a regular commit just effectively undoes what that commit did, and is fairly straightforward. But reverting a merge commit also undoes the data that the commit changed, but it does absolutely nothing to the effects on history that the merge had. So the merge will still exist, and it will still be seen as joining the two branches together, and future merges will see that merge as the last shared state - and the revert that reverted the merge brought in will not affect that at all. So a "revert" undoes the data changes, but it's very much not an "undo" in the sense that it doesn't undo the effects of a commit on the repository history. So if you think of "revert" as "undo", then you're going to always miss this part of reverts. Yes, it undoes the data, but no, it doesn't undo history. In such a situation, you would want to first revert the previous revert, which would make the history look like this:

---o---o---o---M---x---x---W---x---Y
              /
      ---A---B-------------------C---D

where Y is the revert of W. Such a "revert of the revert" can be done with:

$ git revert W This history would (ignoring possible conflicts between what W and W..Y changed) be equivalent to not having W or Y at all in the history:

---o---o---o---M---x---x-------x----
              /
      ---A---B-------------------C---D

and merging the side branch again will not have conflict arising from an earlier revert and revert of the revert.

---o---o---o---M---x---x-------x-------*
              /                       /
      ---A---B-------------------C---D

Of course the changes made in C and D still can conflict with what was done by any of the x, but that is just a normal merge conflict.

Hive ParseException - cannot recognize input near 'end' 'string'

I was using /Date=20161003 in the folder path while doing an insert overwrite and it was failing. I changed it to /Dt=20161003 and it worked

Code for printf function in C

Here's the GNU version of printf... you can see it passing in stdout to vfprintf:

__printf (const char *format, ...)
{
   va_list arg;
   int done;

   va_start (arg, format);
   done = vfprintf (stdout, format, arg);
   va_end (arg);

   return done;
}

See here.

Here's a link to vfprintf... all the formatting 'magic' happens here.

The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)

PHP cURL, extract an XML response

<?php
function download_page($path){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$path);
    curl_setopt($ch, CURLOPT_FAILONERROR,1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $retValue = curl_exec($ch);          
    curl_close($ch);
    return $retValue;
}

$sXML = download_page('http://alanstorm.com/atom');
$oXML = new SimpleXMLElement($sXML);

foreach($oXML->entry as $oEntry){
    echo $oEntry->title . "\n";
}

runOnUiThread in fragment

In Xamarin.Android

For Fragment:

this.Activity.RunOnUiThread(() => { yourtextbox.Text="Hello"; });

For Activity:

RunOnUiThread(() => { yourtextbox.Text="Hello"; });

Happy coding :-)

How to output oracle sql result into a file in windows?

spool "D:\test\test.txt"

select  
  a.ename  
from  
  employee a  
inner join department b  
on  
(  
  a.dept_id = b.dept_id  
)  
;  
spool off  

This query will spool the sql result in D:\test\test.txt

SQL grammar for SELECT MIN(DATE)

An aggregate function requires a GROUP BY in standard SQL

This is "Get minimum date per title" in plain language

SELECT title, MIN(date) FROM table GROUP BY title

Most RDBMS and the standard require that column is either in the GROUP BY or in a functions (MIN, COUNT etc): MySQL is the notable exception with some extensions that give unpredictable behaviour

Java : Accessing a class within a package, which is the better way?

As already said, on runtime there is no difference (in the class file it is always fully qualified, and after loading and linking the class there are direct pointers to the referred method), and everything in the java.lang package is automatically imported, as is everything in the current package.

The compiler might have to search some microseconds longer, but this should not be a reason - decide for legibility for human readers.

By the way, if you are using lots of static methods (from Math, for example), you could also write

import static java.lang.Math.*;

and then use

sqrt(x)

directly. But only do this if your class is math heavy and it really helps legibility of bigger formulas, since the reader (as the compiler) first would search in the same class and maybe in superclasses, too. (This applies analogously for other static methods and static variables (or constants), too.)

Duplicating a MySQL table, indices, and data

Try this :

`CREATE TABLE new-table (id INT(11) auto_increment primary key) SELECT old-table.name, old-table.group, old-table.floor, old-table.age from old-table;`

I selected 4 columns from old-table and made a new table.

Pandas - How to flatten a hierarchical index in columns

I'll share a straight-forward way that worked for me.

[" ".join([str(elem) for elem in tup]) for tup in df.columns.tolist()]
#df = df.reset_index() if needed

Passing parameters to click() & bind() event in jquery?

From where would you get these values? If they're from the button itself, you could just do

commentbtn.click(function() {
   alert(this.id);
});

If they're a variable in the binding scope, you can access them from without

var id = 1;
commentbtn.click(function() {
   alert(id);
});

If they're a variable in the binding scope, that might change before the click is called, you'll need to create a new closure

for(var i = 0; i < 5; i++) {
   $('#button'+i).click((function(id) {
      return function() {
         alert(id);
      };
   }(i)));
}

How Connect to remote host from Aptana Studio 3

From the Project Explorer, expand the project you want to hook up to a remote site (or just right click and create a new Web project that's empty if you just want to explore a remote site from there). There's a "Connections" node, right click it and select "Add New connection...". A dialog will appear, at bottom you can select the destination as Remote and then click the "New..." button. There you can set up an FTP/FTPS/SFTP connection.

That's how you set up a connection that's tied to a project, typically for upload/download/sync between it and a project.

You can also do Window > Show View > Remote. From that view, you can click the globe icon in the upper right to add connections and in this view you can just browse your remote connections.

Why not use Double or Float to represent currency?

I'll risk being downvoted, but I think the unsuitability of floating point numbers for currency calculations is overrated. As long as you make sure you do the cent-rounding correctly and have enough significant digits to work with in order to counter the binary-decimal representation mismatch explained by zneak, there will be no problem.

People calculating with currency in Excel have always used double precision floats (there is no currency type in Excel) and I have yet to see anyone complaining about rounding errors.

Of course, you have to stay within reason; e.g. a simple webshop would probably never experience any problem with double precision floats, but if you do e.g. accounting or anything else that requires adding a large (unrestricted) amount of numbers, you wouldn't want to touch floating point numbers with a ten foot pole.

Correct way to integrate jQuery plugins in AngularJS

Yes, you are correct. If you are using a jQuery plugin, do not put the code in the controller. Instead create a directive and put the code that you would normally have inside the link function of the directive.

There are a couple of points in the documentation that you could take a look at. You can find them here:
Common Pitfalls

Using controllers correctly

Ensure that when you are referencing the script in your view, you refer it last - after the angularjs library, controllers, services and filters are referenced.

EDIT: Rather than using $(element), you can make use of angular.element(element) when using AngularJS with jQuery

Hide Show content-list with only CSS, no javascript used

I've got another simple solution:

HTML:

<a href="#alert" class="span3" tabindex="0">Hide Me</a>
<a href="#" class="span2" tabindex="0">Show Me</a>
<p id="alert" class="alert" >Some alarming information here</p>

CSS:

body { display: block; }
p.alert:target { display: none; }

Source: http://css-tricks.com/off-canvas-menu-with-css-target/

plot data from CSV file with matplotlib

According to the docs numpy.loadtxt is

a fast reader for simply formatted files. The genfromtxt function provides more sophisticated handling of, e.g., lines with missing values.

so there are only a few options to handle more complicated files. As mentioned numpy.genfromtxt has more options. So as an example you could use

import numpy as np
data = np.genfromtxt('e:\dir1\datafile.csv', delimiter=',', skip_header=10,
                     skip_footer=10, names=['x', 'y', 'z'])

to read the data and assign names to the columns (or read a header line from the file with names=True) and than plot it with

ax1.plot(data['x'], data['y'], color='r', label='the data')

I think numpy is quite well documented now. You can easily inspect the docstrings from within ipython or by using an IDE like spider if you prefer to read them rendered as HTML.

How to reload the current route with the angular 2 router

I am using this one for Angular 10 project:

reloadCurrentRoute() {
    let currentUrl = this.router.url;
    this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
        this.router.navigate([currentUrl]);
    });
}

PS: Tested and works also on "Angular 7, 8, 9"

How should I choose an authentication library for CodeIgniter?

I use a customized version of DX Auth. I found it simple to use, extremely easy to modify and it has a user guide (with great examples) that is very similar to Code Igniter's.

How to read a file and write into a text file?

If you want to do it line by line:

Dim sFileText As String
Dim iInputFile As Integer, iOutputFile as integer

iInputFile = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iInputFile 
iOutputFile = FreeFile
Open "C:\Clients\Converter\2.txt" For Output As #iOutputFile 
Do While Not EOF(iInputFile)
   Line Input #iInputFile , sFileText
   ' sFileTextis a single line of the original file
   ' you can append anything to it before writing to the other file
   Print #iOutputFile, sFileText 
Loop
Close #iInputFile 
Close #iOutputFile 

AngularJS - get element attributes values

If you are using Angular2+ following code will help

You can use following syntax to get attribute value from html element

//to retrieve html element

const element = fixture.debugElement.nativeElement.querySelector('name of element'); // example a, h1, p

//get attribute value from that element

  const attributeValue = element.attributeName // like textContent/href

SQL Server 2005 Setting a variable to the result of a select query

You can use something like

SET @cnt = (SELECT COUNT(*) FROM User)

or

SELECT @cnt = (COUNT(*) FROM User)

For this to work the SELECT must return a single column and a single result and the SELECT statement must be in parenthesis.

Edit: Have you tried something like this?

DECLARE @OOdate DATETIME

SET @OOdate = Select OO.Date from OLAP.OutageHours as OO where OO.OutageID = 1

Select COUNT(FF.HALID) 
from Outages.FaultsInOutages as OFIO 
inner join Faults.Faults as FF 
    ON FF.HALID = OFIO.HALID 
WHERE @OODate = FF.FaultDate
    AND OFIO.OutageID = 1

Implement division with bit-wise operator

The below method is the implementation of binary divide considering both numbers are positive. If subtraction is a concern we can implement that as well using binary operators.

Code

-(int)binaryDivide:(int)numerator with:(int)denominator
{
    if (numerator == 0 || denominator == 1) {
        return numerator;
    }

    if (denominator == 0) {

        #ifdef DEBUG
            NSAssert(denominator == 0, @"denominator should be greater then 0");
        #endif
        return INFINITY;
    }

    // if (numerator <0) {
    //     numerator = abs(numerator);
    // }

    int maxBitDenom = [self getMaxBit:denominator];
    int maxBitNumerator = [self getMaxBit:numerator];
    int msbNumber = [self getMSB:maxBitDenom ofNumber:numerator];

    int qoutient = 0;

    int subResult = 0;

    int remainingBits = maxBitNumerator-maxBitDenom;

    if (msbNumber >= denominator) {
        qoutient |=1;
        subResult = msbNumber - denominator;
    }
    else {
        subResult = msbNumber;
    }

    while (remainingBits>0) {
        int msbBit = (numerator & (1 << (remainingBits-1)))>0 ? 1 : 0;
        subResult = (subResult << 1) |msbBit;
        if (subResult >= denominator) {
            subResult = subResult-denominator;
            qoutient = (qoutient << 1) | 1;
        }
        else {
            qoutient = qoutient << 1;
        }
        remainingBits--;
    }
    return qoutient;
}


-(int)getMaxBit:(int)inputNumber
{
    int maxBit =0;
    BOOL isMaxBitSet = NO;
    for (int i=0; i<sizeof(inputNumber)*8; i++) {
        if (inputNumber & (1 << i) ) {
            maxBit = i;
            isMaxBitSet=YES;
        }
    }
    if (isMaxBitSet) {
        maxBit += 1;
    }
    return maxBit;
}


-(int)getMSB:(int)bits ofNumber:(int)number
{
    int numbeMaxBit = [self getMaxBit:number];
    return number >> (numbeMaxBit -bits);
}

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

In my case I just ignored the following in application.properties file:

# Hibernate

#spring.jpa.hibernate.ddl-auto=update

It works for me....