Receive Quiz JSON string from server and display on screen

Question: i've received Quiz JSON string from server this string contain 10 Question, i received and stored response in ArrayList.  now i want that one Question (and its 4 options)should display on screen then there is next button when i press then next question should be display on screen similarly until control reached all 10 question. my problem is that i cannot do functionality of on press next button show the second one(next) Question. please any one help me i am beginner in android thanks.
Here Is JSON String.
   {
  "status": 200,
  "status_message": "Success",
  "response":
   [
    {
      "quizNumber" :  "1",
        "image" : "",
        "question" : "Which car manufacturer was the first to win 100 F1 races?",
        "option1" : "Ferrari",
        "option2" : "Nissan",
        "option3" : "Ford",
        "option4" : "",
        "answer" : "Ferrari."
    },
    {
      "quizNumber" :  "2",
        "image" : "",
        "question" : "In the professional era which woman has won the most titles at Wimbledon [singles, doubles and mixed] ?",
        "option1" : "Venus",
        "option2" : "Hingis",
        "option3" : "Martina Navratilova",
        "option4" : "Waynetta",
        "answer" : "Martina Navratilova"
    },
    {
      "quizNumber" :  "3",
        "image" : "",
        "question" : "How many times have Liverpool been relegated from the top flight of English football?",
        "option1" : "Four",
        "option2" : "Three",
        "option3" : "Two",
        "option4" : "Five",
        "answer" : "Three"
    }]}

And Here Is my MainActivity.java class.
     package com.example.quistest;

  //import goes here

   public class MainActivity extends Activity {

    String serviceUrl;
    ImageView next;
    TextView question,quizno;
    CheckBox ans_1,ans_2,ans_3,ans_4;
    ArrayList<Quiz_List>data;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    data=new ArrayList<Quiz_List>();

    next=(ImageView) findViewById(R.id.imageView_nextID);
    quizno=(TextView) findViewById(R.id.question_noID);
    question=(TextView) findViewById(R.id.txt_questionID);

    ans_1=(CheckBox) findViewById(R.id.chk_ans1ID);
    ans_2=(CheckBox) findViewById(R.id.chk_ans2ID);
    ans_3=(CheckBox) findViewById(R.id.chk_ans3ID);
    ans_4=(CheckBox) findViewById(R.id.chk_ans4ID);

    next.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "Next...", Toast.LENGTH_SHORT).show();
        }
    });

    if (isNetworkAvailable()) {
        execute();

}

   else {
    // Error message here if network is unavailable.
    Toast.makeText(this, "Network is unavailable!",   Toast.LENGTH_LONG).show();
}

}

private boolean isNetworkAvailable() {
    ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();

    boolean isAvailable = false;
    if (networkInfo != null && networkInfo.isConnected()) {
        isAvailable = true;
    }
    return isAvailable;
}

private void execute() {

    serviceUrl ="http://mobile.betfan.com/api/?action=quiz&key=MEu07MgiuWgXwJOo7Oe1aHL0yM8VvP&sporttype=all";

    class LoginAsync extends AsyncTask<String, Void, String>{

        private Dialog loadingDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loadingDialog = ProgressDialog.show(MainActivity.this, "Please  while wait", "Loading...");
        }

        @Override
        protected String doInBackground(String... params) {

            JSONObject jsonObject = new JSONObject();

            String dataString = jsonObject.toString();

            InputStream is = null;
            List<NameValuePair> nameValuePairs = new
          ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("data", dataString));

            String result = null;

            try{

                HttpClient httpClient = new DefaultHttpClient();
                HttpGet httpRequest = new HttpGet();

                URI apiurl = new URI(serviceUrl);

                httpRequest.setURI(apiurl);

                HttpResponse response = httpClient.execute(httpRequest);

                HttpEntity entity = response.getEntity();

                is = entity.getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();

                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                result = sb.toString();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return result;
        }

        protected void onPostExecute(String result){
            String s = result.trim();

            loadingDialog.dismiss();

                JSONObject respObject;
                try {
                    respObject = new JSONObject(s);
                    String active = respObject.getString("status_message");

                    if(active.equalsIgnoreCase("success")){
                         JSONArray array = respObject.getJSONArray("response");
                            for (int i =0; i<array.length();i++){

                         JSONObject jsonObject = array.getJSONObject(i);
                         String quizNumber= jsonObject.getString("quizNumber");
                         String question= jsonObject.getString("question");
                         String option1 = jsonObject.getString("option1");
                         String option2 = jsonObject.getString("option2");
                         String option3 = jsonObject.getString("option3");
                         String option4 = jsonObject.getString("option4");

                         data.add(new Quiz_List(quizNumber,question,option1,option2,option3,option4));

                         quizno.setText("Question numer:"+quizNumber);
                        MainActivity.this.question.setText(question);
                        ans_1.setText(option1);
                        ans_2.setText(option2);
                        ans_3.setText(option3);
                        ans_4.setText(option4);

                        }

                    }else {
                        Toast.makeText(MainActivity.this, "Quiz received Fail", Toast.LENGTH_LONG).show();

                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

        }

    }

    LoginAsync la = new LoginAsync();
    la.execute();

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
  }
 }

And Here is my AarrayList Quiz_List.java class.
     package com.example.quistest;

   public class Quiz_List {
   private String quiz_no;
   private String question;
   private String answer_1;
   private String answer_2;
   private String answer_3;
   private String answer_4;

  public String getQuiz_no() {
    return quiz_no;
}
public void setQuiz_no(String quiz_no) {
    this.quiz_no = quiz_no;
}

public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnswer_1() {
return answer_1;
}
public void setAnswer_1(String answer_1) {
this.answer_1 = answer_1;
}
public String getAnswer_2() {
return answer_2;
}
public void setAnswer_2(String answer_2) {
this.answer_2 = answer_2;
}
public String getAnswer_3() {
return answer_3;
}
public void setAnswer_3(String answer_3) {
this.answer_3 = answer_3;
}
public String getAnswer_4() {
return answer_4;
}
public void setAnswer_4(String answer_4) {
this.answer_4 = answer_4;
}
public Quiz_List(String quiz_no, String question, String answer_1,
    String answer_2, String answer_3, String answer_4) {
super();
this.quiz_no = quiz_no;
this.question = question;
this.answer_1 = answer_1;
this.answer_2 = answer_2;
this.answer_3 = answer_3;
this.answer_4 = answer_4;
 }

}

Please anyone help  i want when i want press next then it should display second one question(its 4 options) should display on screen.
And In current situation it displays last question(its 4 options) only.
Comment: Did you try intent by putting the value in Bundle ?
Comment: No i don't know that how to implement. i am beginner please write me some code. @Zahidul Islam
Answer: I write an example as per your requriment
1-we have a json array
  {
  "status": 200,
  "status_message": "Success",
  "response":
   [
    {
      "quizNumber" :  "1",
        "image" : "",
        "question" : "Which car manufacturer was the first to win 100 F1 races?",
        "option1" : "Ferrari",
        "option2" : "Nissan",
        "option3" : "Ford",
        "option4" : "",
        "answer" : "Ferrari."
    },
    {
      "quizNumber" :  "2",
        "image" : "",
        "question" : "In the professional era which woman has won the most titles at Wimbledon [singles, doubles and mixed] ?",
        "option1" : "Venus",
        "option2" : "Hingis",
        "option3" : "Martina Navratilova",
        "option4" : "Waynetta",
        "answer" : "Martina Navratilova"
    },
    {
      "quizNumber" :  "3",
        "image" : "",
        "question" : "How many times have Liverpool been relegated from the top flight of English football?",
        "option1" : "Four",
        "option2" : "Three",
        "option3" : "Two",
        "option4" : "Five",
        "answer" : "Three"
    }]}

2-Make a pojo class
class Mypojo {
  String op1,op2,op3,op4,ans;
  Mypojo(String s1,String s2,String s3,String s4,String ss){
        op1 = s1;
       .......
     ans = ss;

}
 //add getter / setter method here
}

3- Now in activity take an array list
  int i = 0;
 ArrayList<Mypojo> mypojo = new AarrayList();

where you parse json
make pojo class object like
Mypojo pojo = new Mypojo(parameters) and pass all parameters
then mypojo.add(pojo);
In this way all json data will be added in pojo type array list.

4-Now in Next button code will be
int arraysize = mypojo.size();

if(i<arraysize){

  i++;
 get all values from pojo arraylist by using i as a index position like
 String op1 = mypojo.get(i).getOp1();
and change your UI.
}

This is for example if you will do all steps correctly your problem will be solved.

Comment: I do all Steps, step wise correctly as You have told me , Now how to change ui? "in last line you have told me". #Dharmendra Pratap
Answer: Initially set in MainActivity
int count=0;

Add 1 to count and send count to MainActivity.class when next button is clicked.
Intent i=new Intent(MainActivity.this,MainActivity.class);
i.putStringExtra("count",count);
startActivity(i);

and according to received count in post Execute
 JSONObject jsonObject = array.getJSONObject(count);
                         String quizNumber= jsonObject.getString("quizNumber");
                         String question= jsonObject.getString("question");
                         String option1 = jsonObject.getString("option1");
                         String option2 = jsonObject.getString("option2");
                         String option3 = jsonObject.getString("option3");
                         String option4 = jsonObject.getString("option4");

Every time next button is clicked count is increased by one
Paste the below in MainActivity
 package com.example.quistest;

  //import goes here

   public class MainActivity extends Activity {

    String serviceUrl;
    ImageView next;
    TextView question,quizno;
    CheckBox ans_1,ans_2,ans_3,ans_4;
    ArrayList<Quiz_List>data;

    String count=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    data=new ArrayList<Quiz_List>();

    next=(ImageView) findViewById(R.id.imageView_nextID);
    quizno=(TextView) findViewById(R.id.question_noID);
    question=(TextView) findViewById(R.id.txt_questionID);

    ans_1=(CheckBox) findViewById(R.id.chk_ans1ID);
    ans_2=(CheckBox) findViewById(R.id.chk_ans2ID);
    ans_3=(CheckBox) findViewById(R.id.chk_ans3ID);
    ans_4=(CheckBox) findViewById(R.id.chk_ans4ID);

    Intent i=getIntent();

    count=i.getStringExtra("count");

    next.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            int new_count=Integer.parseInt(count)+1;

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

            intent.putExtra("count",String.valueOf(new_count));

            Toast.makeText(getApplicationContext(), "Next...", Toast.LENGTH_SHORT).show();
        }
    });

    if (isNetworkAvailable()) {
        execute();

}

   else {
    // Error message here if network is unavailable.
    Toast.makeText(this, "Network is unavailable!",   Toast.LENGTH_LONG).show();
}

}

private boolean isNetworkAvailable() {
    ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();

    boolean isAvailable = false;
    if (networkInfo != null && networkInfo.isConnected()) {
        isAvailable = true;
    }
    return isAvailable;
}

private void execute() {

    serviceUrl ="http://mobile.betfan.com/api/?action=quiz&key=MEu07MgiuWgXwJOo7Oe1aHL0yM8VvP&sporttype=all";

    class LoginAsync extends AsyncTask<String, Void, String>{

        private Dialog loadingDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loadingDialog = ProgressDialog.show(MainActivity.this, "Please  while wait", "Loading...");
        }

        @Override
        protected String doInBackground(String... params) {

            JSONObject jsonObject = new JSONObject();

            String dataString = jsonObject.toString();

            InputStream is = null;
            List<NameValuePair> nameValuePairs = new
          ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("data", dataString));

            String result = null;

            try{

                HttpClient httpClient = new DefaultHttpClient();
                HttpGet httpRequest = new HttpGet();

                URI apiurl = new URI(serviceUrl);

                httpRequest.setURI(apiurl);

                HttpResponse response = httpClient.execute(httpRequest);

                HttpEntity entity = response.getEntity();

                is = entity.getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();

                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                result = sb.toString();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return result;
        }

        protected void onPostExecute(String result){
            String s = result.trim();

            loadingDialog.dismiss();

                JSONObject respObject;
                try {
                    respObject = new JSONObject(s);
                    String active = respObject.getString("status_message");

                    if(active.equalsIgnoreCase("success")){
                         JSONArray array = respObject.getJSONArray("response");

                         JSONObject jsonObject = array.getJSONObject(Integer.parseInt(count));
                         String quizNumber= jsonObject.getString("quizNumber");
                         String question= jsonObject.getString("question");
                         String option1 = jsonObject.getString("option1");
                         String option2 = jsonObject.getString("option2");
                         String option3 = jsonObject.getString("option3");
                         String option4 = jsonObject.getString("option4");

                         data.add(new Quiz_List(quizNumber,question,option1,option2,option3,option4));

                         quizno.setText("Question numer:"+quizNumber);
                        MainActivity.this.question.setText(question);
                        ans_1.setText(option1);
                        ans_2.setText(option2);
                        ans_3.setText(option3);
                        ans_4.setText(option4);

                    }else {
                        Toast.makeText(MainActivity.this, "Quiz received Fail", Toast.LENGTH_LONG).show();

                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

        }

    }

    LoginAsync la = new LoginAsync();
    la.execute();

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
  }
 }

Answer: When you need to pass data from one activity to another activity you need to use intent.putExtra() method to send data.
For send data from your main activity ->
Intent intent = new Intent(MainActivity.this,NEXT_ACTIVITY.class); // Change NEXT_ACTIVITY to your option / answer activity.
intent.putExtra("option_1",option1);
intent.putExtra("option_2",option2);
intent.putExtra("option_3",option3);
intent.putExtra("option_4",option4);
intent.putExtra("answer",answer);
startActivity(intent);

To receive data from your next activity ->
Bundle bundle = getIntent().getExtras();
String option1 = bundle.getString("option_1");
String option2 = bundle.getString("option_2");
String option3 = bundle.getString("option_3");
String option4 = bundle.getString("option_4");
String answer = bundle.getString("answer");

Now you can use these data wherever you want in this activity.
Answer: If you parse json and add data in array list I suggest you make a pojo class and take all values in pojo type array list. When you press next button find array list size and array list index start from 0 to array list size so take a integer (int i = 0 ) and its initial value must be 0(zero).Now use if (i<array.size()) condition and inside it increase integer value (i++) . By this way you can solve your problem.Do not use Intent , all things do in same activity.
Comment: Please write me some code if possible i am beginner thanks a lot :) @Dharmendra Pratap
Comment: please anyone help me how to count my correct question choose and incorrect?


Nested Parallel.For() loops speed and performance

Question: I have a nested for loop.
I have replaced the first For with a Parallel.For() and the speed of calculation increased.
My question is about replacing the second for (inside one) with a Parallel.For(). Will it increase the speed? or there is no difference? or it will be slower?
Edit:
Since the cores are not unlimited (usually there is 2 to 8 cores), the inside loop is running parallel. So, if I change the inside for with a Parallel.For(), again it runs parallel. But i'm not sure how it changes the performance and speed.
Comment: http://guyellisrocks.com/coding/nested-parallel-foreach/ ...What can we tell you that a simple benchmark test wouldn't?
Comment: Depends on the number of cores, but I'd suspect you won't see any improvement. Try it out, though.
Answer: From "Too fine-grained, too coarse-grained" subsection, "Anti-patterns" section in "Patterns of parallel programming" book by .NET parallel computing team:

The answer is that the best balance is found through performance
  testing. If the overheads of parallelization are  minimal as compared
  to the work being done, parallelize as much as possible: in this case,
  that would mean  parallelizing both loops. If the overheads of
  parallelizing the inner loop would degrade performance on most
  systems, think twice before doing so, as it'll likely be best only to
  parallelize the outer loop.

Take a look at that subsection, it is self-contained with detailed examples from parallel ray tracing application. And its suggestion of flattening the loops to have better degree of parallelism may be helpful for you too.
Answer: It again depends on many scenarios,

Number of parallel threads your cpu can run.
Number of iterations.

If your CPU is a single-core processor, you will not get any benefits.
If the number of iterations is greater, you will get some improvements.
If there are just a few iterations, it will be slow as it involves extra overload.
Answer: It depends a lot on the data and functions you use inside the for and the machine. I have been messing lately with the parallel.for and parallel.foreach and found out that they made my apps even slower... (on a 4 core machine, probably if you have a 24 core server is another story)
I think that managing the threads means too much overhead...
Even MS on their documentation (here is a very long pdf on msdn about it http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=19222) admits it doesnt make the apps run faster. You have to try every time, and if it works, great, and if not bad luck.
You should try with the external for and the internal, but at least on the apps i tried none of them made the app faster. External or internal didnt matter much i was just getting the same execution times or even worse.
Maybe if you use Concurrent collections too, you get better performance. But again, without trying there is no way to tell.
EDIT:
I just found a nice link on MSDN that proved to be very useful (in my case) to improve Parallel.foreach performance
http://msdn.microsoft.com/en-us/library/dd560853.aspx


floats within a div

Question: Hi i'm trying to make a div within the front page of my site that contains a floating img and some floating text h3, p and a . I then want to loop the div below with different text/pic . When i do this once it works fine but the container div hasn't stretched to fit the content . So when I add another below it overlaps .
code:

BLOG

Playing At The Phenoix

So we arrived down at the phenoix about 10 past ten .Rommy was all ready out of it and wasn't sure if he could do...read more

Playing At The Phenoix

So we arrived down at the phenoix about 10 past ten .Rommy was all ready out of it and wasn't sure if he could do...read more

#blog {
float:left;
width:400px;
border-top:#0FF solid 6px;

}

#postcont {
padding:10px;
border-top:1px #FFF solid;
margin-top:10px;
}

#blog h1 {
    font-size:20px;
    color:#FFF;
    padding:10px;
    padding-left:0px;
    letter-spacing:2px;
}
#blog p {
    font-size:15px;
    color:#FFF;
    float:right;
    clear:right;
    width:300px;
    margin-right:30px;
    letter-spacing:2px;
    margin-top:5px;
}
#blog a {
    font-size:15px;
    color:#FFF;
    float:right;
    clear:right;
    width:300px;
    margin-right:0px;
    letter-spacing:2px;
    margin-top:5px;
    font-style:italic;
    text-decoration:underline;
}
#blog h3 {
    font-size:15px;
    color:#FFF;
    float:right;
    clear:right;
    width:300px;
    margin-right:30px;
    letter-spacing:2px;
    margin-top:5px;
    font-weight:bold;
}

#blog img {
    float:left;
    clear:left;
}

Comment: show the code with your container div in the html and css
Answer: Block-level elements to not expand to the height of floated elements unless you tell them to. You should add a clearing-element after the last floated element to fix this problem. Instead of:

Use:

For an extended explanation of this solution, as well as an alternative solution, please see: http://www.quirksmode.org/css/clearing.html

floats within a div


$|p\min(x,q)-y\min(x,w)| \leq x |p-y|?$

Question: Let $x,y,w,p,q \geq 0$ such that $p,y \leq 1.$
Is it true that $$|p\min(x,q)-y\min(x,w)| \leq x |p-y|?$$
Tried to come with a proof but it didn't work, it seems the statement is false.
Any idea-example to disprove it?
Answer: Since all variables are nonnegative (in case $y\ne 0$, $p=0$, exchange $p,y$ and $w,q$  in the following treatment; the case  $p=y=0$ is trivial) we can rewrite
$$
|p\min(x,q)-y\min(x,w)| \leq x |p-y|
$$
as
$$
|\frac{1-\frac{y/p}{\min(x,q) / \min(x,w)}}{1 -y/p}| \leq \frac{x}{\min(x,q)}
$$
Denote $z = y/p$. As $0 \le y,p \le 1$ we have that $0\le z< \infty$.
Further, denote $a = \min(x,q) / \min(x,w)$. Then the question translates to
$$
|\frac{1-\frac{z}{a}}{1 -z}| \leq \frac{x}{\min(x,q)}
$$

First, consider $ a\ne 1$. This happens when $w > x \ge q$ or $q > x \ge w$. Then the LHS takes values from $0$ (for $z=a$) to $\to \infty$ (for $z=1$) so the LHS can, for all $z$, never be smaller than anything, which fails the assertion.

Now, consider $ a =  1$. Then we have to show $1 \leq \frac{x}{\min(x,q)} $. This falls into two subcases.
2.1. $a = \min(x,q) / \min(x,w) =1$ is generated for $x >  w=q$. Then we have the condition $1 \leq \frac{x}{\min(x,q)} = \frac{x}{q} > 1$ which holds, with a generic "$<$" in the assertion.
2.2. $a = \min(x,q) / \min(x,w) =1$ is generated for $x \le q$, $x \le  w$. Then we have the condition $1 \leq \frac{x}{\min(x,q)} = \frac{x}{x}= 1$ which holds true, so in this  case  the assertion holds with equality.
Answer: For simply a counterexample, you could use $p=y=1$, $x=w=1$, $q=0$.
If the inequality was true, this would give $1\le0$.

$|p\min(x,q)-y\min(x,w)| \leq x |p-y|?$


Reached End of file while parsing

Question: I keep getting this message when I try to compile:
Reached End of file while parsing
Anyone know why? The only thing that I have figured out is that it has something to do with my curly braces. I have tried to move braces around, add them, and delete them but I can not figure this out. The error occurs in the last line of code.
import java.awt.event.ActionEvent; //Next group of lines import various Java classes
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.GridLayout;
import java.text.*;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class ReadTextFile extends JFrame
{
public static void main(String[] args) throws IOException {
    //Creates Window
    final JFrame frame = new JFrame();
    frame.setSize(450, 300); //Sets size of the window
    frame.setTitle("Read a Text File"); //Adds title to the GUI
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create labels and fields
    JLabel Firstlbl = new JLabel("First Text Line");
    final JTextField FirstField = new JTextField(20);
    FirstField.setText("1st");
    JLabel Secondlbl = new JLabel("Second Text Line");
    final JTextField SecondField = new JTextField(20);
    SecondField.setText("2nd");
    JLabel Thirdlbl = new JLabel("Third Text Line");
    final JTextField ThirdField = new JTextField(20);
    ThirdField.setText("3rd");
    JLabel ButtonLabel = new JLabel("Click button to read text from file.");
    final JButton button = new JButton("Click Here");
    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(4,2));
    panel.add(ButtonLabel);
    panel.add(button);
    panel.add(Firstlbl);
    panel.add(FirstField);
    panel.add(Secondlbl);
    panel.add(SecondField);
    panel.add(Thirdlbl);
    panel.add(ThirdField);
    frame.add(panel);
    class CalculateListener implements ActionListener {

        private boolean readFile(String fileName)
{
    boolean flag = true;

    try{

        //initialize the file object
        BufferedReader reader=new BufferedReader(new FileReader(fileName));
        String line;
        int counter = 0;
        //reading the lines
        while((line = reader.readLine()) != null)
        {
            counter++;
        }
        reader.close();

        //if file has less then 6 line
        if(counter<6)
        {
            //return the message
            JOptionPane.showMessageDialog(this, "Error: This must have minimum 6 lines\nEnter another file name and try again.", "FILE LINES ERROR", JOptionPane.ERROR_MESSAGE);
            flag = false;
        }

        if(flag){

            //initialize the array wtih line counter
            lines = new String [counter];
            reader=new BufferedReader(new FileReader(fileName));
            //reading the lines
            counter =0;
            while((line = reader.readLine()) != null)
            {
                //set the array elements with the lines of the file
                lines[counter++] = line;
            }
            reader.close();

        }

    }
    catch(IOException ioe) //exception if any
    {
        JOptionPane.showMessageDialog(this, "Error"+ioe.getMessage(), "FILE READING ERROR", JOptionPane.ERROR_MESSAGE);
    }
    catch(Exception e) //exception if any
    {
        JOptionPane.showMessageDialog(this, "Error"+e.getMessage(), "GENERAL ERROR", JOptionPane.ERROR_MESSAGE);
    }

    return flag;

}

//method to handle action of button
public void actionPerformed (ActionEvent ae)
{
    if(ae.getSource()== displayButton)
    {
        resultTextArea.setText("");
        String fileName = "input.txt";

        //call the function readFile() with file name
        if(readFile(fileName))
        {
            for(int i=0; i< lines.length; i++)
            {
                if(i%2==0)
                {
                    //display the array elements to text area
                    resultTextArea.append(lines[i]+"\n");

                }
            }

        }

    }
}
}

}
Answer: Yes, you don't have enough closing braces.
One major point of confusion is that all of your code is in a single method (main) which in turn contains a method-local class (CalculateListener) which is 80 lines long.
Did you mean that to be a method-local class? Is there any reason why you want it to be a method-local class Did you just actually forget to "close" your main method? You don't even seem to use CalculateListener anyway, or do anything with the JFrame that main creates.
If you ask your IDE to indent your code for you, it should make it very clear when you have problems like this. Additionally, making your methods shorter and trying to reduce indentation can help. For example, in your actionPerformed method, the whole body of the method is within a single if block. If you just invert the logic of that if, you can save a level of nesting. You can then do the same with the next if block, too:
public void actionPerformed (ActionEvent ae)
{
    if (ae.getSource() != displayButton)
    {
        return;
    }
    resultTextArea.setText("");
    if (!readFile("input.txt"))
    {
        return;
    }
    for (int i=0; i < lines.length; i++)
    {
        if (i % 2 == 0)
        {
            // display the array elements to text area
            resultTextArea.append(lines[i]+"\n");
        }
    }
}

Answer: The problem seems to be with curly braces:

Add 2 ending curly braces } after frame.add(panel); to close your main() method and class
Remove } from last line

Reached End of file while parsing


Display custom output if field doesn't have value in hook_field_formatter_view

Question: Display custom output of field in hook_field_formatter_view() if field is empty.
function hook_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  //My Snippet to display custom output
  // Here $items variable is empty.
  $element = array();
  switch ($instance ['widget'] ['type']) {
  case 'my_widget' :
    if (!isset($items[0])) {
      $output = generate_custom_output();
      $element [0] = array ('#markup' => $output );
    }
    break;
  }
  return $element;
}

my custom field is empty, no $item is available. Now I want to return custom output. But above code doesn't work.
Please suggest any solution.
Answer: I am able to do this as below in hook_field_formatter_view().
switch ($instance ['widget'] ['type']) {
  case 'my_widget' :
    if (empty ( $items )) {
      $output = generate_custom_output();
      $element[]['#markup'] = $output;
      $element ['#items'][] = array('value' => $output);
      $items[] = array('value' => $output);
    }
  break;
}

If anyone have better solution please provide.


Not being able to edit java class in JAR

Question: Using Eclipse I'm trying to edit an old java applet all I have is a .jar, but I can see the files not being able to edit.... the source code is incomplete, so I wanted to edit it and fix it... anyone knows what can I do?
P.S. I just want to modify and fix the program in that jar.
Comment: Possible duplicate of [Modifying a file inside a jar](http://stackoverflow.com/questions/1224817/modifying-a-file-inside-a-jar)
Comment: @malka I think OP is asking how to modify the program contained in the jar, not necessarily how to change the contents of the jar.
Answer: Well first of all, applets are considered obsolete. (In case you didn't know). The files you are trying to see/edit are inside the .jar. So, for me, the easiest way to access the content of a .jar is just changing the extension from .jar to .zip, after that you can access as it was a regular folder and modify whatever you want there. After done, just change the extension to .jar ... Since .jar is like a "package", modifying code while still inside the .jar is not possible/recommended.
Edit: After being able to see the files, you might need a decompiler (as it was mentioned by Jason Braucht in his comment). Check this out:
http://www.javadecompilers.com/
it is an online tool and lets you decompile .class files ...
Comment: yes, now I can access the content and see what I need to modify, thanks
Comment: @tu_1329 I just added a link in my answer. I'm pretty sure you'll find it very useful
Answer: Typically a jar will only include compiled (binary) java classes.  In order to modify the program, you'll need to obtain the source code, or use a Java decompiler to extract the source from the binaries in the jar.
Comment: thanks for the info, I think I'll need to use this decompiler as well


Joomla Installation stuck on white blank page

Question: I have put Joomla_3.8.3 folder under htdocs and run on browser.
http://localhost/Joomla/installation/index.php
It shows white blank page.
I have added this:
extension=php_pdo.dll
extension=php_pdo_mysql.dll

on PHP.ini but it doesn't work.
Could you please help me how to solve it? Thank you.
Comment: Make sure error reporting is on and see if you get any errors.
Comment: what do you get when you go to the url [http://localhost/Joomla](http://localhost/Joomla) ?
Answer: Whenever you ask any Joomla Question you should mention the Joomla version you are using. Anyways first you need to get the errors and then only you can know how to rectify it. In Joomla main folder you will find a file named configuration.php. You need to change the file permission(775 or 777) in order to edit it.
next you need to change these param values to the below given values:
public $debug = '1';
public $error_reporting = 'maximum';

You need to then refresh the same page after saving this file. You cannot save until you change the file permissions. You will get some errors. You can then troubleshoot it.
Note: To change the file permission on Windows you need to right click on the file and then chose Properties. Under Attributes you will find read only checked. Just uncheck Read Only and press Ok. This will make it writable.
Comment: I couldn't find $debug = "1"; I found only this $registry->set('debug', 0);
  $registry->set('debug_lang', 0);  Thank you for help.
Comment: Change this to $registry->set('debug', 1);


Triggering an action after user resets password?

Question: I was hoping there was hook_user_pass_reset, but I seem to be out of luck. Some background:

I made a new field on users called "email_confirmed"
This field gets set = 1 when the user has confirmed their email address
I don't use the "blocked" value, or the normal Drupal way, because I want users to still log in and do stuff. I only want to limit certain actions, which will only become possible after email_confirmed = 1

So all I want to do is update this field = 1, the moment the user uses the confirmation link to change their password. So it will not be good enough to this when the user changes his password. It needs to happen the moment the user has executed the confirmation link?
Comment: It is similar to what drupal.org does, except they use roles, and the _email unverified_ role is assigned before the email is confirmed. It seems a custom module is used for that purpose.
Answer: /**
 * Implements hook_ENTITY_TYPE_update().
 */
function MODULE_user_update(Drupal\user\UserInterface $user) {
  if (!empty($user->original)) { // check previous value exists
    if($user->original->pass->value != $user->pass->value) { // check if pass changed
      $user->field_email_confirmed->value = 1; // set new value
    }
  }
}

Answer: The Logintobbogan module for Drupal 7 does something similar. It implements hook_form_alter() for the user password reset form, which is also used for processing the one-time login link sent in the confirmation email, to set $account->logintoboggan_email_validated to TRUE.
In Drupal 8, it could be still possible to implement something similar. The difference is that the user.reset.login route (whose path is /user/reset/{uid}/{timestamp}/{hash}/login) is handled by a controller. Instead of hook_form_alter(), a module should alter the user.reset.login route to use a different controller, which sets the desired account field.
Alternatively, the email sent for the email confirmation could contain a link to a different route that sets the account field.


How do I modify this code so that it replaces the last value and inserts a new value?

Question: With this code I am writing to file, adding quantity to the same line as its corresponding crop.
These are the content of the text file:
Tomato 2 4 1
Lettuce 3 8 7

At the moment my code simply appends quantity on to the end of the line. What I want to do is insert quantity after crop and remove the final integer from the line.
So if I were to input 'Lettuce' for crop and '9' for quantity then the file would be modified so that it would be like this:
Tomato 2 4 1
Lettuce 9 3 8

However I'm not really sure how to do this.
My code
crop = input('Which crop? ')
quantity = input('How much? ')
file = ('cropdata.txt')

if crop in open(file).read():
 with open(file, 'r') as file_read:
       lines = []

       for line in file_read:
           if crop in line:
               line = str(line.rstrip("\n") + quantity + " "  + "\n")
           lines.append(line)

 with open(file, 'w') as file_rewrite:
    file_rewrite.writelines(lines)
else:
 print('Crop not found.')

Answer: line_parts = line.split (" ")  #possibly after stripping off final "\n"

Now you have an array line_parts consisting of Lettuce, 3, 8, and 7.
You can shift the numeric entries one step to the right until you have Lettuce, 3, 3, 8; then replace line_parts[0] with your new quantity to get Lettuce, 9, 8, 7.
Let line = line_parts[0]+line_parts[1]+line_parts[2]+line_parts[3], append that to lines, and continue as before.
Answer: Don't save data like this. Use structured files to store data:

XML
JSON

If you will use it, this work won't difficult for you.


Open an iframe containing XML

Question: <code>var iframe = $('#auditframe').get(0).contentWindow;

iframe.document.open("text/xml", "replace");
iframe.document.write(xml);
</code>
This works. My iframe gets populated with a valid xml string. But is there any way to open the iframe in a new window? I want the user to see  the XML document that has been added to the frame. Is there any way to solve this?
Thanks
Answer: Similar technique, except you open a blank window, create a new document in the window, and then write the content you want. See this fiddle for a working example: http://jsfiddle.net/2v3Gr/
Comment: If i check the source on the popup, its valid xml, but IE still doesnt show it as an XML, just a text string. Is there any thing to to about that?
Comment: IE apparently ignores the MIME type specified when you open the document and just assumes it's HTML. Not sure what to do about that except to open the window to a URL that actually sends down XML.

Open an iframe containing XML


How to search as subsequence

Question: I would like to search through a database table and return any string that is a subsequence of another string.
When I want to search for a string that is equal to another string, I use the following:
SELECT kmer from data where kmer="ATCG"

Assuming kmer = "ATCG", a match will be made. But what if I wanted to search as a subsequence? Something like the following:
SELECT kmer from data where kmer in "XXATCGXX"

But obviously, this syntax is incorrect. These strings are static and I am not able to use wildcards with the LIKE syntax.
To be clear, any of the following values should return a match:
X
XX
XAT
XATC
ATC
TC
GX
CGXX
A
T
C
G

Just to name a few examples. These are all subsequences of "XXATCGXX" so can I use wildcats to cover all of these possibilities?
Comment: So you are saying `kmer` should be a substring of your parameter? Switch the order: `WHERE "XXATCGXX" LIKE "%" || kmer || "%"`
Comment: Why can't you use `LIKE` ?  Try `WHERE kmer LIKE '%ATCG%'`
Comment: What confuses me about this subject is how am I supposed to know in advance where to put the wild cards? Your example would work in this one case, but what if my string were "XXAT"? In that case a match would not be made even though it is a  subsequence of "XXATCGXX".  Or am I misunderstanding the concept of the wild card?
Comment: The `%` wildcard matches zero or more characters, so I believe the answer is yes.
Comment: Unfortunately I still do not quite understand. Would the absence of a "CG" cause a non match? Please see my edits as I provide more clarification.
Comment: Yes this is exactly what I am referring to. I'm not near a computer now so I can't test it, but the logic seems right.
Comment: Tried this out and it worked. Thank you for your help. I tried doing this but was not familiar with the "||" syntax.
Answer: LIKE is typically used with a column value on the left, but as mentioned by Colonel Thirty Two, you can just reverse the comparison:
SELECT kmer FROM data WHERE 'XXATCGXX' LIKE '%' || kmer || '%';

How to search as subsequence


RSA keys - virtual hosts

Question: Setting up passwordless ssh for multiple users has proved to be kind of a pain.
Currently I'm the single user of this Ubuntu 10.04 LTS VPS. I was able to establish a single RSA passkey under my home/user/.ssh/authorized_keys location. Fine. PuTTy works as expected, and Filezilla (sftp) links up as required.
I've been working on a single site that this user owns, and thats not been a problem. Now, I want to set up some other sites, and I've chosen Webmin with the VirtualMin plugin to make this work.
I made another user (or, rather, virtualmin did), but I've been unable to get FileZilla to link up to this new user. Could anyone with experience here explain what the setup is supposed to look like?
For example, can I use a single RSA key pair for all accounts (if, for example, I give ownership of files to the original user?). Or is it standard practice to create a separate key pair for each user and establish a separate PuTTY/filezilla login for each?
The error "Sever rejected the provided key" sucks after the fifth hour. I'm about to set up an ftp server and call it a day. What should I do to get multiple users to be able to connect to the site using RSA keys?
Answer:
setting up passwordless ssh for multiple users has proved to be kind of a pain.

Only the first time - hopefully through the process you'll learn more about how all the pieces fit together, making it much easier in the future.

can I use a single rsa key pair for all accounts

If you are going to be the only one accessing the accounts, then yes, this is fine.
However, if others will need access to the account(s), they will need their own keypair.

Or is it standard practice to create a separate key pair for each user, and establish a separate putty/filezilla login for each?

Yes! :)
Each person needs to create their own keypair, then provide you with only the public key. The private keys are well, private, and they need to stay with the user that created them. As mentioned above, if you're the only person accessing the accounts, then you can use a single keypair.
Copy each user's public key into their ~/.ssh/authorized_keys file, and then ensure that the ownership and permissions of the .ssh directory and authorized_keys file is correct:
$ chown -R <username> /home/<username>/.ssh
$ chmod 700 /home/<username>/.ssh
$ chmod 600 /home/<username>/.ssh/authorized_keys

Keep in mind that each public key can should be on a single line in the authorized_keys file.
If the above doesn't work, you'll need to do some more digging to see what is going on. If this is the case, edit your answer and post any errors that are showing up in your /var/log/auth.log file upon unsuccessful connection attempts.

I'm about to set up an ftp server and call it a day.

Nooooooo! Remember, FTP Must Die!
Comment: There's nothing wrong with using the same RSA key pair for every account if the same human being has access to them. And there's nothing wrong with using multiple RSA key pairs for an account if more than one person has access to them. RSA key pairs should be owned by agents, such as users. And an RSA key pair allowing access to an account gives that agent access to that account.
Comment: @DavidSchwartz - Yes, those are all true.
Comment: ...edited accordingly.
Comment: thanks for the reply! i may not have time to work on this until tomorrow, but i need to get this worked out (may have a couple more questions). at any rate - i am the only user of this server - it sounds like i should be able make my user keypair work for all sites. probably just need to give ownership of all those dirs to my main user. also "single line" may have been messing me up too. ive been copying and pasting keys into athorized_keys, and i think my editor has been word wrapping... again - thanks for the help!
Comment: ftp must die... lol. awesome site. funny - you spend ten years making web pages via ftp, never gave it a second thought...
Comment: @ErikA - finally found some time to deal with this. After managing to lock myself well out of the server, I duplicated a putty generated key pair to each of my /home//.ssh/authorized_keys and got both putty and filezilla working properly. I think most of my problem was ownership rules, but also the key simply being on a single line... At any rate - thanks for the help.
Comment: @Bosworth99 - good to hear! Cheers!

RSA keys - virtual hosts


How to use ssh_connection:exec in Erlang?

Question: This is an interesting situation, focused on the behavior of erlang ssh modules. I had spent a few hours troubleshooting a problem that turned out to reveal that the Erlang ssh_connection *exec/4* function operates asynchronously.
If you issue the ssh_connection:exec/4 function to run a script that takes several seconds to complete, and then in your erlang program you close the ssh connection, the script execution will terminate. My expectation was that the ssh_connection:exec would be synchronous rather than asynchronous.
Because the time to complete the remote script invoked by ssh_connection:exec is unknown, I chose to not issue the closure ssh:close(). I would like to understand the consequences of that:

Will the gc clear it at some point ?
Will it stay open for good during the whole node existence ?
Is there a way to make the ssh_connection:exec synchronous, as I would believe it should be.

Here is an example of the test erl program that I used to verify this issue. As a script you can run a simple sleep 10 (sleep 10 seconds) to emulate a slow running program.
<code>-module(testssh).
-export([test/5]).

test (ServerName, Port, Command, User, Password) ->

    crypto:start(),
    ssh:start(),
    {ok, SshConnectionRef}                  = ssh:connect(ServerName, Port, [ {user, User}, {password, Password} , {silently_accept_hosts, true} ], 60000  ),
    {ok, SshConnectionChannelRef}           = ssh_connection:session_channel(SshConnectionRef, 60000),
    Status                                  = ssh_connection:exec(SshConnectionRef, SshConnectionChannelRef, Command, 60000),
    ssh:close(SshConnectionRef).
</code>
Remote script:
<code>#!/bin/sh
sleep 10
</code>
Answer: I never had to use the ssh application myself,  but you should be reading something wrong, it is clear in the doc that the result will be delivered as messages to the caller:

[...] the result will be several messages according to the following pattern. Note that the last message will be a channel close message, as the exec request is a one time execution that closes the channel when it is done[...]

See http://www.erlang.org/doc/man/ssh_connection.html#exec-4
So after you call ssh_connection:exec/4 , test with a loop like this:
<code>wait_for_response(ConnectionRef) ->
    receive
            {ssh_cm, ConnectionRef, Msg} ->
                    case Msg of
                            {closed, _ChannelId} ->
                                    io:format("Done");
                            _ ->
                                    io:format("Got: ~p", [Msg]),
                                    wait_for_response(ConnectionRef)
                    end
    end.
</code>
You should receive the command output, and other ssh messages, and finally a 'closed' message that is your signal that the ssh command has properly finished.
Comment: thanks for your comments. In fact I was not aware on how to use this messaging pattern in Erlang. Now it makes sense completely.


Can you recommend some Python HTTP client library?

Question: I want to use Python to capture info from some websites.
I want the HTTP client to meet this conditions:

Supports HTTPS
Will not use too much memory, should not generate a lot of processes or threads.
Has clear documentation and is actively supported

I know that requests, tornado, or the gevent -httpclient
can finish my task, but I do not know which is the best? Or is there some other choices?
Or if there is some other choices written in C/c++.
Answer: Use requests. It has the most same API of the various libraries.
Comment: Here you are:
https://github.com/shazow/urllib3/blob/master/urllib3/connectionpool.py#L498 almost any `httplib.HTTPException` or `socket.error`, save for socket timeout and SSL certificate problem will lead to retry.

A bit later on line 516 `if not conn: return self.urlopen(...)` Recursion! Isn't it a nice way to do repeating?
Comment: I read the info about tornado ,someone say it efficient, how about the efficiency about requests?
Comment: Tornado is efficient if you can profit from asynchronous processing, i.e. if you need many parallel connections. However, *requests* supports asynchronous requests, too: http://docs.python-requests.org/en/latest/user/advanced/#asynchronous-requests - and it fits better since tornado is more a webserver than a http client library.
Comment: Beware that `requests` uses `urllib3` which automatically repeats requests in certain cases. It may be critical to avoid repeating.
Comment: @temoto: It would probably be a good idea to mention in which cases that happens...
Comment: @Djvu `requests` is the most CPU hungry HTTP library out there. On network efficiency, since it's pure Python, you can combine it with green thread solution like `eventlet` to make thousands of concurrent connections. Can't provide any info on memory efficiency, sorry.
Answer: Another option is httplib2.

simple (and therefore efficient)
supports everything one needs and Python 3
not on Github
few months may pass before next commit (partly because it just works)
Comment: I use httplib2 atm. It supports py3, but lacks support of proxy on py3. Its nice and it just works, but there is a number of issues on official tracker which are stuck on for years.
Answer: here's another suggestions:

GRequests allows you to use Requests with Gevent to make asynchronous HTTP Requests easily.
httplib2
Requests
treq
Answer: I find urllib3 is a great option.  It sets up request pooling for you and handles SSL easily.
Also I think requests now uses it under the hood.
http://urllib3.readthedocs.io/en/latest/


Texto por cima de div com bordas

Question: Fala galera! Tenho uma div .apresentacao, nela apliquei bordas para se tornar um triangulo. Beleza, más quero colocar um texto acima, porém com as bordas modificadas da .apresentacao, não fica alinhado.
Como posso melhorar esse meu codigo?
Obrigado pessoal! :)
CODE:

.apresentacao {
  width: 0px;
  height: 0px;
  border-right: 100px solid transparent;
  border-top: 100px solid transparent;
  border-left: 100px solid #f0ad4e;
  border-bottom: 100px solid #f0ad4e;
}

    Aqui vem um texto qualquer

texotexto.

Answer: Veja se é isso:

.apresentacao {
  width: 0px;
  height: 0px;
  border-right: 100px solid transparent;
  border-top: 100px solid transparent;
  border-left: 100px solid #f0ad4e;
  border-bottom: 100px solid #f0ad4e;
}
.content {
  position: relative;
  width: 200px;
  height: 200px;
}
.texto {
  width: 50px;
  bottom: 10px;
  position: absolute;
  left: 10px;
}

      Aqui vem um texto qualquer
      texto

Comment: Posição absoluta e relativa +1
Comment: Rapaz, eu tinha colocado absolute e relative antes más não tava funcionando. Que coisa estranha. OBRIGADO pela resposta. vou ver o que aconteceu!! :)

Texto por cima de div com bordas


What happened to the og-list view in organic groups?

Question: The new version of Organic Groups (7.2) does not have a the view og-list, which used to display a list of all the groups. Any idea why it was removed and how to get the list of all groups?
Answer: I don't know why it was removed, but here's a sample view you can import and tweak as needed. To import, go to /admin/structure/views/import.
<code>$view = new view();
$view->name = 'og_list';
$view->description = 'A list of all Organic Groups';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'og list';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'All Groups';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
$handler->display->display_options['row_options']['links'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'group' => 'group',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['path'] = 'og-list';
$translatables['og_list'] = array(
  t('Master'),
  t('All Groups'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('Page'),
);
</code>
Answer: The OG Extras module could solve some of your needs, among other useful displays and features -

Extra functions, blocks, and views for Organic Groups 7.2. In particular, this module adds views and blocks needed by sites that are not using Panels, although it also may be useful to sites that do use Panels. This module is for Organic Groups 7.2. It will not work with Organic Groups 7.1.
This module was created because the default views and blocks that come with Organic Groups only work in Panels. It restores some of the functionality of the D6 version of Organic Groups.


aws sam LambdaLayer deploying for every new build

Question: I have a Resource in my template.yml:
  MyLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      ContentUri: layers/my-layer
      CompatibleRuntimes:
        - python3.8
    Metadata:
      BuildMethod: makefile

This is my Makefile:
  build-MyLayer:
      mkdir -p "$(ARTIFACTS_DIR)/python"
      cp *.py "$(ARTIFACTS_DIR)/python"
      python -m pip install -r requirements.txt -t "$(ARTIFACTS_DIR)/python"

Every time while I doing sam build and then sam deploy the layer MyLayer deploys to the AWS and new version creating. Even if I do not change the code of the MyLayer module.
How can I disable a layer new version creating in every deploy?
Answer: I found a solution which responds to my requirements.
I am create a separated folder with template.yaml which describes a one resource (AWS::Serverless::LayerVersion) only. When I need release a new version I make a build that resource


Direct limit of torsion-free abelian groups is torsion-free.

Question: I am trying to show that if $G_{\alpha}$ form a directed set of torsionfree abelian groups, then $\varinjlim G_{\alpha}$ is torsionfree abelian.
One approach I thought of is to use a Zorn's lemma argument on the union of a chain of torsionfree abelian groups. An infinite direct product also works if the system is countable?
Another more worked out approach is as follows: Any $g \in \varinjlim G_{\alpha}$ has the form $\mu_{\alpha} (g_{\alpha})$ so that, if $n * g = 0$, then $0 = n*g = n * \mu_{\alpha} (g_{\alpha}) = \mu_{\alpha} (n * g_{\alpha})$. I want to say that $n * g_{\alpha}$ must then be 0  in order to reach a contradiction.
Answer: As you are working in a directed set, each element of the direct limit is
a suitable equivalence class $[g,G_a]$ where $g\in G_a$. Also
$[g,G_a]=0$ iff $\phi_{ab}(G_a)=0$ in $G_b$ for some $b\ge a$ in the index
set $A$. For the direct limit to have torsion, then there must be
some $n\in\Bbb N$ and a $[g,G_a]\ne0$ with $[ng,G_a]=0$. Then there
is $b\ge a$ with $\phi_{ab}(ng)=0$ in $G_b$, that is,
$n\phi_{ab}(g)=0$ in $G_b$. But $\phi_{ab}(g)=0$ as $G_b$ is torsion-free.
That means that $[g,G_a]=0$, contradiction.


How to Use std::unordered_map with std::pair?

Question: I have this error:

binary '==': 'std::pair<const EntityId,EntityData>' does not define this operator or a conversion to a type acceptable to the predefined operator*

In this code:
using EntityId = unsigned int;
using ComponentContainer = std::vector<C_Base*>;
using EntityData = std::pair<Bitmask,ComponentContainer>;

// ERROR below at line:
using EntityContainer = std::unordered_map<EntityId, EntityData>;

Here is the C_Base class:
#include <iostream>
#include <sstream>
#include "ECS_Types.h"

class C_Base{
public:
    C_Base(const Component& l_type): m_type(l_type){}
    virtual ~C_Base(){}

    Component GetType(){ return m_type; }

    friend std::stringstream& operator >>(
        std::stringstream& l_stream, C_Base& b)
    {
        b.ReadIn(l_stream);
        return l_stream;
    }

    virtual void ReadIn(std::stringstream& l_stream) = 0;
protected:
    Component m_type;
};

And the Bitmask class:
#include <stdint.h>

using Bitset = uint32_t;

class Bitmask{
public:
    Bitmask() : bits(0){}
    Bitmask(const Bitset& l_bits) : bits(l_bits){}

    Bitset GetMask() const{ return bits; }
    void SetMask(const Bitset& l_value){ bits = l_value; }

    bool Matches(const Bitmask& l_bits,
        const Bitset& l_relevant = 0)const
    {
        return(l_relevant ?
            ((l_bits.GetMask() & l_relevant) == (bits & l_relevant))
            : (l_bits.GetMask() == bits));
    }

    bool GetBit(const unsigned int& l_pos)const{
        return ((bits&(1 << l_pos)) != 0);
    }
    void TurnOnBit(const unsigned int& l_pos){
        bits |= 1 << l_pos;
    }
    void TurnOnBits(const Bitset& l_bits){
        bits |= l_bits;
    }
    void ClearBit(const unsigned int& l_pos){
        bits &= ~(1 << l_pos);
    }
    void ToggleBit(const unsigned int& l_pos){
        bits ^= 1 << l_pos;
    }

    void Clear(){ bits = 0; }
private:
    Bitset bits;
};

When I try the below code, I get this error using EntityContainer = std::unordered_map;:

'operator __surrogate_func': no matching overloaded function found

struct pair_hash {
    template <class T1, class T2>
    std::size_t operator () ( const std::pair<T1, T2>& p ) const {
        auto h1 = std::hash<T1>{}( p.first );
        auto h2 = std::hash<T2>{}( p.second );

        // Mainly for demonstration purposes, i.e. works but is overly simple
        // In the real world, use sth. like boost.hash_combine
        return h1 ^ h2;
    }
};

using EntityId = unsigned int;

using ComponentContainer = std::vector<C_Base*>;
using EntityData = std::pair<Bitmask,ComponentContainer>;

// ERROR below at line:
using EntityContainer = std::unordered_map<EntityId, EntityData, pair_hash>;

Comment: Can we get a [mre]? `std::pair` does define a `operator ==`
Comment: Note that while `std::pair` has `operator==` defined at least one component of your `std::pair` -- `Bitmask` -- doesn't.
Comment: Also, please edit your question to show the full error message verbatim and tag the line of code that generates the error.
Comment: `std::unordered_map` only needs the key to be hashed/have an `operator==`. So `EntityContainer` should be fine. What is `Component` (As the key for `ComponentFactory`)?
Comment: I'm sorry, my project is big with me, I don't get small project, I add information error line, you can see it.
Comment: And don't worry to >Component and >ComponentFactory, I deleted it
Answer: Although std::pair has operator== implemented it relies on each of the two component parts of the pair having a viable operator== definition of their own (until c++20 which provides synthesized_three-way_comparison).
So you need to define an equality operator for Bitmask...
class Bitmask {
public:
  ...
  bool operator== (const Bitmask &other) const
    {
      return bits == other.bits;
    }
};

Comment: thansk, but so error:
>**binary '==': 'std::pair' does not define this operator or a conversion to a type acceptable to the predefined operator**


Dynamic grouped bar chart

Question: I am trying to create a dynamic bar chart which updates on every iteration of a loop, but the chart only renders once the loop is completed. Can someone please help with this ?
<code>import matplotlib.pyplot as plt
import time
from IPython import display
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
from numpy.random import randn
%matplotlib inline
fig,ax = plt.subplots(1,1)
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
ax.set_xlabel("Load", fontsize=12)
ax.set_ylabel("People", fontsize=12)
y_pos = np.arange(len(people))
ax.set_yticks(y_pos)
ax.set_yticklabels(people, rotation=75)
fig.canvas.draw()
width = 0.4
for i in range(0,3):
    p1 = 3 + 10 * np.random.rand(len(people))
    p2 = 3 + 10 * np.random.rand(len(people))
    df = DataFrame({'p1': p1, 'p2': p2})
    ax.barh(y_pos, df['p1'], width, color='red')
    ax.barh(y_pos + width, df['p2'], width, color='blue')
    fig.canvas.draw()
    time.sleep(0.5)
</code>
Comment: Add a `plt.show()` at every iteration?
Comment: Doesnt help. I am sure i am missing something simple though!
Answer: I figured out the answer. Problem was with %matplotlib inline statement and its placement.
For interactive charts, its suggested to use %matplotlib notebook instead of inline. And its supposed to be placed before matplotlib is imported.
The following code worked!
<code>%matplotlib notebook

import matplotlib.pyplot as plt
import time
from IPython import display
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
from numpy.random import randn
fig,ax = plt.subplots(1,1)
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
ax.set_xlabel("Load", fontsize=12)
ax.set_ylabel("People", fontsize=12)
y_pos = np.arange(len(people))
ax.set_yticks(y_pos)
ax.set_yticklabels(people, rotation=75)
fig.canvas.draw()
width = 0.4
for i in range(0,3):
    p1 = 3 + 10 * np.random.rand(len(people))
    p2 = 3 + 10 * np.random.rand(len(people))
    df = DataFrame({'p1': p1, 'p2': p2})
    ax.barh(y_pos, df['p1'], width, color='red')
    ax.barh(y_pos + width, df['p2'], width, color='blue')
    fig.canvas.draw()
    time.sleep(0.5)
</code>

Dynamic grouped bar chart


Laravel - Como paginar e dar Order By

Question: Tenho esse código:
$modeloVideo = ModeloVideo::paginate(10);

Quero paginar por 10 e exibir order by desc (ordem decrescente).
Como fazer essa query?
Tentei assim :
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\ModeloVideo;

class HomeController extends Controller {

    public function home() {

        //TODOS OS REGISTROS DA TABELA
    $modeloVideo = ModeloVideo::all()->orderBy('created_at', 'desc')->paginate(10);

        $array = array("videos" => $modeloVideo,
        );

        return view('home',$array);
    }

Código do model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class ModeloVideo extends Model {
    //informando a tabela que sera usada
    protected $table = "modeloVideo";
    //quando fizer uma insercao ou update nao adicionar a coluna created ou update

}

?>

e ainda não funcionou, da o erro:
BadMethodCallException
Method orderBy does not exist.
Comment: Não tenho como testar agora, mas acredito que com `ModeloVideo::orderBy('created_at','desc')->paginate(10);` deve funcionar, mas você receberá um `LengthAwarePaginator` e terá que tratar... utilize o `dd();` para testar. Qual a versão do laravel você está utilizando?
Answer: Para realizar a busca com o orderBy e o paginate basta utilizar a seguinte sintaxe:
ModeloVideo::orderBy('created_at', 'desc')->paginate(10);

Assim como essa resposta e  essa no SOen.
Answer: Evite fazer assim, somente alguns casos:
$modeloVideo = ModeloVideo::all()->orderBy('created_at', 'desc')->paginate(10);

porque, você está trazendo no all() todos os registro na base de dados em uma classe collection e depois tem um erro porque não existe orderBy na classe collection o comando é sortBy e por fim gera uma paginação, então está tudo errado, porque, já trazer a massa de dados (todos os registros) da base para depois fazer ordenação e paginação gera um grande gargalo na sua aplicação. A SQL construida para esse comando é: SELECT * FROM modelo_video.
Modo correto: primeiro ordena valores da base e depois faz a paginação tudo isso já vindo pronto os dados da sua tabela, ou seja, na SQL escrita pelo framework Eloquent, exemplo:
$modeloVideo = ModeloVideo::orderBy('created_at', 'desc')->paginate(10);

e a  SQL construida para esse comando (basicamente falando) é: SELECT * FROM modelo_video ORDER BY created_at DESC limit 10 offset 0, e esse dado já vem a quantidade especifica e essa é a grande diferença. Observação: essa SQL é um exemplo, o método paginate busca informações para pagina em várias do próprio Framework, isso é mesmo para exemplificar a parte do gargalo.
Answer: antes de usar o orderBy você precisa buscar os registros no banco:
ModeloVideo::all()->orderBy('created_at', 'desc')->paginate(10);

->all(): busca todos os registros do banco
->orderBy: ordena os valores buscados
para a paginação você precisará usar o método ->paginate, veja o exemplo na documentação oficial

O erro é causado porque o método orderBy não faz parte de instancias de Model e sim de collections.
Comment: valeu o do santo will deu certo era só tirar o all()
Comment: Não consegui entender, pode digitar a query completa que atenda essa condição por favor? $modeloVideo = ModeloVideo::paginate(10); quero paginar por 10 e exibir order by desc
Comment: atualizei a resposta Deny
Comment: Obrigado, mas ainda não funcionou, atualizei a resposta com o código.
Comment: publique qual foi o erro que encontrou...
Comment: BadMethodCallException
Method orderBy does not exist.

Laravel - Como paginar e dar Order By


Global status in the JVM that records OutOfMemoryError?

Question: We have to deal with a class library that does a
catch(Throwable e) {log.error("some message", e)}

but otherwise ignores the problem. Other than running an external command as described in https://stackoverflow.com/a/3878199/2954288, is there some internal global state in the JVM that can be queried to see if an OutOfMemoryError has happened since the startup?
My question is not a duplicate of: Is it a bad practice to catch Throwable?. I am not asking whether or
not we should catch(Throwable). I am asking whether a certain way to deal with it exists.
Comment: @piet.t how about another: "never trust a library which swallows `Throwable`". Who knows what other madness is in there...
Comment: My rule of thumb is "never trust a JVM that has thrown an OOME" because it might look like it is working OK while in fact it isn't. And restarting it will require an external command.
Comment: Exactly. Nevertheless I am in a situation where I would like to at least try to set a last mark before exiting.
Comment: See http://stackoverflow.com/questions/2679330/catching-java-lang-outofmemoryerror
Comment: Possible duplicate of [Is it a bad practice to catch Throwable?](http://stackoverflow.com/questions/6083248/is-it-a-bad-practice-to-catch-throwable)
Comment: You should regard that as a bug in the class library and ask for it to be fixed.
Comment: @Raedwald: certainly not a duplicate of the question you mention, since there is no question that the library should not catch(Throwable). And yes, a bug report is under way.
Answer:
Is there some internal global state in the JVM that can be queried to
  see if an OutOfMemoryError has happened since the startup

Yes, there is a variable out_of_memory_reported. It is internal and is not supposed to be read from outside. Though you can do this with gdb, for example:
$ gdb -p PID

(gdb) p 'report_java_out_of_memory(char const*)::out_of_memory_reported'
$1 = 0

If you'd like a reliable way to intercept all OutOfMemoryErrors from within Java application, whether they are caught or not, you can use JVMTI Exception Callback.
The example can be found here.
Answer: Catching OutOfMemoryError in the path of all possible places where it occurs ... it's not really possible as it can occurs in any Java codes, and internally in the JVM.
When the JVM emits an OOME, sometimes it's recoverable but usually not, so catching it inside your will generally lead to nothing as the JVM will be unusable (it is in a state where it cannot allocate more memory so you cannot process any step in your program)
If you need to know whether or not your application generate OOME and a way to take action, you need to do this from an external point, the easiest way to do this is to use the standard way that the JVM offers you using some jvm starting option.
Usually, for dealing with OOME you use the following JVM starting options:

-XX:+HeapDumpOnOutOfMemoryError tells the JVM to generate a heap dump on OOME so you can analyse it further (for example with Eclipse MAT: http://www.eclipse.org/mat/)
-XX:OnOutOfMemoryError="<cmd args>;<cmd args>" tells the JVM to launch a command on the host in case of OOME. By this you can for example send an email and restart your server!

More informations on statup options ca be found here : http://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html
Comment: Do those flags cause the JVM to do things for *all* OOMEs, or just the uncaught ones?
Comment: I am not after catching it, since I can't anyway. I just wonder if there is some flag within the JVM that would tell me after the fact that bad things have happened.
Comment: That's why I give you the two usefull flags ;) I don't think there is anything else that is usable because as the JVM didn't have anymore memory, it cannot records diagnostic data regarding the cause of OOME ... The only way is to generate a dump and analyse it after as I suggest in my answer.


ARMA forecast has data forecast gap?

Question: I am currently doing a project with R, and I am trying to forecast a dataset that starts in 1992,january and ends in 2015,december. The data has a monthly frequency.
I find that the best model to forecast is ARMA 5,3. I am using a model with trend and seasonal component to forecast. However, when i try to forecast the data, there is a gap between the last observation of the sample and the first observation of the forecast.

Code is as follows for a 5 year forecast (60 months):
    h=60
    fz=((length(sales)+1):(length(sales)+h))

    FMo1 = rep(c(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), h/12)
    FMo2 = rep(c(0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), h/12)
    FMo3 = rep(c(0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0), h/12)
    FMo4 = rep(c(0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0), h/12)
    FMo5 = rep(c(0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0), h/12)
    FMo6 = rep(c(0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0), h/12)
    FMo7 = rep(c(0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0), h/12)
    FMo8 = rep(c(0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0), h/12)
    FMo9 = rep(c(0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0), h/12)
    FMo10 = rep(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0), h/12)
    FMo11 = rep(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0), h/12)
    FMo12 = rep(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1), h/12)
    OutTrend = model.matrix(~ 0  +fz+FMo1+FMo2+FMo3+FMo4+FMo5+FMo6+FMo7+FMo8+FMo9+FMo10+FMo11+FMo12)

    Fitoutsample = sales-arma53.model$residuals

    Forecast1=predict(arma53.model,h,newxreg=OutTrend)$pred
    UF=predict(arma53.model,h,newxreg=OutTrend)$pred+1.96*predict(arma53.model,h,newxreg=OutTrend)$se
LF=predict(arma53.model,h,newxreg=OutTrend)$pred1.96*predict(arma53.model,h,newxreg=OutTrend)$se

    plot(sales,xlim=c(2010,2016+h/12),ylim=c(100000,500000),ylab="Retail sales",main="ARMA(5,3) model with trend and seasonality")
    lines(Fitoutsample,col="green")
    lines(Forecast1,col="blue")
    lines(UF,col="red")
    lines(LF,col="red")

    plot(sales,xlim=c(1992,2016+h/12),ylim=c(100000,500000),ylab="Retail    sales",main="ARMA(5,3) model with trend and seasonality")
    lines(Fitoutsample,col="green")
    lines(Forecast1,col="blue")
    lines(UF,col="red")
    lines(LF,col="red")

The problem also happens when i do an insample forecast, note the period by the end of 2014 that is not covered by the insample forecast:
Comment: No, there is not a gap there is a problem with the graph there is still underlying data. You might have to join it.
Comment: How can i do that?
Comment: I am a little confused ARMA(5,3)  has 5 autoregressive parameters and three moving average parameters.  This is a stationary model.  But you claim a trend and a seasonal component and your data suggests it.  How did you fit the Model?  Are you using the right notation to describe the model?
Comment: I am a student undergoing an elective in R language.

The way the project works is I find a dataset that increases linearly and has a seasonal pattern, as in this case. I used a linear trend and a seasonal trend which had an adjusted R square of 99.7 and then i ran test of AR,MA and ARMA depending on my analysis of the ACF and PACF of residuals provided by the linear+seasonal trend. ARMA 5,3 had the lowest AIC and i used it for this forecast.

The forecast looks fine. I cross checked the first months of 2016 i forecast, and they have a 5-7 percent difference. But how do i fix that gap?
Comment: Perhaps your series has changes in trends or levels over time. Perhaps the seasonal factors have changed over time . perhaps the error process from your models suggests increased volatility i.e. increased or even decreased error variance. perhaps your parameters have changed over time ..Only the data knows for sure or maybe Lamont Cranston knows (joke) .. It is your job/mission to verify any and all of these things as they can have an impact on your prediction error.
Comment: I have also done an in-sample verification and the prediction model is fine. The gap is not a problem with the model, its a problem with the data and i don't know how to fix it? I uploaded the insample in the first post
Answer: There is no gap. Your data is discretely sampled, at monthly intervals. The forecasts are discrete, at monthly intervals. The lines in between these points are linear interpolations for the purpose of painting a pretty picture but they have no meaning. Try to plot with points (use the argument type="b" in the plot function) and you will see: the points are regularly spaced and there is no gap.
If you absolutely want there to be a line in between the last data point and the first forecasted point, duplicate the last data point at the beginning of your forecast vector. This will make it draw an extra line segment of the same color as your regular forecast.

ARMA forecast has data forecast gap?


Univariate analyses with incomplete data set

Question: I'm dealing with a fairly large ecological data set (field data, not collected by me) of approximately 60 attributes measured for about 400 individual trees. Very few trees (~20%) have complete data (have a value for every attribute), the rest are missing one or more data points, due to field-research limitations and error.
I'm working on univariate analyses--basically just generating a bunch of summary statistics--and I'm not sure what is the most responsible approach to handling the missing values?
The conservative approach would be to restrict my analyses to the 20% of individuals with complete data, but that looses a lot of critical information--the data is batched by field sites, and only a few sites have complete information, so I'd have to throw out a bunch of sites, which would kill the overall research objectives.
Alternatively, I could just use all the data, and use a somewhat different set of individuals for each attribute--but my concern with that approach is that it makes comparison of different attributes invalid, because the data isn't paired. This is important, because some of the data is time-series (values for the same attribute in multiple years) and I want to compare different years to each other. For example, I want to look at how "attribute A" changes from year to year, and eventually I intend to correlate that change with other data, such as local temperature and rainfall.
I'm leaning toward the laborious hybrid-approach of using a different data sub-set for each comparison--for example when I look at "attribute A" over multiple years, I'll include only trees that were measured in all relevant sample periods, and exclude any with missing data. But if I want to do the same thing with "attribute B", I'll use a different set of trees, which is complete for that attribute. Before I dig too far into that approach though, I would love any advice folks have about how to handle this issue. I've tried poking around this forum and some text books, but I'm not finding any good answers.
Answer: Your hybrid approach sounds a little bit odd to me, especially if you consider analysing time series data. This could lead to situations where you are comparing three points in time, which have no cases in common.
Example:

t0 case1 case2 case3 case4 (rest is missing)
t1 case3 case4 case5 case6 (rest is missing)
t1 case5 case6 case7 case8 (rest is missing)

t0 & t1 = compare case3 and case4
t1 & t2 = compare case5 and case6
One possible way to deal with missing values without loosing cases, would be using multiple imputation. In multiple imputation you substitute each missing value by several plausible values based on a pre-specified regression model for each variable.
An alternative would be estimating the model with the full information maximum likelihood approach, which is used in many structural equation modeling software packages.
For univariate statictics both approaches could be a bit over the top, but I would give it a chance.
Software:

http://www.jstatsoft.org/v45/i03/paper
http://sites.stat.psu.edu/~jls/misoftwa.html

Sources:

Graham, John W. "Missing data analysis: Making it work in the real world." Annual review of psychology 60 (2009): 549-576.
Schafer, Joseph L., and John W. Graham. "Missing data: our view of the state of the art." Psychological methods 7.2 (2002): 147.
Comment: Thanks for this info, good stuff. Fortunately, I have a lot of observations, so I can restrict analysis to only individuals that were measured in all sample periods--for simple regressions. However, the set of trees with complete data for 'attribute A', is not the same as for 'attribute B'. So, if I want to say "rain causes A to increase, and B to decrease" I am using different individuals for A vs. B. This seems problematic? I could also 'double restrict' the analysis to only trees that are complete for both A and B, but then I lose a lot of power.


Identical methods act differently in VS debug console and Unity debug console

Question: I want to sort 25 numbers (0, 1, 1, 2, 2, 3, 3, ... , 12, 12) randomly in Unity.
First, I wrote a test code in VS.
[Program.cs]
using System;

namespace random {
    class Shuffle {
        // ShuffleNumbers: sort 0, 1, 1, 2, 2, 3, 3, ... 12, 12 (25 numbers) randomly
        public static int[] ShuffleNumbers() {

            // randomArray : randomly sorted numbers
            int[] randomArray = new int[25];

            // howManyCanBeAdded[k] : how many 'k's can be added in randomArray
            int[] howManyCanBeAdded = new int[13] { 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };

            // r : Random object
            System.Random r = new System.Random();

            for (int i = 0; i < 25; ) {
                // create a random number
                int random = r.Next(0, 13);

                // check whether the number can be added
                // if true, add the number to randomArray
                if (howManyCanBeAdded[random] > 0) {
                    howManyCanBeAdded[random]--;
                    randomArray[i++] = random;
                }
            }

            return randomArray;
        }
    }

    class Program {
        static void Main(string[] args) {
            int[] randomArray = random.Shuffle.ShuffleNumbers();
            for(int i = 0; i < 25; i++) {
                Console.Write(randomArray[i]);
                Console.Write(' ');
            }
        }
    }
}

It acted correctly in VS debug console, like this:

So I pasted the code in Unity script.
[Shuffle.cs]
using System;

public class Shuffle
{
    // ShuffleNumbers: sort 0, 1, 1, 2, 2, 3, 3, ... 12, 12 (25 numbers) randomly
    public static int[] ShuffleNumbers() {

        // randomArray : randomly sorted numbers
        int[] randomArray = new int[25];

        // howManyCanBeAdded[k] : how many 'k's can be added in randomArray
        int[] howManyCanBeAdded = new int[13] { 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };

        // r : Random object
        System.Random r = new System.Random();

        for (int i = 0; i < 25; ) {
            // create a random number
            int random = r.Next(0, 13);

            // check whether the number can be added
            // if true, add the number to randomArray
            if (howManyCanBeAdded[random] > 0) {
                howManyCanBeAdded[random]--;
                randomArray[i++] = random;
            }
        }

        return randomArray;
    }
}

[ShuffleObject.cs]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ShuffleObject : MonoBehaviour {
    void Start() {
        int[] randomArray = Shuffle.ShuffleNumbers();
        for(int i = 0; i < 25; i++) {
            Debug.Log(randomArray[i]);
        }
    }
}

Finally, I drag&dropped ShuffleObject.cs file to an empty object in the scene and played.
But the Unity debug console acted differently. It printed only 13 numbers(0, 1, 2, ..., 12).
Why the same code act differently in VS and Unity?
Comment: Maybe you should consider filling an array with the numbers you want and then swapping positions of 2 random indices enough time to get your number in randomized position in your array. Like you will do when you mix a deck of cards... If you do so, swapping 4 times the size of your array should be enough.
Comment: In your code, you've allowed for how many could be added but if it was 0 you dont pick a new number. Therefore you arent necessarily going to get 25 good numbers
Comment: Your printing for loop iterates 25 times (the code is pretty straightforward). It would either throw an out of bounds exception or print **something**. There must be more logs than the screenshot you added.
Comment: @BugFinder he anyway goes through all 25 entries. It is just possible that some of them stay `0` which is the default value of `int`.
Comment: I'd imagine collapsed log and some has more than one entry so only the original numbers show but there's counters in the end
Answer: Make sure in Unity you have Collapse deactivated on the console options (second from left)!

Shows only the first instance of recurring error messages.
This is useful for run-time errors, such as null references, that are sometimes generated on each frame update.

If the same number is logged twice Unity automatically groups them together in one message but with a small 2 or other number on the left side indicating this exact message was logged multiple times.
Since you can return numbers from 0 to 12 it is very probable you get some of the numbers multiple times. So you see them collapsed and it appears to be only exactly 13 messages (your possible values).


Angular - how to check if next value of a callback is a specific one, and do something in case is not?

Question: I'll simplify my code and show you an example:
I have this array of objects:
let myArray = [{month: 1}, {month: 2}, {month: 4}, {month: 6}];

I have a function used to map the values of this object, to another object:
my mapping function:
mapFunction(myObj) {
return {newProperty: myObj.month}
}

then I Call this function inside a map() :
let myNewArray = this.myArray.map(mapFunction);

and this works great, it maps each value of myArray using my function.
Now I want to add an extra step,
if the next iteration of my map() is not a sequential month, it must add an object with the missing month value.
So with the above example, it should add 2 new objects, {month: 3}, {month: 5}
because they are missing, but it should not add the months after the last one, only those that create "holes"
I hope I made myself clear.
My mapping function should check if the next month value equals to the previous + 1
but we need also to consider that there might be bigger gaps, like 2 missing months in a row, and it should fill them both!
Answer: Taking your requirements as stated, you want to fill in the gaps in an ordered, non-sequential array.
One way of performing a complex map is to use the reduce array function.
You could pad out your original array and then pass that into your mapping function:
months = [];

ngOnInit() {
  let myArray = [
    {month: 20},
    {month: 3},
    {month: 4},
    {month: 6}
  ];

  myArray = myArray
    .sort((a, b) => a.month - b.month)
    .reduce((arr, current, idx) => {
      const month = current.month;

      if (idx > 0) {
        const previous = myArray[idx - 1].month + 1;
        for (let i = previous; i < current.month; i++) {
          arr.push({month: i});
        }
      }

      arr.push(current);
      return arr;
    }, []);

  this.months = myArray.map(this.mapFunction);
}

mapFunction(myObj) {
  return {newProperty: myObj.month}
}

DEMO: https://stackblitz.com/edit/angular-hsgdqt
Comment: thank you for the answer, first of all, I simplified everything, all this mapping happens inside a big reduce() function, and the object has 10properties and not only "month". That's why I need to preserve my mapFunction, because it maps all the properties of that object, and my idea was inside the mapFunction(), to put the check, and if the object with the following correct month is missing, then map to a new object that has that missing month, and put to null all other properties
Comment: Map will map an n-dimension array to another n-dimension array. You need something else in there.
Comment: So you could make a "filled-in" version of your original array, and then pass it through your existing function?
Comment: I see, didn't think about this, and it won't be a problem if I put another reduce() inside my bigger reduce? I will try your way, basically with that reduce() you are using, I'm mapping the existing objects to my new interface, and pushing new objects that I created for the missing month in the final array?
Comment: you could also chain the reduce to your map. i.e. `array.map().reduce()`. to preserve your mapping, but then also do the check based on the new array format.
Comment: that is a great idea, I could quickly check the length, and push X empty objects in my array, before mapping, but then, I have a sort function in place as you did in your example, this would push all the empty objects at the end, then it would be enough to sort again after the mapping right? could you provide then an example for my existing mapping function, knowing it will have always 12objects for 12months
Comment: @AJ989 I've updated my answer. That's definitely a cleaner approach and keeps the concerns separate
Comment: @KurtHamilton ok so based on your last updated answer, I should use reduce() as soon as I get my "months" array from my observable, use it to fill with empty months, then finally pass my map function which will map that array to a new array of a different type! Seems all clear, going to try it now
Comment: @KurtHamilton I'm having an issue, if the first month is not 1, but maybe 3, it will create months for value 1 and value 2, how can I change the code to start the count only from the first month value in the array?
Comment: @AJ989 Ah, I put that in as an assumption (never assume!). I've updated my answer.
Comment: damn I hate myself, I made a big mistake, your solution works, but as I told before, the object doesn't only have 1 property, but multiple, and there is a value that I cannot set null, but must come from the DB for that month (each month has a specific value). So I will change the backend, and send all months always, they will have a property called: show: boolean, if false, that month is a "missing" month, so if will only be shown if it creates a hole, but if not, it will be ignored! So how can I change your function, that instead of (finishing on next message, no char left)
Comment: that instead of checking what "months" are missing, it checks on every object, the new property "show", and if false, it must check if removing that month would create a hole, if not, remove it
Comment: I will make another question with the new issue, so we keep this good solution you answered
Comment: The solution will depend on how strict your requirements are, but it should be fairly simple.
Answer: You can create add new items into array using simple loop:

let myArray = [{month: 1}, {month: 2}, {month: 4}, {month: 6}];
let min = Math.min.apply(Math, myArray.map(o => o.month));
let max = Math.max.apply(Math, myArray.map(o => o.month));

const createArray = (i) => {
  let fooArray = [];
  for (let index = 1; index <= i; index++) {
      fooArray.push({month: index})
  }
  return fooArray;
}

console.log(createArray(max));


Finding $a\in(0,10)$ so that the linear spline for $f(x)=e^{-x^2}$ is sufficiently accurate and $n_1+n_2\le 12$

Question:
Suppose we're given a function $f(x)=e^{-x^2}$ and we want to make a piecewise linear interpolation on the interval $[0,10]$ under the following constraints:

We divide the interval $[0,10]$ into two intervals $[0,a]$ and $[a,10]$ and make equidistant partitions into $n_1$ and $n_2$ intervals respectively.
We're looking for a given (global) accuracy of $\varepsilon=10^{-2}.$
$n_1+n_2\le 12.$

My thoughts:
I took a look at the function $f(x)=e^{-x^2}$ restricted to $[0,10].$ I computed the first three derivatives $$\begin{aligned}f'(x)&=-2xe^{-x^2}\\f''(x)&=(4x^2-2)e^{-x^2}\\f'''(x)&=-4x(2x^2-3)e^{-x^2}\end{aligned}$$ $f$ is decreasing on $[0,10]$ and has a saddle point at $x=\frac1{\sqrt 2}.$ From the lectures, I know, if we're interpolating a function $f\in C^2([a,b]),$ with a linear spline $\varphi,$ there is the following estimation:  $$|f(x)-\varphi(x)|\le\frac18h^2M_2,$$ where $h$ is the maximum distance of the nodes and $M_2:=\max\limits_{[a,b]}|f''(x)|.$ In our case, $$|f(x)-\varphi(x)|\le\frac18\max\left\{\frac{a}{n_1},\frac{10-a}{n_2}\right\}^2\underbrace{\left|f''(\sqrt{3/2})\right|}_{\frac4{e^{3/2}}}\le\varepsilon=10^{-2}.$$
I'm not sure, though, what $a$ should be. If we look at $f$ on $\Bbb R,$ it has a horizontal asymptote $y=0$ (since $\lim\limits_{x\to\infty}f'(x)=0$ and $\lim\limits_{x\to\infty}f(x)=0$) so, if we choose some $a\ge\frac1{\sqrt 2},$ maybe we would need less nodes to more accurately interpolate $f_{\Big|[a,10]}$ as it seems to approach the $x$-axis, but I don't quite know how to argue that.
Any advice or guidance would be appreciated.
Answer: Look at the graph of $f''$ over $[0,10]$. Choose short intervals (large values of $n_1$ and $n_2$) in regions where $f''$ is large, and longer ones where it's small. The idea is to make the product $h^2M_2$ roughly constant.
Other than the fuzzy advice I gave above, I don't know how to approach this mathematically. But it should be easy to investigate experimentally using a program like Mathematica.
If you really want to be rigorous, you can set up an optimization problem where $a$ and $n_1$ and $n_2$ are the independent variables, and the approximation error is the objective function to be minimized. Then, just throw the problem to your favorite optimization procedure.
Answer: Attached a MATHEMATICA script which computes the maximum deviation absolute value, for each semi-segment considering the practical possible configurations of $n_1, n_2, a$. The first plot shows the behavior for the set and the last plot shows the needed solution.
Clear[fun]
fun[a_, n_?IntegerQ] :=
 Module[{dif = {}, a1, a2, n1, n2, dx1, dx2, xm, ym, k},
  g[x_] := Exp[-x^2];
  a1 = a;
  a2 = 10 - a;
  n1 = n;
  n2 = 12 - n;
  dx1 = a1/n1;
  dx2 = a2/n2;
  X1 = Table[{dx1 k, g[dx1 k]}, {k, 0, n1}];
  X2 = Table[{a + dx2 k, g[a + dx2 k]}, {k, 0, n2}];
  For[k = 1, k < n1, k++,
   {xm, ym} = (X1[[k]] + X1[[k + 1]])/2;
   AppendTo[dif, Abs[g[xm] - ym]]
   ];
  For[k = 1, k < n2, k++,
   {xm, ym} = (X2[[k]] + X2[[k + 1]])/2;
   AppendTo[dif, Abs[g[xm] - ym]]
   ];
  Return[Max[dif]]
  ]

grs = Table[Plot[fun[a, n], {a, 0.5, 9.5}], {n, 3, 10}];
Show[AppendTo[grs, Plot[0.01, {a, 0.05, 9.5}, PlotStyle -> Red]], PlotRange -> {0, 0.03}]

Show[{grs[[8]], Plot[0.01, {a, 0.05, 9.5}, PlotStyle -> Red]}, PlotRange -> {0, 0.01}]