Programs & Examples On #Ajdt

AJDT stands for AspectJ Development Tools, an Eclipse plug-in for Aspect Oriented Software Development in Java.

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

I had to delete Tomcat's work directory as it had cached previously generated files. To do this:

  1. Stop Tomcat
  2. Delete the 'work' directory
  3. Start Tomcat

This will cause the work directory to be newly generated.

Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

If you are going with Custom Static Cells just comment this method:

//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    static NSString *CellIdentifier = @"notificationCell";
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
//    return cell;

and give the cells an identifier at "Attributes Inspector" in storyboard.

TokenMismatchException in VerifyCsrfToken.php Line 67

You can solve by delete the line. go to app\http\kernel.php, here you can see the line \App\Http\Middleware\VerifyCsrfToken::class, This worked for me.

No Multiline Lambda in Python: Why not?

Let me try to tackle @balpha parsing problem. I would use parentheses around the multiline lamda. If there is no parentheses, the lambda definition is greedy. So the lambda in

map(lambda x:
      y = x+1
      z = x-1

returns a function that returns (y*z, [1,2,3])


map((lambda x:
      y = x+1
      z = x-1


map(func, [1,2,3])

where func is the multiline lambda that return y*z. Does that work?

What is a practical, real world example of the Linked List?

In the .NET BCL, the class System.Exception has a property called InnerException, which points to another exception or else is null. This forms a linked list.

In System.Type, the BaseType property points to another type in the same way.

How to customize Bootstrap 3 tab color

.panel.with-nav-tabs .panel-heading {_x000D_
  padding: 5px 5px 0 5px;_x000D_
.panel.with-nav-tabs .nav-tabs {_x000D_
  border-bottom: none;_x000D_
.panel.with-nav-tabs .nav-justified {_x000D_
  margin-bottom: -1px;_x000D_
/*** PANEL DEFAULT ***/_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:focus {_x000D_
  color: #777;_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:focus {_x000D_
  color: #777;_x000D_
  background-color: #ddd;_x000D_
  border-color: transparent;_x000D_
.with-nav-tabs.panel-default .nav-tabs>>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>>a:focus {_x000D_
  color: #555;_x000D_
  background-color: #fff;_x000D_
  border-color: #ddd;_x000D_
  border-bottom-color: transparent;_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #f5f5f5;_x000D_
  border-color: #ddd;_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #777;_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #ddd;_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #555;_x000D_
/*** PANEL PRIMARY ***/_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:focus {_x000D_
  color: #fff;_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #3071a9;_x000D_
  border-color: transparent;_x000D_
.with-nav-tabs.panel-primary .nav-tabs>>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>>a:focus {_x000D_
  color: #428bca;_x000D_
  background-color: #fff;_x000D_
  border-color: #428bca;_x000D_
  border-bottom-color: transparent;_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #428bca;_x000D_
  border-color: #3071a9;_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #fff;_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #3071a9;_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  background-color: #4a9fe9;_x000D_
/*** PANEL SUCCESS ***/_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:focus {_x000D_
  color: #3c763d;_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:focus {_x000D_
  color: #3c763d;_x000D_
  background-color: #d6e9c6;_x000D_
  border-color: transparent;_x000D_
.with-nav-tabs.panel-success .nav-tabs>>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>>a:focus {_x000D_
  color: #3c763d;_x000D_
  background-color: #fff;_x000D_
  border-color: #d6e9c6;_x000D_
  border-bottom-color: transparent;_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #dff0d8;_x000D_
  border-color: #d6e9c6;_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #3c763d;_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #d6e9c6;_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #3c763d;_x000D_
/*** PANEL INFO ***/_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:focus {_x000D_
  color: #31708f;_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:focus {_x000D_
  color: #31708f;_x000D_
  background-color: #bce8f1;_x000D_
  border-color: transparent;_x000D_
.with-nav-tabs.panel-info .nav-tabs>>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>>a:focus {_x000D_
  color: #31708f;_x000D_
  background-color: #fff;_x000D_
  border-color: #bce8f1;_x000D_
  border-bottom-color: transparent;_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #d9edf7;_x000D_
  border-color: #bce8f1;_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #31708f;_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #bce8f1;_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #31708f;_x000D_
/*** PANEL WARNING ***/_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:focus {_x000D_
  color: #8a6d3b;_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:focus {_x000D_
  color: #8a6d3b;_x000D_
  background-color: #faebcc;_x000D_
  border-color: transparent;_x000D_
.with-nav-tabs.panel-warning .nav-tabs>>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>>a:focus {_x000D_
  color: #8a6d3b;_x000D_
  background-color: #fff;_x000D_
  border-color: #faebcc;_x000D_
  border-bottom-color: transparent;_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #fcf8e3;_x000D_
  border-color: #faebcc;_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #8a6d3b;_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #faebcc;_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #8a6d3b;_x000D_
/*** PANEL DANGER ***/_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:focus {_x000D_
  color: #a94442;_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:focus {_x000D_
  color: #a94442;_x000D_
  background-color: #ebccd1;_x000D_
  border-color: transparent;_x000D_
.with-nav-tabs.panel-danger .nav-tabs>>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>>a:focus {_x000D_
  color: #a94442;_x000D_
  background-color: #fff;_x000D_
  border-color: #ebccd1;_x000D_
  border-bottom-color: transparent;_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #f2dede;_x000D_
  /* bg color */_x000D_
  border-color: #ebccd1;_x000D_
  /* border color */_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #a94442;_x000D_
  /* normal text color */_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #ebccd1;_x000D_
  /* hover bg color */_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  /* active text color */_x000D_
  background-color: #a94442;_x000D_
  /* active bg color */_x000D_
<script src=""></script>_x000D_
<link href="//" rel="stylesheet" id="bootstrap-css">_x000D_
<script src="//"></script>_x000D_
<!------ Include the above in your HEAD tag ---------->_x000D_
<div class="container">_x000D_
  <div class="page-header">_x000D_
    <h1>Panels with nav tabs.<span class="pull-right label label-default">:)</span></h1>_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-default">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1default" data-toggle="tab">Default 1</a></li>_x000D_
            <li><a href="#tab2default" data-toggle="tab">Default 2</a></li>_x000D_
            <li><a href="#tab3default" data-toggle="tab">Default 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4default" data-toggle="tab">Default 4</a></li>_x000D_
                <li><a href="#tab5default" data-toggle="tab">Default 5</a></li>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1default">Default 1</div>_x000D_
            <div class="tab-pane fade" id="tab2default">Default 2</div>_x000D_
            <div class="tab-pane fade" id="tab3default">Default 3</div>_x000D_
            <div class="tab-pane fade" id="tab4default">Default 4</div>_x000D_
            <div class="tab-pane fade" id="tab5default">Default 5</div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-primary">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1primary" data-toggle="tab">Primary 1</a></li>_x000D_
            <li><a href="#tab2primary" data-toggle="tab">Primary 2</a></li>_x000D_
            <li><a href="#tab3primary" data-toggle="tab">Primary 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4primary" data-toggle="tab">Primary 4</a></li>_x000D_
                <li><a href="#tab5primary" data-toggle="tab">Primary 5</a></li>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1primary">Primary 1</div>_x000D_
            <div class="tab-pane fade" id="tab2primary">Primary 2</div>_x000D_
            <div class="tab-pane fade" id="tab3primary">Primary 3</div>_x000D_
            <div class="tab-pane fade" id="tab4primary">Primary 4</div>_x000D_
            <div class="tab-pane fade" id="tab5primary">Primary 5</div>_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-success">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1success" data-toggle="tab">Success 1</a></li>_x000D_
            <li><a href="#tab2success" data-toggle="tab">Success 2</a></li>_x000D_
            <li><a href="#tab3success" data-toggle="tab">Success 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4success" data-toggle="tab">Success 4</a></li>_x000D_
                <li><a href="#tab5success" data-toggle="tab">Success 5</a></li>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1success">Success 1</div>_x000D_
            <div class="tab-pane fade" id="tab2success">Success 2</div>_x000D_
            <div class="tab-pane fade" id="tab3success">Success 3</div>_x000D_
            <div class="tab-pane fade" id="tab4success">Success 4</div>_x000D_
            <div class="tab-pane fade" id="tab5success">Success 5</div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-info">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1info" data-toggle="tab">Info 1</a></li>_x000D_
            <li><a href="#tab2info" data-toggle="tab">Info 2</a></li>_x000D_
            <li><a href="#tab3info" data-toggle="tab">Info 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4info" data-toggle="tab">Info 4</a></li>_x000D_
                <li><a href="#tab5info" data-toggle="tab">Info 5</a></li>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1info">Info 1</div>_x000D_
            <div class="tab-pane fade" id="tab2info">Info 2</div>_x000D_
            <div class="tab-pane fade" id="tab3info">Info 3</div>_x000D_
            <div class="tab-pane fade" id="tab4info">Info 4</div>_x000D_
            <div class="tab-pane fade" id="tab5info">Info 5</div>_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-warning">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1warning" data-toggle="tab">Warning 1</a></li>_x000D_
            <li><a href="#tab2warning" data-toggle="tab">Warning 2</a></li>_x000D_
            <li><a href="#tab3warning" data-toggle="tab">Warning 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4warning" data-toggle="tab">Warning 4</a></li>_x000D_
                <li><a href="#tab5warning" data-toggle="tab">Warning 5</a></li>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1warning">Warning 1</div>_x000D_
            <div class="tab-pane fade" id="tab2warning">Warning 2</div>_x000D_
            <div class="tab-pane fade" id="tab3warning">Warning 3</div>_x000D_
            <div class="tab-pane fade" id="tab4warning">Warning 4</div>_x000D_
            <div class="tab-pane fade" id="tab5warning">Warning 5</div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-danger">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1danger" data-toggle="tab">Danger 1</a></li>_x000D_
            <li><a href="#tab2danger" data-toggle="tab">Danger 2</a></li>_x000D_
            <li><a href="#tab3danger" data-toggle="tab">Danger 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4danger" data-toggle="tab">Danger 4</a></li>_x000D_
                <li><a href="#tab5danger" data-toggle="tab">Danger 5</a></li>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1danger">Danger 1</div>_x000D_
            <div class="tab-pane fade" id="tab2danger">Danger 2</div>_x000D_
            <div class="tab-pane fade" id="tab3danger">Danger 3</div>_x000D_
            <div class="tab-pane fade" id="tab4danger">Danger 4</div>_x000D_
            <div class="tab-pane fade" id="tab5danger">Danger 5</div>_x000D_

Required maven dependencies for Apache POI to work

this is the list of maven artifact id for all poi component. in this link

How can I merge two MySQL tables?

It depends on the semantic of the primary key. If it's just autoincrement, then use something like:

insert into table1 (all columns except pk)
select all_columns_except_pk 
from table2;

If PK means something, you need to find a way to determine which record should have priority. You could create a select query to find duplicates first (see answer by cpitis). Then eliminate the ones you don't want to keep and use the above insert to add records that remain.

Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments

onActivityCreated() - Deprecated

onActivityCreated() is now deprecated as Fragments Version 1.3.0-alpha02

The onActivityCreated() method is now deprecated. Code touching the fragment's view should be done in onViewCreated() (which is called immediately before onActivityCreated()) and other initialization code should be in onCreate(). To receive a callback specifically when the activity's onCreate() is complete, a LifeCycleObserver should be registered on the activity's Lifecycle in onAttach(), and removed once the onCreate() callback is received.

Detailed information can be found here

Adding a column to an existing table in a Rails migration

You can also force to table columns in table using force: true, if you table is already exist.


ActiveRecord::Schema.define(version: 20080906171750) do
  create_table "authors", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"

Google maps responsive resize

Move your map variable into a scope where the event listener can use it. You are creating the map inside your initialize() function and nothing else can use it when created that way.

var map; //<-- This is now available to both event listeners and the initialize() function
function initialize() {
  var mapOptions = {
   center: new google.maps.LatLng(40.5472,12.282715),
   zoom: 6,
   mapTypeId: google.maps.MapTypeId.ROADMAP
  map = new google.maps.Map(document.getElementById("map-canvas"),
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
 var center = map.getCenter();
 google.maps.event.trigger(map, "resize");

What is the equivalent of Select Case in Access SQL?

You could do below:

iif ( OpeningBalance>=0 And OpeningBalance<=500 , 20, 

                  iif ( OpeningBalance>=5001 And OpeningBalance<=10000 , 30, 

                       iif ( OpeningBalance>=10001 And OpeningBalance<=20000 , 40, 

50 ) ) ) as commission
from table

What is the JavaScript version of sleep()?

The problem with using an actual sleep function is that JavaScript is single-threaded and a sleep function will pretty much make your browser tab hang for that duration.

Table cell widths - fixing width, wrapping/truncating long words

<style type="text/css">
td { word-wrap: break-word;max-width:50px; }            

How to open maximized window with Javascript?'your_url', 'popup_name','height=' + screen.height + ',width=' + screen.width + ',resizable=yes,scrollbars=yes,toolbar=yes,menubar=yes,location=yes')

How to load a text file into a Hive table stored as sequence files

You can load the text file into a textfile Hive table and then insert the data from this table into your sequencefile.

Start with a tab delimited file:

% cat /tmp/input.txt
a       b
a2      b2

create a sequence file

hive> create table test_sq(k string, v string) stored as sequencefile;

try to load; as expected, this will fail:

hive> load data local inpath '/tmp/input.txt' into table test_sq;

But with this table:

hive> create table test_t(k string, v string) row format delimited fields terminated by '\t' stored as textfile;

The load works just fine:

hive> load data local inpath '/tmp/input.txt' into table test_t;
hive> select * from test_t;
a       b
a2      b2

Now load into the sequence table from the text table:

insert into table test_sq select * from test_t;

Can also do load/insert with overwrite to replace all.

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

Gwerder's solution wont work because hash =; happens before the stream is done being finalized. Thus AngraX's issues. Also the hmac.write statement is un-necessary in this example.

Instead do this:

var crypto    = require('crypto');
var hmac;
var algorithm = 'sha1';
var key       = 'abcdeg';
var text      = 'I love cupcakes';
var hash;

hmac = crypto.createHmac(algorithm, key);

// readout format:
//or also commonly: hmac.setEncoding('base64');

// callback is attached as listener to stream's finish event:
hmac.end(text, function () {
    hash =;
    // something with the hash...

More formally, if you wish, the line

hmac.end(text, function () {

could be written

hmac.end(text, 'utf8', function () {

because in this example text is a utf string

How can I display an RTSP video stream in a web page?

Also you can try opensource WebRTC Media Server Kurento

Which can play RTSP video stream and send it to WebRTC or transcode to RTMP or saving on server.

We are useing it on Production for the following cases:

 - WebRTC to Webrtc (many to many)
 - WebRTC to RTMP
 - RTSP to WebRTC

How to write LaTeX in IPython Notebook?

I developed prettyPy, which offers a nice way to print equation. Unfortunately, it's not performant and needs testing.


enter image description here

Granted, sympy is a great alternative and although prettyPy doesn't allow for evaluating expressions, variable initialization is not required.

add/remove active class for ul list with jquery?

    $('.cliked').click(function() {_x000D_
.liactive {_x000D_
    background: orange;_x000D_
<script src=""></script>_x000D_
  className="sidebar-nav position-fixed "_x000D_
        <a className="cliked liactive" href="#">_x000D_
            check Kyc Status_x000D_
        <a className="cliked" href="#">_x000D_
            My Investments_x000D_
        <a className="cliked" href="#">_x000D_
            My SIP_x000D_
        <a className="cliked" href="#">_x000D_
            My Tax Savers Fund_x000D_
        <a className="cliked" href="#">_x000D_
            Transaction History_x000D_
        <a className="cliked" href="#">_x000D_
            Invest Now_x000D_
        <a className="cliked" href="#">_x000D_
            My Profile_x000D_
        <a className="cliked" href="#">_x000D_
        <a className="cliked" href="#">_x000D_
            Suggestion Portfolio_x000D_
        <a className="cliked" href="#">_x000D_
            Bluk Lumpsum / Bulk SIP_x000D_

System.IO.IOException: file used by another process

The code works as best I can tell. I would fire up Sysinternals process explorer and find out what is holding the file open. It might very well be Visual Studio.

Writing files in Node.js

Point 1:

If you want to write something into a file. means: it will remove anything already saved in the file and write the new content. use fs.promises.writeFile()

Point 2:

If you want to append something into a file. means: it will not remove anything already saved in the file but append the new item in the file content.then first read the file, and then add the content into the readable value, then write it to the file. so use fs.promises.readFile and fs.promises.writeFile()

example 1: I want to write a JSON object in my JSON file .

const fs = require('fs');
writeFile  ('./my_data.json' , {id:1, name:'my name'} )
async function writeFile  (filename ,writedata) {
    try {
        await fs.promises.writeFile(filename, JSON.stringify(writedata,null, 4), 'utf8');
       console.log ('data is written successfully in the file')
    catch(err) {
        console.log ('not able to write data in the file ')

example2 : if you want to append data to a JSON file. you want to add data {id:1, name:'my name'} to file my_data.json on the same folder root. just call append_data (file_path , data ) function.

It will append data in the JSON file if the file existed . or it will create the file and add the data to it.

   const fs = require('fs');
   data = {id:1, name:'my name'}
   file_path = './my_data.json'
   append_data (file_path , data )

   async function append_data (filename , data ) {

      if (fs.existsSync(filename)) {
         read_data = await readFile(filename)
         if (read_data == false) {
             console.log('not able to read file')
         else {
             dataWrittenStatus = await writeFile(filename, read_data)
             if dataWrittenStatus == true {
               console.log('data added successfully')
               console.log('data adding failed')
          dataWrittenStatus = await writeFile(filename, [data])
          if dataWrittenStatus == true {
             console.log('data added successfully')
             console.log('data adding failed')

async function readFile  (filePath) {
  try {
    const data = await fs.promises.readFile(filePath, 'utf8')
    return JSON.parse(data)
 catch(err) {
     return false;

async function writeFile  (filename ,writedata) {
  try {
      await fs.promises.writeFile(filename, JSON.stringify(writedata,null, 4), 'utf8');
      return true
  catch(err) {
      return false

How do I set the colour of a label (coloured text) in Java?

One of the disadvantages of using HTML for labels is when you need to write a localizable program (which should work in several languages). You will have issues to change just the translatable text. Or you will have to put the whole HTML code into your translations which is very awkward, I would even say absurd :)

title.text=<html>Text color: <font color='red'>red</font></html>

title.text=<html>Couleur du texte: <font color='red'>rouge</font></html>

title.text=<html>???? ??????: <font color='red'>???????</font></html>

What does the "map" method do in Ruby?


#each runs a function for each element in an array. The following two code excerpts are equivalent:

x = 10
["zero", "one", "two"].each{|element|
    puts element
x = 10
array = ["zero", "one", "two"]

for i in 0..2
    puts array[i]


#map applies a function to each element of an array, returning the resulting array. The following are equivalent:

array = ["zero", "one", "two"]
newArray ={|element| element.capitalize()}
array = ["zero", "one", "two"]

newArray = []
    newArray << element.capitalize()


#map! is like #map, but modifies the array in place. The following are equivalent:

array = ["zero", "one", "two"]!{|element| element.capitalize()}
array = ["zero", "one", "two"]
array ={|element| element.capitalize()}

Find a pair of elements from an array whose sum equals a given number

Nice solution from Codeaddict. I took the liberty of implementing a version of it in Ruby:

def find_sum(arr,sum)
 result ={}
 h = Hash[ {|i| [i,i]}]
 arr.each { |l| result[l] = sum-l  if h[sum-l] && !result[sum-l]  }

To allow duplicate pairs (1,5), (5,1) we just have to remove the && !result[sum-l] instruction

How to clear browser cache with php?

It seams you need to versionate, so when some change happens browser will catch something new and user won't need to clear browser's cache.

You can do it by subfolders (example /css/v1/style.css) or by filename (example: css/style_v1.css) or even by setting different folders for your website, example:

And use a .htaccess or even change httpd.conf to redirect to your current application.

If's about one image or page:

    <?$time = date("H:i:s");?>
    <img src="myfile.jpg?time=<?$time;?>">

You can use $time on parts when you don't wanna cache. So it will always pull a new image. Versionate it seams a better approach, otherwise it can overload your server. Remember, browser's cache it's not only good to user experience, but also for your server.

Best XML Parser for PHP

I would have to say SimpleXML takes the cake because it is firstly an extension, written in C, and is very fast. But second, the parsed document takes the form of a PHP object. So you can "query" like $root->myElement.

Windows equivalent to UNIX pwd

cd without any parameters is equivalent to pwd on Unix/Linux.

From the console output of typing cd /?:

Displays the name of or changes the current directory.


Type CD without parameters to display the current drive and directory.

Maven version with a property

The version of the pom.xml should be valid

<version>2.2.4 SNAPSHOT</version>

This version should not be like 2.2.4. etc

Pyspark: display a spark data frame in a table format

As mentioned by @Brent in the comment of @maxymoo's answer, you can try


to get a prettier table in Jupyter. But this can take some time to run if you are not caching the spark dataframe. Also, .limit() will not keep the order of original spark dataframe.

How can I make a horizontal ListView in Android?

Have you looked into using a HorizontalScrollView to wrap your list items? That will allow each of your list items to be horizontally scrollable (what you put in there is up to you, and can make them dynamic items similar to ListView). This will work well if you are only after a single row of items.

Check if a Postgres JSON array contains a string

A small variation but nothing new infact. It's really missing a feature...

select info->>'name' from rabbits 
where '"carrots"' = ANY (ARRAY(
    select * from json_array_elements(info->'food'))::text[]);

Sorting a set of values

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.

You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.

* See the comments for exceptions.

What is the keyguard in Android?

Yes, I also found it here: It's seems a key-input protection mechanism which includes the screen-lock, but not only includes it. According to this webpage, it also defines some key-input restriction for auto-test framework in Android.

Create a folder inside documents folder in iOS apps

I don't have enough reputation to comment on Manni's answer, but [paths objectAtIndex:0] is the standard way of getting the application's Documents Directory

Because the NSSearchPathForDirectoriesInDomains function was designed originally for Mac OS X, where there could be more than one of each of these directories, it returns an array of paths rather than a single path. In iOS, the resulting array should contain the single path to the directory. Listing 3-1 shows a typical use of this function.

Listing 3-1 Getting the path to the application’s Documents directory

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

Thread.sleep can throw an InterruptedException which is a checked exception. All checked exceptions must either be caught and handled or else you must declare that your method can throw it. You need to do this whether or not the exception actually will be thrown. Not declaring a checked exception that your method can throw is a compile error.

You either need to catch it:

try {
} catch (InterruptedException e) {
    // handle the exception...        
    // For example consider calling Thread.currentThread().interrupt(); here.

Or declare that your method can throw an InterruptedException:

public static void main(String[]args) throws InterruptedException


Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

If this occurs IE intranet only, check compatibility settings and uncheck "Display intranet sites in Compatibility mode" .


enter image description here

How to filter Pandas dataframe using 'in' and 'not in' like in SQL

You can use pd.Series.isin.

For "IN" use: something.isin(somewhere)

Or for "NOT IN": ~something.isin(somewhere)

As a worked example:

import pandas as pd

>>> df
0        US
1        UK
2   Germany
3     China
>>> countries_to_keep
['UK', 'China']
0    False
1     True
2    False
3     True
Name: country, dtype: bool
>>> df[]
1        UK
3     China
>>> df[]
0        US
2   Germany

Get the current file name in gulp.src()

You can use the gulp-filenames module to get the array of paths. You can even group them by namespaces:

var filenames = require("gulp-filenames");



filenames.get("coffeescript") // ["",""]  
                              // Do Something With it 

Refresh Part of Page (div)

Use Ajax for this.

Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.

Relevant function:


$('#thisdiv').load(document.URL +  ' #thisdiv');

Note, load automatically replaces content. Be sure to include a space before the id selector.

How can I get a resource content from a static context?

I am using API level 27 and found a best solution after struggling for around two days. If you want to read a xml file from a class which doesn't derive from Activity or Application then do the following.

  1. Put the testdata.xml file inside the assets directory.

  2. Write the following code to get the testdata document parsed.

        InputStream inputStream = this.getClass().getResourceAsStream("/assets/testdata.xml");
        // create a new DocumentBuilderFactory
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // use the factory to create a documentbuilder
        DocumentBuilder builder = factory.newDocumentBuilder();
        // create a new document from input stream
        Document doc = builder.parse(inputStream);

What is the difference between HTTP_HOST and SERVER_NAME in PHP?

Depends what I want to find out. SERVER_NAME is the host name of the server, whilst HTTP_HOST is the virtual host that the client connected to.

Putting -moz-available and -webkit-fill-available in one width (css property)

I needed my ASP.NET drop down list to take up all available space, and this is all I put in the CSS and it is working in Firefox and IE11:

width: 100%

I had to add the CSS class into the asp:DropDownList element

How to sort an array in descending order in Ruby

You could do:

a.sort{|a,b| b[:bar] <=> a[:bar]}

Execution order of events when pressing PrimeFaces p:commandButton

It failed because you used ajax="false". This fires a full synchronous request which in turn causes a full page reload, causing the oncomplete to be never fired (note that all other ajax-related attributes like process, onstart, onsuccess, onerror and update are also never fired).

That it worked when you removed actionListener is also impossible. It should have failed the same way. Perhaps you also removed ajax="false" along it without actually understanding what you were doing. Removing ajax="false" should indeed achieve the desired requirement.

Also is it possible to execute actionlistener and oncomplete simultaneously?

No. The script can only be fired before or after the action listener. You can use onclick to fire the script at the moment of the click. You can use onstart to fire the script at the moment the ajax request is about to be sent. But they will never exactly simultaneously be fired. The sequence is as follows:

  • User clicks button in client
  • onclick JavaScript code is executed
  • JavaScript prepares ajax request based on process and current HTML DOM tree
  • onstart JavaScript code is executed
  • JavaScript sends ajax request from client to server
  • JSF retrieves ajax request
  • JSF processes the request lifecycle on JSF component tree based on process
  • actionListener JSF backing bean method is executed
  • action JSF backing bean method is executed
  • JSF prepares ajax response based on update and current JSF component tree
  • JSF sends ajax response from server to client
  • JavaScript retrieves ajax response
    • if HTTP response status is 200, onsuccess JavaScript code is executed
    • else if HTTP response status is 500, onerror JavaScript code is executed
  • JavaScript performs update based on ajax response and current HTML DOM tree
  • oncomplete JavaScript code is executed

Note that the update is performed after actionListener, so if you were using onclick or onstart to show the dialog, then it may still show old content instead of updated content, which is poor for user experience. You'd then better use oncomplete instead to show the dialog. Also note that you'd better use action instead of actionListener when you intend to execute a business action.

See also:

iFrame Height Auto (CSS)

This is my PURE CSS solution :)

Add, scrolling yes to your iframe.

<iframe src="your iframe link" width="100%" scrolling="yes" frameborder="0"></iframe>

The trick :)

    html, body, iframe { height: 100%; }
    html { overflow: hidden; }

You don't need to worry about responsiveness :)

How/when to generate Gradle wrapper files?

As of Gradle 2.4, you can use gradle wrapper --gradle-version X.X to configure a specific version of the Gradle wrapper, without adding any tasks to your build.gradle file. The next time you use the wrapper, it will download the appropriate Gradle distribution to match.

Adding a stylesheet to (using Visual Studio 2010)

The only thing you have to do is to add in the cshtml file, in the head, the following line:


The entire head will look somethink like that:

         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
         <title>HTML Page</title>

Hope it helps!!

ASP.NET Web API session or something?

You can use cookies if the data is small enough and does not present a security concern. The same HttpContext.Current based approach should work.

Request and response HTTP headers can also be used to pass information between service calls.

How can I display two div in one line via css inline property

You don't need to use display:inline to achieve this:

.inline { 
    border: 1px solid red;
    float:left;/*Add float left*/
    margin :10px;

You can use float-left.

Using float:left is best way to place multiple div elements in one line. Why? Because inline-block does have some problem when is viewed in IE older versions.


httpd Server not started: (13)Permission denied: make_sock: could not bind to address [::]:88

In Linux(Centos 6 or higher) ports from 0 to 1024 are reserved for system use. you can force the system to bind to address any port lower than 1024 if you use root or privileged user.

I installed Apache-2.4 from source with non-root user and I solved this problem by allowing port higher than 1024(ex:8080) and modified http.conf file. chang Listen 80 to Listen 8080

What is the correct syntax of ng-include?

On ng-build, file not found(404) error occur. So we can use below code

<ng-include src="'views/transaction/test.html'"></ng-include>

insted of,

<div ng-include="'views/transaction/test.html'"></div>

What is the difference between print and puts?

print outputs each argument, followed by $,, to $stdout, followed by $\. It is equivalent to args.join($,) + $\

puts sets both $, and $\ to "\n" and then does the same thing as print. The key difference being that each argument is a new line with puts.

You can require 'english' to access those global variables with user-friendly names.

What is the proper way to re-attach detached objects in Hibernate?

All of these answers miss an important distinction. update() is used to (re)attach your object graph to a Session. The objects you pass it are the ones that are made managed.

merge() is actually not a (re)attachment API. Notice merge() has a return value? That's because it returns you the managed graph, which may not be the graph you passed it. merge() is a JPA API and its behavior is governed by the JPA spec. If the object you pass in to merge() is already managed (already associated with the Session) then that's the graph Hibernate works with; the object passed in is the same object returned from merge(). If, however, the object you pass into merge() is detached, Hibernate creates a new object graph that is managed and it copies the state from your detached graph onto the new managed graph. Again, this is all dictated and governed by the JPA spec.

In terms of a generic strategy for "make sure this entity is managed, or make it managed", it kind of depends on if you want to account for not-yet-inserted data as well. Assuming you do, use something like

if ( session.contains( myEntity ) ) {
    // nothing to do... myEntity is already associated with the session
else {
    session.saveOrUpdate( myEntity );

Notice I used saveOrUpdate() rather than update(). If you do not want not-yet-inserted data handled here, use update() instead...

When should we call System.exit in Java

Java Language Specification says that

Program Exit

A program terminates all its activity and exits when one of two things happens:

All the threads that are not daemon threads terminate.

Some thread invokes the exit method of class Runtime or class System, and the exit operation is not forbidden by the security manager.

It means that You should use it when You have big program (well, at lest bigger than this one) and want to finish its execution.

Passing a variable from one php include file to another: global vs. not

Here is a pitfall to avoid. In case you need to access your variable $name within a function, you need to say "global $name;" at the beginning of that function. You need to repeat this for each function in the same file.

global $name;

function foo() {
  echo $name;

function bar() {
  echo $name;


will only show errors. The correct way to do that would be:


function foo() {
  global $name;
  echo $name;

function bar() {
  global $name;
  echo $name;


Change a Rails application to production

By default server runs on development environment: $ rails s

If you're running on production environment: $ rails s -e production or $ RAILS_ENV=production rails s

Variables within app.config/web.config

Usally, I end up writing a static class with properties to access each of the settings of my web.config.

public static class ConfigManager 
    public static string MyBaseDir
        return ConfigurationManager.AppSettings["MyBaseDir"].toString();

    public static string Dir1
        return MyBaseDir + ConfigurationManager.AppSettings["Dir1"].toString();


Usually, I also do type conversions when required in this class. It allows to have a typed access to your config, and if settings change, you can edit them in only one place.

Usually, replacing settings with this class is relatively easy and provides a much greater maintainability.

Task.Run with Parameter(s)?

It's unclear if the original problem was the same problem I had: wanting to max CPU threads on computation inside a loop while preserving the iterator's value and keeping inline to avoid passing a ton of variables to a worker function.

for (int i = 0; i < 300; i++)
    Task.Run(() => {
        var x = ComputeStuff(datavector, i); // value of i was incorrect
        var y = ComputeMoreStuff(x);
        // ...

I got this to work by changing the outer iterator and localizing its value with a gate.

for (int ii = 0; ii < 300; ii++)
    System.Threading.CountdownEvent handoff = new System.Threading.CountdownEvent(1);
    Task.Run(() => {
        int i = ii;

        var x = ComputeStuff(datavector, i);
        var y = ComputeMoreStuff(x);
        // ...


Border around each cell in a range

xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid

Counting in a FOR loop using Windows Batch script

It's not working because the entire for loop (from the for to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.

In other words, %count% is replaced with its value 1 before running the loop.

What you need is something like:

setlocal enableextensions enabledelayedexpansion
set /a count = 1
for /f "tokens=*" %%a in ( do (
  set /a count += 1
  echo !count!

Delayed expansion using ! instead of % will give you the expected behaviour. See also here.

Also keep in mind that setlocal/endlocal actually limit scope of things changed inside so that they don't leak out. If you want to use count after the endlocal, you have to use a "trick" made possible by the very problem you're having:

endlocal && set count=%count%

Let's say count has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:

endlocal && set count=7

Then, when it's executed, the inner scope is closed off, returning count to it's original value. But, since the setting of count to seven happens in the outer scope, it's effectively leaking the information you need.

You can string together multiple sub-commands to leak as much information as you need:

endlocal && set count=%count% && set something_else=%something_else%

Changing the URL in react-router v4 without using Redirect or Link

Try this,


warning works for versions prior to v4



for v4 and above

Vertical Text Direction

Try using an SVG file, it seems to have better browser compatibility, and won't break your responsive designs.

I tried the CSS transform, and had much trouble with the transform-origin; and ended up going with an SVG file. It took like 10 minutes, and I could control it a bit with CSS too.

You can use Inkscape to make the SVG if you don't have Adobe Illustrator.

How do I check OS with a preprocessor directive?

I did not find Haiku definition here. To be complete, Haiku-os definition is simple __HAIKU__

How to merge a specific commit in Git

You can use git cherry-pick to apply a single commit by itself to your current branch.

Example: git cherry-pick d42c389f

How to check if a variable exists in a FreeMarker template?

Also I think if_exists was used like:

Hi ${userName?if_exists}, How are you?

which will not break if userName is null, the result if null would be:

Hi , How are you?

if_exists is now deprecated and has been replaced with the default operator ! as in

Hi ${userName!}, How are you?

the default operator also supports a default value, such as:

Hi ${userName!"John Doe"}, How are you?

File Upload with Angular Material

Adding to all the answers above (which is why I made it a community wiki), it is probably best to mark any input<type="text"> with tabindex="-1", especially if using readonly instead of disabled (and perhaps the <input type="file">, although it should be hidden, it is still in the document, apparently). Labels did not act correctly when using the tab / enter key combinations, but the button did. So if you are copying one of the other solutions on this page, you may want to make those changes.

OWIN Startup Class Missing

This could be faced in Visual Studio 2015 as well when you use the Azure AD with a MVC project. Here it create the startup file as Startup.Auth.cs in App_Start folder but it will be missing the

[assembly: OwinStartup(typeof(MyWebApp.Startup))]

So add it and you should be good to go. This goes before the namespace start.

Circle button css

The problem is that the actual width of an a tag depends on its contents. Your code has no text in the a tag, so it appears like a hunger-sunken circle. If you use the div tag along the a, you get the desired results.

Check this code out:

.btn {
  background-color: green;
  border-radius: 50%;
  /*this will rounden-up the button*/
  width: 80px;
  height: 80px;
  /*keep the height and width equal*/
<a href="#">
 <!--use the URL you want to use-->
 <button class="btn">press me</button>

How to add google-play-services.jar project dependency so my project will run and present map

The quick start guide that keyboardsurfer references will work if you need to get your project to build properly, but it leaves you with a dummy google-play-services project in your Eclipse workspace, and it doesn't properly link Eclipse to the Google Play Services Javadocs.

Here's what I did instead:

  1. Install the Google Play Services SDK using the instructions in the Android Maps V2 Quick Start referenced above, or the instructions to Setup Google Play Services SDK, but do not follow the instructions to add Google Play Services into your project.

  2. Right click on the project in the Package Explorer, select Properties to open the properties for your project.

  3. (Only if you already followed the instructions in the quick start guide!) Remove the dependency on the google-play-services project:

    • Click on the Android category and remove the reference to the google-play-services project.

    • Click on the Java Build Path category, then the Projects tab and remove the reference to the google-play-services project.

  4. Click on the Java Build Path category, then the Libraries tab.

  5. Click Add External JARs... and select the google-play-services.jar file. This should be in [Your ADT directory]\sdk\extras\google\google_play_services\libproject\google-play-services_lib\libs.

  6. Click on the arrow next to the new google-play-services.jar entry, and select the Javadoc Location item.

  7. Click Edit... and select the folder containing the Google Play Services Javadocs. This should be in [Your ADT directory]\sdk\extras\google\google_play_services\docs\reference.

  8. Still in the Java Build Path category, click on the Order and Export tab. Check the box next to the google-play-services.jar entry.

  9. Click OK to save your project properties.

Your project should now have access to the Google Play Services library, and the Javadocs should display properly in Eclipse.

Remove .php extension with .htaccess

I've ended up with the following working code:

RewriteEngine on 
RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC]
RewriteRule ^ /%1 [NC,L,R]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [NC,L]

Spring Test & Security: How to mock authentication?

Add in pom.xml:


and use for authorization request. See the sample usage at (


4.0.0.RC2 works for spring-security 3.x. For spring-security 4 spring-security-test become part of spring-security (, version is the same).

Setting Up is changed:

public void setup() {
    mvc = MockMvcBuilders

Sample for basic-authentication:

Commenting out code blocks in Atom

Possible reason: watch out for overlapping keybindings. It has happened in my case and deactivated the initial toggle line comment binding:

enter image description here

The Keybindings you can find in the Edit -> Preferences -> Keybindings of the application navbar.

The solution was overriding binding for github:toggle-patch-selection-mode

enter image description here

How do I output the difference between two specific revisions in Subversion?

See svn diff in the manual:

svn diff -r 8979:11390

MySQL - UPDATE query with LIMIT

UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 LIMIT 1001, 1000

This query is not correct (or at least i don't know a possible way to use limit in UPDATE queries), you should put a where condition on you primary key (this assumes you have an auto_increment column as your primary key, if not provide more details):

UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 WHERE primary_key BETWEEN 1001 AND 2000

For the second query you must use IS

UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 WHERE panel_id is null

EDIT - if your primary_key is a column named MAX+1 you query should be (with backticks as stated correctly in the comment):

UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 WHERE `MAX+1` BETWEEN 1001 AND 2000

To update the rows with MAX+1 from 1001 TO 2000 (including 1001 and 2000)

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

Had this problem when setting up a new slave server. Found it was the slave server IP address was missing from the master server /etc/hosts.allow file. Added the IP address and it let me connect to the master server.

Note that I use hosts.allow and hosts.deny to control access.

reading external sql script in python

according me, it is not possible


  1. import .sql file on mysql server

  2. after

    import mysql.connector
    import pandas as pd

    and then you use .sql file by convert to dataframe

WCF service startup error "This collection already contains an address with scheme http"

And in my case it was simple: I used 'Add WCF Service' wizard in Visual Studio, which automatically created corresponding sections in app.config. Then I went on reading How to: Host a WCF Service in a Managed Application. The problem was: I didn't need to specify the url to run the web service.


using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))


using (ServiceHost host = new ServiceHost(typeof(HelloWorldService))

And the error is gone.

Generic idea: if you provide base address as a param and specify it in config, you get this error. Most probably, that's not the only way to get the error, thou.

Convert month int to month name

You can do something like this instead.

return new DateTime(2010, Month, 1).ToString("MMM");

MySQL: Fastest way to count number of rows

I handled tables for the German Government with sometimes 60 million records.

And we needed to know many times the total rows.

So we database programmers decided that in every table is record one always the record in which the total record numbers is stored. We updated this number, depending on INSERT or DELETE rows.

We tried all other ways. This is by far the fastest way.

What does the keyword Set actually do in VBA?

Off the top of my head, Set is used to assign COM objects to variables. By doing a Set I suspect that under the hood it's doing an AddRef() call on the object to manage it's lifetime.

Using Java generics for JPA findAll() query with WHERE clause

This will work, and if you need where statement you can add it as parameter.

class GenericDAOWithJPA<T, ID extends Serializable> {


public List<T> findAll() {
            return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();

.NET Out Of Memory Exception - Used 1.3GB but have 16GB installed

Its worth mentioning that the default for an 'Any CPU' compile now checks the 'Prefer 32bit' check box. Being set to AnyCPU, on a 64bit OS with 16gb of RAM can still hit an out of memory exception at 2gb if this is checked.


Getting Index of an item in an arraylist;

I think a for-loop should be a valid solution :

    public int getIndexByname(String pName)
        for(AuctionItem _item : *yourArray*)
                return *yourarray*.indexOf(_item)
        return -1;

How do I delete a local repository in git?

In the repository directory you remove the directory named .git and that's all :). On Un*x it is hidden, so you might not see it from file browser, but

cd repository-path/
rm -r .git

should do the trick.

Fiddler not capturing traffic from browsers

I had exactly the same problem. I finally gave up. Reset Chrome's browser settings to default. Uninstalled then reinstalled Fiddler. After that, everything worked.

Using app.config in .Net Core

It is possible to use your usual System.Configuration even in .NET Core 2.0 on Linux. Try this test example:

  1. Created a .NET Standard 2.0 Library (say MyLib.dll)
  2. Added the NuGet package System.Configuration.ConfigurationManager v4.4.0. This is needed since this package isn't covered by the meta-package NetStandard.Library v2.0.0 (I hope that changes)
  3. All your C# classes derived from ConfigurationSection or ConfigurationElement go into MyLib.dll. For example MyClass.cs derives from ConfigurationSection and MyAccount.cs derives from ConfigurationElement. Implementation details are out of scope here but Google is your friend.
  4. Create a .NET Core 2.0 app (e.g. a console app, MyApp.dll). .NET Core apps end with .dll rather than .exe in Framework.
  5. Create an app.config in MyApp with your custom configuration sections. This should obviously match your class designs in #3 above. For example:

<?xml version="1.0" encoding="utf-8"?>
    <section name="myCustomConfig" type="MyNamespace.MyClass, MyLib" />
    <myAccount id="007" />

That's it - you'll find that the app.config is parsed properly within MyApp and your existing code within MyLib works just fine. Don't forget to run dotnet restore if you switch platforms from Windows (dev) to Linux (test).

Additional workaround for test projects

If you're finding that your App.config is not working in your test projects, you might need this snippet in your test project's .csproj (e.g. just before the ending </Project>). It basically copies App.config into your output folder as testhost.dll.config so dotnet test picks it up.

  <!-- START: This is a buildtime work around for -->
  <Target Name="CopyCustomContent" AfterTargets="AfterBuild">
    <Copy SourceFiles="App.config" DestinationFiles="$(OutDir)\testhost.dll.config" />
  <!-- END: This is a buildtime work around for -->

How to get directory size in PHP

Just another function using native php functions.

function dirSize($dir)
        $dirSize = 0;
        if(!is_dir($dir)){return false;};
        $files = scandir($dir);if(!$files){return false;}
        $files = array_diff($files, array('.','..'));

        foreach ($files as $file) {
                 $dirSize += dirSize("$dir/$file");
                $dirSize += filesize("$dir/$file");
        return $dirSize;

NOTE: this function returns the files sizes, NOT the size on disk

Javascript close alert box

You can use label and set its fade in and out time for e.g Hide it initially and show on click. $('#div_Message').fadeIn(500).delay(1000).fadeOut(1500);

Interface type check with Typescript

It's now possible, I just released an enhanced version of the TypeScript compiler that provides full reflection capabilities. You can instantiate classes from their metadata objects, retrieve metadata from class constructors and inspect interface/classes at runtime. You can check it out here

Usage example:

In one of your typescript files, create an interface and a class that implements it like the following:

interface MyInterface {
    doSomething(what: string): number;

class MyClass implements MyInterface {
    counter = 0;

    doSomething(what: string): number {
        console.log('Doing ' + what);
        return this.counter++;

now let's print some the list of implemented interfaces.

for (let classInterface of MyClass.getClass().implements) {
    console.log('Implemented interface: ' +

compile with reflec-ts and launch it:

$ node main.js
Implemented interface: MyInterface
Member name: counter - member kind: number
Member name: doSomething - member kind: function

See reflection.d.ts for Interface meta-type details.

UPDATE: You can find a full working example here

remove double quotes from Json return data using Jquery

For niche needs when you know your data like your example ... this works :


JSON.parse("House");  // for example

How to get all subsets of a set? (powerset)

The Python itertools page has exactly a powerset recipe for this:

from itertools import chain, combinations

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))


>>> list(powerset("abcd"))
[(), ('a',), ('b',), ('c',), ('d',), ('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd'), ('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'd'), ('b', 'c', 'd'), ('a', 'b', 'c', 'd')]

If you don't like that empty tuple at the beginning, you can just change the range statement to range(1, len(s)+1) to avoid a 0-length combination.

Passive Link in Angular 2 - <a href=""> equivalent

I wonder why no one is suggesting routerLink and routerLinkActive (Angular 7)

<a [routerLink]="[ '/resources' ]" routerLinkActive="currentUrl!='/resources'">

I removed the href and now using this. When using href, it was going to the base url or reloading the same route again.

IIS 7, HttpHandler and HTTP Error 500.21

On windows server 2016 i have used:

dism /online /enable-feature /featurename:IIS-ASPNET45 /all

Also can be done via Powershell:

Install-WindowsFeature .NET-Framework-45-Features

Find full path of the Python interpreter?

There are a few alternate ways to figure out the currently used python in Linux is:

  1. which python command.
  2. command -v python command
  3. type python command

Similarly On Windows with Cygwin will also result the same.

kuvivek@HOSTNAME ~
$ which python

kuvivek@HOSTNAME ~
$ whereis python
python: /usr/bin/python /usr/bin/python3.4 /usr/lib/python2.7 /usr/lib/python3.4        /usr/include/python2.7 /usr/include/python3.4m /usr/share/man/man1/python.1.gz

kuvivek@HOSTNAME ~
$ which python3

kuvivek@HOSTNAME ~
$ command -v python

kuvivek@HOSTNAME ~
$ type python
python is hashed (/usr/bin/python)

If you are already in the python shell. Try anyone of these. Note: This is an alternate way. Not the best pythonic way.

>>> import os
>>> os.popen('which python').read()
>>> os.popen('type python').read()
'python is /usr/bin/python\n'
>>> os.popen('command -v python').read()

If you are not sure of the actual path of the python command and is available in your system, Use the following command.

pi@osboxes:~ $ which python
pi@osboxes:~ $ readlink -f $(which python)
pi@osboxes:~ $ 
pi@osboxes:~ $ which python3
pi@osboxes:~ $ 
pi@osboxes:~ $ readlink -f $(which python3)
pi@osboxes:~ $ 

What's the easiest way to escape HTML in Python?

cgi.escape is fine. It escapes:

  • < to &lt;
  • > to &gt;
  • & to &amp;

That is enough for all HTML.

EDIT: If you have non-ascii chars you also want to escape, for inclusion in another encoded document that uses a different encoding, like Craig says, just use:

data.encode('ascii', 'xmlcharrefreplace')

Don't forget to decode data to unicode first, using whatever encoding it was encoded.

However in my experience that kind of encoding is useless if you just work with unicode all the time from start. Just encode at the end to the encoding specified in the document header (utf-8 for maximum compatibility).


>>> cgi.escape(u'<a>bá</a>').encode('ascii', 'xmlcharrefreplace')

Also worth of note (thanks Greg) is the extra quote parameter cgi.escape takes. With it set to True, cgi.escape also escapes double quote chars (") so you can use the resulting value in a XML/HTML attribute.

EDIT: Note that cgi.escape has been deprecated in Python 3.2 in favor of html.escape, which does the same except that quote defaults to True.

java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

You will get this error when you call any of the setXxx() methods on PreparedStatement, while the SQL query string does not have any placeholders ? for this.

For example this is wrong:

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (val1, val2, val3)";
// ...

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1); // Fail.
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);

You need to fix the SQL query string accordingly to specify the placeholders.

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (?, ?, ?)";
// ...

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1);
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);

Note the parameter index starts with 1 and that you do not need to quote those placeholders like so:

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES ('?', '?', '?')";

Otherwise you will still get the same exception, because the SQL parser will then interpret them as the actual string values and thus can't find the placeholders anymore.

See also:

CSS: fixed position on x-axis but not y?

No, it's not possible with pure CSS. That kind of positioning fixes the element in the viewport. I'd suggest simply fixing the element to one of the sides of the viewport (i.e. top, bottom, left or right) so that it doesn't interfere with other content.

How do I remove documents using Node.js Mongoose?

To generalize you can use:

SomeModel.find( $where, function(err,docs){
  if (err) return console.log(err);
  if (!docs || !Array.isArray(docs) || docs.length === 0) 
    return console.log('no docs found');
  docs.forEach( function (doc) {

Another way to achieve this is:

SomeModel.collection.remove( function (err) {
  if (err) throw err;
  // collection is now empty but not deleted

Can I change the name of `nohup.out`?

As the file handlers points to i-nodes (which are stored independently from file names) on Linux/Unix systems You can rename the default nohup.out to any other filename any time after starting nohup something&. So also one could do the following:

$ nohup something&
$ mv nohup.out nohup2.out
$ nohup something2&

Now something adds lines to nohup2.out and something2 to nohup.out.

Add image in title bar

you should be searching about how to add favicon.ico . You can try adding favicon.ico directly in your html pages like this

<link rel="shortcut icon" href="/favicon.png" type="image/png">
<link rel="shortcut icon" type="image/png" href="" />

Or you can update that in your webserver. It is advised to add in your webserver as you don't need to add this in each of your html pages (assuming no includes).

To add in your apache place the favicon.ico in your root website director and add this in httpd.conf

AddType image/x-icon .ico

How do I split a multi-line string into multiple lines?

Like the others said:

inputString.split('\n')  # --> ['Line 1', 'Line 2', 'Line 3']

This is identical to the above, but the string module's functions are deprecated and should be avoided:

import string
string.split(inputString, '\n')  # --> ['Line 1', 'Line 2', 'Line 3']

Alternatively, if you want each line to include the break sequence (CR,LF,CRLF), use the splitlines method with a True argument:

inputString.splitlines(True)  # --> ['Line 1\n', 'Line 2\n', 'Line 3']

Unable to resolve "unable to get local issuer certificate" using git on Windows with self-signed certificate

In case of github Repositories (or any none-self-signed certs), choosing below while installing Git-on-windows, resolved the issue.

enter image description here

How can I delete a service in Windows?

If they are .NET created services you can use the installutil.exe with the /u switch its in the .net framework folder like C:\Windows\Microsoft.NET\Framework64\v2.0.50727

Force update of an Android app when a new version is available

I used a simple approach to make this work:

  1. Create Firebase database
  2. Add your latest version
  3. If the version is different than the installed version, show the popup of installing the update. It works perfectly for me...

Removing page title and date when printing web page (with CSS?)

You can add this in your stylesheet: @page{size:auto; margin:5mm;} But this discards the page number too

Multiplication on command line terminal

For more advanced and precise math consider using bc(1).

echo "3 * 2.19" | bc -l 

In JavaScript can I make a "click" event fire programmatically for a file input element?

There are ways to redirect events to the control but don't expect to be able to easily fire events to the fire control yourself as the browsers will try to block that for (good) security reasons.

If you only need the file dialog to show up when a user clicks something, let's say because you want better looking file upload buttons, then you might want to take a look at what Shaun Inman came up with.

I've been able to achieve keyboard triggering with creative shifting of focus in and out of the control between keydown, keypress & keyup events. YMMV.

My sincere advice is to leave this the alone, because this is a world of browser-incompatibility-pain. Minor browser updates may also block tricks without warning and you may have to keep reinventing hacks to keep it working.

Binning column with python pandas

You can use pandas.cut:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
   percentage     binned
0       46.50   (25, 50]
1       44.20   (25, 50]
2      100.00  (50, 100]
3       42.12   (25, 50]

bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
   percentage binned
0       46.50      5
1       44.20      5
2      100.00      6
3       42.12      5

Or numpy.searchsorted:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
   percentage  binned
0       46.50       5
1       44.20       5
2      100.00       6
3       42.12       5

...and then value_counts or groupby and aggregate size:

s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50]     3
(50, 100]    1
(10, 25]     0
(5, 10]      0
(1, 5]       0
(0, 1]       0
Name: percentage, dtype: int64

s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
(0, 1]       0
(1, 5]       0
(5, 10]      0
(10, 25]     0
(25, 50]     3
(50, 100]    1
dtype: int64

By default cut return categorical.

Series methods like Series.value_counts() will use all categories, even if some categories are not present in the data, operations in categorical.

Bootstrap carousel width and height

I found that if you just want to change the height of the element the image takes up, this will be the code that will help

.carousel-item { height: 600px !important; }

however, this won't make the size of the image dynamic, it will simply crop the image to its size.

Declaring an HTMLElement Typescript

The type comes after the name in TypeScript, partly because types are optional.

So your line:

HTMLElement el = document.getElementById('content');

Needs to change to:

const el: HTMLElement = document.getElementById('content');

Back in 2013, the type HTMLElement would have been inferred from the return value of getElementById, this is still the case if you aren't using strict null checks (but you ought to be using the strict modes in TypeScript). If you are enforcing strict null checks you will find the return type of getElementById has changed from HTMLElement to HTMLElement | null. The change makes the type more correct, because you don't always find an element.

So when using type mode, you will be encouraged by the compiler to use a type assertion to ensure you found an element. Like this:

const el: HTMLElement | null = document.getElementById('content');

if (el) {
  const definitelyAnElement: HTMLElement = el;

I have included the types to demonstrate what happens when you run the code. The interesting bit is that el has the narrower type HTMLElement within the if statement, due to you eliminating the possibility of it being null.

You can do exactly the same thing, with the same resulting types, without any type annotations. They will be inferred by the compiler, thus saving all that extra typing:

const el = document.getElementById('content');

if (el) {
  const definitelyAnElement = el;

Android Whatsapp/Chat Examples

Check out yowsup

Yowsup is a python library that allows you to do all the previous in your own app. Yowsup allows you to login and use the Whatsapp service and provides you with all capabilities of an official Whatsapp client, allowing you to create a full-fledged custom Whatsapp client.

A solid example of Yowsup's usage is Wazapp. Wazapp is full featured Whatsapp client that is being used by hundreds of thousands of people around the world. Yowsup is born out of the Wazapp project. Before becoming a separate project, it was only the engine powering Wazapp. Now that it matured enough, it was separated into a separate project, allowing anyone to build their own Whatsapp client on top of it. Having such a popular client as Wazapp, built on Yowsup, helped bring the project into a much advanced, stable and mature level, and ensures its continuous development and maintaince.

Yowsup also comes with a cross platform command-line frontend called yowsup-cli. yowsup-cli allows you to jump into connecting and using Whatsapp service directly from command line.

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

I used the plain .css. It worked great. Note that I deleted the following from the bootstrap.min.css:

/* Fade transition for carousel items */

.carousel .item {
   left: 0 !important;
   -webkit-transition: opacity .4s;
    /*adjust timing here */ 
   -moz-transition: opacity .4s; 
   -o-transition: opacity .4s; 
   transition: opacity .4s; 

.carousel-control { 
   background-image: none !important; 
   /* remove background gradients on controls */ 

/* Fade controls with items */

.next.left, .prev.right {
   opacity: 1; 
   z-index: 1;

.active.left, .active.right {
   opacity: 0;
   z-index: 2;

How do I create a self-signed certificate for code signing on Windows?

Updated Answer

If you are using the following Windows versions or later: Windows Server 2012, Windows Server 2012 R2, or Windows 8.1 then MakeCert is now deprecated, and Microsoft recommends using the PowerShell Cmdlet New-SelfSignedCertificate.

If you're using an older version such as Windows 7, you'll need to stick with MakeCert or another solution. Some people suggest the Public Key Infrastructure Powershell (PSPKI) Module.

Original Answer

While you can create a self-signed code-signing certificate (SPC - Software Publisher Certificate) in one go, I prefer to do the following:

Creating a self-signed certificate authority (CA)

makecert -r -pe -n "CN=My CA" -ss CA -sr CurrentUser ^
         -a sha256 -cy authority -sky signature -sv MyCA.pvk MyCA.cer

(^ = allow batch command-line to wrap line)

This creates a self-signed (-r) certificate, with an exportable private key (-pe). It's named "My CA", and should be put in the CA store for the current user. We're using the SHA-256 algorithm. The key is meant for signing (-sky).

The private key should be stored in the MyCA.pvk file, and the certificate in the MyCA.cer file.

Importing the CA certificate

Because there's no point in having a CA certificate if you don't trust it, you'll need to import it into the Windows certificate store. You can use the Certificates MMC snapin, but from the command line:

certutil -user -addstore Root MyCA.cer

Creating a code-signing certificate (SPC)

makecert -pe -n "CN=My SPC" -a sha256 -cy end ^
         -sky signature ^
         -ic MyCA.cer -iv MyCA.pvk ^
         -sv MySPC.pvk MySPC.cer

It is pretty much the same as above, but we're providing an issuer key and certificate (the -ic and -iv switches).

We'll also want to convert the certificate and key into a PFX file:

pvk2pfx -pvk MySPC.pvk -spc MySPC.cer -pfx MySPC.pfx

If you want to protect the PFX file, add the -po switch, otherwise PVK2PFX creates a PFX file with no passphrase.

Using the certificate for signing code

signtool sign /v /f MySPC.pfx ^
              /t http://timestamp.url MyExecutable.exe

(See why timestamps may matter)

If you import the PFX file into the certificate store (you can use PVKIMPRT or the MMC snapin), you can sign code as follows:

signtool sign /v /n "Me" /s SPC ^
              /t http://timestamp.url MyExecutable.exe

Some possible timestamp URLs for signtool /t are:


Full Microsoft documentation


For those who are not .NET developers, you will need a copy of the Windows SDK and .NET framework. A current link is available here: SDK & .NET (which installs makecert in C:\Program Files\Microsoft SDKs\Windows\v7.1). Your mileage may vary.

MakeCert is available from the Visual Studio Command Prompt. Visual Studio 2015 does have it, and it can be launched from the Start Menu in Windows 7 under "Developer Command Prompt for VS 2015" or "VS2015 x64 Native Tools Command Prompt" (probably all of them in the same folder).

How to wrap text around an image using HTML/CSS

With CSS Shapes you can go one step further than just float text around a rectangular image.

You can actually wrap text such that it takes the shape of the edge of the image or polygon that you are wrapping it around.

DEMO FIDDLE (Currently working on webkit - caniuse)

.oval {_x000D_
  width: 400px;_x000D_
  height: 250px;_x000D_
  color: #111;_x000D_
  border-radius: 50%;_x000D_
  text-align: center;_x000D_
  font-size: 90px;_x000D_
  float: left;_x000D_
  shape-outside: ellipse();_x000D_
  padding: 10px;_x000D_
  background-color: MediumPurple;_x000D_
  background-clip: content-box;_x000D_
span {_x000D_
  padding-top: 70px;_x000D_
  display: inline-block;_x000D_
<div class="oval"><span>PHP</span>_x000D_
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has_x000D_
  survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing_x000D_
  software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley_x000D_
  of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing_x000D_
  Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy_x000D_
  text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised_x000D_
  in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

Also, here is a good list apart article on CSS Shapes

java.lang.RuntimeException: Unable to start activity ComponentInfo

After trying few answers they are either not related to my project or , I have tried cleaning and rebuilding ( But it didn't work for me directly. I have compared it with older version of code, in which i observed some library files(jars and aars in External Libraries directory) are missing. Tried Invalidate Cache and Restart worked, which created all the libraries and working fine.

Get last dirname/filename in a file path argument in Bash

Bash can get the last part of a path without having to call the external basename:


What does the Excel range.Rows property really do?

I've found myself using range.Rows for its effects in the Copy method. It copies the height of the rows from the origin to the destination, which is the behaviour I want.

rngLastRecord.Rows.Copy Destination:=Sheets("Availability").Range("a" & insertRow)

If I had used rngLastRecord.Copy instead of rngLastRecord.Rows.Copy, the row heights would be whatever was there before the copy.

How to add an extra row to a pandas dataframe

Upcoming pandas 0.13 version will allow to add rows through loc on non existing index data. However, be aware that under the hood, this creates a copy of the entire DataFrame so it is not an efficient operation.

Description is here and this new feature is called Setting With Enlargement.

Classes vs. Modules in VB.NET

Modules are by no means deprecated and are used heavily in the VB language. It's the only way for instance to implement an extension method in VB.Net.

There is one huge difference between Modules and Classes with Static Members. Any method defined on a Module is globally accessible as long as the Module is available in the current namespace. In effect a Module allows you to define global methods. This is something that a class with only shared members cannot do.

Here's a quick example that I use a lot when writing VB code that interops with raw COM interfaces.

Module Interop
  Public Function Succeeded(ByVal hr as Integer) As Boolean
  End Function

  Public Function Failed(ByVal hr As Integer) As Boolean
  End Function
End Module

Class SomeClass
  Sub Foo()
    Dim hr = CallSomeHrMethod()
    if Succeeded(hr) then
    End If
  End Sub
End Class

Line break (like <br>) using only css

It works like this:

h4 {
h4:after {
    white-space: pre;


The trick comes from here: (to have more explanation)

What is the difference between application server and web server?

Application server and web server both are used to host web application. Web Server is deal with web container on the other hand Application Server is deal with web container as well as EJB (Enterprise JavaBean) container or COM+ container for Microsoft dot Net.

Web Server is designed to serve HTTP static Content like HTML, images etc. and for the dynamic content have plugins to support scripting languages like Perl, PHP, ASP, JSP etc and it is limited to HTTP protocol. Below servers can generate dynamic HTTP content.

Web Server's Programming Environment:


Apache Tomcat: Servlet

Jetty: Servlet

Apache: Php, CGI

Application Server can do whatever Web Server is capable and listens using any protocol as well as App Server have components and features to support Application level services such as Connection Pooling, Object Pooling, Transaction Support, Messaging services etc.

Application Server's Programming Environment:



JBoss: EJB

WebLogic Application Server: EJB

gcc makefile error: "No rule to make target ..."

The problem I found was even sillier than what other folks have mentioned.

Our makefiles get passed lists of things to build. Someone added TheOtherLibrary to one of the lists, as shown below.

LIBRARYDIRS = src/Library
LIBRARYDIRS = src/TheOtherLibrary

They should have done this:

LIBRARYDIRS = src/Library
LIBRARYDIRS += src/TheOtherLibrary

Had they done it the second way, they would not have wiped out the Library build. The plus in += is very important.

How to setup virtual environment for Python in VS Code?

With a newer VS Code version it's quite simple.

Open VS Code in your project's folder.

Then open Python Terminal (Ctrl-Shift-P: Python: Create Terminal)

In the terminal:

python -m venv .venv

you'll then see the following dialog: enter image description here

click Yes

Then Python: Select Interpreter (via Ctrl-Shift-P)

and select the option (in my case towards the bottom)

Python 3.7 (venv) ./venv/Scripts/python.exe

If you see

Activate.ps1 is not digitally signed. You cannot run this script on the current system.

you'll need to do the following:

For more information see:

How to convert hex string to Java string?

First of all read in the data, then convert it to byte array:

 byte b = Byte.parseByte(str, 16); 

and then use String constructor:

new String(byte[] bytes) 

or if the charset is not system default then:

new String(byte[] bytes, String charsetName) 

Select distinct values from a large DataTable column

dt- your data table name

ColumnName- your columnname i.e id

DataView view = new DataView(dt);
DataTable distinctValues = new DataTable();
distinctValues = view.ToTable(true, ColumnName);

How to install an apk on the emulator in Android Studio?

For those using Mac and you get a command not found error, what you need to do is


./adb install "yourapk.apk"

enter image description here

HTML form input tag name element array with JavaScript

To answer your questions in order:
1) There is no specific name for this. It's simply multiple elements with the same name (and in this case type as well). Name isn't unique, which is why id was invented (it's supposed to be unique).

function getElementsByTagAndName(tag, name) {
    //you could pass in the starting element which would make this faster
    var elem = document.getElementsByTagName(tag);  
    var arr = new Array();
    var i = 0;
    var iarr = 0;
    var att;
    for(; i < elem.length; i++) {
        att = elem[i].getAttribute("name");
        if(att == name) {
            arr[iarr] = elem[i];
    return arr;

Change type of varchar field to integer: "cannot be cast automatically to type integer"

If you've accidentally or not mixed integers with text data you should at first execute below update command (if not above alter table will fail):

UPDATE the_table SET col_name = replace(col_name, 'some_string', '');

Change border color on <select> HTML form

.form-error {
        border: 2px solid #e74c3c;

<div class="form-error">
                                {!! Form::select('color', $colors->prepend('Please Select Color', ''),           ,['class' => 'form-control dropselect form-error'
                                ,'tabindex' => $count++, 'id' => 'color']) !!}

how to set ulimit / file descriptor on docker container the image tag is phusion/baseimage-docker

If using the docker-compose file, Based on docker compose version 2.x We can set like as below, by overriding the default config.

  nproc: 65535
    soft: 26677
    hard: 46677

In Javascript, how to conditionally add a member to an object?

Better answer:

const a = {
   ...(someCondition ? {b: 5} : {})

Random String Generator Returning Same String

A very simple implementation that uses Path.GetRandomFileName():

using System.IO;   
public static string RandomStr()
    string rStr = Path.GetRandomFileName();
    rStr = rStr.Replace(".", ""); // For Removing the .
    return rStr;

Now just call RandomStr().

How to get row count in an Excel file using POI library?

If you do a check

 res="Sheet Cannot be empty";

This will make sure you have at least one row with data except header. Below is my program which works fine. Excel file has three columns ie. ID, NAME , LASTNAME

XSSFWorkbook workbook = new XSSFWorkbook(inputstream);
        XSSFSheet sheet = workbook.getSheetAt(0);
        Row header = sheet.getRow(0);
        int n = header.getLastCellNum();
        String header1 = header.getCell(0).getStringCellValue();
        String header2 = header.getCell(1).getStringCellValue();
        String header3 = header.getCell(2).getStringCellValue();
        if (header1.equals("ID") && header2.equals("NAME")
                && header3.equals("LASTNAME")) {
                System.out.println("Sheet empty");
                        iterate over sheet to get cell values
                          SOP("invalid format");

How to change Android version and code version number?

After updating the manifest file, instead of building your project, go to command line and reach the path ...bld\Debug\platforms\android. Run the command "ant release". Your new release.apk file will have a new version code.

Excel - find cell with same value in another worksheet and enter the value to the left of it

The easiest way is probably with VLOOKUP(). This will require the 2nd worksheet to have the employee number column sorted though. In newer versions of Excel, apparently sorting is no longer required.

For example, if you had a "Sheet2" with two columns - A = the employee number, B = the employee's name, and your current worksheet had employee numbers in column D and you want to fill in column E, in cell E2, you would have:

=VLOOKUP($D2, Sheet2!$A$2:$B$65535, 2, FALSE)

Then simply fill this formula down the rest of column D.


  • The first argument $D2 specifies the value to search for.
  • The second argument Sheet2!$A$2:$B$65535 specifies the range of cells to search in. Excel will search for the value in the first column of this range (in this case Sheet2!A2:A65535). Note I am assuming you have a header cell in row 1.
  • The third argument 2 specifies a 1-based index of the column to return from within the searched range. The value of 2 will return the second column in the range Sheet2!$A$2:$B$65535, namely the value of the B column.
  • The fourth argument FALSE says to only return exact matches.

https connection using CURL from command line

use --cacert to specify a .crt file. ca-root-nss.crt for example.

Pythonic way to check if a list is sorted or not

I would just use

if sorted(lst) == lst:
    # code here

unless it's a very big list in which case you might want to create a custom function.

if you are just going to sort it if it's not sorted, then forget the check and sort it.


and don't think about it too much.

if you want a custom function, you can do something like

def is_sorted(lst, key=lambda x: x):
    for i, el in enumerate(lst[1:]):
        if key(el) < key(lst[i]): # i is the index of the previous element
            return False
    return True

This will be O(n) if the list is already sorted though (and O(n) in a for loop at that!) so, unless you expect it to be not sorted (and fairly random) most of the time, I would, again, just sort the list.

how to calculate binary search complexity

Let me make it easy for all of you with an example.

For simplicity purpose, let's assume there are 32 elements in an array in the sorted order out of which we are searching for an element using binary search.

1 2 3 4 5 6 ... 32

Assume we are searching for 32. after the first iteration, we will be left with

17 18 19 20 .... 32

after the second iteration, we will be left with

25 26 27 28 .... 32

after the third iteration, we will be left with

29 30 31 32

after the fourth iteration, we will be left with

31 32

In the fifth iteration, we will find the value 32.

So, If we convert this into a mathematical equation, we will get

(32 X (1/25)) = 1

=> n X (2-k) = 1

=> (2k) = n

=> k log22 = log2n

=> k = log2n

Hence the proof.

Default value in Go's method

NO,but there are some other options to implement default value. There are some good blog posts on the subject, but here are some specific examples.

**Option 1:** The caller chooses to use default values
// Both parameters are optional, use empty string for default value
func Concat1(a string, b int) string {
  if a == "" {
    a = "default-a"
  if b == 0 {
    b = 5

  return fmt.Sprintf("%s%d", a, b)

**Option 2:** A single optional parameter at the end
// a is required, b is optional.
// Only the first value in b_optional will be used.
func Concat2(a string, b_optional string {
  b := 5
  if len(b_optional) > 0 {
    b = b_optional[0]

  return fmt.Sprintf("%s%d", a, b)

**Option 3:** A config struct
// A declarative default value syntax
// Empty values will be replaced with defaults
type Parameters struct {
  A string `default:"default-a"` // this only works with strings
  B string // default is 5

func Concat3(prm Parameters) string {
  typ := reflect.TypeOf(prm)

  if prm.A == "" {
    f, _ := typ.FieldByName("A")
    prm.A = f.Tag.Get("default")

  if prm.B == 0 {
    prm.B = 5

  return fmt.Sprintf("%s%d", prm.A, prm.B)

**Option 4:** Full variadic argument parsing (javascript style)
func Concat4(args ...interface{}) string {
  a := "default-a"
  b := 5

  for _, arg := range args {
    switch t := arg.(type) {
      case string:
        a = t
      case int:
        b = t
        panic("Unknown argument")

  return fmt.Sprintf("%s%d", a, b)

Optimal way to concatenate/aggregate strings

I found Serge's answer to be very promising, but I also encountered performance issues with it as-written. However, when I restructured it to use temporary tables and not include double CTE tables, the performance went from 1 minute 40 seconds to sub-second for 1000 combined records. Here it is for anyone who needs to do this without FOR XML on older versions of SQL Server:

     ID                 INT
    ,VALUE              VARCHAR(MAX) NULL
    ,VALUECOUNT         INT




            ,CTE.VALUE + ' ' + SV.VALUE AS VALUE
    JOIN    CTE 
        ON  SV.ID = CTE.ID


Find location of a removable SD card

I came up with the following solution based on some answers found here.


public class ExternalStorage {

    public static final String SD_CARD = "sdCard";
    public static final String EXTERNAL_SD_CARD = "externalSdCard";

     * @return True if the external storage is available. False otherwise.
    public static boolean isAvailable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            return true;
        return false;

    public static String getSdCardPath() {
        return Environment.getExternalStorageDirectory().getPath() + "/";

     * @return True if the external storage is writable. False otherwise.
    public static boolean isWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        return false;


     * @return A map of all storage locations available
    public static Map<String, File> getAllStorageLocations() {
        Map<String, File> map = new HashMap<String, File>(10);

        List<String> mMounts = new ArrayList<String>(10);
        List<String> mVold = new ArrayList<String>(10);

        try {
            File mountFile = new File("/proc/mounts");
                Scanner scanner = new Scanner(mountFile);
                while (scanner.hasNext()) {
                    String line = scanner.nextLine();
                    if (line.startsWith("/dev/block/vold/")) {
                        String[] lineElements = line.split(" ");
                        String element = lineElements[1];

                        // don't add the default mount path
                        // it's already in the list.
                        if (!element.equals("/mnt/sdcard"))
        } catch (Exception e) {

        try {
            File voldFile = new File("/system/etc/vold.fstab");
                Scanner scanner = new Scanner(voldFile);
                while (scanner.hasNext()) {
                    String line = scanner.nextLine();
                    if (line.startsWith("dev_mount")) {
                        String[] lineElements = line.split(" ");
                        String element = lineElements[2];

                        if (element.contains(":"))
                            element = element.substring(0, element.indexOf(":"));
                        if (!element.equals("/mnt/sdcard"))
        } catch (Exception e) {

        for (int i = 0; i < mMounts.size(); i++) {
            String mount = mMounts.get(i);
            if (!mVold.contains(mount))

        List<String> mountHash = new ArrayList<String>(10);

        for(String mount : mMounts){
            File root = new File(mount);
            if (root.exists() && root.isDirectory() && root.canWrite()) {
                File[] list = root.listFiles();
                String hash = "[";
                    for(File f : list){
                        hash += f.getName().hashCode()+":"+f.length()+", ";
                hash += "]";
                    String key = SD_CARD + "_" + map.size();
                    if (map.size() == 0) {
                        key = SD_CARD;
                    } else if (map.size() == 1) {
                        key = EXTERNAL_SD_CARD;
                    map.put(key, root);


                 map.put(SD_CARD, Environment.getExternalStorageDirectory());
        return map;


Map<String, File> externalLocations = ExternalStorage.getAllStorageLocations();
File sdCard = externalLocations.get(ExternalStorage.SD_CARD);
File externalSdCard = externalLocations.get(ExternalStorage.EXTERNAL_SD_CARD);

Preventing multiple clicks on button

If you are doing a full round-trip post-back, you can just make the button disappear. If there are validation errors, the button will be visible again upon reload of the page.

First set add a style to your button:

<h:commandButton id="SaveBtn" value="Save"

Then make it hide when clicked.

$(document).ready(function() {
    $(".hideOnClick").click(function(e) {

Can we rely on String.isEmpty for checking null condition on a String in Java?

You can't use String.isEmpty() if it is null. Best is to have your own method to check null or empty.

public static boolean isBlankOrNull(String str) {
    return (str == null || "".equals(str.trim()));

Close Form Button Event

Try this:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    // You may decide to prompt to user else just kill.

Get local IP address in Node.js

I'm using Node.js 0.6.5:

$ node -v

Here is what I do:

var util = require('util');
var exec = require('child_process').exec;

function puts(error, stdout, stderr) {

exec("hostname -i", puts);

Oracle Not Equals Operator

There is no functional or performance difference between the two. Use whichever syntax appeals to you.

It's just like the use of AS and IS when declaring a function or procedure. They are completely interchangeable.

Regular Expression for any number greater than 0?

I think this would perfectly work :




Not valid :


How to change a nullable column to not nullable in a Rails migration?

Per the Strong Migrations gem, using change_column_null in production is a bad idea because it blocks reads and writes while all records are checked.

The recommended way to handle these migrations (Postgres specific) is to separate this process into two migrations.

One to alter the table with the constraint:

class SetSomeColumnNotNull < ActiveRecord::Migration[6.0]
  def change
    safety_assured do
      execute 'ALTER TABLE "users" ADD CONSTRAINT "users_some_column_null" CHECK ("some_column" IS NOT NULL) NOT VALID'

And a separate migration to validate it:

class ValidateSomeColumnNotNull < ActiveRecord::Migration[6.0]
  def change
    safety_assured do
      execute 'ALTER TABLE "users" VALIDATE CONSTRAINT "users_some_column_null"'

The above examples are pulled (and slightly altered) from the linked documentation. Apparently for Postgres 12+ you can also add NOT NULL to the schema and then drop the constraint after the validation has been run:

class ValidateSomeColumnNotNull < ActiveRecord::Migration[6.0]
  def change
    safety_assured do
      execute 'ALTER TABLE "users" VALIDATE CONSTRAINT "users_some_column_null"'

    # in Postgres 12+, you can then safely set NOT NULL on the column
    change_column_null :users, :some_column, false
    safety_assured do
      execute 'ALTER TABLE "users" DROP CONSTRAINT "users_some_column_null"'

Naturally, this means your schema will not show that the column is NOT NULL for earlier versions of Postgres, so I'd also advise setting a model level validation to require the value to be present (though I'd suggest the same even for versions of PG that do allow this step).

Further, before running these migrations you'll want to update all existing records with a value other than null, and make sure any production code that writes to the table is not writing null for the value(s).

How to create a link to a directory

Symbolic or soft link (files or directories, more flexible and self documenting)

#     Source                             Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx

Hard link (files only, less flexible and not self documenting)

#   Source                             Link
ln /home/jake/doc/test/2000/something /home/jake/xxx

More information: man ln

/home/jake/xxx is like a new directory. To avoid "is not a directory: No such file or directory" error, as @trlkly comment, use relative path in the target, that is, using the example:

  1. cd /home/jake/
  2. ln -s /home/jake/doc/test/2000/something xxx

How to search in a List of Java object

As your list is an ArrayList, it can be assumed that it is unsorted. Therefore, there is no way to search for your element that is faster than O(n).

If you can, you should think about changing your list into a Set (with HashSet as implementation) with a specific Comparator for your sample class.

Another possibility would be to use a HashMap. You can add your data as Sample (please start class names with an uppercase letter) and use the string you want to search for as key. Then you could simply use

Sample samp = myMap.get(myKey);

If there can be multiple samples per key, use Map<String, List<Sample>>, otherwise use Map<String, Sample>. If you use multiple keys, you will have to create multiple maps that hold the same dataset. As they all point to the same objects, space shouldn't be that much of a problem.

Oracle: how to set user password unexpire?

While applying the new profile to the user,you should also check for resource limits are "turned on" for the database as a whole i.e.RESOURCE_LIMIT = TRUE

Let check the parameter value.
If in Case it is :

SQL> show parameter resource_limit
NAME                                 TYPE        VALUE
------------------------------------ ----------- ---------
resource_limit                       boolean     FALSE
Its mean resource limit is off,we ist have to enable it. 

Use the ALTER SYSTEM statement to turn on resource limits. 

System altered.

How to build query string with Javascript

You can do that nowadays with FormData and URLSearchParams without the need to loop over anything.

const formData = new FormData(form);
const searchParams = new URLSearchParams(formData);
const queryString = searchParams.toString();

Older browsers will need a polyfill, though.

.ps1 cannot be loaded because the execution of scripts is disabled on this system

There are certain scenarios in which you can follow the steps suggested in the other answers, verify that Execution Policy is set correctly, and still have your scripts fail. If this happens to you, you are probably on a 64-bit machine with both 32-bit and 64-bit versions of PowerShell, and the failure is happening on the version that doesn't have Execution Policy set. The setting does not apply to both versions, so you have to explicitly set it twice.

Look in your Windows directory for System32 and SysWOW64.

Repeat these steps for each directory:

  1. Navigate to WindowsPowerShell\v1.0 and launch powershell.exe
  2. Check the current setting for ExecutionPolicy:

    Get-ExecutionPolicy -List

  3. Set the ExecutionPolicy for the level and scope you want, for example:

    Set-ExecutionPolicy -Scope LocalMachine Unrestricted

Note that you may need to run PowerShell as administrator depending on the scope you are trying to set the policy for.

You can read a lot more here: Running Windows PowerShell Scripts

How to do perspective fixing?

The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.

The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.

Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.

How to select min and max values of a column in a datatable?

int minAccountLevel = int.MaxValue;
int maxAccountLevel = int.MinValue;
foreach (DataRow dr in table.Rows)
    int accountLevel = dr.Field<int>("AccountLevel");
    minAccountLevel = Math.Min(minAccountLevel, accountLevel);
    maxAccountLevel = Math.Max(maxAccountLevel, accountLevel);

Yes, this really is the fastest way. Using the Linq Min and Max extensions will always be slower because you have to iterate twice. You could potentially use Linq Aggregate, but the syntax isn't going to be much prettier than this already is.

Oracle PL Sql Developer cannot find my tnsnames.ora file

I recently had the problem of deleting the tnsnames.ora from the path where I had it, my solution was to create an environment variable called TNS_NAME with the value the path where the tnsnames.ora file is located and ready

WPF: simple TextBox data binding

Just for future needs.

In Visual Studio 2013 with .NET Framework 4.5, for a window property, try adding ElementName=window to make it work.

<Grid Name="myGrid" Height="437.274">
  <TextBox Text="{Binding Path=Name2, ElementName=window}"/>

The builds tools for v120 (Platform Toolset = 'v120') cannot be found

I had a similar problem. VS 2015 Community (MSBuild 14) building a c++ app, wanted to use VS 2010 (v100) tools. It all came down giving msbuild an invalid configuration option. Strange.

So, recheck all those options and parameters.

Common Header / Footer with static HTML

Since HTML does not have an "include" directive, I can think only of three workarounds

  1. Frames
  2. Javascript
  3. CSS

A little comment on each of the methods.

Frames can be either standard frames or iFrames. Either way, you will have to specify a fixed height for them, so this might not be the solution you are looking for.

Javascript is a pretty broad subject and there probably exist many ways how one might use it to achieve the desired effect. Off the top of my head however I can think of two ways:

  1. Full-blown AJAX request, which requests the header/footer and then places them in the right place of the page;
  2. <script type="text/javascript" src="header.js"> which has something like this in it: document.write('My header goes here');

Doing it via CSS would be really an abuse. CSS has the content property which allows you to insert some HTML content, although it's not really intended to be used like this. Also I'm not sure about browser support for this construct.

How do I store data in local storage using Angularjs?

this is a bit of my code that stores and retrieves to local storage. i use broadcast events to save and restore the values in the model.

app.factory('userService', ['$rootScope', function ($rootScope) {

    var service = {

        model: {
            name: '',
            email: ''

        SaveState: function () {
            sessionStorage.userService = angular.toJson(service.model);

        RestoreState: function () {
            service.model = angular.fromJson(sessionStorage.userService);

    $rootScope.$on("savestate", service.SaveState);
    $rootScope.$on("restorestate", service.RestoreState);

    return service;

define() vs. const

No one says anything about php-doc, but for me that is also a very significant argument for the preference of const:

 * My foo-bar const
 * @var string
const FOO = 'BAR';

How to set a tkinter window to a constant size

You turn off pack_propagate by setting pack_propagate(0)

Turning off pack_propagate here basically says don't let the widgets inside the frame control it's size. So you've set it's width and height to be 500. Turning off propagate stills allows it to be this size without the widgets changing the size of the frame to fill their respective width / heights which is what would happen normally

To turn off resizing the root window, you can set root.resizable(0, 0), where resizing is allowed in the x and y directions respectively.

To set a maxsize to window, as noted in the other answer you can set the maxsize attribute or minsize although you could just set the geometry of the root window and then turn off resizing. A bit more flexible imo.

Whenever you set grid or pack on a widget it will return None. So, if you want to be able to keep a reference to the widget object you shouldn't be setting a variabe to a widget where you're calling grid or pack on it. You should instead set the variable to be the widget Widget(master, ....) and then call pack or grid on the widget instead.

import tkinter as tk

def startgame():


mw = tk.Tk()

#If you have a large number of widgets, like it looks like you will for your
#game you can specify the attributes for all widgets simply like this.
mw.option_add("*Button.Background", "black")
mw.option_add("*Button.Foreground", "red")

mw.title('The game')
#You can set the geometry attribute to change the root windows size
mw.geometry("500x500") #You want the size of the app to be 500x500
mw.resizable(0, 0) #Don't allow resizing in the x or y direction

back = tk.Frame(master=mw,bg='black')
back.pack_propagate(0) #Don't allow the widgets inside to determine the frame's width / height
back.pack(fill=tk.BOTH, expand=1) #Expand the frame to fill the root window

#Changed variables so you don't have these set to None from .pack()
go = tk.Button(master=back, text='Start Game', command=startgame)
close = tk.Button(master=back, text='Quit', command=mw.destroy)
info = tk.Label(master=back, text='Made by me!', bg='red', fg='black')


Java: how to initialize String[]?

I believe you just migrated from C++, Well in java you have to initialize a data type(other then primitive types and String is not a considered as a primitive type in java ) to use them as according to their specifications if you don't then its just like an empty reference variable (much like a pointer in the context of C++).

public class StringTest {
    public static void main(String[] args) {
        String[] errorSoon = new String[100];
        errorSoon[0] = "Error, why?";
        //another approach would be direct initialization
        String[] errorsoon = {"Error , why?"};   

Keyboard shortcut to paste clipboard content into command prompt window (Win XP)

If you're a Cygwin user, you can append the following to your ~/.bashrc file:

stty lnext ^q stop undef start undef

And the following to your ~/.inputrc file:

"\C-v": paste-from-clipboard
"\C-C": copy-to-clipboard

Restart your Cygwin terminal.

(Note, I've used an uppercase C for copy, since CTRL+c is assigned to the break function on most consoles. Season to taste.)


Submitting a form by pressing enter without a submit button

For those who have problems with IE and for others too.

    float: left;
    width: 1px;
    height: 1px;
    background-color: transparent;
    border: none;

alternatives to REPLACE on a text or ntext datatype

IF your data won't overflow 4000 characters AND you're on SQL Server 2000 or compatibility level of 8 or SQL Server 2000:

UPDATE [CMS_DB_test].[dbo].[cms_HtmlText] 
SET Content = CAST(REPLACE(CAST(Content as NVarchar(4000)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%' 

For SQL Server 2005+:

UPDATE [CMS_DB_test].[dbo].[cms_HtmlText] 
SET Content = CAST(REPLACE(CAST(Content as NVarchar(MAX)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%' 

Android - java.lang.SecurityException: Permission Denial: starting Intent

In my case, this error was due to incorrect paths used to specify intents in my preferences xml file after I renamed the project. For instance, where I had:

<PreferenceScreen xmlns:android="">
        android:title="Add/Edit Recipe">

I needed the following instead:

<PreferenceScreen xmlns:android="">
        android:title="Add/Edit Recipe">

Correcting the path names fixed the problem.

I get Access Forbidden (Error 403) when setting up new alias

If you have installed a module on Xampp (on Linux) via Bitnami and changed chown settings, make sure that the /opt/lampp/apps/<app>/htdocs and tmp usergroup is daemon with all other sibling files and folders chowned to the user you installed as, e.g. cd /opt/lampp/apps/<app>, sudo chown -R root:root ., followed by sudo chown -R root:daemon htdocs tmp.

JavaScript vs for

FYI - jQuery Users

jQuery's each(callback) method uses for( ; ; ) loop by default, and will use for( in ) only if the length is undefined.

Therefore, I would say it is safe to assume the correct order when using this function.


$(['a','b','c']).each(function() {
//Outputs "a" then "b" then "c"

The downside of using this is that if you're doing some non UI logic, your functions will be less portable to other frameworks. The each() function is probably best reserved for use with jQuery selectors and for( ; ; ) might be advisable otherwise.

How to call javascript function on page load in

Place this line before the closing script tag,writing from memory:

window.onload  = GetTimeZoneOffset;

i think the question is how to call the javascript function on pageload

"unadd" a file to svn before commit

Full process (Unix svn package):

Check files are not in SVN:

> svn st -u folder 
? folder

Add all (including ignored files):

> svn add folder
A   folder
A   folder/file1.txt
A   folder/folder2
A   folder/folder2/file2.txt
A   folder/folderToIgnore
A   folder/folderToIgnore/fileToIgnore1.txt
A   fileToIgnore2.txt

Remove "Add" Flag to All * Ignore * files:

> cd folder

> svn revert --recursive folderToIgnore
Reverted 'folderToIgnore'
Reverted 'folderToIgnore/fileToIgnore1.txt'

> svn revert fileToIgnore2.txt
Reverted 'fileToIgnore2.txt'

Edit svn ignore on folder

svn propedit svn:ignore .

Add two singles lines with just the following:


Check which files will be upload and commit:

> cd ..

> svn st -u
A   folder
A   folder/file1.txt
A   folder/folder2
A   folder/folder2/file2.txt

> svn ci -m "Commit message here"

How to set environment variables in Python?

Use setdefault function to set a new variable if the variable does not exist in the environment.

make sure you set the environment variable as a string, not int. Otherwise will throw TypeError.

import os

if not os.environ.get("DEBUSSY"):
     os.environ["DEBUSSY"] = "1"


htaccess redirect all pages to single page

Add this for pages not currently on your site...

ErrorDocument 404

Along with your Redirect 301 / that should cover all the bases...

Good luck!

Converting a generic list to a CSV string

This website did some extensive testing about how to write to a file using buffered writer, reading line by line seems to be the best way, using string builder was one of the slowest.

I use his techniques a great deal for writing stuff to file it works well.

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

I am a little bit late, but I had this error too. I solved the problem by checking what where the values that where updating.

I found out that my query was wrong and that there where over 250+ edits pending. So I corrected my query, and now it works correct.

So in my situation: Check the query for errors, by debugging over the result that the query returns. After that correct the query.

Hope this helps resolving future problems.

How do I horizontally center an absolute positioned element inside a 100% width div?

Was missing the use of calc in the answers, which is a cleaner solution.

#logo {
  position: absolute;
  left: calc(50% - 25px);
  height: 50px;
  width: 50px;
  background: red;


Works in most modern browsers:

Maybe it's too soon to use it without a fallback, but I thought maybe for future visitors it would be helpful.

Font is not available to the JVM with Jasper Reports

I faced the issue with my web application based on Spring 3 and deployed on Weblogic 10.3 on Oracle Linux 6. The solution mentioned at the link did not work for me.

I had to take the following steps - 1. Copy the Arial*.ttf font files to JROCKIT_JAVA_HOME/jre/lib/fonts directory 2. Make entries of the fonts in 3. Restart the cluster from Weblogic console


Android Gradle Could not reserve enough space for object heap

For Android Studio 1.3 : (Method 1)

Step 1 : Open file in your Android Studio project.

Step 2 : Add this line at the end of the file

org.gradle.jvmargs=-XX\:MaxHeapSize\=256m -Xmx256m

Above methods seems to work but if in case it won't then do this (Method 2)

Step 1 : Start Android studio and close any open project (File > Close Project).

Step 2 : On Welcome window, Go to Configure > Settings.

Step 3 : Go to Build, Execution, Deployment > Compiler

Step 4 : Change Build process heap size (Mbytes) to 1024 and Additional build process to VM Options to -Xmx512m.

Step 5 : Close or Restart Android Studio.

SOLVED - Andriod Studio 1.3 Gradle Could not reserve enough space for object heap Issue

Beginner Python Practice?

I always find it easier to learn a language in a specific problem domain. You might try looking at Django and doing the tutorial. This will give you a very light-weight intro to both Python and to a web framework (a very well-documented one) that is 100% Python.

Then do something in your field(s) of expertise -- graph generation, or whatever -- and tie that into a working framework to see if you got it right. My universe tends to be computational linguistics and there are a number of Python-based toolkits to help get you started. E.g. Natural Language Toolkit.

Just a thought.

Is HTML considered a programming language?

The 'M' stands for a 'Markup'. It's a 'Markup Language' not a programming language. Some people will disagree with this, but my opinion is that if it lacks logical constructs (conditional branching, iteration, etc) its not really a programming language.

As for the resume, I would suggest putting HTML and XML under a section like 'Technologies'. I usually have a section like this where I list things like version control software, OS's I've developed for, build systems, etc.

How to render html with AngularJS templates

So maybe you want to have this in your index.html to load the library, script, and initialize the app with a view:

  <body ng-app="yourApp">
    <div class="span12">
      <div ng-view=""></div>
    <script src=""></script>
    <script src="script.js"></script>

Then yourView.html could just be:

  <h1>{{ stuff.h1 }}</h1>
  <p>{{ stuff.content }}</p>

scripts.js could have your controller with data $scope'd to it.

    .controller('YourCtrl', function ($scope) {
      $scope.stuff = {
        'content':"A paragraph..."

Lastly, you'll have to config routes and assign the controller to view for it's $scope (i.e. your data object)

angular.module('yourApp', [])
.config(function ($routeProvider) {
    .when('/', {
      templateUrl: 'views/yourView.html',
      controller: 'YourCtrl'

I haven't tested this, sorry if there's a bug but I think this is the Angularish way to get data

The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'Negotiate,NTLM'

You can eliminate the client from the problem by using wftech, this is an old tool but I have found it useful in diagnosing authentication issues. wfetch allows you to specify NTLM, Negotiate and kerberos, this may well help you better understand your problem. As you are trying to call a service and wfetch knows nothing about WCF, I would suggest applying your endpoint binding (PROVIDERSSoapBinding) to the serviceMetadata then you can do an HTTP GET of the WSDL for the service with the same security settings.

Another option, which may be available to you is to force the server to use NTLM, you can do this by either editing the metabase (IIS 6) and removing the Negotiate setting, more details at

If you are using IIS 7.x then the approach is slightly different, details of how to configure the authentication providers are here

I notice that you have blocked out the server address with, so I'm guessing that this is an IP address rather than a server name, this may cause issues with authentication, so if possible try targeting the machine name.

Sorry that I haven't given you the answer but rather pointers for getting closer to the issue, but I hope it helps.

I'll finish by saying that I have experienced this same issue and my only recourse was to use Kerberos rather than NTLM, don't forget you'll need to register an SPN for the service if you do go down this route.

ExecuteNonQuery doesn't return results

Whenever you want to execute an SQL statement that shouldn't return a value or a record set, the ExecuteNonQuery should be used.

So if you want to run an update, delete, or insert statement, you should use the ExecuteNonQuery. ExecuteNonQuery returns the number of rows affected by the statement. This sounds very nice, but whenever you use the SQL Server 2005 IDE or Visual Studio to create a stored procedure it adds a small line that ruins everything.

That line is: SET NOCOUNT ON; This line turns on the NOCOUNT feature of SQL Server, which "Stops the message indicating the number of rows affected by a Transact-SQL statement from being returned as part of the results" and therefore it makes the stored procedure always to return -1 when called from the application (in my case a web application).

In conclusion, remove that line from your stored procedure, and you will now get a value indicating the number of rows affected by the statement.

Happy programming!

Convert string to JSON Object

Combining Saurabh Chandra Patel's answer with Molecular Man's observation, you should have something like this:

JSON.parse('{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}');

Bootstrap radio button "checked" flag

You have to use active in the label to make it work as mentioned above. But you can use checked="checked" and it will work too. It's not necessary but it's more legible and makes more sense as it is more html format compliance.

Regex to extract URLs from href attribute in HTML with Python

The best answer is...

Don't use a regex

The expression in the accepted answer misses many cases. Among other things, URLs can have unicode characters in them. The regex you want is here, and after looking at it, you may conclude that you don't really want it after all. The most correct version is ten-thousand characters long.

Admittedly, if you were starting with plain, unstructured text with a bunch of URLs in it, then you might need that ten-thousand-character-long regex. But if your input is structured, use the structure. Your stated aim is to "extract the url, inside the anchor tag's href." Why use a ten-thousand-character-long regex when you can do something much simpler?

Parse the HTML instead

For many tasks, using Beautiful Soup will be far faster and easier to use:

>>> from bs4 import BeautifulSoup as Soup
>>> html = Soup(s, 'html.parser')           # Soup(s, 'lxml') if lxml is installed
>>> [a['href'] for a in html.find_all('a')]
['', '']

If you prefer not to use external tools, you can also directly use Python's own built-in HTML parsing library. Here's a really simple subclass of HTMLParser that does exactly what you want:

from html.parser import HTMLParser

class MyParser(HTMLParser):
    def __init__(self, output_list=None):
        if output_list is None:
            self.output_list = []
            self.output_list = output_list
    def handle_starttag(self, tag, attrs):
        if tag == 'a':


>>> p = MyParser()
>>> p.feed(s)
>>> p.output_list
['', '']

You could even create a new method that accepts a string, calls feed, and returns output_list. This is a vastly more powerful and extensible way than regular expressions to extract information from html.

Ruby, remove last N characters from a string?

I would suggest chop. I think it has been mentioned in one of the comments but without links or explanations so here's why I think it's better:

It simply removes the last character from a string and you don't have to specify any values for that to happen.

If you need to remove more than one character then chomp is your best bet. This is what the ruby docs have to say about chop:

Returns a new String with the last character removed. If the string ends with \r\n, both characters are removed. Applying chop to an empty string returns an empty string. String#chomp is often a safer alternative, as it leaves the string unchanged if it doesn’t end in a record separator.

Although this is used mostly to remove separators such as \r\n I've used it to remove the last character from a simple string, for example the s to make the word singular.

spring autowiring with unique beans: Spring expected single matching bean but found 2

If I'm not mistaken, the default bean name of a bean declared with @Component is the name of its class its first letter in lower-case. This means that

public class SuggestionService {

declares a bean of type SuggestionService, and of name suggestionService. It's equivalent to

public class SuggestionService {

or to

<bean id="suggestionService" .../>

You're redefining another bean of the same type, but with a different name, in the XML:

<bean id="SuggestionService" class="">

So, either specify the name of the bean in the annotation to be SuggestionService, or use the ID suggestionService in the XML (don't forget to also modify the <ref> element, or to remove it, since it isn't needed). In this case, the XML definition will override the annotation definition.

PyCharm import external library

I wanted to add an import path, for another project elsewhere in my workspace. MacOS Catalina 10.15.5 PyCharm Community 2020.1.1

PyCharm - Preferences - Project interpreter - Cog symbol - Show All

At the bottom of that dialog, it shows 5 buttons: Plus, Minus, Pencil, Funnel, and Directory tree.

Click Directory tree. You can now use the Plus button in the new dialog to add your 'external library' search path.

If successful, you should now see the directory name in the "External Libraries" pane in the Project panel.

Simple way to calculate median with MySQL

Taken from:

I would suggest another way, without join, but working with strings

i did not checked it with tables with large data, but small/medium tables it works just fine.

The good thing here, that it works also by GROUPING so it can return the median for several items.

here is test code for test table:

DROP TABLE test.test_median
CREATE TABLE test.test_median AS
SELECT 'book' AS grp, 4 AS val UNION ALL


SELECT 'bike', 26 

and the code for finding the median for each group:

         SUBSTRING_INDEX( SUBSTRING_INDEX( GROUP_CONCAT(val ORDER BY val), ',', COUNT(*)/2 ), ',', -1) as the_median,
         GROUP_CONCAT(val ORDER BY val) as all_vals_for_debug
FROM test.test_median


grp | the_median| all_vals_for_debug
bike| 22        | 22,26
book| 4         | 2,2,3,4,7,8,9
note| 11        | 11

how to know status of currently running jobs

EXECUTE master.dbo.xp_sqlagent_enum_jobs 1,''

Notice the column Running, obviously 1 means that it is currently running, and [Current Step]. This returns job_id to you, so you'll need to look these up, e.g.:

SELECT top 100 *
 FROM   msdb..sysjobs
 WHERE  job_id IN (0x9DAD1B38EB345D449EAFA5C5BFDC0E45, 0xC00A0A67D109B14897DD3DFD25A50B80, 0xC92C66C66E391345AE7E731BFA68C668)

How to list only top level directories in Python?

You could also use os.scandir:

with os.scandir(os.getcwd()) as mydir:
    dirs = [ for i in mydir if i.is_dir()]

In case you want the full path you can use i.path.

Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because os.DirEntry objects expose this information if the operating system provides it when scanning a directory.

Generate a random date between two other dates

from random import randrange
from datetime import timedelta

def random_date(start, end):
    This function will return a random datetime between two datetime 
    delta = end - start
    int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
    random_second = randrange(int_delta)
    return start + timedelta(seconds=random_second)

The precision is seconds. You can increase precision up to microseconds, or decrease to, say, half-hours, if you want. For that just change the last line's calculation.

example run:

from datetime import datetime

d1 = datetime.strptime('1/1/2008 1:30 PM', '%m/%d/%Y %I:%M %p')
d2 = datetime.strptime('1/1/2009 4:50 AM', '%m/%d/%Y %I:%M %p')

print(random_date(d1, d2))


2008-12-04 01:50:17

Where to download visual studio express 2005?

As of late April 2009, Microsoft has discontinued all previous versions of Visual Studio Express, including 2005. It is no longer possible to obtain these previous versions from the Microsoft website.

From Here

Regex match text between tags


Regular expression visualization

Add g (global) flag after:

             //^-----here it is 

However if you want to get all matched elements, then you need something like this:

var str = "<b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";

var result = str.match(/<b>(.*?)<\/b>/g).map(function(val){
   return val.replace(/<\/?b>/g,'');
//result -> ["Bob", "20", "programming"] 

If an element has attributes, regexp will be:

/<b [^>]+>(.*?)<\/b>/g.exec(str)

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it?

List myArrayList  = Collections.synchronizedList(new ArrayList());

//add your elements  

synchronized(myArrayList) {
    Iterator i = myArrayList.iterator(); 
     while (i.hasNext()){
         Object  object =;