Programs & Examples On #Scroll

Scrolling refers to the continuous sliding of content across a display screen.

How to scroll to top of a div using jQuery?

I don't know why but you have to add a setTimeout with at least for me 200ms:

setTimeout( function() {$("#DIV_ID").scrollTop(0)}, 200 );

Tested with Firefox / Chrome / Edge.

How to display scroll bar onto a html table

If you get to the point where all the mentioned solutions don't work (as it got for me), do this:

  • Create two tables. One for the header and another for the body
  • Give the two tables different parent containers/divs
  • Style the second table's div to allow vertical scroll of its contents.

Like this, in your HTML

<div class="table-header-class">
    <table>
       <thead>
          <tr>
            <th>Ava</th>
            <th>Alexis</th>
            <th>Mcclure</th>
          </tr>
       </thead>
    </table>
</div>
<div class="table-content-class">
   <table>
       <tbody>
          <tr>
            <td>I am the boss</td>
            <td>No, da-da is not the boss!</td>
            <td>Alexis, I am the boss, right?</td>
          </tr>
       </tbody>
    </table>
</div>

Then style the second table's parent to allow vertical scroll, in your CSS

    .table-content-class {
        overflow-y: scroll;    // use auto; or scroll; to allow vertical scrolling; 
        overflow-x: hidden;    // disable horizontal scroll 
    }

how can I enable scrollbars on the WPF Datagrid?

If any of the parent containers RowDefinition Height set to "Auto" also stoppers for scrollbars

Alternatively you may set Height "*"

Which happened in my case.

Making a UITableView scroll when text field is selected

I think I've come up with the solution to match the behaviour of Apple's apps.

First, in your viewWillAppear: subscribe to the keyboard notifications, so you know when the keyboard will show and hide, and the system will tell you the size of the keyboard, but dont' forget to unregister in your viewWillDisappear:.

[[NSNotificationCenter defaultCenter]
    addObserver:self
       selector:@selector(keyboardWillShow:)
           name:UIKeyboardWillShowNotification
         object:nil];
[[NSNotificationCenter defaultCenter]
    addObserver:self
       selector:@selector(keyboardWillHide:)
           name:UIKeyboardWillHideNotification
         object:nil];

Implement the methods similar to the below so that you adjust the size of your tableView to match the visible area once the keyboard shows. Here I'm tracking the state of the keyboard separately so I can choose when to set the tableView back to full height myself, since you get these notifications on every field change. Don't forget to implement keyboardWillHide: and choose somewhere appropriate to fix your tableView size.

-(void) keyboardWillShow:(NSNotification *)note
{
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue: &keyboardBounds];
    keyboardHeight = keyboardBounds.size.height;
    if (keyboardIsShowing == NO)
    {
        keyboardIsShowing = YES;
        CGRect frame = self.view.frame;
        frame.size.height -= keyboardHeight;

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationDuration:0.3f];
        self.view.frame = frame;
        [UIView commitAnimations];
    }
}

Now here's the scrolling bit, we work out a few sizes first, then we see where we are in the visible area, and set the rect we want to scroll to to be either the half view above or below the middle of the text field based on where it is in the view. In this case, we have an array of UITextFields and an enum that keeps track of them, so multiplying the rowHeight by the row number gives us the actual offset of the frame within this outer view.

- (void) textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame = textField.frame;
    CGFloat rowHeight = self.tableView.rowHeight;
    if (textField == textFields[CELL_FIELD_ONE])
    {
        frame.origin.y += rowHeight * CELL_FIELD_ONE;
    }
    else if (textField == textFields[CELL_FIELD_TWO])
    {
        frame.origin.y += rowHeight * CELL_FIELD_TWO;
    }
    else if (textField == textFields[CELL_FIELD_THREE])
    {
        frame.origin.y += rowHeight * CELL_FIELD_THREE;
    }
    else if (textField == textFields[CELL_FIELD_FOUR])
    {
        frame.origin.y += rowHeight * CELL_FIELD_FOUR;
    }
    CGFloat viewHeight = self.tableView.frame.size.height;
    CGFloat halfHeight = viewHeight / 2;
    CGFloat midpoint = frame.origin.y + (textField.frame.size.height / 2);
    if (midpoint < halfHeight)
    {
        frame.origin.y = 0;
        frame.size.height = midpoint;
    }
    else
    {
        frame.origin.y = midpoint;
        frame.size.height = midpoint;
    }
    [self.tableView scrollRectToVisible:frame animated:YES];
}

This seems to work quite nicely.

Body set to overflow-y:hidden but page is still scrollable in Chrome

Another solution I found to work is to set a mousewheel handler on the inside container and make sure it doesn't propagate by setting its last parameter to false and stopping the event bubble.

document.getElementById('content').addEventListener('mousewheel',function(evt){evt.cancelBubble=true;   if (evt.stopPropagation) evt.stopPropagation},false);

Scroll works fine in the inner container, but the event doesn't propagate to the body and so it does not scroll. This is in addition to setting the body properties overflow:hidden and height:100%.

How to disable RecyclerView scrolling?

At activity's onCreate method, you can simply do:

recyclerView.stopScroll()

and it stops scrolling.

How do I get the scroll position of a document?

If you are using Jquery 1.6 or above, use prop to access the value.

$(document).prop('scrollHeight')

Previous versions used to get the value from attr but not post 1.6.

javascript: detect scroll end

This worked for me:

$(window).scroll(function() {
  buffer = 40 // # of pixels from bottom of scroll to fire your function. Can be 0
  if ($(".myDiv").prop('scrollHeight') - $(".myDiv").scrollTop() <= $(".myDiv").height() + buffer )   {
    doThing();
  }
});

Must use jQuery 1.6 or higher

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

The code below works for me (thanks to Christopher Zimmermann for his blog post http://dev.magnolia-cms.com/blog/2012/05/strategies-for-the-iframe-on-the-ipad-problem/). The problems are:

  1. There are no scroll bars to let the user know that they can scroll
  2. Users have to use two-finger scrolling
  3. The PDF files are not centered (still working on it)

    <!DOCTYPE HTML>
    <html>
    <head>
      <title>Testing iFrames on iPad</title>
      <style>
      div {
        border: solid 1px green;
        height:100px;
      }
    
    .scroller{
        border:solid 1px #66AA66;
        height: 400px;
        width: 400px;
        overflow: auto;
        text-align:center;
    
    }
    </style>
    

    <table>
      <tr>
        <td><div class="scroller">
        <iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
    </div>
        </td>
        <td><div class="scroller">
        <iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
    </div>
        </td>
      </tr>
      <tr>
      <td><div class="scroller">
        <iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
    </div>
        </td>
        <td><div class="scroller">
        <iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
    </div>
        </td>
      </tr>
    </table>
    <div> Here are some additional contents.</div>
    

How to detect scroll direction

This one deserves an update - nowadays we have the wheel event :

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
$(window).on('wheel', function(e) {_x000D_
_x000D_
 var delta = e.originalEvent.deltaY;_x000D_
_x000D_
 if (delta > 0) $('body').text('down');_x000D_
 else $('body').text('up');_x000D_
_x000D_
 return false; // this line is only added so the whole page won't scroll in the demo_x000D_
});_x000D_
});
_x000D_
body {_x000D_
  font-size: 22px;_x000D_
  text-align: center;_x000D_
  color: white;_x000D_
  background: grey;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Support has been pretty good on modern browsers for quite a while already :

  • Chrome 31+
  • Firefox 17+
  • IE9+
  • Opera 18+
  • Safari 7+

https://developer.mozilla.org/en-US/docs/Web/Events/wheel

If deeper browser support is required, probably best to use mousewheel.js instead of messing about :

https://plugins.jquery.com/mousewheel/

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
$(window).mousewheel(function(turn, delta) {_x000D_
_x000D_
 if (delta > 0) $('body').text('up');_x000D_
 else $('body').text('down');_x000D_
_x000D_
 return false; // this line is only added so the whole page won't scroll in the demo_x000D_
});_x000D_
});
_x000D_
body {_x000D_
  font-size: 22px;_x000D_
  text-align: center;_x000D_
  color: white;_x000D_
  background: grey;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js"></script>
_x000D_
_x000D_
_x000D_

How do I scroll a row of a table into view (element.scrollintoView) using jQuery?

This runnable example shows how to use scrollIntoView() which is supported in all modern browsers: https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView#Browser_Compatibility

The example below uses jQuery to select the element with #yourid.

_x000D_
_x000D_
$( "#yourid" )[0].scrollIntoView();
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<p>..</p>_x000D_
<p>..</p>_x000D_
<p>..</p>_x000D_
<p>..</p>_x000D_
<p>..</p>_x000D_
<p>..</p>_x000D_
<p>..</p>_x000D_
<p>..</p>_x000D_
<p>..</p>_x000D_
<p>..</p>_x000D_
<p>..</p>_x000D_
<p>..</p>_x000D_
<p>..</p>_x000D_
<p>..</p>_x000D_
<p>..</p>_x000D_
<p>..</p>_x000D_
<p>..</p>_x000D_
<p id="yourid">Hello world.</p>_x000D_
<p>..</p>_x000D_
<p>..</p>_x000D_
<p>..</p>_x000D_
<p>..</p>
_x000D_
_x000D_
_x000D_

How do you make a div follow as you scroll?

A better JQuery answer would be:

$('#ParentContainer').scroll(function() { 
    $('#FixedDiv').animate({top:$(this).scrollTop()});
});

You can also add a number after scrollTop i.e .scrollTop() + 5 to give it buff.

A good suggestion would also to limit the duration to 100 and go from default swing to linear easing.

$('#ParentContainer').scroll(function() { 
    $('#FixedDiv').animate({top:$(this).scrollTop()},100,"linear");
})

Scroll / Jump to id without jQuery

if you want smooth scrolling add behavior configuration.

document.getElementById('id').scrollIntoView({
  behavior: 'smooth'
});

jQuery animate scroll

var page_url = windws.location.href;
var page_id = page_url.substring(page_url.lastIndexOf("#") + 1);
if (page_id == "") {
    $("html, body").animate({
        scrollTop: $("#scroll-" + page_id).offset().top
    }, 2000)
} else if (page_id == "") {
    $("html, body").animate({
        scrollTop: $("#scroll-" + page_id).offset().top
    }, 2000)
}

});

Programmatically scroll a UIScrollView

scrollView.setContentOffset(CGPoint(x: y, y: x), animated: true)

Add vertical scroll bar to panel

Below is the code that implements custom vertical scrollbar. The important detail here is to know when scrollbar is needed by calculating how much space is consumed by the controls that you add to the panel.

panelUserInput.SuspendLayout();
panelUserInput.Controls.Clear();
panelUserInput.AutoScroll = false;
panelUserInput.VerticalScroll.Visible = false;

// here you'd be adding controls

int x = 20, y = 20, height = 0;
for (int inx = 0; inx < numControls; inx++ )
{
    // this example uses textbox control
    TextBox txt = new TextBox();
    txt.Location = new System.Drawing.Point(x, y);
    // add whatever details you need for this control
    // before adding it to the panel
    panelUserInput.Controls.Add(txt);
    height = y + txt.Height;
    y += 25;
}
if (height > panelUserInput.Height)
{
    VScrollBar bar = new VScrollBar();
    bar.Dock = DockStyle.Right;
    bar.Scroll += (sender, e) => { panelUserInput.VerticalScroll.Value =  bar.Value; };
    bar.Top = 0;
    bar.Left = panelUserInput.Width - bar.Width;
    bar.Height = panelUserInput.Height;
    bar.Visible = true;
    panelUserInput.Controls.Add(bar);
}
panelUserInput.ResumeLayout();

// then update the form
this.PerformLayout();

Maintain/Save/Restore scroll position when returning to a ListView

For an activity derived from ListActivity that implements LoaderManager.LoaderCallbacks using a SimpleCursorAdapter it did not work to restore the position in onReset(), because the activity was almost always restarted and the adapter was reloaded when the details view was closed. The trick was to restore the position in onLoadFinished():

in onListItemClick():

// save the selected item position when an item was clicked
// to open the details
index = getListView().getFirstVisiblePosition();
View v = getListView().getChildAt(0);
top = (v == null) ? 0 : (v.getTop() - getListView().getPaddingTop());

in onLoadFinished():

// restore the selected item which was saved on item click
// when details are closed and list is shown again
getListView().setSelectionFromTop(index, top);

in onBackPressed():

// Show the top item at next start of the app
index = 0;
top = 0;

Scrolling an iframe with JavaScript?

Use the scrollTop property of the frame's content to set the content's vertical scroll-offset to a specific number of pixels (like 100):

<iframe src="foo.html" onload="this.contentWindow.document.documentElement.scrollTop=100"></iframe>

Changing route doesn't scroll to top in the new page

Try this http://ionicframework.com/docs/api/service/$ionicScrollDelegate/

It does scroll to the top of the list scrollTop()

How to detect scroll position of page using jQuery

$(window).scroll( function() { 
 var scrolled_val = $(document).scrollTop().valueOf();
 alert(scrolled_val+ ' = scroll value');
});

This is another way of getting the value of scroll.

jQuery scroll to element

Updated answer as of 2019:

$('body').animate({
    scrollTop: $('#subject').offset().top - $('body').offset().top + $('body').scrollTop()
}, 'fast');

Keep overflow div scrolled to bottom unless user scrolls up

In 2020, you can use css snap, but before Chrome 81 the layout change will not trigger re-snap, a pure css chat ui works on Chrome 81, also you can check Can I use CSS snap.

This demo will snap the last element if visible, scroll to bottom to see the effect.

_x000D_
_x000D_
.container {
  overflow-y: scroll;
  overscroll-behavior-y: contain;
  scroll-snap-type: y proximity;
}

.container > div > div:last-child {
  scroll-snap-align: end;
}

.container > div > div {
  background: lightgray;
  height: 3rem;
  font-size: 1.5rem;
}
.container > div > div:nth-child(2n) {
  background: gray;
}
_x000D_
<div class="container" style="height:6rem">
<div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
</div>
_x000D_
_x000D_
_x000D_

enter image description here

EDIT

use scroll-snap-type: y proximity;, scroll up easier.

How to disable scrolling in UITableView table when the content fits on the screen

So there's are multiple answers and requires a all content at once place so I'm adding this answer:

If you're using AutoLayout, by setting this only should work for you:

  • In code:

tableView.alwaysBounceVertical = false

  • or In Interface Builder:

Just find this option and untick "Bounce Vertically" option.

Here's the reference:

enter image description here

If you're not using AutoLayout:

 override func viewDidLayoutSubviews() {
    // Enable scrolling based on content height
    tableView.isScrollEnabled = tableView.contentSize.height > tableView.frame.size.height
 }

Check if a user has scrolled to the bottom

This is my two cents:

$('#container_element').scroll( function(){
        console.log($(this).scrollTop()+' + '+ $(this).height()+' = '+ ($(this).scrollTop() + $(this).height())   +' _ '+ $(this)[0].scrollHeight  );
        if($(this).scrollTop() + $(this).height() == $(this)[0].scrollHeight){
            console.log('bottom found');
        }
    });

Header div stays at top, vertical scrolling div below with scrollbar only attached to that div

Here is a demo. Use position:fixed; top:0; left:0; so the header always stay on top.

?#header {
    background:red;
    height:50px;
    width:100%;
    position:fixed;
    top:0;
    left:0;    
}.scroller {
    height:300px; 
    overflow:scroll;    
}

How to scroll to an element inside a div?

Code should be:

var divElem = document.getElementById('scrolling_div');
var chElem = document.getElementById('element_within_div');
var topPos = divElem.offsetTop;
divElem.scrollTop = topPos - chElem.offsetTop;

You want to scroll the difference between child top position and div's top position.

Get access to child elements using:

var divElem = document.getElementById('scrolling_div'); 
var numChildren = divElem.childNodes.length;

and so on....

Page scroll up or down in Selenium WebDriver (Selenium 2) using java

Thanks for Ripon Al Wasim's answer. I did some improvement. because of network problems, I retry three times until break loop.

driver.get(url)
# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
try_times = 0
while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollBy(0,2000)")

    # Wait to load page
    time.sleep(scroll_delay)
    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")

    if last_height == new_height:
        try_times += 1

    if try_times > 3:
        try_times = 0
        break
    last_height = new_height

How to disable scrolling temporarily?

Another solution:

body {
    overflow-y: scroll;
    width: 100%;
    margin: 0 auto;
}

This way you always have a vertical scrollbar, but as most of my content is longer than the viewport, this is ok for me. Content is centered with a separate div, but without setting margin again in body my content would stay at the left.

These are the two function I use to show my popup/modal:

var popup_bodyTop = 0;
var popup_bodyLeft = 0;

function popupShow(id)
{
    $('#'+ id).effect('fade');
    $('#popup-overlay').effect('fade');

    // remember current scroll-position
    // because when setting/unsetting position: fixed to body
    // the body would scroll to 0,0
    popup_bodyLeft = $(document).scrollLeft();
    popup_bodyTop  = $(document).scrollTop();

    // invert position
    var x = - popup_bodyLeft;
    var y = - popup_bodyTop;

    $('body').css('position', 'fixed');
    $('body').css('top', y.toString() +'px');
    $('body').css('left', x.toString() +'px');
}

function popupHide(id)
{
    $('#'+ id).effect('fade');
    $('#popup-overlay').effect('fade');
    $('body').css('position', '');
    $('html, body').scrollTop(popup_bodyTop);
    $('html, body').scrollLeft(popup_bodyLeft);
}

Result: non scrollable background and no re-positioning of the content because of the left scrollbar. Tested with current FF, Chrome and IE 10.

jQuery load more data on scroll

In jQuery, check whether you have hit the bottom of page using scroll function. Once you hit that, make an ajax call (you can show a loading image here till ajax response) and get the next set of data, append it to the div. This function gets executed as you scroll down the page again.

$(window).scroll(function() {
    if($(window).scrollTop() == $(document).height() - $(window).height()) {
           // ajax call get data from server and append to the div
    }
});

How can I scroll a div to be visible in ReactJS?

Just in case someone stumbles here, I did it this way

  componentDidMount(){
    const node = this.refs.trackerRef;
    node && node.scrollIntoView({block: "end", behavior: 'smooth'})
  }
  componentDidUpdate() {
    const node = this.refs.trackerRef;
    node && node.scrollIntoView({block: "end", behavior: 'smooth'})
  }

  render() {
    return (

      <div>
        {messages.map((msg, index) => {
          return (
            <Message key={index} msgObj={msg}
              {/*<p>some test text</p>*/}
            </Message>
          )
        })}

        <div style={{height: '30px'}} id='#tracker' ref="trackerRef"></div>
      </div>
    )
  }

scrollIntoView is native DOM feature link

It will always shows tracker div

Trigger event when user scroll to specific element - with jQuery

Inview library triggered event and works well with jquery 1.8 and higher! https://github.com/protonet/jquery.inview

$('div').on('inview', function (event, visible) {
  if (visible == true) {
    // element is now visible in the viewport
  } else {
    // element has gone out of viewport
  }
});

Read this https://remysharp.com/2009/01/26/element-in-view-event-plugin

How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

Sort and Lock Table is the only solution I have seen which does work on other browsers than IE. (although this "locked column css" might do the trick as well). Required code block below.

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="robots" content="noindex, nofollow">
  <meta name="googlebot" content="noindex, nofollow">
  <script type="text/javascript" src="/js/lib/dummy.js"></script>
    <link rel="stylesheet" type="text/css" href="/css/result-light.css">
  <style type="text/css">
    /* Scrollable Content Height */
.scrollContent {
 height:100px;
 overflow-x:hidden;
 overflow-y:auto;
}
.scrollContent tr {
 height: auto;
 white-space: nowrap;
}

/* Prevent Mozilla scrollbar from hiding right-most cell content */
.scrollContent tr td:last-child {
 padding-right: 20px;
}

/* Fixed Header Height */
.fixedHeader tr {
 position: relative;
 height: auto;
}

/* Put border around entire table */
div.TableContainer {
 border: 1px solid #7DA87D;
}

/* Table Header formatting */
.headerFormat {
 background-color: white;
 color: #FFFFFF;
 margin: 3px;
 padding: 1px;
 white-space: nowrap;
 font-family: Helvetica;
 font-size: 16px;
 text-decoration: none;
 font-weight: bold;
}
.headerFormat tr td {
 border: 1px solid #000000;
 background-color: #7DA87D;
}

/* Table Body (Scrollable Content) formatting */
.bodyFormat tr td {
    color: #000000;
    margin: 3px;
    padding: 1px;
    border: 0px none;
    font-family: Helvetica;
    font-size: 12px;
}

/* Use to set different color for alternating rows */
.alternateRow {
  background-color: #E0F1E0;
}

/* Styles used for SORTING */
.point {
 cursor:pointer;
}
td.sortedColumn {
  background-color: #E0F1E0;
}

tr.alternateRow td.sortedColumn {
  background-color: #c5e5c5;
}
.total {
    background-color: #FED362;
    color: #000000;
    white-space: nowrap;
    font-size: 12px;
    text-decoration: none;
}
  </style>

  <title></title>
<script type='text/javascript'>//<![CDATA[

/* This script and many more are available free online at
The JavaScript Source :: http://www.javascriptsource.com
Created by: Stan Slaughter :: http://www.stansight.com/ */

/* ======================================================
Generic Table Sort

Basic Concept: A table can be sorted by clicking on the title of any
column in the table, toggling between ascending and descending sorts.


Assumptions:

* The first row of the table contains column titles that are "clicked"
  to sort the table

* The images 'desc.gif','asc.gif','none.gif','sorting.gif' exist

* The img tag is in each column of the the title row to represent the
  sort graphic.

* The CSS classes 'alternateRow' and 'sortedColumn' exist so we can
  have alternating colors for each row and a highlight the sorted
  column.  Something like the <style> definition below, but with the
  background colors set to whatever you want.

   <style>
   tr.alternateRow {
     background-color: #E0F1E0;
   }

   td.sortedColumn {
     background-color: #E0F1E0;
   }

   tr.alternateRow td.sortedColumn {
     background-color: #c5e5c5;
   }
   </style>

====================================================== */

function sortTable(td_element,ignoreLastLines) {

  // If the optional ignoreLastLines parameter (number of lines *not* to sort at end of table)
  // was not passed then make it 0
  ignoreLastLines = (typeof(ignoreLastLines)=='undefined') ? 0 : ignoreLastLines;

  var sortImages =['data:image/gif;base64,R0lGODlhCgAKAMQXAJOkk3mReXume3uTe3mieXGPcXOYc/Hx8Xadds/Wz9vg24ejh3GUcYOgg6a0pnGVcfP18+3w7c3TzdPY06u4q/r8+v///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABcALAAAAAAKAAoAAAUz4IVcZDleixQIQjA1pFFZx2FVRklZvOWUl8LsVgBeFLyE8TLgDZYESISwvAAA1QvjAQwBADs=','data:image/gif;base64,R0lGODlhCgAKAMQXAJOkk3mReXume3uTe3mieXGPcXOYc/Hx8Xadds/Wz9vg24ejh3GUcYOgg6a0pnGVcfP18+3w7c3TzdPY06u4q/r8+v///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABcALAAAAAAKAAoAAAUw4CVeDzOeFwCgIhFBBDtY1sAmtIIWFV0VJweNRhkZeoeDpWIQNSYBgSAgWYgQLGwIADs=','data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7','http://web.archive.org/web/20150906203819im_/http://www.javascriptsource.com/miscellaneous/sorting.gif'];

  // Get the image used in the first row of the current column
  var sortColImage = td_element.getElementsByTagName('img')[0];

  // If current image is 'asc.gif' or 'none.gif' (elements 1 and 2 of sortImages array) then this will
  // be a descending sort else it will be ascending - get new sort image icon and set sort order flag
  var sortAscending = false;
  var newSortColImage = "";
  if (sortColImage.getAttribute('src').indexOf(sortImages[1])>-1 ||
    sortColImage.getAttribute('src').indexOf(sortImages[2])>-1) {
    newSortColImage = sortImages[0];
    sortAscending = false;
  } else {
    newSortColImage = sortImages[1];
    sortAscending = true;
  }

  // Assign "SORTING" image icon (element 3 of sortImages array)) to current column title
  // (will replace with newSortColImage when sort completes)
  sortColImage.setAttribute('src',sortImages[3]);

  // Find which column was clicked by getting it's column position
  var indexCol = td_element.cellIndex;

  // Get the table element from the td element that was passed as a parameter to this function
  var table_element = td_element.parentNode;
  while (table_element.nodeName != "TABLE") {
    table_element = table_element.parentNode;
  }

  // Get all "tr" elements from the table and assign then to the Array "tr_elements"
  var tr_elements = table_element.getElementsByTagName('tr');

  // Get all the images used in the first row then set them to 'none.gif'
  // (element 2 or sortImages array) except for the current column (all ready been changed)
  var allImg = tr_elements[0].getElementsByTagName('img');
    for(var i=0;i<allImg.length;i++){
    if(allImg[i]!=sortColImage){allImg[i].setAttribute('src',sortImages[2])}
  }

  // Some explantion of the basic concept of the following code before we
  // actually start.  Essentially we are going to copy the current columns information
  // into an array to be sorted. We'll sort the column array then go back and use the information
  // we saved about the original row positions to re-order the entire table.
  // We are never really sorting more than a columns worth of data, which should keep the sorting fast.

  // Create a new array for holding row information
  var clonedRows = new Array()

  // Create a new array to store just the selected column values, not the whole row
  var originalCol = new Array();

  // Now loop through all the data row elements
  // NOTE: Starting at row 1 because row 0 contains the column titles
  for (var i=1; i<tr_elements.length - ignoreLastLines; i++) {

   // "Clone" the tr element i.e. save a copy all of its attributes and values
   clonedRows[i]=tr_elements[i].cloneNode(true);

   // Text value of the selected column on this row
   var valueCol = getTextValue(tr_elements[i].cells[indexCol]);

   // Format text value for sorting depending on its type, ie Date, Currency, number, etc..
   valueCol = FormatForType(valueCol);

   // Assign the column value AND the row number it was originally on in the table
   originalCol[i]=[valueCol,tr_elements[i].rowIndex];
  }

  // Get rid of element "0" from this array.  A value was never assigned to it because the first row
  // in the table just contained the column titles, which we did not bother to assign.
  originalCol.shift();

  // Sort the column array returning the value of a sort into a new array
  sortCol = originalCol.sort(sortCompare);

  // If it was supposed to be an Ascending sort then reverse the order
  if (sortAscending) { sortCol.reverse(); }

  // Now take the values from the sorted column array and use that information to re-arrange
  // the order of the tr_elements in the table
  for (var i=1; i < tr_elements.length - ignoreLastLines; i++) {

    var old_row = sortCol[i-1][1];
    var new_row = i;
    tr_elements[i].parentNode.replaceChild(clonedRows[old_row],tr_elements[new_row]);
  }

   // Format the table, making the rows alternating colors and highlight the sorted column
   makePretty(table_element,indexCol,ignoreLastLines);

  // Assign correct sort image icon to current column title
  sortColImage.setAttribute('src',newSortColImage);
}

// Function used by the sort routine to compare the current value in the array with the next one
function sortCompare (currValue, nextValue) {
 // Since the elements of this array are actually arrays themselves, just sort
 // on the first element which contiains the value, not the second which contains
 // the original row position
  if ( currValue[0] == nextValue[0] ) return 0;
  if ( currValue[0] < nextValue[0] ) return -1;
  if ( currValue[0] > nextValue[0] ) return 1;
}

//-----------------------------------------------------------------------------
// Functions to get and compare values during a sort.
//-----------------------------------------------------------------------------

// This code is necessary for browsers that don't reflect the DOM constants
// (like IE).
if (document.ELEMENT_NODE == null) {
   document.ELEMENT_NODE = 1;
   document.TEXT_NODE = 3;
}

function getTextValue(el) {
  var i;
  var s;
  // Find and concatenate the values of all text nodes contained within the
  // element.
  s = "";
  for (i = 0; i < el.childNodes.length; i++)
    if (el.childNodes[i].nodeType == document.TEXT_NODE)
      s += el.childNodes[i].nodeValue;
    else if (el.childNodes[i].nodeType == document.ELEMENT_NODE &&
             el.childNodes[i].tagName == "BR")
      s += " ";
    else
      // Use recursion to get text within sub-elements.
      s += getTextValue(el.childNodes[i]);

  return normalizeString(s);
}

// Regular expressions for normalizing white space.
var whtSpEnds = new RegExp("^\\s*|\\s*$", "g");
var whtSpMult = new RegExp("\\s\\s+", "g");

function normalizeString(s) {
  s = s.replace(whtSpMult, " ");  // Collapse any multiple whites space.
  s = s.replace(whtSpEnds, "");   // Remove leading or trailing white space.
  return s;
}

// Function used to modify values to make then sortable depending on the type of information
function FormatForType(itm) {
  var sortValue = itm.toLowerCase();

  // If the item matches a date pattern (MM/DD/YYYY or MM/DD/YY or M/DD/YYYY)
  if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/) ||
      itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/) ||
      itm.match(/^\d[\/-]\d\d[\/-]\d\d\d\d$/) ) {

    // Convert date to YYYYMMDD format for sort comparison purposes
    // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
    var yr = -1;

    if (itm.length == 10) {
      sortValue = itm.substr(6,4)+itm.substr(0,2)+itm.substr(3,2);
     } else if (itm.length == 9) {
      sortValue = itm.substr(5,4)+"0" + itm.substr(0,1)+itm.substr(2,2);
    } else {
      yr = itm.substr(6,2);
      if (parseInt(yr) < 50) {
        yr = '20'+yr;
      } else {
        yr = '19'+yr;
      }
        sortValue = yr+itm.substr(3,2)+itm.substr(0,2);
    }

  }



  // If the item matches a Percent patten (contains a percent sign)
  if (itm.match(/%/)) {
   // Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.
   sortValue = itm.replace(/[^0-9.-]/g,'');
   sortValue = parseFloat(sortValue);
  }

  // If item starts with a "(" and ends with a ")" then remove them and put a negative sign in front
  if (itm.substr(0,1) == "(" & itm.substr(itm.length - 1,1) == ")") {
   itm = "-" + itm.substr(1,itm.length - 2);
  }

// If the item matches a currency pattern (starts with a dollar or negative dollar sign)
  if (itm.match(/^[£$]|(^-)/)) {
   // Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.
   sortValue = itm.replace(/[^0-9.-]/g,'');
   if (isNaN(sortValue)) {
     sortValue = 0;
   } else {
     sortValue = parseFloat(sortValue);
   }
}

  // If the item matches a numeric pattern
  if (itm.match(/(\d*,\d*$)|(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/)) {
   // Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.
   sortValue = itm.replace(/[^0-9.-]/g,'');
 //  sortValue = sortValue.replace(/,/g,'');
   if (isNaN(sortValue)) {
     sortValue = 0;
   } else {
     sortValue = parseFloat(sortValue);
   }
  }

  return sortValue;
}

//-----------------------------------------------------------------------------
// Functions to update the table appearance after a sort.
//-----------------------------------------------------------------------------

// Style class names.
var rowClsNm = "alternateRow";
var colClsNm = "sortedColumn";

// Regular expressions for setting class names.
var rowTest = new RegExp(rowClsNm, "gi");
var colTest = new RegExp(colClsNm, "gi");

function makePretty(tblEl, col, ignoreLastLines) {

  var i, j;
  var rowEl, cellEl;

  // Set style classes on each row to alternate their appearance.
  for (i = 1; i < tblEl.rows.length - ignoreLastLines; i++) {
   rowEl = tblEl.rows[i];
   rowEl.className = rowEl.className.replace(rowTest, "");
    if (i % 2 != 0)
      rowEl.className += " " + rowClsNm;
    rowEl.className = normalizeString(rowEl.className);
    // Set style classes on each column (other than the name column) to
    // highlight the one that was sorted.
    for (j = 0; j < tblEl.rows[i].cells.length; j++) {
      cellEl = rowEl.cells[j];
      cellEl.className = cellEl.className.replace(colTest, "");
      if (j == col)
        cellEl.className += " " + colClsNm;
      cellEl.className = normalizeString(cellEl.className);
    }
  }


}

// END Generic Table sort.

// =================================================

// Function to scroll to top before sorting to fix an IE bug
// Which repositions the header off the top of the screen
// if you try to sort while scrolled to bottom.
function GoTop() {
 document.getElementById('TableContainer').scrollTop = 0;
}

//]]> 
</script>
</head>
<body>
  <table cellpadding="0" cellspacing="0" border="0">
<tr><td>
<div id="TableContainer" class="TableContainer" style="height:230px;">
<table class="scrollTable">
 <thead class="fixedHeader headerFormat">
  <tr>
   <td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort"><b>NAME</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
   <td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Amt</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
   <td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Lvl</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
   <td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Rank</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
   <td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Position</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
   <td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Date</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
  </tr>
 </thead>
 <tbody class="scrollContent bodyFormat" style="height:200px;">
   <tr class="alternateRow">
    <td>Maha</td>
    <td align="right">$19,923.19</td>
    <td align="right">100</td>
    <td align="right">100</td>
    <td>Owner</td>
    <td align="right">01/02/2001</td>
   </tr>
   <tr>
    <td>Thrawl</td>
    <td align="right">$9,550</td>
    <td align="right">159</td>
    <td align="right">100%</td>
    <td>Co-Owner</td>
    <td align="right">11/07/2003</td>
   </tr>
   <tr class="alternateRow">
    <td>Marhanen</td>
    <td align="right">$223.04</td>
    <td align="right">83</td>
    <td align="right">99%</td>
    <td>Banker</td>
    <td align="right">06/27/2006</td>
   </tr>
   <tr>
    <td>Peter</td>
    <td align="right">$121</td>
    <td align="right">567</td>
    <td align="right">23423%</td>
    <td>FishHead</td>
    <td align="right">06/06/2006</td>
   </tr>
   <tr class="alternateRow">
    <td>Jones</td>
    <td align="right">$15</td>
    <td align="right">11</td>
    <td align="right">15%</td>
    <td>Bubba</td>
    <td align="right">10/27/2005</td>
   </tr>
   <tr>
    <td>Supa-De-Dupa</td>
    <td align="right">$145</td>
    <td align="right">91</td>
    <td align="right">32%</td>
    <td>momma</td>
    <td align="right">12/15/1996</td>
   </tr>
   <tr class="alternateRow">
    <td>ClickClock</td>
    <td align="right">$1,213</td>
    <td align="right">23</td>
    <td align="right">1%</td>
    <td>Dada</td>
    <td align="right">1/30/1998</td>
   </tr>
   <tr>
    <td>Mrs. Robinson</td>
    <td align="right">$99</td>
    <td align="right">99</td>
    <td align="right">99%</td>
    <td>Wife</td>
    <td align="right">07/04/1963</td>
   </tr>
   <tr class="alternateRow">
    <td>Maha</td>
    <td align="right">$19,923.19</td>
    <td align="right">100</td>
    <td align="right">100%</td>
    <td>Owner</td>
    <td align="right">01/02/2001</td>
   </tr>
   <tr>
    <td>Thrawl</td>
    <td align="right">$9,550</td>
    <td align="right">159</td>
    <td align="right">100%</td>
    <td>Co-Owner</td>
    <td align="right">11/07/2003</td>
   </tr>
   <tr class="alternateRow">
    <td>Marhanen</td>
    <td align="right">$223.04</td>
    <td align="right">83</td>
    <td align="right">59%</td>
    <td>Banker</td>
    <td align="right">06/27/2006</td>
   </tr>
   <tr>
    <td>Peter</td>
    <td align="right">$121</td>
    <td align="right">567</td>
    <td align="right">534.23%</td>
    <td>FishHead</td>
    <td align="right">06/06/2006</td>
   </tr>
   <tr class="alternateRow">
    <td>Jones</td>
    <td align="right">$15</td>
    <td align="right">11</td>
    <td align="right">15%</td>
    <td>Bubba</td>
    <td align="right">10/27/2005</td>
   </tr>
   <tr>
    <td>Supa-De-Dupa</td>
    <td align="right">$145</td>
    <td align="right">91</td>
    <td align="right">42%</td>
    <td>momma</td>
    <td align="right">12/15/1996</td>
   </tr>
   <tr class="alternateRow">
    <td>ClickClock</td>
    <td align="right">$1,213</td>
    <td align="right">23</td>
    <td align="right">2%</td>
    <td>Dada</td>
    <td align="right">1/30/1998</td>
   </tr>
   <tr>
    <td>Mrs. Robinson</td>
    <td align="right">$99</td>
    <td align="right">99</td>
    <td align="right">(-10.42%)</td>
    <td>Wife</td>
    <td align="right">07/04/1963</td>
   </tr>
   <tr class="alternateRow">
    <td>Maha</td>
    <td align="right">-$19,923.19</td>
    <td align="right">100</td>
    <td align="right">(-10.01%)</td>
    <td>Owner</td>
    <td align="right">01/02/2001</td>
   </tr>
   <tr>
    <td>Thrawl</td>
    <td align="right">$9,550</td>
    <td align="right">159</td>
    <td align="right">-10.20%</td>
    <td>Co-Owner</td>
    <td align="right">11/07/2003</td>
   </tr>
   <tr class="total">
    <td><strong>TOTAL</strong>:</td>
    <td align="right"><strong>999999</strong></td>
    <td align="right"><strong>9999999</strong></td>
    <td align="right"><strong>99</strong></td>
    <td > </td>
    <td align="right"> </td>
   </tr>
 </tbody>
</table>
</div>
</td></tr>
</table>
</body>
</html>

Can I change the scroll speed using css or jQuery?

The scroll speed CAN be changed, adjusted, reversed, all of the above - via javascript (or a js library such as jQuery).

WHY would you want to do this? Parallax is just one of the reasons. I have no idea why anyone would argue against doing so -- the same negative arguments can be made against hiding DIVs, sliding elements up/down, etc. Websites are always a combination of technical functionality and UX design -- a good designer can use almost any technical capability to improve UX. That is what makes him/her good.

Toni Almeida of Portugal created a brilliant demo, reproduced below:

jsFiddle Demo

HTML:

<div id="myDiv">
    Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. <span class="boldit">Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. </span>
</div>

javascript/jQuery:

  function wheel(event) {
      var delta = 0;
      if (event.wheelDelta) {(delta = event.wheelDelta / 120);}
      else if (event.detail) {(delta = -event.detail / 3);}

      handle(delta);
      if (event.preventDefault) {(event.preventDefault());}
      event.returnValue = false;
  }

  function handle(delta) {
      var time = 1000;
      var distance = 300;

      $('html, body').stop().animate({
          scrollTop: $(window).scrollTop() - (distance * delta)
      }, time );
  }

  if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false);}
    window.onmousewheel = document.onmousewheel = wheel;

Source:

How to change default scrollspeed,scrollamount,scrollinertia of a webpage

ListBox with ItemTemplate (and ScrollBar!)

I pasted your code into test project, added about 20 items and I get usable scroll bars, no problem, and they work as expected. When I only add a couple items (such that scrolling is unnecessary) I get no usable scrollbar. Could this be the case? that you are not adding enough items?

If you remove the ScrollViewer.VerticalScrollBarVisibility="Visible" then the scroll bars only appear when you have need of them.

How to scroll to specific item using jQuery?

Not sure why no one says the obvious, as there's a built in javascript scrollTo function:

scrollTo( $('#element').position().top );

Reference.

Make a nav bar stick

You can do it with CSS only by creating your menu twice. It's not ideal but it gives you the opportunity have a different design for the menu once it's on top and you'll have nothing else than CSS, no jquery. Here is an example with DIV (you can of course change it to NAV if you prefer):

<div id="hiddenmenu">
 THIS IS MY HIDDEN MENU
</div>
<div id="header">
 Here is my header with a lot of text and my main menu
</div>
<div id="body">
 MY BODY
</div>

And then have the following CSS:

#hiddenmenu {
position: fixed;
top: 0;
z-index:1;
 }
#header {
top: 0;
position:absolute;
z-index:2;
 }
#body {
padding-top: 80px;
position:absolute;
z-index: auto;
 }

Here is a fiddle for you to see: https://jsfiddle.net/brghtk4z/1/

How do I get the height of a div's full content with jQuery?

  1. Using scrollHeight is not only buggy, but doesn't work when your container has a hardcoded height (which is probably most cases, since you wanna get contents height without doing container.height() itself)
  2. @shazboticus-s-shazbot solution is good when you can mess around with the container height temporarily / have a hard-coded height.
  3. An alternative solution would be:

_x000D_
_x000D_
$('#outer')_x000D_
    // Get children in array format, as we'll be reducing them into a single number_x000D_
    .contents().toArray()_x000D_
    // Filter out text and comment nodes, only allowing tags_x000D_
    .filter(el => el.nodeType === 1)_x000D_
    // Sum up all the children individual heights_x000D_
    .reduce((accumulator, el) => $(el).outerHeight(true) + accumulator, 0);
_x000D_
_x000D_
_x000D_

Of course, this latter alternative only works when #outer doesn't have immediate text childrens that take up space and you want to measure. Those are my 2 cents.

  1. If you want to measure unwrapped text, I'd suggest modifying your DOM tree and having an inner <div> of which you can measure easily by doing $('#outer').children().height()

RecyclerView - How to smooth scroll to top of item on a certain position?

You can reverse your list by list.reverse() and finaly call RecylerView.scrollToPosition(0)

    list.reverse()
    layout = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,true)  
    RecylerView.scrollToPosition(0)

Remove scrollbars from textarea

Give a class for eg: scroll to the textarea tag. And in the css add this property -

_x000D_
_x000D_
.scroll::-webkit-scrollbar {
   display: none;
 }
_x000D_
<textarea class='scroll'></textarea>
_x000D_
_x000D_
_x000D_

It worked for without missing the scroll part

How to window.scrollTo() with a smooth effect

2018 Update

Now you can use just window.scrollTo({ top: 0, behavior: 'smooth' }) to get the page scrolled with a smooth effect.

_x000D_
_x000D_
const btn = document.getElementById('elem');_x000D_
_x000D_
btn.addEventListener('click', () => window.scrollTo({_x000D_
  top: 400,_x000D_
  behavior: 'smooth',_x000D_
}));
_x000D_
#x {_x000D_
  height: 1000px;_x000D_
  background: lightblue;_x000D_
}
_x000D_
<div id='x'>_x000D_
  <button id='elem'>Click to scroll</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Older solutions

You can do something like this:

_x000D_
_x000D_
var btn = document.getElementById('x');_x000D_
_x000D_
btn.addEventListener("click", function() {_x000D_
  var i = 10;_x000D_
  var int = setInterval(function() {_x000D_
    window.scrollTo(0, i);_x000D_
    i += 10;_x000D_
    if (i >= 200) clearInterval(int);_x000D_
  }, 20);_x000D_
})
_x000D_
body {_x000D_
  background: #3a2613;_x000D_
  height: 600px;_x000D_
}
_x000D_
<button id='x'>click</button>
_x000D_
_x000D_
_x000D_

ES6 recursive approach:

_x000D_
_x000D_
const btn = document.getElementById('elem');_x000D_
_x000D_
const smoothScroll = (h) => {_x000D_
  let i = h || 0;_x000D_
  if (i < 200) {_x000D_
    setTimeout(() => {_x000D_
      window.scrollTo(0, i);_x000D_
      smoothScroll(i + 10);_x000D_
    }, 10);_x000D_
  }_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', () => smoothScroll());
_x000D_
body {_x000D_
  background: #9a6432;_x000D_
  height: 600px;_x000D_
}
_x000D_
<button id='elem'>click</button>
_x000D_
_x000D_
_x000D_

Disable scrolling in an iPhone web application?

This should work. No more gray areas at the top or bottom:)

<script type="text/javascript">
   function blockMove() {
      event.preventDefault() ;
}
</script>

<body ontouchmove="blockMove()">

But this also disables any scrollable areas. If you want to keep your scrollable areas and still remove the rubber band effect at the top and bottom, see here: https://github.com/joelambert/ScrollFix.

Get div's offsetTop positions in React

I do realize that the author asks question in relation to a class-based component, however I think it's worth mentioning that as of React 16.8.0 (February 6, 2019) you can take advantage of hooks in function-based components.

Example code:

import { useRef } from 'react'

function Component() {
  const inputRef = useRef()

  return (
    <input ref={inputRef} />
    <div
      onScroll={() => {
        const { offsetTop } = inputRef.current
        ...
      }}
    >
  )
}

JQuery window scrolling event?

Check if the user has scrolled past the header ad, then display the footer ad.

if($(your header ad).position().top < 0) { $(your footer ad).show() }

Am I correct at what you are looking for?

Get div tag scroll position using JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function scollPos() {
            var div = document.getElementById("myDiv").scrollTop;
            document.getElementById("pos").innerHTML = div;
        }
    </script>
</head>
<body>
    <form id="form1">
    <div id="pos">
    </div>
    <div id="myDiv" style="overflow: auto; height: 200px; width: 200px;" onscroll="scollPos();">
        Place some large content here
    </div>
    </form>
</body>
</html>

How to check if element is visible after scrolling?

Update: use IntersectionObserver


The best method I have found so far is the jQuery appear plugin. Works like a charm.

Mimics a custom "appear" event, which fires when an element scrolls into view or otherwise becomes visible to the user.

$('#foo').appear(function() {
  $(this).text('Hello world');
});

This plugin can be used to prevent unnecessary requests for content that's hidden or outside the viewable area.

How to scroll the page when a modal dialog is longer than the screen?

simple way you can do this by adding this css So, you just added this to CSS:

.modal-body {
position: relative;
padding: 20px;
height: 200px;
overflow-y: scroll;
}

and it's working!

jQuery scroll to ID from different page

On the link put a hash:

<a href="otherpage.html#elementID">Jump</a>

And on other page, you can do:

$('html,body').animate({
  scrollTop: $(window.location.hash).offset().top
});

On other page, you should have element with id set to elementID to scroll to. Of course you can change the name of it.

Detect user scroll down or scroll up in jQuery

To differentiate between scroll up/down in jQuery, you could use:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
    }
    else{
        //scroll down
    }   
});

This method also works in divs that have overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

Automatically scroll down chat div

Let's review a few useful concepts about scrolling first:

When should you scroll?

  • User has loaded messages for the first time.
  • New messages have arrived and you are at the bottom of the scroll (you don't want to force scroll when the user is scrolling up to read previous messages).

Programmatically that is:

if (firstTime) {
  container.scrollTop = container.scrollHeight;
  firstTime = false;
} else if (container.scrollTop + container.clientHeight === container.scrollHeight) {
  container.scrollTop = container.scrollHeight;
}

Full chat simulator (with JavaScript):

https://jsfiddle.net/apvtL9xa/

_x000D_
_x000D_
const messages = document.getElementById('messages');_x000D_
_x000D_
function appendMessage() {_x000D_
 const message = document.getElementsByClassName('message')[0];_x000D_
  const newMessage = message.cloneNode(true);_x000D_
  messages.appendChild(newMessage);_x000D_
}_x000D_
_x000D_
function getMessages() {_x000D_
 // Prior to getting your messages._x000D_
  shouldScroll = messages.scrollTop + messages.clientHeight === messages.scrollHeight;_x000D_
  /*_x000D_
   * Get your messages, we'll just simulate it by appending a new one syncronously._x000D_
   */_x000D_
  appendMessage();_x000D_
  // After getting your messages._x000D_
  if (!shouldScroll) {_x000D_
    scrollToBottom();_x000D_
  }_x000D_
}_x000D_
_x000D_
function scrollToBottom() {_x000D_
  messages.scrollTop = messages.scrollHeight;_x000D_
}_x000D_
_x000D_
scrollToBottom();_x000D_
_x000D_
setInterval(getMessages, 100);
_x000D_
#messages {_x000D_
  height: 200px;_x000D_
  overflow-y: auto;_x000D_
}
_x000D_
<div id="messages">_x000D_
  <div class="message">_x000D_
    Hello world_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fade In on Scroll Down, Fade Out on Scroll Up - based on element position in window

I tweaked your code a bit and made it more robust. In terms of progressive enhancement it's probaly better to have all the fade-in-out logic in JavaScript. In the example of myfunksyde any user without JavaScript sees nothing because of the opacity: 0;.

    $(window).on("load",function() {
    function fade() {
        var animation_height = $(window).innerHeight() * 0.25;
        var ratio = Math.round( (1 / animation_height) * 10000 ) / 10000;

        $('.fade').each(function() {

            var objectTop = $(this).offset().top;
            var windowBottom = $(window).scrollTop() + $(window).innerHeight();

            if ( objectTop < windowBottom ) {
                if ( objectTop < windowBottom - animation_height ) {
                    $(this).html( 'fully visible' );
                    $(this).css( {
                        transition: 'opacity 0.1s linear',
                        opacity: 1
                    } );

                } else {
                    $(this).html( 'fading in/out' );
                    $(this).css( {
                        transition: 'opacity 0.25s linear',
                        opacity: (windowBottom - objectTop) * ratio
                    } );
                }
            } else {
                $(this).html( 'not visible' );
                $(this).css( 'opacity', 0 );
            }
        });
    }
    $('.fade').css( 'opacity', 0 );
    fade();
    $(window).scroll(function() {fade();});
});

See it here: http://jsfiddle.net/78xjLnu1/16/

Cheers, Martin

scrollTop jquery, scrolling to div with id?

instead of

$('html, body').animate({scrollTop:xxx}, 'slow');

use

$('html, body').animate({scrollTop:$('#div_id').position().top}, 'slow');

this will return the absolute top position of whatever element you select as #div_id

CSS - Overflow: Scroll; - Always show vertical scroll bar?

Please note on iPad Safari, NoviceCoding's solution won't work if you have -webkit-overflow-scrolling: touch; somewhere in your CSS. The solution is either removing all the occurrences of -webkit-overflow-scrolling: touch; or putting -webkit-overflow-scrolling: auto; with NoviceCoding's solution.

html/css buttons that scroll down to different div sections on a webpage

try this:

<input type="button" onClick="document.getElementById('middle').scrollIntoView();" />

Disable scrolling in all mobile devices

In page header, add

<meta name="viewport" content="width=device-width, initial-scale=1, minimum-sacle=1, maximum-scale=1, user-scalable=no">

In page stylesheet, add

html, body {
  overflow-x: hidden;
  overflow-y: hidden;
}

It is both html and body!

Scroll to the top of the page after render in react.js

Since the original solution was provided for very early version of react, here is an update:

constructor(props) {
    super(props)
    this.myRef = React.createRef()   // Create a ref object 
}

componentDidMount() {
  this.myRef.current.scrollTo(0, 0);
}

render() {
    return <div ref={this.myRef}></div> 
}   // attach the ref property to a dom element

Disable vertical scroll bar on div overflow: auto

You should use only

overflow-y:hidden; - Use this for hiding the Vertical scroll

overflow-x:auto; - Use this to show Horizontal scroll

Luke has mentioned as both hidden. so I have given this separately.

Scroll Element into View with Selenium

JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("javascript:window.scrollBy(250,350)");

You may want to try this.

ipad safari: disable scrolling, and bounce effect?

Try this JS solution that toggles webkitOverflowScrolling style. The trick here is that this style is off, mobile Safari goes to ordinary scrolling and prevents over-bounce — alas, it is not able to cancel ongoing drag. This complex solution also tracks onscroll as bounce over the top makes scrollTop negative that may be tracked. This solution was tested on iOS 12.1.1 and has single drawback: while accelerating the scroll single over-bounce still happens as resetting the style may not cancel it immediately.

function preventScrollVerticalBounceEffect(container) {
  setTouchScroll(true) //!: enable before the first scroll attempt

  container.addEventListener("touchstart", onTouchStart)
  container.addEventListener("touchmove", onTouch, { passive: false })
  container.addEventListener("touchend", onTouchEnd)
  container.addEventListener("scroll", onScroll)

  function isTouchScroll() {
    return !!container.style.webkitOverflowScrolling
  }

  let prevScrollTop = 0, prevTouchY, opid = 0

  function setTouchScroll(on) {
    container.style.webkitOverflowScrolling = on ? "touch" : null

    //Hint: auto-enabling after a small pause makes the start
    // smoothly accelerated as required. After the pause the
    // scroll position is settled, and there is no delta to
    // make over-bounce by dragging the finger. But still,
    // accelerated content makes short single over-bounce
    // as acceleration may not be off instantly.

    const xopid = ++opid
    !on && setTimeout(() => (xopid === opid) && setTouchScroll(true), 250)

    if(!on && container.scrollTop < 16)
      container.scrollTop = 0
    prevScrollTop = container.scrollTop
  }

  function isBounceOverTop() {
    const dY = container.scrollTop - prevScrollTop
    return dY < 0 && container.scrollTop < 16
  }

  function isBounceOverBottom(touchY) {
    const dY = touchY - prevTouchY

    //Hint: trying to bounce over the bottom, the finger moves
    // up the screen, thus Y becomes smaller. We prevent this.

    return dY < 0 && container.scrollHeight - 16 <=
      container.scrollTop + container.offsetHeight
  }

  function onTouchStart(e) {
    prevTouchY = e.touches[0].pageY
  }

  function onTouch(e) {
    const touchY = e.touches[0].pageY

    if(isBounceOverBottom(touchY)) {
      if(isTouchScroll())
        setTouchScroll(false)
      e.preventDefault()
    }

    prevTouchY = touchY
  }

  function onTouchEnd() {
    prevTouchY = undefined
  }

  function onScroll() {
    if(isTouchScroll() && isBounceOverTop()) {
      setTouchScroll(false)
    }
  }
}

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

Add this code after sending message and before getting message from server

recyclerView.scrollToPosition(mChatList.size() - 1);

How to make div follow scrolling smoothly with jQuery?

I needed the div to stop when it reach a certain object, so i did it like this:

var el = $('#followdeal');
    var elpos_original = el.offset().top;
    $(window).scroll(function(){
        var elpos = el.offset().top;
        var windowpos = $(window).scrollTop();
        var finaldestination = windowpos;
        var stophere = ( $('#filtering').offset().top ) - 170;
        if(windowpos<elpos_original || windowpos>=stophere) {
            finaldestination = elpos_original;
            el.stop().animate({'top':10});
        } else {
            el.stop().animate({'top':finaldestination-elpos_original+10},500);
        }
    });

How to scroll the window using JQuery $.scrollTo() function

jQuery now supports scrollTop as an animation variable.

$("#id").animate({"scrollTop": $("#id").scrollTop() + 100});

You no longer need to setTimeout/setInterval to scroll smoothly.

How to get scrollbar position with Javascript?

it's like this :)

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

Detecting scroll direction

You can get the scrollbar position using document.documentElement.scrollTop. And then it is simply matter of comparing it to the previous position.

Stop fixed position at footer

I ran into this same issue recently, posted the my solution also here: Preventing element from displaying on top of footer when using position:fixed

You can achieve a solution leveraging the position property of the element with jQuery, switching between the default value (static for divs), fixed and absolute. You will also need a container element for your fixed element. Finally, in order to prevent the fixed element to go over the footer, this container element can't be the parent of the footer.

The javascript part involves calculating the distance in pixels between your fixed element and the top of the document, and comparing it with the current vertical position of the scrollbar relatively to the window object (i.e. the number of pixels above that are hidden from the visible area of the page) every time the user scrolls the page. When, on scrolling down, the fixed element is about to disappear above, we change its position to fixed and stick on top of the page.

This causes the fixed element to go over the footer when we scroll to the bottom, especially if the browser window is small. Therefore, we will calculate the distance in pixels of the footer from the top of the document and compare it with the height of the fixed element plus the vertical position of the scrollbar: when the fixed element is about to go over the footer, we will change its position to absolute and stick at the bottom, just over the footer.

Here's a generic example.

The HTML structure:

<div id="content">
    <div id="leftcolumn">
        <div class="fixed-element">
            This is fixed 
        </div>
    </div>
    <div id="rightcolumn">Main content here</div>
    <div id="footer"> The footer </div>
</div>  

The CSS:

#leftcolumn {
    position: relative;
}
.fixed-element {
    width: 180px;
}
.fixed-element.fixed {
    position: fixed;
    top: 20px;
}
.fixed-element.bottom {
    position: absolute;
    bottom: 356px; /* Height of the footer element, plus some extra pixels if needed */
}

The JS:

// Position of fixed element from top of the document
var fixedElementOffset = $('.fixed-element').offset().top;
// Position of footer element from top of the document.
// You can add extra distance from the bottom if needed,
// must match with the bottom property in CSS
var footerOffset = $('#footer').offset().top - 36;

var fixedElementHeight = $('.fixed-element').height(); 

// Check every time the user scrolls
$(window).scroll(function (event) {

    // Y position of the vertical scrollbar
    var y = $(this).scrollTop();

    if ( y >= fixedElementOffset && ( y + fixedElementHeight ) < footerOffset ) {
        $('.fixed-element').addClass('fixed');
        $('.fixed-element').removeClass('bottom');          
    }
    else if ( y >= fixedElementOffset && ( y + fixedElementHeight ) >= footerOffset ) {
        $('.fixed-element').removeClass('fixed');           
        $('.fixed-element').addClass('bottom');
    }
    else {
        $('.fixed-element').removeClass('fixed bottom');
    }

 });

Scroll to the top of the page using JavaScript?

$(document).scrollTop(0); also works.

ScrollTo function in AngularJS

What about angular-scroll, it's actively maintained and there is no dependency to jQuery..

Animate scroll to ID on page load

$(jQuery.browser.webkit ? "body": "html").animate({ scrollTop: $('#title1').offset().top }, 1000);

jquery-animate-body-for-all-browsers.

Listview Scroll to the end of the list after updating the list

The transcript mode is what you want and is used by Google Talk and the SMS/MMS application. Are you correctly calling notifyDatasetChanged() on your adapter when you add items?

jQuery move to anchor location on page load

Description

You can do this using jQuery's .scrollTop() and .offset() method

Check out my sample and this jsFiddle Demonstration

Sample

$(function() {
    $(document).scrollTop( $("#header").offset().top );  
});

More Information

Scroll RecyclerView to show selected item on top

If you looking for vertical LinearLayout Manager you can achieve smooth scrolling using a custom LinearSmoothScroller:

import android.content.Context;
import android.graphics.PointF;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;

public class SnappingLinearLayoutManager extends LinearLayoutManager {

    public SnappingLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
                                       int position) {
        RecyclerView.SmoothScroller smoothScroller = new TopSnappedSmoothScroller(recyclerView.getContext());
        smoothScroller.setTargetPosition(position);
        startSmoothScroll(smoothScroller);
    }

    private class TopSnappedSmoothScroller extends LinearSmoothScroller {
        public TopSnappedSmoothScroller(Context context) {
            super(context);

        }

        @Override
        public PointF computeScrollVectorForPosition(int targetPosition) {
            return SnappingLinearLayoutManager.this
                    .computeScrollVectorForPosition(targetPosition);
        }

        @Override
        protected int getVerticalSnapPreference() {
            return SNAP_TO_START;
        }
    }
}

use an instance of the layoutmanager in recycle view and then calling recyclerView.smoothScrollToPosition(pos); will smooth scroll to selected position to top of the recycler view

Smooth scrolling when clicking an anchor link

There is a css way of doing this using scroll-behavior. Add the following property.

    scroll-behavior: smooth;

And that is it. No JS required.

_x000D_
_x000D_
a {_x000D_
  display: inline-block;_x000D_
  width: 50px;_x000D_
  text-decoration: none;_x000D_
}_x000D_
nav, scroll-container {_x000D_
  display: block;_x000D_
  margin: 0 auto;_x000D_
  text-align: center;_x000D_
}_x000D_
nav {_x000D_
  width: 339px;_x000D_
  padding: 5px;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
scroll-container {_x000D_
  display: block;_x000D_
  width: 350px;_x000D_
  height: 200px;_x000D_
  overflow-y: scroll;_x000D_
  scroll-behavior: smooth;_x000D_
}_x000D_
scroll-page {_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
  height: 100%;_x000D_
  font-size: 5em;_x000D_
}
_x000D_
<nav>_x000D_
  <a href="#page-1">1</a>_x000D_
  <a href="#page-2">2</a>_x000D_
  <a href="#page-3">3</a>_x000D_
</nav>_x000D_
<scroll-container>_x000D_
  <scroll-page id="page-1">1</scroll-page>_x000D_
  <scroll-page id="page-2">2</scroll-page>_x000D_
  <scroll-page id="page-3">3</scroll-page>_x000D_
</scroll-container>
_x000D_
_x000D_
_x000D_

PS: please check the browser compatibility.

How to scroll to top of page with JavaScript/jQuery?

To answer your edited-in question, you could register the onscroll handler like so:

document.documentElement.onscroll = document.body.onscroll = function() {
    this.scrollTop = 0;
    this.onscroll = null;
}

This will make it so that the first attempt at scrolling (which is likely the automatic one done by the browser) will be effectively cancelled.

How to increase scrollback buffer size in tmux?

The history limit is a pane attribute that is fixed at the time of pane creation and cannot be changed for existing panes. The value is taken from the history-limit session option (the default value is 2000).

To create a pane with a different value you will need to set the appropriate history-limit option before creating the pane.

To establish a different default, you can put a line like the following in your .tmux.conf file:

set-option -g history-limit 3000

Note: Be careful setting a very large default value, it can easily consume lots of RAM if you create many panes.

For a new pane (or the initial pane in a new window) in an existing session, you can set that session’s history-limit. You might use a command like this (from a shell):

tmux set-option history-limit 5000 \; new-window

For (the initial pane of the initial window in) a new session you will need to set the “global” history-limit before creating the session:

tmux set-option -g history-limit 5000 \; new-session

Note: If you do not re-set the history-limit value, then the new value will be also used for other panes/windows/sessions created in the future; there is currently no direct way to create a single new pane/window/session with its own specific limit without (at least temporarily) changing history-limit (though show-option (especially in 1.7 and later) can help with retrieving the current value so that you restore it later).

Have a fixed position div that needs to scroll if content overflows

Generally speaking, fixed section should be set with width, height and top, bottom properties, otherwise it won't recognise its size and position.

If the used box is direct child for body and has neighbours, then it makes sense to check z-index and top, left properties, since they could overlap each other, which might affect your mouse hover while scrolling the content.

Here is the solution for a content box (a direct child of body tag) which is commonly used along with mobile navigation.

.fixed-content {
    position: fixed;
    top: 0;
    bottom:0;

    width: 100vw; /* viewport width */
    height: 100vh; /* viewport height */
    overflow-y: scroll;
    overflow-x: hidden;
}

Hope it helps anybody. Thank you!

scroll up and down a div on button click using jquery

For the go up, you just need to use scrollTop instead of scrollBottom:

$("#upClick").on("click", function () {
    scrolled = scrolled - 300;
    $(".cover").stop().animate({
        scrollTop: scrolled
    });
});

Also, use the .stop() method to stop the currently-running animation on the cover div. When .stop() is called on an element, the currently-running animation (if any) is immediately stopped.

FIDDLE DEMO

How do I automatically scroll to the bottom of a multiline text box?

It seems the interface has changed in .NET 4.0. There is the following method that achieves all of the above. As Tommy Engebretsen suggested, putting it in a TextChanged event handler makes it automatic.

textBox1.ScrollToEnd();

Show/Hide Div on Scroll

<div>
  <div class="a">
    A
  </div>
</div>?


$(window).scroll(function() {
  if ($(this).scrollTop() > 0) {
    $('.a').fadeOut();
  } else {
    $('.a').fadeIn();
  }
});

Sample

How do you add a scroll bar to a div?

Css class to have a nice Div with scroll

.DivToScroll{   
    background-color: #F5F5F5;
    border: 1px solid #DDDDDD;
    border-radius: 4px 0 4px 0;
    color: #3B3C3E;
    font-size: 12px;
    font-weight: bold;
    left: -1px;
    padding: 10px 7px 5px;
}

.DivWithScroll{
    height:120px;
    overflow:scroll;
    overflow-x:hidden;
}

how to automatically scroll down a html page?

You can use two different techniques to achieve this.

The first one is with javascript: set the scrollTop property of the scrollable element (e.g. document.body.scrollTop = 1000;).

The second is setting the link to point to a specific id in the page e.g.

<a href="mypage.html#sectionOne">section one</a>

Then if in your target page you'll have that ID the page will be scrolled automatically.

How can I make a div stick to the top of the screen once it's been scrolled to?

My solution is a little verbose, but it handles variable positioning from the left edge for centered layouts.

// Ensurs that a element (usually a div) stays on the screen
//   aElementToStick   = The jQuery selector for the element to keep visible
global.makeSticky = function (aElementToStick) {
    var $elementToStick = $(aElementToStick);
    var top = $elementToStick.offset().top;
    var origPosition = $elementToStick.css('position');

    function positionFloater(a$Win) {
        // Set the original position to allow the browser to adjust the horizontal position
        $elementToStick.css('position', origPosition);

        // Test how far down the page is scrolled
        var scrollTop = a$Win.scrollTop();
        // If the page is scrolled passed the top of the element make it stick to the top of the screen
        if (top < scrollTop) {
            // Get the horizontal position
            var left = $elementToStick.offset().left;
            // Set the positioning as fixed to hold it's position
            $elementToStick.css('position', 'fixed');
            // Reuse the horizontal positioning
            $elementToStick.css('left', left);
            // Hold the element at the top of the screen
            $elementToStick.css('top', 0);
        }
    }

    // Perform initial positioning
    positionFloater($(window));

    // Reposition when the window resizes
    $(window).resize(function (e) {
        positionFloater($(this));
    });

    // Reposition when the window scrolls
    $(window).scroll(function (e) {
        positionFloater($(this));
    });
};

Detect if a page has a vertical scrollbar?

Simply compare the width of the documents root element (i.e. html element) against the inner portion of the window:

if ((window.innerWidth - document.documentElement.clientWidth) >0) console.log('V-scrollbar active')

If you also need to know the scrollbar width:

vScrollbarWidth = window.innerWidth - document.documentElement.clientWidth;

Pure CSS scroll animation

Use anchor links and the scroll-behavior property (MDN reference) for the scrolling container:

scroll-behavior: smooth;

Browser support: Firefox 36+, Chrome 61+ (therefore also Edge 79+) and Opera 48+.

Intenet Explorer, non-Chromium Edge and (so far) Safari do not support scroll-behavior and simply "jump" to the link target.

Example usage:

<head>
  <style type="text/css">
    html {
      scroll-behavior: smooth;
    }
  </style>
</head>
<body id="body">
  <a href="#foo">Go to foo!</a>

  <!-- Some content -->

  <div id="foo">That's foo.</div>
  <a href="#body">Back to top</a>
</body>

Here's a Fiddle.

And here's also a Fiddle with both horizontal and vertical scrolling.

Smooth scroll to div id jQuery

You need to animate the html, body

DEMO http://jsfiddle.net/kevinPHPkevin/8tLdq/1/

$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#myDiv").offset().top
    }, 2000);
});

How to move screen without moving cursor in Vim?

I've used these shortcuts in the past (note: separate key strokes i.e. tap z, let go, tap the subsequent key):

z enter --> moves current line to top of screen

z . --> moves current line to center of screen

z - --> moves current line to bottom

If it's not obvious:

enter means the Return or Enter key.

. means the DOT or "full stop" key (.).

- means the HYPHEN key (-)

For what it's worth, z. avoids the danger of saving and closing Vi by accidentally typing ZZ if the caps-lock is on.

How to load images dynamically (or lazily) when users scrolls them into view

The Swiss Army knife of image lazy loading is YUI's ImageLoader.

Because there is more to this problem than simply watching the scroll position.

Scroll back to the top of scrollable div

2020 UPDATE

You can use .scroll() to easily scroll elements or window. It has a built-in smooth scroll effect so basically the code couldn't be simpler.

Standard properties:

var options = {
    top:       0,        // Number of pixels along the Y axis to scroll the window or element
    left:      0,        // Number of pixels along the X axis to scroll the window or element.
    behavior:  'smooth'  // ('smooth'|'auto') - animate smoothly, or move in a single jump
}

DOCS: https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll

SEE ALSO: .scrollIntoView() https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView


DEMO:

_x000D_
_x000D_
document.getElementById('btn').addEventListener('click',function(){

  document.getElementById('container').scroll({top:0,behavior:'smooth'});
  
});
_x000D_
/*DEMO*/
#container{
  width:300px;
  max-height:300px;
  padding:1rem;
  margin-left:auto;
  margin-right:auto;
  background-color:#222;
  color:#ccc;
  text-align:justify;
  overflow-y:auto;
}
#btn{
  width:100%;
  margin-top:1rem;
}
_x000D_
<div id="container">
  <div>Lorem ipsum dolor sit amet, consectetur adipiscing 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. Lorem ipsum dolor sit amet, consectetur adipiscing 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. Lorem ipsum dolor sit amet, consectetur adipiscing 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. Lorem ipsum dolor sit amet, consectetur adipiscing 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. Lorem ipsum dolor sit amet, consectetur adipiscing 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>
  <button id="btn">Scroll to top</button>
</div>
_x000D_
_x000D_
_x000D_

scrollIntoView Scrolls just too far

Solution if you are using Ionic Capacitor, Angular Material, and need to support iOS 11.

                document.activeElement.parentElement.parentElement.scrollIntoView({block: 'center', behavior: 'smooth'}); 

The key is to scroll to the parent of the parent which is the wrapper around the input. This wrapper includes the label for the input which is now no longer cut off.

If you only need to support iOS 14 the "block" center param actually works, so this is sufficient:

                document.activeElement.scrollIntoView({block: 'center', behavior: 'smooth'}); 

How to scroll HTML page to given anchor?

Smoothly scroll to the proper position (2019)

Get correct y coordinate and use window.scrollTo({top: y, behavior: 'smooth'})

const id = 'anchorName2';
const yourElement = document.getElementById(id);
const y = yourElement.getBoundingClientRect().top + window.pageYOffset;

window.scrollTo({top: y, behavior: 'smooth'});

With offset

scrollIntoView is a good option too but it may not works perfectly in some cases. For example when you need additional offset. With scrollTo you just need to add that offset like this:

const yOffset = -10; 

window.scrollTo({top: y + yOffset, behavior: 'smooth'});

Jquery .on('scroll') not firing the event while scrolling

You probably forgot to give # before id for id selector, you need to give # before id ie is ulId

You problably need to bind scroll event on div that contains the ul and scrolls. You need to bind the event with div instead of ul

$(document).on( 'scroll', '#idOfDivThatContainsULandScroll', function(){
    console.log('Event Fired');
});

Edit

The above would not work because the scroll event does not bubble up in DOM which is used for event delegation, see this question why doesn't delegate work for scroll?

But with modern browsers > IE 8 you can do it by other way. Instead of delegating by using jquery you can do it using event capturing with java script document.addEventListener, with the third argument as true; see how bubbling and capturing work in this tuturial.

Live Demo

document.addEventListener('scroll', function (event) {
    if (event.target.id === 'idOfUl') { // or any other filtering condition        
        console.log('scrolling', event.target);
    }
}, true /*Capture event*/);

If you do not need event delegation then you can bind scroll event directly to the ul instead of delegating it through document.

Live Demo

$("#idOfUl").on( 'scroll', function(){
   console.log('Event Fired');
});

Auto height div with overflow and scroll when needed

I'm surprised no one's mentioned calc() yet.

I wasn't able to make-out your specific case from your fiddles, but I understand your problem: you want a height: 100% container that can still use overflow-y: auto.

This doesn't work out of the box because overflow requires some hard-coded size constraint to know when it ought to start handling overflow. So, if you went with height: 100px, it'd work as expected.

The good news is that calc() can help, but it's not as simple as height: 100%.

calc() lets you combine arbitrary units of measure.

So, for the situation you describe in the picture you include: picture of desired state

Since all the elements above and below the pink div are of a known height (let's say, 200px in total height), you can use calc to determine the height of ole pinky:

height: calc(100vh - 200px);

or, 'height is 100% of the view height minus 200px.'

Then, overflow-y: auto should work like a charm.

How to make div fixed after you scroll to that div?

I know this is tagged html/css only, but you can't do that with css only. Easiest way will be using some jQuery.

var fixmeTop = $('.fixme').offset().top;       // get initial position of the element

$(window).scroll(function() {                  // assign scroll event listener

    var currentScroll = $(window).scrollTop(); // get current position

    if (currentScroll >= fixmeTop) {           // apply position: fixed if you
        $('.fixme').css({                      // scroll to that element or below it
            position: 'fixed',
            top: '0',
            left: '0'
        });
    } else {                                   // apply position: static
        $('.fixme').css({                      // if you scroll above it
            position: 'static'
        });
    }

});

http://jsfiddle.net/5n5MA/2/

Making TextView scrollable on Android

Try this:

android:scrollbars = "vertical"

How can I scroll to a specific location on the page using jquery?

There is no need to use any plugin, you can do it like this:

var divPosition = $('#divId').offset();

then use this to scroll document to specific DOM:

$('html, body').animate({scrollTop: divPosition.top}, "slow");

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

All the solutions given in this thread don't mention an existing - and native - way to solve this problem without reordering DOM and/or using event preventing tricks. But there's a good reason: this way is proprietary - and available on MS web platform only. Quoting MSDN:

-ms-scroll-chaining property - specifies the scrolling behavior that occurs when a user hits the scroll limit during a manipulation. Property values:

chained - Initial value. The nearest scrollable parent element begins scrolling when the user hits a scroll limit during a manipulation. No bounce effect is shown.

none - A bounce effect is shown when the user hits a scroll limit during a manipulation.

Granted, this property is supported on IE10+/Edge only. Still, here's a telling quote:

To give you a sense of how popular preventing scroll chaining may be, according to my quick http-archive search "-ms-scroll-chaining: none" is used in 0.4% of top 300K pages despite being limited in functionality and only supported on IE/Edge.

And now good news, everyone! Starting from Chrome 63, we finally have a native cure for Blink-based platforms too - and that's both Chrome (obviously) and Android WebView (soon).

Quoting the introducing article:

The overscroll-behavior property is a new CSS feature that controls the behavior of what happens when you over-scroll a container (including the page itself). You can use it to cancel scroll chaining, disable/customize the pull-to-refresh action, disable rubberbanding effects on iOS (when Safari implements overscroll-behavior), and more.[...]

The property takes three possible values:

auto - Default. Scrolls that originate on the element may propagate to ancestor elements.

contain - prevents scroll chaining. Scrolls do not propagate to ancestors but local effects within the node are shown. For example, the overscroll glow effect on Android or the rubberbanding effect on iOS which notifies the user when they've hit a scroll boundary. Note: using overscroll-behavior: contain on the html element prevents overscroll navigation actions.

none - same as contain but it also prevents overscroll effects within the node itself (e.g. Android overscroll glow or iOS rubberbanding).

[...] The best part is that using overscroll-behavior does not adversely affect page performance like the hacks mentioned in the intro!

Here's this feature in action. And here's corresponding CSS Module document.

UPDATE: Firefox, since version 59, has joined the club, and MS Edge is expected to implement this feature in version 18. Here's the corresponding caniusage.

How to programmatically disable page scrolling with jQuery

This may or may not work for your purposes, but you can extend jScrollPane to fire other functionality before it does its scrolling. I've only just tested this a little bit, but I can confirm that you can jump in and prevent the scrolling entirely. All I did was:

  • Download the demo zip: http://github.com/vitch/jScrollPane/archives/master
  • Open the "Events" demo (events.html)
  • Edit it to use the non-minified script source: <script type="text/javascript" src="script/jquery.jscrollpane.js"></script>
  • Within jquery.jscrollpane.js, insert a "return;" at line 666 (auspicious line number! but in case your version differs slightly, this is the first line of the positionDragY(destY, animate) function

Fire up events.html, and you'll see a normally scrolling box which due to your coding intervention won't scroll.

You can control the entire browser's scrollbars this way (see fullpage_scroll.html).

So, presumably the next step is to add a call to some other function that goes off and does your anchoring magic, then decides whether to continue with the scroll or not. You've also got API calls to set scrollTop and scrollLeft.

If you want more help, post where you get up to!

Hope this has helped.

How to enable scrolling of content inside a modal?

Set height for modal-body and not for the whole modal to get a perfect scroll on modal overlay. I get it work like this:

.MyModal {
    height: 450px;
    overflow-y: auto;
}

Here you can set height as per your requirements.

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

jQuery Scroll to bottom of page/iframe

scrollTop() returns the number of pixels that are hidden from view from the scrollable area, so giving it:

$(document).height()

will actually overshoot the bottom of the page. For the scroll to actually 'stop' at the bottom of the page, the current height of the browser window needs subtracting. This will allow the use of easing if required, so it becomes:

$('html, body').animate({ 
   scrollTop: $(document).height()-$(window).height()}, 
   1400, 
   "easeOutQuint"
);

jQuery window scroll event does not fire up

$('#div').scroll(function () {
   if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight-1) {

     //fire your event


    }
}

How to redraw DataTable with new data

If you want to refresh the table without adding new data then use this:

First, create the API variable of your table like this:

var myTableApi = $('#mytable').DataTable(); // D must be Capital in this.

And then use refresh code wherever you want:

myTableApi.search(jQuery('input[type="search"]').val()).draw() ;

It will search data table with current search value (even if it's blank) and refresh data,, this work even if Datatable has server-side processing enabled.

How to put labels over geom_bar in R with ggplot2

As with many tasks in ggplot, the general strategy is to put what you'd like to add to the plot into a data frame in a way such that the variables match up with the variables and aesthetics in your plot. So for example, you'd create a new data frame like this:

dfTab <- as.data.frame(table(df))
colnames(dfTab)[1] <- "x"
dfTab$lab <- as.character(100 * dfTab$Freq / sum(dfTab$Freq))

So that the x variable matches the corresponding variable in df, and so on. Then you simply include it using geom_text:

ggplot(df) + geom_bar(aes(x,fill=x)) + 
    geom_text(data=dfTab,aes(x=x,y=Freq,label=lab),vjust=0) +
    opts(axis.text.x=theme_blank(),axis.ticks=theme_blank(),
        axis.title.x=theme_blank(),legend.title=theme_blank(),
        axis.title.y=theme_blank())

This example will plot just the percentages, but you can paste together the counts as well via something like this:

dfTab$lab <- paste(dfTab$Freq,paste("(",dfTab$lab,"%)",sep=""),sep=" ")

Note that in the current version of ggplot2, opts is deprecated, so we would use theme and element_blank now.

Adding n hours to a date in Java?

To simplify @Christopher's example.

Say you have a constant

public static final long HOUR = 3600*1000; // in milli-seconds.

You can write.

Date newDate = new Date(oldDate.getTime() + 2 * HOUR);

If you use long to store date/time instead of the Date object you can do

long newDate = oldDate + 2 * HOUR;

How to use border with Bootstrap

There's a property in CSS called box-sizing. It determines the total width of an element on your page. The default value is content-box, which doesn't include the padding, margin, or border of the element.

Hence, if you set a div to have width: 500px and 20px padding all around, it will take up 540px on your website (500 + 20 + 20).

This is what is causing your problem. Bootstrap calculates set widths for things just like the above example, and these things don't have borders. Since Bootstrap fits together like a puzzle, adding a border to one of the sides would yield a total width of 501px (continuing the above example) and break your layout.

The easiest way to fix this is to adjust your box-sizing. The value you would use is box-sizing: border-box. This includes the padding and border in your box elements. You can read more about box-sizing here.

A problem with this solution is that it only works on IE8+. Consequently, if you need deeper IE support you'll need to override the Bootstrap widths to account for your border.

To give an example of how to calculate a new width, begin by checking the width that Bootstrap sets on your element. Let's say it's a span6 and has a width of 320px (this is purely hypothetical, the actual width of your span6 will depend on your specific configuration of Bootstrap). If you wanted to add a single border on the right hand side with a 20px padding over there, you'd write this CSS in your stylesheet

.span6 {
  padding-right: 20px;
  border-right: 1px solid #ddd;
  width: 299px;
 }

where the new width is calculated by:

old width - padding - border

Oracle DB: How can I write query ignoring case?

You could also use Regular Expressions:

SELECT * FROM TABLE WHERE REGEXP_LIKE (TABLE.NAME,'IgNoReCaSe','i');

How to randomize Excel rows

Here's a macro that allows you to shuffle selected cells in a column:

Option Explicit

Sub ShuffleSelectedCells()
  'Do nothing if selecting only one cell
  If Selection.Cells.Count = 1 Then Exit Sub
  'Save selected cells to array
  Dim CellData() As Variant
  CellData = Selection.Value
  'Shuffle the array
  ShuffleArrayInPlace CellData
  'Output array to spreadsheet
  Selection.Value = CellData
End Sub

Sub ShuffleArrayInPlace(InArray() As Variant)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ShuffleArrayInPlace
' This shuffles InArray to random order, randomized in place.
' Source: http://www.cpearson.com/excel/ShuffleArray.aspx
' Modified by Tom Doan to work with Selection.Value two-dimensional arrays.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
  Dim J As Long, _
    N As Long, _
    Temp As Variant
  'Randomize
  For N = LBound(InArray) To UBound(InArray)
    J = CLng(((UBound(InArray) - N) * Rnd) + N)
    If J <> N Then
      Temp = InArray(N, 1)
      InArray(N, 1) = InArray(J, 1)
      InArray(J, 1) = Temp
    End If
  Next N
End Sub

You can read the comments to see what the macro is doing. Here's how to install the macro:

  1. Open the VBA editor (Alt + F11).
  2. Right-click on "ThisWorkbook" under your currently open spreadsheet (listed in parentheses after "VBAProject") and select Insert / Module.
  3. Paste the code above and save the spreadsheet.

Now you can assign the "ShuffleSelectedCells" macro to an icon or hotkey to quickly randomize your selected rows (keep in mind that you can only select one column of rows).

How to connect to my http://localhost web server from Android Emulator

I needed to figure out the system host IP address for the emulator "Nox App Player". Here is how I figured out it was 172.17.100.2.

  1. Installed Android Terminal Emulator from the app store
  2. Issue ip link show command to show all network interfaces. Of particular interest was the eth1 interface
  3. Issue ifconfig eth1 command, shows net as 172.17.100.15/255.255.255.0
  4. Begin pinging addresses starting at 172.17.100.1, got a hit on `172.17.100.2'. Not sure if a firewall would interfere but it didn't in my case

Maybe this can help someone else figure it out for other emulators.

Inserting records into a MySQL table using Java

There is a mistake in your insert statement chage it to below and try : String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";

MySQL pivot table query with dynamic columns

The only way in MySQL to do this dynamically is with Prepared statements. Here is a good article about them:

Dynamic pivot tables (transform rows to columns)

Your code would look like this:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(IF(pa.fieldname = ''',
      fieldname,
      ''', pa.fieldvalue, NULL)) AS ',
      fieldname
    )
  ) INTO @sql
FROM product_additional;

SET @sql = CONCAT('SELECT p.id
                    , p.name
                    , p.description, ', @sql, ' 
                   FROM product p
                   LEFT JOIN product_additional AS pa 
                    ON p.id = pa.id
                   GROUP BY p.id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

See Demo

NOTE: GROUP_CONCAT function has a limit of 1024 characters. See parameter group_concat_max_len

How to sort with lambda in Python

You're trying to use key functions with lambda functions.

Python and other languages like C# or F# use lambda functions.

Also, when it comes to key functions and according to the documentation

Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons.

...

The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.

So, key functions have a parameter key and it can indeed receive a lambda function.

In Real Python there's a nice example of its usage. Let's say you have the following list

ids = ['id1', 'id100', 'id2', 'id22', 'id3', 'id30']

and want to sort through its "integers". Then, you'd do something like

sorted_ids = sorted(ids, key=lambda x: int(x[2:])) # Integer sort

and printing it would give

['id1', 'id2', 'id3', 'id22', 'id30', 'id100']

In your particular case, you're only missing to write key= before lambda. So, you'd want to use the following

a = sorted(a, key=lambda x: x.modified, reverse=True)

functional way to iterate over range (ES6/7)

One can create an empty array, fill it (otherwise map will skip it) and then map indexes to values:

Array(8).fill().map((_, i) => i * i);

error::make_unique is not a member of ‘std’

In my case I was needed update the std=c++

I mean in my gradle file was this

android {
    ...

    defaultConfig {
        ...

        externalNativeBuild {
            cmake {
                cppFlags "-std=c++11", "-Wall"
                arguments "-DANDROID_STL=c++_static",
                        "-DARCORE_LIBPATH=${arcore_libpath}/jni",
                        "-DARCORE_INCLUDE=${project.rootDir}/app/src/main/libs"
            }
        }
       ....
    }

I changed this line

android {
    ...

    defaultConfig {
        ...

        externalNativeBuild {
            cmake {
                cppFlags "-std=c++17", "-Wall"   <-- this number from 11 to 17 (or 14)
                arguments "-DANDROID_STL=c++_static",
                        "-DARCORE_LIBPATH=${arcore_libpath}/jni",
                        "-DARCORE_INCLUDE=${project.rootDir}/app/src/main/libs"
            }
        }
       ....
    }

That's it...

How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

Do you have access to the command prompt ?

Method 1 : Command Prompt

The specifics of the Java installed on the system can be determined by executing the following command java -version

Method 2 : Folder Structure

In case you do not have access to command prompt then determining the folder where Java.

32 Bit : C:\Program Files (x86)\Java\jdk1.6.0_30

64 Bit : C:\Program Files\Java\jdk1.6.0_25

However during the installation it is possible that the user might change the installation folder.

Method 3 : Registry

You can also see the version installed in registry editor.

  1. Go to registry editor

  2. Edit -> Find

  3. Search for Java. You will get the registry entries for Java.

  4. In the entry with name : DisplayName & DisplayVersion, the installed java version is displayed

Android Imagebutton change Image OnClick

This misled me a bit - it should be setImageResource instead of setBackgroundResource :) !!

The following works fine :

ImageButton btn = (ImageButton)findViewById(R.id.imageButton1);       
 btn.setImageResource(R.drawable.actions_record);

while when using the setBackgroundResource the actual imagebutton's image stays while the background image is changed which leads to a ugly looking imageButton object

Thanks.

How to extract img src, title and alt from html using php?

If it's XHTML, your example is, you need only simpleXML.

<?php
$input = '<img src="/image/fluffybunny.jpg" title="Harvey the bunny" alt="a cute little fluffy bunny"/>';
$sx = simplexml_load_string($input);
var_dump($sx);
?>

Output:

object(SimpleXMLElement)#1 (1) {
  ["@attributes"]=>
  array(3) {
    ["src"]=>
    string(22) "/image/fluffybunny.jpg"
    ["title"]=>
    string(16) "Harvey the bunny"
    ["alt"]=>
    string(26) "a cute little fluffy bunny"
  }
}

Redirect from a view to another view

That's not how ASP.NET MVC is supposed to be used. You do not redirect from views. You redirect from the corresponding controller action:

public ActionResult SomeAction()
{
    ...
    return RedirectToAction("SomeAction", "SomeController");
}

Now since I see that in your example you are attempting to redirect to the LogOn action, you don't really need to do this redirect manually, but simply decorate the controller action that requires authentication with the [Authorize] attribute:

[Authorize]
public ActionResult SomeProtectedAction()
{
    ...
}

Now when some anonymous user attempts to access this controller action, the Forms Authentication module will automatically intercept the request much before it hits the action and redirect the user to the LogOn action that you have specified in your web.config (loginUrl).

Parse query string into an array

For this specific question the chosen answer is correct but if there is a redundant parameter—like an extra "e"—in the URL the function will silently fail without an error or exception being thrown:

a=2&b=2&c=5&d=4&e=1&e=2&e=3 

So I prefer using my own parser like so:

//$_SERVER['QUERY_STRING'] = `a=2&b=2&c=5&d=4&e=100&e=200&e=300` 

$url_qry_str  = explode('&', $_SERVER['QUERY_STRING']);

//arrays that will hold the values from the url
$a_arr = $b_arr = $c_arr = $d_arr = $e_arr =  array();

foreach( $url_qry_str as $param )
    {
      $var =  explode('=', $param, 2);
      if($var[0]=="a")      $a_arr[]=$var[1];
      if($var[0]=="b")      $b_arr[]=$var[1];
      if($var[0]=="c")      $c_arr[]=$var[1];
      if($var[0]=="d")      $d_arr[]=$var[1];
      if($var[0]=="e")      $e_arr[]=$var[1];
    }

    var_dump($e_arr); 
    // will return :
    //array(3) { [0]=> string(1) "100" [1]=> string(1) "200" [2]=> string(1) "300" } 

Now you have all the occurrences of each parameter in its own array, you can always merge them into one array if you want to.

Hope that helps!

Shuffle an array with python, randomize array item order with python

Be aware that random.shuffle() should not be used on multi-dimensional arrays as it causes repetitions.

Imagine you want to shuffle an array along its first dimension, we can create the following test example,

import numpy as np
x = np.zeros((10, 2, 3))

for i in range(10):
   x[i, ...] = i*np.ones((2,3))

so that along the first axis, the i-th element corresponds to a 2x3 matrix where all the elements are equal to i.

If we use the correct shuffle function for multi-dimensional arrays, i.e. np.random.shuffle(x), the array will be shuffled along the first axis as desired. However, using random.shuffle(x) will cause repetitions. You can check this by running len(np.unique(x)) after shuffling which gives you 10 (as expected) with np.random.shuffle() but only around 5 when using random.shuffle().

Database Structure for Tree Data Structure

You mention the most commonly implemented, which is Adjacency List: https://blogs.msdn.microsoft.com/mvpawardprogram/2012/06/25/hierarchies-convert-adjacency-list-to-nested-sets

There are other models as well, including materialized path and nested sets: http://communities.bmc.com/communities/docs/DOC-9902

Joe Celko has written a book on this subject, which is a good reference from a general SQL perspective (it is mentioned in the nested set article link above).

Also, Itzik Ben-Gann has a good overview of the most common options in his book "Inside Microsoft SQL Server 2005: T-SQL Querying".

The main things to consider when choosing a model are:

1) Frequency of structure change - how frequently does the actual structure of the tree change. Some models provide better structure update characteristics. It is important to separate structure changes from other data changes however. For example, you may want to model a company's organizational chart. Some people will model this as an adjacency list, using the employee ID to link an employee to their supervisor. This is usually a sub-optimal approach. An approach that often works better is to model the org structure separate from employees themselves, and maintain the employee as an attribute of the structure. This way, when an employee leaves the company, the organizational structure itself does not need to be changes, just the association with the employee that left.

2) Is the tree write-heavy or read-heavy - some structures work very well when reading the structure, but incur additional overhead when writing to the structure.

3) What types of information do you need to obtain from the structure - some structures excel at providing certain kinds of information about the structure. Examples include finding a node and all its children, finding a node and all its parents, finding the count of child nodes meeting certain conditions, etc. You need to know what information will be needed from the structure to determine the structure that will best fit your needs.

SELECT where row value contains string MySQL

My suggestion would be

$value = $_POST["myfield"];

$Query = Database::Prepare("SELECT * FROM TABLE WHERE MYFIELD LIKE ?");
$Query->Execute(array("%".$value."%"));

Example of Named Pipes

using System;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            StartServer();
            Task.Delay(1000).Wait();


            //Client
            var client = new NamedPipeClientStream("PipesOfPiece");
            client.Connect();
            StreamReader reader = new StreamReader(client);
            StreamWriter writer = new StreamWriter(client);

            while (true)
            {
                string input = Console.ReadLine();
                if (String.IsNullOrEmpty(input)) break;
                writer.WriteLine(input);
                writer.Flush();
                Console.WriteLine(reader.ReadLine());
            }
        }

        static void StartServer()
        {
            Task.Factory.StartNew(() =>
            {
                var server = new NamedPipeServerStream("PipesOfPiece");
                server.WaitForConnection();
                StreamReader reader = new StreamReader(server);
                StreamWriter writer = new StreamWriter(server);
                while (true)
                {
                    var line = reader.ReadLine();
                    writer.WriteLine(String.Join("", line.Reverse()));
                    writer.Flush();
                }
            });
        }
    }
}

What is the best collation to use for MySQL with PHP?

Be very, very aware of this problem that can occur when using utf8_general_ci.

MySQL will not distinguish between some characters in select statements, if the utf8_general_ci collation is used. This can lead to very nasty bugs - especially for example, where usernames are involved. Depending on the implementation that uses the database tables, this problem could allow malicious users to create a username matching an administrator account.

This problem exposes itself at the very least in early 5.x versions - I'm not sure if this behaviour as changed later.

I'm no DBA, but to avoid this problem, I always go with utf8-bin instead of a case-insensitive one.

The script below describes the problem by example.

-- first, create a sandbox to play in
CREATE DATABASE `sandbox`;
use `sandbox`;

-- next, make sure that your client connection is of the same 
-- character/collate type as the one we're going to test next:
charset utf8 collate utf8_general_ci

-- now, create the table and fill it with values
CREATE TABLE `test` (`key` VARCHAR(16), `value` VARCHAR(16) )
    CHARACTER SET utf8 COLLATE utf8_general_ci;

INSERT INTO `test` VALUES ('Key ONE', 'value'), ('Key TWO', 'valúe');

-- (verify)
SELECT * FROM `test`;

-- now, expose the problem/bug:
SELECT * FROM test WHERE `value` = 'value';

--
-- Note that we get BOTH keys here! MySQLs UTF8 collates that are 
-- case insensitive (ending with _ci) do not distinguish between 
-- both values!
--
-- collate 'utf8_bin' doesn't have this problem, as I'll show next:
--

-- first, reset the client connection charset/collate type
charset utf8 collate utf8_bin

-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin;

-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';

--
-- Note that we get just one key now, as you'd expect.
--
-- This problem appears to be specific to utf8. Next, I'll try to 
-- do the same with the 'latin1' charset:
--

-- first, reset the client connection charset/collate type
charset latin1 collate latin1_general_ci

-- next, convert the values that we've previously inserted
-- in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET latin1 COLLATE latin1_general_ci;

-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';

--
-- Again, only one key is returned (expected). This shows 
-- that the problem with utf8/utf8_generic_ci isn't present 
-- in latin1/latin1_general_ci
--
-- To complete the example, I'll check with the binary collate
-- of latin1 as well:

-- first, reset the client connection charset/collate type
charset latin1 collate latin1_bin

-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET latin1 COLLATE latin1_bin;

-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';

--
-- Again, only one key is returned (expected).
--
-- Finally, I'll re-introduce the problem in the exact same 
-- way (for any sceptics out there):

-- first, reset the client connection charset/collate type
charset utf8 collate utf8_generic_ci

-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

-- now, re-check for the problem/bug
SELECT * FROM test WHERE `value` = 'value';

--
-- Two keys.
--

DROP DATABASE sandbox;

How to use JavaScript to change div backgroundColor

If you are willing to insert non-semantic nodes into your document, you can do this in a CSS-only IE-compatible manner by wrapping your divs in fake A tags.

<style type="text/css">
  .content {
    background: #ccc;
  }

  .fakeLink { /* This is to make the link not look like one */
    cursor: default;
    text-decoration: none;
    color: #000;
  }

  a.fakeLink:hover .content {
    background: #000;
    color: #fff;
  }

</style>
<div id="catestory">

  <a href="#" onclick="return false();" class="fakeLink">
    <div class="content">
      <h2>some title here</h2>
      <p>some content here</p>
    </div>
  </a>

  <a href="#" onclick="return false();" class="fakeLink">
    <div class="content">
      <h2>some title here</h2>
      <p>some content here</p>
    </div>
  </a>

  <a href="#" onclick="return false();" class="fakeLink">
    <div class="content">
      <h2>some title here</h2>
      <p>some content here</p>
    </div>
  </a>

</div>

How can you tell when a layout has been drawn?

An alternative to the usual methods is to hook into the drawing of the view.

OnPreDrawListener is called many times when displaying a view, so there is no specific iteration where your view has valid measured width or height. This requires that you continually verify (view.getMeasuredWidth() <= 0) or set a limit to the number of times you check for a measuredWidth greater than zero.

There is also a chance that the view will never be drawn, which may indicate other problems with your code.

final View view = [ACQUIRE REFERENCE]; // Must be declared final for inner class
ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    @Override
    public boolean onPreDraw() {
        if (view.getMeasuredWidth() > 0) {     
            view.getViewTreeObserver().removeOnPreDrawListener(this);
            int width = view.getMeasuredWidth();
            int height = view.getMeasuredHeight();
            //Do something with width and height here!
        }
        return true; // Continue with the draw pass, as not to stop it
    }
});

OraOLEDB.Oracle provider is not registered on the local machine

  1. Right Click on My Computer
  2. Click on properties
  3. Click on Advanced System Settings
  4. Click on "Environment Variables" button.
  5. In the system Variable section find the "PATH" variable
  6. Edit the "PATH" variable and add Oracle installation path to it (from your local machine) like ;C:\oracle\product\10.2.0\client_1\bin

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

While this question has been answered already (it's a bug that causes bottomLeftRadius and bottomRightRadius to be reversed), the bug has been fixed in android 3.1 (api level 12 - tested on the emulator).

So to make sure your drawables look correct on all platforms, you should put "corrected" versions of the drawables (i.e. where bottom left/right radii are actually correct in the xml) in the res/drawable-v12 folder of your app. This way all devices using an android version >= 12 will use the correct drawable files, while devices using older versions of android will use the "workaround" drawables that are located in the res/drawables folder.

How do you tell if caps lock is on using JavaScript?

In JQuery. This covers the event handling in Firefox and will check for both unexpected uppercase and lowercase characters. This presupposes an <input id="password" type="password" name="whatever"/>element and a separate element with id 'capsLockWarning' that has the warning we want to show (but is hidden otherwise).

$('#password').keypress(function(e) {
    e = e || window.event;

    // An empty field resets the visibility.
    if (this.value === '') {
        $('#capsLockWarning').hide();
        return;
    }

    // We need alphabetic characters to make a match.
    var character = String.fromCharCode(e.keyCode || e.which);
    if (character.toUpperCase() === character.toLowerCase()) {
        return;
    }

    // SHIFT doesn't usually give us a lowercase character. Check for this
    // and for when we get a lowercase character when SHIFT is enabled. 
    if ((e.shiftKey && character.toLowerCase() === character) ||
        (!e.shiftKey && character.toUpperCase() === character)) {
        $('#capsLockWarning').show();
    } else {
        $('#capsLockWarning').hide();
    }
});

How do I change the hover over color for a hover over table in Bootstrap?

.table-hover tbody tr:hover td {
    background: #ffffff;
}

"Conversion to Dalvik format failed with error 1" on external JAR

I personally managed to fix this by manually editing the project.properties file within the Eclipse project.

What it was:

target=android-16
android.library.reference.1=..\\..\\github\\ActionBarSherlock\\library
android.library.reference.2=../../github/android-numberpicker/library

What I changed it to so the problem went away:

target=android-16
android.library.reference.1=../../github/ActionBarSherlock/library
android.library.reference.2=../../github/android-numberpicker/library

This file was not fixed automatically by using the "Fix Project Properties" tool.

How do I get a decimal value when using the division operator in Python?

Other answers suggest how to get a floating-point value. While this wlil be close to what you want, it won't be exact:

>>> 0.4/100.
0.0040000000000000001

If you actually want a decimal value, do this:

>>> import decimal
>>> decimal.Decimal('4') / decimal.Decimal('100')
Decimal("0.04")

That will give you an object that properly knows that 4 / 100 in base 10 is "0.04". Floating-point numbers are actually in base 2, i.e. binary, not decimal.

Git - how delete file from remote repository

Use commands :

git rm /path to file name /

followed by

git commit -m "Your Comment"

git push

your files will get deleted from the repository

Initializing default values in a struct

You can do it by using a constructor, like this:

struct Date
{
int day;
int month;
int year;

Date()
{
    day=0;
    month=0;
    year=0;
}
};

or like this:

struct Date
{
int day;
int month;
int year;

Date():day(0),
       month(0),
       year(0){}
};

In your case bar.c is undefined,and its value depends on the compiler (while a and b were set to true).

How to convert a Drawable to a Bitmap?

So after looking (and using) of the other answers, seems they all handling ColorDrawable and PaintDrawable badly. (Especially on lollipop) seemed that Shaders were tweaked so solid blocks of colors were not handled correctly.

I am using the following code now:

public static Bitmap drawableToBitmap(Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    }

    // We ask for the bounds if they have been set as they would be most
    // correct, then we check we are  > 0
    final int width = !drawable.getBounds().isEmpty() ?
            drawable.getBounds().width() : drawable.getIntrinsicWidth();

    final int height = !drawable.getBounds().isEmpty() ?
            drawable.getBounds().height() : drawable.getIntrinsicHeight();

    // Now we check we are > 0
    final Bitmap bitmap = Bitmap.createBitmap(width <= 0 ? 1 : width, height <= 0 ? 1 : height,
            Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}

Unlike the others, if you call setBounds on the Drawable before asking to turn it into a bitmap, it will draw the bitmap at the correct size!

Return JSON for ResponseEntity<String>

An alternative solution is to use a wrapper for the String, for instances this:

public class StringResponse {
    private String response;
    public StringResponse(String response) {
        this.response = response;
    }
    public String getResponse() {
        return response;
    }
}

Then return this in your controller's methods:

ResponseEntity<StringResponse>

how to set font size based on container size?

I used Fittext on some of my projects and it looks like a good solution to a problem like this.

FitText makes font-sizes flexible. Use this plugin on your fluid or responsive layout to achieve scalable headlines that fill the width of a parent element.

Boxplot in R showing the mean

Based on the answers by @James and @Jyotirmoy Bhattacharya I came up with this solution:

zx <- replicate (5, rnorm(50))
zx_means <- (colMeans(zx, na.rm = TRUE))
boxplot(zx, horizontal = FALSE, outline = FALSE)
points(zx_means, pch = 22, col = "darkgrey", lwd = 7)

(See this post for more details)

If you would like to add points to horizontal box plots, please see this post.

What is thread safe or non-thread safe in PHP?

Needed background on concurrency approaches:

Different web servers implement different techniques for handling incoming HTTP requests in parallel. A pretty popular technique is using threads -- that is, the web server will create/dedicate a single thread for each incoming request. The Apache HTTP web server supports multiple models for handling requests, one of which (called the worker MPM) uses threads. But it supports another concurrency model called the prefork MPM which uses processes -- that is, the web server will create/dedicate a single process for each request.

There are also other completely different concurrency models (using Asynchronous sockets and I/O), as well as ones that mix two or even three models together. For the purpose of answering this question, we are only concerned with the two models above, and taking Apache HTTP server as an example.

Needed background on how PHP "integrates" with web servers:

PHP itself does not respond to the actual HTTP requests -- this is the job of the web server. So we configure the web server to forward requests to PHP for processing, then receive the result and send it back to the user. There are multiple ways to chain the web server with PHP. For Apache HTTP Server, the most popular is "mod_php". This module is actually PHP itself, but compiled as a module for the web server, and so it gets loaded right inside it.

There are other methods for chaining PHP with Apache and other web servers, but mod_php is the most popular one and will also serve for answering your question.

You may not have needed to understand these details before, because hosting companies and GNU/Linux distros come with everything prepared for us.

Now, onto your question!

Since with mod_php, PHP gets loaded right into Apache, if Apache is going to handle concurrency using its Worker MPM (that is, using Threads) then PHP must be able to operate within this same multi-threaded environment -- meaning, PHP has to be thread-safe to be able to play ball correctly with Apache!

At this point, you should be thinking "OK, so if I'm using a multi-threaded web server and I'm going to embed PHP right into it, then I must use the thread-safe version of PHP". And this would be correct thinking. However, as it happens, PHP's thread-safety is highly disputed. It's a use-if-you-really-really-know-what-you-are-doing ground.

Final notes

In case you are wondering, my personal advice would be to not use PHP in a multi-threaded environment if you have the choice!

Speaking only of Unix-based environments, I'd say that fortunately, you only have to think of this if you are going to use PHP with Apache web server, in which case you are advised to go with the prefork MPM of Apache (which doesn't use threads, and therefore, PHP thread-safety doesn't matter) and all GNU/Linux distributions that I know of will take that decision for you when you are installing Apache + PHP through their package system, without even prompting you for a choice. If you are going to use other webservers such as nginx or lighttpd, you won't have the option to embed PHP into them anyway. You will be looking at using FastCGI or something equal which works in a different model where PHP is totally outside of the web server with multiple PHP processes used for answering requests through e.g. FastCGI. For such cases, thread-safety also doesn't matter. To see which version your website is using put a file containing <?php phpinfo(); ?> on your site and look for the Server API entry. This could say something like CGI/FastCGI or Apache 2.0 Handler.

If you also look at the command-line version of PHP -- thread safety does not matter.

Finally, if thread-safety doesn't matter so which version should you use -- the thread-safe or the non-thread-safe? Frankly, I don't have a scientific answer! But I'd guess that the non-thread-safe version is faster and/or less buggy, or otherwise they would have just offered the thread-safe version and not bothered to give us the choice!

How can I include null values in a MIN or MAX?

Use IsNull

SELECT recordid, MIN(startdate), MAX(IsNull(enddate, Getdate()))
FROM tmp 
GROUP BY recordid

I've modified MIN in the second instruction to MAX

Python sum() function with list parameter

Have you used the variable sum anywhere else? That would explain it.

>>> sum = 1
>>> numbers = [1, 2, 3]
>>> numsum = (sum(numbers))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

The name sum doesn't point to the function anymore now, it points to an integer.

Solution: Don't call your variable sum, call it total or something similar.

Mongoose: Find, modify, save

I wanted to add something very important. I use JohnnyHK method a lot but I noticed sometimes the changes didn't persist to the database. When I used .markModified it worked.

User.findOne({username: oldUsername}, function (err, user) {
   user.username = newUser.username;
   user.password = newUser.password;
   user.rights = newUser.rights;

   user.markModified(username)
   user.markModified(password)
   user.markModified(rights)
    user.save(function (err) {
    if(err) {
        console.error('ERROR!');
    }
});
});

tell mongoose about the change with doc.markModified('pathToYourDate') before saving.

How to link an image and target a new window

<a href="http://www.google.com" target="_blank">
  <img width="220" height="250" border="0" align="center"  src=""/>
</a>

How to pass credentials to httpwebrequest for accessing SharePoint Library

If you need to run request as the current user from desktop application use CredentialCache.DefaultCredentials (see on MSDN).

Your code looks fine if you need to run a request from server side code or under a different user.

Please note that you should be careful when storing passwords - consider using the SecureString version of the constructor.

Open Bootstrap Modal from code-behind

This method of opening the Modal would not display the Modal for me. I found this as a work arround.

I removed:

 ScriptManager.RegisterStartupScript(this,this.GetType(),"Pop", "openModal();", true);

Than I added an asp:label named lblJavaScript and in code behind call:

lblJavaScript.Text = "<script language=\"JavaScript\">openModal()</script>";

Now the Modal will display.

'uint32_t' identifier not found error

You can #include <cstdint>. It's part of C++-standard since 2011.

Image overlay on responsive sized images bootstrap

If i understand your question you want to have the overlay just over the image and not cover everything?

I'd set the parent DIV (i renamed in content in the jsfiddle) position to relative, as the overlay should be positioned relative to this div not the window.

.content
{
  position: relative;
}

I did some pocking around and updated your fiddle to just have the overlay sized to the img which (I think) is what you want, let me know anyway :) http://jsfiddle.net/b9Vyw/

Angular2 QuickStart npm start is not working correctly

Uninstall all existing node packages. Update node and npm.As it is given in documentation as at least node v5.x.x and npm 3.x.x else it will cause errors .

Do npm clean. Then do npm install, npm start.

This solved the issue for me.

Update value of a nested dictionary of varying depth

Update to @Alex Martelli's answer to fix a bug in his code to make the solution more robust:

def update_dict(d, u):
    for k, v in u.items():
        if isinstance(v, collections.Mapping):
            default = v.copy()
            default.clear()
            r = update_dict(d.get(k, default), v)
            d[k] = r
        else:
            d[k] = v
    return d

The key is that we often want to create the same type at recursion, so here we use v.copy().clear() but not {}. And this is especially useful if the dict here is of type collections.defaultdict which can have different kinds of default_factorys.

Also notice that the u.iteritems() has been changed to u.items() in Python3.

How is Pythons glob.glob ordered?

Please try this code:

sorted(glob.glob( os.path.join(path, '*.png') ),key=lambda x:float(re.findall("([0-9]+?)\.png",x)[0]))

Restoring MySQL database from physical files

If you are restoring the folder don't forget to chown the files to mysql:mysql

chown -R mysql:mysql /var/lib/mysql-data

otherwise you will get errors when trying to drop a database or add new column etc..

and restart MySQL

service mysql restart

Bootstrap: 'TypeError undefined is not a function'/'has no method 'tab'' when using bootstrap-tabs

Probably is the use of the "on" event that Bootstrap use a lot and was inserted at jQuery 1.7 http://api.jquery.com/on/

jQuery on window resize

You can bind resize using .resize() and run your code when the browser is resized. You need to also add an else condition to your if statement so that your css values toggle the old and the new, rather than just setting the new.

How to automatically generate a stacktrace when my program crashes

Look at:

man 3 backtrace

And:

#include <exeinfo.h>
int backtrace(void **buffer, int size);

These are GNU extensions.

Is there a limit to the length of a GET request?

This article sums it up pretty well

Summary: It's implementation dependent, as there is no specified limit in the RFC. It'd be safe to use up to 2000 characters (IE's limit.) If you are anywhere near this length, you should make sure you really need URIs that long, maybe an alternative design could get around that.

URIs should be readable, even when used to send data.

Convert an int to ASCII character

Straightforward way:

char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char aChar = digits[i];

Safer way:

char aChar = '0' + i;

Generic way:

itoa(i, ...)

Handy way:

sprintf(myString, "%d", i)

C++ way: (taken from Dave18 answer)

std::ostringstream oss;
oss << 6;

Boss way:

Joe, write me an int to char converter

Studboss way:

char aChar = '6';

Joe's way:

char aChar = '6'; //int i = 6;

Nasa's way:

//Waiting for reply from satellite...

Alien's way: '9'

//Greetings.

God's way:

Bruh I built this

Peter Pan's way:

char aChar;

switch (i)
{
  case 0:
    aChar = '0';
    break;
  case 1:
    aChar = '1';
    break;
  case 2:
    aChar = '2';
    break;
  case 3:
    aChar = '3';
    break;
  case 4:
    aChar = '4';
    break;
  case 5:
    aChar = '5';
    break;
  case 6:
    aChar = '6';
    break;
  case 7:
    aChar = '7';
    break;
  case 8:
    aChar = '8';
    break;
  case 9:
    aChar = '9';
    break;
  default:
    aChar = '?';
    break;
}

Santa Claus's way:

//Wait till Christmas!
sleep(457347347);

Gravity's way:

//What

'6' (Jersey) Mikes'™ way:

//

SO way:

Guys, how do I avoid reading beginner's guide to C++?

My way:

or the highway.

Comment: I've added Handy way and C++ way (to have a complete collection) and I'm saving this as a wiki.

Edit: satisfied?

A field initializer cannot reference the nonstatic field, method, or property

This line:

private dynamic defaultReminder = 
                          reminder.TimeSpanText[TimeSpan.FromMinutes(15)];

You cannot use an instance variable to initialize another instance variable. Why? Because the compiler can rearrange these - there is no guarantee that reminder will be initialized before defaultReminder, so the above line might throw a NullReferenceException.

Instead, just use:

private dynamic defaultReminder = TimeSpan.FromMinutes(15);

Alternatively, set up the value in the constructor:

private dynamic defaultReminder;

public Reminders()
{
    defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)]; 
}

There are more details about this compiler error on MSDN - Compiler Error CS0236.

long long in C/C++

It depends in what mode you are compiling. long long is not part of the C++ standard but only (usually) supported as extension. This affects the type of literals. Decimal integer literals without any suffix are always of type int if int is big enough to represent the number, long otherwise. If the number is even too big for long the result is implementation-defined (probably just a number of type long int that has been truncated for backward compatibility). In this case you have to explicitly use the LL suffix to enable the long long extension (on most compilers).

The next C++ version will officially support long long in a way that you won't need any suffix unless you explicitly want the force the literal's type to be at least long long. If the number cannot be represented in long the compiler will automatically try to use long long even without LL suffix. I believe this is the behaviour of C99 as well.

Safest way to convert float to integer in python?

Combining two of the previous results, we have:

int(round(some_float))

This converts a float to an integer fairly dependably.

Is there any JSON Web Token (JWT) example in C#?

It would be better to use standard and famous libraries instead of writing the code from scratch.

  1. JWT for encoding and decoding JWT tokens
  2. Bouncy Castle supports encryption and decryption, especially RS256 get it here

Using these libraries you can generate a JWT token and sign it using RS256 as below.

    public string GenerateJWTToken(string rsaPrivateKey)
    {
        var rsaParams = GetRsaParameters(rsaPrivateKey);
        var encoder = GetRS256JWTEncoder(rsaParams);

        // create the payload according to the Google's doc
        var payload = new Dictionary<string, object>
        {
            { "iss", ""},
            { "sub", "" },
            // and other key-values according to the doc
        };

        // add headers. 'alg' and 'typ' key-values are added automatically.
        var header = new Dictionary<string, object>
        {
            { "kid", "{your_private_key_id}" },
        };

        var token = encoder.Encode(header,payload, new byte[0]);

        return token;
    }

    private static IJwtEncoder GetRS256JWTEncoder(RSAParameters rsaParams)
    {
        var csp = new RSACryptoServiceProvider();
        csp.ImportParameters(rsaParams);

        var algorithm = new RS256Algorithm(csp, csp);
        var serializer = new JsonNetSerializer();
        var urlEncoder = new JwtBase64UrlEncoder();
        var encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

        return encoder;
    }

    private static RSAParameters GetRsaParameters(string rsaPrivateKey)
    {
        var byteArray = Encoding.ASCII.GetBytes(rsaPrivateKey);
        using (var ms = new MemoryStream(byteArray))
        {
            using (var sr = new StreamReader(ms))
            {
                // use Bouncy Castle to convert the private key to RSA parameters
                var pemReader = new PemReader(sr);
                var keyPair = pemReader.ReadObject() as AsymmetricCipherKeyPair;
                return DotNetUtilities.ToRSAParameters(keyPair.Private as RsaPrivateCrtKeyParameters);
            }
        }
    }

ps: the RSA private key should have the following format:

-----BEGIN RSA PRIVATE KEY----- {base64 formatted value} -----END RSA PRIVATE KEY-----

Django set field value after a form is initialized

If you want to do it within the form's __init__ method for some reason, you can manipulate the initial dict:

class MyForm(forms.Form):
    my_field = forms.CharField(max_length=255)

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.initial['my_field'] = 'Initial value'

Nexus 5 USB driver

Currently experienced this problem with my Nexus 5, when attempting to sideload latest 4.4.1 OTA update via stock recovery.

Solution:

  1. Open Android SDK Manager (in console get to sdk directory then run tools\android)
  2. Download/install latest USB drivers (under Extras).
  3. In Windows Device Manager (devmgmt.msc), right click the Nexus 5 device and select Update Driver Software.
  4. Browse My Computer for driver software > Android SDK Dir > Extras > usb_driver

Function pointer as parameter

The correct way to do this is:

typedef void (*callback_function)(void); // type for conciseness

callback_function disconnectFunc; // variable to store function pointer type

void D::setDisconnectFunc(callback_function pFunc)
{
    disconnectFunc = pFunc; // store
}

void D::disconnected()
{
    disconnectFunc(); // call
    connected = false;
}

Using TortoiseSVN how do I merge changes from the trunk to a branch and vice versa?

You should use "merge a range of revision".

To merge changes from the trunk to a branch, inside the branch working copy choose "merge range of revisions" and enter the trunk URL and the start and end revisions to merge.

The same in the opposite way to merge a branch in the trunk.

About the --reintegrate flag, check the manual here: http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-merge.html#tsvn-dug-merge-reintegrate

Error: allowDefinition='MachineToApplication' beyond application level

In Visual Studio 2013 I struggled with this for a while and it is pretty much easy to solve just follow what the exceptions says "virtual directory not being configured as an application in IIS"

In my case I had WebService planted inside IIS website so

  1. I opened the website in IIS manager
  2. right clicked the WCF folder
  3. clicked Convert to Application
  4. and then submitted with Ok

WCF is back and running.

oracle.jdbc.driver.OracleDriver ClassNotFoundException

You can add a JAR which having above specified class exist e.g.ojdbc jar which supported by installed java version, also make sure that you have added it into classpath.

I don't understand -Wl,-rpath -Wl,

The -Wl,xxx option for gcc passes a comma-separated list of tokens as a space-separated list of arguments to the linker. So

gcc -Wl,aaa,bbb,ccc

eventually becomes a linker call

ld aaa bbb ccc

In your case, you want to say "ld -rpath .", so you pass this to gcc as -Wl,-rpath,. Alternatively, you can specify repeat instances of -Wl:

gcc -Wl,aaa -Wl,bbb -Wl,ccc

Note that there is no comma between aaa and the second -Wl.

Or, in your case, -Wl,-rpath -Wl,..

Func delegate with no return type

Occasionally you will want to write a delegate for event handling, in which case you can take advantage of System.EvenHandler<T> which implicitly accepts an argument of type object in addition to the second parameter that should derive from EventArgs. EventHandlers will return void

I personally found this useful during testing for creating a one-off callback in a function body.

Find the greatest number in a list of numbers

What about max()

highest = max(1, 2, 3)  # or max([1, 2, 3]) for lists

How do a send an HTTPS request through a proxy in Java?

Try the Apache Commons HttpClient library instead of trying to roll your own: http://hc.apache.org/httpclient-3.x/index.html

From their sample code:

  HttpClient httpclient = new HttpClient();
  httpclient.getHostConfiguration().setProxy("myproxyhost", 8080);

  /* Optional if authentication is required.
  httpclient.getState().setProxyCredentials("my-proxy-realm", " myproxyhost",
   new UsernamePasswordCredentials("my-proxy-username", "my-proxy-password"));
  */

  PostMethod post = new PostMethod("https://someurl");
  NameValuePair[] data = {
     new NameValuePair("user", "joe"),
     new NameValuePair("password", "bloggs")
  };
  post.setRequestBody(data);
  // execute method and handle any error responses.
  // ...
  InputStream in = post.getResponseBodyAsStream();
  // handle response.


  /* Example for a GET reqeust
  GetMethod httpget = new GetMethod("https://someurl");
  try { 
    httpclient.executeMethod(httpget);
    System.out.println(httpget.getStatusLine());
  } finally {
    httpget.releaseConnection();
  }
  */

How to include a sub-view in Blade templates?

When you use laravel modules, you may add the name's module:

@include('cimple::shared.posts_list')

What exactly is the function of Application.CutCopyMode property in Excel

By referring this(http://www.excelforum.com/excel-programming-vba-macros/867665-application-cutcopymode-false.html) link the answer is as below:

Application.CutCopyMode=False is seen in macro recorder-generated code when you do a copy/cut cells and paste . The macro recorder does the copy/cut and paste in separate statements and uses the clipboard as an intermediate buffer. I think Application.CutCopyMode = False clears the clipboard. Without that line you will get the warning 'There is a large amount of information on the Clipboard....' when you close the workbook with a large amount of data on the clipboard.

With optimised VBA code you can usually do the copy/cut and paste operations in one statement, so the clipboard isn't used and Application.CutCopyMode = False isn't needed and you won't get the warning.

Text overwrite in visual studio 2010

press your keyboard Insert Key

Permission is only granted to system app

Have same error from time to time (when I set install location to "prefer external" in manifest). Just clean and rebuild project. Works for me.

How do you stash an untracked file?

You can simply do it with below command

git stash save --include-untracked

or

git stash save -u

For more about git stash Visit this post (Click Here)

Spark specify multiple column conditions for dataframe join

Spark SQL supports join on tuple of columns when in parentheses, like

... WHERE (list_of_columns1) = (list_of_columns2)

which is a way shorter than specifying equal expressions (=) for each pair of columns combined by a set of "AND"s.

For example:

SELECT a,b,c
FROM    tab1 t1
WHERE 
   NOT EXISTS
   (    SELECT 1
        FROM    t1_except_t2_df e
        WHERE (t1.a, t1.b, t1.c) = (e.a, e.b, e.c)
   )

instead of

SELECT a,b,c
FROM    tab1 t1
WHERE 
   NOT EXISTS
   (    SELECT 1
        FROM    t1_except_t2_df e
        WHERE t1.a=e.a AND t1.b=e.b AND t1.c=e.c
   )

which is less readable too especially when list of columns is big and you want to deal with NULLs easily.

Oracle JDBC ojdbc6 Jar as a Maven Dependency

Go to the C drive->user->PcName->find .m2 and Paste the downloaded ojdbc jar file there, Server will automatically pick this.

A quick and easy way to join array elements with a separator (the opposite of split) in Java

A fast and simple solution without any 3rd party includes.

public static String strJoin(String[] aArr, String sSep) {
    StringBuilder sbStr = new StringBuilder();
    for (int i = 0, il = aArr.length; i < il; i++) {
        if (i > 0)
            sbStr.append(sSep);
        sbStr.append(aArr[i]);
    }
    return sbStr.toString();
}

Warning: comparison with string literals results in unspecified behaviour

You want to use strcmp() == 0 to compare strings instead of a simple ==, which will just compare if the pointers are the same (which they won't be in this case).

args[i] is a pointer to a string (a pointer to an array of chars null terminated), as is "&" or "<".

The expression argc[i] == "&" checks if the two pointers are the same (point to the same memory location).

The expression strcmp( argc[i], "&") == 0 will check if the contents of the two strings are the same.

ZIP Code (US Postal Code) validation

To allow a user to enter a Canadian Postal code with lower case letters as well, the regex would need to look like this:

/^([a-zA-Z][0-9][a-zA-Z])\s*([0-9][a-zA-Z][0-9])$/

callback to handle completion of pipe

Based nodejs document, http://nodejs.org/api/stream.html#stream_event_finish, it should handle writableStream's finish event.

var writable = getWriteable();
var readable = getReadable();
readable.pipe(writable);
writable.on('finish', function(){ ... });

What is the difference between AF_INET and PF_INET in socket programming?

Checking the header file solve's the problem. One can check for there system compiler.

For my system , AF_INET == PF_INET

AF == Address Family And PF == Protocol Family

Protocol families, same as address families.

enter image description here

Get OS-level system information

On Windows, you can run the systeminfo command and retrieves its output for instance with the following code:

private static class WindowsSystemInformation
{
    static String get() throws IOException
    {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec("systeminfo");
        BufferedReader systemInformationReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        StringBuilder stringBuilder = new StringBuilder();
        String line;

        while ((line = systemInformationReader.readLine()) != null)
        {
            stringBuilder.append(line);
            stringBuilder.append(System.lineSeparator());
        }

        return stringBuilder.toString().trim();
    }
}

Recursively looping through an object to build a property list

UPDATE: JUST USE JSON.stringify to print objects on screen!

All you need is this line:

document.body.innerHTML = '<pre>' + JSON.stringify(ObjectWithSubObjects, null, "\t") + '</pre>';

This is my older version of printing objects recursively on screen:

 var previousStack = '';
    var output = '';
    function objToString(obj, stack) {
        for (var property in obj) {
            var tab = '&nbsp;&nbsp;&nbsp;&nbsp;';
            if (obj.hasOwnProperty(property)) {
                if (typeof obj[property] === 'object' && typeof stack === 'undefined') {
                    config = objToString(obj[property], property);
                } else {
                    if (typeof stack !== 'undefined' && stack !== null && stack === previousStack) {
                        output = output.substring(0, output.length - 1);  // remove last }
                        output += tab + '<span>' + property + ': ' + obj[property] + '</span><br />'; // insert property
                        output += '}';   // add last } again
                    } else {
                        if (typeof stack !== 'undefined') {
                            output += stack + ': {  <br />' + tab;
                        }
                        output += '<span>' + property + ': ' + obj[property] + '</span><br />';
                        if (typeof stack !== 'undefined') {
                            output += '}';
                        }
                    }
                    previousStack = stack;
                }
            }
        }
        return output;
    }

Usage:

document.body.innerHTML = objToString(ObjectWithSubObjects);

Example output:

cache: false
position: fixed
effect: { 
    fade: false
    fall: true
}

Obviously this can be improved by adding comma's when needed and quotes from string values. But this was good enough for my case.

How to make return key on iPhone make keyboard disappear?

Your UITextFields should have a delegate object (UITextFieldDelegate). Use the following code in your delegate to make the keyboard disappear:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
}

Should work so far...

Difference between getAttribute() and getParameter()

Basic difference between getAttribute() and getParameter() is the return type.

java.lang.Object getAttribute(java.lang.String name)
java.lang.String getParameter(java.lang.String name)

Convert serial.read() into a useable string using Arduino?

If you want to read messages from the serial port and you need to deal with every single message separately I suggest separating messages into parts using a separator like this:

String getMessage()
{
  String msg=""; //the message starts empty
  byte ch; // the character that you use to construct the Message 
  byte d='#';// the separating symbol 

  if(Serial.available())// checks if there is a new message;
  {
      while(Serial.available() && Serial.peek()!=d)// while the message did not finish
      {
          ch=Serial.read();// get the character
          msg+=(char)ch;//add the character to the message
          delay(1);//wait for the next character
      }
     ch=Serial.read();// pop the '#' from the buffer
     if(ch==d) // id finished
         return msg;
     else
         return "NA";
  }
  else
      return "NA"; // return "NA" if no message;
}

This way you will get a single message every time you use the function.

ConcurrentHashMap vs Synchronized HashMap

ConcurrentHashMap uses finer-grained locking mechanism known as lock stripping to allow greater degree of shared access. Due to this it provides better concurrency and scalability.

Also iterators returned for ConcurrentHashMap are weakly consistent instead of fail fast technique used by Synchronized HashMap.

How to display and hide a div with CSS?

To hide an element, use:

display: none;
visibility: hidden;

To show an element, use:

display: block;
visibility: visible;

The difference is:

Visibility handles the visibility of the tag, the display handles space it occupies on the page.

If you set the visibility and do not change the display, even if the tags are not seen, it still occupies space.

Press enter in textbox to and execute button command

If you're just gonna click the button when Enter was pressed how about this?

private void textbox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            buttonSearch.PerformClick();
        }

Using RegEx in SQL Server

A similar approach to @mwigdahl's answer, you can also implement a .NET CLR in C#, with code such as;

using System.Data.SqlTypes;
using RX = System.Text.RegularExpressions;

public partial class UserDefinedFunctions
{
 [Microsoft.SqlServer.Server.SqlFunction]
 public static SqlString Regex(string input, string regex)
 {
  var match = RX.Regex.Match(input, regex).Groups[1].Value;
  return new SqlString (match);
 }
}

Installation instructions can be found here

Pass object to javascript function

function myFunction(arg) {
    alert(arg.var1 + ' ' + arg.var2 + ' ' + arg.var3);
}

myFunction ({ var1: "Option 1", var2: "Option 2", var3: "Option 3" });

Gets byte array from a ByteBuffer in java

This is a simple way to get a byte[], but part of the point of using a ByteBuffer is avoiding having to create a byte[]. Perhaps you can get whatever you wanted to get from the byte[] directly from the ByteBuffer.

iOS9 Untrusted Enterprise Developer with no option to trust

Do it like this:

Enter image description here

Go to Settings -> General -> Profiles - tap on your Profile - tap on the Trust button.

but iOS10 has a little change,

Users should go to Settings - General - Device Management - tap on your Profile - tap on Trust button.

enter image description here

Reference: iOS10AdaptationTips

Pandas get the most frequent values of a column

Use:

df['name'].mode()

or

df['name'].value_counts().idxmax()

How to initialize a JavaScript Date to a particular time zone

Maybe this will help you

_x000D_
_x000D_
/**_x000D_
 * Shift any Date timezone._x000D_
 * @param {Date} date - Date to update._x000D_
 * @param {string} timezone - Timezone as `-03:00`._x000D_
 */_x000D_
function timezoneShifter(date, timezone) {_x000D_
  let isBehindGTM = false;_x000D_
  if (timezone.startsWith("-")) {_x000D_
    timezone = timezone.substr(1);_x000D_
    isBehindGTM = true;_x000D_
  }_x000D_
_x000D_
  const [hDiff, mDiff] = timezone.split(":").map((t) => parseInt(t));_x000D_
  const diff = hDiff * 60 + mDiff * (isBehindGTM ? 1 : -1);_x000D_
  const currentDiff = new Date().getTimezoneOffset();_x000D_
_x000D_
  return new Date(date.valueOf() + (currentDiff - diff) * 60 * 1000);_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
const _now = new Date()_x000D_
console.log(_x000D_
  [_x000D_
    "Here: " + _now.toLocaleString(),_x000D_
    "Greenwich: " + timezoneShifter(_now, "00:00").toLocaleString(),_x000D_
    "New York: " + timezoneShifter(_now, "-04:00").toLocaleString(),_x000D_
    "Tokyo: " + timezoneShifter(_now, "+09:00").toLocaleString(),_x000D_
    "Buenos Aires: " + timezoneShifter(_now, "-03:00").toLocaleString(),_x000D_
  ].join('\n')_x000D_
);
_x000D_
_x000D_
_x000D_

Could not load file or assembly 'System.Web.Mvc'

We want to add it because we are making a class library that uses it.

For me it is here...

C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies

Granting Rights on Stored Procedure to another user of Oracle

SQL> grant create any procedure to testdb;

This is a command when we want to give create privilege to "testdb" user.

Subtract 1 day with PHP

How about this: convert it to a unix timestamp first, subtract 60*60*24 (exactly one day in seconds), and then grab the date from that.

$newDate = strtotime($date_raw) - 60*60*24;
echo date('Y-m-d',$newDate);

Note: as apokryfos has pointed out, this would technically be thrown off by daylight savings time changes where there would be a day with either 25 or 23 hours

frequent issues arising in android view, Error parsing XML: unbound prefix

unbound prefix error for ViewPager Indicator:

Along with the following header tags in your parentLayout:

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"

Also add:

xmlns:app="http://schemas.android.com/apk/res-auto"

This did the trick for me.

Is there a way to get colored text in GitHubflavored Markdown?

You can not color plain text in a GitHub README.md file. You can however add color to code samples in your GitHub README.md file with the tags below.

To do this, just add tags, such as these samples, to your README.md file:

```json
   // Code for coloring
```
```html
   // Code for coloring
```
```js
   // Code for coloring
```
```css
   // Code for coloring
```
// etc.

**Colored Code Example, JavaScript:** place this code below, in your GitHub README.md file and see how it colors the code for you.
  import { Component } from '@angular/core';
  import { MovieService } from './services/movie.service';

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [ MovieService ]
  })
  export class AppComponent {
    title = 'app works!';
  }

No "pre" or "code" tags are needed.

This is now covered in the GitHub Markdown documentation (about half way down the page, there's an example using Ruby). GitHub uses Linguist to identify and highlight syntax - you can find a full list of supported languages (as well as their markdown keywords) over in the Linguist's YAML file.

DEMO

Rails: How do I create a default value for attributes in Rails activerecord's model?

For column types Rails supports out of the box - like the string in this question - the best approach is to set the column default in the database itself as Daniel Kristensen indicates. Rails will introspect on the DB and initialize the object accordingly. Plus, that makes your DB safe from somebody adding a row outside of your Rails app and forgetting to initialize that column.

For column types Rails doesn't support out of the box - e.g. ENUM columns - Rails won't be able to introspect the column default. For these cases you do not want to use after_initialize (it is called every time an object is loaded from the DB as well as every time an object is created using .new), before_create (because it occurs after validation), or before_save (because it occurs upon update too, which is usually not what you want).

Rather, you want to set the attribute in a before_validation on: create, like so:

before_validation :set_status_because_rails_cannot, on: :create

def set_status_because_rails_cannot
  self.status ||= 'P'
end

Need to remove href values when printing in Chrome

_x000D_
_x000D_
@media print {_x000D_
   a[href]:after {_x000D_
      display: none;_x000D_
      visibility: hidden;_x000D_
   }_x000D_
}
_x000D_
_x000D_
_x000D_

Work's perfect.

Setting width and height

The below worked for me - but dont forget to put this in the "options" param.

var myChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
    maintainAspectRatio: false,
    responsive:true,
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero: true
            }
        }]
    }
}
});

Shorthand if/else statement Javascript

var x = y !== undefined ? y : 1;

Note that var x = y || 1; would assign 1 for any case where y is falsy (e.g. false, 0, ""), which may be why it "didn't work" for you. Also, if y is a global variable, if it's truly not defined you may run into an error unless you access it as window.y.


As vol7ron suggests in the comments, you can also use typeof to avoid the need to refer to global vars as window.<name>:

var x = typeof y != "undefined" ? y : 1;

What's the best/easiest GUI Library for Ruby?

There's a discussion here that might be useful.

From my own (limited) exposure, I'd say that shoes was the most fun and probably the "easiest" to get into. Be warned, however, that figuring out what was wrong when something breaks can be tricky (at least, it was for me).

For a real-world application that I was planning to deploy to real-world users, I think I'd go with wxruby.

Set Windows process (or user) memory limit

Depending on your applications, it might be easier to limit the memory the language interpreter uses. For example with Java you can set the amount of RAM the JVM will be allocated.

Otherwise it is possible to set it once for each process with the windows API

SetProcessWorkingSetSize Function

How can I check if a checkbox is checked?

Use this below simple code: https://jsfiddle.net/Divyesh_Patel/v7a4h3kr/7/

_x000D_
_x000D_
<input type="checkbox" id="check">_x000D_
<a href="#" onclick="check()">click</a>_x000D_
<button onclick="check()">_x000D_
button_x000D_
</button>_x000D_
<script>_x000D_
 function check() {_x000D_
      if (document.getElementById('check').checked) {_x000D_
            alert("checked");_x000D_
        } else {_x000D_
            alert("You didn't check it! Let me check it for you.");_x000D_
        }_x000D_
       _x000D_
    }_x000D_
_x000D_
</script>
_x000D_
_x000D_
_x000D_

Print multiple arguments in Python

Use f-string:

print(f'Total score for {name} is {score}')

Or

Use .format:

print("Total score for {} is {}".format(name, score))

Anaconda export Environment file

I can't find anything in the conda specs which allow you to export an environment file without the prefix: ... line. However, as Alex pointed out in the comments, conda doesn't seem to care about the prefix line when creating an environment from file.

With that in mind, if you want the other user to have no knowledge of your default install path, you can remove the prefix line with grep before writing to environment.yml.

conda env export | grep -v "^prefix: " > environment.yml

Either way, the other user then runs:

conda env create -f environment.yml

and the environment will get installed in their default conda environment path.

If you want to specify a different install path than the default for your system (not related to 'prefix' in the environment.yml), just use the -p flag followed by the required path.

conda env create -f environment.yml -p /home/user/anaconda3/envs/env_name

Note that Conda recommends creating the environment.yml by hand, which is especially important if you are wanting to share your environment across platforms (Windows/Linux/Mac). In this case, you can just leave out the prefix line.

denied: requested access to the resource is denied : docker

I also encountered this error message, using the Gitlab registry. The difference was that I was attempting to change the name of the image from previous builds. The problem there, is that the registry for the image being pushed did not exist, because the new name of the image didn't match any of the projects in my group.

TLDR: In Gitlab, the image name has to match the project name.

Firebase onMessageReceived not called when app in background

Just override the OnCreate method of FirebaseMessagingService. It is called when your app is in background:

public override void OnCreate()
{
    // your code
    base.OnCreate();
}

Get the system date and split day, month and year

You can do like follow:

 String date = DateTime.Now.Date.ToString();
    String Month = DateTime.Now.Month.ToString();
    String Year = DateTime.Now.Year.ToString();

On the place of datetime you can use your column..

Return Boolean Value on SQL Select Statement

I do it like this:

SELECT 1 FROM [dbo].[User] WHERE UserID = 20070022

Seeing as a boolean can never be null (at least in .NET), it should default to false or you can set it to that yourself if it's defaulting true. However 1 = true, so null = false, and no extra syntax.

Note: I use Dapper as my micro orm, I'd imagine ADO should work the same.

How to get a variable from a file to another file in Node.js

You need module.exports:

Exports

An object which is shared between all instances of the current module and made accessible through require(). exports is the same as the module.exports object. See src/node.js for more information. exports isn't actually a global but rather local to each module.

For example, if you would like to expose variableName with value "variableValue" on sourceFile.js then you can either set the entire exports as such:

module.exports = { variableName: "variableValue" };

Or you can set the individual value with:

module.exports.variableName = "variableValue";

To consume that value in another file, you need to require(...) it first (with relative pathing):

const sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);

Alternatively, you can deconstruct it.

const { variableName } = require('./sourceFile');
//            current directory --^
// ../     would be one directory down
// ../../  is two directories down

If all you want out of the file is variableName then

./sourceFile.js:

const variableName = 'variableValue'
module.exports = variableName

./consumer.js:

const variableName = require('./sourceFile')

Edit (2020):

Since Node.js version 8.9.0, you can also use ECMAScript Modules with varying levels of support. The documentation.

  • For Node v13.9.0 and beyond, experimental modules are enabled by default
  • For versions of Node less than version 13.9.0, use --experimental-modules

Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:

  • Files ending in .mjs.
  • Files ending in .js when the nearest parent package.json file contains a top-level field "type" with a value of "module".
  • Strings passed in as an argument to --eval or --print, or piped to node via STDIN, with the flag --input-type=module.

Once you have it setup, you can use import and export.

Using the example above, there are two approaches you can take

./sourceFile.js:

// This is a named export of variableName
export const variableName = 'variableValue'
// Alternatively, you could have exported it as a default. 
// For sake of explanation, I'm wrapping the variable in an object
// but it is not necessary. 
// You can actually omit declaring what variableName is here. 
// { variableName } is equivalent to { variableName: variableName } in this case. 
export default { variableName: variableName } 

./consumer.js:

// There are three ways of importing. 
// If you need access to a non-default export, then 
// you use { nameOfExportedVariable } 
import { variableName } from './sourceFile'
console.log(variableName) // 'variableValue'

// Otherwise, you simply provide a local variable name 
// for what was exported as default.
import sourceFile from './sourceFile'
console.log(sourceFile.variableName) // 'variableValue'

./sourceFileWithoutDefault.js:

// The third way of importing is for situations where there
// isn't a default export but you want to warehouse everything
// under a single variable. Say you have:
export const a = 'A'
export const b = 'B'

./consumer2.js

// Then you can import all exports under a single variable
// with the usage of * as:
import * as sourceFileWithoutDefault from './sourceFileWithoutDefault'

console.log(sourceFileWithoutDefault.a) // 'A'
console.log(sourceFileWithoutDefault.b) // 'B'

// You can use this approach even if there is a default export:
import * as sourceFile from './sourceFile'

// Default exports are under the variable default:
console.log(sourceFile.default) // { variableName: 'variableValue' }

// As well as named exports:
console.log(sourceFile.variableName) // 'variableValue

Expected initializer before function name

Try adding a semi colon to the end of your structure:

 struct sotrudnik {
    string name;
    string speciality;
    string razread;
    int zarplata;
} //Semi colon here

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);

 }

Calling startActivity() from outside of an Activity?

Android Doc says -

FLAG_ACTIVITY_NEW_TASK requirement is now enforced

With Android 9, you cannot start an activity from a non-activity context unless you pass the intent flag FLAG_ACTIVITY_NEW_TASK. If you attempt to start an activity without passing this flag, the activity does not start, and the system prints a message to the log.

Note: The flag requirement has always been the intended behavior, and was enforced on versions lower than Android 7.0 (API level 24). A bug in Android 7.0 prevented the flag requirement from being enforced.

That means for (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) it is mandatory to add Intent.FLAG_ACTIVITY_NEW_TASK while calling startActivity() from outside of an Activity context.

So it is better to add flag for all the versions -

...
Intent i = new Intent(this, Wakeup.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
...

How to check if a file exists from inside a batch file

Try something like the following example, quoted from the output of IF /? on Windows XP:

IF EXIST filename. (
    del filename.
) ELSE (
    echo filename. missing.
)

You can also check for a missing file with IF NOT EXIST.

The IF command is quite powerful. The output of IF /? will reward careful reading. For that matter, try the /? option on many of the other built-in commands for lots of hidden gems.  

class method generates "TypeError: ... got multiple values for keyword argument ..."

just add 'staticmethod' decorator to function and problem is fixed

class foo(object):
    @staticmethod
    def foodo(thing=None, thong='not underwear'):
        print thing if thing else "nothing" 
        print 'a thong is',thong

Unable to run Java code with Intellij IDEA

My classes contained a main() method yet I was unable to see the Run option. That option was enabled once I marked a folder containing my class files as a source folder:

  1. Right click the folder containing your source
  2. Select Mark Directory as → Test Source Root

Some of the classes in my folder don't have a main() method, but I still see a Run option for those.

Control flow in T-SQL SP using IF..ELSE IF - are there other ways?

No, but you should be careful when using IF...ELSE...END IF in stored procs. If your code blocks are radically different, you may suffer from poor performance because the procedure plan will need to be re-cached each time. If it's a high-performance system, you may want to compile separate stored procs for each code block, and have your application decide which proc to call at the appropriate time.

Android Recyclerview vs ListView with Viewholder

Okay so little bit of digging and I found these gems from Bill Philips article on RecycleView

RecyclerView can do more than ListView, but the RecyclerView class itself has fewer responsibilities than ListView. Out of the box, RecyclerView does not:

  • Position items on the screen
  • Animate views
  • Handle any touch events apart from scrolling

All of this stuff was baked in to ListView, but RecyclerView uses collaborator classes to do these jobs instead.

The ViewHolders you create are beefier, too. They subclass RecyclerView.ViewHolder, which has a bunch of methods RecyclerView uses. ViewHolders know which position they are currently bound to, as well as which item ids (if you have those). In the process, ViewHolder has been knighted. It used to be ListView’s job to hold on to the whole item view, and ViewHolder only held on to little pieces of it.

Now, ViewHolder holds on to all of it in the ViewHolder.itemView field, which is assigned in ViewHolder’s constructor for you.

Sync data between Android App and webserver

@Grantismo gives a great overview of Android sync components.

SyncManagerAndroid library provides a simple 2-way sync implementation to plug into the Android Sync framework (AbstractThreadedSyncAdapter.OnPerformSync).

https://github.com/sschendel/SyncManagerAndroid

Creating a textarea with auto-resize

For those who want the textarea to be auto resized on both width and height:

HTML:

<textarea class='textbox'></textarea>
<div>
  <span class='tmp_textbox'></span>
</div>

CSS:

.textbox,
.tmp_textbox {
  font-family: 'Arial';
  font-size: 12px;
  resize: none;
  overflow:hidden;
}

.tmp_textbox {
  display: none;
}

jQuery:

$(function(){
  //alert($('.textbox').css('padding'))
  $('.textbox').on('keyup change', checkSize)
  $('.textbox').trigger('keyup')

  function checkSize(){
    var str = $(this).val().replace(/\r?\n/g, '<br/>');
    $('.tmp_textbox').html( str )
    console.log($(this).val())

    var strArr = str.split('<br/>')
    var row = strArr.length
    $('.textbox').attr('rows', row)
    $('.textbox').width( $('.tmp_textbox').width() + parseInt($('.textbox').css('padding')) * 2 + 10 )
  }
})

Codepen:

http://codepen.io/anon/pen/yNpvJJ

Cheers,

Issue when importing dataset: `Error in scan(...): line 1 did not have 145 elements`

If you are using linux, and the data file is from windows. It probably because the character ^M Find it and delete. done!

How to check if a div is visible state or not?

Check if it's visible.

$("#singlechatpanel-1").is(':visible');

Check if it's hidden.

$("#singlechatpanel-1").is(':hidden');

How to run composer from anywhere?

Just move it to /usr/local/bin folder and remove the extension

sudo mv composer.phar /usr/local/bin/composer

SUM OVER PARTITION BY

In my opinion, I think it's important to explain the why behind the need for a GROUP BY in your SQL when summing with OVER() clause and why you are getting repeated lines of data when you are expecting one row per BrandID.

Take this example: You need to aggregate the total sale price of each order line, per specific order category, between two dates, but you also need to retain individual order data in your final results. A SUM() on the SalesPrice column would not allow you to get the correct totals because it would require a GROUP BY, therefore squashing the details because you wouldn't be able to keep the individual order lines in the select statement.

Many times we see a #temp table, @table variable, or CTE filled with the sum of our data and grouped up so we can join to it again later to get a column of the sums we need. This can add processing time and extra lines of code. Instead, use OVER(PARTITION BY ()) like this:

SELECT
  OrderLine, 
  OrderDateTime, 
  SalePrice, 
  OrderCategory,
  SUM(SalePrice) OVER(PARTITION BY OrderCategory) AS SaleTotalPerCategory
FROM tblSales 
WHERE OrderDateTime BETWEEN @StartDate AND @EndDate

Notice we are not grouping and we have individual order lines column selected. The PARTITION BY in the last column will return us a sales price total for each row of data in each category. What the last column essentially says is, we want the sum of the sale price (SUM(SalePrice)) over a partition of my results and by a specified category (OVER(PARTITION BY CategoryHere)).

If we remove the other columns from our select statement, and leave our final SUM() column, like this:

SELECT
  SUM(SalePrice) OVER(PARTITION BY OrderCategory) AS SaleTotalPerCategory
FROM tblSales 
WHERE OrderDateTime BETWEEN @StartDate AND @EndDate

The results will still repeat this sum for each row in our original result set. The reason is this method does not require a GROUP BY. If you don't need to retain individual line data, then simply SUM() without the use of OVER() and group up your data appropriately. Again, if you need an additional column with specific totals, you can use the OVER(PARTITION BY ()) method described above without additional selects to join back to.

The above is purely for explaining WHY he is getting repeated lines of the same number and to help understand what this clause provides. This method can be used in many ways and I highly encourage further reading from the documentation here:

Over Clause

Why does modern Perl avoid UTF-8 by default?

You should enable the unicode strings feature, and this is the default if you use v5.14;

You should not really use unicode identifiers esp. for foreign code via utf8 as they are insecure in perl5, only cperl got that right. See e.g. http://perl11.org/blog/unicode-identifiers.html

Regarding utf8 for your filehandles/streams: You need decide by yourself the encoding of your external data. A library cannot know that, and since not even libc supports utf8, proper utf8 data is rare. There's more wtf8, the windows aberration of utf8 around.

BTW: Moose is not really "Modern Perl", they just hijacked the name. Moose is perfect Larry Wall-style postmodern perl mixed with Bjarne Stroustrup-style everything goes, with an eclectic aberration of proper perl6 syntax, e.g. using strings for variable names, horrible fields syntax, and a very immature naive implementation which is 10x slower than a proper implementation. cperl and perl6 are the true modern perls, where form follows function, and the implementation is reduced and optimized.

Find the min/max element of an array in JavaScript

Below script worked for me in ndoejs:

 var numbers = [1, 2, 3, 4];
 console.log('Value:: ' + Math.max.apply(null, numbers) ); // 4

Convert one date format into another in PHP

Try this:

$old_date = date('y-m-d-h-i-s');
$new_date = date('Y-m-d H:i:s', strtotime($old_date));

How to use Sublime over SSH

I know this is way old, but I have a really cool way of doing this that is worth sharing.

What is required in Conemu and WinSCP. These are simple instructions

  1. Open WinSCP.exe and login to my desired remote server (I have
    found that it's important to login before attaching ... ).

  2. In the preferences for WinSCP - two settings to change. Choose Explorer type interface and rather than Commander - so you don't see local files. Unless you want to (but that seems like it would suck here). Set up Sublime as your default editor.

  3. With ConEmu open, right click the tab bar and select the option Attach to.... A dialog box will open with your running applications. Choose, WinSCP and select OK. ConEmu will now have an open tab with WinSCP displaying your remote files.

  4. Right click on the WinSCP tab and choose New console.... When the dialog box opens, enter the path to the Sublime executable on your system. Before you press Start, In the box that says New console split select the radio button to right and set the percentage. I usually choose 75%, but you can customize this to your liking, and it can be changed later.

    1. Now you will see Sublime in the same window running to the right of WinSCP. In Sublime, from the View menu, choose Sidebar->Hide Sidebar, and bam, you now have remote files in exactly the same manner as you would locally - with a few caveats of course that comes with editing anything remotely. WinSCP is lightening fast though.

I have two monitors - left monitor display's Chrome browser, right monitor displays code editor. Also in ConEmu, I create another tab and ssh into the site I'm working on, so I can do things like run gulp or grunt remotely and also manipulate files from the command line. Seriously sped up development.

Here's a screenshot:

Setup Screenshot

How can I use optional parameters in a T-SQL stored procedure?

Five years late to the party.

It is mentioned in the provided links of the accepted answer, but I think it deserves an explicit answer on SO - dynamically building the query based on provided parameters. E.g.:

Setup

-- drop table Person
create table Person
(
    PersonId INT NOT NULL IDENTITY(1, 1) CONSTRAINT PK_Person PRIMARY KEY,
    FirstName NVARCHAR(64) NOT NULL,
    LastName NVARCHAR(64) NOT NULL,
    Title NVARCHAR(64) NULL
)
GO

INSERT INTO Person (FirstName, LastName, Title)
VALUES ('Dick', 'Ormsby', 'Mr'), ('Serena', 'Kroeger', 'Ms'), 
    ('Marina', 'Losoya', 'Mrs'), ('Shakita', 'Grate', 'Ms'), 
    ('Bethann', 'Zellner', 'Ms'), ('Dexter', 'Shaw', 'Mr'),
    ('Zona', 'Halligan', 'Ms'), ('Fiona', 'Cassity', 'Ms'),
    ('Sherron', 'Janowski', 'Ms'), ('Melinda', 'Cormier', 'Ms')
GO

Procedure

ALTER PROCEDURE spDoSearch
    @FirstName varchar(64) = null,
    @LastName varchar(64) = null,
    @Title varchar(64) = null,
    @TopCount INT = 100
AS
BEGIN
    DECLARE @SQL NVARCHAR(4000) = '
        SELECT TOP ' + CAST(@TopCount AS VARCHAR) + ' *
        FROM Person
        WHERE 1 = 1'

    PRINT @SQL

    IF (@FirstName IS NOT NULL) SET @SQL = @SQL + ' AND FirstName = @FirstName'
    IF (@LastName IS NOT NULL) SET @SQL = @SQL + ' AND FirstName = @LastName'
    IF (@Title IS NOT NULL) SET @SQL = @SQL + ' AND Title = @Title'

    EXEC sp_executesql @SQL, N'@TopCount INT, @FirstName varchar(25), @LastName varchar(25), @Title varchar(64)', 
         @TopCount, @FirstName, @LastName, @Title
END
GO

Usage

exec spDoSearch @TopCount = 3
exec spDoSearch @FirstName = 'Dick'

Pros:

  • easy to write and understand
  • flexibility - easily generate the query for trickier filterings (e.g. dynamic TOP)

Cons:

  • possible performance problems depending on provided parameters, indexes and data volume

Not direct answer, but related to the problem aka the big picture

Usually, these filtering stored procedures do not float around, but are being called from some service layer. This leaves the option of moving away business logic (filtering) from SQL to service layer.

One example is using LINQ2SQL to generate the query based on provided filters:

    public IList<SomeServiceModel> GetServiceModels(CustomFilter filters)
    {
        var query = DataAccess.SomeRepository.AllNoTracking;

        // partial and insensitive search 
        if (!string.IsNullOrWhiteSpace(filters.SomeName))
            query = query.Where(item => item.SomeName.IndexOf(filters.SomeName, StringComparison.OrdinalIgnoreCase) != -1);
        // filter by multiple selection
        if ((filters.CreatedByList?.Count ?? 0) > 0)
            query = query.Where(item => filters.CreatedByList.Contains(item.CreatedById));
        if (filters.EnabledOnly)
            query = query.Where(item => item.IsEnabled);

        var modelList = query.ToList();
        var serviceModelList = MappingService.MapEx<SomeDataModel, SomeServiceModel>(modelList);
        return serviceModelList;
    }

Pros:

  • dynamically generated query based on provided filters. No parameter sniffing or recompile hints needed
  • somewhat easier to write for those in the OOP world
  • typically performance friendly, since "simple" queries will be issued (appropriate indexes are still needed though)

Cons:

  • LINQ2QL limitations may be reached and forcing a downgrade to LINQ2Objects or going back to pure SQL solution depending on the case
  • careless writing of LINQ might generate awful queries (or many queries, if navigation properties loaded)

jQuery - Uncaught RangeError: Maximum call stack size exceeded

Your calls are made recursively which pushes functions on to the stack infinitely that causes max call stack exceeded error due to recursive behavior. Instead try using setTimeout which is a callback.

Also based on your markup your selector is wrong. it should be #advisersDiv

Demo

function fadeIn() {
    $('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
    setTimeout(fadeOut,1); //<-- Provide any delay here
};

function fadeOut() {
    $('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
    setTimeout(fadeIn,1);//<-- Provide any delay here
};
fadeIn();

How to increase dbms_output buffer?

Here you go:

DECLARE
BEGIN
  dbms_output.enable(NULL); -- Disables the limit of DBMS
  -- Your print here !
END;

Executing JavaScript after X seconds

onclick = "setTimeout(function() { document.getElementById('div1').style.display='none';document.getElementById('div2').style.display='none'}, 1000)"

Change 1000 to the number of milliseconds you want to delay.

how to run a winform from console application?

You should be able to use the Application class in the same way as Winform apps do. Probably the easiest way to start a new project is to do what Marc suggested: create a new Winform project, and then change it in the options to a console application

Android: Unable to add window. Permission denied for this window type

if you use apiLevel >= 19, don't use

WindowManager.LayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT 

which gets the following error:

android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@40ec8528 -- permission denied for this window type

Use this instead:

LayoutParams.TYPE_TOAST or TYPE_APPLICATION_PANEL

newline in <td title="">

Using &#xA; Works in Chrome to create separate lines in a tooltip.

SQL How to correctly set a date variable value and use it?

If you manually write out the query with static date values (e.g. '2009-10-29 13:13:07.440') do you get any rows?

So, you are saying that the following two queries produce correct results:

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > '2009-10-29 13:13:07.440') AND (pa.AdvertiserID = 12345))

DECLARE @sp_Date DATETIME
SET @sp_Date = '2009-10-29 13:13:07.440'

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > @sp_Date) AND (pa.AdvertiserID = 12345))

Mapping object to dictionary and vice versa

Reflection can take you from an object to a dictionary by iterating over the properties.

To go the other way, you'll have to use a dynamic ExpandoObject (which, in fact, already inherits from IDictionary, and so has done this for you) in C#, unless you can infer the type from the collection of entries in the dictionary somehow.

So, if you're in .NET 4.0 land, use an ExpandoObject, otherwise you've got a lot of work to do...

Convert a list of objects to an array of one of the object's properties

For everyone who is stuck with .NET 2.0, like me, try the following way (applicable to the example in the OP):

ConfigItemList.ConvertAll<string>(delegate (ConfigItemType ci) 
{ 
   return ci.Name; 
}).ToArray();

where ConfigItemList is your list variable.

How to fire an event on class change using jQuery?

Use trigger to fire your own event. When ever you change class add trigger with name

JS Fiddle DEMO

$("#main").on('click', function () {
    $("#chld").addClass("bgcolorRed").trigger("cssFontSet");
});

$('#chld').on('cssFontSet', function () {

    alert("Red bg set ");
});

Learn jQuery: Simple and easy jQuery tutorials blog

UIView Infinite 360 degree rotation animation?

I think you should better add a UIVIew Category:

#import <QuartzCore/QuartzCore.h>
#import "UIView+Rotate.h"

Implementation UIView (Rotate)

  • (void)remrotate360WithDuration:(CGFloat)duration repeatCount: (float)repeatCount
    {
        CABasicAnimation *fullRotation;
        fullRotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        fullRotation.fromValue = [NSNumber numberWithFloat:0];
        fullRotation.toValue = [NSNumber numberWithFloat:(2*M_PI)];
        // fullRotation.toValue = [NSNumber numberWithFloat:-(2*M_PI)]; // added this minus sign as i want to rotate it to anticlockwise
        fullRotation.duration = duration;
        fullRotation.speed = 2.0f; // Changed rotation speed
        if (repeatCount == 0)
            fullRotation.repeatCount = MAXFLOAT;
        else
            fullRotation.repeatCount = repeatCount;
    
        [self.layer addAnimation:fullRotation forKey:@"360"];
    }
    

Not using this methods :)

  • (void)remstopAllAnimations
    {
        [self.layer removeAllAnimations];
    };
    
  • (void)rempauseAnimations
    {
        [self rempauseLayer:self.layer];
    }
    
  • (void)remresumeAnimations
    {
        [self remresumeLayer:self.layer];
    }
    
  • (void)rempauseLayer:(CALayer *)layer
    {
        CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
        layer.speed = 0.0;
        layer.timeOffset = pausedTime;
    }
    
  • (void)remresumeLayer:(CALayer *)layer
    {
        CFTimeInterval pausedTime = [layer timeOffset];
        layer.speed = 1.0;
        layer.timeOffset = 0.0;
        layer.beginTime = 0.0;
        CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
        layer.beginTime = timeSincePause;
    }
    

MySQL query String contains

Use:

SELECT *
  FROM `table`
 WHERE INSTR(`column`, '{$needle}') > 0

Reference:

How can I select rows with most recent timestamp for each key value?

For the sake of completeness, here's another possible solution:

SELECT sensorID,timestamp,sensorField1,sensorField2 
FROM sensorTable s1
WHERE timestamp = (SELECT MAX(timestamp) FROM sensorTable s2 WHERE s1.sensorID = s2.sensorID)
ORDER BY sensorID, timestamp;

Pretty self-explaining I think, but here's more info if you wish, as well as other examples. It's from the MySQL manual, but above query works with every RDBMS (implementing the sql'92 standard).

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

I had the same issue, for me this fixed the issue:
right click on the project ->maven -> update project

maven -> update project

.Net: How do I find the .NET version?

If you'r developing some .Net app (for ex. web app), you can make 1 line of error code (like invoke wrong function name) and reload your page, the .Net version will be showenter image description here

Java 8: Difference between two LocalDateTime in multiple units

Here a single example using Duration and TimeUnit to get 'hh:mm:ss' format.

Duration dur = Duration.between(localDateTimeIni, localDateTimeEnd);
long millis = dur.toMillis();

String.format("%02d:%02d:%02d", 
        TimeUnit.MILLISECONDS.toHours(millis),
        TimeUnit.MILLISECONDS.toMinutes(millis) - 
        TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
        TimeUnit.MILLISECONDS.toSeconds(millis) - 
        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));

How to pass variable number of arguments to a PHP function

An old question, I know, however, none of the answers here really do a good job of simply answer the question.

I just played around with php and the solution looks like this:

function myFunction($requiredArgument, $optionalArgument = "default"){
   echo $requiredArgument . $optionalArgument;
}

This function can do two things:

If its called with only the required parameter: myFunction("Hi") It will print "Hi default"

But if it is called with the optional parameter: myFunction("Hi","me") It will print "Hi me";

I hope this helps anyone who is looking for this down the road.

How do I time a method's execution in Java?

I have written a method to print the method execution time in a much readable form. For example, to calculate the factorial of 1 Million, it takes approximately 9 minutes. So the execution time get printed as:

Execution Time: 9 Minutes, 36 Seconds, 237 MicroSeconds, 806193 NanoSeconds

The code is here:

public class series
{
    public static void main(String[] args)
    {
        long startTime = System.nanoTime();

        long n = 10_00_000;
        printFactorial(n);

        long endTime = System.nanoTime();
        printExecutionTime(startTime, endTime);

    }

    public static void printExecutionTime(long startTime, long endTime)
    {
        long time_ns = endTime - startTime;
        long time_ms = TimeUnit.NANOSECONDS.toMillis(time_ns);
        long time_sec = TimeUnit.NANOSECONDS.toSeconds(time_ns);
        long time_min = TimeUnit.NANOSECONDS.toMinutes(time_ns);
        long time_hour = TimeUnit.NANOSECONDS.toHours(time_ns);

        System.out.print("\nExecution Time: ");
        if(time_hour > 0)
            System.out.print(time_hour + " Hours, ");
        if(time_min > 0)
            System.out.print(time_min % 60 + " Minutes, ");
        if(time_sec > 0)
            System.out.print(time_sec % 60 + " Seconds, ");
        if(time_ms > 0)
            System.out.print(time_ms % 1E+3 + " MicroSeconds, ");
        if(time_ns > 0)
            System.out.print(time_ns % 1E+6 + " NanoSeconds");
    }
}

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

egyamado's answer was really helpful! You can enhance it for your particular setup with something like this:

import sublime, sublime_plugin
import webbrowser

class OpenBrowserCommand(sublime_plugin.TextCommand):
   def run(self, edit, keyPressed, localHost, pathToFiles):  
      for region in self.view.sel():  
         if not region.empty():  
            # Get the selected text  
            url = self.view.substr(region)  
            # prepend beginning of local host url 
            url = localHost + url  
         else:
            # prepend beginning of local host url 
            url = localHost + self.view.file_name()
            # replace local path to file
            url = url.replace(pathToFiles, "")


         if keyPressed == "1":
            navigator = webbrowser.get("open -a /Applications/Firefox.app %s")
         if keyPressed == "2":
            navigator = webbrowser.get("open -a /Applications/Google\ Chrome.app %s")
         if keyPressed == "3":
            navigator = webbrowser.get("open -a /Applications/Safari.app %s")
         navigator.open_new(url)

And then in your keybindings:

{ "keys": ["alt+1"], "command": "open_browser", "args": {"keyPressed": "1", "localHost": "http://nbrown.smartdestinations.com", "pathToFiles":"/opt/local/apache2/htdocs"}},
{ "keys": ["alt+2"], "command": "open_browser", "args": {"keyPressed": "2", "localHost": "http://nbrown.smartdestinations.com", "pathToFiles":"/opt/local/apache2/htdocs"}},
{ "keys": ["alt+3"], "command": "open_browser", "args": {"keyPressed": "3", "localHost": "http://nbrown.smartdestinations.com", "pathToFiles":"/opt/local/apache2/htdocs"}}

We store sample urls at the top of all our templates, so the first part allows you to highlight that sample URL and launch it in a browser. If no text is highlighted, it will simply use the file name. You can adjust the command calls in the keybindings to your localhost url and the system path to the documents you're working on.

Example using Hyperlink in WPF

Hope this help someone as well.

using System.Diagnostics;
using System.Windows.Documents;

namespace Helpers.Controls
{
    public class HyperlinkEx : Hyperlink
    {
        protected override void OnClick()
        {
            base.OnClick();

            Process p = new Process()
            {
                StartInfo = new ProcessStartInfo()
                {
                    FileName = this.NavigateUri.AbsoluteUri
                }
            };
            p.Start();
        }
    }
}

Using (Ana)conda within PyCharm

Change the project interpreter to ~/anaconda2/python/bin by going to File -> Settings -> Project -> Project Interpreter. Also update the run configuration to use the project default Python interpreter via Run -> Edit Configurations. This makes PyCharm use Anaconda instead of the default Python interpreter under usr/bin/python27.

How to open in default browser in C#

public static void GoToSite(string url)
{
     System.Diagnostics.Process.Start(url);
}

that should solve your problem

How to import other Python files?

from file import function_name  ######## Importing specific function
function_name()                 ######## Calling function

and

import file              ######## Importing whole package
file.function1_name()    ######## Calling function
file.function2_name()    ######## Calling function

Here are the two simple ways I have understood by now and make sure your "file.py" file which you want to import as a library is present in your current directory only.

How to change the color of a SwitchCompat from AppCompat library

My working example of using style and android:theme simultaneously (API >= 21)

<android.support.v7.widget.SwitchCompat
    android:id="@+id/wan_enable_nat_switch"
    style="@style/Switch"
    app:layout_constraintBaseline_toBaselineOf="@id/wan_enable_nat_label"
    app:layout_constraintEnd_toEndOf="parent" />

<style name="Switch">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:paddingEnd">16dp</item>
    <item name="android:focusableInTouchMode">true</item>
    <item name="android:theme">@style/ThemeOverlay.MySwitchCompat</item>
</style>

<style name="ThemeOverlay.MySwitchCompat" parent="">
    <item name="colorControlActivated">@color/colorPrimaryDark</item>
    <item name="colorSwitchThumbNormal">@color/text_outline_not_active</item>
    <item name="android:colorForeground">#42221f1f</item>
</style>

Converting NSString to NSDictionary / JSON

I believe you are misinterpreting the JSON format for key values. You should store your string as

NSString *jsonString = @"{\"ID\":{\"Content\":268,\"type\":\"text\"},\"ContractTemplateID\":{\"Content\":65,\"type\":\"text\"}}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

Now if you do following NSLog statement

NSLog(@"%@",[json objectForKey:@"ID"]);

Result would be another NSDictionary.

{
    Content = 268;
    type = text;
}

Hope this helps to get clear understanding.

Clear git local cache

All .idea files that are explicitly ignored are still showing up to commit

you have to remove them from the staging area

git rm --cached .idea

now you have to commit those changes and they will be ignored from this point on.
Once git start to track changes it will not "stop" tracking them even if they were added to the .gitignore file later on.

You must explicitly remove them and then commit your removal manually in order to fully ignore them.


enter image description here

enter image description here

How to send email via Django?

Send the email to a real SMTP server. If you don't want to set up your own then you can find companies that will run one for you, such as Google themselves.

JavaScript override methods

Once should avoid emulating classical OO and use prototypical OO instead. A nice utility library for prototypical OO is traits.

Rather then overwriting methods and setting up inheritance chains (one should always favour object composition over object inheritance) you should be bundling re-usable functions into traits and creating objects with those.

Live Example

var modifyA = {
    modify: function() {
        this.x = 300;
        this.y = 400;
    }
};

var modifyB = {
    modify: function() {
        this.x = 3000;
        this.y = 4000;
    }
};

C = function(trait) {
    var o = Object.create(Object.prototype, Trait(trait));

    o.modify();
    console.log("sum : " + (o.x + o.y));

    return o;
}

//C(modifyA);
C(modifyB);

Best way to generate a random float in C#

Best approach, no crazed values, distributed with respect to the representable intervals on the floating-point number line (removed "uniform" as with respect to a continuous number line it is decidedly non-uniform):

static float NextFloat(Random random)
{
    double mantissa = (random.NextDouble() * 2.0) - 1.0;
    // choose -149 instead of -126 to also generate subnormal floats (*)
    double exponent = Math.Pow(2.0, random.Next(-126, 128));
    return (float)(mantissa * exponent);
}

(*) ... check here for subnormal floats

Warning: generates positive infinity as well! Choose exponent of 127 to be on the safe side.

Another approach which will give you some crazed values (uniform distribution of bit patterns), potentially useful for fuzzing:

static float NextFloat(Random random)
{
    var buffer = new byte[4];
    random.NextBytes(buffer);
    return BitConverter.ToSingle(buffer,0);
}

An improvement over the previous version is this one, which does not create "crazed" values (neither infinities nor NaN) and is still fast (also distributed with respect to the representable intervals on the floating-point number line):

public static float Generate(Random prng)
{
    var sign = prng.Next(2);
    var exponent = prng.Next((1 << 8) - 1); // do not generate 0xFF (infinities and NaN)
    var mantissa = prng.Next(1 << 23);

    var bits = (sign << 31) + (exponent << 23) + mantissa;
    return IntBitsToFloat(bits);
}

private static float IntBitsToFloat(int bits)
{
    unsafe
    {
        return *(float*) &bits;
    }
}

Least useful approach:

static float NextFloat(Random random)
{
    // Not a uniform distribution w.r.t. the binary floating-point number line
    // which makes sense given that NextDouble is uniform from 0.0 to 1.0.
    // Uniform w.r.t. a continuous number line.
    //
    // The range produced by this method is 6.8e38.
    //
    // Therefore if NextDouble produces values in the range of 0.0 to 0.1
    // 10% of the time, we will only produce numbers less than 1e38 about
    // 10% of the time, which does not make sense.
    var result = (random.NextDouble()
                  * (Single.MaxValue - (double)Single.MinValue))
                  + Single.MinValue;
    return (float)result;
}

Floating point number line from: Intel Architecture Software Developer's Manual Volume 1: Basic Architecture. The Y-axis is logarithmic (base-2) because consecutive binary floating point numbers do not differ linearly.

Comparison of distributions, logarithmic Y-axis

Recursively look for files with a specific extension

find $directory -type f -name "*.in"|grep $substring

What does "if (rs.next())" mean?

I'm presuming you're using Java 6 and that the ResultSet that you're using is a java.sql.ResultSet.

The JavaDoc for the ResultSet.next() method states:

Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown.

So, if(rs.next(){ //do something } means "If the result set still has results, move to the next result and do something".

As BalusC pointed out, you need to replace

ResultSet rs = stmt.executeQuery(sql);

with

ResultSet rs = stmt.executeQuery();

Because you've already set the SQL to use in the statement with your previous line

PreparedStatement stmt = conn.prepareStatement(sql);

If you weren't using the PreparedStatement, then ResultSet rs = stmt.executeQuery(sql); would work.

Is it possible to have a multi-line comments in R?

Put the following into your ~/.Rprofile file:

exclude <-  function(blah) {
    "excluded block"
}

Now, you can exclude blocks like follows:

stuffiwant

exclude({
    stuffidontwant
    morestuffidontwant
})

Equivalent of typedef in C#

Both C++ and C# are missing easy ways to create a new type which is semantically identical to an exisiting type. I find such 'typedefs' totally essential for type-safe programming and its a real shame c# doesn't have them built-in. The difference between void f(string connectionID, string username) to void f(ConID connectionID, UserName username) is obvious ...

(You can achieve something similar in C++ with boost in BOOST_STRONG_TYPEDEF)

It may be tempting to use inheritance but that has some major limitations:

  • it will not work for primitive types
  • the derived type can still be casted to the original type, ie we can send it to a function receiving our original type, this defeats the whole purpose
  • we cannot derive from sealed classes (and ie many .NET classes are sealed)

The only way to achieve a similar thing in C# is by composing our type in a new class:

Class SomeType { 
  public void Method() { .. }
}

sealed Class SomeTypeTypeDef {
  public SomeTypeTypeDef(SomeType composed) { this.Composed = composed; }

  private SomeType Composed { get; }

  public override string ToString() => Composed.ToString();
  public override int GetHashCode() => HashCode.Combine(Composed);
  public override bool Equals(object obj) => obj is TDerived o && Composed.Equals(o.Composed); 
  public bool Equals(SomeTypeTypeDefo) => object.Equals(this, o);

  // proxy the methods we want
  public void Method() => Composed.Method();
}

While this will work it is very verbose for just a typedef. In addition we have a problem with serializing (ie to Json) as we want to serialize the class through its Composed property.

Below is a helper class that uses the "Curiously Recurring Template Pattern" to make this much simpler:

namespace Typedef {

  [JsonConverter(typeof(JsonCompositionConverter))]
  public abstract class Composer<TDerived, T> : IEquatable<TDerived> where TDerived : Composer<TDerived, T> {
    protected Composer(T composed) { this.Composed = composed; }
    protected Composer(TDerived d) { this.Composed = d.Composed; }

    protected T Composed { get; }

    public override string ToString() => Composed.ToString();
    public override int GetHashCode() => HashCode.Combine(Composed);
    public override bool Equals(object obj) => obj is Composer<TDerived, T> o && Composed.Equals(o.Composed); 
    public bool Equals(TDerived o) => object.Equals(this, o);
  }

  class JsonCompositionConverter : JsonConverter {
    static FieldInfo GetCompositorField(Type t) {
      var fields = t.BaseType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);
      if (fields.Length!=1) throw new JsonSerializationException();
      return fields[0];
    }

    public override bool CanConvert(Type t) {
      var fields = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);
      return fields.Length == 1;
    }

    // assumes Compositor<T> has either a constructor accepting T or an empty constructor
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
      while (reader.TokenType == JsonToken.Comment && reader.Read()) { };
      if (reader.TokenType == JsonToken.Null) return null; 
      var compositorField = GetCompositorField(objectType);
      var compositorType = compositorField.FieldType;
      var compositorValue = serializer.Deserialize(reader, compositorType);
      var ctorT = objectType.GetConstructor(new Type[] { compositorType });
      if (!(ctorT is null)) return Activator.CreateInstance(objectType, compositorValue);
      var ctorEmpty = objectType.GetConstructor(new Type[] { });
      if (ctorEmpty is null) throw new JsonSerializationException();
      var res = Activator.CreateInstance(objectType);
      compositorField.SetValue(res, compositorValue);
      return res;
    }

    public override void WriteJson(JsonWriter writer, object o, JsonSerializer serializer) {
      var compositorField = GetCompositorField(o.GetType());
      var value = compositorField.GetValue(o);
      serializer.Serialize(writer, value);
    }
  }

}

With Composer the above class becomes simply:

sealed Class SomeTypeTypeDef : Composer<SomeTypeTypeDef, SomeType> {
   public SomeTypeTypeDef(SomeType composed) : base(composed) {}

   // proxy the methods we want
   public void Method() => Composed.Method();
}

And in addition the SomeTypeTypeDef will serialize to Json in the same way that SomeType does.

Hope this helps !

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

I'm going to assume that your lack of quotes around the selector is just a transcription error, but you should check it anyway. Also, I don't see where you are actually giving the form an id. Usually you do this with the htmlAttributes parameter. I don't see you using the signature that has it. Again, though, if the form is submitting at all, this could be a transcription error.

If the selector and the id aren't the problem I'm suspicious that it might be because the click handler is added via markup when you use the Ajax BeginForm extension. You might try using $('form').trigger('submit') or in the worst case, have the click handler on the anchor create a hidden submit button in the form and click it. Or even create your own ajax submission using pure jQuery (which is probably what I would do).

Lastly, you should realize that by replacing the submit button, you're going to totally break this for people who don't have javascript enabled. The way around this is to also have a button hidden using a noscript tag and handle both AJAX and non-AJAX posts on the server.

BTW, it's consider standard practice, Microsoft not withstanding, to add the handlers via javascript not via markup. This keeps your javascript organized in one place so you can more easily see what's going on on the form. Here's an example of how I would use the trigger mechanism.

  $(function() {
      $('form#ajaxForm').find('a.submit-link').click( function() {
           $('form#ajaxForm').trigger('submit');
      }).show();
  }

<% using (Ajax.BeginForm("Update", "Description", new { id = Model.Id },
     new AjaxOptions
     {
       UpdateTargetId = "DescriptionDiv",
       HttpMethod = "post"
     }, new { id = "ajaxForm" } )) {%>
   Description:
   <%= Html.TextBox("Description", Model.Description) %><br />
   <a href="#" class="submit-link" style="display: none;">Save</a>
   <noscript>
       <input type="submit" value="Save" />
   </noscript>
<% } %>

How to select a drop-down menu value with Selenium using Python?

It works with option value:

from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[@class='class_name']/option[@value='option_value']").click()

Convert python datetime to timestamp in milliseconds

For those who searches for an answer without parsing and loosing milliseconds, given dt_obj is a datetime:

python3 only, elegant

int(dt_obj.timestamp() * 1000)

both python2 and python3 compatible:

import time

int(time.mktime(dt_obj.utctimetuple()) * 1000 + dt_obj.microsecond / 1000)

how to print an exception using logger?

You can use this method to log the exception stack to String

 public String stackTraceToString(Throwable e) {
    StringBuilder sb = new StringBuilder();
    for (StackTraceElement element : e.getStackTrace()) {
        sb.append(element.toString());
        sb.append("\n");
    }
    return sb.toString();
}

Start/Stop and Restart Jenkins service on Windows

Small hints for routine work.

Create a bat file, name it and use for exact run/stop/restart Jenkins service

#!/bin/bash
# go to Jenkins folder
cd C:\Program Files (x86)\Jenkins

#to stop:
jenkins.exe stop

#to start:
#jenkins.exe start

#to restart:
#jenkins.exe restart

How to detect when facebook's FB.init is complete

While some of the above solutions work, I thought I'd post our eventual solution - which defines a 'ready' method that will fire as soon as FB is initialized and ready to go. It has the advantage over other solutions that it's safe to call either before or after FB is ready.

It can be used like so:

f52.fb.ready(function() {
    // safe to use FB here
});

Here's the source file (note that it's defined within a 'f52.fb' namespace).

if (typeof(f52) === 'undefined') { f52 = {}; }
f52.fb = (function () {

    var fbAppId = f52.inputs.base.fbAppId,
        fbApiInit = false;

    var awaitingReady = [];

    var notifyQ = function() {
        var i = 0,
            l = awaitingReady.length;
        for(i = 0; i < l; i++) {
            awaitingReady[i]();
        }
    };

    var ready = function(cb) {
        if (fbApiInit) {
            cb();
        } else {
            awaitingReady.push(cb);
        }
    };

    window.fbAsyncInit = function() {
        FB.init({
            appId: fbAppId,
            xfbml: true,
            version: 'v2.0'
        });

        FB.getLoginStatus(function(response){
            fbApiInit = true;
            notifyQ();
        });
    };

    return {
        /**
         * Fires callback when FB is initialized and ready for api calls.
         */
        'ready': ready
    };

})();

How to find the statistical mode?

Based on @Chris's function to calculate the mode or related metrics, however using Ken Williams's method to calculate frequencies. This one provides a fix for the case of no modes at all (all elements equally frequent), and some more readable method names.

Mode <- function(x, method = "one", na.rm = FALSE) {
  x <- unlist(x)
  if (na.rm) {
    x <- x[!is.na(x)]
  }

  # Get unique values
  ux <- unique(x)
  n <- length(ux)

  # Get frequencies of all unique values
  frequencies <- tabulate(match(x, ux))
  modes <- frequencies == max(frequencies)

  # Determine number of modes
  nmodes <- sum(modes)
  nmodes <- ifelse(nmodes==n, 0L, nmodes)

  if (method %in% c("one", "mode", "") | is.na(method)) {
    # Return NA if not exactly one mode, else return the mode
    if (nmodes != 1) {
      return(NA)
    } else {
      return(ux[which(modes)])
    }
  } else if (method %in% c("n", "nmodes")) {
    # Return the number of modes
    return(nmodes)
  } else if (method %in% c("all", "modes")) {
    # Return NA if no modes exist, else return all modes
    if (nmodes > 0) {
      return(ux[which(modes)])
    } else {
      return(NA)
    }
  }
  warning("Warning: method not recognised.  Valid methods are 'one'/'mode' [default], 'n'/'nmodes' and 'all'/'modes'")
}

Since it uses Ken's method to calculate frequencies the performance is also optimised, using AkselA's post I benchmarked some of the previous answers as to show how my function is close to Ken's in performance, with the conditionals for the various ouput options causing only minor overhead: Comparison of Mode functions

Change border-bottom color using jquery?

$('#elementid').css('border-bottom', 'solid 1px red');

Change "on" color of a Switch

Easiest way is defining track tint, and setting tint mode to src_over to remove 30% transparency.

android:trackTint="@drawable/toggle_style"
android:trackTintMode="src_over"

toggle_style.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/informationDefault"
        android:state_checked="true"
        />
    <item android:color="@color/textDisabled" android:state_checked="false"/>
</selector>

Object not found! The requested URL was not found on this server. localhost

write in file config

$config['base_url'] = 'http://localhost:8000/test/content/home/';

java.lang.NoClassDefFoundError: org/json/JSONObject

The Exception it self says it all java.lang.ClassNotFoundException: org.json.JSONObject

You have not added the necessary jar file which will be having org.json.JSONObject class to your classpath.

You can Download it From Here

Connect to SQL Server database from Node.js

//start the program
var express = require('express');
var app = express();

app.get('/', function (req, res) {

    var sql = require("mssql");

    // config for your database
    var config = {
        user: 'datapullman',
        password: 'system',
        server: 'localhost', 
        database: 'chat6' 
    };

    // connect to your database
    sql.connect(config, function (err) {

        if (err) console.log(err);

        // create Request object
        var request = new sql.Request();

        // query to the database and get the records

        request.query("select * From emp", function (err, recordset) {            
            if  (err) console.log(err)

            // send records as a response
            res.send(recordset);

        });
    });
});

var server = app.listen(5000, function () {
    console.log('Server is running..');
});

//create a table as emp in a database (i have created as chat6)

// programs ends here

//save it as app.js and run as node app.js //open in you browser as localhost:5000

SQLite: How do I save the result of a query as a CSV file?

In addition to the above answers you can also use .once in a similar way to .output. This outputs only the next query to the specified file, so that you don't have to follow with .output stdout.

So in the above example

.mode csv
.headers on
.once test.csv
select * from tbl1;

Tomcat Servlet: Error 404 - The requested resource is not available

Writing Java servlets is easy if you use Java EE 7

@WebServlet("/hello-world")
public class HelloWorld extends HttpServlet {
  @Override
  public void doGet(HttpServletRequest request, 
                  HttpServletResponse response) {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   out.println("Hello World");
   out.flush();
  }
}

Since servlet 3.0

The good news is the deployment descriptor is no longer required!

Read the tutorial for Java Servlets.

Is <div style="width: ;height: ;background: "> CSS?

Yes, it is called Inline CSS, Here you styling the div using some height, width, and background.

Here the example:

<div style="width:50px;height:50px;background color:red">

You can achieve same using Internal or External CSS

2.Internal CSS:

  <head>
    <style>
    div {
    height:50px;
    width:50px;
    background-color:red;
    foreground-color:white;
    }
    </style>
  </head>
  <body>
    <div></div>
  </body>

3.External CSS:

<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div></div>
</body>

style.css /external css file/

 div {
        height:50px;
        width:50px;
        background-color:red;
    }

What is the proper way to test if a parameter is empty in a batch file?

I usually use this:

IF "%1."=="." GOTO MyLabel

If %1 is empty, the IF will compare "." to "." which will evaluate to true.

How to display items side-by-side without using tables?

Usually I do this:

<div>
   <p> 
       <img src='1.jpg' align='left' />
       Text Here
   <p>
</div>

Converting a String to a List of Words?

The most simple way:

>>> import re
>>> string = 'This is a string, with words!'
>>> re.findall(r'\w+', string)
['This', 'is', 'a', 'string', 'with', 'words']

When should null values of Boolean be used?

Wow, what on earth? Is it just me or are all these answers wrong or at least misleading?

The Boolean class is a wrapper around the boolean primitive type. The use of this wrapper is to be able to pass a boolean in a method that accepts an object or generic. Ie vector.

A Boolean object can NEVER have a value of null. If your reference to a Boolean is null, it simply means that your Boolean was never created.

You might find this useful: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Boolean.java

A null Boolean reference should only be used to trigger similar logic to which you have any other null reference. Using it for three state logic is clumsy.

EDIT: notice, that Boolean a = true; is a misleading statement. This really equals something closer to Boolean a = new Boolean(true); Please see autoboxing here: http://en.wikipedia.org/wiki/Boxing_%28computer_science%29#Autoboxing

Perhaps this is where much of the confusion comes from.

EDIT2: Please read comments below. If anyone has an idea of how to restructure my answer to incorporate this, please do so.

How to call C++ function from C?

You need to create a C API for exposing the functionality of your C++ code. Basically, you will need to write C++ code that is declared extern "C" and that has a pure C API (not using classes, for example) that wraps the C++ library. Then you use the pure C wrapper library that you've created.

Your C API can optionally follow an object-oriented style, even though C is not object-oriented. Ex:

 // *.h file
 // ...
 #ifdef __cplusplus
 #define EXTERNC extern "C"
 #else
 #define EXTERNC
 #endif

 typedef void* mylibrary_mytype_t;

 EXTERNC mylibrary_mytype_t mylibrary_mytype_init();
 EXTERNC void mylibrary_mytype_destroy(mylibrary_mytype_t mytype);
 EXTERNC void mylibrary_mytype_doit(mylibrary_mytype_t self, int param);

 #undef EXTERNC
 // ...


 // *.cpp file
 mylibrary_mytype_t mylibrary_mytype_init() {
   return new MyType;
 }

 void mylibrary_mytype_destroy(mylibrary_mytype_t untyped_ptr) {
    MyType* typed_ptr = static_cast<MyType*>(untyped_ptr);
    delete typed_ptr;
 }

 void mylibrary_mytype_doit(mylibrary_mytype_t untyped_self, int param) {
    MyType* typed_self = static_cast<MyType*>(untyped_self);
    typed_self->doIt(param);
 }

NodeJS - What does "socket hang up" actually mean?

Ran into this issue yesterday running my web application and node.js server through IntelliJ IDEA 2016.3.6. All I had to do was clear my cookies and cache in my Chrome browser.

how to add <script>alert('test');</script> inside a text box?

is you want fix XSS on input element? you can encode string before output to input field

PHP:

$str = htmlentities($str);

C#:

str = WebUtility.HtmlEncode(str);

after that output value direct to input field:

<input type="text" value="<?php echo $str" />

header('HTTP/1.0 404 Not Found'); not doing anything

i think this will help you

content of .htaccess

ErrorDocument 404 /error.php
ErrorDocument 400 /error.php
ErrorDocument 401 /error.php
ErrorDocument 403 /error.php
ErrorDocument 405 /error.php
ErrorDocument 406 /error.php
ErrorDocument 409 /error.php
ErrorDocument 413 /error.php
ErrorDocument 414 /error.php
ErrorDocument 500 /error.php
ErrorDocument 501 /error.php

error.php and .htaccess should be put in the same directory [in this case]

PHP CURL CURLOPT_SSL_VERIFYPEER ignored

According to documentation: to verify host or peer certificate you need to specify alternate certificates with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option.

Also look at CURLOPT_SSL_VERIFYHOST:

  • 1 to check the existence of a common name in the SSL peer certificate.
  • 2 to check the existence of a common name and also verify that it matches the hostname provided.

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

Log4j2 configuration - No log4j2 configuration file found

Is this a simple eclipse java project without maven etc? In that case you will need to put the log4j2.xml file under src folder in order to be able to find it on the classpath. If you use maven put it under src/main/resources or src/test/resources

How do I calculate r-squared using Python and Numpy?

I originally posted the benchmarks below with the purpose of recommending numpy.corrcoef, foolishly not realizing that the original question already uses corrcoef and was in fact asking about higher order polynomial fits. I've added an actual solution to the polynomial r-squared question using statsmodels, and I've left the original benchmarks, which while off-topic, are potentially useful to someone.


statsmodels has the capability to calculate the r^2 of a polynomial fit directly, here are 2 methods...

import statsmodels.api as sm
import statsmodels.formula.api as smf

# Construct the columns for the different powers of x
def get_r2_statsmodels(x, y, k=1):
    xpoly = np.column_stack([x**i for i in range(k+1)])    
    return sm.OLS(y, xpoly).fit().rsquared

# Use the formula API and construct a formula describing the polynomial
def get_r2_statsmodels_formula(x, y, k=1):
    formula = 'y ~ 1 + ' + ' + '.join('I(x**{})'.format(i) for i in range(1, k+1))
    data = {'x': x, 'y': y}
    return smf.ols(formula, data).fit().rsquared # or rsquared_adj

To further take advantage of statsmodels, one should also look at the fitted model summary, which can be printed or displayed as a rich HTML table in Jupyter/IPython notebook. The results object provides access to many useful statistical metrics in addition to rsquared.

model = sm.OLS(y, xpoly)
results = model.fit()
results.summary()

Below is my original Answer where I benchmarked various linear regression r^2 methods...

The corrcoef function used in the Question calculates the correlation coefficient, r, only for a single linear regression, so it doesn't address the question of r^2 for higher order polynomial fits. However, for what it's worth, I've come to find that for linear regression, it is indeed the fastest and most direct method of calculating r.

def get_r2_numpy_corrcoef(x, y):
    return np.corrcoef(x, y)[0, 1]**2

These were my timeit results from comparing a bunch of methods for 1000 random (x, y) points:

  • Pure Python (direct r calculation)
    • 1000 loops, best of 3: 1.59 ms per loop
  • Numpy polyfit (applicable to n-th degree polynomial fits)
    • 1000 loops, best of 3: 326 µs per loop
  • Numpy Manual (direct r calculation)
    • 10000 loops, best of 3: 62.1 µs per loop
  • Numpy corrcoef (direct r calculation)
    • 10000 loops, best of 3: 56.6 µs per loop
  • Scipy (linear regression with r as an output)
    • 1000 loops, best of 3: 676 µs per loop
  • Statsmodels (can do n-th degree polynomial and many other fits)
    • 1000 loops, best of 3: 422 µs per loop

The corrcoef method narrowly beats calculating the r^2 "manually" using numpy methods. It is >5X faster than the polyfit method and ~12X faster than the scipy.linregress. Just to reinforce what numpy is doing for you, it's 28X faster than pure python. I'm not well-versed in things like numba and pypy, so someone else would have to fill those gaps, but I think this is plenty convincing to me that corrcoef is the best tool for calculating r for a simple linear regression.

Here's my benchmarking code. I copy-pasted from a Jupyter Notebook (hard not to call it an IPython Notebook...), so I apologize if anything broke on the way. The %timeit magic command requires IPython.

import numpy as np
from scipy import stats
import statsmodels.api as sm
import math

n=1000
x = np.random.rand(1000)*10
x.sort()
y = 10 * x + (5+np.random.randn(1000)*10-5)

x_list = list(x)
y_list = list(y)

def get_r2_numpy(x, y):
    slope, intercept = np.polyfit(x, y, 1)
    r_squared = 1 - (sum((y - (slope * x + intercept))**2) / ((len(y) - 1) * np.var(y, ddof=1)))
    return r_squared
    
def get_r2_scipy(x, y):
    _, _, r_value, _, _ = stats.linregress(x, y)
    return r_value**2
    
def get_r2_statsmodels(x, y):
    return sm.OLS(y, sm.add_constant(x)).fit().rsquared
    
def get_r2_python(x_list, y_list):
    n = len(x_list)
    x_bar = sum(x_list)/n
    y_bar = sum(y_list)/n
    x_std = math.sqrt(sum([(xi-x_bar)**2 for xi in x_list])/(n-1))
    y_std = math.sqrt(sum([(yi-y_bar)**2 for yi in y_list])/(n-1))
    zx = [(xi-x_bar)/x_std for xi in x_list]
    zy = [(yi-y_bar)/y_std for yi in y_list]
    r = sum(zxi*zyi for zxi, zyi in zip(zx, zy))/(n-1)
    return r**2
    
def get_r2_numpy_manual(x, y):
    zx = (x-np.mean(x))/np.std(x, ddof=1)
    zy = (y-np.mean(y))/np.std(y, ddof=1)
    r = np.sum(zx*zy)/(len(x)-1)
    return r**2
    
def get_r2_numpy_corrcoef(x, y):
    return np.corrcoef(x, y)[0, 1]**2
    
print('Python')
%timeit get_r2_python(x_list, y_list)
print('Numpy polyfit')
%timeit get_r2_numpy(x, y)
print('Numpy Manual')
%timeit get_r2_numpy_manual(x, y)
print('Numpy corrcoef')
%timeit get_r2_numpy_corrcoef(x, y)
print('Scipy')
%timeit get_r2_scipy(x, y)
print('Statsmodels')
%timeit get_r2_statsmodels(x, y)

Best way to clear a PHP array's values

Sadly I can't answer the other questions, don't have enough reputation, but I need to point something out that was VERY important for me, and I think it will help other people too.

Unsetting the variable is a nice way, unless you need the reference of the original array!

To make clear what I mean: If you have a function wich uses the reference of the array, for example a sorting function like

function special_sort_my_array(&$array)
{
    $temporary_list = create_assoziative_special_list_out_of_array($array);

    sort_my_list($temporary_list);

    unset($array);
    foreach($temporary_list as $k => $v)
    {
        $array[$k] = $v;
    }
}

it is not working! Be careful here, unset deletes the reference, so the variable $array is created again and filled correctly, but the values are not accessable from outside the function.

So if you have references, you need to use $array = array() instead of unset, even if it is less clean and understandable.

javascript regex - look behind alternative?

This is an equivalent solution to Tim Pietzcker's answer (see also comments of same answer):

^(?!.*filename\.js$).*\.js$

It means, match *.js except *filename.js.

To get to this solution, you can check which patterns the negative lookbehind excludes, and then exclude exactly these patterns with a negative lookahead.

iOS 7.0 No code signing identities found

My fix for this problem was:

Xcode > Preferences. In Accounts click on your Apple ID. Click View Details, click on your projects Provisioning Profile (I think this helps) and click the refresh button bottom left.

vertical alignment of text element in SVG

According to SVG spec, alignment-baseline only applies to <tspan>, <textPath>, <tref> and <altGlyph>. My understanding is that it is used to offset those from the <text> object above them. I think what you are looking for is dominant-baseline.

Possible values of dominant-baseline are:

auto | use-script | no-change | reset-size | ideographic | alphabetic | hanging | mathematical | central | middle | text-after-edge | text-before-edge | inherit

Check the W3C recommendation for the dominant-baseline property for more information about each possible value.

Using Cygwin to Compile a C program; Execution error

Regarding the cygwin1.dll not found error, a solution I have used for at least 8 years is to add the Cygwin bin directories to the end of my %PATH% in My Computer -> Properties -> Advanced -> Environment Variables. I add them to the end of the path so in my normal work, they are searched last, minimizing the possibility of conflicts (in fact, I have had no problems with conflicts in all this time).

When you invoke the Cygwin Bash Shell, those directories get prepended to the %PATH% so everything works as intended in that environment as well.

When not running in Cygwin shell, my %PATH% is:

Path=c:\opt\perl\bin; \
     ...
     C:\opt\cygwin\bin; \
     C:\opt\cygwin\usr\bin; \
     C:\opt\cygwin\usr\local\bin;

This way, for example, ActiveState Perl's perl is found first when I am not in a Cygwin Shell, but the Cygwin perl is found when I am working in the Cygwin Shell.

How to Get XML Node from XDocument

The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:

XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
                    where xml2.Element("ID").Value == variable
                    select xml2).FirstOrDefault();

This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.

Marc

How to emit an event from parent to child?

Within the parent, you can reference the child using @ViewChild. When needed (i.e. when the event would be fired), you can just execute a method in the child from the parent using the @ViewChild reference.