Button's text not change on RecyclerView

Question: I have a code for RecyclerView where I added 3 buttons one of them is Shortlist button. When I am clicking on button, success is coming from server on volley response. I need when I clicked on button then button's text should be changed and another's item will not be effected.
Below is my CardAdapter class where I extends RecyclerView.Adapter
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private static final String url ="http://192.168.2.110/xp/shortlist1.php";
private static final String url1 = "http://192.168.2.110/xp/express_intrest.php";
private static final String KEY_MATRI_ID_TO="matriID_to";
private static final String KEY_MATRI_ID_BY="matriID_by";

SessionManager session;
public String matri_id_to, matri_id_by, str_gender;
String str;

//Imageloader to load image
private ImageLoader imageLoader;
private Context context;

//List to store all superheroes
List<SuperHero> superHeroes;

//Constructor of this class
public CardAdapter(List<SuperHero> superHeroes, Context context){
    super();
    //Getting all superheroes
    this.superHeroes = superHeroes;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.superheroes_list, parent, false);
    // Session class instance
    session = new SessionManager(context);
    session.checkLogin();
    // get user data from session
    HashMap<String, String> user = session.getUserDetails();
    matri_id_by = user.get(SessionManager.KEY_EMAIL);
    str_gender = user.get(SessionManager.KEY_GENDER);

    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

    //Getting the particular item from the list
    final SuperHero superHero =  superHeroes.get(position);

    //Loading image from url
    imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
    imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.drawable.image, android.R.drawable.ic_dialog_alert));

    holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
    holder.textViewId.setText(superHero.getMglId());
    holder.AgeHeight.setText(superHero.getAgeHeight()+" / "+superHero.getAge());
    holder.Community.setText(superHero.getCommunity()+" / "+superHero.getCaste());
    holder.Occupation.setText(superHero.getOccupation());
    holder.Income.setText(superHero.getIncome());
    //   holder.btnShortlist.setText(superHero.getShortlist());
    //   holder.btnEI.setText(superHero.getExpress_Intrest());

    holder.btnShortlist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            superHero.setShortlist("Wait...");
            holder.btnShortlist.setText(superHero.getShortlist());
            matri_id_to = superHero.getMglId();
            holder.shortlist(position);
        }
    });

    str = superHero.getShortlist();
    Log.e("sh____________",str);

    if(str.toString().equalsIgnoreCase("shortlisted")) {
        holder.btnShortlist.setText(str);
        holder.btnShortlist.setBackgroundColor(Color.parseColor("#FF0E3671"));
        holder.btnShortlist.setEnabled(false);
    }
    else{
        holder.btnShortlist.setText(str);
    }

    holder.btnViewProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent n = new Intent(holder.itemView.getContext(),BlankActivity.class);
            String str_id = holder.textViewId.getText().toString();
            n.putExtra("ID",str_id);
            holder.itemView.getContext().startActivity(n);
        }
    });

    holder.btnEI.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        }
    });

}

public SuperHero getItem(int position){
    return superHeroes.get(position);
}

@Override
public int getItemCount() {return superHeroes.size();}

class ViewHolder extends RecyclerView.ViewHolder{
    public NetworkImageView imageView;
    public TextView textViewId;
    public TextView AgeHeight;
    public TextView Community;
    public TextView Occupation;
    public TextView Income;
    public Button btnShortlist;
    public Button btnViewProfile;
    public Button btnEI;

    //Initializing Views
    public ViewHolder(final View itemView) {
        super(itemView);
        imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
        textViewId = (TextView) itemView.findViewById(R.id.textViewId);
        AgeHeight = (TextView) itemView.findViewById(R.id.AgeHeight);
        Community = (TextView) itemView.findViewById(R.id.Community);
        Occupation = (TextView) itemView.findViewById(R.id.Occupation);
        Income = (TextView) itemView.findViewById(R.id.Income);
        btnShortlist = (Button) itemView.findViewById(R.id.btnshort);
        btnViewProfile = (Button) itemView.findViewById(R.id.buttonViewProfile);
        btnEI = (Button) itemView.findViewById(R.id.btnExpressIntrest);
    }

    public void shortlist(final int position) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response.trim().equalsIgnoreCase("success")) {
                    superHeroes.get(position).setShortlist("Shortlisted");
                    holder.btnShortlist.setText(superHero.getShortlist());
                    notifyDataSetChanged();
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(KEY_MATRI_ID_BY, matri_id_by);
                params.put(KEY_MATRI_ID_TO, matri_id_to);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(stringRequest);
      }
     }
    }

Comment: you can set text of button on success response of that action.
Comment: Yes I did it as button.setText("Shortlisted") but it does not take it
Comment: On success of your api call, you're only calling `notifyDataSetChanged()` for the adapter having the old data-set. How are you updating the `List` on success of api call? I think you're missing this part.
Comment: I used button.setText("Shortlisted") on Success but it's not working and I remove it from there
Comment: Since there's no changes being mage in your data-set, once you call `notifyDataSetChanged()`, it's gonna bind the old values to the views. Try returning list in api response, and subsequently, changing the older list to newer one and then call `notifyDataSetChanged()`.
Comment: Please explain what do u want to tell
Answer: You problem is in onClickListener. update the code as mentioned below:
holder.btnShortlist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            superHero.setShortlist("Wait...");
            holder.btnShortlist.setText(superHero.getShortlist());
            matri_id_to = superHero.getMglId();
            holder.shortlist(position);
        }
     });

If you don't do so then your view will be reset when you scroll or the item will be recycled for the condition you have added:
if(str.toString().equalsIgnoreCase("shortlisted")) {
    holder.btnShortlist.setText(str);
    holder.btnShortlist.setBackgroundColor(Color.parseColor("#FF0E3671"));
    holder.btnShortlist.setEnabled(false);
}
else{
    holder.btnShortlist.setText(str);
}

Further,
public void shortlist(final ViewHolder holder, final int position) {
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            if (response.trim().equalsIgnoreCase("success")) {
                // If response is success then button's text should be changed i.e "Shortlisted"
                superHeroes.get(position).setShortlist("Shortlisted");
                holder.btnShortlist.setText(superHero.getShortlist());
                notifyDataSetChanged();
            }
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put(KEY_MATRI_ID_BY, matri_id_by);
            params.put(KEY_MATRI_ID_TO, matri_id_to);
            return params;
        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(context);
    requestQueue.add(stringRequest);
}

If still it will not come then call notifyDataSetChanged() at the last of onClick().
Update you condition and get your required result:
If you change any UI in adapter in if block then there should be proper reflect of the same change in UI for else case otherwise when the view will refreshed, you UI may not recycled as per desired. So updated your code for the condition you have mentioned:
if (str.toString().equalsIgnoreCase("shortlisted")) {
        holder.btnShortlist.setText(str);
        holder.btnShortlist.setBackgroundColor(Color.parseColor("#FF0E3671"));
        holder.btnShortlist.setEnabled(false);
    } else {
        holder.btnShortlist.setText(str);

        //Color you want in else case
        holder.btnShortlist.setBackgroundColor(Color.parseColor("#FF0E3671"));

        //State you want in else case
        holder.btnShortlist.setEnabled(false);
    }

Comment: Wait... is coming on button text now and I have checked with notifyDataSetChanged()
Comment: Please vote up and accept the answer if it is a solution to your question. Thanks
Comment: there is no solution yet my issue because when I am clicking on button then wait... is coming on button's text
Comment: superHero.setShortlist("Wait...") is working when clicking on button but if response is success then  btnShortlist.setText("Shortlisted"); not working
Comment: Updated my answer further.
Comment: There is no way for not to work the code. You can debug your code and can check the flow. May be you are missing something else somewhere. Otherwise if you are using the same code then it should work.
Comment: But it show error on     holder.btnShortlist.setText(superHero.getShortlist());
Comment: It does not take superHero here
Comment: my friend, take list varible.getShortlist.... As per the logical flow I can see, you can comment this line and it should work as you are calling notifyDataSetChanged() just after that. Please update the variable to your class variable (List variable) or comment the line and let me know if it is having problem further.
Comment: @VKSGODIYAL this is accepted answer. For your understanding, debug and follow al above mentioned steps.
Comment: Please can you tell me exact that where should I added button onClickListiner because in below answer he is saying that you have to move your onClickListener in your ViewHolder.
Comment: can not resolve symbol   holde and superHero in line   holder.btnShortlist.setText(superHero.getShortlist());
Comment: Your code to write onClickListener is correct. Can you please update your present code? I will check and then comment further.
Comment: When I have comment this line (holder.btnShortlist.setText(superHero.getShortlist());) then it's working but there is one another problem with  holder.btnShortlist.setBackgroundColor(Color.parseColor("#FF0E3671"));      In some item's button color is different if text is shortlist
Comment: I have corrected your error at the end of the answer. Check and get the desired output.
Answer: The easy way of doing this will be to pass the reference on the view you want to change.
 holder.btnShortlist.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        holder.btnShortlist.setText("Wait...");
        matri_id_to = superHero.getMglId();
        shortlist( holder.btnShortlist,position); // change this line

    }
});

And then in your response you can do this.
 public void shortlist(final Button button , final int position) { // Pass button as param
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            if(response.trim().equalsIgnoreCase("success")) {
                // If response is success then button's text should be changed i.e "Shortlisted"
               button.setText("ShortListed"); // finally set your text
                notifyDataSetChanged();
            }
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put(KEY_MATRI_ID_BY,matri_id_by);
            params.put(KEY_MATRI_ID_TO,matri_id_to);
            return params;
        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(context);
    requestQueue.add(stringRequest);
}

EDIT:
you have to move your onClickListener in your ViewHolder.
 public ViewHolder(final View itemView) {
    super(itemView);
    imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
    textViewId = (TextView) itemView.findViewById(R.id.textViewId);
    AgeHeight = (TextView) itemView.findViewById(R.id.AgeHeight);
    Community = (TextView) itemView.findViewById(R.id.Community);
    Occupation = (TextView) itemView.findViewById(R.id.Occupation);
    Income = (TextView) itemView.findViewById(R.id.Income);
    btnShortlist = (Button) itemView.findViewById(R.id.btnshort);
    btnShortlist.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        btnShortlist.setText("Wait...");
        matri_id_to = superHeroes.get(getAdapterPosition()).getMglId();
        shortlist(btnShortlist,position); // change this line

    }
});

}

Comment: In this logic when I clicked on button then above item's button text is changed
Comment: I don't think this would work once the view is recycled.
Comment: you have to move your `onClickListener` in your `ViewHolder`. your `onClickListener` is reinitializing everytime it is created.
Comment: then I try this (shortlist(btnShortlist,getAdapterPosition());) and yet not working
Comment: @M.WaqasPervez please tell me this error I did not resolve yet
Comment: can you update your question with the code you are trying so i can get what you are doing


Gatsby/Wordpress: GraphQLError: Fragment cannot be spread here as objects of type "foo" can never be of type "bar"

Question: I am using GraphQL to pull information from custom ACF fields in Wordpress onto my Gatsby site. My query originally queried three ACF fields (ImageRow, TextRow and ImageTextRow), however I then deleted the first two rows and removed them from the query. I then. added a new row called HeroRow, however since then I have been getting this error:
ERROR #85901  GRAPHQL

There was an error in your GraphQL query:

Fragment cannot be spread here as objects of type "WPGraphQL_Page_Customcontentblocks" can never be of
type "WPGraphQL_Page_Customcontentblocks_Customcontentblocks_HeroRow".

File: gatsby-node.js:82:28

My query is as follows:
    query {
        wpgraphql {
            pages(first: 5000, where: {status : PUBLISH}){
                nodes {
                    title
                    uri
                    status
                    content
                    customContentBlocks {
                      customcontentblocks {
                        ... on WPGraphQL_Page_Customcontentblocks_Customcontentblocks_ImageTextRow {
                            fieldGroupName
                            version
                            imageV1 {
                                sourceUrl
                            }
                            titleV1
                            subtitleV1
                            textV1
                            linksV1 {
                                links {
                                  target
                                  title
                                  url
                                }
                              }
                            imageV2 {
                                sourceUrl
                            }
                            titleV2
                            subtitleV2
                            textV2
                            listV2 {
                                listItem
                            }
                            ctaV2 {
                                target
                                title
                                url
                            }
                          }
                        }
                        ... on WPGraphQL_Page_Customcontentblocks_Customcontentblocks_HeroRow {
                            fieldGroupName
                            title
                            image {
                              sourceUrl
                            }
                            links {
                              link {
                                target
                                title
                                url
                              }
                            }
                        }
                    }
                }
            }
        }
    }

I am able to query the ImageTextRow without issue if I query it alone, but whenever the HeroRow is included I get the same error message.
I have set up my HeroRow layout in the same way as my ImageTextRow layout (both are siblings and sit under the customContentBlocks field group), so I would expect the query to work the same for both.
I have also tested the query on the Wordpress end using the GraphiQL IDE and the query works fine on the Wordpress end, the problem just seems to be on the Gatsby end.
Answer: I managed to resolve this issue, however I'm not entirely sure why this fixed it:
By chaging the order of the different layouts in my query so that the offending layout (HeroRow) was NOT the last one in the query, everything worked fine:
    query {
        wpgraphql {
            pages(first: 5000, where: {status : PUBLISH}){
                nodes {
                    title
                    uri
                    status
                    content
                    customContentBlocks {
                      customcontentblocks {
                        ... on WPGraphQL_Page_Customcontentblocks_Customcontentblocks_HeroRow {
                            fieldGroupName
                            title
                            image {
                              sourceUrl
                            }
                            links {
                              link {
                                target
                                title
                                url
                              }
                            }
                        }
                        ... on WPGraphQL_Page_Customcontentblocks_Customcontentblocks_ImageTextRow {
                            fieldGroupName
                            version
                            imageV1 {
                                sourceUrl
                            }
                            titleV1
                            subtitleV1
                            textV1
                            linksV1 {
                                links {
                                  target
                                  title
                                  url
                                }
                              }
                            imageV2 {
                                sourceUrl
                            }
                            titleV2
                            subtitleV2
                            textV2
                            listV2 {
                                listItem
                            }
                            ctaV2 {
                                target
                                title
                                url
                            }
                          }
                        }
                    }
                }
            }
        }
    }

I have since added multiple subsequent rows and all is working as expected.


JQUERY ajax passing value from MVC View to Controller

Question: What I want is to pass the value of txtComments from View (using jquery/ajax) to Controller.
The problem is the ajax/jquery doesn't accept script tags as string. Meaning, when I input any script/html tag in the txtComments the ajax goes to the error function and not being able to go in the controller.
Here is the jQuery:
        $('#btnSaveComments').click(function () {
            var comments = $('#txtComments').val();
            var selectedId = $('#hdnSelectedId').val();

            $.ajax({
                url: '<%: Url.Action("SaveComments")%>?id=' + selectedId + '&comments=' + escape(comments),
                type: "post",
                cache: false,
                success: function (savingStatus) {
                    $("#hdnOrigComments").val($('#txtComments').val());
                    $('#lblCommentsNotification').text(savingStatus);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    $('#lblCommentsNotification').text("Error encountered while saving the comments.");
                }
            });
        });

Here is the controller:
        [HttpPost]
        public ActionResult SaveComments(int id, string comments){
             var actions = new Actions(User.Identity.Name);
             var status = actions.SaveComments(id, comments);
             return Content(status);
        }

I also tried $('#txtComments').serialize() instead of escape(comments) but still the same.
Comment: i am facing the same issue!  how did you solve it?
Answer: Try using the data option of the $.ajax function. More info here.
$('#btnSaveComments').click(function () {
    var comments = $('#txtComments').val();
    var selectedId = $('#hdnSelectedId').val();

    $.ajax({
        url: '<%: Url.Action("SaveComments")%>',
        data: { 'id' : selectedId, 'comments' : comments },
        type: "post",
        cache: false,
        success: function (savingStatus) {
            $("#hdnOrigComments").val($('#txtComments').val());
            $('#lblCommentsNotification').text(savingStatus);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#lblCommentsNotification').text("Error encountered while saving the comments.");
        }
    });
});

Comment: thanks! it worked. i just revised the code to data:{ 'id': selectedId, 'comments': escape(comments)} so jquery/ajax will accept it.
Comment: @tobias86 I have 30+ parameters, should I do the same thing as you have presented? I tried using an object and use JSON.stringify. However, sometimes it is giving null values. It happens intermittently. So we are trying to eliminate the object parameter and send every parameter one by one to avoid that intermittent issue. Do you have any suggestion to better address this problem? Thanks.
Answer: Here's  an alternative way to do the same call. And your type should always be in CAPS, eg. type:"GET" / type:"POST".
$.ajax({
      url:/ControllerName/ActionName,
      data: "id=" + Id + "&param2=" + param2,
      type: "GET",
      success: function(data){
            // code here
      },
      error: function(passParams){
           // code here
      }
});

Another alternative will be to use the data-ajax on a link.
Click Me!

Assuming u had a div with the I'd _content, this will call the action and replace the content inside that div with the data returned from that action.

Not really a direct answer to ur question but its some info u should be aware of ;).
Answer: $('#btnSaveComments').click(function () {
    var comments = $('#txtComments').val();
    var selectedId = $('#hdnSelectedId').val();

    $.ajax({
        url: '<%: Url.Action("SaveComments")%>',
        data: { 'id' : selectedId, 'comments' : comments },
        type: "post",
        cache: false,
        success: function (savingStatu`enter code here`s) {
            $("#hdnOrigComments").val($('#txtComments').val());
            $('#lblCommentsNotification').text(savingStatus);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#lblCommentsNotification').text("Error encountered while saving the comments.");
        }
    });
});

Answer: View Data
==============

 @model IEnumerable<DemoApp.Models.BankInfo>

    Search Results

@if (!Model.Any())
{

            No Bank(s) found

}
else
{

                @Html.DisplayNameFor(model => model.Name)

                @Html.DisplayNameFor(model => model.Address)

                @Html.DisplayNameFor(model => model.Postcode)

        @foreach (var item in Model)
        {

                    @Html.DisplayFor(modelItem => item.Name)

                    @Html.DisplayFor(modelItem => item.Address)

                    @Html.DisplayFor(modelItem => item.Postcode)

                    <input type="button" class="btn btn-default bankdetails" value="Select" data-id="@item.Id" />

        }

}


Getting flow to pick from a union of tuples

Question: I have a function that returns a union of tuples and it seems like flow is unable to pick one of these tuples no matter what I do.  Example (try flow link):
declare function genNumber(): [Error, null] | [null, number];

const [err, num] = genNumber();

if (err) {
  throw err;
}

// num should now be a number, but I can't convince flow of this
(num: number);

num on the last line should clearly be number but flow still thinks it's null | number.  I have a couple of workarounds, which is to flip the err check to if (!num) {, or to just have the generating function lie and change the return type to [Error, ((null: any): number)] | [null, number] but I honestly hate both of these.
Answer: I think your problem here is destructuring the result, as the analysis can't determine which of the return types applies.  A possible solution is covered in the docs, "Disjoint unions with exact types", you're achieving something similar in your second example (Try it here).
type Success = {| success: false, error: Error |}
type Failure = {| success: true, num: number |}

declare function genNumber(): Success | Failure;

const result = genNumber();

if (!result.success) {
  throw result.error;
}

// num should now be a number
(result.num: number);

Update:
It seems that node style callbacks cannot be handled in flow at present (Github issue).
Here is how a node callback would be defined (Try):
type Completion = (err: ?Error, result: ?number) => void;

function myFunc(done: Completion) {
  done(null, 1);
}

myFunc((err, result) => {
  if (err) throw err;

  if (result) (result: number);

});

And here is how your tuple could be defined (Try):
declare function genNumber(): [?Error, ?number];

const [err, num] = genNumber();

if (err) {
  throw err;
}

if (num) {
  (num: number);
}

Granted that this is still not as clean as you had hoped for.  I couldn't get Flow Try to pass a version of this with Promise as the input and return type, it doesn't seem to like the await keyword (Try).
async function gen<T>(promise: Promise<T> | T): Promise<[?Error, ?T]> {
    return new Promise((resolve, reject) => {
        Promise.all([promise])
            .then(result => resolve([null, result[0]]))
            .catch(e => reject([e, null]));
    });
}

const [ err, num ] = await gen(1);

if (err) throw err;

if (num) (num:number);

Comment: Yeah, I'm pretty sure that flow is through away the tuple information and just keeping `err = Error | null`, `num = null | number` which is a pain.
 Keeping the data in an object or even array works, but I'm trying to find something cleaner as the actual use case is in a very generic utility function
Comment: I'm not sure a tuple is the clearest use in that case, I guess you're aiming for something more concise and that's why you went for destructuring.  If you could combine the `error` and `num` values into the same property, e.g. `result` you might get closer.
Comment: The actual function signature in my case is `function gen(promise: Promise | T): Promise<[Error, null] | [null, T]>`.  It's basically a try/catch wrapper that returns `[err, null]` or `[null, response]`.  Usage is then `const [err, whatever] = await gen(someFnThatReturnsAPromise())`.  Putting this in an object would tie the response and error together, which just seems weird.
Comment: Which begs the question, why not just use `Promise.then()` and `.catch()`?  Or why return a tuple, when a return type of `Error | number` would suffice?  I think if you edited your example to include the full context of what you want to achieve it might help.
Comment: Because I feel it's the best API :)  It's also habit as I'm trying to copy an API that exists in hack (exactly this) and node (to slightly less extent) which accepts callbacks in the form of `(err, resp) => void`.  I also have 5 other similar functions that are meant to handle slightly different intents which is why I'm not just using Promises.  But this is all off-topic.  I'm really just concerned with getting flow to behave with tuple unions, but that might be impossible for now.
Comment: I've updated my answer with some more findings. Nothing seems perfect ;-)


Algorithm for removing a symbol and generating permutations

Question: I have the following char array "AbA" and I want to generate a set of char arrays which represents all possible combinations of removing the char='A' from the initial char array ,so the result will be a set containing "bA","Ab","b" another example is  "AbAbA",then the result will be "bAbA" ,"AbbA" ,"AbAb","bbA" and so on the last element will be bb ( without 3 A's) .How can I create such an algorithm ,what should be the idea?
Comment: Thanks for the specification, whats your question?
Comment: My questions is any ideas how to create such an algorithm?
Comment: Welcome to stackoverflow.com. Please take some time to read [the help pages](http://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). Also please [take the tour](http://stackoverflow.com/tour) and [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). Lastly please learn how to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve).
Comment: I also recommend you read [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/), as well as all of http://idownvotedbecau.se/ to learn some reasons you will get negative votes.
Comment: I'd use a `std::set`, and put all the suitable permutations in that.
Answer: You can use a backtrack algorithm and using a for loop remove each appearance of the pattern character in the original string and check if the found string has been created before, if not print it and run the backtrack algorithm on the string with the found character omitted from it.
<code>#include <iostream>
#include <string>
#include <set>

using namespace std;

set <string> combinations;

inline void back_track_character_remover (string orig, char pat){

    for (int i=0 ; i<orig.size()-1 ; i++){
        if (orig[i]==pat){ // find each appearance of pattern on original string
            int t = combinations.size();
            string new_orig = orig.substr(0,i)+orig.substr(i+1,orig.size()-i-1); // create new string with the found pattern omitted
            combinations.insert(new_orig);
            if (combinations.size()!=t){ // check if adding the new string makes a new permutation
                cout << new_orig << endl; // print new combination
                back_track_character_remover(new_orig,pat); // checl new string to find other appearances of pattern
            }
        }
    }
    // for easier use of for loop check last element separately
    int t = combinations.size();
    if (orig[orig.size()-1]==pat){
        string new_orig = orig.substr(0,orig.size()-1);
        combinations.insert(new_orig);
        if (combinations.size()!=t){
            cout << new_orig << endl;
            back_track_character_remover(new_orig,pat);
        }
    }
}

int main(){

    string original;
    char pattern;
    cin >> original >> pattern;
    combinations.empty();
    cout << original << endl;
    back_track_character_remover(original,pattern);

}
</code>


Android camera intent never returns to app

Question: I have a very frustrating problem. Im using android camera intent to launch the video camera and record a video.
What I expect: When I press stop I want to return to my apps activity via the onActivityResult to do some stuff like display a thumb image of the video recording etc.
What is happening: When i press stop the screen flashes as if returning to the app but then simply keeps on displaying the camera. I have put a log inside onActivityResult and it never calls back here! Please note, this is not the issue where the intent data == null. This is an issue where the method is never called at all. When i look inside my media directory the video file is in fact there so the recording did take place and stored the file there.
What im doing:
    I am calling the camera intent from a button click inside my activity:
public class MainActivity extends Activity {

  public void startVideo(){
    //set the path
    String fileName = "MyVid_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".mp4";
    File externalFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), fileName);
    Uri videoUri = Uri.fromFile(externalFile)

    //setup up the video intent
    Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
    takeVideoIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, maxStorage); //set the max file size - variable calculated elsewhere
    takeVideoIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,   Configuration.ORIENTATION_LANDSCAPE); //set the camera orientation
    takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, CamcorderProfile.QUALITY_480P); //set the camera resolution
    takeVideoIntent.putExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, true); //set the camera btns

    //start the intent
    if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takeVideoIntent, VIDEO_INTENT);
    }
  }

  //then i have the onActivtyResult - this part is never called, regardless of whether data is null or not
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      Log.d("***1 LOG onActivityResult - requestCode: ", String.valueOf(requestCode));
  }

}

My permissions are as follows:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-feature android:name="android.hardware.camera" android:required="true" />

And my activity that launches the intent is declared as a portrait view in the manifest, although the camera intent is set as landscape in the code as earlier showed:
<activity
        android:theme="@style/AppTheme"
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait">
</activity>

I am doing something similar for still photos which works like a charm. This code also works fine on the emulator, but when testing on my device (Galaxy S3) it gives this behaviour and only for video. I have searched high and low for a solution but cant find anything, any advice , pointers or links would be greatly appreciated!!
Comment: I have found a solution of this issue, please follow the link: http://stackoverflow.com/a/36640559/3819836
Answer: If you're calling it from a Fragment override the Fragment.onActivityResult() from the Fragment, otherwise you should expect it from the Activity.onActivityResult(). For debug purposes, add logs to both.
And on the Activity one don't forget to call super.onActivityResult() otherwise it might supress the one from the Fragment.
Comment: Thank you very much for your response. My code sits inside of an activity MainActivity, so i am not calling it from a fragment at this stage although I will defo keep in mind what you've said once I refactor. At this stage I'm just struggeling to get the app running in its most basic form. Will amend my question to reflect the activity


How to prevent Method calls from Unknown addins

Question: I have a core set of libs(framework) built on top of prism and it loads other modules built by other 3rd parties which should use the "recommended" approach but there's no inbuilt mechanism ( as far as i can tell ) to prevent any 3rd party code to use methods which are meant for internal/core use only.
Is there a pattern to check for assembly of the calling code and verify it to contain some known signature perhaps ?
This is for prism but i suppose would apply to any DI/IoC framework where certain methods are internal only
Comment: You may want to consider using a different container for your 3rd party addins; this way your plugins can't import internal services, as your plugin container won't be configured to provide them.  This assumes, of course, that you're splitting up internal services into their own classes (or at least interfaces).
Answer: Methods for internal use should be marked internal, and therefore invisible to the third-party callers.  If you need to share methods across your own assemblies, use the InternalsVisibleToAttribute.
EDIT
To make members unavailable to third-party assemblies, mark the members internal.  This prohibits access by third-party assemblies.  I mentioned the InternalsVisibleToAttribute because of the possibility that

your internal code comprises more than one assembly
you have marked some members public to provide inter-assembly access, but you don't want third-party code to have access to these members.

Example:
code for MyAssemblyA:
public static class SomeClass
{
    //this method is public because I want to be able to use it in MyAssemblyB
    public static void SomeMethodThatShouldBeInternal()
    {

    }
}

code for my MyAssemblyB:
public class Program
{
    public static void Main()
    {
        SomeClass.SomeMethodThatShouldBeInternal();
    }
}

To prevent third-party code from having access to SomeMethodThatShouldBeInternal(), change the declaration:
public static class SomeClass
{
    internal static void SomeMethodThatShouldBeInternal()
    {

    }
}

Now, MyAssemblyB will not compile!  However, you can fix that by adding this attribyute to MyAssemblyA:
[assembly: InternalsVisibleTo("MyAssemblyB")]

Comment: That's the opposite of what is asked, excerpt - Specifies that types that are ordinarily visible only within the current assembly are visible to a specified assembly.
From here http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx
Comment: @Kumar I mentioned `InternalsVisibleToAttribute` in case you made your members public for internal access.  See edited answer for details.
Comment: oh i see, that might work except for DI via MEF, will look into it, thx


transition not working in toggleclass while adding in table

Question:

    <button id="but">Button</button>

        <colgroup>
            <col></col>
            <col></col>
        </colgroup>

            Month
            Savings

            January
            $100

In this above example transition not working while adding toggle class
  in jquery in table.please help me how to do that.please don't change
  structure.

Fiddle Link
Comment: You don't need to check if it has class before doing a toggleClass as that will automatically remove the class if it's there and add it if it's not.
Answer: You have to have a set width to begin with, here is an example: JSFiddle
table col {
    width: 75px; /* added this */
    -webkit-transition:width .8s ease;
    ...

Alternatively, you could use jQuery's animate() to change the width, in this case you would remove the css transitions: JSFiddle
if ($col.hasClass("expanded")) {
    $col.removeClass('expanded');
    $col.animate({"width": ""}, "slow");
} else {
    $('table col').addClass('expanded');
    $col.animate({"width": "200px"}, "slow");
}

As for your edit to using toggleClass, part of the reason it wasn't working was because you didn't source jQueryUI... the other part seems to be that it doesn't work with col. It works if I add a width on the table, see here... or on the td which should have the same affect you want, see here.
Comment: this is my structure how to give transition for that
Comment: @PradeepKumar, like I mentioned at the end of my answer, you can use `td` in place of `col`, see here http://jsfiddle.net/psn2kt5n/10/


For $(G,X)$ - manifolds can we assume $X$ is simply connected?

Question: This is based on my rough understanding, so let me know which part if any is wrong. Suppose $M$ is a $(G,X)$-manifold, where $X$ is a homogeneous $G$-space. Pullback a $(G,X)$ structure from $X$ to its universal cover $\widetilde{X}$. The $(G,X)$-automorphisms $\mathrm{Aut}(\widetilde{X})$ form a Lie group acting transitively on $\widetilde{X}$, making it a homogeneous $\mathrm{Aut}(\widetilde{X})$-space. There is a surjective homomorphism $\phi:\mathrm{Aut}(\widetilde{X})\to G$ pushing down automorphisms whose kernel is equal to the deck transformations of $\widetilde{X}$. The map $\widetilde{X}\to X$ is equivariant with respect to $\phi$ and the group actions from $\mathrm{Aut}(\widetilde{X})$ and $G$. Because of this any $(\mathrm{Aut}(\widetilde{X}),\widetilde{X})$-manifold is automatically a $(G,X)$-manifold. Finally, each $(G,X)$ structure on $M$ lifts to a unique $(\mathrm{Aut}(\widetilde{X}),\widetilde{X})$ structure on $M$ making the correspondence bijective.
If the argument is correct, I would appreciate it if someone could point me to a source where it is stated that $(G,X)$ structures are in one to one correspondence with $(\mathrm{Aut}(\widetilde{X}),\widetilde{X})$ structures, or something similar.
Comment: All what you wrote is correct, but your ultimate question is unclear. What is supposed to work? The construction of a simply connected homogeneous space? (Then of course, you just proved it.) Something else?
Comment: I do not know a reference but try to prove it. There is a natural correspondence, you just have to check that it is a bijection.
Comment: @MoisheKohan I think you've answered my question. I apologize that my goal was unclear, I was hoping to show that their is a one-to-one correspondence between $(G,X)$ structures and $(\mathrm{Aut}(\widetilde{X}),\widetilde{X})$ structures. Do you happen to know a source where this is worked out in more detail?
Answer: Here's a partial proof in terms of developing maps. Let's take for granted that
$(\mathrm{Aut}(\widetilde{X}),\widetilde{X}))$ is a homogeneous space. Let $\mathrm{dev}:\widetilde{M}\to X$ be a developing map. From the universal property, there exists a lift $\widetilde{\mathrm{dev}}:\widetilde{M}\to \widetilde{X}$ of the developing map to the universal cover. It suffices to show the existence of a developing map $\widetilde{h}:\pi_1(M)\to \mathrm{Aut}(\widetilde{X}).$ That is, for each deck transformation $\gamma\in \pi_1(M)$ we have to prove the existence of a transformation $\widetilde{h}(\gamma)\in \mathrm{Aut}(\widetilde{X})$ such that $\widetilde{h}(\gamma)\circ \widetilde{\mathrm{dev}}=\widetilde{\mathrm{dev}}\circ \gamma$.
Let $\pi:\widetilde{X}\to X$ be the projection, and let $h:\pi_1(M)\to G$ be the holonomy representation for the $(G,X)$ structure. By the universal property, there exists an automorphism $\sigma:\widetilde{X}\to \widetilde{X}$ such that  $\pi \circ \sigma = h(\gamma)\circ  \pi.$ Then
$$
\pi \circ \sigma \circ \widetilde{\mathrm{dev}}
=h(\gamma)\circ \pi \circ \widetilde{\mathrm{dev}}
=h(\gamma)\circ \mathrm{dev}
=\mathrm{dev}\circ \gamma
=\pi \circ \widetilde{\mathrm{dev}}\circ \gamma.
$$
Since $\sigma \circ \widetilde{\mathrm{dev}}$ and $\widetilde{\mathrm{dev}}\circ \gamma$ both lift the same map, they must be related by a deck transformation $\phi$ of $\widetilde{X}$. Then
$$
(\phi \circ \sigma)\circ \widetilde{\mathrm{dev}}
=\widetilde{\mathrm{dev}}\circ \gamma,
$$
so we can define $\widetilde{h}(\gamma)=\phi \circ \sigma$.

This $(\mathrm{Aut}(\widetilde{X}),\widetilde{X})$ structure induces the appropriate $(G,X)$ structure on $M$ because $\pi \circ \widetilde{\mathrm{dev}}=\mathrm{dev}$ by definition. Any other developing map $\widetilde{M}\to \widetilde{X}$ lifting $\mathrm{dev}$ must be separated from $\mathrm{dev}$ by a deck transformation of $\widetilde{X}$. Any deck transformation is an automorphism of $\widetilde{X}$, so this other developing map induces the same $(\mathrm{Aut}(\widetilde{X}),\widetilde{X})$ structure on $M$.


Problems with permissions in apache Ubuntu 13.10

Question: I have had some problems with setting up my localhost.
I have been following this guide --> how-do-i-set-up-a-local-domain-name-in-apache-and-ubuntu
But now I'm stuck my localhost only returns a 403 error so there is some problems with my permissions but i have no idea of what it should be..
Any help would be greatly appreciated.
Regards Peter
Comment: Please show relevant lines of /var/log/apache2/error.log or if you have set one in the vhost config the matching errorlog of your domain. Also: Do you get any errors when you restart apache2?
Answer: Let's say your webserver runs as the user www-data and that your site's document root is /var/www/blah.
Check that the www-data user has permissions to enter /var/www/blah with:

As root, run su - www-data then cd /var/www/blah. If this returns a permission denied error, your permissions to one of the directories in the path are set incorrectly. Fix with chmod +x /var/.....
Again, as root run: date > /var/www/blah/date.txt; chmod +r /var/www/blah/date.txt. Can you access http://yourdomain.com/date.txt ? If you can, your virtualhost is probably configured with directory indexing disabled and most likely it tries to find an index.html, index.htm, index.php, etc. and when it fails, it throws an HTTP/403.
Comment: Thank you for the answer!

I can creat the file and chmod it but i still can't access it thru my browser, I've also tried to create an index.html with the same method with the same result
Comment: Were you able to enter the document root directory as the user that the webserver runs as (typically www-data)?
Comment: I think I was, sorry I'm not the most experienced ubnutu user (been at it for about 4 month) but I ran these commands in my terminal

su root
su - www-data

the whoami-command returned www-data
and when I cd into my sites folder (/home/username/Sites/pl) I'm not reciving any permissionerrors


"Ambiguous column name" exception when using order-by in collection mapping

Question: Consider this class that represents a node in a hierarchical structure:
public class Node
{
    public Node()
    {
        Children = new List<Node>();
    }

    public virtual int Id { get; set; }

    public virtual IList<Node> Children { get; set; }

    public virtual Node Parent { get; set; }

    public virtual int Position
    {
        get { return Parent == null ? -1 : Parent.Children.IndexOf(this); }
        set { }
    }
}

The mapping looks like this (as NHibernate does not support lists in bidirectional associations, I use a bag here and have the children determine their position automatically):
<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" namespace="AmbiguousColumn" assembly="AmbiguousColumn" xmlns="urn:nhibernate-mapping-2.2">
  <class name="Node">
    <id name="Id" type="Int32">
      <generator class="identity" />
    </id>
    <bag name="Children" inverse="true" cascade="all" order-by="Position">
      <key column="Parent" />
      <one-to-many class="Node" />
    </bag>
    <many-to-one name="Parent" />
    <property name="Position" />
  </class>
</hibernate-mapping>

To get all nodes with their children loaded I'd use a query like this:
var nodes = session.QueryOver<Node>()
                   .Fetch(x => x.Children).Eager
                   .List();

However, executing this results in an exception:

NHibernate.Exceptions.GenericADOException: could not execute query
   [...(sql)...] ---> System.Data.SqlClient.SqlException: Ambiguous column name 'Position'.

The SQL:
SELECT
    this_.Id as Id0_1_,
    this_.Parent as Parent0_1_,
    this_.Position as Position0_1_,
    children2_.Parent as Parent3_,
    children2_.Id as Id3_,
    children2_.Id as Id0_0_,
    children2_.Parent as Parent0_0_,
    children2_.Position as Position0_0_
FROM
    Node this_
left outer join
    Node children2_
        on this_.Id=children2_.Parent
ORDER BY
    Position

I understand why this happens: NH joins the same table twice, but uses the order clause without qualifying the column name.
The question is: how can I make this scenario work? Resorting to  instead of  is probably difficult as I'd like to have a bidirectional relation.
There are a couple of similar question on SO, but nowhere did I find an actual solution.

Update: the error is database/driver specific. Using the Sql Server CE (e.g. SqlServerCeDriver and MsSqlCe40Dialect) I get the proper query. Using Sql Server (e.g. Sql2008ClientDriver and MsSql2012Dialect) produces the unqualified queries.
According to my own tests, this behavior still exists in the master branch on github.
A gist with a test case: https://gist.github.com/anonymous/5377535
Answer: I think I found the cause of the problem and viable workarounds:
The cause of the issue is the fact that the column is called "Position", which is a reserved word in ODBC according to http://msdn.microsoft.com/en-us/library/ms189822.aspx
This combined with the fact that the default value for NH's hbm2ddl.keywords property is set to "keywords" somehow caused NH not to qualify the order-by clause, probably because it though "Position" was a keyword, not a column.
http://nhforge.org/blogs/nhibernate/archive/2009/06/24/auto-quote-table-column-names.aspx
Ways to fix it:
1) Use a different name for the property - one that isn't a keyword. In this case, PositionInParent would have worked without any issues.
2) Quote the order by clause properly using back-ticks.
<bag name="Children" inverse="true" cascade="all" order-by="`Position`">

Or whatever it takes in your mapping API of choice, e.g. in mapping by code:
cls.Bag(x => x.Children,
        map =>
        {
            map.Inverse(true);
            map.Cascade(Cascade.All);
            map.Key(key => key.Column("Parent"));
            map.OrderBy("`Position`"); // note that you must not use a lambda expression in this case
        },
        map => map.OneToMany());

3) Disable keyword auto import, ie. set hbm2ddl.keywords to none (neither keywords nor auto-quote will work):
<property name="hbm2ddl.keywords">none</property>

Or programmatically:
config.DataBaseIntegration(db => db.KeywordsAutoImport = Hbm2DDLKeyWords.None);

You can still auto-quote reserved words by calling SchemaMetadataUpdater.QuoteTableAndColumns just before building the session factory.
SchemaMetadataUpdater.QuoteTableAndColumns(config);

I'll stick with approach 3 for now as it is the most painless so far.
Comment: Damn. The NHibernate test project has `none` by default. This why I thought it was a bug. I've deleted my answer as it was wrong.
Comment: @penfold Don't worry, your answer led my efforts to the right direction. Without your "wrong" answer, I probably wouldn't have played with the NH source. I wrote a unit test inside the NH source which to my surprise didn't fail. I checked any differences between their test setup and my test app and found hbm2ddl.keywords to be different.


iOS Custom View Size Inside UINavigationController When Toolbar Shown

Question: I have a pretty straightforward setup: A UINavigationController with setToolbarHidden NO. So the container for the custom view inside the stuff owned by the UINavigationController should be the distance from the bottom of the navigation bar to the top of the toolbar.

However, what I get is (as you might be able to glean from the screen shot by looking through the translucent toolbar) the distance from the bottom of the nav bar to the bottom of the screen.
I've set the autoresizingMask to UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth in my viewDidAppear, but it never gets the "right" answer that takes the toolbar height into account. I can calculate the toolbar height and subtract it from the view height, resetting the height of the custom view, but the real problem re-emerges when the device is rotated. This seems like an autoresize kind of problem and I'm baffled why the toolbar isn't taken into account.
Any tips how to have the custom view resize, taking the space the toolbar occupies into account?
A couple of notes:

I am creating all of this programmatically, not using IB
I've examined it in Symbiote, which is very reliable (at least for me) and it verifies what I can see and measure via NSLog output

I see apps doing this all the time, so I feel like I must be missing something.
Code:
// Code translated from RubyMotion

view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
self.tableView = [[UITableView alloc] initWithFrame:view.bounds style:UITableViewStylePlain];
self.tableView.accessibilityLabel = @"events table";
self.tableView.backgroundColor = [UIColor whiteColor];
[self.tableView setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth];

self.tableView.dataSource = self;
self.tableView.delegate = self;
self.tableView.tableHeaderView = searchBar; // assume I created a searchbar

[self.view addSubview:self.tableView];

Thanks in advance.
Comment: Can you post the code used to create this views? Maybe there's a bug there...
Comment: could you log the frame of your view and the frame of the tableview? just to know what they are exactly
Comment: Here it is (oddly, both are exactly the same size, which is the device size. These loggings are from viewDidAppear:

2013-02-07 12:23:02.021 View frame is # size=#>
2013-02-07 12:23:02.022 Table frame is # size=#>
Answer: When you make the toolbar translucent, the content view is automatically sized to consume the space all the way down to the bottom of the bar, corresponding to the fact that you expect to see something through it.  When you make the toolbar opaque, the content view will be sized to fit in the space denoted by the arrow in your drawing.
So somewhere in your viewDidLoad, you can set:
self.navigationController.toolbar.translucent = NO;

Although really, this should be the default value, so you must be setting it to YES somewhere, if not in this view controller then perhaps in a parent?


Displaying Form Failures Next To Form Fields

Question: This was formed by TonyMancini, but I need help now.  The form does validate, but, it comes up with a new page that looks like
There were 57 errors in your submission, please correct them.
Please enter your first name
There were 57 errors in your submission, please correct them.
Please enter your last name
There were 57 errors in your submission, please correct them.
Please enter your 9 digit social security number
There were 57 errors in your submission, please correct them.
Please enter your phone number
There were 57 errors in your submission, please correct them.
Please enter your address
There were 57 errors in your submission, please correct them.
Please enter your city
etc.
Is it possible to have the errors show up next to my form fields? Or not?
<?php
// Create a dynamic array for the error messages and validate everything before sending them back to the form that shows them
// Here is a sample of your code with the dynamic array built in

$error_msgs = array ();
$error = 0; //Error flag

if ($_POST['first_name']){
$first_name = $_POST['first_name'];
} else {
$error_msgs[] = "Please enter your first name";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['last_name']){
$last_name = $_POST['last_name'];
} else {
$error_msgs[] = "Please enter your last name";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['ssn']){
$ssn = $_POST['ssn'];
} else {
$error_msgs[] = "Please enter your 9 digit social security number";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['phone']){
$phone = $_POST['phone'];
} else {
$error_msgs[] = "Please enter your phone number";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['address']){
$address = $_POST['address'];
} else {
$error_msgs[] = "Please enter your address";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['city']){
$city = $_POST['city'];
} else {
$error_msgs[] = "Please enter your city";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['state']){
$state = $_POST['state'];
} else {
$error_msgs[] = "Please select your state";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['zip']){
$zip = $_POST['zip'];
} else {
$error_msgs[] = "Please enter your 5 digit zip code";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['position']){
$position = $_POST['position'];
} else {
$error_msgs[] = "Please enter position desired, or type N/A if open for discussion";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['wage']){
$wage = $_POST['wage'];
} else {
$error_msgs[] = "Please enter 0.00 if open for discussion";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['Emergencycontactname']){
$Emergencycontactname = $_POST['Emergencycontactname'];
} else {
 $error_msgs[] = "Please enter your emergency contact's name";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['Emergencycontactaddress']){
$Emergencycontactaddress = $_POST['Emergencycontactaddress'];
} else {
 $error_msgs[] = "Please enter your emergency contact's address";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['Emergencycontactcity']){
$Emergencycontactcity = $_POST['Emergencycontactcity'];
} else {
 $error_msgs[] = "Please enter your emergency contact's city";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['Emergencycontactstate']){
$Emergencycontactstate = $_POST['Emergencycontactstate'];
} else {
 $error_msgs[] = "Please select your emergency contact's state";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['Emergencycontactzip']){
$Emergencycontactzip = $_POST['Emergencycontactzip'];
} else {
 $error_msgs[] = "Please enter your emergency contact's 5 digit zip code";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['Emergencycontactphone']){
$Emergencycontactphone = $_POST['Emergencycontactphone'];
} else {
 $error_msgs[] = "Please enter your emergency contact's phone number";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['highest']){
$highest = $_POST['highest'];
} else {
 $error_msgs[] = "Please enter your highest level of education";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['degree']){
$degree = $_POST['degree'];
} else {
 $error_msgs[] = "Please enter N/A if none";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['age']){
$age = $_POST['age'];
} else {
 $error_msgs[] = "Please enter yes or no";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['problems']){
$problems = $_POST['problems'];
} else {
 $error_msgs[] = "Please enter yes or no";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['shiftwork']){
$shiftwork = $_POST['shiftwork'];
} else {
 $error_msgs[] = "Please enter yes or no";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['apprenticeship']){
$apprenticeship = $_POST['apprenticeship'];
} else {
 $error_msgs[] = "Please enter yes or no";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['disabilities']){
$disabilities = $_POST['disabilities'];
} else {
 $error_msgs[] = "Please enter yes or no";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['ifyes']){
$ifyes = $_POST['ifyes'];
} else {
 $error_msgs[] = "If you answered no to above question, type N/A";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['accommodate']){
$accommodate = $_POST['accommodate'];
} else {
 $error_msgs[] = "Type N/A if you answered N/A for above question";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['experience']){
$experience = $_POST['experience'];
} else {
 $error_msgs[] = "Please enter yes or no";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['ifyes2']){
$ifyes2 = $_POST['ifyes2'];
} else {
 $error_msgs[] = "If you answered no to above, type N/A, otherwise describe";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['cname']){
$cname = $_POST['cname'];
} else {
 $error_msgs[] = "Please enter company name";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['caddress']){
$caddress = $_POST['caddress'];
} else {
 $error_msgs[] = "Please enter company address";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['cphone']){
$cphone = $_POST['cphone'];
} else {
 $error_msgs[] = "Please enter company phone number";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['ccperson']){
$ccperson = $_POST['ccperson'];
} else {
 $error_msgs[] = "Please enter company contact person's name";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['ctype']){
$ctype = $_POST['ctype'];
} else {
 $error_msgs[] = "Please enter type of work";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['cwage']){
$cwage = $_POST['cwage'];
} else {
 $error_msgs[] = "Please enter wage earned";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['cstart']){
$cstart = $POST['cstart'];
} else {
 $error_msgs[] = "Please enter date started";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['cend']){
$cend = $POST['cend'];
} else {
 $error_msgs[] = "Please enter date ended";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['reason']){
$reason = $_POST['reason'];
} else {
 $error_msgs[] = "Please enter reason for leaving";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['cname2']){
$cname2 = $_POST['cname2'];
} else {
 $error_msgs[] = "Please enter company name or type N/A";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['caddress2']){
$caddress2 = $_POST['caddress2'];
} else {
 $error_msgs[] = "Please enter company address or type N/A";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['cphone2']){
$cphone2 = $_POST['cphone2'];
} else {
 $error_msgs[] = "Please enter company phone number or type N/A";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['ccperson2']){
$ccperson2 = $_POST['ccperson2'];
} else {
 $error_msgs[] = "Please enter company contact person's name or type N/A";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['ctype2']){
$ctype2 = $_POST['ctype2'];
} else {
 $error_msgs[] = "Please enter type of work or type N/A";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['cwage2']){
$cwage2 = $_POST['cwage2'];
} else {
 $error_msgs[] = "Please enter wage earned or type 0.00 if N/A";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['cstart2']){
$cstart2 = $POST['cstart2'];
} else {
 $error_msgs[] = "Please enter date started or type N/A";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['cend2']){
$cend2 = $POST['cend2'];
} else {
 $error_msgs[] = "Please enter date ended or type N/A";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['reason2']){
$reason2 = $_POST['reason2'];
} else {
 $error_msgs[] = "Please enter reason for leaving or type N/A";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['cname3']){
$cname3 = $_POST['cname3'];
} else {
 $error_msgs[] = "Please enter company name or type N/A";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['caddress3']){
$caddress3 = $_POST['caddress3'];
} else {
 $error_msgs[] = "Please enter company address or type N/A";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['cphone3']){
$cphone3 = $_POST['cphone3'];
} else {
 $error_msgs[] = "Please enter company phone number or type N/A";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['ccperson3']){
$ccperson3 = $_POST['ccperson3'];
} else {
 $error_msgs[] = "Please enter company contact person's name or type N/A";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['ctype3']){
$ctype3 = $_POST['ctype3'];
} else {
 $error_msgs[] = "Please enter type of work or type N/A";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['cwage3']){
$cwage3 = $_POST['cwage3'];
} else {
$error_msgs[] = "Please enter wage earned or type 0.00 if N/A";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['cstart3']){
$cstart3 = $POST['cstart3'];
} else {
$error_msgs[] = "Please enter date started or type N/A";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['cend3']){
$cend3 = $POST['cend3'];
} else {
$error_msgs[] = "Please enter date ended or type N/A";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['reason3']){
$reason3 = $_POST['reason3'];
} else {
$error_msgs[] = "Please enter reason for leaving or type N/A";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['maywe']){
$maywe = $_POST['maywe'];
} else {
$error_msgs[] = "Type names of companies you do not want us to contact, or type, ok all";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['additional']){
$additional = $_POST['additional'];
} else {
$error_msgs[] = "Type N/A if you do not have any additional information";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['electronicsignfn']){
$electronicsignfn = $_POST['electronicsignfn'];
} else {
$error_msgs[] = "Please enter your full name";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['electronicsignssn']){
$electronicsignssn = $_POST['electronicsignssn'];
} else {
$error_msgs[] = "Please enter your 9 digit social security number";
$errors++; //Flag to let the code know that there are errors, used in every case
}

if ($_POST['emailaddress']){
$emailaddress = $_POST['emailaddress'];
} else {
$error_msgs[] = "Please enter your email address";
$errors++; //Flag to let the code know that there are errors, used in every case
}

// Finally at the end, check to see if there are any errors and display them all
if ($errors > 0) {
// Display your error array
foreach (    $error_msgs as &$msg) {
echo "There were " . $errors . " errors in your submission, please correct them.
";
echo $msg . "
";
}
} else {
// Add code here to submit the form however you'd like
}
?>

Answer: Your conditional tests are most likely going to evaluate to false everytime.  You probably need to test with isset() or empty() like this:
if (isset($_POST['field'])) {
    // a value was posted
} else {
    // error
}

or
if (!empty($_POST['field'])) {
    // a value was posted
} else {
    // error
}

It is possible to have the errors show up next to your input fields, but you need to work on first things first, which is to get your form working correctly.
Comment: I mean it works great, but the error message(s) show up on a new page and you have to click the back button, but then you might now remember the errors you needed to fix.
Comment: I will add that I'm not very fluent with programming language, in fact, I suck at it.


How can I register The Witcher 2 and get the Troll Trouble DLC?

Question: I just started up the game launcher and saw that the "Troll Trouble" DLC is free if you register the game.  If I try to register through the launcher menu, I get this error:

Connection error. Try again later.

I also tried to register through the website, but both the Register and Login links in the top-right of the web page appear to be dead.  (If you view source, the CSS class is "inactive".)
Is there any way I can work around this?
Edit: Now I get the following error:

A connection with the server could not be established.

So it definitely seems to be due to the work they're doing for the patch.
Answer: Hmm, I just found this.  I assume the "second downtime" is occurring now, and they haven't actually posted about it yet.

We are currently updating the servers and preparing for the incoming patch release. We will be posting updates on this issue.
UPDATE: The servers are up but we predict another downtime today. It shouldn't take more than an hour and we will inform about it.

Edit: I was able to register through the launcher later but still cannot sign into the website.  The only DLC available was the Polish voiceovers and subtitles, until I restarted the launcher. Troll Trouble was there and I am downloading it (just ignore the box asking you for a pre-order code and hit "Download").
You can get your preorder stuff using the info in one of their blog posts and you can patch the game using this post if it doesn't update automagically.
Edit 2: Patch 1.2 is out and comes with all of the previous DLC.
Comment: Does this make my question Too Localized?
Comment: Assuming the problem goes away in a couple hours, yes.  You can delete it if that is the case.
Comment: Looks like issues persist, I'll try to keep this answer somewhat current to help other people.


Change the color of x and y axis of a graph from a GUI in MATLAB

Question: I am trying to change the color of a graph I created in MATLAB GUIDE. I initially set the colors of the x-axis and y-axis to be white in GUIDE but whenever I output to the graph, the both axes change color back to the default which is black. This is the code I am using to output my graph :
axes(handles.axes1); % axes1 is the tag for my graph in GUIDE
time = 0:1/fs:(length(handles.x)-1)/fs;
plot(time,handles.x);
title('Original Signal');

I looked at MATLAB documentation but did not find an example related to my problem since it is not the actual graph I want the color change but the x and y axis. Is this possible?
Answer: Calling high level plotting functions like plot() resets the axes properties to their defaults. To preserve your custom properties, use the line() function instead:
axes(handles.axes1);
time = 0:1/fs:(length(handles.x)-1)/fs;
line(time,handles.x);
title('Original Signal');

Answer: Some Research
Thanks to OP's question I have learnt something new today. So, I knew that one can change the XColor of the axes by code too, with the command – set(handles.axes1,'XColor',colorname), where colorname could be any color, like 'r' for red, 'k' for black, etc. So, I would have suggested to use set(handles.axes1,'XColor','w'), but then one has to remember what XColor was set through GUIDE and copy over that information to the associated M-file, which isn't "elegant enough".
My initial idea was to extract that XColor info from Fig-file at the initialization stage of the GUI, which is at GUINAME_ OpeningFcn, save it into the handles structure and use it later on in callback functions through the handles again. I tried to call color_data = get(handles.axes1,'XColor') at the end of this function to get the XColor info as a three element vector. That didn't work as it was giving me [1 1 1] which represents the default color white.
Next obvious thing was to put the color_data extracting command at the start of GUINAME_ OpeningFcn, before handles.output is set inside that function and it worked! Thus, the conclusion is that handles.output = hObject is putting at least Color information to default values.
Back to work
For OP, the steps would be following :
Put this at the start of GUINAME_ OpeningFcn
axes1_XColor = get(handles.axes1,'XColor');
axes1_YColor = get(handles.axes1,'YColor');

handles.axes1_XColor = axes1_XColor;
handles.axes1_YColor = axes1_YColor;

set(handles.axes1,'XColor',handles.axes1_XColor);
set(handles.axes1,'YColor',handles.axes1_YColor);

When plotting inside any function that has handles as one of the inputs, use the following commands after plot
set(handles.axes1,'XColor',handles.axes1_XColor);
set(handles.axes1,'YColor',handles.axes1_YColor);

Thus, for your example it would be –
axes(handles.axes1); % axes1 is the tag for my graph in GUIDE
time = 0:1/fs:(length(handles.x)-1)/fs;
plot(time,handles.x);
title('Original Signal');

set(handles.axes1,'XColor',handles.axes1_XColor);
set(handles.axes1,'YColor',handles.axes1_YColor);

Let's hope it works for you, let us know!
Comment: Yes it worked wonderfully. Thank you very much and for the explanation you gave.


Is the body wrapping div really necessary?

Question: A popular technique to build a set fixed centered layout is wrap everything in the body in a div and set some CSS rules on it, for example:

        all content here

#wrap { width: 850px; margin: 0 auto; }

I was wondering, if there is a reason to add this extra wrapping div, since setting the same CSS rules on the body works. Is it for compatibility with some browsers or just a tradition?
Comment: @PeeHaa a whole bunch, I've tested it on IE6, IE7, IE8, Chrome 15, Opera 11.60, Firefox 4, Firefox 8
Comment: On what browser does it work when setting it on the body?
Comment: indeed you seem to be right. Although the margin doesn't work as wyou would expect. I.e. it seem to function more like padding since the background doesn't apply to it and takes the whole width. Didn't knew that though.
Comment: @PeeHaa I'm sure there are some gotcha, in case I get caught by strange behaviour I will try to add that wrapping.
Comment: Have you looked at my fiddle in the comment on [Robs' answer](http://stackoverflow.com/questions/8721408/is-the-body-wrapping-div-really-necessary#answer-8721493)? I don't think there is a way around that issue. Unless you want to give all (inner) elements a background.
Comment: @PeeHaa saw it now, thanks. Interesting... so it doesn't work as any other div... so wanting to give an inner background would be a case in which the additional wrap is needed.
Answer: No. You do not need a "wrapper" div that so many use because they saw others do so. Use the body for that as you should. Setting CSS properties on the body was a problem in the past but not any longer.
Comment: +1; from experience you're correct but I'd love to see some sources regarding browser support.
Comment: Remember that you can go one step further, and turn `body, div#wrap` into `html, body`. That is to say, whatever you would put in `body` goes to `html`, and whatever was in `div#wrap` would go to `body`.
Comment: @Rob: Mostly `width`/`height` and `padding`/`margin` issues, IIRC. And for the bottom-most element these aren't really relevant properties, anyway.
Comment: @You - I was trying to find something more authoritative cause I know I read one but this was discussed on SO before: http://stackoverflow.com/questions/5800407/is-it-a-good-idea-to-style-the-body-tag
Comment: @BoltClock - True to an extent. There are problems with setting things on the html element but I can't recall what they were.
Comment: [Here](http://www.sitepoint.com/styling-the-html-and-body-elements/)'s an (incomplete) article on browser support in styling `html`/`body` elements. And [here](http://camendesign.com/code/developpeurs_sans_frontieres)'s another interesting article on the subject.
Comment: @You - Ah! Yes. Kroc's article, the second one, is the one I remember.
Comment: @Rob you DO still need a wrapper. If you look at the following [example](http://jsfiddle.net/NP2ES/) you will see that the entire background is red. So it doesn't use (it does, but different) the margin (what you would expect). Tested in Chrome.
Comment: @PeeHaa - Yes. Read the second article linked to by You.
Answer: It might work in some browsers, I don't think it'll work in all of them. Also, it's quite common to set a background on the body, then a separate one on the wrap.
Answer: If you need a specific background for the whole page and a centered container, you can't do otherwise. It also provides a way to use "layers" like lightboxes that need to blur the whole #wrap content.
Answer: To add the extra wrapper enables the body and div to change independently.


Laravel-4 Polymorphic Relationship showing both type with the respective tables

Question: i understand how the polymorphic relations works, but still i don't understood how can i get the results of table morphed associating to the respective tables. Let's go with a example for understand better.
we have the normal example with History, Order, and User table.
History | table
id
historable_id
historable_type
event

Orders | table
id
order

Users | Table
id
fullname

Then let's go with the our polymorphic relationship:
History model
Class History extends Eloquent {
 function historable() {
   $this->morphTo();
 }

}

User model
Class User extends Eloquent {
   function history() {
     $this->morphMany('History','historable');
   }
}

Order model
Class Order extends ELoquent {
  function hisotry() {
    $this->morphMany('History','historable');
  }
}

Now if i want get all the users history i can just do something like that
$user = User::find(1);
foreach ($user->historable as $history) {
  echo "Name:".$user->fullname;
  echo "Event:".$history->event;
}

My question is, how can get both of the history of users and orders in one selection and automatically it associates with the datas belonging?
Example of my expectation of the result:

History

   id
   Category
   Name
   Event

   1
   Order
   SmartPhone
   Bought

   2
   User
   Jhon Smith
   Book SmartPhone

Answer: You can using History class as a normal eloquent model. The historable relation on the History model will return either a User or Order instance.
And for your expected result, code may be like:
$histories = History::all();

foreach ($histories as $history) {
  echo 'ID:' . $history->id;
  echo 'Category:' . ($history->historable instanceof User) ? 'User' : 'Order';
  echo 'Name:' .  ($history->historable instanceof User) ? $history->historable->fullname  : $history->historable->order ;
  echo "Event:".$history->event;
}


x*x != x*x in auto-variable?

Question: How does x * x get changed by storing it in an "auto variable"? I think it should still be the same, and my tests show that the types, the sizes, and the values apparently all are the same.
But even x * x == (xx = x * x) is false. What the hell?
(Note: I know IEEE 754 and how float and double work and their usual issues, but this one baffles me.)
#include <iostream>
#include <cmath>
#include <typeinfo>
#include <iomanip>
using namespace std;

int main() {
    auto x = sqrt(11);
    auto xx = x * x;
    cout << boolalpha << fixed << setprecision(130);
    cout << "   xx == 11           " << (   xx == 11          ) << endl;
    cout << "x * x == 11           " << (x * x == 11          ) << endl;
    cout << "x * x == xx           " << (x * x == xx          ) << endl;
    cout << "x * x == (xx = x * x) " << (x * x == (xx = x * x)) << endl;
    cout << "x * x == x * x        " << (x * x == x * x       ) << endl;
    cout << "types        " << typeid(xx).name() << " " << typeid(x * x).name() << endl;
    cout << "sizeofs      " << sizeof(xx) << " " << sizeof(x * x) << endl;
    cout << "xx           " << xx    << endl;
    cout << "x * x        " << x * x << endl;
}

Here's the output:
   xx == 11           true
x * x == 11           false
x * x == xx           false
x * x == (xx = x * x) false
x * x == x * x        true
types        d d
sizeofs      8 8
xx           11.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
x * x        11.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

Compiled with this:
C:\Stefan\code\leetcode>g++ test4.cpp -static-libstdc++ -std=c++11 -o a.exe

C:\Stefan\code\leetcode>g++ --version
g++ (GCC) 4.8.1
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Comment: Unrelated, but you can print `bools` as `true` or `false` using `std::cout<< std::boolalpha;`. That will save you some code.
Comment: This has nothing to do with `auto`. All your variables are deduced as `double`s, it's just a matter of floating point precision. See e.g. [this](http://stackoverflow.com/questions/14151740/sqrt-perfect-squares-and-floating-point-errors).
Comment: @juanchopanza Thanks, used that now.
Comment: @vsoftco Your link doesn't seem to explain this. Does it really?
Comment: @vsoftco The question there is quite different and none of the answers there explain my issue. Looks like you don't understand my question.
Answer: This is the usual imprecision with doubles.  You don't mention your hardware, but on x86 (32 bit Intel) the temporaries used during calculations are 10 byte long doubles.  The x * x will be one of those, while the xx = x * x will be stored to an 8 byte double before being loaded back into the FPU for the compare.
You may get different results if you turn optimizations on, or build a 64 bit executable.
Comment: Is there any way to get such a 10 byte long double as a variable?
Comment: @StefanPochmann Declare it as a `long double`, but it depends on what your compiler supports.  Some will use 10 bytes for `long double`, others will use 8.  I'm not familiar with g++ to say what it does.
Comment: `long double` worked, now all the comparisons show what I expected (and `sizeof` is 12). Thanks!
Comment: @StefanPochmann: `long double` may be aligned to 4 bytes for performance reasons.
Comment: Check your `FLT_EVAL_METHOD`

x*x != x*x in auto-variable?


Delphi Threading With TRestRequest

Question: I am relatively new to the RestRequest tools. I am hoping somebody has solved the issue of waiting for the async call to finish...
I have a program which makes hundreds of different api calls, the call then processes the result, and passes the result back to the procedure which called the api's execution, which can then continue...
Only problem as always with doing such calls without threading, is that the software hangs until the call is complete... To try and remedy this I changed RESTRequest.Execute; to RESTRequest.ExecuteAsync();, but now my problem is that my code continues without waiting for the restrequest's response.
again to try and bypass this problem I have tried several solutions, even api.RESTRequest.ExecuteAsync().WaitFor; (which throws an error thread error: the handler is invalid (6))
Is there any way at all that I can change the below function to run as a separate thread (only the execute part is important to run in thread)... Basically I just want to show an animated loading icon everytime the function is called, and for the rest of my code to wat until this function completes...
I hope there is a simpler solution than to start using full on multithreading..
Code
function run_api_command():boolean;
begin

  result := false;
  RESTResponse.Content.Empty;
  RESTAdapter.Dataset:= ds_action;
  RESTAdapter.RootElement:= '';

  try
    RESTRequest.ExecuteAsync;

    if(ds_action.Active = false) then ds_action.Active:=true;
    if(ds_action.FieldByName('result').AsString<>'Success') then
      begin
        showmessage(ds_action.FieldByName('result').AsString);
      end
    else
      begin
        RESTAdapter.RootElement:= 'data';
        result := true;
      end;
  except
    on E: Exception do
      begin
        if(e.Message = 'REST request failed: Error sending data: (12007) The server name or address could not be resolved') then
          begin
            if(messagedlg('Could not connect to server. Would you like to retry?', mterror,[mbYes,mbNo],0)=mrYes) then
              begin
                result := run_api_command();
              end;
          end
        else
          begin
            showmessage(RESTResponse.Content);
          end;
      end;
  end;
end;

Answer: ExecuteAsync() runs in a worker thread (the TRESTExecutionThread object that it returns).  However, ExecuteAsync() has an AFreeThread parameter that defaults to True.  As the documentation clearly states:

When the AFreeThread parameter is set to False, this method returns a reference to this execution thread.
Note: If the AFreeThread parameter is set to True, the method returns an invalid reference.

So calling WaitFor() on the returned object pointer will crash by default.
Even if the returned object pointer were valid when AFreeThread=True, calling WaitFor() would still crash.  When a TThread object's FreeOnTerminate property is set to True, the object frees its underlying API handle (as well as destroys itself from memory) when the thread finishes running, which causes WaitFor() to fail with the "handle is invalid" error (or even causes an access violation or similar error).  TThread.WaitFor() has a logic bug 1 that does not handle the case when TThread.FreeOnTerminate=True.
(1 That bug was introduced all the way back in Delphi 6, when TThread was rewritten for Kylix support, and it was never corrected in later versions.)
If you want the caller to wait for a response from the REST server, either:

use Execute() instead of ExecuteAsync(), or at least set AFreeThread=False so you can call WaitFor() (or equivalent, like MsgWaitForMultipleObjects()) on the thread object, and then deal with the consequences of performing a wait in the main UI thread.

use Execute(), but move your entire logic to your own worker thread, and have it sync with the main UI thread as needed.

The better solution is to simply not wait at all, which means redesigning your code flow.  Continue using ExecuteAsync(), but pass it a completion callback that will be called when the request is complete, and let that callback drive the next step in your code.  Don't actively wait for ExecuteAsync() to complete, let it notify you.
procedure run_api_command();
begin
  ...
  RESTRequest.ExecuteAsync(
    procedure
    begin
      if not RESTResponse.Status.Success then
      begin
        // do something ...
      end else begin
        // do something else ...
      end;
    end,
    True
  );
end;

Comment: Can this completion callback be used also in C++ ?
Comment: @truthseeker yes. Note that the callback takes an anonymous procedure, which requires some extra work in C++ but is doable. See [How to Handle Delphi Anonymous Methods in C++](https://docwiki.embarcadero.com/RADStudio/en/How_to_Handle_Delphi_Anonymous_Methods_in_C%2B%2B) for details.
Comment: I managed to write completion handler in C++. Is the code in completion handler needed also in new RAD Studio ? Because from some time there is ACompletionHandlerWithError parameter which I successfully used. Not sure if it is needed to check RESTResponse.Status.Success and if yes in which of the two completion handler (normal and error).
Comment: I am responding to my own question. It is required to check RESTResponse.Status also when error completion handler is present. Some errors do not call error completion handler for example HTTP 400 Bad Request.
Answer: Extending onto Remy's answer...

"but now my problem is that my code continues without waiting for the restrequest's response"

This is the exact purpose of Async requests. You're not supposed to wait, you're supposed to send the request and move on to something else. You're also supposed to provide a callback procedure if you wish to capture the result, but I don't see you doing that in your code.
Synchronous and Asynchronous calls are quite different design architectures which cannot be simply switched between as trivially as you may wish. You can't just change Execute to ExecuteAsync without also re-designing the rest. Execute by nature waits for the response within the calling thread. However, ExecuteAsync by nature spawns the request in a new thread, so that your code can continue while it's doing your work in the background. There is no waiting involved in Async requests - it defies the whole purpose of them.
The most ideal option in your case is to chain one request off of the other's response. Meaning, send your first request only. Once you receive the response, then send your next request from within its response callback.

"...since I want to create the function as a sort of "global api call" function to make coding a bit less..."

That's perfectly fine. You can still have one single main procedure which performs all the work. It's when to make each of these calls which matters here. A button's OnClick event is never the appropriate place to do such a thing, though. The only thing that button should do (since it's in the main UI thread) is initiate a request. If you want your UI to be responsive at all after this point, then that request should spawn a new thread in some way, shape, or form.
In any case though, WaitFor just won't cut it for your request. You want a responsive UI. WaitFor will defy this requirement, and lock up your application's main thread anyway. The whole purpose of doing this work in another thread is to show a "waiting" animation, which will not be animated if your main thread is busy waiting for anything.

EDIT
I actually thought of another possibility. Still spawn your first request only. But instead of "chaining" one request off of the other's response, just do all the rest of the work from within that first request's callback. Since at this point, it's already in a thread, there's not necessarily a need to spawn yet another thread for the next request. Just perform the remainder of what you need after the first request, in the existing thread you've already spawned.

On a side note, this is a very common problem in the modern programming world...
Comment: I know what blindly means, and it's a poor use here.. I still +1 your answer.
Comment: @John I can see the confusion - I merely meant "blindly" as in not immediately watching for the result. Instead, a new thread acts as another "person" to "inform" you of "changes" in the "thread"... In other words, another thread is responsible for doing work, and the calling thread doesn't have to care much about the precise details. They just want results. Think of spawning a new thread as, say, hiring a new employee who can perform a job for you. You give them a task, and you let them go their way to do that task, while you continue with other things.

Delphi Threading With TRestRequest


Gallery CSS into JQuery / Ajax page div

Question: Please someone help me out with this:
I have the gallery html page loaded and getting called in correctly to my mainContent div in my page.  if you go here:
http://dageniusmarketer.com/DigitalWonderland/index-jquery.html
click on portfolio, you will see that the gallery loads, but, the image thumbnails and display is way off. its supposed to look and act like this:
dageniusmarketer.com/DigitalWonderland/pages/Galleriffic/advanced.html
I believe it has everything to do with loading the stylesheet for the gallery into my mainContent div, only that I do not know how to do it.  I may be wrong, but i believe that is the problem.  Could someone view my source and tell me how to fix it so the gallery displays the correct way in my main site?
I also would like to load the home page into the mainContent div upon initial loading of the site.  How do I do this?
Any and all help is appreciated.
Thanks
Answer: When you load the page "Portfolio" into your mainpage (index-jquery.html), the paths to the css and javascript in the loaded html are wrong. They point to non-existend locations.
When I adjusted the paths to <link type="text/css" href="http://dageniusmarketer.com/DigitalWonderland/pages/Galleriffic/css/basic.css" rel="stylesheet"/> and like wise for the other <link> and

Gallery CSS into JQuery / Ajax page div


How do dynamically construct for loop from map values

Question: I have a function which returns Map of String to List i.e Map<String,List<Integer>> here is my piece of code
   Map<String,List<Integer>> myList=new TreeMap<String, List<Integer>>();
      List<Integer> firstList=new ArrayList<Integer>();
      firstList.add(1);
      firstList.add(2);
      firstList.add(3);
      myList.put("1", firstList);
      List<Integer> secodList=new ArrayList<Integer>();
      secodList.add(3);
      secodList.add(4);
      secodList.add(5);
      myList.put("2", secodList);
      for (int i = 0; i < myList.get("1").size(); i++) {
         for (int j = 0; j < myList.get("2").size(); j++) {
            System.out.println(myList.get("1").get(i) +"  "+myList.get("2").get(j));
          }
        }

For the time being i have iterated over the loop since i know there is only 2 entries . But myListMap is growable it might have 3 entries , or even 4 entries how do i dynamically construct the for loop .
Comment: Hint: `myList.entrySet()` returns `Set>`. See https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#entrySet--. Also see: https://stackoverflow.com/questions/46898/how-do-i-efficiently-iterate-over-each-entry-in-a-java-map
Answer: To iterate a Map <key, value> you can use myMap.entrySet (). This method:

Returns a Set view of the mappings contained in this map

more information in the documentation suggested in Daniel Cheung comment
I give two versions of the same solution, one simplified and the other making each step explicit.
lists and map on which to iterate
 /**
 * int lists are created
 **/
List<Integer> firstList=new ArrayList<Integer>();
firstList.add(1);
firstList.add(2);
firstList.add(3);

List<Integer> secodList=new ArrayList<Integer>();
secodList.add(5);
secodList.add(6);
secodList.add(7);

List<Integer> tList=new ArrayList<Integer>();
tList.add(8);
tList.add(9);
tList.add(10);

/**
 * the map is created, the lists of int and keys are added
 **/
Map<String, List<Integer>> myMap=new TreeMap<String, List<Integer>>();

myMap.put("one", firstList);
myMap.put("two", secodList);
myMap.put("three", tList);

1 Explained version
//a set of inputs of type <String, List <Integer>> is created
Set<Map.Entry<String,List<Integer>>> mapAsSet;
//each entry in myMap is assigned
mapAsSet= myMap.entrySet();

//iterates through each entry in the set
for (Map.Entry<String, List<Integer>> entry : mapAsSet) {

    System.out.println(entry);
}

Output
one=[1, 2, 3]
three=[8, 9, 10]
two=[5, 6, 7]

2 Simplified version
//The "entry" set is created and the for iterates through each key and its associated value.
for (Map.Entry<String, List<Integer>> entry : myMap.entrySet()) {

    //with entry.getValue () we access its value, which is the list of int corresponding to each "entry" of the set
    //with .foreach (v-> action) you access each value of the int list corresponding to each "entry" of the for.
    entry.getValue().forEach(j-> System.out.println(entry.getKey() +"  "+ j) );
}

Output
one  1
one  2
one  3
three  8
three  9
three  10
two  5
two  6
two  7

Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: @Federremu it will not work for more than 2 entries
Comment: I edit the answer to make it clearer. The code was tested and works on any number of map elements. Let me know if I misinterpreted your question @Unknown Guy.