Programs & Examples On #Css

CSS (Cascading Style Sheets) is a representation style sheet language used for describing the look and formatting of HTML (Hyper Text Markup Language), XML (Extensible Markup Language) documents and SVG elements including (but not limited to) colors, layout, fonts, and animations. It also describes how elements should be rendered on screen, on paper, in speech, or on other media.

z-index not working with fixed positioning

This question can be solved in a number of ways, but really, knowing the stacking rules allows you to find the best answer that works for you.

Solutions

The <html> element is your only stacking context, so just follow the stacking rules inside a stacking context and you will see that elements are stacked in this order

  1. The stacking context’s root element (the <html> element in this case)
  2. Positioned elements (and their children) with negative z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)
  3. Non-positioned elements (ordered by appearance in the HTML)
  4. Positioned elements (and their children) with a z-index value of auto (ordered by appearance in the HTML)
  5. Positioned elements (and their children) with positive z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)

So you can

  1. set a z-index of -1, for #under positioned -ve z-index appear behind non-positioned #over element
  2. set the position of #over to relative so that rule 5 applies to it

The Real Problem

Developers should know the following before trying to change the stacking order of elements.

  1. When a stacking context is formed
    • By default, the <html> element is the root element and is the first stacking context
  2. Stacking order within a stacking context

The Stacking order and stacking context rules below are from this link

When a stacking context is formed

  • When an element is the root element of a document (the <html> element)
  • When an element has a position value other than static and a z-index value other than auto
  • When an element has an opacity value less than 1
  • Several newer CSS properties also create stacking contexts. These include: transforms, filters, css-regions, paged media, and possibly others. https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context
  • As a general rule, it seems that if a CSS property requires rendering in an offscreen context, it must create a new stacking context.

Stacking Order within a Stacking Context

The order of elements:

  1. The stacking context’s root element (the <html> element is the only stacking context by default, but any element can be a root element for a stacking context, see rules above)
    • You cannot put a child element behind a root stacking context element
  2. Positioned elements (and their children) with negative z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)
  3. Non-positioned elements (ordered by appearance in the HTML)
  4. Positioned elements (and their children) with a z-index value of auto (ordered by appearance in the HTML)
  5. Positioned elements (and their children) with positive z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)

Make an image responsive - the simplest way

Width: 100% will break it when you view on a wider are.

Following is Bootstrap's img-responsive

max-width: 100%; 
display:block; 
height: auto;

What is the HTML unicode character for a "tall" right chevron?

From the description and from the reference to the search box in the Ubuntu site, I gather that you actually want an arrowhead character pointing to the right. There are no Unicode characters designed to be used as arrowheads, but some of them may visually resemble an arrowhead.

In particular, if you draw your idea of the character at Shapecatcher.com, you will find many suggestions, such as “>” RIGHT-POINTING ANGLE BRACKET' (U+232A) and “?” MEDIUM RIGHT-POINTING ANGLE BRACKET ORNAMENT (U+276D).

Such characters generally have limited support in fonts, so you would need to carefully write a longish font-family list or to use a downloadable font. See my Guide to using special characters in HTML.

Especially if the intended use is as a symbol in a search box, as the reference to the Ubuntu page suggests, it is questionable whether you should use a character at all. It’s not really an element of text here; rather, a graphic symbol that accompanies text but isn’t a part of it. So why take all the trouble with using a character (safely), when it isn’t really a character?

When 1 px border is added to div, Div size increases, Don't want to do that

I needed to be able to "border" any element by adding a class and not affect its dimensions. A good solution for me was to use box-shadow. But in some cases the effect was not visible due to other siblings. So I combined both typical box-shadow as well as inset box-shadow. The result is a border look without changing any dimensions.

Values separated by comma. Here's a simple example:

.add_border {
    box-shadow:-1px 0 1px 1px rgba(0, 0, 0, 0.75), inset -1px 0 0 1px rgba(0, 0, 0, 0.75);
}

jsfiddle

Adjust for your preferred look and you're good to go!

Bootstrap push div content to new line

Do a row div.

Like this:

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

How to make certain text not selectable with CSS

The CSS below stops users from being able to select text.

-webkit-user-select: none; /* Safari */        
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+/Edge */
user-select: none; /* Standard */

To target IE9 downwards the html attribute unselectable must be used instead:

<p unselectable="on">Test Text</p>

How do I vertically align something inside a span tag?

Set padding-top to be an appropriate value to push the x down, then subtract the value you have for padding-top from the height.

X close button only using css

Here's a good drop-in solution for perfectly centered circular X icon buttons

  • Using only CSS
  • Not relying on a font
  • The thickness and length of the tines of the X can be configured without affecting centering, using width and height in the pseudo element rule .close::before, .close::after
  • Screen reader support using aria-label
  • Works on a light or dark background by using transparent grays and currentColor to adapt to the current text color specified on the button or an ancestor.

_x000D_
_x000D_
.close {
    vertical-align: middle;
    border: none;
    color: inherit;
    border-radius: 50%;
    background: transparent;
    position: relative;
    width: 32px;
    height: 32px;
    opacity: 0.6;
}
.close:focus,
.close:hover {
    opacity: 1;
    background: rgba(128, 128, 128, 0.5);
}
.close:active {
    background: rgba(128, 128, 128, 0.9);
}
/* tines of the X */
.close::before,
.close::after {
    content: " ";
    position: absolute;
    top: 50%;
    left: 50%;
    height: 20px;
    width: 4px;
    background-color: currentColor;
}
.close::before {
    transform: translate(-50%, -50%) rotate(45deg);
}
.close::after {
    transform: translate(-50%, -50%) rotate(-45deg);
}
_x000D_
<div style="padding: 15px">
    <button class="close" aria-label="Close"></button>
</div>
<div style="background: black; color: white; padding: 15px">
    <button class="close" aria-label="Close"></button>
</div>
<div style="background: orange; color: yellow; padding: 15px">
    <button class="close" aria-label="Close"></button>
</div>
_x000D_
_x000D_
_x000D_

Inline style to act as :hover in CSS

I'm afraid it can't be done, the pseudo-class selectors can't be set in-line, you'll have to do it on the page or on a stylesheet.

I should mention that technically you should be able to do it according to the CSS spec, but most browsers don't support it

Edit: I just did a quick test with this:

<a href="test.html" style="{color: blue; background: white} 
            :visited {color: green}
            :hover {background: yellow}
            :visited:hover {color: purple}">Test</a>

And it doesn't work in IE7, IE8 beta 2, Firefox or Chrome. Can anyone else test in any other browsers?

How can I control the width of a label tag?

Giving width to Label is not a proper way. you should take one div or table structure to manage this. but still if you don't want to change your whole code then you can use following code.

label {
  width:200px;
  float: left;
}

CSS - how to make image container width fixed and height auto stretched

What you're looking for is min-height and max-height.

img {
    max-width: 100%;
    height: auto;
}

.item {
    width: 120px;
    min-height: 120px;
    max-height: auto;
    float: left;
    margin: 3px;
    padding: 3px;
}

On a CSS hover event, can I change another div's styling?

Yes, you can do that, but only if #b is after #a in the HTML.

If #b comes immediately after #a: http://jsfiddle.net/u7tYE/

#a:hover + #b {
    background: #ccc
}

<div id="a">Div A</div>
<div id="b">Div B</div>

That's using the adjacent sibling combinator (+).

If there are other elements between #a and #b, you can use this: http://jsfiddle.net/u7tYE/1/

#a:hover ~ #b {
    background: #ccc
}

<div id="a">Div A</div>
<div>random other elements</div>
<div>random other elements</div>
<div>random other elements</div>
<div id="b">Div B</div>

That's using the general sibling combinator (~).

Both + and ~ work in all modern browsers and IE7+

If #b is a descendant of #a, you can simply use #a:hover #b.

ALTERNATIVE: You can use pure CSS to do this by positioning the second element before the first. The first div is first in markup, but positioned to the right or below the second. It will work as if it were a previous sibling.

How do you get centered content using Twitter Bootstrap?

As of February 2013, in some cases, I add a "centred" class to the "span" div:

<div class="container">
  <div class="row">
    <div class="span9 centred">
      This div will be centred.
    </div>
  </div>
</div>

and to CSS:

[class*="span"].centred {
  margin-left: auto;
  margin-right: auto;
  float: none;
}

The reason for this is because the span* div's get floated to the left, and the "auto margin" centering technique works only if the div is not floated.

Demo (on JSFiddle): http://jsfiddle.net/5RpSh/8/embedded/result/

JSFiddle: http://jsfiddle.net/5RpSh/8/

Changing :hover to touch/click for mobile devices

I got the same trouble, in mobile device with Microsoft's Edge browser. I can solve the problem with: aria-haspopup="true". It need to add to the div and the :hover, :active, :focus for the other mobile browsers.

Example html:

<div class="left_bar" aria-haspopup="true">

CSS:

.left_bar:hover, .left_bar:focus, .left_bar:active{
    left: 0%;
    }

Drop-down menu that opens up/upward with pure css

If we are use chosen dropdown list, then we can use below css(No JS/JQuery require)

<select chosen="{width: '100%'}" ng- 
   model="modelName" class="form-control input- 
   sm"
   ng- 
   options="persons.persons as 
   persons.persons for persons in 
   jsonData"
   ng- 
   change="anyFunction(anyParam)" 
   required>
   <option value=""> </option>
</select>
<style>   
.chosen-container .chosen-drop {
    border-bottom: 0;
    border-top: 1px solid #aaa;
    top: auto;
    bottom: 40px;
}

.chosen-container.chosen-with-drop .chosen-single {
    border-top-left-radius: 0px;
    border-top-right-radius: 0px;

    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;

    background-image: none;
}

.chosen-container.chosen-with-drop .chosen-drop {
    border-bottom-left-radius: 0px;
    border-bottom-right-radius: 0px;

    border-top-left-radius: 5px;
    border-top-right-radius: 5px;

    box-shadow: none;

    margin-bottom: -16px;
}
</style>

Google Chrome form autofill and its yellow background

I fixed this issue for a password field i have like this:

Set the input type to text instead of password

Remove the input text value with jQuery

Convert the input type to password with jQuery

<input type="text" class="remove-autofill">

$('.js-remove-autofill').val('');    
$('.js-remove-autofill').attr('type', 'password');

CSS transition between left -> right and top -> bottom positions

This worked for me on Chromium. The % for translate is in reference to the size of the bounding box of the element it is applied to so it perfectly gets the element to the lower right edge while not having to switch which property is used to specify it's location.

topleft {
  top: 0%;
  left: 0%;
}
bottomright {
  top: 100%;
  left: 100%;
  -webkit-transform: translate(-100%,-100%);
}

How to make a floated div 100% height of its parent?

I made an example resolving your problem.

You have to make a wrapper, float it, then position absolute your div and give to it 100% height.

HTML

<div class="container">
    <div class="left">"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." </div>
  <div class="right-wrapper">
    <div class="right">"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." </div>
  </div>
  <div class="clear">&nbsp;</div>
</div>

CSS:

.container {
    width: 100%;
    position:relative;
}
.left {
    width: 50%;
    background-color: rgba(0, 0, 255, 0.6);
    float: left;
}
.right-wrapper {
    width: 48%;
    float: left;
}
.right {
    height: 100%;
    position: absolute;
}

Explanation: The .right div is absolutely positioned. That means that its width and height, and top and left positiones will be calculed based on the first parent div absolutely or relative positioned ONLY if width or height properties are explicitly declared in CSS; if they aren't explicty declared, those properties will be calculed based on the parent container (.right-wrapper).

So, the 100% height of the DIV will be calculed based on .container final height, and the final position of .right position will be calculed based on the parent container.

CSS text-transform capitalize on all caps

You can almost do it with:

.link {
  text-transform: lowercase;
}
.link:first-letter,
.link:first-line {
  text-transform: uppercase;
}

It will give you the output:

Small Caps
All Caps

Why not use tables for layout in HTML?

Flex has a tag for laying things out in vertical columns. I don't think they got the whole layout/content thing right either to be honest, but at least they've resolved that issue.

Like many of the people frustrated with CSS I've also looked far and wide for an easy answer, was duped into feeling elated when I thought I had found it, and then had my hopes dashed to pieces when I opened the page in Chrome. I'm definitely not skilled enough to say it's not possible, but I haven't seen anyone offer up sample code for peer review proving unequivocally that it can be done reliably.

So can someone from the CSS side of this island recommend a mindset/methodology for laying out vertical columns? I've tried absolute positioning in second and third rows, but i end up with stuff overlapping everywhere and float has similar issues if the page is shrunk down.

If there was an answer to this I'd be ecstatic to -do the right thing- Just tell me something like, "Hey have you tried **flow:vertical|horizontal" and I'm totally out of your hair.

Determine if an element has a CSS class with jQuery

In the interests of helping anyone who lands here but was actually looking for a jQuery free way of doing this:

element.classList.contains('your-class-name')

How can I increase a scrollbar's width using CSS?

Yes.

If the scrollbar is not the browser scrollbar, then it will be built of regular HTML elements (probably divs and spans) and can thus be styled (or will be Flash, Java, etc and can be customized as per those environments).

The specifics depend on the DOM structure used.

CSS two divs next to each other

You can use flexbox to lay out your items:

_x000D_
_x000D_
#parent {_x000D_
  display: flex;_x000D_
}_x000D_
#narrow {_x000D_
  width: 200px;_x000D_
  background: lightblue;_x000D_
  /* Just so it's visible */_x000D_
}_x000D_
#wide {_x000D_
  flex: 1;_x000D_
  /* Grow to rest of container */_x000D_
  background: lightgreen;_x000D_
  /* Just so it's visible */_x000D_
}
_x000D_
<div id="parent">_x000D_
  <div id="wide">Wide (rest of width)</div>_x000D_
  <div id="narrow">Narrow (200px)</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This is basically just scraping the surface of flexbox. Flexbox can do pretty amazing things.


For older browser support, you can use CSS float and a width properties to solve it.

_x000D_
_x000D_
#narrow {_x000D_
  float: right;_x000D_
  width: 200px;_x000D_
  background: lightblue;_x000D_
}_x000D_
#wide {_x000D_
  float: left;_x000D_
  width: calc(100% - 200px);_x000D_
  background: lightgreen;_x000D_
}
_x000D_
<div id="parent">_x000D_
  <div id="wide">Wide (rest of width)</div>_x000D_
  <div id="narrow">Narrow (200px)</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to customize Bootstrap 3 tab color

I think you should edit the anchor tag on bootstrap.css. Otherwise give customized style to the anchor tag with !important (to override the default style on bootstrap.css).

Example code

_x000D_
_x000D_
.nav {_x000D_
    background-color: #000 !important;_x000D_
}_x000D_
_x000D_
.nav>li>a {_x000D_
    background-color: #666 !important;_x000D_
    color: #fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">_x000D_
_x000D_
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div role="tabpanel">_x000D_
_x000D_
  <!-- Nav tabs -->_x000D_
  <ul class="nav nav-tabs" role="tablist">_x000D_
    <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>_x000D_
    <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>_x000D_
    <li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>_x000D_
    <li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>_x000D_
  </ul>_x000D_
_x000D_
  <!-- Tab panes -->_x000D_
  <div class="tab-content">_x000D_
    <div role="tabpanel" class="tab-pane active" id="home">...</div>_x000D_
    <div role="tabpanel" class="tab-pane" id="profile">tab1</div>_x000D_
    <div role="tabpanel" class="tab-pane" id="messages">tab2</div>_x000D_
    <div role="tabpanel" class="tab-pane" id="settings">tab3</div>_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle: http://jsfiddle.net/zjjpocv6/2/

Center form submit buttons HTML / CSS

http://jsfiddle.net/SebastianPataneMasuelli/rJxQC/

i just wrapped a div around them and made it align center. then you don't need any css on the buttons to center them.

<div class="buttonHolder">
  <input value="Search" title="Search" type="submit" id="btn_s"> 
  <input value="I'm Feeling Lucky" title="I'm Feeling Lucky" name="lucky" type="submit" id="btn_i">
</div>

.buttonHolder{ text-align: center; }

Is it possible to set the stacking order of pseudo-elements below their parent element?

I know this question is ancient and has an accepted answer, but I found a better solution to the problem. I am posting it here so I don't create a duplicate question, and the solution is still available to others.

Switch the order of the elements. Use the :before pseudo-element for the content that should be underneath, and adjust margins to compensate. The margin cleanup can be messy, but the desired z-index will be preserved.

I've tested this with IE8 and FF3.6 successfully.

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

I solved the issue by using overflow-x:hidden; as follows

@media screen and (max-width: 441px){

#end_screen { (NOte:-the end_screen is the wrapper div for all other div's inside it.)
  overflow-x: hidden;
   }
 }

structure is as follows

1st div end_screen >> inside it >> end_screen_2(div) >> inside it >> end_screen_2.

'end_screen is the wrapper of end_screen_1 and end_screen_2 div's

Pure css close button

Edit: Updated css to match with what you have..

DEMO

HTML

<div>
    <span class="close-btn"><a href="#">X</a></span>
</div>

CSS

.close-btn {
    border: 2px solid #c2c2c2;
    position: relative;
    padding: 1px 5px;
    top: -20px;
    background-color: #605F61;
    left: 198px;
    border-radius: 20px;
}

.close-btn a {
    font-size: 15px;
    font-weight: bold;
    color: white;
    text-decoration: none;
}

Fix columns in horizontal scrolling

Solved using JavaScript + jQuery! I just need similar solution to my project but current solution with HTML and CSS is not ok for me because there is issue with column height + I need more then one column to be fixed. So I create simple javascript solution using jQuery

You can try it here https://jsfiddle.net/kindrosker/ffwqvntj/

All you need is setup home many columsn will be fixed in data-count-fixed-columns parameter

<table class="table" data-count-fixed-columns="2" cellpadding="0" cellspacing="0">

and run js function

app_handle_listing_horisontal_scroll($('#table-listing'))

How to load CSS Asynchronously

you can try to get it in a lot of ways :

1.Using media="bogus" and a <link> at the foot

<head>
    <!-- unimportant nonsense -->
    <link rel="stylesheet" href="style.css" media="bogus">
</head>
<body>
    <!-- other unimportant nonsense, such as content -->
    <link rel="stylesheet" href="style.css">
</body>

2.Inserting DOM in the old way

<script type="text/javascript">
(function(){
  var bsa = document.createElement('script');
     bsa.type = 'text/javascript';
     bsa.async = true;
     bsa.src = 'https://s3.buysellads.com/ac/bsa.js';
  (document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(bsa);
})();
</script>

3.if you can try plugins you could try loadCSS

<script>
  // include loadCSS here...
  function loadCSS( href, before, media ){ ... }
  // load a file
  loadCSS( "path/to/mystylesheet.css" );
</script>

How to change border color of textarea on :focus

Try out this probably it will work

input{
outline-color: #fff //your color
outline-style: none // it depend on you 
}

Can I use a :before or :after pseudo-element on an input field?

try next:

_x000D_
_x000D_
label[for="userName"] {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
label[for="userName"]::after {_x000D_
  content: '[after]';_x000D_
  width: 22px;_x000D_
  height: 22px;_x000D_
  display: inline-block;_x000D_
  position: absolute;_x000D_
  right: -30px;_x000D_
}
_x000D_
<label for="userName">_x000D_
 Name: _x000D_
 <input type="text" name="userName" id="userName">_x000D_
 </label>
_x000D_
_x000D_
_x000D_

jQuery trigger file input

Correct code:

<style>
    .upload input[type='file']{
        position: absolute;
        float: left;
        opacity: 0; /* For IE8 "Keep the IE opacity settings in this order for max compatibility" */
        -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; /* For IE5 - 7 */
        filter: alpha(opacity=0);
        width: 100px; height: 30px; z-index: 51
    }
    .upload input[type='button']{
        width: 100px;
        height: 30px;
        z-index: 50;
    }
    .upload input[type='submit']{
        display: none;
    }
    .upload{
        width: 100px; height: 30px
    }
</style>
<div class="upload">
    <input type='file' ID="flArquivo" onchange="upload();" />
    <input type="button" value="Selecionar" onchange="open();" />
    <input type='submit' ID="btnEnviarImagem"  />
</div>

<script type="text/javascript">
    function open() {
        $('#flArquivo').click();
    }
    function upload() {
        $('#btnEnviarImagem').click();
    }
</script>

How to style a disabled checkbox?

You can select it using css like this:

input[disabled] { /* css attributes */ }

Darken CSS background image?

You can use the CSS3 Linear Gradient property along with your background-image like this:

#landing-wrapper {
    display:table;
    width:100%;
    background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
    background-position:center top;
    height:350px;
}

Here's a demo:

_x000D_
_x000D_
#landing-wrapper {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
  background-position: center top;_x000D_
  height: 350px;_x000D_
  color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
_x000D_
_x000D_

css selector to match an element without attribute x

:not selector:

input:not([type]), input[type='text'], input[type='password'] {
    /* style here */
}

Support: in Internet Explorer 9 and higher

How to position a div scrollbar on the left hand side?

Kind of an old question, but I thought I should throw in a method which wasn't widely available when this question was asked.

You can reverse the side of the scrollbar in modern browsers using transform: scaleX(-1) on a parent <div>, then apply the same transform to reverse a child, "sleeve" element.

HTML

<div class="parent">
  <div class="sleeve">
    <!-- content -->
  </div>
</div>

CSS

.parent {
  overflow: auto;
  transform: scaleX(-1); //Reflects the parent horizontally
}

.sleeve {
  transform: scaleX(-1); //Flips the child back to normal
}

Note: You may need to use an -ms-transform or -webkit-transform prefix for browsers as old as IE 9. Check CanIUse and click "show all" to see older browser requirements.

Have a div cling to top of screen if scrolled down past it

Use position:fixed; and set the top:0;left:0;right:0;height:100px; and you should be able to have it "stick" to the top of the page.

<div style="position:fixed;top:0;left:0;right:0;height:100px;">Some buttons</div>

What replaces cellpadding, cellspacing, valign, and align in HTML5 tables?

/* cellpadding */
th, td { padding: 5px; }

/* cellspacing */
table { border-collapse: separate; border-spacing: 5px; } /* cellspacing="5" */
table { border-collapse: collapse; border-spacing: 0; }   /* cellspacing="0" */

/* valign */
th, td { vertical-align: top; }

/* align (center) */
table { margin: 0 auto; }

Adding horizontal spacing between divs in Bootstrap 3

From what I understand you want to make a navigation bar or something similar to it. What I recommend doing is making a list and editing the items from there. Just try this;

<ul>
    <li class='item col-md-12 panel' id='gameplay-title'>Title</li>
    <li class='item col-md-6 col-md-offset-3 panel' id='gameplay-scoreboard'>Scoreboard</li>
</ul>

And so on... To add more categories add another ul in there. Now, for the CSS you just need this;

ul {
    list-style: none;
}
.item {
    display: inline;
    padding-right: 20px;
}

CSS: how to add white space before element's content?

/* Most Accurate Setting if you only want
   to do this with CSS Pseudo Element */
p:before { 
   content: "\00a0";
   padding-right: 5px; /* If you need more space b/w contents */
}

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>

iPhone 5 CSS media query

Another useful media feature is device-aspect-ratio.

Note that the iPhone 5 does not have a 16:9 aspect ratio. It is in fact 40:71.

iPhone < 5:
@media screen and (device-aspect-ratio: 2/3) {}

iPhone 5:
@media screen and (device-aspect-ratio: 40/71) {}

iPhone 6:
@media screen and (device-aspect-ratio: 375/667) {}

iPhone 6 Plus:
@media screen and (device-aspect-ratio: 16/9) {}

iPad:
@media screen and (device-aspect-ratio: 3/4) {}

Reference:
Media Queries @ W3C
iPhone Model Comparison
Aspect Ratio Calculator

React img tag issue with url and class

Remember that your img is not really a DOM element but a javascript expression.

  1. This is a JSX attribute expression. Put curly braces around the src string expression and it will work. See http://facebook.github.io/react/docs/jsx-in-depth.html#attribute-expressions

  2. In javascript, the class attribute is reference using className. See the note in this section: http://facebook.github.io/react/docs/jsx-in-depth.html#react-composite-components

    /** @jsx React.DOM */
    
    var Hello = React.createClass({
        render: function() {
            return <div><img src={'http://placehold.it/400x20&text=slide1'} alt="boohoo" className="img-responsive"/><span>Hello {this.props.name}</span></div>;
        }
    });
    
    React.renderComponent(<Hello name="World" />, document.body);
    

Pure CSS animation visibility with delay

Use animation-delay:

div {
    width: 100px;
    height: 100px;
    background: red;
    opacity: 0;

    animation: fadeIn 3s;
    animation-delay: 5s;
    animation-fill-mode: forwards;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

Fiddle

How to set a border for an HTML div tag

 .centerImge {
        display: block;
        margin-left: auto;
        margin-right: auto;
        width: 50%;
        height:50%;
    }
 <div>
 @foreach (var item in Model)
{
<span> <img src="@item.Thumbnail"  class="centerImge" /></span>
  <h3 style="text-align:center">  @item.CategoryName</h3>
}
 </div>

Remove white space above and below large text in an inline-block element

I had a similar problem. As you increase the line-height the space above the text increases. It's not padding but it will affect the vertical space between content. I found that adding a -ve top margin seemed to do the trick. It had to be done for all of the different instances of line-height and it varies with font-family too. Maybe this is something which designers need to be more aware of when passing design requirements (?) So for a particular instance of font-family and line-height:

h1 {
    font-family: 'Garamond Premier Pro Regular';
    font-size: 24px;
    color: #001230;
    line-height: 29px;
    margin-top: -5px;    /* CORRECTION FOR LINE-HEIGHT */
}

Bootstrap Dropdown menu is not working

My bootstrap version was pointing to bootstap4-alpha,

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"
integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn"
crossorigin="anonymous"></script>

changed to 4-beta

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"
        integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1"
        crossorigin="anonymous"></script>

and it started working

How do you make div elements display inline?

That's something else then:

_x000D_
_x000D_
div.inline { float:left; }_x000D_
.clearBoth { clear:both; }
_x000D_
<div class="inline">1<br />2<br />3</div>_x000D_
<div class="inline">1<br />2<br />3</div>_x000D_
<div class="inline">1<br />2<br />3</div>_x000D_
<br class="clearBoth" /><!-- you may or may not need this -->
_x000D_
_x000D_
_x000D_

CSS change button style after click

What is the code of your button? If it's an a tag, then you could do this:

_x000D_
_x000D_
a {_x000D_
  padding: 5px;_x000D_
  background: green;_x000D_
}_x000D_
a:visited {_x000D_
  background: red;_x000D_
}
_x000D_
<a href="#">A button</a>
_x000D_
_x000D_
_x000D_

Or you could use jQuery to add a class on click, as below:

_x000D_
_x000D_
$("#button").click(function() {_x000D_
  $("#button").addClass('button-clicked');_x000D_
});
_x000D_
.button-clicked {_x000D_
  background: red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="button">Button</button>
_x000D_
_x000D_
_x000D_

how to display a div triggered by onclick event

function showstuff(boxid){
   document.getElementById(boxid).style.visibility="visible";
}
<button onclick="showstuff('id_to_show');" />

This will help you, I think.

CSS property to pad text inside of div

Padding is a way to add kind of a margin inside the Div.
Just Use

div { padding-left: 20px; }

And to mantain the size, you would have to -20px from the original width of the Div.

JQuery addclass to selected div, remove class if another div is selected

Are you looking something like this short and effective:

http://jsfiddle.net/XBfMV/

$('div').on('click',function(){
  $('div').removeClass('active');
  $(this).addClass('active');
});

you can simply add a general class 'active' for selected div. when a div is clicked, remove the 'active' class, and add it to the clicked div.

Separators for Navigation

Add the separator to the li background and make sure the link doesn't expand to cover the separator, which means the separator won't be click-able.

CSS for the "down arrow" on a <select> element?

No, the down arrow is a browser element. It's built in [and different] in every browser. You can, however, replace the select box with a custom drop down box using javascript.

Jan Hancic mentioned a jQuery plugin to do just that.

Use CSS to remove the space between images

I found that the only option that worked for me was

font-size:0;

I was also using overflow and white-space: nowrap; float: left; seems to mess things up

Creating a Zoom Effect on an image on hover using CSS?

  <div class="item">
  <img src="yamahdi1.jpg" alt="pepsi" width="50" height="58">
  <img src="yamahdi.jpg" alt="pepsi" width="50" height="58">
  <div class="item-overlay top"></div>

css:

.item img {

  -moz-transition: all 0.3s;
  -webkit-transition: all 0.3s;
  transition: all 0.3s;
}
.item img:hover {
  -moz-transform: scale(1.1);
  -webkit-transform: scale(1.1);
  transform: scale(1.1);
}

Using a custom (ttf) font in CSS

This is not a system font. this font is not supported in other systems. you can use font-face, convert font from this Site or from this

enter image description here

Twitter Bootstrap scrollable table rows and fixed header

Just stack two bootstrap tables; one for columns, the other for content. No plugins, just pure bootstrap (and that ain't no bs, haha!)

  <table id="tableHeader" class="table" style="table-layout:fixed">
        <thead>
            <tr>
                <th>Col1</th>
                ...
            </tr>
        </thead>
  </table>
  <div style="overflow-y:auto;">
    <table id="tableData" class="table table-condensed" style="table-layout:fixed">
        <tbody>
            <tr>
                <td>data</td>
                ...
            </tr>
        </tbody>
    </table>
 </div>

Demo JSFiddle

The content table div needs overflow-y:auto, for vertical scroll bars. Had to use table-layout:fixed, otherwise, columns did not line up. Also, had to put the whole thing inside a bootstrap panel to eliminate space between the tables.

Have not tested with custom column widths, but provided you keep the widths consistent between the tables, it should work.

    // ADD THIS JS FUNCTION TO MATCH UP COL WIDTHS
    $(function () {

        //copy width of header cells to match width of cells with data
        //so they line up properly
        var tdHeader = document.getElementById("tableHeader").rows[0].cells;
        var tdData = document.getElementById("tableData").rows[0].cells;

        for (var i = 0; i < tdData.length; i++)
            tdHeader[i].style.width = tdData[i].offsetWidth + 'px';

    });

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

Rucksack is brilliant, but you don't necessarily have to resort to build tools like Gulp or Grunt etc.

I made a demo using CSS Custom Properties (CSS Variables) to easily control the min and max font sizes.

Like so:

* {
  /* Calculation */
  --diff: calc(var(--max-size) - var(--min-size));
  --responsive: calc((var(--min-size) * 1px) + var(--diff) * ((100vw - 420px) / (1200 - 420))); /* Ranges from 421px to 1199px */
}

h1 {
  --max-size: 50;
  --min-size: 25;
  font-size: var(--responsive);
}

h2 {
  --max-size: 40;
  --min-size: 20;
  font-size: var(--responsive);
}

How to programmatically disable page scrolling with jQuery

I think the best and clean solution is:

window.addEventListener('scroll',() => {
    var x = window.scrollX;
    var y = window.scrollY;
    window.scrollTo(x,y);
});

And with jQuery:

$(window).on('scroll',() => {
    var x = window.scrollX;
    var y = window.scrollY;
    window.scrollTo(x,y)
})

Those event listener should block scrolling. Just remove them to re enable scrolling

Difference between <span> and <div> with text-align:center;?

Spans are inline, divs are block elements. i.e. spans are only as wide as their respective content. You can align the span inside the surrounding container (if it's a block container), but you can't align the content.

Span is primarily used for formatting purposes. If you want to arrange or position the contents, use div, p or some other block element.

How to make blinking/flashing text with CSS 3

It works for me by using class=blink for the respective element(s)

Simple JS Code

// Blink
      setInterval(function()
        {

        setTimeout(function()
        {

        //$(".blink").css("color","rgba(0,0,0,0.1)"); // If you want simply black/white blink of text
        $(".blink").css("visibility","hidden"); // This is for Visibility of the element  


        },900);


        //$(".blink").css("color","rgba(0,0,0,1)");  // If you want simply black/white blink of text
        $(".blink").css("visibility","visible");  // This is for Visibility of the element

        },1000);

css 100% width div not taking up full width of parent

html, body{ 
  width:100%;
}

This tells the html to be 100% wide. But 100% refers to the whole browser window width, so no more than that.

You may want to set a min width instead.

html, body{ 
  min-width:100%;
}

So it will be 100% as a minimum, bot more if needed.

How do I vertically center text with CSS?

.element{position: relative;top: 50%;transform: translateY(-50%);}

Add this small code in the CSS property of your element. It is awesome. Try it!

CSS3 background image transition

Try this, will make the background animated worked on web but hybrid mobile app not working

@-webkit-keyframes breath {
 0%   {  background-size: 110% auto; }
 50%  {  background-size: 140% auto; }
 100% {  background-size: 110% auto; }      
}
body {
   -webkit-animation: breath 15s linear infinite;
   background-image: url(images/login.png);
    background-size: cover;
}

HTML Table cell background image alignment

use like this your inline css

<td width="178" rowspan="3" valign="top" 
align="right" background="images/left.jpg" 
style="background-repeat:background-position: right top;">
</td>

Make Iframe to fit 100% of container's remaining height

It will work with below mentioned code

<iframe src="http: //www.google.com.tw"style="position: absolute; height: 100%; border: none"></iframe>

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

There might be a fix to <input type="button"> - but if there is, I don't know it.

Otherwise, a good option seems to be to replace it with a carefully styled a element.

Example: http://jsfiddle.net/Uka5v/

.button {
    background-color: #E3E1B8; 
    padding: 2px 4px;
    font: 13px sans-serif;
    text-decoration: none;
    border: 1px solid #000;
    border-color: #aaa #444 #444 #aaa;
    color: #000
}

Upsides include that the a element will style consistently between different (older) versions of Internet Explorer without any extra work, and I think my link looks nicer than that button :)

How do I change Bootstrap 3 column order on mobile layout?

Starting with the mobile version first, you can achieve what you want, most of the time.

Examples here:

http://jsbin.com/wulexiq/edit?html,css,output

<div class="container">
      <h1>PUSH - PULL Bootstrap demo</h1>
    <h2>Version 1:</h2>

    <div class="row">

      <div class="col-xs-12 col-sm-5 col-sm-push-3 green">
        IN MIDDLE ON SMALL/MEDIUM/LARGE SCREEN
        <hr> TOP ROW XS-SMALL SCREEN
      </div>

      <div class="col-xs-12 col-sm-4 col-sm-push-3 gold">
        TO THE RIGHT ON SMALL/MEDIUM/LARGE SCREEN
        <hr> MIDDLE ROW ON XS-SMALL
      </div>

      <div class="col-xs-12 col-sm-3 col-sm-pull-9 red">
        TO THE LEFT ON SMALL/MEDIUM/LARGE SCREEN
        <hr> BOTTOM ROW ON XS-SMALL
      </div>

    </div>

    <h2>Version 2:</h2>

    <div class="row">

      <div class="col-xs-12 col-sm-4 col-sm-push-8 yellow">
        TO THE RIGHT ON SMALL/MEDIUM/LARGE SCREEN
        <hr> TOP ROW ON XS-SMALL
      </div>

      <div class="col-xs-12 col-sm-4 col-sm-pull-4 blue">
        TO THE LEFT ON SMALL/MEDIUM/LARGE SCREEN
        <hr> MIDDLE ROW XS-SMALL SCREEN
      </div>

      <div class="col-xs-12 col-sm-4 col-sm-pull-4 pink">
        IN MIDDLE ON SMALL/MEDIUM/LARGE SCREEN
        <hr> BOTTOM ROW ON XS-SMALL
      </div>

    </div>

    <h2>Version 3:</h2>

    <div class="row">

      <div class="col-xs-12 col-sm-5 cyan">
        TO THE LEFT ON SMALL/MEDIUM/LARGE SCREEN TOP ROW ON XS-SMALL
      </div>

      <div class="col-xs-12 col-sm-3 col-sm-push-4 orange">
        TO THE RIGHT ON SMALL/MEDIUM/LARGE SCREEN
        <hr> MIDDLE ROW ON XS-SMALL
      </div>

      <div class="col-xs-12 col-sm-4 col-sm-pull-3 brown">
        IN THE MIDDLE ON SMALL/MEDIUM/LARGE SCREEN
        <hr> BOTTOM ROW XS-SMALL SCREEN
      </div>

    </div>

    <h2>Version 4:</h2>
    <div class="row">

      <div class="col-xs-12 col-sm-4 col-sm-push-8 darkblue">
        TO THE RIGHT ON SMALL/MEDIUM/LARGE SCREEN
        <hr> TOP ROW XS-SMALL SCREEN
      </div>

      <div class="col-xs-12 col-sm-4 beige">
        MIDDLE ON SMALL/MEDIUM/LARGE SCREEN
        <hr> MIDDLE ROW ON XS-SMALL
      </div>

      <div class="col-xs-12 col-sm-4 col-sm-pull-8 silver">
        TO THE LEFT ON SMALL/MEDIUM/LARGE SCREEN
        <hr> BOTTOM ROW ON XS-SMALL
      </div>

    </div>

  </div>

How can I set the font-family & font-size inside of a div?

You need a semicolon after font-family: Arial, Helvetica, sans-serif. This will make your updated code the following:

<!DOCTYPE>
<html>
    <head>
        <title>DIV Font</title>

        <style>
            .my_text
            {
                font-family:    Arial, Helvetica, sans-serif;
                font-size:      40px;
                font-weight:    bold;
            }
        </style>
    </head>

    <body>
        <div class="my_text">some text</div>
    </body>
</html>

What is a user agent stylesheet?

Answering the question in title, what is the user agent stylesheet, the set of default styles in the browser: Here are some of them (and most relevant ones also in today's web):

Personal opinion: Don't fight with them. They have good default values, for example, in rtl/bidi cases and are consistent nowadays. Reset what you see irrelevant to you, not all of them at once.

How to remove focus border (outline) around text/input boxes? (Chrome)

This will definitely work. Orange outline will not show anymore.. Common for all tags:

*:focus {
    outline: none;
}

Specific to some tag, ex: input tag

input:focus {
   outline:none;
}

Left/Right float button inside div

Change display:inline to display:inline-block

.test {
  width:200px;
  display:inline-block;
  overflow: auto;
  white-space: nowrap;
  margin:0px auto;
  border:1px red solid;
}

Space between two rows in a table?

since I have a background image behind the table, faking it with white padding wouldn't work. I opted to put an empty row in-between each row of content:

<tr class="spacer"><td></td></tr>

then use css to give the spacer rows a certain height and transparent background.

What is the difference between "screen" and "only screen" in media queries?

Let's break down your examples one by one.

@media (max-width:632px)

This one is saying for a window with a max-width of 632px that you want to apply these styles. At that size you would be talking about anything smaller than a desktop screen in most cases.

@media screen and (max-width:632px)

This one is saying for a device with a screen and a window with max-width of 632px apply the style. This is almost identical to the above except you are specifying screen as opposed to the other available media types the most common other one being print.

@media only screen and (max-width:632px)

Here is a quote straight from W3C to explain this one.

The keyword ‘only’ can also be used to hide style sheets from older user agents. User agents must process media queries starting with ‘only’ as if the ‘only’ keyword was not present.

As there is no such media type as "only", the style sheet should be ignored by older browsers.

Here's the link to that quote that is shown in example 9 on that page.

Hopefully this sheds some light on media queries.

EDIT:

Be sure to check out @hybrids excellent answer on how the only keyword is really handled.

Font Awesome 5 font-family issue

I had tried all above the solutions for Font Awesome 5 but it wasn't working for me. :(

Finally, I got a solution!

Just use font-family: "Font Awesome 5 Pro"; in your CSS instead of using font-family: "Font Awesome 5 Free OR Solids OR Brands";

How do I make a text input non-editable?

<input type="text" value="3" class="field left" readonly>

You could see in https://www.w3schools.com/tags/att_input_readonly.asp

The method to set "readonly":

$("input").attr("readonly", true)

to cancel "readonly"(work in jQuery):

$("input").attr("readonly", false)

move div with CSS transition

I added the vendor prefixes, and changed the animation to all, so you have both opacity and width that are animated.

Is this what you're looking for ? http://jsfiddle.net/u2FKM/3/

css transition opacity fade background

It's not fading to "black transparent" or "white transparent". It's just showing whatever color is "behind" the image, which is not the image's background color - that color is completely hidden by the image.

If you want to fade to black(ish), you'll need a black container around the image. Something like:

.ctr {
    margin: 0; 
    padding: 0;
    background-color: black;
    display: inline-block;
}

and

<div class="ctr"><img ... /></div>

How to put a div in center of browser using CSS?

<html>
<head>
<style>
*
{
    margin:0;
    padding:0;
}

html, body
{
    height:100%;
}

#distance
{
    width:1px;
    height:50%;
    margin-bottom:-300px;
    float:left;
}


#something
{
    position:relative;
    margin:0 auto;
    text-align:left;
    clear:left;
    width:800px;
    min-height:600px;
    height:auto;
    border: solid 1px #993333;
    z-index: 0;
}

/* for Internet Explorer */
* html #something{
height: 600px;
}
</style>

</head>
<body>

<div id="distance"></div>

<div id="something">
</div>
</body>

</html>

Tested in FF2-3, IE6-7, Opera and works well!

How to force the browser to reload cached CSS and JavaScript files

Google Chrome has the Hard Reload as well as the Empty Cache and Hard Reload option. You can click and hold the reload button (in Inspect Mode) to select one.

Remove IE10's "clear field" X button on certain inputs?

You should style for ::-ms-clear (http://msdn.microsoft.com/en-us/library/windows/apps/hh465740.aspx):

::-ms-clear {
   display: none;
}

And you also style for ::-ms-reveal pseudo-element for password field:

::-ms-reveal {
   display: none;
}

position: fixed doesn't work on iPad and iPhone

A lot of mobile browsers deliberately do not support position:fixed; on the grounds that fixed elements could get in the way on a small screen.

The Quirksmode.org site has a very good blog post that explains the problem: http://www.quirksmode.org/blog/archives/2010/12/the_fifth_posit.html

Also see this page for a compatibility chart showing which mobile browsers support position:fixed;: http://www.quirksmode.org/m/css.html

(but note that the mobile browser world is moving very quickly, so tables like this may not stay up-to-date for long!)

Update: iOS 5 and Android 4 are both reported to have position:fixed support now.

I tested iOS 5 myself in an Apple store today and can confirm that it does work with position fixed. There are issues with zooming in and panning around a fixed element though.

I found this compatibility table far more up to date and useful than the quirksmode one: http://caniuse.com/#search=fixed

It has up to date info on Android, Opera (mini and mobile) & iOS.

Available text color classes in Bootstrap

You can use text classes:

.text-primary
.text-secondary
.text-success
.text-danger
.text-warning
.text-info
.text-light
.text-dark
.text-muted
.text-white

use text classes in any tag where needed.

<p class="text-primary">.text-primary</p>
<p class="text-secondary">.text-secondary</p>
<p class="text-success">.text-success</p>
<p class="text-danger">.text-danger</p>
<p class="text-warning">.text-warning</p>
<p class="text-info">.text-info</p>
<p class="text-light bg-dark">.text-light</p>
<p class="text-dark">.text-dark</p>
<p class="text-muted">.text-muted</p>
<p class="text-white bg-dark">.text-white</p>

You can add your own classes or modify above classes as your requirement.

How to resize an image to fit in the browser window?

Use this code in your style tag

<style>
html {
  background: url(imagename) no-repeat center center fixed;
  background-size: cover;
  height: 100%;
  overflow: hidden;
}
</style>

For div to extend full height

if setting height to 100% doesn't work, try min-height=100% for div. You still have to set the html tag.

html {
    height: 100%;
    margin: 0px;
    padding: 0px;
    position: relative;
}

#fullHeight{

    width: 450px;
    **min-height: 100%;**
    background-color: blue;

}

How to reference a .css file on a razor view?

For CSS that are reused among the entire site I define them in the <head> section of the _Layout:

<head>
    <link href="@Url.Content("~/Styles/main.css")" rel="stylesheet" type="text/css" />
    @RenderSection("Styles", false)
</head>

and if I need some view specific styles I define the Styles section in each view:

@section Styles {
    <link href="@Url.Content("~/Styles/view_specific_style.css")" rel="stylesheet" type="text/css" />
}

Edit: It's useful to know that the second parameter in @RenderSection, false, means that the section is not required on a view that uses this master page, and the view engine will blissfully ignore the fact that there is no "Styles" section defined in your view. If true, the view won't render and an error will be thrown unless the "Styles" section has been defined.

Div Size Automatically size of content

If you are coming here, there is high chance width: min-content or width: max-content can fix your problem. This can force an element to use the smallest or largest space the browser could choose…

This is the modern solution. Here is a small tutorial for that.

There is also fit-content, which often works like min-content, but is more flexible. (But also has worse browser support.)

This is a quite new feature and some browsers do not support it yet, but browser support is growing. See the current browser status here.

Hide vertical scrollbar in <select> element

You can use a <div> to cover the scrollbar if you really want it to disappear.
Although it won't work on IE6, modern browsers do let you put a <div> on top of it.

HTML-Tooltip position relative to mouse pointer

This CAN be done with pure html and css. It may not be the best way but we all have different limitations. There are 3 ways that could be useful depending on what your specific circumstances are.

  1. The first involves overlaying an invisible table over top of your link with a hover action on each cell that displays an image.

_x000D_
_x000D_
#imagehover td:hover::after{_x000D_
  content: "             ";_x000D_
  white-space: pre;_x000D_
  background-image: url("http://www.google.com/images/srpr/logo4w.png");_x000D_
  position: relative;_x000D_
  left: 5px;_x000D_
  top: 5px;_x000D_
  font-size: 20px;_x000D_
  background-color: transparent;_x000D_
  background-position: 0px 0px;_x000D_
  background-size: 60px 20px;_x000D_
  background-repeat: no-repeat;_x000D_
  _x000D_
}_x000D_
_x000D_
_x000D_
#imagehover table, #imagehover th, #imagehover td {_x000D_
  border: 0px;_x000D_
  border-spacing: 0px;_x000D_
}
_x000D_
<a href="https://www.google.com">_x000D_
<table id="imagehover" style="width:50px;height:10px;z-index:9999;position:absolute" cellspacing="0">_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
_x000D_
</table>_x000D_
Google</a>
_x000D_
_x000D_
_x000D_

  1. The second relies on being able to create your own cursor image

_x000D_
_x000D_
#googleLink{_x000D_
_x000D_
cursor: url(https://winter-bush-d06c.sto.workers.dev/cursor-extern.php?id=98272),url(https://9dc1a5c00e8109665645209c2d036b1c.cloudflareworkers.com/cursor-extern.php?id=98272),auto;_x000D_
_x000D_
}
_x000D_
<a href="https://www.google.com" id="googleLink">Google</a>
_x000D_
_x000D_
_x000D_

  1. While the normal title tooltip doesn't technically allow images it does allow any unicode characters including block letters and emojis which may suite your needs.

_x000D_
_x000D_
<a href="https://www.google.com" title="??" alt="??">Google</a>
_x000D_
_x000D_
_x000D_

Should CSS always preceed Javascript?

I think this wont be true for all the cases. Because css will download parallel but js cant. Consider for the same case,

Instead of having single css, take 2 or 3 css files and try it out these ways,

1) css..css..js 2) css..js..css 3) js..css..css

I'm sure css..css..js will give better result than all others.

Change Text Color of Selected Option in a Select Box

ONE COLOR CASE - CSS only

Just to register my experience, where I wanted to set only the color of the selected option to a specific one.

I first tried to set by css only the color of the selected option with no success.

Then, after trying some combinations, this has worked for me with SCSS:

select {
      color: white; // color of the selected option

      option {
        color: black; // color of all the other options
      }
 }

Take a look at a working example with only CSS:

_x000D_
_x000D_
select {_x000D_
  color: yellow; // color of the selected option_x000D_
 }_x000D_
_x000D_
select option {_x000D_
  color: black; // color of all the other options_x000D_
}
_x000D_
<select id="mySelect">_x000D_
    <option value="apple" >Apple</option>_x000D_
    <option value="banana" >Banana</option>_x000D_
    <option value="grape" >Grape</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

For different colors, depending on the selected option, you'll have to deal with js.

Creating a simple login form

Using <table> is not a bad choice. Of course it is bit old fashioned. 

But still not obsolete. But if you prefer you can use "Boostrap". There you have options for panels and enhanced forms.

This is the sample code for your requirement. Used minimal styles to simplify.

<!DOCTYPE html>
<html>
   <head>
      <title>Simple Login Form</title>
   </head>
   <style>
      table{
      border-style: solid;
      position: absolute;
      top: 40%;
      left : 40%;
      padding:10px;
      }
   </style>
   <body>
      <form method="post" action="login.php">
         <table>
            <tr bgcolor="black">
               <th colspan="3"><font color="white">Enter login details</th>
            </tr>
            <tr height="20"></tr>
            <tr>
               <td>User Name</td>
               <td>:</td>
               <td>
                  <input type="text" name="username"/>
               </td>
            </tr>
            <tr>
               <td>Password</td>
               <td>:</td>
               <td>
                  <input type="password" name="password"/>
               </td>
            </tr>
            <tr height="10"></tr>
            <tr>
               <td></td>
               <td></td>
               <td align="center"><input type="submit" value="Submit"></td>
            </tr>
         </table>
      </form>
   </body>
</html>

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

This answer may have to be modified depending on what you were trying to achieve with position: fixed;. If all you want is two columns side by side then do the following:

http://jsfiddle.net/8weSA/1/

I floated both columns to the left.

Note: I added min-height to each column for illustrative purposes and I simplified your CSS.

_x000D_
_x000D_
body {_x000D_
  background-color: #444;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
  width: 1005px;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
_x000D_
#leftcolumn,_x000D_
#rightcolumn {_x000D_
  border: 1px solid white;_x000D_
  float: left;_x000D_
  min-height: 450px;_x000D_
  color: white;_x000D_
}_x000D_
_x000D_
#leftcolumn {_x000D_
  width: 250px;_x000D_
  background-color: #111;_x000D_
}_x000D_
_x000D_
#rightcolumn {_x000D_
  width: 750px;_x000D_
  background-color: #777;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
  <div id="leftcolumn">_x000D_
    Left_x000D_
  </div>_x000D_
  <div id="rightcolumn">_x000D_
    Right_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

If you would like the left column to stay in place as you scroll do the following:

http://jsfiddle.net/8weSA/2/

Here we float the right column to the right while adding position: relative; to #wrapper and position: fixed; to #leftcolumn.

Note: I again used min-height for illustrative purposes and can be removed for your needs.

_x000D_
_x000D_
body {_x000D_
  background-color: #444;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
  width: 1005px;_x000D_
  margin: 0 auto;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
#leftcolumn,_x000D_
#rightcolumn {_x000D_
  border: 1px solid white;_x000D_
  min-height: 750px;_x000D_
  color: white;_x000D_
}_x000D_
_x000D_
#leftcolumn {_x000D_
  width: 250px;_x000D_
  background-color: #111;_x000D_
  min-height: 100px;_x000D_
  position: fixed;_x000D_
}_x000D_
_x000D_
#rightcolumn {_x000D_
  width: 750px;_x000D_
  background-color: #777;_x000D_
  float: right;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
  <div id="leftcolumn">_x000D_
    Left_x000D_
  </div>_x000D_
  <div id="rightcolumn">_x000D_
    Right_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Change div width live with jQuery

There are two ways to do this:

CSS: Use width as %, like 75%, so the width of the div will change automatically when user resizes the browser.

Javascipt: Use resize event

$(window).bind('resize', function()
{
    if($(window).width() > 500)
        $('#divID').css('width', '300px');
    else
        $('divID').css('width', '200px');
});

Hope this will help you :)

Styling an anchor tag to look like a submit button

I Suggest you to use both Input Submit / Button instead of anchor and put this line of code onClick="javascript:location.href = 'http://stackoverflow.com';" in that Input Submit / Button which you want to work as link.

Submit Example

<input type="submit" value="Submit" onClick="javascript:location.href = 'some_url';" />

Button Example

<button type="button" onClick="javascript:location.href = 'some_url';" />Submit</button>

Make Div overlay ENTIRE page (not just viewport)?

First of all, I think you've misunderstood what the viewport is. The viewport is the area a browser uses to render web pages, and you cannot in any way build your web sites to override this area in any way.

Secondly, it seems that the reason that your overlay-div won't cover the entire viewport is because you have to remove all margins on BODY and HTML.

Try adding this at the top of your stylesheet - it resets all margins and paddings on all elements. Makes further development easier:

* { margin: 0; padding: 0; }

Edit: I just understood your question better. Position: fixed; will probably work out for you, as Jonathan Sampson have written.

Custom CSS for <audio> tag?

There are CSS options for the audio tag.

Like: html 5 audio tag width

But if you play around with it you'll see results can be unexpected - as of August 2012.

How can I determine whether a 2D Point is within a Polygon?

Here is a JavaScript variant of the answer by M. Katz based on Nirg's approach:

function pointIsInPoly(p, polygon) {
    var isInside = false;
    var minX = polygon[0].x, maxX = polygon[0].x;
    var minY = polygon[0].y, maxY = polygon[0].y;
    for (var n = 1; n < polygon.length; n++) {
        var q = polygon[n];
        minX = Math.min(q.x, minX);
        maxX = Math.max(q.x, maxX);
        minY = Math.min(q.y, minY);
        maxY = Math.max(q.y, maxY);
    }

    if (p.x < minX || p.x > maxX || p.y < minY || p.y > maxY) {
        return false;
    }

    var i = 0, j = polygon.length - 1;
    for (i, j; i < polygon.length; j = i++) {
        if ( (polygon[i].y > p.y) != (polygon[j].y > p.y) &&
                p.x < (polygon[j].x - polygon[i].x) * (p.y - polygon[i].y) / (polygon[j].y - polygon[i].y) + polygon[i].x ) {
            isInside = !isInside;
        }
    }

    return isInside;
}

How do I add a Font Awesome icon to input field?

.fa-file-o {
    position: absolute;
    left: 50px;
    top: 15px;
    color: #ffffff
}

<div>
 <span class="fa fa-file-o"></span>
 <input type="button" name="" value="IMPORT FILE"/>
</div>

Appending to an empty DataFrame in Pandas?

And if you want to add a row, you can use a dictionary:

df = pd.DataFrame()
df = df.append({'name': 'Zed', 'age': 9, 'height': 2}, ignore_index=True)

which gives you:

   age  height name
0    9       2  Zed

Access iframe elements in JavaScript

this code worked for me:

window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId');

Changing default startup directory for command prompt in Windows 7

On windows 7:

  1. Do a search for "cmd" on your Windows computer
    1. right-click cmd and left click "Pin to start menu" (Alternatively, right-click cmd - click copy and then paste to your desktop )
    2. right-click the cmd in your start menu or on your desktop (depending on choice 2 above) - left click properties
    3. inside the "start in" text box paste the location of your default start directory
    4. Press Apply and OK

Every time you click on the cmd in your start menu or your desktop shortcut, the CMD will open in your default location

Sorting using Comparator- Descending order (User defined classes)

You can do the descending sort of a user-defined class this way overriding the compare() method,

Collections.sort(unsortedList,new Comparator<Person>() {
    @Override
    public int compare(Person a, Person b) {
        return b.getName().compareTo(a.getName());
    }
});

Or by using Collection.reverse() to sort descending as user Prince mentioned in his comment.

And you can do the ascending sort like this,

Collections.sort(unsortedList,new Comparator<Person>() {
    @Override
    public int compare(Person a, Person b) {
        return a.getName().compareTo(b.getName());
    }
});

Replace the above code with a Lambda expression(Java 8 onwards) we get concise:

Collections.sort(personList, (Person a, Person b) -> b.getName().compareTo(a.getName()));

As of Java 8, List has sort() method which takes Comparator as parameter(more concise) :

personList.sort((a,b)->b.getName().compareTo(a.getName()));

Here a and b are inferred as Person type by lambda expression.

Get current folder path

string appPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);

From Path.GetDirectoryName

Returns the directory information for the specified path string.

From Application.ExecutablePath

Gets the path for the executable file that started the application, including the executable name.

How to export and import environment variables in windows?

Combine @vincsilver and @jdigital's answers with some modifications,

  1. export .reg to current directory
  2. add date mark

code:

set TODAY=%DATE:~0,4%-%DATE:~5,2%-%DATE:~8,2%

regedit /e "%CD%\user_env_variables[%TODAY%].reg" "HKEY_CURRENT_USER\Environment"
regedit /e "%CD%\global_env_variables[%TODAY%].reg" "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

Output would like:

global_env_variables[2017-02-14].reg
user_env_variables[2017-02-14].reg

How can I save a base64-encoded image to disk?

UPDATE

I found this interesting link how to solve your problem in PHP. I think you forgot to replace space by +as shown in the link.

I took this circle from http://images-mediawiki-sites.thefullwiki.org/04/1/7/5/6204600836255205.png as sample which looks like:

http://images-mediawiki-sites.thefullwiki.org/04/1/7/5/6204600836255205.png

Next I put it through http://www.greywyvern.com/code/php/binary2base64 which returned me:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAAAAACPAi4CAAAAB3RJTUUH1QEHDxEhOnxCRgAAAAlwSFlzAAAK8AAACvABQqw0mAAAAXBJREFUeNrtV0FywzAIxJ3+K/pZyctKXqamji0htEik9qEHc3JkWC2LRPCS6Zh9HIy/AP4FwKf75iHEr6eU6Mt1WzIOFjFL7IFkYBx3zWBVkkeXAUCXwl1tvz2qdBLfJrzK7ixNUmVdTIAB8PMtxHgAsFNNkoExRKA+HocriOQAiC+1kShhACwSRGAEwPP96zYIoE8Pmph9qEWWKcCWRAfA/mkfJ0F6dSoA8KW3CRhn3ZHcW2is9VOsAgoqHblncAsyaCgcbqpUZQnWoGTcp/AnuwCoOUjhIvCvN59UBeoPZ/AYyLm3cWVAjxhpqREVaP0974iVwH51d4AVNaSC8TRNNYDQEFdlzDW9ob10YlvGQm0mQ+elSpcCCBtDgQD7cDFojdx7NIeHJkqi96cOGNkfZOroZsHtlPYoR7TOp3Vmfa5+49uoSSRyjfvc0A1kLx4KC6sNSeDieD1AWhrJLe0y+uy7b9GjP83l+m68AJ72AwSRPN5g7uwUAAAAAElFTkSuQmCC

saved this string to base64 which I read from in my code.

var fs      = require('fs'),
data        = fs.readFileSync('base64', 'utf8'),
base64Data,
binaryData;

base64Data  =   data.replace(/^data:image\/png;base64,/, "");
base64Data  +=  base64Data.replace('+', ' ');
binaryData  =   new Buffer(base64Data, 'base64').toString('binary');

fs.writeFile("out.png", binaryData, "binary", function (err) {
    console.log(err); // writes out file without error, but it's not a valid image
});

I get a circle back, but the funny thing is that the filesize has changed :)...

END

When you read back image I think you need to setup headers

Take for example imagepng from PHP page:

<?php
$im = imagecreatefrompng("test.png");

header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

I think the second line header('Content-Type: image/png');, is important else your image will not be displayed in browser, but just a bunch of binary data is shown to browser.

In Express you would simply just use something like below. I am going to display your gravatar which is located at http://www.gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG and is a jpeg file when you curl --head http://www.gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG. I only request headers because else curl will display a bunch of binary stuff(Google Chrome immediately goes to download) to console:

curl --head "http://www.gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG"
HTTP/1.1 200 OK
Server: nginx
Date: Wed, 03 Aug 2011 12:11:25 GMT
Content-Type: image/jpeg
Connection: keep-alive
Last-Modified: Mon, 04 Oct 2010 11:54:22 GMT
Content-Disposition: inline; filename="cabf735ce7b8b4471ef46ea54f71832d.jpeg"
Access-Control-Allow-Origin: *
Content-Length: 1258
X-Varnish: 2356636561 2352219240
Via: 1.1 varnish
Expires: Wed, 03 Aug 2011 12:16:25 GMT
Cache-Control: max-age=300
Source-Age: 1482

$ mkdir -p ~/tmp/6922728
$ cd ~/tmp/6922728/
$ touch app.js

app.js

var app = require('express').createServer();

app.get('/', function (req, res) {
    res.contentType('image/jpeg');
    res.sendfile('cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG');
});

app.get('/binary', function (req, res) {
    res.sendfile('cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG');
});

app.listen(3000);

$ wget "http://www.gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG"
$ node app.js

IPython/Jupyter Problems saving notebook as PDF

I had this error in Windows 10. I followed these three steps and it solved my problem:

  1. Install nbconvert

    pip install nbconvert

  2. Install pandoc

https://pandoc.org/installing.html

  1. Install miktex

https://miktex.org/download


Also it is good to update libraries:

pip install jupyter --upgrade
pip install --upgrade --user nbconvert

IntelliJ show JavaDocs tooltip on mouse over

After doing CTRL+Q, you can

  1. Pin the tooltip (top right corner)
  2. Check Docked Mode (under gear in top right after pinning)
  3. Size as desired
  4. Click icon for Auto show documentation for selected item

Then when you move your cursor, the documentation will appear in this box. It costs you a little screen real estate, but I find it's worth it.

I'd post a screenshot but SO won't let me post images.

WARNING: Setting property 'source' to 'org.eclipse.jst.jee.server:appname' did not find a matching property

Despite this question being rather old, I had to deal with a similar warning and wanted to share what I found out.

First of all this is a warning and not an error. So there is no need to worry too much about it. Basically it means, that Tomcat does not know what to do with the source attribute from context.

This source attribute is set by Eclipse (or to be more specific the Eclipse Web Tools Platform) to the server.xml file of Tomcat to match the running application to a project in workspace.

Tomcat generates a warning for every unknown markup in the server.xml (i.e. the source attribute) and this is the source of the warning. You can safely ignore it.

Get skin path in Magento?

To get that file use the below code.

include(Mage::getBaseDir('skin').'myfunc.php');

But it is not a correct way. To add your custom functions you can use the below file.

app/code/core/Mage/core/functions.php

Kindly avoid to use the PHP function under skin dir.

Multiple lines of text in UILabel

The best solution I have found (to an otherwise frustrating problem that should have been solved in the framework) is similar to vaychick's.

Just set number of lines to 0 in either IB or code

myLabel.numberOfLines = 0;

This will display the lines needed but will reposition the label so its centered horizontally (so that a 1 line and 3 line label are aligned in their horizontal position). To fix that add:

CGRect currentFrame = myLabel.frame;
CGSize max = CGSizeMake(myLabel.frame.size.width, 500);
CGSize expected = [myString sizeWithFont:myLabel.font constrainedToSize:max lineBreakMode:myLabel.lineBreakMode]; 
currentFrame.size.height = expected.height;
myLabel.frame = currentFrame;

Display curl output in readable JSON format in Unix shell script

Check out curljson

$ pip install curljson
$ curljson -i <the-json-api-url>

turn typescript object into json string

If you're using fs-extra, you can skip the JSON.stringify part with the writeJson function:

const fsExtra = require('fs-extra');

fsExtra.writeJson('./package.json', {name: 'fs-extra'})
.then(() => {
  console.log('success!')
})
.catch(err => {
  console.error(err)
})

Create a string and append text to it

Another way to do this is to add the new characters to the string as follows:

Dim str As String

str = ""

To append text to your string this way:

str = str & "and this is more text"

How to Implement DOM Data Binding in JavaScript

Yesterday, I started to write my own way to bind data.

It's very funny to play with it.

I think it's beautiful and very useful. At least on my tests using firefox and chrome, Edge must works too. Not sure about others, but if they support Proxy, I think it will work.

https://jsfiddle.net/2ozoovne/1/

<H1>Bind Context 1</H1>
<input id='a' data-bind='data.test' placeholder='Button Text' />
<input id='b' data-bind='data.test' placeholder='Button Text' />
<input type=button id='c' data-bind='data.test' />
<H1>Bind Context 2</H1>
<input id='d' data-bind='data.otherTest' placeholder='input bind' />
<input id='e' data-bind='data.otherTest' placeholder='input bind' />
<input id='f' data-bind='data.test' placeholder='button 2 text - same var name, other context' />
<input type=button id='g' data-bind='data.test' value='click here!' />
<H1>No bind data</H1>
<input id='h' placeholder='not bound' />
<input id='i' placeholder='not bound'/>
<input type=button id='j' />

Here is the code:

(function(){
    if ( ! ( 'SmartBind' in window ) ) { // never run more than once
        // This hack sets a "proxy" property for HTMLInputElement.value set property
        var nativeHTMLInputElementValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
        var newDescriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
        newDescriptor.set=function( value ){
            if ( 'settingDomBind' in this )
                return;
            var hasDataBind=this.hasAttribute('data-bind');
            if ( hasDataBind ) {
                this.settingDomBind=true;
                var dataBind=this.getAttribute('data-bind');
                if ( ! this.hasAttribute('data-bind-context-id') ) {
                    console.error("Impossible to recover data-bind-context-id attribute", this, dataBind );
                } else {
                    var bindContextId=this.getAttribute('data-bind-context-id');
                    if ( bindContextId in SmartBind.contexts ) {
                        var bindContext=SmartBind.contexts[bindContextId];
                        var dataTarget=SmartBind.getDataTarget(bindContext, dataBind);
                        SmartBind.setDataValue( dataTarget, value);
                    } else {
                        console.error( "Invalid data-bind-context-id attribute", this, dataBind, bindContextId );
                    }
                }
                delete this.settingDomBind;
            }
            nativeHTMLInputElementValue.set.bind(this)( value );
        }
        Object.defineProperty(HTMLInputElement.prototype, 'value', newDescriptor);

    var uid= function(){
           return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
               var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
               return v.toString(16);
          });
   }

        // SmartBind Functions
        window.SmartBind={};
        SmartBind.BindContext=function(){
            var _data={};
            var ctx = {
                "id" : uid()    /* Data Bind Context Id */
                , "_data": _data        /* Real data object */
                , "mapDom": {}          /* DOM Mapped objects */
                , "mapDataTarget": {}       /* Data Mapped objects */
            }
            SmartBind.contexts[ctx.id]=ctx;
            ctx.data=new Proxy( _data, SmartBind.getProxyHandler(ctx, "data"))  /* Proxy object to _data */
            return ctx;
        }

        SmartBind.getDataTarget=function(bindContext, bindPath){
            var bindedObject=
                { bindContext: bindContext
                , bindPath: bindPath 
                };
            var dataObj=bindContext;
            var dataObjLevels=bindPath.split('.');
            for( var i=0; i<dataObjLevels.length; i++ ) {
                if ( i == dataObjLevels.length-1 ) { // last level, set value
                    bindedObject={ target: dataObj
                    , item: dataObjLevels[i]
                    }
                } else {    // digg in
                    if ( ! ( dataObjLevels[i] in dataObj ) ) {
                        console.warn("Impossible to get data target object to map bind.", bindPath, bindContext);
                        break;
                    }
                    dataObj=dataObj[dataObjLevels[i]];
                }
            }
            return bindedObject ;
        }

        SmartBind.contexts={};
        SmartBind.add=function(bindContext, domObj){
            if ( typeof domObj == "undefined" ){
                console.error("No DOM Object argument given ", bindContext);
                return;
            }
            if ( ! domObj.hasAttribute('data-bind') ) {
                console.warn("Object has no data-bind attribute", domObj);
                return;
            }
            domObj.setAttribute("data-bind-context-id", bindContext.id);
            var bindPath=domObj.getAttribute('data-bind');
            if ( bindPath in bindContext.mapDom ) {
                bindContext.mapDom[bindPath][bindContext.mapDom[bindPath].length]=domObj;
            } else {
                bindContext.mapDom[bindPath]=[domObj];
            }
            var bindTarget=SmartBind.getDataTarget(bindContext, bindPath);
            bindContext.mapDataTarget[bindPath]=bindTarget;
            domObj.addEventListener('input', function(){ SmartBind.setDataValue(bindTarget,this.value); } );
            domObj.addEventListener('change', function(){ SmartBind.setDataValue(bindTarget, this.value); } );
        }

        SmartBind.setDataValue=function(bindTarget,value){
            if ( ! ( 'target' in bindTarget ) ) {
                var lBindTarget=SmartBind.getDataTarget(bindTarget.bindContext, bindTarget.bindPath);
                if ( 'target' in lBindTarget ) {
                    bindTarget.target=lBindTarget.target;
                    bindTarget.item=lBindTarget.item;
                } else {
                    console.warn("Still can't recover the object to bind", bindTarget.bindPath );
                }
            }
            if ( ( 'target' in bindTarget ) ) {
                bindTarget.target[bindTarget.item]=value;
            }
        }
        SmartBind.getDataValue=function(bindTarget){
            if ( ! ( 'target' in bindTarget ) ) {
                var lBindTarget=SmartBind.getDataTarget(bindTarget.bindContext, bindTarget.bindPath);
                if ( 'target' in lBindTarget ) {
                    bindTarget.target=lBindTarget.target;
                    bindTarget.item=lBindTarget.item;
                } else {
                    console.warn("Still can't recover the object to bind", bindTarget.bindPath );
                }
            }
            if ( ( 'target' in bindTarget ) ) {
                return bindTarget.target[bindTarget.item];
            }
        }
        SmartBind.getProxyHandler=function(bindContext, bindPath){
            return  {
                get: function(target, name){
                    if ( name == '__isProxy' )
                        return true;
                    // just get the value
                    // console.debug("proxy get", bindPath, name, target[name]);
                    return target[name];
                }
                ,
                set: function(target, name, value){
                    target[name]=value;
                    bindContext.mapDataTarget[bindPath+"."+name]=value;
                    SmartBind.processBindToDom(bindContext, bindPath+"."+name);
                    // console.debug("proxy set", bindPath, name, target[name], value );
                    // and set all related objects with this target.name
                    if ( value instanceof Object) {
                        if ( !( name in target) || ! ( target[name].__isProxy ) ){
                            target[name]=new Proxy(value, SmartBind.getProxyHandler(bindContext, bindPath+'.'+name));
                        }
                        // run all tree to set proxies when necessary
                        var objKeys=Object.keys(value);
                        // console.debug("...objkeys",objKeys);
                        for ( var i=0; i<objKeys.length; i++ ) {
                            bindContext.mapDataTarget[bindPath+"."+name+"."+objKeys[i]]=target[name][objKeys[i]];
                            if ( typeof value[objKeys[i]] == 'undefined' || value[objKeys[i]] == null || ! ( value[objKeys[i]] instanceof Object ) || value[objKeys[i]].__isProxy )
                                continue;
                            target[name][objKeys[i]]=new Proxy( value[objKeys[i]], SmartBind.getProxyHandler(bindContext, bindPath+'.'+name+"."+objKeys[i]));
                        }
                        // TODO it can be faster than run all items
                        var bindKeys=Object.keys(bindContext.mapDom);
                        for ( var i=0; i<bindKeys.length; i++ ) {
                            // console.log("test...", bindKeys[i], " for ", bindPath+"."+name);
                            if ( bindKeys[i].startsWith(bindPath+"."+name) ) {
                                // console.log("its ok, lets update dom...", bindKeys[i]);
                                SmartBind.processBindToDom( bindContext, bindKeys[i] );
                            }
                        }
                    }
                    return true;
                }
            };
        }
        SmartBind.processBindToDom=function(bindContext, bindPath) {
            var domList=bindContext.mapDom[bindPath];
            if ( typeof domList != 'undefined' ) {
                try {
                    for ( var i=0; i < domList.length ; i++){
                        var dataTarget=SmartBind.getDataTarget(bindContext, bindPath);
                        if ( 'target' in dataTarget )
                            domList[i].value=dataTarget.target[dataTarget.item];
                        else
                            console.warn("Could not get data target", bindContext, bindPath);
                    }
                } catch (e){
                    console.warn("bind fail", bindPath, bindContext, e);
                }
            }
        }
    }
})();

Then, to set, just:

var bindContext=SmartBind.BindContext();
SmartBind.add(bindContext, document.getElementById('a'));
SmartBind.add(bindContext, document.getElementById('b'));
SmartBind.add(bindContext, document.getElementById('c'));

var bindContext2=SmartBind.BindContext();
SmartBind.add(bindContext2, document.getElementById('d'));
SmartBind.add(bindContext2, document.getElementById('e'));
SmartBind.add(bindContext2, document.getElementById('f'));
SmartBind.add(bindContext2, document.getElementById('g'));

setTimeout( function() {
    document.getElementById('b').value='Via Script works too!'
}, 2000);

document.getElementById('g').addEventListener('click',function(){
bindContext2.data.test='Set by js value'
})

For now, I've just added the HTMLInputElement value bind.

Let me know if you know how to improve it.

Using Excel as front end to Access database (with VBA)

Given the ease of use of Access, I don't see a compelling reason to use Excel at all other than to export data for number crunching. Access is designed to easily build data forms and, in my opinion, will be orders of magnitude easier and less time-consuming than using Excel. A few hours to learn the Access object model will pay for itself many times over in terms of time and effort.

How To Show And Hide Input Fields Based On Radio Button Selection

***This will work.........
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
 window.onload = function() {
    document.getElementById('ifYes').style.display = 'none';
    document.getElementById('ifNo').style.display = 'none';
}
function yesnoCheck() {
    if (document.getElementById('yesCheck').checked) {
        document.getElementById('ifYes').style.display = 'block';
        document.getElementById('ifNo').style.display = 'none';
        document.getElementById('redhat1').style.display = 'none';
        document.getElementById('aix1').style.display = 'none';
    } 
    else if(document.getElementById('noCheck').checked) {
        document.getElementById('ifNo').style.display = 'block';
        document.getElementById('ifYes').style.display = 'none';
        document.getElementById('redhat1').style.display = 'none';
        document.getElementById('aix1').style.display = 'none';
   }
}
function yesnoCheck1() {
   if(document.getElementById('redhat').checked) {
       document.getElementById('redhat1').style.display = 'block';
       document.getElementById('aix1').style.display = 'none';
    }
   if(document.getElementById('aix').checked) {
       document.getElementById('aix1').style.display = 'block';
       document.getElementById('redhat1').style.display = 'none';
    }
}
</script>
</head>
<body>
Select os :<br>
windows
<input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="yesCheck"/>Unix
<input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="noCheck"/>
<br>
<div id="ifYes" style="display:none">
Windows 2008<input type="radio" name="win" value="2008"/>
Windows 2012<input type="radio" name="win" value="2012"/>
</div>
<div id="ifNo" style="display:none">
Red Hat<input type="radio" name="unix" onclick="javascript:yesnoCheck1();"value="2008" 

id="redhat"/>
AIX<input type="radio" name="unix" onclick="javascript:yesnoCheck1();"  
value="2012" id="aix"/>
</div>
<div id="redhat1" style="display:none">
Red Hat 6.0<input type="radio" name="redhat" value="2008" id="redhat6.0"/>
Red Hat 6.1<input type="radio" name="redhat" value="2012" id="redhat6.1"/>
</div>
<div id="aix1" style="display:none">
aix 6.0<input type="radio" name="aix" value="2008" id="aix6.0"/>
aix 6.1<input type="radio" name="aix" value="2012" id="aix6.1"/
</div>
</body> 
</html>***

What does "use strict" do in JavaScript, and what is the reasoning behind it?

Small examples to compare:

Non-strict mode:

_x000D_
_x000D_
for (i of [1,2,3]) console.log(i)_x000D_
    _x000D_
// output:_x000D_
// 1_x000D_
// 2_x000D_
// 3
_x000D_
_x000D_
_x000D_

Strict mode:

_x000D_
_x000D_
'use strict';_x000D_
for (i of [1,2,3]) console.log(i)_x000D_
_x000D_
// output:_x000D_
// Uncaught ReferenceError: i is not defined
_x000D_
_x000D_
_x000D_

Non-strict mode:

_x000D_
_x000D_
String.prototype.test = function () {_x000D_
  console.log(typeof this === 'string');_x000D_
};_x000D_
_x000D_
'a'.test();_x000D_
_x000D_
// output_x000D_
// false
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
String.prototype.test = function () {_x000D_
  'use strict';_x000D_
  _x000D_
  console.log(typeof this === 'string');_x000D_
};_x000D_
_x000D_
'a'.test();_x000D_
_x000D_
// output_x000D_
// true
_x000D_
_x000D_
_x000D_

How to connect SQLite with Java?

If you are using Netbeans using Maven to add library is easier. I have tried using above solutions but it didn't work.

<dependencies>
    <dependency>
      <groupId>org.xerial</groupId>
      <artifactId>sqlite-jdbc</artifactId>
      <version>3.7.2</version>
    </dependency>
</dependencies>

I have added Maven dependency and java.lang.ClassNotFoundException: org.sqlite.JDBC error gone.

What is the difference between & and && in Java?

Besides && and || being short circuiting, also consider operator precedence when mixing the two forms. I think it will not be immediately apparent to everybody that result1 and result2 contain different values.

boolean a = true;
boolean b = false;
boolean c = false;

boolean result1 = a || b && c; //is true;  evaluated as a || (b && c)
boolean result2 = a  | b && c; //is false; evaluated as (a | b) && c

json_encode() escaping forward slashes

Yes, but don't - escaping forward slashes is a good thing. When using JSON inside <script> tags it's necessary as a </script> anywhere - even inside a string - will end the script tag.

Depending on where the JSON is used it's not necessary, but it can be safely ignored.

Understanding ASP.NET Eval() and Bind()

The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval() and Bind(), taking advantage of the strongly-typed bindings.

*Note: this will only work if you're not using a SqlDataSource or an anonymous object. It requires a Strongly-typed object (from an EF model or any other class).

This code snippet shows how Eval and Bind would be used for a ListView control (InsertItem needs Bind, as explained by Darin Dimitrov above, and ItemTemplate is read-only (hence they're labels), so just needs an Eval):

<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
    <InsertItemTemplate>
        <li>
            Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />         
            Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />        
            <asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />        
        </li>
    </InsertItemTemplate>
    <ItemTemplate>
        <li>
            Title: <asp:Label ID="Title" runat="server" Text='<%#  Eval("Title") %>' /><br />
            Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />        
            <asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
        </li>
      </ItemTemplate>

From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType, which points to the type of object you're assigning to its data source.

<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>

Picture is the strongly type object (from EF model). We then replace:

Bind(property) -> BindItem.property
Eval(property) -> Item.property

So this:

<%# Bind("Title") %>      
<%# Bind("Description") %>         
<%#  Eval("Title") %> 
<%# Eval("Description") %>

Would become this:

<%# BindItem.Title %>         
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>

Advantages over Eval & Bind:

  • IntelliSense can find the correct property of the object your're working withenter image description here
  • If property is renamed/deleted, you will get an error before page is viewed in browser
  • External tools (requires full versions of VS) will correctly rename item in markup when you rename a property on your object

Source: from this excellent book

How to flush route table in windows?

In Microsoft Windows, you can go through by route -f command to delete your current Gateway, check route / ? for more advance option, like add / delete etc and also can write a batch to add route on specific time as well but if you need to delete IP cache, then you have the option to use arp command.

BeautifulSoup getting href

You can use find_all in the following way to find every a element that has an href attribute, and print each one:

from BeautifulSoup import BeautifulSoup

html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''

soup = BeautifulSoup(html)

for a in soup.find_all('a', href=True):
    print "Found the URL:", a['href']

The output would be:

Found the URL: some_url
Found the URL: another_url

Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all instead.


If you want all tags with an href, you can omit the name parameter:

href_tags = soup.find_all(href=True)

Submit form without reloading page

You can use jQuery serialize function along with get/post as follows:

$.get('server.php?' + $('#theForm').serialize())

$.post('server.php', $('#theform').serialize())

jQuery Serialize Documentation: http://api.jquery.com/serialize/

Simple AJAX submit using jQuery:

// this is the id of the submit button
$("#submitButtonId").click(function() {

    var url = "path/to/your/script.php"; // the script where you handle the form input.

    $.ajax({
           type: "POST",
           url: url,
           data: $("#idForm").serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the php script.
           }
         });

    return false; // avoid to execute the actual submit of the form.
});

MySQL check if a table exists without throwing an exception

Here is the my solution that I prefer when using stored procedures. Custom mysql function for check the table exists in current database.

delimiter $$

CREATE FUNCTION TABLE_EXISTS(_table_name VARCHAR(45))
RETURNS BOOLEAN
DETERMINISTIC READS SQL DATA
BEGIN
    DECLARE _exists  TINYINT(1) DEFAULT 0;

    SELECT COUNT(*) INTO _exists
    FROM information_schema.tables 
    WHERE table_schema =  DATABASE()
    AND table_name =  _table_name;

    RETURN _exists;

END$$

SELECT TABLE_EXISTS('you_table_name') as _exists

How to disable mouse scroll wheel scaling with Google Maps API

Use that piece of code, that will give you all the color and zooming control of google map. (scaleControl: false and scrollwheel: false will prevent the mousewheel from zoom up or down)

_x000D_
_x000D_
function initMap() {_x000D_
            // Styles a map in night mode._x000D_
            var map = new google.maps.Map(document.getElementById('map'), {_x000D_
                center: {lat: 23.684994, lng: 90.356331},_x000D_
                zoom: 8,_x000D_
                scaleControl: false,_x000D_
                scrollwheel: false,_x000D_
              styles: [_x000D_
                {elementType: 'geometry', stylers: [{color: 'F1F2EC'}]},_x000D_
                {elementType: 'labels.text.stroke', stylers: [{color: '877F74'}]},_x000D_
                {elementType: 'labels.text.fill', stylers: [{color: '877F74'}]},_x000D_
                {_x000D_
                  featureType: 'administrative.locality',_x000D_
                  elementType: 'labels.text.fill',_x000D_
                  stylers: [{color: '#d59563'}]_x000D_
                },_x000D_
                {_x000D_
                  featureType: 'poi',_x000D_
                  elementType: 'labels.text.fill',_x000D_
                  stylers: [{color: '#d59563'}]_x000D_
                },_x000D_
                {_x000D_
                  featureType: 'poi.park',_x000D_
                  elementType: 'geometry',_x000D_
                  stylers: [{color: '#263c3f'}]_x000D_
                },_x000D_
                {_x000D_
                  featureType: 'poi.park',_x000D_
                  elementType: 'labels.text.fill',_x000D_
                  stylers: [{color: '#f77c2b'}]_x000D_
                },_x000D_
                {_x000D_
                  featureType: 'road',_x000D_
                  elementType: 'geometry',_x000D_
                  stylers: [{color: 'F5DAA6'}]_x000D_
                },_x000D_
                {_x000D_
                  featureType: 'road',_x000D_
                  elementType: 'geometry.stroke',_x000D_
                  stylers: [{color: '#212a37'}]_x000D_
                },_x000D_
                {_x000D_
                  featureType: 'road',_x000D_
                  elementType: 'labels.text.fill',_x000D_
                  stylers: [{color: '#f77c2b'}]_x000D_
                },_x000D_
                {_x000D_
                  featureType: 'road.highway',_x000D_
                  elementType: 'geometry',_x000D_
                  stylers: [{color: '#746855'}]_x000D_
                },_x000D_
                {_x000D_
                  featureType: 'road.highway',_x000D_
                  elementType: 'geometry.stroke',_x000D_
                  stylers: [{color: 'F5DAA6'}]_x000D_
                },_x000D_
                {_x000D_
                  featureType: 'road.highway',_x000D_
                  elementType: 'labels.text.fill',_x000D_
                  stylers: [{color: 'F5DAA6'}]_x000D_
                },_x000D_
                {_x000D_
                  featureType: 'transit',_x000D_
                  elementType: 'geometry',_x000D_
                  stylers: [{color: '#2f3948'}]_x000D_
                },_x000D_
                {_x000D_
                  featureType: 'transit.station',_x000D_
                  elementType: 'labels.text.fill',_x000D_
                  stylers: [{color: '#f77c2b3'}]_x000D_
                },_x000D_
                {_x000D_
                  featureType: 'water',_x000D_
                  elementType: 'geometry',_x000D_
                  stylers: [{color: '#0676b6'}]_x000D_
                },_x000D_
                {_x000D_
                  featureType: 'water',_x000D_
                  elementType: 'labels.text.fill',_x000D_
                  stylers: [{color: '#515c6d'}]_x000D_
                },_x000D_
                {_x000D_
                  featureType: 'water',_x000D_
                  elementType: 'labels.text.stroke',_x000D_
                  stylers: [{color: '#17263c'}]_x000D_
                }_x000D_
              ]_x000D_
            });_x000D_
    _x000D_
             var marker = new google.maps.Marker({_x000D_
              position: {lat: 23.684994, lng: 90.356331},_x000D_
              map: map,_x000D_
              title: 'BANGLADESH'_x000D_
            });_x000D_
          }
_x000D_
_x000D_
_x000D_

Difference between FetchType LAZY and EAGER in Java Persistence API?

EAGER loading of collections means that they are fetched fully at the time their parent is fetched. So if you have Course and it has List<Student>, all the students are fetched from the database at the time the Course is fetched.

LAZY on the other hand means that the contents of the List are fetched only when you try to access them. For example, by calling course.getStudents().iterator(). Calling any access method on the List will initiate a call to the database to retrieve the elements. This is implemented by creating a Proxy around the List (or Set). So for your lazy collections, the concrete types are not ArrayList and HashSet, but PersistentSet and PersistentList (or PersistentBag)

How to name an object within a PowerPoint slide?

Yes. Click on the object (textbox, shape, etc.) to select the object and in the Drawing Tools | Format tab, click on Selection Pane in the Arrange group. From there, you'll see names of objects - you can double click (or press F2) on any name and rename it. By deselecting it, it becomes renamed. You can also get to this from the Home tab -> Drawing group -> Arrange drop-down -> Selection pane or by pressing ALT + F10.

How do you post to the wall on a facebook page (not profile)

Get PHP SDK from github and run the following code:

<?php
$attachment = array(
    'message' => 'this is my message',
    'name' => 'This is my demo Facebook application!',
    'caption' => "Caption of the Post",
    'link' => 'http://mylink.com',
    'description' => 'this is a description',
    'picture' => 'http://mysite.com/pic.gif',
    'actions' => array(
        array(
            'name' => 'Get Search',
            'link' => 'http://www.google.com'
        )
    )
);

$result = $facebook->api('/me/feed/', 'post', $attachment);

the above code will Post the message on to your wall... and if you want to post onto your friends or others wall then replace me with the Facebook User Id of that user..for further information look out the API Documentation.

python error: no module named pylab

I solved the same problem by installing "matplotlib".

Difference of keywords 'typename' and 'class' in templates?

  1. No difference
  2. Template type parameter Container is itself a template with two type parameters.

How to reset / remove chrome's input highlighting / focus border?

I had to do all of the following to completely remove it:

outline-style: none;
box-shadow: none;
border-color: transparent;

Example:

_x000D_
_x000D_
button {_x000D_
  border-radius: 20px;_x000D_
  padding: 20px;_x000D_
}_x000D_
_x000D_
.no-focusborder:focus {_x000D_
  outline-style: none;_x000D_
  box-shadow: none;_x000D_
  border-color: transparent;_x000D_
  background-color: black;_x000D_
  color: white;_x000D_
}
_x000D_
<p>Click in the white space, then press the "Tab" key.</p>_x000D_
<button>Button 1 (unchanged)</button>_x000D_
<button class="no-focusborder">Button 2 (no focus border, custom focus indicator to show focus is present but the unwanted highlight is gone)</button>_x000D_
<br/><br/><br/><br/><br/><br/>
_x000D_
_x000D_
_x000D_

Bootstrap $('#myModal').modal('show') is not working

This can happen for a few reasons:

  1. You forgot to include Jquery library in the document
  2. You included the Jquery library more than once in the document
  3. You forgot to include bootstrap.js library in the document
  4. The versions of your Javascript and Bootstrap does not match. Refer bootstrap documentation to make sure the versions are matching
  5. The modal <div> is missing the modal class
  6. The id of the modal <div> is incorrect. (eg: you wrongly prepended # in the id of the <div>)
  7. # sign is missing in the Jquery selector

Set the maximum character length of a UITextField in Swift

Modern Swift

Note that much of the example code online regarding this problem is extremely out of date.

Paste the following into any Swift file in your project. (You can name the file anything, for example, "Handy.swift".)

This finally fixes one of the stupidest problems in iOS:

enter image description here

Your text fields now have a .maxLength.

It is completely OK to set that value in storyboard during development, or, set it in code while the app is running.

// simply have this in any Swift file, say, Handy.swift

import UIKit
private var __maxLengths = [UITextField: Int]()
extension UITextField {
    @IBInspectable var maxLength: Int {
        get {
            guard let l = __maxLengths[self] else {
               return 150 // (global default-limit. or just, Int.max)
            }
            return l
        }
        set {
            __maxLengths[self] = newValue
            addTarget(self, action: #selector(fix), for: .editingChanged)
        }
    }
    func fix(textField: UITextField) {
        let t = textField.text
        textField.text = t?.prefix(maxLength).string
    }
}

It's that simple.


Footnote - these days to safely truncate a String in swift, you simply .prefix(n)


An even simpler one-off version...

The above fixes all text fields in your project.

If you just want one particular text field to simply be limited to say "4", and that's that...

class PinCodeEntry: UITextField {
    
    override func didMoveToSuperview() {
        
        super.didMoveToSuperview()
        addTarget(self, action: #selector(fixMe), for: .editingChanged)
    }
    
    @objc private func fixMe() { text = text?.prefix(4) }
}

Phew! That's all there is to it.

(Just BTW, here's a similar very useful tip relating to UITextView, https://stackoverflow.com/a/42333832/294884 )


For the OCD programmer (like me)...

As @LeoDabus reminds, .prefix returns a substring. If you're incredibly caring, this

let t = textField.text
textField.text = t?.prefix(maxLength)

would be

if let t: String = textField.text {
    textField.text = String(t.prefix(maxLength))
}

Enjoy!

Change Bootstrap tooltip color

You can use this way:

<a href="#" data-toggle="tooltip" data-placement="bottom"
   title="" data-original-title="Tooltip on bottom"
   class="red-tooltip">Tooltip on bottom</a>

And in the CSS:

.tooltip-arrow,
.red-tooltip + .tooltip > .tooltip-inner {background-color: #f00;}

jsFiddle


Moeen MH: With the most recent version of bootstrap, you may need to do this in order to get rid of black arrow:

.red-tooltip + .tooltip.top > .tooltip-arrow {background-color: #f00;}

Use this for Bootstrap 4:

.bs-tooltip-auto[x-placement^=bottom] .arrow::before,
.bs-tooltip-bottom .arrow::before {
  border-bottom-color: #f00; /* Red */
}

Full Snippet:

_x000D_
_x000D_
$(function() {_x000D_
  $('[data-toggle="tooltip"]').tooltip()_x000D_
})
_x000D_
.tooltip-main {_x000D_
  width: 15px;_x000D_
  height: 15px;_x000D_
  border-radius: 50%;_x000D_
  font-weight: 700;_x000D_
  background: #f3f3f3;_x000D_
  border: 1px solid #737373;_x000D_
  color: #737373;_x000D_
  margin: 4px 121px 0 5px;_x000D_
  float: right;_x000D_
  text-align: left !important;_x000D_
}_x000D_
_x000D_
.tooltip-qm {_x000D_
  float: left;_x000D_
  margin: -2px 0px 3px 4px;_x000D_
  font-size: 12px;_x000D_
}_x000D_
_x000D_
.tooltip-inner {_x000D_
  max-width: 236px !important;_x000D_
  height: 76px;_x000D_
  font-size: 12px;_x000D_
  padding: 10px 15px 10px 20px;_x000D_
  background: #FFFFFF;_x000D_
  color: rgb(0, 0, 0, .7);_x000D_
  border: 1px solid #737373;_x000D_
  text-align: left;_x000D_
}_x000D_
_x000D_
.tooltip.show {_x000D_
  opacity: 1;_x000D_
}_x000D_
_x000D_
.bs-tooltip-auto[x-placement^=bottom] .arrow::before,_x000D_
.bs-tooltip-bottom .arrow::before {_x000D_
  border-bottom-color: #f00;_x000D_
  /* Red */_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.bundle.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="tooltip-main" data-toggle="tooltip" data-placement="top" data-original-title="Hello world"><span class="tooltip-qm">?</span></div>_x000D_
<style>_x000D_
  .bs-tooltip-auto[x-placement^=bottom] .arrow::before,_x000D_
  .bs-tooltip-bottom .arrow::before {_x000D_
    border-bottom-color: #f00;_x000D_
    /* Red */_x000D_
  }_x000D_
</style>
_x000D_
_x000D_
_x000D_

UITextField text change event

Swift 4

func addNotificationObservers() {

    NotificationCenter.default.addObserver(self, selector: #selector(textFieldDidChangeAction(_:)), name: .UITextFieldTextDidChange, object: nil)

}

@objc func textFieldDidChangeAction(_ notification: NSNotification) {

    let textField = notification.object as! UITextField
    print(textField.text!)

}

PostgreSQL - SQL state: 42601 syntax error

Your function would work like this:

CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS 
$$
BEGIN

RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;

END     
$$ LANGUAGE plpgsql;

Call:

SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
  • You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.

  • The aggregate function count() returns bigint, but you had rowcount defined as integer, so you need an explicit cast ::int to make this work

  • I use dollar quoting to avoid quoting hell.

However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.

Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)

The query itself seems rather odd, btw. But that's beside the point here.

DataTrigger where value is NOT null?

You can use DataTrigger class in Microsoft.Expression.Interactions.dll that come with Expression Blend.

Code Sample:

<i:Interaction.Triggers>
    <i:DataTrigger Binding="{Binding YourProperty}" Value="{x:Null}" Comparison="NotEqual">
       <ie:ChangePropertyAction PropertyName="YourTargetPropertyName" Value="{Binding YourValue}"/>
    </i:DataTrigger
</i:Interaction.Triggers>

Using this method you can trigger against GreaterThan and LessThan too. In order to use this code you should reference two dll's:

System.Windows.Interactivity.dll

Microsoft.Expression.Interactions.dll

How to Define Callbacks in Android?

Example to implement callback method using interface.

Define the interface, NewInterface.java.

package javaapplication1;

public interface NewInterface {
    void callback();
}

Create a new class, NewClass.java. It will call the callback method in main class.

package javaapplication1;

public class NewClass {

    private NewInterface mainClass;

    public NewClass(NewInterface mClass){
        mainClass = mClass;
    }

    public void calledFromMain(){
        //Do somthing...

        //call back main
        mainClass.callback();
    }
}

The main class, JavaApplication1.java, to implement the interface NewInterface - callback() method. It will create and call NewClass object. Then, the NewClass object will callback it's callback() method in turn.

package javaapplication1;
public class JavaApplication1 implements NewInterface{

    NewClass newClass;

    public static void main(String[] args) {

        System.out.println("test...");

        JavaApplication1 myApplication = new JavaApplication1();
        myApplication.doSomething();

    }

    private void doSomething(){
        newClass = new NewClass(this);
        newClass.calledFromMain();
    }

    @Override
    public void callback() {
        System.out.println("callback");
    }

}

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

You are missing the python mysqldb library. Use this command (for Debian/Ubuntu) to install it: sudo apt-get install python-mysqldb

Query based on multiple where clauses in Firebase

Using Firebase's Query API, you might be tempted to try this:

// !!! THIS WILL NOT WORK !!!
ref
  .orderBy('genre')
  .startAt('comedy').endAt('comedy')
  .orderBy('lead')                  // !!! THIS LINE WILL RAISE AN ERROR !!!
  .startAt('Jack Nicholson').endAt('Jack Nicholson')
  .on('value', function(snapshot) { 
      console.log(snapshot.val()); 
  });

But as @RobDiMarco from Firebase says in the comments:

multiple orderBy() calls will throw an error

So my code above will not work.

I know of three approaches that will work.

1. filter most on the server, do the rest on the client

What you can do is execute one orderBy().startAt()./endAt() on the server, pull down the remaining data and filter that in JavaScript code on your client.

ref
  .orderBy('genre')
  .equalTo('comedy')
  .on('child_added', function(snapshot) { 
      var movie = snapshot.val();
      if (movie.lead == 'Jack Nicholson') {
          console.log(movie);
      }
  });

2. add a property that combines the values that you want to filter on

If that isn't good enough, you should consider modifying/expanding your data to allow your use-case. For example: you could stuff genre+lead into a single property that you just use for this filter.

"movie1": {
    "genre": "comedy",
    "name": "As good as it gets",
    "lead": "Jack Nicholson",
    "genre_lead": "comedy_Jack Nicholson"
}, //...

You're essentially building your own multi-column index that way and can query it with:

ref
  .orderBy('genre_lead')
  .equalTo('comedy_Jack Nicholson')
  .on('child_added', function(snapshot) { 
      var movie = snapshot.val();
      console.log(movie);
  });

David East has written a library called QueryBase that helps with generating such properties.

You could even do relative/range queries, let's say that you want to allow querying movies by category and year. You'd use this data structure:

"movie1": {
    "genre": "comedy",
    "name": "As good as it gets",
    "lead": "Jack Nicholson",
    "genre_year": "comedy_1997"
}, //...

And then query for comedies of the 90s with:

ref
  .orderBy('genre_year')
  .startAt('comedy_1990')
  .endAt('comedy_2000')
  .on('child_added', function(snapshot) { 
      var movie = snapshot.val();
      console.log(movie);
  });

If you need to filter on more than just the year, make sure to add the other date parts in descending order, e.g. "comedy_1997-12-25". This way the lexicographical ordering that Firebase does on string values will be the same as the chronological ordering.

This combining of values in a property can work with more than two values, but you can only do a range filter on the last value in the composite property.

A very special variant of this is implemented by the GeoFire library for Firebase. This library combines the latitude and longitude of a location into a so-called Geohash, which can then be used to do realtime range queries on Firebase.

3. create a custom index programmatically

Yet another alternative is to do what we've all done before this new Query API was added: create an index in a different node:

  "movies"
      // the same structure you have today
  "by_genre"
      "comedy"
          "by_lead"
              "Jack Nicholson"
                  "movie1"
              "Jim Carrey"
                  "movie3"
      "Horror"
          "by_lead"
              "Jack Nicholson"
                  "movie2"
      

There are probably more approaches. For example, this answer highlights an alternative tree-shaped custom index: https://stackoverflow.com/a/34105063


If none of these options work for you, but you still want to store your data in Firebase, you can also consider using its Cloud Firestore database.

Cloud Firestore can handle multiple equality filters in a single query, but only one range filter. Under the hood it essentially uses the same query model, but it's like it auto-generates the composite properties for you. See Firestore's documentation on compound queries.

Extract the first word of a string in a SQL Server query

Enhancement of Ben Brandt's answer to compensate even if the string starts with space by applying LTRIM(). Tried to edit his answer but rejected, so I am now posting it here separately.

DECLARE @test NVARCHAR(255)
SET @test = 'First Second'

SELECT SUBSTRING(LTRIM(@test),1,(CHARINDEX(' ',LTRIM(@test) + ' ')-1))

Best practice: PHP Magic Methods __set and __get

I do a mix of edem's answer and your second code. This way, I have the benefits of common getter/setters (code completion in your IDE), ease of coding if I want, exceptions due to inexistent properties (great for discovering typos: $foo->naem instead of $foo->name), read only properties and compound properties.

class Foo
{
    private $_bar;
    private $_baz;

    public function getBar()
    {
        return $this->_bar;
    }

    public function setBar($value)
    {
        $this->_bar = $value;
    }

    public function getBaz()
    {
        return $this->_baz;
    }

    public function getBarBaz()
    {
        return $this->_bar . ' ' . $this->_baz;
    }

    public function __get($var)
    {
        $func = 'get'.$var;
        if (method_exists($this, $func))
        {
            return $this->$func();
        } else {
            throw new InexistentPropertyException("Inexistent property: $var");
        }
    }

    public function __set($var, $value)
    {
        $func = 'set'.$var;
        if (method_exists($this, $func))
        {
            $this->$func($value);
        } else {
            if (method_exists($this, 'get'.$var))
            {
                throw new ReadOnlyException("property $var is read-only");
            } else {
                throw new InexistentPropertyException("Inexistent property: $var");
            }
        }
    }
}

Convert datetime value into string

This is super old, but I figured I'd add my 2c. DATE_FORMAT does indeed return a string, but I was looking for the CAST function, in the situation that I already had a datetime string in the database and needed to pattern match against it:

http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html

In this case, you'd use:

CAST(date_value AS char)

This answers a slightly different question, but the question title seems ambiguous enough that this might help someone searching.

scp copy directory to another server with private key auth

Covert .ppk to id_rsa using tool PuttyGen, (http://mydailyfindingsit.blogspot.in/2015/08/create-keys-for-your-linux-machine.html) and

scp -C -i ./id_rsa -r /var/www/* [email protected]:/var/www

it should work !

How to delete an item in a list if it exists?

Eek, don't do anything that complicated : )

Just filter() your tags. bool() returns False for empty strings, so instead of

new_tag_list = f1.striplist(tag_string.split(",") + selected_tags)

you should write

new_tag_list = filter(bool, f1.striplist(tag_string.split(",") + selected_tags))

or better yet, put this logic inside striplist() so that it doesn't return empty strings in the first place.

Wait until boolean value changes it state

This is not my prefered way to do this, cause of massive CPU consumption.

If that is actually your working code, then just keep it like that. Checking a boolean once a second causes NO measurable CPU load. None whatsoever.

The real problem is that the thread that checks the value may not see a change that has happened for an arbitrarily long time due to caching. To ensure that the value is always synchronized between threads, you need to put the volatile keyword in the variable definition, i.e.

private volatile boolean value;

Note that putting the access in a synchronized block, such as when using the notification-based solution described in other answers, will have the same effect.

Get changes from master into branch in Git

Easy way

# 1. Create a new remote branch A base on last master
# 2. Checkout A
# 3. Merge aq to A

Find a string between 2 known values

For future reference, I found this code snippet at http://www.mycsharpcorner.com/Post.aspx?postID=15 If you need to search for different "tags" it works very well.

    public static string[] GetStringInBetween(string strBegin,
        string strEnd, string strSource,
        bool includeBegin, bool includeEnd)           
    {
        string[] result ={ "", "" };
        int iIndexOfBegin = strSource.IndexOf(strBegin);
        if (iIndexOfBegin != -1)
        {
            // include the Begin string if desired
            if (includeBegin)
                iIndexOfBegin -= strBegin.Length;
            strSource = strSource.Substring(iIndexOfBegin
                + strBegin.Length);
            int iEnd = strSource.IndexOf(strEnd);
            if (iEnd != -1)
            {
                // include the End string if desired
                if (includeEnd)
                    iEnd += strEnd.Length;
                result[0] = strSource.Substring(0, iEnd);
                // advance beyond this segment
                if (iEnd + strEnd.Length < strSource.Length)
                    result[1] = strSource.Substring(iEnd
                        + strEnd.Length);
            }
        }
        else
            // stay where we are
            result[1] = strSource;
        return result;
    }

HTML: can I display button text in multiple lines?

This CSS might work for <input type="button" ..:

white-space: normal

How to implement LIMIT with SQL Server?

If your ID is unique identifier type or your id in table is not sorted you must do like this below.

select * from
(select ROW_NUMBER() OVER (ORDER BY (select 0)) AS RowNumber,* from table1) a
where a.RowNumber between 2 and 5



The code will be

select * from limit 2,5

Find closest previous element jQuery

No, there is no "easy" way. Your best bet would be to do a loop where you first check each previous sibling, then move to the parent node and all of its previous siblings.

You'll need to break the selector into two, 1 to check if the current node could be the top level node in your selector, and 1 to check if it's descendants match.

Edit: This might as well be a plugin. You can use this with any selector in any HTML:

(function($) {
    $.fn.closestPrior = function(selector) {
        selector = selector.replace(/^\s+|\s+$/g, "");
        var combinator = selector.search(/[ +~>]|$/);
        var parent = selector.substr(0, combinator);
        var children = selector.substr(combinator);
        var el = this;
        var match = $();
        while (el.length && !match.length) {
            el = el.prev();
            if (!el.length) {
                var par = el.parent();
                // Don't use the parent - you've already checked all of the previous 
                // elements in this parent, move to its previous sibling, if any.
                while (par.length && !par.prev().length) {
                    par = par.parent();
                }
                el = par.prev();
                if (!el.length) {
                    break;
                }
            }
            if (el.is(parent) && el.find(children).length) {
                match = el.find(children).last();
            }
            else if (el.find(selector).length) {
                match = el.find(selector).last();
            }
        }
        return match;
    }
})(jQuery);

How to replace sql field value

You could just use REPLACE:

UPDATE myTable SET emailCol = REPLACE(emailCol, '.com', '.org')`.

But take into account an email address such as [email protected] will be updated to [email protected].

If you want to be on a safer side, you should check for the last 4 characters using RIGHT, and append .org to the SUBSTRING manually instead. Notice the usage of UPPER to make the search for the .com ending case insensitive.

UPDATE myTable 
SET emailCol = SUBSTRING(emailCol, 1, LEN(emailCol)-4) + '.org'
WHERE UPPER(RIGHT(emailCol,4)) = '.COM';

See it working in this SQLFiddle.

How to convert integer to char in C?

 void main ()
 {
    int temp,integer,count=0,i,cnd=0;
    char ascii[10]={0};
    printf("enter a number");
    scanf("%d",&integer);


     if(integer>>31)
     {
     /*CONVERTING 2's complement value to normal value*/    
     integer=~integer+1;    
     for(temp=integer;temp!=0;temp/=10,count++);    
     ascii[0]=0x2D;
     count++;
     cnd=1;
     }
     else
     for(temp=integer;temp!=0;temp/=10,count++);    
     for(i=count-1,temp=integer;i>=cnd;i--)
     {

        ascii[i]=(temp%10)+0x30;
        temp/=10;
     }
    printf("\n count =%d ascii=%s ",count,ascii);

 }

Downloading images with node.js

I ran into this problem some days ago, for a pure NodeJS answer I would suggest using Stream to merge the chunks together.

var http = require('http'),                                                
    Stream = require('stream').Transform,                                  
    fs = require('fs');                                                    

var url = 'http://www.google.com/images/srpr/logo11w.png';                    

http.request(url, function(response) {                                        
  var data = new Stream();                                                    

  response.on('data', function(chunk) {                                       
    data.push(chunk);                                                         
  });                                                                         

  response.on('end', function() {                                             
    fs.writeFileSync('image.png', data.read());                               
  });                                                                         
}).end();

The newest Node versions won't work well with binary strings, so merging chunks with strings is not a good idea when working with binary data.

*Just be careful when using 'data.read()', it will empty the stream for the next 'read()' operation. If you want to use it more than once, store it somewhere.

What is the difference between os.path.basename() and os.path.dirname()?

Both functions use the os.path.split(path) function to split the pathname path into a pair; (head, tail).

The os.path.dirname(path) function returns the head of the path.

E.g.: The dirname of '/foo/bar/item' is '/foo/bar'.

The os.path.basename(path) function returns the tail of the path.

E.g.: The basename of '/foo/bar/item' returns 'item'

From: http://docs.python.org/2/library/os.path.html#os.path.basename

Match exact string

It depends. You could

string.match(/^abc$/)

But that would not match the following string: 'the first 3 letters of the alphabet are abc. not abc123'

I think you would want to use \b (word boundaries):

_x000D_
_x000D_
var str = 'the first 3 letters of the alphabet are abc. not abc123';_x000D_
var pat = /\b(abc)\b/g;_x000D_
console.log(str.match(pat));
_x000D_
_x000D_
_x000D_

Live example: http://jsfiddle.net/uu5VJ/

If the former solution works for you, I would advise against using it.

That means you may have something like the following:

var strs = ['abc', 'abc1', 'abc2']
for (var i = 0; i < strs.length; i++) {
    if (strs[i] == 'abc') {
        //do something 
    }
    else {
        //do something else
    }
}

While you could use

if (str[i].match(/^abc$/g)) {
    //do something 
}

It would be considerably more resource-intensive. For me, a general rule of thumb is for a simple string comparison use a conditional expression, for a more dynamic pattern use a regular expression.

More on JavaScript regexes: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

Return array from function

Your BlockID function uses the undefined variable images, which will lead to an error. Also, you should not use an Array here - JavaScripts key-value-maps are plain objects:

function BlockID() {
    return {
        "s": "Images/Block_01.png",
        "g": "Images/Block_02.png",
        "C": "Images/Block_03.png",
        "d": "Images/Block_04.png"
    };
}

MySQL error - #1062 - Duplicate entry ' ' for key 2

  1. Drop the primary key first: (The primary key is your responsibility)

    ALTER TABLE Persons DROP PRIMARY KEY ;
    
  2. Then make all insertions:

  3. Add new primary key just like before dropping:

    ALTER TABLE Persons ADD PRIMARY KEY (P_Id);
    

Find row in datatable with specific id

You can use LINQ to DataSet/DataTable

var rows = dt.AsEnumerable()
               .Where(r=> r.Field<int>("ID") == 5);

Since each row has a unique ID, you should use Single/SingleOrDefault which would throw exception if you get multiple records back.

DataRow dr = dt.AsEnumerable()
               .SingleOrDefault(r=> r.Field<int>("ID") == 5);

(Substitute int for the type of your ID field)

CSS for grabbing cursors (drag & drop)

In case anyone else stumbles across this question, this is probably what you were looking for:

.grabbable {
    cursor: move; /* fallback if grab cursor is unsupported */
    cursor: grab;
    cursor: -moz-grab;
    cursor: -webkit-grab;
}

 /* (Optional) Apply a "closed-hand" cursor during drag operation. */
.grabbable:active {
    cursor: grabbing;
    cursor: -moz-grabbing;
    cursor: -webkit-grabbing;
}

LINQ Contains Case Insensitive

Assuming we're working with strings here, here's another "elegant" solution using IndexOf().

public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
    return this.ObjectContext.FACILITY_ITEM
        .Where(fi => fi.DESCRIPTION
                       .IndexOf(description, StringComparison.OrdinalIgnoreCase) != -1);
}

When to use SELECT ... FOR UPDATE?

Short answers:

Q1: Yes.

Q2: Doesn't matter which you use.

Long answer:

A select ... for update will (as it implies) select certain rows but also lock them as if they have already been updated by the current transaction (or as if the identity update had been performed). This allows you to update them again in the current transaction and then commit, without another transaction being able to modify these rows in any way.

Another way of looking at it, it is as if the following two statements are executed atomically:

select * from my_table where my_condition;

update my_table set my_column = my_column where my_condition;

Since the rows affected by my_condition are locked, no other transaction can modify them in any way, and hence, transaction isolation level makes no difference here.

Note also that transaction isolation level is independent of locking: setting a different isolation level doesn't allow you to get around locking and update rows in a different transaction that are locked by your transaction.

What transaction isolation levels do guarantee (at different levels) is the consistency of data while transactions are in progress.

Regular expression to match any character being repeated more than 10 times

You can also use PowerShell to quickly replace words or character reptitions. PowerShell is for Windows. Current version is 3.0.

$oldfile = "$env:windir\WindowsUpdate.log"

$newfile = "$env:temp\newfile.txt"
$text = (Get-Content -Path $oldfile -ReadCount 0) -join "`n"

$text -replace '/(.)\1{9,}/', ' ' | Set-Content -Path $newfile

Find package name for Android apps to use Intent to launch Market app from web

The following bash script can be used to display the package and activity names in an apk, and launch the application by passing it an APK file.

apk_start.sh

package=`aapt dump badging $* | grep package | awk '{print $2}' | sed s/name=//g | sed s/\'//g`
activity=`aapt dump badging $* | grep Activity | awk '{print $2}' | sed s/name=//g | sed s/\'//g`
echo
echo package : $package
echo activity: $activity
echo
echo Launching application on device....
echo
adb shell am start -n $package/$activity

Then to launch the application in the emulator, simply supply the APK filename like so:

apk_start.sh /tmp/MyApp.apk

Of course if you just want the package and activity name of the apk to be displayed, delete the last line of the script.

You can stop an application in the same way by using this script:

apk_stop.sh

package=`aapt dump badging $* | grep package | awk '{print $2}' | sed s/name=//g | sed s/\'//g`
adb shell am force-stop $package

like so:

apk_stop.sh /tmp/MyApp.apk

Important Note: aapt can be found here:

<android_sdk_home>/build-tools/android-<ver>/aapt

TypeError: Cannot read property 'then' of undefined

TypeError: Cannot read property 'then' of undefined when calling a Django service using AngularJS.

If you are calling a Python service, the code will look like below:

this.updateTalentSupplier=function(supplierObj){
  var promise = $http({
    method: 'POST',
      url: bbConfig.BWS+'updateTalentSupplier/',
      data:supplierObj,
      withCredentials: false,
      contentType:'application/json',
      dataType:'json'
    });
    return promise; //Promise is returned 
}

We are using MongoDB as the database(I know it doesn't matter. But if someone is searching with MongoDB + Python (Django) + AngularJS the result should come.

Convert AM/PM time to 24 hours format?

DateTime dt = DateTime.Parse("01:00 pm"); //Time in string formate

TimeSpan time = new TimeSpan(); 

time = dt.TimeOfDay;

Console.WriteLine(time);

Result : 13:00:00

What are C++ functors and their uses?

Except for used in callback, C++ functors can also help to provide a Matlab liking access style to a matrix class. There is a example.

Create Generic method constraining T to an Enum

I do have specific requirement where I required to use enum with text associated with enum value. For example when I use enum to specify error type it required to describe error details.

public static class XmlEnumExtension
{
    public static string ReadXmlEnumAttribute(this Enum value)
    {
        if (value == null) throw new ArgumentNullException("value");
        var attribs = (XmlEnumAttribute[]) value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof (XmlEnumAttribute), true);
        return attribs.Length > 0 ? attribs[0].Name : value.ToString();
    }

    public static T ParseXmlEnumAttribute<T>(this string str)
    {
        foreach (T item in Enum.GetValues(typeof(T)))
        {
            var attribs = (XmlEnumAttribute[])item.GetType().GetField(item.ToString()).GetCustomAttributes(typeof(XmlEnumAttribute), true);
            if(attribs.Length > 0 && attribs[0].Name.Equals(str)) return item;
        }
        return (T)Enum.Parse(typeof(T), str, true);
    }
}

public enum MyEnum
{
    [XmlEnum("First Value")]
    One,
    [XmlEnum("Second Value")]
    Two,
    Three
}

 static void Main()
 {
    // Parsing from XmlEnum attribute
    var str = "Second Value";
    var me = str.ParseXmlEnumAttribute<MyEnum>();
    System.Console.WriteLine(me.ReadXmlEnumAttribute());
    // Parsing without XmlEnum
    str = "Three";
    me = str.ParseXmlEnumAttribute<MyEnum>();
    System.Console.WriteLine(me.ReadXmlEnumAttribute());
    me = MyEnum.One;
    System.Console.WriteLine(me.ReadXmlEnumAttribute());
}

How to include a sub-view in Blade templates?

EDIT: Below was the preferred solution in 2014. Nowadays you should use @include, as mentioned in the other answer.


In Laravel views the dot is used as folder separator. So for example I have this code

return View::make('auth.details', array('id' => $id));

which points to app/views/auth/details.blade.php

And to include a view inside a view you do like this:

file: layout.blade.php

<html>
  <html stuff>
  @yield('content')
</html>

file: hello.blade.php

@extends('layout')

@section('content')
  <html stuff>
@stop

SQL query with avg and group by

As I understand, you want the average value for each id at each pass. The solution is

SELECT id, pass, avg(value) FROM data_r1
GROUP BY id, pass;

Programmatically change UITextField Keyboard type

There is a property for this called keyboardType. What you'll want to do is replace where you have strings @"Number Pad and @"Default with UIKeyboardTypeNumberPad and UIKeyboardTypeDefault.

Your new code should look something like this:

if(user is prompted for numeric input only)
    [textField setKeyboardType:UIKeyboardTypeNumberPad];

else if(user is prompted for alphanumeric input)
    [textField setKeyboardType:UIKeyboardTypeDefault];

Good Luck!

Get the last non-empty cell in a column in Google Sheets

There may be a more eloquent way, but this is the way I came up with:

The function to find the last populated cell in a column is:

=INDEX( FILTER( A:A ; NOT( ISBLANK( A:A ) ) ) ; ROWS( FILTER( A:A ; NOT( ISBLANK( A:A ) ) ) ) )

So if you combine it with your current function it would look like this:

=DAYS360(A2,INDEX( FILTER( A:A ; NOT( ISBLANK( A:A ) ) ) ; ROWS( FILTER( A:A ; NOT( ISBLANK( A:A ) ) ) ) ))

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

My solution was to do a combination of these two resources:

https://gist.github.com/tamoyal/2ea1fcdf99c819b4e07d

and

http://www.gab.lc/articles/migration_postgresql_9-3_to_9-4

The second one helped more then the first one. Also to not, don't follow the steps as is as some are not necessary. Also, if you are not being able to backup the data via postgres console, you can use alternative approach, and backup it with pgAdmin 3 or some other program, like I did in my case.

Also, the link: https://help.ubuntu.com/stable/serverguide/postgresql.html Helped to set the encrypted password and set md5 for authenticating the postgres user.

After all is done, to check the postgres server version run in terminal:

sudo -u postgres psql postgres

After entering the password run in postgres terminal:

SHOW SERVER_VERSION;

It will output something like:

 server_version 
----------------
 9.4.5

For setting and starting postgres I have used command:

> sudo bash # root
> su postgres # postgres

> /etc/init.d/postgresql start
> /etc/init.d/postgresql stop

And then for restoring database from a file:

> psql -f /home/ubuntu_username/Backup_93.sql postgres

Or if doesn't work try with this one:

> pg_restore --verbose --clean --no-acl --no-owner -h localhost -U postgres -d name_of_database ~/your_file.dump

And if you are using Rails do a bundle exec rake db:migrate after pulling the code :)

Facebook page automatic "like" URL (for QR Code)

The answers above seem partly outdated.

The URL builder on https://developers.facebook.com/docs/plugins/like-button/ worked nicely for me.

You can configure, preview and the get the code/URL in different flavors: HTML5, XFBML, IFRAME, URL

Mysql - How to quit/exit from stored procedure

To handle this situation in a portable way (ie will work on all databases because it doesn’t use MySQL label Kung fu), break the procedure up into logic parts, like this:

CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
BEGIN
     IF tablename IS NOT NULL THEN
         CALL SP_Reporting_2(tablename);
     END IF;
END;

CREATE PROCEDURE SP_Reporting_2(IN tablename VARCHAR(20))
BEGIN
     #proceed with code
END;

What exactly does Double mean in java?

A double is an IEEE754 double-precision floating point number, similar to a float but with a larger range and precision.

IEEE754 single precision numbers have 32 bits (1 sign, 8 exponent and 23 mantissa bits) while double precision numbers have 64 bits (1 sign, 11 exponent and 52 mantissa bits).

A Double in Java is the class version of the double basic type - you can use doubles but, if you want to do something with them that requires them to be an object (such as put them in a collection), you'll need to box them up in a Double object.

Best way to do multiple constructors in PHP

I know I'm super late to the party here, but I came up with a fairly flexible pattern that should allow some really interesting and versatile implementations.

Set up your class as you normally would, with whatever variables you like.

class MyClass{
    protected $myVar1;
    protected $myVar2;

    public function __construct($obj = null){
        if($obj){
            foreach (((object)$obj) as $key => $value) {
                if(isset($value) && in_array($key, array_keys(get_object_vars($this)))){
                    $this->$key = $value;
                }
            }
        }
    }
}

When you make your object just pass an associative array with the keys of the array the same as the names of your vars, like so...

$sample_variable = new MyClass([
    'myVar2'=>123, 
    'i_dont_want_this_one'=> 'This won\'t make it into the class'
    ]);

print_r($sample_variable);

The print_r($sample_variable); after this instantiation yields the following:

MyClass Object ( [myVar1:protected] => [myVar2:protected] => 123 )

Because we've initialize $group to null in our __construct(...), it is also valid to pass nothing whatsoever into the constructor as well, like so...

$sample_variable = new MyClass();

print_r($sample_variable);

Now the output is exactly as expected:

MyClass Object ( [myVar1:protected] => [myVar2:protected] => )

The reason I wrote this was so that I could directly pass the output of json_decode(...) to my constructor, and not worry about it too much.

This was executed in PHP 7.1. Enjoy!

What does android:layout_weight mean?

In a nutshell, layout_weight specifies how much of the extra space in the layout to be allocated to the View.

LinearLayout supports assigning a weight to individual children. This attribute assigns an "importance" value to a view, and allows it to expand to fill any remaining space in the parent view. Views' default weight is zero.

Calculation to assign any remaining space between child

In general, the formula is:

space assigned to child = (child's individual weight) / (sum of weight of every child in Linear Layout)

Example 1

If there are three text boxes and two of them declare a weight of 1, while the third one is given no weight (0), then remaining space is assigned as follows:

1st text box = 1/(1+1+0)

2nd text box = 1/(1+1+0)

3rd text box = 0/(1+1+0)

Example 2

Let's say we have a text label and two text edit elements in a horizontal row. The label has no layout_weight specified, so it takes up the minimum space required to render. If the layout_weight of each of the two text edit elements is set to 1, the remaining width in the parent layout will be split equally between them (because we claim they are equally important).

Calculation:

1st label = 0/(0+1+1)

2nd text box = 1/(0+1+1)

3rd text box = 1/(0+1+1)

If, instead, the first one text box has a layout_weight of 1, and the second text box has a layout_weight of 2, then one third of the remaining space will be given to the first, and two thirds to the second (because we claim the second one is more important).

Calculation:

1st label = 0/(0+1+2)

2nd text box = 1/(0+1+2)

3rd text box = 2/(0+1+2)


Source article

How to hide command output in Bash

Use this.

{
  /your/first/command
  /your/second/command
} &> /dev/null

Explanation

To eliminate output from commands, you have two options:

  • Close the output descriptor file, which keeps it from accepting any more input. That looks like this:

    your_command "Is anybody listening?" >&-
    

    Usually, output goes either to file descriptor 1 (stdout) or 2 (stderr). If you close a file descriptor, you'll have to do so for every numbered descriptor, as &> (below) is a special BASH syntax incompatible with >&-:

    /your/first/command >&- 2>&-
    

    Be careful to note the order: >&- closes stdout, which is what you want to do; &>- redirects stdout and stderr to a file named - (hyphen), which is not what what you want to do. It'll look the same at first, but the latter creates a stray file in your working directory. It's easy to remember: >&2 redirects stdout to descriptor 2 (stderr), >&3 redirects stdout to descriptor 3, and >&- redirects stdout to a dead end (i.e. it closes stdout).

    Also beware that some commands may not handle a closed file descriptor particularly well ("write error: Bad file descriptor"), which is why the better solution may be to...

  • Redirect output to /dev/null, which accepts all output and does nothing with it. It looks like this:

    your_command "Hello?" > /dev/null
    

    For output redirection to a file, you can direct both stdout and stderr to the same place very concisely, but only in bash:

    /your/first/command &> /dev/null
    

Finally, to do the same for a number of commands at once, surround the whole thing in curly braces. Bash treats this as a group of commands, aggregating the output file descriptors so you can redirect all at once. If you're familiar instead with subshells using ( command1; command2; ) syntax, you'll find the braces behave almost exactly the same way, except that unless you involve them in a pipe the braces will not create a subshell and thus will allow you to set variables inside.

{
  /your/first/command
  /your/second/command
} &> /dev/null

See the bash manual on redirections for more details, options, and syntax.

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3

For me it was a problem with firebase package.

Only add "@firebase/database": "0.2.1", for your package.json, reinstall node_modules and works.

How to use a decimal range() step value?

Here's a solution using itertools:

import itertools

def seq(start, end, step):
    if step == 0:
        raise ValueError("step must not be 0")
    sample_count = int(abs(end - start) / step)
    return itertools.islice(itertools.count(start, step), sample_count)

Usage Example:

for i in seq(0, 1, 0.1):
    print(i)

twitter-bootstrap: how to get rid of underlined button text when hovering over a btn-group within an <a>-tag?

Easy way to remove the underline from the anchor tag if you use bootstrap. for my case, I used to like this;

 <a href="#first1" class=" nav-link">
   <button type="button" class="btn btn-warning btn-lg btn-block">
   Reserve Table
   </button>
 </a>

How can I get the SQL of a PreparedStatement?

If you're using MySQL you can log the queries using MySQL's query log. I don't know if other vendors provide this feature, but chances are they do.

Drawable image on a canvas

Drawable d = ContextCompat.getDrawable(context, R.drawable.***)
d.setBounds(left, top, right, bottom);
d.draw(canvas);

How do I get the old value of a changed cell in Excel VBA?

an idea ...

  • write these in the ThisWorkbook module
  • close and open the workbook
    Public LastCell As Range

    Private Sub Workbook_Open()

        Set LastCell = ActiveCell

    End Sub

    Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)

        Set oa = LastCell.Comment

        If Not oa Is Nothing Then
        LastCell.Comment.Delete
        End If

        Target.AddComment Target.Address
        Target.Comment.Visible = True
        Set LastCell = ActiveCell

    End Sub

How to wait for async method to complete?

The following snippet shows a way to ensure the awaited method completes before returning to the caller. HOWEVER, I wouldn't say it's good practice. Please edit my answer with explanations if you think otherwise.

public async Task AnAsyncMethodThatCompletes()
{
    await SomeAsyncMethod();
    DoSomeMoreStuff();
    await Task.Factory.StartNew(() => { }); // <-- This line here, at the end
}

await AnAsyncMethodThatCompletes();
Console.WriteLine("AnAsyncMethodThatCompletes() completed.")

Connecting to smtp.gmail.com via command line

gmail uses an encrypted connection. So, even after you establish a connection, you wont be able to send any email. The encryption is a little complex to manage. Try using openssl instead.

The thread below should help-

How to send email using simple SMTP commands via Gmail?

How can I get an object's absolute position on the page in Javascript?

var cumulativeOffset = function(element) {
    var top = 0, left = 0;
    do {
        top += element.offsetTop  || 0;
        left += element.offsetLeft || 0;
        element = element.offsetParent;
    } while(element);

    return {
        top: top,
        left: left
    };
};

(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)

Assign an initial value to radio button as checked

For anyone looking for an Angular2 (2.4.8) solution, since this is a generically-popular question when searching:

<div *ngFor="let choice of choices">
  <input type="radio" [checked]="choice == defaultChoice">
</div>

This will add the checked attribute to the input given the condition, but will add nothing if the condition fails.

Do not do this:

[attr.checked]="choice == defaultChoice"

because this will add the attribute checked="false" to every other input element.

Since the browser only looks for the presence of the checked attribute (the key), ignoring its value, so the last input in the group will be checked.

Get started with Latex on Linux

To get started with LaTeX on Linux, you're going to need to install a couple of packages:

  1. You're going to need a LaTeX distribution. This is the collection of programs that comprise the (La)TeX computer typesetting system. The standard LaTeX distribution on Unix systems used to be teTeX, but it has been superceded by TeX Live. Most Linux distributions have installation packages for TeX Live--see, for example, the package database entries for Ubuntu and Fedora.

  2. You will probably want to install a LaTeX editor. Standard Linux text editors will work fine; in particular, Emacs has a nice package of (La)TeX editing macros called AUCTeX. Specialized LaTeX editors also exist; of those, Kile (KDE Integrated LaTeX Environment) is particularly nice.

  3. You will probably want a LaTeX tutorial. The classic tutorial is "A (Not So) Short Introduction to LaTeX2e," but nowadays the LaTeX wikibook might be a better choice.

Linux command to print directory structure in the form of a tree

Since it was a successful comment, I am adding it as an answer:
with files:

 find . | sed -e "s/[^-][^\/]*\//  |/g" -e "s/|\([^ ]\)/|-\1/" 

If file exists then delete the file

You're close, you just need to delete the file before trying to over-write it.

dim infolder: set infolder = fso.GetFolder(IN_PATH)
dim file: for each file in infolder.Files

    dim name: name = file.name
    dim parts: parts = split(name, ".")

    if UBound(parts) = 2 then

       ' file name like a.c.pdf    

        dim newname: newname = parts(0) & "." & parts(2)
        dim newpath: newpath = fso.BuildPath(OUT_PATH, newname)

        ' warning:
        ' if we have source files C:\IN_PATH\ABC.01.PDF, C:\IN_PATH\ABC.02.PDF, ...
        ' only one of them will be saved as D:\OUT_PATH\ABC.PDF

        if fso.FileExists(newpath) then
            fso.DeleteFile newpath
        end if

        file.Move newpath

    end if

next

How do I update Anaconda?

To update your installed version to the latest version, say 2019.07, run:

conda install anaconda=2019.07

In most cases, this method can meet your needs and avoid dependency problems.

casting int to char using C++ style casting

You can implicitly convert between numerical types, even when that loses precision:

char c = i;

However, you might like to enable compiler warnings to avoid potentially lossy conversions like this. If you do, then use static_cast for the conversion.

Of the other casts:

  • dynamic_cast only works for pointers or references to polymorphic class types;
  • const_cast can't change types, only const or volatile qualifiers;
  • reinterpret_cast is for special circumstances, converting between pointers or references and completely unrelated types. Specifically, it won't do numeric conversions.
  • C-style and function-style casts do whatever combination of static_cast, const_cast and reinterpret_cast is needed to get the job done.

What's the difference between dependencies, devDependencies and peerDependencies in npm package.json file?

Dependencies vs dev dependencies

Dev dependencies are modules which are only required during development whereas dependencies are required at runtime. If you are deploying your application, dependencies has to be installed, or else your app simply will not work. Libraries that you call from your code that enables the program to run can be considered as dependencies.

Eg- React , React - dom

Dev dependency modules need not be installed in the production server since you are not gonna develop in that machine .compilers that covert your code to javascript , test frameworks and document generators can be considered as dev-dependencies since they are only required during development .

Eg- ESLint , Babel , webpack

@FYI,

mod-a
  dev-dependents:
    - mod-b
  dependents:
    - mod-c

mod-d
?  dev-dependents:
    - mod-e
  dependents:
    - mod-a

----

npm install mod-d

installed modules:
  - mod-d
  - mod-a
  - mod-c

----

checkout the mod-d code repository

npm install

installed modules:
  - mod-a
  - mod-c
  - mod-e

If you are publishing to npm, then it is important that you use the correct flag for the correct modules. If it is something that your npm module needs to function, then use the "--save" flag to save the module as a dependency. If it is something that your module doesn't need to function but it is needed for testing, then use the "--save-dev" flag.

# For dependent modules
?npm install dependent-module --save

?# For dev-dependent modules
np?m install development-module --save-dev

What's the difference between HEAD^ and HEAD~ in Git?

actual example of the difference between HEAD~ and HEAD^

HEAD^ VS HEAD~

The #include<iostream> exists, but I get an error: identifier "cout" is undefined. Why?

You can add this at the beginning after #include <iostream>:

using namespace std;

How to add Options Menu to Fragment in Android

Setting the options menu after creating the fragment view worked well for me.

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setHasOptionsMenu(true);        
}

How do I perform an IF...THEN in an SQL SELECT?

Use CASE. Something like this.

SELECT Salable =
        CASE Obsolete
        WHEN 'N' THEN 1
        ELSE 0
    END

Setting ANDROID_HOME enviromental variable on Mac OS X

Setup ANDROID_HOME , JAVA_HOME enviromental variable on Mac OS X

Add In .bash_profile file

export JAVA_HOME=$(/usr/libexec/java_home)

export ANDROID_HOME=/Users/$USER/Library/Android/sdk

export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

For Test

echo $ANDROID_HOME
echo $JAVA_HOME

How do I calculate someone's age based on a DateTime type birthday?

Simple Code

 var birthYear=1993;
 var age = DateTime.Now.AddYears(-birthYear).Year;

How can I make a menubar fixed on the top while scrolling

This should get you started

 <div class="menuBar">
        <img class="logo" src="logo.jpg"/>
        <div class="nav"> 
            <ul>
                <li>Menu1</li>
                <li>Menu 2</li>
                <li>Menu 3</li>
            </ul> 
        </div>
    </div>



body{
    margin-top:50px;}
.menuBar{
    width:100%;
    height:50px;
    display:block;
    position:absolute;
    top:0;
    left:0;
    }
.logo{
    float:left;
    }
.nav{
    float:right;
    margin-right:10px;}
.nav ul li{
    list-style:none;
    float:left;
    }

Setting selected values for ng-options bound select elements

Using ng-selected for selected value. I Have successfully implemented code in AngularJS v1.3.2

_x000D_
_x000D_
<select ng-model="objBillingAddress.StateId"  >_x000D_
   <option data-ng-repeat="c in States" value="{{c.StateId}}" ng-selected="objBillingAddress.BillingStateId==c.StateId">{{c.StateName}}</option>_x000D_
                                                </select>
_x000D_
_x000D_
_x000D_

UnicodeEncodeError: 'ascii' codec can't encode character at special name

Try setting the system default encoding as utf-8 at the start of the script, so that all strings are encoded using that.

Example -

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

The above should set the default encoding as utf-8 .

Checking if a variable is initialized

Since MyClass is a POD class type, those non-static data members will have indeterminate initial values when you create a non-static instance of MyClass, so no, that is not a valid way to check if they have been initialized to a specific non-zero value ... you are basically assuming they will be zero-initialized, which is not going to be the case since you have not value-initialized them in a constructor.

If you want to zero-initialize your class's non-static data members, it would be best to create an initialization list and class-constructor. For example:

class MyClass
{
    void SomeMethod();

    char mCharacter;
    double mDecimal;

    public:
        MyClass();
};

MyClass::MyClass(): mCharacter(0), mDecimal(0) {}

The initialization list in the constructor above value-initializes your data-members to zero. You can now properly assume that any non-zero value for mCharacter and mDecimal must have been specifically set by you somewhere else in your code, and contain non-zero values you can properly act on.

Equivalent of shell 'cd' command to change the working directory?

Further into direction pointed out by Brian and based on sh (1.0.8+)

from sh import cd, ls

cd('/tmp')
print ls()

Is it possible to remove the hand cursor that appears when hovering over a link? (or keep it set as the normal pointer)

That's exactly what cursor: pointer; is supposed to do.

If you want the cursor to remain normal, you should be using cursor: default

Calling a function of a module by using its name (a string)

Given a string, with a complete python path to a function, this is how I went about getting the result of said function:

import importlib
function_string = 'mypackage.mymodule.myfunc'
mod_name, func_name = function_string.rsplit('.',1)
mod = importlib.import_module(mod_name)
func = getattr(mod, func_name)
result = func()

Regular expression to allow spaces between words

Try this: (Python version)

"(A-Za-z0-9 ){2, 25}"

change the upper limit based on your data set

How to override and extend basic Django admin templates?

I agree with Chris Pratt. But I think it's better to create the symlink to original Django folder where the admin templates place in:

ln -s /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin/ templates/django_admin

and as you can see it depends on python version and the folder where the Django installed. So in future or on a production server you might need to change the path.

Custom Drawable for ProgressBar/ProgressDialog

Try setting:

android:indeterminateDrawable="@drawable/progress" 

It worked for me. Here is also the code for progress.xml:

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:pivotX="50%" android:pivotY="50%" android:fromDegrees="0"
    android:toDegrees="360">

    <shape android:shape="ring" android:innerRadiusRatio="3"
        android:thicknessRatio="8" android:useLevel="false">

        <size android:width="48dip" android:height="48dip" />

        <gradient android:type="sweep" android:useLevel="false"
            android:startColor="#4c737373" android:centerColor="#4c737373"
            android:centerY="0.50" android:endColor="#ffffd300" />

    </shape>

</rotate> 

Failed to find target with hash string 'android-25'

I have got same error for Android-28. In SDK manager - SDK Platform it shows me that Android API 28 is partially installed and no further updates available. so that I updated ANDROID-SDK-BUILD-TOOLS from SDK Tools and after restarting project. It will work. This might be helpful for other who faces same issue as I faced.

Delaying function in swift

For adding argument to delay function.

First setup a dictionary then add it as the userInfo. Unwrap the info with the timer as the argument.

let arg : Int = 42
let infoDict : [String : AnyObject] = ["argumentInt", arg]

NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "functionHereWithArgument:", userInfo: infoDict, repeats: false)

Then in the called function

func functionHereWithArgument (timer : NSTimer)
{
    if let userInfo = timer.userInfo as? Dictionary<String, AnyObject>
    {
         let argumentInt : Int = (userInfo[argumentInt] as! Int)
    }
}

How do I install the babel-polyfill library?

babel-polyfill allows you to use the full set of ES6 features beyond syntax changes. This includes features such as new built-in objects like Promises and WeakMap, as well as new static methods like Array.from or Object.assign.

Without babel-polyfill, babel only allows you to use features like arrow functions, destructuring, default arguments, and other syntax-specific features introduced in ES6.

https://www.quora.com/What-does-babel-polyfill-do

https://hackernoon.com/polyfills-everything-you-ever-wanted-to-know-or-maybe-a-bit-less-7c8de164e423

modal View controllers - how to display and dismiss

I think you misunderstood some core concepts about iOS modal view controllers. When you dismiss VC1, any presented view controllers by VC1 are dismissed as well. Apple intended for modal view controllers to flow in a stacked manner - in your case VC2 is presented by VC1. You are dismissing VC1 as soon as you present VC2 from VC1 so it is a total mess. To achieve what you want, buttonPressedFromVC1 should have the mainVC present VC2 immediately after VC1 dismisses itself. And I think this can be achieved without delegates. Something along the lines:

UIViewController presentingVC = [self presentingViewController];
[self dismissViewControllerAnimated:YES completion:
 ^{
    [presentingVC presentViewController:vc2 animated:YES completion:nil];
 }];

Note that self.presentingViewController is stored in some other variable, because after vc1 dismisses itself, you shouldn't make any references to it.

IN-clause in HQL or Java Persistence Query Language

query.setParameterList("name", new String[] { "Ron", "Som", "Roxi"}); fixed my issue

How to import a bak file into SQL Server Express

To do this via TSQL (ssms query window or sqlcmd.exe) just run:

RESTORE DATABASE MyDatabase FROM DISK='c:\backups\MyDataBase1.bak'

To do it via GUI - open SSMS, right click on Databases and follow the steps below

enter image description here enter image description here

What does an exclamation mark mean in the Swift language?

An Optional variable may contain a value or may be not

case 1: var myVar:String? = "Something"

case 2: var myVar:String? = nil

now if you ask myVar!, you are telling compiler to return a value in case 1 it will return "Something"

in case 2 it will crash.

Meaning ! mark will force compiler to return a value, even if its not there. thats why the name Force Unwrapping.

Document directory path of Xcode Device Simulator

The best way to find the path is to do via code.

Using Swift, just paste the code below inside the function application in your AppDelegate.swift

let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsPath = paths.first as String
println(documentsPath)

For Obj-C code, look answer from @Ankur

How to edit incorrect commit message in Mercurial?

EDIT: As pointed out by users, don't use MQ, use commit --amend. This answer is mostly of historic interest now.

As others have mentioned the MQ extension is much more suited for this task, and you don't run the risk of destroying your work. To do this:

  1. Enable the MQ extension, by adding something like this to your hgrc:

    [extensions]
    mq =
    
  2. Update to the changeset you want to edit, typically tip:

    hg up $rev
    
  3. Import the current changeset into the queue:

    hg qimport -r .
    
  4. Refresh the patch, and edit the commit message:

    hg qrefresh -e
    
  5. Finish all applied patches (one, in this case) and store them as regular changesets:

    hg qfinish -a
    

I'm not familiar with TortoiseHg, but the commands should be similar to those above. I also believe it's worth mentioning that editing history is risky; you should only do it if you're absolutely certain that the changeset hasn't been pushed to or pulled from anywhere else.

Apply style ONLY on IE

Apart from the IE conditional comments, this is an updated list on how to target IE6 to IE10.

See specific CSS & JS hacks beyond IE.

/***** Attribute Hacks ******/

/* IE6 */
#once { _color: blue }

/* IE6, IE7 */
#doce { *color: blue; /* or #color: blue */ }

/* Everything but IE6 */
#diecisiete { color/**/: blue }

/* IE6, IE7, IE8, but also IE9 in some cases :( */
#diecinueve { color: blue\9; }

/* IE7, IE8 */
#veinte { color/*\**/: blue\9; }

/* IE6, IE7 -- acts as an !important */
#veintesiete { color: blue !ie; } /* string after ! can be anything */

/* IE8, IE9 */
#anotherone  {color: blue\0/;} /* must go at the END of all rules */

/* IE9, IE10, IE11 */
@media screen and (min-width:0\0) {
    #veintidos { color: red}
}


/***** Selector Hacks ******/

/* IE6 and below */
* html #uno  { color: red }

/* IE7 */
*:first-child+html #dos { color: red }

/* IE8 (Everything but IE 6,7) */
html>/**/body #cuatro { color: red }

/* Everything but IE6-8 */
:root *> #quince { color: red  }

/* IE7 */
*+html #dieciocho {  color: red }

/* IE 10+ */
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
   #veintiun { color: red; }
}

Check if a specific tab page is selected (active)

This can work as well.

if (tabControl.SelectedTab.Text == "tabText" )
{
    .. do stuff
}

How to kill zombie process

I tried:

ps aux | grep -w Z   # returns the zombies pid
ps o ppid {returned pid from previous command}   # returns the parent
kill -1 {the parent id from previous command}

this will work :)

Using IF ELSE statement based on Count to execute different Insert statements

Not very clear what you mean by

"I cant find any examples to help me understand how I can use this to run 2 different statements:"

. Is it using CASE like a SWITCH you are after?

select case when totalCount >= 0 and totalCount < 11 then '0-10'
            when tatalCount > 10 and totalCount < 101 then '10-100'
            else '>100' end as newColumn
from (
  SELECT [Some Column], COUNT(*) TotalCount
  FROM INCIDENTS
  WHERE [Some Column] = 'Target Data'
  GROUP BY [Some Column]
) A

How to set radio button selected value using jquery

Below script works fine in all browser:

function RadionButtonSelectedValueSet(name, SelectdValue) {
     $('input[name="' + name + '"][value="' + SelectdValue + '"]').attr('checked',true);
}

How to use BeanUtils.copyProperties?

If you want to copy from searchContent to content, then code should be as follows

BeanUtils.copyProperties(content, searchContent);

You need to reverse the parameters as above in your code.

From API,

public static void copyProperties(Object dest, Object orig)
                           throws IllegalAccessException,
                                  InvocationTargetException)

Parameters:

dest - Destination bean whose properties are modified

orig - Origin bean whose properties are retrieved

SOAP Action WSDL

When soapAction is missing in the SOAP 1.2 request (and many clients do not set it, even when it is specified in WSDL), some app servers (eg. jboss) infer the "actual" soapAction from {xsd:import namespace}+{wsdl:operation name}. So, to make the inferred "actual" soapAction match the expected soapAction, you can set the expected soapAction to {xsd:import namespace}+{wsdl:operation name} in your WS definition (@WebMethod(action=...) for Java EE)

Eg. for a typical Java EE case, this helps (not the Stewart's case, National Rail WS has 'soapAction' set):

@WebMethod(action = "http://packagename.of.your.webservice.class.com/methodName")

If you cannot change the server, you will have to force client to fill soapAction.

Where to get this Java.exe file for a SQL Developer installation

you should browse to where java installed, then go to bin directory which contains the java.exe file.

example - C:\Program Files\Java\jdk1.6.0_03\bin\java.exe

but you should run your SQL Developer as Administrator

Go Back to Previous Page

We can show a back button using html code in our pages which can take the browser window to the previous page. This page will have a button or a link and by clicking it browser will return to previous page. This can be done by using html or by using JavaScript in the client side.

Here is the code of this button

<INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);">

Using JavaScript

We can use JavaScript to create a link to take us back to previous or history page. Here is the code to move back the browser using client side JavaScript.

<a href = "javascript:history.back()">Back to previous page</a>

How to change Jquery UI Slider handle

This change only first handle in multihandle slider. In apiDoc you can see:"For example, if you specify values: [ 1, 5, 18 ] and create one custom handle, the plugin will create the other two."

What to gitignore from the .idea folder?

You can simply ignore all of them by adding .idea/* to the .gitignore file.

127 Return code from $?

127 - command not found

example: $caat The error message will

bash:

caat: command not found

now you check using echo $?

Generate random int value from 3 to 6

DECLARE @min INT = 3;
DECLARE @max INT = 6;
SELECT @min + ROUND(RAND() * (@max - @min), 0);

Step by step

DECLARE @min INT = 3;
DECLARE @max INT = 6;

DECLARE @rand DECIMAL(19,4) = RAND();
DECLARE @difference INT = @max - @min;
DECLARE @chunk INT = ROUND(@rand * @difference, 0);
DECLARE @result INT = @min + @chunk; 
SELECT @result;

Note that a user-defined function thus not allow the use of RAND(). A workaround for this (source: http://blog.sqlauthority.com/2012/11/20/sql-server-using-rand-in-user-defined-functions-udf/) is to create a view first.

CREATE VIEW [dbo].[vw_RandomSeed]
AS
SELECT        RAND() AS seed

and then create the random function

CREATE FUNCTION udf_RandomNumberBetween
(
    @min INT,
    @max INT
)
RETURNS INT
AS
BEGIN
    RETURN @min + ROUND((SELECT TOP 1 seed FROM vw_RandomSeed) * (@max - @min), 0);
END

How to link external javascript file onclick of button

It is totally possible, i did something similar based on the example of Mike Sav. That's the html page and ther shoul be an external test.js file in the same folder

example.html:

<html>
<button type="button" value="Submit" onclick="myclick()" >
Click here~!
<div id='mylink'></div>
</button>
<script type="text/javascript">
function myclick(){
    var myLink = document.getElementById('mylink');
    myLink.onclick = function(){
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = "./test.js"; 
            document.getElementsByTagName("head")[0].appendChild(script);
            return false;
    }
    document.getElementById('mylink').click();
}
</script>
</html>

test.js:

alert('hello world')

Load dimension value from res/values/dimension.xml from source code

The Resource class also has a method getDimensionPixelSize() which I think will fit your needs.

How do I delete specific characters from a particular String in Java?

Reassign the variable to a substring:

s = s.substring(0, s.length() - 1)

Also an alternative way of solving your problem: you might also want to consider using a StringTokenizer to read the file and set the delimiters to be the characters you don't want to be part of words.

How to change resolution (DPI) of an image?

DPI should not be stored in an bitmap image file, as most sources of data for bitmaps render it meaningless.

A bitmap image is stored as pixels. Pixels have no inherent size in any respect. It's only at render time - be it monitor, printer, or automated crossstitching machine - that DPI matters.

A 800x1000 pixel bitmap image, printed at 100 dpi, turns into a nice 8x10" photo. Printed at 200 dpi, the EXACT SAME bitmap image turns into a 4x5" photo.

Capture an image with a digital camera, and what does DPI mean? It's certainly not the size of the area focused onto the CCD imager - that depends on the distance, and with NASA returning images of galaxies that are 100,000 light years across, and 2 million light years apart, in the same field of view, what kind of DPI do you get from THAT information?

Don't fall victim to the idea of the DPI of a bitmap image - it's a mistake. A bitmap image has no physical dimensions (save for a few micrometers of storage space in RAM or hard drive). It's only a displayed image, or a printed image, that has a physical size in inches, or millimeters, or furlongs.

Bootstrap 3: Scroll bars

You need to use overflow option like below:

.nav{
    max-height: 300px;
    overflow-y: scroll; 
}

Change the height according to amount of items you need to show

make iframe height dynamic based on content inside- JQUERY/Javascript

I found that the accepted answer didn't suffice, since X-FRAME-OPTIONS: Allow-From isn't supported in safari or chrome. Went with a different approach instead, found in a presentation given by Ben Vinegar from Disqus. The idea is to add an event listener to the parent window, and then inside the iframe, use window.postMessage to send an event to the parent telling it to do something (resize the iframe).

So in the parent document, add an event listener:

window.addEventListener('message', function(e) {
  var $iframe = jQuery("#myIframe");
  var eventName = e.data[0];
  var data = e.data[1];
  switch(eventName) {
    case 'setHeight':
      $iframe.height(data);
      break;
  }
}, false);

And inside the iframe, write a function to post the message:

function resize() {
  var height = document.getElementsByTagName("html")[0].scrollHeight;
  window.parent.postMessage(["setHeight", height], "*"); 
}

Finally, inside the iframe, add an onLoad to the body tag to fire the resize function:

<body onLoad="resize();">

How can I make a Python script standalone executable to run without ANY dependency?

Yes, it is possible to compile Python scripts into standalone executables.

PyInstaller can be used to convert Python programs into stand-alone executables, under Windows, Linux, Mac OS X, FreeBSD, Solaris, and AIX. It is one of the recommended converters.

py2exe converts Python scripts into only executable on the Windows platform.

Cython is a static compiler for both the Python programming language and the extended Cython programming language.

Git log out user from command line

Remove your SSH keys from ~/.ssh (or where you stored them).

Remove your user settings:

git config --global --unset user.name
git config --global --unset user.email
git config --global --unset credential.helper

Or all your global settings:

git config --global --unset-all

Maybe there's something else related to the credentials store, but I always used git over SSH.

What is the purpose of the var keyword and when should I use it (or omit it)?

Always use the var keyword to declare variables. Why? Good coding practice should be enough of a reason in itself, but omitting it means it is declared in the global scope (a variable like this is called an "implied" global). Douglas Crockford recommends never using implied globals, and according to the Apple JavaScript Coding Guidelines:

Any variable created without the var keyword is created at the global scope and is not garbage collected when the function returns (because it doesn’t go out of scope), presenting the opportunity for a memory leak.

How do I apply CSS3 transition to all properties except background-position?

For anyone looks for a shorthand way, to add transition for all properties except for one specific property with delay, be aware of there're differences among even modern browsers.

A simple demo below shows the difference. Check out full code

div:hover {
  width: 500px;
  height: 500px;
  border-radius: 0;
  transition: all 2s, border-radius 2s 4s;
}

Chrome will "combine" the two animation (which is like I expect), like below:

enter image description here

While Safari "separates" it (which may not be expected):

enter image description here

A more compatible way is that you assign the specific transition for specific property, if you have a delay for one of them.

Removing padding gutter from grid columns in Bootstrap 4

Bootstrap4: Comes with .no-gutters out of the box. source: https://github.com/twbs/bootstrap/pull/21211/files

Bootstrap3:

Requires custom CSS.

Stylesheet:

.row.no-gutters {
  margin-right: 0;
  margin-left: 0;

  & > [class^="col-"],
  & > [class*=" col-"] {
    padding-right: 0;
    padding-left: 0;
  }
}

Then to use:

<div class="row no-gutters">
  <div class="col-xs-4">...</div>
  <div class="col-xs-4">...</div>
  <div class="col-xs-4">...</div>
</div>

It will:

  • Remove margin from the row
  • Remove padding from all columns directly beneath the row

Why am I getting error for apple-touch-icon-precomposed.png

I guess apple devices make those requests if the device owner adds the site to it. This is the equivalent of the favicon. To resolve, add 2 100×100 png files, save it as apple-touch-icon-precomposed.png and apple-touch-icon.png and upload it to the root directory of the server. After that, the error should be gone.

I noticed lots of requests for apple-touch-icon-precomposed.png and apple-touch-icon.png in the logs that tried to load the images from the root directory of the site. I first thought it was a misconfiguration of the mobile theme and plugin, but found out later that Apple devices make those requests if the device owner adds the site to it.

Source: Why Webmasters Should Analyze Their 404 Error Log (Mar 2012; by Martin Brinkmann)

how to install gcc on windows 7 machine?

  1. Extract the package to C:\ from here and install it

  2. Copy the path C:\MinGW\bin which contains gcc.exe.

  3. go to Control Panel->System->Advanced>Environment variables, and add or modify PATH. (just concatenate with ';')

  4. Then, open a cmd.exe command prompt (Windows + R and type cmd, if already opened, please close and open a new one, to get the path change)

  5. change the folder to your file path by cd D:\c code Path

  6. type gcc main.c -o helloworld.o. It will compile the code. for C++ use g++

7 type ./helloworld to run the program.

If zlib1.dll is missing, download from here

multiple axis in matplotlib with different scales

if you want to do very quick plots with secondary Y-Axis then there is much easier way using Pandas wrapper function and just 2 lines of code. Just plot your first column then plot the second but with parameter secondary_y=True, like this:

df.A.plot(label="Points", legend=True)
df.B.plot(secondary_y=True, label="Comments", legend=True)

This would look something like below:

enter image description here

You can do few more things as well. Take a look at Pandas plotting doc.

include external .js file in node.js app

To place an emphasis on what everyone else has been saying var foo in top level does not create a global variable. If you want a global variable then write global.foo. but we all know globals are evil.

If you are someone who uses globals like that in a node.js project I was on I would refactor them away for as there are just so few use cases for this (There are a few exceptions but this isn't one).

// Declare application
var app = require('express').createServer();

// Declare usefull stuff for DB purposes
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

require('./models/car.js').make(Schema, mongoose);

in car.js

function make(Schema, mongoose) {
    // Define Car model
    CarSchema = new Schema({
      brand        : String,
      type : String
    });
    mongoose.model('Car', CarSchema);
}

module.exports.make = make;

Convert string to variable name in python

x='buffalo'    
exec("%s = %d" % (x,2))

After that you can check it by:

print buffalo

As an output you will see: 2

Extract a substring according to a pattern

Another method to extract a substring

library(stringr)
substring <- str_extract(string, regex("(?<=:).*"))
#[1] "E001" "E002" "E003
  • (?<=:): look behind the colon (:)

Bootstrap date time picker

Well, here the positioning of the css and script links makes a to of difference. Bootstrap executes in CSS and then Scripts fashion. So if you have even one script written at incorrect place it makes a lot of difference. You can follow the below snippet and change your code accordingly.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="utf-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
    <!-- <link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.css"> -->_x000D_
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css"> _x000D_
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker-standalone.css"> _x000D_
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/js/bootstrap-datetimepicker.min.js"></script>_x000D_
    _x000D_
</head>_x000D_
<body>_x000D_
     <div class="container">_x000D_
          <div class="row">_x000D_
            <div class='col-sm-6'>_x000D_
                <div class="form-group">_x000D_
                    <div class='input-group date' id='datetimepicker1'>_x000D_
                        <input type='text' class="form-control" />_x000D_
                        <span class="input-group-addon">_x000D_
                            <span class="glyphicon glyphicon-calendar"></span>_x000D_
                        </span>_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
            <script type="text/javascript">_x000D_
                $(function () {_x000D_
                    $('#datetimepicker1').datetimepicker();_x000D_
                });_x000D_
            </script>_x000D_
          </div>_x000D_
       </div>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Why is the <center> tag deprecated in HTML?

Food for thought: what would a text-to-speech synthesizer do with <center>?

Could not resolve this reference. Could not locate the assembly

I had the same warning in VS 2017. As it turned out in my case I had added a unit test project and needed to set a dependency for the unit test on the DLL it was testing.

CSS Display an Image Resized and Cropped

Thanks sanchothefat.

I have an improvement to your answer. As crop is very tailored for every image, this definitions should be at the HTML instead of CSS.

<div style="overflow:hidden;">
   <img src="img.jpg" alt="" style="margin:-30% 0px -10% 0px;" />
</div>

Margin on child element moves parent element

The margin of the elements contained within .child are collapsing.

<html>
<style type="text/css" media="screen">
    #parent {background:#dadada;}
    #child {background:red; margin-top:17px;}
</style>
<body>
<div id="parent">

    <p>&amp;</p>

    <div id="child">
        <p>&amp;</p>    
    </div>

</div>
</body>
</html>

In this example, p is receiving a margin from the browser default styles. Browser default font-size is typically 16px. By having a margin-top of more than 16px on #child you start to notice it's position move.

Handling file renames in git

For git 1.7.x the following commands worked for me:

git mv css/iphone.css css/mobile.css
git commit -m 'Rename folder.' 

There was no need for git add, since the original file (i.e. css/mobile.css) was already in the committed files previously.

Is there a foreach loop in Go?

This may be obvious, but you can inline the array like so:

package main

import (
    "fmt"
)

func main() {
    for _, element := range [3]string{"a", "b", "c"} {
        fmt.Print(element)
    }
}

outputs:

abc

https://play.golang.org/p/gkKgF3y5nmt

What does cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);

When the normType is NORM_MINMAX, cv::normalize normalizes _src in such a way that the min value of dst is alpha and max value of dst is beta. cv::normalize does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).

CV_8UC1 says how many channels dst has.

The documentation here is pretty clear: http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize

logout and redirecting session in php

Use this instead:

<?
session_start();
session_unset();
session_destroy();

header("location:home.php");
exit();
?>

Unable to start Genymotion Virtual Device - Virtualbox Host Only Ethernet Adapter Failed to start

I recently had this problem, and setting up the virtual network configurations did not work. I found this then: https://forums.virtualbox.org/viewtopic.php?f=6&t=70199

Virtualbox seems to vhave a bug in recent releases. Reinstall it using cmd prompt, and use this as arguments for the executable : -msiparams NETWORKTYPE=NDIS5

This did the trick to me. I'm on windows 10, using the VirtualBox-5.0.10-104061-Win version.
Note that, this seems not to be a problem with genymotion only. Hope I spare you some time. I sure spent more than I thought it would take me.

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

This adds to rm8x's answer.

Download and install the NuGet command line tool.

List all of our locals:

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

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

How to check whether a string is Base64 encoded or not

This works in Python:

import base64

def IsBase64(str):
    try:
        base64.b64decode(str)
        return True
    except Exception as e:
        return False

if IsBase64("ABC"):
    print("ABC is Base64-encoded and its result after decoding is: " + str(base64.b64decode("ABC")).replace("b'", "").replace("'", ""))
else:
    print("ABC is NOT Base64-encoded.")

if IsBase64("QUJD"):
    print("QUJD is Base64-encoded and its result after decoding is: " + str(base64.b64decode("QUJD")).replace("b'", "").replace("'", ""))
else:
    print("QUJD is NOT Base64-encoded.")

Summary: IsBase64("string here") returns true if string here is Base64-encoded, and it returns false if string here was NOT Base64-encoded.

Set UITableView content inset permanently

      self.rx.viewDidAppearOnce
            .flatMapLatest { _ in RxKeyboard.instance.isHidden }
            .bind(onNext: { [unowned self] isHidden in
                guard !isHidden else { return }
                self.tableView.beginUpdates()
                self.tableView.contentInsetAdjustmentBehavior = .automatic
                self.tableView.endUpdates()
            })
            .disposed(by: self.disposeBag)

ImportError: No module named apiclient.discovery

If none of the above solutions work for you, consider if you might have installed python through Anaconda. If this is the case then installing the google API library with conda might fix it.

Run:

python --version

If you get something like

Python 3.6.4 :: Anaconda, Inc.

Then try:

conda install google-api-python-client

As bgoodr has pointed out in a comment you might need to specify the channel (think repository) to get the google API library. At the time of writing this means running the command:

conda install -c conda-forge google-api-python-client

See more at https://anaconda.org/conda-forge/google-api-python-client

Pass by pointer & Pass by reference

In fact, most compilers emit the same code for both functions calls, because references are generally implemented using pointers.

Following this logic, when an argument of (non-const) reference type is used in the function body, the generated code will just silently operate on the address of the argument and it will dereference it. In addition, when a call to such a function is encountered, the compiler will generate code that passes the address of the arguments instead of copying their value.

Basically, references and pointers are not very different from an implementation point of view, the main (and very important) difference is in the philosophy: a reference is the object itself, just with a different name.

References have a couple more advantages compared to pointers (e. g. they can't be NULL, so they are safer to use). Consequently, if you can use C++, then passing by reference is generally considered more elegant and it should be preferred. However, in C, there's no passing by reference, so if you want to write C code (or, horribile dictu, code that compiles with both a C and a C++ compiler, albeit that's not a good idea), you'll have to restrict yourself to using pointers.

ResultSet exception - before start of result set

Every answer uses .next() or uses .beforeFirst() and then .next(). But why not this:

result.first();

So You just set the pointer to the first record and go from there. It's available since java 1.2 and I just wanted to mention this for anyone whose ResultSet exists of one specific record.

How to use executeReader() method to retrieve the value of just one cell

It is not recommended to use DataReader and Command.ExecuteReader to get just one value from the database. Instead, you should use Command.ExecuteScalar as following:

String sql = "SELECT ColumnNumber FROM learer WHERE learer.id = " + index;
SqlCommand cmd = new SqlCommand(sql,conn);
learerLabel.Text = (String) cmd.ExecuteScalar();

Here is more information about Connecting to database and managing data.

How do I display todays date on SSRS report?

You can also drag and drop "Execution Time" item from Built-in Fields list.

How do I turn off the output from tar commands on Unix?

Just drop the option v.

-v is for verbose. If you don't use it then it won't display:

tar -zxf tmp.tar.gz -C ~/tmp1

How can you create multiple cursors in Visual Studio Code

Alt + Command + Shift will add a cursor to the next instance of what you've selected. E.g. a variable or function name

Passing data to a bootstrap modal

Bootstrap 4.0 gives an option to modify modal data using jquery: https://getbootstrap.com/docs/4.0/components/modal/#varying-modal-content

Here is the script tag on the docs :

$('#exampleModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget) // Button that triggered the modal
  var recipient = button.data('whatever') // Extract info from data-* attributes
  // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
  // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
  var modal = $(this)
  modal.find('.modal-title').text('New message to ' + recipient)
  modal.find('.modal-body input').val(recipient)
})

It works for the most part. Only call to modal was not working. Here is a modification on the script that works for me:

$(document).on('show.bs.modal', '#exampleModal',function(event){
... // same as in above script
})

How do I specify "close existing connections" in sql script

try this C# code to drop your database

public static void DropDatabases(string dataBase) {

        string sql =  "ALTER DATABASE "  + dataBase + "SET SINGLE_USER WITH ROLLBACK IMMEDIATE" ;

        using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["DBRestore"].ConnectionString))
        {
            connection.Open();
            using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection))
            {
                command.CommandType = CommandType.Text;
                command.CommandTimeout = 7200;
                command.ExecuteNonQuery();
            }
            sql = "DROP DATABASE " + dataBase;
            using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection))
            {
                command.CommandType = CommandType.Text;
                command.CommandTimeout = 7200;
                command.ExecuteNonQuery();
            }
        }
    }

How to get DropDownList SelectedValue in Controller in MVC

Use SelectList to bind @HtmlDropdownListFor and specify selectedValue parameter in it.

http://msdn.microsoft.com/en-us/library/dd492553(v=vs.108).aspx

Example : you can do like this for getting venderid

@Html.DropDownListFor(m => m.VendorId,Model.Vendor)


   public class MobileViewModel 
   {          
    public List<tbInsertMobile> MobileList;
    public SelectList Vendor { get; set; }
    public int VenderID{get;set;}
   }
   [HttpPost]
   public ActionResult Action(MobileViewModel model)
   {
            var Id = model.VenderID;

Quickly create a large file on a Linux system

Linux & all filesystems

xfs_mkfile 10240m 10Gigfile

Linux & and some filesystems (ext4, xfs, btrfs and ocfs2)

fallocate -l 10G 10Gigfile

OS X, Solaris, SunOS and probably other UNIXes

mkfile 10240m 10Gigfile

HP-UX

prealloc 10Gigfile 10737418240

Explanation

Try mkfile <size> myfile as an alternative of dd. With the -n option the size is noted, but disk blocks aren't allocated until data is written to them. Without the -n option, the space is zero-filled, which means writing to the disk, which means taking time.

mkfile is derived from SunOS and is not available everywhere. Most Linux systems have xfs_mkfile which works exactly the same way, and not just on XFS file systems despite the name. It's included in xfsprogs (for Debian/Ubuntu) or similar named packages.

Most Linux systems also have fallocate, which only works on certain file systems (such as btrfs, ext4, ocfs2, and xfs), but is the fastest, as it allocates all the file space (creates non-holey files) but does not initialize any of it.

Java Webservice Client (Best way)

You can find some resources related to developing web services client using Apache axis2 here.

http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html

Below posts gives good explanations about developing web services using Apache axis2.

http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/

http://wso2.org/library/136

How can I avoid ResultSet is closed exception in Java?

make sure you have closed all your statments and resultsets before running rs.next. Finaly guarantees this

public boolean flowExists( Integer idStatusPrevious, Integer idStatus, Connection connection ) {
    LogUtil.logRequestMethod();

    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        ps = connection.prepareStatement( Constants.SCRIPT_SELECT_FIND_FLOW_STATUS_BY_STATUS );
        ps.setInt( 1, idStatusPrevious );
        ps.setInt( 2, idStatus );

        rs = ps.executeQuery();

        Long count = 0L;

        if ( rs != null ) {
            while ( rs.next() ) {
                count = rs.getLong( 1 );
                break;
            }
        }

        LogUtil.logSuccessMethod();

        return count > 0L;
    } catch ( Exception e ) {
        String errorMsg = String
            .format( Constants.ERROR_FINALIZED_METHOD, ( e.getMessage() != null ? e.getMessage() : "" ) );
        LogUtil.logError( errorMsg, e );

        throw new FatalException( errorMsg );
    } finally {
        rs.close();
        ps.close();
    }

mysql error 2005 - Unknown MySQL server host 'localhost'(11001)

The case is like :

 mysql connects will localhost when network is not up.
 mysql cannot connect when network is up.

You can try the following steps to diagnose and resolve the issue (my guess is that some other service is blocking port on which mysql is hosted):

  1. Disconnect the network.
  2. Stop mysql service (if windows, try from services.msc window)
  3. Connect to network.
  4. Try to start the mysql and see if it starts correctly.
  5. Check for system logs anyways to be sure that there is no error in starting mysql service.
  6. If all goes well try connecting.
  7. If fails, try to do a telnet localhost 3306 and see what output it shows.
  8. Try changing the port on which mysql is hosted, default 3306, you can change to some other port which is ununsed.

This should ideally resolve the issue you are facing.

PHP new line break in emails

if you are outputting the code as html - change /n -->
and do echo $message;

How to get pip to work behind a proxy server

The pip's proxy parameter is, according to pip --help, in the form scheme://[user:passwd@]proxy.server:port

You should use the following:

pip install --proxy http://user:password@proxyserver:port TwitterApi

Also, the HTTP_PROXY env var should be respected.

Note that in earlier versions (couldn't track down the change in the code, sorry, but the doc was updated here), you had to leave the scheme:// part out for it to work, i.e. pip install --proxy user:password@proxyserver:port

How to hide app title in android?

You can do it programatically:

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class ActivityName extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // remove title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
    }
}

Or you can do it via your AndroidManifest.xml file:

<activity android:name=".ActivityName"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">
</activity>

Edit: I added some lines so that you can show it in fullscreen, as it seems that's what you want.

How to get text box value in JavaScript

If you are using any user control and want to get any text box values then you can use the below code:

var result = document.getElementById('LE_OtherCostsDetails_txtHomeOwnerInsurance').value;

Here, LE_OtherCostsDetails, is the name of the user control and txtHomeOwnerInsurance is the id of the text box.

Deep copy an array in Angular 2 + TypeScript

This is working for me:

this.listCopy = Object.assign([], this.list);

MetadataException: Unable to load the specified metadata resource

I also had the same problem and solution as per Rick, except that I was importing an existing .edmx to a new project, and while the base namespace didn't matter it was imported into a different subdirectory so I also had to update the connection string inside Web.Config in three places, to include the different subdirectory naming:

How to create named and latest tag in Docker?

ID=$(docker build -t creack/node .) doesn't work for me since ID will contain the output from the build.

SO I'm using this small BASH script:

#!/bin/bash

set -o pipefail

IMAGE=...your image name...
VERSION=...the version...

docker build -t ${IMAGE}:${VERSION} . | tee build.log || exit 1
ID=$(tail -1 build.log | awk '{print $3;}')
docker tag $ID ${IMAGE}:latest

docker images | grep ${IMAGE}

docker run --rm ${IMAGE}:latest /opt/java7/bin/java -version

How to improve Netbeans performance?

  • Download the latest Netbeans
  • Remove all the plugins you don't need.
  • Use the latest version of Java

Question mark and colon in JavaScript

hsb.s = max != 0 ? 255 * delta / max : 0;

? is a ternary operator. It works like an if in conjunction with the :

!= means not equals

So, the long form of this line would be

if (max != 0) { //if max is not zero
  hsb.s = 255 * delta / max;
} else {
  hsb.s = 0;
}

sklearn error ValueError: Input contains NaN, infinity or a value too large for dtype('float64')

Remove all infinite values:

(and replace with min or max for that column)

import numpy as np

# generate example matrix
matrix = np.random.rand(5,5)
matrix[0,:] = np.inf
matrix[2,:] = -np.inf
>>> matrix
array([[       inf,        inf,        inf,        inf,        inf],
       [0.87362809, 0.28321499, 0.7427659 , 0.37570528, 0.35783064],
       [      -inf,       -inf,       -inf,       -inf,       -inf],
       [0.72877665, 0.06580068, 0.95222639, 0.00833664, 0.68779902],
       [0.90272002, 0.37357483, 0.92952479, 0.072105  , 0.20837798]])

# find min and max values for each column, ignoring nan, -inf, and inf
mins = [np.nanmin(matrix[:, i][matrix[:, i] != -np.inf]) for i in range(matrix.shape[1])]
maxs = [np.nanmax(matrix[:, i][matrix[:, i] != np.inf]) for i in range(matrix.shape[1])]

# go through matrix one column at a time and replace  + and -infinity 
# with the max or min for that column
for i in range(matrix.shape[1]):
    matrix[:, i][matrix[:, i] == -np.inf] = mins[i]
    matrix[:, i][matrix[:, i] == np.inf] = maxs[i]

>>> matrix
array([[0.90272002, 0.37357483, 0.95222639, 0.37570528, 0.68779902],
       [0.87362809, 0.28321499, 0.7427659 , 0.37570528, 0.35783064],
       [0.72877665, 0.06580068, 0.7427659 , 0.00833664, 0.20837798],
       [0.72877665, 0.06580068, 0.95222639, 0.00833664, 0.68779902],
       [0.90272002, 0.37357483, 0.92952479, 0.072105  , 0.20837798]])

How to convert Integer to int?

Since you say you're using Java 5, you can use setInt with an Integer due to autounboxing: pstmt.setInt(1, tempID) should work just fine. In earlier versions of Java, you would have had to call .intValue() yourself.

The opposite works as well... assigning an int to an Integer will automatically cause the int to be autoboxed using Integer.valueOf(int).

How can I get current date in Android?

This method can use for to get current date from the system.

public static String getCurrentDateAndTime(){
    Date c = Calendar.getInstance().getTime();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
    String formattedDate = simpleDateFormat.format(c);
    return formattedDate;
}

How do you detect/avoid Memory leaks in your (Unmanaged) code?

I would recommend using Memory Validator from software verify. This tool proved itself to be of invaluable help to help me track down memory leaks and to improve the memory management of the applications i am working on.

A very complete and fast tool.