text:
Q: Aggregate text based on a criteria On a previous question I asked a similar question that relied on a helper table to be a part of the criteria for splitting the data. It seems that my current goal is easier, but I couldn't figure it out.
Given the table:
CREATE TABLE conversations (id int, record_id int, is_response bool, text text);
INSERT INTO conversations VALUES
  (1,  1,  false, 'in text 1')
, (2,  1,  true , 'response text 1')
, (3,  1,  false, 'in text 2')
, (4,  1,  true , 'response text 2')
, (5,  1,  true , 'response text 3')
, (6,  2,  false, 'in text 1')
, (7,  2,  true , 'response text 1')
, (8,  2,  false, 'in text 2')
, (9,  2,  true , 'response text 2')
, (10, 2,  true , 'response text 3');

I would like to aggregate the text based on the is_response value and output the following:
 record_id | aggregated_text                                   |
 ----------+---------------------------------------------------+
 1         |in text 1 response text 1                          |
 ----------+---------------------------------------------------+
 1         |in text 2 response text 2 response text 3          |
 ----------+---------------------------------------------------+
 2         |in text 1 response text 1                          |
 ----------+---------------------------------------------------+
 2         |in text 2 response text 2 response text 3          |

I've tried the following query, but it fails to aggregate two responses in a row, IE :is_response is true in a sequence.
SELECT
    record_id,
    string_agg(text, ' ' ORDER BY id) AS aggregated_text
FROM (
    SELECT
        *,
        coalesce(sum(incl::integer) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0) AS grp
    FROM (
        SELECT *, is_response as incl
        FROM conversations
         ) c
     ) c1
GROUP BY record_id, grp
HAVING bool_or(incl)
ORDER BY max(id);

The output of my query just adds another line for the following is_response row like so:
 record_id | aggregated_text                                   |
 ----------+---------------------------------------------------+
 1         |in text 1 response text 1                          |
 ----------+---------------------------------------------------+
 1         |in text 2 response text 2                          |
 ----------+---------------------------------------------------+
 1         |response text 3                                    |
 ----------+---------------------------------------------------+
 2         |in text 1 response text 1                          |
 ----------+---------------------------------------------------+
 2         |in text 2 response text 2                          |
 ----------+---------------------------------------------------+
 2         | response text 3                                   |
 ----------+---------------------------------------------------+

How can I fix it?

A: This is basically a simpler version of your previous question.
SELECT record_id, string_agg(text, ' ') As context
FROM  (
   SELECT *, count(NOT is_response OR NULL) OVER (PARTITION BY record_id ORDER BY id) AS grp
   FROM   conversations
   ORDER  BY record_id, id
   ) sub
GROUP  BY record_id, grp
ORDER  BY record_id, grp;

Produces exactly the desired result, with a single window function in a subquery and then aggregate.
Detailed explanation and links in my answer to your last question:

*

*Select partitions based on matches in other table

A: Here's a variation of the answer I gave in your previous question:
SELECT record_id, string_agg(text, ' ')
FROM (
    SELECT *, coalesce(sum(incl::integer) OVER w,0) AS subgrp
    FROM (
        SELECT *, is_response AND NOT coalesce(lead(is_response) OVER w,false) AS incl
        FROM conversations
        WINDOW w AS (PARTITION BY record_id ORDER BY id)
    ) t
    WINDOW w AS (PARTITION BY record_id ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)
) t1
GROUP BY record_id, subgrp
HAVING bool_or(incl)
ORDER BY min(id);

The idea is that for each row we look at the next row of the same record with the help of the lead window function. If there is not such row, or if there is one and its is_response is false while the current is_response is true, then we select that row, aggregating all previous unused values of text.
This query also ensures that if the last conversation if incomplete (which doesn't happen in you sample data), it will be omitted.


text:
Q: Evaluate: $\lim_{\theta \to \frac {\pi}{4}}\frac {\cos \theta - \sin \theta}{\theta - \frac {\pi}{4}}$
Evaluate: $$\lim_{\theta \to \pi/4} \frac {\cos \theta - \sin \theta}{\theta - \pi/4}$$

My Attempt:
This limit takes $\dfrac {0}{0}$ form when $\theta =\dfrac {\pi}{4}$.
Here, $\dfrac {0}{0}$ form is an indeterminate form. So how do I make it determinate?

A: Without l'Hospital:
$$\frac{\cos x-\sin x}{x-\frac\pi4}=\frac{\cos x-\cos\left(\frac\pi2-x\right)}{x-\frac\pi4}\stackrel{(**)}=\frac{-2\sin\frac\pi4\cdot\sin\frac{2x-\frac\pi2}2}{x-\frac\pi4}=-2\cdot\frac1{\sqrt2}\frac{\sin\left(x-\frac\pi4\right)}{x-\frac\pi4}$$
Finally, you can substitute $\;y:=x-\frac\pi4\;$ , and observe that $\;x\to\frac\pi4\implies y\to 0\;$ , so we get:
$$\lim_{x\to\frac\pi4}\frac{\cos x-\sin x}{x-\frac\pi4}=\lim_{x\to\frac\pi4}-\frac2{\sqrt2}\frac{\sin\left(x-\frac\pi4\right)}{x-\frac\pi4}=\lim_{y\to0}\,-\sqrt2\,\frac{\sin y}y=-\sqrt2$$
$(**)\;\;$ We used above the trigonometric identity:
$$\color{red}{\cos\alpha-\cos\beta=-2\sin\frac{\alpha+\beta}2\,\sin\frac{\alpha-\beta}2}$$

A: Since your limit is in the form $\frac{0}{0}$, you can use L'Hopital's rule.
$$\lim_{\theta \to \pi/4} \frac{\cos{\theta}-\sin{\theta}}{\theta-\frac{\pi}{4}}=\lim_{\theta \to \pi/4} \frac{\frac{d}{d\theta}(\cos{\theta}-\sin{\theta})}{\frac{d}{d\theta}(\theta-\frac{\pi}{4})}=\lim_{\theta \to \pi/4}(-\sin{\theta}-\cos{\theta})=\cdots$$
Now that your limit is not indeterminate, you can evaluate your limit by substitution.

A: If you know that for small $x$ you have $\sin x\approx x$ (from Taylor expansion or l'Hopital), you can write $\theta-\pi/4=x$. Then you can show $$\cos\left(x+\frac{\pi}{4}\right)-\sin\left(x+\frac{\pi}{4}\right)=-\sqrt2 \sin x$$
Then your limit is $-\sqrt2$

A: Note that $\cos(\pi/4) = \sin(\pi/4)$ and hence we can add subtract this in numerator to get the expression as $$\frac{\cos\theta - \cos(\pi/4)}{\theta - (\pi/4)} - \frac{\sin\theta - \sin(\pi/4)}{\theta - (\pi/4)}$$ and one can easily note that these fractions tend to derivatives of $\cos $ and $\sin $ at $\pi/4$ as $\theta\to\pi/4$. Thus the desired limit is $-\sin(\pi/4) - \cos(\pi/4) = -\sqrt{2}$.

A: If $f(x)=\cos(x)-\sin(x)$, then $f\left(\frac\pi4\right)=0$, and therefore your limit is$$\lim_{x\to\pi/4}\frac{f(x)-f(\pi/4)}{x-\pi/4}=f'\left(\frac\pi4\right)=-\sqrt2.$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set for specific directory open_basedir I have a directory /htdocs/unsecured and I want to limit whatever is in that directory or its subdirectories from accessing anything outside of that directory. Where and how do I set open_basedir for this directory only?

A: You can set open_basedir in your Apache configuration file, php.ini, or in a .htaccess file.
I normally set this in an apache config file such as /etc/httpd/conf/httpd.conf.
You will have a directory structure for your current domain/virtual-host and you can add the line directly in there:
<VirtualHost 123.123.123.123:80>
    <Directory /htdocs/unsecured>
        php_admin_value open_basedir "C:/htdocs/unsecured"
    </Directory>
</VirtualHost>

Note: The 123.123.123.123 is the IP address of your domain and this sample block potentially leaves out a lot of data for this configuration only showing what's needed for open_basedir.
In php.ini, you can do this on a much-more general level (and it will be applied to every domain on your server) with:
open_basedir = "/htdocs/unsecured"

In .htaccess, you should be able to use the following (though I haven't tested):
php_value open_basedir "/htdocs/unsecured"

EDIT (Windows path)
Per a comment, you're running xammp on Windows (and not using Virtual Hosts). With this information, I would suggest to put your open_basedir rule in your php.ini file. This should (hopefully) work for you:
open_basedir = "C:\xampp\htdocs\unsecured"

In linux, a : is a field separator. In Windows, the ; is the separator - so this should work, but I am unable to test it personally.

A: You may change the open_basedir in php.ini, in your httpd.conf or during runtime as well.


text:
Q: Multiple if-else statements into polymorphism in c++ I've read through several issues regarding the topic at interest however still have a difficult time coming to a conclusion. I apologise in advanced if this is a redundant question.
To get to the point, my problem is trying to implement a logical payoff test. For example, a financial product may have several conditions and depending on each condition the payoff will differ. However, the how many conditions are unknown until the contract is received. Goal is to program a payoff implementation while not hard coding each if statement whenever a new product comes. For example I receive first a contract with only one condition. The next day I receive a contract with two condition etc. I understand that this problem can be tackled with polymorphism but I have a difficult time how.
The payoffs themselves are coded using polymorphism.
For example I have an abstract generic payoff class with concrete generic payoff classes.
class cPayoffAbstract
{
private:
public:
   cPayoffAbstract(){}
   virtual cPayoffAbstract* clone() const = 0;
   virtual ~cPayoffAbstract(){}
   virtual double operator()(double& x) const = 0;
};

class cPayoffConcrete1 : public cPayoffAbstract
{
private:
   double y;
public:
   cPayoffConcrete1(double& argY);
   virtual cPayoffConcrete1* clone() const;
   virtual ~cPayoffConcrete1(){}
   virtual double operator()(double& x) const;
};

class cPayoffConcrete2 : public cPayoffAbstract
{
private:
   double y;
public:
   cPayoffConcrete2(double& argY);
   virtual cPayoffConcrete2* clone() const;
   virtual ~cPayoffConcrete2(){}
   virtual double operator()(double& x) const;
};

Then I have another class to define the interface of a more complex payoff.
#include <cPayoffAbstract.h>
#include <SmartPtr.h>
#include <vector>
class cConditionalPayoff
{
private:
   // Some data members
public:
   cConditionalPayoff(const SmartPtr<cPayoffAbstract>& argPayoffPtr1, const SmartPtr<cPayoffAbstract>& argPayoffPtr2);

   // some methods ...
   double fConditionalPayoff(const std::vector<double>& argXs, double& argY, double& argZ) const;
};

Suppose there is a contract with few conditions and depending on the conditions will have different payoff which is implemented in the generic payoff class.
double cConditionalPayoff::fConditionalPayoff(const std::vector<double>& argXs, double& argY, double& argZ) const
{
   for (unsigned long i = 0; i < argXs.size(); i++)
   {
      if (argXs[i] > argY) { return dmPayoffPtr1->operator()(argXs[i]); }
      else
      {
          if (argXs[i] < argZ) { return dmPayoffPtr2->operator()(argXs[i]); }
          else { return argX[i]; }
      }
   }
}

The problem comes when for example a different contract with similar payoffs but more conditions are designed in the contract. Then the above if statements must be recoded in or  another method has to be implemented.
Thus, the goal is to implement the fConditionalPayoff in a dynamic way instead of coding in ifs ad hoc.
I hope my re-edit helps clarify some misunderstanding. I apologise if there were.
Thank you again.

A: Perhaps you could split logic into two parts (pseudocode):
class PayOffProcessor;

class PayOffProcessor1 : public PayOffProcessor { ... };
class PayOffProcessor2 : public PayOffProcessor { ... };
class PayOffProcessor3 : public PayOffProcessor { ... };

class PayOffProcessor
{
    virtual void process() = 0;

    static PayOffProcessor * processorForData(double x, double y, double z)
    {
        static PayOffProcessor1 processor1;
        static PayOffProcessor2 processor2;
        static PayOffProcessor3 processor3;
        if (x > y)
        {
            return &processor1;
        }
        if (x < z)
        {
            return &processor2;
        }
        return &processor3;
    }
};

double myclass::conditionalPayoff(std::vector<double>& x, double& y, double& z) const
{
     for (unsigned long i = 0; i < x.size(); i++)
     {
         processorForData(x, y, z)->process();
     }
}

A: My understanding of your problem is that you want to dynamically add behaviors to your Contract object.
In this case, I think what you need is the Decorator Pattern.
You can find its description here : http://www.oodesign.com/decorator-pattern.html
and some explanations here : http://oreilly.com/catalog/hfdesignpat/chapter/ch03.pdf

A: Polymorphism can only be applied, if you know about all the possible combinations of condition, so you can derive from your abstract class for each one of them and implement the checking function for these conditions.
If you don't know what conditions are possible, they should be defined by a user input or whatever. You could approach this like the following:
Input: Vector<Values>, Vector<ConditionType>, Vector<ConditionValue>, Vector<PayOffType>

In the ConditionType Vector you write sth. like a string of "<" or ">" or sth.
void checkConditions(vector<double> values, vector<string> condType, vector<double> condValues, vector<string/int> PayOfftype) {
  for(int i=0; i<values.size(); i++) {
    switch(condType[i]) {
      case("<"):
        if(values[i] < condValues[i]) {
           PayOff po = getPayOffByType(PayOfftype[i]);
           po.payoff();
        }
        break;
      case(">"):
        ...
      break;
      ...
    }
  }
}

You could pass into this a default payoff type, if no condition applies as well.


text:
Q: How do I find the area of an inscribed triangle with a vertex at the intersection of an ellipse and a hyperbola with the same foci? I'm having some trouble with a problem that asks for the area of a triangle with a vertex at the intersection of an ellipse and a hyperbola. Here it is:

An ellipse and a hyperbola have the same foci - $F_1$ and $F_2$. These curves cross at 4 points - let $P$ be one of the points. These curves also intersect the line $F_1F_2$ at 4 points labelled $Q$, $R$, $S$ and $T$ in that order. If $RS = 20$, $ST = 14$ and $∆PF_1F_2$ is isosceles, compute the area of $∆PF_1F_2$.

Here is what I have so far. Let $a_e, b_e$ be the parameters for the ellipse, $a_h, b_h$ be the parameters for the hyperbola, and $\hat x, \hat y$ be the coordinates of $P$. Assume both curves are centered at the origin and $F_1$ has a negative x-coordinate. I deduced that
$$
\begin{equation}
\begin{split}
\begin{gathered}
a_e = \frac {20 + 2 * 14} 2 = 24\\
a_h = \frac {20} 2 = 10\\
2c \neq PF_1 \rightarrow 2c = PF_2\\
2c = a_h - \left( \frac c {a_h} \right) \hat x = 10 - \left( \frac c {10} \right) \hat x
\end{gathered}
\end{split}
\end{equation}
$$
However, I'm not sure where to go from here. I had a thought of trying to solve for $\hat x$ in terms of $c$, then plugging it into the equation for the ellipse and trying to solve for $\hat y$, then doing $\frac 1 2 * 2c * \hat y$ would give me the area of the triangle purely in terms of $c$. But then there would still be a $b_e$ floating around, and I don't know what $c$ is... any advice on solving this?

A: We know that the apex of the triangle must be one of the foci. If it were $P$, then an intersection of the two conics would lie on the ellipse's minor axis, which is not possible with confocal conics with the given vertices. Wlog take the apex to be at $F_1$.

By Heron's formula, the area of the triangle is $$A=\sqrt{s\,(s-|F_1P|)\,(s-|F_2P|)\,(s-|F_1F_2|)}$$ where $s$ is the semi-perimeter $(|F_1P|+|F_2P|+|F_1F_2|)/2$. Setting $|F_1F_2|=|F_1P|=2f$, $|F_2P|=2d$ and simplifying gives $A=d\sqrt{4f^2-d^2}$.
From the properties of the two conic sections we know that $$|F_1P|+|F_2P|=2f+2d=|QT|=2a_e \\ |F_1P|-|F_2P|=2f-2d=|RS|=2a_h.$$ Solving these equations for $f$ and $d$ yields $$\begin{align}f&=\frac12(a_e+a_h)\\d&=\frac12(a_e-a_h).\end{align}$$ Plug in the values that you've computed for the semi-axis lengths, and you're done.


text:
Q: What is the difference between '>>' and ' / ' , shifting and division in java we can shift using >> operator, and we can use '/' to divide in java. What I am asking is what really happens behind the scene when we do these operations, both are exactly same or not..?

A: No, absolutely not the same.
You can use >> to divide, yes, but just by 2, because >> shift all the bits to the right with the consequence of dividing by 2 the number.
This is just because of how binary base operations work. And works for unsigned numbers, for signed ones it depends on which codification are you using and what kind of shift it is.
eg.
122 = 01111010 >> 1 = 00111101 = 61

A: Check this out for an explanation on bit shifting:
What are bitwise shift (bit-shift) operators and how do they work?
Once you understand that, you should understand the difference between that and the division operation.


text:
Q: How to make fillPolygon(s) behined JButtom [Strange rendering]
First of all sorry for my english.
I got a strange rendering bug: fillPolygon rendered in front of the 2. and 3. JButton and if I move the mouse over the buttons the rendering suddenly turns to correct. I'm not sure what's the problem.
I make a BufferedImage filled with stars (also i tryed without of BufferedImage).

public void paint(Graphics g) {
    super.paint(g);
    g.drawImage(background, 0 , 0, null );
}

The buttons setup:
    for(int i = 0; i < buttons.length; i++) {
        buttons[i] = new JButton(names[i]);
        buttons[i].setFont(font);
        buttons[i].addActionListener(al);
        buttons[i].setActionCommand(actionCommands[i]);
        buttons[i].setVisible(defaultButtonVisibility[i]);
    }

The panel settup:
private void panelSetup(Color background) {
    panel = new JPanel();
    panel.setSize(getSize());
    panel.setBackground(background);
    panel.setLayout(new GridBagLayout());

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.fill = GridBagConstraints.HORIZONTAL;

    for(int i = 0; i < 5; i++) panel.add(buttons[i], gbc);
    makeBackground();
}

A: public void paint(Graphics g) {
    super.paint(g);
    g.drawImage(background, 0 , 0, null );
}

When you do custom painting, you should be overriding the paintComponent() method:
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(background, 0 , 0, null );
}

Read the section from the Swing tutorial on A Closer Look at the Paint Mechanism.
You will see that the component and all its children are painted, and then you attempt to paint an image on top of them. For a background you need to paint the background of the panel first, and then paint the child components.

if I move the mouse over the buttons the rendering suddenly turns to correct.

This is because the button needs to be repainted to reflect the "rollover" effect. So the button is temporarily painted over top of the background.
However, try resizing the frame and the background will appear again, because the entire frame get repainted.


text:
Q: Once checkbox is true, how do you make it false once clicked again? (Rails 4) I'm having trouble updating my boolean to be false again once clicked for a second time.
  def completed
    if @todo.update_attribute(:completed, true)
      flash[:success] = "Wowzers."
      redirect_to dashboard_path
    else
      flash.now[:error] = "Not so wowzers..."
      render :new
    end
  end

This is what I have currently, it sets my boolean to true once clicked but I'm not sure how to if @todo.update_attribute(:completed, true, false)thinking this would be like a toggle, true then false but it's not the case.
I have also tried
  if params[:completed] == 0
    @todo.update_attribute(:completed, true)
    flash[:success] = "Wowzers."
    redirect_to dashboard_path
  elsif params[:completed] == 1
    @todo.update_attribute(:completed, false)
    flash[:success] = "Wowzers."
    redirect_to dashboard_path
  end

But this doesn't save to my database (true or false).
My question here is; how can I toggle my checkbox true then false, rather than just true or false?

A: The basic principle of logical negation is !, the not operator, is your friend:
@todo.update_attribute(:completed, !@todo.completed)

That will flip it back and forth.

A: In HTML post requests, params are always passed as strings so params[:completed] == 1 will always be false. You probably want params[:completed] == '1' or params[:completed] == 'true'.
Also, if you want to toggle a param, simply use the toggle action.
@todo.toggle(:completed)

Otherwise, to save based on inequality of your param use
if @todo.update_attribute(:completed, params[:completed] != '1')
  flash[:success] = "Wowzers."
elsif
  flash[:error] = "Couldn't update completed status"
end
redirect_to dashboard_path

A:  def completed
    if  @todo.update_attribute(:completed, params[:completed])
      flash[:success] = "Wowzers."
      redirect_to dashboard_path
    else
      flash.now[:error] = "Not so wowzers..."
      render :new
    end
  end


text:
Q: how to center JLabel in Jframe Swing? I have this working code for a stop watch in Swing. I want to have the label Time Remaining 300 seconds centered on the second line`. here is my code.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

public class TimerGUI extends JPanel {
    JLabel promptLabel, timerLabel;
    final int count = 30;
    JButton start;
    JButton end;
    Timer timer;

    public TimerGUI() {
        setLayout(new GridLayout(0,2));

        start = new JButton("Start");
        add(start);
        Event e = new Event();
        start.addActionListener(e);

        end = new JButton("End");
        end.setEnabled(false);
        add(end);
        end.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                timer.stop();
                start.setEnabled(true);
                end.setEnabled(false);
                timerLabel.setText("Time Remaining " + count + " seconds");

            }

        });

        timerLabel = new JLabel("Time Remaining 300 seconds");
        add(timerLabel);

    }

    private class Event implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            start.setEnabled(false);
            end.setEnabled(true);
            timerLabel.setText("Time Remaining " + count + " seconds");

            TimeClass tc = new TimeClass(count);
            timer = new Timer(1000, tc);
            timer.start();

        }
    }

    private class TimeClass implements ActionListener {
        int counter;

        public TimeClass(int count) {
            this.counter = count;

        }

        @Override
        public void actionPerformed(ActionEvent e) {
            counter--;
            if (counter <= 5) {
                Toolkit.getDefaultToolkit().beep();
            }

            if (counter >= 1) {
                timerLabel.setText("Time Remaining " + counter + " seconds");
            } else {
                timer.stop();
                timerLabel.setText("game over");
            }

        }
    }

    public static void main(String[] args) {
        JFrame myframe = new JFrame();
        TimerGUI timer = new TimerGUI();
        // myframe.getContentPane().add(content,BorderLayout.CENTER);
        myframe.getContentPane().add(timer, BorderLayout.CENTER);
        myframe.setTitle("Hangman Game");
        myframe.pack();
        myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myframe.setLocationRelativeTo(null);
        myframe.setVisible(true);

    }

}

EDIT:
changing to this.
timerLabel = new JLabel("Time Remaining 300 seconds");
        add(timerLabel,SwingConstants.CENTER);

gives different ouput, kindly see the image

A: You can use the following
jLabelvariable.setLocation((this.getWidth()-jLabelvariable.getWidth())/2,50);

Here 50 is the height of label from top of the frame.

A: Change your JLabel's horizontal alignment. The constructor can help you do this by changing:
timerLabel = new JLabel("Time Remaining 300 seconds");

to:
timerLabel = new JLabel("Time Remaining 300 seconds", SwingConstants.CENTER);

Also nest your JPanels each using its own layout. e.g.,
import java.awt.BorderLayout;
import java.awt.GridLayout;

import javax.swing.*;

public class TimerFoo extends JPanel {
   public TimerFoo() {
      JPanel centerPanel = new JPanel(new GridLayout(0, 2));
      centerPanel.add(new JButton("Foo"));
      centerPanel.add(new JButton("Bar"));

      JLabel bottomLabel = new JLabel("Bottom Label", SwingConstants.CENTER);

      int gap = 5;
      setLayout(new BorderLayout(gap, gap));
      setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
      add(centerPanel, BorderLayout.CENTER);
      add(bottomLabel, BorderLayout.PAGE_END);
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("TimerFoo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new TimerFoo());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

A: you can use this to center it horizontally
labelVariable.setHorizontalAlignment(JLabel.CENTER);

A: Read JavaDoc of JLabel. It has description for the class and all the APIs, including text alignment.


text:
Q: R Shiny: Check condition based on reactive expressions in observeEvent I would like to build a Shiny App with two tabs:
In one tab, some values are entered as input. In the next tab, the user can find an output that is based on the values entered in the first tab.
However, before proceeding to the output I want to check if summing up three entries will give the fourth entry.
To do so, I want to use reactive expressions that contain the values of the different entries.
Here is an example of what I would like to do:
# clean environment
rm(list = ls(all = TRUE))

library(shiny)

# Create user interface (UI)
u <- tagList(
  navbarPage(
    # UI for input
    title = "",
    id = "Example_App",
    tabPanel("Model input",
             fluidRow(
               column(11, offset = 0,
                      br(),
                      h4("Model input"),
                      br(),
                      sidebarPanel(
                        div(textInput('str_Input1', 'Input 1\n', "",
                                     placeholder = "5.6, 6.7, 4.1"), class = "subheading"),
                        div(textInput('str_Input2', 'Input 2\n', "",
                                      placeholder = "5.6, 6.7, 4.1"), class = "subheading"),
                        div(textInput('str_Input3', 'Input 3\n', "",
                                      placeholder = "5.6, 6.7, 4.1"), class = "subheading"),
                        div(textInput('str_Input4', 'Input 4\n', "",
                                      placeholder = "5.6, 6.7, 4.1"), class = "subheading"),
                        actionButton('jumpToModelOutput', 'Run')),
                      mainPanel(
                        h4('You entered'),
                        verbatimTextOutput("oid_Input1"),
                        verbatimTextOutput("oid_Input2"),
                        verbatimTextOutput("oid_Input3"),
                        verbatimTextOutput("oid_Input4"))))),
    # UI for output
    tabPanel("Model output",
             fluidRow(
               column(11, offset = 0,
                      br(),
                      h4('Your output will be here.'))
                      ))))

# Define server output
s <- shinyServer(function(input, output, session) {

  # Define reactive expressions
  num_Input1 <- reactive(as.numeric(unlist(strsplit(input$str_Input1,","))))
  num_Input2 <- reactive(as.numeric(unlist(strsplit(input$str_Input2,","))))
  num_Input3 <- reactive(as.numeric(unlist(strsplit(input$str_Input3,","))))
  num_Input4 <- reactive(as.numeric(unlist(strsplit(input$str_Input4,","))))

  # Define server output for input check
  output$oid_Input1 <- renderPrint({
    cat("Input 1:\n")
    print(num_Input1())
    })
  output$oid_Input2 <- renderPrint({
    cat("Input 2:\n")
    print(num_Input2())
  })
  output$oid_Input3 <- renderPrint({
    cat("Input 3:\n")
    print(num_Input3())
  })
  output$oid_Input4 <- renderPrint({
    cat("Input 4:\n")
    print(num_Input4())
  })

  # Check if conditions are fulfilled before switching to Model output
  observeEvent(input$jumpToModelOutput, {
     if(!all.equal((num_Input1() + num_Input2() + num_Input3()),num_Input4())){
       showNotification("Error.", type = "error")
     }else{
          updateTabsetPanel(session, "Example_App",
                            selected = "Model output")
        }})

})

# Create the Shiny app
shinyApp(u, s)

When I enter "1,2,3" into all tabs and press the button, the App stops and I get the following message:
"Listening on http://127.0.0.1:3925
Warning: Error in !: invalid argument type"
Removing the ! gives the following message:
Warning: Error in if: argument is not interpretable as logical
As far as I get the messages, the reactive expressions are not interpreted as numeric (?) but summing them up and printing them gives correct results.
Could anyone please help me finding the problem?

A: The issue is that all.equal returns a string containing a report of the difference in the passed values. That's why the docs (see ?all.equal) state:

Do not use all.equal directly in if expressions—either use isTRUE(all.equal(....)) or identical if appropriate.

Hence, to fix your issue wrap inside isTRUE:
observeEvent(input$jumpToModelOutput, {
    if (!isTRUE(all.equal(num_Input1() + num_Input2() + num_Input3(), num_Input4()))) {
      showNotification("Error.", type = "error")
    } else {
      updateTabsetPanel(session, "Example_App",
        selected = "Model output"
      )
    }
  })

A: all.equal returns a string if the elements are not equal, and you can't use a ! on a string. You can first check with isTRUE if it's TRUE or not and then negate it (note: you can't use isFALSE because in case it's not TRUE, all.equal returns a string). If you expect the elements to be exactly equal, you could use identical to make things easier.
I've also summed up all element in each input before adding them, is this what you wanted to do?
# Check if conditions are fulfilled before switching to Model output
  observeEvent(input$jumpToModelOutput, {
    if(!isTRUE(all.equal((sum(num_Input1()) + sum(num_Input2()) + sum(num_Input3())),sum(num_Input4())))){
      showNotification("Error.", type = "error")
    }else{
      updateTabsetPanel(session, "Example_App",
                        selected = "Model output")
    }})


text:
Q: How to solve - Unable to locate the specified class: Session.php in codeigniter I am trying to use session in all controllers, but can't get success.
Here is my controller code of library.
<?php if(!defined('BASEPATH')) exit('NO direct script access allowed');

class MY_Controller extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();

    }

    public function is_logged_in()
    {
        $user = $this->session->userdata('username');
        return isset($user);
    }
}

?>

And here I am inherit It in my other controller file.
class Homepage extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function CheckSession()
    {
        if ($this->is_logged_in())
        {
            echo '111';
        }
    }
}

I also try helper but giving me same error.
<?php
        function is_logged_in() {
        // Get current CodeIgniter instance
        $CI =& get_instance();
        // We need to use $CI->session instead of $this->session
        $user = $CI->session->userdata('user_data');
        if (!isset($user)) { return false; } else { return true; }
    }
    ?>

autoload.php part
$autoload['helper'] = array('url','form','file','login');
$autoload['drivers'] = array('session');
$autoload['libraries'] = array('database','session', 'email', 'form_validation', 'MY_Controller');
I am Following this link.

A: either you need to autoload session library in your authoload.php like this
$autoload['libraries'] = array('session');

or load session library in constructor of library file like this
public function __construct()
{
    parent::__construct();
    $this->load->library('session');
}


text:
Q: In Android, how can I programmatically set an AutoCompleteTextView at the start of an activity? (Java) I'm using the AutoCompleteTextView as an ExposedDropdownMenu per the Google Material Guidelines. First I would like to state that I am able to successfully set the AutoCompleteTextView's text value programmatically by waiting ~300ms after the onCreate() function is called, with the proper values inside of the dropdown suggestion menu. However, when I set the AutoCompleteTextView's text programmatically beforehand (e.g. inside of the onCreate() w/o delay), a weird issue arises where the dropdown menu of the AutoCompleteTextView is empty for some reason (and no it's not because of filtering).
NOTE: I have modified this code from my original source code to make it easier to understand and less complex. It has not been tested and may have errors.
private String[] VALUES = new String[]{"val1", "val2", "val3", "val4"};

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ArrayAdapter<String> adapter = new ArrayAdapter<>(mainActivity.getApplicationContext(), R.layout.dropdown_menu_popup_item, VALUES);

    AutoCompleteTextView autoCompleteTextView = findViewById(R.id.auto_complete_text_view);
    autoCompleteTextView.setAdapter(adapter);
    autoCompleteTextView.setOnItemClickListener((parent, view, position, id) -> {
        //Do something here when item is selected
    });

    //Here I want to set the text value to something in onCreate()
    //without having to wait a random amount of time
    autoCompleteTextView.setText("val3", false);
}

This results in the AutoCompleteTextView's dropdown menu only containing "val3" and no other values from the adapter. At first glance it looks like it's filtering but it's not (note that the filter boolean is set to false). The list only contains "val3". However if I wait ~300ms or so, then it works as expected.
private String[] VALUES = new String[]{"val1", "val2", "val3", "val4"};

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ArrayAdapter<String> adapter = new ArrayAdapter<>(mainActivity.getApplicationContext(), R.layout.dropdown_menu_popup_item, VALUES);

    AutoCompleteTextView autoCompleteTextView = findViewById(R.id.auto_complete_text_view);
    autoCompleteTextView.setAdapter(adapter);
    autoCompleteTextView.setOnItemClickListener((parent, view, position, id) -> {
        //Do something here when item is selected
    });

    new AsyncTaskThatWaits300ms().execute();
}

private static class WaitForAutoCompleteTextViews extends AsyncTask<String, Void, Boolean> {

    private ProgressDialog dialog = new ProgressDialog(MainActivity.this);

    @Override
    protected void onPreExecute() {
        if (dialog != null) {
            this.dialog.setMessage("Waiting 300ms...");
            this.dialog.show();
        }
    }

    @Override
    protected Boolean doInBackground(final String... args) {
        try {
            //Do something
            Thread.sleep(300);
            return true;
        } catch (Exception e) {
            Log.e(TAG, "doInBackground error: ", e);
            return false;
        }
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        if (dialog != null) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }
        //If I set it here, the text will display with the correct values in the dropdown list, instead of only "val3".
        autoCompleteTextView.setText("val3", false);
    }
}

A: Do you want to set text  of a specific item on autocomplete textview by clicking on that item? If it is then
autoCompleteTextView.setText() will be inner of the onitemclicklistener() method.


text:
Q: Asking for admin privileges for only standard accounts I am moving some files to /Applications directory by my application and using SMJobBless() for Elevating to admin rights privileges.
But it prompts for admin credentials for any type of account- admin or standard_user, can we put a check and ask for admin credentials only for standard users by using any objective-c API?
Edit -- If anyone has tried or gone through process of installing Dropbox, then Dropbox installer does the same(i.e it asks for admin privileges only for standard accounts for copying it's .app file to /Applications).

A: Based on the answer of another question, I've made a file that seems to suit you (I've just translated it from C to Objective-C and removed the printf's; the original link is at the end of the answer).
NSPrivileges.h
#import <Foundation/Foundation.h>

@interface NSPrivileges : NSObject

+(BOOL)hasAdminPrivileges;

@end

NSPrivileges.m
#import "NSPrivileges.h"
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <strings.h>
#include <pwd.h>
#include <grp.h>

@implementation NSPrivileges

+(BOOL)hasAdminPrivileges{
    uid_t current_user_id = getuid();
    struct passwd *pwentry = getpwuid(current_user_id);
    struct group *grentry = getgrgid(getgid());

    struct group *admin_group = getgrnam("admin");
    while(*admin_group->gr_mem != NULL) {
        if (strcmp(pwentry->pw_name, *admin_group->gr_mem) == 0) {
            return YES;
        }
        admin_group->gr_mem++;
    }
    return NO;
}

@end

Now, you just need to import NSPrivileges.h to the file which needs to know if the user is an admin or not and use the command [NSPrivileges hasAdminPrivileges] to find out (it will return a BOOL, so it will be easy to deal with). Hope that helps you.
Here is my reference:
Objective C and OS user type


text:
Q: GoogleSignIn (iOS) getTokensWithHandler doesn't call its closure after token has expired I am using Google Sign-In 5.0.2 with a Swift 4 iOS app.  Here is my code to get a current id Token:
public static func getJwtToken(completion: @escaping (Result<String, Error>) -> Void) {
        assert(Config.isAuthEnabled())

        GIDSignIn.sharedInstance()?.currentUser?.authentication.getTokensWithHandler({ gidAuth, error in
            if let error = error {
                completion(.failure(error))
            } else if let token = gidAuth?.idToken {
                completion(.success(token))
            } else {
                assertionFailure("shouldn't have come here")
            }
        })
    }

This works fine when I launch the app.
But if I leave the app running for an hour (to let the id token expire), then the next time getTokensWithHandler is called, it will not call my closure.  Subsequent calls to getTokensWithHandler will once again call my closure.
I would like it to behave consistently so that my closure is always called, even if the token needs to be refreshed.
Anyone have any ideas on what I need to do to achieve this?

A: I figured out the answer to this problem after spending some more time on it.
My problem was I was trying to hack the Google SDK's closure to be synchronous instead of just letting it call the closure when it was ready.  The function call that I claimed never called its closure would've called it if I had let the program flow naturally instead of trying to make it call the closure when I expected it to be called.  I was using a semaphore somewhere in the call stack that was waiting until the closure got called and I just needed stop making assumptions about when Google's SDK would perform its work.
I'm still trying to get used to this async-first paradigm of Swift.


text:
Q: Is there a way to make all onclick elements navigateable by keyboard? With links and form fields you can use tab to cycle trough and activate them.
In my code however I use lots of elements, that have an onclick attribute to perform different actions. For example a table, where each tr is clickable and expands on click.
Now I want my page to be browseable by keyboard only as well.
I was thinking about setting tabindex on each tr, which worked in Firefox (I was able to tab through the items, but not click them), but did not in Chrome.
How can I cycle through all elements containing onclick using the keyboard? If not with plain HTML, maybe with JQuery.

A: I'd recommend that you simply wrap the elements in anchor tags ().

A: Why not put a button on the row that will do the same action as the onclick of the row?
A button (or a link) will also get picked up by a screen reader.

A: fiddle. Tabindex works in chrome 12 for me.
What's your actual problem?

A: What you can possibly do, is keep track of the current element with onclick selected, and everytime the user hits - lets say the ~ button - it will move to the next one, and when he hits Enter - just trigger the .click(); for that element.
I've set up an example on jsfiddle: http://jsfiddle.net/dvirazulay/4kJnM/
This is sort of re-implementing tabindex, and you could do it better and change the actual selector to your liking...

A: Something like this fiddle?
jQuery
var currentRow = -1;
$lastTd = jQuery();

$(document).keyup(function(event) {
    if ($.inArray([38, 40], event.keyCode)) {
        var $rows = $('table > tbody > tr');
        var newRow = currentRow + (event.keyCode == 40 ? 1 : -1);
        if (newRow > $rows.length - 1 || newRow < 0) return;

        currentRow = newRow;

        $lastTd.find('>div').hide();
        $lastTd.find('>span.indicator').remove();

        $lastTd = $rows.eq(currentRow)
                .find('>td')
                .prepend('> ');

        // Show the content div
        $lastTd.find('div').fadeIn();
    }
});

A: Using tabindex="0" allows you to navigate and move focus to the element/row with the tab-key. However, there is no way to trigger the onclick event by keyboard.
To overcome this, add an onkeydown event that triggers the onclick event:

You need to filter out other keypresses, except for space(32) and enter(13) when mimicing a click.
This listener would be better to put in a script rather than inline, but i'm just demonstrating the concept here.

A: I hope something like this might work for you, (it does not for me, i am poor at JS). You could edit it and you would get an invisible button filling the background of the table element and to tell the user which is selected you could have borders.
<!DOCTYPE HTML>

        <title>Nav</title>

                Sample
                Sample

                1
                2

                3
                4

                5
                6

                7
                8


text:
Q: iterar sobre objeto lm en r new_dataset es un dataset con 19 variables, lo que intento hacer es hacer un modelo que logre el mejor ajuste siguiendo esta metodología: primero que quede fija la variable dependiente Y. Segundo que pruebe las variables desde ds[,1] hasta ds[,19]. Tercero que cuando la variable tenga un p-valor por debajo de 0.05 la deje en el modelo de lo contrario que la elimine.
for (i in new_dataset) {
  prueba_modelo <- lm(data = new_dataset, formula =
                        ds$Y~ i)
  p_val_prueba <- data.frame(summary(prueba_modelo)$coefficients[ ,4])

    if(p_val_prueba[i,1]<0.05){
        prueba_modelo <- lm(data = new_dataset, formula =
                         ds$Y ~ i)
  } else {

  prueba_modelo <- lm(data = new_dataset, formula =
                          ds$regresion_otto.ir ~ i+1)

  }

 }


text:
Q: Flex items overflowing in Firefox I'm trying to create a form with first row a single text field 100% width and 2nd row 3 fields equidistant. It works fine on Chrome. However it's overflowing on FireFox.

.form {
  display: flex;
  flex-direction: column;
  width: 300px;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
}

.form input {
  width: 100%;
  padding: 20px;
}

.form .number {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form .expiry {
  display: flex;
  width: 100%;
  justify-content: space-between;
}

    <input data-stripe="number" placeholder="Credit Card Number" class="" type="text">

    <input data-stripe="exp-month" placeholder="MM" class="" type="text">
    <input data-stripe="exp-year" placeholder="YY" class="" type="text">
    <input data-stripe="cvc" placeholder="CVC" class="" type="text">

https://jsfiddle.net/xhr031yr/2/

A: You will need to set:
.form .expiry input {
  min-width: 0;
}

jsFiddle
The reason is flex items have min-width:auto set by default, and for a replaced element such as <input>, it has intrinsic dimensions. The flex item won't shrink when the total width of the input boxes exceeded.
You can also give the size attribute a smaller value (default is 20 for text input) to make it smaller:
<input type="text" size="3">

References

*

*Automatic Minimum Size of Flex Items

*Replaced elements

*HTML <input> attribute size

A: I can't tell you why that's happening, my guess is the way the browser handles the input element.
You can achieve the layout by...

*

*Add the box-sizing rule.

*Wrapping the inputs in a container
fiddle

html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

.form {
  display: flex;
  flex-direction: column;
  width: 300px;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
}

.form input {
  width: 100%;
  padding: 20px;
}

.form .number {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form .expiry {
  display: flex;
  width: 100%;
  justify-content: space-between;
}

    <input data-stripe="number" placeholder="Credit Card Number" class="" type="text">

      <input data-stripe="exp-month" placeholder="MM" class="" type="text">

      <input data-stripe="exp-year" placeholder="YY" class="" type="text">

      <input data-stripe="cvc" placeholder="CVC" class="" type="text">


text:
Q: How to use GRASS module to delineate watershed area? Update#1:I changed to work under qgis 1.8, I only input the DEM file and run the r.watershed module, and I got this:

I have a DEM file of one specified region, and I take the following steps to get files that might be used:

*

*Fill Sinks(this one I use SAGA module instead of GRASS)

*r.fill.dir

After step 2, I want to get flow accumulation file, but I can not find this kind of module in GRASS, so I pass it and directly try the r.watershed module.
There are several input options in this module, like this:
I tried any of files I have as input files, but I can't get the output files through this module, and always got this error message:

The log below told me that the data source is invalid, and I go to check the sextante message log:
ERROR|Wed Jan 22 2014 12:38:01|Could not load model watersheds.model|ALGORITHM:saga:catchmentarea(parallel)

What should I do to successfully use the r.watershed module?
Thanks for giving me any suggestion!

A: Please do not use sink-filling for r.watershed, it is nor needed nor desired. r.watershed takes care by itself due to its internal least cost routing algorithm.
A minimalistic example:
r.watershed elev=dem basin=catchments thresh=10000

For a tutorial, see http://grasswiki.osgeo.org/wiki/Creating_watersheds


text:
Q: The structure of a family of k- subsets of a n-set Call a set a $n$-set if its number of elements is $n$. Let $F=\{A_1,A_2,...,A_m\}$ be a family of $k$-subsets of a $n$-set. Suppose $F$ has additionally the following property:
If $A_i$ is any element of $F$ and if $B$ is any $k-1$-subset of $A_i$ then there exists an $A_j$ different from $A_i$ (depending on $B$) in $F$ s.t. $B$ is a subset of $A_j$.
Question: Can we characterize the structure of sets $F$? Of course the set of all $k$ subsets of an $m$-set with  $k< m\leq n$  has the property above. But are there any other family of subsets with this property?


text:
Q: Use Airport Express as a WIFI extender on non-Apple? I have a wireless router / modem from my cable provider and I was looking to use my existing Airport Express as a WIFI range extender. Is this possible? I currently have it connected directly with a cat6 cable but I rather use it wirelessly to get extra range.
Thank you in advance!

A: This is sadly not possible, you can only extend a network created by another Airport Extreme/Express.


text:
Q: istream streamsize ERROR reading lines i need help to solve my problem.
I want to read a text file and work on it using pointers.
I have, for test, 3 files: a, b and c:
a.txt contains 1 line like 29 RTY3050027/C BYZ23451 180 5.790 30.654
b.txt  contains 10 lines
c.txt contains 1000 lines
My code is:
#include <fstream>
#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    ifstream leggiROF("a.txt");

    leggiROF.seekg(0, ios::end);
    long int dimensione=leggiROF.tellg();
    cout << "File length: " << dimensione << " bytes" << endl;

    leggiROF.seekg(0, ios::beg);
    char *pLeggiROF=nullptr;
    pLeggiROF=new char [dimensione];
    // if RAM is available
    leggiROF.read(pLeggiROF, dimensione);

    if(leggiROF)
    {
        cout << "all characters read successfully.\n";
        cout << pLeggiROF << endl;
    }
    else
        /* ADDED LINES */
        int offSet=(dimensione-(dimensione-leggiROF.gcount()));
        cout << "Error: only " << leggiROF.gcount() << " bytes can be read!" << endl;
        leggiROF.read(pLeggiROF, offSet);
        cout << pLeggiROF << endl;

    leggiROF.close();

    delete[] pLeggiROF;
    pLeggiROF=nullptr;

    return 0;
}

Now i have these results with the 3 different files:
a.txt 1 line
29 RTY3050027/C BYZ23451 180 5.790 30.654

File length: 41 bytes
all characters read successfully.
29 RTY3050027/C BYZ23451 180 5.790 30.654

b.txt 10 lines
29 RTY3050027/C BYZ23451 180 5.790 30.654
....

File length: 412 bytes
ERROR: only 403 bytes could be read

c.txt 1000 lines
29 RTY3050027/C BYZ23451 180 5.790 30.654
....
File length: 41480 bytes
ERROR: only 40481 bytes could be read

A: I solved modifing the if else cycle (see code). I introduced an offSet variable. The only thing is that the last line of the big file (1000 lines) is dirt.
10 RYN123457/2 BYZ34512 270 32.907 21.221ïû┤öÅh
see the strange characters after the last number (21.221)


text:
Q: JQuery Terminal typing animation not displaying special HTML characters or class styles until after animation completes I'm using code from the JQuery Terminal examples to emulate typed animation in a console window. I can get the animation to work as intended, but during the course of the animation special HTML characters do not display until after the animation completes. For example, while the animation is running, the console renders '\' instead of ''
This problem also applies to styles assigned to the class of any div that's being animated. The styles do not show up until after the animation is complete.
Below is the code used to animate (adapted from the JQuery Terminal examples page):
var anim = false;
    function typed(finish_typing) {
        return function(term, message, delay, finished, classname) {
            anim = true;
            var prompt = term.get_prompt();
            var c = 0;
            if (message.length > 0) {
                term.set_prompt('');
                var interval = setInterval(function() {
                    term.insert(message[c++]);
                    if (c == message.length) {
                        clearInterval(interval);
                        // execute in next interval
                        setTimeout(function() {
                            // swap command with prompt
                            finish_typing(term, message, prompt, classname);
                            anim = false
                            finish && finish();
                        }, delay);
                    }
                }, delay);
            }
        };
    }

var typed_message = typed(function(term, message, prompt, classname) {
    if (typeof classname === "undefined") { classname = "default"; }
    term.set_command('');
    term.echo(message, {
        finalize: function(div) { div.addClass(classname); }});
    term.set_prompt(prompt);
});

And an example of how it's being called:
E.match(/^\s*ping\s*$/i)?
    typed_message(N, "PONG", 10, function(){finished = true;}, "pong"):

In this case, styles applied to the "pong" class that's assigned to the div output by typed_message do not display until after the text is finished typing.
Is there a way to go about having the styles or special characters display while the animation is running?

A: Slightly modified typed animation using set_prompt instead of insert, also $.terminal.substring and length (that last one need to go to $.terminal.length).

var anim = false;
function typed(finish_typing) {
    return function(term, message, delay, finish) {
        anim = true;
        var prompt = term.get_prompt();
        var c = 0;
        if (message.length > 0) {
            term.set_prompt('');
            var new_prompt = '';
            var interval = setInterval(function() {
                // handle html entities like &
                var chr = $.terminal.substring(message, c, c+1);
                new_prompt += chr;
                term.set_prompt(new_prompt);
                c++;
                if (c == length(message)) {
                    clearInterval(interval);
                    // execute in next interval
                    setTimeout(function() {
                        // swap command with prompt
                        finish_typing(term, message, prompt);
                        anim = false
                        finish && finish();
                    }, delay);
                }
            }, delay);
        }
    };
}

function length(string) {
   return $('<span>' + $.terminal.strip(string) + '</span>').text().length;
}

var typed_message = typed(function(term, message, prompt) {
    term.set_command('');
    term.echo(message);
    term.set_prompt(prompt);
});
$('body').terminal(function(command, term) {
  typed_message(term, '[[;#fff;;class_name]hello]', 400);
});
body {
  min-height: 100vh;
  margin: 0;
}
.class_name {
  text-decoration: underline;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.terminal/1.8.0/js/jquery.terminal.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.terminal/1.8.0/css/jquery.terminal.min.css" rel="stylesheet"/>

The example on the site was updated accordingly.


text:
Q: Cannot enable basic auth on Windows-Exporter to secure node between Windows and Prometheus As a test environment to monitor status of Windows Servers (CPU, Disk usage, Memory, network etc) I have placed two testing nodes with Windows-Exporter configured on custom port :15000
Next, I have created proper jobs for each separate Windows instances and created dashboard in Grafana.
The problem is that I'm looking for securing nodes so only Prometheus server can access node output and all other computers in same network get deny access to node website.
I have tried to install Windows Node with setting:
msiexec /i windows_exporter-0.19.0-amd64.msi LISTEN_PORT="15000" EXTRA_FLAGS="--web.config.file=C:\Configuration\web.yml"

As well as with different configurations of " and ' in commandline for EXTRA_FLAGS parameter - yet it seems they are being ignored. The only parameter working fine is change of listen port.
I have followed instructions provided at https://prometheus.io/docs/guides/basic-auth/ to set up basic auth.
Web.yml looks like this:
 basic_auth:
      username: 'scrapper'
      password: '$2a$14$AWpxyT1KcRPSE07IfmqTqOZznpMfGwxHP8uPVQV8G0qdjggND3hgC'

However, after installation with msiexec - entry in Windows services for windows_exporter is without web.config.file entry:
"C:\Program Files\windows_exporter\windows_exporter.exe" --log.format logger:eventlog?name=windows_exporter --telemetry.addr 0.0.0.0:15000

I have tried to edit service entry with sc command but it broke node completely, making me rolling back to unprotected access to node.
Does basic auth work on windows-exporter same way as on node-exporter for Linux OSes?
Or is there other possible way to secure access to node exposed data without need to install IIS?

A: I have never worked with node exporter in Windows, but in Linux, your Web.yml configuration file should be as follows:
 basic_auth_users:
        <string>: <secret>

like this:
basic_auth_users:
scrapper: $2a$14$AWpxyT1KcRPSE07IfmqTqOZznpMfGwxHP8uPVQV8G0qdjggND3hgC


text:
Q: How to write Junit test case for executeUpdateNativeQuery() In java I need to write a test case for following method with out hitting actual DB or configuring in memory database
public void deleteExistingRecord( List<String> extSrcIds) throws Exception {
    Map<String, Object> params = new HashMap<>();
    params.put("extSourceIds", extSrcIds);
    String query = "DELETE FROM REG.EXT_ACTIONED_RECORD T WHERE EXT_SRC_ID in :extSourceIds";
    executeUpdateNativeQuery(query, params);
}

A: If you want to check if a method is called, you have to create a mock. See the Mockito website for more details: https://site.mockito.org/


text:
Q: Apache Zookeeper not able to read config file, despite providing one When I start up the Apache Zookeper with this command:
sudo ./zookeeper-server-start.sh ../config/zookeeper.properties
I notice that on startup, it will emit this warning:
[2018-06-27 11:21:47,038] WARN Either no config or no quorum defined in config, running  in standalone mode (org.apache.zookeeper.server.quorum.QuorumPeerMain)
There's not much in there, but I have double checked, and the config is indeed there. Here is its contents:
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# the directory where the snapshot is stored.
dataDir=/tmp/zookeeper
# the port at which the clients will connect
clientPort=2181
# disable the per-ip limit on the number of connections since this is a non-production config
maxClientCnxns=0

What lead me to this discover is that I am actually currently having issues where my Brokers and Zookeepers both are randomly shutting down, without reason. The only reason for the shutdown I am given is:
Signal was killed at: [2018-06-27 13:39:52,423] INFO Terminating process due to signal SIGHUP (kafka.Kafka$)
But that's probably another question - my real question is - why can't my Kafka zookeeper find and keep its config that I am feeding it as a parameter?


text:
Q: How to iterate over array of hashes, then populate new hash keys using iterated hash values in Ruby I have an array like this:
result = [
  {:label=>:road, :value=>"carl-schurz str."},
  {:label=>:house_number, :value=>"25"},
  {:label=>:postcode, :value=>"36041"},
  {:label=>:city, :value=>"fulda"},
  {:label=>:state_district, :value=>"fulda kreis"}
]

I would like to return a hash like the following:
output = {
  "road" => "carl-schurz str.",
  "house_number" => "25",
  "postcode" => "36041",
  "city" => "fulda",
  "state_district" => "fulda kreis"
}

Since I know that hashes can also have positions, I've been trying things like:
result.each do |r|
    r.each do |key, value|
      output[value[0]] = value[1]
    end
   end

But I'm not getting the correct results..

A: Just adding some other solutions FYI.
I personally would have done something like this:
Hash[result.map { |h| [h[:label], h[:value]] }]

Another thing you could look into is each_with_object, which can be pretty handy for constructing new objects. In this case that would look something like:
new_hash = result.each_with_object({}) do |h, r|
  r[h[:label]] = h[:value]
end

A: You can do it easily with "map"...
result.map { |h| [h[:label], h[:value]] }.to_h
Hash[result.map { |h| [h[:label], h[:value]] }]

...or even "reduce"...
result.reduce(Hash.new) { |h,o| h[o[:label]] = o[:value]; h }

This simple benchmark shows that the "reduce" form is slightly faster than the others:
require 'benchmark'

result = [
  {:label=>:road, :value=>"carl-schurz str."},
  {:label=>:house_number, :value=>"25"},
  {:label=>:postcode, :value=>"36041"},
  {:label=>:city, :value=>"fulda"},
  {:label=>:state_district, :value=>"fulda kreis"}
]

n = 1_000_000

Benchmark.bmbm do |x|
  x.report('Hash[]    ') { n.times { Hash[result.map { |h| [h[:label], h[:value]] }] } }
  x.report('map...to_h') { n.times { result.map { |h| [h[:label], h[:value]] }.to_h } }
  x.report('reduce    ') { n.times { result.reduce(Hash.new) { |h,o| h[o[:label]] = o[:value]; h } } }
end

#                  user     system      total        real
# Hash[]       1.830000   0.040000   1.870000 (  1.882664)
# map...to_h   1.760000   0.040000   1.800000 (  1.810998)
# reduce       1.590000   0.030000   1.620000 (  1.633808) *

A: result.map { |h| h.values_at(:label, :value) }.to_h
  #=> {:road=>"carl-schurz str.", :house_number=>"25", :postcode=>"36041",
  #    :city=>"fulda", :state_district=>"fulda kreis"}

A: One more way:
result.map.with_object({}) { |h, new_h| new_h[h[:label]] = h[:value] }

A: I was able to get the desired result using this:
result.each do |r|
  output[r.values[0]] = values[1]
end

Knowing to use hash_object.values was the key.


text:
Q: Problem in implementing Search Filter in Reactjs- Trigger issues I am implementing a react data table with a search filter in it to search the rows. You can see the UI here for a better understanding of code. I implemented it to search the rows by names initially. (I will implement it to search in all columns later).
As you can see in the UI that there are three entries at top named "Kamakshi", "Kanika" and "Kanika" respectively. When I type "Kam" in the search box then this result is shown. Now on pressing backspace my input becomes "ka", which means my search result should show three rows of "Kamakshi", "Kanika" and "Kanika". But there are no changes.
I want to trigger the search filter everytime there is a change in input. I passed it as dependency in useEffect but it didn't worked.
Here is my Bookings2.js (Table is implemented in this)
import React, {useState, useEffect} from 'react';
import axios from 'axios';
import {Link} from 'react-router-dom';
import '../../static/Bookings.css';
import {BsFilterRight} from "react-icons/bs";

let bookings_array = [];
const Bookings2= ()=>{
    const[Bookings, setBooking]=useState([]);
    const[search, setSearch]=useState("");

    useEffect(()=>{
        loadUsers();
    }, []);

    useEffect(()=>{
        if(search.length){
        setBooking(
                Bookings.filter(Booking =>
                    Booking.name.toLowerCase().includes(search.toLowerCase())
                )
            )
        }else{
            setBooking(bookings_array)
        }
    }, [search, Bookings]);

    const loadUsers= async()=>{
        const result =await axios.get("http://localhost:3001/Bookings");
        bookings_array=result.data.reverse();
        setBooking(bookings_array);
    };

    const deleteUser=async id => {
        await axios.delete(`http://localhost:3001/Bookings/${id}`);
        loadUsers();
    }

    return(

Bookings2 Page

                        <BsFilterRight/>
                            <input
                                placeholder=" search....."
                                onChange={e=>setSearch(e.target.value)}
                            />

                        Name
                        Consultant
                        Email
                        Action

                    {Bookings.map((Booking,index)=>(

                            {index+1}
                            {Booking.name}
                            {Booking.consultant}
                            {Booking.email}

                                <Link class="btn btn-primary mr-2" to={`/Bookings/view/${Booking.id}`}>View</Link>
                                <Link class="btn btn-outline-primary mr-2" to={`/Bookings/edit/${Booking.id}`}>Edit</Link>
                                <Link class="btn btn-danger" onClick={()=>deleteUser(Booking.id)}>Delete</Link>

                    ))}

    );
};

export default Bookings2;

A: Whenever a change happens in the search, you are removing things from Bookings...but you do not add them back in when new changes roll in, which is why they are not returning on a backspace. You need to run your loadUsers function again if you want to load your original Bookings back in to be filtered.

A: Instead of filtering the state array, try filtering the original, which is stored in bookings_array. So change this:
if (search.length) {
    setBooking(
        Bookings.filter(Booking =>
            Booking.name.toLowerCase().includes(search.toLowerCase())
        )
    )
} else {
    setBooking(bookings_array)
}

to:
if (search.length) {
    setBooking(
        bookings_array.filter(Booking =>
            Booking.name.toLowerCase().includes(search.toLowerCase())
        )
    )
} else {
    setBooking(bookings_array)
}


text:
Q: algorithm ruby (rails) array of best scores I'm trying to link some ( ten ) items with another one.
To choose the items I have some criteria that are attributes of my item (let's say "category", "size" and "weight").
Each of these criteria have a score (let's say 15 for category, 8 for size and 3 for weight).
My idea to find then ten best items to link with the current was something like that :

*

*Get an array with all combinations of the criteria possible ordered by score. In this case I should have :
[['category', 'size', 'weigth'], ['category','size'], ['category', 'weight'], ['category'], ['size', 'weight'], ['size'], ['weight] ]   ( the corresponding scores are : 26, 23, 18, 15, 11, 8, 3 )

*Then make a unique request with all the combinations in order with a UNION between each combination and a limit 10 at the end.
The sql request will be something like :
(Select *
From items
Where category = "food"
and size = "3"
and weight = "7")
UNION
(Select *
From items
where category = "food"
and size = "3")
UNION
(.....)
limit 10;
I have tested this request and it seems to work well. The idea is that the important requests are the first so the results of the firsts requests are in the top and the limit 10 will just keep the most relevant results. But in telling that I have some doubt it can works on other database (it works on mysql but i'm not sure it will work with PostGreSQL). What do you think of that?

*

*And that's it I can link the results with my current item.

My problem is in the first point I don't know how to have this ordered array with all criteria combinations.
If you've got an idea I will take it ^^
Thank you in advance.

A: Updated as per @tokland's comment.
Here's how you can create an array of combinations:
>> a = [*1..3]
#=> [1, 2, 3]
>> b = (1..a.size).map { |n| a.combination(n).to_a }.flatten(1)
#=> [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]

In another step you can map, combine and sort.


text:
Q: How to make a matrix from two arrays column and rows in JS? I have a json data format:
[{'note':'n1','subject':'subject1','value':10},{'note':'n3','subject':'subject2','value':19}];
from that I have generate two arrays one for header column cols and other for row rows

let notes = [{'note':'n1','subject':'subject1','value':10},{'note':'n3','subject':'subject2','value':19}];

let cols = ['n1', 'n2', 'n3'];
let rows = ['subject1', 'subject2'];

let matrix = Array(cols.length).fill(Array(rows.length).fill(0));
for(const x of notes){
    let {note, subject, value} = x;
    matrix[cols.indexOf(note)][rows.indexOf(subject)] = note;
}
console.log(matrix)

Expected result:
[[10,0,0],[0,0,19]]

But My goal is to render it as an HTML table looks like this:

Subj\Note
Note1
Note2
Note3

Subj1
10
0
0

subj2
0
0
19

How could I do that, Any suggestion or help is much appreciated!

A: I can think of couple ways to do it.  One way would be to loop thru cols and rows using forEach and find the matching value in notes or return 0 to construct the matrix as follows:

let notes = [
  {'note':'n1','subject':'subject1','value':10},
  {'note':'n3','subject':'subject2','value':19}
]

let cols = ['n1', 'n2', 'n3']
let rows = ['subject1', 'subject2']

let matrix = []

rows.forEach(row => {
  let newRow = []
  cols.forEach(col => {
    newRow.push(notes.find(n => n.note === col && n.subject === row)?.value || 0)
  })
  matrix.push(newRow)
})

console.log(matrix)

Another method might be to use reduce to loop thru cols and rows to get your matrix:

let notes = [
  {'note':'n1','subject':'subject1','value':10},
  {'note':'n3','subject':'subject2','value':19}
]

let cols = ['n1', 'n2', 'n3']
let rows = ['subject1', 'subject2']

let matrix = rows.reduce((accRow, row) => {
  accRow.push(cols.reduce((accCol, col) => {
    accCol.push(notes.find(n => n.note === col && n.subject === row)?.value || 0)
    return accCol
  }, []))
  return accRow
}, [])

console.log(matrix)

A: You're on the right track. Just a few points:

*

*Your intention is to declare and create a 2D array but that's not actually the case

*You have rows and columns mixed up

*Instead of = note you should have = value.

let notes = [{'note':'n1','subject':'subject1','value':10},{'note':'n3','subject':'subject2','value':19}];

let cols = ['n1', 'n2', 'n3'];
let rows = ['subject1', 'subject2'];

let matrix = Array(rows.length).fill().map(() => Array(cols.length).fill(0));
for(const x of notes) {
    let {note, subject, value} = x;
    matrix[rows.indexOf(subject)][cols.indexOf(note)] = value;
}
console.log(matrix)


text:
Q: why am getting this exception: Exception in thread "main" org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException i am reading excel file using apache poi 3.16 here is my code
try
        {
            String excelPath = "C:\\Users\\wecme\\Desktop\\AccountStatement.xls";
            FileInputStream fileInputStream = new FileInputStream(new File(excelPath));

            // Create Workbook instance holding .xls file
            XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);

            // Get the first worksheet
            XSSFSheet sheet = workbook.getSheetAt(0);

            // Iterate through each rows
            java.util.Iterator<Row> rowIterator = sheet.iterator();

            while (rowIterator.hasNext())
            {
                // Get Each Row
                Row row = rowIterator.next();

                // Iterating through Each column of Each Row
                java.util.Iterator<Cell> cellIterator = row.cellIterator();

                while (cellIterator.hasNext())
                {

                    Cell cell = cellIterator.next();

                    // Checking the cell format
                    switch (cell.getCellType())
                    {
                   case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                        break;
                   case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getStringCellValue() + "\t");
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:
                        System.out.print(cell.getBooleanCellValue() + "\t");
                        break;

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

        } catch (IOException ie)
        {
            ie.printStackTrace();
        }

my excel data looks like this:
Datetime    Description TransactionId   Credit Amount   Debit Amount    Remaining   OdAmount    EnteredBy   Remarks
1/6/2017 8:14   IDEA (9542010237) COMMISSION    GLGHQN  0.31    0   2721.92 0   iNHYD0390437LO  IDEA COMMISSION

when i read other file which is not having time with date its reading properly ,but when  i try to read this file this exception coming
Exception in thread "main" org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No valid entries or contents found, this is not a valid OOXML (Office Open XML) file
at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:286)
at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:758)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:327)
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:37)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:291)
at excelRead.ReadExcel.main(ReadExcel.java:27)

please help me , thank you.

A: You're creating a XSSFWorkbook which is only suitable for working on xlsx files, i.e. the new xml based office format. Your file extension (xls) however suggests that this is the older Microsoft Office (2003 I guess) format. In order to fix the error you need to convert the file to xlsx format or you need to work with a HSSFWorkbook
You can find some samples concerning HSSF here: https://poi.apache.org/spreadsheet/examples.html#hssf-only
Some examples concerning XDDF can be found here: https://poi.apache.org/spreadsheet/examples.html#xssf-only

A: According to the code where the Exception is thrown (see: https://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/openxml4j/opc/ZipPackage.java?view=markup#l286)
And also the name of the package (openxml4j) it is required that the files are in an openxml compatible format. (i.e. xlsx)
In your case the library cannot open the file because it is not in a .zip format that it can open.
This question has also been asked two months ago, maybe this is also helpful:
How to fix NotOfficeXmlFileException in java Apache POI?


text:
Q: OpenCV 3 C++ Mat fetching with pointer goes random I'm quite new to OpenCV and I'm now using version 3.4.1 with C++ implementation. I'm still exploring, so this question is not specific to a project, but is more of a "try to understand how it works". Please consider, with the same idea in mind, that I know that I'm somehow "reinventing the will" with this code, but I wrote this example to understand "HOW IT WORKS".
The idea is:

*

*Read an RGB image

*Make it binary

*Find Connected areas

*Colour each area differently

As an example I'm using a 5x5 pixel RGB image saved as BMP. The image is a white box with black pixels all around it's contour.

Up to the point where I get the ConnectedComponents matrix, named Mat::Labels, it all goes fine. If I print the Matrix I see exactly what I expect:
11111
10001
10001
10001
11111

Remember that I've inverted the threshold so it is correct to get 1 on the edges...
I then create a Mat with same size of Mat::Labels but 3 channels to colour it with RGB. This is named Mat::ColoredLabels.
Next step is to instanciate a pointer that runs through the Mat::Labels and for each position in the Mat::Labels where the value is 1 fill the corresponding Mat:.ColoredLabels position with a color.
HERE THINGS GOT VERY WRONG ! The pointer does not fetch the Mat::Labels row byt row as I would expect but follows some other order.
Questions:

*

*Am I doing something wrong or it is "obvious" that the pointer fetching follows some "umpredictable" order ?

*How could I set values of a Matrix (Mat::ColoredLabels) based on the values of another matrix (Mat::Labels) ?
.
#include "opencv2\highgui.hpp"
#include "opencv2\opencv.hpp"
#include <stdio.h>

using namespace cv;

int main(int argc, char *argv[]) {

char* FilePath = "";
Mat Img;
Mat ImgGray;
Mat ImgBinary;
Mat Labels;

uchar *P;
uchar *CP;

// Image acquisition
if (argc < 2) {
    printf("Missing argument");
    return -1;
}

FilePath = argv[1];
Img = imread(FilePath, CV_LOAD_IMAGE_COLOR);
if (Img.empty()) {
    printf("Invalid image");
    return -1;
}

// Convert to Gray...I know I could convert it right away while loading....
cvtColor(Img, ImgGray, CV_RGB2GRAY);

// Threshold (inverted) to obtain black background and white blobs-> it works
threshold(ImgGray, ImgBinary, 170, 255, CV_THRESH_BINARY_INV);

// Find Connected Components and put the 1/0 result in Mat::Labels
int BlobsNum = connectedComponents(ImgBinary, Labels, 8, CV_16U);

// Just to see what comes out with a 5x5 image. I get:
//  11111
//  10001
//  10001
//  10001
//  11111

std::cout << Labels << "\n";

// Prepare to fetch the Mat(s) with pointer to be fast
int nRows = Labels.rows;
int nCols = Labels.cols * Labels.channels();
if (Labels.isContinuous()) {
    nCols *= nRows;
    nRows = 1;
}

// Prepare a Mat as big as LAbels but with 3 channels to color different blobs
Mat ColoredLabels(Img.rows, Img.cols, CV_8UC3, cv::Scalar(127, 127, 127));

int ColoredLabelsNumChannels = ColoredLabels.channels();
// Fetch Mat::Labels and Mat::ColoredLabes with the same for cycle...
for (int i = 0; i < nRows; i++) {

    // !!! HERE SOMETHING GOES WRONG !!!!
    P = Labels.ptr<uchar>(i);
    CP = ColoredLabels.ptr<uchar>(i);

    for (int j = 0; j < nCols; j++) {

        // The coloring operation does not work
        if (P[j] > 0) {
            CP[j*ColoredLabelsNumChannels] = 0;
            CP[j*ColoredLabelsNumChannels + 1] = 0;
            CP[j*ColoredLabelsNumChannels + 2] = 255;
        }
    }

}

std::cout << "\n" << ColoredLabels << "\n";
namedWindow("ColoredLabels", CV_WINDOW_NORMAL);
imshow("ColoredLabels", ColoredLabels);

waitKey(0);

printf("Execution completed succesfully");
return 0;
}

A: You used connectedComponents function with CV_16U parameter. This means that the single element of the image will consist of 16 bits (hence '16') and you have to interpret them as unsigned integer (hence 'U'). And since ptr returns a pointer, you have to dereference it to get the value.
Therefore you should access label image elements in the following way:
unsigned short val = *Labels.ptr<unsigned short>(i) // or uint16_t

unsigned short val = Labels.at<unsigned short>.at(y, x);

Regarding your second question, it is as simple as that, but of course you have to understand which type casts result in loss of precisions or overflows and which ones not.
mat0.at<int>(y, x) = mat1.at<int>(y, x); // both matrices have CV_32S types

mat2.at<int>(y, x) = mat3.at<char>(y,x); // CV_32S and CV_8S

// Implicit cast occurs. Possible information loss: assigning 32-bit integer values to 8-bit ints
// mat4.at<unsigned char>(y, x) = mat5.at<unsigned int>(y, x); // CV_8U and CV_32U


text:
Q: Sending a file with RestClient request I have a service in .Net Core which takes an IFormFile as a parameter. I would like to send the data from this IFormFile up to an Api. The code below is the auto generated code from postman which worked for my request. In the 'attachmentRequest.AddFile("file", file);' line, file is a string of the local path which postman uploaded the file from. What is the best way to send my IFormfile as the file sent? Do I use a stream and save the IFormfile to a location in .Net Core and pass that address?
          public async Task<bool> PostIssue(IFormFile file)
            {
            var client = new RestClient("https://sample/10000/attachments");
            client.Timeout = -1;
            var attachmentRequest = new RestRequest(Method.POST);
            attachmentRequest.AddHeader("X-Atlassian-Token", "no-check");
            attachmentRequest.AddHeader("Authorization", "Basic xxxxxxxxxxxxxx=");
            attachmentRequest.AddHeader("Cookie", "atlassian.xsrf.token=xxxxxxxxxxxxxxxxxx_lin");
            attachmentRequest.AddFile("file", file);
            IRestResponse attachmentResponse = client.Execute(attachmentRequest);
            Console.WriteLine(attachmentResponse.Content);

            if (attachmentResponse.IsSuccessful)
            {
                return true;
            }
            else
            {
                return false;
           }
         }

A: You use the second method of AddFile:
  public IRestRequest AddFile (string name, byte [] bytes, string fileName, string contentType = null);

Convert the IFormFile file to byte array format instead of getting the path to transfer the file.
What you said is that uploading to the local using stream is indeed possible, but this is an extra action, you can directly operate IFormFile into byte form and transfer it to the API, as shown below:
 public async Task<bool> PostIssue(IFormFile file)
        {
            var client = new RestClient("http://localhost:50855/Users");
            client.Timeout = -1;
            var attachmentRequest = new RestRequest(Method.POST);
            attachmentRequest.AddHeader("X-Atlassian-Token", "no-check");
            attachmentRequest.AddHeader("Authorization", "Basic xxxxxxxxxxxxxx=");
            attachmentRequest.AddHeader("Cookie", "atlassian.xsrf.token=xxxxxxxxxxxxxxxxxx_lin");

            using (var ms = new MemoryStream())
            {
                file.CopyTo(ms);
                var fileBytes = ms.ToArray();
                attachmentRequest.AddFile("filename",fileBytes, file.FileName);
            }
            IRestResponse attachmentResponse = client.Execute(attachmentRequest);
            Console.WriteLine(attachmentResponse.Content);
            if (attachmentResponse.IsSuccessful)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

Api:
public async Task<IActionResult> attachments()
        {
            var file = Request.Form.Files["filename"]; //get the file
            //do something you want
            return Ok();
        }

Here is the test result:


text:
Q: Как показывать попап только 2 раза с разницей в 3 минуты? всем программерам JavaScript! Я новичок и интересует такой вопрос:
У меня на сайте срабатывает функция mouseleave (когда посетитель уводит курсор вверх со страницы), а внутри лежит код который активирует попап. Мне нужно, чтобы этот код срабатывал только 2 раза: первый как и сейчас, а второй только через 3 минуты - то есть если посетитель увёл мышь вверх, увидел попап, закрыл его, то в ближайшие 3 минуты, если он будет уводить мышку вверх попап не будет всплывать.
Перебровала кучу способов и вариантов,  но видимо что-то делаю не так((( Подскажите что делать?
Вот мой изначальный код:
$(document).mouseleave(function(e){
  if (e.clientY < 0) {
    $("#staypopup").addClass("show");
  }
})

A: new Date().getTime() возвращает количество миллисекунд, прошедших с 1-го января 1970. Ну и три минуты в миллисекундах - 180000 :

var lastPop = 0;
var count = 0;

$(document).on('mouseleave', popup);

function popup(e){
  var now = new Date().getTime();
  var left_3min = 10000 < ( now - lastPop );

  console.log(now - lastPop);

  if (e.clientY < 0 && left_3min) {
    $("#staypopup").addClass("show");
    lastPop = now;

    if( ++count == 2 )
      $(document).off('mouseleave', popup);
  }
}
#staypopup { display: none; }
#staypopup.show { display: block; padding: 50px; background: orange; }

Закрыть

A: Как-то так:
$(document).on('mouseleave.show-staypopup', function (e) {
  if (e.clientY < 0) {
    $("#staypopup").addClass("show")
    $(document).off('mouseleave.show-staypopup')

    setTimeout(function () {
      $(document).on('mouseleave.show-staypopup', function (e) {
        if (e.clientY < 0) {
          $("#staypopup").addClass("show");
          $(document).off('mouseleave.show-staypopup')
        }
      })
    }, 180000)
  }
})


text:
Q: json_encode for flot chart I am stumped on producing a specifically formatted JSON for a flot chart.  Any help is much appreciated!
I use this php code
$query = mysql_query('SELECT * FROM all_programs_extended');

while($row = mysql_fetch_assoc($query)) {
$newData[] = array(
                    'label' => $row['program_type'],
                    'data'  => array(
                "employee1" => $row['employee1'],
                                "employee2" => $row['employee2'],
                "employee3" => $row['employee3']
                                )
                    );

}

print json_encode($newData);

which produces this valid JSON
[{"label":"Program A","data":{"employee1":"5","employee2":"3","employee3":"1"}},
{"label":"Program B","data":{"employee1":"0","employee2":"4","employee3":"2"}},
{"label":"Program A","data":{"employee1":"4","employee2":"2","employee3":"4"}}]

but I need it look like this:
{
    "label": "Program A",
    "data": [[employee1, 5], [employee2, 3], [employee3, 1]],
     "label": "Program B",
    "data": [[employee1, 0], [employee2, 4], [employee3, 2]],
     "label": "Program C",
    "data": [[employee1, 4], [employee2, 2], [employee3, 4]]

}

I seem to have mixed up by brackets and braces, and I also need a comma separating my value pairs between brackets rather than the colon in the first JSON.  Be nice to get ride of the quotation marks around the numbers too!
Thanks very much!

A: Just suround employeeX by an additional array:
$newData[] = array(
    'label' => $row['program_type'],
    'data'  => array(
        array(
            "employee1" => $row['employee1']
        ),
        array (
            "employee2" => $row['employee2']
        ),
        array (
            "employee3" => $row['employee3']
        )
    )
);


text: Q: Azure web app work with azurewebsites but not with domain I created a web app with Angular 9 on top of asp.net core using web api, everything is working ok using the myapp.azurewebsites.net but when I access the app using app.mydomain.com I start getting unauthorized calls to my web api methods (using autorize in controller), the autentication is with identity server with a pfx certificate created by azure and bind to the domain... what is wrong?


text:
Q: run app in background android i build app for location manager.i have a one method which give me lattitute and longitude.
Here are my class and activity.
GPStracker.java
public class GPSTracker extends Service implements LocationListener {

private final Context mContext;
private final Handler _handler = new Handler();
private static int DATA_INTERVAL = 1 * 60 * 1000;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */
public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GPSTracker.this);
    }
}

/**
 * Function to get latitude
 * */
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will lauch Settings Options
 * */
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {

}
public void notifyUser() {
    NotificationManager notificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent intent = new Intent(GPSTracker.this, AndroidGPSTrackingActivity.class);

    //use the flag FLAG_UPDATE_CURRENT to override any notification already there
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification notification = new Notification(R.drawable.ic_launcher, "Some Text", System.currentTimeMillis());
    notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND;

    notification.setLatestEventInfo(this, "", "", contentIntent);
    //10 is a random number I chose to act as the id for this notification
    notificationManager.notify(10, notification);
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

}

AndroidGPSTrackingActivity.java
public class AndroidGPSTrackingActivity extends Activity {

Button btnShowLocation;

Geocoder geocoder;
List<Address> addresses;
private final Handler _handler = new Handler();
private static int DATA_INTERVAL = 1 * 60 * 1000;
// GPSTracker class
GPSTracker gps;
double longitude;
double latitude;
String address,city,state,country,postalCode,knownName,city2;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    geocoder = new Geocoder(this, Locale.getDefault());

    location();

    btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

    // show location button click event
    btnShowLocation.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // create class object

            location();
        }
    });
}

public void location(){

    gps = new GPSTracker(AndroidGPSTrackingActivity.this);

    // check if GPS enabled
    if(gps.canGetLocation()){

        latitude = gps.getLatitude();
        longitude = gps.getLongitude();
        try {
            addresses = geocoder.getFromLocation(latitude, longitude, 1);
            Log.d("adddd", String.valueOf(addresses));
            address = addresses.get(0).getAddressLine(0);
            city = addresses.get(0).getAddressLine(1);
            state = addresses.get(0).getAddressLine(2);

        } catch (IOException e) {
            e.printStackTrace();
        }
        // \n is for new line
        Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude + address + "\n"
                +city +" "+ state
                , Toast.LENGTH_LONG).show();
        _handler.postDelayed(getData, DATA_INTERVAL);
    }else{
        // can't get location
        // GPS or Network is not enabled
        // Ask user to enable GPS/network in settings
        gps.showSettingsAlert();
    }

}

public void notifyUser() {
    NotificationManager notificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent intent = new Intent(AndroidGPSTrackingActivity.this, AndroidGPSTrackingActivity.class);

    //use the flag FLAG_UPDATE_CURRENT to override any notification already there
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification notification = new Notification(R.drawable.ic_launcher, "Some Text", System.currentTimeMillis());
    notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND;

    notification.setLatestEventInfo(this, city, state, contentIntent);
    //10 is a random number I chose to act as the id for this notification
    notificationManager.notify(10, notification);
}

private final Runnable getData = new Runnable()
{
    @Override
    public void run()
    {

        location();
        notifyUser();
    }
};

}

it gives me location from lattitute and longitute.
but when i terminate the app from recent app it does't work.
how to continue this (location()) method in background even if i terminate the app.
please help me.
Thanks in advance

A: you can build remote service to get location info,remote service do not belong your app,it will not be terminated even your app is killed. you can bind remote service to get location info.


text:
Q: Django Viewset detail supports only with pk? not args? My ACTION view is not working.
How to pass args not only pk?

I was using function based api like
Function Based Api View (1)
{host}:{port}/api/food/<year>/<month>/<day>/

Now, I have new viewset for model Food.
ViewSet (2)
{host}:{port}/food/

I hope to integrate this apis to one ModelViewSet so i did like below.
WHAT I WANT (1) + (2)
{host}:{port}/food/files/<year>/<month>/<day>/
{host}:{port}/food/

My Code
class FoodViewSet(viewsets.ModelViewSet):
    queryset = Food.objects.all()
    permission_classes = [blahblah]
    authentication_classes = [blahblah]

    def list(self, request, *args, **kwargs):
        ...
        return Response(blahblah)

    def create(self, request, *args, **kwargs):
        ...
        return Response(blahblah)

    @action(['GET'], detail=True)
    def files(self, request, year, month, day):
        ...
        return Response(blahblah)

A: Sorry, I clear this problem with query url like below.
URL
{host}:{port}/food/files/?year=2019&month=02&day=27

MY CODE
@action(['GET'], detail=False)
def files(self, request):
    year = request.query_params.get('year')
    month = request.query_params.get('month')
    day = request.query_params.get('day')


text:
Q: XML parsing failed in the sqlplus I get following error when executing the query

Invalid token in '[count(../[name(../)=name(.)])=count(../) and count(../*)>1'

However when installing the Itstar_xml_util package, it asks for two initial variables one quot and another call gt, which form the initial structure of the XML, I believe that is causing the error, someone knows how to configure correctly?
SQL> @C:\instantclient_11_2\itstar_xml_util.pxk
     Packge created.
     Enter value for quot: ?
     Enter value for gt: ?

Also follow the query...
SQL > declare
      l_sql_string varchar2(32000);
      l_xml xmltype;
      l_json xmltype;
      begin
      l_sql_string := 'select DESCRICAO from VEI_TIPO_VEICULO';
      l_xml := 'itstar_xml_util.sql2xml(l_sql_string);
      dbms_output.put_line(l_xml.getclobval());
      l_json := itstar_xml_util.xml2json(l_xml);
      dbms_output.put_line(l_json.getclobval());
      end;
      /

A: You have to call
SET DEFINE OFF

before installing the package to ensure that &quot and &gt are not recognized as substitution variables. See also docs.