Programs & Examples On #Internet explorer

Internet Explorer (commonly abbreviated to IE or MSIE) is a web browser developed by Microsoft and is included as part of Microsoft Windows.

Force IE10 to run in IE10 Compatibility View?

If you want to set the compatibility mode in the browser itself and not in the html do the following

  1. Open IE 10
  2. Press the ALT Key to bring up the IE Menubar
  3. Click on the Tools menu
  4. Click on compatibility view setting.
  5. Clicks check the box; display all the websites in compatibility view or
  6. Add only the desired websites to the compatibility view

As shown in the image below. The website should then open up with IE 10 Compatibility view.

enter image description here

Selenium Webdriver submit() vs click()

The submit() function is there to make life easier. You can use it on any element inside of form tags to submit that form.

You can also search for the submit button and use click().

So the only difference is click() has to be done on the submit button and submit() can be done on any form element.

It's up to you.

http://docs.seleniumhq.org/docs/03_webdriver.jsp#user-input-filling-in-forms

window.print() not working in IE

This worked for me, it works in firefox, ie and chrome.

    var content = "This is a test Message";

    var contentHtml = [
        '<div><b>',
        'TestReport',
        '<button style="float:right; margin-right:10px;"',
        'id="printButton" onclick="printDocument()">Print</button></div>',
        content
    ].join('');

    var printWindow = window.open();

    printWindow.document.write('<!DOCTYPE HTML><html><head<title>Reports</title>',
        '<script>function printDocument() {',
        'window.focus();',
        'window.print();',
        'window.close();',
        '}',
        '</script>');

    printWindow.document.write("stylesheet link here");

    printWindow.document.write('</head><body>');
    printWindow.document.write(contentHtml);
    printWindow.document.write('</body>');
    printWindow.document.write('</html>');
    printWindow.document.close();

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_

How to launch an application from a browser?

We use a sonicwall vpn. It launches a java applet that launches mstc with all the credentials setup. You really can't do this without a java applet or activex plugin.

Microsoft uses this technique itself on their small business server for getting inside the network. I wouldn't say it is a terrible idea, as long as platform independence isn't important.

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

The code below will work just fine in all browsers:

<button onClick="location.href = 'http://www.google.com'">Go to Google</button>

IE prompts to open or save json result from server

Sadly, this is just another annoying quirk of using Internet Explorer.

enter image description here

The simple solution is to run a small .reg file on your PC, to tell IE to automatically open .json files, rather than nag about whether to open/save it.

I've put a copy of the file you'll need here:

JSON mime type

You'll need to have Admin rights to run this.

How can I use console logging in Internet Explorer?

There is Firebug Lite which gives a lot of Firebug functionality in IE.

How to enable Auto Logon User Authentication for Google Chrome

Chrome did change their menus since this question was asked. This solution was tested with Chrome 47.0.2526.73 to 72.0.3626.109.

If you are using Chrome right now, you can check your version with : chrome://version

  1. Goto: chrome://settings

  1. Scroll down to the bottom of the page and click on "Advanced" to show more settings.

OLDER VERSIONS:

Scroll down to the bottom of the page and click on "Show advanced settings..." to show more settings.

  1. In the "System" section, click on "Open proxy settings".

OLDER VERSIONS:

In the "Network" section, click on "Change proxy settings...".

  1. Click on the "Security" tab, then select "Local intranet" icon and click on "Sites" button.

  1. Click on "Advanced" button.

  1. Insert your intranet local address and click on the "Add" button.

  1. Close all windows.

That's it.

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

The difference is that if you only specify the DOCTYPE, IE’s Compatibility View Settings take precedence. By default these settings force all intranet sites into Compatibility View regardless of DOCTYPE. There’s also a checkbox to use Compatibility View for all websites, regardless of DOCTYPE.

IE Compatibility View Settings dialog

X-UA-Compatible overrides the Compatibility View Settings, so the page will render in standards mode regardless of the browser settings. This forces standards mode for:

  • intranet pages
  • external web pages when the computer administrator has chosen “Display all websites in Compatibility View” as the default—think big companies, governments, universities
  • when you unintentionally end up on the Microsoft Compatibility View List
  • cases where users have manually added your website to the list in Compatibility View Settings

DOCTYPE alone cannot do that; you will end up in one of the Compatibility View modes in these cases regardless of DOCTYPE.

If both the meta tag and the HTTP header are specified, the meta tag takes precedence.

This answer is based on examining the complete rules for deciding document mode in IE8, IE9, and IE10. Note that looking at the DOCTYPE is the very last fallback for deciding the document mode.

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

While there are several excellent answers, ranging from usual suspects to newer solutions, I would like to provide one more to the fray that addresses what you should do when you are working on a solution with multiple projects.

Before I arrived at this solution, I kept looking at bindingInformation in the applicationhost.config of the solution, tirelessly looking for any hint of why things were simply not working.

Turns out, the simple thing that I overlooked was that different projects have individual settings too.

So, besides Project > {Project-Name} Properties... > Web > Start Action on my Backend Project, I also had to Go to Website > Start Options... > Start Action on my Frontend Project. Once there, I selected Don't open a page. Wait for a request from an external application and have been happy ever since!

Backend Settings Frontend Settings

filter: progid:DXImageTransform.Microsoft.gradient is not working in ie7

You didn't specify a GradientType:

background: #f0f0f0; /* Old browsers */
background: -moz-linear-gradient(top, #ffffff 0%, #eeeeee 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#eeeeee)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#eeeeee',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* W3C */

source: http://www.colorzilla.com/gradient-editor/

PNG transparency issue in IE8

My scenario:

  • I had a background image that had a 24bit alpha png that was set to an anchor link.
  • The anchor was being faded in on hover using Jquery.

eg.

a.button { background-image: url(this.png; }

I found that applying the mark-up provided by Dan Tello didn't work.

However, by placing a span within the anchor element, and setting the background-image to that element I was able to achieve a good result using Dan Tello's markup.

eg.

a.button span { background-image: url(this.png; }

Flexbox not working in Internet Explorer 11

See "Can I Use" for the full list of IE11 Flexbox bugs and more

There are numerous Flexbox bugs in IE11 and other browsers - see flexbox on Can I Use -> Known Issues, where the following are listed under IE11:

  • IE 11 requires a unit to be added to the third argument, the flex-basis property
  • In IE10 and IE11, containers with display: flex and flex-direction: column will not properly calculate their flexed childrens' sizes if the container has min-height but no explicit height property
  • IE 11 does not vertically align items correctly when min-height is used

Also see Philip Walton's Flexbugs list of issues and workarounds.

Make Adobe fonts work with CSS3 @font-face in IE9

As a Mac user, I was unable to use the MS-DOS and Windows command line tools that were mentioned to fix the font embedding permission. However, I found out that you can fix this using FontLab to set the permission to 'Everything is allowed'. I hope this recipe on how to set the font permission to Installable on Mac OS X is useful for others as well.

<!--[if !IE]> not working

An update if somebody still reaches this page, wondering why the ie targeting doesnt work. IE 10 and onward no longer support conditional comments. From the MS official website:

Support for conditional comments has been removed in Internet Explorer 10 standards and quirks modes for improved interoperability and compliance with HTML5.

Please see here for more details: http://msdn.microsoft.com/en-us/library/ie/hh801214(v=vs.85).aspx

If you desperately need to target ie, you can use this jquery code to add a ie class to and then use .ie class in your css to target ie browsers.

if ($.browser.msie) {
 $("html").addClass("ie");
}

Update: $.browser is not available after jQuery 1.9. If you upgrade to jQuery above 1.9 or you already use it, you can include jQuery migration script after jQuery so that it adds missing parts: jQuery Migrate Plugin

Alternatively, please check this thread for possible workarounds: browser.msie error after update to jQuery 1.9.1

IE8 crashes when loading website - res://ieframe.dll/acr_error.htm

Error "res://ieframe.dll/acr_error.htm#"

In my case, cannot open some websites or after openned IE8 gave "cannot return to website error". After some visits to MS help sites like this and followed all the instructioms with no avail I saw what seems to me a tip.

In one of the MS websites they say to delete old Java versions using "control panel" and "add remove programs". I did just that but only saw one version of Java v.6u22. Then I got the idea of download the last version of Java from some days ago v.6u29 and voila... IE8 is working now and seems OK. I'm writing this in the hope this can help others.

Date constructor returns NaN in IE, but works in Firefox and Chrome

You can use the following code to parse ISO8601 date string:

function parseISO8601(d) {
    var timestamp = d;
    if (typeof (d) !== 'number') {
        timestamp = Date.parse(d);
    }
    return new Date(timestamp);
};

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.

HTML5 and frameborder

This works

iframe{
    border-width: 0px;
}

How to launch multiple Internet Explorer windows/tabs from batch file?

Try this in your batch file:

@echo off
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.google.com
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.yahoo.com

Flexbox Not Centering Vertically in IE

Just in case someone gets here with the same issue I had, which is not specifically addressed in previous comments.

I had margin: auto on the inner element which caused it to stick to the bottom of it's parent (or the outer element). What fixed it for me was changing the margin to margin: 0 auto;.

.trim() in JavaScript not working in IE

We can get official code From the internet! Refer this:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim

Running the following code before any other code will create trim() if it's not natively available.

if (!String.prototype.trim) {
  (function() {
    // Make sure we trim BOM and NBSP
    var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
    String.prototype.trim = function() {
      return this.replace(rtrim, '');
    };
  })();
}

for more: I just found there is js project for supporting EcmaScript 5: https://github.com/es-shims/es5-shim by reading the source code, we can get more knowledge about trim.

defineProperties(StringPrototype, {
 // http://blog.stevenlevithan.com/archives/faster-trim-javascript
 // http://perfectionkills.com/whitespace-deviations/
  trim: function trim() {
    if (typeof this === 'undefined' || this === null) {
      throw new TypeError("can't convert " + this + ' to object');
    }
    return String(this).replace(trimBeginRegexp, '').replace(trimEndRegexp, '');
  }
}, hasTrimWhitespaceBug);

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

To answer your question: no, it's not possible to have multiple versions of IE (if that is what you meant) installed in a 'normal' way (i.e. not a hack, a sandbox or a VM etc). It's perfectly ok to have multiple browsers of different types installed on the same machine, such as IE8, Firefox 3 and Chrome all at once.

SandboxIE should allow you to install multiple versions of IE side-by-side (as well as other software), and this is less hassle than going down the virtual machine route.

However, from a QA point of view I'd strongly recommend installing different versions on different machines as the best option from a testing point of view. This will give you the most realistic testing environment. If you don't have the hardware for that, then virtual machines are the next best option as mentioned in some of the other answers.

Force Internet Explorer to use a specific Java Runtime Environment install?

If you mean when you are not the person writing the web page, then you could disable the add ons you do not wish to use with the Manage Add-Ons IE Options screen added in Win XP SP2

'innerText' works in IE, but not in Firefox

innerText has been added to Firefox and should be available in the FF45 release: https://bugzilla.mozilla.org/show_bug.cgi?id=264412

A draft spec has been written and is expected to be incorporated into the HTML living standard in the future: http://rocallahan.github.io/innerText-spec/, https://github.com/whatwg/html/issues/465

Note that currently the Firefox, Chrome and IE implementations are all incompatible. Going forward, we can probably expect Firefox, Chrome and Edge to converge while old IE remains incompatible.

See also: https://github.com/whatwg/compat/issues/5

IE6/IE7 css border on select element

As far as I know, it's not possible in IE because it uses the OS component.

Here is a link where the control is replaced, but I don't know if thats what you want to do.

Edit: The link is broken I'm dumping the content

<select> Something New, Part 1

By Aaron Gustafson

So you've built a beautiful, standards-compliant site utilizing the latest and greatest CSS techniques. You've mastered control of styling every element, but in the back of your mind, a little voice is nagging you about how ugly your <select>s are. Well, today we're going to explore a way to silence that little voice and truly complete our designs. With a little DOM scripting and some creative CSS, you too can make your <select>s beautiful… and you won't have to sacrifice accessibility, usability or graceful degradation.

The Problem

We all know the <select> is just plain ugly. In fact, many try to limit its use to avoid its classic web circa 1994 inset borders. We should not avoid using the <select> though--it is an important part of the current form toolset; we should embrace it. That said, some creative thinking can improve it.

The <select>

We'll use a simple for our example:

<select id="something" name="something">
  <option value="1">This is option 1</option>
  <option value="2">This is option 2</option>
  <option value="3">This is option 3</option>
  <option value="4">This is option 4</option>
  <option value="5">This is option 5</option>
</select>

[Note: It is implied that this <select> is in the context of a complete form.]

So we have five <option>s within a <select>. This <select> has a uniquely assigned id of "something." Depending on the browser/platform you're viewing it on, your <select> likely looks roughly like this:

A <select> as rendered in Windows XP/Firefox 1.0.2.
(source: easy-designs.net)

or this

A <select> as rendered in Mac OSX/Safari 1.2.
(source: easy-designs.net)

Let's say we want to make it look a little more modern, perhaps like this:

Our concept of a nicely-styled <select>.
(source: easy-designs.net)

So how do we do it? Keeping the basic <select> is not an option. Apart from basic background color, font and color adjustments, you don't really have a lot of control over the .

However, we can mimic the superb functionality of a <select> in a new form control without sacrificing semantics, usability or accessibility. In order to do that, we need to examine the nature of a <select>.

A <select> is, essentially, an unordered list of choices in which you can choose a single value to submit along with the rest of a form. So, in essence, it's a <ul> on steroids. Continuing with that line of thinking, we can replace the <select> with an unordered list, as long as we give it some enhanced functionality. As <ul>s can be styled in a myriad of different ways, we're almost home free. Now the questions becomes "how to ensure that we maintain the functionality of the <select> when using a <ul>?" In other words, how do we submit the correct value along with the form, if we are no longer using a form control?

The solution

Enter the DOM. The final step in the process is making the <ul> function/feel like a <select>, and we can accomplish that with JavaScript/ECMA Script and a little clever CSS. Here is the basic list of requirements we need to have a functional faux <select>:

  • click the list to open it,
  • click on list items to change the value assigned & close the list,
  • show the default value when nothing is selected, and
  • show the chosen list item when something is selected.

With this plan, we can begin to tackle each part in succession.

Building the list

So first we need to collect all of the attributes and s out of the and rebuild it as a . We accomplish this by running the following JS:

function selectReplacement(obj) {
  var ul = document.createElement('ul');
  ul.className = 'selectReplacement';
  // collect our object's options
  var opts = obj.options;
  // iterate through them, creating <li>s
  for (var i=0; i<opts.length; i++) {
    var li = document.createElement('li');
    var txt = document.createTextNode(opts[i].text);
    li.appendChild(txt);
    ul.appendChild(li);
  }
  // add the ul to the form
  obj.parentNode.appendChild(ul);
}

You might be thinking "now what happens if there is a selected <option> already?" We can account for this by adding another loop before we create the <li>s to look for the selected <option>, and then store that value in order to class our selected <li> as "selected":

…
  var opts = obj.options;
  // check for the selected option (default to the first option)
  for (var i=0; i<opts.length; i++) {
    var selectedOpt;
    if (opts[i].selected) {
      selectedOpt = i;
      break; // we found the selected option, leave the loop
    } else {
      selectedOpt = 0;
    }
  }
  for (var i=0; i<opts.length; i++) {
    var li = document.createElement('li');
    var txt = document.createTextNode(opts[i].text);
    li.appendChild(txt);
    if (i == selectedOpt) {
      li.className = 'selected';
    }
    ul.appendChild(li);
…

[Note: From here on out, option 5 will be selected, to demonstrate this functionality.]

Now, we can run this function on every <select> on the page (in our case, one) with the following:

function setForm() {
  var s = document.getElementsByTagName('select');
  for (var i=0; i<s.length; i++) {
    selectReplacement(s[i]);
  }
}
window.onload = function() {
  setForm();
}

We are nearly there; let's add some style.

Some clever CSS

I don't know about you, but I am a huge fan of CSS dropdowns (especially the Suckerfish variety). I've been working with them for some time now and it finally dawned on me that a <select> is pretty much like a dropdown menu, albeit with a little more going on under the hood. Why not apply the same stylistic theory to our faux-<select>? The basic style goes something like this:

ul.selectReplacement {
  margin: 0;
  padding: 0;
  height: 1.65em;
  width: 300px;
}
ul.selectReplacement li {
  background: #cf5a5a;
  color: #fff;
  cursor: pointer;
  display: none;
  font-size: 11px;
  line-height: 1.7em;
  list-style: none;
  margin: 0;
  padding: 1px 12px;
  width: 276px;
}
ul.selectOpen li {
  display: block;
}
ul.selectOpen li:hover {
  background: #9e0000;
  color: #fff;
}

Now, to handle the "selected" list item, we need to get a little craftier:

ul.selectOpen li {
  display: block;
}
ul.selectReplacement li.selected {
  color: #fff;
  display: block;
}
ul.selectOpen li.selected {
  background: #9e0000;
  display: block;
}
ul.selectOpen li:hover,
ul.selectOpen li.selected:hover {
  background: #9e0000;
  color: #fff;
}

Notice that we are not using the :hover pseudo-class for the <ul> to make it open, instead we are class-ing it as "selectOpen". The reason for this is two-fold:

  1. CSS is for presentation, not behavior; and
  2. we want our faux-<select> behave like a real <select>, we need the list to open in an onclick event and not on a simple mouse-over.

To implement this, we can take what we learned from Suckerfish and apply it to our own JavaScript by dynamically assigning and removing this class in ``onclickevents for the list items. To do this right, we will need the ability to change theonclick` events for each list item on the fly to switch between the following two actions:

  1. show the complete faux-<select> when clicking the selected/default option when the list is collapsed; and
  2. "select" a list item when it is clicked & collapse the faux-<select>.

We will create a function called selectMe() to handle the reassignment of the "selected" class, reassignment of the onclick events for the list items, and the collapsing of the faux-<select>:

As the original Suckerfish taught us, IE will not recognize a hover state on anything apart from an <a>, so we need to account for that by augmenting some of our code with what we learned from them. We can attach onmouseover and onmouseout events to the "selectReplacement" class-ed <ul> and its <li>s:

function selectReplacement(obj) {
  …
  // create list for styling
  var ul = document.createElement('ul');
  ul.className = 'selectReplacement';
  if (window.attachEvent) {
    ul.onmouseover = function() {
      ul.className += ' selHover';
    }
    ul.onmouseout = function() {
      ul.className = 
        ul.className.replace(new RegExp(" selHover\\b"), '');
    }
  }
  …
  for (var i=0; i<opts.length; i++) {
    …
    if (i == selectedOpt) {
      li.className = 'selected';
    }
    if (window.attachEvent) {
      li.onmouseover = function() {
        this.className += ' selHover';
      }
      li.onmouseout = function() {
        this.className = 
          this.className.replace(new RegExp(" selHover\\b"), '');
      }
    }
  ul.appendChild(li);
}

Then, we can modify a few selectors in the CSS, to handle the hover for IE:

ul.selectReplacement:hover li,
ul.selectOpen li {
  display: block;
}
ul.selectReplacement li.selected {
  color: #fff;
  display: block;
}
ul.selectReplacement:hover li.selected**,
ul.selectOpen li.selected** {
  background: #9e0000;
  display: block;
}
ul.selectReplacement li:hover,
ul.selectReplacement li.selectOpen,
ul.selectReplacement li.selected:hover {
  background: #9e0000;
  color: #fff;
  cursor: pointer;
}

Now we have a list behaving like a <select>; but we still need a means of changing the selected list item and updating the value of the associated form element.

JavaScript fu

We already have a "selected" class we can apply to our selected list item, but we need a way to go about applying it to a <li> when it is clicked on and removing it from any of its previously "selected" siblings. Here's the JS to accomplish this:

function selectMe(obj) {
  // get the <li>'s siblings
  var lis = obj.parentNode.getElementsByTagName('li');
  // loop through
  for (var i=0; i<lis.length; i++) {
    // not the selected <li>, remove selected class
    if (lis[i] != obj) {
      lis[i].className='';
    } else { // our selected <li>, add selected class
      lis[i].className='selected';
    }
  }
}

[Note: we can use simple className assignment and emptying because we are in complete control of the <li>s. If you (for some reason) needed to assign additional classes to your list items, I recommend modifying the code to append and remove the "selected" class to your className property.]

Finally, we add a little function to set the value of the original <select> (which will be submitted along with the form) when an <li> is clicked:

function setVal(objID, selIndex) {
  var obj = document.getElementById(objID);
  obj.selectedIndex = selIndex;
}

We can then add these functions to the onclick event of our <li>s:

…
  for (var i=0; i<opts.length; i++) {
    var li = document.createElement('li');
    var txt = document.createTextNode(opts[i].text);
    li.appendChild(txt);
    li.selIndex = opts[i].index;
    li.selectID = obj.id;
    li.onclick = function() {
      setVal(this.selectID, this.selIndex);
      selectMe(this);
    }
    if (i == selectedOpt) {
      li.className = 'selected';
    }
    ul.appendChild(li);
  }
…

There you have it. We have created our functional faux-. As we have not hidden the originalyet, we can [watch how it behaves](files/4.html) as we choose different options from our faux-. Of course, in the final version, we don't want the original to show, so we can hide it byclass`-ing it as "replaced," adding that to the JS here:

function selectReplacement(obj) {
  // append a class to the select
  obj.className += ' replaced';
  // create list for styling
  var ul = document.createElement('ul');
…

Then, add a new CSS rule to hide the

select.replaced {
  display: none;
}

With the application of a few images to finalize the design (link not available) , we are good to go!


And here is another link to someone that says it can't be done.

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

Server Side solution is the recommended one, as @TimmyFranks proposed in his answer, but if one needs to implement the X-UA-Compatible rule on the page level, please read the following tips, to benefit from the experience of the one who already got burned


The X-UA-Compatible meta tag must appear straight after the title in the <head> element. No other meta tags, css links and js scripts calls can be placed before it.

<head>
    <title>Site Title</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta charset="utf-8">
    <script type="text/javascript" src="/jsFile.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
    <link rel="shortcut icon" href="/apple-touch-icon.png" />
</head>

If there are any conditional comments in the page (lets say located in the <html>), they must be placed under, after the <head>.

// DON'T: place class inside the HTML tag 
<!--[if gt IE 8]><!--> 
    <html class="aboveIe8"> 
<!--<![endif]-->

// DO: place the class inside the BODY tag
<!--[if gt IE 8]><!--> 
    <body class="aboveIe8"> 
<!--<![endif]-->

Html5BoilerPlate's team wrote about this bug - http://h5bp.com/i/378 They have several solutions.

Regarding Intranet & Compatibility view, there're settings when you go to tools > Compatibility view settings.

Compatibility view settings

How to disable Compatibility View in IE

The answer given by FelixFett worked for me. To reiterate:

<meta http-equiv="X-UA-Compatible" content="IE=11; IE=10; IE=9; IE=8; IE=7; IE=EDGE" />

I have it as the first 'meta' tag in my code. I added 10 and 11 as those are versions that are published now for Internet Explorer.

I would've just commented on his answer but I do not have a high enough reputation...

Finding an elements XPath using IE Developer tool

You can find/debug XPath/CSS locators in the IE as well as in different browsers with the tool called SWD Page Recorder

The only restrictions/limitations:

  1. The browser should be started from the tool
  2. Internet Explorer Driver Server - IEDriverServer.exe - should be downloaded separately and placed near SwdPageRecorder.exe

Apply CSS rules if browser is IE

A fast approach is to use the following according to ie that you want to focus (check the comments), inside your css files (where margin-top, set whatever css attribute you like):

margin-top: 10px\9; /*It will apply to all ie from 8 and below */
*margin-top: 10px; /*It will apply to ie 7 and below */
_margin-top: 10px; /*It will apply to ie 6 and below*/

A better approach would be to check user agent or a conditional if, in order to avoid the loading of unnecessary CSS in other browsers.

Viewing local storage contents on IE

Since localStorage is a global object, you can add a watch in the dev tools. Just enter the dev tools, goto "watch", click on "Click to add..." and type in "localStorage".

CSS to hide INPUT BUTTON value text

I had this noted from somewhere:

adding text-transform to input to remove it

input.button {
    text-indent:-9999px;
    text-transform:capitalize;
}

Support for ES6 in Internet Explorer 11

The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.

If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.

CSS Selector for <input type="?"

Sadly the other posters are correct that you're ...actually as corrected by kRON, you are ok with your IE7 and a strict doc, but most of us with IE6 requirements are reduced to JS or class references for this, but it is a CSS2 property, just one without sufficient support from IE^h^h browsers.

Out of completeness, the type selector is - similar to xpath - of the form [attribute=value] but many interesting variants exist. It will be quite powerful when it's available, good thing to keep in your head for IE8.

'console' is undefined error for Internet Explorer

Noticed that OP is using Firebug with IE, so assume it's Firebug Lite. This is a funky situation as console gets defined in IE when the debugger window is opened, but what happens when Firebug is already running? Not sure, but perhaps the "firebugx.js" method might be a good way to test in this situation:

source:

https://code.google.com/p/fbug/source/browse/branches/firebug1.2/lite/firebugx.js?r=187

    if (!window.console || !console.firebug) {
        var names = [
            "log", "debug", "info", "warn", "error", "assert",
            "dir","dirxml","group","groupEnd","time","timeEnd",
            "count","trace","profile","profileEnd"
        ];
        window.console = {};
        for (var i = 0; i < names.length; ++i)
            window.console[names[i]] = function() {}
    }

(updated links 12/2014)

What is the size limit of a post request?

One of the best solutions for this, you do not use multiple or more than 1,000 input fields. You can concatenate multiple inputs with any special character, for ex. @.

See this:

<input type='text' name='hs1' id='hs1'>
<input type='text' name='hs2' id='hs2'>
<input type='text' name='hs3' id='hs3'>
<input type='text' name='hs4' id='hs4'>
<input type='text' name='hs5' id='hs5'>

<input type='hidden' name='hd' id='hd'>

Using any script (JavaScript or JScript),

document.getElementById("hd").value = document.getElementById("hs1").value+"@"+document.getElementById("hs2").value+"@"+document.getElementById("hs3").value+"@"+document.getElementById("hs4").value+"@"+document.getElementById("hs5").value

With this, you will bypass the max_input_vars issue. If you increase max_input_vars in the php.ini file, that is harmful to the server because it uses more server cache memory, and this can sometimes crash the server.

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

I realize this is a rather late post but still a possible solution for the OP. I use IE9 on Win 7 and have been having Adobe Reader's grey screen issues for several months when trying to open pdf bank and credit card statements online. I could open everything in Firefox or Opera but not IE. I finally tried PDF-Viewer, set it as the default pdf viewer in its preferences and no more problems. I'm sure there are other free viewers out there, like Foxit, PDF-Xchange, etc., that will give better results than Reader with less headaches. Adobe is like some of the other big companies that develop software on a take it or leave it basis ... so I left it.

Apply style ONLY on IE

A bit late on this one but this worked perfectly for me when trying to hide the background for IE6 & 7

.myclass{ 
    background-image: url("images/myimg.png");
    background-position: right top;
    background-repeat: no-repeat;
    background-size: 22px auto;
    padding-left: 48px;
    height: 42px;
    _background-image: none;
    *background-image: none;
}

I got this hack via: http://briancray.com/posts/target-ie6-and-ie7-with-only-1-extra-character-in-your-css/

#myelement
{
    color: #999; /* shows in all browsers */
    *color: #999; /* notice the * before the property - shows in IE7 and below */
    _color: #999; /* notice the _ before the property - shows in IE6 and below */
}

'JSON' is undefined error in JavaScript in Internet Explorer

Change the content type to 'application/x-www-form-urlencoded'

CSS-Only Scrollable Table with fixed headers

Another implementation but without any overflow on tbody and dynamic columns. Requires JavaScript though. A container div is used to house the column headings. When the table is scrolled past the view port, a fixed header appears at the top. If table is scrolled horizontally, the fixed header scrolls as well.

Column headings are created using span elements with display: inline-block and a negative margin is used to scroll header horizontally. Also optimized using RequestAnimationFrame to avoid any jank.

function rAF(scrollLeft) {
  var offsetLeft = 0 - scrollLeft;
  $('.hdr__inner span:first-child').css('margin-left', offsetLeft);
}

https://codepen.io/lloydleo/pen/NRpqEE

CSS3 transform: rotate; in IE9

Try this

<!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>Untitled Document</title>
<style type="text/css">
body {
    margin-left: 50px;
    margin-top: 50px;
    margin-right: 50px;
    margin-bottom: 50px;
}
.rotate {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 16px;
    -webkit-transform: rotate(-10deg);
    -moz-transform: rotate(-10deg);
    -o-transform: rotate(-10deg);
    -ms-transform: rotate(-10deg);
    -sand-transform: rotate(10deg);
    display: block;
    position: fixed;
}
</style>
</head>

<body>
<div class="rotate">Alpesh</div>
</body>
</html>

How to automatically allow blocked content in IE?

You have two options:

  1. Use a Mark of the Web. This will enable a single html page to load. It See here for details. To do this, add the following to your web page below the doctype and above the html tag:

    <!-- saved from url=(0014)about:internet -->

  2. Disable this feature. To do so go to Internet Options->Advanced->Security->Allow Active Content... Then close IE. When you restart IE, it will not give you this error.

How does one target IE7 and IE8 with valid CSS?

The actual problem is not IE8, but the hacks that you use for earlier versions of IE.

IE8 is pretty close to be standards compliant, so you shouldn't need any hacks at all for it, perhaps only some tweaks. The problem is if you are using some hacks for IE6 and IE7; you will have to make sure that they only apply to those versions and not IE8.

I made the web site of our company compatible with IE8 a while ago. The only thing that I actually changed was adding the meta tag that tells IE that the pages are IE8 compliant...

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

I ran into a similar issue that impacted all my browsers. After completely uninstalling all my JREs and JDKs then startig from scratch, I ran into the same issue. I'm running Win 7 pro 64 bit.

I detailed out the solution here (Why does Java 7 fail to Verify after successful JRE installation - Java 7 not running my any browser)

but basically I added this "-Djava.net.preferIPv4Stack=true" to my vm args (set in the Java Control Panel, under Java tab / View) and that solved the issues I was facing... seems like a hack but I guess the latest JRE does not handle IPv6 type requests properly

Detect IE version (prior to v9) in JavaScript

function getIEVersion(){
     if (/MSIE |Trident\//.test( navigator.userAgent )=== false) return -1;
    /**[IE <=9]*/
    var isIE9L = typeof ( window.attachEvent ) === 'function' && !( Object.prototype.toString.call( window.opera ) == '[object Opera]' ) ? true : false;
    var re;
    if(isIE9L){
        re = new RegExp( "MSIE ([0-9]{1,}[\.0-9]{0,})" );
        if(re.exec( navigator.userAgent ) !== null)
            return parseFloat( RegExp.$1 );
        return -1;
    }
    /**[/IE <=9]*/
    /** [IE >= 10]*/
    if(navigator.userAgent.indexOf( 'Trident/' ) > -1){
        re = new RegExp( "rv:([0-9]{1,}[\.0-9]{0,})" );
        if(re.exec( navigator.userAgent ) !== null)
            return parseFloat( RegExp.$1 );
        return -1;
    }
    /**[/IE >= 10]*/
    return -1;
};

Check here ==>

var ieVersion = getIEVersion();

if(ieVersion < 0){
    //Not IE
}
//A version of IE

Learn more about browser navigator https://developer.mozilla.org/en-US/docs/Web/API/Window/navigator

Save base64 string as PDF at client side with JavaScript

You should be able to download the file using

window.open("data:application/pdf;base64," + Base64.encode(out));

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!

window.location.reload with clear cache

i had this problem and i solved it using javascript

 location.reload(true);

you may also use

window.history.forward(1);

to stop the browser back button after user logs out of the application.

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

I'm glad that worked out, so I guess you had to explicitly set 'auto' on IE6 in order for it to mimic other browsers!

I actually recently found another technique for scaling images, again designed for backgrounds. This technique has some interesting features:

  1. The image aspect ratio is preserved
  2. The image's original size is maintained (that is, it can never shrink only grow)

The markup relies on a wrapper element:

<div id="wrap"><img src="test.png" /></div>

Given the above markup you then use these rules:

#wrap {
  height: 100px;
  width: 100px;
}
#wrap img {
  min-height: 100%;
  min-width: 100%;
}

If you then control the size of wrapper you get the interesting scale effects that I list above.

To be explicit, consider the following base state: A container that is 100x100 and an image that is 10x10. The result is a scaled image of 100x100.

  1. Starting at the base state, the container resized to 20x100, the image stays resized at 100x100.
  2. Starting at the base state, the image is changed to 10x20, the image resizes to 100x200.

So, in other words, the image is always at least as big as the container, but will scale beyond it to maintain it's aspect ratio.

This probably isn't useful for your site, and it doesn't work in IE6. But, it is useful to get a scaled background for your view port or container.

How to make Google Fonts work in IE?

Try this type of link , it will run in also IE . hope this helps .

<link href='//fonts.googleapis.com/css?family=Josefin+Sans:300,400,600,700,300italic' rel='stylesheet' type='text/css'>

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

This did the trick for me; full example:

HTML:

<a href="/my-popup.php" class="import">Click for my popup on same domain</a>

Javascript:

(function(){
    var doc = document;

    jQuery('.import').click(function(e){
        e.preventDefault();
        window.popup = window.open(jQuery(this).attr('href'), 'importwindow', 'width=500, height=200, top=100, left=200, toolbar=1');

        window.popup.onload = function() {
            window.popup.onbeforeunload = function(){
                doc.location.reload(true); //will refresh page after popup close
            }
        }
    });
})();

Intercept page exit event

Instead of an annoying confirmation popup, it would be nice to delay leaving just a bit (matter of milliseconds) to manage successfully posting the unsaved data to the server, which I managed for my site using writing dummy text to the console like this:

window.onbeforeunload=function(e){
  // only take action (iterate) if my SCHEDULED_REQUEST object contains data        
  for (var key in SCHEDULED_REQUEST){   
    postRequest(SCHEDULED_REQUEST); // post and empty SCHEDULED_REQUEST object
    for (var i=0;i<1000;i++){
      // do something unnoticable but time consuming like writing a lot to console
      console.log('buying some time to finish saving data'); 
    };
    break;
  };
}; // no return string --> user will leave as normal but data is send to server

Edit: See also Synchronous_AJAX and how to do that with jquery

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.

"Stack overflow in line 0" on Internet Explorer

I set up a default project and found out the following:

The problem is the combination of smartNavigation and maintainScrollPositionOnPostBack. The error only occurs when both are set to true.

In my case, the error was produced by:

<pages smartNavigation="true" maintainScrollPositionOnPostBack="true" />

Any other combination works fine.

Can anybody confirm this?

Why don't self-closing script elements work?

Simply modern answer is because the tag is denoted as mandatory that way

Tag omission None, both the starting and ending tag are mandatory.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script

How do I force Internet Explorer to render in Standards Mode and NOT in Quirks?

Sadly, they want us to use a tag to let their browser know what to do. Look at this documentation, it tell us to use:

<meta http-equiv="X-UA-Compatible" content="IE=edge" >

and it should do.

Why does an onclick property set with setAttribute fail to work in IE?

Not relevant to the onclick issue, but also related:

For html attributes whose name collide with javascript reserved words, an alternate name is chosen, eg. <div class=''>, but div.className, or <label for='...'>, but label.htmlFor.

In reasonable browsers, this doesn't affect setAttribute. So in gecko and webkit you'd call div.setAttribute('class', 'foo'), but in IE you have to use the javascript property name instead, so div.setAttribute('className', 'foo').

How to downgrade from Internet Explorer 11 to Internet Explorer 10?

Go to installed updates and just uninstall Internet Explorer 11 Windows update. It works for me.

How to stop IIS asking authentication for default website on localhost

What worked for me is ,,,

Click Start>control panel>Administrative Tools>Internet Information Services

Expand the left tree, right-click your WebSite>Properties

Click on Directory Security, then in "Anonymous access and authentication control" click on Edit

Enable Anonymous access>browse> enter the credentials of the admin (like Administrator) (check names),> Click OK

Apply the settings and it should work fine.

How to support placeholder attribute in IE8 and 9

<input type="text" name="Name" value="Name" onfocus="this.value = ''" onblur=" if(this.value = '') { value = 'Name'}" />

How to detect IE11?

Detect most browsers with this:

var getBrowser = function(){
  var navigatorObj = navigator.appName,
      userAgentObj = navigator.userAgent,
      matchVersion;
  var match = userAgentObj.match(/(opera|chrome|safari|firefox|msie|trident)\/?\s*(\.?\d+(\.\d+)*)/i);
  if( match && (matchVersion = userAgentObj.match(/version\/([\.\d]+)/i)) !== null) match[2] = matchVersion[1];
  //mobile
  if (navigator.userAgent.match(/iPhone|Android|webOS|iPad/i)) {
    return match ? [match[1], match[2], mobile] : [navigatorObj, navigator.appVersion, mobile];
  }
  // web browser
  return match ? [match[1], match[2]] : [navigatorObj, navigator.appVersion, '-?'];
};

https://gist.github.com/earlonrails/5266945

Select dropdown with fixed width cutting off content in IE

Here is a solution that actually works.

It sets the width in IE and doesn't mess up your page layout and doesn't close the dropdown when you mouse over the select options like some of the other solutions on this page.

You will need however to change the margin-right value and width values to match what you have for your select fields.

Also you can replace the $('select') with $('#Your_Select_ID_HERE') to only effect a specific select field. As well you will need to call the function fixIESelect() on the body onload or via jQuery using DOM ready as I did in my code below:

//////////////////////////
// FIX IE SELECT INPUT //
/////////////////////////
window.fixIESelect_clickset = false;
function fixIESelect()
{
 if ($.browser.msie)
 {
  $('select').mouseenter(function ()
  {
   $(this).css("width","auto");
   $(this).css("margin-right","-100");
  });
  $('select').bind('click focus',function ()
  {
   window.fixIESelect_clickset = true;
  });
  $('select').mouseout(function ()
  {
   if(window.fixIESelect_clickset != true)
   {
    $(this).css("width","93px");
    window.fixIESelect_clickset = false;
   }
  });
  $('select').bind('blur change',function ()
  {
   $(this).css("width","93px");
  });
 }
}
/////////////
// ONLOAD //
////////////
$(document).ready(function()
{
 fixIESelect();
});

Online Internet Explorer Simulators

By way of reference, here is another screenshot rendering tool: https://browserlab.adobe.com/

It also does a number of other browsers and platforms as well, and provides a few nice little options like onion skinning etc.


Note: It seems that recently Internet Explorer 6 was removed, which makes it considerably less useful :S

Internet Explorer 11 detection

Use Navigator:-

The navigator is an object that contains all information about the client machine's browser.

navigator.appName returns the name of the client machine's browser.

_x000D_
_x000D_
navigator.appName === 'Microsoft Internet Explorer' ||  !!(navigator.userAgent.match(/Trident/) || navigator.userAgent.match(/rv:11/)) || (typeof $.browser !== "undefined" && $.browser.msie === 1) ? alert("Please dont use IE.") : alert("This is not IE")
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Force IE8 Into IE7 Compatiblity Mode

its even simpler than that. Using HTML you can just add this metatag to your page (first thing on the page):

<meta http-equiv="X-UA-Compatible" content="IE=7" />

If you wanted to do it using.net, you just have to send your http request with that meta information in the header. This would require a page refresh to work though.

Also, you can look at a similar question here: Compatibility Mode in IE8 using VBScript

Div Scrollbar - Any way to style it?

No, you can't in Firefox, Safari, etc. You can in Internet Explorer. There are several scripts out there that will allow you to make a scroll bar.

How do I make background-size work in IE?

In IE11 Windows 7 this worked for me,

background-size: 100% 100%;

Where's the IE7/8/9/10-emulator in IE11 dev tools?

I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).

Read my answer there for a fuller explaination, but in short:

  • They removed it deliberately, because compat mode is not actually really very good for testing compatibility.

  • If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.

  • The only way to get compat mode in IE11 is to set the X-UA-Compatible header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.

How to fix Array indexOf() in JavaScript for Internet Explorer browsers

The full code then would be this:

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(obj, start) {
         for (var i = (start || 0), j = this.length; i < j; i++) {
             if (this[i] === obj) { return i; }
         }
         return -1;
    }
}

For a really thorough answer and code to this as well as other array functions check out Stack Overflow question Fixing JavaScript Array functions in Internet Explorer (indexOf, forEach, etc.).

includes() not working in all browsers

import 'core-js/es7/array' 

into polyfill.ts worked for me.

SCRIPT438: Object doesn't support property or method IE

We were able to solve this problem by adding in the Object.Assign polyfill to the files being imported and throwing the error. We would make it the highest import, that way it would be available to the other code to be called in the stack.

import "mdn-polyfills/Object.assign";

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill

Setting the height of a SELECT in IE

Use a UI library, like jquery or yui, that provides an alternative to the native SELECT element, typically as part of the implementation of a combo box.

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

Here is the latest correct way that I know of how to check for IE and Edge:

if (/MSIE 10/i.test(navigator.userAgent)) {
   // This is internet explorer 10
   window.alert('isIE10');
}

if (/MSIE 9/i.test(navigator.userAgent) || /rv:11.0/i.test(navigator.userAgent)) {
    // This is internet explorer 9 or 11
    window.location = 'pages/core/ie.htm';
}

if (/Edge\/\d./i.test(navigator.userAgent)){
   // This is Microsoft Edge
   window.alert('Microsoft Edge');
}

Note that you don't need the extra var isIE10 in your code because it does very specific checks now.

Also check out this page for the latest IE and Edge user agent strings because this answer may become outdated at some point: https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx

"X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE"

If you support IE, for versions of Internet Explorer 8 and above, this:

<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7" />

Forces the browser to render as that particular version's standards. It is not supported for IE7 and below.

If you separate with semi-colon, it sets compatibility levels for different versions. For example:

<meta http-equiv="X-UA-Compatible" content="IE=7; IE=9" />

Renders IE7 and IE8 as IE7, but IE9 as IE9. It allows for different levels of backwards compatibility. In real life, though, you should only chose one of the options:

<meta http-equiv="X-UA-Compatible" content="IE=8" />

This allows for much easier testing and maintenance. Although generally the more useful version of this is using Emulate:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

For this:

<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

It forces the browser the render at whatever the most recent version's standards are.

For more information, there is plenty to read about on MSDN,

Support for "border-radius" in IE

It is not planned for IE8. See the CSS Compatibility page.

Beyond that no plans have been released. Rumors exist that IE8 will be the last version for Windows XP

Setting the character encoding in form submit for Internet Explorer

Just got the same problem and I have a relatively simple solution that does not require any change in the page character encoding(wich is a pain in the ass).

For example, your site is in utf-8 and you want to post a form to a site in iso-8859-1. Just change the action of the post to a page on your site that will convert the posted values from utf-8 to iso-8859-1.

this could be done easily in php with something like this:

<?php
$params = array();
foreach($_POST as $key=>$value) {
    $params[] = $key."=".rawurlencode(utf8_decode($value));
}
$params = implode("&",$params);

//then you redirect to the final page in iso-8859-1
?>

How to start automatic download of a file in Internet Explorer?

I hate when sites complicate download so much and use hacks instead of a good old link.

Dead simple version:

<a href="file.zip">Start automatic download!</a>

It works! In every browser!


If you want to download a file that is usually displayed inline (such as an image) then HTML5 has a download attribute that forces download of the file. It also allows you to override filename (although there is a better way to do it):

<a href="report-generator.php" download="result.xls">Download</a>

Version with a "thanks" page:

If you want to display "thanks" after download, then use:

<a href="file.zip" 
   onclick="if (event.button==0) 
     setTimeout(function(){document.body.innerHTML='thanks!'},500)">
 Start automatic download!
</a>

Function in that setTimeout might be more advanced and e.g. download full page via AJAX (but don't navigate away from the page — don't touch window.location or activate other links).

The point is that link to download is real, can be copied, dragged, intercepted by download accelerators, gets :visited color, doesn't re-download if page is left open after browser restart, etc.

That's what I use for ImageOptim

Is it still valid to use IE=edge,chrome=1?

It's still valid to use IE=edge,chrome=1.

But, since the chrome frame project has been wound down the chrome=1 part is redundant for browsers that don't already have the chrome frame plug in installed.

I use the following for correctness nowadays

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

File opens instead of downloading in internet explorer in a href link

This is not a code issue. It is your default IE settings

To change the "always open" setting:

  1. In Windows Explorer, click on the "Tools" menu, choose "Folder options"
  2. In the window that appears, click on the "File Types" tab, and scroll through the list until you find the file extension you want to change (they're in alphabetical order). For example, if Internet Explorer always tries to open .zip files, scroll through the list until you find the entry for "zip".
  3. Click on the file type, then the "Advanced" button.
  4. Check the "Confirm after download" box, then click OK > Close.

EDIT: If you ask me , instead of making any changes in the code i would add the following text "Internet Explorer users: To download file, "Rightclick" the link and hit "Save target as" to download the file."

EDIT 2: THIS solution will work perfectly for you. Its a solution i just copied from the other answer. Im not trying to pass it off as my own

Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"filename.xxx\"

However you must make sure that you specify the type of file(s) you allow. You have mentioned in your post that you want this for any type of file. This will be an issue.

For ex. If your site has images and if the end user clicks these images then they will be downloaded on his computer instead of opening in a new page. Got the point. So you need to specify the file extensions.

Could not complete the operation due to error 80020101. IE

wrap your entire code block in this:

//<![CDATA[

//code here

//]]>

also make sure to specify the type of script to be text/javascript

try that and let me know how it goes

"Object doesn't support property or method 'find'" in IE

I solved same issue by adding polyfill following:

<script src="https://cdn.polyfill.io/v3/polyfill.min.js?features=default,Array.prototype.includes,Array.prototype.find"></script>

A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern functionality on older browsers that do not natively support it.

Hope someone find this helpful.

Internet Explorer cache location

If you are using Dot.Net then the code you need is

Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)

Click my name if you want the code to delete these files plus FireFox temp files and Flash shared object/Flash Cookies

How do I get rid of an element's offset using CSS?

This seems weird, but you can try setting vertical-align: top in the CSS for the inputs. That fixes it in IE8, at least.

Input placeholders for Internet Explorer

I suggest you a simple function :

function bindInOut(element,value)
{
    element.focus(function()
    {
        if(element.val() == value) element.val('');         
    }).
    blur(function()
    {
        if(element.val() == '') element.val(value);
    });

    element.blur();
}

And to use it, call it in this way :

bindInOut($('#input'),'Here your value :)');

MSIE and addEventListener Problem in Javascript?

As of IE11, you need to use addEventListener. attachEvent is deprecated and throws an error.

The response content cannot be parsed because the Internet Explorer engine is not available, or

I have had this issue also, and while -UseBasicParsing will work for some, if you actually need to interact with the dom it wont work. Try using a a group policy to stop the initial configuration window from ever appearing and powershell won't stop you anymore. See here https://wahlnetwork.com/2015/11/17/solving-the-first-launch-configuration-error-with-powershells-invoke-webrequest-cmdlet/

Took me just a few minutes once I found this page, once the GP is set, powershell will allow you through.

addEventListener in Internet Explorer

As Delan said, you want to use a combination of addEventListener for newer versions, and attachEvent for older ones.

You'll find more information about event listeners on MDN. (Note there are some caveats with the value of 'this' in your listener).

You can also use a framework like jQuery to abstract the event handling altogether.

$("#someelementid").bind("click", function (event) {
   // etc... $(this) is whetver caused the event
});

Does Internet Explorer 8 support HTML 5?

IE8's HTML5 support is limited, but Internet Explorer 9 has just been released and has strong support for the new emerging HTML5 technologies.

jQuery not working with IE 11

The problem was caused because the page was an intranet site, & IE had compatibility mode set to default for this. IE11 does support addEventListener()

Force IE compatibility mode off using tags

After many hours troubleshooting this stuff... Here are some quick highlights that helped us from the X-UA-Compatible docs: http://msdn.microsoft.com/en-us/library/cc288325(VS.85).aspx#ctl00_contentContainer_ctl16

Using <meta http-equiv="X-UA-Compatible" content=" _______ " />

  • The Standard User Agent modes (the non-emulate ones) ignore <!DOCTYPE> directives in your page and render based on the standards supported by that version of IE (e.g., IE=8 will better obey table border spacing and some pseudo selectors than IE=7).

  • Whereas, the Emulate modes tell IE to follow any <!DOCTYPE> directives in your page, rendering standards mode based the version you choose and quirks mode based on IE=5

  • Possible values for the content attribute are:

    content="IE=5"

    content="IE=7"

    content="IE=EmulateIE7"

    content="IE=8"

    content="IE=EmulateIE8"

    content="IE=9"

    content="IE=EmulateIE9"

    content="IE=edge"

"Access is denied" JavaScript error when trying to access the document object of a programmatically-created <iframe> (IE-only)

if the document.domain property is set in the parent page, Internet Explorer gives me an "Access is denied"

Sigh. Yeah, it's an IE issue (bug? difficult to say as there is no documented standard for this kind of unpleasantness). When you create a srcless iframe it receives a document.domain from the parent document's location.host instead of its document.domain. At that point you've pretty much lost as you can't change it.

A horrendous workaround is to set src to a javascript: URL (urgh!):

 iframe.src= "javascript:'<html><body><p>Hello<\/p><script>do things;<\/script>'";

But for some reason, such a document is unable to set its own document.domain from script in IE (good old “unspecified error”), so you can't use that to regain a bridge between the parent(*). You could use it to write the whole document HTML, assuming the widget doesn't need to talk to its parent document once it's instantiated.

However iframe JavaScript URLs don't work in Safari, so you'd still need some kind of browser-sniffing to choose which method to use.

*: For some other reason, you can, in IE, set document.domain from a second document, document.written by the first document. So this works:

if (isIE)
    iframe.src= "javascript:'<script>window.onload=function(){document.write(\\'<script>document.domain=\\\""+document.domain+"\\\";<\\\\/script>\\');document.close();};<\/script>'";

At this point the hideousness level is too high for me, I'm out. I'd do the external HTML like David said.

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

Use a virtual machine. Start fresh as often as you want, and stop doing these hacks that may or may not simulate a clean machine.

Seriously, use VMWare or VirtualPC.

How can I prevent the backspace key from navigating back?

Most of the answers are in jquery. You can do this perfectly in pure Javascript, simple and no library required. This article was a good starting point for me but since keyIdentifier is deprecated, I wanted this code to be more secure so I added ||e.keyCode==8 to the if statement. Also, the code wasn't working well on Firefox so I added return false; and now it works perfectly well. Here it is:

<script type="text/javascript">
window.addEventListener('keydown',function(e){if(e.keyIdentifier=='U+0008'||e.keyIdentifier=='Backspace'||e.keyCode==8){if(e.target==document.body){e.preventDefault();return false;}}},true);
</script>

This code works great because,

  1. It is in pure javascript (no library required).
  2. Not only it checks the key pressed, it confirms if the action is really a browser "back" action.
  3. Together with the above, user can type and delete text from input text boxes on the web page without any problems while still preventing the back button action.
  4. It is short, clean, fast and straight to the point.

You can add console.log(e); for your your test purposes, and hit F12 in chrome, go to "console" tab and hit "backspace" on the page and look inside it to see what values are returned, then you can target all of those parameters to further enhance the code above to suit your needs.

IE Driver download location Link for Selenium

Use the below link to download IE Driver latest version

IE Driver

Background color on input type=button :hover state sticks in IE

You need to make sure images come first and put in a comma after the background image call. then it actually does work:

    background:url(egg.png) no-repeat 70px 2px #82d4fe; /* Old browsers */
background:url(egg.png) no-repeat 70px 2px, -moz-linear-gradient(top, #82d4fe 0%, #1db2ff 78%) ; /* FF3.6+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-gradient(linear, left top, left bottom, color-stop(0%,#82d4fe), color-stop(78%,#1db2ff)); /* Chrome,Safari4+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Chrome10+,Safari5.1+ */
background:url(egg.png) no-repeat 70px 2px, -o-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Opera11.10+ */
background:url(egg.png) no-repeat 70px 2px, -ms-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#82d4fe', endColorstr='#1db2ff',GradientType=0 ); /* IE6-9 */
background:url(egg.png) no-repeat 70px 2px, linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* W3C */

IE11 Document mode defaults to IE7. How to reset?

If the problem is happening on a specific computer,then please try the following fix provided you have Internet Explorer 11.

Please open regedit.exe as an Administrator. Navigate to the following path/paths:

  1. For 32 bit machine:

    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION
    
  2. For 64 bit machine:

    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION & 
    HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION
    

And delete the REG_DWORD value iexplore.exe.

Please close and relaunch the website using Internet Explorer 11, it will default to Edge as Document Mode.

How to set IE11 Document mode to edge as default?

I've come across this problem myself. In my case, resetting IE was the quickest solution to the problem:

http://support.microsoft.com/kb/923737

FIX CSS <!--[if lt IE 8]> in IE

    <!--[if IE]>
    <style type='text/css'>
    #header ul#h-menu li a{font-weight:normal!important}
    </style>
    <![endif]-->

will apply that style in all versions of IE.

What key in windows registry disables IE connection parameter "Automatically Detect Settings"?

Indeed, the 9th byte indicates the check state of the button, but the answers above don't take into account the checkbox which enables manual configuration. This check state value is also present in this ninth byte. The real answer should thus be:

Byte value

00001001 = Manual proxy is checked

00000101 = Use automatic configuration script is checked

00000011 = Automatically detect settings is checked

When multiple checkboxes are checked, the value of the 9th byte is the result of the bitwise OR operation on the values for which the checkbox is checked.

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

Spark - load CSV file as DataFrame?

In Java 1.8 This code snippet perfectly working to read CSV files

POM.xml

<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_2.11</artifactId>
    <version>2.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-sql_2.10 -->
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-sql_2.10</artifactId>
    <version>2.0.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.scala-lang/scala-library -->
<dependency>
    <groupId>org.scala-lang</groupId>
    <artifactId>scala-library</artifactId>
    <version>2.11.8</version>
</dependency>
<dependency>
    <groupId>com.databricks</groupId>
    <artifactId>spark-csv_2.10</artifactId>
    <version>1.4.0</version>
</dependency>

Java

SparkConf conf = new SparkConf().setAppName("JavaWordCount").setMaster("local");
// create Spark Context
SparkContext context = new SparkContext(conf);
// create spark Session
SparkSession sparkSession = new SparkSession(context);

Dataset<Row> df = sparkSession.read().format("com.databricks.spark.csv").option("header", true).option("inferSchema", true).load("hdfs://localhost:9000/usr/local/hadoop_data/loan_100.csv");

        //("hdfs://localhost:9000/usr/local/hadoop_data/loan_100.csv");
System.out.println("========== Print Schema ============");
df.printSchema();
System.out.println("========== Print Data ==============");
df.show();
System.out.println("========== Print title ==============");
df.select("title").show();

How can I print out C++ map values?

Since C++17 you can use range-based for loops together with structured bindings for iterating over your map. This improves readability, as you reduce the amount of needed first and second members in your code:

std::map<std::string, std::pair<std::string, std::string>> myMap;
myMap["x"] = { "a", "b" };
myMap["y"] = { "c", "d" };

for (const auto &[k, v] : myMap)
    std::cout << "m[" << k << "] = (" << v.first << ", " << v.second << ") " << std::endl;

Output:

m[x] = (a, b)
m[y] = (c, d)

Code on Coliru

Ruby value of a hash key?

How about this?

puts "ok" if hash_variable["key"] == "X"

You can access hash values with the [] operator

How to get current user who's accessing an ASP.NET application?

If you're using membership you can do: Membership.GetUser()

Your code is returning the Windows account which is assigned with ASP.NET.

Additional Info Edit: You will want to include System.Web.Security

using System.Web.Security

How to extract one column of a csv file

You could use awk for this. Change '$2' to the nth column you want.

awk -F "\"*,\"*" '{print $2}' textfile.csv

How to read all files in a folder from Java?

import java.io.File;


public class ReadFilesFromFolder {
  public static File folder = new File("C:/Documents and Settings/My Documents/Downloads");
  static String temp = "";

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Reading files under the folder "+ folder.getAbsolutePath());
    listFilesForFolder(folder);
  }

  public static void listFilesForFolder(final File folder) {

    for (final File fileEntry : folder.listFiles()) {
      if (fileEntry.isDirectory()) {
        // System.out.println("Reading files under the folder "+folder.getAbsolutePath());
        listFilesForFolder(fileEntry);
      } else {
        if (fileEntry.isFile()) {
          temp = fileEntry.getName();
          if ((temp.substring(temp.lastIndexOf('.') + 1, temp.length()).toLowerCase()).equals("txt"))
            System.out.println("File= " + folder.getAbsolutePath()+ "\\" + fileEntry.getName());
        }

      }
    }
  }
}

How can I create a carriage return in my C# string

myString += Environment.NewLine;

myString = myString + Environment.NewLine;

Making HTTP Requests using Chrome Developer tools

If your web page has jquery in your page, then you can do it writing on chrome developers console:

$.get(
    "somepage.php",
    {paramOne : 1, paramX : 'abc'},
    function(data) {
       alert('page content: ' + data);
    }
);

Its jquery way of doing it!

How to call a function, PostgreSQL

you declare your function as returning boolean, but it never returns anything.

Key Value Pair List

Using one of the subsets method in this question

var list = new List<KeyValuePair<string, int>>() { 
    new KeyValuePair<string, int>("A", 1),
    new KeyValuePair<string, int>("B", 0),
    new KeyValuePair<string, int>("C", 0),
    new KeyValuePair<string, int>("D", 2),
    new KeyValuePair<string, int>("E", 8),
};

int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);

EDIT

a full console application:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<KeyValuePair<string, int>>() { 
                new KeyValuePair<string, int>("A", 1),
                new KeyValuePair<string, int>("B", 2),
                new KeyValuePair<string, int>("C", 3),
                new KeyValuePair<string, int>("D", 4),
                new KeyValuePair<string, int>("E", 5),
                new KeyValuePair<string, int>("F", 6),
            };

            int input = 12;
            var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);

            foreach (var res in alternatives)
            {
                Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
            }
            Console.WriteLine("END");
            Console.ReadLine();
        }
    }

    public static class Extenions
    {
        public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
        {
            List<T> list = enumerable.ToList();
            ulong upper = (ulong)1 << list.Count;

            for (ulong i = 0; i < upper; i++)
            {
                List<T> l = new List<T>(list.Count);
                for (int j = 0; j < sizeof(ulong) * 8; j++)
                {
                    if (((ulong)1 << j) >= upper) break;

                    if (((i >> j) & 1) == 1)
                    {
                        l.Add(list[j]);
                    }
                }

                yield return l;
            }
        }
    }
}

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

New .NET 5 Solution:

In .NET 5, a new class has been introduced called JsonContent, which derives from HttpContent. See in Microsoft docs

This class has a static method called Create(), which takes an object as a parameter.

Usage:

var myObject = new
{
    foo = "Hello",
    bar = "World",
};

JsonContent content = JsonContent.Create(myObject);

HttpResponseMessage response = await _httpClient.PostAsync("https://...", content);

Change the Theme in Jupyter Notebook?

Instead of installing a library inside Jupyter, I would recommend you use the 'Dark Reader' extension in Chrome (you can find 'Dark Reader' extension in other browsers, e.g. Firefox). You can play with it; filter the URL(s) you want to have dark theme, or even how define the Dark theme for yourself. Below are couple of examples:

enter image description here

enter image description here

I hope it helps.

Visual Studio: How to break on handled exceptions?

Check Managing Exceptions with the Debugger page, it explains how to set this up.

Essentially, here are the steps (during debugging):

  1. On the Debug menu, click Exceptions.

  2. In the Exceptions dialog box, select Thrown for an entire category of exceptions, for example, Common Language Runtime Exceptions.

    -or-

    Expand the node for a category of exceptions, for example, Common Language Runtime Exceptions, and select Thrown for a specific exception within that category.

How to increment a number by 2 in a PHP For Loop

You should do it like this:

 for ($i=1; $i <=10; $i+=2) 
{ 
    echo $i.'<br>';
}

"+=" you can increase your variable as much or less you want. "$i+=5" or "$i+=.5"

Get screen width and height in Android

Kotlin Version via Extension Property

If you want to know the size of the screen in pixels as well as dp, using these extension properties really helps:


DimensionUtils.kt

import android.content.res.Resources
import android.graphics.Rect
import android.graphics.RectF
import android.util.DisplayMetrics
import kotlin.math.roundToInt

/**
 * @author aminography
 */

private val displayMetrics: DisplayMetrics by lazy { Resources.getSystem().displayMetrics }

val screenRectPx: Rect
    get() = displayMetrics.run { Rect(0, 0, widthPixels, heightPixels) }

val screenRectDp: RectF
    get() = displayMetrics.run { RectF(0f, 0f, widthPixels.px2dp, heightPixels.px2dp) }

val Number.px2dp: Float
    get() = this.toFloat() / displayMetrics.density

val Number.dp2px: Int
    get() = (this.toFloat() * displayMetrics.density).roundToInt()


Usage:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val widthPx = screenRectPx.width()
        val heightPx = screenRectPx.height()
        println("[PX] screen width: $widthPx , height: $heightPx")

        val widthDp = screenRectDp.width()
        val heightDp = screenRectDp.height()
        println("[DP] screen width: $widthDp , height: $heightDp")
    }
}

Result:

When the device is in portrait orientation:

[PX] screen width: 1440 , height: 2392
[DP] screen width: 360.0 , height: 598.0

When the device is in landscape orientation:

[PX] screen width: 2392 , height: 1440
[DP] screen width: 598.0 , height: 360.0

How should I escape strings in JSON?

For those who came here looking for a command-line solution, like me, cURL's --data-urlencode works fine:

curl -G -v -s --data-urlencode 'query={"type" : "/music/artist"}' 'https://www.googleapis.com/freebase/v1/mqlread'

sends

GET /freebase/v1/mqlread?query=%7B%22type%22%20%3A%20%22%2Fmusic%2Fartist%22%7D HTTP/1.1

, for example. Larger JSON data can be put in a file and you'd use the @ syntax to specify a file to slurp in the to-be-escaped data from. For example, if

$ cat 1.json 
{
  "type": "/music/artist",
  "name": "The Police",
  "album": []
}

you'd use

curl -G -v -s --data-urlencode [email protected] 'https://www.googleapis.com/freebase/v1/mqlread'

And now, this is also a tutorial on how to query Freebase from the command line :-)

How using try catch for exception handling is best practice

The only time you should worry your users about something that happened in the code is if there is something they can or need to do to avoid the issue. If they can change data on a form, push a button or change a application setting in order to avoid the issue then let them know. But warnings or errors that the user has no ability to avoid just makes them lose confidence in your product.

Exceptions and Logs are for you, the developer, not your end user. Understanding the right thing to do when you catch each exception is far better than just applying some golden rule or rely on an application-wide safety net.

Mindless coding is the ONLY kind of wrong coding. The fact that you feel there is something better that can be done in those situations shows that you are invested in good coding, but avoid trying to stamp some generic rule in these situations and understand the reason for something to throw in the first place and what you can do to recover from it.

CSS Classes & SubClasses

The class you apply on the div can be used to as a reference point to style elements with that div, for example.

<div class="area1">
    <table>
        <tr>
                <td class="item">Text Text Text</td>
                <td class="item">Text Text Text</td>
        </tr>
    </table>
</div>


.area1 { border:1px solid black; }

.area1 td { color:red; } /* This will effect any TD within .area1 */

To be super semantic you should move the class onto the table.

    <table class="area1">
        <tr>
                <td>Text Text Text</td>
                <td>Text Text Text</td>
        </tr>
    </table>

Ansible: filter a list by its attributes

To filter a list of dicts you can use the selectattr filter together with the equalto test:

network.addresses.private_man | selectattr("type", "equalto", "fixed")

The above requires Jinja2 v2.8 or later (regardless of Ansible version).


Ansible also has the tests match and search, which take regular expressions:

match will require a complete match in the string, while search will require a match inside of the string.

network.addresses.private_man | selectattr("type", "match", "^fixed$")

To reduce the list of dicts to a list of strings, so you only get a list of the addr fields, you can use the map filter:

... | map(attribute='addr') | list

Or if you want a comma separated string:

... | map(attribute='addr') | join(',')

Combined, it would look like this.

- debug: msg={{ network.addresses.private_man | selectattr("type", "equalto", "fixed") | map(attribute='addr') | join(',') }}

How to get String Array from arrays.xml file

Your array.xml is not right. change it to like this

Here is array.xml file

<?xml version="1.0" encoding="utf-8"?>  
<resources>  
    <string-array name="testArray">  
        <item>first</item>  
        <item>second</item>  
        <item>third</item>  
        <item>fourth</item>  
        <item>fifth</item>  
   </string-array>
</resources>

To show error message without alert box in Java Script

Try like this:

function validate(el, status){
     var targetVal = document.getElementById(el).value;
     var statusEl = document.getElementById(status);
     if(targetVal.length > 0){
        statusEl.innerHTML = '';
  }
     else{
        statusEL.innerHTML = "Invalid Name";
   }
}

Now HTML:

<!doctype html>
<html lang='en'>
<head>
<title>Derp...</title>
</head>
<body>
<form name="myform">
  First_Name
  <input type="text" id="fname" name="fname" onblur="validate('fname','fnameStatus')">
  <br />
  <span id="fnameStatus"></span>
  <br />
  Last_Name
  <input type="text" id="lname" name="lname" onblur="validate('lname','lnameStatus')"> 
  <br />
  <span id="lnameStatus"></span>
  <br />
  <input type=button value=check> 
</form>
</body>
</html>

Draw radius around a point in Google map

Using the Google Maps API V3, create a Circle object, then use bindTo() to tie it to the position of your Marker (since they are both google.maps.MVCObject instances).

// Create marker 
var marker = new google.maps.Marker({
  map: map,
  position: new google.maps.LatLng(53, -2.5),
  title: 'Some location'
});

// Add circle overlay and bind to marker
var circle = new google.maps.Circle({
  map: map,
  radius: 16093,    // 10 miles in metres
  fillColor: '#AA0000'
});
circle.bindTo('center', marker, 'position');

You can make it look just like the Google Latitude circle by changing the fillColor, strokeColor, strokeWeight etc (full API).

See more source code and example screenshots.

python for increment inner loop

I read all the above answers and those are actually good.

look at this code:

for i in range(1, 4):
    print("Before change:", i)
    i = 20 # changing i variable
    print("After change:", i) # this line will always print 20

When we execute above code the output is like below,

Before Change: 1
After change: 20
Before Change: 2
After change: 20
Before Change: 3
After change: 20

in python for loop is not trying to increase i value. for loop is just assign values to i which we gave. Using range(4) what we are doing is we give the values to for loop which need assign to the i.

You can use while loop instead of for loop to do same thing what you want,

i = 0
while i < 6:
    print(i)
    j = 0
    while j < 5:
        i += 2 # to increase `i` by 2

This will give,

0
2
4

Thank you !

How to respond to clicks on a checkbox in an AngularJS directive?

I prefer to use the ngModel and ngChange directives when dealing with checkboxes. ngModel allows you to bind the checked/unchecked state of the checkbox to a property on the entity:

<input type="checkbox" ng-model="entity.isChecked">

Whenever the user checks or unchecks the checkbox the entity.isChecked value will change too.

If this is all you need then you don't even need the ngClick or ngChange directives. Since you have the "Check All" checkbox, you obviously need to do more than just set the value of the property when someone checks a checkbox.

When using ngModel with a checkbox, it's best to use ngChange rather than ngClick for handling checked and unchecked events. ngChange is made for just this kind of scenario. It makes use of the ngModelController for data-binding (it adds a listener to the ngModelController's $viewChangeListeners array. The listeners in this array get called after the model value has been set, avoiding this problem).

<input type="checkbox" ng-model="entity.isChecked" ng-change="selectEntity()">

... and in the controller ...

var model = {};
$scope.model = model;

// This property is bound to the checkbox in the table header
model.allItemsSelected = false;

// Fired when an entity in the table is checked
$scope.selectEntity = function () {
    // If any entity is not checked, then uncheck the "allItemsSelected" checkbox
    for (var i = 0; i < model.entities.length; i++) {
        if (!model.entities[i].isChecked) {
            model.allItemsSelected = false;
            return;
        }
    }

    // ... otherwise ensure that the "allItemsSelected" checkbox is checked
    model.allItemsSelected = true;
};

Similarly, the "Check All" checkbox in the header:

<th>
    <input type="checkbox" ng-model="model.allItemsSelected" ng-change="selectAll()">
</th>

... and ...

// Fired when the checkbox in the table header is checked
$scope.selectAll = function () {
    // Loop through all the entities and set their isChecked property
    for (var i = 0; i < model.entities.length; i++) {
        model.entities[i].isChecked = model.allItemsSelected;
    }
};

CSS

What is the best way to... add a CSS class to the <tr> containing the entity to reflect its selected state?

If you use the ngModel approach for the data-binding, all you need to do is add the ngClass directive to the <tr> element to dynamically add or remove the class whenever the entity property changes:

<tr ng-repeat="entity in model.entities" ng-class="{selected: entity.isChecked}">

See the full Plunker here.

session handling in jquery

Assuming you're referring to this plugin, your code should be:

// To Store
$(function() {
    $.session.set("myVar", "value");
});


// To Read
$(function() {
    alert($.session.get("myVar"));
});

Before using a plugin, remember to read its documentation in order to learn how to use it. In this case, an usage example can be found in the README.markdown file, which is displayed on the project page.

How to wait till the response comes from the $http request, in angularjs?

You should use promises for async operations where you don't know when it will be completed. A promise "represents an operation that hasn't completed yet, but is expected in the future." (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)

An example implementation would be like:

myApp.factory('myService', function($http) {

    var getData = function() {

        // Angular $http() and then() both return promises themselves 
        return $http({method:"GET", url:"/my/url"}).then(function(result){

            // What we return here is the data that will be accessible 
            // to us after the promise resolves
            return result.data;
        });
    };


    return { getData: getData };
});


function myFunction($scope, myService) {
    var myDataPromise = myService.getData();
    myDataPromise.then(function(result) {  

       // this is only run after getData() resolves
       $scope.data = result;
       console.log("data.name"+$scope.data.name);
    });
}

Edit: Regarding Sujoys comment that What do I need to do so that myFuction() call won't return till .then() function finishes execution.

function myFunction($scope, myService) { 
    var myDataPromise = myService.getData(); 
    myDataPromise.then(function(result) { 
         $scope.data = result; 
         console.log("data.name"+$scope.data.name); 
    }); 
    console.log("This will get printed before data.name inside then. And I don't want that."); 
 }

Well, let's suppose the call to getData() took 10 seconds to complete. If the function didn't return anything in that time, it would effectively become normal synchronous code and would hang the browser until it completed.

With the promise returning instantly though, the browser is free to continue on with other code in the meantime. Once the promise resolves/fails, the then() call is triggered. So it makes much more sense this way, even if it might make the flow of your code a bit more complex (complexity is a common problem of async/parallel programming in general after all!)

How to divide two columns?

Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.

e.g. if you do this:

SELECT 1 / 2

you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.

e.g.

SELECT CAST(1 AS DECIMAL) / 2

gives 0.500000

Scroll Automatically to the Bottom of the Page

jQuery isn't necessary. Most of the top results I got from a Google search gave me this answer:

window.scrollTo(0,document.body.scrollHeight);

Where you have nested elements, the document might not scroll. In this case, you need to target the element that scrolls and use it's scroll height instead.

window.scrollTo(0,document.querySelector(".scrollingContainer").scrollHeight);

You can tie that to the onclick event of your question (i.e. <div onclick="ScrollToBottom()" ...).

Some additional sources you can take a look at:

Getting "conflicting types for function" in C, why?

Watch again:

char dest[5];
char src[5] = "test";

printf("String: %s\n", do_something(dest, src));

Focus on this line:

printf("String: %s\n", do_something(dest, src));

You can clearly see that the do_something function is not declared!

If you look a little further,

printf("String: %s\n", do_something(dest, src));

char *do_something(char *dest, const char *src)
{
return dest;
}

you will see that you declare the function after you use it.

You will need to modify this part with this code:

char *do_something(char *dest, const char *src)
{
return dest;
}

printf("String: %s\n", do_something(dest, src));

Cheers ;)

How to add row of data to Jtable from values received from jtextfield and comboboxes

you can use this code as template please customize it as per your requirement.

DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

Issue with background color and Google Chrome

I had the same issue on a couple of sites and fixed it by moving the background styling from body to html (which I guess is a variation of the body {} to html, body{} technique already mentioned but shows that you can make do with the style on html only), e.g.

body {
   background-color:#000000;
   background-image:url('images/bg.png');
   background-repeat:repeat-x;
   font-family:Arial,Helvetica,sans-serif;
   font-size:85%;
   color:#cccccc;

}

becomes

html {
   background-color:#000000;
   background-image:url('images/bg.png');
   background-repeat:repeat-x;
}
body {
   font-family:Arial,Helvetica,sans-serif;
   font-size:85%;
   color:#cccccc;
}

This worked in IE6-8, Chrome 4-5, Safari 4, Opera 10 and Firefox 3.x with no obvious nasty side-effects.

Sum all values in every column of a data.frame in R

mapply(sum,people[,-1])

Height Weight 
   199    425 

How to play a local video with Swift?

another Swift 3 Example. The provided solution did not work for me.

private func playVideo(from file:String) {
    let file = file.components(separatedBy: ".")

    guard let path = Bundle.main.path(forResource: file[0], ofType:file[1]) else {
        debugPrint( "\(file.joined(separator: ".")) not found")
        return
    }
    let player = AVPlayer(url: URL(fileURLWithPath: path))

    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = self.view.bounds
    self.view.layer.addSublayer(playerLayer)
    player.play()
}

useage:

playVideo(from: "video.extension")

Note: Check Copy Bundle Resources under Build Phases to ensure that the video is available to the Project.

Is there such a thing as min-font-size and max-font-size?

Please note that setting font-sizing with px is not recommended due to accessibility concerns:

"defining font sizes in px is not accessible, because the user cannot change the font size in some browsers. For example, users with limited vision may wish to set the font size much larger than the size chosen by a web designer." (see https://developer.mozilla.org/en-US/docs/Web/CSS/font-size)

A more accessible approach is to set font-size: 100% in the html, which respects user default size settings, and THEN using either percentages or relative units when resizing (em or rem), for example with a @media query.

(see https://betterwebtype.com/articles/2019/06/16/5-keys-to-accessible-web-typography/)

Can't install any packages in Node.js using "npm install"

This error might also occur due to proxy settings, once check that your proxy allow the access to npm commands.

It worked for me quite well.

Git Bash doesn't see my PATH

For those of you who have tried all the above mentioned methods including Windows system env. variables, .bashrc, .bashprofile, etc. AND can see the correct path in 'echo $PATH' ... I may have a solution for you.

suppress the errors using exec 2> /dev/null

My script runs fine but was throwing 'command not found' or 'No directory found' errors even though, as far as I can tell, the paths were flush. So, if you suppress those errors (might have to also add 'set +e'), than it works properly.

Can ordered list produce result that looks like 1.1, 1.2, 1.3 (instead of just 1, 2, 3, ...) with css?

None of solutions on this page works correctly and universally for all levels and long (wrapped) paragraphs. It’s really tricky to achieve a consistent indentation due to variable size of marker (1., 1.2, 1.10, 1.10.5, …); it can’t be just “faked,” not even with a precomputed margin/padding for each possible indentation level.

I finally figured out a solution that actually works and doesn’t need any JavaScript.

It’s tested on Firefox 32, Chromium 37, IE 9 and Android Browser. Doesn't work on IE 7 and previous.

CSS:

ol {
  list-style-type: none;
  counter-reset: item;
  margin: 0;
  padding: 0;
}

ol > li {
  display: table;
  counter-increment: item;
  margin-bottom: 0.6em;
}

ol > li:before {
  content: counters(item, ".") ". ";
  display: table-cell;
  padding-right: 0.6em;    
}

li ol > li {
  margin: 0;
}

li ol > li:before {
  content: counters(item, ".") " ";
}

Example: Example

Try it on JSFiddle, fork it on Gist.

Apache Proxy: No protocol handler was valid

For my Apache2.4 + php5-fpm installation to start working, I needed to activate the following Apache modules:

sudo a2enmod proxy
sudo a2enmod proxy_fcgi

No need for proxy_http, and this is what sends all .php files straight to php5-fpm:

<FilesMatch \.php$>
    SetHandler "proxy:unix:/var/run/php5-fpm.sock|fcgi://localhost"
</FilesMatch>

How to use a decimal range() step value?

I know I'm late to the party here, but here's a trivial generator solution that's working in 3.6:

def floatRange(*args):
    start, step = 0, 1
    if len(args) == 1:
        stop = args[0]
    elif len(args) == 2:
        start, stop = args[0], args[1]
    elif len(args) == 3:
        start, stop, step = args[0], args[1], args[2]
    else:
        raise TypeError("floatRange accepts 1, 2, or 3 arguments. ({0} given)".format(len(args)))
    for num in start, step, stop:
        if not isinstance(num, (int, float)):
            raise TypeError("floatRange only accepts float and integer arguments. ({0} : {1} given)".format(type(num), str(num)))
    for x in range(int((stop-start)/step)):
        yield start + (x * step)
    return

then you can call it just like the original range()... there's no error handling, but let me know if there is an error that can be reasonably caught, and I'll update. or you can update it. this is StackOverflow.

How do I remove the title bar from my app?

  1. open styles.xml
  2. insert
 <style name="no_title" parent="AppTheme">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowContentOverlay">@null</item>
 </style>

you can change name="---------"

  1. open Androidmaifest.xm

    find android:theme="@style/AppTheme" chang to android:theme="@style/no_title"

  2. click select Theme on menubar (it's green color near MainActivity)

    • click project Theme
    • click no_title (on you right hand Side)
    • click OK

What does the "yield" keyword do?

There is another yield use and meaning (since Python 3.3):

yield from <expr>

From PEP 380 -- Syntax for Delegating to a Subgenerator:

A syntax is proposed for a generator to delegate part of its operations to another generator. This allows a section of code containing 'yield' to be factored out and placed in another generator. Additionally, the subgenerator is allowed to return with a value, and the value is made available to the delegating generator.

The new syntax also opens up some opportunities for optimisation when one generator re-yields values produced by another.

Moreover this will introduce (since Python 3.5):

async def new_coroutine(data):
   ...
   await blocking_action()

to avoid coroutines being confused with a regular generator (today yield is used in both).

"for loop" with two variables?

Any reason you can't use a nested for loop?

for i in range(x):
   for j in range(y):
       #code that uses i and j

How to Automatically Close Alerts using Twitter Bootstrap

Using the 'close' action on the alert does not work for me, because it removes the alert from the DOM and I need the alert multiple times (I'm posting data with ajax and I show a message to the user on every post). So I created this function that create the alert every time I need it and then starts a timer to close the created alert. I pass into the function the id of the container to which I want to append the alert, the type of alert ('success', 'danger', etc.) and the message. Here is my code:

function showAlert(containerId, alertType, message) {
    $("#" + containerId).append('<div class="alert alert-' + alertType + '" id="alert' + containerId + '">' + message + '</div>');
    $("#alert" + containerId).alert();
    window.setTimeout(function () { $("#alert" + containerId).alert('close'); }, 2000);
}

Using BETWEEN in CASE SQL statement

You do not specify why you think it is wrong but I can se two dangers:

BETWEEN can be implemented differently in different databases sometimes it is including the border values and sometimes excluding, resulting in that 1 and 31 of january would end up NOTHING. You should test how you database does this.

Also, if RATE_DATE contains hours also 2010-01-31 might be translated to 2010-01-31 00:00 which also would exclude any row with an hour other that 00:00.

When should an Excel VBA variable be killed or set to Nothing?

I have at least one situation where the data is not automatically cleaned up, which would eventually lead to "Out of Memory" errors. In a UserForm I had:

Public mainPicture As StdPicture
...
mainPicture = LoadPicture(PAGE_FILE)

When UserForm was destroyed (after Unload Me) the memory allocated for the data loaded in the mainPicture was not being de-allocated. I had to add an explicit

mainPicture = Nothing

in the terminate event.

How can I change Mac OS's default Java VM returned from /usr/libexec/java_home

I had a similar situation, and the following process worked for me:

  1. In the terminal, type

    vi ~/.profile
    
  2. Then add this line in the file, and save

    export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk<version>.jdk/Contents/Home
    

    where version is the one on your computer, such as 1.7.0_25

  3. Exit the editor, then type the following command make it become effective

    source ~/.profile 
    

Then type java -version to check the result

    java -version 

What is .profile? From:http://computers.tutsplus.com/tutorials/speed-up-your-terminal-workflow-with-command-aliases-and-profile--mac-30515

.profile file is a hidden file. It is an optional file which tells the system which commands to run when the user whose profile file it is logs in. For example, if my username is bruno and there is a .profile file in /Users/bruno/, all of its contents will be executed during the log-in procedure.

Ignore .classpath and .project from Git

Add the below lines in .gitignore and place the file inside ur project folder

/target/
/.classpath
/*.project
/.settings
/*.springBeans

instanceof Vs getClass( )

Do you want to match a class exactly, e.g. only matching FileInputStream instead of any subclass of FileInputStream? If so, use getClass() and ==. I would typically do this in an equals, so that an instance of X isn't deemed equal to an instance of a subclass of X - otherwise you can get into tricky symmetry problems. On the other hand, that's more usually useful for comparing that two objects are of the same class than of one specific class.

Otherwise, use instanceof. Note that with getClass() you will need to ensure you have a non-null reference to start with, or you'll get a NullPointerException, whereas instanceof will just return false if the first operand is null.

Personally I'd say instanceof is more idiomatic - but using either of them extensively is a design smell in most cases.

What can MATLAB do that R cannot do?

Support for interactive graphics is much better in matlab than in R. I hate matlab as a language, but I get jealous when I see how its users can explore data with mouse operations, while I'm busy repeating commands with new values for xlim etc. Matlab also handles multi-panel plots much better than any of the R methods for the task. Generally, R graphics has a 1960s feel. It's fine for publication, but not the best solution for interactive exploration of data.

How can I test that a variable is more than eight characters in PowerShell?

You can also use -match against a Regular expression. Ex:

if ($dbUserName -match ".{8}" )
{
    Write-Output " Please enter more than 8 characters "
    $dbUserName=read-host " Re-enter database user name"
}

Also if you're like me and like your curly braces to be in the same horizontal position for your code blocks, you can put that on a new line, since it's expecting a code block it will look on next line. In some commands where the first curly brace has to be in-line with your command, you can use a grave accent marker (`) to tell powershell to treat the next line as a continuation.

Display Yes and No buttons instead of OK and Cancel in Confirm box?

There is the Jquery alert plugin

$.alerts.okButton = ' Yes ';
$.alerts.cancelButton = ' No ';

How to create a DataFrame of random integers with Pandas?

numpy.random.randint accepts a third argument (size) , in which you can specify the size of the output array. You can use this to create your DataFrame -

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

Here - np.random.randint(0,100,size=(100, 4)) - creates an output array of size (100,4) with random integer elements between [0,100) .


Demo -

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

which produces:

     A   B   C   D
0   45  88  44  92
1   62  34   2  86
2   85  65  11  31
3   74  43  42  56
4   90  38  34  93
5    0  94  45  10
6   58  23  23  60
..  ..  ..  ..  ..

Contain an image within a div?

Here is javascript I wrote to do just this.

function ImageTile(parentdiv, imagediv) {
imagediv.style.position = 'absolute';

function load(image) {
    //
    // Reset to auto so that when the load happens it resizes to fit our image and that
    // way we can tell what size our image is. If we don't do that then it uses the last used
    // values to auto-size our image and we don't know what the actual size of the image is.
    //
    imagediv.style.height = "auto";
    imagediv.style.width = "auto";
    imagediv.style.top = 0;
    imagediv.style.left = 0;

    imagediv.src = image;
}

//bind load event (need to wait for it to finish loading the image)
imagediv.onload = function() {
    var vpWidth = parentdiv.clientWidth;
    var vpHeight = parentdiv.clientHeight;
    var imgWidth = this.clientWidth;
    var imgHeight = this.clientHeight;

    if (imgHeight > imgWidth) {
        this.style.height = vpHeight + 'px';
        var width = ((imgWidth/imgHeight) * vpHeight);
        this.style.width = width + 'px';
        this.style.left = ((vpWidth - width)/2) + 'px';
    } else {
        this.style.width = vpWidth + 'px';
        var height = ((imgHeight/imgWidth) * vpWidth);
        this.style.height = height + 'px';
        this.style.top = ((vpHeight - height)/2) + 'px';
    }
};

return {
    "load": load
};

}

And to use it just do something like this:

 var tile1 = ImageTile(document.documentElement, document.getElementById("tile1"));
 tile1.load(url);

I use this for a slideshow in which I have two of these "tiles" and I fade one out and the other in. The loading is done on the "tile" that is not visible to avoid the jarring visual affect of the resetting of the style back to "auto".

How to redirect the output of a PowerShell to a file during its execution

Microsoft has announced on Powershell's Connections web site (2012-02-15 at 4:40 PM) that in version 3.0 they have extended the redirection as a solution to this problem.

In PowerShell 3.0, we've extended output redirection to include the following streams: 
 Pipeline (1) 
 Error    (2) 
 Warning  (3) 
 Verbose  (4) 
 Debug    (5)
 All      (*)

We still use the same operators
 >    Redirect to a file and replace contents
 >>   Redirect to a file and append to existing content
 >&1  Merge with pipeline output

See the "about_Redirection" help article for details and examples.

help about_Redirection

"std::endl" vs "\n"

If you use Qt and endl, you could accidentally end up using an incorrect endl which gives you very surprising results. See the following code snippet:

#include <iostream>
#include <QtCore/QtCore> 
#include <QtGui/QtGui>

// notice that there is no "using namespace std;"
int main(int argc, char** argv)
{
    QApplication qapp(argc,argv);
    QMainWindow mw;
    mw.show();
    std::cout << "Finished Execution!" << endl;
    // This prints something similar to: "Finished Execution!67006AB4"
    return qapp.exec();
}

Note that I wrote endl instead of std::endl (which would have been correct) and apparently there is a endl function defined in qtextstream.h (which is part of QtCore).

Using "\n" instead of endl completely sidesteps any potential namespace issues. This is also a good example why putting symbols into the global namespace (like Qt does by default) is a bad idea.

Permanently adding a file path to sys.path in Python

There are a few ways. One of the simplest is to create a my-paths.pth file (as described here). This is just a file with the extension .pth that you put into your system site-packages directory. On each line of the file you put one directory name, so you can put a line in there with /path/to/the/ and it will add that directory to the path.

You could also use the PYTHONPATH environment variable, which is like the system PATH variable but contains directories that will be added to sys.path. See the documentation.

Note that no matter what you do, sys.path contains directories not files. You can't "add a file to sys.path". You always add its directory and then you can import the file.

How can I count the number of characters in a Bash variable

Use the wc utility with the print the byte counts (-c) option:

$ SO="stackoverflow"
$ echo -n "$SO" | wc -c
    13

You'll have to use the do not output the trailing newline (-n) option for echo. Otherwise, the newline character will also be counted.

System.Data.OracleClient requires Oracle client software version 8.1.7

Update 1: It is possible for different users to have different path. But its not the likely problem here. There is more chance that the user that the iwam user doesn't have permission to the oracle client directory.

Update 0: Its suppose to work. Check for environment variable ( That are needed to find the oracle client and tnsnames.ora ). Also, Maybe you have a 32/64 bit issues. Also, consider using the Oracle Data Provider for .NET ( search for odp.net)

Finding Android SDK on Mac and adding to PATH

1. How to find it

  • Open Android studio, go to Android Studio > Preferences
  • Search for sdk
  • Something similar to this (this is a Windows box as you can see) will show

You can see the location there – most of the time it is:

/Users/<name>/Library/Android/sdk

2. How to install it, if not there

Standalone SDK download page

3. How to add it to the path

Open your Terminal edit your ~/.bash_profile file in nano by typing:

nano ~/.bash_profile

If you use Zsh, edit ~/.zshrc instead.

Go to the end of the file and add the directory path to your $PATH:

export PATH="${HOME}/Library/Android/sdk/tools:${HOME}/Library/Android/sdk/platform-tools:${PATH}"
  • Save it by pressing Ctrl+X
  • Restart the Terminal
  • To see if it is working or not, type in the name of any file or binary which are inside the directories that you've added (e.g. adb) and verify it is opened/executed

How to increase the execution timeout in php?

To really increase the time limit i prefer to first get the current value. set_time_limit is not always increasing the time limit. If the current value (e.g. from php.ini or formerly set) is higher than the value used in current call of set_time_limit, it will decrease the time limit!

So what's with a small helper like this?

/**
 * @param int $seconds Time in seconds
 * @return bool
 */
function increase_time_limit(int $seconds): bool
{
    return set_time_limit(max(
        ini_get('max_execution_time'), $seconds
    ));
}

// somewhere else in your code
increase_time_limit(180);

See also: Get max_execution_time in PHP script

How to find all the tables in MySQL with specific column names in them?

If you want "To get all tables only", Then use this query:

SELECT TABLE_NAME 
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME like '%'
and TABLE_SCHEMA = 'tresbu_lk'

If you want "To get all tables with Columns", Then use this query:

SELECT DISTINCT TABLE_NAME, COLUMN_NAME  
FROM INFORMATION_SCHEMA.COLUMNS  
WHERE column_name LIKE '%'  
AND TABLE_SCHEMA='tresbu_lk'

What is the path for the startup folder in windows 2008 server

SHGetKnownFolderPath:

Retrieves the full path of a known folder identified by the folder's KNOWNFOLDERID.

And, FOLDERID_CommonStartup:

Default Path %ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\StartUp

There are also managed equivalents, but you haven't told us what you're programming in.

count number of characters in nvarchar column

text doesn't work with len function.

ntext, text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead. For more information, see Using Large-Value Data Types.

Source

sqlite3.OperationalError: unable to open database file

had the same problem but top answer is too long for me so I suggest to open another shell window type cd #enter and try again

Read Variable from Web.Config

Assuming the key is contained inside the <appSettings> node:

ConfigurationSettings.AppSettings["theKey"];

As for "writing" - put simply, dont.

The web.config is not designed for that, if you're going to be changing a value constantly, put it in a static helper class.

'Property does not exist on type 'never'

I had the same error and replaced the dot notation with bracket notation to suppress it.

e.g.: obj.name -> obj['name']

Minimum 6 characters regex expression

This match 6 or more any chars but newline:

/^.{6,}$/

error: invalid type argument of ‘unary *’ (have ‘int’)

Barebones C program to produce the above error:

#include <iostream>
using namespace std;
int main(){
    char *p;
    *p = 'c';

    cout << *p[0];  
    //error: invalid type argument of `unary *'
    //peeking too deeply into p, that's a paddlin.

    cout << **p;    
    //error: invalid type argument of `unary *'
    //peeking too deeply into p, you better believe that's a paddlin.
}

ELI5:

The master puts a shiny round stone inside a small box and gives it to a student. The master says: "Open the box and remove the stone". The student does so.

Then the master says: "Now open the stone and remove the stone". The student said: "I can't open a stone".

The student was then enlightened.

Bootstrap Carousel Full Screen

You can do it without forcing html and body to me 100% height. Use view port height instead. And with mouse wheel control too.

_x000D_
_x000D_
function debounce(func, wait, immediate) {_x000D_
  var timeout;_x000D_
  return function() {_x000D_
    var context = this,_x000D_
      args = arguments;_x000D_
    var later = function() {_x000D_
      timeout = null;_x000D_
      if (!immediate) func.apply(context, args);_x000D_
    };_x000D_
    var callNow = immediate && !timeout;_x000D_
    clearTimeout(timeout);_x000D_
    timeout = setTimeout(later, wait);_x000D_
    if (callNow) func.apply(context, args);_x000D_
  };_x000D_
}_x000D_
_x000D_
var slider = document.getElementById("demo");_x000D_
var onScroll = debounce(function(direction) {_x000D_
  //console.log(direction);_x000D_
  if (direction == false) {_x000D_
   $('.carousel-control-next').click();_x000D_
  } else {_x000D_
   $('.carousel-control-prev').click();_x000D_
  }_x000D_
}, 100, true);_x000D_
_x000D_
slider.addEventListener("wheel", function(e) {_x000D_
  e.preventDefault();_x000D_
  var delta;_x000D_
  if (event.wheelDelta) {_x000D_
    delta = event.wheelDelta;_x000D_
  } else {_x000D_
    delta = -1 * event.deltaY;_x000D_
  }_x000D_
_x000D_
  onScroll(delta >= 0);_x000D_
});
_x000D_
.carousel-item {_x000D_
  height: 100vh;_x000D_
  background: #212121;_x000D_
}_x000D_
_x000D_
.carousel-control-next,_x000D_
.carousel-control-prev {_x000D_
  width: 8% !important;_x000D_
}_x000D_
_x000D_
.carousel-item.active,_x000D_
.carousel-item-left,_x000D_
.carousel-item-right {_x000D_
  display: flex !important;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
.carousel-item h1 {_x000D_
    color: #fff;_x000D_
    font-size: 72px;_x000D_
    padding: 0 10%;_x000D_
 }
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div id="demo" class="carousel slide" data-ride="carousel" data-interval="false">_x000D_
_x000D_
  <!-- The slideshow -->_x000D_
  <div class="carousel-inner">_x000D_
    <div class="carousel-item active">_x000D_
      <h1 class="display-1 text-center">Lorem ipsum dolor sit amet adipisicing</h1>_x000D_
    </div>_x000D_
    <div class="carousel-item">_x000D_
      <h1 class="display-1 text-center">Inventore omnis odio, dolore culpa atque?</h1>_x000D_
    </div>_x000D_
    <div class="carousel-item">_x000D_
     <h1 class="display-1 text-center">Lorem ipsum dolor sit</h1>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <!-- Left and right controls -->_x000D_
  <a class="carousel-control-prev" href="#demo" data-slide="prev">_x000D_
    <span class="carousel-control-prev-icon"></span>_x000D_
  </a>_x000D_
  <a class="carousel-control-next" href="#demo" data-slide="next">_x000D_
    <span class="carousel-control-next-icon"></span>_x000D_
  </a>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Set style for TextView programmatically

We can use TextViewCompact.setTextAppearance(textView, R.style.xyz).

Android doc for reference.

How to get my Android device Internal Download Folder path

if a device has an SD card, you use:

Environment.getExternalStorageState() 

if you don't have an SD card, you use:

Environment.getDataDirectory()

if there is no SD card, you can create your own directory on the device locally.

    //if there is no SD card, create new directory objects to make directory on device
        if (Environment.getExternalStorageState() == null) {
                        //create new file directory object
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }// end of SD card checking

add permissions on your manifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Happy coding..

.NET Excel Library that can read/write .xls files

You may consider 3rd party tool that called Excel Jetcell .NET component for read/write excel files:

C# sample

// Create New Excel Workbook
ExcelWorkbook Wbook = new ExcelWorkbook();
ExcelCellCollection Cells = Wbook.Worksheets.Add("Sheet1").Cells;

Cells["A1"].Value = "Excel writer example (C#)";
Cells["A1"].Style.Font.Bold = true;
Cells["B1"].Value = "=550 + 5";

// Write Excel XLS file
Wbook.WriteXLS("excel_net.xls");

VB.NET sample

' Create New Excel Workbook
Dim Wbook As ExcelWorkbook = New ExcelWorkbook()
Dim Cells As ExcelCellCollection = Wbook.Worksheets.Add("Sheet1").Cells

Cells("A1").Value = "Excel writer example (C#)"
Cells("A1").Style.Font.Bold = True
Cells("B1").Value = "=550 + 5"

' Write Excel XLS file
Wbook.WriteXLS("excel_net.xls")

How to develop Android app completely using python?

You could try BeeWare - as described on their website:

Write your apps in Python and release them on iOS, Android, Windows, MacOS, Linux, Web, and tvOS using rich, native user interfaces. One codebase. Multiple apps.

Gives you want you want now to write Android Apps in Python, plus has the advantage that you won't need to learn yet another framework in future if you end up also wanting to do something on one of the other listed platforms.

Here's the Tutorial for Android Apps.

How to make a WPF window be on top of all other windows of my app (not system wide)?

I too faced the same problem and followed Google to this question. Recently I found the following worked for me.

CustomWindow cw = new CustomWindow();
cw.Owner = this;
cw.ShowDialog();

How do I plot only a table in Matplotlib?

You can di this:

#axs[1].plot(clust_data[:,0],clust_data[:,1]) # Remove this if you don't need it
axs[1].axis("off")  # This will leave the table alone in the window 

ld.exe: cannot open output file ... : Permission denied

Got the same issue. Read this. Disabled the antivirus software (mcaffee). Et voila

Confirmed by the antivirus log:

Blocked by Access Protection rule d:\mingw64\x86_64-w64-mingw32\bin\ld.exe d:\workspace\cpp\bar\foo.exe User-defined Rules:ctx3 Action blocked : Create

Oracle: SQL query that returns rows with only numeric values

You can use following command -

LENGTH(TRIM(TRANSLATE(string1, '+-.0123456789', '')))

This will return NULL if your string1 is Numeric

your query would be -

select * from tablename 
where LENGTH(TRIM(TRANSLATE(X, '+-.0123456789', ''))) is null

How can I create a product key for my C# application?

You can do something like create a record which contains the data you want to authenticate to the application. This could include anything you want - e.g. program features to enable, expiry date, name of the user (if you want to bind it to a user). Then encrypt that using some crypto algorithm with a fixed key or hash it. Then you just verify it within your program. One way to distribute the license file (on windows) is to provide it as a file which updates the registry (saves the user having to type it).

Beware of false sense of security though - sooner or later someone will simply patch your program to skip that check, and distribute the patched version. Or, they will work out a key that passes all checks and distribute that, or backdate the clock, etc. It doesn't matter how convoluted you make your scheme, anything you do for this will ultimately be security through obscurity and they will always be able to this. Even if they can't someone will, and will distribute the hacked version. Same applies even if you supply a dongle - if someone wants to, they can patch out the check for that too. Digitally signing your code won't help, they can remove that signature, or resign it.

You can complicate matters a bit by using techniques to prevent the program running in a debugger etc, but even this is not bullet proof. So you should just make it difficult enough that an honest user will not forget to pay. Also be very careful that your scheme does not become obtrusive to paying users - it's better to have some ripped off copies than for your paying customers not to be able to use what they have paid for.

Another option is to have an online check - just provide the user with a unique ID, and check online as to what capabilities that ID should have, and cache it for some period. All the same caveats apply though - people can get round anything like this.

Consider also the support costs of having to deal with users who have forgotten their key, etc.

edit: I just want to add, don't invest too much time in this or think that somehow your convoluted scheme will be different and uncrackable. It won't, and cannot be as long as people control the hardware and OS your program runs on. Developers have been trying to come up with ever more complex schemes for this, thinking that if they develop their own system for it then it will be known only to them and therefore 'more secure'. But it really is the programming equivalent of trying to build a perpetual motion machine. :-)

Can't find AVD or SDK manager in Eclipse

Window -> Custom Perspective -> Command Groups Availability -> Android SDK and AVD Manager check it

Creating a thumbnail from an uploaded image

You Can Use The Simplest Method

<?php
function make_thumb($src, $dest, $desired_width) {

    /* read the source image */
    $source_image = imagecreatefromjpeg($src);
    $width = imagesx($source_image);
    $height = imagesy($source_image);

    /* find the "desired height" of this thumbnail, relative to the desired width  */
    $desired_height = floor($height * ($desired_width / $width));

    /* create a new, "virtual" image */
    $virtual_image = imagecreatetruecolor($desired_width, $desired_height);

    /* copy source image at a resized size */
    imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);

    /* create the physical thumbnail image to its destination */
    imagejpeg($virtual_image, $dest);
}

$src="1494684586337H.jpg";
$dest="new.jpg";
$desired_width="200";
make_thumb($src, $dest, $desired_width);
?>

Which mime type should I use for mp3

mp3 files sometimes throw strange mime types as per this answer: https://stackoverflow.com/a/2755288/14482130

If you are doing some user validation do not allow 'application/octet-stream' or 'application/x-zip-compressed' as suggested above since they can contain be .exe or other potentially dangerous files.

In order to validate when mime type gives a false negative you can use fleep as per this answer https://stackoverflow.com/a/52570299/14482130 to finish the validation.

How to use an existing database with an Android application

If you already have a database, keep it in your asset folder and copy it in your application. For more detail, see Android database basics.

calling parent class method from child class object in java

If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super to call the parent method, inside the body of the child method.

public class PolyTest{
    public static void main(String args[]){
        new Child().foo();
    }

}
class Parent{
    public void foo(){
        System.out.println("I'm the parent.");
    }
}

class Child extends Parent{
    @Override
    public void foo(){
        //super.foo();
        System.out.println("I'm the child.");
    }
}

This would print:

I'm the child.

Uncomment the commented line and it would print:

I'm the parent.

I'm the child.

You should look for the concept of Polymorphism.

jQuery find element by data attribute value

you can also use andSelf() method to get wrapper DOM contain then find() can be work around as your idea

_x000D_
_x000D_
$(function() {_x000D_
  $('.slide-link').andSelf().find('[data-slide="0"]').addClass('active');_x000D_
})
_x000D_
.active {_x000D_
  background: green;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<a class="slide-link" href="#" data-slide="0">1</a>_x000D_
<a class="slide-link" href="#" data-slide="1">2</a>_x000D_
<a class="slide-link" href="#" data-slide="2">3</a>
_x000D_
_x000D_
_x000D_

What's the difference between all the Selection Segues?

For clarity, I'd like to illustrate @Joey's answer above with these gifs :

Show

enter image description here

Show Detail

enter image description here

Present Modally

enter image description here

Present As Popover

enter image description here

HTML5 Canvas: Zooming

One option is to use css zoom feature:

$("#canvas_id").css("zoom","x%"); 

How to install MinGW-w64 and MSYS2?

MSYS has not been updated a long time, MSYS2 is more active, you can download from MSYS2, it has both mingw and cygwin fork package.

To install the MinGW-w64 toolchain (Reference):

  1. Open MSYS2 shell from start menu
  2. Run pacman -Sy pacman to update the package database
  3. Re-open the shell, run pacman -Syu to update the package database and core system packages
  4. Re-open the shell, run pacman -Su to update the rest
  5. Install compiler:
    • For 32-bit target, run pacman -S mingw-w64-i686-toolchain
    • For 64-bit target, run pacman -S mingw-w64-x86_64-toolchain
  6. Select which package to install, default is all
  7. You may also need make, run pacman -S make

Error: expected type-specifier before 'ClassName'

For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).

This can be caused in many ways:

  • You forgot to #include the header that defines it.
  • Your inclusion guards (#ifndef BLAH_H) are defective (your #ifndef BLAH_H doesn't match your #define BALH_H due to a typo or copy+paste mistake).
  • Your inclusion guards are accidentally used twice (two separate files both using #define MYHEADER_H, even if they are in separate directories)
  • You forgot that you are using a template (eg. new Vector() should be new Vector<int>())
  • The compiler is thinking you meant one scope when really you meant another (For example, if you have NamespaceA::NamespaceB, AND a <global scope>::NamespaceB, if you are already within NamespaceA, it'll look in NamespaceA::NamespaceB and not bother checking <global scope>::NamespaceB) unless you explicitly access it.
  • You have a name clash (two entities with the same name, such as a class and an enum member).

To explicitly access something in the global namespace, prefix it with ::, as if the global namespace is a namespace with no name (e.g. ::MyType or ::MyNamespace::MyType).

Calculating number of full months between two dates in SQL

I googled over internet. And suggestion I found is to add +1 to the end.

Try do it like this:

Declare @Start DateTime
Declare @End DateTime

Set @Start = '11/1/07'
Set @End = '2/29/08'

Select DateDiff(Month, @Start, @End + 1)

How to convert String object to Boolean Object?

Use .isBool in your String value. It work for me

your_string.isBool

How to view kafka message

If you're wondering why the original answer is not working. Well it might be that you're not in the home directory. Try this:

$KAFKA_HOME/bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning

StringStream in C#

You can create a MemoryStream from a String and use that in any third-party function that requires a stream. In this case, MemoryStream, with the help of UTF8.GetBytes, provides the functionality of Java's StringStream.

From String examples

String content = "stuff";
using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(content)))
{
    Print(stream); //or whatever action you need to perform with the stream
    stream.Seek(0, SeekOrigin.Begin); //If you need to use the same stream again, don't forget to reset it.
    UseAgain(stream);
}

To String example

stream.Seek(0, SeekOrigin.Begin);
string s;
using (var readr = new StreamReader(stream))
{
    s = readr.ReadToEnd();
}
//and don't forget to dispose the stream if you created it

Count items in a folder with PowerShell

You should use Measure-Object to count things. In this case it would look like:

Write-Host ( Get-ChildItem c:\MyFolder | Measure-Object ).Count;

or if that's too long

Write-Host ( dir c:\MyFolder | mo).Count;

and in PowerShell 4.0 use the measure alias instead of mo

Write-Host (dir c:\MyFolder | measure).Count;

jQuery function to get all unique elements from an array?

    // for numbers
    a = [1,3,2,4,5,6,7,8, 1,1,4,5,6]
    $.unique(a)
    [7, 6, 1, 8, 3, 2, 5, 4]

    // for string
    a = ["a", "a", "b"]
    $.unique(a)
    ["b", "a"]

And for dom elements there is no example is needed here I guess because you already know that!

Here is the jsfiddle link of live example: http://jsfiddle.net/3BtMc/4/

PHP Get all subdirectories of a given directory

Almost the same as in your previous question:

$iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($yourStartingPath), 
            RecursiveIteratorIterator::SELF_FIRST);

foreach($iterator as $file) {
    if($file->isDir()) {
        echo strtoupper($file->getRealpath()), PHP_EOL;
    }
}

Replace strtoupper with your desired function.

Convert base class to derived class

I have found one solution to this, not saying it's the best one, but it feels clean to me and doesn't require any major changes to my code. My code looked similar to yours until I realized it didn't work.

My Base Class

public class MyBaseClass
{
   public string BaseProperty1 { get; set; }
   public string BaseProperty2 { get; set; }
   public string BaseProperty3 { get; set; }
   public string BaseProperty4 { get; set; }
   public string BaseProperty5 { get; set; }
}

My Derived Class

public class MyDerivedClass : MyBaseClass
{
   public string DerivedProperty1 { get; set; }
   public string DerivedProperty2 { get; set; }
   public string DerivedProperty3 { get; set; }
}

Previous method to get a populated base class

public MyBaseClass GetPopulatedBaseClass()
{
   var myBaseClass = new MyBaseClass();

   myBaseClass.BaseProperty1 = "Something"
   myBaseClass.BaseProperty2 = "Something else"
   myBaseClass.BaseProperty3 = "Something more"
   //etc...

   return myBaseClass;
}

Before I was trying this, which gave me a unable to cast error

public MyDerivedClass GetPopulatedDerivedClass()
{
   var newDerivedClass = (MyDerivedClass)GetPopulatedBaseClass();

   newDerivedClass.UniqueProperty1 = "Some One";
   newDerivedClass.UniqueProperty2 = "Some Thing";
   newDerivedClass.UniqueProperty3 = "Some Thing Else";

   return newDerivedClass;
}

I changed my code as follows bellow and it seems to work and makes more sense now:

Old

public MyBaseClass GetPopulatedBaseClass()
{
   var myBaseClass = new MyBaseClass();

   myBaseClass.BaseProperty1 = "Something"
   myBaseClass.BaseProperty2 = "Something else"
   myBaseClass.BaseProperty3 = "Something more"
   //etc...

   return myBaseClass;
}

New

public void FillBaseClass(MyBaseClass myBaseClass)
{
   myBaseClass.BaseProperty1 = "Something"
   myBaseClass.BaseProperty2 = "Something else"
   myBaseClass.BaseProperty3 = "Something more"
   //etc...
}

Old

public MyDerivedClass GetPopulatedDerivedClass()
{
   var newDerivedClass = (MyDerivedClass)GetPopulatedBaseClass();

   newDerivedClass.UniqueProperty1 = "Some One";
   newDerivedClass.UniqueProperty2 = "Some Thing";
   newDerivedClass.UniqueProperty3 = "Some Thing Else";

   return newDerivedClass;
}

New

public MyDerivedClass GetPopulatedDerivedClass()
{
   var newDerivedClass = new MyDerivedClass();

   FillBaseClass(newDerivedClass);

   newDerivedClass.UniqueProperty1 = "Some One";
   newDerivedClass.UniqueProperty2 = "Some Thing";
   newDerivedClass.UniqueProperty3 = "Some Thing Else";

   return newDerivedClass;
}

Excel Date to String conversion

Here's another option. Use Excel's built in 'Text to Columns' wizard. It's found under the Data tab in Excel 2007.

If you have one column selected, the defaults for file type and delimiters should work, then it prompts you to change the data format of the column. Choosing text forces it to text format, to make sure that it's not stored as a date.

Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Widget.ActionBar.Title'

Make sure you've set your target API (different from the target SDK) in the Project Properties (not the manifest) to be at least 4.0/API 14.

How to set placeholder value using CSS?

From what I understand using,

::-webkit-input-placeholder::beforeor ::-webkit-input-placeholder::after,

to add more placeholder content doesn't work anymore. Think its a new Chrome update.

Really annoying as it was a great workaround, now im back to just adding lots of empty spaces between lines that I want in a placeholder. eg:

<input type="text" value="" id="email1" placeholder="I am on one line.                                              I am on a second line                                                                                     etc etc..." />

What is the best way to conditionally apply attributes in AngularJS?

I got this working by hard setting the attribute. And controlling the attribute applicability using the boolean value for the attribute.

Here is the code snippet:

<div contenteditable="{{ condition ? 'true' : 'false'}}"></div>

I hope this helps.

bootstrap multiselect get selected values

$('#multiselect1').on('change', function(){
    var selected = $(this).find("option:selected");
    var arrSelected = [];
    selected.each(function(){
       arrSelected.push($(this).val());
    });
});

How to turn off page breaks in Google Docs?

If You want to REMOVE page break from document

use Edit / Find-Replace \f with regex

If You want to TURN OFF (as You asked)

uncheck "Print Layout" from the "View" menu, but dotted lines will remain indicating page breaks

Execute combine multiple Linux commands in one line

I find lots of answer for this kind of question misleading

Modified from this post: https://www.webmasterworld.com/linux/3613813.htm

The following code will create bash window and works exactly as a bash window. Hope this helps. Too many wrong/not-working answers out there...

            Process proc;
            try {
                //create a bash window
                proc = Runtime.getRuntime().exec("/bin/bash");
                if (proc != null) {
                       BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
                       PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
                       BufferedReader err = new BufferedReader(new InputStreamReader(
                       proc.getErrorStream()));
                       //input into the bash window
                       out.println("cd /my_folder");
                       out.println("rm *.jar");
                       out.println("svn co path to repo");
                       out.println("mvn compile package install");
                       out.println("exit");
                       String line;
                        System.out.println("----printing output-----");
                          while ((line = in.readLine()) != null) {
                             System.out.println(line);
                          }
                          while((line = err.readLine()) != null) {
                             //read errors
                          }
                          proc.waitFor();
                          in.close();
                          out.close();
                          err.close();
                          proc.destroy();
                }

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

jQuery Validate Plugin - How to create a simple custom rule?

Step 1 Included the cdn like

     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

     <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>

Step 2 Code Like

  $(document).ready(function(){
        $("#submit").click(function () {
              $('#myform').validate({ // initialize the plugin
                rules: {
                    id: {
                        required: true,
                        email: true
                    },
                    password: {
                        required: true,
                        minlength: 1
                    }
                },
                messages: {
                    id: {
                        required: "Enter Email Id"

                    },
                    password: {
                        required: "Enter Email Password"

                    }
                },
                submitHandler: function (form) { // for demo
                    alert('valid form submitted'); // for demo
                    return false; // for demo
                }
            });
       }):
  }); 

MongoDB and "joins"

one kind of join a query in mongoDB, is ask at one collection for id that match , put ids in a list (idlist) , and do find using on other (or same) collection with $in : idlist

u = db.friends.find({"friends": something }).toArray()
idlist= []
u.forEach(function(myDoc) { idlist.push(myDoc.id ); } )
db.family.find({"id": {$in : idlist} } )

Search all of Git history for a string?

Try the following commands to search the string inside all previous tracked files:

git log --patch  | less +/searching_string

or

git rev-list --all | GIT_PAGER=cat xargs git grep 'search_string'

which needs to be run from the parent directory where you'd like to do the searching.

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

I don't think this is your case, but I'll post it if it helps anyone. I had the same issue and the problem was that Node didn't respond at all (I had a condition that when failed didn't do anything - so no response) - So if increasing all your timeouts didn't solve it, make sure all scenarios get a response.

Create File If File Does Not Exist

For Example

    string rootPath = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System));
        rootPath += "MTN";
        if (!(File.Exists(rootPath)))
        {
            File.CreateText(rootPath);
        }

How to configure log4j to only keep log files for the last seven days?

I assume you're using RollingFileAppender? In which case, it has a property called MaxBackupIndex which you can set to limit the number of files. For example:

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=7
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

The following classes could not be instantiated: - android.support.v7.widget.Toolbar

none of above worked for me , i updated the appCompat - v7 version in my app gradle file from 23 to 25.3.1. helped to make it work for me

Passing Javascript variable to <a href >

Alternatively you could just use a document.write:

<script type="text\javascript">
var loc = "http://";
document.write('<a href="' + loc + '">Link text</a>');
</script>

Entity Framework: There is already an open DataReader associated with this Command

I solved the problem easily (pragmatic) by adding the option to the constructor. Thus, i use that only when needed.

public class Something : DbContext
{
    public Something(bool MultipleActiveResultSets = false)
    {
        this.Database
            .Connection
            .ConnectionString = Shared.ConnectionString /* your connection string */
                              + (MultipleActiveResultSets ? ";MultipleActiveResultSets=true;" : "");
    }
...

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

HttpClient webClient = new HttpClient();
Uri uri = new Uri("your url");
HttpResponseMessage response = await webClient.GetAsync(uri)
var jsonString = await response.Content.ReadAsStringAsync();
var objData = JsonConvert.DeserializeObject<List<CategoryModel>>(jsonString);

How can I calculate the difference between two dates?

If you want all the units, not just the biggest one, use one of these 2 methods (based on @Ankish's answer):

Example output: 28 D | 23 H | 59 M | 59 S

+ (NSString *) remaningTime:(NSDate *)startDate endDate:(NSDate *)endDate
{
    NSCalendarUnit units = NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *components = [[NSCalendar currentCalendar] components:units fromDate: startDate toDate: endDate options: 0];
    return [NSString stringWithFormat:@"%ti D | %ti H | %ti M | %ti S", [components day], [components hour], [components minute], [components second]];
}

+ (NSString *) timeFromNowUntil:(NSDate *)endDate
{
    return [self remaningTime:[NSDate date] endDate:endDate];
}

Cannot import XSSF in Apache POI

Problem: While importing the " org.apache.poi.xssf.usermodel.XSSFWorkbook"class showing an error in eclipse.

Solution: Use This maven dependency to resolve this problem:

<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-ooxml</artifactId>
   <version>3.15</version>
</dependency>

-Hari Krishna Neela

C# if/then directives for debug vs release

DEBUG/_DEBUG should be defined in VS already.

Remove the #define DEBUG in your code. Set preprocessors in the build configuration for that specific build.

The reason it prints "Mode=Debug" is because of your #define and then skips the elif.

The right way to check is:

#if DEBUG
    Console.WriteLine("Mode=Debug"); 
#else
    Console.WriteLine("Mode=Release"); 
#endif

Don't check for RELEASE.

Execute Insert command and return inserted Id in Sql

USE AdventureWorks2012;
GO
IF OBJECT_ID(N't6', N'U') IS NOT NULL 
    DROP TABLE t6;
GO
IF OBJECT_ID(N't7', N'U') IS NOT NULL 
    DROP TABLE t7;
GO
CREATE TABLE t6(id int IDENTITY);
CREATE TABLE t7(id int IDENTITY(100,1));
GO
CREATE TRIGGER t6ins ON t6 FOR INSERT 
AS
BEGIN
   INSERT t7 DEFAULT VALUES
END;
GO
--End of trigger definition

SELECT id FROM t6;
--IDs empty.

SELECT id FROM t7;
--ID is empty.

--Do the following in Session 1
INSERT t6 DEFAULT VALUES;
SELECT @@IDENTITY;
/*Returns the value 100. This was inserted by the trigger.*/

SELECT SCOPE_IDENTITY();
/* Returns the value 1. This was inserted by the 
INSERT statement two statements before this query.*/

SELECT IDENT_CURRENT('t7');
/* Returns value inserted into t7, that is in the trigger.*/

SELECT IDENT_CURRENT('t6');
/* Returns value inserted into t6. This was the INSERT statement four statements before this query.*/

-- Do the following in Session 2.
SELECT @@IDENTITY;
/* Returns NULL because there has been no INSERT action 
up to this point in this session.*/

SELECT SCOPE_IDENTITY();
/* Returns NULL because there has been no INSERT action 
up to this point in this scope in this session.*/

SELECT IDENT_CURRENT('t7');
/* Returns the last value inserted into t7.*/

Multiple conditions in ngClass - Angular 4

you need object notation

<section [ngClass]="{'class1':condition1, 'class2': condition2, 'class3':condition3}" > 

ref: NgClass

How do I set headers using python's urllib?

For multiple headers do as follow:

import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('param1', '212212')
req.add_header('param2', '12345678')
req.add_header('other_param1', 'sample')
req.add_header('other_param2', 'sample1111')
req.add_header('and_any_other_parame', 'testttt')
resp = urllib2.urlopen(req)
content = resp.read()

Collection was modified; enumeration operation may not execute

There is one link where it elaborated very well & solution is also given. Try it if you got proper solution please post here so other can understand. Given solution is ok then like the post so other can try these solution.

for you reference original link :- https://bensonxion.wordpress.com/2012/05/07/serializing-an-ienumerable-produces-collection-was-modified-enumeration-operation-may-not-execute/

When we use .Net Serialization classes to serialize an object where its definition contains an Enumerable type, i.e. collection, you will be easily getting InvalidOperationException saying "Collection was modified; enumeration operation may not execute" where your coding is under multi-thread scenarios. The bottom cause is that serialization classes will iterate through collection via enumerator, as such, problem goes to trying to iterate through a collection while modifying it.

First solution, we can simply use lock as a synchronization solution to ensure that the operation to the List object can only be executed from one thread at a time. Obviously, you will get performance penalty that if you want to serialize a collection of that object, then for each of them, the lock will be applied.

Well, .Net 4.0 which makes dealing with multi-threading scenarios handy. for this serializing Collection field problem, I found we can just take benefit from ConcurrentQueue(Check MSDN)class, which is a thread-safe and FIFO collection and makes code lock-free.

Using this class, in its simplicity, the stuff you need to modify for your code are replacing Collection type with it, use Enqueue to add an element to the end of ConcurrentQueue, remove those lock code. Or, if the scenario you are working on do require collection stuff like List, you will need a few more code to adapt ConcurrentQueue into your fields.

BTW, ConcurrentQueue doesnât have a Clear method due to underlying algorithm which doesnât permit atomically clearing of the collection. so you have to do it yourself, the fastest way is to re-create a new empty ConcurrentQueue for a replacement.

How do Python's any and all functions work?

>>> any([False, False, False])
False
>>> any([False, True, False])
True
>>> all([False, True, True])
False
>>> all([True, True, True])
True

AngularJS ui-router login authentication

I wanted to share another solution working with the ui router 1.0.0.X

As you may know, stateChangeStart and stateChangeSuccess are now deprecated. https://github.com/angular-ui/ui-router/issues/2655

Instead you should use $transitions http://angular-ui.github.io/ui-router/1.0.0-alpha.1/interfaces/transition.ihookregistry.html

This is how I achieved it:

First I have and AuthService with some useful functions

angular.module('myApp')

        .factory('AuthService',
                ['$http', '$cookies', '$rootScope',
                    function ($http, $cookies, $rootScope) {
                        var service = {};

                        // Authenticates throug a rest service
                        service.authenticate = function (username, password, callback) {

                            $http.post('api/login', {username: username, password: password})
                                    .success(function (response) {
                                        callback(response);
                                    });
                        };

                        // Creates a cookie and set the Authorization header
                        service.setCredentials = function (response) {
                            $rootScope.globals = response.token;

                            $http.defaults.headers.common['Authorization'] = 'Bearer ' + response.token;
                            $cookies.put('globals', $rootScope.globals);
                        };

                        // Checks if it's authenticated
                        service.isAuthenticated = function() {
                            return !($cookies.get('globals') === undefined);
                        };

                        // Clear credentials when logout
                        service.clearCredentials = function () {
                            $rootScope.globals = undefined;
                            $cookies.remove('globals');
                            $http.defaults.headers.common.Authorization = 'Bearer ';
                        };

                        return service;
                    }]);

Then I have this configuration:

angular.module('myApp', [
    'ui.router',
    'ngCookies'
])
        .config(['$stateProvider', '$urlRouterProvider',
            function ($stateProvider, $urlRouterProvider) {
                $urlRouterProvider.otherwise('/resumen');
                $stateProvider
                        .state("dashboard", {
                            url: "/dashboard",
                            templateUrl: "partials/dashboard.html",
                            controller: "dashCtrl",
                            data: {
                                authRequired: true
                            }
                        })
                        .state("login", {
                            url: "/login",
                            templateUrl: "partials/login.html",
                            controller: "loginController"
                        })
            }])

        .run(['$rootScope', '$transitions', '$state', '$cookies', '$http', 'AuthService',
            function ($rootScope, $transitions, $state, $cookies, $http, AuthService) {

                // keep user logged in after page refresh
                $rootScope.globals = $cookies.get('globals') || {};
                $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.globals;

                $transitions.onStart({
                    to: function (state) {
                        return state.data != null && state.data.authRequired === true;
                    }
                }, function () {
                    if (!AuthService.isAuthenticated()) {
                        return $state.target("login");
                    }
                });
            }]);

You can see that I use

data: {
   authRequired: true
}

to mark the state only accessible if is authenticated.

then, on the .run I use the transitions to check the autheticated state

$transitions.onStart({
    to: function (state) {
        return state.data != null && state.data.authRequired === true;
    }
}, function () {
    if (!AuthService.isAuthenticated()) {
        return $state.target("login");
    }
});

I build this example using some code found on the $transitions documentation. I'm pretty new with the ui router but it works.

Hope it can helps anyone.

Find what 2 numbers add to something and multiply to something

Come on guys, there is no need to loop, just use simple math to solve this equation system:

a*b = i;

a+b = j;

a = j/b;

a = i-b;

j/b = i-b; so:

b + j/b + i = 0

b^2 + i*b + j = 0

From here, its a quadratic equation, and it's trivial to find b (just implement the quadratic equation formula) and from there get the value for a.

EDIT:

There you go:

function finder($add,$product)
{

 $inside_root = $add*$add - 4*$product;

 if($inside_root >=0)
 {

     $b = ($add + sqrt($inside_root))/2;
     $a = $add - $b;

     echo "$a+$b = $add and $a*$b=$product\n";

 }else
 {
   echo "No real solution\n";
 }
}

Real live action:

http://codepad.org/JBxMgHBd

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 do you easily create empty matrices javascript?

With ES6 spread operator: Array(9).fill([...Array(9)])

Generating a UUID in Postgres for Insert statement?

Without extensions (cheat)

SELECT uuid_in(md5(random()::text || clock_timestamp()::text)::cstring);

output>> c2d29867-3d0b-d497-9191-18a9d8ee7830

(works at least in 8.4)

  • Thanks to @Erwin Brandstetter for clock_timestamp() explanation.

If you need a valid v4 UUID

SELECT uuid_in(overlay(overlay(md5(random()::text || ':' || clock_timestamp()::text) placing '4' from 13) placing to_hex(floor(random()*(11-8+1) + 8)::int)::text from 17)::cstring);

enter image description here * Thanks to @Denis Stafichuk @Karsten and @autronix


Also, in modern Postgres, you can simply cast:

SELECT md5(random()::text || clock_timestamp()::text)::uuid

is there any alternative for ng-disabled in angular2?

Yes You can either set [disabled]= "true" or if it is an radio button or checkbox then you can simply use disable

For radio button:

<md-radio-button disabled>Select color</md-radio-button>

For dropdown:

<ng-select (selected)="someFunction($event)" [disabled]="true"></ng-select>

python-dev installation error: ImportError: No module named apt_pkg

  1. Check your default Python 3 version:
python --version
Python 3.7.5
  1. cd into /usr/lib/python3/dist-packages and check the apt_pkg.* files. You will find that there is none for your default Python version:
ll apt_pkg.*
apt_pkg.cpython-36m-x86_64-linux-gnu.so
  1. Create the symlink:
sudo ln -s apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.cpython-37m-x86_64- linux-gnu.so 

cmake and libpthread

The following should be clean (using find_package) and work (the find module is called FindThreads):

cmake_minimum_required (VERSION 2.6) 
find_package (Threads)
add_executable (myapp main.cpp ...)
target_link_libraries (myapp ${CMAKE_THREAD_LIBS_INIT})

Git blame -- prior commits?

git blame -L 10,+1 fe25b6d^ -- src/options.cpp

You can specify a revision for git blame to look back starting from (instead of the default of HEAD); fe25b6d^ is the parent of fe25b6d.


Edit: New to Git 2.23, we have the --ignore-rev option added to git blame:

git blame --ignore-rev fe25b6d

While this doesn't answer OP's question of giving the stack of commits (you'll use git log for that, as per the other answer), it is a better way of this solution, as you won't potentially misblame the other lines.

How to get Bitmap from an Uri?

Use startActivityForResult metod like below

        startActivityForResult(new Intent(Intent.ACTION_PICK).setType("image/*"), PICK_IMAGE);

And you can get result like this:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_OK) {
        return;
    }
    switch (requestCode) {
        case PICK_IMAGE:
            Uri imageUri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
            } catch (IOException e) {
                e.printStackTrace();
            }
         break;
    }
}

How do I declare an array of undefined or no initial size?

Here's a sample program that reads stdin into a memory buffer that grows as needed. It's simple enough that it should give some insight in how you might handle this kind of thing. One thing that's would probably be done differently in a real program is how must the array grows in each allocation - I kept it small here to help keep things simpler if you wanted to step through in a debugger. A real program would probably use a much larger allocation increment (often, the allocation size is doubled, but if you're going to do that you should probably 'cap' the increment at some reasonable size - it might not make sense to double the allocation when you get into the hundreds of megabytes).

Also, I used indexed access to the buffer here as an example, but in a real program I probably wouldn't do that.

#include <stdlib.h>
#include <stdio.h>


void fatal_error(void);

int main( int argc, char** argv)
{
    int buf_size = 0;
    int buf_used = 0;

    char* buf = NULL;
    char* tmp = NULL;    

    char c;
    int i = 0;

    while ((c = getchar()) != EOF) {
        if (buf_used == buf_size) {
             //need more space in the array

             buf_size += 20;
             tmp = realloc(buf, buf_size); // get a new larger array
             if (!tmp) fatal_error();

             buf = tmp;
        }

        buf[buf_used] = c; // pointer can be indexed like an array
        ++buf_used;
    }

    puts("\n\n*** Dump of stdin ***\n");

    for (i = 0; i < buf_used; ++i) {
        putchar(buf[i]);
    }

    free(buf);

    return 0;
}

void fatal_error(void)
{
    fputs("fatal error - out of memory\n", stderr);
    exit(1);
}

This example combined with examples in other answers should give you an idea of how this kind of thing is handled at a low level.

MySQL match() against() - order by relevance and column?

I was just playing around with this, too. One way you can add extra weight is in the ORDER BY area of the code.

For example, if you were matching 3 different columns and wanted to more heavily weight certain columns:

SELECT search.*,
MATCH (name) AGAINST ('black' IN BOOLEAN MODE) AS name_match,
MATCH (keywords) AGAINST ('black' IN BOOLEAN MODE) AS keyword_match,
MATCH (description) AGAINST ('black' IN BOOLEAN MODE) AS description_match
FROM search
WHERE MATCH (name, keywords, description) AGAINST ('black' IN BOOLEAN MODE)
ORDER BY (name_match * 3  + keyword_match * 2  + description_match) DESC LIMIT 0,100;

HTTP Status 405 - HTTP method POST is not supported by this URL java servlet

if you are using tomcat you may try this

<servlet-mapping>

    <http-method>POST</http-method>

</servlet-mapping>

in addition to <servlet-name> and <url-mapping>

How to format a number as percentage in R?

Check out the percent function from the formattable package:

library(formattable)
x <- c(0.23, 0.95, 0.3)
percent(x)
[1] 23.00% 95.00% 30.00%

WPF MVVM: How to close a window

I struggled with this topic for some time, and eventually went with the simplest approach that is still consistent with MVVM: Have the button execute the Command that does all the heavy lifting and have the button's Click handler close the window.

XAML

<Button x:Name="buttonOk" 
        Click="closeWindow" 
        Command="{Binding SaveCommand}" />

XAML.cs

public void closeWindow() 
{
    this.DialogResult = true;
}

SaveCommand.cs

 // I'm in my own file, not the code-behind!

True, there is still code-behind, but there isn't anything inherently bad about that. And it makes the most sense to me, from an OO perspective, to just tell the window to close itself.

Understanding the ngRepeat 'track by' expression

a short summary:

track by is used in order to link your data with the DOM generation (and mainly re-generation) made by ng-repeat.

when you add track by you basically tell angular to generate a single DOM element per data object in the given collection

this could be useful when paging and filtering, or any case where objects are added or removed from ng-repeat list.

usually, without track by angular will link the DOM objects with the collection by injecting an expando property - $$hashKey - into your JavaScript objects, and will regenerate it (and re-associate a DOM object) with every change.

full explanation:

http://www.bennadel.com/blog/2556-using-track-by-with-ngrepeat-in-angularjs-1-2.htm

a more practical guide:

http://www.codelord.net/2014/04/15/improving-ng-repeat-performance-with-track-by/

(track by is available in angular > 1.2 )

String Array object in Java

Currently you can't access the arrays named name and country, because they are member variables of your Athelete class.

Based on what it looks like you're trying to do, this will not work.

These arrays belong in your main class.

Jquery UI tooltip does not support html content

You may modify the source code 'jquery-ui.js' , find this default function for retrieving target element's title attribute content.

var tooltip = $.widget( "ui.tooltip", {
version: "1.11.4",
options: {
    content: function() {
        // support: IE<9, Opera in jQuery <1.7
        // .text() can't accept undefined, so coerce to a string
        var title = $( this ).attr( "title" ) || "";
        // Escape title, since we're going from an attribute to raw HTML
        return $( "<a>" ).text( title ).html();
    },

change it to

var tooltip = $.widget( "ui.tooltip", {
version: "1.11.4",
options: {
    content: function() {
        // support: IE<9, Opera in jQuery <1.7
        // .text() can't accept undefined, so coerce to a string
        if($(this).attr('ignoreHtml')==='false'){
            return $(this).prop("title");
        }
        var title = $( this ).attr( "title" ) || "";
        // Escape title, since we're going from an attribute to raw HTML
        return $( "<a>" ).text( title ).html();
    },

thus whenever you want to display html tips , just add an attribute ignoreHtml='false' on your target html element; like this <td title="<b>display content</b><br/>other" ignoreHtml='false'>display content</td>

C++ create string of text and variables

In C++11 you can use std::to_string:

std::string var = "sometext" + std::to_string(somevar) + "sometext" + std::to_string(somevar);  

Number of elements in a javascript object

The concept of number/length/dimensionality doesn't really make sense for an Object, and needing it suggests you really want an Array to me.

Edit: Pointed out to me that you want an O(1) for this. To the best of my knowledge no such way exists I'm afraid.

Get age from Birthdate

Try this function...

function calculate_age(birth_month,birth_day,birth_year)
{
    today_date = new Date();
    today_year = today_date.getFullYear();
    today_month = today_date.getMonth();
    today_day = today_date.getDate();
    age = today_year - birth_year;

    if ( today_month < (birth_month - 1))
    {
        age--;
    }
    if (((birth_month - 1) == today_month) && (today_day < birth_day))
    {
        age--;
    }
    return age;
}

OR

function getAge(dateString) 
{
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) 
    {
        age--;
    }
    return age;
}

See Demo.

add title attribute from css

Can do, with jQuery:

$(document).ready(function() {
    $('.mandatory').each(function() {
        $(this).attr('title', $(this).attr('class'));
    });
});

How to read a single character at a time from a file in Python?

I learned a new idiom for this today while watching Raymond Hettinger's Transforming Code into Beautiful, Idiomatic Python:

import functools

with open(filename) as f:
    f_read_ch = functools.partial(f.read, 1)
    for ch in iter(f_read_ch, ''):
        print 'Read a character:', repr(ch) 

How to prevent a jQuery Ajax request from caching in Internet Explorer?

If you set unique parameters, then the cache does not work, for example:

$.ajax({
    url : "my_url",
    data : {
        'uniq_param' : (new Date()).getTime(),
        //other data
    }});

"No such file or directory" error when executing a binary

It is possible that the executable is statically linked and that is why ldd gzip does not see any links - because it isn't. I don't know much about things that far back so I don't know if there would be incompatibilities if libraries are linked in statically. I might expect there to be.

I know it's the most obvious thing going and I'm sure you've done it, but chmod +x ./gzip, yes? No such file or directory is a classic symptom of that not being done, that's why I mention it.

What does it mean to have an index to scalar variable error? python

exponent is a 1D array. This means that exponent[0] is a scalar, and exponent[0][i] is trying to access it as if it were an array.

Did you mean to say:

L = identity(len(l))
for i in xrange(len(l)):
    L[i][i] = exponent[i]

or even

L = diag(exponent)

?

Safe String to BigDecimal conversion

The following sample code works well (locale need to be obtained dynamically)

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.text.ParsePosition;
import java.util.Locale;

class TestBigDecimal {
    public static void main(String[] args) {

        String str = "0,00";
        Locale in_ID = new Locale("in","ID");
        //Locale in_ID = new Locale("en","US");

        DecimalFormat nf = (DecimalFormat)NumberFormat.getInstance(in_ID);
        nf.setParseBigDecimal(true);

        BigDecimal bd = (BigDecimal)nf.parse(str, new ParsePosition(0));

        System.out.println("bd value : " + bd);
    }
}

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

Please try this code

new_column=df[['col1', 'col2', 'col3', 'col4']].groupby(['col1', 'col2']).count()
df['count_it']=new_column
df

I think that code will add a column called 'count it' which count of each group

Scroll to the top of the page using JavaScript?

If you don't want smooth scrolling, you can cheat and stop the smooth scrolling animation pretty much as soon as you start it... like so:

   $(document).ready(function() {
      $("a[href='#top']").click(function() {
          $("html, body").animate({ scrollTop: 0 }, "1");              
          $('html, body').stop(true, true);

          //Anything else you want to do in the same action goes here

          return false;                              
      });
  });

I've no idea whether it's recommended/allowed, but it works :)

When would you use this? I'm not sure, but perhaps when you want to use one click to animate one thing with Jquery, but do another without animation? ie open a slide-in admin login panel at the top of the page, and instantly jump to the top to see it.

XML to CSV Using XSLT

Found an XML transform stylesheet here (wayback machine link, site itself is in german)

The stylesheet added here could be helpful:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="iso-8859-1"/>

<xsl:strip-space elements="*" />

<xsl:template match="/*/child::*">
<xsl:for-each select="child::*">
<xsl:if test="position() != last()">"<xsl:value-of select="normalize-space(.)"/>",    </xsl:if>
<xsl:if test="position()  = last()">"<xsl:value-of select="normalize-space(.)"/>"<xsl:text>&#xD;</xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Perhaps you want to remove the quotes inside the xsl:if tags so it doesn't put your values into quotes, depending on where you want to use the CSV file.

AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

During the creation of S3Client you can specify the endpoint mapping to a particular region. If default of s3.amazonaws.com then bucket will be created in us-east-1 which is North Virginia.

More details on S3 endpoints and regions in AWS docs: http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region.

So, always make sure about the endpoint/region while creating the S3Client and access S3 resouces using the same client in the same region.

If the bucket is created from AWS S3 Console, then check the region from the console for that bucket then create a S3 Client in that region using the endpoint details mentioned in the above link.

Format JavaScript date as yyyy-mm-dd

Here is one way to do it:

var date = Date.parse('Sun May 11,2014');

function format(date) {
  date = new Date(date);

  var day = ('0' + date.getDate()).slice(-2);
  var month = ('0' + (date.getMonth() + 1)).slice(-2);
  var year = date.getFullYear();

  return year + '-' + month + '-' + day;
}

console.log(format(date));

How to align title at center of ActionBar in default theme(Theme.Holo.Light)

You can create a custom layout and apply it to the actionBar.

To do so, follow those 2 simple steps:

  1. Java Code

    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    getSupportActionBar().setCustomView(R.layout.actionbar);
    

Where R.layout.actionbar is the following layout.

  1. XML

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical">
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:id="@+id/action_bar_title"
        android:text="YOUR ACTIVITY TITLE"
        android:textColor="#ffffff"
        android:textSize="24sp" />
    </LinearLayout>
    

It can be as complex as you want. Try it out!

EDIT:

To set the background you can use the property android:background in the container layout (LinearLayout in that case). You may need to set the layout height android:layout_height to match_parent instead of wrap_content.

Moreover, you can also add a LOGO / ICON to it. To do so, simply add an ImageView inside your layout, and set layout orientation property android:orientation to horizontal (or simply use a RelativeLayout and manage it by yourself).

To change the title of above custom action bar dynamically, do this:

TextView title=(TextView)findViewById(getResources().getIdentifier("action_bar_title", "id", getPackageName()));
title.setText("Your Text Here");

What is the difference between a static method and a non-static method?

Well, more technically speaking, the difference between a static method and a virtual method is the way the are linked.

A traditional "static" method like in most non OO languages gets linked/wired "statically" to its implementation at compile time. That is, if you call method Y() in program A, and link your program A with library X that implements Y(), the address of X.Y() is hardcoded to A, and you can not change that.

In OO languages like JAVA, "virtual" methods are resolved "late", at run-time, and you need to provide an instance of a class. So in, program A, to call virtual method Y(), you need to provide an instance, B.Y() for example. At runtime, every time A calls B.Y() the implementation called will depend on the instance used, so B.Y() , C.Y() etc... could all potential provide different implementations of Y() at runtime.

Why will you ever need that? Because that way you can decouple your code from the dependencies. For example, say program A is doing "draw()". With a static language, thats it, but with OO you will do B.draw() and the actual drawing will depend on the type of object B, which, at runtime, can change to square a circle etc. That way your code can draw multiple things with no need to change, even if new types of B are provided AFTER the code was written. Nifty -

Find unique lines

Use as follows:

sort < filea | uniq > fileb

setting an environment variable in virtualenv

In case you're using virtualenvwrapper (I highly recommend doing so), you can define different hooks (preactivate, postactivate, predeactivate, postdeactivate) using the scripts with the same names in $VIRTUAL_ENV/bin/. You need the postactivate hook.

$ workon myvenv

$ cat $VIRTUAL_ENV/bin/postactivate
#!/bin/bash
# This hook is run after this virtualenv is activated.
export DJANGO_DEBUG=True
export S3_KEY=mykey
export S3_SECRET=mysecret

$ echo $DJANGO_DEBUG
True

If you want to keep this configuration in your project directory, simply create a symlink from your project directory to $VIRTUAL_ENV/bin/postactivate.

$ rm $VIRTUAL_ENV/bin/postactivate
$ ln -s .env/postactivate $VIRTUAL_ENV/bin/postactivate

You could even automate the creation of the symlinks each time you use mkvirtualenv.

Cleaning up on deactivate

Remember that this wont clean up after itself. When you deactivate the virtualenv, the environment variable will persist. To clean up symmetrically you can add to $VIRTUAL_ENV/bin/predeactivate.

$ cat $VIRTUAL_ENV/bin/predeactivate
#!/bin/bash
# This hook is run before this virtualenv is deactivated.
unset DJANGO_DEBUG

$ deactivate

$ echo $DJANGO_DEBUG

Remember that if using this for environment variables that might already be set in your environment then the unset will result in them being completely unset on leaving the virtualenv. So if that is at all probable you could record the previous value somewhere temporary then read it back in on deactivate.

Setup:

$ cat $VIRTUAL_ENV/bin/postactivate
#!/bin/bash
# This hook is run after this virtualenv is activated.
if [[ -n $SOME_VAR ]]
then
    export SOME_VAR_BACKUP=$SOME_VAR
fi
export SOME_VAR=apple

$ cat $VIRTUAL_ENV/bin/predeactivate
#!/bin/bash
# This hook is run before this virtualenv is deactivated.
if [[ -n $SOME_VAR_BACKUP ]]
then
    export SOME_VAR=$SOME_VAR_BACKUP
    unset SOME_VAR_BACKUP
else
    unset SOME_VAR
fi

Test:

$ echo $SOME_VAR
banana

$ workon myenv

$ echo $SOME_VAR
apple

$ deactivate

$ echo $SOME_VAR
banana

Deleting an object in java?

//Just use a List
//create the list
public final List<Object> myObjects;

//instantiate the list
myObjects = new ArrayList<Object>();

//add objects to the list
Object object = myObject;
myObjects.add(object);

//remove the object calling this method if you have more than 1 objects still works with 1
//object too.

private void removeObject(){
int len = myObjects.size();
for(int i = 0;i<len; i++){
Objects object = myObjects.get(i);
myObjects.remove(object);
}
}

How to use 'git pull' from the command line?

Open up your git bash and type

echo $HOME

This shall be the same folder as you get when you open your command window (cmd) and type

echo %USERPROFILE%

And – of course – the .ssh folder shall be present on THAT directory.

make a phone call click on a button

I've just solved the problem on an Android 4.0.2 device (GN) and the only version working for this device/version was similar to the first 5-starred with CALL_PHONE permission and the answer:

Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:123456789"));
startActivity(callIntent);

With any other solution i got the ActivityNotFoundException on this device/version. How about the older versions? Would someone give feedback?

What are .NET Assemblies?

See this:

In the Microsoft .NET framework, an assembly is a partially compiled code library for use in deployment, versioning and security

How to run regasm.exe from command line other than Visual Studio command prompt?

I use the following in a batch file:

path = %path%;C:\Windows\Microsoft.NET\Framework\v2.0.50727
regasm httpHelper\bin\Debug\httpHelper.dll /tlb:.\httpHelper.tlb /codebase
pause

Android: Go back to previous activity

Just try this in, first activity

Intent mainIntent = new Intent(Activity1.this, Activity2.class);
this.startActivity(mainIntent);

In your second activity

@Override
public void onBackPressed() {
    this.finish();
}

Highlighting Text Color using Html.fromHtml() in Android?

Alternative solution: Using a WebView instead. Html is easy to work with.

WebView webview = new WebView(this);

String summary = "<html><body>Sorry, <span style=\"background: red;\">Madonna</span> gave no results</body></html>";

webview.loadData(summary, "text/html", "utf-8");

In what cases do I use malloc and/or new?

The new and delete operators can operate on classes and structures, whereas malloc and free only work with blocks of memory that need to be cast.

Using new/delete will help to improve your code as you will not need to cast allocated memory to the required data structure.

How do you get the footer to stay at the bottom of a Web page?

CSS :

  #container{
            width: 100%;
            height: 100vh;
            }
 #container.footer{
            float:left;
            width:100%;
            height:20vh;
            margin-top:80vh;
            background-color:red;
            }

HTML:

           <div id="container">
               <div class="footer">
               </div>
           </div>

This should do the trick if you are looking for a responsive footer aligned at the bottom of the page,which always keeps a top-margin of 80% of the viewport height.

How to change the pop-up position of the jQuery DatePicker control

First I think there should be a afterShowing method in the datepicker object, where you could change the position after jquery has done all its voodoo in the _showDatepicker method. Additionally, a parameter called preferedPosition would be also desirable, so you could set it and jquery modify it in case the dialog is rendered outside the viewport.

There's a "trick" to do this last thing. If you study the _showDatepicker method, you will see the use of a private variable $.datepikcer._pos. That variable will be setup if nobody has set it up before. If you modify that variable before showing the dialog, Jquery will take it and will try to allocate the dialog in that position, and if it renders out of the screen, it will adjust it to make sure it is visible. Sounds good, eh?

Problem is; _pos is private, but if you don't mind that. You can:

$('input.date').datepicker({
    beforeShow: function(input, inst)
    {
        $.datepicker._pos = $.datepicker._findPos(input); //this is the default position
        $.datepicker._pos[0] = whatever; //left
        $.datepicker._pos[1] = whatever; //top
    }
});

But be careful of Jquery-ui updates, because a change in the internal implementation of the _showDatepicker might break your code.

How do I format a date as ISO 8601 in moment.js?

var date = moment(new Date(), moment.ISO_8601);
console.log(date);

What is the difference between a 'closure' and a 'lambda'?

It depends on whether a function uses external variable or not to perform operation.

External variables - variables defined outside the scope of a function.

  • Lambda expressions are stateless because It depends on parameters, internal variables or constants to perform operations.

    Function<Integer,Integer> lambda = t -> {
        int n = 2
        return t * n 
    }
    
  • Closures hold state because it uses external variables (i.e. variable defined outside the scope of the function body) along with parameters and constants to perform operations.

    int n = 2
    
    Function<Integer,Integer> closure = t -> {
        return t * n 
    }
    

When Java creates closure, it keeps the variable n with the function so it can be referenced when passed to other functions or used anywhere.

Toolbar navigation icon never set

I tried to set up toolbar like @Gabriele Mariotti, but I had some problem with title. So then I set order to

toolbar.setTitle("Title")
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_good);

and it works.

Is there a function to split a string in PL/SQL?

You could use a combination of SUBSTR and INSTR as follows :

Example string : field = 'DE124028#@$1048708#@$000#@$536967136#@$'

The seperator being #@$.

To get the '1048708' for example :

If the field is of fixed length ( 7 here ) :

substr(field,instr(field,'#@$',1,1)+3,7)

If the field is of variable length :

substr(field,instr(field,'#@$',1,1)+3,instr(field,'#@$',1,2) - (instr(field,'#@$',1,1)+3)) 

You should probably look into SUBSTR and INSTR functions for more flexibility.

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

How can I upload files asynchronously?

Try

_x000D_
_x000D_
async function saveFile() _x000D_
{_x000D_
    let formData = new FormData();           _x000D_
    formData.append("file", file.files[0]);_x000D_
    await fetch('addFile.do', {method: "POST", body: formData});    _x000D_
    alert("Data Uploaded: ");_x000D_
}
_x000D_
<span>File</span>_x000D_
<input type="file" id="file" name="file" size="10"/>_x000D_
<input type="button" value="Upload" onclick="saveFile()"/>
_x000D_
_x000D_
_x000D_

The content-type='multipart/form-data' is set by browser automatically, the file name is added automatically too to filename FormData parameter (and can be easy read by server). Here is more developed example with err handling and json adding

_x000D_
_x000D_
async function saveFile(inp) _x000D_
{_x000D_
    let user = { name:'john', age:34 };_x000D_
    let formData = new FormData();_x000D_
    let photo = inp.files[0];      _x000D_
         _x000D_
    formData.append("photo", photo);_x000D_
    formData.append("user", JSON.stringify(user));  _x000D_
    _x000D_
    try {_x000D_
       let r = await fetch('/upload/image', {method: "POST", body: formData}); _x000D_
       console.log('HTTP response code:',r.status); _x000D_
       alert('success');_x000D_
    } catch(e) {_x000D_
       console.log('Huston we have problem...:', e);_x000D_
    }_x000D_
    _x000D_
}
_x000D_
<input type="file" onchange="saveFile(this)" >_x000D_
<br><br>_x000D_
Before selecting the file Open chrome console > network tab to see the request details._x000D_
<br><br>_x000D_
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
_x000D_
_x000D_
_x000D_

Specify sudo password for Ansible

You can use ansible vault which will code your password into encrypted vault. After that you can use variable from vault in playbooks.

Some documentation on ansible vault:
http://docs.ansible.com/playbooks_vault.html

We are using it as vault per environment. To edit vault we have command as:
ansible-vault edit inventories/production/group_vars/all/vault

If you want to call vault variable you have to use ansible-playbook with parameters like:
ansible-playbook -s --vault-password-file=~/.ansible_vault.password

Yes we are storing vault password in local directory in plain text but it's not more dangerous like store root password for every system. Root password is inside vault file or you can have it like sudoers file for your user/group.

I'm recommending to use sudoers file on the server. Here is example for group admin:
%admin ALL=(ALL) NOPASSWD:ALL

How to fix "Headers already sent" error in PHP

I got this error many times before, and I am certain all PHP programmer got this error at least once before.

Possible Solution 1

This error may have been caused by the blank spaces before the start of the file or after the end of the file.These blank spaces should not be here.

ex) THERE SHOULD BE NO BLANK SPACES HERE

   echo "your code here";

?>
THERE SHOULD BE NO BLANK SPACES HERE

Check all files associated with file that causes this error.

Note: Sometimes EDITOR(IDE) like gedit (a default linux editor) add one blank line on save file. This should not happen. If you are using Linux. you can use VI editor to remove space/lines after ?> at the end of the page.

Possible Solution 2: If this is not your case, then use ob_start to output buffering:

<?php
  ob_start();

  // code 

 ob_end_flush();
?> 

This will turn output buffering on and your headers will be created after the page is buffered.

Javascript - Get Image height

It's worth noting that in Firefox 3 and Safari, resizing an image by just changing the height and width doesn't look too bad. In other browsers it can look very noisy because it's using nearest-neighbor resampling. Of course, you're paying to serve a larger image, but that might not matter.

Initializing an Array of Structs in C#

I'd use a static constructor on the class that sets the value of a static readonly array.

public class SomeClass
{
   public readonly MyStruct[] myArray;

   public static SomeClass()
   {
      myArray = { {"foo", "bar"},
                  {"boo", "far"}};
   }
}

HTTP Error 500.30 - ANCM In-Process Start Failure

Plz see my prev answer in this same thread to understand the whole. Sorry for multiple answers

After further investigation, the issue was happening due to VS 2019 picks the latest patch(default behavior of VS) of .net core 2.2 which is 2.2.8 for me to publish the application. We can restrict this to a specific version of choice by using

<RuntimeFrameworkVersion>2.2.4</RuntimeFrameworkVersion>

See Here. This finally solved my issue even though the latest patch is not applied. I can build from any VS 2017 or VS 2019, both publish the application for .net core 2.2.0 runtime version

enter image description here

Java, "Variable name" cannot be resolved to a variable

public void setHoursWorked(){
    hoursWorked = hours;
}

You haven't defined hours inside that method. hours is not passed in as a parameter, it's not declared as a variable, and it's not being used as a class member, so you get that error.

Oracle PL/SQL - Are NO_DATA_FOUND Exceptions bad for stored procedure performance?

you dont have to use open when you are using for loops.

declare
cursor cur_name is  select * from emp;
begin
for cur_rec in cur_name Loop
    dbms_output.put_line(cur_rec.ename);
end loop;
End ;

or

declare
cursor cur_name is  select * from emp;
cur_rec emp%rowtype;
begin
Open cur_name;
Loop
Fetch cur_name into  Cur_rec;
   Exit when cur_name%notfound;
    dbms_output.put_line(cur_rec.ename);
end loop;
Close cur_name;
End ;

Display encoded html with razor

this is pretty simple:

HttpUtility.HtmlDecode(Model.Content)

Another Solution, you could also return a HTMLString, Razor will output the correct formatting:

in the view itself:

@Html.GetSomeHtml()

in controller:

public static HtmlString GetSomeHtml()
{
    var Data = "abc<br/>123";
    return new HtmlString(Data);
}

default value for struct member in C

Create a default struct as the other answers have mentioned:

struct MyStruct
{
    int flag;
}

MyStruct_default = {3};

However, the above code will not work in a header file - you will get error: multiple definition of 'MyStruct_default'. To solve this problem, use extern instead in the header file:

struct MyStruct
{
    int flag;
};

extern const struct MyStruct MyStruct_default;

And in the c file:

const struct MyStruct MyStruct_default = {3};

Hope this helps anyone having trouble with the header file.

POST request with JSON body

You need to use the cURL library to send this request.

<?php
// Your ID and token
$blogID = '8070105920543249955';
$authToken = 'OAuth 2.0 token here';

// The data to send to the API
$postData = array(
    'kind' => 'blogger#post',
    'blog' => array('id' => $blogID),
    'title' => 'A new post',
    'content' => 'With <b>exciting</b> content...'
);

// Setup cURL
$ch = curl_init('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/');
curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => array(
        'Authorization: '.$authToken,
        'Content-Type: application/json'
    ),
    CURLOPT_POSTFIELDS => json_encode($postData)
));

// Send the request
$response = curl_exec($ch);

// Check for errors
if($response === FALSE){
    die(curl_error($ch));
}

// Decode the response
$responseData = json_decode($response, TRUE);

// Close the cURL handler
curl_close($ch);

// Print the date from the response
echo $responseData['published'];

If, for some reason, you can't/don't want to use cURL, you can do this:

<?php
// Your ID and token
$blogID = '8070105920543249955';
$authToken = 'OAuth 2.0 token here';

// The data to send to the API
$postData = array(
    'kind' => 'blogger#post',
    'blog' => array('id' => $blogID),
    'title' => 'A new post',
    'content' => 'With <b>exciting</b> content...'
);

// Create the context for the request
$context = stream_context_create(array(
    'http' => array(
        // http://www.php.net/manual/en/context.http.php
        'method' => 'POST',
        'header' => "Authorization: {$authToken}\r\n".
            "Content-Type: application/json\r\n",
        'content' => json_encode($postData)
    )
));

// Send the request
$response = file_get_contents('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/', FALSE, $context);

// Check for errors
if($response === FALSE){
    die('Error');
}

// Decode the response
$responseData = json_decode($response, TRUE);

// Print the date from the response
echo $responseData['published'];

How to do a SQL NOT NULL with a DateTime?

Just to rule out a possibility - it doesn't appear to have anything to do with the ANSI_NULLS option, because that controls comparing to NULL with the = and <> operators. IS [NOT] NULL works whether ANSI_NULLS is ON or OFF.

I've also tried this against SQL Server 2005 with isql, because ANSI_NULLS defaults to OFF when using DB-Library.

How to go from one page to another page using javascript?

Easier method is window.location.href = "http://example.com/new_url";

But what if you want to check if username and password whether empty or not using JavaScript and send it to the php to check whether user in the database. You can do this easily following this code.

html form -

<form name="myForm" onsubmit="return validateForm()" method="POST" action="login.php" >         
    <input type="text" name="username" id="username" />
    <input type="password" name="password" id="password" />
    <input type="submit" name="submitBt"value="LogIn" />
</form>

javascript validation-

function validateForm(){
    var uname = document.forms["myForm"]["username"].value;
    var pass = document.forms["myForm"]["password"].value;

    if((!isEmpty(uname, "Log In")) && (!isEmpty(pass, "Password"))){

        return true;
    }else{
        return false;
    }
}

function isEmpty(elemValue, field){
    if((elemValue == "") || (elemValue == null)){
        alert("you can not have "+field+" field empty");
        return true;
    }else{
        return false;
    }
}

check if user in the database using php

<?php
    $con = mysqli_connect("localhost","root","1234","users");

    if(mysqli_connect_errno()){
        echo "Couldn't connect ".mysqli_connect_error();
    }else{
        //echo "connection successful <br />";
    }

    $uname_tb = $_POST['username'];
    $pass_tb = $_POST['password'];

    $query ="SELECT * FROM user";
    $result = mysqli_query($con,$query);

    while($row = mysqli_fetch_array($result)){
        if(($row['username'] == $uname_tb) && ($row['password'] == $pass_tb)){
            echo "Login Successful";
            header('Location: dashbord.php');
            exit();
        }else{
            echo "You are not in our database".mysqli_connect_error();
        }
    }
    mysqli_close($con);
?>

Center the content inside a column in Bootstrap 4

_x000D_
_x000D_
.row>.col, .row>[class^=col-] {_x000D_
    padding-top: .75rem;_x000D_
    padding-bottom: .75rem;_x000D_
    background-color: rgba(86,61,124,.15);_x000D_
    border: 1px solid rgba(86,61,124,.2);_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container">_x000D_
  <div class="row justify-content-md-center">_x000D_
    <div class="col col-lg-2">_x000D_
      1 of 3_x000D_
    </div>_x000D_
    <div class="col col-lg-2">_x000D_
      1 of 2_x000D_
    </div>_x000D_
    <div class="col col-lg-2">_x000D_
      3 of 3_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Renaming files in a folder to sequential numbers

Again using Pero's solution with little modifying, because find will be traversing the directory tree in the order items are stored within the directory entries. This will (mostly) be consistent from run to run, on the same machine and will essentially be "file/directory creation order" if there have been no deletes.

However, in some case you need to get some logical order, say, by name, which is used in this example.

find -name '*.jpg' | sort -n | # find jpegs
gawk 'BEGIN{ a=1 }{ printf "mv %s %04d.jpg\n", $0, a++ }' | # build mv command
bash # run that command 

How do I convert a date/time to epoch time (unix time/seconds since 1970) in Perl?

There are many Date manipulation modules on CPAN. My particular favourite is DateTime and you can use the strptime modules to parse dates in arbitrary formats. There are also many DateTime::Format modules on CPAN for handling specialised date formats, but strptime is the most generic.

bypass invalid SSL certificate in .net core

In .NetCore, you can add the following code snippet at services configure method , I added a check to make sure only that we by pass the SSL certificate in development environment only

services.AddHttpClient("HttpClientName", client => {
// code to configure headers etc..
}).ConfigurePrimaryHttpMessageHandler(() => {
                  var handler = new HttpClientHandler();
                  if (hostingEnvironment.IsDevelopment())
                  {
                      handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
                  }
                  return handler;
              });

Java String split removed empty values

String[] split = data.split("\\|",-1);

This is not the actual requirement in all the time. The Drawback of above is show below:

Scenerio 1:
When all data are present:
    String data = "5|6|7||8|9|10|";
    String[] split = data.split("\\|");
    String[] splt = data.split("\\|",-1);
    System.out.println(split.length); //output: 7
    System.out.println(splt.length); //output: 8

When data is missing:

Scenerio 2: Data Missing
    String data = "5|6|7||8|||";
    String[] split = data.split("\\|");
    String[] splt = data.split("\\|",-1);
    System.out.println(split.length); //output: 5
    System.out.println(splt.length); //output: 8

Real requirement is length should be 7 although there is data missing. Because there are cases such as when I need to insert in database or something else. We can achieve this by using below approach.

    String data = "5|6|7||8|||";
    String[] split = data.split("\\|");
    String[] splt = data.replaceAll("\\|$","").split("\\|",-1);
    System.out.println(split.length); //output: 5
    System.out.println(splt.length); //output:7

What I've done here is, I'm removing "|" pipe at the end and then splitting the String. If you have "," as a seperator then you need to add ",$" inside replaceAll.

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

A lot depends on what kind of project it is. WTP's JSP support either expects the JSP files to be under the same folder that's the parent of the WEB-INF folder (src/web, which it will then treat as "/" to find TLDs), or to have project metadata set up to help it know where that root is (done for you in a Dynamic Web Project through Deployment Assembly). How are you referring to the TLD file, and where is the JSP file located?

And maybe I missed the original post to the Eclipse forums; the one I saw was posted a full day after this one.

php static function

Calling non-static methods statically generates an E_STRICT level warning.

How to comment lines in rails html.erb files?

This is CLEANEST, SIMPLEST ANSWER for CONTIGUOUS NON-PRINTING Ruby Code:

The below also happens to answer the Original Poster's question without, the "ugly" conditional code that some commenters have mentioned.


  1. CONTIGUOUS NON-PRINTING Ruby Code

    • This will work in any mixed language Rails View file, e.g, *.html.erb, *.js.erb, *.rhtml, etc.

    • This should also work with STD OUT/printing code, e.g. <%#= f.label :title %>

    • DETAILS:

      Rather than use rails brackets on each line and commenting in front of each starting bracket as we usually do like this:

        <%# if flash[:myErrors] %>
          <%# if flash[:myErrors].any? %>
            <%# if @post.id.nil? %>
              <%# if @myPost!=-1 %>
                <%# @post = @myPost %>
              <%# else %>
                <%# @post = Post.new %>
              <%# end %>
            <%# end %>
          <%# end %>
        <%# end %>
      

      YOU CAN INSTEAD add only one comment (hashmark/poundsign) to the first open Rails bracket if you write your code as one large block... LIKE THIS:

        <%# 
          if flash[:myErrors] then
            if flash[:myErrors].any? then
              if @post.id.nil? then
                if @myPost!=-1 then
                  @post = @myPost 
                else 
                  @post = Post.new 
                end 
              end 
            end 
          end 
        %>
      

event Action<> vs event EventHandler<>

Looking at Standard .NET event patterns we find

The standard signature for a .NET event delegate is:

void OnEventRaised(object sender, EventArgs args);

[...]

The argument list contains two arguments: the sender, and the event arguments. The compile time type of sender is System.Object, even though you likely know a more derived type that would always be correct. By convention, use object.

Below on same page we find an example of the typical event definition which is something like

public event EventHandler<EventArgs> EventName;

Had we defined

class MyClass
{
  public event Action<MyClass, EventArgs> EventName;
}

the handler could have been

void OnEventRaised(MyClass sender, EventArgs args);

where sender has the correct (more derived) type.

How to redirect stderr and stdout to different files in the same line in script?

Try this:

your_command 2>stderr.log 1>stdout.log

More information

The numerals 0 through 9 are file descriptors in bash. 0 stands for standard input, 1 stands for standard output, 2 stands for standard error. 3 through 9 are spare for any other temporary usage.

Any file descriptor can be redirected to a file or to another file descriptor using the operator >. You can instead use the operator >> to appends to a file instead of creating an empty one.

Usage:

file_descriptor > filename

file_descriptor > &file_descriptor

Please refer to Advanced Bash-Scripting Guide: Chapter 20. I/O Redirection.