text:
Q: Bind9 DNS - How to redirect domain to another domain I'm trying to redirect facebook.com ( and all subdomains ) to google.com, however I appear to be missing something.
zone "facebook.com" {
    type master;
    file "/etc/bind/nene-block";
};

That is my named.conf.local
nene-block:http://pastebin.com/DQmj8huw
Basically, what I want to do is redirect users who go to facebook to google. I've been trying for hours but I can't find a solution.
With these settings, I get DNS_PROBE_FINISHED_NXDOMAIN in Chrome

A: It looks like you're trying to use this example code from JISC to spoof Facebook DNS. I see a few possible problems.

*

*Have you tested your BIND setup to see if it works at all? Create some simple records on it for local addresses first, before trying Facebook.

*Your SOA record is confusing. You're saying that the authoritative DNS is found at www.facebook.com, not your own server. What is your local server name, BTW?

*AAAA records are for IPv6 but you have IPv4 in them. You should probably omit AAAA until you have a better handle on the other parts.

*If this is intended as an actual method of blocking users from reaching Facebook, not just a personal experiment, then it won't work. Users can just switch to external DNS.


text:
Q: Residuals still zero inflated after running zero-inflated poisson mixed effect model with glmmTMB I am working with observational data which has a right skew in the dependent variable. This is a mixed effect model with a poisson distribution as based on discrete data. After finding the residuals from the model were not normal, and sjstats function overfit(model) highlighted zero-inflation to be an issue I ran the model in glmmTMB:
fit_zipoisson <- glmmTMB(freq~(B1 + B2)+(1|ref),data=da, ziformula=~1,
    family=poisson())

But running the model diagnostics afterwards still reveal a non-normal distribution and a zero-inflation.
zero_count(fit_zipoisson)

Zero-Count overfitting

Observed zero-counts: 295
Predicted zero-counts: 100
                 Ratio: 0.34

Model is underfitting zero-counts (probable zero-inflation).

Shapiro-Wilk normality test

data:  resid(fit_zipoisson)
W = 0.57262, p-value < 2.2e-16

Does anyone have any advice on what to do next?

A: A better way to check the fit of such a model would be the simulated scaled residuals of the DHARMa package. In addition, note that the glmmTMB() fits the model using the Laplace approximation which may not be optimal do discrete data. As an alternative you may also try the GLMMadaptive package that fits the same model using the adaptive Gaussian quadrature. You can also find an example of testing the goodness-of-fit here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating action with Magnific Popup to Make Profile Photo Default I could use help with creating a style sheet to override the default ones from Magnific Popup (https://github.com/joshuajansen/magnific-popup-rails).
I have the code for a user to select their default_profile_id from their uploaded images. The problem I have is I need code that will allow the current user to make that decision from their page. For example the current user hovers over their photo, and the text "Make Profile Photo" appears on it (https://s18.postimg.cc/arl81snll/mouse.jpg). I don't know how to create a style sheet or modify what I do have so that this action can work.
Any help with adding this action to the photos would be much appreciated.
Photos Controller:
 def new
    @photo = Photo.new
  end

  def create
    @photo = Photo.new(params[:photo])
    @photo.user = current_user
    if @photo.save
      flash[:notice] = "Successfully created photos."
      redirect_to :back
    else
      render :action => 'new'
    end
  end

  def resize(width, height, gravity = 'Center')
    manipulate! do |img|
      img.combine_options do |cmd|
        cmd.resize "#{width}"
        if img[:width]  'edit'
    end
  end

  def destroy
    @photo = Photo.find(params[:id])
    @photo.destroy
    flash[:notice] = "Successfully destroyed photo."
    redirect_to @photo.gallery
  end

  def choose_default_photo
    @photo = Photo.find params[:photo_id]
    current_user.default_photo = @photo
    redirect_to '/profile' # or wherever I want to send them
  end
end

Photo model:
  attr_accessible :title, :body, :gallery_id, :name, :image, :remote_image_url
  belongs_to :gallery
  has_many :gallery_users, :through => :gallery, :source => :user
  belongs_to :user
  mount_uploader :image, ImageUploader

  LIMIT = 5

  validate do |record|
    record.validate_photo_quota
  end

  def validate_photo_quota
    return unless self.user
    if self.user.photos(:reload).count >= LIMIT
      errors.add(:base, :exceeded_quota)
    end
  end
end

User Model:
  has_many :photos
  belongs_to :default_photo, :class_name => "Photo"
  after_create :setup_gallery

  private
  def setup_gallery
     Gallery.create(user: self)
   end
end

User Controller:
  def new
    @user = User.new
  end

  def show
    @user = User.find(params[:id])
  end

  def destroy
     User.find(id_params).destroy
     flash[:success] = "User deleted."
     redirect_to users_url
   end

    def choose_default_photo
      @photo = Photo.find params[:photo_id]
      current_user.default_photo = @photo
      redirect_to '/profile'
    end

The columns for the photos table are:
id, created_at, updated_at, image, name, user_id
Users table has the following related columns:
id, default_photo_id (integer)

A: You can either have two images and swap images when a mouse-over occurs or you can use CSS effects such as :hover and opacity to make the image appear as you like.
Sample CSS showing em, px, and % for a 190x190 pixel image. Sizing and position would need to be adjusted to suite your needs.
/* resize so easier to view */
img.profImg {
    width: 480px;
    /* z-index: 1; */
}
/* all hover items */
.overImg {
  background: #111111;
  color: white;
  opacity: 0.6;
  border-radius: 0.5em;
  width: 190px;
  height: 190px;
  /* z-index: 2; */
}
/* hover effects */
.carImg:hover .overImg  { display:block; }
.carImg .overImg { display:none; }
/* specific to car image, will need to be adjusted */
.car-over-2 {
  position: absolute;
  top: 310px;
  left: 25px;
}
.car-over {
  position: absolute;
  top: 36px;
  left: 25px;
}
/* text near bottom of image */
.overText {
    color: white;
    font-size: 1.1em;
    position: relative;
    top: 85%;
    left: 12.5%;
    z-index: 3;
}
/* X button to close: should use an icon for this */
.closer {
    background-color: white;
    color: black;
    font-size: 0.8em;
    border-radius: 5em;
    padding: 0.2em;
    width: 2em;
    height: 1em;
    position: relative;
    left: 85%;
    top: -8px;
}

Corresponding HTML:

Make Profile Photo

      X

And a plunker file: http://plnkr.co/edit/44G96cTdYsfJh6NCQUjE?p=preview

A: for your backend code
 def choose_default_photo
   @photo = Photo.find params[:photo_id]
   current_user.default_photo = @photo
   redirect_to '/profile'
 end

doesn't work, you have to use current_user.update default_photo: @photo
and then on front end, it's easier to use Javascript, you can send Ajax request to server when the photo been clicked by user
you can use what css :hover to show hidden text, as @user508994's answer, following is the main part
.carImg:hover .overImg  { display:block; }
.carImg .overImg { display:none; }


text:
Q: JSP - using a variable as the url in c:import Is there any way that we can use a variable in a <c:import> statement in JSP such as:
<c:import url="<%=_header%>"></c:import>, where _header is a JSP String defined thus;
// host will typically equal: uk.domain.com or fr.domain.com
String host = request.getServerName();
// cc is attempting to become the country code for the domain
String cc = host.substring(0, host.indexOf("."));

String _header = "http://assets.domain.com/" + cc + "/includes/header_" + cc + ".jsp";

We host a number of sites across multiple markets. Being able to define one template this way would be ideal as it would mean fewer changes to templates. Unfortunately whenever including <c:import url="<%=_header%>"></c:import> the server fails to load the page.
But including, for instance: <c:import url="http://assets.domain.com/uk/includes/header_uk.jsp?market=<%=cc%>"></c:import> seems to work fine...
Any thoughts?!

Edit: Turns out the <%=cc%> var in the URL wasn't actually working. Had to do the following instead to get it to work;
String cc = host.substring(0, host.indexOf("."));
session.setAttribute("cc", cc);

...

<c:import url="http://assets.domain.com/uk/includes/header_uk.jsp"><c:param name="market">${cc}</c:param></c:import>

Still haven't solved the variable URL problem yet, however...

A: You can't reliably mix scriptlets with taglibs/EL. They runs in different moments and scopes. You should choose to use the one or the other. Since the use of scriptlets is officially discouraged since JSP 2.0 (released Nov 2003), I'd recommend to drop it altogether and go ahead with taglibs/EL only.
The following scriptlet
<%
    // host will typically equal: uk.domain.com or fr.domain.com
    String host = request.getServerName();
    // cc is attempting to become the country code for the domain
    String cc = host.substring(0, host.indexOf("."));
%>

can be replaced by the following taglib/EL:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<c:set var="cc" value="${fn:split(pageContext.request.serverName, '.')[0]}" />

so that it's available as ${cc} in EL.
<c:import url="http://assets.domain.com/${cc}/includes/header_${cc}.jsp" />


text:
Q: how to target an element of our class with hive to change it good morning,
I don't know how to access an element of my boxHive without rebuilding it
I would like to be able to update some information without changing the existing one
Here is how I do it here, I use the constructor of my model class to add notes but it rebuilds all my class at the same time I would like it to rebuild only ListNote
class InformationPatient extends StatefulWidget {
  final Patients patients;
  final int index;

  const InformationPatient(this.patients, this.index, {Key? key})
      : super(key: key);

  @override
  State<InformationPatient> createState() => _InformationPatientState();
}

class _InformationPatientState extends State<InformationPatient> {
  late Box<Patients> boxPatient;

  @override
  void initState() {
    super.initState();
    boxPatient = Hive.box('Patient');
  }

  void _addNote(String newtitle, String newnote, String newconclusion) {
    final newNOTE = Patients(
      listOfNotes: [
        ListNote(title: newtitle, note: newnote, conclusion: newconclusion)
      ],
    );
    boxPatient.put(widget.index, newNOTE);
    Navigator.of(context).pop();
  }

And here is my class model
import 'package:hive_flutter/hive_flutter.dart';

part 'listpatient.g.dart';

@HiveType(typeId: 0)
class Patients {
  @HiveField(0)
  final String? name;

  @HiveField(1)
  final String? firstname;

  @HiveField(3)
  final String? dateofbirth;

  @HiveField(4)
  final String? email;

  @HiveField(5)
  final String? phonenumber;

  @HiveField(6)
  final DateTime? date;

  @HiveField(7)
  final int? id;

  @HiveField(8)
  final List<ListNote>? listOfNotes;

  const Patients({
    this.name,
    this.firstname,
    this.dateofbirth,
    this.email,
    this.phonenumber,
    this.date,
    this.id,
    this.listOfNotes,
  });
}

@HiveType(typeId: 10)
class ListNote {
  @HiveField(1)
  final String? title;

  @HiveField(2)
  final String? note;

  @HiveField(3)
  final String? conclusion;

  ListNote({
    this.title,
    this.note,
    this.conclusion,
  });
}

A: Actually Hive offers only Write and Read operations, as you can see from its official documentation for flutter
so in order to update an Object in your boxPatient Box you need to get it with this:
    Patients patients = boxPatient.get(widget.index);

then make your edits over it, then save it again on that same key:
    boxPatient.put(widget.index, patients);

you can say we just updated it with this process.


text:
Q: ASM x86 relative JMP I'm doing some ASM code in a C code with the asm function.
My environment is DVL with gcc version 3.
Hi need to make a JMP to a relative address like %eip+0x1f.
How can I do this ?
Thanks

A: x86 supports a short jump (JMP, opcode EB + 1 byte relative address) which should do what you want.
In most assemblers (including gcc's inline asm IIRC) you can just put a label where you want to jump to, and use jmp mylabel and let the assember figure out the correct opcode and relative address for the jump.


text:
Q: (Root) Mean Square Error of two pandas.Series I have two pandas.Series objects with equal number of elements (they are predictions and target values) and I need to compute the (R)MSE of these two series.
I can use
targets.sub(predictions).pow(2).mean()

for the MSE but I feel that there is a lot of copying1 involved (first for the subtraction result, then for the exponentiation result). Is there an elegant way that does not involve the two copies?

1 Maybe memory allocation is a better term.

A: If you are only concerned with overall memory footprint in case the Series are huge, the following might help since it does not require temporary storage for intermediate results. However, it has much worse performance.
sum((t-p) ** 2 for t,p in zip(targets, predictions)), 0.0)/len(targets)


text:
Q: PyQt Class not working for the second usage I'm using PyQt to fully load a page(including JS) and get it contents using Beautiful Soup. Works fine at the first iteration, but after, it crashes. I don't have a big knowledge in Python, and even less in PyQt, so any help is very welcome.
Class borrowed from here.
from PyQt4.QtCore import QUrl, SIGNAL
from PyQt4.QtGui import QApplication
from PyQt4.QtWebKit import QWebPage

from bs4 import BeautifulSoup
from bs4.dammit import UnicodeDammit
import sys
import signal

class Render(QWebPage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebPage.__init__(self)
        self.html = None
        signal.signal(signal.SIGINT, signal.SIG_DFL)
        self.connect(self, SIGNAL('loadFinished(bool)'), self._finished_loading)
        self.mainFrame().load(QUrl(url))
        self.app.exec_()

    def _finished_loading(self, result):
        self.html = self.mainFrame().toHtml()
        self.soup = BeautifulSoup(UnicodeDammit(self.html).unicode_markup)
        self.app.quit()

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

l = ["http://www.google.com/?q=a", "http://www.google.com/?q=b", "http://www.google.com/?q=c"]

for page in l:
    soup = Render(page).soup
    print("# soup done: " + page)

A: The example crashes because the RenderPage class attempts to create a new QApplication and event-loop for every url it tries to load.
Instead, only one QApplication should be created, and the QWebPage subclass should load a new url after each page has been processed, rather than using a for-loop.
Here's a re-write of the example which should do what you want:
import sys, signal
from bs4 import BeautifulSoup
from bs4.dammit import UnicodeDammit
from PyQt4 import QtCore, QtGui, QtWebKit

class WebPage(QtWebKit.QWebPage):
    def __init__(self):
        QtWebKit.QWebPage.__init__(self)
        self.mainFrame().loadFinished.connect(self.handleLoadFinished)

    def process(self, items):
        self._items = iter(items)
        self.fetchNext()

    def fetchNext(self):
        try:
            self._url, self._func = next(self._items)
            self.mainFrame().load(QtCore.QUrl(self._url))
        except StopIteration:
            return False
        return True

    def handleLoadFinished(self):
        self._func(self._url, self.mainFrame().toHtml())
        if not self.fetchNext():
            print('# processing complete')
            QtGui.qApp.quit()

def funcA(url, html):
    print('# processing:', url)
    # soup = BeautifulSoup(UnicodeDammit(html).unicode_markup)
    # do stuff with soup...

def funcB(url, html):
    print('# processing:', url)
    # soup = BeautifulSoup(UnicodeDammit(html).unicode_markup)
    # do stuff with soup...

if __name__ == '__main__':

    items = [
        ('http://stackoverflow.com', funcA),
        ('http://google.com', funcB),
        ]

    signal.signal(signal.SIGINT, signal.SIG_DFL)
    print('Press Ctrl+C to quit\n')
    app = QtGui.QApplication(sys.argv)
    webpage = WebPage()
    webpage.process(items)
    sys.exit(app.exec_())


text:
Q: Webbrowser in Python I trying open page with Russian symbols.
webbrowser.open('https://www.google.com/?q=привет')

But I have this in browser: https://www.google.com/?q=??????

A: Use a unicode string.
webbrowser.open(u'https://www.google.com/?q=привет')

You'll probably also want to use UTF-8 encoding for your source file, so make sure your editor actually saves in UTF-8 and add this to the top of the program
# -*- coding: utf-8 -*-


text:
Q: How to display data in html component using ionic and api I am getting the data in the console but  not getting the data in the HTML component in Ionic. How to display the data in blog-list.page.ts .when I am console.log(books) run then I am getting the data but when I am trying it in the HTML component then do not getting the data.
book-list.page.ts
import { Component, OnInit } from '@angular/core';
import{Book} from '../book';
import { first } from 'rxjs/operators';
import{UserService} from '../user.service';

@Component({
  selector: 'app-book-list',
  templateUrl: './book-list.page.html',
  styleUrls: ['./book-list.page.scss'],
})
export class BookListPage implements OnInit {
  books: Book[] = [];
  constructor(private userService: UserService) { }

  ngOnInit() {
    this.getBook()
  }

  getBook(){
  this.userService.getBook().pipe(first()).subscribe(books => {
  books = books;
  console.log(books);
});
  }
}

blog-list.page.html
<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-menu-button></ion-menu-button>
    </ion-buttons>
    <ion-title>
      Book List
    </ion-title>
    <ion-buttons slot="end">
      <ion-button routerLink="/user-detail">
        <ion-icon name="add-circle"></ion-icon>
      </ion-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

<ion-content padding>
  <ion-card>

    <ion-card-content>
      <ion-card-subtitle>Books:</ion-card-subtitle>
      <ul *ngFor="let book of books">

        <li>{{book.title}}</li>

      </ul>
      <ion-buttons slot="primary">
        <ion-button routerLink="/edit/">
          <ion-icon slot="icon-only" name="create"></ion-icon>
        </ion-button>
        <ion-button (click)="delete()">
          <ion-icon slot="icon-only" name="trash"></ion-icon>
        </ion-button>
      </ion-buttons>
    </ion-card-content>
  </ion-card>
</ion-content>

A: You need to actually assign your data to your variable books:
getBook(){
  this.userService.getBook().pipe(first()).subscribe(books => {
    this.books = books; // use "this"
    console.log(this.books); // now your data is in your array
  });
}


text:
Q: Laravel 5.4 - Where to change the id for login During authentification it use the wrong id so i have this error :
SQLSTATE[42S22]: Column not found: 1054 Field'id' unknow in where clause (SQL: select * from "acteur" where "id" = 22 limit 1
The right id is : id_biodiv_acteur. And the model for the table acteur is User.php
So I made these change :
In Authenticable, User, LoginController i did protected $primaryKey = 'id_biodiv_acteur';.
In GenericUser i did this :
public function getAuthIdentifierName()
    {
        return 'id_biodiv_acteur';
    }

But it's not working.
If in the table of my database I put id instead of id_biodiv_acteur it work, but i want to keep the right id.
Ask me if you need to see some code.
Thanks for your help !

A: In your user model which I think in your case is the "acteur" model you need to set protected $primaryKey = 'id_biodiv_acteur';


text:
Q: How to prevent Rails from picking the same random name again? In my Rails 4 application I have this controller action that generate a number of sample projects so the user can play with it:
class ProjectsController < ApplicationController

  def generate_samples
    100.times do
      p = current_user.projects.build(
        :name         => random_name,
        :hourly_rate  => random_hourly_rate
      p.save!
    end
    flash[:success] = "Sample projects created."
  end

end

Since my Project model will only accept new records with unique names, the above function breaks if the same random_name gets picked twice within one function call. How can this be prevented?

A: Either have your function check if the name picked already exists, and repeat, or use something like an UUID where the risk of picking two times the same id is almost 0:
name: SecureRandom.uuid


text:
Q: C++ Build error was not declared in this scope Im writing a small program in C++. I have created 2 files "Main.cpp" and "openni_grabber.cpp". As you can see from the code I'm starting a thread from the main. Once I try to build I get an error message: 'SimpleOpenNIProcessor' Was not declared in this scope.
Where in the code do I need to declare SimpleOpenNIProcessor?
Main.cpp
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/cloud_viewer.h>

int main()
{
    SimpleOpenNIProcessor v;
    v.run();
    return(0);
}

openni_grabber.cpp
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/common/time.h>

class SimpleOpenNIProcessor
{
    SimpleOpenNIProcessor()
    {
    };

    public:
    void cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr &cloud)
    {
        static unsigned count = 0;
        static double last = pcl::getTime ();
        if (++count == 30)
        {
            double now = pcl::getTime ();
            std::cout << "distance of center pixel :" << cloud->points [(cloud->width >> 1) * (cloud->height + 1)].z << " mm. Average framerate: " << double(count)/double(now - last) << " Hz" <<  std::endl;
            count = 0;
            last = now;
        }
    }

    void run ()
    {
        // create a new grabber for OpenNI devices
        pcl::Grabber* interface = new pcl::OpenNIGrabber();

        // make callback function from member function
        boost::function<void (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr&)> f =
            boost::bind (&SimpleOpenNIProcessor::cloud_cb_, this, _1);

        // connect callback function for desired signal. In this case its a point cloud with color values
        boost::signals2::connection c = interface->registerCallback (f);

        // start receiving point clouds
        interface->start ();

        // wait until user quits program with Ctrl-C, but no busy-waiting -> sleep (1);
        while (true)
        boost::this_thread::sleep (boost::posix_time::seconds (1));

        // stop the grabber
        interface->stop ();
    }
}

A: Well, it's just as it says: SimpleOpenNIProcessor is not declared at the point you try to instantiate it.
We typically put class definitions in header files to conveniently sprinkle them around our project.
For more information, read your C++ book.


text:
Q: Finding curves in a dataset Let's say I have a dataset that contains x y values of a function such as sin(x) and a range. How do I detect the curves in this dataset (the peaks and troughs of the sin function in this)?

A: Given a set of (x,y) coordinates of sufficient size you can fit any kind of function you like to it, a sine function, a high- (or low-) degree polynomial, linear, exponential, splines, anything at all.  Getting a good fit is the tricky part.
You should really have an idea of the kind of function that the data ought to fit before heading off to find it.  For example, if your data comes from a cyclic process which you believe has a constant cycle with a stable amplitude, try fitting a single sine function to it. (And if this is what you want to do, follow @duyffmo's advice.)
In one of your comments you hint that the data is random.  If that is the case, don't waste your time trying to fit a curve to it, one good definition of the term random is that there is no function which can generate a truly random series of data.  If you just mean something like 'kind of sine-ish with random variations in amplitude and phase' well, that's what goodness-of-fit measures are for, they quantify the difference between your model (ie the function you select) and the data you feed into the process.

A: You could try the brute force approach and use a search algorithm to locate the min and the max.
Another option would be to fit least-squares polynomials to your data and find local maxima and minima from the approximation via derivatives. This is a bit risky though unless your approximation is a very good fit.
If your data is very oscillatory you could try approximation using splines.
Without seeing the data it is hard to say. If your data is noisy then using a finite difference approach to calculate derivatives is risky as derivative methods are very sensitive to noise.
I would say that you will get the most flexibility using least-squares spline approximations. This will enable you to handle a very wide range of data input. It is not the easiest thing to implement in the world unless you can get hold of a numerical linear algebra library but it might get you the best results.

A: If you have (x, y) data, and you're certain you want trigonometric functions, your best bet is to do a Fast Fourier Transform.  You'll get all the frequencies present in the data.  You'll be able to see which ones have the greatest magnitude and dominate your signal.  You can filter it to remove frequencies you aren't interested.  There's a great deal of literature and software available to help you.  You can even use CUDA and GPUs if you'd like - there's a built in FFT package.

A: If you know nothing of the function you are modelling and just want to find the turning points, you can differentiate the curve and find where this crosses zero.
One way to approximate the derivative of a discrete dataset is by taking (y2-y1)/(x2-x1) for each adjacent pair of points. You could loop through the data points and record where this changes from a positive value to a negative value or vice versa.

A: A solution I figured out yesterday: Use a sliding window (I use a 5th of my dataset size) over the data, and vote for the local minima and maxima, when the window has been slid over the data the most votes tend to be the centre of the curves. For further processing, once I had this data I would threshold the points to water it down to a few strong points, and then perform polynomial regression (to 3 degrees), take the a value (in ax^2+bx+c) to determine the size of the curve (if it is too flat then just consider it a straight line with an anomaly).
I'd like to add that I may not have described the problem accurately, when I said sin(x) I was using an example that generated curves, my data will in no way follow a trigonomic function (or any function), and the curves will be at random places making regression inaccurate.
This may not be the perfect solution but it does work.


text:
Q: Get row with most minimum values in R I have this problem that, for the life of me, I have been unable to solve. Some help would be highly appreciated.
Suppose we have this data.frame:
Session <- c("A", "B", "C", "A", "B", "A")
V1 <- c(1, 1, 2, 3, 2, 4)
V2 <- c(1, 1, 2, 1, 1, 3)
V3 <- c(3, 1, 2, 3, 2, 2)
df <- data.frame(Session, V1, V2, V3)
df
  Session V1 V2 V3
1       A  1  1  3
2       B  1  1  1
3       C  2  2  2
4       A  3  1  3
5       B  2  1  2
6       A  4  3  2

I'd like to get the rows that have the MOST minimum values for each column GROUPED by the variable Session.
The expected ouput, in this case, would be the following:
  Session V1 V2 V3
1       A  1  1  3
2       B  1  1  1
3       C  2  2  2

If more than one row has the same amount of minimum values per variable, one row should be valid enough.
Thank you very much,
Aleix.

A: Ok, I found a way of doing it, that I'm pretty sure is not the best way of doing. If you can improve this solution, please do.
First I created a data.table from the df object:
library(data.table)
dt <- setDT(df)

Then I also created a function that returns the value of the most present element in a vector:
most <- function(a1){ return(as.integer(names(sort(table(a1), decreasing = TRUE))[1]))}

To test it I executed the following:
most(c(1,2,3,3,3,2,1))
[1] 3

Then I searched for the rows that contained the minimum values for each column:
mins <- dt[, list(.I[which.min(V1)], .I[which.min(V2)], .I[which.min(V3)] ), by = "Session"]
mins
   Session V1 V2 V3
1:       A  1  1  6
2:       B  2  2  2
3:       C  3  3  3

And, finally, I used the previous result to search for those rows on the original data.table object (dt) like so:
result <- dt[apply(mins[,, by=c("Session")], FUN = max_mins, MAR = 1)]
result
   Session V1 V2 V3
1:       A  1  1  3
2:       B  1  1  1
3:       C  2  2  2

That's about it. I really hope this can help someone.


text:
Q: How to distinguish between Build and Run in the Dockerfile? I need to set a proxy environment variable during the build of a container. But the proxy environment variable must not be set, when the container runs.
I have used the ENV command in the Dockerfile to set the variable. But this sets the variable during the build and the run of the container. As far as I can see the Dockerfile does not support a unset for ENV commands.
How to specify an environment for the build but not for the run?

A: What you need to use is the build arg which is not persisted in the image. The  doc section Set build-time variables (--build-arg) describes exactly what you want:

You can use ENV instructions in a Dockerfile to define variable
  values. These values persist in the built image. However, often
  persistence is not what you want. Users want to specify variables
  differently depending on which host they build an image on.
A good example is http_proxy or source versions for pulling
  intermediate files. The ARG instruction lets Dockerfile authors define
  values that users can set at build-time using the --build-arg flag:

FROM alpine

ARG hello
RUN env # This will output hello=world

CMD env # When running the container, there is not env variable "hello"

docker build --build-arg hello=world -t test . # This will output hello=world env variable
docker run test # There is no env variable "hello"

As you can see above the hello shows as an env variable only on build. It is not persisted in the image so it doesn't show on docker run

A: Why don't you set the variable to empty or null? It will still exist but won't have a value which you can account for during runtime


text:
Q: Automation error when creating scatter plot I'm trying to create a scatter plot using VBA. The data source should be two disjoint columns. It even worked once. However after I filled one column of table using another VBA code it crashed. Tried to google it but to no avail. Hope someone could help!!
Sub XY_Chart()

    Dim r1, r2, rngDataSource As Range
    Dim iDataRowsCt As Long
    Dim iDataColsCt As Integer
    Dim iSrsIx As Integer
    Dim chtChart As Chart
    Dim srsNew As Series

    Set r1 = Application.ActiveSheet.Range("C2:C88111")
    Set r2 = Application.ActiveSheet.Range("E2:E88111")
    Set rngDataSource = Application.Union(r1, r2)
        With rngDataSource
            iDataRowsCt = .Rows.Count
            iDataColsCt = .Columns.Count
        End With
        '' Create the chart
        ActiveSheet.Unprotect
        Set chtChart = ActiveSheet.ChartObjects.Add( _
            Left:=ActiveSheet.Columns(ActiveWindow.ScrollColumn).Left + _
                ActiveWindow.Width / 4, _
            Width:=ActiveWindow.Width / 2, _
            Top:=ActiveSheet.Rows(ActiveWindow.ScrollRow).Top + _
                ActiveWindow.Height / 4, _
            Height:=ActiveWindow.Height / 2).Chart

        With chtChart
            .ChartType = xlXYScatterline

            '' Remove any series created with the chart
            Do Until .SeriesCollection.Count = 0
                .SeriesCollection(1).Delete
            Loop

            For iSrsIx = 1 To iDataColsCt - 1 Step 2
                '' Add each series
                Set srsNew = .SeriesCollection.NewSeries
                With srsNew
                    .Name = rngDataSource.Cells(1, iSrsIx + 1)
                    .Values = rngDataSource.Cells(2, iSrsIx + 1) _
                        .Resize(iDataRowsCt - 1, 1)
                    .XValues = rngDataSource.Cells(2, iSrsIx) _
                        .Resize(iDataRowsCt - 1, 1)
                End With
            Next
        End With
End Sub

And I have another piece of code that should do the same.
It gives mistake on
.Chart.PlotBy = xlRows
The mistake is Run-time error '-2147221504' (80040000)
Automation error
Invalid OLEVERB structure
Sub GRPH()

    Dim lastRow As Long
    Dim average, std As Double
    Dim cht  As Object
    Dim r1, r2, r3 As Range

    'Find the last Row with data in a Column
    With ActiveSheet
        lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With

        Set r1 = Application.ActiveSheet.Range("C2:C88111")
        Set r2 = Application.ActiveSheet.Range("E2:E88111")
        Set r3 = Application.Union(r1, r2)
        Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)

    With cht
        .Chart.SetSourceData Source:=r3
        .Chart.PlotBy = xlRows
        .ChartType = xlXYScatterLines
    End With

End Sub

A: Change your .ChartType to xlXYScatterlines. It'd be best during times like this to record a macro and get the proper chart type from there, especially when it's throwing an error on the chart type line. ;)


text:
Q: MySQL order by "id" first then by "date" I'm trying to order my table by active campaign first followed with the "endDate". Which means, new created campaigns will always be on top followed by the date. When the campaign ends, I want the latest "endDate" to be on top.
Here's my query below:
SELECT   campaignId,
         status,
         dateCreated,
         startDate,
         endDate
FROM     campaign
WHERE    deleted='False'
ORDER BY DATE(endDate) > DATE(CURDATE()) DESC, campaignId DESC

Looking at the screenshot below, some are not ordered by the "endDate" (highlighted with red box)

The first part is correct, which means the "endDate" haven't ends and is sorted by id first. However, the last part is wrong, ended campaigns should be sorted by the "endDate". Where I did wrong ?
Update SQL Fiddle (Please ignore  WHERE deleted='False' when using) : http://sqlfiddle.com/#!9/0a7afb

A: ORDER BY DATE(endDate) > DATE(CURDATE()) DESC says that future campaigns go first. It does not say in which order. Add the expression into the select clause and you will see.
You can do ORDER BY DATE(endDate) > DATE(CURDATE()) DESC, endDate DESC, campaignId DESC, but the DATE(endDate) > DATE(CURDATE()) expression makes sorting very slow and prevents use of an index. Moreover, you don't have to do DATE() on a date column.
If you want separate list of future campaigns and past campaigns, you better do two queries, putting the endDate condition into where clause. However, for small datasets it does not matter.

A: I've solved the problem by using "CASE" statement. Just in case someone find this useful.
    SELECT
     campaignId, status, dateCreated, startDate, endDate
   FROM campaign
   WHERE
       deleted='False'
   ORDER BY
       CASE WHEN endDate > CURDATE() THEN campaignId END DESC,
       CASE WHEN endDate < CURDATE() THEN DATE(endDate) END DESC

A:     SELECT
     campaignId, status, dateCreated, startDate, endDate
   FROM campaign
   WHERE
       deleted='False'
   ORDER BY
       DATE(endDate) DESC, campaignId DESC

This should work.
Basically you don't need  > condition in order by.
If you want to have filter for date greater than current date then it should be in where condition.


text:
Q: Syntax error with unioned tables This query works...
$stm = $pdo->prepare("SELECT T1.Taxon, T1.Rank, T2.Taxon, T2.Rank FROM     gz_life_reptiles_new T1
LEFT JOIN gz_life_reptiles_new T2 ON T2.Taxon = T1.Taxon
UNION
SELECT T1.Taxon, T1.Rank, T2.Taxon, T2.Rank FROM gz_life_reptiles_new T1
RIGHT JOIN gz_life_reptiles T2 ON T2.Taxon = T1.Taxon");
 $stm->execute(array(
));

However, I want to combine them into a single virtual table with the name "combined" so I can perform more operations, including GROUP BY, something like this...
$stm = $pdo->prepare("SELECT *
FROM (SELECT T1.Taxon, T1.Rank, T2.Taxon, T2.Rank FROM  gz_life_reptiles_new T1
LEFT JOIN gz_life_reptiles_new T2 ON T2.Taxon = T1.Taxon
UNION
SELECT T3.Taxon, T3.Rank, T4.Taxon, T4.Rank FROM gz_life_reptiles_new T3
RIGHT JOIN gz_life_reptiles T4 ON T4.Taxon = T3.Taxon
) AS Combined
GROUP BY Taxon");
 $stm->execute(array(
));

However, I didn't write it correctly. I get the error message #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') AS Combined
GROUP BY Taxon
LIMIT 0, 30' at line 6
Can anyone see what I'm doing wrong?

A: MySQL doesn't allow subqueries in the from clause for a view.  So, just do:
SELECT T1.Taxon, T1.Rank, T2.Taxon, T2.Rank
FROM  gz_life_reptiles_new T1 LEFT JOIN
      gz_life_reptiles_new T2
      ON T2.Taxon = T1.Taxon
UNION
SELECT T3.Taxon, T3.Rank, T4.Taxon, T4.Rank
FROM gz_life_reptiles_new T3 RIGHT JOIN
     gz_life_reptiles T4
     ON T4.Taxon = T3.Taxon;

The distinct probably does what you want for removing duplicates.  If not, then you have a challenge.
EDIT:
Okay, here is another method:
SELECT T1.Taxon, T1.Rank, T2.Taxon, T2.Rank
FROM  gz_life_reptiles_new T1 LEFT JOIN
      gz_life_reptiles_new T2
      ON T2.Taxon = T1.Taxon
UNION ALL
SELECT T3.Taxon, T3.Rank, T4.Taxon, T4.Rank
FROM gz_life_reptiles_new T3 RIGHT JOIN
     gz_life_reptiles T4
     ON T4.Taxon = T3.Taxon
WHERE NOT EXISTS (SELECT 1
                  FROM gz_life_reptiles_new T1
                  WHERE T4.Taxon = T1.Taxon
                 );

By the way, do you intend for the first LEFT JOIN to be on gz_life_reptiles_new twice?  The structure of your query is usually to approximate a FULL OUTER JOIN and the structure is: "FROM A LEFT JOIN B UNION ALL FROM B LEFT JOIN A".  That is, the same tables are in both queries.


text:
Q: logback cannot set timezone in Spring Boot App I have an example related with ELK in my Spring Boot. Even if I defined timezone in logback-spring.xml and set my timezone in dateFormat:tz of Kibana, timestamp in document is 3 hours back of timestamp. I think timezone cannot be detected.
Here is the screenshot shown below.
Image
Here is my project link : Project Link
How can I fix that issue?
Here is my logback-spring.xml shown below.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <property scope="context" name="log.fileExtension" value="log"/>
    <property scope="context" name="log.fileName" value="Springboot-Elk"/>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS,Europe/Istanbul}] [${HOSTNAME}] [%thread] %level %logger{36}@%method:%line - %msg%n</pattern>
        </layout>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log.fileName}.%d{yyyy-MM-dd}.${log.fileExtension}</fileNamePattern>
        </rollingPolicy>
        <encoder>
            <pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS,Europe/Istanbul}] [${HOSTNAME}] [%thread] %level %logger{36}@%method:%line - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="STASH" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
        <destination>logstash:5044</destination>
        <!-- encoder is required -->
        <encoder class="net.logstash.logback.encoder.LogstashEncoder">
            <timeZone>Europe/Istanbul</timeZone>
            <timestampPattern>yyyy-MM-dd HH:mm:ss.SSS,Europe/Istanbul</timestampPattern>
        </encoder>
        <keepAliveDuration>5 minutes</keepAliveDuration>
    </appender>

    <logger name="org.hibernate" level="ERROR">
        <appender-ref ref="STASH"/>
    </logger>

    <root level="ERROR">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="STASH"/>
        <appender-ref ref="FILE"/>
    </root>

    <root level="INFO">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="STASH"/>
        <appender-ref ref="FILE"/>
    </root>
</configuration>

A: Can you try changing console log appender tag to
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}{GMT+3}] [${HOSTNAME}] [%thread] %level %logger{36}@%method:%line - %msg%n</pattern>
        </layout>
    </appender>


text:
Q: VSS failure due to shadow storage size I have used VSS API to make snapshot of C:. The program fails with VSS exception. But when I try to create snapshot of same volume using VSS Admin it completes successfully.
I found the shadow storage space is less then 300 mb and hence it caused my program to fail. Increasing the space of shadow storage worked for me.
My questions are:

*

*How does VSS Admin work fine even if the shadowstorage space is less than 300MB?

*Why can't a program created using VSS API also create a snapshot?

What's missing?


text:
Q: Global configuration for http request headers I'm setting up a node-red flow. This flow have serveral http requests. Each of this http request nodes need the same header parameter. For example i set msg.headers["Authorization"]. However i have to set this parameter for each http request node with a change node. Is there away to define this globaly and inject this automaticly to http request node?

A: No
The closest you could do is to add a function or change node that adds the headers to a subflow then you can use instances of that subflow before each HTTP request node.
That way you only need to edit the subflow to change all the instances.


text:
Q: Fade in effect on one of the images on the page. I have an image on my webpage. The image is not the background but it covers almost 30% of the page. and the image is huge in size for a webpage(200KB). So when the image completes loading it just flashes on the page which looks very ugly. So I wanted the image to fade-in after its downloaded completely on the webpage. As the background color of the image and the background color of the web-page are the same it will look like a good animation. As if only the contents of the image are fading in. Any ways is it possible?

A: since you are using such a large image I'm going to assume that it is a JPG. And assuming you are not on a mobile device and it is flashing in, I am also going to assume that it is a baseline JPG. Wow, that's a lot of assumptions :)
I would recommend using a progressive JPG, it will load around the same time as a content it a rough form. It will progressively enhance it self in layers until it reaches full quality.
You can also wrap it in a div of the same dimensions to keep your content from jerking around.
If you want it to fade in you can add display:none; to you image and using jquery on document ready use the fadeIn method.
img {
    height:400px;
    width:400px;
    display:none;
}

<img id="myimg" src="http://placehold.it/400x400" >

$(document).ready(function() {
    $('#myimg').fadeIn('fast');
});


text:
Q: Missing node_events.{h,cc} in Node js causing build issues with old-ish package I'm experimenting with r-node, a package that relies on Node js. The package itself is a bit outdated, relying on node_events, an old file from the mid 2010s. At the build stage, it complains of the following:
src/binding.cc:24:10: fatal error: 'node_events.h' file not found
#include <node_events.h>
         ^
1 error generated.
make[1]: *** [src/binding.o] Error 1
make: *** [server] Error 2

node_events was removed from Node js circa 2 years ago: https://github.com/joyent/node/commit/4ef8f06fe62edb74fded0e817266cb6398e69f36#src/node_events.h
I'm wondering what the background is--why did the node js folks remove this particular file, and how would package writers update their end to keep up with this. Thanks.

A: As much as I understand node.js source code when it existed node_events.{h,cc} the platform used an emitter writed in C :
var EventEmitter = exports.EventEmitter = process.EventEmitter

But they realised that it would be much better to create an event emitter directly from javascript code:
var EventEmitter = NativeModule.require('events').EventEmitter;

lib/events.js:
function EventEmitter() {
      this.domain = null;
      if (exports.usingDomains) {
        // if there is an active domain, then attach to it.
        domain = domain || require('domain');
        if (domain.active && !(this instanceof domain.Domain)) {
          this.domain = domain.active;
        }
      }
      this._events = this._events || null;
      this._maxListeners = this._maxListeners || defaultMaxListeners;
    }
    exports.EventEmitter = EventEmitter;

So if you are using a package that uses the old event emitter just delete the inclusion #include <node_events.h>(with all deps) from the sources that you want to update and recompile again.


text:
Q: Unable to pass data into Generic DetailView in django I am trying to pass two models to my template view. The problem is that no data shows up in the view.
Here is some code that I have tried:
 # views.py
 class ServiceDetailView(generic.DetailView):
      model = Service
      template_name = "service_detail.html"

      def get_context_data(self, **kwargs):
           context = super(ServiceDetailView, self).get_context_data(**kwargs)
           context['prices'] = Price.objects.filter(service__serviceid=self.kwargs.get('pk'))
           return context

 #service_detail.html

Other Hospital Descriptions

       {% for price in prices.price_value.all %}

price

       {% endfor %}

Nothing is passed. Service_id is the primary key and price is linked to the service table.

A: If you are already passing prices queryset, then why are using price_value? I think this code will work just fine:

Other Hospital Descriptions

   {% for price in prices %}

{{ price }}

   {% endfor %}

Or if Price model has a related_name in ForeignKey to Service named price_value, then the following code will work as well:

Other Hospital Descriptions

   {% for price in object.price_value.all %}

{{ price }}

   {% endfor %}

In that case, you don't need to pass the Price queryset.
Or if it does not have any related_name, then {% for price in  object.price_set.all %} will work as well.


text:
Q: Selecting certain data to show in console from an Array (Java) I have a JSON file with the structure
{
    "Search": {
        "CarInfo": [
            {
                "name": "Focus",
                "price": 107.25,
                "supplier": "Ford",
                "rating": 5.4
            }
        ]
    }
}

I've put this into an array after parsing, and now I want to print the array so that it just shows name and price, for example, of all the cars (20+ cars in my JSON).
So far, I can only get it to print the full pointer of the array, so the full (name,price,supplier & rating).
for (int i = 0; i < list.size(); i++) {
    System.out.println(list.get(i));
}

I've tried to use contains("name"), and that won't work. Just wondering if there is a way around this to just print out what I want, or if there is a different way and I've approached this wrong.


text:
Q: ASP.net MVC page - show in progress and run some task in background While I was working in windows application, we show loading in progress message and don't freeze the application and run the required process in background. How to handle the same process in ASP.Net MVC application
For example, I am listing student list in a page. Also there is Upload button which gives more students list. On click of upload button after file s selected, screen will be inaccessible until it completes the process of reading the content from file and convert it into database and refresh the grid. Can we have some background process which will not freeze the page

A: When you have long running task which is taking too much time to complete and the user has to wait until it's not completed, in this situation you have to write background tasks in your ASP.NET website.
Such as HangFire (or similar similar open source libraries) used for writing background tasks in your ASP.NET website.


text:
Q: How can i solve Magmi - Update Disabled Error When i try o upload images using magmi, i get error like,

A: The upload/upgrade feature has been removed because it enabled exploits.
Relevant code change: https://sourceforge.net/p/magmi/git/ci/875893212a9c0a89d018466d023bd2fbd339dbb0/
If you revert this (i.e. change if(false) to if($zipok) etc.), you will be able to use the feature again, but you have to be absolutely sure that

*

*nobody except you has access to the Magmi web interface (for example, add  HTTP authentication or IP restriction) - Magmi itself does not secure access out of the box

*you upload the update from a trusted source

That being said, you are talking about uploading images. Did you try to upload an image in the "Update Magmi" form? That's not how it works. Upload the images to media/import in the Magento directory, using SFTP, then specify the image file names in the CSV as described here:
http://wiki.magmi.org/index.php?title=Image_attributes_processor#Image_Import_Mode


text:
Q: Export function only to module test? I use the standard way (according to the Rust book) to write unit tests:
fn func() -> i32 {
    0
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn func_test() {
        let res = func();
    }
}

to make it compile, I have to make func public via the pub keyword.
Is it possible to make func private, but use it inside the inner test module?

A: As of Rust 1.15 your code works without problems!
Previously only public symbols were imported via a wildcard-import (like use super::*;). This behavior changed as specified in RFC 1560. You can see my full previous answer in the edit logs.


text:
Q: Selecting all sub children when Checkbox of child is checked in treeview using jquery I am using this jquery to select all the children when a parent is clicked and it is working fine.
$(document).ready(function () {
    $("div[id $= Tree_Index]").find("input[type=checkbox]:first").click(function () {
        $(this).closest("div").find(':checkbox').attr('checked', this.checked);
    });
});

Now, if i have a sub child for a child, i want to select all the sub children when a child is selected. How can I achieve this in jquery.

                	<input type="checkbox" id="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn0CheckBox" name="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn0CheckBox">Clinics

		<input type="checkbox" id="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn1CheckBox" name="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn1CheckBox">GP Clinics

		<input type="checkbox" id="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn2CheckBox" name="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn2CheckBox">CDMP Participating Clinics

		<input type="checkbox" id="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn3CheckBox" name="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn3CheckBox">CHAS Participating Clinics - Dental

		<input type="checkbox" id="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn4CheckBox" name="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn4CheckBox">CHAS Participating Clinics – Medical

		<input type="checkbox" id="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn5CheckBox" name="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn5CheckBox">IDAPE/ElderShield Disability Assessors

		<input type="checkbox" id="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn6CheckBox" name="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn6CheckBox">Other GP Clinics

		<input type="checkbox" id="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn7CheckBox" name="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn7CheckBox">Other Clinics

		<input type="checkbox" id="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn8CheckBox" name="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn8CheckBox">Community Geriatric Clinics

		<input type="checkbox" id="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn9CheckBox" name="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn9CheckBox">Community VWO Clinics

		<input type="checkbox" id="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn10CheckBox" name="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn10CheckBox">Counselling Service

		<input type="checkbox" id="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn11CheckBox" name="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn11CheckBox">Physiotherapy Service

		<input type="checkbox" id="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn12CheckBox" name="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn12CheckBox">Private Medical Centres

		<input type="checkbox" id="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn13CheckBox" name="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn13CheckBox">Psychiatric Outpatient Rehabilitation Centres

		<input type="checkbox" id="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn14CheckBox" name="ctl00_cphMain_ctlEsnSearchByServices_Treecontrol_Left_0_Tree_Indexn14CheckBox">Polyclinics

A: Use prop() and change event (better than click) instead:
$(document).ready(function () {
    $("div[id $= Tree_Index]").find("input[type=checkbox]:first").change(function () {
        $(this).closest("div").find(':checkbox').prop('checked', this.checked);
    });
});

A: Working jsFiddle Demo
Your markup is so complex. So, the best way to make a relation between
your parents and childs is using attributes instead of
hierarchy of your HTML.
Consider the following markup:

<input type="checkbox" data-rel="parent" data-id="1" />Parent 1

<input type="checkbox" data-rel="child" data-id="1" />Child 1.1

<input type="checkbox" data-rel="child" data-id="1" />Child 1.2

<input type="checkbox" data-rel="child" data-id="1" />Child 1.3

<input type="checkbox" data-rel="child" data-id="1" />Child 1.4

<input type="checkbox" data-rel="parent" data-id="2" />Parent 2

<input type="checkbox" data-rel="child" data-id="2" />Child 2.1

<input type="checkbox" data-rel="child" data-id="2" />Child 2.2

<input type="checkbox" data-rel="child" data-id="2" />Child 2.3

<input type="checkbox" data-rel="child" data-id="2" />Child 2.4

As you can see, I make a relation between parents and child
with data-rel and data-id attributes.
Then in your jQuery code:
$(document).ready(function () {
    // whenever the parent checkbox changed
    $(':checkbox[data-rel="parent"]').on('change', function () {
        // get the current group by data-id attribute
        var id = $(this).attr('data-id');

        // get childs checkboxes within the current group
        $(':checkbox[data-rel="child"][data-id="' + id + '"]').prop('checked', this.checked);
    });
});

Working jsFiddle Demo
Because you said that you can't change your markup (as it's a controller in ASP.net), here
is the solution to your markup:
$(function () {
    $('.tree').on('change', ':checkbox', function () {
        var checked = this.checked;
        var $elem = $(this).closest('table');
        var depth = $elem.find('div').length;
        var $childs = $elem.nextAll('table');
        $childs.each(function () {
            var $child = $(this);
            var d = $child.find('div').length;
            if (d <= depth) {
                return false;
            }

            $child.find(':checkbox').prop('checked', checked);
        });
    });
});

*

*[!] Don't forget to check the jsFiddle Demo.

A: It is quite hard with the markup you have, webforms is well know for producing horrible markup like this. The main problem is the hierarchical nature of the tree view is not actually reflected in a hierarchy in the markup. Having said that, the following javascript is a way of achieving the result you are looking for.
Fiddle here: http://jsfiddle.net/sLngS/
 $(document).ready(function () {
        $("input:checkbox").change(function () {
           var currentLevel = $(this).parents('tr').children('td').length;
           var isChecked = $(this).prop('checked');
            $('tr').each(function(index, value){
                var level = $('td',this).length;
                if (level >= (currentLevel + 1)){
                    $("input:checkbox", this).prop('checked', isChecked);
                }
            })
        });
    });


text:
Q: matlab, how do i write a statement that will give me time on xaxis from y=0.3 x=[0:.01:10];
y=(x.^2).*(exp(-x));

plot(x,y), grid
y1=max(y);

xlabel('TIME');
ylabel('CONCENTRATION IN BLOOD');
title('CONCENTRATIN OF SUSTANCE IN BLOOD vs TIME');

fprintf('(a) The maximum concentraion is %f \n',y1)

That's my program, and I'm having trouble to write a statement that will give me the time at when y=0.3 please assist
thank you

A: One key issue here is that there are multiple points on your plot where y = 0.3. If you want to find all of them in a simple way, you can follow these steps:

*

*Subtract 0.3 from your vector y, so that the points you want to find become zero crossings.

*Find the indices in the above vector where there is a sign change.

*For the y values on either side of the zero crossings, compute the percentage of the difference between them at which the value 0.3 lies. This essentially performs a linear interpolation between the two points on either side of the zero crossing.

*Use the above percentage to find the corresponding value of x for the zero crossing.

And here's the code along with a plot to show the points found:
>> yDesired = 0.3;
>> index = find(diff(sign(y-yDesired)));
>> pctOfDiff = (yDesired-y(index))./(y(index+1)-y(index));
>> xDesired = x(index)+pctOfDiff.*(x(index+1)-x(index))

xDesired =

    0.8291    3.9528

>> plot(x,y);
>> hold on;
>> plot(xDesired,yDesired,'r*')
>> xlabel('x');
>> ylabel('y');

A: A straightforward answer is:
find(min(abs(y- 0.3))== abs(y- 0.3))

giving
ans = 84

thus
x(84)
ans = 0.83000

Now, if you increase the resolution in x, you'll also be able to find a solution closer to the analytical one.
> x=[0.5:.000001:1]; y=(x.^2).*(exp(-x));
> x(find(min(abs(y- 0.3))== abs(y- 0.3)))
ans =  0.82907

Edit:
And of'course in order to find all zeros:
> x=[0:.01:10]; y=(x.^2).*(exp(-x));
2> find(abs(y- 0.3)< 1e-3)
ans =
    84   396
> x(find(abs(y- 0.3)< 1e-3))
ans =
   0.83000   3.95000

A: If you have the symbolic toolbox in MATLAB, you can do the following
syms x
x=solve('x^2*exp(-x)=y')

x=
  (-2)*lambertw(k, -((-1)^l*y^(1/2))/2)

Here lambertw is the solution to y=x*exp(x), which is available as a function in MATLAB. So you can now define a function as,
t=@(y,k,l)(-2)*lambertw(k, -((-1)^l*y^(1/2))/2)

lambertw is a multivalued function with several branches. The variable k lets you choose a branch of the solution. You need the principal branch, hence k=0. l (lower case L) is just to pick the appropriate square root of y. We need the positive square root, hence l=0. Therefore,  you can get the value of t or the time for any value of y by using the function.
So using your example, t(0.3,0,0) gives 0.8291.
EDIT
I forgot that there are two branches of the solution that give you real outputs (gnovice's answer reminded me of that). So, for both solutions, use
t(0.3,[0,-1],0)

which gives 0.8921 and 3.9528.

A: An easier way to find the index (and therefore x-value) is:
[minDiff, index] = min(abs(y-0.3))

minDiff =

  3.9435e-004

index =

    84

 x(index)

ans =

    0.8300

A: In addition to the solutions already posted, I am adding other ways to solve the problem:
f = @(x) (x.^2).*(exp(-x));             %# function handle
y0 = 0.3;

format long

%# find root of function near s0
x1 = fzero(@(x)f(x)-y0, 1)              %# find solution near x=1
x2 = fzero(@(x)f(x)-y0, 3)              %# find solution near x=3

%# find minimum of function in range [s1,s2]
x1 = fminbnd(@(x)abs(f(x)-y0), 0, 2)    %# find solution in the range x∈[0,2]
x2 = fminbnd(@(x)abs(f(x)-y0), 2, 4)    %# find solution in the range x∈[2,4]


text:
Q: Heroku выдает ошибку при загрузке файлов на сторонний ftp Пользуюсь Paperclip и Хероку. При создании поста (модель Post) Paperclip загружает файлы с помощью гема "paperclip-storage-ftp" на сторонний ФТП. На локальной машине все грузится и показывает нормально, но после деплоя на Хероку при создании поста вылетает ошибка "We're sorry, but something went wrong." и пост не создается. Логи выдают следующее:
2016-05-14T13:50:25.610993+00:00 app[web.1]: [paperclip] saving ftp://user@ftp.site.com:public_html/site.com/paperclip/images/9/medium/heroku-og-cad174838a49b266550809e29026ec9bc18e056dae8f9cf523ea4237379691f9.png
2016-05-14T13:50:25.610833+00:00 app[web.1]: [paperclip] saving ftp://user@ftp.site.com:public_html/site.com/paperclip/images/9/small/heroku-og-cad174838a49b266550809e29026ec9bc18e056dae8f9cf523ea4237379691f9.png
2016-05-14T13:50:25.610678+00:00 app[web.1]: [paperclip] saving ftp://user@ftp.site.com:public_html/site.com/paperclip/images/9/original/heroku-og-cad174838a49b266550809e29026ec9bc18e056dae8f9cf523ea4237379691f9.png
2016-05-14T13:50:26.139144+00:00 app[web.1]:    (2.2ms)  ROLLBACK
2016-05-14T13:50:26.141032+00:00 app[web.1]: ):
2016-05-14T13:50:26.139691+00:00 app[web.1]: Completed 500 Internal Server Error in 3926ms (ActiveRecord: 24.5ms)
2016-05-14T13:50:26.141022+00:00 app[web.1]:
2016-05-14T13:50:26.141031+00:00 app[web.1]: Net::FTPPermError (500 I won't open a connection to 172.18.180.250 (only to 23.23.61.72)
2016-05-14T13:50:26.141038+00:00 app[web.1]:   vendor/ruby-2.2.4/lib/ruby/2.2.0/net/ftp.rb:418:in `transfercmd'
2016-05-14T13:50:26.141036+00:00 app[web.1]:   vendor/ruby-2.2.4/lib/ruby/2.2.0/monitor.rb:211:in `mon_synchronize'
2016-05-14T13:50:26.141038+00:00 app[web.1]:   vendor/ruby-2.2.4/lib/ruby/2.2.0/net/ftp.rb:513:in `block (2 levels) in retrlines'
2016-05-14T13:50:26.141035+00:00 app[web.1]:   vendor/ruby-2.2.4/lib/ruby/2.2.0/net/ftp.rb:362:in `block in voidcmd'
2016-05-14T13:50:26.140951+00:00 heroku[router]: at=info method=POST path="/posts" host=arcane-taiga-31170.herokuapp.com request_id=6ad00282-fea1-44d3-aa16-7c59877f7954 fwd="92.100.238.86" dyno=web.1 connect=1ms service=4237ms status=500 bytes=1714
2016-05-14T13:50:26.141037+00:00 app[web.1]:   vendor/ruby-2.2.4/lib/ruby/2.2.0/net/ftp.rb:376:in `sendport'
2016-05-14T13:50:26.141036+00:00 app[web.1]:   vendor/ruby-2.2.4/lib/ruby/2.2.0/net/ftp.rb:360:in `voidcmd'
2016-05-14T13:50:26.141033+00:00 app[web.1]:   vendor/ruby-2.2.4/lib/ruby/2.2.0/net/ftp.rb:327:in `getresp'
2016-05-14T13:50:26.141034+00:00 app[web.1]:   vendor/ruby-2.2.4/lib/ruby/2.2.0/net/ftp.rb:339:in `voidresp'
2016-05-14T13:50:26.141040+00:00 app[web.1]:   vendor/ruby-2.2.4/lib/ruby/2.2.0/monitor.rb:211:in `mon_synchronize'
2016-05-14T13:50:26.141039+00:00 app[web.1]:   vendor/ruby-2.2.4/lib/ruby/2.2.0/net/ftp.rb:199:in `with_binary'
2016-05-14T13:50:26.141043+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/paperclip-storage-ftp-1.2.7/lib/paperclip/storage/ftp/server.rb:103:in `mktree'
2016-05-14T13:50:26.141040+00:00 app[web.1]:   vendor/ruby-2.2.4/lib/ruby/2.2.0/net/ftp.rb:511:in `block in retrlines'
2016-05-14T13:50:26.141045+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/paperclip-storage-ftp-1.2.7/lib/paperclip/storage/ftp.rb:49:in `block (3 levels) in flush_writes'
2016-05-14T13:50:26.141042+00:00 app[web.1]:   vendor/ruby-2.2.4/lib/ruby/2.2.0/net/ftp.rb:743:in `nlst'
2016-05-14T13:50:26.141046+00:00 app[web.1]:
2016-05-14T13:50:26.141041+00:00 app[web.1]:   vendor/ruby-2.2.4/lib/ruby/2.2.0/net/ftp.rb:510:in `retrlines'
2016-05-14T13:50:26.141044+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/paperclip-storage-ftp-1.2.7/lib/paperclip/storage/ftp/server.rb:68:in `put_files'

Установки Paperclip в модели Post:
has_attached_file :image, styles: { small: "350x250>", medium: "700x500#" },
                    default_url: "/images/:style/missing.png",
                    :storage => :ftp,
                    :path => "public_html/site.com/paperclip/:attachment/:id/:style/:filename",
                    :url => "http://site.com/paperclip/:attachment/:id/:style/:filename",
                    :ftp_servers => [
                        {
                            :host     => "ftp.site.com",
                            :user     => "user",
                            :password => "password"
                        },
                    ],
                    :ftp_connect_timeout => 5, # optional, nil by default (OS default timeout)
                    :ftp_ignore_failing_connections => true, # optional, false by default
                    :ftp_keep_empty_directories => true # optional, false by default

A: Проблема решена добавлением строки ":passive  => true" в файле модели:
:ftp_servers => [
                        {
                            :host     => "site.com",
                            :user     => "user",
                            :password => "password",
                            :passive  => true
}


text:
Q: Is it possible to change a row color based on time and whether a cell is empty or not? I have a spreadsheet that has 2 sheets (Sheet1 and Sheet2). Sheet1 is connected to a form to receive responses, while Sheet2 is just a copy of information from Sheet1 with sorting and formatting using the ImportRange function. The form responses only uses column A:G while column H and I will be filled in later.
After a response is received the color of the row where the the response is will change to Yellow. After column H is filled, the row color will change to Blue, and after I is filled, turns to Green.
Is it possible or not using Conditional Formatting or Google App Script that if after a response is received (row turns Yellow), if within 5 minutes there's no data entered into column H, the row for column A:G changes to "Red" and will only changes to "Blue" after H is filled in?
So far, I have only tried using Conditional Formatting where I used the Custom Formula is... =$G2<>"" condition.
Apart from that someone suggested using the following code on App Script(using differences between Unixtime) but I couldn't get it to work properly (it doesn't turn "Red" after 10 minutes, it just stay as yellow):
function myFunction() {
  ss = SpreadsheetApp.getActiveSpreadsheet().getDataRange();

  var unixStart = new Date(1970, 1, 1, 0, 0, 0);
  var nowDate = ss.getCell(2, 13).getValue() - (unixStart * 86400);
  var rows = ss.getLastRow();

  for (var i = 2; i <= rows; i++){
   var checkTime = ss.getCell(i, 7).getValue() - (unixStart * 86400);
    if (nowDate - checkTime < 600000){
      SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRange(i, 1, 1, 7).setBackground("yellow");
    }
  }
}

A: You can color cells based on time without having to use Apps Script, which keeps your file simpler.
For your use case, you can do this by controlling your limit with a helper column with this formula:
=time_stamp + 5/24/60

where time_stamp is the timestamp produced by Forms. This will add 5 minutes to when the form is submitted automatically.
You can then use this new column as one of the rules in conditional formatting for the cells in the range A:G, with this formula:
=AND(NOW()>time_stamp_plus_5, $H2="", $I2="")

and set the fill color to red. This will change all of the cells within A:G, which meet the following 3 conditions, to red color:

*

*The current time as determined by NOW() is after 5 minutes after the form submission.

*Column H is empty.

*Column I is empty.

You can then add the additional rules as usual for the yellow, blue, and green coloring:

*

*Yellow: =$time_stamp<>""

*Blue: =$H2<>""

*Green: =$I2<>""
The only hiccup is that, by default, NOW() only recalculates when a change is made on the form. You can tell it to recalculate automatically every minute by going to File > Spreadsheet settings > Calculation > Recalculation and set it to "On change and every minute". This will make sure that NOW() always updates every minute.

As you stated in the comments, there is a confounding issue for your setup with the way you sorted the newest form submissions first. I would suggest submitting a separate question for that issue to see whether some workarounds can be made for your setup.


text:
Q: CSS input styling and overflow issues I would love to style my input field very similar to the divs I am building. However, I am unable to solve sizing issues.
Here is an example
http://codepen.io/anon/pen/kLwlm
And here is one more (with overflow:visible and fixed height)
http://codepen.io/anon/pen/Fxjzf
As you can see, it looks very different than the divs, and no matter what I tried, I could not make them look similar. First of all, I would love to make the input in a way that the text will pop put (overflow: visible? not working).
Secondly, the height should be similar to the divs. Setting the height and line-height properties does seem to effect the temporary text, but when it's clicked (and started to type) it breaks. (check second example)
Shortly, open to suggestions.

A: Try this solution here:
@import url(http://fonts.googleapis.com/css?family=Playfair+Display:400,700,900,400italic,700italic,900italic);

body {
  margin: 100px;
  background-color: #f7f7f7;
}
input{
  border:0;
}

div, input{
  font-family: 'Playfair Display', serif;
  font-size: 40px;
  background-color: #ff44ff;
  width: 100%;
  margin-top: 20px;
  line-height: 40px;
}

div {
  padding: 1px 0px 13px 2px;
  color: #999;
}

A: I tried placing the input in div and then making the input background to transparent. YOu can play with the spacing to you liking, but it works http://codepen.io/anon/pen/Brcpl

A: I came up with this JSFiddle. I removed the line-height and positioned text using padding instead (that fixed the aligning of the input text).I also styled the placeholder. Here is a part of your CSS which I changed (do read the notes in it).
div, input{
  font-family: 'Playfair Display', serif;
  font-size: 40px;
  background-color: #ff44ff;
  width: 100%;
  margin-top: 20px;
  padding: 5px 0px 5px 0px;/*use padding to adapt the size*/
}
/*Change placeholder properties*/
#s::-webkit-input-placeholder {
   color: black;
}
#s:-moz-placeholder { /* Firefox 18- */
   color: black;
}
#s::-moz-placeholder {  /* Firefox 19+ */
   color: black;
}
#s:-ms-input-placeholder {
   color: black;
}

PS: I do suggest styling the input-box differently so the visitors of your website notice it is actually a input-box.

A: What about this one: http://codepen.io/anon/pen/lcgAD
css
div input {
  border: none;
  font-size: 40px;
  width: 100%;
  background: transparent;
  color: #000;
  font-family: 'Playfair Display', serif;
}

div input:hover {

}

div {
  color: #000;
  background-color: #892;
  height: 41px;
}

html
<div>
  <input placeholder="Enter E-Mail ayxml@gmail.com" value="Enter E-Mail ayxml@gmail.com"/>
</div>


text:
Q: Nullpointer exception in Spring Java Project with Swing GUI Hell Everyone,
I am new to spring, java programming. I have created a java program which is supposed to access the database on the action of click, but I do not know why I am getting nullpointer exception because all the object is being set properly.
Swing Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ibm.quest.taxonomyupdate.ui;

import com.ibm.quest.taxonomyupdate.model.TypeCategory;
import com.ibm.quest.taxonomyupdate.model.TypeCategoryJDBCTemplate;
import javax.swing.ButtonGroup;

/**
 *
 * @author Ashish Tyagi
 */
public class ApplicationWindow extends javax.swing.JFrame {
    TypeCategoryJDBCTemplate typeCategoryJDBCtemplate;

    /**
     * Creates new form ApplicationWindow
     */

    public void setTypeCategoryJDBCtemplate(TypeCategoryJDBCTemplate typeCategoryJDBCtemplate) {
        this.typeCategoryJDBCtemplate = typeCategoryJDBCtemplate;
        System.err.println("setter in the application window "+this.typeCategoryJDBCtemplate);
    }

    public ApplicationWindow() {
        initComponents();
        addRadioButtonInGroup();
        setTitle("Taxonomy Updator");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        buttonGroup = new javax.swing.ButtonGroup();
        infoLabel = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        searchButton = new javax.swing.JButton();
        beginButton = new javax.swing.JRadioButton();
        endButton = new javax.swing.JRadioButton();
        exactButton = new javax.swing.JRadioButton();
        anywhereButton = new javax.swing.JRadioButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        closeButton = new javax.swing.JButton();
        updateAllButton = new javax.swing.JButton();
        updateButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        infoLabel.setText("Please enter the text you wants to search");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(11, 10, 0, 0);
        getContentPane().add(infoLabel, gridBagConstraints);

        jTextField1.setText("jTextField1");
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 10;
        gridBagConstraints.ipadx = 279;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(6, 10, 0, 0);
        getContentPane().add(jTextField1, gridBagConstraints);

        searchButton.setText("Search");
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 19;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 25;
        gridBagConstraints.ipadx = 17;
        gridBagConstraints.ipady = -3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(6, 6, 0, 10);
        getContentPane().add(searchButton, gridBagConstraints);

        beginButton.setText("Begin with");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(2, 10, 0, 0);
        getContentPane().add(beginButton, gridBagConstraints);

        endButton.setText("End with");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(2, 0, 0, 0);
        getContentPane().add(endButton, gridBagConstraints);

        exactButton.setText("Exact Match");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 5;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(2, 0, 0, 0);
        getContentPane().add(exactButton, gridBagConstraints);

        anywhereButton.setText("Anywhere");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 9;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 11;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(2, 0, 0, 0);
        getContentPane().add(anywhereButton, gridBagConstraints);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 44;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipadx = 351;
        gridBagConstraints.ipady = 60;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(2, 10, 0, 10);
        getContentPane().add(jScrollPane1, gridBagConstraints);

        closeButton.setText("Close");
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 43;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(175, 6, 0, 10);
        getContentPane().add(closeButton, gridBagConstraints);

        updateAllButton.setText("Update All");
        updateAllButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateAllButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 6;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.gridwidth = 24;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(175, 6, 0, 0);
        getContentPane().add(updateAllButton, gridBagConstraints);

        updateButton.setText("Update");
        updateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.gridwidth = 4;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(175, 8, 0, 0);
        getContentPane().add(updateButton, gridBagConstraints);

        pack();
    }// </editor-fold>

private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {
    String text = jTextField1.getText();
    java.util.List<TypeCategory> records = this.typeCategoryJDBCtemplate.listTypeCategory(text);
    for(TypeCategory value:records)
    System.out.println(value.getDescription()+"  "+value.getTaxonomydescription());
}

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void updateAllButtonActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        this.dispose();
    }

    /**
     * @param args the command line arguments
     */
    public void start() {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ApplicationWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ApplicationWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ApplicationWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ApplicationWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ApplicationWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JRadioButton anywhereButton;
    private javax.swing.JRadioButton beginButton;
    private javax.swing.ButtonGroup buttonGroup;
    private javax.swing.JButton closeButton;
    private javax.swing.JRadioButton endButton;
    private javax.swing.JRadioButton exactButton;
    private javax.swing.JLabel infoLabel;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JButton searchButton;
    private javax.swing.JButton updateAllButton;
    private javax.swing.JButton updateButton;
    // End of variables declaration

    private void addRadioButtonInGroup() {
        buttonGroup = new ButtonGroup();
        buttonGroup.add(beginButton);
        buttonGroup.add(endButton);
        buttonGroup.add(exactButton);
        buttonGroup.add(anywhereButton);
    }
}

Main File:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ibm.quest.taxonomyupdate;
import com.ibm.quest.taxonomyupdate.model.TypeCategoryJDBCTemplate;
import org.springframework.context.ApplicationContext;
import com.ibm.quest.taxonomyupdate.ui.ApplicationWindow;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author Ashish Tyagi
 */
public class TaxonomyUpdater {
    public static void main(String [] args){
        ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Config.xml");
        ApplicationWindow window= (ApplicationWindow) context.getBean("applicationWindow");
        window.start();
//        TypeCategoryJDBCTemplate typecategoryJDBCTemplate = (TypeCategoryJDBCTemplate)context.getBean("typeCategoryJDBCTemplate");
//        window.setTypeCategoryJDBCtemplate(typecategoryJDBCTemplate);
//        List<TypeCategory> records=typecategoryJDBCTemplate.listTypeCategory("Q2%");
//        for(TypeCategory value:records)
//            System.out.println(value.getTypecatind()+"  "+value.getDescription()+" "+value.getTaxonomydescription());
    }

}

Spring-Config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:flow="http://www.springframework.org/schema/webflow-config"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:jms="http://www.springframework.org/schema/jms"
       xmlns:lang="http://www.springframework.org/schema/lang"
       xmlns:osgi="http://www.springframework.org/schema/osgi"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:util="http://www.springframework.org/schema/util"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
          http://www.springframework.org/schema/webflow-config http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd
          http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
          http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.2.xsd
          http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.2.xsd
          http://www.springframework.org/schema/osgi http://www.springframework.org/schema/osgi/spring-osgi-1.2.xsd
          http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
          http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
">
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver" />
        <property name="url" value="jdbc:db2://sample.sample.com:3798/sampledb"/>
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>
    <bean id="typeCategoryJDBCTemplate" class="com.ibm.quest.taxonomyupdate.model.TypeCategoryJDBCTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <bean id="applicationWindow" class="com.ibm.quest.taxonomyupdate.ui.ApplicationWindow">
        <property name="typeCategoryJDBCtemplate" ref="typeCategoryJDBCTemplate" />
    </bean>

</beans>

Logs which is verifying that object is being created but still null pointer exception.
Mar 17, 2013 12:24:51 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.ibm.db2.jcc.DB2Driver
Inside the setDataSoureorg.springframework.jdbc.datasource.DriverManagerDataSource@4389b7
setter in the application window com.ibm.quest.taxonomyupdate.model.TypeCategoryJDBCTemplate@18c6fd4
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at com.ibm.quest.taxonomyupdate.ui.ApplicationWindow.searchButtonActionPerformed(ApplicationWindow.java:207)
    at com.ibm.quest.taxonomyupdate.ui.ApplicationWindow.access$100(ApplicationWindow.java:15)
    at com.ibm.quest.taxonomyupdate.ui.ApplicationWindow$2.actionPerformed(ApplicationWindow.java:88)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6505)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6270)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4861)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.java:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2719)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729)
    at java.awt.EventQueue.access$200(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:688)
    at java.awt.EventQueue$3.run(EventQueue.java:686)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:702)
    at java.awt.EventQueue$4.run(EventQueue.java:700)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:699)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

A: Thanks all for looking into it, but I have found the problem in my code which was to create the window in ApplicatoinWindow -> start() method. It was creating the object and returning the control.
 /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new ApplicationWindow().setVisible(true);
        }
    });

I changed it to
        /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            setVisible(true);
        }
    });


text:
Q: Error getting window size on android: "The method getWindowManager is undefined" I need to get the window height and the weight.
I have this in my code:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
width1 = metrics.widthPixels;
height1 = metrics.heightPixels;

but I have an error:

The method getWindowManager is undefined

what i should import for this?
or i can get the sizes of the screed in different ways?
i have imported
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;
import android.content.Context;
import android.util.DisplayMetrics;

A: Use this:
 display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
 display.getWidth(); // to get width of the screen
 display.getHeight(); // to get height of the Screen

UPDATE
Please review the Android-Developer site. For more reference.
You can use below snippet of code to fetch height-width of the device.
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

A: Where are you using this code?
The error of the getWindowManager says that cannot find the method because the root of your class doesn't have it.
Try this:
((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(metrics);

or
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
  .getDefaultDisplay().getMetrics(metrics);

If this doesn't work, please paste your activity

A: Use the Context of the activity with getActivityContext()
DisplayMetrics metrics = new DisplayMetrics();
getActivityContext().getWindowManager().getDefaultDisplay().getMetrics(metrics);
width1 = metrics.widthPixels;
height1 = metrics.heightPixels;

A: You could use this for example if you are using it inside a fragment:
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);

A: Please check if you are calling above method in an activity class, or outside activity.
For Wallpaper, this method is not availed to you to get height or width of window, you need to get width and height of available window by using surface.

A: it works for me
import android.app.Activity;

((Activity)getContext()).getWindowManager().getDefaultDisplay().getMetrics(metrics);

mediaProjectionManager = (MediaProjectionManager)((Activity) getContext()).getSystemService(Context.MEDIA_PROJECTION_SERVICE);


text:
Q: React Spring useTransition renders first item three times Having a problem with useTransition, console logging transitions is outputting Menu three times instead Menu1, Menu2, Menu3
Ttransition.map also renders Menu1 three times
const [items, setItems] = useState([{ text: 'Menu1'}, { text: 'Menu2'}, { text: 'Menu3'}]);

const transitions = useTransition(items, item => item, {
        from: { transform: 'translate3d(0,-40px,0)', opacity: '0' },
        enter: { transform: 'translate3d(0,0px,0)', opacity: '1'},
        leave: { transform: 'translate3d(0,-40px,0)', opacity: '0'},
    })

return (
    <Menu style={animatonmenu}>

        {transitions.map(({ item, props, key }) =>
            <animated.li key={key} style={props} onClick={() => setClicked(true)}>{item.text}</animated.li>
        )}

    </Menu>
)};

A: From looking at the documentation on useTransition the problem seems to be this part:
const transitions = useTransition(items, (item) => item, {
    from: { transform: "translate3d(0,-40px,0)", opacity: "0" },
    enter: { transform: "translate3d(0,0px,0)", opacity: "1" },
    leave: { transform: "translate3d(0,-40px,0)", opacity: "0" }
});

Instead of doing (item) => item you should do (item) => item.key. Because otherwise react-spring is probably not able to uniquely identify each item.
So instead you should do something like this:
export default function App() {
  const [items, setItems] = useState([
    { key: 1, text: "Menu1" },
    { key: 2, text: "Menu2" },
    { key: 3, text: "Menu3" }
  ]);

  const transitions = useTransition(items, (item) => item.key, {
    from: { transform: "translate3d(0,-40px,0)", opacity: "0" },
    enter: { transform: "translate3d(0,0px,0)", opacity: "1" },
    leave: { transform: "translate3d(0,-40px,0)", opacity: "0" }
  });

  return (

        {transitions.map(({ item, props, key }) => (
          <animated.li key={key} style={props}>
            {item.text}
          </animated.li>
        ))}

  );
}