Programs & Examples On #Firefox

Mozilla Firefox is a free, open-source cross-platform web browser. Use this tag if your question is related to the inner workings of Firefox or if it relates to code that is not working on Firefox which does work in other browsers. Questions about Firefox add-on development should be tagged [firefox-addon]. If your question is about using Firefox for browsing (i.e. as an end user) you should ask your question on Super User instead.

Detecting the onload event of a window opened with window.open

First of all, when your first initial window is loaded, it is cached. Therefore, when creating a new window from the first window, the contents of the new window are not loaded from the server, but are loaded from the cache. Consequently, no onload event occurs when you create the new window.

However, in this case, an onpageshow event occurs. It always occurs after the onload event and even when the page is loaded from cache. Plus, it now supported by all major browsers.

 window.popup = window.open($(this).attr('href'), 'Ad', 'left=20,top=20,width=500,height=500,toolbar=1,resizable=0');
 $(window.popup).onpageshow = function() {
     alert("Popup has loaded a page");
 };

The w3school website elaborates more on this:

The onpageshow event is similar to the onload event, except that it occurs after the onload event when the page first loads. Also, the onpageshow event occurs every time the page is loaded, whereas the onload event does not occur when the page is loaded from the cache.

How do I programmatically click on an element in JavaScript?

The document.createEvent documentation says that "The createEvent method is deprecated. Use event constructors instead."

So you should use this method instead:

var clickEvent = new MouseEvent("click", {
    "view": window,
    "bubbles": true,
    "cancelable": false
});

and fire it on an element like this:

element.dispatchEvent(clickEvent);

as shown here.

JavaScript open in a new window, not tab

I just tried this with IE (11) and Chrome (54.0.2794.1 canary SyzyASan):

window.open(url, "_blank", "x=y")

... and it opened in a new window.

Which means that Clint pachl had it right when he said that providing any one parameter will cause the new window to open.

-- and apparently it doesn't have to be a legitimate parameter!

(YMMV - as I said, I only tested it in two places...and the next upgrade might invalidate the results, any way)

ETA: I just noticed, though - in IE, the window has no decorations.

The character encoding of the plain text document was not declared - mootool script

I got this error using Spring Boot (in Mozilla),

because I was just testing some basic controller -> service -> repository communication by directly returning some entities from the database to the browser (as JSON).

I forgot to put data in the database, so my method wasn't returning anything... and I got this error.

Now that I put some data in my db, it works fine (the error is removed). :D

How to hide scrollbar in Firefox?

I used this and it worked. https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-width

html {
scrollbar-width: none;
}

Note: User Agents must apply any scrollbar-width value set on the root element to the viewport.

Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property

in my case, I must to set path in properties file, in many hours I find the way:

application.properties file:

webdriver.gecko.driver="/lib/geckodriver-v0.26.0-win64/geckodriver.exe"

in java code:

private static final Logger log = Logger.getLogger(Login.class.getName());
private FirefoxDriver driver;
private FirefoxProfile firefoxProfile;
private final String BASE_URL = "https://www.myweb.com/";
private static final String RESOURCE_NAME = "main/resources/application.properties"; // could also be a constant
private Properties properties;

public Login() {
    init();
}

private void init() {
    properties = new Properties();
    try(InputStream resourceStream = getClass().getClassLoader().getResourceAsStream(RESOURCE_NAME)) {
        properties.load(resourceStream);
    } catch (IOException e) {
        System.err.println("Could not open Config file");
        log.log(Level.SEVERE, "Could not open Config file", e);
    }
    // open incognito tab by default
    firefoxProfile = new FirefoxProfile();
    firefoxProfile.setPreference("browser.privatebrowsing.autostart", true);
    // geckodriver driver path to run
    String gekoDriverPath = properties.getProperty("webdriver.gecko.driver");
    log.log(Level.INFO, gekoDriverPath);
    System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir") + gekoDriverPath);
    log.log(Level.INFO, System.getProperty("webdriver.gecko.driver"));
    System.setProperty("webdriver.gecko.driver", System.getProperty("webdriver.gecko.driver").replace("\"", ""));
    if (driver == null) {
        driver = new FirefoxDriver();
    }

}

How to open SharePoint files in Chrome/Firefox

You can use web-based protocol handlers for the links as per https://sharepoint.stackexchange.com/questions/70178/how-does-sharepoint-2013-enable-editing-of-documents-for-chrome-and-fire-fox

Basically, just prepend ms-word:ofe|u| to the links to your SharePoint hosted Word documents.

Detect all Firefox versions in JS

If you'd like to know what is the numeric version of FireFox you can use the following snippet:

var match = window.navigator.userAgent.match(/Firefox\/([0-9]+)\./);
var ver = match ? parseInt(match[1]) : 0;

firefox proxy settings via command line

You could also use this Powershell script I wrote to do just this, and all other Firefox settings as well.

https://bitbucket.org/remyservices/powershell-firefoxpref/wiki/Home

Using this you could easily manage Firefox using computer startup and user logon scripts. See the wiki page for directions on how to use it.

How to get HTML 5 input type="date" working in Firefox and/or IE 10

Thank Alexander, I found a way how to modify format for en lang. (Didn't know which lang uses such format)

 $.webshims.formcfg = {
        en: {
            dFormat: '/',
            dateSigns: '/',
            patterns: {
                d: "yy/mm/dd"
            }
        }
     };

 $.webshims.activeLang('en');

Button inside of anchor link works in Firefox but not in Internet Explorer?

You can't have a <button> inside an <a> element. As W3's content model description for the <a> element states:

"there must be no interactive content descendant."

(a <button> is considered interactive content)

To get the effect you're looking for, you can ditch the <a> tags and add a simple event handler to each button which navigates the browser to the desired location, e.g.

<input type="button" value="stackoverflow.com" onClick="javascript:location.href = 'http://stackoverflow.com';" />

Please consider not doing this, however; there's a reason regular links work as they do:

  • Users can instantly recognize links and understand that they navigate to other pages
  • Search engines can identify them as links and follow them
  • Screen readers can identify them as links and advise their users appropriately

You also add a completely unnecessary requirement to have JavaScript enabled just to perform a basic navigation; this is such a fundamental aspect of the web that I would consider such a dependency as unacceptable.

You can style your links, if desired, using a background image or background color, border and other techniques, so that they look like buttons, but under the covers, they should be ordinary links.

Targeting only Firefox with CSS

Updated(from @Antoine comment)

You can use @supports

_x000D_
_x000D_
@supports (-moz-appearance:none) {_x000D_
    h1 { color:red; } _x000D_
}
_x000D_
<h1>This should be red in FF</h1>
_x000D_
_x000D_
_x000D_

More on @supports here

Class has been compiled by a more recent version of the Java Environment

You can try this way

javac --release 8 yourClass.java

How to remove the arrow from a select element in Firefox

Would you accept minor changes to the html?

Something like putting a div tag containing the select tag.

Take a look.

Disable cross domain web security in Firefox

Check out my addon that works with the latest Firefox version, with beautiful UI and support JS regex: https://addons.mozilla.org/en-US/firefox/addon/cross-domain-cors

Update: I just add Chrome extension for this https://chrome.google.com/webstore/detail/cross-domain-cors/mjhpgnbimicffchbodmgfnemoghjakai

enter image description here

How can I get browser to prompt to save password?

None of the answers already make it clear you can use the HTML5 History API to prompt to save the password.

First, you need to make sure you have at least a <form> element with a password and email or username field. Most browsers handle this automatically as long as you use the right input types (password, email or username). But to be sure, set the autocomplete values correctly for each input element.

You can find a list of the autocomplete values here: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete

The ones you need are: username, email and current-password

Then you have two possibilities:

  • If you navigate away to a different URL after submitting, most browsers will prompt to save the password.
  • If you don't want to redirect to a different URL or even reload the page (e.g. a single page application). Just prevent the event defaults (using e.preventDefault) in your submit handler of the form. You can use the HTML5 history API to push something on the history to indicate you 'navigated' inside your single page application. The browser will now prompt to save the password and username.
history.pushState({}, "Your new page title");

You can also change the page's URL, but that is not required to prompt to save the password:

history.pushState({}, "Your new page title", "new-url");

Documentation: https://developer.mozilla.org/en-US/docs/Web/API/History/pushState

This has the additional benefit that you can prevent the browser to ask to save the password if the user entered the password incorrectly. Note that in some browsers the browser will always ask to save the credentials, even when you call .preventDefault and not use the history API.

If you don't want to navigate away and/or modify the browser history, you can use replaceState instead (this also works).

How can I detect browser type using jQuery?

You can use this code to find correct browser and you can make changes for any target browser.....

_x000D_
_x000D_
function myFunction() { _x000D_
        if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 ){_x000D_
            alert('Opera');_x000D_
        }_x000D_
        else if(navigator.userAgent.indexOf("Chrome") != -1 ){_x000D_
            alert('Chrome');_x000D_
        }_x000D_
        else if(navigator.userAgent.indexOf("Safari") != -1){_x000D_
            alert('Safari');_x000D_
        }_x000D_
        else if(navigator.userAgent.indexOf("Firefox") != -1 ){_x000D_
             alert('Firefox');_x000D_
        }_x000D_
        else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )){_x000D_
          alert('IE'); _x000D_
        }  _x000D_
        else{_x000D_
           alert('unknown');_x000D_
        }_x000D_
    }
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
 <title>Browser detector</title>_x000D_
_x000D_
</head>_x000D_
<body onload="myFunction()">_x000D_
// your code here _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

I see in the documentation page an example like this:

<source src="foo.ogg" type="video/ogg; codecs=&quot;dirac, speex&quot;">

Maybe you should enclose the codec information with &quot; entities instead of actual quotes and the type attribute with quotes instead of apostrophes.

You can also try removing the codec info altogether.

Play sound file in a web-page in the background

With me the problem was solved by removing the type attribute:

<embed name="myMusic" loop="true" hidden="true" src="Music.mp3"></embed>

Cerntainly not the cleanest way.

If you're using HTML5: MP3 isn't supported by Firefox. Wav and Ogg are though. Here you can find an overview of which browser support which type of audio: http://www.w3schools.com/html/html5_audio.asp

View JSON file in Browser

Right click on JSON file, select open, navigate to program you want open with(notepad). Consecutive opens automatically use notepad.

Preventing an image from being draggable or selectable without using JS

Depending on the situation, it is often helpful to make the image a background image of a div with CSS.

<div id='my-image'></div>

Then in CSS:

#my-image {
    background-image: url('/img/foo.png');
    width: ???px;
    height: ???px;
}

See this JSFiddle for a live example with a button and a different sizing option.

How to verify an XPath expression in Chrome Developers tool or Firefox's Firebug?

I verify XPath and CSS selectors using WebSync Chrome extension.

It provides possibility to verify selectors and also to generate/modify selectors by clicking on element attributes.

https://chrome.google.com/webstore/detail/natu-websync/aohpgnblncapofbobbilnlfliihianac

enter image description here

How to remove Firefox's dotted outline on BUTTONS as well as links?

No need to define a selector.

:focus {outline:none;}
::-moz-focus-inner {border:0;}

However, this violates accessibility best practices from the W3C. The outline is there to help those navigating with keyboards.

https://www.w3.org/TR/WCAG20-TECHS/F78.html#F78-examples

Save base64 string as PDF at client side with JavaScript

you can use this function to download file from base64.

function downloadPDF(pdf) {
const linkSource = `data:application/pdf;base64,${pdf}`;
const downloadLink = document.createElement("a");
const fileName = "abc.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();}

This code will made an anchor tag with href and download file. if you want to use button then you can call click method on your button click.

i hope this will help of you thanks

.attr("disabled", "disabled") issue

UPDATED

DEMO: http://jsbin.com/uneti3/3

your code is wrong, it should be something like this:

 $(bla).click(function() { 
        var disable =  $target.toggleClass('open').hasClass('open');
       $target.prev().prop("disabled", disable);
  });

you are using the toggleClass function in wrong way

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

I found this blog post which cleared up a few things. To quote the most relevant bit:

Mixed Active Content is now blocked by default in Firefox 23!

What is Mixed Content?
When a user visits a page served over HTTP, their connection is open for eavesdropping and man-in-the-middle (MITM) attacks. When a user visits a page served over HTTPS, their connection with the web server is authenticated and encrypted with SSL and hence safeguarded from eavesdroppers and MITM attacks.

However, if an HTTPS page includes HTTP content, the HTTP portion can be read or modified by attackers, even though the main page is served over HTTPS. When an HTTPS page has HTTP content, we call that content “mixed”. The webpage that the user is visiting is only partially encrypted, since some of the content is retrieved unencrypted over HTTP. The Mixed Content Blocker blocks certain HTTP requests on HTTPS pages.

The resolution, in my case, was to simply ensure the jquery includes were as follows (note the removal of the protocol):

<link rel="stylesheet" href="//code.jquery.com/ui/1.8.10/themes/smoothness/jquery-ui.css" type="text/css">
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.min.js"></script>

Note that the temporary 'fix' is to click on the 'shield' icon in the top-left corner of the address bar and select 'Disable Protection on This Page', although this is not recommended for obvious reasons.

UPDATE: This link from the Firefox (Mozilla) support pages is also useful in explaining what constitutes mixed content and, as given in the above paragraph, does actually provide details of how to display the page regardless:

Most websites will continue to work normally without any action on your part.

If you need to allow the mixed content to be displayed, you can do that easily:

Click the shield icon Mixed Content Shield in the address bar and choose Disable Protection on This Page from the dropdown menu.

The icon in the address bar will change to an orange warning triangle Warning Identity Icon to remind you that insecure content is being displayed.

To revert the previous action (re-block mixed content), just reload the page.

Edit and replay XHR chrome/firefox etc?

No need to install 3rd party extensions!

There exists the javascript-snippet, which you can add as browser-bookmark and then activate on any site to track & modify the requests. It looks like:

enter image description here

For further instructions, review the github page.

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

A better solution:

function getViewportSize(w) {
    var w = w || window;
    if(w.innerWidth != null)
        return {w:w.innerWidth, h:w.innerHeight};
    var d = w.document;
    if (document.compatMode == "CSS1Compat") {
        return {
            w: d.documentElement.clientWidth,
            h: d.documentElement.clientHeight
        };
    }
    return { w: d.body.clientWidth, h: d.body.clientWidth };
}


function isViewportVisible(e) {
    var box = e.getBoundingClientRect();
    var height = box.height || (box.bottom - box.top);
    var width = box.width || (box.right - box.left);
    var viewport = getViewportSize();
    if(!height || !width)
        return false;
    if(box.top > viewport.h || box.bottom < 0)
        return false;
    if(box.right < 0 || box.left > viewport.w)
        return false;
    return true;
}

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

Note: localhost is the hostname for an address using the local (loopback) network interface, and 127.0.0.1 is its IP in the IPv4 network standard (it's ::1 in IPv6). 0.0.0.0 is the IPv4 standard "current network" IP address.

I experienced this error with a Docker setup. I had a Docker container running on an external server, and I'd (correctly) mapped its ports out as 127.0.0.1:9232:9232. By port-forwarding ssh remote -L 9232:127.0.0.1:9232, I'd expected to be able to communicate with the remote server's port 9232 as if it were my own local port.

It turned out that the Docker container was internally running its process on 127.0.0.1:9232 rather than 0.0.0.0:9232, and so even though I'd specified the container's port-mappings correctly, they weren't on the correct interface for being mapped out.

Firefox 'Cross-Origin Request Blocked' despite headers

I found that my problem was that the server I've sent the cross request to had a certificate that was not trusted.

If you want to connect to a cross domain with https, you have to add an exception for this certificate first.

You can do this by visiting the blocked link once and addibng the exception.

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

It was happening to me in ZF2. I was trying to load the Modal content but I forgot to disable the layout before.

So:

$viewModel = new ViewModel();
$viewModel->setTerminal(true);
return $viewModel;

Running sites on "localhost" is extremely slow

I had same issues, edited my hosts file 127.0.0.1 localhost, but noticed no difference.

I then disabled Compression in the IIS panel and applied, and problem appears to now be resolved.

IIS Manager > Compression > Uncheck 'Enable dynamic content compression' and uncheck 'Enable static content compression'. Then 'Apply'.

Hope this helps!

regards, Geoff

"The stylesheet was not loaded because its MIME type, "text/html" is not "text/css"

In the head section of your html document:

<link rel="stylesheet" type="text/css" href="/path/to/ABCD.css">

Your css file should be css only and not contain any markup.

Programmatically Install Certificate into Mozilla

Recent versions of Firefox support a policies.json file that will be applied to all Firefox profiles.

For CA certificates, you have some options, here's one example, tested with Linux/Ubuntu where I already have system-wide CA certs in /usr/local/share/ca-certificates:

In /usr/lib/firefox/distribution/policies.json

{
    "policies": {
        "Certificates": {
            "Install": [
                "/usr/local/share/ca-certificates/my-custom-root-ca.crt"
            ]
        }
    }
}

Support for Thunderbird is on its way.

How to debug Angular JavaScript Code

You can debug using browsers built in developer tools.

  1. open developer tools in browser and go to source tab.

  2. open the file do you want to debug using Ctrl+P and search file name

  3. add break point on a line ny clicking on left side of the code.

  4. refresh the page.

There are lot of plugin available for debugging you can refer for using chrome plugin Debug Angular Application using "Debugger for chrome" plugin

What is the correct "-moz-appearance" value to hide dropdown arrow of a <select> element

It is worth trying these 2 options below while we're still waiting for the fix in FF35:

select {
    -moz-appearance: scrollbartrack-vertical;
}

or

select {
    -moz-appearance: treeview;
}

They will just hide any arrow background image you have put in to custom style your select element. So you get a bog standard browser arrow instead of a horrible combo of both browser arrow and your own custom arrow.

Open new popup window without address bars in firefox & IE

Firefox 3.0 and higher have disabled setting location by default. resizable and status are also disabled by default. You can verify this by typing `about:config' in your address bar and filtering by "dom". The items of interest are:

  • dom.disable_window_open_feature.location
  • dom.disable_window_open_feature.resizable
  • dom.disable_window_open_feature.status

You can get further information at the Mozilla Developer site. What this basically means, though, is that you won't be able to do what you want to do.

One thing you might want to do (though it won't solve your problem), is put quotes around your window feature parameters, like so:

window.open('/pageaddress.html','winname','directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=400,height=350');

Can I call jQuery's click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

Click handlers on anchor tags are a special case in jQuery.

I think you might be getting confused between the anchor's onclick event (known by the browser) and the click event of the jQuery object which wraps the DOM's notion of the anchor tag.

You can download the jQuery 1.3.2 source here.

The relevant sections of the source are lines 2643-2645 (I have split this out to multiple lines to make it easier to comprehend):

// Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
if (
     (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && 
       elem["on"+type] && 
       elem["on"+type].apply( elem, data ) === false
   )
     event.result = false;

Hide Spinner in Input Number - Firefox 29

Faced the same issue post Firefox update to 29.0.1, this is also listed out here https://bugzilla.mozilla.org/show_bug.cgi?id=947728

Solutions: They(Mozilla guys) have fixed this by introducing support for "-moz-appearance" for <input type="number">. You just need to have a style associated with your input field with "-moz-appearance:textfield;".

I prefer the CSS way E.g.:-

.input-mini{
-moz-appearance:textfield;}

Or

You can do it inline as well:

<input type="number" style="-moz-appearance: textfield">

Custom CSS Scrollbar for Firefox

As of now there is just two property for firefox scrollbar customization is available .

scrollbar-color & scrollbar width

scrollbar-color:red yellow; (track,thumb) scrollbar-width:5px;

HTML

<div class="demo">

css

.demo {
overflow-y:scroll;
}

.demo {
scrollbar-color:red yellow;
scrollbar-width:5px;
}

onchange event on input type=range is not triggering in firefox while dragging

UPDATE: I am leaving this answer here as an example of how to use mouse events to use range/slider interactions in desktop (but not mobile) browsers. However, I have now also written a completely different and, I believe, better answer elsewhere on this page that uses a different approach to providing a cross-browser desktop-and-mobile solution to this problem.

Original answer:

Summary: A cross-browser, plain JavaScript (i.e. no-jQuery) solution to allow reading range input values without using on('input'... and/or on('change'... which work inconsistently between browsers.

As of today (late Feb, 2016), there is still browser inconsistency so I'm providing a new work-around here.

The problem: When using a range input, i.e. a slider, on('input'... provides continuously updated range values in Mac and Windows Firefox, Chrome and Opera as well as Mac Safari, while on('change'... only reports the range value upon mouse-up. In contrast, in Internet Explorer (v11), on('input'... does not work at all, and on('change'... is continuously updated.

I report here 2 strategies to get identical continuous range value reporting in all browsers using vanilla JavaScript (i.e. no jQuery) by using the mousedown, mousemove and (possibly) mouseup events.

Strategy 1: Shorter but less efficient

If you prefer shorter code over more efficient code, you can use this 1st solution which uses mousesdown and mousemove but not mouseup. This reads the slider as needed, but continues firing unnecessarily during any mouse-over events, even when the user has not clicked and is thus not dragging the slider. It essentially reads the range value both after 'mousedown' and during 'mousemove' events, slightly delaying each using requestAnimationFrame.

_x000D_
_x000D_
var rng = document.querySelector("input");_x000D_
_x000D_
read("mousedown");_x000D_
read("mousemove");_x000D_
read("keydown"); // include this to also allow keyboard control_x000D_
_x000D_
function read(evtType) {_x000D_
  rng.addEventListener(evtType, function() {_x000D_
    window.requestAnimationFrame(function () {_x000D_
      document.querySelector("div").innerHTML = rng.value;_x000D_
      rng.setAttribute("aria-valuenow", rng.value); // include for accessibility_x000D_
    });_x000D_
  });_x000D_
}
_x000D_
<div>50</div><input type="range"/>
_x000D_
_x000D_
_x000D_

Strategy 2: Longer but more efficient

If you need more efficient code and can tolerate longer code length, then you can use the following solution which uses mousedown, mousemove and mouseup. This also reads the slider as needed, but appropriately stops reading it as soon as the mouse button is released. The essential difference is that is only starts listening for 'mousemove' after 'mousedown', and it stops listening for 'mousemove' after 'mouseup'.

_x000D_
_x000D_
var rng = document.querySelector("input");_x000D_
_x000D_
var listener = function() {_x000D_
  window.requestAnimationFrame(function() {_x000D_
    document.querySelector("div").innerHTML = rng.value;_x000D_
  });_x000D_
};_x000D_
_x000D_
rng.addEventListener("mousedown", function() {_x000D_
  listener();_x000D_
  rng.addEventListener("mousemove", listener);_x000D_
});_x000D_
rng.addEventListener("mouseup", function() {_x000D_
  rng.removeEventListener("mousemove", listener);_x000D_
});_x000D_
_x000D_
// include the following line to maintain accessibility_x000D_
// by allowing the listener to also be fired for_x000D_
// appropriate keyboard events_x000D_
rng.addEventListener("keydown", listener);
_x000D_
<div>50</div><input type="range"/>
_x000D_
_x000D_
_x000D_

Demo: Fuller explanation of the need for, and implementation of, the above work-arounds

The following code more fully demonstrates numerous aspects of this strategy. Explanations are embedded in the demonstration:

_x000D_
_x000D_
var select, inp, listen, unlisten, anim, show, onInp, onChg, onDn1, onDn2, onMv1, onMv2, onUp, onMvCombo1, onDnCombo1, onUpCombo2, onMvCombo2, onDnCombo2;_x000D_
_x000D_
select   = function(selctr)     { return document.querySelector(selctr);      };_x000D_
inp = select("input");_x000D_
listen   = function(evtTyp, cb) { return inp.   addEventListener(evtTyp, cb); };_x000D_
unlisten = function(evtTyp, cb) { return inp.removeEventListener(evtTyp, cb); };_x000D_
anim     = function(cb)         { return window.requestAnimationFrame(cb);    };_x000D_
show = function(id) {_x000D_
 return function() {_x000D_
    select("#" + id + " td~td~td"   ).innerHTML = inp.value;_x000D_
    select("#" + id + " td~td~td~td").innerHTML = (Math.random() * 1e20).toString(36); // random text_x000D_
  };_x000D_
};_x000D_
_x000D_
onInp      =                  show("inp" )                                      ;_x000D_
onChg      =                  show("chg" )                                      ;_x000D_
onDn1      =                  show("mdn1")                                      ;_x000D_
onDn2      = function() {anim(show("mdn2"));                                   };_x000D_
onMv1      =                  show("mmv1")                                      ;_x000D_
onMv2      = function() {anim(show("mmv2"));                                   };_x000D_
onUp       =                  show("mup" )                                      ;_x000D_
onMvCombo1 = function() {anim(show("cmb1"));                                   };_x000D_
onDnCombo1 = function() {anim(show("cmb1"));   listen("mousemove", onMvCombo1);};_x000D_
onUpCombo2 = function() {                    unlisten("mousemove", onMvCombo2);};_x000D_
onMvCombo2 = function() {anim(show("cmb2"));                                   };_x000D_
onDnCombo2 = function() {anim(show("cmb2"));   listen("mousemove", onMvCombo2);};_x000D_
_x000D_
listen("input"    , onInp     );_x000D_
listen("change"   , onChg     );_x000D_
listen("mousedown", onDn1     );_x000D_
listen("mousedown", onDn2     );_x000D_
listen("mousemove", onMv1     );_x000D_
listen("mousemove", onMv2     );_x000D_
listen("mouseup"  , onUp      );_x000D_
listen("mousedown", onDnCombo1);_x000D_
listen("mousedown", onDnCombo2);_x000D_
listen("mouseup"  , onUpCombo2);
_x000D_
table {border-collapse: collapse; font: 10pt Courier;}_x000D_
th, td {border: solid black 1px; padding: 0 0.5em;}_x000D_
input {margin: 2em;}_x000D_
li {padding-bottom: 1em;}
_x000D_
<p>Click on 'Full page' to see the demonstration properly.</p>_x000D_
<table>_x000D_
  <tr><th></th><th>event</th><th>range value</th><th>random update indicator</th></tr>_x000D_
  <tr id="inp" ><td>A</td><td>input                                </td><td>100</td><td>-</td></tr>_x000D_
  <tr id="chg" ><td>B</td><td>change                               </td><td>100</td><td>-</td></tr>_x000D_
  <tr id="mdn1"><td>C</td><td>mousedown                            </td><td>100</td><td>-</td></tr>_x000D_
  <tr id="mdn2"><td>D</td><td>mousedown using requestAnimationFrame</td><td>100</td><td>-</td></tr>_x000D_
  <tr id="mmv1"><td>E</td><td>mousemove                            </td><td>100</td><td>-</td></tr>_x000D_
  <tr id="mmv2"><td>F</td><td>mousemove using requestAnimationFrame</td><td>100</td><td>-</td></tr>_x000D_
  <tr id="mup" ><td>G</td><td>mouseup                              </td><td>100</td><td>-</td></tr>_x000D_
  <tr id="cmb1"><td>H</td><td>mousedown/move combo                 </td><td>100</td><td>-</td></tr>_x000D_
  <tr id="cmb2"><td>I</td><td>mousedown/move/up combo              </td><td>100</td><td>-</td></tr>_x000D_
</table>_x000D_
<input type="range" min="100" max="999" value="100"/>_x000D_
<ol>_x000D_
  <li>The 'range value' column shows the value of the 'value' attribute of the range-type input, i.e. the slider. The 'random update indicator' column shows random text as an indicator of whether events are being actively fired and handled.</li>_x000D_
  <li>To see browser differences between input and change event implementations, use the slider in different browsers and compare A and&nbsp;B.</li>_x000D_
  <li>To see the importance of 'requestAnimationFrame' on 'mousedown', click a new location on the slider and compare C&nbsp;(incorrect) and D&nbsp;(correct).</li>_x000D_
  <li>To see the importance of 'requestAnimationFrame' on 'mousemove', click and drag but do not release the slider, and compare E&nbsp;(often 1&nbsp;pixel behind) and F&nbsp;(correct).</li>_x000D_
  <li>To see why an initial mousedown is required (i.e. to see why mousemove alone is insufficient), click and hold but do not drag the slider and compare E&nbsp;(incorrect), F&nbsp;(incorrect) and H&nbsp;(correct).</li>_x000D_
  <li>To see how the mouse event combinations can provide a work-around for continuous update of a range-type input, use the slider in any manner and note whichever of A or B continuously updates the range value in your current browser. Then, while still using the slider, note that H and I provide the same continuously updated range value readings as A or B.</li>_x000D_
  <li>To see how the mouseup event reduces unnecessary calculations in the work-around, use the slider in any manner and compare H and&nbsp;I. They both provide correct range value readings. However, then ensure the mouse is released (i.e. not clicked) and move it over the slider without clicking and notice the ongoing updates in the third table column for H but not&nbsp;I.</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Firefox and SSL: sec_error_unknown_issuer

If anyone else is experiencing this issue with an Ubuntu LAMP and "COMODO Positive SSL" try to build your own bundle from the certs in the compressed file.

cat AddTrustExternalCARoot.crt COMODORSAAddTrustCA.crt COMODORSADomainValidationSecureServerCA.crt > YOURDOMAIN.ca-bundle

Selenium 2.53 not working on Firefox 47

Unfortunately Selenium WebDriver 2.53.0 is not compatible with Firefox 47.0. The WebDriver component which handles Firefox browsers (FirefoxDriver) will be discontinued. As of version 3.0, Selenium WebDriver will need the geckodriver binary to manage Firefox browsers. More info here and here.

Therefore, in order to use Firefox 47.0 as browser with Selenium WebDriver 2.53.0, you need to download the Firefox driver (which is a binary file called geckodriver as of version 0.8.0, and formerly wires) and export its absolute path to the variable webdriver.gecko.driver as a system property in your Java code:

System.setProperty("webdriver.gecko.driver", "/path/to/geckodriver");

Luckily, the library WebDriverManager can do this work for you, i.e. download the proper Marionette binary for your machine (Linux, Mac, or Windows) and export the value of the proper system property. To use this library, you need to include this dependency into your project:

<dependency>
    <groupId>io.github.bonigarcia</groupId>
    <artifactId>webdrivermanager</artifactId>
    <version>4.3.1</version>
</dependency>

... and then execute this line in your program before using WebDriver:

WebDriverManager.firefoxdriver().setup();

A complete running example of a JUnit 4 test case using WebDriver could be as follows:

public class FirefoxTest {

    protected WebDriver driver;

    @BeforeClass
    public static void setupClass() {
        WebDriverManager.firefoxdriver().setup();
    }

    @Before
    public void setupTest() {
        driver = new FirefoxDriver();
    }

    @After
    public void teardown() {
        if (driver != null) {
            driver.quit();
        }
    }

    @Test
    public void test() {
        // Your test code here
    }
}

Take into account that Marionette will be the only option for future (for WebDriver 3+ and Firefox 48+), but currently (version 0.9.0 at writing time) is not very stable. Take a look to the Marionette roadmap for further details.

UPDATE

Selenium WebDriver 2.53.1 has been released on 30th June 2016. FirefoxDriver is working again with Firefox 47.0.1 as browser.

How can I close a window with Javascript on Mozilla Firefox 3?

This code works for both IE 7 and the latest version of Mozilla although the default setting in mozilla doesnt allow to close a window through javascript.

Here is the code:

function F11() { window.open('','_parent',''); window.open("login.aspx", "", "channelmode"); window.close(); }

To change the default setting :

1.type"about:config " in your firefox address bar and enter;

2.make sure your "dom.allow_scripts_to_close_windows" is true

ReferenceError: event is not defined error in Firefox

It is because you forgot to pass in event into the click function:

$('.menuOption').on('click', function (e) { // <-- the "e" for event

    e.preventDefault(); // now it'll work

    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();
});

On a side note, e is more commonly used as opposed to the word event since Event is a global variable in most browsers.

Selenium using Python - Geckodriver executable needs to be in PATH

This error message...

FileNotFoundError: [WinError 2] The system cannot find the file specified

...implies that your program was unable to locate the specified file and while handling the exception the following exception occurred:

selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.

... which implies that your program was unable to locate the GeckoDriver in the process of initiating/spawnning a new Browsing Context i.e. Firefox Browser session.


You can download the latest GeckoDriver from mozilla / geckodriver, unzip/untar and store the GeckoDriver binary/executable anywhere with in your system passing the absolute path of the GeckoDriver through the key executable_path as follows:

from selenium import webdriver

driver = webdriver.Firefox(executable_path='/path/to/geckodriver')
driver.get('http://google.com/')

In case is not installed at the default location (i.e. installed at a custom location) additionally you need to pass the absolute path of firefox binary through the attribute binary_location as follows:

# An Windows example
from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
options.binary_location = r'C:\Program Files\Mozilla Firefox\firefox.exe'
driver = webdriver.Firefox(firefox_options=options, executable_path=r'C:\WebDrivers\geckodriver.exe')
driver.get('http://google.com/')

"google is not defined" when using Google Maps V3 in Firefox remotely

Another suggestion that helped me:

Here is what happent to me => My script was working once in 3 time I was loading the page and the error was the «google is not defined».

My function using the google map was in my jQuery document's ready function

$(function(){
   //Here was my logic
})

I simply added this code to make sure it works:

$(function(){
   $(window).load(function(){
       //Here is my logic now
   });
});

It works like a charm. If you want more details on difference between document ready and window load, here is a great post about it: window.onload vs $(document).ready()

The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.

The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.

How can I zoom an HTML element in Firefox and Opera?

I've been swearing at this for a while. Zoom is definitely not the solutions, it works in chrome, it works partially in IE but moves the entire html div, firefox doesnt do a thing.

My solution that worked for me was using both a scaling and a translation, and also adding the original height and weight and then setting the height and weight of the div itself:

#miniPreview {
transform: translate(-710px, -1000px) rotate(0rad) skewX(0rad) scale(0.3, 0.3);
transform-origin: 1010px 1429px 0px;
width: 337px;
height: 476px;

Obviously change these to your own needs. It gave me the same result in all browsers.

Postman addon's like in firefox

I liked PostMan, it was the main reason why I kept using Chrome, now I'm good with HttpRequester

https://addons.mozilla.org/En-us/firefox/addon/httprequester/?src=search

Get current cursor position in a textbox

It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.

_x000D_
_x000D_
function textbox()_x000D_
{_x000D_
        var ctl = document.getElementById('Javascript_example');_x000D_
        var startPos = ctl.selectionStart;_x000D_
        var endPos = ctl.selectionEnd;_x000D_
        alert(startPos + ", " + endPos);_x000D_
}
_x000D_
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">
_x000D_
_x000D_
_x000D_

Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart and selectionEnd.

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

I used the following code on Django side to interpret the OPTIONS request and to set the required Access-Control headers. After this my cross domain requests from Firefox started working. As said before, the browser first sends the OPTIONS request and then immediately after that the POST/GET

def send_data(request):
    if request.method == "OPTIONS": 
        response = HttpResponse()
        response['Access-Control-Allow-Origin'] = '*'
        response['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
        response['Access-Control-Max-Age'] = 1000
        # note that '*' is not valid for Access-Control-Allow-Headers
        response['Access-Control-Allow-Headers'] = 'origin, x-csrftoken, content-type, accept'
        return response
    if request.method == "POST":
        # ... 

Edit: it seems to be that at least in some cases you also need to add the same Access-Control headers to the actual response. This can be a little bit confusing, since the request seems to succeed, but Firefox does not pass the contents of the response to the Javascript.

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

May not be directly related to browsers but fiddler is another good software.

Fiddler web debugger

How to add java plugin for Firefox on Linux?

you should add plug in to your local setting of firefox in your user home

 vladimir@shinsengumi ~/.mozilla/plugins $ pwd
 /home/vladimir/.mozilla/plugins 
 vladimir@shinsengumi ~/.mozilla/plugins $ ls -ltr
 lrwxrwxrwx 1 vladimir vladimir 60 Jan  1 23:06 libnpjp2.so -> /home/vladimir/Install/jdk1.6.0_32/jre/lib/amd64/libnpjp2.so

Switch firefox to use a different DNS than what is in the windows.host file

I am using the SwitchHost extension exactly for this problem: https://addons.mozilla.org/en-US/firefox/addon/14258

It is easy to configure, and even more easy to switch hosts.

How can I simulate mobile devices and debug in Firefox Browser?

I would use the "Responsive Design View" available under Tools -> Web Developer -> Responsive Design View. It will let you test your CSS against different screen sizes.

Disable firefox same origin policy

In about:config add content.cors.disable (empty string).

How do I make a file:// hyperlink that works in both IE and Firefox?

just use

file:///

works in IE, Firefox and Chrome as far as I can tell.

see http://msdn.microsoft.com/en-us/library/aa767731(VS.85).aspx for more info

Does Google Chrome work with Selenium IDE (as Firefox does)?

Just fyi . This is available as nuget package in visual studio environment. Please let me know if you need more information as I have used it. URL can be found Link to nuget

You can also find some information here. Blog with more details

How to Maximize a firefox browser window using Selenium WebDriver with node.js

The statement :: driver.manage().window.maximize(); Works perfectly, but the window maximizes only after loading the page on browser, it does not maximizes at the time of initializing the browser.

here : (driver) is called object of Firefox driver, it may be any thing depending on the initializing of Firefox object by you only.

How to view/delete local storage in Firefox?

To inspect your localStorage items you may type console.log(localStorage); in your javascript console (firebug for example or in new FF versions the shipped js console).

You can use this line of Code to get rid of the browsers localStorage contents. Just execute it in your javascript console:

localStorage.clear();

.setAttribute("disabled", false); changes editable attribute to false

Just set the property directly: .

eleman.disabled = false;

Submit button doesn't work

Are you using HTML5? If so, check whether you have any <input type="hidden"> in your form with the property required. Remove that required property. Internet Explorer won't take this property, so it works but Chrome will.

Div 100% height works on Firefox but not in IE

I don't think IE supports the use of auto for setting height / width, so you could try giving this a numeric value (like Jarett suggests).

Also, it doesn't look like you are clearing your floats properly. Try adding this to your CSS for #container:

#container {
    height:100%;
    width:100%;
    overflow:hidden;
    /* for IE */
    zoom:1;
}

Take a full page screenshot with Firefox on the command-line

You can use selenium and the webdriver for Firefox.

import selenium.webdriver
import selenium.common

options = selenium.webdriver.firefox.options.Options()
# options.headless = True
with selenium.webdriver.Firefox(options=options) as driver:
    driver.get('http://google.com')
    time.sleep(2)
    root=driver.find_element_by_tag_name('html')
    root.screenshot('whole page screenshot.png')

Firefox "ssl_error_no_cypher_overlap" error

"Error code: ssl_error_no_cypher_overlap" error message after login, when Welcome screen expected--using Firefox browser

Solution

Enable support for 40-bit RSA encryption in the Firefox Browser: 1: enter 'about:config' in Browser Address bar 2: find/select "security.ssl3.rsa_rc4_40_md5" 3: set boolean to TRUE

Does document.body.innerHTML = "" clear the web page?

document.body.innerHTML = ''; does clear the body, yeah. But it clears the innerHTML as it is at the moment the code is ran. As you run the code before the images and the script are actually in the body, it tries to clear the body, but there's nothing to clear.

If you want to clear the body, you have to run the code after the body has been filled with content. You can do this by either placing the <script> block as the last child of body, so everything is loaded before the code is ran, or you have to use some way to listen to the dom:loaded event.

Difference between DOM parentNode and parentElement

Just like with nextSibling and nextElementSibling, just remember that, properties with "element" in their name always returns Element or null. Properties without can return any other kind of node.

console.log(document.body.parentNode, "is body's parent node");    // returns <html>
console.log(document.body.parentElement, "is body's parent element"); // returns <html>

var html = document.body.parentElement;
console.log(html.parentNode, "is html's parent node"); // returns document
console.log(html.parentElement, "is html's parent element"); // returns null

Only on Firefox "Loading failed for the <script> with source"

I ran into the same issue (exact error message) and after digging for a couple of hours, I found that the content header needs to be set to application/javascript instead of the application/json that I had. After changing that, it now works.

clientHeight/clientWidth returning different values on different browsers

It may be caused by IE's box model bug. To fix this, you can use the Box Model Hack.

Playing MP4 files in Firefox using HTML5 video

This is caused by the limited support for the MP4 format within the video tag in Firefox. Support was not added until Firefox 21, and it is still limited to Windows 7 and above. The main reason for the limited support revolves around the royalty fee attached to the mp4 format.

Check out Supported media formats and Media formats supported by the audio and video elements directly from the Mozilla crew or the following blog post for more information:

http://pauljacobson.org/2010/01/22/2010122firefox-and-its-limited-html-5-video-support-html/

The right way of setting <a href=""> when it's a local file

The href value inside the base tag will become your reference point for all your relative paths and thus override your current directory path value otherwise - the '~' is the root of your site

    <head>
        <base href="~/" />
    </head>

Is there a css cross-browser value for "width: -moz-fit-content;"?

width: intrinsic;           /* Safari/WebKit uses a non-standard name */
width: -moz-max-content;    /* Firefox/Gecko */
width: -webkit-max-content; /* Chrome */

How to open a new tab using Selenium WebDriver

The code below will open the link in a new tab.

String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN);
driver.findElement(By.linkText("urlLink")).sendKeys(selectLinkOpeninNewTab);

The code below will open an empty new tab.

String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,"t");
driver.findElement(By.linkText("urlLink")).sendKeys(selectLinkOpeninNewTab);

CSS @font-face not working with Firefox, but working with Chrome and IE

I've had this problem too. I found the answer here: http://www.dynamicdrive.com/forums/showthread.php?t=63628

This is an example of the solution that works on firefox, you need to add this line to your font face css:

src: local(font name), url("font_name.ttf");

How to enable CORS on Firefox?

It's only possible when the server sends this header: Access-Control-Allow-Origin: *

If this is your code then you can setup it like this (PHP):

header('Access-Control-Allow-Origin: *');

How to turn off caching on Firefox?

On the same page you want to disable the caching do this : FYI: the version am working on is 30.0

You can :

open webdeveloper toolbar open web developer

and pick disable cache

After that it will reload page from its own (you are on) and every thing is recached and any furthure request are recahed every time too and you may keep the web developer open always to keep an eye and make sure its always on (check).

Get image data url in JavaScript?

Note: This only works if the image is from the same domain as the page, or has the crossOrigin="anonymous" attribute and the server supports CORS. It's also not going to give you the original file, but a re-encoded version. If you need the result to be identical to the original, see Kaiido's answer.


You will need to create a canvas element with the correct dimensions and copy the image data with the drawImage function. Then you can use the toDataURL function to get a data: url that has the base-64 encoded image. Note that the image must be fully loaded, or you'll just get back an empty (black, transparent) image.

It would be something like this. I've never written a Greasemonkey script, so you might need to adjust the code to run in that environment.

function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    // Get the data-URL formatted image
    // Firefox supports PNG and JPEG. You could check img.src to
    // guess the original format, but be aware the using "image/jpg"
    // will re-encode the image.
    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

Getting a JPEG-formatted image doesn't work on older versions (around 3.5) of Firefox, so if you want to support that, you'll need to check the compatibility. If the encoding is not supported, it will default to "image/png".

How can I prevent the backspace key from navigating back?

Not sure why no-one's just answered this - seems like a perfectly reasonable technical question to ask whether it's possible.

No, I don't think there's a cross-browser way to disable the backspace button. I know it's not enabled by default in FF these days though.

Access to file download dialog in Firefox

Not that I know of. But you can configure Firefox to automatically start the download and save the file in a specific place. Your test could then check that the file actually arrived.

Webdriver Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms

On Windows: Check as well the "bitness" of your Firefox. Firefox 43.0.1 64bit does not work with Selenium 2.50.0. Working well with Firefox 43.0.1 32bit ...

X-Frame-Options: ALLOW-FROM in firefox and chrome

I posted this question and never saw the feedback (which came in several months after, it seems :).

As Kinlan mentioned, ALLOW-FROM is not supported in all browsers as an X-Frame-Options value.

The solution was to branch based on browser type. For IE, ship X-Frame-Options. For everyone else, ship X-Content-Security-Policy.

Hope this helps, and sorry for taking so long to close the loop!

clear cache of browser by command line

Here is how to clear all trash & caches (without other private data in browsers) by a command line. This is a command line batch script that takes care of all trash (as of April 2014):

erase "%TEMP%\*.*" /f /s /q
for /D %%i in ("%TEMP%\*") do RD /S /Q "%%i"

erase "%TMP%\*.*" /f /s /q
for /D %%i in ("%TMP%\*") do RD /S /Q "%%i"

erase "%ALLUSERSPROFILE%\TEMP\*.*" /f /s /q
for /D %%i in ("%ALLUSERSPROFILE%\TEMP\*") do RD /S /Q "%%i"

erase "%SystemRoot%\TEMP\*.*" /f /s /q
for /D %%i in ("%SystemRoot%\TEMP\*") do RD /S /Q "%%i"


@rem Clear IE cache -  (Deletes Temporary Internet Files Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
erase "%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*") do RD /S /Q "%%i"

@rem Clear Google Chrome cache
erase "%LOCALAPPDATA%\Google\Chrome\User Data\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Google\Chrome\User Data\*") do RD /S /Q "%%i"


@rem Clear Firefox cache
erase "%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*") do RD /S /Q "%%i"

pause

I am pretty sure it will run for some time when you first run it :) Enjoy!

new Date() is working in Chrome but not Firefox

Simple Solution, This works with All Browsers,

var StringDate = "24-11-2017"   
var DateVar = StringDate.split("-");
var DateVal = new Date(DateVar[1] + "/" + DateVar[0] + "/" + DateVar[2]);
alert(DateVal);

How to use the gecko executable with Selenium

It is important to remember that the driver(file) must have execution permission (linux chmod +x geckodriver).

To sum up:

  1. Download gecko driver
  2. Add execution permission
  3. Add system property:

    System.setProperty("webdriver.gecko.driver", "FILE PATH");

  4. Instantiate and use the class

    WebDriver driver = new FirefoxDriver();

  5. Do whatever you want

  6. Close the driver

    driver.close;

Hide scroll bar, but while still being able to scroll

UPDATE:

Firefox now supports hiding scrollbars with CSS, so all major browsers are now covered (Chrome, Firefox, Internet Explorer, Safari, etc.).

Simply apply the following CSS to the element you want to remove scrollbars from:

.container {
    overflow-y: scroll;
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none;  /* Internet Explorer 10+ */
}
.container::-webkit-scrollbar { /* WebKit */
    width: 0;
    height: 0;
}

This is the least hacky cross browser solution that I'm currently aware of. Check out the demo.


ORIGINAL ANSWER:

Here's another way that hasn't been mentioned yet. It's really simple and only involves two divs and CSS. No JavaScript or proprietary CSS is needed, and it works in all browsers. It doesn't require explicitly setting the width of the container either, thus making it fluid.

This method uses a negative margin to move the scrollbar out of the parent and then the same amount of padding to push the content back to its original position. The technique works for vertical, horizontal and two way scrolling.

Demos:

Example code for the vertical version:

HTML:

<div class="parent">
  <div class="child">
    Your content.
  </div>
</div>

CSS:

.parent {
  width: 400px;
  height: 200px;
  border: 1px solid #AAA;
  overflow: hidden;
}

.child {
  height: 100%;
  margin-right: -50px; /* Maximum width of scrollbar */
  padding-right: 50px; /* Maximum width of scrollbar */
  overflow-y: scroll;
}

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

The simplest way is to use the below code before you define your Driver.

System.setProperty("webdriver.firefox.bin",
                    "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");

"application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint

Just start your browser with superuser rights, and don't forget to set Java's JRE security to medium.

Is there a <meta> tag to turn off caching in all browsers?

This is a link to a great Case Study on the industry wide misunderstanding of controlling caches.

http://securityevaluators.com/knowledge/case_studies/caching/

In summary, according to this article, only Cache-Control: no-store is recognized by Chrome, Firefox, and IE. IE recognizes other controls, but Chrome and Firefox do not.

Webdriver and proxy server for firefox

For PAC based urls

 Proxy proxy = new Proxy();
 proxy.setProxyType(Proxy.ProxyType.PAC);
 proxy.setProxyAutoconfigUrl("http://some-server/staging.pac");
 DesiredCapabilities capabilities = new DesiredCapabilities();
 capabilities.setCapability(CapabilityType.PROXY, proxy);
 return new FirefoxDriver(capabilities);

I hope this could help.

'innerText' works in IE, but not in Firefox

Note that the Element::innerText property will not contain the text which has been hidden by CSS style "display:none" in Google Chrome (as well it will drop the content that has been masked by other CSS technics (including font-size:0, color:transparent, and a few other similar effects that cause the text not to be rendered in any visible way).

Other CSS properties are also considered :

  • First the "display:" style of inner elements is parsed to determine if it delimits a block content (such as "display:block" which is the default of HTML block elements in the browser's builtin stylesheet, and whose behavior as not been overriden by your own CSS style); if so a newline will be inserted in the value of the innerText property. This won't happen with the textContent property.
  • The CSS properties that generate inline contents will also be considered : for example the inline element <br \> that generates an inline newline will also generate an newline in the value of innerText.
  • The "display:inline" style causes no newline either in textContent or innerText.
  • The "display:table" style generates newlines around the table and between table rows, but"display:table-cell" will generate a tabulation character.
  • The "position:absolute" property (used with display:block or display:inline, it does not matter) will also cause a line break to be inserted.
  • Some browsers will also include a single space separation between spans

But Element::textContent will still contain ALL contents of inner text elements independantly of the applied CSS even if they are invisible. And no extra newlines or whitespaces will be generated in textContent, which just ignores all styles and the structure and inline/block or positioned types of inner elements.

A copy/paste operation using mouse selection will discard the hidden text in the plain-text format that is put in the clipboard, so it won't contain everything in the textContent, but only what is within innerText (after whitespace/newline generation as above).

Both properties are then supported in Google Chrome, but their content may then be different. Older browsers still included in innetText everything like what textContent now contains (but their behavior in relation with then generation of whitespaces/newlines was inconsistant).

jQuery will solve these inconsistencies between browsers using the ".text()" method added to the parsed elements it returns via a $() query. Internally, it solves the difficulties by looking into the HTML DOM, working only with the "node" level. So it will return something looking more like the standard textContent.

The caveat is that that this jQuery method will not insert any extra spaces or line breaks that may be visible on screen caused by subelements (like <br />) of the content.

If you design some scripts for accessibility and your stylesheet is parsed for non-aural rendering, such as plugins used to communicate with a Braille reader, this tool should use the textContent if it must include the specific punctuation signs that are added in spans styled with "display:none" and that are typically included in pages (for example for superscripts/subscripts), otherwise the innerText will be very confusive on the Braille reader.

Texts hidden by CSS tricks are now typically ignored by major search engines (that will also parse the CSS of your HTML pages, and will also ignore texts that are not in contrasting colors on the background) using an HTML/CSS parser and the DOM property "innerText" exactly like in modern visual browsers (at least this invisible content will not be indexed so hidden text cannot be used as a trick to force the inclusion of some keywords in the page to check its content) ; but this hidden text will be stil displayed in the result page (if the page was still qualified from the index to be included in results), using the "textContent" property instead of the full HTML to strip the extra styles and scripts.

IF you assign some plain-text in any one of these two properties, this will overwrite the inner markup and styles applied to it (only the assigned element will keep its type, attributes and styles), so both properties will then contain the same content. However, some browsers will now no longer honor the write to innerText, and will only let you overwrite the textContent property (you cannot insert HTML markup when writing to these properties, as HTML special characters will be properly encoded using numeric character references to appear literally, if you then read the innerHTML property after the assignment of innerText or textContent.

How to enable named/bind/DNS full logging?

Run command rndc querylog on or add querylog yes; to options{}; section in named.conf to activate that channel.

Also make sure you’re checking correct directory if your bind is chrooted.

Getting last month's date in php

It works for me:

Today is: 31/03/2012

echo date("Y-m-d", strtotime(date('m', mktime() - 31*3600*24).'/01/'.date('Y').' 00:00:00')); // 2012-02-01
echo  date("Y-m-d", mktime() - 31*3600*24); // 2012-02-29

How do you change the text in the Titlebar in Windows Forms?

this.Text = "Your Text Here"

Place this under Initialize Component and it should change on form load.

Fitting a density curve to a histogram in R

Dirk has explained how to plot the density function over the histogram. But sometimes you might want to go with the stronger assumption of a skewed normal distribution and plot that instead of density. You can estimate the parameters of the distribution and plot it using the sn package:

> sn.mle(y=c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4)))
$call
sn.mle(y = c(rep(65, times = 5), rep(25, times = 5), rep(35, 
    times = 10), rep(45, times = 4)))

$cp
    mean     s.d. skewness 
41.46228 12.47892  0.99527 

Skew-normal distributed data plot

This probably works better on data that is more skew-normal:

Another skew-normal plot

D3.js: How to get the computed width and height for an arbitrary element?

.getBoundingClientRect() returns the size of an element and its position relative to the viewport.We can easily get following

  • left, right
  • top, bottom
  • height, width

Example :

var element = d3.select('.elementClassName').node();
element.getBoundingClientRect().width;

Best way to check if a URL is valid

public function testing($Url=''){
    $ch = curl_init($Url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if($httpcode >= 200 && $httpcode <= 301){
        $this->output->set_header('Access-Control-Allow-Origin: *');
        $this->output->set_content_type('application/json', 'utf-8');
        $this->output->set_status_header(200);
        $this->output->set_output(json_encode('VALID URL', JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        return;
    }else{
        $this->output->set_header('Access-Control-Allow-Origin: *');
        $this->output->set_content_type('application/json', 'utf-8');
        $this->output->set_status_header(200);
        $this->output->set_output(json_encode('INVALID URL', JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        return;
    }
}

After installing with pip, "jupyter: command not found"

Execute this in Terminal

export PATH=~/anaconda3/bin:$PATH

Worked for me on Ubuntu 16.10, Python3, Anaconda3

UPDATE

Add path in your ~/.bashrc or ~/.zshrc(if you are using zsh bash) file

vi ~/.bashrc

add the below line to the file

PATH=~/path/to/anaconda:$PATH

Close the file with

esc + : + wq

ORDER BY the IN value list

On researching this some more I found this solution:

SELECT * FROM "comments" WHERE ("comments"."id" IN (1,3,2,4)) 
ORDER BY CASE "comments"."id"
WHEN 1 THEN 1
WHEN 3 THEN 2
WHEN 2 THEN 3
WHEN 4 THEN 4
END

However this seems rather verbose and might have performance issues with large datasets. Can anyone comment on these issues?

Counting the Number of keywords in a dictionary in python

The number of distinct words (i.e. count of entries in the dictionary) can be found using the len() function.

> a = {'foo':42, 'bar':69}
> len(a)
2

To get all the distinct words (i.e. the keys), use the .keys() method.

> list(a.keys())
['foo', 'bar']

How to select a dropdown value in Selenium WebDriver using Java

You can use following methods to handle drop down in selenium.

  1. driver.selectByVisibleText("Text");
  2. driver.selectByIndex(1);
  3. driver.selectByValue("prog");

For more details you can refer http://www.codealumni.com/handle-drop-selenium-webdriver/ this post.

It will definately help you a lot in resolving your queries.

Understanding `scale` in R

log simply takes the logarithm (base e, by default) of each element of the vector.
scale, with default settings, will calculate the mean and standard deviation of the entire vector, then "scale" each element by those values by subtracting the mean and dividing by the sd. (If you use scale(x, scale=FALSE), it will only subtract the mean but not divide by the std deviation.)

Note that this will give you the same values

   set.seed(1)
   x <- runif(7)

   # Manually scaling
   (x - mean(x)) / sd(x)

   scale(x)

Spring Security exclude url patterns in security annotation configurartion

Found the solution in Spring security examples posted in Github.

WebSecurityConfigurerAdapter has a overloaded configure message that takes WebSecurity as argument which accepts ant matchers on requests to be ignored.

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/authFailure");
}

See Spring Security Samples for more details

How to remove old Docker containers

UPDATED 2021 (NEWEST)

docker container prune

This - 2017 (OLD) way

To remove ALL STOPPED CONTAINERS

docker rm $(docker ps -a -q)

To remove ALL CONTAINERS (STOPPED AND NON STOPPED)

docker rm  -f $(docker ps -a -q)

jQuery make global variable

set the variable on window:

window.a_href = a_href;

Android draw a Horizontal line between views

In each parent LinearLayout for which you want dividers between components, add android:divider="?android:dividerHorizontal" or android:divider="?android:dividerVertical.

Choose appropriate between them as per orientation of your LinearLayout.

Till I know, this resource style is added from Android 4.3.

Large WCF web service request failing with (400) HTTP Bad Request

In my case, it was not working even after trying all solutions and setting all limits to max. In last I found out that a Microsoft IIS filtering module Url Scan 3.1 was installed on IIS/website, which have it's own limit to reject incoming requests based on content size and return "404 Not found page".

It's limit can be updated in %windir%\System32\inetsrv\urlscan\UrlScan.ini file by setting MaxAllowedContentLength to the required value.

For eg. following will allow upto 300 mb requests

MaxAllowedContentLength=314572800

Hope it will help someone!

How to get StackPanel's children to fill maximum space downward?

The reason that this is happening is because the stack panel measures every child element with positive infinity as the constraint for the axis that it is stacking elements along. The child controls have to return how big they want to be (positive infinity is not a valid return from the MeasureOverride in either axis) so they return the smallest size where everything will fit. They have no way of knowing how much space they really have to fill.

If your view doesn’t need to have a scrolling feature and the answer above doesn't suit your needs, I would suggest implement your own panel. You can probably derive straight from StackPanel and then all you will need to do is change the ArrangeOverride method so that it divides the remaining space up between its child elements (giving them each the same amount of extra space). Elements should render fine if they are given more space than they wanted, but if you give them less you will start to see glitches.

If you want to be able to scroll the whole thing then I am afraid things will be quite a bit more difficult, because the ScrollViewer gives you an infinite amount of space to work with which will put you in the same position as the child elements were originally. In this situation you might want to create a new property on your new panel which lets you specify the viewport size, you should be able to bind this to the ScrollViewer’s size. Ideally you would implement IScrollInfo, but that starts to get complicated if you are going to implement all of it properly.

How to handle change text of span

Span does not have 'change' event by default. But you can add this event manually.

Listen to the change event of span.

$("#span1").on('change',function(){
     //Do calculation and change value of other span2,span3 here
     $("#span2").text('calculated value');
});

And wherever you change the text in span1. Trigger the change event manually.

$("#span1").text('test').trigger('change'); 

How to save a list as numpy array in python?

You can use numpy.asarray, for example to convert a list into an array:

>>> a = [1, 2]
>>> np.asarray(a)
array([1, 2])

Proper way to get page content

A simple, fast way to get the content by id :

echo get_post_field('post_content', $id);

And if you want to get the content formatted :

echo apply_filters('the_content', get_post_field('post_content', $id));

Works with pages, posts & custom posts.

How to Flatten a Multidimensional Array?

If you have an array of objects and want to flatten it with a node, just use this function:

function objectArray_flatten($array,$childField) {
    $result = array();
    foreach ($array as $node)
    {
        $result[] = $node;
        if(isset($node->$childField))
        {
            $result = array_merge(
                $result, 
                objectArray_flatten($node->$childField,$childField)
            );
            unset($node->$childField);
        }

    }
    return $result;
}

CSS to hide INPUT BUTTON value text

This following has worked best for me:

HTML:

<input type="submit"/>

CSS:

input[type=submit] {
    background: url(http://yourURLhere) no-repeat;
    border: 0;
    display: block;
    font-size:0;
    height: 38px;
    width: 171px;
}

If you don't set value on your <input type="submit"/> it will place the default text "Submit" inside your button. SO, just set the font-size: 0; on your submit and then make sure you set a height and width for your input type so that your image will display. DON'T forget media queries for your submit if you need them, for example:

CSS:

@media (min-width:600px) {
  input[type=submit] {
    width:200px;
    height: 44px;
  }
}

This means when the screen is at exactly 600px wide or greater the button will change it's dimensions

Access camera from a browser

    <style type="text/css">
        #container {
            margin: 0px auto;
            width: 500px;
            height: 375px;
            border: 10px #333 solid;
        }

        #videoElement {
          width: 500px;
          height: 375px;
          background-color: #777;
        }
    </style>    
<div id="container">
            <video autoplay="true" id="videoElement"></video>
        </div>
        <script type="text/javascript">
          var video = document.querySelector("#videoElement");
          navigator.getUserMedia = navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia||navigator.oGetUserMedia;
    
          if(navigator.getUserMedia) {
            navigator.getUserMedia({video:true}, handleVideo, videoError);
          }
    
          function handleVideo(stream) {
            video.srcObject=stream;
            video.play();
          }
    
          function videoError(e) {
    
          }
        </script>

byte[] to file in Java

Use Apache Commons IO

FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)

Or, if you insist on making work for yourself...

try (FileOutputStream fos = new FileOutputStream("pathname")) {
   fos.write(myByteArray);
   //fos.close(); There is no more need for this line since you had created the instance of "fos" inside the try. And this will automatically close the OutputStream
}

"Unmappable character for encoding UTF-8" error

I'm in the process of setting up a CI build server on a Linux box for a legacy system started in 2000. There is a section that generates a PDF that contains non-UTF8 characters. We are in the final steps of a release, so I cannot replace the characters giving me grief, yet for Dilbertesque reasons, I cannot wait a week to solve this issue after the release. Fortunately, the "javac" command in Ant has an "encoding" parameter.

 <javac destdir="${classes.dir}" classpathref="production-classpath" debug="on"
     includeantruntime="false" source="${java.level}" target="${java.level}"

     encoding="iso-8859-1">

     <src path="${production.dir}" />
 </javac>

How to close off a Git Branch?

Yes, just delete the branch by running git push origin :branchname. To fix a new issue later, branch off from master again.

Select from one table where not in another

To expand on Johan's answer, if the part_num column in the sub-select can contain null values then the query will break.

To correct this, add a null check...

SELECT pm.id FROM r2r.partmaster pm
WHERE pm.id NOT IN 
      (SELECT pd.part_num FROM wpsapi4.product_details pd 
                  where pd.part_num is not null)
  • Sorry but I couldn't add a comment as I don't have the rep!

how to remove new lines and returns from php string?

Replace a string :

$str = str_replace("\n", '', $str);

u using also like, (%n, %t, All Special characters, numbers, char,. etc)

which means any thing u can replace in a string.

How to count the NaN values in a column in pandas DataFrame

One solution is finding out null value rows and converting them into dataframe and then checking the length of the new dataframe.-

nan_rows = df[df['column_name'].isnull()]
print(len(nan_rows))

Cloud Firestore collection count

Be careful counting number of documents for large collections. It is a little bit complex with firestore database if you want to have a precalculated counter for every collection.

Code like this doesn't work in this case:

export const customerCounterListener = 
    functions.firestore.document('customers/{customerId}')
    .onWrite((change, context) => {

    // on create
    if (!change.before.exists && change.after.exists) {
        return firestore
                 .collection('metadatas')
                 .doc('customers')
                 .get()
                 .then(docSnap =>
                     docSnap.ref.set({
                         count: docSnap.data().count + 1
                     }))
    // on delete
    } else if (change.before.exists && !change.after.exists) {
        return firestore
                 .collection('metadatas')
                 .doc('customers')
                 .get()
                 .then(docSnap =>
                     docSnap.ref.set({
                         count: docSnap.data().count - 1
                     }))
    }

    return null;
});

The reason is because every cloud firestore trigger has to be idempotent, as firestore documentation say: https://firebase.google.com/docs/functions/firestore-events#limitations_and_guarantees

Solution

So, in order to prevent multiple executions of your code, you need to manage with events and transactions. This is my particular way to handle large collection counters:

const executeOnce = (change, context, task) => {
    const eventRef = firestore.collection('events').doc(context.eventId);

    return firestore.runTransaction(t =>
        t
         .get(eventRef)
         .then(docSnap => (docSnap.exists ? null : task(t)))
         .then(() => t.set(eventRef, { processed: true }))
    );
};

const documentCounter = collectionName => (change, context) =>
    executeOnce(change, context, t => {
        // on create
        if (!change.before.exists && change.after.exists) {
            return t
                    .get(firestore.collection('metadatas')
                    .doc(collectionName))
                    .then(docSnap =>
                        t.set(docSnap.ref, {
                            count: ((docSnap.data() && docSnap.data().count) || 0) + 1
                        }));
        // on delete
        } else if (change.before.exists && !change.after.exists) {
            return t
                     .get(firestore.collection('metadatas')
                     .doc(collectionName))
                     .then(docSnap =>
                        t.set(docSnap.ref, {
                            count: docSnap.data().count - 1
                        }));
        }

        return null;
    });

Use cases here:

/**
 * Count documents in articles collection.
 */
exports.articlesCounter = functions.firestore
    .document('articles/{id}')
    .onWrite(documentCounter('articles'));

/**
 * Count documents in customers collection.
 */
exports.customersCounter = functions.firestore
    .document('customers/{id}')
    .onWrite(documentCounter('customers'));

As you can see, the key to prevent multiple execution is the property called eventId in the context object. If the function has been handled many times for the same event, the event id will be the same in all cases. Unfortunately, you must have "events" collection in your database.

Can Android Studio be used to run standard Java projects?

Tested in Android Studio 0.8.14:
I was able to get a standard project running with minimal steps in this way:

  • In an open Android Studio project, click File > New Module.
  • Click More Modules > Java Library > Next, then fill in whatever you prefer for the names.
  • A new module will appear as a folder on the same level as your "app" folder in the Project Structure. Open it and open the new Java class file.

    You can then add your code, and choose Build > Run 'YourClassName'. Presto, your code is running with no Android device!

  • How do I parse a string with a decimal point to a double?

    The below is less efficient, but I use this logic. This is valid only if you have two digits after decimal point.

    double val;
    
    if (temp.Text.Split('.').Length > 1)
    {
        val = double.Parse(temp.Text.Split('.')[0]);
    
        if (temp.Text.Split('.')[1].Length == 1)
            val += (0.1 * double.Parse(temp.Text.Split('.')[1]));
        else
            val += (0.01 * double.Parse(temp.Text.Split('.')[1]));
    }
    else
        val = double.Parse(RR(temp.Text));
    

    PostgreSQL: How to change PostgreSQL user password?

    You can and should have the users's password encrypted:

    ALTER USER username WITH ENCRYPTED PASSWORD 'password';
    

    How to clear the Entry widget after a button is pressed in Tkinter?

    After poking around a bit through the Introduction to Tkinter, I came up with the code below, which doesn't do anything except display a text field and clear it when the "Clear text" button is pushed:

    import tkinter as tk
    
    class App(tk.Frame):
        def __init__(self, master):
            tk.Frame.__init__(self, master, height=42, width=42)
            self.entry = tk.Entry(self)
            self.entry.focus()
            self.entry.pack()
            self.clear_button = tk.Button(self, text="Clear text", command=self.clear_text)
            self.clear_button.pack()
    
        def clear_text(self):
            self.entry.delete(0, 'end')
    
    def main():
        root = tk.Tk()
        App(root).pack(expand=True, fill='both')
        root.mainloop()
    
    if __name__ == "__main__":
        main()
    

    Get size of a View in React Native

    You can directly use the Dimensions module and calc your views sizes. Actually, Dimensions give to you the main window sizes.

    import { Dimensions } from 'Dimensions';
    
    Dimensions.get('window').height;
    Dimensions.get('window').width;
    

    Hope to help you!

    Update: Today using native StyleSheet with Flex arranging on your views help to write clean code with elegant layout solutions in wide cases instead computing your view sizes...

    Although building a custom grid components, which responds to main window resize events, could produce a good solution in simple widget components

    How can I run PowerShell with the .NET 4 runtime?

    If you only need to execute a single command, script block, or script file in .NET 4, try using Activation Configuration Files from .NET 4 to start only a single instance of PowerShell using version 4 of the CLR.

    Full details:

    http://blog.codeassassin.com/2011/03/23/executing-individual-powershell-commands-using-net-4/

    An example PowerShell module:

    https://gist.github.com/882528

    android.content.res.Resources$NotFoundException: String resource ID #0x0

    The evaluated value for settext was integer so it went to see a resource attached to it but it was not found, you wanted to set text so it should be string so convert integer into string by attaching .toStringe or String.valueOf(int) will solve your problem!

    How to backup MySQL database in PHP?

    From the answer of @DevWL, I got "Undefined offset ..." at

    if ($j<($num_fields-1)) { $data.= ','; }
    

    I made some changes to:

    • preserve relationships (foreign keys)
    • use Transactions
    • remove the uneedy $num_fields

    class DBbackup {
     public $suffix;
     public $dirs;
     protected $dbInstance;
     public function __construct() {
       try{
        $this->dbInstance = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, 
        $username, $password);
      } catch(Exception $e) {
        die("Error ".$e->getMessage());
      }
       $this->suffix = date('Ymd_His');
     }
    
     public function backup($tables = '*'){
       $output = "-- database backup - ".date('Y-m-d H:i:s').PHP_EOL;
       $output .= "SET NAMES utf8;".PHP_EOL;
       $output .= "SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';".PHP_EOL;
       $output .= "SET foreign_key_checks = 0;".PHP_EOL;
       $output .= "SET AUTOCOMMIT = 0;".PHP_EOL;
       $output .= "START TRANSACTION;".PHP_EOL;
       //get all table names
       if($tables == '*') {
         $tables = [];
         $query = $this->dbInstance->prepare('SHOW TABLES');
         $query->execute();
         while($row = $query->fetch(PDO::FETCH_NUM)) {
           $tables[] = $row[0];
         }
         $query->closeCursor();
       }
       else {
         $tables = is_array($tables) ? $tables : explode(',',$tables);
       }
    
       foreach($tables as $table) {
    
         $query = $this->dbInstance->prepare("SELECT * FROM `$table`");
         $query->execute();
         $output .= "DROP TABLE IF EXISTS `$table`;".PHP_EOL;
    
         $query2 = $this->dbInstance->prepare("SHOW CREATE TABLE `$table`");
         $query2->execute();
         $row2 = $query2->fetch(PDO::FETCH_NUM);
         $query2->closeCursor();
         $output .= PHP_EOL.$row2[1].";".PHP_EOL;
    
           while($row = $query->fetch(PDO::FETCH_NUM)) {
             $output .= "INSERT INTO `$table` VALUES(";
             for($j=0; $j<count($row); $j++) {
               $row[$j] = addslashes($row[$j]);
               $row[$j] = str_replace("\n","\\n",$row[$j]);
               if (isset($row[$j]))
                 $output .= "'".$row[$j]."'";
               else $output .= "''";
               if ($j<(count($row)-1))
                $output .= ',';
             }
             $output .= ");".PHP_EOL;
           }
         }
         $output .= PHP_EOL.PHP_EOL;
    
       $output .= "COMMIT;";
       //save filename
    
       $filename = 'db_backup_'.$this->suffix.'.sql';
       $this->writeUTF8filename($filename,$output);
     }
    
    
     private function writeUTF8filename($fn,$c){  /* save as utf8 encoding */
       $f=fopen($fn,"w+");
       # Now UTF-8 - Add byte order mark
       fwrite($f, pack("CCC",0xef,0xbb,0xbf));
       fwrite($f,$c);
       fclose($f);
     }
    

    }

    And usage example:

    $Backup = new DBbackup();
    $Backup->backup();
    

    This works great on MySQL 10.1.34-MariaDB , PHP : 7.2.7

    rake assets:precompile RAILS_ENV=production not working as required

    Replace

    rake assets:precompile RAILS_ENV=production
    

    with

    rake assets:precompile (RAILS_ENV=production bundle exec rake assets:precompile is the exact rake task)

    Since precompilation is done in production mode only, no need to explicitly specify the environment.

    Update:

    Try adding the below line to your Gemfile:

    group :assets do
      gem 'therubyracer'
      gem 'sass-rails', "  ~> 3.1.0"
      gem 'coffee-rails', "~> 3.1.0"
      gem 'uglifier'
    end
    

    Then run bundle install.

    Hope it will work :)

    How can I hide select options with JavaScript? (Cross browser)

    I thought I was bright ;-)

    In CSS:

    option:disabled {display:none;}
    

    In Firefox and Chrome, a select with only the enabled options were created. Nice.

    In IE, the enabled options were shown, the disabled where just blank lines, in their original location. Bad.

    In Edge, the enabled options shown at top, followed by blank lines for disabled options. Acceptable.

    Typescript empty object for a typed variable

    Really depends on what you're trying to do. Types are documentation in typescript, so you want to show intention about how this thing is supposed to be used when you're creating the type.

    Option 1: If Users might have some but not all of the attributes during their lifetime

    Make all attributes optional

    type User = {
      attr0?: number
      attr1?: string
    }
    

    Option 2: If variables containing Users may begin null

    type User = {
    ...
    }
    let u1: User = null;
    

    Though, really, here if the point is to declare the User object before it can be known what will be assigned to it, you probably want to do let u1:User without any assignment.

    Option 3: What you probably want

    Really, the premise of typescript is to make sure that you are conforming to the mental model you outline in types in order to avoid making mistakes. If you want to add things to an object one-by-one, this is a habit that TypeScript is trying to get you not to do.

    More likely, you want to make some local variables, then assign to the User-containing variable when it's ready to be a full-on User. That way you'll never be left with a partially-formed User. Those things are gross.

    let attr1: number = ...
    let attr2: string = ...
    let user1: User = {
      attr1: attr1,
      attr2: attr2
    }
    

    How to set custom header in Volley Request

    That is my code, dont forget = object: if don't put don't works

    val queue = Volley.newRequestQueue(this)
            val url = "http://35.237.133.137:8080/lamarrullaWS/rest/lamarrullaAPI"
            // Request a string response from the provided URL.
            val jsonObjectRequest = object: JsonObjectRequest(Request.Method.GET, url, null,
                    Response.Listener { response ->
                        txtPrueba.text = "Response: %s".format(response.toString())
                    },
                    Response.ErrorListener { txtPrueba.text = "That didn't work!" }
            )
            {
                @Throws(AuthFailureError::class)
                override fun getHeaders(): Map<String, String> {
                    val headers = HashMap<String, String>()
                    headers.put("Content-Type", "application/json")
                    return headers
                }
            }
            queue.add(jsonObjectRequest)
    

    Android: Creating a Circular TextView?

    The typical solution is to define the shape and use it as background but as the number of digits varies it's no more a perfect circle, it looks like a rectangle with round edges or Oval. So I have developed this solution, it's working great. Hope it will help someone.

    Circular Text View

    Here is the code of custom TextView

    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.util.AttributeSet;
    import android.widget.TextView;
    
    public class CircularTextView extends TextView
    {
    private float strokeWidth;
    int strokeColor,solidColor;
    
    public CircularTextView(Context context) {
        super(context);
    }
    
    public CircularTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    
    public CircularTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    
    
    @Override
    public void draw(Canvas canvas) {
    
        Paint circlePaint = new Paint();
        circlePaint.setColor(solidColor);
        circlePaint.setFlags(Paint.ANTI_ALIAS_FLAG);
    
        Paint strokePaint = new Paint();
        strokePaint.setColor(strokeColor);
        strokePaint.setFlags(Paint.ANTI_ALIAS_FLAG);
    
        int  h = this.getHeight();
        int  w = this.getWidth();
    
        int diameter = ((h > w) ? h : w);
        int radius = diameter/2;
    
        this.setHeight(diameter);
        this.setWidth(diameter);
    
        canvas.drawCircle(diameter / 2 , diameter / 2, radius, strokePaint);
    
        canvas.drawCircle(diameter / 2, diameter / 2, radius-strokeWidth, circlePaint);
    
        super.draw(canvas);
    }
    
    public void setStrokeWidth(int dp)
    {
        float scale = getContext().getResources().getDisplayMetrics().density;
        strokeWidth = dp*scale;
    
    }
    
    public void setStrokeColor(String color)
    {
        strokeColor = Color.parseColor(color);
    }
    
    public void setSolidColor(String color)
    {
        solidColor = Color.parseColor(color);
    
    }
    }
    

    Then in your XML, give some padding and make sure its gravity is center

    <com.app.tot.customtextview.CircularTextView
            android:id="@+id/circularTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="11"
            android:gravity="center"
            android:padding="3dp"/>
    

    And you can set the stroke width

    circularTextView.setStrokeWidth(1);
    circularTextView.setStrokeColor("#ffffff");
    circularTextView.setSolidColor("#000000");
    

    How can I manually generate a .pyc file from a .py file

    It's been a while since I last used Python, but I believe you can use py_compile:

    import py_compile
    py_compile.compile("file.py")
    

    How do I generate a random int number?

    For strong random seed I always use CryptoRNG and not Time.

    using System;
    using System.Security.Cryptography;
    
    public class Program
    {
        public static void Main()
        {
            var random = new Random(GetSeed());
            Console.WriteLine(random.Next());
        }
    
        public static int GetSeed() 
        {
            using (var rng = new RNGCryptoServiceProvider())
            {
                var intBytes = new byte[4];
                rng.GetBytes(intBytes);
                return BitConverter.ToInt32(intBytes, 0);
            }
        }
    }
    

    How to unset (remove) a collection element after fetching it?

    You would want to use ->forget()

    $collection->forget($key);
    

    Link to the forget method documentation

    number of values in a list greater than a certain number

    You can create a smaller intermediate result like this:

    >>> j = [4, 5, 6, 7, 1, 3, 7, 5]
    >>> len([1 for i in j if i > 5])
    3
    

    Where is the default log location for SharePoint/MOSS?

    For Sharepoint 2007

    C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\LOGS

    Android Studio don't generate R.java for my import project

    I had this problem after update gradle...

    There are several reasons that causes the projectenter image description here not to be built:

    1-Unknown error in drawable or xml files

    2-Update gradle or libraries and etc ...

    Solution :

    1-Clean and rebuild project

    2-Delete .idea and build folders in project file(shown in picture) then goto "File/Invalidate catch-restart"

    3-Roll back to previous gradle version and libraries.

    How to enable assembly bind failure logging (Fusion) in .NET

    If you already have logging enabled and you still get this error on Windows 7 64 bit, try this in IIS 7.5:

    1. Create a new application pool

    2. Go to the Advanced Settings of this application pool

    3. Set the Enable 32-Bit Application to True

    4. Point your web application to use this new pool

    Warning - Build path specifies execution environment J2SE-1.4

    In eclipse preferences, go to Java->Installed JREs->Execution Environment and set up a JRE Execution Environment for J2SE-1.4

    How to fix a locale setting warning from Perl

    I am now using this:

    $ cat /etc/environment
    ...
    LC_ALL=en_US.UTF-8
    LANG=en_US.UTF-8
    

    Then log out of SSH session and log in again.

    Old answer:

    Only this helped me:

    $ locale
    locale: Cannot set LC_ALL to default locale: No such file or directory
    LANG=en_US.UTF-8
    LANGUAGE=
    LC_CTYPE=en_US.UTF-8
    LC_NUMERIC=ru_RU.UTF-8
    LC_TIME=ru_RU.UTF-8
    LC_COLLATE="en_US.UTF-8"
    LC_MONETARY=ru_RU.UTF-8
    LC_MESSAGES="en_US.UTF-8"
    LC_PAPER=ru_RU.UTF-8
    LC_NAME=ru_RU.UTF-8
    LC_ADDRESS=ru_RU.UTF-8
    LC_TELEPHONE=ru_RU.UTF-8
    LC_MEASUREMENT=ru_RU.UTF-8
    LC_IDENTIFICATION=ru_RU.UTF-8
    LC_ALL=
    
    $ sudo su
    
    # export LANGUAGE=en_US.UTF-8
    # export LANG=en_US.UTF-8
    # export LC_ALL=en_US.UTF-8
    
    # locale-gen en_US.UTF-8
    Generating locales...
      en_US.UTF-8... up-to-date
    Generation complete.
    
    # dpkg-reconfigure locales
    Generating locales...
      en_AG.UTF-8... done
      en_AU.UTF-8... done
      en_BW.UTF-8... done
      en_CA.UTF-8... done
      en_DK.UTF-8... done
      en_GB.UTF-8... done
      en_HK.UTF-8... done
      en_IE.UTF-8... done
      en_IN.UTF-8... done
      en_NG.UTF-8... done
      en_NZ.UTF-8... done
      en_PH.UTF-8... done
      en_SG.UTF-8... done
      en_US.UTF-8... up-to-date
      en_ZA.UTF-8... done
      en_ZM.UTF-8... done
      en_ZW.UTF-8... done
    Generation complete.
    
    # exit
    
    $ locale
    LANG=en_US.UTF-8
    LANGUAGE=en_US.UTF-8
    LC_CTYPE="en_US.UTF-8"
    LC_NUMERIC="en_US.UTF-8"
    LC_TIME="en_US.UTF-8"
    LC_COLLATE="en_US.UTF-8"
    LC_MONETARY="en_US.UTF-8"
    LC_MESSAGES="en_US.UTF-8"
    LC_PAPER="en_US.UTF-8"
    LC_NAME="en_US.UTF-8"
    LC_ADDRESS="en_US.UTF-8"
    LC_TELEPHONE="en_US.UTF-8"
    LC_MEASUREMENT="en_US.UTF-8"
    LC_IDENTIFICATION="en_US.UTF-8"
    LC_ALL=en_US.UTF-8
    

    How do I empty an input value with jQuery?

    A better way is:

    $("#element").val(null);
    

    How can I create a dynamic button click event on a dynamic button?

    Button button = new Button();
    button.Click += (s,e) => { your code; };
    //button.Click += new EventHandler(button_Click);
    container.Controls.Add(button);
    
    //protected void button_Click (object sender, EventArgs e) { }
    

    How to force uninstallation of windows service

    sc delete sericeName
    

    Just make sure the service is stopped before doing this. I have seen this work most times. There are times where I have seen windows get stuck on something and it insists on a reboot.

    How do I set up Vim autoindentation properly for editing Python files?

    for more advanced python editing consider installing the simplefold vim plugin. it allows you do advanced code folding using regular expressions. i use it to fold my class and method definitions for faster editing.

    How to map atan2() to degrees 0-360

    An alternative solution is to use the mod () function defined as:

    function mod(a, b) {return a - Math.floor (a / b) * b;}

    Then, with the following function, the angle between ini(x,y) and end(x,y) points is obtained. The angle is expressed in degrees normalized to [0, 360] deg. and North referencing 360 deg.

        function angleInDegrees(ini, end) {
            var radian = Math.atan2((end.y - ini.y), (end.x - ini.x));//radian [-PI,PI]
            return mod(radian * 180 / Math.PI + 90, 360);
        }
    

    IsNumeric function in c#

    public bool IsNumeric(string value)
    {
        return value.All(char.IsNumber);
    }
    

    SQL Server NOLOCK and joins

    Neither. You set the isolation level to READ UNCOMMITTED which is always better than giving individual lock hints. Or, better still, if you care about details like consistency, use snapshot isolation.

    jQuery: Wait/Delay 1 second without executing code

    $.delay is used to delay animations in a queue, not halt execution.

    Instead of using a while loop, you need to recursively call a method that performs the check every second using setTimeout:

    var check = function(){
        if(condition){
            // run when condition is met
        }
        else {
            setTimeout(check, 1000); // check again in a second
        }
    }
    
    check();
    

    setting system property

    System.setProperty("gate.home", "/some/directory");
    

    For more information, see:

    Why is 2 * (i * i) faster than 2 * i * i in Java?

    Byte codes: https://cs.nyu.edu/courses/fall00/V22.0201-001/jvm2.html Byte codes Viewer: https://github.com/Konloch/bytecode-viewer

    On my JDK (Windows 10 64 bit, 1.8.0_65-b17) I can reproduce and explain:

    public static void main(String[] args) {
        int repeat = 10;
        long A = 0;
        long B = 0;
        for (int i = 0; i < repeat; i++) {
            A += test();
            B += testB();
        }
    
        System.out.println(A / repeat + " ms");
        System.out.println(B / repeat + " ms");
    }
    
    
    private static long test() {
        int n = 0;
        for (int i = 0; i < 1000; i++) {
            n += multi(i);
        }
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            n += multi(i);
        }
        long ms = (System.currentTimeMillis() - startTime);
        System.out.println(ms + " ms A " + n);
        return ms;
    }
    
    
    private static long testB() {
        int n = 0;
        for (int i = 0; i < 1000; i++) {
            n += multiB(i);
        }
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            n += multiB(i);
        }
        long ms = (System.currentTimeMillis() - startTime);
        System.out.println(ms + " ms B " + n);
        return ms;
    }
    
    private static int multiB(int i) {
        return 2 * (i * i);
    }
    
    private static int multi(int i) {
        return 2 * i * i;
    }
    

    Output:

    ...
    405 ms A 785527736
    327 ms B 785527736
    404 ms A 785527736
    329 ms B 785527736
    404 ms A 785527736
    328 ms B 785527736
    404 ms A 785527736
    328 ms B 785527736
    410 ms
    333 ms
    

    So why? The byte code is this:

     private static multiB(int arg0) { // 2 * (i * i)
         <localVar:index=0, name=i , desc=I, sig=null, start=L1, end=L2>
    
         L1 {
             iconst_2
             iload0
             iload0
             imul
             imul
             ireturn
         }
         L2 {
         }
     }
    
     private static multi(int arg0) { // 2 * i * i
         <localVar:index=0, name=i , desc=I, sig=null, start=L1, end=L2>
    
         L1 {
             iconst_2
             iload0
             imul
             iload0
             imul
             ireturn
         }
         L2 {
         }
     }
    

    The difference being: With brackets (2 * (i * i)):

    • push const stack
    • push local on stack
    • push local on stack
    • multiply top of stack
    • multiply top of stack

    Without brackets (2 * i * i):

    • push const stack
    • push local on stack
    • multiply top of stack
    • push local on stack
    • multiply top of stack

    Loading all on the stack and then working back down is faster than switching between putting on the stack and operating on it.

    Property 'value' does not exist on type EventTarget in TypeScript

    add any type to event

    event: any
    

    example

    [element].addEvenListener('mousemove', (event: any) =>{
    //CODE//
    } )
    

    what happens is that typescript adds event as Event type and for some reason it doesn't recognize some properties. Adding it of type any no longer exists this problem, this works for any document.[Property]

    Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in

    You have a JSON string, not an object. Tell jQuery that you expect a JSON response and it will parse it for you. Either use $.getJSON instead of $.get, or pass the dataType argument to $.get:

    $.get(
        'index.php?r=admin/post/ajax',
        {"parentCatId":parentCatId},
        function(data){                     
            $.each(data, function(key, value){
                console.log(key + ":" + value)
            })
        },
        'json'
    );
    

    Find and Replace string in all files recursive using grep and sed

    As @Didier said, you can change your delimiter to something other than /:

    grep -rl $oldstring /path/to/folder | xargs sed -i s@$oldstring@$newstring@g
    

    Excel formula to get cell color

    As commented, just in case the link I posted there broke, try this:

    Add a Name(any valid name) in Excel's Name Manager under Formula tab in the Ribbon.
    Then assign a formula using GET.CELL function.

    =GET.CELL(63,INDIRECT("rc",FALSE))

    63 stands for backcolor.
    Let's say we name it Background so in any cell with color type:

    =Background

    Result:
    enter image description here

    Notice that Cells A2, A3 and A4 returns 3, 4, and 5 respectively which equates to the cells background color index. HTH.
    BTW, here's a link on Excel's Color Index

    Simple int to char[] conversion

    Use this. Beware of i's larger than 9, as these will require a char array with more than 2 elements to avoid a buffer overrun.

    char c[2];
    int i=1;
    sprintf(c, "%d", i);
    

    Run php script as daemon process

    you can check pm2 here is, http://pm2.keymetrics.io/

    create a ssh file, such as worker.sh put into your php script that you will deal with.

    worker.sh

    php /path/myscript.php
    

    daemon start

    pm2 start worker.sh
    

    Cheers, that is it.

    error: pathspec 'test-branch' did not match any file(s) known to git

    This error can also appear if your git branch is not correct even though case sensitive wise. In my case I was getting this error as actual branch name was "CORE-something" but I was taking pull like "core-something".

    How to add an extra column to a NumPy array

    I liked this:

    new_column = np.zeros((len(a), 1))
    b = np.block([a, new_column])
    

    Set keyboard caret position in html textbox

    function SetCaretEnd(tID) {
        tID += "";
        if (!tID.startsWith("#")) { tID = "#" + tID; }
        $(tID).focus();
        var t = $(tID).val();
        if (t.length == 0) { return; }
        $(tID).val("");
        $(tID).val(t);
        $(tID).scrollTop($(tID)[0].scrollHeight); }
    

    How to redirect DNS to different ports

    Use SRV record. If you are using freenom go to cloudflare.com and connect your freenom server to cloudflare (freenom doesn't support srv records) use _minecraft as service tcp as protocol and your ip as target (you need "a" record to use your ip. I recommend not using your "Arboristal.com" domain as "a" record. If you use "Arboristal.com" as your "a" record hackers can go in your router settings and hack your network) priority - 0, weight - 0 and port - the port you want to use.(i know this because i was in the same situation) Do the same for any domain provider. (sorry if i made spell mistakes)

    how to change text in Android TextView

    per your advice, i am using handle and runnables to switch/change the content of the TextView using a "timer". for some reason, when running, the app always skips the second step ("Step Two: fry egg"), and only show the last (third) step ("Step three: serve egg").

    TextView t; 
    private String sText;
    
    private Handler mHandler = new Handler();
    
    private Runnable mWaitRunnable = new Runnable() {
        public void run() {
            t.setText(sText);
        }
    };
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        setContentView(R.layout.main);
    
        mMonster = BitmapFactory.decodeResource(getResources(),
                R.drawable.monster1);
    
        t=new TextView(this); 
        t=(TextView)findViewById(R.id.TextView01); 
    
        sText = "Step One: unpack egg";
        t.setText(sText);
    
        sText = "Step Two: fry egg";        
        mHandler.postDelayed(mWaitRunnable, 3000);
    
        sText = "Step three: serve egg";
        mHandler.postDelayed(mWaitRunnable, 4000);      
        ...
    }
    

    How to get the Mongo database specified in connection string in C#

    Update:

    MongoServer.Create is obsolete now (thanks to @aknuds1). Instead this use following code:

    var _server = new MongoClient(connectionString).GetServer();
    

    It's easy. You should first take database name from connection string and then get database by name. Complete example:

    var connectionString = "mongodb://localhost:27020/mydb";
    
    //take database name from connection string
    var _databaseName = MongoUrl.Create(connectionString).DatabaseName;
    var _server = MongoServer.Create(connectionString);
    
    //and then get database by database name:
    _server.GetDatabase(_databaseName);
    

    Important: If your database and auth database are different, you can add a authSource= query parameter to specify a different auth database. (thank you to @chrisdrobison)

    From docs:

    NOTE If you are using the database segment as the initial database to use, but the username and password specified are defined in a different database, you can use the authSource option to specify the database in which the credential is defined. For example, mongodb://user:pass@hostname/db1?authSource=userDb would authenticate the credential against the userDb database instead of db1.

    Iterate over values of object

    You could use underscore.js and the each function:

    _.each({key1: "value1", key2: "value2"}, function(value) {
      console.log(value);
    });
    

    How to declare array of zeros in python (or an array of a certain size)

    Just for completeness: To declare a multidimensional list of zeros in python you have to use a list comprehension like this:

    buckets = [[0 for col in range(5)] for row in range(10)]
    

    to avoid reference sharing between the rows.

    This looks more clumsy than chester1000's code, but is essential if the values are supposed to be changed later. See the Python FAQ for more details.

    How to create a private class method?

    ExiRe wrote:

    Such behavior of ruby is really frustrating. I mean if you move to private section self.method then it is NOT private. But if you move it to class << self then it suddenly works. It is just disgusting.

    Confusing it probably is, frustrating it may well be, but disgusting it is definitely not.

    It makes perfect sense once you understand Ruby's object model and the corresponding method lookup flow, especially when taking into consideration that private is NOT an access/visibility modifier, but actually a method call (with the class as its recipient) as discussed here... there's no such thing as "a private section" in Ruby.

    To define private instance methods, you call private on the instance's class to set the default visibility for subsequently defined methods to private... and hence it makes perfect sense to define private class methods by calling private on the class's class, ie. its metaclass.

    Other mainstream, self-proclaimed OO languages may give you a less confusing syntax, but you definitely trade that off against a confusing and less consistent (inconsistent?) object model without the power of Ruby's metaprogramming facilities.

    How to change Maven local repository in eclipse

    In general, these answer the question: How to change your user settings file? But the question I wanted answered was how to change my local maven repository location. The answer is that you have to edit settings.xml. If the file does not exist, you have to create it. You set or change the location of the file at Window > Preferences > Maven > User Settings. It's the User Settings entry at

    Maven User Settings dialog

    It's the second file input; the first with information in it.

    If it's not clear, [redacted] should be replaced with the local file path to your .m2 folder.

    If you click the "open file" link, it opens the settings.xml file for editing in Eclipse.

    If you have no settings.xml file yet, the following will set the local repository to the Windows 10 default value for a user named mdfst13:

    <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                                  https://maven.apache.org/xsd/settings-1.0.0.xsd">
    
      <localRepository>C:\Users\mdfst13\.m2\repository</localRepository>
    </settings>
    

    You should set this to a value appropriate to your system. I haven't tested it, but I suspect that in Linux, the default value would be /home/mdfst13/.m2/repository. And of course, you probably don't want to set it to the default value. If you are reading this, you probably want to set it to some other value. You could just delete it if you wanted the default.

    Credit to this comment by @ejaenv for the name of the element in the settings file: <localRepository>. See Maven — Settings Reference for more information.

    Credit to @Ajinkya's answer for specifying the location of the User Settings value in Eclipse Photon.

    If you already have a settings.xml file, you should merge this into your existing file. I.e. <settings and <localRepository> should only appear once in the file, and you probably want to retain any settings already there. Or to say that another way, edit any existing local repository entry if it exists or just add that line to the file if it doesn't.

    I had to restart Eclipse for it to load data into the new repository. Neither "Update Settings" nor "Reindex" was sufficient.

    Dynamically create and submit form

    Using Jquery

    $('<form/>', { action: url, method: 'POST' }).append(
        $('<input>', {type: 'hidden', id: 'id_field_1', name: 'name_field_1', value: val_field_1}),
        $('<input>', {type: 'hidden', id: 'id_field_2', name: 'name_field_2', value: val_field_2}),
    ).appendTo('body').submit();
    

    Width equal to content

    set width attribute as: width: fit-content

    demo: http://jsfiddle.net/rvrjp7/pyq3C/114

    What's the easiest way to install a missing Perl module?

    Try App::cpanminus:

    # cpanm Chocolate::Belgian
    

    It's great for just getting stuff installed. It provides none of the more complex functionality of CPAN or CPANPLUS, so it's easy to use, provided you know which module you want to install. If you haven't already got cpanminus, just type:

    # cpan App::cpanminus
    

    to install it.

    It is also possible to install it without using cpan at all. The basic bootstrap procedure is,

    curl -L http://cpanmin.us | perl - --sudo App::cpanminus
    

    For more information go to the App::cpanminus page and look at the section on installation.

    With CSS, how do I make an image span the full width of the page as a background image?

    If you're hoping to use background-image: url(...);, I don't think you can. However, if you want to play with layering, you can do something like this:

    <img class="bg" src="..." />
    

    And then some CSS:

    .bg
    {
      width: 100%;
      z-index: 0;
    }
    

    You can now layer content above the stretched image by playing with z-indexes and such. One quick note, the image can't be contained in any other elements for the width: 100%; to apply to the whole page.

    Here's a quick demo if you can't rely on background-size: http://jsfiddle.net/bB3Uc/

    How to make a PHP SOAP call using the SoapClient class

    You need a multi-dimensional array, you can try the following:

    $params = array(
       array(
          "id" => 100,
          "name" => "John",
       ),
       "Barrel of Oil",
       500
    );
    

    in PHP an array is a structure and is very flexible. Normally with soap calls I use an XML wrapper so unsure if it will work.

    EDIT:

    What you may want to try is creating a json query to send or using that to create a xml buy sort of following what is on this page: http://onwebdev.blogspot.com/2011/08/php-converting-rss-to-json.html

    How to set all elements of an array to zero or any same value?

    If your array has static storage allocation, it is default initialized to zero. However, if the array has automatic storage allocation, then you can simply initialize all its elements to zero using an array initializer list which contains a zero.

    // function scope
    // this initializes all elements to 0
    int arr[4] = {0};
    // equivalent to
    int arr[4] = {0, 0, 0, 0};
    
    // file scope
    int arr[4];
    // equivalent to
    int arr[4] = {0};
    

    Please note that there is no standard way to initialize the elements of an array to a value other than zero using an initializer list which contains a single element (the value). You must explicitly initialize all elements of the array using the initializer list.

    // initialize all elements to 4
    int arr[4] = {4, 4, 4, 4};
    // equivalent to
    int arr[] = {4, 4, 4, 4};
    

    How to vertically center a <span> inside a div?

    Quick answer for single line span

    Make the child (in this case a span) the same line-height as the parent <div>'s height

    <div class="parent">
      <span class="child">Yes mom, I did my homework lol</span>
    </div>
    

    You should then add the CSS rules

    .parent { height: 20px; }
    .child { line-height: 20px; vertical-align: middle; }
    



    Or you can target it with a child selector

    .parent { height: 20px; }
    .parent > span { line-height: 20px; vertical-align: middle; }
    

    Background on my own use of this

    I ran into this similar issue where I needed to vertically center items in a mobile menu. I made the div and spans inside the same line height. Note that this is for a meteor project and therefore not using inline css ;)

    HTML

    <div class="international">        
      <span class="intlFlag">
        {{flag}}        
      </span>
    
      <span class="intlCurrent">
        {{country}}
      </span>
    
      <span class="intlButton">
        <i class="fa fa-globe"></i>
      </span> 
    </div>
    

    CSS (option for multiple spans in a div)

    .international {
      height: 42px;
    }
    
    .international > span {
      line-height: 42px;
    }
    

    In this case if I just had one span I could have added the CSS rule directly to that span.

    CSS (option for one specific span)

    .intlFlag { line-height: 42px; }
    

    Here is how it displayed for me

    enter image description here

    Php, wait 5 seconds before executing an action

    In https://www.php.net/manual/es/function.usleep.php

    <?php
    // Wait 2 seconds
    usleep(2000000);
    
    // if you need 5 seconds
    usleep(5000000);
    ?>
    

    Using the slash character in Git branch name

    Are you sure branch labs does not already exist (as in this thread)?

    You can't have both a file, and a directory with the same name.

    You're trying to get git to do basically this:

    % cd .git/refs/heads
    % ls -l
    total 0
    -rw-rw-r-- 1 jhe jhe 41 2009-11-14 23:51 labs
    -rw-rw-r-- 1 jhe jhe 41 2009-11-14 23:51 master
    % mkdir labs
    mkdir: cannot create directory 'labs': File exists
    

    You're getting the equivalent of the "cannot create directory" error.
    When you have a branch with slashes in it, it gets stored as a directory hierarchy under .git/refs/heads.

    Missing Authentication Token while accessing API Gateway?

    Found this in the docs:

    If the AWS_IAM authorization were used, you would sign the request using the Signature Version 4 protocols.

    Signing request with Signature Version 4


    You can also generate an SDK for your API.

    How to generate an SDK for an API in API Gateway

    Once you've generated the SDK for the platform of your choice, step 6 mentions that if you're using AWS credentials, the request to the API will be signed:

    1. To initialize the API Gateway-generated SDK with AWS credentials, use code similar to the following. If you use AWS credentials, all requests to the API will be signed. This means you must set the appropriate CORS Accept headers for each request:

      var apigClient = apigClientFactory.newClient({
        accessKey: 'ACCESS_KEY',
        secretKey: 'SECRET_KEY',
      });
      

    What is HTTP "Host" header?

    I would always recommend going to the authoritative source when trying to understand the meaning and purpose of HTTP headers.

    The "Host" header field in a request provides the host and port
    information from the target URI, enabling the origin server to
    distinguish among resources while servicing requests for multiple
    host names on a single IP address.

    https://tools.ietf.org/html/rfc7230#section-5.4

    UILabel Align Text to center

    In xamarin ios suppose your label name is title then do the following

    title.TextAlignment = UITextAlignment.Center;
    

    Android textview usage as label and value

    You can use <LinearLayout> to group elements horizontaly. Also you should use style to set margins, background and other properties. This will allow you not to repeat code for every label you use. Here is an example:

    <LinearLayout
                        style="@style/FormItem"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal">
                    <TextView
                            style="@style/FormLabel"
                            android:layout_width="wrap_content"
                            android:layout_height="@dimen/default_element_height"
                            android:text="@string/name_label"
                            />
    
                    <EditText
                            style="@style/FormText.Editable"
                            android:id="@+id/cardholderName"
                            android:layout_width="wrap_content"
                            android:layout_height="@dimen/default_element_height"
                            android:layout_weight="1"
                            android:gravity="right|center_vertical"
                            android:hint="@string/card_name_hint"
                            android:imeOptions="actionNext"
                            android:singleLine="true"
                            />
                </LinearLayout>
    

    Also you can create a custom view base on the layout above. Have you looked at Creating custom view ?

    How do I make a semi transparent background?

    Although dated, not one answer on this thread can be used universally. Using rgba to create transparent color masks - that doesn't exactly explain how to do so with background images.

    My solution works for background images or color backgrounds.

    _x000D_
    _x000D_
    #parent {_x000D_
        font-family: 'Open Sans Condensed', sans-serif;_x000D_
        font-size: 19px;_x000D_
        text-transform: uppercase;_x000D_
        border-radius: 50%;_x000D_
        margin: 20px auto;_x000D_
        width: 125px;_x000D_
        height: 125px;_x000D_
        background-color: #476172;_x000D_
        background-image: url('https://unsplash.it/200/300/?random');_x000D_
        line-height: 29px;_x000D_
        text-align:center;_x000D_
    }_x000D_
    _x000D_
    #content {_x000D_
        color: white;_x000D_
        height: 125px !important;_x000D_
        width: 125px !important;_x000D_
        display: table-cell;_x000D_
        border-radius: 50%;_x000D_
        vertical-align: middle;_x000D_
        background: rgba(0,0,0, .3);_x000D_
    }
    _x000D_
    <h1 id="parent"><a href="" id="content" title="content" rel="home">Example</a></h1>
    _x000D_
    _x000D_
    _x000D_

    What are the time complexities of various data structures?

    Arrays

    • Set, Check element at a particular index: O(1)
    • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
    • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
    • Similarly, Insert for arrays is basically Set as mentioned in the beginning

    ArrayList:

    • Add: Amortized O(1)
    • Remove: O(n)
    • Contains: O(n)
    • Size: O(1)

    Linked List:

    • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
    • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
    • Searching: O(n)

    Doubly-Linked List:

    • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
    • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
    • Searching: O(n)

    Stack:

    • Push: O(1)
    • Pop: O(1)
    • Top: O(1)
    • Search (Something like lookup, as a special operation): O(n) (I guess so)

    Queue/Deque/Circular Queue:

    • Insert: O(1)
    • Remove: O(1)
    • Size: O(1)

    Binary Search Tree:

    • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

    Red-Black Tree:

    • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

    Heap/PriorityQueue (min/max):

    • Find Min/Find Max: O(1)
    • Insert: O(log n)
    • Delete Min/Delete Max: O(log n)
    • Extract Min/Extract Max: O(log n)
    • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

    HashMap/Hashtable/HashSet:

    • Insert/Delete: O(1) amortized
    • Re-size/hash: O(n)
    • Contains: O(1)

    Print an integer in binary format in Java

    I think it's the simplest algorithm so far (for those who don't want to use built-in functions):

    public static String convertNumber(int a)  { 
                  StringBuilder sb=new StringBuilder();
                  sb.append(a & 1);
                  while ((a>>=1) != 0)  { 
                      sb.append(a & 1);
                   }
                  sb.append("b0");
                  return sb.reverse().toString();
      }
    

    Example:

    convertNumber(1) --> "0b1"

    convertNumber(5) --> "0b101"

    convertNumber(117) --> "0b1110101"

    How it works: while-loop moves a-number to the right (replacing the last bit with second-to-last, etc), gets the last bit's value and puts it in StringBuilder, repeats until there are no bits left (that's when a=0).

    Spring Resttemplate exception handling

    Another solution is the one described here at the end of this post by "enlian": http://springinpractice.com/2013/10/07/handling-json-error-object-responses-with-springs-resttemplate

    try{
         restTemplate.exchange(...)
    } catch(HttpStatusCodeException e){
         String errorpayload = e.getResponseBodyAsString();
         //do whatever you want
    } catch(RestClientException e){
         //no response payload, tell the user sth else 
    }
    

    How to use Python's pip to download and keep the zipped files for a package?

    In version 7.1.2 pip downloads the wheel of a package (if available) with the following:

    pip install package -d /path/to/downloaded/file
    

    The following downloads a source distribution:

    pip install package -d /path/to/downloaded/file --no-binary :all:
    

    These download the dependencies as well, if pip is aware of them (e.g., if pip show package lists them).


    Update

    As noted by Anton Khodak, pip download command is preferred since version 8. In the above examples this means that /path/to/downloaded/file needs to be given with option -d, so replacing install with download works.

    Of Countries and their Cities

    There are quite a few available.

    The following has database for 2,401,039 cities

    http://www.geodatasource.com/world-cities-database/free

    How do I view 'git diff' output with my preferred diff tool/ viewer?

    A short summary of the above great answers:

    git difftool --tool-help
    git config --global diff.tool <chosen tool>
    git config --global --add difftool.prompt false
    

    Then use it by typing (optionally specifying file name as well):

    git difftool
    

    Show MySQL host via SQL Command

    To get current host name :-

    select @@hostname;
    show variables where Variable_name like '%host%';
    

    To get hosts for all incoming requests :-

    select host from information_schema.processlist;
    

    Based on your last comment,
    I don't think you can resolve IP for the hostname using pure mysql function,
    as it require a network lookup, which could be taking long time.

    However, mysql document mention this :-

    resolveip google.com.sg
    

    docs :- http://dev.mysql.com/doc/refman/5.0/en/resolveip.html

    How to check the function's return value if true or false

    You don't need to call ValidateForm() twice, as you are above. You can just do

    if(!ValidateForm()){
    ..
    } else ...
    

    I think that will solve the issue as above it looks like your comparing true/false to the string equivalent 'false'.

    Where is the syntax for TypeScript comments documented?

    Future

    The TypeScript team, and other TypeScript involved teams, plan to create a standard formal TSDoc specification. The 1.0.0 draft hasn't been finalised yet: https://github.com/Microsoft/tsdoc#where-are-we-on-the-roadmap

    enter image description here

    Current

    TypeScript uses JSDoc. e.g.

    /** This is a description of the foo function. */
    function foo() {
    }
    

    To learn jsdoc : https://jsdoc.app/

    Demo

    But you don't need to use the type annotation extensions in JSDoc.

    You can (and should) still use other jsdoc block tags like @returns etc.

    Example

    Just an example. Focus on the types (not the content).

    JSDoc version (notice types in docs):

    /**
     * Returns the sum of a and b
     * @param {number} a
     * @param {number} b
     * @returns {number}
     */
    function sum(a, b) {
        return a + b;
    }
    

    TypeScript version (notice the re-location of types):

    /**
     * Takes two numbers and returns their sum
     * @param a first input to sum
     * @param b second input to sum
     * @returns sum of a and b
     */
    function sum(a: number, b: number): number {
        return a + b;
    }
    

    Why is the <center> tag deprecated in HTML?

    I still use the <center> tag sometimes because nothing in CSS works as well. Examples of trying to use a <div> trick and failing:

    _x000D_
    _x000D_
    <div style="text-align: center;">This div is centered, but it's a simple example.</div>_x000D_
    <br />_x000D_
    <div style="text-align: center;"><table border="1"><tr><td>&lt;div style="text-align: center;"&gt; didn't center correctly.</td></tr></table></div>_x000D_
    <br />_x000D_
    <div style="text-align: center;margin-left:auto;margin-right:auto"><table border="1"><tr><td>&lt;div style="text-align: center;margin-left:auto;margin-right:auto"&gt; still didn't center either</td></tr></table></div>_x000D_
    <br />_x000D_
    <center><table border="1"><tr><td>Actually Centered with &lt;center&gt; tag</td></tr></table></center>
    _x000D_
    _x000D_
    _x000D_

    <center> gets results. To use CSS instead, you sometimes have to put CSS in several places and mess with it to get it to center right. To answer your question, CSS has become a religion with believers and followers who shunned <center> <b> <i> <u> as blasphemy, unholy, and much too simple for the sake of their own job security. And if they try to take your <table> away from you, ask them what the CSS equivalent of the colspan or rowspan attribute is.

    It is not the abstract or bookish truth, but the lived truth that counts.
    -- Zen

    Which tool to build a simple web front-end to my database

    For Data access you can use OData. Here is a demo where Scott Hanselman creates an OData front end to StackOverflow database in 30 minutes, with XML and JSON access: Creating an OData API for StackOverflow including XML and JSON in 30 minutes.

    For administrative access, like phpMyAdmin package, there is no well established one. You may give a try to IIS Database Manager.

    Python causing: IOError: [Errno 28] No space left on device: '../results/32766.html' on disk with lots of space

    In my case, when I run df -i it shows me that my number of inodes are full and then I have to delete some of the small files or folder. Otherwise it will not allow us to create files or folders once inodes get full.

    All you have to do is delete files or folder that has not taken up full space but is responsible for filling inodes.

    Change all files and folders permissions of a directory to 644/755

    The easiest way is to do:

    chmod -R u+rwX,go+rX,go-w /path/to/dir
    

    which basically means:

    to change file modes -Recursively by giving:

    • user: read, write and eXecute permissions,
    • group and other users: read and eXecute permissions, but not -write permission.

    Please note that X will make a directory executable, but not a file, unless it's already searchable/executable.

    +X - make a directory or file searchable/executable by everyone if it is already searchable/executable by anyone.

    Please check man chmod for more details.

    See also: How to chmod all directories except files (recursively)? at SU

    How do I embed a mp4 movie into my html?

    Most likely the TinyMce editor is adding its own formatting to the post. You'll need to see how you can escape TinyMce's editing abilities. The code works fine for me. Is it a wordpress blog?

    How to work with string fields in a C struct?

    I think this solution uses less code and is easy to understand even for newbie.

    For string field in struct, you can use pointer and reassigning the string to that pointer will be straightforward and simpler.

    Define definition of struct:

    typedef struct {
      int number;
      char *name;
      char *address;
      char *birthdate;
      char gender;
    } Patient;
    

    Initialize variable with type of that struct:

    Patient patient;
    patient.number = 12345;
    patient.address = "123/123 some road Rd.";
    patient.birthdate = "2020/12/12";
    patient.gender = "M";
    

    It is that simple. Hope this answer helps many developers.

    Ping site and return result in PHP

    Another option (if you need/want to ping instead of send an HTTP request) is the Ping class for PHP. I wrote it for just this purpose, and it lets you use one of three supported methods to ping a server (some servers/environments only support one of the three methods).

    Example usage:

    require_once('Ping/Ping.php');
    $host = 'www.example.com';
    $ping = new Ping($host);
    $latency = $ping->ping();
    if ($latency) {
      print 'Latency is ' . $latency . ' ms';
    }
    else {
      print 'Host could not be reached.';
    }
    

    Selecting between two dates within a DateTime field - SQL Server

    select * 
    from blah 
    where DatetimeField between '22/02/2009 09:00:00.000' and '23/05/2009 10:30:00.000'
    

    Depending on the country setting for the login, the month/day may need to be swapped around.

    SQL Switch/Case in 'where' clause

    The problem with this is that when the SQL engine goes to evaluate the expression, it checks the FROM portion to pull the proper tables, and then the WHERE portion to provide some base criteria, so it cannot properly evaluate a dynamic condition on which column to check against.

    You can use a WHERE clause when you're checking the WHERE criteria in the predicate, such as

    WHERE account_location = CASE @locationType
                                  WHEN 'business' THEN 45
                                  WHEN 'area' THEN 52
                             END
    

    so in your particular case, you're going to need put the query into a stored procedure or create three separate queries.

    Simulate low network connectivity for Android

    Since iPhones developer option apply on wifi tethering, you can get an iPhone which has iOS 6 and above (and has been set to use for developments with the xcode), set it to emulate the desired network profile, connect your Android device to its hotspot

    enter image description here

    How to use the PI constant in C++

    Rather than writing

    #define _USE_MATH_DEFINES
    

    I would recommend using -D_USE_MATH_DEFINES or /D_USE_MATH_DEFINES depending on your compiler.

    This way you are assured that even in the event of someone including the header before you do (and without the #define) you will still have the constants instead of an obscure compiler error that you will take ages to track down.

    Best practices for adding .gitignore file for Python projects?

    Here are some other files that may be left behind by setuptools:

    MANIFEST
    *.egg-info
    

    How to show hidden divs on mouseover?

    Pass the mouse over the container and go hovering on the divs I use this for jQuery DropDown menus mainly:

    Copy the whole document and create a .html file you'll be able to figure out on your own from that!

                <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                <html xmlns="http://www.w3.org/1999/xhtml">
                <head>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                <title>The Divs Case</title>
                <style type="text/css">
                * {margin:0px auto;
                padding:0px;}
    
                .container {width:800px;
                height:600px;
                background:#FFC;
                border:solid #F3F3F3 1px;}
    
                .div01 {float:right;
                background:#000;
                height:200px;
                width:200px;
                display:none;}
    
                .div02 {float:right;
                background:#FF0;
                height:150px;
                width:150px;
                display:none;}
    
                .div03 {float:right;
                background:#FFF;
                height:100px;
                width:100px;
                display:none;}
    
                div.container:hover div.div01 {display:block;}
                div.container div.div01:hover div.div02  {display:block;}
                div.container div.div01 div.div02:hover div.div03 {display:block;}
    
                </style>
                </head>
                <body>
    
                <div class="container">
                  <div class="div01">
                    <div class="div02">
                        <div class="div03">
                        </div>
                    </div>
                  </div>
    
                </div>
                </body>
                </html>
    

    Unable to access JSON property with "-" dash

    jsonObj.profile-id is a subtraction expression (i.e. jsonObj.profile - id).

    To access a key that contains characters that cannot appear in an identifier, use brackets:

    jsonObj["profile-id"]
    

    Download JSON object as a file from browser

        downloadJsonFile(data, filename: string){
            // Creating a blob object from non-blob data using the Blob constructor
            const blob = new Blob([JSON.stringify(data)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            // Create a new anchor element
            const a = document.createElement('a');
            a.href = url;
            a.download = filename || 'download';
            a.click();
            a.remove();
          }
    

    You can easily auto download file with using Blob and transfer it in first param downloadJsonFile. filename is name of file you wanna set.

    How to delete/truncate tables from Hadoop-Hive?

    To Truncate:

    hive -e "TRUNCATE TABLE IF EXISTS $tablename"
    

    To Drop:

    hive -e "Drop TABLE IF EXISTS $tablename"
    

    How to check if array element exists or not in javascript?

    Someone please correct me if i'm wrong, but AFAIK the following is true:

    1. Arrays are really just Objects under the hood of JS
    2. Thus, they have the prototype method hasOwnProperty "inherited" from Object
    3. in my testing, hasOwnProperty can check if anything exists at an array index.

    So, as long as the above is true, you can simply:

    const arrayHasIndex = (array, index) => Array.isArray(array) && array.hasOwnProperty(index);

    usage:

    arrayHasIndex([1,2,3,4],4); outputs: false

    arrayHasIndex([1,2,3,4],2); outputs: true

    How can I find where I will be redirected using cURL?

    The answer above didn't work for me on one of my servers, something to to with basedir, so I re-hashed it a little. The code below works on all my servers.

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $a = curl_exec($ch);
    curl_close( $ch ); 
    // the returned headers
    $headers = explode("\n",$a);
    // if there is no redirection this will be the final url
    $redir = $url;
    // loop through the headers and check for a Location: str
    $j = count($headers);
    for($i = 0; $i < $j; $i++){
    // if we find the Location header strip it and fill the redir var       
    if(strpos($headers[$i],"Location:") !== false){
            $redir = trim(str_replace("Location:","",$headers[$i]));
            break;
        }
    }
    // do whatever you want with the result
    echo redir;
    

    Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

    If you have

    @Transactional // Spring Transactional
    class MyDao extends Dao {
    }
    

    and super-class

    class Dao {
        public void save(Entity entity) { getEntityManager().merge(entity); }
    }
    

    and you call

    @Autowired MyDao myDao;
    myDao.save(entity);
    

    you won't get a Spring TransactionInterceptor (that gives you a transaction).

    This is what you need to do:

    @Transactional 
    class MyDao extends Dao {
        public void save(Entity entity) { super.save(entity); }
    }
    

    Unbelievable but true.

    How do I check if a type is a subtype OR the type of an object?

    If you're trying to do it in a Xamarin Forms PCL project, the above solutions using IsAssignableFrom gives an error:

    Error: 'Type' does not contain a definition for 'IsAssignableFrom' and no extension method 'IsAssignableFrom' accepting a first argument of type 'Type' could be found (are you missing a using directive or an assembly reference?)

    because IsAssignableFrom asks for a TypeInfo object. You can use the GetTypeInfo() method from System.Reflection:

    typeof(BaseClass).GetTypeInfo().IsAssignableFrom(typeof(unknownType).GetTypeInfo())

    Calculating arithmetic mean (one type of average) in Python

    def avg(l):
        """uses floating-point division."""
        return sum(l) / float(len(l))
    

    Examples:

    l1 = [3,5,14,2,5,36,4,3]
    l2 = [0,0,0]
    
    print(avg(l1)) # 9.0
    print(avg(l2)) # 0.0
    

    Passing data between view controllers

    To send the data from one view controller (VC) to the other, use this simple approach:

    YourNextVC *nxtScr = (YourNextVC*)[self.storyboard  instantiateViewControllerWithIdentifier:@"YourNextVC"];//Set this identifier from your storyboard
    
    nxtScr.comingFrom = @"PreviousScreen"l
    [self.navigationController nxtScr animated:YES];
    

    How to avoid the "divide by zero" error in SQL?

    You can handle the error appropriately when it propagates back to the calling program (or ignore it if that's what you want). In C# any errors that occur in SQL will throw an exception that I can catch and then handle in my code, just like any other error.

    I agree with Beska in that you do not want to hide the error. You may not be dealing with a nuclear reactor but hiding errors in general is bad programming practice. This is one of the reasons most modern programming languages implement structured exception handling to decouple the actual return value with an error / status code. This is especially true when you are doing math. The biggest problem is that you cannot distinguish between a correctly computed 0 being returned or a 0 as the result of an error. Instead any value returned is the computed value and if anything goes wrong an exception is thrown. This will of course differ depending on how you are accessing the database and what language you are using but you should always be able to get an error message that you can deal with.

    try
    {
        Database.ComputePercentage();
    }
    catch (SqlException e)
    {
        // now you can handle the exception or at least log that the exception was thrown if you choose not to handle it
        // Exception Details: System.Data.SqlClient.SqlException: Divide by zero error encountered.
    }
    

    HTML form with two submit buttons and two "target" attributes

    Have both buttons submit to the current page and then add this code at the top:

    <?php
        if(isset($_GET['firstButtonName'])
            header("Location: first-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
        if(isset($_GET['secondButtonName'])
            header("Location: second-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
    ?>
    

    It could also be done using $_SESSION if you don't want them to see the variables.

    MVC If statement in View

    Every time you use html syntax you have to start the next razor statement with a @. So it should be @if ....

    Differences between contentType and dataType in jQuery ajax function

    From the documentation:

    contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')

    Type: String

    When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it'll always be sent to the server (even if no data is sent). If no charset is specified, data will be transmitted to the server using the server's default charset; you must decode this appropriately on the server side.

    and:

    dataType (default: Intelligent Guess (xml, json, script, or html))

    Type: String

    The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

    They're essentially the opposite of what you thought they were.

    python getoutput() equivalent in subprocess

    Use subprocess.Popen:

    import subprocess
    process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = process.communicate()
    print(out)
    

    Note that communicate blocks until the process terminates. You could use process.stdout.readline() if you need the output before it terminates. For more information see the documentation.

    How can I clear the NuGet package cache using the command line?

    This adds to rm8x's answer.

    Download and install the NuGet command line tool.

    List all of our locals:

    $ nuget locals all -list
    http-cache: C:\Users\MyUser\AppData\Local\NuGet\v3-cache
    packages-cache: C:\Users\MyUser\AppData\Local\NuGet\Cache
    global-packages: C:\Users\MyUser\.nuget\packages\
    

    We can now delete these manually or as rm8x suggests, use nuget locals all -clear.

    What is dtype('O'), in pandas?

    'O' stands for object.

    #Loading a csv file as a dataframe
    import pandas as pd 
    train_df = pd.read_csv('train.csv')
    col_name = 'Name of Employee'
    
    #Checking the datatype of column name
    train_df[col_name].dtype
    
    #Instead try printing the same thing
    print train_df[col_name].dtype
    

    The first line returns: dtype('O')

    The line with the print statement returns the following: object

    Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null

    For others that might still be having this issue, even after trying the above recommendations, using an incorrect selector for your map canvas in the initialize function can cause this same issue as the function is trying to access something that doesn't exist. Double-check that your map Id matches in your initialize function and your HTML or this same error may be thrown.

    In other words, make sure your IDs match up. ;)

    Calling multiple JavaScript functions on a button click

      <asp:Button ID="btnSubmit" runat="server"  OnClientClick ="showDiv()"
       OnClick="btnImport_Click" Text="Upload" ></asp:Button>
    

    Determine number of pages in a PDF file

    I've used the code above that solves the problem using regex and it works, but it's quite slow. It reads the entire file to determine the number of pages.

    I used it in a web app and pages would sometimes list 20 or 30 PDFs at a time and in that circumstance the load time for the page went from a couple seconds to almost a minute due to the page counting method.

    I don't know if the 3rd party libraries are much better, I would hope that they are and I've used pdflib in other scenarios with success.

    Bootstrap push div content to new line

    Do a row div.

    Like this:

    _x000D_
    _x000D_
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">_x000D_
    <div class="grid">_x000D_
        <div class="row">_x000D_
            <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 bg-success">Under me should be a DIV</div>_x000D_
            <div class="col-lg-6 col-md-6 col-sm-5 col-xs-12 bg-danger">Under me should be a DIV</div>_x000D_
        </div>_x000D_
        <div class="row">_x000D_
            <div class="col-lg-3 col-md-3 col-sm-4 col-xs-12 bg-warning">I am the last DIV</div>_x000D_
        </div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    How do I get the XML SOAP request of an WCF Web service request?

    Option 1

    Use message tracing/logging.

    Have a look here and here.


    Option 2

    You can always use Fiddler to see the HTTP requests and response.


    Option 3

    Use System.Net tracing.

    Split string into array of character strings

    Maybe you can use a for loop that goes through the String content and extract characters by characters using the charAt method.

    Combined with an ArrayList<String> for example you can get your array of individual characters.

    Bootstrap 3 panel header with buttons wrong position

    You are part right. with <b>title</b> it looks fine, but I would like to use <h4>.

    I have put <h4 style="display: inline;"> and it seams to work.

    Now, I only need to add some vertival align.

    How to get page content using cURL?

    Get content with Curl php

    request server support Curl function, enable in httpd.conf in folder Apache

    
    function UrlOpener($url)
         global $output;
         $ch = curl_init(); 
         curl_setopt($ch, CURLOPT_URL, $url); 
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
         $output = curl_exec($ch); 
         curl_close($ch);    
         echo $output;
    
    

    If get content by google cache use Curl you can use this url: http://webcache.googleusercontent.com/search?q=cache:Put your url Sample: http://urlopener.mixaz.net/

    Reading a string with scanf

    An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

    Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

    I don't believe I've ever encountered a system on which that doesn't work, and in practice you're probably safe. None the less, it's wrong, and it could fail on some platforms. (Hypothetical example: a "debugging" implementation that includes type information with every pointer. I think the C implementation on the Symbolics "Lisp Machines" did something like this.)

    RecyclerView vs. ListView

    I want just emphasize that RecyclerView is a part of the compatibility package. It means that instead of using the feature and code from OS, every application carries own RecyclerView implementation. Potentially, a feature similar to RecyclerView can be a part of a future OS and using it from there can be beneficial. For example Harmony OS will be out soon.The compatibility package license can be changed in the future and it can be an implication. Summery of disadvantages:

    1. licensing
    2. a bigger foot print especially as a part of many apps
    3. losing in efficiency if some feature coming from OS can be there

    But on a good note, an implementation of some functionality, as swiping items, is coming from RecyclerView.

    All said above has to be taken in a consideration.

    Align DIV's to bottom or baseline

    I had something similar and got it to work by effectively adding some padding-top to the child.

    I'm sure some of the other answers here would get to the solution, but I couldn't get them to easily work after a lot of time; I instead ended up with the padding-top solution which is elegant in its simplicity, but seems kind of hackish to me (not to mention the pixel value it sets would probably depend on the parent height).

    C++ vector's insert & push_back difference

    Beside the fact, that push_back(x) does the same as insert(x, end()) (maybe with slightly better performance), there are several important thing to know about these functions:

    1. push_back exists only on BackInsertionSequence containers - so, for example, it doesn't exist on set. It couldn't because push_back() grants you that it will always add at the end.
    2. Some containers can also satisfy FrontInsertionSequence and they have push_front. This is satisfied by deque, but not by vector.
    3. The insert(x, ITERATOR) is from InsertionSequence, which is common for set and vector. This way you can use either set or vector as a target for multiple insertions. However, set has additionally insert(x), which does practically the same thing (this first insert in set means only to speed up searching for appropriate place by starting from a different iterator - a feature not used in this case).

    Note about the last case that if you are going to add elements in the loop, then doing container.push_back(x) and container.insert(x, container.end()) will do effectively the same thing. However this won't be true if you get this container.end() first and then use it in the whole loop.

    For example, you could risk the following code:

    auto pe = v.end();
    for (auto& s: a)
        v.insert(pe, v);
    

    This will effectively copy whole a into v vector, in reverse order, and only if you are lucky enough to not get the vector reallocated for extension (you can prevent this by calling reserve() first); if you are not so lucky, you'll get so-called UndefinedBehavior(tm). Theoretically this isn't allowed because vector's iterators are considered invalidated every time a new element is added.

    If you do it this way:

    copy(a.begin(), a.end(), back_inserter(v);
    

    it will copy a at the end of v in the original order, and this doesn't carry a risk of iterator invalidation.

    [EDIT] I made previously this code look this way, and it was a mistake because inserter actually maintains the validity and advancement of the iterator:

    copy(a.begin(), a.end(), inserter(v, v.end());
    

    So this code will also add all elements in the original order without any risk.

    Difference between JE/JNE and JZ/JNZ

    From the Intel's manual - Instruction Set Reference, the JE and JZ have the same opcode (74 for rel8 / 0F 84 for rel 16/32) also JNE and JNZ (75 for rel8 / 0F 85 for rel 16/32) share opcodes.

    JE and JZ they both check for the ZF (or zero flag), although the manual differs slightly in the descriptions of the first JE rel8 and JZ rel8 ZF usage, but basically they are the same.

    Here is an extract from the manual's pages 464, 465 and 467.

     Op Code    | mnemonic  | Description
     -----------|-----------|-----------------------------------------------  
     74 cb      | JE rel8   | Jump short if equal (ZF=1).
     74 cb      | JZ rel8   | Jump short if zero (ZF ? 1).
    
     0F 84 cw   | JE rel16  | Jump near if equal (ZF=1). Not supported in 64-bit mode.
     0F 84 cw   | JZ rel16  | Jump near if 0 (ZF=1). Not supported in 64-bit mode.
    
     0F 84 cd   | JE rel32  | Jump near if equal (ZF=1).
     0F 84 cd   | JZ rel32  | Jump near if 0 (ZF=1).
    
     75 cb      | JNE rel8  | Jump short if not equal (ZF=0).
     75 cb      | JNZ rel8  | Jump short if not zero (ZF=0).
    
     0F 85 cd   | JNE rel32 | Jump near if not equal (ZF=0).
     0F 85 cd   | JNZ rel32 | Jump near if not zero (ZF=0).
    

    Regular vs Context Free Grammars

    a regular grammer is never ambiguous because it is either left linear or right linear so we cant make two decision tree for regular grammer so it is always unambiguous.but othert than regular grammar all are may or may not be regular

    R Language: How to print the first or last rows of a data set?

    If you want to print the last 10 lines, use

    tail(dataset, 10)
    

    for the first 10, you could also do

    head(dataset, 10)
    

    How to force an entire layout View refresh?

    Intent intent = getIntent();
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    finish();
    startActivity(intent);
    

    This allows you to reload with theme changes and hides the animations.

    Exporting functions from a DLL with dllexport

    For C++ :

    I just faced the same issue and I think it is worth mentioning a problem comes up when one use both __stdcall (or WINAPI) and extern "C":

    As you know extern "C" removes the decoration so that instead of :

    __declspec(dllexport) int Test(void)                        --> dumpbin : ?Test@@YaHXZ
    

    you obtain a symbol name undecorated:

    extern "C" __declspec(dllexport) int Test(void)             --> dumpbin : Test
    

    However the _stdcall ( = macro WINAPI, that changes the calling convention) also decorates names so that if we use both we obtain :

       extern "C" __declspec(dllexport) int WINAPI Test(void)   --> dumpbin : _Test@0
    

    and the benefit of extern "C" is lost because the symbol is decorated (with _ @bytes)

    Note that this only occurs for x86 architecture because the __stdcall convention is ignored on x64 (msdn : on x64 architectures, by convention, arguments are passed in registers when possible, and subsequent arguments are passed on the stack.).

    This is particularly tricky if you are targeting both x86 and x64 platforms.


    Two solutions

    1. Use a definition file. But this forces you to maintain the state of the def file.

    2. the simplest way : define the macro (see msdn) :

    #define EXPORT comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)

    and then include the following pragma in the function body:

    #pragma EXPORT
    

    Full Example :

     int WINAPI Test(void)
    {
        #pragma EXPORT
        return 1;
    }
    

    This will export the function undecorated for both x86 and x64 targets while preserving the __stdcall convention for x86. The __declspec(dllexport) is not required in this case.

    Cleanest way to write retry logic?

    Implemented LBushkin's answer in the latest fashion:

        public static async Task Do(Func<Task> task, TimeSpan retryInterval, int maxAttemptCount = 3)
        {
            var exceptions = new List<Exception>();
            for (int attempted = 0; attempted < maxAttemptCount; attempted++)
            {
                try
                {
                    if (attempted > 0)
                    {
                        await Task.Delay(retryInterval);
                    }
    
                    await task();
                    return;
                }
                catch (Exception ex)
                {
                    exceptions.Add(ex);
                }
            }
            throw new AggregateException(exceptions);
        }
    
        public static async Task<T> Do<T>(Func<Task<T>> task, TimeSpan retryInterval, int maxAttemptCount = 3)
        {
            var exceptions = new List<Exception>();
            for (int attempted = 0; attempted < maxAttemptCount; attempted++)
            {
                try
                {
                    if (attempted > 0)
                    {
                        await Task.Delay(retryInterval);
                    }
                    return await task();
                }
                catch (Exception ex)
                {
                    exceptions.Add(ex);
                }
            }
            throw new AggregateException(exceptions);
        }  
    

    and to use it:

    await Retry.Do([TaskFunction], retryInterval, retryAttempts);
    

    whereas the function [TaskFunction] can either be Task<T> or just Task.

    How to pass an array into a SQL Server stored procedure

    You need to pass it as an XML parameter.

    Edit: quick code from my project to give you an idea:

    CREATE PROCEDURE [dbo].[GetArrivalsReport]
        @DateTimeFrom AS DATETIME,
        @DateTimeTo AS DATETIME,
        @HostIds AS XML(xsdArrayOfULong)
    AS
    BEGIN
        DECLARE @hosts TABLE (HostId BIGINT)
    
        INSERT INTO @hosts
            SELECT arrayOfUlong.HostId.value('.','bigint') data
            FROM @HostIds.nodes('/arrayOfUlong/u') as arrayOfUlong(HostId)
    

    Then you can use the temp table to join with your tables. We defined arrayOfUlong as a built in XML schema to maintain data integrity, but you don't have to do that. I'd recommend using it so here's a quick code for to make sure you always get an XML with longs.

    IF NOT EXISTS (SELECT * FROM sys.xml_schema_collections WHERE name = 'xsdArrayOfULong')
    BEGIN
        CREATE XML SCHEMA COLLECTION [dbo].[xsdArrayOfULong]
        AS N'<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
        <xs:element name="arrayOfUlong">
            <xs:complexType>
                <xs:sequence>
                    <xs:element maxOccurs="unbounded"
                                name="u"
                                type="xs:unsignedLong" />
                </xs:sequence>
            </xs:complexType>
        </xs:element>
    </xs:schema>';
    END
    GO
    

    Generic htaccess redirect www to non-www

    I used the above rule to fwd www to no www and it works fine for the homepage, however on the internal pages they are forwarding to /index.php

    I found this other rule in my .htaccess file which is causing this but not sure what to do about it. Any suggestions would be great:

    ############################################
    ## always send 404 on missing files in these folders
    
        RewriteCond %{REQUEST_URI} !^/(media|skin|js)/
    
    ############################################
    ## never rewrite for existing files, directories and links
    
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-l
    
    ############################################
    ## rewrite everything else to index.php
    
        RewriteRule .* index.php [L]
    

    Is there a way to know your current username in mysql?

    Try the CURRENT_USER() function. This returns the username that MySQL used to authenticate your client connection. It is this username that determines your privileges.

    This may be different from the username that was sent to MySQL by the client (for example, MySQL might use an anonymous account to authenticate your client, even though you sent a username). If you want the username the client sent to MySQL when connecting use the USER() function instead.

    The value indicates the user name you specified when connecting to the server, and the client host from which you connected. The value can be different from that of CURRENT_USER().

    http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_current-user

    Convert string to title case with JavaScript

    Just another version to add to the mix. This will also check if the string.length is 0:

    String.prototype.toTitleCase = function() {
        var str = this;
        if(!str.length) {
            return "";
        }
        str = str.split(" ");
        for(var i = 0; i < str.length; i++) {
            str[i] = str[i].charAt(0).toUpperCase() + (str[i].substr(1).length ? str[i].substr(1) : '');
        }
        return (str.length ? str.join(" ") : str);
    };
    

    What causes this error? "Runtime error 380: Invalid property value"

    Looks like the answers above are for when you are writing and compiling a program, but I'm using a Vendor's software, Catalog.exe, part of the Voyager card catalog by "Ex Libris" and I'm getting the error as well:

    catalog-error.png http://img805.imageshack.us/img805/8275/catalogerror.png

    I have two Windows 7 32-bit machines. The newer one is giving me the error but on the older one it runs fine. I have done a lot of research with Google and here are some of the things I've found that people are saying related to this issue. Maybe one of these things will help fix the error for you, although they didn't work for me:

    From what others are saying (like David M) I think it could be related to the MSVBM60.DLL library - but it appears that on both of my computers this file is the exact same (same version, size, date, etc).

    Since that file wasn't different I tried to find what other (dll) files the application could be using, so I launched Process Explorer by Sysinternals and took a look at the application (it loads and then crashes when you tell it to "connect"), and the screenshots below are what I found.

    screen1.png http://img195.imageshack.us/img195/2231/screen1oo.png

    screen2.png http://img88.imageshack.us/img88/2153/screen2ao.png

    screen3.png

    Now, I'm not a Windows / VB programmer, just a power user, and so I'm about at the end of my knowledge for what to do. I've talked to the software vendor and they recommend reinstalling Windows. That will probably work, but it just bugs me that this program can run on Windows 7, but something on this particular system is causing errors. Finally, this is an image that has been deployed on multiple machines already and so while re-installing Windows once is not a big deal it would save me some serious time if I could figure out a fix or workaround.

    Shell command to tar directory excluding certain files/folders

    To avoid possible 'xargs: Argument list too long' errors due to the use of find ... | xargs ... when processing tens of thousands of files, you can pipe the output of find directly to tar using find ... -print0 | tar --null ....

    # archive a given directory, but exclude various files & directories 
    # specified by their full file paths
    find "$(pwd -P)" -type d \( -path '/path/to/dir1' -or -path '/path/to/dir2' \) -prune \
       -or -not \( -path '/path/to/file1' -or -path '/path/to/file2' \) -print0 | 
       gnutar --null --no-recursion -czf archive.tar.gz --files-from -
       #bsdtar --null -n -czf archive.tar.gz -T -
    

    Changing .gitconfig location on Windows

    Solution without having to change Windows HOME variable
    OS: Windows 10
    git version: 2.27.0.windows.1

    I use portable version of Git, so all my config files are on my pen-drive(E:). This is what worked for me:

    1. Download portable Git from https://git-scm.com/. Run the file and install it in the required location. I installed it in E:\git.
    2. Run git-bash.exe from E:\git.
    3. I wanted to put .gitconfig and other bash files in E, so I created a folder called home where I want them all in.
      mkdir home
    4. Go to etc folder and open the file called profile (In my case, it's E:\git\etc\profile)
    5. Add absolute path to the home directory we created (or to the directory where you want to have your .gitconfig file located) at the end of the profile file.
      HOME="E:\git\home"

    Now it no longer searches in the C:\Users<username> directory for .gitconfig but only looks in your set path above.

    $ git config --global --list
    fatal: unable to read config file 'E:/git/home/.gitconfig': No such file or directory
    

    It gave an error because there isn't a .gitconfig file there yet. This is just to demonstrate that we have successfully changed the location of the .gitconfig file without changing the HOME directory in Windows.

    Missing Push Notification Entitlement

    There are some really good suggestions on here.

    Referring to the last screenshot that Mina provided, after initially archiving my app, the provisioning profile mentioned during uploading contained a wildcard (XC.*). This is wrong.

    It took some considerable effort in order to resolve this. I had to perform a combination of the suggestions that Simon Woodside & Mina Fawzy provided.

    If you have any existing certificates and provisioning profiles related to your project, now would be a good time to remove them all locally, and revoke them all remotely. Give yourself a fresh start.

    Mina Fawzy's detailed suggestion is excellent. Performing Mina's suggestion, if performed correctly, should take care of you online.

    Enter Simon's suggestion. Two things I needed to check inside my project. Using XCode, go here:

    PROJECT -> BUILD SETTINGS -> CODE SIGNING

    Review the Code Signing Identity and Provisioning Profile properties. Make sure you set those two properties to that of your project name. Don't allow XCode to automatically select for you, and don't use some generic code signing identity (e.g. Iphone Developer).

    Make sure you can actually install the app onto your devices before deciding to archive.

    Change grid interval and specify tick labels in Matplotlib

    A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.

    import matplotlib.pyplot as plt
    from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)
    
    fig, ax = plt.subplots(figsize=(10, 8))
    
    # Set axis ranges; by default this will put major ticks every 25.
    ax.set_xlim(0, 200)
    ax.set_ylim(0, 200)
    
    # Change major ticks to show every 20.
    ax.xaxis.set_major_locator(MultipleLocator(20))
    ax.yaxis.set_major_locator(MultipleLocator(20))
    
    # Change minor ticks to show every 5. (20/4 = 5)
    ax.xaxis.set_minor_locator(AutoMinorLocator(4))
    ax.yaxis.set_minor_locator(AutoMinorLocator(4))
    
    # Turn grid on for both major and minor ticks and style minor slightly
    # differently.
    ax.grid(which='major', color='#CCCCCC', linestyle='--')
    ax.grid(which='minor', color='#CCCCCC', linestyle=':')
    

    Matplotlib Custom Grid

    Create a Date with a set timezone without using a string representation

    d = new Date();
    utc = d.getTime() + (d.getTimezoneOffset() * 60000);
    nd = new Date(utc + (3600000*offset));
    
    offset value base on which location time zone you would like to set 
    For India offset value +5.5,
    New York offset value -4,
    London offset value +1
    

    for all location offset Wiki List of UTC time offsets

    libxml/tree.h no such file or directory

    On Mountain Lion I was facing same issue, which was resolved by adding /usr/include/libxml2 to include paths with flag "recursive", use this if all above is not fruitful.

    Hiding elements in responsive layout?

    Bootstrap 4.x answer

    hidden-* classes are removed from Bootstrap 4 beta onward.

    If you want to show on medium and up use the d-* classes, e.g.:

    <div class="d-none d-md-block">This will show in medium and up</div>
    

    If you want to show only in small and below use this:

    <div class="d-block d-md-none"> This will show only in below medium form factors</div>
    

    Screen size and class chart

    | Screen Size        | Class                          |
    |--------------------|--------------------------------|
    | Hidden on all      | .d-none                        |
    | Hidden only on xs  | .d-none .d-sm-block            |
    | Hidden only on sm  | .d-sm-none .d-md-block         |
    | Hidden only on md  | .d-md-none .d-lg-block         |
    | Hidden only on lg  | .d-lg-none .d-xl-block         |
    | Hidden only on xl  | .d-xl-none                     |
    | Visible on all     | .d-block                       |
    | Visible only on xs | .d-block .d-sm-none            |
    | Visible only on sm | .d-none .d-sm-block .d-md-none |
    | Visible only on md | .d-none .d-md-block .d-lg-none |
    | Visible only on lg | .d-none .d-lg-block .d-xl-none |
    | Visible only on xl | .d-none .d-xl-block            |
    

    Rather than using explicit .visible-* classes, you make an element visible by simply not hiding it at that screen size. You can combine one .d-*-none class with one .d-*-block class to show an element only on a given interval of screen sizes (e.g. .d-none.d-md-block.d-xl-none shows the element only on medium and large devices).

    Documentation

    pros and cons between os.path.exists vs os.path.isdir

    Most of the time, it is the same.

    But, path can exist physically whereas path.exists() returns False. This is the case if os.stat() returns False for this file.

    If path exists physically, then path.isdir() will always return True. This does not depend on platform.

    .htaccess rewrite to redirect root URL to subdirectory

    This will try the subdir if the file doesn't exist in the root. Needed this as I moved a basic .html website that expects to be ran at the root level and pushed it to a subdir. Only works if all files are flat (no .htaccess trickery in the subdir possible). Useful for linked things like css and js files.

    # Internal Redirect to subdir if file is found there.
    RewriteEngine on
    RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_URI} !-s
    RewriteCond %{DOCUMENT_ROOT}/subdir/%{REQUEST_URI} -s
    RewriteRule ^(.*)$ /subdir/$1 [L]
    

    LINQ to Entities does not recognize the method

    I got the same error in this code:

     var articulos_en_almacen = xx.IV00102.Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();
    

    this was the exactly error:

    System.NotSupportedException: 'LINQ to Entities does not recognize the method 'Boolean Exists(System.Predicate`1[conector_gp.Models.almacenes_por_sucursal])' method, and this method cannot be translated into a store expression.'

    I solved this way:

    var articulos_en_almacen = xx.IV00102.ToList().Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();
    

    I added a .ToList() before my table, this decouple the Entity and linq code, and avoid my next linq expression be translated

    NOTE: this solution isn't optimal, because avoid entity filtering, and simply loads all table into memory

    How to print from Flask @app.route to python console

    I think the core issue with Flask is that stdout gets buffered. I was able to print with print('Hi', flush=True). You can also disable buffering by setting the PYTHONUNBUFFERED environment variable (to any non-empty string).

    Grouped bar plot in ggplot

    First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

    raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
    raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
    raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
    raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
    
    raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it
    
    freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level
    

    Then you need to create a data frame out of it, melt it and plot it:

    Names=c("Food","Music","People")     # create list of names
    data=data.frame(cbind(freq),Names)   # combine them into a data frame
    data=data[,c(5,3,1,2,4)]             # sort columns
    
    # melt the data frame for plotting
    data.m <- melt(data, id.vars='Names')
    
    # plot everything
    ggplot(data.m, aes(Names, value)) +   
      geom_bar(aes(fill = variable), position = "dodge", stat="identity")
    

    Is this what you're after?

    enter image description here

    To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

    > head(df)
      ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
    1  1    A  1980   450   338   154    36    13     9
    2  2    A  2000   288   407   212    54    16    23
    3  3    A  2020   196   434   246    68    19    36
    4  4    B  1980   111   326   441    90    21    11
    5  5    B  2000    63   298   443   133    42    21
    6  6    B  2020    36   257   462   162    55    30
    

    Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

    For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

    > data
       Names Very.Bad Bad Good Very.Good
    1   Food        7   6    5         2
    2  Music        5   5    7         3
    3 People        6   3    7         4
    

    Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

    How can I turn a DataTable to a CSV?

    Try changing sb.Append(Environment.NewLine); to sb.AppendLine();.

    StringBuilder sb = new StringBuilder();          
    foreach (DataColumn col in dt.Columns)         
    {             
        sb.Append(col.ColumnName + ',');         
    }          
    
    sb.Remove(sb.Length - 1, 1);         
    sb.AppendLine();          
    
    foreach (DataRow row in dt.Rows)         
    {             
        for (int i = 0; i < dt.Columns.Count; i++)             
        {                 
            sb.Append(row[i].ToString() + ",");             
        }              
    
        sb.AppendLine();         
    }          
    
    File.WriteAllText("test.csv", sb.ToString());
    

    How remove border around image in css?

    maybe add border:none to under a.info:hover span or text-decoration:none

    Allow only numeric value in textbox using Javascript

    Javascript For only numeric value in textbox ::

    <input type="text" id="textBox" runat="server" class="form-control" onkeydown="return onlyNos(event)" tabindex="0" /> 
    
    
        <!--Only Numeric value in Textbox Script -->
            <script type="text/javascript">
                function onlyNos(e, t) {
                    try {
                        if (window.event) {
                            var charCode = window.event.keyCode;
                        }
                        else if (e) {
                            var charCode = e.which;
                        }
                        else { return true; }
                        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                            return false;
                        }
                        return true;
                    }
                    catch (err) {
                        alert(err.Description);
                    }
                }
            </script>
            <!--Only Numeric value in Textbox Script -->
    

    How to loop through all the files in a directory in c # .net?

    You can have a look at this page showing Deep Folder Copy, it uses recursive means to iterate throught the files and has some really nice tips, like filtering techniques etc.

    http://www.codeproject.com/Tips/512208/Folder-Directory-Deep-Copy-including-sub-directori

    T-sql - determine if value is integer

    With sqlserver 2005 and later you can use regex-like character classes with LIKE operator. See here.

    To check if a string is a non-negative integer (it is a sequence of decimal digits) you can test that it doesn't contain other characters.

    SELECT numstr
      FROM table
     WHERE numstr NOT LIKE '%[^0-9]%'
    

    Note1: This will return empty strings too.

    Note2: Using LIKE '%[0-9]%' will return any string that contains at least a digit.

    See fiddle

    Convert image from PIL to openCV format

    The code commented works as well, just choose which do you prefer

    import numpy as np
    from PIL import Image
    
    
    def convert_from_cv2_to_image(img: np.ndarray) -> Image:
        # return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
        return Image.fromarray(img)
    
    
    def convert_from_image_to_cv2(img: Image) -> np.ndarray:
        # return cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR)
        return np.asarray(img)
    

    Convert dictionary to list collection in C#

    If you want to use Linq then you can use the following snippet:

    var listNumber = dicNumber.Keys.ToList();
    

    PHP memcached Fatal error: Class 'Memcache' not found

    I went into wp-config/ and deleted the object-cache.php and advanced-cache.php and it worked fine for me.

    jQuery: checking if the value of a field is null (empty)

    Assuming

    var val = $('#person_data[document_type]').value();
    

    you have these cases:

    val === 'NULL';  // actual value is a string with content "NULL"
    val === '';      // actual value is an empty string
    val === null;    // actual value is null (absence of any value)
    

    So, use what you need.

    Apache Server (xampp) doesn't run on Windows 10 (Port 80)

    First, open regedit run as administrator see image open HKEY_LOCAL_MACHINE\SYSTEM\CurrentCurrentControlSet\Services\HTTP open Start, change value from 3 to 4 see image then restart your computer

    How to get a thread and heap dump of a Java process on Windows that's not running in a console

    In addition to using the mentioned jconsole/visualvm, you can use jstack -l <vm-id> on another command line window, and capture that output.

    The <vm-id> can be found using the task manager (it is the process id on windows and unix), or using jps.

    Both jstack and jps are include in the Sun JDK version 6 and higher.

    Binding Combobox Using Dictionary as the Datasource

    Just Try to do like this....

    SortedDictionary<string, int> userCache = UserCache.getSortedUserValueCache();
    
        // Add this code
        if(userCache != null)
        {
            userListComboBox.DataSource = new BindingSource(userCache, null); // Key => null
            userListComboBox.DisplayMember = "Key";
            userListComboBox.ValueMember = "Value";
        }
    

    javascript password generator

    I also developed my own password generator, with random length (between 16 and 40 by default), strong passwords, maybe it could help.

    function randomChar(string) {
      return string[Math.floor(Math.random() * string.length)];
    }
    
    // you should use another random function, like the lodash's one.
    function random(min = 0, max = 1) {
     return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    
    // you could use any shuffle function, the lodash's one, or the following https://stackoverflow.com/a/6274381/6708504
    function shuffle(a) {
      for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
      }
    
      return a;
    }
    
    function generatePassword() {
      const symbols = '§±!@#$%^&*()-_=+[]{}\\|?/<>~';
      const numbers = '0123456789';
      const lowercaseLetters = 'abcdefghijklmnopqrstuvwxyz';
      const uppercaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      const minCharsGroup = 4;
      const maxCharsGroup = 10;
      const randomSymbols = [...Array(random(minCharsGroup, maxCharsGroup))].map(() => randomChar(symbols));
      const randomNumbers = [...Array(random(minCharsGroup, maxCharsGroup))].map(() => randomChar(numbers));
      const randomUppercasesLetters = [...Array(random(minCharsGroup, maxCharsGroup))].map(() => randomChar(uppercaseLetters));
      const randomLowercasesLetters = [...Array(random(minCharsGroup, maxCharsGroup))].map(() => randomChar(lowercaseLetters));
      const chars = [...randomSymbols, ...randomNumbers, ...randomUppercasesLetters, ...randomLowercasesLetters];
    
      return shuffle(chars).join('');
    }
    

    git replace local version with remote version

    This is the safest solution:

    git stash
    

    Now you can do whatever you want without fear of conflicts.

    For instance:

    git checkout origin/master
    

    If you want to include the remote changes in the master branch you can do:

    git reset --hard origin/master
    

    This will make you branch "master" to point to "origin/master".

    SecurityException: Permission denied (missing INTERNET permission?)

    Android Studio 1.3b1 (not sure about other versions) autocompleted my internet permission to ANDROID.PERMISSION.INTERNET. Changing it to android.permission.INTERNET fixed the issue.

    How to extract a single value from JSON response?

    Only suggestion is to access your resp_dict via .get() for a more graceful approach that will degrade well if the data isn't as expected.

    resp_dict = json.loads(resp_str)
    resp_dict.get('name') # will return None if 'name' doesn't exist
    

    You could also add some logic to test for the key if you want as well.

    if 'name' in resp_dict:
        resp_dict['name']
    else:
        # do something else here.
    

    How to use placeholder as default value in select2 framework

    you can init placeholder in you select html code in two level such as:

    <select class="form-control select2" style="width: 100%;" data-placeholder="Select a State">
       <option></option>
       <option>?????</option>
       <option>????</option>
       <option>??????</option>
       <option>?????</option>
       <option>?????</option>
       <option>?????</option>
       <option>???</option>   
    </select>
    

    1.set data-placeholder attribute in your select tag 2.set empty tag in first of your select tag

    Copy files on Windows Command Line with Progress

    This technet link has some good info for copying large files. I used an exchange server utility mentioned in the article which shows progress and uses non buffered copy functions internally for faster transfer.

    In another scenario, I used robocopy. Robocopy GUI makes it easier to get your command line options right.

    ValueError: max() arg is an empty sequence

    Since you are always initialising self.listMyData to an empty list in clkFindMost your code will always lead to this error* because after that both unique_names and frequencies are empty iterables, so fix this.

    Another thing is that since you're iterating over a set in that method then calculating frequency makes no sense as set contain only unique items, so frequency of each item is always going to be 1.

    Lastly dict.get is a method not a list or dictionary so you can't use [] with it:

    Correct way is:

    if frequencies.get(name):
    

    And Pythonic way is:

    if name in frequencies:
    

    The Pythonic way to get the frequency of items is to use collections.Counter:

    from collections import Counter   #Add this at the top of file.
    
    def clkFindMost(self, parent):
    
            #self.listMyData = []   
            if self.listMyData:
               frequencies = Counter(self.listMyData)
               self.txtResults.Value = max(frequencies, key=frequencies.get)
            else:
               self.txtResults.Value = '' 
    

    max() and min() throw such error when an empty iterable is passed to them. You can check the length of v before calling max() on it.

    >>> lst = []
    >>> max(lst)
    
    Traceback (most recent call last):
      File "<pyshell#2>", line 1, in <module>
        max(lst)
    ValueError: max() arg is an empty sequence
    >>> if lst:
        mx = max(lst)
    else:
        #Handle this here
    

    If you are using it with an iterator then you need to consume the iterator first before calling max() on it because boolean value of iterator is always True, so we can't use if on them directly:

    >>> it = iter([])
    >>> bool(it)
    True
    >>> lst = list(it)
    >>> if lst:
           mx = max(lst)
        else:
          #Handle this here   
    

    Good news is starting from Python 3.4 you will be able to specify an optional return value for min() and max() in case of empty iterable.

    "Port 4200 is already in use" when running the ng serve command

    Just restart the IDE you are using, then it will work.

    Direct download from Google Drive using Google Drive API

    Update December 8th, 2015 According to Google Support using the

    googledrive.com/host/ID
    

    method will be turned off on Aug 31st, 2016.


    I just ran into this issue.

    The trick is to treat your Google Drive folder like a web host.

    Update April 1st, 2015

    Google Drive has changed and there's a simple way to direct link to your drive. I left my previous answers below for reference but to here's an updated answer.

    1. Create a Public folder in Google Drive.

    2. Share this drive publicly.

      enter image description here

    3. Get your Folder UUID from the address bar when you're in that folder

      enter image description here
    4. Put that UUID in this URL

      https://googledrive.com/host/<folder UUID>/
    5. Add the file name to where your file is located.

      https://googledrive.com/host/<folder UUID>/<file name>

    Which is intended functionality by Google
    new Google Drive Link.

    All you have to do is simple get the host URL for a publicly shared drive folder. To do this, you can upload a plain HTML file and preview it in Google Drive to find your host URL.

    Here are the steps:

    1. Create a folder in Google Drive.

    2. Share this drive publicly.

      enter image description here

    3. Upload a simple HTML file. Add any additional files (subfolders ok)

      enter image description here

    4. Open and "preview" the HTML file in Google Drive

      enter image description here

    5. Get the URL address for this folder

      enter image description here

    6. Create a direct link URL from your URL folder base

      enter image description here

    7. This URL should allow direct downloads of your large files.

    [edit]

    I forgot to add. If you use subfolders to organize your files, you simple use the folder name as you would expect in a URL hierarchy.

    https://googledrive.com/host/<your public folders id string>/images/my-image.png


    What I was looking to do

    I created a custom Debian image with Virtual Box for Vagrant. I wanted to share this ".box" file with colleagues so they could put the direct link into their Vagrantfile.

    In the end, I needed a direct link to the actual file.

    Google Drive problem

    If you set the file permissions to be publicly available and create/generate a direct access link by using something like the gdocs2direct tool or just crafting the link yourself:

    https://docs.google.com/uc?export=download&id=<your file id>

    You will get a cookie based verification code and prompt "Google could not scan this file" prompt, which won't work for things such as wget or Vagrantfile configs.

    The code that it generates is a simple code that appends GET query variable ...&confirm=### to the string, but it's per user specific, so it's not like you can copy/paste that query variable for others.

    But if you use the above "Web page hosting" method, you can get around that prompt.

    I hope that helps!

    How do I align a label and a textarea?

    Try setting a height on your td elements.

    vertical-align: middle; 
    

    means the element the style is applied to will be aligned within the parent element. The height of the td may be only as high as the text inside.

    How to escape strings in SQL Server using PHP?

    Another way to handle single and double quotes is:

    function mssql_escape($str)
    {
        if(get_magic_quotes_gpc())
        {
            $str = stripslashes($str);
        }
        return str_replace("'", "''", $str);
    }
    

    Are 64 bit programs bigger and faster than 32 bit versions?

    More data is transferred between the CPU and RAM for each memory fetch (64 bits instead of 32), so 64-bit programs can be faster provided they are written so that they properly take advantage of this.

    how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery

    Try this:

     function GetDateFormat(controlName) {
            if ($('#' + controlName).val() != "") {      
                var d1 = Date.parse($('#' + controlName).val().toString().replace(/([0-9]+)\/([0-9]+)/,'$2/$1'));
                if (d1 == null) {
                    alert('Date Invalid.');
                    $('#' + controlName).val("");
                }
                    var array = d1.toString('dd-MMM-yyyy');
                    $('#' + controlName).val(array);
            }
        }
    

    The RegExp replace .replace(/([0-9]+)\/([0-9]+)/,'$2/$1') change day/month position.

    Can an int be null in Java?

    Any Primitive data type like int,boolean, or float etc can't store the null(lateral),since java has provided Wrapper class for storing the same like int to Integer,boolean to Boolean.

    Eg: Integer i=null;

    When creating a service with sc.exe how to pass in context parameters?

    Parameters for created services have some peculiar formating issues, in particular if the command includes spaces or quotes:

    If you want to enter command line parameters for the service, you have to enclose the whole command line in quotes. (And always leave a space after binPath= and before the first quote, as mrswadge pointed out)

    So, to create a service for the command PATH\COMMAND.EXE --param1=xyz you would use the following binPath parameter:

    binPath= "PATH\COMMAND.EXE --param1=xyz"
            ^^                             ^
            ||                             |
      space    quote                     quote
    

    If the path to the executable contains spaces, you have to enclose the path in quotes.

    So for a command that has both parameters and a path with spaces, you need nested quotes. You have to escape the inner quotes with backslashes \". The same holds if the parameters themselves contain quotes, you will need to escape those too.

    Despite using backslashes as escape characters, you do not have to escape the regular backslashes contained in the path. This is contrary to how you normally use backslashes as escape characters.

    So for a command like
    "PATH WITH SPACES \COMMAND.EXE" --param-with-quotes="a b c" --param2:

    binPath= "\"PATH WITH SPACES \COMMAND.EXE\" --param-with-quotes=\"a b c\" --param2"
             ^ ^                 ^           ^                      ^       ^         ^
             | |                 |           |                      |       |         | 
     opening     escaped      regular     escaped                    escaped       closing
       quote     quote       backslash    closing                    quotes          quote
         for     for            in         quote                      for              for
       whole     path          path       for path                  parameter        whole
     command                                                                       command
    

    Here is a concrete example from the SVNserve documentation, which shows all special cases:

    sc create svnserve 
       binpath= "\"C:\Program Files\CollabNet Subversion Server\svnserve.exe\" --service -r \"C:\my repositories\"  "
       displayname= "Subversion Server" depend= Tcpip start= auto 
    

    (linebreaks are added for readability, do not include them)

    This would add a new service with the command line "C:\Program Files\CollabNet Subversion Server\svnserve.exe" --service -r "C:\my repositories".

    So in summary

    • space after each sc parameter: binpath=_, displayname=_ and depend=_
    • each sc parameter that contains spaces must be enclosed in quotes
    • all additional quotes inside the binpath are escaped with backslashes: \"
    • all backslashes inside the binpath are not escaped

    How to run Selenium WebDriver test cases in Chrome

    You need to install the Chrome driver. You can install this package using NuGet as shown below: