Programs & Examples On #Background repeat

A CSS Property that defines whether or not background property of an element should "tile" to fill the entire element if the background is smaller than the element. This can be broken up into background-repeat-x for horizontal repeating and background-repeat-y for vertical repeating. The background repeat properly is typically used with an image for the background property.

Vertical Align Center in Bootstrap 4

In Bootstrap 4 (beta), use align-middle. Refer to Bootstrap 4 Documentation on Vertical alignment:

Change the alignment of elements with the vertical-alignment utilities. Please note that vertical-align only affects inline, inline-block, inline-table, and table cell elements.

Choose from .align-baseline, .align-top, .align-middle, .align-bottom, .align-text-bottom, and .align-text-top as needed.

How to add image background to btn-default twitter-bootstrap button?

_x000D_
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<style type="text/css">_x000D_
  .sign-in-facebook_x000D_
  {_x000D_
    background-image: url('http://i.stack.imgur.com/e2S63.png');_x000D_
    background-position: -9px -7px;_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: 39px 43px;_x000D_
    padding-left: 41px;_x000D_
    color: #000;_x000D_
  }_x000D_
  .sign-in-facebook:hover_x000D_
  {_x000D_
    background-image: url('http://i.stack.imgur.com/e2S63.png');_x000D_
    background-position: -9px -7px;_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: 39px 43px;_x000D_
    padding-left: 41px;_x000D_
    color: #000;_x000D_
  }_x000D_
</style>_x000D_
<p>My current button got white background<br/>_x000D_
<input type="button" value="Sign In with Facebook" class="sign-in-facebook btn btn-secondary" style="margin-top:2px; margin-bottom:2px;" >_x000D_
</p>_x000D_
<p>I need the current btn-default style like below<br/>_x000D_
<input type="button" class="btn btn-default" value="Sign In with Facebook" />_x000D_
</p>_x000D_
<strong>NOTE:</strong> facebook icon at left side of the button.
_x000D_
_x000D_
_x000D_

Background image jumps when address bar hides iOS/Android/Mobile Chrome

For those who would like to listen to the actual inner height and vertical scroll of the window while the Chrome mobile browser is transition the URL bar from shown to hidden and vice versa, the only solution that I found is to set an interval function, and measure the discrepancy of the window.innerHeight with its previous value.

This introduces this code:

_x000D_
_x000D_
var innerHeight = window.innerHeight;_x000D_
window.setInterval(function ()_x000D_
{_x000D_
  var newInnerHeight = window.innerHeight;_x000D_
  if (newInnerHeight !== innerHeight)_x000D_
  {_x000D_
    var newScrollY = window.scrollY + newInnerHeight - innerHeight;_x000D_
    // ... do whatever you want with this new scrollY_x000D_
    innerHeight = newInnerHeight;_x000D_
  }_x000D_
}, 1000 / 60);
_x000D_
_x000D_
_x000D_

I hope that this will be handy. Does anyone knows a better solution?

How to add Button over image using CSS?

You need to give relative or absolute or fixed positioning to your container (#shop) and set its zIndex to say 100.

You also need to give say relative positioning to your elements with the class content and lower zIndex say 97.

Do the above-mentioned with your images too and set their zIndex to 91.

And then position your button higher by setting its position to absolute and zIndex to 95

See the DEMO

HTML

<div id="shop">

 <div class="content"> Counter-Strike 1.6 Steam 

     <img src="http://www.openvms.org/images/samples/130x130.gif">

         <a href="#"><span class='span'><span></a>

     </div>

 <div class="content"> Counter-Strike 1.6 Steam 

     <img src="http://www.openvms.org/images/samples/130x130.gif">

         <a href="#"><span class='span'><span></a>

     </div>

  </div>

CSS

#shop{
    background-image: url("images/shop_bg.png");
    background-repeat: repeat-x;    
    height:121px;
    width: 984px;
    margin-left: 20px;
    margin-top: 13px;
    position:relative;
    z-index:100
}

#shop .content{    
    width: 182px; /*328 co je 1/3 - 20margin left*/
    height: 121px;
    line-height: 20px;
    margin-top: 0px;
    margin-left: 9px;
    margin-right:0px;
    display:inline-block;
    position:relative;
    z-index:97

}

img{

    position:relative;
    z-index:91

}

.span{

    width:70px;
    height:40px;
    border:1px solid red;
    position:absolute;
    z-index:95;
    right:60px;
    bottom:-20px;

}

CSS: stretching background image to 100% width and height of screen?

You need to set the height of html to 100%

body {
    background-image:url("../images/myImage.jpg");
    background-repeat: no-repeat;
    background-size: 100% 100%;
}
html {
    height: 100%
}

http://jsfiddle.net/8XUjP/

How to make a transparent HTML button?

Setting its background image to none also works:

button {
    background-image: none;
}

Bootstrap 3 - jumbotron background image effect

After inspecting the sample website you provided, I found that the author might achieve the effect by using a library called Stellar.js, take a look at the library site, cheers!

HTTP Status 500 - org.apache.jasper.JasperException: java.lang.NullPointerException

In Tomcat a .java and .class file will be created for every jsp files with in the application and the same can be found from the path below, Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\index_jsp.java

In your case the jsp name is error.jsp so the path should be something like below Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\error_jsp.java in line no 124 you are trying to access a null object which results in null pointer exception.

How do I add a margin between bootstrap columns without wrapping

I was facing the same issue; and the following worked well for me. Hope this helps someone landing here:

<div class="row">
    <div class="col-md-6">
        <div class="col-md-12">
            Set room heater temperature
        </div>
    </div>
    <div class="col-md-6">
        <div class="col-md-12">
            Set room heater temperature
        </div>
    </div>
</div>

This will automatically render some space between the 2 divs. enter image description here

How to show full height background image?

 html, body {
    height:100%;
}

body { 
    background: url(images/bg.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Decreasing height of bootstrap 3.0 navbar

I think we can write this fewer styles, without changing the existing color. The following worked for me (in Bootstrap 3.2.0)

.navbar-nav > li > a { padding-top: 5px !important; padding-bottom: 5px !important; }
.navbar { min-height: 32px !important; }
.navbar-brand { padding-top: 5px; padding-bottom: 10px; padding-left: 10px; }

The last one ('navbar-brand') is actually needed only if you have text as your 'brand' name.

Bootstrap 3 Carousel fading to new slide instead of sliding to new slide

The update from 3.2.x to 3.3.x broke some of the solutions explained here and on other threads because of the change: "Added transforms to improve carousel performance in modern browsers."

If you are using Bootstrap 3.3.x there's a solution here:
http://codepen.io/transportedman/pen/NPWRGq

Basically you need to add the "carousel-fade" class to your carousel so that you have:
<div class="carousel slide carousel-fade">

And then include the following CSS:

/*
  Bootstrap Carousel Fade Transition (for Bootstrap 3.3.x)
  CSS from:       http://codepen.io/transportedman/pen/NPWRGq
  and:            http://stackoverflow.com/questions/18548731/bootstrap-3-carousel-fading-to-new-slide-instead-of-sliding-to-new-slide
  Inspired from:  http://codepen.io/Rowno/pen/Afykb 
*/
.carousel-fade .carousel-inner .item {
  opacity: 0;
  transition-property: opacity;
}

.carousel-fade .carousel-inner .active {
  opacity: 1;
}

.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
  left: 0;
  opacity: 0;
  z-index: 1;
}

.carousel-fade .carousel-inner .next.left,
.carousel-fade .carousel-inner .prev.right {
  opacity: 1;
}

.carousel-fade .carousel-control {
  z-index: 2;
}

/*
  WHAT IS NEW IN 3.3: "Added transforms to improve carousel performance in modern browsers."
  Need to override the 3.3 new styles for modern browsers & apply opacity
*/
@media all and (transform-3d), (-webkit-transform-3d) {
    .carousel-fade .carousel-inner > .item.next,
    .carousel-fade .carousel-inner > .item.active.right {
      opacity: 0;
      -webkit-transform: translate3d(0, 0, 0);
              transform: translate3d(0, 0, 0);
    }
    .carousel-fade .carousel-inner > .item.prev,
    .carousel-fade .carousel-inner > .item.active.left {
      opacity: 0;
      -webkit-transform: translate3d(0, 0, 0);
              transform: translate3d(0, 0, 0);
    }
    .carousel-fade .carousel-inner > .item.next.left,
    .carousel-fade .carousel-inner > .item.prev.right,
    .carousel-fade .carousel-inner > .item.active {
      opacity: 1;
      -webkit-transform: translate3d(0, 0, 0);
              transform: translate3d(0, 0, 0);
    }
}

Refresh Page and Keep Scroll Position

Thanks Sanoj, that worked for me.
However iOS does not support "onbeforeunload" on iPhone. Workaround for me was to set localStorage with js:

<button onclick="myFunction()">Click me</button>

<script>
document.addEventListener("DOMContentLoaded", function(event) { 
            var scrollpos = localStorage.getItem('scrollpos');
            if (scrollpos) window.scrollTo(0, scrollpos);
        });
function myFunction() {
  localStorage.setItem('scrollpos', window.scrollY);
  location.reload(); 
}
</script>

Uncaught ReferenceError: $ is not defined

This probably happens, when you forget to include your jQuery CDN or local path

Full-screen responsive background image

For the full-screen responsive background image cover

<div class="full-screen">

</div>

CSS

.full-screen{
    background-image: url("img_girl.jpg");
    height: 100%; 
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}

Making text background transparent but not text itself

For a fully transparent background use:

background: transparent;

Otherwise for a semi-transparent color fill use:

background: rgba(255,255,255,0.5); // or hsla(0, 0%, 100%, 0.5)

where the values are:

background: rgba(red,green,blue,opacity); // or hsla(hue, saturation, lightness, opacity)

You can also use rgba values for gradient backgrounds.

To get transparency on an image background simply reduce the opacity of the image in an image editor of you choice beforehand.

remove borders around html input

use this i hope this help ful to you... border:none !important; background-color:transparent;

try this

<div id="generic_search"><input type="search" onkeypress="return runScript(event)" /></div>
<button type="button" id="generic_search_button" /></button>

HTML Table cell background image alignment

This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:

<table>
    <tr>
        <td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
            Hello World
        </td>
    </tr>
</table>

background-image: url("images/plaid.jpg") no-repeat; wont show up

You either use :

background-image: url("images/plaid.jpg");
background-repeat: no-repeat;

... or

background: transparent url("images/plaid.jpg") top left no-repeat;

... but definitively not

background-image: url("images/plaid.jpg") no-repeat;

EDIT : Demo at JSFIDDLE using absolute paths (in case you have troubles referring to your images with relative paths).

HTML5 image icon to input placeholder

  1. You can set it as background-image and use text-indent or a padding to shift the text to the right.
  2. You can break it up into two elements.

Honestly, I would avoid usage of HTML5/CSS3 without a good fallback. There are just too many people using old browsers that don't support all the new fancy stuff. It will take a while before we can drop the fallback, unfortunately :(

The first method I mentioned is the safest and easiest. Both ways requires Javascript to hide the icon.

CSS:

input#search {
    background-image: url(bg.jpg);
    background-repeat: no-repeat;
    text-indent: 20px;
}

HTML:

<input type="text" id="search" name="search" onchange="hideIcon(this);" value="search" />

Javascript:

function hideIcon(self) {
    self.style.backgroundImage = 'none';
}

September 25h, 2013

I can't believe I said "Both ways requires JavaScript to hide the icon.", because this is not entirely true.

The most common timing to hide placeholder text is on change, as suggested in this answer. For icons however it's okay to hide them on focus which can be done in CSS with the active pseudo-class.

#search:active { background-image: none; }

Heck, using CSS3 you can make it fade away!

http://jsfiddle.net/2tTxE/


November 5th, 2013

Of course, there's the CSS3 ::before pseudo-elements too. Beware of browser support though!

            Chrome  Firefox     IE      Opera   Safari
:before     (yes)   1.0         8.0     4       4.0
::before    (yes)   1.5         9.0     7       4.0

https://developer.mozilla.org/en-US/docs/Web/CSS/::before

Responsive css background images

CSS:

background-size: 100%;

That should do the trick! :)

Insert a background image in CSS (Twitter Bootstrap)

The problem can also be the ordering of your style sheet imports. I had to move my custom style sheet import below the bootstrap import.

How to handle iframe in Selenium WebDriver using java

In Webdriver, you should use driver.switchTo().defaultContent(); to get out of a frame. You need to get out of all the frames first, then switch into outer frame again.

// between step 4 and step 5
// remove selenium.selectFrame("relative=up");
driver.switchTo().defaultContent(); // you are now outside both frames
driver.switchTo().frame("cq-cf-frame");
// now continue step 6
driver.findElement(By.xpath("//button[text()='OK']")).click(); 

Background position, margin-top?

#div-name

{

  background-image: url('../images/background-art-main.jpg');
  background-position: top right 50px;
  background-repeat: no-repeat;
}

HTML not loading CSS file

I had a similar problem and tested different ways to solve it.

Eventually I understood that my index.htm file had been saved with "Unicode" encoding (for using Farsi characters in my page) while my .css file had been save with "ANSI" format.

I changed the encoding of my .css file to "Unicode" with Notepad and the problem got solved.

CSS background image to fit width, height should auto-scale in proportion

There is a CSS3 property for this, namely background-size (compatibility check). While one can set length values, it's usually used with the special values contain and cover. In your specific case, you should use cover:

body {
    background-image:    url(images/background.svg);
    background-size:     cover;                      /* <------ */
    background-repeat:   no-repeat;
    background-position: center center;              /* optional, center the image */
}

Eggsplanation for contain and cover

Sorry for the bad pun, but I'm going to use the picture of the day by Biswarup Ganguly for demonstration. Lets say that this is your screen, and the gray area is outside of your visible screen. For demonstration, I'm going to assume a 16x9 ratio.

screen

We want to use the aforementioned picture of the day as a background. However, we cropped the image to 4x3 for some reason. We could set the background-size property to some fixed length, but we will focus on contain and cover. Note that I also assume that we didn't mangle the width and/or height of body.

contain

contain

Scale the image, while preserving its intrinsic aspect ratio (if any), to the largest size such that both its width and its height can fit inside the background positioning area.

This makes sure that the background image is always completely contained in the background positioning area, however, there could be some empty space filled with your background-color in this case:

contain

cover

cover

Scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area.

This makes sure that the background image is covering everything. There will be no visible background-color, however depending on the screen's ratio a great part of your image could be cut off:

cover

Demonstration with actual code

_x000D_
_x000D_
div > div {_x000D_
  background-image: url(http://i.stack.imgur.com/r5CAq.jpg);_x000D_
  background-repeat: no-repeat;_x000D_
  background-position: center center;_x000D_
  background-color: #ccc;_x000D_
  border: 1px solid;_x000D_
  width: 20em;_x000D_
  height: 10em;_x000D_
}_x000D_
div.contain {_x000D_
  background-size: contain;_x000D_
}_x000D_
div.cover {_x000D_
  background-size: cover;_x000D_
}_x000D_
/********************************************_x000D_
 Additional styles for the explanation boxes _x000D_
*********************************************/_x000D_
_x000D_
div > div {_x000D_
  margin: 0 1ex 1ex 0;_x000D_
  float: left;_x000D_
}_x000D_
div + div {_x000D_
  clear: both;_x000D_
  border-top: 1px dashed silver;_x000D_
  padding-top:1ex;_x000D_
}_x000D_
div > div::after {_x000D_
  background-color: #000;_x000D_
  color: #fefefe;_x000D_
  margin: 1ex;_x000D_
  padding: 1ex;_x000D_
  opacity: 0.8;_x000D_
  display: block;_x000D_
  width: 10ex;_x000D_
  font-size: 0.7em;_x000D_
  content: attr(class);_x000D_
}
_x000D_
<div>_x000D_
  <div class="contain"></div>_x000D_
  <p>Note the grey background. The image does not cover the whole region, but it's fully <em>contained</em>._x000D_
  </p>_x000D_
</div>_x000D_
<div>_x000D_
  <div class="cover"></div>_x000D_
  <p>Note the ducks/geese at the bottom of the image. Most of the water is cut, as well as a part of the sky. You don't see the complete image anymore, but neither do you see any background color; the image <em>covers</em> all of the <code>&lt;div&gt;</code>.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I make my website's background transparent without making the content (images & text) transparent too?

I think what's happening, is that, since the wrapper id is relatively position, it just appears on the same position with the body tag, what you should do, is that you can add a Z-index to the wrapper id.

#wrapper {
margin: auto;
text-align: left;
width: 832px;
position: relative;
padding-top: 27px;
z-index: 99; /* added this line */
 }

This should make layers above the transparent body tag.

Fit background image to div

If what you need is the image to have the same dimensions of the div, I think this is the most elegant solution:

background-size: 100% 100%;

If not, the answer by @grc is the most appropriated one.

Source: http://www.w3schools.com/cssref/css3_pr_background-size.asp

css with background image without repeating the image

body {
    background: url(images/image_name.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Here is a good solution to get your image to cover the full area of the web app perfectly

background-size in shorthand background property (CSS3)

Just a note for reference: I was trying to do shorthand like so:

background: url('../images/sprite.png') -312px -234px / 355px auto no-repeat;

but iPhone Safari browsers weren't showing the image properly with a fixed position element. I didn't check with a non-fixed, because I'm lazy. I had to switch the css to what's below, being careful to put background-size after the background property. If you do them in reverse, the background reverts the background-size to the original size of the image. So generally I would avoid using the shorthand to set background-size.

background: url('../images/sprite.png') -312px -234px no-repeat;
background-size: 355px auto;

Can I fade in a background image (CSS: background-image) with jQuery?

You can give opacity value as

div {opacity: 0.4;}

For IE, you can specify as

div { filter:alpha(opacity=10));}

Lower the value - Higher the transparency.

How to position a table at the center of div horizontally & vertically

I discovered that I had to include

body { width:100%; }

for "margin: 0 auto" to work for tables.

Auto height of div

Here is the Latest solution of the problem:

In your CSS file write the following class called .clearfix along with the pseudo selector :after

.clearfix:after {
content: "";
display: table;
clear: both;
}

Then, in your HTML, add the .clearfix class to your parent Div. For example:

<div class="clearfix">
    <div></div>
    <div></div>
</div>

It should work always. You can call the class name as .group instead of .clearfix , as it will make the code more semantic. Note that, it is Not necessary to add the dot or even a space in the value of Content between the double quotation "".

Source: http://css-snippets.com/page/2/

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

To get rid of the default dropdown arrow use:

-moz-appearance: window; 

add title attribute from css

Well, although it's not actually possible to change the title attribute, it is possible to show a tooltip completely from css. You can check a working version out at http://jsfiddle.net/HzH3Z/5/.

What you can do is style the label:after selector and give it display:none, and set it's content from css. You can then change the display attribute to display:block on label:hover:after, and it will show. Like this:

label:after{
    content: "my tooltip";
    padding: 2px;
    display:none;
    position: relative;
    top: -20px;
    right: -30px;
    width: 150px;
    text-align: center;
    background-color: #fef4c5;
    border: 1px solid #d4b943;
    -moz-border-radius: 2px;
    -webkit-border-radius: 2px;
    -ms-border-radius: 2px;
    border-radius: 2px;
}
label:hover:after{
    display: block;
}

Div not expanding even with content inside

Floated elements don’t take up any vertical space in their containing element.

All of your elements inside #albumhold are floated, apart from #albumhead, which doesn’t look like it’d take up much space.

However, if you add overflow: hidden; to #albumhold (or some other CSS to clear floats inside it), it will expand its height to encompass its floated children.

Stretch background image css?

.style1 {
  background: url(images/bg.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

Works in:

  • Safari 3+
  • Chrome Whatever+
  • IE 9+
  • Opera 10+ (Opera 9.5 supported background-size but not the keywords)
  • Firefox 3.6+ (Firefox 4 supports non-vendor prefixed version)

In addition you can try this for an IE solution

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
zoom: 1;

Credit to this article by Chris Coyier http://css-tricks.com/perfect-full-page-background-image/

How to rotate the background image in the container?

CSS:

.reverse {
  transform: rotate(180deg);
}

.rotate {
  animation-duration: .5s;
  animation-iteration-count: 1;
  animation-name: yoyo;
  animation-timing-function: linear;
}

@keyframes yoyo {
  from { transform: rotate(  0deg); }
  to   { transform: rotate(360deg); }
}

Javascript:

$(buttonElement).click(function () {
  $(".arrow").toggleClass("reverse")

  return false
})

$(buttonElement).hover(function () {
  $(".arrow").addClass("rotate")
}, function() {
  $(".arrow").removeClass("rotate")
})

PS: I've found this somewhere else but don't remember the source

How to center a (background) image within a div?

This works for me for aligning the image to center of div.

.yourclass {
  background-image: url(image.png);
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
}

CSS background-image not working

I have tried your code and found that if we put background-image: url(image.png); in btn-pToolName and change color:#000000. it displays the image at background.

my test css:

           .btn-pTool {
                margin: 0;
                padding: 0;
            }

            .btn-pToolName {
                text-align: center;
                width: 26px;
                height: 190px;
                display: block;
                color: #000000;
                text-decoration: none;
                font-family: Arial, Helvetica, sans-serif;
                font-weight: bold;
                font-size: 1em;
                line-height: 32px;
                background-image: url(defalut.png);
                background-repeat: no-repeat;
            }

and test html:

        <div class="pToolContainer">
            <span class="btn-pTool"><a class="btn-pToolName" href="#">adad</a></span>
            <div class="pToolSlidePanel"></div>
        </div>

Hope this helps.

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

That offset is basically the x,y position that the browser has calculated for the element based on it's position css attribute. So if you put a <br> before it or any other element, it would change the offset. For example, you could set it to 0 by:

#inputBox{position:absolute;top:0px;left:0px;}

or

#inputBox{position:relative;top:-12px;left:-2px;}

Therefore, whatever positioning issue you have, is not necessarily an issue with offset, though you could always fix it by playing with the top,left,right and bottom attributes.

Is your problem browser incompatibility?

CSS: image link, change on hover

If you have just a few places where you wish to create this effect, you can use the following html code that requires no css. Just insert it.

<a href="TARGET URL GOES HERE"><img src="URL OF FIRST IMAGE GOES HERE" 
onmouseover="this.src='URL OF IMAGE ON HOVER GOES HERE'"
onmouseout="this.src='URL OF FIRST IMAGE GOES HERE AGAIN'" /></A>

Be sure to write the quote marks exactly as they are here, or it will not work.

HTML / CSS How to add image icon to input type="button"?

If you're using spritesheets this becomes impossible and the element must be wrapped.

.btn{
    display: inline-block;
    background: blue;
    position: relative;
    border-radius: 5px;
}
.input, .btn:after{
    color: #fff;
}
.btn:after{
    position: absolute;
    content: '@';
    right: 0;
    width: 1.3em;
    height: 1em;
}
.input{
    background: transparent;
    color: #fff;
    border: 0;
    padding-right: 20px;
    cursor: pointer;
    position: relative;
    padding: 5px 20px 5px 5px;
    z-index: 1;
}

Check out this fiddle: http://jsfiddle.net/AJNnZ/

Add URL link in CSS Background Image?

You can not add links from CSS, you will have to do so from the HTML code explicitly. For example, something like this:

<a href="whatever.html"><li id="header"></li></a>

Does height and width not apply to span?

Span starts out as an inline element. You can change its display attribute to block, for instance, and its height/width attributes will start to take effect.

Align DIV's to bottom or baseline

The answer posted by Y. Shoham (using absolute positioning) seems to be the simplest solution in most cases where the container is a fixed height, but if the parent DIV has to contain multiple DIVs and auto adjust it's height based on dynamic content, then there can be a problem. I needed to have two blocks of dynamic content; one aligned to the top of the container and one to the bottom and although I could get the container to adjust to the size of the top DIV, if the DIV aligned to the bottom was taller, it would not resize the container but would extend outside. The method outlined above by romiem using table style positioning, although a bit more complicated, is more robust in this respect and allowed alignment to the bottom and correct auto height of the container.

CSS

#container {
        display: table;
        height: auto;
}

#top {
    display: table-cell;
    width:50%;
    height: 100%;
}

#bottom {
    display: table-cell;
    width:50%;
    vertical-align: bottom;
    height: 100%;
}

HTML

<div id=“container”>
    <div id=“top”>Dynamic content aligned to top of #container</div>
    <div id=“bottom”>Dynamic content aligned to botttom of #container</div>
</div>

Example

I realise this is not a new answer but I wanted to comment on this approach as it lead me to find my solution but as a newbie I was not allowed to comment, only post.

Make the image go behind the text and keep it in center using CSS

You can position both the image and the text with position:absolute or position:relative. Then the z-index property will work. E.g.

#sometext {
    position:absolute;
    z-index:1;

}
image.center {
    position:absolute;
    z-index:0;
}

Use whatever method you like to center it.

Another option/hack is to make the image the background, either on the whole page or just within the text box.

Force sidebar height 100% using CSS (with a sticky bottom image)?

Further to @montrealmike 's answer, can I just add my adaptation?

I did this:

.container { 
  overflow: hidden; 
  .... 
} 

#sidebar { 
  margin-bottom: -101%;
  padding-bottom: 101%; 
  .... 
} 

I did the "101%" thing to cater for the (ultra rare) possibility that somebody may be viewing the site on a huge screen with a height more than 5000px!

Great answer though, montrealmike. It worked perfectly for me.

Replacing H1 text with a logo image: best method for SEO and accessibility?

One point no one has touched on is the fact that the h1 attribute should be specific to every page and using the site logo will effectively replicate the H1 on every page of the site.

I like to use a z index hidden h1 for each page as the best SEO h1 is often not the best for sales or aesthetic value.

How do I stretch a background image to cover the entire HTML element?

background: url(images/bg.jpg) no-repeat center center fixed; 
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;

How do I force a DIV block to extend to the bottom of a page even if it has no content?

Sticky footer with fixed height:

HTML scheme:

<body>
   <div id="wrap">
   </div>
   <div id="footer">
   </div>
</body>

CSS:

html, body {
    height: 100%;
}
#wrap {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -60px;
}
#footer {
    height: 60px;
}

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

How to move (and overwrite) all files from one directory to another?

For moving and overwriting files, it doesn't look like there is the -R option (when in doubt check your options by typing [your_cmd] --help. Also, this answer depends on how you want to move your file. Move all files, files & directories, replace files at destination, etc.

When you type in mv --help it returns the description of all options.

For mv, the syntax is mv [option] [file_source] [file_destination]

To move simple files: mv image.jpg folder/image.jpg

To move as folder into destination mv folder home/folder

To move all files in source to destination mv folder/* home/folder/

Use -v if you want to see what is being done: mv -v

Use -i to prompt before overwriting: mv -i

Use -u to update files in destination. It will only move source files newer than the file in the destination, and when it doesn't exist yet: mv -u

Tie options together like mv -viu, etc.

Adding IN clause List to a JPA Query

You must convert to List as shown below:

    String[] valores = hierarquia.split(".");       
    List<String> lista =  Arrays.asList(valores);

    String jpqlQuery = "SELECT a " +
            "FROM AcessoScr a " +
            "WHERE a.scr IN :param ";

    Query query = getEntityManager().createQuery(jpqlQuery, AcessoScr.class);                   
    query.setParameter("param", lista);     
    List<AcessoScr> acessos = query.getResultList();

how to set mongod --dbpath

You can set dbPath in the mongodb.conf file:

storage:
    dbPath: "/path/to/your/database/data/db"

It's a YAML-based configuration file format (since Mongodb 2.6 version), so pay attention no tabs only spaces, and space after ": "

usually this file located in the *nix systems here: /etc/mongodb.conf

So then just run

$ mongod -f /etc/mongodb.conf

And mongod process will start...

(on the Windows something like)

> C:\MongoDB\bin\mongod.exe -f C:\MongoDB\mongod.conf

Java random numbers using a seed

Problem is that you seed the random generator again. Every time you seed it the initial state of the random number generator gets reset and the first random number you generate will be the first random number after the initial state

Jenkins - how to build a specific branch

I don't think you can both within the same jenkins job, what you need to do is to configure a new jenkins job which will have access to your github to retrieve branches and then you can choose which one to manually build.

Just mark it as a parameterized build, specify a name, and a parameter configured as git parameter

enter image description here

and now you can configure git options:

enter image description here

How do I git rm a file without deleting it from disk?

git rm --cached file

should do what you want.

You can read more details at git help rm

How do I enable logging for Spring Security?

Spring security logging for webflux reactive apps is now available starting with version 5.4.0-M2 (as mentionned by @bzhu in comment How do I enable logging for Spring Security?)

Until this gets into a GA release, here is how to get this milestone release in gradle

repositories {
    mavenCentral()
    if (!version.endsWith('RELEASE')) {
        maven { url "https://repo.spring.io/milestone" }
    }
}

// Force earlier milestone release to get securing logging preview
// https://docs.spring.io/spring-security/site/docs/current/reference/html5/#getting-gradle-boot
// https://github.com/spring-projects/spring-security/pull/8504
// https://github.com/spring-projects/spring-security/releases/tag/5.4.0-M2
ext['spring-security.version']='5.4.0-M2'
dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }

}

Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?

Ran into the same issue and researched this for a few minutes.

I was taught to use Windows 3.1 and DOS, remember those days? Shortly after I worked with Macintosh computers strictly for some time, then began to sway back to Windows after buying a x64-bit machine.

There are actual reasons behind these changes (some would say historical significance), that are necessary for programmers to continue their work.

Most of the changes are mentioned above:

  • Program Files vs Program Files (x86)

    In the beginning the 16/86bit files were written on, '86' Intel processors.

  • System32 really means System64 (on 64-bit Windows)

    When developers first started working with Windows7, there were several compatibility issues where other applications where stored.

  • SysWOW64 really means SysWOW32

    Essentially, in plain english, it means 'Windows on Windows within a 64-bit machine'. Each folder is indicating where the DLLs are located for applications it they wish to use them.

Here are two links with all the basic info you need:

Hope this clears things up!

How to display count of notifications in app launcher icon

It works in samsung touchwiz launcher

public static void setBadge(Context context, int count) {
    String launcherClassName = getLauncherClassName(context);
    if (launcherClassName == null) {
        return;
    }
    Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
    intent.putExtra("badge_count", count);
    intent.putExtra("badge_count_package_name", context.getPackageName());
    intent.putExtra("badge_count_class_name", launcherClassName);
    context.sendBroadcast(intent);
}

public static String getLauncherClassName(Context context) {

    PackageManager pm = context.getPackageManager();

    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);

    List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
    for (ResolveInfo resolveInfo : resolveInfos) {
        String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
        if (pkgName.equalsIgnoreCase(context.getPackageName())) {
            String className = resolveInfo.activityInfo.name;
            return className;
        }
    }
    return null;
}

How can I override Bootstrap CSS styles?

See https://bootstrap.themes.guide/how-to-customize-bootstrap.html

  1. For simple CSS Overrides, you can add a custom.css below the bootstrap.css

    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/custom.css">
    
  2. For more extensive changes, SASS is the recommended method.

    • create your own custom.scss
    • import Bootstrap after the changes in custom.scss
    • For example, let’s change the body background-color to light-gray #eeeeee, and change the blue primary contextual color to Bootstrap's $purple variable...

      /* custom.scss */    
      
      /* import the necessary Bootstrap files */
      @import "bootstrap/functions";
      @import "bootstrap/variables";
      
      /* -------begin customization-------- */   
      
      /* simply assign the value */ 
      $body-bg: #eeeeee;
      
      /* or, use an existing variable */
      $theme-colors: (
        primary: $purple
      );
      /* -------end customization-------- */  
      
      /* finally, import Bootstrap to set the changes! */
      @import "bootstrap";
      

opening a window form from another form programmatically

private void btnchangerate_Click(object sender, EventArgs e)
    {
        this.Hide();  //current form will hide
        Form1 fm = new Form1(); //another form will open
        fm.Show();


    }

on click btn current form will hide and new form will open

Oracle - What TNS Names file am I using?

Shouldn't it always be "$ORACLE_ HOME/network/admin/tnsnames.ora"? Then you can just do "echo $oracle_ home" or the *nix equivalent.

@Pete Holberton You are entirely correct. Which reminds me, there's another monkey wrench in the works called TWO_ TASK

According http://www.orafaq.com/wiki/TNS_ADMIN
TNS_ADMIN is an environment variable that points to the directory where the SQL*Net configuration files (like sqlnet.ora and tnsnames.ora) are located.

Sqlite or MySql? How to decide?

The sqlite team published an article explaining when to use sqlite that is great read. Basically, you want to avoid using sqlite when you have a lot of write concurrency or need to scale to terabytes of data. In many other cases, sqlite is a surprisingly good alternative to a "traditional" database such as MySQL.

Create a custom callback in JavaScript

   function callback(e){
      return e;
   }
    var MyClass = {
       method: function(args, callback){
          console.log(args);
          if(typeof callback == "function")
          callback();
       }    
    }

==============================================

MyClass.method("hello",function(){
    console.log("world !");
});

==============================================

Result is:

hello world !

Remove querystring from URL

If you need to perform complex operation on URL, you can take a look to the jQuery url parser plugin.

100% height minus header?

As mentioned in the comments height:100% relies on the height of the parent container being explicitly defined. One way to achieve what you want is to use absolute/relative positioning, and specifying the left/right/top/bottom properties to "stretch" the content out to fill the available space. I have implemented what I gather you want to achieve in jsfiddle. Try resizing the Result window and you will see the content resizes automatically.

The limitation of this approach in your case is that you have to specify an explicit margin-top on the parent container to offset its contents down to make room for the header content. You can make it dynamic if you throw in javascript though.

HTML input file selection event not firing upon selecting the same file

In this article, under the title "Using form input for selecting"

http://www.html5rocks.com/en/tutorials/file/dndfiles/

<input type="file" id="files" name="files[]" multiple />

<script>
function handleFileSelect(evt) {

    var files = evt.target.files; // FileList object

    // files is a FileList of File objects. List some properties.
    var output = [];
    for (var i = 0, f; f = files[i]; i++) {
     // Code to execute for every file selected
    }
    // Code to execute after that

}

document.getElementById('files').addEventListener('change', 
                                                  handleFileSelect, 
                                                  false);
</script>

It adds an event listener to 'change', but I tested it and it triggers even if you choose the same file and not if you cancel.

Groovy - How to compare the string?

String str = "saveMe"
compareString(str)

def compareString(String str){
  def str2 = "saveMe"

  // using single quotes
  println 'single quote string class' + 'String.class'.class
  println str + ' == ' + str2 + " ? " + (str == str2)
  println ' str = ' +  '$str' //  interpolation not supported

  // using double quotes, Interpolation supported
  println "double quoted string with interpolation " + "GString.class $str".class
  println "double quoted string without interpolation " + "String.class".class
  println "$str equals $str2 ? " + str.equals(str2) 
  println '$str == $str2 ? ' + "$str==$str2"
  println '${str == str2} ? ' + "${str==str2} ? "

  println '$str equalsIgnoreCase $str2 ? ' + str.equalsIgnoreCase(str2)   

  println '''
  triple single quoted Multi-line string, Interpolation not supported $str ${str2}
  Groovy has also an operator === that can be used for objects equality
  === is equivalent to o1.is(o2)
  '''
  println '''
  triple quoted string 
  '''
  println 'triple single quoted string ' + '''' string '''.class

  println """ 
  triple double quoted Multi-line string, Interpolation is supported $str == ${str2}
  just like double quoted strings with the addition that they are multiline
  '\${str == str2} ? ' ${str == str2} 
  """
  println 'triple double quoted string ' + """ string """.class
} 

output:

single quote string classclass java.lang.String
saveMe == saveMe ? true
str = $str
double quoted string with interpolation class org.codehaus.groovy.runtime.GStringImpl
double quoted string without interpolation class java.lang.String
saveMe equals saveMe ? true
$str == $str2 ? saveMe==saveMe
${str == str2} ? true ? 
$str equalsIgnoreCase $str2 ? true 

triple single quoted Multi-line string, Interpolation not supported $str ${str2}
Groovy has also an operator === that can be used for objects equality
=== is equivalent to o1.is(o2)


triple quoted string 

triple single quoted string class java.lang.String

triple double quoted Multi-line string, Interpolation is supported saveMe == saveMe
just like double quoted strings with the addition that they are multiline
'${str == str2} ? ' true 

triple double quoted string class java.lang.String

Cannot create Maven Project in eclipse

Just delete the ${user.home}/.m2/repository/org/apache/maven/archetypes to refresh all files needed, it worked fine to me!

is of a type that is invalid for use as a key column in an index

There is a limitation in SQL Server (up till 2008 R2) that varchar(MAX) and nvarchar(MAX) (and several other types like text, ntext ) cannot be used in indices. You have 2 options:
1. Set a limited size on the key field ex. nvarchar(100)
2. Create a check constraint that compares the value with all the keys in the table. The condition is:

([dbo].[CheckKey]([key])=(1))

and [dbo].[CheckKey] is a scalar function defined as:

CREATE FUNCTION [dbo].[CheckKey]
(
    @key nvarchar(max)
)
RETURNS bit
AS
BEGIN
    declare @res bit
    if exists(select * from key_value where [key] = @key)
        set @res = 0
    else
        set @res = 1

    return @res
END

But note that a native index is more performant than a check constraint so unless you really can't specify a length, don't use the check constraint.

IntelliJ how to zoom in / out

Double click shift, type zoom and switch zoom to on

enter image description here

Spring JPA and persistence.xml

This may be old, but if anyone has the same problem try changing unitname to just name in the PersistenceContext annotation:

From

@PersistenceContext(unitName="educationPU")

to

@PersistenceContext(name="educationPU")

Java Equivalent of C# async/await?

The await uses a continuation to execute additional code when the asynchronous operation completes (client.GetStringAsync(...)).

So, as the most close approximation I would use a CompletableFuture<T> (the Java 8 equivalent to .net Task<TResult>) based solution to process the Http request asynchronously.

UPDATED on 25-05-2016 to AsyncHttpClient v.2 released on Abril 13th of 2016:

So the Java 8 equivalent to the OP example of AccessTheWebAsync() is the following:

CompletableFuture<Integer> AccessTheWebAsync()
{
    AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
    return asyncHttpClient
       .prepareGet("http://msdn.microsoft.com")
       .execute()
       .toCompletableFuture()
       .thenApply(Response::getResponseBody)
       .thenApply(String::length);
}

This usage was taken from the answer to How do I get a CompletableFuture from an Async Http Client request? and which is according to the new API provided in version 2 of AsyncHttpClient released on Abril 13th of 2016, that has already intrinsic support for CompletableFuture<T>.

Original answer using version 1 of AsyncHttpClient:

To that end we have two possible approaches:

  • the first one uses non-blocking IO and I call it AccessTheWebAsyncNio. Yet, because the AsyncCompletionHandler is an abstract class (instead of a functional interface) we cannot pass a lambda as argument. So it incurs in inevitable verbosity due to the syntax of anonymous classes. However, this solution is the most close to the execution flow of the given C# example.

  • the second one is slightly less verbose however it will submit a new Task that ultimately will block a thread on f.get() until the response is complete.

First approach, more verbose but non-blocking:

static CompletableFuture<Integer> AccessTheWebAsyncNio(){
    final AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    final CompletableFuture<Integer> promise = new CompletableFuture<>();
    asyncHttpClient
        .prepareGet("https://msdn.microsoft.com")
        .execute(new AsyncCompletionHandler<Response>(){
            @Override
            public Response onCompleted(Response resp) throws Exception {
                promise.complete(resp.getResponseBody().length());
                return resp;
            }
        });
    return promise;
}

Second approach less verbose but blocking a thread:

static CompletableFuture<Integer> AccessTheWebAsync(){
    try(AsyncHttpClient asyncHttpClient = new AsyncHttpClient()){
        Future<Response> f = asyncHttpClient
            .prepareGet("https://msdn.microsoft.com")
            .execute();
        return CompletableFuture.supplyAsync(
            () -> return f.join().getResponseBody().length());
    }
}

reCAPTCHA ERROR: Invalid domain for site key

I ran into this issue also and my solution was to verify I was integrating the appropriate client code for the version I had selected.

In my case, I had selected reCAPTCHA v3 but was taking client integration code for v2.

V3 looks like this:

<script src="https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key"></script>
<script>
  grecaptcha.ready(function() {
      grecaptcha.execute('reCAPTCHA_site_key', {action: 'homepage'}).then(function(token) {
         ...
      });
  });
</script>

V2 code looks like this:

<html>
  <head>
    <title>reCAPTCHA demo: Simple page</title>
     <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  </head>
  <body>
    <form action="?" method="POST">
      <div class="g-recaptcha" data-sitekey="your_site_key"></div>
      <br/>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

As for which version you have, this will be what you decided at the start of your reCAPTCHA account setup. enter image description here

PHP preg replace only allow numbers

I think you're saying you want to remove all non-numeric characters. If so, \D means "anything that isn't a digit":

preg_replace('/\D/', '', $c)

How to get an enum value from a string value in Java?

Another way of doing this by using implicit static method name() of Enum. name will return the exact string used to create that enum which can be used to check against provided string:

public enum Blah {

    A, B, C, D;

    public static Blah getEnum(String s){
        if(A.name().equals(s)){
            return A;
        }else if(B.name().equals(s)){
            return B;
        }else if(C.name().equals(s)){
            return C;
        }else if (D.name().equals(s)){
            return D;
        }
        throw new IllegalArgumentException("No Enum specified for this string");
    }
}

Testing:

System.out.println(Blah.getEnum("B").name());

//it will print B  B

inspiration: 10 Examples of Enum in Java

Break promise chain and call a function based on the step in the chain where it is broken (rejected)

When rejecting you should pass an rejection error, then wrap step error handlers in a function that checks whether the rejection should be processed or "rethrown" until the end of the chain :

// function mocking steps
function step(i) {
    i++;
    console.log('step', i);
    return q.resolve(i);
}

// function mocking a failing step
function failingStep(i) {
    i++;
    console.log('step '+ i + ' (will fail)');
    var e = new Error('Failed on step ' + i);
    e.step = i;
    return q.reject(e);
}

// error handler
function handleError(e){
    if (error.breakChain) {
        // handleError has already been called on this error
        // (see code bellow)
        log('errorHandler: skip handling');
        return q.reject(error);
    }
    // firs time this error is past to the handler
    console.error('errorHandler: caught error ' + error.message);
    // process the error 
    // ...
    //
    error.breakChain = true;
    return q.reject(error);
}

// run the steps, will fail on step 4
// and not run step 5 and 6
// note that handleError of step 5 will be called
// but since we use that error.breakChain boolean
// no processing will happen and the error will
// continue through the rejection path until done(,)

  step(0) // 1
  .catch(handleError)
  .then(step) // 2
  .catch(handleError)
  .then(step) // 3
  .catch(handleError)
  .then(failingStep)  // 4 fail
  .catch(handleError)
  .then(step) // 5
  .catch(handleError)
  .then(step) // 6
  .catch(handleError)
  .done(function(){
      log('success arguments', arguments);
  }, function (error) {
      log('Done, chain broke at step ' + error.step);
  });

What you'd see on the console :

step 1
step 2
step 3
step 4 (will fail)
errorHandler: caught error 'Failed on step 4'
errorHandler: skip handling
errorHandler: skip handling
Done, chain broke at step 4

Here is some working code https://jsfiddle.net/8hzg5s7m/3/

If you have specific handling for each step, your wrapper could be something like:

/*
 * simple wrapper to check if rejection
 * has already been handled
 * @param function real error handler
 */
function createHandler(realHandler) {
    return function(error) {
        if (error.breakChain) {
            return q.reject(error);
        }
        realHandler(error);
        error.breakChain = true;
        return q.reject(error);    
    }
}

then your chain

step1()
.catch(createHandler(handleError1Fn))
.then(step2)
.catch(createHandler(handleError2Fn))
.then(step3)
.catch(createHandler(handleError3Fn))
.done(function(){
    log('success');
}, function (error) {
    log('Done, chain broke at step ' + error.step);
});

PostgreSQL: insert from another table

You could use coalesce:

insert into destination select coalesce(field1,'somedata'),... from source;

Android Debug Bridge (adb) device - no permissions

The cause of that problem has to do with system permissions (thanks @ IsaacCisneros for this suggestion). Somehow HTC Wildfire (and maybe the others) need something more from the system than Samsung devices. Simple solution is to run Eclipse as a root, but this is not very comfortable with non-sudo Linux systems like Fedora.

I've found another way of achieving the same goal, which seems to be more user friendly and is lesser security hole then running entire IDE with super user privileges. Mind this is still only a workaround of the problem. System root usage should be minimalized only to administrative tasks, and “adb” was designed to work with normal user account without SUID. Despite of the fact that the proper setting of SUID is quite secure, every single permission increase is a potential system security hole.

1.Setting ownership of the adb binary (owner – root, owner group - user_group):

chown root:user_group adb

2.Setting permissions with SUID:

chmod 4550 adb

This should result something similar to this (ls -llh):

-r-sr-x---. 1 root user_name 1.2M Jan 8 11:42 adb

After that you will be able to run adb as a root, event though you'll be using your normal user account. You can run Eclipse as a normal user and your HTC should be discovered properly.

./adb devices 
List of devices attached 
HT0BPPY15230    device 

What does enumerate() mean?

As other users have mentioned, enumerate is a generator that adds an incremental index next to each item of an iterable.

So if you have a list say l = ["test_1", "test_2", "test_3"], the list(enumerate(l)) will give you something like this: [(0, 'test_1'), (1, 'test_2'), (2, 'test_3')].

Now, when this is useful? A possible use case is when you want to iterate over items, and you want to skip a specific item that you only know its index in the list but not its value (because its value is not known at the time).

for index, value in enumerate(joint_values):
   if index == 3:
       continue

   # Do something with the other `value`

So your code reads better because you could also do a regular for loop with range but then to access the items you need to index them (i.e., joint_values[i]).

Although another user mentioned an implementation of enumerate using zip, I think a more pure (but slightly more complex) way without using itertools is the following:

def enumerate(l, start=0):
    return zip(range(start, len(l) + start), l)

Example:

l = ["test_1", "test_2", "test_3"]
enumerate(l)
enumerate(l, 10)

Output:

[(0, 'test_1'), (1, 'test_2'), (2, 'test_3')]

[(10, 'test_1'), (11, 'test_2'), (12, 'test_3')]

As mentioned in the comments, this approach with range will not work with arbitrary iterables as the original enumerate function does.

Global Git ignore

From here.

If you create a file in your repo named .gitignore git will use its rules when looking at files to commit. Note that git will not ignore a file that was already tracked before a rule was added to this file to ignore it. In such a case the file must be un-tracked, usually with :

git rm --cached filename

Is it your case ?

This app won't run unless you update Google Play Services (via Bazaar)

I've been trying to run an Android Google Maps v2 under an emulator, and I found many ways to do that, but none of them worked for me. I have always this warning in the Logcat Google Play services out of date. Requires 3025100 but found 2010110 and when I want to update Google Play services on the emulator nothing happened. The problem was that the com.google.android.gms APK was not compatible with the version of the library in my Android SDK.

I installed these files "com.google.android.gms.apk", "com.android.vending.apk" on my emulator and my app Google Maps v2 worked fine. None of the other steps regarding /system/app were required.

angularjs - ng-repeat: access key and value from JSON array object

try this..

<tr ng-repeat='item in items'>
<td>{{item.Name}}</td>
<td>{{item.Price}}</td>
<td>{{item.Quantity}}</td>
</tr>

Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?

Should I use(or both) for signing apk for play store release? An answer is YES.

As per https://source.android.com/security/apksigning/v2.html#verification :

In Android 7.0, APKs can be verified according to the APK Signature Scheme v2 (v2 scheme) or JAR signing (v1 scheme). Older platforms ignore v2 signatures and only verify v1 signatures.

I tried to generate build with checking V2(Full Apk Signature) option. Then when I tried to install a release build in below 7.0 device and I am unable to install build in the device.

After that I tried to build by checking both version checkbox and generate release build. Then able to install build.

Replace and overwrite instead of appending

import os#must import this library
if os.path.exists('TwitterDB.csv'):
        os.remove('TwitterDB.csv') #this deletes the file
else:
        print("The file does not exist")#add this to prevent errors

I had a similar problem, and instead of overwriting my existing file using the different 'modes', I just deleted the file before using it again, so that it would be as if I was appending to a new file on each run of my code.

"CAUTION: provisional headers are shown" in Chrome debugger

This caution message also occurs if the response is invalid and therefore dropped by the browser.

In my case the request was correctly sent to the server, the server-side code then produced an error and my custom error handling returned the error message in the HTTP status message field. But this error was not received on the client side, due to invalid characters in the error message (described here http://aspnetwebstack.codeplex.com/workitem/1386) which resulted in corrupt response headers.

Copy data into another table

If both tables are truly the same schema:

INSERT INTO newTable
SELECT * FROM oldTable

Otherwise, you'll have to specify the column names (the column list for newTable is optional if you are specifying a value for all columns and selecting columns in the same order as newTable's schema):

INSERT INTO newTable (col1, col2, col3)
SELECT column1, column2, column3
FROM oldTable

jQuery AJAX Call to PHP Script with JSON Return

Make it dataType instead of datatype.

And add below code in php as your ajax request is expecting json and will not accept anything, but json.

header('Content-Type: application/json');

Correct Content type for JSON and JSONP

The response visible in firebug is text data. Check Content-Type of the response header to verify, if the response is json. It should be application/json for dataType:'json' and text/html for dataType:'html'.

How to check ASP.NET Version loaded on a system?

Alternatively, you can create a button on your webpage and in the Page_Load type;

Trace.IsEnabled = True

And in the button click event type;

Response.Write(Trace)

This will bring up all the trace information and you will find your ASP.NET version in the "Response Headers Collection" under "X-ASPNet-Version".

Generate an HTML Response in a Java Servlet

Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:

public void doGet(HttpServletRequest request,
       HttpServletResponse response)
       throws IOException, ServletException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   out.println("HTML from an external file:");     
   request.getRequestDispatcher("/pathToFile/fragment.html")
          .include(request, response); 
   out.close();
}

What are access specifiers? Should I inherit with private, protected or public?

The explanation from Scott Meyers in Effective C++ might help understand when to use them:

Public inheritance should model "is-a relationship," whereas private inheritance should be used for "is-implemented-in-terms-of" - so you don't have to adhere to the interface of the superclass, you're just reusing the implementation.

How to Find the Default Charset/Encoding in Java?

This is really strange... Once set, the default Charset is cached and it isn't changed while the class is in memory. Setting the "file.encoding" property with System.setProperty("file.encoding", "Latin-1"); does nothing. Every time Charset.defaultCharset() is called it returns the cached charset.

Here are my results:

Default Charset=ISO-8859-1
file.encoding=Latin-1
Default Charset=ISO-8859-1
Default Charset in Use=ISO8859_1

I'm using JVM 1.6 though.

(update)

Ok. I did reproduce your bug with JVM 1.5.

Looking at the source code of 1.5, the cached default charset isn't being set. I don't know if this is a bug or not but 1.6 changes this implementation and uses the cached charset:

JVM 1.5:

public static Charset defaultCharset() {
    synchronized (Charset.class) {
        if (defaultCharset == null) {
            java.security.PrivilegedAction pa =
                    new GetPropertyAction("file.encoding");
            String csn = (String) AccessController.doPrivileged(pa);
            Charset cs = lookup(csn);
            if (cs != null)
                return cs;
            return forName("UTF-8");
        }
        return defaultCharset;
    }
}

JVM 1.6:

public static Charset defaultCharset() {
    if (defaultCharset == null) {
        synchronized (Charset.class) {
            java.security.PrivilegedAction pa =
                    new GetPropertyAction("file.encoding");
            String csn = (String) AccessController.doPrivileged(pa);
            Charset cs = lookup(csn);
            if (cs != null)
                defaultCharset = cs;
            else
                defaultCharset = forName("UTF-8");
        }
    }
    return defaultCharset;
}

When you set the file encoding to file.encoding=Latin-1 the next time you call Charset.defaultCharset(), what happens is, because the cached default charset isn't set, it will try to find the appropriate charset for the name Latin-1. This name isn't found, because it's incorrect, and returns the default UTF-8.

As for why the IO classes such as OutputStreamWriter return an unexpected result,
the implementation of sun.nio.cs.StreamEncoder (witch is used by these IO classes) is different as well for JVM 1.5 and JVM 1.6. The JVM 1.6 implementation is based in the Charset.defaultCharset() method to get the default encoding, if one is not provided to IO classes. The JVM 1.5 implementation uses a different method Converters.getDefaultEncodingName(); to get the default charset. This method uses its own cache of the default charset that is set upon JVM initialization:

JVM 1.6:

public static StreamEncoder forOutputStreamWriter(OutputStream out,
        Object lock,
        String charsetName)
        throws UnsupportedEncodingException
{
    String csn = charsetName;
    if (csn == null)
        csn = Charset.defaultCharset().name();
    try {
        if (Charset.isSupported(csn))
            return new StreamEncoder(out, lock, Charset.forName(csn));
    } catch (IllegalCharsetNameException x) { }
    throw new UnsupportedEncodingException (csn);
}

JVM 1.5:

public static StreamEncoder forOutputStreamWriter(OutputStream out,
        Object lock,
        String charsetName)
        throws UnsupportedEncodingException
{
    String csn = charsetName;
    if (csn == null)
        csn = Converters.getDefaultEncodingName();
    if (!Converters.isCached(Converters.CHAR_TO_BYTE, csn)) {
        try {
            if (Charset.isSupported(csn))
                return new CharsetSE(out, lock, Charset.forName(csn));
        } catch (IllegalCharsetNameException x) { }
    }
    return new ConverterSE(out, lock, csn);
}

But I agree with the comments. You shouldn't rely on this property. It's an implementation detail.

MVC4 Passing model from view to controller

I hope this complete example will help you.

This is the TaxiInfo class which holds information about a taxi ride:

namespace Taxi.Models
{
    public class TaxiInfo
    {
        public String Driver { get; set; }
        public Double Fare { get; set; }
        public Double Distance { get; set; }
        public String StartLocation { get; set; }
        public String EndLocation { get; set; }
    }
}

We also have a convenience model which holds a List of TaxiInfo(s):

namespace Taxi.Models
{
    public class TaxiInfoSet
    {
        public List<TaxiInfo> TaxiInfoList { get; set; }

        public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
        {
            TaxiInfoList = new List<TaxiInfo>();

            foreach(var TaxiInfo in TaxiInfos)
            {
                TaxiInfoList.Add(TaxiInfo);
            }
        }
    }
}

Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:

public ActionResult Index()
{
    var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
    var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };

    return View(new TaxiInfoSet(taxi1,taxi2));
}

The code for the view is as follows:

@model Taxi.Models.TaxiInfoSet
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@foreach(var TaxiInfo in Model.TaxiInfoList){
    <form>
        <h1>Cost: [email protected]</h1>
        <h2>Distance: @(TaxiInfo.Distance) km</h2>
        <p>
            Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
        </p>
        @Html.ActionLink("Home","Booking",TaxiInfo)
    </form>
}

The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:

    public ActionResult Booking(TaxiInfo Taxi)
    {
        return View(Taxi);
    }

This returns a the following view:

@model Taxi.Models.TaxiInfo

@{
    ViewBag.Title = "Booking";
}

<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>

A visual tour:

The Index view

The Booking view

Handling a Menu Item Click Event - Android

This is how it looks like in Kotlin

main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never" />
<item
    android:id="@+id/action_logout"
    android:orderInCategory="101"
    android:title="@string/sign_out"
    app:showAsAction="never" />

Then in MainActivity

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    // Inflate the menu; this adds items to the action bar if it is present.
    menuInflater.inflate(R.menu.main, menu)
    return true
}

This is onOptionsItemSelected function

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return when(item.itemId){
        R.id.action_settings -> {
            true
        }
        R.id.action_logout -> {
            signOut()
            true
        }
        else -> return super.onOptionsItemSelected(item)
    }
}

For starting new activity

private fun signOut(){
    MySharedPreferences.clearToken()
    startSplashScreenActivity()
}

private fun startSplashScreenActivity(){
    val intent = Intent(GrepToDo.applicationContext(), SplashScreenActivity::class.java)
    startActivity(intent)
    finish()
}

How can I use console logging in Internet Explorer?

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

Java List.contains(Object with field value equal to x)

Streams

If you are using Java 8, perhaps you could try something like this:

public boolean containsName(final List<MyObject> list, final String name){
    return list.stream().filter(o -> o.getName().equals(name)).findFirst().isPresent();
}

Or alternatively, you could try something like this:

public boolean containsName(final List<MyObject> list, final String name){
    return list.stream().map(MyObject::getName).filter(name::equals).findFirst().isPresent();
}

This method will return true if the List<MyObject> contains a MyObject with the name name. If you want to perform an operation on each of the MyObjects that getName().equals(name), then you could try something like this:

public void perform(final List<MyObject> list, final String name){
    list.stream().filter(o -> o.getName().equals(name)).forEach(
            o -> {
                //...
            }
    );
}

Where o represents a MyObject instance.

Alternatively, as the comments suggest (Thanks MK10), you could use the Stream#anyMatch method:

public boolean containsName(final List<MyObject> list, final String name){
    return list.stream().anyMatch(o -> o.getName().equals(name));
}

How to use putExtra() and getExtra() for string data

put string first

Intent secondIntent = new Intent(this, typeof(SecondActivity));
            secondIntent.PutExtra("message", "Greetings from MainActivity");

retrieve it after that

var message = this.Intent.GetStringExtra("message");

thats All ;)

Creating new database from a backup of another Database on the same server?

I think that is easier than this.

  • First, create a blank target database.
  • Then, in "SQL Server Management Studio" restore wizard, look for the option to overwrite target database. It is in the 'Options' tab and is called 'Overwrite the existing database (WITH REPLACE)'. Check it.
  • Remember to select target files in 'Files' page.

You can change 'tabs' at left side of the wizard (General, Files, Options)

Closing pyplot windows

Please use

plt.show(block=False)
plt.close('all')

How to protect Excel workbook using VBA?

  1. in your sample code you must remove the brackets, because it's not a functional assignment; also for documentary reasons I would suggest you use the := notation (see code sample below)

    1. Application.Thisworkbook refers to the book containing the VBA code, not necessarily the book containing the data, so be cautious.

Express the sheet you're working on as a sheet object and pass it, together with a logical variable to the following sub:

Sub SetProtectionMode(MySheet As Worksheet, ProtectionMode As Boolean)

    If ProtectionMode Then
        MySheet.Protect DrawingObjects:=True, Contents:=True, _
                        AllowSorting:=True, AllowFiltering:=True
    Else
        MySheet.Unprotect
    End If
End Sub

Within the .Protect method you can define what you want to allow/disallow. This code block will switch protection on/off - without password in this example, you can add it as a parameter or hardcoded within the Sub. Anyway somewhere the PW will be hardcoded. If you don't want this, just call the Protection Dialog window and let the user decide what to do:

Application.Dialogs(xlDialogProtectDocument).Show

Hope that helps

Good luck - MikeD

SQL - select distinct only on one column

You will use the following query:

SELECT * FROM [table] GROUP BY NUMBER;

Where [table] is the name of the table.

This provides a unique listing for the NUMBER column however the other columns may be meaningless depending on the vendor implementation; which is to say they may not together correspond to a specific row or rows.

Convert this string to datetime

Use DateTime::createFromFormat

$date = date_create_from_format('d/m/Y:H:i:s', $s);
$date->getTimestamp();

UL or DIV vertical scrollbar

Sometimes it is not eligible to set height to pixel values. However, it is possible to show vertical scrollbar through setting height of div to 100% and overflow to auto.

Let me show an example:

<div id="content" style="height: 100%; overflow: auto">
  <p>some text</p>
  <ul>
    <li>text</li>
    .....
    <li>text</li>
</div>

Convert DOS line endings to Linux line endings in Vim

Change the line endings in the view:

:e ++ff=dos
:e ++ff=mac
:e ++ff=unix

This can also be used as saving operation (:w alone will not save using the line endings you see on screen):

:w ++ff=dos
:w ++ff=mac
:w ++ff=unix

And you can use it from the command-line:

for file in *.cpp
do 
    vi +':w ++ff=unix' +':q' "$file"
done

Calculate cosine similarity given 2 sentence strings

A simple pure-Python implementation would be:

import math
import re
from collections import Counter

WORD = re.compile(r"\w+")


def get_cosine(vec1, vec2):
    intersection = set(vec1.keys()) & set(vec2.keys())
    numerator = sum([vec1[x] * vec2[x] for x in intersection])

    sum1 = sum([vec1[x] ** 2 for x in list(vec1.keys())])
    sum2 = sum([vec2[x] ** 2 for x in list(vec2.keys())])
    denominator = math.sqrt(sum1) * math.sqrt(sum2)

    if not denominator:
        return 0.0
    else:
        return float(numerator) / denominator


def text_to_vector(text):
    words = WORD.findall(text)
    return Counter(words)


text1 = "This is a foo bar sentence ."
text2 = "This sentence is similar to a foo bar sentence ."

vector1 = text_to_vector(text1)
vector2 = text_to_vector(text2)

cosine = get_cosine(vector1, vector2)

print("Cosine:", cosine)

Prints:

Cosine: 0.861640436855

The cosine formula used here is described here.

This does not include weighting of the words by tf-idf, but in order to use tf-idf, you need to have a reasonably large corpus from which to estimate tfidf weights.

You can also develop it further, by using a more sophisticated way to extract words from a piece of text, stem or lemmatise it, etc.

How to programmatically round corners and set random background colors

I think the fastest way to do this is:

GradientDrawable gradientDrawable = new GradientDrawable(
            GradientDrawable.Orientation.TOP_BOTTOM, //set a gradient direction 
            new int[] {0xFF757775,0xFF151515}); //set the color of gradient
gradientDrawable.setCornerRadius(10f); //set corner radius

//Apply background to your view
View view = (RelativeLayout) findViewById( R.id.my_view );
if(Build.VERSION.SDK_INT>=16)
     view.setBackground(gradientDrawable);
else view.setBackgroundDrawable(gradientDrawable);    

relative path in require_once doesn't work

In my case it doesn't work, even with __DIR__ or getcwd() it keeps picking the wrong path, I solved by defining a costant in every file I need with the absolute base path of the project:

if(!defined('THISBASEPATH')){ define('THISBASEPATH', '/mypath/'); }
require_once THISBASEPATH.'cache/crud.php';
/*every other require_once you need*/

I have MAMP with php 5.4.10 and my folder hierarchy is basilar:

q.php 
w.php 
e.php 
r.php 
cache/a.php 
cache/b.php 
setting/a.php 
setting/b.php

....

OWIN Security - How to Implement OAuth2 Refresh Tokens

Freddy's answer helped me a lot to get this working. For the sake of completeness here's how you could implement hashing of the token:

private string ComputeHash(Guid input)
{
    byte[] source = input.ToByteArray();

    var encoder = new SHA256Managed();
    byte[] encoded = encoder.ComputeHash(source);

    return Convert.ToBase64String(encoded);
}

In CreateAsync:

var guid = Guid.NewGuid();
...
_refreshTokens.TryAdd(ComputeHash(guid), refreshTokenTicket);
context.SetToken(guid.ToString());

ReceiveAsync:

public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
    Guid token;

    if (Guid.TryParse(context.Token, out token))
    {
        AuthenticationTicket ticket;

        if (_refreshTokens.TryRemove(ComputeHash(token), out ticket))
        {
            context.SetTicket(ticket);
        }
    }
}

CSS:Defining Styles for input elements inside a div

Like this.

.divContainer input[type="text"] {
  width:150px;
}
.divContainer input[type="radio"] {
  width:20px;
}

Align an element to bottom with flexbox

Try This

_x000D_
_x000D_
.content {_x000D_
      display: flex;_x000D_
      flex-direction: column;_x000D_
      height: 250px;_x000D_
      width: 200px;_x000D_
      border: solid;_x000D_
      word-wrap: break-word;_x000D_
    }_x000D_
_x000D_
   .content h1 , .content h2 {_x000D_
     margin-bottom: 0px;_x000D_
    }_x000D_
_x000D_
   .content p {_x000D_
     flex: 1;_x000D_
    }
_x000D_
   <div class="content">_x000D_
  <h1>heading 1</h1>_x000D_
  <h2>heading 2</h2>_x000D_
  <p>Some more or less text</p>_x000D_
  <a href="/" class="button">Click me</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Multiple submit buttons in the same form calling different Servlets

If you use jQuery, u can do it like this:

<form action="example" method="post" id="loginform">
  ...
  <input id="btnin" type="button" value="login"/>
  <input id="btnreg" type="button" value="regist"/>
</form>

And js will be:

$("#btnin").click(function(){
   $("#loginform").attr("action", "user_login");
   $("#loginform").submit();
}
$("#btnreg").click(function(){
   $("#loginform").attr("action", "user_regist");
   $("#loginform").submit();
}

XML Error: There are multiple root elements

You need to enclose your <parent> elements in a surrounding element as XML Documents can have only one root node:

<parents> <!-- I've added this tag -->
    <parent>
        <child>
            Text
        </child>
    </parent>
    <parent>
        <child>
            <grandchild>
                Text
            </grandchild>
            <grandchild>
                Text
            </grandchild>
        </child>
        <child>
            Text
        </child>
    </parent>
</parents> <!-- I've added this tag -->

As you're receiving this markup from somewhere else, rather than generating it yourself, you may have to do this yourself by treating the response as a string and wrapping it with appropriate tags, prior to attempting to parse it as XML.

So, you've a couple of choices:

  1. Get the provider of the web service to return you actual XML that has one root node
  2. Pre-process the XML, as I've suggested above, to add a root node
  3. Pre-process the XML to split it into multiple chunks (i.e. one for each <parent> node) and process each as a distinct XML Document

Using SSIS BIDS with Visual Studio 2012 / 2013

Today March 6, 2013, Microsoft released SQL Server Data Tools – Business Intelligence for Visual Studio 2012 (SSDT BI) templates. With SSDT BI for Visual Studio 2012 you can develop and deploy SQL Server Business intelligence projects. Projects created in Visual Studio 2010 can be opened in Visual Studio 2012 and the other way around without upgrading or downgrading – it just works.

The download/install is named to ensure you get the SSDT templates that contain the Business Intelligence projects. The setup for these tools is now available from the web and can be downloaded in multiple languages right here: http://www.microsoft.com/download/details.aspx?id=36843

Subprocess check_output returned non-zero exit status 1

The word check_ in the name means that if the command (the shell in this case that returns the exit status of the last command (yum in this case)) returns non-zero status then it raises CalledProcessError exception. It is by design. If the command that you want to run may return non-zero status on success then either catch this exception or don't use check_ methods. You could use subprocess.call in your case because you are ignoring the captured output, e.g.:

import subprocess

rc = subprocess.call(['grep', 'pattern', 'file'],
                     stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
if rc == 0: # found
   ...
elif rc == 1: # not found
   ...
elif rc > 1: # error
   ...

You don't need shell=True to run the commands from your question.

How do you connect localhost in the Android emulator?

Thanks to author of this blog: https://bigdata-etl.com/solved-how-to-connect-from-android-emulator-to-application-on-localhost/

Defining network security config in xml

<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
       <domain includeSubdomains="true">10.0.2.2</domain>
    </domain-config>
</network-security-config>

And setting it on AndroidManifest.xml

 <application
    android:networkSecurityConfig="@xml/network_security_config"
</application>

Solved issue for me!

Please refer: https://developer.android.com/training/articles/security-config

canvas.toDataURL() SecurityError

Try the code below ...

<img crossOrigin="anonymous"
     id="imgpicture" 
     fall-back="images/penang realty,Apartment,house,condominium,terrace house,semi d,detached,
                bungalow,high end luxury properties,landed properties,gated guarded house.png" 
     ng-src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" 
     height="220"
     width="200"
     class="watermark">

PDO closing connection

<?php if(!class_exists('PDO2')) {
    class PDO2 {
        private static $_instance;
        public static function getInstance() {
            if (!isset(self::$_instance)) {
                try {
                    self::$_instance = new PDO(
                        'mysql:host=***;dbname=***',
                        '***',
                        '***',
                        array(
                            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_general_ci",
                            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION
                        )
                    );
                } catch (PDOException $e) {
                    throw new PDOException($e->getMessage(), (int) $e->getCode());
                }
            }
            return self::$_instance;
        }
        public static function closeInstance() {
            return self::$_instance = null;
        }
    }
}
$req = PDO2::getInstance()->prepare('SELECT * FROM table');
$req->execute();
$count = $req->rowCount();
$results = $req->fetchAll(PDO::FETCH_ASSOC);
$req->closeCursor();
// Do other requests maybe
// And close connection
PDO2::closeInstance();
// print output

Full example, with custom class PDO2.

how to parse xml to java object?

One thing that is really important to understand considering you have an XML file as :

<customer id="100">
    <Age>29</Age>
    <NAME>mkyong</NAME>
</customer>

I am sorry to inform you but :

@XmlElement
public void setAge(int age) {
    this.age = age;
}

will not help you, as it tries to look for "age" instead of "Age" element name from the XML.

I encourage you to manually specify the element name matching the one in the XML file :

@XmlElement(name="Age")
public void setAge(int age) {
    this.age = age;
}

And if you have for example :

@XmlRootElement
@XmlAccessorType (XmlAccessType.FIELD)
public class Customer {
...

It means it will use java beans by default, and at this time if you specify that you must not set another

@XmlElement(name="NAME")

annotation above a setter method for an element <NAME>..</NAME> it will fail saying that there cannot be two elements on one single variables.

I hope that it helps.

Create html documentation for C# code

Doxygen or Sandcastle help file builder are the primary tools that will extract XML documentation into HTML (and other forms) of external documentation.

Note that you can combine these documentation exporters with documentation generators - as you've discovered, Resharper has some rudimentary helpers, but there are also much more advanced tools to do this specific task, such as GhostDoc (for C#/VB code with XML documentation) or my addin Atomineer Pro Documentation (for C#, C++/CLI, C++, C, VB, Java, JavaScript, TypeScript, JScript, PHP, Unrealscript code containing XML, Doxygen, JavaDoc or Qt documentation).

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

You can try this way

javac --release 8 yourClass.java

Various ways to remove local Git changes

Use:

git checkout -- <file>

To discard the changes in the working directory.

How do I add space between items in an ASP.NET RadioButtonList

Even though, the best approach for this situation is set custom CSS styles - an alternative could be:

  • Use Width property and set the percentaje as you see more suitable for your purposes.

In my desired scenario, I need set (2) radiobuttons/items as follows:

o Item 1 o Item 2

Example:

<asp:RadioButtonList ID="rbtnLstOptionsGenerateCertif" runat="server" 
    BackColor="Transparent" BorderColor="Transparent" RepeatDirection="Horizontal" 
    EnableTheming="False" Width="40%">
    <asp:ListItem Text="Item 1" Value="0" />
    <asp:ListItem Text="Item 2" Value="1" />
</asp:RadioButtonList>

Rendered result:

_x000D_
_x000D_
<table id="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif" class="chxbx2" border="0" style="background-color:Transparent;border-color:Transparent;width:40%;">
  <tbody>
    <tr>
      <td>
        <input id="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_0" type="radio" name="ctl00$ContentPlaceHolder$rbtnLstOptionsGenerateCertif" value="0" checked="checked">
        <label for="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_0">Item 1</label>
      </td>
      <td>
        <input id="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_1" type="radio" name="ctl00$ContentPlaceHolder$rbtnLstOptionsGenerateCertif" value="1">
        <label for="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_1">Item 2</label>
      </td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

How to get coordinates of an svg element?

I was trying to select an area of svg with a rectangle and get all the elements from it. For this, element.getBoundingClientRect() worked perfectly for me. It returns current coordinates of svg elements regardless of whether svg is scaled or transformed.

How to fit Windows Form to any screen resolution?

Probably a maximized Form helps, or you can do this manually upon form load:

Code Block

this.Location = new Point(0, 0);

this.Size = Screen.PrimaryScreen.WorkingArea.Size;

And then, play with anchoring, so the child controls inside your form automatically fit in your form's new size.

Hope this helps,

How to Create a real one-to-one relationship in SQL Server

A 1 to 1 relationship is very much possible. Even if the relationship diagram doesn't show the 1 to 1 relationship explicitly. If you implement it as below, it will function as a one to one relationship.

I will use a basic example to explain the concept where a single person can only have a single passport. This example works perfectly in MS Access. For the SQL Server version follow this link.

Remember that in MS Access, SQL scripts can only be run one at a time and not as displayed here in sequence.

CREATE TABLE Person
(
Pk_Person_Id INT PRIMARY KEY,
Name VARCHAR(255),
EmailId VARCHAR(255),
);

CREATE TABLE PassportDetails
(
Pk_Passport_Id INT PRIMARY KEY,
Passport_Number VARCHAR(255),
Fk_Person_Id INT NOT NULL UNIQUE, 
FOREIGN KEY(Fk_Person_Id) REFERENCES Person(Pk_Person_Id)
);

How do I change the value of a global variable inside of a function

Just use the name of that variable.

In JavaScript, variables are only local to a function, if they are the function's parameter(s) or if you declare them as local explicitely by typing the var keyword before the name of the variable.

If the name of the local value has the same name as the global value, use the window object

See this jsfiddle

_x000D_
_x000D_
x = 1;_x000D_
y = 2;_x000D_
z = 3;_x000D_
_x000D_
function a(y) {_x000D_
  // y is local to the function, because it is a function parameter_x000D_
  console.log('local y: should be 10:', y); // local y through function parameter_x000D_
  y = 3; // will only overwrite local y, not 'global' y_x000D_
  console.log('local y: should be 3:', y); // local y_x000D_
  // global value could be accessed by referencing through window object_x000D_
  console.log('global y: should be 2:', window.y) // global y, different from local y ()_x000D_
_x000D_
  var x; // makes x a local variable_x000D_
  x = 4; // only overwrites local x_x000D_
  console.log('local x: should be 4:', x); // local x_x000D_
  _x000D_
  z = 5; // overwrites global z, because there is no local z_x000D_
  console.log('local z: should be 5:', z); // local z, same as global_x000D_
  console.log('global z: should be 5 5:', window.z, z) // global z, same as z, because z is not local_x000D_
}_x000D_
a(10);_x000D_
console.log('global x: should be 1:', x); // global x_x000D_
console.log('global y: should be 2:', y); // global y_x000D_
console.log('global z: should be 5:', z); // global z, overwritten in function a
_x000D_
_x000D_
_x000D_

Edit

With ES2015 there came two more keywords const and let, which also affect the scope of a variable (Language Specification)

SQL Server 2005 Using CHARINDEX() To split a string

Create FUNCTION [dbo].[fnSplitString] 
( 
    @string NVARCHAR(200), 
    @delimiter CHAR(1) 
) 
RETURNS @output TABLE(splitdata NVARCHAR(10) 
) 
BEGIN 
    DECLARE @start INT, @end INT 
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) 
    WHILE @start < LEN(@string) + 1 BEGIN 
        IF @end = 0  
            SET @end = LEN(@string) + 1

        INSERT INTO @output (splitdata)  
        VALUES(SUBSTRING(@string, @start, @end - @start)) 
        SET @start = @end + 1 
        SET @end = CHARINDEX(@delimiter, @string, @start)

    END 
    RETURN 

END**strong text**

iOS 7: UITableView shows under status bar

Adding to the top answer:

after the 2nd method did not initially seem to work I did some additional tinkering and have found the solution.

TLDR; the top answer's 2nd solution almost works, but for some versions of xCode ctrl+dragging to "Top Layout Guide" and selecting Vertical Spacing does nothing. However, by first adjusting the size of the Table View and then selecting "Top Space to Top Layout Guide" works


  1. Drag a blank ViewController onto the storyboard. View Controller

  2. Drag a UITableView object into the View. (Not UITableViewController). Position it in the very center using the blue layout guides.

Table View Center Image

  1. Drag a UITableViewCell into the TableView. This will be your prototype reuse cell, so don't forget to set it's Reuse Identifier under the Attributes tab or you'll get a crash.

Add Table View Cell Reuse Identifier

  1. Create your custom subclass of UIViewController, and add the <UITableViewDataSource, UITableViewDelegate> protocols. Don't forget to set your storyboard's ViewController to this class in the Identity Inspector.

  2. Create an outlet for your TableView in your implementation file, and name it "tableView"

Create Outlet tableView

  1. Right click the TableView and drag both the dataSource and the delegate to your ViewController.

dataSource delegate

Now for the part of not clipping into the status bar.

  1. Grab the top edge of your Table View and move it down to one of the dashed blue auto-layout guides that are near the top

resize

  1. Now, you can control drag from the Table View to the top and select Top Space to Top Layout Guide

Top Space to Top Layout Guide

  1. It will give you an error about ambiguous layout of TableView, just Add Missing Constraints and your done.

Add Missing Constraints

Now you can set up your table view like normal, and it won't clip the status bar!

Make a div fill up the remaining width

The Div that has to take the remaining space has to be a class.. The other divs can be id(s) but they must have width..

CSS:

#main_center {
    width:1000px;
    height:100px;
    padding:0px 0px;
    margin:0px auto;
    display:block;
}
#left {
    width:200px;
    height:100px;
    padding:0px 0px;
    margin:0px auto;
    background:#c6f5c6;
    float:left;
}
.right {
    height:100px;
    padding:0px 0px;
    margin:0px auto;
    overflow:hidden;
    background:#000fff;
}
.clear {
    clear:both;
}

HTML:

<body>
    <div id="main_center">
        <div id="left"></div>
        <div class="right"></div>
        <div class="clear"></div>
    </div>
</body>

The following link has the code in action, which should solve the remaining area coverage issue.

jsFiddle

Why is Node.js single threaded?

Node.js was created explicitly as an experiment in async processing. The theory was that doing async processing on a single thread could provide more performance and scalability under typical web loads than the typical thread-based implementation.

And you know what? In my opinion that theory's been borne out. A node.js app that isn't doing CPU intensive stuff can run thousands more concurrent connections than Apache or IIS or other thread-based servers.

The single threaded, async nature does make things complicated. But do you honestly think it's more complicated than threading? One race condition can ruin your entire month! Or empty out your thread pool due to some setting somewhere and watch your response time slow to a crawl! Not to mention deadlocks, priority inversions, and all the other gyrations that go with multithreading.

In the end, I don't think it's universally better or worse; it's different, and sometimes it's better and sometimes it's not. Use the right tool for the job.

Android: How to bind spinner to custom object list?

If you don't need a separated class, i mean just a simple adapter mapped on your object. Here is my code based on ArrayAdapter functions provided.

And because you might need to add item after adapter creation (eg database item asynchronous loading).

Simple but efficient.

editCategorySpinner = view.findViewById(R.id.discovery_edit_category_spinner);

// Drop down layout style - list view with radio button         
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

// attaching data adapter to spinner, as you can see i have no data at this moment
editCategorySpinner.setAdapter(dataAdapter);
final ArrayAdapter<Category> dataAdapter = new ArrayAdapter<Category>

(getActivity(), android.R.layout.simple_spinner_item, new ArrayList<Category>(0)) {


        // And the "magic" goes here
        // This is for the "passive" state of the spinner
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // I created a dynamic TextView here, but you can reference your own  custom layout for each spinner item
            TextView label = (TextView) super.getView(position, convertView, parent);
            label.setTextColor(Color.BLACK);
            // Then you can get the current item using the values array (Users array) and the current position
            // You can NOW reference each method you has created in your bean object (User class)
            Category item = getItem(position);
            label.setText(item.getName());

            // And finally return your dynamic (or custom) view for each spinner item
            return label;
        }

        // And here is when the "chooser" is popped up
        // Normally is the same view, but you can customize it if you want
        @Override
        public View getDropDownView(int position, View convertView,
                                    ViewGroup parent) {
            TextView label = (TextView) super.getDropDownView(position, convertView, parent);
            label.setTextColor(Color.BLACK);
            Category item = getItem(position);
            label.setText(item.getName());

            return label;
        }
    };

And then you can use this code (i couldn't put Category[] in adapter constructor because data are loaded separatly).

Note that adapter.addAll(items) refresh spinner by calling notifyDataSetChanged() in internal.

categoryRepository.getAll().observe(this, new Observer<List<Category>>() {

            @Override
            public void onChanged(@Nullable final List<Category> items) {
                dataAdapter.addAll(items);
            }
});

What is the meaning of the word logits in TensorFlow?

Here is a concise answer for future readers. Tensorflow's logit is defined as the output of a neuron without applying activation function:

logit = w*x + b,

x: input, w: weight, b: bias. That's it.


The following is irrelevant to this question.

For historical lectures, read other answers. Hats off to Tensorflow's "creatively" confusing naming convention. In PyTorch, there is only one CrossEntropyLoss and it accepts un-activated outputs. Convolutions, matrix multiplications and activations are same level operations. The design is much more modular and less confusing. This is one of the reasons why I switched from Tensorflow to PyTorch.

How do I left align these Bootstrap form items?

If you are saying that your problem is how to left align the form labels, see if this helps:
http://jsfiddle.net/panchroma/8gYPQ/

Try changing the text-align left / right in the CSS

.form-horizontal .control-label{
    /* text-align:right; */
    text-align:left;
    background-color:#ffa;
}

Good luck!

foreach for JSON array , syntax

Try this:

$.each(result,function(index, value){
    console.log('My array has at position ' + index + ', this value: ' + value);
});

Why am I getting a " Traceback (most recent call last):" error?

At the beginning of your file you set raw_input to 0. Do not do this, at it modifies the built-in raw_input() function. Therefore, whenever you call raw_input(), it is essentially calling 0(), which raises the error. To remove the error, remove the first line of your code:

M = 1.6
# Miles to Kilometers 
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(raw_input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: %f\n" % M_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(raw_input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: %f\n") % F_conv
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(raw_input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: %f\n" % G_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(raw_input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: %f\n" % P_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(raw_input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: %f\n" % inches_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

How to use EOF to run through a text file in C?

How you detect EOF depends on what you're using to read the stream:

function                  result on EOF or error                    
--------                  ----------------------
fgets()                   NULL
fscanf()                  number of succesful conversions
                            less than expected
fgetc()                   EOF
fread()                   number of elements read
                            less than expected

Check the result of the input call for the appropriate condition above, then call feof() to determine if the result was due to hitting EOF or some other error.

Using fgets():

 char buffer[BUFFER_SIZE];
 while (fgets(buffer, sizeof buffer, stream) != NULL)
 {
   // process buffer
 }
 if (feof(stream))
 {
   // hit end of file
 }
 else
 {
   // some other error interrupted the read
 }

Using fscanf():

char buffer[BUFFER_SIZE];
while (fscanf(stream, "%s", buffer) == 1) // expect 1 successful conversion
{
  // process buffer
}
if (feof(stream)) 
{
  // hit end of file
}
else
{
  // some other error interrupted the read
}

Using fgetc():

int c;
while ((c = fgetc(stream)) != EOF)
{
  // process c
}
if (feof(stream))
{
  // hit end of file
}
else
{
  // some other error interrupted the read
}

Using fread():

char buffer[BUFFER_SIZE];
while (fread(buffer, sizeof buffer, 1, stream) == 1) // expecting 1 
                                                     // element of size
                                                     // BUFFER_SIZE
{
   // process buffer
}
if (feof(stream))
{
  // hit end of file
}
else
{
  // some other error interrupted read
}

Note that the form is the same for all of them: check the result of the read operation; if it failed, then check for EOF. You'll see a lot of examples like:

while(!feof(stream))
{
  fscanf(stream, "%s", buffer);
  ...
}

This form doesn't work the way people think it does, because feof() won't return true until after you've attempted to read past the end of the file. As a result, the loop executes one time too many, which may or may not cause you some grief.

What is the difference between pip and conda?

Can I use pip to install iPython?

Sure, both (first approach on page)

pip install ipython

and (third approach, second is conda)

You can manually download IPython from GitHub or PyPI. To install one of these versions, unpack it and run the following from the top-level source directory using the Terminal:

pip install .

are officially recommended ways to install.

Why should I use conda as another python package manager when I already have pip?

As said here:

If you need a specific package, maybe only for one project, or if you need to share the project with someone else, conda seems more appropriate.

Conda surpasses pip in (YMMV)

  • projects that use non-python tools
  • sharing with colleagues
  • switching between versions
  • switching between projects with different library versions

What is the difference between pip and conda?

That is extensively answered by everyone else.

Assert that a WebElement is not present using Selenium WebDriver with java

For node.js I've found the following to be effective way to wait for an element to no longer be present:

// variable to hold loop limit
    var limit = 5;
// variable to hold the loop count
    var tries = 0;
        var retry = driver.findElements(By.xpath(selector));
            while(retry.size > 0 && tries < limit){
                driver.sleep(timeout / 10)
                tries++;
                retry = driver.findElements(By.xpath(selector))
            }

How can I account for period (AM/PM) using strftime?

format = '%Y-%m-%d %H:%M %p'

The format is using %H instead of %I. Since %H is the "24-hour" format, it's likely just discarding the %p information. It works just fine if you change the %H to %I.

How to send parameters with jquery $.get()

If you say that it works with accessing directly manageproducts.do?option=1 in the browser then it should work with:

$.get('manageproducts.do', { option: '1' }, function(data) {
    ...
});

as it would send the same GET request.

ssh connection refused on Raspberry Pi

Apparently, the SSH server on Raspbian is now disabled by default. If there is no server listening for connections, it will not accept them. You can manually enable the SSH server according to this raspberrypi.org tutorial :

As of the November 2016 release, Raspbian has the SSH server disabled by default.

There are now multiple ways to enable it. Choose one:

From the desktop

  1. Launch Raspberry Pi Configuration from the Preferences menu
  2. Navigate to the Interfaces tab
  3. Select Enabled next to SSH
  4. Click OK

From the terminal with raspi-config

  1. Enter sudo raspi-config in a terminal window
  2. Select Interfacing Options
  3. Navigate to and select SSH
  4. Choose Yes
  5. Select Ok
  6. Choose Finish

Start the SSH service with systemctl

sudo systemctl enable ssh
sudo systemctl start ssh

On a headless Raspberry Pi

For headless setup, SSH can be enabled by placing a file named ssh, without any extension, onto the boot partition of the SD card. When the Pi boots, it looks for the ssh file. If it is found, SSH is enabled, and the file is deleted. The content of the file does not matter: it could contain text, or nothing at all.

Interface vs Abstract Class (general OO)

tl;dr; When you see “Is A” relationship use inheritance/abstract class. when you see “has a” relationship create member variables. When you see “relies on external provider” implement (not inherit) an interface.

Interview Question: What is the difference between an interface and an abstract class? And how do you decide when to use what? I mostly get one or all of the below answers: Answer 1: You cannot create an object of abstract class and interfaces.

ZK (That’s my initials): You cannot create an object of either. So this is not a difference. This is a similarity between an interface and an abstract class. Counter Question: Why can’t you create an object of abstract class or interface?

Answer 2: Abstract classes can have a function body as partial/default implementation.

ZK: Counter Question: So if I change it to a pure abstract class, marking all the virtual functions as abstract and provide no default implementation for any virtual function. Would that make abstract classes and interfaces the same? And could they be used interchangeably after that?

Answer 3: Interfaces allow multi-inheritance and abstract classes don’t.

ZK: Counter Question: Do you really inherit from an interface? or do you just implement an interface and, inherit from an abstract class? What’s the difference between implementing and inheriting? These counter questions throw candidates off and make most scratch their heads or just pass to the next question. That makes me think people need help with these basic building blocks of Object-Oriented Programming. The answer to the original question and all the counter questions is found in the English language and the UML. You must know at least below to understand these two constructs better.

Common Noun: A common noun is a name given “in common” to things of the same class or kind. For e.g. fruits, animals, city, car etc.

Proper Noun: A proper noun is the name of an object, place or thing. Apple, Cat, New York, Honda Accord etc.

Car is a Common Noun. And Honda Accord is a Proper Noun, and probably a Composit Proper noun, a proper noun made using two nouns.

Coming to the UML Part. You should be familiar with below relationships:

  • Is A
  • Has A
  • Uses

Let’s consider the below two sentences. - HondaAccord Is A Car? - HondaAccord Has A Car?

Which one sounds correct? Plain English and comprehension. HondaAccord and Cars share an “Is A” relationship. Honda accord doesn’t have a car in it. It “is a” car. Honda Accord “has a” music player in it.

When two entities share the “Is A” relationship it’s a better candidate for inheritance. And Has a relationship is a better candidate for creating member variables. With this established our code looks like this:

abstract class Car
{
   string color;
   int speed;
}
class HondaAccord : Car
{
   MusicPlayer musicPlayer;
}

Now Honda doesn't manufacture music players. Or at least it’s not their main business.

So they reach out to other companies and sign a contract. If you receive power here and the output signal on these two wires it’ll play just fine on these speakers.

This makes Music Player a perfect candidate for an interface. You don’t care who provides support for it as long as the connections work just fine.

You can replace the MusicPlayer of LG with Sony or the other way. And it won’t change a thing in Honda Accord.

Why can’t you create an object of abstract classes?

Because you can’t walk into a showroom and say give me a car. You’ll have to provide a proper noun. What car? Probably a honda accord. And that’s when a sales agent could get you something.

Why can’t you create an object of an interface? Because you can’t walk into a showroom and say give me a contract of music player. It won’t help. Interfaces sit between consumers and providers just to facilitate an agreement. What will you do with a copy of the agreement? It won’t play music.

Why do interfaces allow multiple inheritance?

Interfaces are not inherited. Interfaces are implemented. The interface is a candidate for interaction with the external world. Honda Accord has an interface for refueling. It has interfaces for inflating tires. And the same hose that is used to inflate a football. So the new code will look like below:

abstract class Car
{
    string color;
    int speed;
}
class HondaAccord : Car, IInflateAir, IRefueling
{
    MusicPlayer musicPlayer;
}

And the English will read like this “Honda Accord is a Car that supports inflating tire and refueling”.

How to semantically add heading to a list

You could also use the <figure> element to link a heading to your list like this:

<figure>
    <figcaption>My favorite fruits</figcaption>    
       <ul>
          <li>Banana</li>
          <li>Orange</li>
          <li>Chocolate</li>
       </ul>
</figure>

Source: https://www.w3.org/TR/2017/WD-html53-20171214/single-page.html#the-li-element (Example 162)

Python recursive folder read

This worked for me:

import glob

root_dir = "C:\\Users\\Scott\\" # Don't forget trailing (last) slashes    
for filename in glob.iglob(root_dir + '**/*.jpg', recursive=True):
     print(filename)
     # do stuff

How do I pass command line arguments to a Node.js program?

Parsing argument based on standard input ( --key=value )

const argv = (() => {
    const arguments = {};
    process.argv.slice(2).map( (element) => {
        const matches = element.match( '--([a-zA-Z0-9]+)=(.*)');
        if ( matches ){
            arguments[matches[1]] = matches[2]
                .replace(/^['"]/, '').replace(/['"]$/, '');
        }
    });
    return arguments;
})();

Command example

node app.js --name=stackoverflow --id=10 another-argument --text="Hello World"

Result of argv: console.log(argv)

{
    name: "stackoverflow",
    id: "10",
    text: "Hello World"
}

Run as java application option disabled in eclipse

I had this same problem. For me, the reason turned out to be that I had a mismatch in the name of the class and the name of the file. I declared class "GenSig" in a file called "SignatureTester.java".

I changed the name of the class to "SignatureTester", and the "Run as Java Application" option showed up immediately.

How to detect DIV's dimension changed?

You can use iframe or object using contentWindow or contentDocument on resize. Without setInterval or setTimeout

The steps:

  1. Set your element position to relative
  2. Add inside an transparent absolute hidden IFRAME
  3. Listen to IFRAME.contentWindow - onresize event

An example of HTML:

<div style="height:50px;background-color:red;position:relative;border:1px solid red">
<iframe style=width:100%;height:100%;position:absolute;border:none;background-color:transparent allowtransparency=true>
</iframe>
This is my div
</div>

The Javascript:

$('div').width(100).height(100);
$('div').animate({width:200},2000);

$('object').attr({
    type : 'text/html'
})
$('object').on('resize,onresize,load,onload',function(){
    console.log('ooooooooonload')
})

$($('iframe')[0].contentWindow).on('resize',function(){
    console.log('div changed')
})

Running Example

JsFiddle: https://jsfiddle.net/qq8p470d/


See more:

Import existing source code to GitHub

Add a GitHub repository as remote origin (replace [] with your URL):

git remote add origin [[email protected]:...]

Switch to your master branch and copy it to develop branch:

git checkout master
git checkout -b develop

Push your develop branch to the GitHub develop branch (-f means force):

git push -f origin develop:develop

"&" meaning after variable type

It means you're passing the variable by reference.

In fact, in a declaration of a type, it means reference, just like:

int x = 42;
int& y = x;

declares a reference to x, called y.

PHP call Class method / function

$f = new Functions;
$var = $f->filter($_GET['params']);

Have a look at the PHP manual section on Object Oriented programming

iOS Remote Debugging

Open Safari Desktop iOS

Develop -> Responsive Design Mode

Click "Other" under device

Paste this: Mozilla/5.0 (iPad; CPU OS 10_2_1 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.79 Mobile/14D27 Safari/602.1

Use Safari inspect tools.

C++ performance vs. Java/C#

I don't know either...my Java programs are always slow. :-) I've never really noticed C# programs being particularly slow, though.

DateTime.ToString() format that can be used in a filename or extension?

You can make a path for your file as bellow:

string path = "fileName-"+DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + ".txt";

How does one convert a grayscale image to RGB in OpenCV (Python)?

One you convert your image to gray-scale you cannot got back. You have gone from three channel to one, when you try to go back all three numbers will be the same. So the short answer is no you cannot go back. The reason your backtorgb function this throwing that error is because it needs to be in the format:

CvtColor(input, output, CV_GRAY2BGR)

OpenCV use BGR not RGB, so if you fix the ordering it should work, though your image will still be gray.

How to create a printable Twitter-Bootstrap page

To make print view look like tablet or desktop include bootstrap as .less, not as .css and then you can overwrite bootstrap responsive classes in the end of bootstrap_variables file for example like this:

@container-sm:      1200px;
@container-md:      1200px;
@container-lg:      1200px;
@screen-sm:         0;

Don't worry about putting this variables in the end of the file. LESS supports lazy loading of variables so they will be applied.

Can you autoplay HTML5 videos on the iPad?

Let video muted first to ensure autoplay in ios, then unmute it if you want.

<video autoplay loop muted playsinline>
  <source src="video.mp4?123" type="video/mp4">
</video>

<script type="text/javascript">
$(function () {
  if (!navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
    $("video").prop('muted', false);
  }
});
</script>

Conditionally Remove Dataframe Rows with R

Use the which function:

A <- c('a','a','b','b','b')
B <- c(1,0,1,1,0)
d <- data.frame(A, B)

r <- with(d, which(B==0, arr.ind=TRUE))
newd <- d[-r, ]

Changing project port number in Visual Studio 2013

To specify a port for the ASP.NET Development Server

  • In Solution Explorer, click the name of the application.

  • In the Properties pane, click the down-arrow beside Use dynamic ports and select False from the dropdown list.

  • This will enable editing of the Port number property.

  • In the Properties pane, click the text box beside Port number and
    type in a port number. Click outside of the Properties pane. This
    saves the property settings.

  • Each time you run a file-system Web site within Visual Web Developer, the ASP.NET Development Server will listen on the specified port.

Hope this helps.

Force re-download of release dependency using Maven

You cannot make Maven re-download dependencies, but what you can do instead is to purge dependencies that were incorrectly downloaded using mvn dependency:purge-local-repository

See: http://maven.apache.org/plugins/maven-dependency-plugin/purge-local-repository-mojo.html

How to get the selected date value while using Bootstrap Datepicker?

If you wan't the date in full text string format you can do it like this:

$('#your-datepicker').data().datepicker.viewDate

Python regular expressions return true/false

If you really need True or False, just use bool

>>> bool(re.search("hi", "abcdefghijkl"))
True
>>> bool(re.search("hi", "abcdefgijkl"))
False

As other answers have pointed out, if you are just using it as a condition for an if or while, you can use it directly without wrapping in bool()

How to read if a checkbox is checked in PHP?

$is_checked = isset($_POST['your_checkbox_name']) &&
              $_POST['your_checkbox_name'] == 'on';

Short circuit evaluation will take care so that you don't access your_checkbox_name when it was not submitted.

How to properly add cross-site request forgery (CSRF) token using PHP

The variable $token is not being retrieved from the session when it's in there

Insert 2 million rows into SQL Server quickly

Re the solution for SqlBulkCopy:

I used the StreamReader to convert and process the text file. The result was a list of my object.

I created a class than takes Datatable or a List<T> and a Buffer size (CommitBatchSize). It will convert the list to a data table using an extension (in the second class).

It works very fast. On my PC, I am able to insert more than 10 million complicated records in less than 10 seconds.

Here is the class:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{

public class BulkUploadToSql<T>
{
    public IList<T> InternalStore { get; set; }
    public string TableName { get; set; }
    public int CommitBatchSize { get; set; }=1000;
    public string ConnectionString { get; set; }

    public void Commit()
    {
        if (InternalStore.Count>0)
        {
            DataTable dt;
            int numberOfPages = (InternalStore.Count / CommitBatchSize)  + (InternalStore.Count % CommitBatchSize == 0 ? 0 : 1);
            for (int pageIndex = 0; pageIndex < numberOfPages; pageIndex++)
                {
                    dt= InternalStore.Skip(pageIndex * CommitBatchSize).Take(CommitBatchSize).ToDataTable();
                BulkInsert(dt);
                }
        } 
    }

    public void BulkInsert(DataTable dt)
    {
        using (SqlConnection connection = new SqlConnection(ConnectionString))
        {
            // make sure to enable triggers
            // more on triggers in next post
            SqlBulkCopy bulkCopy =
                new SqlBulkCopy
                (
                connection,
                SqlBulkCopyOptions.TableLock |
                SqlBulkCopyOptions.FireTriggers |
                SqlBulkCopyOptions.UseInternalTransaction,
                null
                );

            // set the destination table name
            bulkCopy.DestinationTableName = TableName;
            connection.Open();

            // write the data in the "dataTable"
            bulkCopy.WriteToServer(dt);
            connection.Close();
        }
        // reset
        //this.dataTable.Clear();
    }

}

public static class BulkUploadToSqlHelper
{
    public static DataTable ToDataTable<T>(this IEnumerable<T> data)
    {
        PropertyDescriptorCollection properties =
            TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;
    }
}

}

Here is an example when I want to insert a List of my custom object List<PuckDetection> (ListDetections):

var objBulk = new BulkUploadToSql<PuckDetection>()
{
        InternalStore = ListDetections,
        TableName= "PuckDetections",
        CommitBatchSize=1000,
        ConnectionString="ENTER YOU CONNECTION STRING"
};
objBulk.Commit();

The BulkInsert class can be modified to add column mapping if required. Example you have an Identity key as first column.(this assuming that the column names in the datatable are the same as the database)

//ADD COLUMN MAPPING
foreach (DataColumn col in dt.Columns)
{
        bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
}

Conditional formatting using AND() function

I was having the same problem with the AND() breaking the conditional formatting. I just happened to try treating the AND as multiplication, and it works! Remove the AND() function and just multiply your arguments. Excel will treat the booleans as 1 for true and 0 for false. I just tested this formula and it seems to work.

=(INDIRECT(ADDRESS(4,COLUMN()))>=INDIRECT(ADDRESS(ROW(),4)))*(INDIRECT(ADDRESS(4,COLUMN()))<=INDIRECT(ADDRESS(ROW(),5)))

How to asynchronously call a method in Java

You can use @Async annotation from jcabi-aspects and AspectJ:

public class Foo {
  @Async
  public void save() {
    // to be executed in the background
  }
}

When you call save(), a new thread starts and executes its body. Your main thread continues without waiting for the result of save().

Get Country of IP Address with PHP

Use the widget www.feedsalive.com, to get the country informations & last page information as well.

Difference between onLoad and ng-init in angular

From angular's documentation,

ng-init SHOULD NOT be used for any initialization. It should be used only for aliasing. https://docs.angularjs.org/api/ng/directive/ngInit

onload should be used if any expression needs to be evaluated after a partial view is loaded (by ng-include). https://docs.angularjs.org/api/ng/directive/ngInclude

The major difference between them is when used with ng-include.

<div ng-include="partialViewUrl" onload="myFunction()"></div>

In this case, myFunction is called everytime the partial view is loaded.

<div ng-include="partialViewUrl" ng-init="myFunction()"></div>

Whereas, in this case, myFunction is called only once when the parent view is loaded.

LaTeX table positioning

In my case I was having an issue where the table was not being displayed right after the paragraph I inserted it, so I simply changed

\begin{table}[]

to

\begin{table}[ht]

How to install beautiful soup 4 with python 2.7 on windows

Install pip

Download get-pip. Remember to save it as "get-pip.py"

Now go to the download folder. Right click on get-pip.py then open with python.exe.

You can add system variable by

(by doing this you can use pip and easy_install without specifying path)

1 Clicking on Properties of My Computer

2 Then chose Advanced System Settings

3 Click on Advanced Tab

4 Click on Environment Variables

5 From System Variables >>> select variable path.

6 Click edit then add the following lines at the end of it

 ;c:\Python27;c:\Python27\Scripts

(please dont copy this, just go to your python directory and copy the paths similar to this)

NB:- you have to do this once only.

Install beautifulsoup4

Open cmd and type

pip install beautifulsoup4

Manifest Merger failed with multiple errors in Android Studio

I had a weird encounter with this problem. when renaming variable name to user_name, I mistakenly rename all of the name to user_name for the project. So my xml tag <color name:""> became <color user_name:""> same goes for string, style, manifest too. But when I check merged manifest, it showed nothing, because I had only one manifest, nothing to find.

So, check if you have any malformed xml file or not.

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

You're missing service name:

 SQL> connect username/password@hostname:port/SERVICENAME

EDIT

If you can connect to the database from other computer try running there:

select sys_context('USERENV','SERVICE_NAME') from dual

and

select sys_context('USERENV','SID') from dual

How do you clone a Git repository into a specific folder?

Here's how I would do it, but I have made an alias to do it for me.

$ cd ~Downloads/git; git clone https:git.foo/poo.git

There is probably a more elegant way of doing this, however I found this to be easiest for myself.

Here's the alias I created to speed things along. I made it for zsh, but it should work just fine for bash or any other shell like fish, xyzsh, fizsh, and so on.

Edit ~/.zshrc, /.bashrc, etc. with your favorite editor (mine is Leafpad, so I would write $ leafpad ~/.zshrc).

My personal preference, however, is to make a zsh plugin to keep track of all my aliases. You can create a personal plugin for oh-my-zsh by running these commands:

$ cd ~/.oh-my-zsh/
$ cd plugins/
$ mkdir your-aliases-folder-name; cd your-aliases-folder-name
     # In my case '~/.oh-my-zsh/plugins/ev-aliases/ev-aliases'
$ leafpad your-zsh-aliases.plugin.zsh
     # Again, in my case 'ev-aliases.plugin.zsh'

Afterwards, add these lines to your newly created blank alises.plugin file:

# Git aliases
alias gc="cd ~/Downloads/git; git clone "

(From here, replace your name with mine.)

Then, in order to get the aliases to work, they (along with zsh) have to be sourced-in (or whatever it's called). To do so, inside your custom plugin document add this:

## Ev's Aliases

#### Remember to re-source zsh after making any changes with these commands:

#### These commands should also work, assuming ev-aliases have already been sourced before:

allsource="source $ZSH/oh-my-zsh.sh ; source /home/ev/.oh-my-zsh/plugins/ev-aliases/ev-aliases.plugin.zsh; clear"
sourceall="source $ZSH/oh-my-zsh.sh ; source /home/ev/.oh-my-zsh/plugins/ev-aliases/ev-aliases.plugin.zsh"
#### 

####################################

# git aliases

alias gc="cd ~/Downloads/git; git clone "
# alias gc="git clone "
# alias gc="cd /your/git/folder/or/whatever; git clone "

####################################

Save your oh-my-zsh plugin, and run allsource. If that does not seem to work, simply run source $ZSH/oh-my-zsh.sh; source /home/ev/.oh-my-zsh/plugins/ev-aliases/ev-aliases.plugin.zsh. That will load the plugin source which will allow you to use allsource from now on.


I'm in the process of making a Git repository with all of my aliases. Please feel free to check them out here: Ev's dot-files. Please feel free to fork and improve upon them to suit your needs.

Case-insensitive string comparison in C++

Take advantage of the standard char_traits. Recall that a std::string is in fact a typedef for std::basic_string<char>, or more explicitly, std::basic_string<char, std::char_traits<char> >. The char_traits type describes how characters compare, how they copy, how they cast etc. All you need to do is typedef a new string over basic_string, and provide it with your own custom char_traits that compare case insensitively.

struct ci_char_traits : public char_traits<char> {
    static bool eq(char c1, char c2) { return toupper(c1) == toupper(c2); }
    static bool ne(char c1, char c2) { return toupper(c1) != toupper(c2); }
    static bool lt(char c1, char c2) { return toupper(c1) <  toupper(c2); }
    static int compare(const char* s1, const char* s2, size_t n) {
        while( n-- != 0 ) {
            if( toupper(*s1) < toupper(*s2) ) return -1;
            if( toupper(*s1) > toupper(*s2) ) return 1;
            ++s1; ++s2;
        }
        return 0;
    }
    static const char* find(const char* s, int n, char a) {
        while( n-- > 0 && toupper(*s) != toupper(a) ) {
            ++s;
        }
        return s;
    }
};

typedef std::basic_string<char, ci_char_traits> ci_string;

The details are on Guru of The Week number 29.

Start ssh-agent on login

Users of the fish shell can use this script to do the same thing.

# content has to be in .config/fish/config.fish
# if it does not exist, create the file
setenv SSH_ENV $HOME/.ssh/environment

function start_agent                                                                                                                                                                    
    echo "Initializing new SSH agent ..."
    ssh-agent -c | sed 's/^echo/#echo/' > $SSH_ENV
    echo "succeeded"
    chmod 600 $SSH_ENV 
    . $SSH_ENV > /dev/null
    ssh-add
end

function test_identities                                                                                                                                                                
    ssh-add -l | grep "The agent has no identities" > /dev/null
    if [ $status -eq 0 ]
        ssh-add
        if [ $status -eq 2 ]
            start_agent
        end
    end
end

if [ -n "$SSH_AGENT_PID" ] 
    ps -ef | grep $SSH_AGENT_PID | grep ssh-agent > /dev/null
    if [ $status -eq 0 ]
        test_identities
    end  
else
    if [ -f $SSH_ENV ]
        . $SSH_ENV > /dev/null
    end  
    ps -ef | grep $SSH_AGENT_PID | grep -v grep | grep ssh-agent > /dev/null
    if [ $status -eq 0 ]
        test_identities
    else 
        start_agent
    end  
end

Failed to Connect to MySQL at localhost:3306 with user root

At rigth side in Navigator -> Instance-> Click on Startup/Shutdown -> Click on Start Server

It will work surely

Importing a Maven project into Eclipse from Git


Step 1 : Setting Up Eclipse

First of all you'll need to have a few Eclipse plug-ins installed. So use eclipse IDE software install feature in the help dropdown menu ? Install new software, and add link to Available Software Site, then install it.

  1. GIT plugin (EGIT)- http://download.eclipse.org/egit/updates
  2. Eclipse Maven plugin (M2Eclipse) - http://download.eclipse.org/technology/m2e/releases
  3. Maven SCM Handler for EGit (m2e-egit)

    Install from the M2E Marketplace (Settings ? Maven ? Discovery ? Open Catalog and search for " m2e-egit")


Step 2 : Clone the repository

Clone(download) your Maven Projects from Git

Check out non-eclipse Maven Projects from Git (File ? Import.. ? Maven ? Check out Maven Projects from SCM)

File ? Import.. ? Maven ? Check out Maven Projects from SCM

Now add your git repository link to SCM URI field.Then click next & finish.

How to TryParse for Enum value?

In the end you have to implement this around Enum.GetNames:

public bool TryParseEnum<T>(string str, bool caseSensitive, out T value) where T : struct {
    // Can't make this a type constraint...
    if (!typeof(T).IsEnum) {
        throw new ArgumentException("Type parameter must be an enum");
    }
    var names = Enum.GetNames(typeof(T));
    value = (Enum.GetValues(typeof(T)) as T[])[0];  // For want of a better default
    foreach (var name in names) {
        if (String.Equals(name, str, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase)) {
            value = (T)Enum.Parse(typeof(T), name);
            return true;
        }
    }
    return false;
}

Additional notes:

  • Enum.TryParse is included in .NET 4. See here http://msdn.microsoft.com/library/dd991876(VS.100).aspx
  • Another approach would be to directly wrap Enum.Parse catching the exception thrown when it fails. This could be faster when a match is found, but will likely to slower if not. Depending on the data you are processing this may or may not be a net improvement.

EDIT: Just seen a better implementation on this, which caches the necessary information: http://damieng.com/blog/2010/10/17/enums-better-syntax-improved-performance-and-tryparse-in-net-3-5

Filename timestamp in Windows CMD batch script getting truncated

It wants the full time in DD-MM-YYYY_HH-MM-SS.TT where TT is the ticks. The exception says it all.

Processing $http response in service

I had the same problem, but when I was surfing on the internet I understood that $http return back by default a promise, then I could use it with "then" after return the "data". look at the code:

 app.service('myService', function($http) {
       this.getData = function(){
         var myResponseData = $http.get('test.json').then(function (response) {
            console.log(response);.
            return response.data;
          });
         return myResponseData;

       }
});    
 app.controller('MainCtrl', function( myService, $scope) {
      // Call the getData and set the response "data" in your scope.  
      myService.getData.then(function(myReponseData) {
        $scope.data = myReponseData;
      });
 });

Change directory in PowerShell

Unlike the CMD.EXE CHDIR or CD command, the PowerShell Set-Location cmdlet will change drive and directory, both. Get-Help Set-Location -Full will get you more detailed information on Set-Location, but the basic usage would be

PS C:\> Set-Location -Path Q:\MyDir

PS Q:\MyDir> 

By default in PowerShell, CD and CHDIR are alias for Set-Location.

(Asad reminded me in the comments that if the path contains spaces, it must be enclosed in quotes.)

Use success() or complete() in AJAX call

Is it that success() returns earlier than complete()?

Yes; the AJAX success() method runs before the complete() method.

Below is a diagram illustrating the process flow:

AJAX call process flow diagram.

It is important to note that

  • The success() (Local Event) is only called if the request was successful (no errors from the server, no errors with the data).

  • On the other hand, the complete() (Local Event) is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.

... more details on AJAX Events here.

Ruby on Rails: How do I add placeholder text to a f.text_field?

In your view template, set a default value:

f.text_field :password, :value => "password"

In your Javascript (assuming jquery here):

$(document).ready(function() {
  //add a handler to remove the text
});

How do I send a POST request with PHP?

Try PEAR's HTTP_Request2 package to easily send POST requests. Alternatively, you can use PHP's curl functions or use a PHP stream context.

HTTP_Request2 also makes it possible to mock out the server, so you can unit-test your code easily

Function to check if a string is a date

In case you don't know the date format:

/**
 * Check if the value is a valid date
 *
 * @param mixed $value
 *
 * @return boolean
 */
function isDate($value) 
{
    if (!$value) {
        return false;
    }

    try {
        new \DateTime($value);
        return true;
    } catch (\Exception $e) {
        return false;
    }
}

var_dump(isDate('2017-01-06')); // true
var_dump(isDate('2017-13-06')); // false
var_dump(isDate('2017-02-06T04:20:33')); // true
var_dump(isDate('2017/02/06')); // true
var_dump(isDate('3.6. 2017')); // true
var_dump(isDate(null)); // false
var_dump(isDate(true)); // false
var_dump(isDate(false)); // false
var_dump(isDate('')); // false
var_dump(isDate(45)); // false

Creating a Plot Window of a Particular Size

This will depend on the device you're using. If you're using a pdf device, you can do this:

pdf( "mygraph.pdf", width = 11, height = 8 )
plot( x, y )

You can then divide up the space in the pdf using the mfrow parameter like this:

par( mfrow = c(2,2) )

That makes a pdf with four panels available for plotting. Unfortunately, some of the devices take different units than others. For example, I think that X11 uses pixels, while I'm certain that pdf uses inches. If you'd just like to create several devices and plot different things to them, you can use dev.new(), dev.list(), and dev.next().

Other devices that might be useful include:

There's a list of all of the devices here.

Run text file as commands in Bash

you can also just run it with a shell, for example:

bash example.txt

sh example.txt

Case vs If Else If: Which is more efficient?

I believe because cases must be constant values, the switch statement does the equivelent of a goto, so based on the value of the variable it jumps to the right case, whereas in the if/then statement it must evaluate each expression.

How to retrieve value from elements in array using jQuery?

Use map function

var values = $("input[name^='card']").map(function (idx, ele) {
   return $(ele).val();
}).get();

Removing object from array in Swift 3

In Swift 3 and 4

var array = ["a", "b", "c", "d", "e", "f"]

for (index, element) in array.enumerated().reversed() {
    array.remove(at: index)
}

From Swift 4.2 you can use more advanced approach(faster and memory efficient)

array.removeAll(where: { $0 == "c" })

instead of

array = array.filter { !$0.hasPrefix("c") }

Read more here

Entity Framework code-first: migration fails with update-database, forces unneccessary(?) add-migration

In answer to your general question of

So I am curious: What did I do to disorientate migrations? And what can I do to get it working with just one initial migration?

I've just had the same error message as you after I merged several branches and the migrations got confused about the current state of the database. Worst of all, this was only happening on the client's server, not on our development systems.

In trying to work out what was happening there, I came across this superb Microsoft guide:

Microsoft's guide to Code First Migrations in Team Environments

Whilst that guide was written to explain migrations in teams, it also gives the best explanation I've found of how the migrations work internally, which may well lead to an explanation for the behaviour your seeing. It's very worth putting an hour aside to read all of that for anyone who works with EF6 or below.

For anyone brought to this question by that error message after merging migrations, the trick of generating a blank migration with the current state of the database solved things for me, but do be very sure to have read the whole guide to know if that solution is appropriate in your case.

What's the difference between Instant and LocalDateTime?

You are wrong about LocalDateTime: it does not store any time-zone information and it has nanosecond precision. Quoting the Javadoc (emphasis mine):

A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.

LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision. For example, the value "2nd October 2007 at 13:45.30.123456789" can be stored in a LocalDateTime.

The difference between the two is that Instant represents an offset from the Epoch (01-01-1970) and, as such, represents a particular instant on the time-line. Two Instant objects created at the same moment in two different places of the Earth will have exactly the same value.

Java 8 Stream and operation on arrays

Be careful if you have to deal with large numbers.

int[] arr = new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE};
long sum = Arrays.stream(arr).sum(); // Wrong: sum == 0

The sum above is not 2 * Integer.MIN_VALUE. You need to do this in this case.

long sum = Arrays.stream(arr).mapToLong(Long::valueOf).sum(); // Correct

How to determine an object's class?

Multiple right answers were presented, but there are still more methods: Class.isAssignableFrom() and simply attempting to cast the object (which might throw a ClassCastException).

Possible ways summarized

Let's summarize the possible ways to test if an object obj is an instance of type C:

// Method #1
if (obj instanceof C)
    ;

// Method #2
if (C.class.isInstance(obj))
    ;

// Method #3
if (C.class.isAssignableFrom(obj.getClass()))
    ;

// Method #4
try {
    C c = (C) obj;
    // No exception: obj is of type C or IT MIGHT BE NULL!
} catch (ClassCastException e) {
}

// Method #5
try {
    C c = C.class.cast(obj);
    // No exception: obj is of type C or IT MIGHT BE NULL!
} catch (ClassCastException e) {
}

Differences in null handling

There is a difference in null handling though:

  • In the first 2 methods expressions evaluate to false if obj is null (null is not instance of anything).
  • The 3rd method would throw a NullPointerException obviously.
  • The 4th and 5th methods on the contrary accept null because null can be cast to any type!

To remember: null is not an instance of any type but it can be cast to any type.

Notes

  • Class.getName() should not be used to perform an "is-instance-of" test becase if the object is not of type C but a subclass of it, it may have a completely different name and package (therefore class names will obviously not match) but it is still of type C.
  • For the same inheritance reason Class.isAssignableFrom() is not symmetric:
    obj.getClass().isAssignableFrom(C.class) would return false if the type of obj is a subclass of C.

How to split csv whose columns may contain ,

Use a library like LumenWorks to do your CSV reading. It'll handle fields with quotes in them and will likely overall be more robust than your custom solution by virtue of having been around for a long time.

Use Toast inside Fragment

A simple [Fragment] subclass.
Kotlin!
contextA - is a parent (main) Activity. Set it on create object.

class Start(contextA: Context) : Fragment() {

var contextB: Context = contextA;

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    val fl = inflater.inflate(R.layout.fragment_start, container, false)

    // only thet variant is worked on me
    fl.button.setOnClickListener { view -> openPogodaUrl(view) }

    return fl;
}

fun openPogodaUrl(view: View) {        
    try {
        pogoda.webViewClient = object : WebViewClient() { // pogoda - is a WebView
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                view?.loadUrl(url)
                return true
            }
        }
        pogoda.loadUrl("http://exemple.com/app_vidgets/pogoda.html");
    }
    catch (e: Exception)
    {
        Toast.makeText(contextB, e.toString(), Toast.LENGTH_LONG).show();
    }
}

}

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.

How to get the current URL within a Django template?

Above answers are correct and they give great and short answer.

I was also looking for getting the current page's url in Django template as my intention was to activate HOME page, MEMBERS page, CONTACT page, ALL POSTS page when they are requested.

I am pasting the part of the HTML code snippet that you can see below to understand the use of request.path. You can see it in my live website at http://pmtboyshostelraipur.pythonanywhere.com/

<div id="navbar" class="navbar-collapse collapse">
  <ul class="nav navbar-nav">
        <!--HOME-->
        {% if "/" == request.path %}
      <li class="active text-center">
          <a href="/" data-toggle="tooltip" title="Home" data-placement="bottom">
            <i class="fa fa-home" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true">
            </i>
          </a>
      </li>
      {% else %}
      <li class="text-center">
          <a href="/" data-toggle="tooltip" title="Home" data-placement="bottom">
            <i class="fa fa-home" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true">
            </i>
          </a>
      </li>
      {% endif %}

      <!--MEMBERS-->
      {% if "/members/" == request.path %}
      <li class="active text-center">
        <a href="/members/" data-toggle="tooltip" title="Members"  data-placement="bottom">
          <i class="fa fa-users" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true"></i>
        </a>
      </li>
      {% else %}
      <li class="text-center">
        <a href="/members/" data-toggle="tooltip" title="Members"  data-placement="bottom">
          <i class="fa fa-users" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true"></i>
        </a>
      </li>
      {% endif %}

      <!--CONTACT-->
      {% if "/contact/" == request.path %}
      <li class="active text-center">
        <a class="nav-link" href="/contact/"  data-toggle="tooltip" title="Contact"  data-placement="bottom">
            <i class="fa fa-volume-control-phone" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true"></i>
          </a>
      </li>
      {% else %}
      <li class="text-center">
        <a class="nav-link" href="/contact/"  data-toggle="tooltip" title="Contact"  data-placement="bottom">
            <i class="fa fa-volume-control-phone" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true"></i>
          </a>
      </li>
      {% endif %}

      <!--ALL POSTS-->
      {% if "/posts/" == request.path %}
      <li class="text-center">
        <a class="nav-link" href="/posts/"  data-toggle="tooltip" title="All posts"  data-placement="bottom">
            <i class="fa fa-folder-open" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true"></i>
          </a>
      </li>
      {% else %}
      <li class="text-center">
        <a class="nav-link" href="/posts/"  data-toggle="tooltip" title="All posts"  data-placement="bottom">
            <i class="fa fa-folder-open" style="font-size:25px; padding-left: 5px; padding-right: 5px" aria-hidden="true"></i>
          </a>
      </li>
      {% endif %}
</ul>

Use of Application.DoEvents()

Check out the MSDN Documentation for the Application.DoEvents method.

How to extract IP Address in Spring MVC Controller get call?

I use such method to do this

public class HttpReqRespUtils {

    private static final String[] IP_HEADER_CANDIDATES = {
        "X-Forwarded-For",
        "Proxy-Client-IP",
        "WL-Proxy-Client-IP",
        "HTTP_X_FORWARDED_FOR",
        "HTTP_X_FORWARDED",
        "HTTP_X_CLUSTER_CLIENT_IP",
        "HTTP_CLIENT_IP",
        "HTTP_FORWARDED_FOR",
        "HTTP_FORWARDED",
        "HTTP_VIA",
        "REMOTE_ADDR"
    };

    public static String getClientIpAddressIfServletRequestExist() {

        if (RequestContextHolder.getRequestAttributes() == null) {
            return "0.0.0.0";
        }

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        for (String header: IP_HEADER_CANDIDATES) {
            String ipList = request.getHeader(header);
            if (ipList != null && ipList.length() != 0 && !"unknown".equalsIgnoreCase(ipList)) {
                String ip = ipList.split(",")[0];
                return ip;
            }
        }

        return request.getRemoteAddr();
    }
}

Check if a value exists in ArrayList

Better to use a HashSet than an ArrayList when you are checking for existence of a value. Java docs for HashSet says: "This class offers constant time performance for the basic operations (add, remove, contains and size)"

ArrayList.contains() might have to iterate the whole list to find the instance you are looking for.

Angular 4 Pipe Filter

The transform method signature changed somewhere in an RC of Angular 2. Try something more like this:

export class FilterPipe implements PipeTransform {
    transform(items: any[], filterBy: string): any {
        return items.filter(item => item.id.indexOf(filterBy) !== -1);
    }
}

And if you want to handle nulls and make the filter case insensitive, you may want to do something more like the one I have here:

export class ProductFilterPipe implements PipeTransform {

    transform(value: IProduct[], filterBy: string): IProduct[] {
        filterBy = filterBy ? filterBy.toLocaleLowerCase() : null;
        return filterBy ? value.filter((product: IProduct) =>
            product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1) : value;
    }
}

And NOTE: Sorting and filtering in pipes is a big issue with performance and they are NOT recommended. See the docs here for more info: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

Which characters are valid/invalid in a JSON key name?

It is worth mentioning that while starting the keys with numbers is valid, it could cause some unintended issues.

Example:

var testObject = {
    "1tile": "test value"
};
console.log(testObject.1tile); // fails, invalid syntax
console.log(testObject["1tile"]; // workaround

How to unstage large number of files without deleting the content

2019 update

As pointed out by others in related questions (see here, here, here, here, here, here, and here), you can now unstage a file with git restore --staged <file>.

To unstage all the files in your project, run the following from the root of the repository (the command is recursive):

git restore --staged .

If you only want to unstage the files in a directory, navigate to it before running the above or run:

git restore --staged <directory-path>

Notes

  • git restore was introduced in July 2019 and released in version 2.23.
    With the --staged flag, it restores the content of the working tree from HEAD (so it does the opposite of git add and does not delete any change).

  • This is a new command, but the behaviour of the old commands remains unchanged. So the older answers with git reset or git reset HEAD are still perfectly valid.

  • When running git status with staged uncommitted file(s), this is now what Git suggests to use to unstage file(s) (instead of git reset HEAD <file> as it used to prior to v2.23).

Showing loading animation in center of page while making a call to Action method in ASP .NET MVC

Another solution that it is similar to those already exposed here is this one. Just before the closing body tag place this html:

<div id="resultLoading" style="display: none; width: 100%; height: 100%; position: fixed; z-index: 10000; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto;">
    <div style="width: 340px; height: 200px; text-align: center; position: fixed; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto; z-index: 10; color: rgb(255, 255, 255);">
        <div class="uil-default-css">
            <img src="/images/loading-animation1.gif" style="max-width: 150px; max-height: 150px; display: block; margin-left: auto; margin-right: auto;" />
        </div>
        <div class="loader-text" style="display: block; font-size: 18px; font-weight: 300;">&nbsp;</div>
    </div>
    <div style="background: rgb(0, 0, 0); opacity: 0.6; width: 100%; height: 100%; position: absolute; top: 0px;"></div>
</div>

Finally, replace .loader-text element's content on the fly on every navigation event and turn on the #resultloading div, note that it is initially hidden.

var showLoader = function (text) {
    $('#resultLoading').show();
    $('#resultLoading').find('.loader-text').html(text);
};

jQuery(document).ready(function () {
    jQuery(window).on("beforeunload ", function () {
        showLoader('Loading, please wait...');
    });
});

This can be applied to any html based project with jQuery where you don't know which pages of your administration area will take too long to finish loading.

The gif image is 176x176px but you can use any transparent gif animation, please take into account that the image size is not important as it will be maxed to 150x150px.

Also, the function showLoader can be called on an element's click to perform an action that will further redirect the page, that is why it is provided ad an individual function. i hope this can also help anyone.

How to calculate distance from Wifi router using Signal Strength?

Don't care if you are a moderator. I wrote my text towards my audience not as a technical writer

All you guys need to learn to navigate with tools that predate GPS. Something like a sextant, octant, backstaff or an astrolabe.

If you have receive the signal from 3 different locations then you only need to measure the signal strength and make a ratio from those locations. Simple triangle calculation where a2+b2=c2. The stronger the signal strength the closer the device is to the receiver.

How to replace special characters in a string?

You can get unicode for that junk character from charactermap tool in window pc and add \u e.g. \u00a9 for copyright symbol. Now you can use that string with that particular junk caharacter, don't remove any junk character but replace with proper unicode.

grabbing first row in a mysql query only

To return only one row use LIMIT 1:

SELECT *
FROM tbl_foo
WHERE name = 'sarmen'
LIMIT 1

It doesn't make sense to say 'first row' or 'last row' unless you have an ORDER BY clause. Assuming you add an ORDER BY clause then you can use LIMIT in the following ways:

  • To get the first row use LIMIT 1.
  • To get the 2nd row you can use limit with an offset: LIMIT 1, 1.
  • To get the last row invert the order (change ASC to DESC or vice versa) then use LIMIT 1.

How does "make" app know default target to build if no target is specified?

To save others a few seconds, and to save them from having to read the manual, here's the short answer. Add this to the top of your make file:

.DEFAULT_GOAL := mytarget

mytarget will now be the target that is run if "make" is executed and no target is specified.

If you have an older version of make (<= 3.80), this won't work. If this is the case, then you can do what anon mentions, simply add this to the top of your make file:

.PHONY: default
default: mytarget ;

References: https://www.gnu.org/software/make/manual/html_node/How-Make-Works.html

use localStorage across subdomains

I'm using xdLocalStorage, this is a lightweight js library which implements LocalStorage interface and support cross domain storage by using iframe post message communication.( angularJS support )

https://github.com/ofirdagan/cross-domain-local-storage

Why is &#65279; appearing in my HTML?

Just use notepad ++ with encoding UTF-8 without BOM.

Consider marking event handler as 'passive' to make the page more responsive

This hides the warning message:

jQuery.event.special.touchstart = {
  setup: function( _, ns, handle ) {
      this.addEventListener("touchstart", handle, { passive: !ns.includes("noPreventDefault") });
  }
};

PHP ini file_get_contents external url

The is related to the ini configuration setting allow_url_fopen.

You should be aware that enable that option may make some bugs in your code exploitable.

For instance, this failure to validate input may turn into a full-fledged remote code execution vulnerability:

copy($_GET["file"], "."); 

Python Pandas replicate rows in dataframe

This is an old question, but since it still comes up at the top of my results in Google, here's another way.

import pandas as pd
import numpy as np

df = pd.DataFrame({'col1':list("abc"),'col2':range(3)},index = range(3))

Say you want to replicate the rows where col1="b".

reps = [3 if val=="b" else 1 for val in df.col1]
df.loc[np.repeat(df.index.values, reps)]

You could replace the 3 if val=="b" else 1 in the list interpretation with another function that could return 3 if val=="b" or 4 if val=="c" and so on, so it's pretty flexible.

Cannot kill Python script with Ctrl-C

Ctrl+C terminates the main thread, but because your threads aren't in daemon mode, they keep running, and that keeps the process alive. We can make them daemons:

f = FirstThread()
f.daemon = True
f.start()
s = SecondThread()
s.daemon = True
s.start()

But then there's another problem - once the main thread has started your threads, there's nothing else for it to do. So it exits, and the threads are destroyed instantly. So let's keep the main thread alive:

import time
while True:
    time.sleep(1)

Now it will keep print 'first' and 'second' until you hit Ctrl+C.

Edit: as commenters have pointed out, the daemon threads may not get a chance to clean up things like temporary files. If you need that, then catch the KeyboardInterrupt on the main thread and have it co-ordinate cleanup and shutdown. But in many cases, letting daemon threads die suddenly is probably good enough.

Debug/run standard java in Visual Studio Code IDE and OS X?

Code Runner Extension will only let you "run" java files.

To truly debug 'Java' files follow the quick one-time setup:

  • Install Java Debugger Extension in VS Code and reload.
  • open an empty folder/project in VS code.
  • create your java file (s).
  • create a folder .vscode in the same folder.
  • create 2 files inside .vscode folder: tasks.json and launch.json
  • copy paste below config in tasks.json:
{
    "version": "2.0.0",
    "type": "shell",
    "presentation": {
        "echo": true,
        "reveal": "always",
        "focus": false,
        "panel": "shared"
    },
    "isBackground": true,
    "tasks": [
        {
            "taskName": "build",
            "args": ["-g", "${file}"],
            "command": "javac"
        }
    ]
}
  • copy paste below config in launch.json:
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Debug Java",
            "type": "java",
            "request": "launch",
            "externalConsole": true,                //user input dosen't work if set it to false :(
            "stopOnEntry": true,
            "preLaunchTask": "build",                 // Runs the task created above before running this configuration
            "jdkPath": "${env:JAVA_HOME}/bin",        // You need to set JAVA_HOME enviroment variable
            "cwd": "${workspaceRoot}",
            "startupClass": "${workspaceRoot}${file}",
            "sourcePath": ["${workspaceRoot}"],   // Indicates where your source (.java) files are
            "classpath": ["${workspaceRoot}"],    // Indicates the location of your .class files
            "options": [],                             // Additional options to pass to the java executable
            "args": []                                // Command line arguments to pass to the startup class
        }

    ],
    "compounds": []
}

You are all set to debug java files, open any java file and press F5 (Debug->Start Debugging).


Tip: *To hide .class files in the side explorer of VS code, open settings of VS code and paste the below config:

"files.exclude": {
        "*.class": true
    }

enter image description here

Jenkins, specifying JAVA_HOME

i saw into Eclipse > Preferences>installed JREs > JRE Definition i found the directory of java_home so it's /Library/Java/JavaVirtualMachines/jdk1.7.0_17.jdk/Contents/Home

Manage toolbar's navigation and back button from fragment in android

Probably the cleanest solution:

abstract class NavigationChildFragment : Fragment() {

    abstract fun onCreateChildView(inflater: LayoutInflater,
                                   container: ViewGroup?,
                                   savedInstanceState: Bundle?): View?

    override fun onCreateView(inflater: LayoutInflater,
                              container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        val activity = activity as? MainActivity
        activity?.supportActionBar?.setDisplayHomeAsUpEnabled(true)
        setHasOptionsMenu(true)
        return onCreateChildView(inflater, container, savedInstanceState)
    }

    override fun onDestroyView() {
        val activity = activity as? MainActivity
        activity?.supportActionBar?.setDisplayHomeAsUpEnabled(false)
        setHasOptionsMenu(false)
        super.onDestroyView()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val activity = activity as? MainActivity
        return when (item.itemId) {
            android.R.id.home -> {
                activity?.onBackPressed()
                true
            }
            else              -> super.onOptionsItemSelected(item)
        }
    }
}

Just use this class as parent for all Fragments that should support navigation.

Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

The CLASS_H is an include guard; it's used to avoid the same header file being included multiple times (via different routes) within the same CPP file (or, more accurately, the same translation unit), which would lead to multiple-definition errors.

Include guards aren't needed on CPP files because, by definition, the contents of the CPP file are only read once.

You seem to have interpreted the include guards as having the same function as import statements in other languages (such as Java); that's not the case, however. The #include itself is roughly equivalent to the import in other languages.

drop down list value in asp.net

You can add an empty value such as:

ddlmonths.Items.Insert(0, new ListItem("Select Month", ""))

And just add a validation to prevent chosing empty option such as asp:RequiredFieldValidator.

Calling C/C++ from Python?

First you should decide what is your particular purpose. The official Python documentation on extending and embedding the Python interpreter was mentioned above, I can add a good overview of binary extensions. The use cases can be divided into 3 categories:

  • accelerator modules: to run faster than the equivalent pure Python code runs in CPython.
  • wrapper modules: to expose existing C interfaces to Python code.
  • low level system access: to access lower level features of the CPython runtime, the operating system, or the underlying hardware.

In order to give some broader perspective for other interested and since your initial question is a bit vague ("to a C or C++ library") I think this information might be interesting to you. On the link above you can read on disadvantages of using binary extensions and its alternatives.

Apart from the other answers suggested, if you want an accelerator module, you can try Numba. It works "by generating optimized machine code using the LLVM compiler infrastructure at import time, runtime, or statically (using the included pycc tool)".

How to install pip for Python 3.6 on Ubuntu 16.10?

Let's suppose that you have a system running Ubuntu 16.04, 16.10, or 17.04, and you want Python 3.6 to be the default Python.

If you're using Ubuntu 16.04 LTS, you'll need to use a PPA:

sudo add-apt-repository ppa:jonathonf/python-3.6  # (only for 16.04 LTS)

Then, run the following (this works out-of-the-box on 16.10 and 17.04):

sudo apt update
sudo apt install python3.6
sudo apt install python3.6-dev
sudo apt install python3.6-venv
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.6 get-pip.py
sudo ln -s /usr/bin/python3.6 /usr/local/bin/python3
sudo ln -s /usr/local/bin/pip /usr/local/bin/pip3

# Do this only if you want python3 to be the default Python
# instead of python2 (may be dangerous, esp. before 2020):
# sudo ln -s /usr/bin/python3.6 /usr/local/bin/python

When you have completed all of the above, each of the following shell commands should indicate Python 3.6.1 (or a more recent version of Python 3.6):

python --version   # (this will reflect your choice, see above)
python3 --version
$(head -1 `which pip` | tail -c +3) --version
$(head -1 `which pip3` | tail -c +3) --version

No Network Security Config specified, using platform default - Android Log

This occurs to the api 28 and above, because doesn't accept http anymore, you need to change if you want to accept http or localhost requests.

  1. Create an XML file Create XML file

  2. Add the following code on the new XML file you created Add base-config

  3. Add this on AndroidManifest.xml Add this code line

VBA Date as integer

Just use CLng(Date).

Note that you need to use Long not Integer for this as the value for the current date is > 32767

Setting attribute disabled on a SPAN element does not prevent click events

Try unbinding the event.

$("span").click(function(){
alert($(this).text());
    $("span").not($(this)).unbind('click');
});

Here is the fiddle

How to get the id of the element clicked using jQuery

You can get the id of clicked one by this code

$("span").on("click",function(e){
    console.log(e.target.Id);
});

Use .on() event for future compatibility

Error With Port 8080 already in use

In your apache conf folder, open the httpd file and look for 8080 port. Change 8080 to any port you like. I believe you will find 8080 on two places. Restart your server to see changes.

Execute a PHP script from another PHP script

You can invoke a PHP script manually from the command line

hello.php
<?php
 echo 'hello world!';
?>

Command line:
php hello.php

Output:
hello world!

See the documentation: http://php.net/manual/en/features.commandline.php


EDIT OP edited the question to add a critical detail: the script is to be executed by another script.

There are a couple of approaches. First and easiest, you could simply include the file. When you include a file, the code within is "executed" (actually, interpreted). Any code that is not within a function or class body will be processed immediately. Take a look at the documentation for include (docs) and/or require (docs) (note: include_once and require_once are related, but different in an important way. Check out the documents to understand the difference) Your code would look like this:

 include('hello.php');
 /* output
 hello world!
 */

Second and slightly more complex is to use shell_exec (docs). With shell_exec, you will call the php binary and pass the desired script as the argument. Your code would look like this:

$output = shell_exec('php hello.php');
echo "<pre>$output</pre>";
/* output
hello world!
*/

Finally, and most complex, you could use the CURL library to call the file as though it were requested via a browser. Check out the CURL library documentation here: http://us2.php.net/manual/en/ref.curl.php

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.myDomain.com/hello.php");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)

$output = curl_exec($ch);
curl_close($ch);
echo "<pre>$output</pre>";
/* output
hello world!
*/

Documentation for functions used

Import XXX cannot be resolved for Java SE standard classes

If the project is Maven, you can try this way :

  1. right click the "Maven Dependencies"-->"Build Path"-->"Remove from the build path";
  2. right click the project ,navigate to "Maven"--->"Update project....";

Then the import issue should be solved .

How to insert text in a td with id, using JavaScript

append a text node as follows

var td1 = document.getElementById('td1');
var text = document.createTextNode("some text");
td1.appendChild(text);

Updating state on props change in React Form

componentWillReceiveProps is being deprecated because using it "often leads to bugs and inconsistencies".

If something changes from the outside, consider resetting the child component entirely with key.

Providing a key prop to the child component makes sure that whenever the value of key changes from the outside, this component is re-rendered. E.g.,

<EmailInput
  defaultEmail={this.props.user.email}
  key={this.props.user.id}
/>

On its performance:

While this may sound slow, the performance difference is usually insignificant. Using a key can even be faster if the components have heavy logic that runs on updates since diffing gets bypassed for that subtree.

How to prevent sticky hover effects for buttons on touch devices

This worked for me: put the hover styling in a new class

.fakehover {background: red}

Then add / remove the class as and when required

$(".someclass > li").on("mouseenter", function(e) {
  $(this).addClass("fakehover");
});
$(".someclass > li").on("mouseleave", function(e) {
  $(this).removeClass("fakehover");
});

Repeat for touchstart and touchend events. Or whatever events you like to get the desired result, for example I wanted the hover effect to be toggled on a touch screen.

What is the difference between mocking and spying when using Mockito?

[Test double types]

Mock vs Spy

Mock is a bare double object. This object has the same methods signatures but realisation is empty and return default value - 0 and null

Spy is a cloned double object. New object is cloned based on a real object but you have a possibility to mock it

class A {
    String foo1() {
        foo2();
        return "RealString_1";
    }

    String foo2() {
        return "RealString_2";
    }

    void foo3() { foo4(); }

    void foo4() { }
}
@Test
public void testMockA() {
    //given
    A mockA = Mockito.mock(A.class);
    Mockito.when(mockA.foo1()).thenReturn("MockedString");

    //when
    String result1 = mockA.foo1();
    String result2 = mockA.foo2();

    //then
    assertEquals("MockedString", result1);
    assertEquals(null, result2);

    //Case 2
    //when
    mockA.foo3();

    //then
    verify(mockA).foo3();
    verify(mockA, never()).foo4();
}

@Test
public void testSpyA() {
    //given
    A spyA = Mockito.spy(new A());

    Mockito.when(spyA.foo1()).thenReturn("MockedString");

    //when
    String result1 = spyA.foo1();
    String result2 = spyA.foo2();

    //then
    assertEquals("MockedString", result1);
    assertEquals("RealString_2", result2);

    //Case 2
    //when
    spyA.foo3();

    //then
    verify(spyA).foo3();
    verify(spyA).foo4();
}

Why use 'virtual' for class properties in Entity Framework model definitions?

I understand the OPs frustration, this usage of virtual is not for the templated abstraction that the defacto virtual modifier is effective for.

If any are still struggling with this, I would offer my view point, as I try to keep the solutions simple and the jargon to a minimum:

Entity Framework in a simple piece does utilize lazy loading, which is the equivalent of prepping something for future execution. That fits the 'virtual' modifier, but there is more to this.

In Entity Framework, using a virtual navigation property allows you to denote it as the equivalent of a nullable Foreign Key in SQL. You do not HAVE to eagerly join every keyed table when performing a query, but when you need the information -- it becomes demand-driven.

I also mentioned nullable because many navigation properties are not relevant at first. i.e. In a customer / Orders scenario, you do not have to wait until the moment an order is processed to create a customer. You can, but if you had a multi-stage process to achieve this, you might find the need to persist the customer data for later completion or for deployment to future orders. If all nav properties were implemented, you'd have to establish every Foreign Key and relational field on the save. That really just sets the data back into memory, which defeats the role of persistence.

So while it may seem cryptic in the actual execution at run time, I have found the best rule of thumb to use would be: if you are outputting data (reading into a View Model or Serializable Model) and need values before references, do not use virtual; If your scope is collecting data that may be incomplete or a need to search and not require every search parameter completed for a search, the code will make good use of reference, similar to using nullable value properties int? long?. Also, abstracting your business logic from your data collection until the need to inject it has many performance benefits, similar to instantiating an object and starting it at null. Entity Framework uses a lot of reflection and dynamics, which can degrade performance, and the need to have a flexible model that can scale to demand is critical to managing performance.

To me, that always made more sense than using overloaded tech jargon like proxies, delegates, handlers and such. Once you hit your third or fourth programming lang, it can get messy with these.

How Long Does it Take to Learn Java for a Complete Newbie?

OK, based on some of the previous answers, I am expecting to get downvoted for this, but, I think you are delusional to think you can learn, on your own, how to program in Java in 10 weeks with no programming background. No person, with NO programming experience, other than some sort of prodigy, is going to learn to program in Java or almost any language in 10 weeks.

For clarity, copying and running hello world from a book does not make you a programmer. Hell, it will most likely take days just to get that working in some IDE.

Now, can you study and potentially pass some test? Maybe, but that depends on the depth and format of the test.

If I asked if I could become a doctor in 10 weeks, I would get laughed at for asking, so I am somewhat surprised at the answers that indicate that it is somewhat possible. I can stick a bandaid on my daughter now, but it hardly makes me a medical professional, it just means I managed their version of hello world.

Replace all spaces in a string with '+'

Do this recursively:

public String replaceSpace(String s){
    if (s.length() < 2) {
        if(s.equals(" "))
            return "+";
        else
            return s;
    }
    if (s.charAt(0) == ' ')
        return "+" + replaceSpace(s.substring(1));
    else
        return s.substring(0, 1) + replaceSpace(s.substring(1));
}

How do you easily create empty matrices javascript?

better. that exactly will work.

let mx = Matrix(9, 9);

function Matrix(w, h){
    let mx = Array(w);
    for(let i of mx.keys())
        mx[i] = Array(h);
    return mx;
}


what was shown

Array(9).fill(Array(9)); // Not correctly working

It does not work, because all cells are fill with one array

Ternary operator in AngularJS templates

There it is : ternary operator got added to angular parser in 1.1.5! see the changelog

Here is a fiddle showing new ternary operator used in ng-class directive.

ng-class="boolForTernary ? 'blue' : 'red'"

jQuery ajax upload file in asp.net mvc

Upload files using AJAX in ASP.Net MVC

Things have changed since HTML5

JavaScript

document.getElementById('uploader').onsubmit = function () {
    var formdata = new FormData(); //FormData object
    var fileInput = document.getElementById('fileInput');
    //Iterating through each files selected in fileInput
    for (i = 0; i < fileInput.files.length; i++) {
        //Appending each file to FormData object
        formdata.append(fileInput.files[i].name, fileInput.files[i]);
    }
    //Creating an XMLHttpRequest and sending
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/Home/Upload');
    xhr.send(formdata);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText);
        }
    }
    return false;
}   

Controller

public JsonResult Upload()
{
    for (int i = 0; i < Request.Files.Count; i++)
    {
        HttpPostedFileBase file = Request.Files[i]; //Uploaded file
        //Use the following properties to get file's name, size and MIMEType
        int fileSize = file.ContentLength;
        string fileName = file.FileName;
        string mimeType = file.ContentType;
        System.IO.Stream fileContent = file.InputStream;
        //To save file, use SaveAs method
        file.SaveAs(Server.MapPath("~/")+ fileName ); //File will be saved in application root
    }
    return Json("Uploaded " + Request.Files.Count + " files");
}

EDIT : The HTML

<form id="uploader">
    <input id="fileInput" type="file" multiple>
    <input type="submit" value="Upload file" />
</form>

Node.js - Find home directory in platform agnostic way

Well, it would be more accurate to rely on the feature and not a variable value. Especially as there are 2 possible variables for Windows.

function getUserHome() {
  return process.env.HOME || process.env.USERPROFILE;
}

EDIT: as mentioned in a more recent answer, https://stackoverflow.com/a/32556337/103396 is the right way to go (require('os').homedir()).

Integer expression expected error in shell script

If you are using -o (or -a), it needs to be inside the brackets of the test command:

if [ "$age" -le "7" -o "$age" -ge " 65" ]

However, their use is deprecated, and you should use separate test commands joined by || (or &&) instead:

if [ "$age" -le "7" ] || [ "$age" -ge " 65" ]

Make sure the closing brackets are preceded with whitespace, as they are technically arguments to [, not simply syntax.

In bash and some other shells, you can use the superior [[ expression as shown in kamituel's answer. The above will work in any POSIX-compliant shell.

jQuery/JavaScript to replace broken images

I believe this is what you're after: jQuery.Preload

Here's the example code from the demo, you specify the loading and not found images and you're all set:

jQuery('#images img').preload({
  placeholder:'placeholder.jpg',
  notFound:'notfound.jpg'
});

What is NODE_ENV and how to use it in Express?

Typically, you'd use the NODE_ENV variable to take special actions when you develop, test and debug your code. For example to produce detailed logging and debug output which you don't want in production. Express itself behaves differently depending on whether NODE_ENV is set to production or not. You can see this if you put these lines in an Express app, and then make a HTTP GET request to /error:

app.get('/error', function(req, res) {
  if ('production' !== app.get('env')) {
    console.log("Forcing an error!");
  }
  throw new Error('TestError');
});

app.use(function (req, res, next) {
  res.status(501).send("Error!")
})

Note that the latter app.use() must be last, after all other method handlers!

If you set NODE_ENV to production before you start your server, and then send a GET /error request to it, you should not see the text Forcing an error! in the console, and the response should not contain a stack trace in the HTML body (which origins from Express). If, instead, you set NODE_ENV to something else before starting your server, the opposite should happen.

In Linux, set the environment variable NODE_ENV like this:

export NODE_ENV='value'

How can I make my own event in C#?

I have a full discussion of events and delegates in my events article. For the simplest kind of event, you can just declare a public event and the compiler will create both an event and a field to keep track of subscribers:

public event EventHandler Foo;

If you need more complicated subscription/unsubscription logic, you can do that explicitly:

public event EventHandler Foo
{
    add
    {
        // Subscription logic here
    }
    remove
    {
        // Unsubscription logic here
    }
}

Setting UILabel text to bold

Use attributed string:

// Define attributes
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :Dictionary = [NSFontAttributeName : labelFont]

// Create attributed string
var attrString = NSAttributedString(string: "Foo", attributes:attributes)
label.attributedText = attrString

You need to define attributes.

Using attributed string you can mix colors, sizes, fonts etc within one text

Word count from a txt file program

#!/usr/bin/python
file=open("D:\\zzzz\\names2.txt","r+")
wordcount={}
for word in file.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1
for k,v in wordcount.items():
    print k, v