text:
Q: How to auto count previous 6 months annoucement record in SQL put in the separate box? I have facing big problem to auto count previous 6 months annoucement record in SQL put in the separate box. Is using loop to count the annoucement record? Anyone can guide me or give me an example to do it? If can, better using my code to edit and let me refer. Thanks a lot.
Below is my coding:
    <?php
    $sql_select = 'SELECT * FROM announcement where id = 20' ; //This I try to test id = 20 announcment to call out data

    $query_select = db_conn_select($sql_select);
    foreach ($query_select as $rs_select) {
    $title = $rs_select['title'];
    $date = $rs_select['posted_date'];
    $contents = $rs_select['contents'];
     }

     ?>

<?php echo $title ?> (<?php echo $date ?>)

       <button type="button" class="btn btn-default btn-xs collapse-box" data-toggle="collapse" data-target="#collapseExample1" aria-expanded="false" aria-controls="collapseExample"></button>

    <?php echo $contents ?>

Below is my database information (I want get the posted_date previous 6 months annoucement record to show):

My coding output show like the below:

Actually I want the output like below show auto count previous 6 months announcements put in the separate box :

A: There are two problems:
1) Your query will only return one record. You need to change it so it fetches a set of records from the last 6 months.
The general pattern for finding the last 6 months is easy to find online
yourdatecolumn >= CURDATE() - INTERVAL 6 MONTH

(credit to this answer specifically in this case, but there are dozens of examples available). N.B. You didn't specify, but I'm assuming your DBMS is MySQL, since that's most commonly used with PHP. If you have a different DBMS, you can find an equivalent answer online with a few seconds of searching.
2) you're ending your loop too soon. The current code is ok for one record, but will fail when there is more than one. It will loop over all the records, but then keep assigning their values the same variables, so after the loop finishes you end up with just the last record's values inside those variables. And you are not using a loop to create the HTML multiple times.
To fix that, just bring the HTML inside the loop. Here's the final version:
<?php
$sql_select = 'SELECT * FROM announcement where posted_date >= CURDATE() - INTERVAL 6 MONTH';

$query_select = db_conn_select($sql_select);
foreach ($query_select as $rs_select) {
  $title = $rs_select['title'];
  $date = $rs_select['posted_date'];
  $contents = $rs_select['contents'];
  ?>

        <?php echo $title ?> (
        <?php echo $date ?>)

        <button type="button" class="btn btn-default btn-xs collapse-box" data-toggle="collapse" data-target="#collapseExample1" aria-expanded="false" aria-controls="collapseExample"></button>

      <?php echo $contents ?>

<?php
}
?>

That way it will create the same HTML repeatedly for each record, and use the current values of your variables within each version.


text:
Q: Analysis on Memory Management I'm doing Memory management analysis for my Java web application,
Before starting my tomcat the free memory in RAM was around 595 MB, Once I started the server the free memory goes to 151 MB. When I took the Heap dump, the objects were occupying 262 MB.
So will tomcat alone take remaining 181 MB?
Another question is, I ran Load Test with 500 Users. The free memory goes to 8MB, When I took heap dump here, It was around 265MB. So free space 151 MB is reduced to 8MB, What could be reason
Please note that I used top command to check free memory in RAM.

A: It all depends on how you compute the free memory (Profiler? TaskManager? Programmatically?) and which memory you are evaluating (Heap? Non-Heap? etc...) Tomcat on its own does not take much memory (I don't recall exactly, but a basic setup should definitely not take 180Mb)

A: The free memory is the memory not used by the kernel, programs or disk cache.  How big the disk cache is varies based on which files you have accessed or deleted and is a poor indication of memory consumption.
Java uses quite a bit of memory starting up.  Much of it is shared.  Tomcat can be a relatively complex application depending on what you load, but to use 181 MB for the JVM and Tomcat seems reasonable to me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: XMLHttpRequest bad response with firefox I have a problem when i try to get data from my Server by XMLHttpRequest with Firefox (it works well on Google Chrome)
The value of XMLHttpRequest.response is twice the normal value
Let me show you, when i try with Chrome, the response is :
"[{"field1": value1, "field2": value2}]"

This is perfect
But with Firefox, response is :
"[{"field1": value1, "field2": value2}][{"field1": value1, "field2": value2}]"

It's exactly the same data, and without a ',' between them. So when i try to do an JSON.parse(response), it fail.
This is how i do my XMLHttpRequest :
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost/api/Gifts/full');
xhr.onload = onLoad;
xhr.send(null)

function onLoad() {
  // We can see here the problem here
  console.log('this response = ', this.response);
}

Why firefox send me the value twice ?
EDIT :
I add xhr.setRequestHeader('Cache-Control', 'no-cache'); and it seems working but only for latest version of mozilla (54.0.1). It's really weird


text:
Q: simple_form custom wrapper with a plain radio button I am trying to make custom wrapper for a hybrid form like this:

The idea here is that there are the radio buttons that enable either the date picker, occurrences or indefinite.  I currently have these manually created and I am trying to make a custom Simple Form wrapper to avoid all the hassle of adding tons of code to a simple input.  The second occurrence input is the one that I can't get quite right.  Here is the HTML for the form shown:

   End Date

        <input class="radio_buttons required" type="radio" value="date" name="work_order[end_task]" id="work_order_end_task_date">

      <input disabled="" type="text" value="" name="work_order[end_date]" id="work_order_end_date" data-provide="datepicker" data-date-format="yyyy-mm-dd" data-date-clear-btn="true" data-date-today-btn="linked" data-date-orientation="auto right" data-date-today-highlight="true" class="date required form-control left-border-rounded">

        <input class="radio_buttons required" type="radio" value="number" name="work_order[end_task]" id="work_order_end_task_number">

      <input class="numeric integer form-control" type="string" value="" name="work_order[count]" id="work_order_count">

        Occurrence(s)

            <input class="radio_buttons optional radio_buttons" type="radio" value="none" checked="checked" name="work_order[end_task]" id="work_order_end_task_none">

      <input class="string optional form-control" type="text" value="" name="work_order[count]" id="work_order_count">
      Occurrence(s)

<input class="radio_buttons optional" type="radio" value="none" checked="checked" name="work_order[end_task]" id="work_order_end_task_none">Indefinite

The issue is all the extra spans and labels being added.  Here is my code:
<%= f.input :count, wrapper: :input_group do %>
  <%= f.input :end_task, as: :radio_buttons, wrapper: :radio_addon, collection: [['','none']], label: false %>
  <%= f.input_field :count, as: :string, class: "form-control" %>
  Occurrence(s)
<% end %>

and wrappers:
  config.wrappers :input_group, tag: 'div', class: 'input-group', error_class: 'has-error' do |b|
    b.use :html5
    b.use :input, class: 'form-control'
  end

  config.wrappers :radio_addon, tag: 'span', class: 'input-group-addon border-none' do |b|
    b.use :html5
    b.optional :readonly
    b.use :input, class: 'radio_buttons'
  end

So how do I get rid of the
and  on the radio buttons and then all the extra classes ( integer optional work_order_count for example) being inserted into the wrappers and inputs?

A: I think I figured this out (sort of):

    <%= f.radio_button :end_task, 'number', label: false %>

Works like a charm.  I would still like to add a custom wrapper to this to avoid having to manually add the wrapper span but that does not seem to work.


text:
Q: How can solve OAuthException while i am post a message on facebook i am doing a sample Facebook application in that i am POST a file to a particular person only, while i am doing this i got an error message like..
05-27 14:33:51.806: DEBUG/Response(2211): {"error":{"type":"OAuthException","message":"(#803) Some of the aliases you requested do not exist: friends"}}

Code:
Bundle b = new Bundle();
accesstoken = facebook.getAccessToken();
b.putString("method", "read_stream");
b.putString("attachment","{\"name\":\"" + "\",\"href\":\"google.co.in"; + "\",\"description\":\"" + "\",\"media\":[{\"type\":\"image\",\"src\":\"" + "" + "\",\"href\":\"" + "\"}]}");
String response = facebook.request("friend_id", b, "POST");

A: Have you tried to check documentation for facebook and obtain knowledge, that "friends" is wrong, you should use "friend" or "friendlist" instead.


text:
Q: Dynamic compilation of an element in angular The question is same as Equivalent of $compile in Angular 2
But I have an element

Hello {{name}}!

I have defined name in the class as
this.name = "Mr_Perfect {{job}}";
this.job  = "UI Developer";

Now, I need to compile the div dynamically. I just checked the above link and few answers are deprecated and the accepted answer in the question is good but need to write a lot of code just to compile a small element.
Are there any better methods in the recent releases of angular?

A: You could do

Hello !


text:
Q: Floating point status transfer on ARM7 Cortex A8 There is a comparison:
if( val0 > val1 )

where val0 and val1 are double variables.
The code generated by the Apple LLVM compiler is
+0x184  vcmpe.f64                      d17, d16
+0x188  vmrs                           APSR_nzcv, fpscr <-- FP status transfer (30 cycles stall of ALU)
+0x18c  ble.w                          .....

Is there any way to avoid this kind of transfer?
[UPDATE] The code is running on the Cortex-A8 processor.

A: As it seems it's impossible to avoid flags transition as with the code flow management deals ARM part of the processor, not Neon co-processor.
Question is closed.


text:
Q: Draw in another component I have a homework to do but there is not enough information and I'm stuck right now... Here is the issue, I have three classes :

*

*"ChoicePanel" extends JPanel and add buttons to select a color with a JComboBox
public class ChoicePanel extends JPanel{

    Draw dessin;

    public ChoicePanel(Draw df) {
        dessin = df;
        ...
        // couleurs
        final JComboBox<String> couleurs = new JComboBox<>(new String[] {"bleu", "jaune", "rouge"});
        add(couleurs);
    }

    /** Know what color is selected */
    private Color determineCouleur(int indice){
        switch (indice) {
        case 0:
            return Color.BLUE;
        case 1:
            return Color.YELLOW;
        case 2:
            return Color.RED;
        default:
            return Color.BLACK;
        }
    }
}

*"Draw" extends JPanel and stock all outline and paint them

*"Main" create the frame with those classes included
I have to set Draw as a MouseMotionListener but i can't get the color selected in ChoixePanel because the JComobox is created in the construcor and I can't set it to a field.
So how can I check ChoicePanel's buttons values from Draw ?
Every answer will be very helpfull !

A: The goal of the exercise may be to help you learn about scope and access in Java. Let's refactor the example seen here to meet your requirements.

*

*A ChoicePanel needs a way to update an instance of the Draw panel; you can pass a reference as a parameter to the panel's constructor or the factory method shown below.
public static JPanel create(Draw draw) {…}

*In the combo's action listener set the color on draw; optionally invoke draw.repaint() if the change is not to a bound property such as background color.
Hue h = (Hue) colors.getSelectedItem();
draw.setBackground(h.getColor());
//draw.repaint();

*Because Draw may contain no components, override getPreferredSize() as shown here and below.

*
I can't create a private class…

For convenience in running the example below, ChoicePanel and Draw are included as private static members. Simply move each to its own file, absent the modifiers, to get stand-alone classes having package-private access from Main.
JFrame f = new JFrame("Main");
Draw d = new Draw();
f.add(d, BorderLayout.CENTER);
f.add(ChoicePanel.create(d), BorderLayout.SOUTH);

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * @see https://stackoverflow.com/a/5663782/230513
 */
public class Main {

    private static class ChoicePanel {

        public static JPanel create(Draw draw) {
            JPanel p = new JPanel();
            final JComboBox colors = new JComboBox();
            for (Hue h : Hue.values()) {
                colors.addItem(h);
            }
            colors.addActionListener((ActionEvent e) -> {
                Hue h = (Hue) colors.getSelectedItem();
                draw.setBackground(h.getColor());
            });
            p.add(colors);
            return p;
        }
    }

    private static class Draw extends JPanel {

        public Draw() {
            this.setBackground(Hue.values()[0].getColor());
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(320, 240);
        }
    }

    public enum Hue {

        Cyan(Color.cyan), Magenta(Color.magenta), Yellow(Color.yellow),
        Red(Color.red), Green(Color.green), Blue(Color.blue);

        private final Color color;

        private Hue(Color color) {
            this.color = color;
        }

        public Color getColor() {
            return color;
        }
    }

    private void display() {
        JFrame f = new JFrame("Main");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Draw d = new Draw();
        f.add(d, BorderLayout.CENTER);
        f.add(ChoicePanel.create(d), BorderLayout.SOUTH);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            new Main().display();
        });
    }
}


text:
Q: xamarin android rounded imageview height and width adjustment I am using xamarin android native for my application development. I rounded the image from bitmap on the ImageView using the following code.
<ImageView
      android:id="@+id/proimg"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:src="@drawable/pro1" />

in code,
imgpro.SetImageBitmap(bitmap);
imgpro.SetImageDrawable(ImageHelper.getRoundedCornerImage(bitmap, 120));

public class ImageHelper
{

            public static Android.Support.V4.Graphics.Drawable.RoundedBitmapDrawable getRoundedCornerImage(Bitmap thePic, int cornerRadius)
            {
                Android.Support.V4.Graphics.Drawable.RoundedBitmapDrawable dr = Android.Support.V4.Graphics.Drawable.RoundedBitmapDrawableFactory.Create(null, thePic);
                dr.CornerRadius = cornerRadius;
                return dr;
            }
}

But the image comes with empty space like below(empty spaces highlights with red mark):
The image does not adjust based on the ImageView.
Can anyone help me to resolve this issue.
Thanks in Advance

A: Try this one:
<ImageView
       android:id="@+id/proimg"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:scaleType="centerCrop"
       android:adjustViewBounds="true
       android:src="@drawable/pro1" />


text:
Q: "Explanation power" of a parameter Suppose there are two practically similar statistical models with similar "breath": $L(\theta)$ and $M(a,b)$, where $\theta, a, b$ are parameters. When fitting with data, if we assume that $b$ is fixed, then the fit of $M$ is usually worse than $L$.
In plain words, this might be due to, intuitively, $a$ only contributing to about half of the "explanation power" of $M$, while $\theta$ contributes to the full explanation power. It is not surprising to see that $L$ fits better than $M$.
What is the appropriate name for "explanation power"? How to properly describe this phenomenon? I only took one statistics class so I am not sure which word I should use.


text:
Q: Notify when the user presses the home button I know that I cant override the home button like with the back button. But can the android system fire an event if the home button is pressed? I want to catch this action in order to show a warning message if the user presses the home button. I've looked into several options, the most obvious one, for beginner would be to override the home button
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_HOME) {
        // action goes here
    } else {
        return super.onKeyDown(keyCode, event);
    }
}

But this doesnt work, and I'm completly aware of it.
The onPause method will be called once the current Activity finishes. This method will also be called when the user changes Activity in my application. So is there anyway I can show the user a notifying box, when he presses the home button?
Thanks in advance

A: Actually, it is not possible to catch home button pressed event like others, it is a feature to protect the user.
But there is a hack for your situation:
@Override
public void onAttachedToWindow()
{
    this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
    super.onAttachedToWindow();
}

onAttachedToWindow

This is called when the view is attached to a window

You may read Activity Lifecycle how this hack works.
Also, here is the evidence which shows this method works.

A: @Override
    protected void onUserLeaveHint() {
        // TODO Auto-generated method stub
        super.onUserLeaveHint();
    }

This can also help


text:
Q: Cannot get Data into PHP webservice from JSON in Android     import android.app.Activity;
    import android.os.Bundle;
    import android.os.StrictMode;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicHeader;
    import org.apache.http.protocol.HTTP;
    import org.apache.http.util.EntityUtils;
    import org.json.JSONObject;

    public class MainActivity extends Activity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            if (android.os.Build.VERSION.SDK_INT > 9) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }

            Button btn = (Button) findViewById(R.id.btnInsert);
            EditText editText = (EditText) findViewById(R.id.editText);

            final String value = editText.getText().toString();

            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    try {
                        JSONObject jsonobj = new JSONObject();
                        jsonobj.put("name", value);

                        DefaultHttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppostreq = new HttpPost("http://www.myurl.com/WebserviceInsert2.php");

                        StringEntity se = new StringEntity(jsonobj.toString());

                        Log.d("jsonobj is :>", String.valueOf(jsonobj));

                        se.setContentType("application/json;charset=UTF-8");
                        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));

                        httppostreq.setEntity(se);

                        HttpResponse httpresponse = httpclient.execute(httppostreq);

                        String responseText = null;
                        try {
                            responseText = EntityUtils.toString(httpresponse.getEntity());   // {"code":1}
                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.i("Parse Exception", e + "");
                        }

                        Log.d("Response Text is : ", responseText);

                        JSONObject json = new JSONObject(responseText);

                        int code = json.getInt("code");

                        if (code == 1)
                            Toast.makeText(getApplicationContext(), "Successful", Toast.LENGTH_LONG).show();
                        else
                            Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_LONG).show();
                    } catch (Exception e) {
                        Log.d("Error :>", String.valueOf(e));
                    }
                }
            });
        }
    }

PHP Code:
<?php

    include("include/config.php");

    $name=$_POST["name"];
    //echo $name;

    $flag['code']=0;

    if($result=mysql_query("INSERT INTO test (name) VALUES ('".$name."')"))
    {
        $flag['code']=1;
    }

    print(json_encode($flag));

    $obj->close();

?>

Database table field "name" is blank. The Insert Query fire successfully but.. data was not inserting into table.
I think PHP file was not getting properly 'name' argument from POST method which send by android applicaiton(JSON).

A: you have not posted actual logcat but you can try this code
HttpClient httpClient = new DefaultHttpClient();
//Get COding
HttpPost httpPost = new HttpPost(your_url);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("name", value));
//you can add  more parameters here
httpPost.setEntity(new UrlEncodedFormEntity(parameters));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
response=EntityUtils.toString(httpEntity);

you can add or set content type or Header Usual read this for more
http://developer.android.com/reference/org/apache/http/client/HttpClient.html

A: Because your requesting that url using GET, Method. If your sending any request to the server without mentioning then HttpClient will assume that request for GET, But in your PHP your mentioned its $_POST["name"]; If you replace =$_POST["name"]; with _REQUEST["name"];
Or else you have to set the request type is Post.
Then data may going to inserted to database.


text:
Q: Codeclimate test coverage formatter for Golang Nowhere in Codeclimate docs written how to specify coverage formatter. But when I'm trying to send coverage to Codeclimate:
./cc-test-reporter before-build
./cc-test-reporter after-build

It is failing:

Error: could not find any viable formatter. available formatters: simplecov, lcov, coverage.py, clover, gocov, gcov, cobertura, jacoco

I have gocov installed. Also I generated a report with goconv:
gocov test -coverprofile=out

And I tried to specify the report file to Codeclimate in various ways:
./cc-test-reporter after-build out
./cc-test-reporter after-build < out

But had no luck...
I haven't found any formatter related directives for .codeclimate.yml file. The doc is written in super "you know" style so it didn't help. How to enable/send test coverage with Codeclimate?

A: Export var:
CC_TEST_REPORTER_ID=...

Run:
for pkg in $(go list ./... | grep -v vendor); do
    go test -coverprofile=$(echo $pkg | tr / -).cover $pkg
done
echo "mode: set" > c.out
grep -h -v "^mode:" ./*.cover >> c.out
rm -f *.cover

./cc-test-reporter after-build

A: Abby from Code Climate Support here. Currently, the test-reporter tries to infer where the coverage data could be from a set of default paths.  This is usually enough for users following the default setup of the coverage tool.
But, in the case where the output is not located on one of those paths, you can use the test-reporter low-level commands to indicate the
type of coverage data and where it is. In this particular case you would do something like:
export CC_TEST_REPORTER_ID=<repo-test-reporter-id>
./cc-test-reporter before-build
gocov test -coverprofile=out
./cc-test-reporter format-coverage --input-type gocov out
./cc-test-reporter upload-coverage

You can check more on how to use a test-reporter command by using the flag --help. For example, ./cc-test-reporter format-coverage --help.
That should get you in a good place. If not, let us know at hello@codeclimate.com or here, and I can get more insight. :)

A: For those of you that still have this problem:
For me - the problem was that I had incorrectly named the output coverage file  as "cp.out" instead of "c.out" which is what the cc-test-reporter expects.
Here's my working script:

#!/bin/sh
inputFile=$1
while IFS="=" read -r repo reporterID
do
    cd "$HOME""/go/src/github.com/""$repo" || exit
    echo "performing code coverage upload for ""$repo"
    git checkout master && git pull ##don't know if main is used
    cp -f "$HOME"/shellScripts/test-reporter-latest-darwin-amd64 .
    chmod 755 test-reporter-latest-darwin-amd64
    ./test-reporter-latest-darwin-amd64 before-build
    export CC_TEST_REPORTER_ID="$reporterID"
    go test -coverprofile=c.out ./...

    ./test-reporter-latest-darwin-amd64 after-build --prefix "github.com/""$repo"
    echo
    echo "======================="
    echo
done < "$inputFile"


text:
Q: Prove or disprove : $\sqrt{1 + \sqrt{4+\sqrt{16+\sqrt{256...}}}} = \sqrt{2+\sqrt{5}}$ Edit: My initial question was regarding the expressions:
$\sqrt{1 + \sqrt{4+\sqrt{16+\sqrt{64... + \sqrt{4^{n}}}}}}$
And in general:
$\sqrt{1 + \sqrt{k+\sqrt{k^2+\sqrt{k^3... + \sqrt{k^{n}}}}}}$
And their limits, however, my working out was wrong. So, if someone can explain how to find the values of the above two expressions, that would be great!
This is just something I've noticed playing around with the radicals, and I honestly don't have much idea on how to prove it. These were my ideas:
Let $\sqrt{1 + \sqrt{4+\sqrt{16+\sqrt{256... + \sqrt{4^{2^n}}}}}} = A_n$
My logic was as follows:
$A_n = \sqrt{1 + \sqrt{4+\sqrt{16+\sqrt{256... + \sqrt{4^{2^n}}}}}}$
$A_n^2 = 1 + \sqrt{4+\sqrt{16+\sqrt{256... + \sqrt{4^{2^n}}}}}$
$A_n^2 = 1 + 2\sqrt{1+\frac{1}{4}\sqrt{16+\sqrt{256... + \sqrt{4^{2^n}}}}}$
$A_n^2 = 1 + 2\sqrt{1+\sqrt{1+\frac{1}{16}\sqrt{256+... + \sqrt{4^{2^n}}}}}$
$A_n^2 = 1 + 2\sqrt{1+\sqrt{1+\sqrt{1+... + \sqrt{1}}}}$
$A_{\infty}^2 = 1 + 2\sqrt{1+\sqrt{1+\sqrt{1+... }}} = 1 + 2\phi = 2 + \sqrt{5}$
$A_{\infty} = \sqrt{2 + \sqrt{5}}$
Then, rather than this specific case, how would we evaluate:
$L = \sqrt{1 + \sqrt{k+\sqrt{k^2+\sqrt{k^4+\sqrt{k^8+...}}}}}$
Would we also get $L = \sqrt{\sqrt{k}\phi + 1}$?
And what about expressions such as:
$\sqrt{1 + \sqrt{2+\sqrt{3+...}}}$
Thanks for any answers and guidance!

A: Let $\phi_n:=\sqrt{1+\sqrt{1+\cdots+\sqrt{1}}}$ ($n$ square roots); note that $\phi_n\to\phi$, the golden ratio.
Let $a_{n,r}:=\sqrt{k^{2^{r-n+1}}+\sqrt{\cdots+\sqrt{k^{2^r}}}}$.
For induction in $n$, assume that $a_{n,r}=k^{2^{r-n}}\phi_n$.
Then $$a_{n+1,r}=\sqrt{k^{2^{r-n}}+a_{n,r}}=\sqrt{k^{2^{r-n}}+k^{2^{r-n}}\phi_n}=k^{2^{r-n-1}}\phi_{n+1}$$
The initial case $n=0$ is trivially true.
Thus $\sqrt{k+\sqrt{\cdots}}=\lim_{r\to\infty}a_{r+1,r}=\lim_{r\to\infty}\sqrt{k}\phi_{r+1}=\sqrt{k}\phi$.
Hence $\sqrt{1+\sqrt{k+\cdots}}=\sqrt{1+\sqrt{k}\phi}$.


text:
Q: Differents sizes for \section titles I would like to add an appendix to my report. In order to do that, I add the appendix package which "rename" \section to Appendix A, B, etc ... But I want to make it smaller while keeping the others \section of the documents as the same size as before. Do you know how to do that ? Thanks in advance, Romain.
\documentclass[a4paper,12pt]{article}
\usepackage[a4paper, total={6in, 8in}]{geometry}
\usepackage[title]{appendix}
\begin{document}
\section{Title of the section}
\begin{appendices}
\section{Title of the appendix A}
\section{Title of the appendix B}
\end{appendices}
\end{document}

When I try the following command, I have a problem with the table of content.
\documentclass[a4paper,12pt]{article}
\usepackage[a4paper, total={6in, 8in}]{geometry}
%\usepackage[title]{appendix} % No longer needed
\makeatletter
\renewcommand\appendix{\par
  \setcounter{section}{0}%
  \setcounter{subsection}{0}%
  \gdef\thesection{Appendix \@Alph\c@section}
  \renewcommand\section{\@startsection {section}{1}{\z@}%
    {-3.5ex \@plus -1ex \@minus -.2ex}%
    {2.3ex \@plus.2ex}%
    {\normalfont\large\bfseries}}% from \Large
  \renewcommand\subsection{\@startsection{subsection}{2}{\z@}%
    {-3.25ex\@plus -1ex \@minus -.2ex}%
    {1.5ex \@plus .2ex}%
    {\normalfont\normalsize\bfseries}}% from \large
}
\makeatother
\begin{document}
\newpage
\tableofcontents
\newpage
\section{Title of the section}
\appendix % Added
%\begin{appendices} % No longer needed
\section{Title of the appendix A}
\section{Title of the appendix B}
%\end{appendices} % No longer needed
\end{document}

A: Something like this?
\documentclass[a4paper,12pt]{article}
\usepackage[a4paper, total={6in, 8in}]{geometry}
%\usepackage[title]{appendix} % No longer needed
\makeatletter
\renewcommand\appendix{\par
  \setcounter{section}{0}%
  \setcounter{subsection}{0}%
  \gdef\thesection{Appendix \@Alph\c@section}
  \renewcommand\section{\@startsection {section}{1}{\z@}%
    {-3.5ex \@plus -1ex \@minus -.2ex}%
    {2.3ex \@plus.2ex}%
    {\normalfont\large\bfseries}}% from \Large
  \renewcommand\subsection{\@startsection{subsection}{2}{\z@}%
    {-3.25ex\@plus -1ex \@minus -.2ex}%
    {1.5ex \@plus .2ex}%
    {\normalfont\normalsize\bfseries}}% from \large
}
\makeatother
\begin{document}
\section{Title of the section}
\appendix % Added
%\begin{appendices} % No longer needed
\section{Title of the appendix A}
\section{Title of the appendix B}
%\end{appendices} % No longer needed
\end{document}

Note that I don't use appendix package but the result in your MWE is the same. If you have other reasons beside having Appendix [...] in each section and subsection let me know.


text:
Q: No events such as 'Editing did Change' for a NSTextField? When I developed for the iPhone I had multiple events on touch that could be true for a button. (e.g. Editing did Change, Editing did End …)
Now that I develop for Mac OSX I want my application to recognize multiple events in a NSTextField.
How to do that? Is there an alternative for the events?
Thanks!
EDIT: May delegates be the key?

A: You need to set an object as the delegate of your NSTextField. As NSTextField is a subclass of NSControl, it will call the -controlTextDidChange: method on your object if you implement it.
@interface MyObject : NSObject
{
    IBOutlet NSTextField* textField;
}
@end

@implementation MyObject
- (void)awakeFromNib
{
    [textField setDelegate:self];
}

- (void)controlTextDidChange:(NSNotification *)notification
{
    if([notification object] == textField)
    {
        NSLog(@"The contents of the text field changed");
    }
}
@end


text:
Q: How to use wrap CPTAxisLabel into two lines using corePlot library in iphone sdk? I want to display CPTAxisLabel intwo lines if the text length is greater than 50 characters. How can i do that? I saw a method to draw a string in a rect. But I don't know how to call this method.
 If the following method is the solution for this please help me how to call this. Otherwise please provide me otherway.
Thanks in advance
-(void)drawInRect:(CGRect)rect withTextStyle:(CPTTextStyle *)style inContext:(CGContextRef)context
{
    if ( style.color == nil ) return;
CGContextSaveGState(context);
CGColorRef textColor = style.color.cgColor;

CGContextSetStrokeColorWithColor(context, textColor);
CGContextSetFillColorWithColor(context, textColor);

CPTPushCGContext(context);

UIFont *theFont = [UIFont fontWithName:style.fontName size:style.fontSize];

[self drawInRect:rect
        withFont:theFont
   lineBreakMode:UILineBreakModeWordWrap
       alignment:(UITextAlignment)style.textAlignment];

CGContextRestoreGState(context);
CPTPopCGContext();

}

A: No need to reinvent the wheel—CPTTextLayer can do multi-line text. Insert newline characters ('\n') where you want line breaks. CPTTextStyle can control the text alignment (left, center, right).


text:
Q: Django model choice field exclude value this is a example a model choice:
class Student(models.Model):
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    GRADUATE = 'GR'
    YEAR_IN_SCHOOL_CHOICES = [
        (FRESHMAN, 'Freshman'),
        (SOPHOMORE, 'Sophomore'),
        (JUNIOR, 'Junior'),
        (SENIOR, 'Senior'),
        (GRADUATE, 'Graduate'),
    ]
    year_in_school = models.CharField(
        max_length=2,
        choices=YEAR_IN_SCHOOL_CHOICES,
   )

forms.py :
class StudentForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.queryset = Student.objects.exclude(year_in_school='Freshman')

how can filter the choices for example exclude 'Freshman' from the list on the forms.py?


text:
Q: MongoDB Document Expired Event On Spring Boot I have an scenario in which I need to be aware of which document is deleted in my MongoDB. For instance: I have a collection with this index:
@Field
@Indexed(name="createdIndex", expireAfterSeconds = 120)
private Date created;

My question is: Is there any callback I can put my hands (Spring Boot) to know which document was deleted ?...


text:
Q: How to select used items in a ManyToMany Doctrine relation I have two entities (Item & Tag) linked by a bidirectional ManyToMany relation, and I'd like to display the entity (Tag) records that are actually used in a relation with the other entity (Item) :
Here is my Item entity:
class Item
{
    /**
     * @ORM\ManyToMany(targetEntity="MyBundle\Entity\Tag", inversedBy="items")
     */
    private $tags;
}

And my Tag enity :
class Tag
{
    /**
     * @ORM\ManyToMany(targetEntity="MyBundle\Entity\Item", mappedBy="tags")
     */
    private $items;
}

Now in my Tag Repository I've tried this :
class TagRepository extends \Doctrine\ORM\EntityRepository
{
    public function findAllUsed()
    {
        return $this->createQueryBuilder('t')
            ->leftJoin('t.items', 'items')
            ->groupBy('items.id')
            ->having('COUNT(t.id) > 0')
            ->orderBy('t.name', 'ASC')
            ->getQuery()
            ->getResult();
    }
}

But it doesn't give me the result I'm expecting... Can anyone help? Thanks!

A: I did this from the top of my head, but it should work, I used an innerJoin instead of a leftJoin and then added a where to make sure you get the records that are linked:
public function findAllUsed()
    {
        return $this->createQueryBuilder('t')
            ->innerjoin('t.items', 'i')
            ->groupBy('i.id')
            ->where('i.id = t.items')
            ->having('COUNT(t.id) > 0')
            ->orderBy('t.name', 'ASC')
            ->getQuery()
            ->getResult();
    }
}

I used this example to formulate the answer: Query on a many-to-many relationship using Doctrine with Symfony2

A: The Problem
I didn't test but It seems your error is in the count clause. You are counting tags having('COUNT(t.id) > 0'). So it will return all tags.
Another error is you grouping by 'items' and selecting only 't'. You don't need group by.
Solutions
Change 'tags' for 'items' in having clause.
public function findAllUsed()
{
    return $this->createQueryBuilder('t')
        ->leftJoin('t.items', 'items')
        ->having('COUNT(items.id) > 0')
        ->orderBy('t.name', 'ASC')
        ->getQuery()
        ->getResult();
}

Another possible way more simple is do a innerJoin like @KevinTheGreat, but check won't need having or where clauses any more:
public function findAllUsed()
{
    return $this->createQueryBuilder('t')
        ->innerJoin('t.items', 'items')
        ->orderBy('t.name', 'ASC')
        ->getQuery()
        ->getResult();
}


text:
Q: How to inverse x>y so that I will have an angled corner? Here's my assignment:
Write a program to draw a red square that is 200 pixels by 200 pixels with this black edge that is 20 pixels wide in the middle and has two diagonal corners (imagine that if the diagonal lines kept going, they would meet in the center of the diagram).
Here's what I've got so far:
      var image = new SimpleImage(200, 200)
      for (var p of image.values()){
      var x = p.getX();
      var y = p.getY();
      if (y < 0) {
          p.setRed(255);
      }
      if (x>y) {p.setRed(255);
      }
      if (x > 20) {p.setRed(255);}
      //if (y > x) {p.setRed(255);}

  }
  print (image);

How should I go on about creating a diagonal corner at the bottom left corner? I've created a diagonal corner at the top left corner with the expression x > y. Is there an inverse of this that could produce the diagonal corner at the bottom left?

A: Try adding one more condition to your for loop:
if(y>180 && x>(200-y) && x<=20){
    p.setRed(255);
}

so the whole code will look like this:
var image = new SimpleImage(200, 200)
 for (var p of image.values()){
     var x = p.getX();
     var y = p.getY();
     if (y < 0) {
         p.setRed(255);}
     if (x>y) {p.setRed(255);}
     if (x > 20) {p.setRed(255);}
     if(y > 180 && x>(200-y) && x <=20){
         p.setRed(255);
    }
}
print (image);

A: Here is my solution:
var image = new SimpleImage(200, 200)
     for (var p of image.values()){
         var x = p.getX();
         var y = p.getY();

         if (x<=20 & y-x >= 0 & y<=200-x) {
             p.setRed(255);
         }
     }
print (image);

Here is the explanation. Draw x and y axis on the picture. Now, there are 4 lines that define the shape you are talking about:
x=0 (the left vertical one)
x = 20 (the right vertical one)
y = x (the main horizontal)
y = 200 - x (the top horizontal)
Now you just need to convert these equalities into inequalities by picking the half of the plane you need, for example x=0 (you need the right hand side) turns into x > 0.
Add all of the equations into the if clause (also notice that x > 0 is not necessary in this situation) and there you go.


text:
Q: How does import really work in Javascript I am having trouble understanding how import works in Javascript. Is it not supposed to just import the named function.
Here are my 2 files -
test.js -
export const add = (a,b) => {
    return a+b
}

export const subtract = (a,b) => {
    return a-b
}

console.log(add(7,7))

console.log(subtract(6,7))

and index.js
import { add } from './test.js'

console.log(add(4,5));

When running node index.js here is the output
14

-1

9

Why is the import also running the function calls in test.js
Thanks for your help.

A: In js import works in a way that the imported modules are invoked first wherever you place your import statements in your file and after that your current file is executed. That's how js works!


text:
Q: Parse a multiline email to var I'm attempting to parse a multi-line email so I can get at the data which is on its own newline under the heading in the body of the email.
It looks like this:
EMAIL STARTING IN APRIL

Marketing ID                                     Local Number
-------------------                              ----------------------
GR332230                                         0000232323

Dispatch Code                                    Logic code
-----------------                                -------------------
GX3472                                           1

Destination ID                                   Destination details
-----------------                                -------------------
3411144

It appears I am getting everything on each messagebox when I use string reader readline, though all I want is the data under each ------ as shown
This is my code:
foreach (MailItem mail in publicFolder.Items)
{
    if (mail != null)
    {

        if (mail is MailItem)
        {

            MessageBox.Show(mail.Body, "MailItem body");
            // Creates new StringReader instance from System.IO
            using (StringReader reader = new StringReader(mail.Body))
            {
                string line;
                while ((line = reader.ReadLine()) !=null)
                //Loop over the lines in the string.
                if (mail.Body.Contains("Marketing ID"))
                {
                    // var localno = mail.Body.Substring(247,15);//not correct approach

                    // MessageBox.Show(localrefno);
                    //MessageBox.Show("found");
                    //var conexid = mail.Body.Replace(Environment.NewLine);

                    var regex = new Regex("<br/>", RegexOptions.Singleline);

                    MessageBox.Show(line.ToString());
                }
            }

            //var stringBuilder = new StringBuilder();

            //foreach (var s in mail.Body.Split(' '))
            //{
            //    stringBuilder.Append(s).AppendLine();
            //}
            //MessageBox.Show(stringBuilder.ToString());

        }
        else
        {
            MessageBox.Show("Nothing found for MailItem");
        }
    }
}

You can see I had numerous attempts with it, even using substring position and using regex. Please help me get the data from each line under the ---.

A:   var dict = new Dictionary<string, string>();
            try
            {
                var lines = email.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                int starts = 0, end = 0, length = 0;
                while (!lines[starts + 1].StartsWith("-")) starts++;
                for (int i = starts + 1; i < lines.Length; i += 3)
                {
                    var mc = Regex.Matches(lines[i], @"(?:^| )-");
                    foreach (Match m in mc)
                    {
                        int start = m.Value.StartsWith(" ") ? m.Index + 1 : m.Index;
                        end = start;
                        while (lines[i][end++] == '-' && end < lines[i].Length - 1) ;
                        length = Math.Min(end - start, lines[i - 1].Length - start);
                        string key = length > 0 ? lines[i - 1].Substring(start, length).Trim() : "";
                        end = start;
                        while (lines[i][end++] == '-' && end < lines[i].Length) ;
                        length = Math.Min(end - start, lines[i + 1].Length - start);
                        string value = length > 0 ? lines[i + 1].Substring(start, length).Trim() : "";
                        dict.Add(key, value);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Email is not in correct format");
            }

Live Demo
Using Regular Expressions:
     var dict = new Dictionary<string, string>();
        try
        {
            var lines = email.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            int starts = 0;
            while (!lines[starts + 1].StartsWith("-")) starts++;
            for (int i = starts + 1; i < lines.Length; i += 3)
            {
                var keys = Regex.Matches(lines[i - 1], @"(?:^| )(\w+\s?)+");
                var values = Regex.Matches(lines[i + 1], @"(?:^| )(\w+\s?)+");
                if (keys.Count == values.Count)
                    for (int j = 0; j < keys.Count; j++)

                        dict.Add(keys[j].Value.Trim(), values[j].Value.Trim());
                else // remove bug if value of first key in a line has no value
                {
                    if (lines[i + 1].StartsWith(" "))
                    {
                        dict.Add(keys[0].Value.Trim(), "");
                        dict.Add(keys[1].Value.Trim(), values[0].Value.Trim());
                    }
                    else
                    {
                        dict.Add(keys[0].Value, values[0].Value.Trim());
                        dict.Add(keys[1].Value.Trim(), "");
                    }
                }

            }
        }
        catch (Exception ex)
        {
            throw new Exception("Email is not in correct format");
        }

Live Demo

A: It is not a very good idea to do that with Regex because it is quite easy to forget the edge cases, not easy to understand, and not easy to debug. It's quite easy to get into a situation that the Regex hangs your CPU and times out. (I cannot make any comment to other answers yet. So, please check at least my other two cases before you pick your final solution.)
In your cases, the following Regex solution works for your provided example. However, some additional limitations are there: You need to make sure there are no empty values in the non-starting or non-ending column. Or, let's say if there are more than two columns and any one of them in the middle is empty will make the names and values of that line mismatched.
Unfortunately, I cannot give you a non-Regex solution because I don't know the spec, e.g.: Will there be empty spaces? Will there be TABs? Does each field has a fixed count of characters or will they be flexible? If it is flexible and can have empty values, what kind of rules to detected which columns are empty? I assume that it is quite possible that they are defined by the column name's length and will have only space as delimiter. If that's the case, there are two ways to solve it, two-pass Regex or write your own parser. If all the fields has fixed length, it would be even more easier to do: Just using the substring to cut the lines and then trim them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

public class Program
{
    public class Record{
        public string Name {get;set;}
        public string Value {get;set;}
    }

    public static void Main()
    {
        var regex = new Regex(@"(?<name>((?!-)[\w]+[ ]?)*)(?>(?>[ \t]+)?(?<name>((?!-)[\w]+[ ]?)+)?)+(?:\r\n|\r|\n)(?>(?<splitters>(-+))(?>[ \t]+)?)+(?:\r\n|\r|\n)(?<value>((?!-)[\w]+[ ]?)*)(?>(?>[ \t]+)?(?<value>((?!-)[\w]+[ ]?)+)?)+", RegexOptions.Compiled);
        var testingValue =
@"EMAIL STARTING IN APRIL

Marketing ID                                     Local Number
-------------------                              ----------------------
GR332230                                         0000232323

Dispatch Code                                    Logic code
-----------------                                -------------------
GX3472                                           1

Destination ID                                   Destination details
-----------------                                -------------------
3411144";
        var matches = regex.Matches(testingValue);

        var rows = (
            from match in matches.OfType<Match>()
            let row = (
                from grp in match.Groups.OfType<Group>()
                select new {grp.Name, Captures = grp.Captures.OfType<Capture>().ToList()}
            ).ToDictionary(item=>item.Name, item=>item.Captures.OfType<Capture>().ToList())
            let names = row.ContainsKey("name")? row["name"] : null
            let splitters = row.ContainsKey("splitters")? row["splitters"] : null
            let values = row.ContainsKey("value")? row["value"] : null
            where names != null && splitters != null &&
                names.Count == splitters.Count &&
                (values==null || values.Count <= splitters.Count)
            select new {Names = names, Values = values}
            );

        var records = new List<Record>();
        foreach(var row in rows)
        {
            for(int i=0; i< row.Names.Count; i++)
            {
                records.Add(new Record{Name=row.Names[i].Value, Value=i < row.Values.Count ? row.Values[i].Value : ""});
            }
        }

        foreach(var record in records)
        {
            Console.WriteLine(record.Name + " = " + record.Value);
        }
    }
}

output:
Marketing ID  = GR332230
Local Number = 0000232323
Dispatch Code  = GX3472
Logic code = 1
Destination ID  = 3411144
Destination details =

Please note that this also works for this kind of message:
EMAIL STARTING IN APRIL
Marketing ID                                     Local Number
-------------------                              ----------------------
GR332230                                         0000232323

Dispatch Code                                    Logic code
-----------------                                -------------------
GX3472                                           1

Destination ID                                   Destination details
-----------------                                -------------------
                                                 3411144

output:
Marketing ID  = GR332230
Local Number = 0000232323
Dispatch Code  = GX3472
Logic code = 1
Destination ID  =
Destination details = 3411144

Or this:
EMAIL STARTING IN APRIL

Marketing ID                                     Local Number
-------------------                              ----------------------

Dispatch Code                                    Logic code
-----------------                                -------------------
GX3472                                           1

Destination ID                                   Destination details
-----------------                                -------------------
                                                 3411144

output:
Marketing ID  =
Local Number =
Dispatch Code  = GX3472
Logic code = 1
Destination ID  =
Destination details = 3411144

A: Here is my attempt. I don't know if the email format can change (rows, columns, etc).
I can't think of an easy way to separate the columns besides checking for a double space (my solution).
class Program
{
    static void Main(string[] args)
    {
        var emailBody = GetEmail();
        using (var reader = new StringReader(emailBody))
        {
            var lines = new List<string>();
            const int startingRow = 2; // Starting line to read from (start at Marketing ID line)
            const int sectionItems = 4; // Header row (ex. Marketing ID & Local Number Line) + Dash Row + Value Row + New Line

            // Add all lines to a list
            string line = "";
            while ((line = reader.ReadLine()) != null)
            {
                lines.Add(line.Trim()); // Add each line to the list and remove any leading or trailing spaces
            }

            for (var i = startingRow; i < lines.Count; i += sectionItems)
            {
                var currentLine = lines[i];
                var indexToBeginSeparatingColumns = currentLine.IndexOf("  "); // The first time we see double spaces, we will use as the column delimiter, not the best solution but should work

                var header1 = currentLine.Substring(0, indexToBeginSeparatingColumns);
                var header2 = currentLine.Substring(indexToBeginSeparatingColumns, currentLine.Length - indexToBeginSeparatingColumns).Trim();

                currentLine = lines[i+2]; //Skip dash line
                indexToBeginSeparatingColumns = currentLine.IndexOf("  ");

                string value1 = "", value2 = "";
                if (indexToBeginSeparatingColumns == -1) // Use case of there being no value in the 2nd column, could be better
                {
                    value1 = currentLine.Trim();
                }
                else
                {
                    value1 = currentLine.Substring(0, indexToBeginSeparatingColumns);
                    value2 = currentLine.Substring(indexToBeginSeparatingColumns, currentLine.Length - indexToBeginSeparatingColumns).Trim();
                }

                Console.WriteLine(string.Format("{0},{1},{2},{3}", header1, value1, header2, value2));
            }
        }
    }

    static string GetEmail()
    {
        return @"EMAIL STARTING IN APRIL

                Marketing ID                                     Local Number
                -------------------                              ----------------------
                GR332230                                         0000232323

                Dispatch Code                                    Logic code
                -----------------                                -------------------
                GX3472                                           1

                Destination ID                                   Destination details
                -----------------                                -------------------
                3411144";
    }
}

Output looks something like this:
Marketing ID,GR332230,Local Number,0000232323
Dispatch Code,GX3472,Logic code,1
Destination ID,3411144,Destination details,

A: Here is an aproach asuming you don't need the headers, info comes in order and mandatory.
This won't work for data that has spaces or optional fields.
foreach (MailItem mail in publicFolder.Items)
{
  MessageBox.Show(mail.Body, "MailItem body");
  // Split by line, remove dash lines.
  var data = Regex.Split(mail.Body, @"\r?\n|\r")
    .Where(l => !l.StartsWith('-'))
    .ToList();
  // Remove headers
  for(var i = data.Count -2; lines >= 0; i -2)
  {
    data.RemoveAt(i);
  }
  // now data contains only the info you want in the order it was presented.
  // Asuming info doesn't have spaces.
  var result = data.SelectMany(d => d.Split(' '));
  // WARNING: Missing info will not be present.
  // {"GR332230", "0000232323", "GX3472", "1", "3411144"}
}


text:
Q: Best and quickest way to parse JSON data to listview android My JSONDATA
[{"Name":"47ABC","Location":"Chennai","Image":"47ABC_175.png","Funding":"150","Founded":"2013 ","Status":1,"RowVAl":1},{"Name":"57ABC","Location":"Mumbai","Image":"57ABC_175.png","Funding":"1250","Founded":"2010 ","Status":2,"RowVAl":1}]

My onBackground class
 protected String doInBackground(String... params) {

  return Utils.getJSONStringHTTPResponse(connString + "/GetSearch", "1");

            }

getJSONStringHTTPResponse class
public static String getJSONStringHTTPResponse(String url,String EmpId) {
        String jsonString = null;
        String httpRequest=url;
        System.out.println("Coonstring : " + httpRequest);

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(httpRequest);
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("PageNumber", EmpId));

        try {

            httpPost.setEntity(new UrlEncodedFormEntity(list));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            jsonString = EntityUtils.toString(httpResponse.getEntity());
            jsonString = android.text.Html.fromHtml(jsonString).toString();
            System.out.println("Response: " + jsonString);

        } catch (Exception e) {
            return "Exception" + e.getMessage();
        }

        return jsonString;
    }

My RowsAdapter class
    public class RowAdapter extends ArrayAdapter<Item> {

        private Activity activity;
        private List<Item> items;
        private Item objBean;
        private int row;

        public RowAdapter(Activity act, int resource, List<Item> arrayList) {
            super(act, resource, arrayList);
            this.activity = act;
            this.row = resource;
            this.items = arrayList;
        }

My onPostExecute class
                    JSONArray jsonArray=new JSONArray(result);

                    for (int i = 0; i < 3; i++) {
                        JSONObject objJson = jsonArray.getJSONObject(i);
                        System.out.println(i+"/"+objJson.getString(Name));
                        Item objItem = new Item();

                        objItem.setName(objJson.getString(Name));
                        objItem.setLocation(objJson.getString(Location));
                        objItem.setImage(objJson.getString(Image));
                        objItem.setFounded(objJson.getString(Funding));
                        objItem.setFounded(objJson.getString(Founded));
                        objItem.setStatus(objJson.getString(Status));
                        objItem.setRowVAls(objJson.getString(RowVAl));

                        System.out.println("obj::"+objItem);
                        arrayOfList.add(objItem);
                      }

 setAdapterToListview();

My SetAdaptertoListView class
public void setAdapterToListview() {
        try {

        objAdapter = new NewsRowAdapter(MainActivity.this, R.layout.row,
                arrayOfList);

            listView.setAdapter(objAdapter);  //i get error on this line
        }catch(Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());

        }
    }

ITEM class
public String getName() {
        return Name;
    }

    public void setName(String Name) {
        this.Name = Name;
    }

contains all the getters and setters.
Whole Stacktrace
07-13 12:07:16.825  11951-11951/com.company.agsl.letsventure W/System.err﹕ java.lang.NullPointerException
07-13 12:07:16.830  11951-11951/com.company.agsl.letsventure W/System.err﹕ at com.company.agsl.letsventure.MainActivity$MyTask.onPostExecute(MainActivity.java:126)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at com.company.agsl.letsventure.MainActivity$MyTask.onPostExecute(MainActivity.java:65)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.os.AsyncTask.finish(AsyncTask.java:631)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.os.AsyncTask.access$600(AsyncTask.java:177)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:99)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.os.Looper.loop(Looper.java:176)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5419)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:525)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
07-13 12:07:16.840  11951-11951/com.company.agsl.letsventure W/System.err﹕ java.lang.NullPointerException
07-13 12:07:16.850  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
07-13 12:07:16.850  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.widget.ListView.setAdapter(ListView.java:470)
07-13 12:07:16.850  11951-11951/com.company.agsl.letsventure W/System.err﹕ at com.company.agsl.letsventure.MainActivity.setAdapterToListview(MainActivity.java:169)
07-13 12:07:16.850  11951-11951/com.company.agsl.letsventure W/System.err﹕ at com.company.agsl.letsventure.MainActivity$MyTask.onPostExecute(MainActivity.java:156)
07-13 12:07:16.850  11951-11951/com.company.agsl.letsventure W/System.err﹕ at com.company.agsl.letsventure.MainActivity$MyTask.onPostExecute(MainActivity.java:65)
07-13 12:07:16.850  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.os.AsyncTask.finish(AsyncTask.java:631)
07-13 12:07:16.850  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.os.AsyncTask.access$600(AsyncTask.java:177)
07-13 12:07:16.850  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
07-13 12:07:16.855  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:99)
07-13 12:07:16.855  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.os.Looper.loop(Looper.java:176)
07-13 12:07:16.855  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5419)
07-13 12:07:16.855  11951-11951/com.company.agsl.letsventure W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
07-13 12:07:16.855  11951-11951/com.company.agsl.letsventure W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:525)
07-13 12:07:16.855  11951-11951/com.company.agsl.letsventure W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
07-13 12:07:16.855  11951-11951/com.company.agsl.letsventure W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
07-13 12:07:16.855  11951-11951/com.company.agsl.letsventure W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
07-13 12:07:16.860  11951-11951/com.company.agsl.letsventure I/System.out﹕ Exception:nullnull
07-13 12:07:16.865  11951-11951/com.company.agsl.letsventure D/AbsListView﹕ unregisterIRListener() is called
07-13 12:07:16.875  11951-11951/com.company.agsl.letsventure E/ViewRootImpl﹕ sendUserActionEvent() mView == null
07-13 12:07:17.110  11951-11951/com.company.agsl.letsventure D/AndroidRuntime﹕ Shutting down VM
07-13 12:07:17.110  11951-11951/com.company.agsl.letsventure W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41e6f700)
07-13 12:07:17.125  11951-11951/com.company.agsl.letsventure E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
            at android.widget.ListView.onMeasure(ListView.java:1140)
            at android.view.View.measure(View.java:16831)
            at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
            at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:477)
            at android.view.View.measure(View.java:16831)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5245)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at android.view.View.measure(View.java:16831)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5245)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
            at android.view.View.measure(View.java:16831)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5245)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2586)
            at android.view.View.measure(View.java:16831)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2189)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1352)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1535)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1249)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6364)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
            at android.view.Choreographer.doCallbacks(Choreographer.java:591)
            at android.view.Choreographer.doFrame(Choreographer.java:561)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
            at android.os.Handler.handleCallback(Handler.java:730)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5419)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
            at dalvik.system.NativeStart.main(Native Method)

getView class
public View getView(final int position, View convertView, ViewGroup parent) {
        View view = convertView;
        ViewHolder holder;

        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(row, null);

            holder = new ViewHolder();
            view.setTag(holder);
        } else {

            holder = (ViewHolder) view.getTag();

        }
        System.out.println(items.size()+" :: Sizess  "+ position);
        if ((items == null) || ((position + 1) > items.size()))
            return view;

        objBean = items.get(position);

        holder.tvName = (TextView) view.findViewById(R.id.name);
        holder.tvLocation = (TextView) view.findViewById(R.id.location);
        holder.tvSector = (TextView) view.findViewById(R.id.sector);
        holder.tvFounded = (TextView) view.findViewById(R.id.foundedyear);
        holder.tvFund=(TextView) view.findViewById(R.id.fundraising);*/
        holder.ivImage= (ImageView) view.findViewById(R.id.imageButton);

        if (holder.tvName != null && null != objBean.getName()
                && objBean.getName().trim().length() > 0) {
            //holder.tvName.setText(Html.fromHtml("Name:"+objBean.getName()));
            holder.tvName.setText(Html.fromHtml(objBean.getName()));
        }

       if (holder.tvLocation != null && null != objBean.getLocation()
                && objBean.getName().trim().length() > 0) {
            holder.tvLocation.setText(Html.fromHtml(objBean.getLocation()));
        }
        if (holder.tvStatus != null && null != objBean.getStatus()
                && objBean.getName().trim().length() > 0) {
            holder.tvStatus.setText(Html.fromHtml(objBean.getStatus()));
        }
        if (holder.tvSector != null&& null != objBean.getSector()
                && objBean.getName().trim().length() > 0) {
            holder.tvSector.setText(Html.fromHtml(objBean.getSector()));
        }
        if (holder.tvFounded != null&& 0 != objBean.getFounded()
                && objBean.getName().trim().length() > 0) {
            holder.tvFounded.setText(Html.fromHtml(""+objBean.getFounded()));
        }
        if (holder.tvFund != null&& 0 != objBean.getFundAsking()
                && objBean.getName().trim().length() > 0) {
            holder.tvFund.setText(Html.fromHtml(""+objBean.getFundAsking()));
        }
        if (holder.ivImage != null&& null != objBean.getName()
                && objBean.getName().trim().length() > 0) {
            URL myUrl = null;
            try {
                myUrl = new URL(objBean.getImage());
                InputStream inputStream = (InputStream)myUrl.getContent();
                Drawable drawable = Drawable.createFromStream(inputStream, null);
                holder.ivImage.setImageDrawable(drawable);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return view;
    }

A: If I'm not wrong you are parsing the
"Status": 1, & "RowVAl": 1

as
objItem.setStatus(objJson.getString(Status));
objItem.setRowVAls(objJson.getString(RowVAl));

but they are clearly Integers not String.
It might be the reason of getting a null pointer exception. Try fixing it and It should solve the issue.

A: For Best and Quickest try this:( use Gson library)
 Gson gson=new Gson();
  Type listType = new TypeToken<ArrayList<Items>>() {
  }.getType();

  List<Items> itemsList=gson.fromJson(line, listType);
  rowAdapter = new RowAdapter(MainActivity.this, R.layout.row,itemsList);
  listView.setAdapter(rowAdapter);

Items class goes here:
public class Items {
        private String Name;
        private String Location;
        private String Image;
        private String Funding;
        private String Founded;
        private int Status;
        private int RowVAI;
        // setters and getters goes here

        public Items() {
        }

       public Items(String name, String location, String image, String funding, String founded, int status, int rowVAI) {
           Name = name;
           Location = location;
           Image = image;
           Funding = funding;
           Founded = founded;
           Status = status;
           RowVAI = rowVAI;
       }

       public String getName() {
           return Name;
       }

       public void setName(String name) {
           Name = name;
       }

       public String getLocation() {
           return Location;
       }

       public void setLocation(String location) {
           Location = location;
       }

       public String getImage() {
           return Image;
       }

       public void setImage(String image) {
           Image = image;
       }

       public String getFunding() {
           return Funding;
       }

       public void setFunding(String funding) {
           Funding = funding;
       }

       public String getFounded() {
           return Founded;
       }

       public void setFounded(String founded) {
           Founded = founded;
       }

       public int getStatus() {
           return Status;
       }

       public void setStatus(int status) {
           Status = status;
       }

       public int getRowVAI() {
           return RowVAI;
       }

       public void setRowVAI(int rowVAI) {
           RowVAI = rowVAI;
       }

       @Override
       public String toString() {
           return "Items{" +
                   "Name='" + Name + '\'' +
                   ", Location='" + Location + '\'' +
                   ", Image='" + Image + '\'' +
                   ", Funding='" + Funding + '\'' +
                   ", Founded='" + Founded + '\'' +
                   ", Status=" + Status +
                   ", RowVAI=" + RowVAI +
                   '}';
       }
   }

output :
[Items{Name='47ABC', Location='Chennai', Image='47ABC_175.png', Funding='150', Founded='2013 ', Status=1, RowVAI=0}, Items{Name='57ABC', Location='Mumbai', Image='57ABC_175.png', Funding='1250', Founded='2010 ', Status=2, RowVAI=0}]

A: Here is the issue
You declare jsonString like this in Utils class getJSONStringHTTPResponse method.
String jsonString = null;
In any case network failure or whatever error happened inside of try {...} block your getJSONStringHTTPResponse must returns null. So when you try to
convert to JSONArray you get nullPointer Exception in the following line
 JSONArray jsonArray=new JSONArray(result);

The solution is you need to find the error inside of the try{} block and need to fix. as well as add null Pointer check in onPostExecute method.
Edit 1:
Edit your getView like this.
if (view == null) {
            LayoutInflater inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(row, null);

            holder = new ViewHolder();
holder.tvName = (TextView) view.findViewById(R.id.name);
        holder.tvLocation = (TextView) view.findViewById(R.id.location);
        holder.tvSector = (TextView) view.findViewById(R.id.sector);
        holder.tvFounded = (TextView) view.findViewById(R.id.foundedyear);
        holder.tvFund=(TextView) view.findViewById(R.id.fundraising);*/
        holder.ivImage= (ImageView) view.findViewById(R.id.imageButton);
            view.setTag(holder);
        } else {

            holder = (ViewHolder) view.getTag();

        }

You need to add the findView methods inside of if condition


text:
Q: c++ word count(as words we take every possible variable name) I was asked to make a program that reads a cin could be text and then counts the words in it(i need to count as a word every name that can be accepted as a variable name ex _a,a1) my problem is that my code works for only one byte. if its more than one the sum is always 0.The only thing i think i can have wrong is that i didn't put the string into an array but a friend of mine told me i don't need to do so.below is my code:
#include<iostream>
#include<string>
#include<stdio.h>
using namespace std;
int main(){
    int sum=0;
    bool z= false;  //z is just a switch to see if we are inside a word\n
    string s;
    cout<<"Insert text: ";
    getline(cin,s);         //here we get the string\n
    int n=s.length()-1;     //for some reason i==(s.length-1) put a warning$
    for(int i=0;i==n;i++){  //here we check each byte to see what it contai$
            cout<<s[i];
            if(isalpha(s[i]) || s[i]=='_'){ //to enter a word we need a let$
                    z=true;
                    sum++;}
            if(z==true){    // if we are in a word we can have numbers as w$
                    if(!isalnum(s[i]) && s[i]!='_'){
                            z=false;}}      // exit the current word and go$
            if(s[i]==EOF){                  // the end\n
                    break;}}
    cout<<"Number of words is: "<<sum<<endl;        // the real end\n
return 0;
}

A: This is so much easier than the code you have provided. We can do this with the STL using an istream iterator. If you choose to use C++ and not C, then you should take advantage of the standard library.
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
using namespace std;
int main(){

   vector<string> words((istream_iterator<string>(cin)), istream_iterator<string>());

   for(int i = 0; i < words.size(); i++)
     cout << words[i] << '\n';
   return 0;
}

A: First of all you don't need dont use getline because it is insecure, use cin instead. Also you do not need the  and use cin instead of getline. Also if getline is used with an array it could pose a serious problem and could be exploited via stack overflow. Sorry I cant help much what you were asking but I just wanted to give you a heads up.

A: Check your for loop.. it runs as long as the second statement is true.. when is it true that i==n? only at the very last byte.. change this to i<=n instead.


text:
Q: Java to CSV file, SuperCSV Dozer: How to avoid looping for a nested object I have the below classes..
SurveyResponse.java
import java.util.List;

public class SurveyResponse {

private int age;

private Boolean consentGiven;

private List<Answer> answers;

public SurveyResponse() {
}

public SurveyResponse(final int age, final Boolean consentGiven, final List<Answer>
answers) {
    this.age = age;
    this.consentGiven = consentGiven;
    this.answers = answers;
}

public int getAge() {
    return age;
}

public List<Answer> getAnswers() {
    return answers;
}

public Boolean getConsentGiven() {
    return consentGiven;
}

public void setAge(final int age) {
    this.age = age;
}

public void setAnswers(final List<Answer> answers) {
    this.answers = answers;
}

public void setConsentGiven(final Boolean consentGiven) {
    this.consentGiven = consentGiven;
}

@Override
public String toString() {
    return String.format("SurveyResponse [age=%s, consentGiven=%s, answers=%s]", age,
        consentGiven, answers);
}

}

Answer.java
public class Answer {
private Integer questionNo;

private String answer;

public Answer() {
}

public Answer(final Integer questionNo, final String answer) {
    this.questionNo = questionNo;
    this.answer = answer;
}

public String getAnswer() {
    return answer;
}

public Integer getQuestionNo() {
    return questionNo;
}

public void setAnswer(final String answer) {
    this.answer = answer;
}

public void setQuestionNo(final Integer questionNo) {
    this.questionNo = questionNo;
}

@Override
public String toString() {
    return String.format("Answer [questionNo=%s, answer=%s]", questionNo, answer);
}

}

and my Main class with the looping which works fine as below -
import java.io.FileWriter;
import java.util.Arrays;
import java.util.List;

import org.supercsv.cellprocessor.FmtBool;
import org.supercsv.cellprocessor.Optional;
import org.supercsv.cellprocessor.Token;
import org.supercsv.cellprocessor.constraint.NotNull;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.dozer.CsvDozerBeanWriter;
import org.supercsv.io.dozer.ICsvDozerBeanWriter;
import org.supercsv.prefs.CsvPreference;

public class Main {

 private static final String[] FIELD_MAPPING = new String[] { "age", // simple field
 mapping
                                                                    // (like
 CsvBeanReader)
    "consentGiven", // as above
    "answers[0].questionNo", // indexed (first element) + deep mapping
    "answers[0].answer", "answers[1].questionNo", // indexed (second element) + deep
mapping
    "answers[1].answer", "answers[2].questionNo", "answers[2].answer" };

/**
 * @param args
 * @throws Exception
 */
public static void main(final String[] args) throws Exception {
    writeWithDozerCsvBeanWriter();

}

private static void writeWithDozerCsvBeanWriter() throws Exception {

    final CellProcessor[] processors = new CellProcessor[] { new Token(0, null), // age
        new FmtBool("Y", "N"), // consent
        new NotNull(), // questionNo 1
        new Optional(), // answer 1
        new NotNull(), // questionNo 2
        new Optional(), // answer 2
        new NotNull(), // questionNo 3
        new Optional() }; // answer 4

    // create the survey responses to write
    final SurveyResponse response1 =
        new SurveyResponse(18, true, Arrays.asList(new Answer(1, "Twelve"), new
Answer(2,
                "Albert Einstein"), new Answer(3, "Big Bang Theory")));
    final SurveyResponse response2 =
        new SurveyResponse(0, true, Arrays.asList(new Answer(1, "Thirteen"), new
Answer(2,
                "Nikola Tesla"), new Answer(3, "Stargate")));
    final SurveyResponse response3 =
        new SurveyResponse(42, false, Arrays.asList(new Answer(1, null), new Answer(2,
                "Carl Sagan"), new Answer(3, "Star Wars")));
    final List<SurveyResponse> surveyResponses =
        Arrays.asList(response1, response2, response3);

    ICsvDozerBeanWriter beanWriter = null;
    try {
        beanWriter =
            new CsvDozerBeanWriter(new
 FileWriter("C:\\Users\\Desktop\\Test.csv"),
                    CsvPreference.STANDARD_PREFERENCE);

        // configure the mapping from the fields to the CSV columns
        beanWriter.configureBeanMapping(SurveyResponse.class, FIELD_MAPPING);

        // write the header
        beanWriter.writeHeader("age", "consentGiven", "questionNo1", "answer1",
            "questionNo2", "answer2", "questionNo3", "answer3");

        // write the beans
        for (final SurveyResponse surveyResponse : surveyResponses) {
            beanWriter.write(surveyResponse, processors);
        }

    } finally {
        if (beanWriter != null) {
            beanWriter.close();
        }
    }
}

}

I want to avoid the looping in the field mapping and processors arrays because..in our app, we have around 100 to 1000 answers. so I wrote the below which is not working. Could someone shed some light as why the below is not working?
Main2.java
import java.io.FileWriter;
import java.util.Arrays;
import java.util.List;

import org.supercsv.cellprocessor.FmtBool;
import org.supercsv.cellprocessor.Optional;
import org.supercsv.cellprocessor.Token;
import org.supercsv.cellprocessor.constraint.NotNull;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.dozer.CsvDozerBeanWriter;
import org.supercsv.io.dozer.ICsvDozerBeanWriter;
import org.supercsv.prefs.CsvPreference;

public class Main2 {

private static final String[] FIELD_MAPPING = new String[] { "age", "consentGiven",
    "answers.questionNo", "answers.answer" };

/**
 * @param args
 * @throws Exception
 */
public static void main(final String[] args) throws Exception {
    writeWithDozerCsvBeanWriter();

}

private static void writeWithDozerCsvBeanWriter() throws Exception {

    final CellProcessor[] processors = new CellProcessor[] { new Token(0, null), // age
        new FmtBool("Y", "N"), // consent
        new NotNull(), // questionNo
        new Optional() // answer
        };

    // create the survey responses to write
    final SurveyResponse response1 =
        new SurveyResponse(18, true, Arrays.asList(new Answer(1, "Twelve"), new
       Answer(2,
                "Albert Einstein"), new Answer(3, "Big Bang Theory")));
    final SurveyResponse response2 =
        new SurveyResponse(0, true, Arrays.asList(new Answer(1, "Thirteen"), new
       Answer(2,
                "Nikola Tesla"), new Answer(3, "Stargate")));
    final SurveyResponse response3 =
        new SurveyResponse(42, false, Arrays.asList(new Answer(1, null), new Answer(2,
                "Carl Sagan"), new Answer(3, "Star Wars")));
    final List<SurveyResponse> surveyResponses =
        Arrays.asList(response1, response2, response3);

    ICsvDozerBeanWriter beanWriter = null;
    try {
        beanWriter =
            new CsvDozerBeanWriter(new
 FileWriter("C:\\Users\\Desktop\\Test.csv"),
                    CsvPreference.STANDARD_PREFERENCE);

        // configure the mapping from the fields to the CSV columns
        beanWriter.configureBeanMapping(SurveyResponse.class, FIELD_MAPPING);

        // write the header
        beanWriter.writeHeader("age", "consentGiven", "questionNo1", "answer1");

        // write the beans
        for (final SurveyResponse surveyResponse : surveyResponses) {
            beanWriter.write(surveyResponse, processors);
        }

    } finally {
        if (beanWriter != null) {
            beanWriter.close();
        }
    }
}

}

Here is the error
6 [main] INFO org.dozer.config.GlobalSettings - Trying to find Dozer configuration
file: dozer.properties

14 [main] WARN org.dozer.config.GlobalSettings - Dozer configuration file not found:
dozer.properties.  Using defaults for all Dozer global properties.
 15 [main] INFO org.dozer.DozerInitializer - Initializing Dozer. Version: 5.4.0, Thread
 Name: main

64 [main] INFO org.dozer.jmx.JMXPlatformImpl - Dozer JMX MBean
[org.dozer.jmx:type=DozerStatisticsController] auto registered with the Platform MBean
Server

65 [main] INFO org.dozer.jmx.JMXPlatformImpl - Dozer JMX MBean
[org.dozer.jmx:type=DozerAdminController] auto registered with the Platform MBean
Server

68 [main] INFO org.dozer.DozerBeanMapper - Initializing a new instance of dozer bean
mapper.

 156 [main] ERROR org.dozer.MappingProcessor - Field mapping error -->

MapId: null
Type: null
Source parent class: SurveyResponse
Source field name: answers.questionNo
Source field type: null
 Source field value: null
Dest parent class: org.supercsv.io.dozer.CsvDozerBeanData
Dest field name: columns
Dest field type: java.util.List
java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.dozer.util.ReflectionUtils.invoke(ReflectionUtils.java:323)
at
  org.dozer.propertydescriptor.GetterSetterPropertyDescriptor.
  getDeepSrcFieldValue(GetterSetterPropertyDescriptor.java:122)
at org.dozer.propertydescriptor.GetterSetterPropertyDescriptor.
 getPropertyValue(GetterSetterPropertyDescriptor.java:75)
at org.dozer.fieldmap.FieldMap.getSrcFieldValue(FieldMap.java:84)
at org.dozer.MappingProcessor.mapField(MappingProcessor.java:275)
at org.dozer.MappingProcessor.map(MappingProcessor.java:248)
at org.dozer.MappingProcessor.map(MappingProcessor.java:197)
at org.dozer.MappingProcessor.map(MappingProcessor.java:187)
at org.dozer.MappingProcessor.map(MappingProcessor.java:133)
at org.dozer.MappingProcessor.map(MappingProcessor.java:128)
at org.dozer.DozerBeanMapper.map(DozerBeanMapper.java:127)
at org.supercsv.io.dozer.CsvDozerBeanWriter.write(CsvDozerBeanWriter.java:132)
at MainAvoidIndexing.writeWithDozerCsvBeanWriter(MainAvoidIndexing.java:68)
at MainAvoidIndexing.main(MainAvoidIndexing.java:29)

     Exception in thread "main" java.lang.IllegalArgumentException: object is not an
     instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
        sun.reflect.DelegatingMethodAccessorImpl.
   invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.dozer.util.ReflectionUtils.invoke(ReflectionUtils.java:323)
at org.dozer.propertydescriptor.GetterSetterPropertyDescriptor.
   getDeepSrcFieldValue(GetterSetterPropertyDescriptor.java:122)
at
  org.dozer.propertydescriptor.GetterSetterPropertyDescriptor.
  getPropertyValue(GetterSetterPr
    opertyDescriptor.java:75)
at org.dozer.fieldmap.FieldMap.getSrcFieldValue(FieldMap.java:84)
at org.dozer.MappingProcessor.mapField(MappingProcessor.java:275)
at org.dozer.MappingProcessor.map(MappingProcessor.java:248)
at org.dozer.MappingProcessor.map(MappingProcessor.java:197)
at org.dozer.MappingProcessor.map(MappingProcessor.java:187)
at org.dozer.MappingProcessor.map(MappingProcessor.java:133)
at org.dozer.MappingProcessor.map(MappingProcessor.java:128)
at org.dozer.DozerBeanMapper.map(DozerBeanMapper.java:127)
at org.supercsv.io.dozer.CsvDozerBeanWriter.write(CsvDozerBeanWriter.java:132)
at MainAvoidIndexing.writeWithDozerCsvBeanWriter(MainAvoidIndexing.java:68)
at MainAvoidIndexing.main(MainAvoidIndexing.java:29)

A: The answers field in SurveyResponse is a List, so you have to use indexed mapping to configure CsvDozerBeanWriter. Indexed mapping is not actually looping - it's just how Dozer knows which element of a List to populate. This is extremely important if you were to ignore a column - it would actually insert a null element for that column.
If you don't use indexed mapping (and just use "answers") then you'd need to configure a cell processor that can take a List<Answer> and convert it to something that can be used as CSV.
Dynamically configuring the field mapping
(Not what you were asking as it turns out, but I'll leave for future reference)
That doesn't mean you have to configure the field mapping with a static String array. You can populate the array dynamically using a simple for-loop. For example,
    String[] fieldMapping = new String[10];
    fieldMapping[0] = "age";
    fieldMapping[1] = "consentGiven";
    int answerStartIndex = 2;
    int answerEndIndex = 8;
    for (int i = answerStartIndex; i <= answerEndIndex; i++){
        fieldMapping[i] = String.format("answers[%s].questionNo",
            i - answerStartIndex);
    }
    fieldMapping[9] = "age";

Which will give you a fieldMapping of:
[age, consentGiven, answers[0].questionNo, answers[1].questionNo,
 answers[2].questionNo, answers[3].questionNo, answers[4].questionNo,
 answers[5].questionNo, answers[6].questionNo, age]


text:
Q: How to chop a complex number? I'm solving some differential equations by iterating and I want to use Chop to get rid of noice smaller than a certain threshold. However, I found that Chop only "chops" the real part, not the imaginary part. My question is, which function can I use in order to approximate both real and imaginary parts that are very close to zero by zero?
For example, if I try to do
A = 10^(-50);
B = I*10^(-50);
Chop[A + B]

The result is just that same number (and actually not even the real number is getting chopped so I'm not sure if I'm understanding this correctly). I would want the result to be zero.

A:
I would want the result to be zero.

Exact numbers do not get Choped, because they are exact
A = 10^(-50);
B = I*10^(-50);
Chop[A + B]

To get chop to work, The numbers need to be real and not exact as you have it. So just add a .
A = 10.^(-50);
B = I*10.^(-50);
Chop[A + B]

Or apply N on it
Chop[N[A + B]]


text:
Q: Why am I getting an error from implementing GestureDetector? I am trying to implement GuestureDetector but I get an error. The "OnGestureListener" and OnDoubleTapListener are both in red and android studio is saying "cannot resolve symbol 'OnGestureListener' . I have tried a few others but it doesn't seem to work. How do I fix this?
public class ScrollingActivity extends AppCompatActivity implements GestureDetector.OnGestureListener,
GestureDetector.OnDoubleTapListener {

A: Make sure you have downloaded right platform versions and APIs in SDK manager, also you have to import correct libraries like:
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.GestureDetector;
import android.view.MotionEvent;

besides, you have to implement following methods:
@Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onDoubleTap(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onDoubleTapEvent(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        this.gd.onTouchEvent(event);
        return super.onTouchEvent(event);
    }


text:
Q: Automatic deserialisation of S3 Events in Lambda I have written a lambda handler that takes a POJO as parameter and tries to print it. When I put an json file in the configured s3 bucket, the event gets triggered, however all the values in the pojo are null. But when I use S3Event as a parameter, I get the expected values (bucket name, key etc).
So my question is - has anyone seen automatic deserialisation working with S3 and java in AWS Lambdas.
Here is my simplified handler
public void handleRequest(ConsolidationJob job, Context context) {
    logger.info("Triggered job: " + job.toString());
}

Here is my pojo
public class ConsolidationJob {

   private List<String> files;

   public List<String> getFiles() {
    return files;
  }

  public void setFiles(List<String> files) {
    this.files = files;
  }

  @Override
public String toString() {
    return "ConsolidationJob{" +
            "files=" + files +
           '}';

And the when I drop the following json
{
"files": [
    "ni-aq-si-ui-i-4c2c11e1.cloud-newsint.co.uk.1454377894220.avro",
    "ni-aq-si-ui-i-4c2c11e1.cloud-newsint.co.uk.1454378378408.avro",
    "ni-aq-uat-ui-i-55c6c7de.cloud-newsint.co.uk.1454376507474.avro"
}

in the logs I see
2017-01-04 12:10:38 <cd42ce01-d276-11e6-bb24-2776804ea5f4> INFO uk.co.avro.FilesConsolidator:40 - Triggered job: ConsolidationJob{files=null}

But when I change my lambda to
public void handleRequest(S3Event job, Context context) {
    logger.info("Triggered s3event: " + job.toJson());
}

It is being invoked  with the right event from which I can get the bucket name and the key to go ahead and pull the file. But that means I have to do the deserialisation manually.

A: Looks like it is not possible mainly because the content in S3 can be any type not just json.
Eventually I used the second approach of using S3Event as a parameter, getting the bucket and key from it and then using Jackson to parse the inputstream to my POJO


text:
Q: I don't have authorized_keys file in my .ssh folder i installed ssh
apt install open ssh-server
then i type
ssh-keygen -t rsa
the i type Cd .ssh
this directory has the public and private keys but don't have the authorized_keys file. i went to the /etc/ssh/sshd_config file and set the path to authorized_keys, then restart ssh, but still the file is not showing.
for this reason it is not enabling other machine to make an ssh connection with my machine using keys.

A: You can create by file from the remote host by executing ssh-copy-id username@your-host.
Alternatively, if you know the public keys, you can manually create the file.