text:
Q: How to place popup on item click in a recycle card view? This is my code on  holder.cart I am setting onclick function to get popup menu but I am getting null pointer exception in lines
PopupMenu popup = new PopupMenu(mContext, view);
showPopupMenu(holder.cart);

can any one solve this on clicking holder.cart I should display a popupmenu layout but here I had used menuinflater, I want to change it to layout inflater and display the popup view.
import android.content.Context;
import android.support.v7.widget.PopupMenu;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.view.MenuInflater;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class RecyclerAdapterProducts extends RecyclerView.Adapter<RecyclerAdapterProducts.ViewHolder> {
    //ArrayList<Products> products;
    OnItemClickListener clickListener;
    ArrayList<ImageAndName> imageAndNames;
    private Context mContext;
    //byte[] imz;

    public RecyclerAdapterProducts(ArrayList<ImageAndName> imageAndNames){
        this.imageAndNames=imageAndNames;
        //this.discounts=discounts;
    }

    /*public SimpleRecyclerAdapter(ArrayList<Products> products){
        this.products=products;
    }*/

    class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        // each data item is just a string in this case
        /*public TextView name,offer;
        public TextView price;*/
        public ImageView im;
        public TextView name;
        public TextView part;
        public ImageButton cart;
        public int position;

        public ViewHolder(View v) {
            super(v);
            name = (TextView)v.findViewById(R.id.code);
            part = (TextView)v.findViewById(R.id.textView11);
            part.setTypeface(null, Typeface.BOLD_ITALIC);
            im = (ImageView)v.findViewById(R.id.productImg);
            v.setOnClickListener(this);
            cart = (ImageButton)v.findViewById(R.id.imageView2);

            /*cart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
*/
                   /*// LayoutInflater inflater = LayoutInflater.from(RecyclerAdapterProducts.this);
                    View popupView = LayoutInflater.from(mContext).inflate(R.layout.quantityalertdialog, null);
                    final EditText subEditText = (EditText)popupView.findViewById(R.id.dialogEditText);

                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        *//*builder.setTitle("AlertDialog");
        builder.setMessage("AlertDialog Message");*//*
                    builder.setView(popupView);
                    AlertDialog alertDialog = builder.create();

                    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

                    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

                    builder.show();*/

                    //View popupView = LayoutInflater.from(mContext).inflate(R.layout.quantityalertdialog, null);
             /*   }
            });*/
            //price = (TextView)v.findViewById(R.id.serviceDate);

            //offer=(TextView)v.findViewById(R.id.offer);

        }

        @Override
        public void onClick(View v) {
            clickListener.onItemClick(v, getAdapterPosition());
        }
    }

    public RecyclerAdapterProducts(Context mContext, ArrayList<ImageAndName> imageAndNames) {
        this.mContext = mContext;
        this.imageAndNames = imageAndNames;
    }
    @Override
    public RecyclerAdapterProducts.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.recycler_card_individual_product, parent, false);
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(final RecyclerAdapterProducts.ViewHolder holder,int position) {
        holder.im.setImageResource(imageAndNames.get(position).getIconImageResource());
        holder.name.setText(imageAndNames.get(position).getName());
        holder.part.setText(imageAndNames.get(position).getPartno());
        holder.cart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupMenu(holder.cart);
            }
        });
        holder.position=position;

    }

    private void showPopupMenu(View view) {
        // inflate menu
        PopupMenu popup = new PopupMenu(mContext, view);
        MenuInflater inflater = popup.getMenuInflater();
        inflater.inflate(R.menu.menu_album, popup.getMenu());
        popup.setOnMenuItemClickListener(new MyMenuItemClickListener());
        popup.show();
    }

    class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener {

        public MyMenuItemClickListener() {
        }

        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.action_add_favourite:
                    Toast.makeText(mContext, "Add to Wishlist", Toast.LENGTH_SHORT).show();
                    return true;
                case R.id.action_play_next:
                    //Toast.makeText(mContext, "Play next", Toast.LENGTH_SHORT).show();
                    return true;
                default:
            }
            return false;
        }
    }
        /*final Products pd= products.get(position);
        if (discounts!=null && discounts.size()>0) {
            for (int i = 0; i < discounts.size(); i++) {
                if (pd.getId().equals(((ArrayList)discounts.get(i)).get(0))){
                    ArrayList disc=(ArrayList)discounts.get(i);
                    holder.offer.setVisibility(View.VISIBLE);
                    holder.offer.setText("Buy "+disc.get(1)+" to get "+disc.get(2)+"% discount");
                }
                else {
                    holder.offer.setVisibility(View.GONE);
                }
            }
        }
        holder.name.setText(pd.getName());
        holder.position=position;
        holder.price.setText(pd.getList_price() + "\u20B9");
        if (pd.getId()!=null) {

            new AsyncTask<Integer, Void, ImageModel>() {
                private ViewHolder v;
                private ImageModel img;
                @Override
                protected ImageModel doInBackground(Integer... params) {
                    //v = params[0];
                    final String url = "http://164.164.35.38:443/seis/productTemplateController/getProductImage/"+params[0];
                    RestTemplate restTemplate = new RestTemplate();
                    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
                    img = restTemplate.getForObject(url, ImageModel.class);
                    //byte[] ing=
                    return img;
                }

                @Override
                protected void onPostExecute(final ImageModel result) {
                    //super.onPostExecute(result);.get(0).toString().getBytes()
                    if (result != null && result.getImage()!=null) {
                        //imz=result.get(0).toString().getBytes();
                        // If this item hasn't been recycled already, hide the
                        // progress and set and show the image
                        new AsyncTask<ViewHolder, Void, Bitmap>() {
                            private ViewHolder v;

                            @Override
                            protected Bitmap doInBackground(ViewHolder... params) {
                                v = params[0];
                                Bitmap bm = BitmapFactory.decodeByteArray(android.util.Base64.decode(result.getImage(), 0), 0, android.util.Base64.decode(result.getImage(), 0).length);
                                return bm;
                            }

                            @Override
                            protected void onPostExecute(Bitmap result) {
                                super.onPostExecute(result);
                                if (v.position == position) {
                                    // If this item hasn't been recycled already, hide the
                                    // progress and set and show the image
                                    v.im.setImageBitmap(result);
                                }
                            }
                        }.execute(holder);
                        //v.im.setImageBitmap(result);
                    }
                }
            }.execute(pd.getId());
        }*/

    @Override
    public int getItemCount() {
        return imageAndNames.size();
    }
    public interface OnItemClickListener {
        public void onItemClick(View view, int position);
    }

    public void SetOnItemClickListener(final OnItemClickListener itemClickListener) {
        this.clickListener = itemClickListener;
    }
}

A: You can add those options programmatically without using xml file as below, may be this could help you out.
Here ONE and TWO is showing the index for options which you are giving in popup menu (which is int value actually). Like on 1st position EDIT POST on 2nd position REMOVE POST etc.
1) on holder.cart click open popup menu as below:
private final static int ONE = 1;
private final static int TWO = 2;

PopupMenu popupMenu = new PopupMenu(this, findViewById(R.id.img_detail_information_options));
popupMenu.getMenu().add(Menu.NONE, ONE, Menu.NONE, getResources().getString(R.string.detail_information_edit_post));
popupMenu.getMenu().add(Menu.NONE, TWO, Menu.NONE, getResources().getString(R.string.detail_information_remove_post));
popupMenu.setOnMenuItemClickListener(this);
popupMenu.show();

Above code will show popup like this:- Screenshot


text:
Q: Array of structure pointers pointing to NULL automatically? Do array of structure pointers point to NULL automatically/without being initialized? I would assume not, but it seems to be operating in that manner in the following line of code:
for (np = hashtab[hash(s)]; np != NULL; np = np->next)
np is a structure pointer, and s is a string.
None of the elements in hashtab[] have even been initialized when the loop begins. Every time I run the program the loop terminates immediately because hashtab[] contains NULL
The full code is below.
struct nlist {       /* table entry: */
    struct nlist *next;   /* next entry in chain */
    char *name;           /* defined name */
    char *defn;           /* replacement text */
};

unsigned hash(char *s)
{
    unsigned hashval;

    for (hashval = 0; *s != '\0'; s++)
        hashval = *s + 31 * hashval;
    return hashval % HASHSIZE;
}

/* lookup:  look for s in hashtab */
struct nlist *lookup(char *s)
{
    struct nlist *np;
    for (np = hashtab[hash(s)]; np != NULL; np = np->next)
    if (strcmp(s, np->name) == 0)
        return np;     /* found */
    return NULL;           /* not found */
}

A: calloc() function will initialize the memory with zeroes.
#include <stdio.h>
char array[100]; // - initialized by zeroes
void main(void)
{
    char array2[100]; // - initialized with random values
    static char array3[100]; // - initialized by zeroes and allocate not in the stack
}

A: Since hashtab is global, it is initialized with default values (assuming it's an array and not a dynamically allocated pointer), including NULL for pointer types.  This is only for globals or locals declared static.

A: Well, where is hashtab defined? I don't see its definition in the code you posted.
If hashtab array is an object with static storage duration, then it is guaranteed to be zero-initialized at program startup. Otherwise, it is not initialized at all. All objects with static storage duration are zero-initialized at program startup.
The code you posted suggests that hashtab is defined as an external object, which probably means that it is indeed an array with static storage duration. That explains why it is initialized with null pointers by default.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Should I use "to" in this sentence after the conjunction? I wrote:

How is it possible to be a mother and [to] see your child is being killed in such a horrible way? to see them beating your child's head to a wall until his brain pours out.

The first part of the conjunction "to be" has "to" should I then use "to" before "see"?
What about "to see" in the beginning of the second sentence? Can a sentence begin like that?
And finally, what is the proper verb for "pours out"...
P.S. I am translating the feelings of someone about a book on WW II.

A: Taking your query a bit at a time:
It's not necessary to repeat to but you can do so if you wish.
However, your sentence would read more easily if you omit the word is

How is it possible to be a mother and [to] see your child being killed in such a horrible way?

Other readers might comment that there are no pleasant ways to see your child being killed but that would have nothing to do with grammar.
The second part of your sentence needs to be separated from the first, not by a full stop but a semi-colon (;) if it's to follow on directly.

to see them beating your child's head to a wall until his brain pours out.

This assumes that you have already identified the people you refer to as them
The word child is neuter and while it's quite correct subsequently to use the masculine pronoun his, which identifies the child as a boy, others might prefer to speak of its head or their head. This is just a matter of preference.
The child's head would be beaten (or dashed) against the wall rather than to the wall.
There's nothing wrong with pours out.Even though brains are normally more like a pasta than a liquid, under the circumstances they might well pour out.


text:
Q: Is There A Simple Way to Convert These String Values To Enum? I'm working on a stock trading app that utilizes the broker's dll file and commands to makes requests through the API. The biggest challenge (to me at least) has been figuring out how to give the API the various data types it requires for input. Right now I'm working on some test code that will buy 1 share of a stock. Many of the necessary conversions I've been able to figure out but enum continues to elude me.
        InsertOrderRequest insertOrderRequest = new InsertOrderRequest();
        insertOrderRequest.m_accountNumber = "00000001";
        insertOrderRequest.m_symbolId = Convert.ToUInt64(1900028);
        insertOrderRequest.m_quantity = Convert.ToDouble(1);
        insertOrderRequest.m_orderType = "Market"; //Needs to be enum
        insertOrderRequest.m_timeInForce = "Day"; //Needs to be enum
        insertOrderRequest.m_action = "Buy"; //Needs to be enum
        insertOrderRequest.m_primaryRoute = "AUTO";

You can see the 3 lines that I've marked "Needs to be enum". Now I've gone into the object browser and determined that "Market", "Day", and "Buy" are the appropriate responses but they aren't the right data type. Is there a line of code similar to "Convert.ToDouble()" that will convert these from string to enum? Thanks.

A: If the strings match the name from an enum, you can parse them like this:
(OrderType) Enum.Parse(typeof(OrderType), "Market");

Alternatively, there is also a TryParse version you can use. Both versions have overloads to ignore the case when matching the name.
If the strings do not match the name from an enum, you will have to create your own mapper. Can be done using a simple switch case.


text:
Q: A ps command with the relevant options that shows the state / status of only ONE process I start 2 processes in the background: xeyes and xclock -update 1. When I run this commane: ps T o pid,tty,time,args,state (this for to output state) it lists:
PID TT           TIME COMMAND                     S
   5875 pts/0    00:00:00 bash                        S
   5881 pts/0    00:00:01 xeyes                       S
   5921 pts/0    00:00:00 xclock -update 1            S
   6141 pts/0    00:00:00 sleep 100                   T
   6340 pts/0    00:00:00 ps T o pid,tty,time,args,st R

How can I print out the state for only one process? For instance if I want to print the state of only the xeyes process.

A: The ps command offers several options to enable you to select what is included in the output. I suggest you take a look at man ps to see the options that it exposes.
If you want to list processes by the command name, you can use the -C option.  For example:
$ ps -C xeyes ... other options ...

You can also select a process by its process ID (if you know it already) using the -p option.  For example:
$ ps -p 5881 ... other options ...


text:
Q: How to use bitblt in linux? Can we use bitblt in linux? I saw a bitblt documentation which states that bitblt was developed to handle graphical operations in windows which confuses me that is it possible to use bitblt in linux.

A: If you want to perform the same operation on Linux, that BITBLT performs on Windows (which btw, stands for Bit Boundary Block Transfer), you can use a the blit function provided by a game programming library called Allegro.


text:
Q: Textarea tag makes two rows instead of one in Firefox but works good in Chrome Can anyone enlightened in html explain why despite being explicitly said to make 1 row:
textarea id="textarea1" rows="1" cols="100"

the code produces two in Firefox 30:

Works in Chrome.

A: Firefox always add extra line for the textarea.
you can use CSS to be more precise about the height length.
Or you can also try using this css exxtension for mozilla only handler


text:
Q: Android Search Framework, Custom Search Suggestions I am developing an application that implements a search provider.  The behaviour that I am trying to accomplish is if an item is not found in the database, I want an item to show up in the search suggestions list that says something like
"select to add " + query + " to the database".
I have researched this endlessly, I have read all of the android search framework developer documentation, and I have searched on Google to no avail.
The only thing I could think of to accomplish this was in the database adapter, if no results are found create a MatrixCursor with the string I described above and the query however, this seems a little messy.
I would also somehow need to make it so that this item has a different Action Intent than a normal suggestion, as I need it to take the user to a page to add the item to the database.
This seems like a fairly reasonable thing to include in an application, I am not sure if I am missing something.

A: I figured this out.  I used a MatrixCursor in my suggestions provider.  I just checked if the results from the query were equal to null, if so, I returned the MatrixCursor.  Now this seems very obvious.  Also, in order to make this item do something different than results returned from the database I had add columns for
         SearchManager.SUGGEST_COLUMN_INTENT_ACTION
         SearchManager.SUGGEST_COLUMN_INTENT_DATA

to the matrix cursor.  And then define the Uri and action intent for the result.  Then, in my search activity just add an if for that particular action intent and then start the appropriate activity.  Works great.


text:
Q: Bulk inject doc to elastic search with nanoseconds timestamp I'm trying to use the latest nanoseconds support provided by ElasticSearch 7.1 (Actually after 7.0). Not sure how to do this correctly.
Before 7.0, ElasticSearch only support timestamp for milliseconds, I use the _bulk API to inject documents.
#bulk post docs to elastic search
def es_bulk_insert(log_lines, batch_size=1000):
   headers = {'Content-Type': 'application/x-ndjson'}
   while log_lines:
       batch, log_lines = log_lines[:batch_size], log_lines[batch_size:]
       batch = '\n'.join([x.es_post_payload for x in batch]) + '\n'
       request = AWSRequest(method='POST', url=f'{ES_HOST}/_bulk', data=batch, headers=headers)
       SigV4Auth(boto3.Session().get_credentials(), 'es', 'eu-west-1').add_auth(request)
       session = URLLib3Session()
       r = session.send(request.prepare())
       if r.status_code > 299:
           raise Exception(f'Received a bad response from Elasticsearch: {r.text}')

The log index is generated per day
#ex:
#log-20190804
#log-20190805
def es_index(self):
       current_date = datetime.strftime(datetime.now(), '%Y%m%d')
       return f'{self.name}-{current_date}'

The timestamp is in nanoseconds "2019-08-07T23:59:01.193379911Z" and it's automatically mapping to a date type by Elasticsearch before 7.0.
"timestamp": {
    "type": "date"
},

Now I want to map the timestamp field to the "date_nanos" type. From here, I think I need to create the ES index with correct mapping before I call the es_bulk_insert() function to upload docs.
GET https://{es_url}/log-20190823
If not exist (return 404)
PUT https://{es_url}/log-20190823/_mapping
{
 "properties": {
    "timestamp": {
      "type": "date_nanos"
    }
  }
}
...
call es_bulk_insert()
...

My questions are:
1. If I do not remap the old data(ex: log-20190804), so the timestamp will have two mappings (data vs data_nano), will there be a conflict when I use Kibana to search for the logs?
2. I didn't see many posts about using this new feature, will that hurt performance a lot? Did anyone use this in prod?
3. Kibana not support nanoseconds search before 7.3 not sure if can sort by nanoseconds correctly, will try.
Thanks!

A: You are right: For date_nanos you need to create the mapping explicitly — otherwise the dynamic mapping will fall back to date.
And you are also correct that Kibana supports date_nanos in general in 7.3; though the relevant ticket is IMO https://github.com/elastic/kibana/issues/31424.
However, sorting doesn't work correctly yet. That is because both date (millisecond precision) and date_nanos (nanosecond precision) are represented as a long since the start of the epoche. So the first one will have a value of 1546344630124 and the second one of 1546344630123456789 — this isn't giving you the expected sort order.
In Elasticsearch there is a parameter for search "numeric_type": "date_nanos" that will cast both to nanosecond precision and thus order correctly (added in 7.2). However, that parameter isn't yet used in Kibana. I've raised an issue for that now.
For performance: The release blog post has some details. Obviously there is overhead (including document size), so I would only use the higher precision if you really need it.


text:
Q: How to make grep return value without comma I want to extract a value from a json file so that I can process it and I try that using grep '"USDEUR" currs.json' | cut -d ':' -f 2 but it returns 0.918695, and the json file looks like this:
{
"success":true,
"terms":"https:\/\/currencylayer.com\/terms",
"privacy":"https:\/\/currencylayer.com\/privacy",
"timestamp":1449232988,
"source":"USD",
"quotes":{
  "USDEUR":0.918695,
  "USDGBP":0.660851,
  "USDPLN":3.95815
}
}

So I want to know how to disable the comma so that I can process the value of USDEUR

A: There are a number of ways to do it.  You could pipe your results through any of the following
tr -d ','
cut -d',' -f1
sed -e 's/,//'

A: With pure grep using perl compatible regular expressions (-P option):
grep -Po 'USDEUR":\K.*(?=,)' file

*

*\K will throw away everything till :

*(?=,) will throw away everything after , (including ,)

A: As a general rule of thumb: if you pipe the output of a text tool (grep or sed) through cut you're already doing something wrong. (Suggesting a second cut pipe is even more idiotic…)
sed -n '/"USDEUR"/s/^.*:\(.*\),$/\1/p'

This used sed in "don't echo lines by default" mode (-n) with a POSIX basic regular expression and a substitution, that basically says: on all lines matching ""USDEUR"", replace the entire line by everything between the colon and a trailing comma, then output the line.
This won't match if your line does not have a trailing comma. On the other hand, you seem to know your input is a numeric field, so just exclude commas:
sed -n '/"USDEUR"/s/^.*:\([^,]*\),*$/\1/p'

This replaces everything between a colon and the end of the line that does not contain a colon, and ignores any amount of trailing colons (zero or one, as your input is supposedly valid JSON).
Otherwise, use a JSON parser is the sensible thing to do. You could cobble together more regexes to also catch strings that may contain commas themselves, but… it isn't worth it at some point, usually.

A: Use a JSON parser to parse JSON, for example jq:
$ jq '.quotes.USDEUR' file.json
0.918695

A: Add another cut.
grep '"USDEUR" currs.json' | cut -d ':' -f 2 | cut -d',' -f 1


text:
Q: Find all differences in an array in O(nlogn) where n is the max range of elements Question: Given a sorted array A find all possible difference of elements from A, where each element is an integer in the range [1, ..., n]. Also, you can assume there are no duplicates. So max size of the array will be <= n.
Note: Total possible differences will be in the range of [1, ..., n-1] because of the above constraints.
Example (for N=12):

Input: 1, 6, 10, 12
Output: 2, 4, 5, 6, 9, 11

The question is similar to this one, except n is the no. of elements in that question, not the upper bound of the element.
There's also an answer in the same question, this one: https://stackoverflow.com/a/8455336/2109808
This guy claims it can really be done in O(nlogn) using fft and self convolution, but I don't get it, and it also seems to be incorrect when I try it on online convolution calculators (like this one).
So, does anyone know how this can be achieved in O(nlogn)?
Thank you in advance :)

A: This answer linked by OP suggest the following steps:

*

*Assume an array with non-repeating elements in the range [0, n-1].*

*Create an array of length n, where elements whose index matches an element of the input are set to 1, other elements are set to 0. This can be created in O(n). For example, given in input array [1,4,5], we create an array [0,1,0,0,1,1].

*Compute the autocorrelation function. This can be computed by taking the FFT, squaring its magnitude, and then taking the IFFT. This is O(n log n).

*The output is non-zero for indices corresponding to a difference present in the input. The element at index 0 is always non-zero, and should be ignored. Finding and printing these elements is O(n).

Note that this process is not correct, because the auto-correlation function as computed through the FFT is circular. That is, given an input array with two values, 0 and n-1, the output will have a non-zero element at index 1 as well as at index n-1. To avoid this, it would be necessary to make the array in step #2 of length 2n, leaving half of it set to 0. The second half of the output array should then be ignored. Doubling the array size doesn't change the computational complexity of the algorithm, which is still O(n log n).
* I changed the range from that given by OP for simplicity, it is trivial to change this range by adding an offset to all indices.


text:
Q: Нужно узнать какой QComboBox выбрал пользователь Есть программа на Python с использованием PyQt5.
Имеются 3 QComboBox:

*

*ComboFizAkt - уровень физической активности, в котором 4 варианта выбора.

*ComboCel - цель (хочу похудеть, хочу улучшить фигуру и т.д.), в котором 3 варианта выбора.

*ComboTrenirovki - кол-во тренировок в неделю, в котором 7 вариантов выбора.

Мне нужно узнать какой комбобокс выбрал пользователь и мне нужно, чтобы я мог использовать выбор в коде.
self.LvlFizAkt.setText("Уровень физической активности:")
self.ComboFizAkt.setItemText("Сидячий")
self.ComboFizAkt.setItemText("Слабый физ. труд")
self.ComboFizAkt.setItemText("Преобладает физ. труд")
self.ComboFizAkt.setItemText("Тяжёлый физ. труд")
self.ComboFizAkt.setItemText("Очень тяжёлый физ. труд")
self.ViborCeli.setText("Ваша цель:")
self.ComboCel.setItemText("Ничего не хочу")
self.ComboCel.setItemText("Хочу похудеть")
self.ComboCel.setItemText("Хочу улучшить фигуру")
self.ComboCel.setItemText("Хочу набрать мыш. массу")
self.KolvoTrenirovok.setText("Кол-во тренировок в неделю:")
self.ComboTrenirovki.setItemText("0")
self.ComboTrenirovki.setItemText("1")
self.ComboTrenirovki.setItemText("2")
self.ComboTrenirovki.setItemText("3")
self.ComboTrenirovki.setItemText("4")
self.ComboTrenirovki.setItemText("5")
self.ComboTrenirovki.setItemText("6")
self.ComboTrenirovki.setItemText("7+")

A: Попробуйте так:
from PyQt5 import QtGui, QtCore, QtWidgets

class Widget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self.label = QtWidgets.QLabel()

        self.comboFizAkt = QtWidgets.QComboBox()
        self.comboFizAkt.addItems(
            ["Сидячий",
             "Слабый физ. труд",
             "Преобладает физ. труд",
             "Очень тяжёлый физ. труд"
            ]
        )
        self.comboCel = QtWidgets.QComboBox()
        self.comboCel.addItems(
            ["Ничего не хочу",
             "Хочу похудеть",
             "Хочу улучшить фигуру",
             "Хочу набрать мыш. массу"
            ]
        )
        self.comboTrenirovki = QtWidgets.QComboBox()
        self.comboTrenirovki.addItems(
            ["0", "1", "2", "3", "4", "5", "6", "7+"]
        )
        self.button = QtWidgets.QPushButton("Проверить выбор пользователя")
        self.button.clicked.connect(self.onClicked)

        self.comboFizAkt.activated.connect(self.label.clear)
        self.comboCel.activated.connect(self.label.clear)
        self.comboTrenirovki.activated.connect(self.label.clear)

        layout = QtWidgets.QFormLayout(self)
        layout.addRow(QtWidgets.QLabel("Уровень физической активности:"), self.comboFizAkt)
        layout.addRow(QtWidgets.QLabel("Ваша цель:"), self.comboCel)
        layout.addRow(QtWidgets.QLabel("Кол-во тренировок в неделю:"), self.comboTrenirovki)
        layout.addRow(self.button)
        layout.addRow(self.label)

    def onClicked(self):
        text1 = self.comboFizAkt.currentText()
        text2 = self.comboCel.currentText()
        text3 = self.comboTrenirovki.currentText()
        self.label.setText(f'''
        {text1}
        {text2}
        {text3}
        ''')

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())


text:
Q: C# + Resharper - Events method with underscore - Naming convention I have VS 2010 with resharper (any version, now 5.1).
The default naming convention coming with R# about public or protected method's name is: "ThisIsMethodName", and I think it's fine.
But, sometimes, the default naming of .NET methods, is not like I'm expecting, for example Page_Load, or (with a button click in webform designer panel) Button1_Click.
As you can see, we have the underscore between words.
Why we have this and how (if it is possible) I can remove all underscores from my solution?

A: These underscores are created by the default Visual Studio WinForm designer (when you double click on the event name in properties panel VS creates a method with this name). I am not sure what is the convention in WCF. This doesn't have anything to do with resharper - you will observe the same behaviour if you disable it. I don't think it is configurable.
You can always rename these methods after they are created (in the usual way - using Resharper).

A: I think I would live with the way dotnet creates the events because you will be renaming every single time you create some control that requires an event.
You can change the defaults in ReSharper if you want to allow for this format. In VS2008, it is in ReSharper -> Options -> Languages -> Common -> Naming Styles.

A: You can change the callback of a form or any elements available in the UI so it matches the naming convention from resharper.
Example:
example on changing callbacks


text:
Q: In an MVC, is it OK to have Ajax code (in View) request a query rather than Controller I'm working with Tizag tutorials here and here.  I have modified the code a tiny bit, as follows:
order.html:

<form name='myForm'>
Max Age: <input type='text' id='age' />

Max WPM: <input type='text' id='wpm' />

Sex: <select id='sex'>
<option>m</option>
<option>f</option>
</select>
<input type='button' onclick='ajax1()' value='Query MySQL' />
</form>

Your result will display here

And the page that's called, ajaxEx1.php:
<?php
$dbhost = "localhost";
$dbuser = "admin";
$dbpass = "abcd";
$dbname = "test01";
mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname) or die(mysql_error());
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
$query = "SELECT * FROM ajax_example WHERE ae_sex = '$sex'";
if(is_numeric($age))
    $query .= " AND ae_age <= $age";
if(is_numeric($wpm))
    $query .= " AND ae_wpm <= $wpm";
    //Execute query
$qry_result = mysql_query($query) or die(mysql_error());
$display_string = "
";
$display_string .= "
";
$display_string .= "Name	";
$display_string .= "Age	";
$display_string .= "Sex	";
$display_string .= "WPM	";
$display_string .= "
";
while($row = mysql_fetch_array($qry_result)){
    $display_string .= "
";
    $display_string .= "$row[ae_name]	";
    $display_string .= "$row[ae_age]	";
    $display_string .= "$row[ae_sex]	";
    $display_string .= "$row[ae_wpm]	";
    $display_string .= "
";
}
echo "Query: " . $query . "
";
$display_string .= "
";
echo $display_string;
?>

This works fine and is pretty straightforward.  However, I note that in this example the query is essentially requested by Javascript in what would be considered a View element in an MVC pattern.  Would that still be good practice in an actual MVC site?  Would the View send some parameters to a file that would either run the query itself or pass it to a DAO and receive the response?
If not, if the above was a piece of an MVC site, how would the Ajax portion would need to be reorganized?

A: If it were me and I was working on a site large enough that it required modularization via the MVC pattern, I would definitely pull out the ajax stuff to a model object and not the view.  Frameworks like Backbone.js work really well for this because the Models have built-in ajax handling and will populate data back and forth for you.
If you wanted to do it yourself you could create a model object that took just the data (not the DOM elements) as arguments and returned the data for you.
function AjaxModel() {

    this.get = function(age, wpm, sex, callback) {

        ajaxRequest = createRequest();
        ajaxRequest.onreadystatechange = callback;

        var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex;
        ajaxRequest.open("GET", "ajaxEx1.php" + queryString, true);
        ajaxRequest.send(null);
    }
}

then you can call it like this:
var ajaxM = new AjaxModel();
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
ajaxM.get(age, wpm, sex, onComplete);

function onComplete(r) {
    /// your ajax complete method
}

If you're site is large enough the inclusion of a Framework like Backbone.js is very worth it in my opinion though.
As a side note, the MVC pattern is a model of how to separate logic, but it's not perfect.  Often I find myself creating many views and models, but very few if any controllers.  View logic is very tied to control in javascript so often I find they just aren't needed.  I would do what makes the most sense to you, while making sure that at least your data is separate from everything else.
Good luck.

A: Everything is OK as long as you know why you're doing it and what the result of it will be ;). But, it's certainly not best practice.
In a MVC application there is usually alot going on "back stage". Every request has it's lifecykle, and the look of this lifecykle depends on the code base it's built upon.
If you choose not to make use of this chain you'll also lose the benefits that comes with it. It may involve various hooks and plugins registered (by you or someone else) to get the system to work as a whole. It may also involve providing system security, such as centralized ACL logic.
I would suggest you use the controller, which in turn requests data from the model. This data can then either be sent directly to the clienten from the controller (as JSON or XML), or to a view that formats the data before it's being handled by the client. But I favour using JSON.
And, the JavaScript should be seperated from the markup (HTML), and put in a .js file.
Best of luck

A: In MVC, you normally post to a controller which construct the model that is passed to the view to display.
You are using AJAX calls to update parts of your view dynamically without reloading the complete view. It is is completely fine to construct your query inside your JavaScript code. If you're concerned about separating model and view code, you may want to look at KnockoutJS for client side (JavaScript) MVVM pattern implementation.

A: I would, never ever, make calls into a database directly with an ajax request.

A: If you're using MVC, the good approach is to use it in the entire app.
So, when doing an ajax request, build the query string or pretty url acording to your framework needs, implement everything as you would use a normal view (View <- Controller <- Model) and just format the view to return the AJAX stuff (partial HTML, JSON, XML, or whatever).
Usually this may be done by just not using a template with the view.

A: I think it is ok to put you ajax code (make it generic and reusable depending on your needs) in a separate javascript file that you can include in the view that needs that kind of ajax call.
You should implement an ajax controller, that will process you ajax requests and just send the response? if it is data you just return data using json. this is how I am doing it with Zend framework.
Take a quick look at this Implementing OOP PHP with AJAX, MVC?


text:
Q: Check alphabetical order of vowelList I'm trying to check to see if the vowels in a word are in alphabetical order, if not discard the word.
I've currently selected the vowels out of the word and added them to a string;
foreach(char c in word[I])
{
    if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
    {
        vowelList.Add(c)
    }
}

how can I check through this list to ensure they are in order without having to compare every character against every other character?

A: You can use LINQ like:
bool IsOrdered = vowelList.OrderBy(c => c).SequenceEqual(vowelList);

You list vowelList will contain characters in the order from your character array, if you sort them using OrderBy the should be same as your original list.
Apart from that you can also modify your check as:
if (new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(c))

A: This should work efficiently:
private static readonly char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
public static bool AreVowelsInAlphabeticalOrder(string word)
{
    int lastIndex = -1;
    for (int i = 0; i < word.Length; i++)
    {
        char c = word[i];
        int vowelIndex = Array.IndexOf(vowels, c);
        if(vowelIndex >= 0)
        {
            if(vowelIndex < lastIndex)
                return false;
            else
                lastIndex = vowelIndex;
        }
    }
    return true;
}

A: I would probably do it something like this using LINQ:
// This list is to keep track of which letters are vowels
var vowels = new List<char> { 'a', 'e', 'i', 'o', 'u' };

// This is the word we want to check the order of
string word = "testing"; // gives true

// We start of by finding all vowels in the word (in the order they appear)
var vowelList = word.Where(letter => vowels.Any(v => letter == v));

// We create a list that looks like we expect it to if its correct order
var expectedResult = vowelList.OrderBy(x => x);

// We check if we have a result in the expected order
bool isOrdered = vowelList.SequenceEqual(expectedResult);

This could be implemented as an extension method on string like this:
public static class StringExtensions
{
    static readonly List<char> _vowels = new List<char> { 'a', 'e', 'i', 'o', 'u' };

    public static bool VowelsOrdered(this string word)
    {
        var vowelList = word.Where(letter => _vowels.Any(v => letter == v));
        var expectedResult = vowelList.OrderBy(x => x);

        return vowelList.SequenceEqual(expectedResult);
    }

    // Could also be implemented with a lower complexity like this
    public static bool VowelsOrdered2(this string word)
    {
        char last = _vowels[0];
        foreach (var c in word)
        {
            if (_vowels.Any(x => x == c))
            {
                if (c < last)
                    return false;
                else
                    last = c;
            }
        }
        return true;
    }
}

Then usage would be like:
string word = "testing";
bool isOrdered = word.VowelsOrdered();


text:
Q: git push from eclipse to a bare repository gets rejected I have bare repository on my PC (running windows 7) - Machine A - and I'm using the command:
git daemon --export-all --verbose --enable=receive-pack

to run the git daemon.
From another maching (mac) - Machine B - I was able to push from the upstream using egit (from eclipse).
My problem is that I'm unable to pull the repository. When I try this, it gives me "rejected" on Machine B. On machine A, I get the following:

[952] [1976] Disconnected
  [5868] Connection from 192.168.1.102:56643
  [5868] Extended attributes (20 bytes) exist
  [5868] Request upload-pack for '/somerepository/.git'
  [952] [5868] Disconnected
  [3088] Connection from 192.168.1.102:56645
  [3088] Extended attributes (20 bytes) exist
  [3088] Request receive-pack for '/somerepository/.git'

Any ideas?


text:
Q: Nonlinear PDE of form $u_y=F(u_x)$ I would appreciate if someone can give me help with the following problem:

Find all solution $u(x, y)$ for
  $$
\left\{ \begin{array}{ll}
u_y=F(u_x) \\
u(x, 0)=h(x) \end{array} \right.,
$$
  where $F$ and $h$ are suitable functions such that problem makes sense.

There is a hint for this: the solution has the form $u=F(p)-pF'(p) +h(x+yF'(p))$, where $p$ is given implicit by $p=h'(x+yF'(p))$.
I have been working in for some days, but couldnt solve. Thanks for any help.

A: Differentiating the PDE w.r.t. $x$ gives
$$
p_y = F(p)_x = F'(p) p_x ,
$$
where $p=u_x$. Let us follow the method of characteristics for the scalar conservation law $p_y-F'(p) p_x=0$. Thus,

*

*$\frac{\text d y}{\text d t} = 1$, letting $y(0)=0$, we know $y=t$.

*$\frac{\text d p}{\text d t} = 0$, letting $p(0)=h'(x_0)$, we know that $p = h'(x_0)$ is constant along characteristics.

*$\frac{\text d x}{\text d t} = -F'(p)$, letting $x(0)=x_0$, we know that the characteristics $x = x_0 - y F'(p)$ are straight lines in the $x$-$y$ plane.
The latter rewrites as $x_0 = x + y F'(p)$. Thus, using $p = h'(x_0)$, we get
$$
p = h'(x + y F'(p)) \, .
$$
Let us compute the evolution of $u(x,y)$ along characteristics
$$
\frac{\text d u}{\text d t} = u_y \frac{\text d y}{\text d t} + u_x \frac{\text d x}{\text d t} = F(p) - p F'(p) \, ,
$$
which is a constant. Integrating the previous identity w.r.t. $t=y$ gives
$u = (F(p) - p F'(p)) t + h(x_0)$, i.e.
$$
u = (F(p) - p F'(p)) y + h(x + y F'(p)) \, .
$$
Note that there must be a mistake in OP, since the proposed solution for $u$ does not satisfy the initial condition.


text:
Q: Removing elements from Set in one-to-Many relationship deletes all records in my table I have a class (Team) which a 'set' of another class (Players) making it one-to-many.  When I try clearing the set of players with my remove all function:  this.players.clear(), to add a new set, hibernate deletes both tables.
Any ideas?

A: Hibernate is deleting two tables because you are clearing the set values of entity inside the transaction. Do the clearing action after closing the hibernate session.


text:
Q: Use greater_equal in adjacent_find to find equivalent elements in sorted sequence Is it UB to use std::greater_equal in std::adjacent_find algorithm to find equivalent (as opposite to equal) elements in sorted range?
The answer can be "no" if order of prev and next elements in std::greater_equal<>{}(*prev, *next) inside of implementation of the algorithm is not specified strictly.
std::container<int> c{1, 2, 3, 3, 4, 5};
assert(std::is_sorted(std::cbegin(c), std::cend(c));
assert(std::adjacent_find(std::cbegin(c), std::cend(c), std::greater_equal<int>{}) != std::cend(c));

A: std::adjacent_find searches for two consecutive elements where the predicate returns true. The C++ standard documents the behavior as finding:

*

**i == *(i + 1) for the overloads with no parameter pred

*pred(*i, *(i + 1)) != false for the overloads with a parameter pred
The second bullet specifies the order that the elements are passed to the predicate.
This example implementation (copied from cppreference.com) should make this clearer.
template<class ForwardIt, class BinaryPredicate>
ForwardIt adjacent_find(ForwardIt first, ForwardIt last, BinaryPredicate p)
{
    if (first == last) {
        return last;
    }
    ForwardIt next = first;
    ++next;
    for (; next != last; ++next, ++first) {
        if (p(*first, *next)) { // <- predicate called here
            return first;
        }
    }
    return last;
}

A:
Is it UB to use std::less in std::adjacent_find algorithm to find
  equivalent (as opposite to equal) elements in sorted range?

It is never undefined behaviour, the only restrictions for predicate passed to std::adjacent_find are proper type and not modyfing its arguments.

A: You are looking at this template:
template< class ForwardIt, class BinaryPredicate>
ForwardIt adjacent_find( ForwardIt first, ForwardIt last, BinaryPredicate p );

Here p is

p     -   binary predicate which returns true if the elements should be treated as equal.

There is no UB here as long as the requirements of the algorithm are met. If for your problem you have to treat less as equal then it's perfectly valid.

A: You don't have UB, but it is not std::less that you want, as 1 < 2, it would return iterator to 1.
You need:
std::vector<int> c{1, 2, 3, 3, 4, 5};
assert(std::is_sorted(std::cbegin(c), std::cend(c));
auto it = std::adjacent_find(std::cbegin(c), std::cend(c),
                             [](auto lhs, auto rhs){
                                 // For unsorted container, you would need
                                 // return !(lhs < rhs) && !(rhs < lhs);
                                 // but as container is sorted,
                                 // we already have (lhs < rhs) || !(rhs < lhs)
                                 return !(lhs < rhs);

                             });
// *it == 3; *(it+1) == 3;


text:
Q: How to find all file names in a directory using windows wildcards i have two files:
asdf.txt.txt
asdf.txt

Is it possible to use cmd to find only the file ending .txt and not the file above it: .txt.txt?
I have :
 dir *.txt

but it still yields both files
is it possible to do this
ps this is for a homework assignment but i looked on line and can't find any way to do this from the cmd line

A: Since this is homework, I won't provide the full answer. But there is a simple solution that uses pipes (|) and FINDSTR.

A: dir *.txt | findstr/v/i "txt.txt"

findstr/v will suppress the lines that contain "txt.txt".  /i tells it that the string in quotes is not case-sensitive.

A: Yes.
It depends on what you're trying to do.  Both files are technically *.txt.  You could do something like dir *f.txt or you could use some faux regex with findstr:
http://technet.microsoft.com/en-us/library/bb490907.aspx

A: As dweiss pointed out, the result given to you is technically correct.
Another (albeit perhaps more complex) solution is to use Powershell to perform GREP-like commands.

A: Starting with:
thing.txt
thing.txt.txt
REN *.txt.txt *.xyz
thing.txt
thing.txt.xyz
DIR *.txt
lists only thing.txt
DIR *.xyz
lists only thing.txt.xyz
REN *.xyz *.txt
gives you back the original filenames.


text:
Q: Creator acknowledgement for a modified project (under GNU GPL) I have been modifying an existing software (which was under the GPL licence). At my workplace, they needed to use the software, but needed some modifications (like new features, different structure, feature modification and removing unused functionalities).
I am about to finish this, but would not like to disrespect the original creator by not abiding the licence. I read several sources like the GPL licence official page, the software's official page and many others, to know what the licence asks from me.
However, I still have some unclear points, like:

*

*Should I inform the original creator of how I am using the program and of my modifications?

*In the licence included in the project, should I state the original source? Should I also make it visible so that any users know that this project was only modified by me?

*Should I leave all the original code (commented) so that it can be seen what I changed?

*I have to prepare a report stating what languages, libraries and frameworks were used and what does the project do. Should I acknowledge the creator here?

I really don't want to be dishonest, but one of my bosses asked me to modify an existing project to spare some time and to take advantage of professional coders with more experience than me. He asked me not to tell anybody about it. Another very important person in the company might be against it once he finds out. I do not want to lie and will clearly state the original owner for everyone to see, if that is required.
Also, whatever the case is, I do intend to credit the owner in the source code, so that at the very least, other programmers know the origin of the project. And if I am asked, I will not deny having modified an existing project. However, it would be really problematic acknowledging the owner for the public eye or in the reports handed to the project managers - especially since they did not even ask about it.

A: None of these things are necessary, but 1, 2 and maybe even 4 are probably good ideas. 3 probably not.

*

*Should I inform the original creator of how I am using the program and of my modifications?

There is definitely no obligation to do this, since the GPL does not allow such a requirement.
Whether or not you should is a more subjective thing, but unless your project is top secret military work I don't see any reason not to tell them. Creators usually benefit from knowing when their work was useful to someone, and knowing exactly which parts you felt the need to add, change or remove may be very useful information if and when they think about updating their program.

*In the licence included in the project, should I state the original source? Should I also make it visible so that any users know that this project was only modified by me?

Technically "the license" needs to be GPL (possibly alongside other licenses), and that means unmodified GPL, so definitely don't modify the license to state the original source.
You do need to state in a separate file (typically the readme) that all of this code is licensed under the GPL. There are also good reasons to state this in every single source file, even though that's not legally necessary.
I'm fairly sure you are not required to mention the original source of the code anywhere (see #1), but since you do have to state the code is GPL'd, you might as well mention the original source alongside that statement.

*Should I leave all the original code (commented) so that it can be seen what I changed?

I can't think of any reason this would be necessary, or desirable. Acknowledgement of the original source is sufficient for anyone who cares to work out what all the changes are. I'd suggest a few sentences in your readme summarizing the changes if you feel that's important information.
Leaving huge amounts of "dead code" around would also be a significant nuisance for anyone maintaining your modified version (including yourself), so I definitely wouldn't do this.

*I have to prepare a report stating what languages, libraries and frameworks were used and what does the project do. Should I acknowledge the creator here?

Again, there's no obligation to do this (see #1). Personally I'd include creators if it was a particularly long or detailed report, but normally I'd just name the libraries and link to their repos. Whether that information is appropriate for your report is something you'll have to decide (though I am curious why you think it would be "problematic" to do so).

A: I agree with everything that is said in Ixrec's answer. The point that I want to add is that commenting code out is almost always a bad idea. It makes the code less readable and neither the old, nor the new version is readily visible.
Instead, if you feel a need to make it crystal clear what you've changed, you can publish the original, unmodified, code alongside with a diff of your changes. The end user can then apply the patch (preferably via a Makefile you provide) . If a stable version of the original is readily available, you might even publish only the diff and ask your users to download the original sources. This might be of particular interest when your users will trust the original author more than you. They might want to review your diff (if it is relatively small) but not read all of the original code.
For example, if you're about to fix a really urgent issue in SQLite, you could publish just this.
sqlite3.diff
16918c16918
<   double r;
---
>   double r = NAN;  /* always initialize variables */
16923c16923
<   }else if( sqlite3StrICmp(zDate,"now")==0){
---
>   }else if( sqlite3StrICmp(zDate,"current")==0){

Makefile
sqlite3-new: sqlite3-new.c
    ${CC} -o $@ ${CPPFLAGS} ${CFLAGS} $< ${LIBS}

sqlite3-new.c: sqlite3.c sqlite3.diff
    patch -o $@ $^

sqlite3.c:
    wget 'https://www.sqlite.org/2016/sqlite-amalgamation-3110000.zip'
    unzip sqlite-amalgamation-3110000.zip
    cp sqlite-amalgamation-3110000/sqlite3.c $@

And make sqlite3-new will do the "right" thing.
(Please don't write build scripts that download random stuff from the internet without the user's consent and without even verifying the download in real life!)


text:
Q: Angular2: convert XMLHttpRequest to Response Part of existing code
    let xhr = new XMLHttpRequest(),
    xhr.onreadystatechange = () => {
        if(xhr.readyState == 4) {
            if(xhr.status >= 200 && xhr.status < 300)
                this.onUpload.emit({xhr: xhr, files: this.files});
            else
                this.onError.emit({xhr: xhr, files: this.files});
        }
    };

I'd like to change this code to emit object of type Response. So I need to convert XMLHttpRequest to Response. Is there any ready way to do this or should I write it myself?


text:
Q: How to create a list of all possible combinations of 3 lists? If I have 3 list [0, 1, 2], [3, 4, 5], [6, 7, 8], how would I obtain an output of a list of lists that are of length three and contain one element from each list and has all possible combinations?
For example, one of the possible combinations of the above is [1, 5, 6].
I tried using numpy.meshgrid, but that only gave me some possible combinations and not all.

A: import itertools
x = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
all_combinations = list(itertools.product(*x))
[(0, 3, 6),
 (0, 3, 7),
 (0, 3, 8),
 (0, 4, 6),
 (0, 4, 7),
 (0, 4, 8),
 (0, 5, 6),
 (0, 5, 7),
 (0, 5, 8),
 (1, 3, 6),
 (1, 3, 7),
 (1, 3, 8),
 (1, 4, 6),
 (1, 4, 7),
 (1, 4, 8),
 (1, 5, 6),
 (1, 5, 7),
 (1, 5, 8),
 (2, 3, 6),
 (2, 3, 7),
 (2, 3, 8),
 (2, 4, 6),
 (2, 4, 7),
 (2, 4, 8),
 (2, 5, 6),
 (2, 5, 7),
 (2, 5, 8)]


text:
Q: How to view the assembly code generated from my JavaScript (in Chrome)? is it somehow possible, to view the final machine code (x86 instruction) that a browser generates from my Javascript? E.g.
--- Raw source ---
function add(a, b){
  return a + b;
}
...

--- Code ---
source_position = 0
kind = FUNCTION
Instructions (size = 456)
0x36953100     0  8b4c2404       mov ecx,[esp+0x4]
0x36953104     4  81f991806049   cmp ecx,0x49608091          ;; object: 0x49608091 <undefined>
0x3695310a    10  750a           jnz 22  (0x36953116)
0x3695310c    12  8b4e13         mov ecx,[esi+0x13]
0x3695310f    15  8b4917         mov ecx,[ecx+0x17]
0x36953112    18  894c2404       mov [esp+0x4],ecx
0x36953116    22  55             push ebp

Thanks!

A: Your script doesn't transform to machine code directly. JavaScript runs on virtual machine V8 (it's true for chrome and classic nodejs) and you can get VM byte code using:
node --print-bytecode script.js

Then V8 executes and optimizes the byte code and calls external C libraries and OS API (system calls) or WEB API. Final machine code may vary even with the same javascript code (for example before and after optimization).
You can also start Chrome from the command line with
--js-flags="--print-bytecode"
UPD:
As @PeterCordes noticed nodejs allow to see Turbofan generated machine code using
node --print-opt-code script.js

Chrome:
--js-flags="--print-opt-code"

Also you can use HTML visualizer like https://github.com/v8/v8/tree/master/tools/turbolizer


text:
Q: Is it possible to intercept the file from a  in javascript? Is it possible to read the content of a file that has been selected with a file input control? I wish to do something like:
<input type="file" id="fileInput" onblur="readFile(this)"/>

<script language="javascript">
   function readFile(file) {
     document.write(file);
   }
</script>

Is anything like this possible? or does the file upload just send the file to the server.

A: It is possible in Firefox, but it is not standardized, so it is not possible portably across browsers (for instance, WebKit does not support it). Your best bet would probably be to upload the file to the server, and then download it again using an XMLHTTPRequest.

A: You can if you use HTA (Hypertext Terminal Application, see http://msdn.microsoft.com/en-us/library/ms536496(VS.85).aspx). If you do, you're bound to Internet Explorer, but free to access files, the registry etc. There are (of course) security issues.

A: It is probably not possible in many browsers. What would happen if we gave arbitraty javascript the ability to read an arbitrary file in the filesystem, using the user's credentials? BAD THINGS. Malicious javascript could easily take the file data and post it back to the server, quietly snooping all your files in the background.
I doubt this is possible, and I strongly recommend against it.
If it needs to be exclusively client-side, why are you using a web application at all? The only files this could display are plain-text, for which there are many easier ways of viewing content.


text:
Q: How does a state vector be projected onto an eigenspace after measurement In http://en.wikipedia.org/wiki/Measurement_in_quantum_mechanics#Degenerate_spectra, it is said that

If there are multiple eigenstates with the same eigenvalue (called degeneracies),..., The probability of measuring a particular eigenvalue is the squared component of the state vector in the corresponding eigenspace, and the new state after measurement is the projection of the original state vector into the appropriate eigenspace.

My question: Is the state vector after measurement when the eigenspace is degenerated a pure state or mixed state? And what is the mathematical formulation of the mentioned "projection" onto the eigenspace?

A: 1) Let there be given a Hilbert space $H$ and a mixed state described by a density operator $\hat{\rho}:H\to H$, which is a positive operator $\hat{\rho}\geq 0$, and with trace ${\rm Tr}(\hat{\rho})=1$.
2) Let $V\subseteq H$ be an eigenspace of states for an Hermitian observable $\hat{A}:H\to H$ with eigenvalue $\lambda\in\mathbb{R}$. (We will ignore subtleties with unbounded operators, domains, selfadjoint extensions, etc., in this answer.)
3) Let $\hat{P}:H\to H$ be the projection operator onto $V$. It is the unique operator, such that

*

*$\hat{P}$  is Hermitian $\hat{P}^{\dagger}=\hat{P}$ (and hence $\hat{P}$ is diagonalizable in an orthonormal basis).

*An idempotent $\hat{P}^2=\hat{P}$ (and hence can only have eigenvalues $0$ and $1$).

*The eigenspace ${\rm ker}(\hat{P}-1)$ for $\hat{P}$  with eigenvalue $1$ is equal to the subspace $V$.

If $(\mid\psi_i\rangle)_{i\in I}$ is an orthonormal basis for $V$, then
$$\hat{P}=\sum_{i\in I}\mid\psi_i\rangle\langle\psi_i\mid. $$
4) Then the collapse $\hat{\rho}\longrightarrow \hat{\rho}^{\prime}$ of the density operator, due to the measurement, would be
$$ \hat{\rho}^{\prime}~=~ \frac{\hat{P}\hat{\rho}\hat{P}}{{\rm Tr}(\hat{P}\hat{\rho})}. $$
5) For a pure state $\hat{\rho}=\mid\psi\rangle\langle\psi\mid $, the collapse $\mid\psi\rangle\longrightarrow\mid\psi\rangle^{\prime}$becomes
$$  \mid\psi\rangle^{\prime}~=~\frac{\hat{P}\mid\psi\rangle}{\sqrt{\langle\psi\mid\hat{P}\mid\psi\rangle}}.$$
So if one starts from a pure state $\mid\psi\rangle$, the collapsed state $\mid\psi\rangle^{\prime}$ would also be pure.

A: The exact projection which a measurment is doing depends on the details of the measurement process. An idealized position measurement is an impossible thing, because it would project to a state of infinitely indefinite momentum, and infinite energy.
Any interaction of a quantum particle with another quantum system which starts with a product state, where the particle is in the state $\psi$ and the system is in the state $\chi$ produces an entangled state, where different states of the particle are entangled with different states of the system. We say that the system is "measuring" the particle when some of the states of the system leave a classical imprint. If the measuring device stops interacting with the particle, the entangled state of the particle looks like a density matrix, and the particle will be left in the relative state to the appropriate state of the measuring device, as projected by the outcome.
The relative state concept is due to Hugh Everett, and it is central to the many-worlds interpretation. Leaving interpretation aside, it is the central tool for describing non-idealized notions of measurement in quantum mechanics.
So if you scatter a photon of wavelength $\lambda$ off a particle, you get different scattering angles at different positions. The scattering angle is entangled with the particle position. If you then let the photon get absorbed by a photosensitive device, the position of the photon reveals which particular state of the particle is present. The description of a particle when it is entangled is no longer by a wavefunction, but by a density matrix, and this continues to be true unless the outgoing photon comes back to the particle to undo the entanglement. When the measurement becomes macroscopic, this is just not going to happen, because the photon has entangled itself with everything else.

A: Suppose you are in the state
$$|\Psi \rangle = a|\alpha_1\rangle + b|\alpha_2\rangle + c|\beta \rangle$$
$|\alpha_1\rangle$ and $|\alpha_2\rangle$ are eigenvectors of the observable $A$, both with eigenvalue $\alpha$.  $|\beta\rangle$ is also an eigenvector of this observable but with the different eigenvalue $\beta$.
If you make a measurement of $A$ and the result is $\alpha$, the state of the system becomes the state
$$N\left(a|\alpha_1\rangle + b|\alpha_2\rangle\right)$$
with $N$ a factor chosen to keep the state normalized.
If you do not know the state of $|\Psi\rangle$ before making the measurement, then you make the measurement and get the value $\alpha$, you don't know the wavefunction after the measurement.  Assuming the three states $|\alpha_1\rangle, |\alpha_2\rangle, |\beta\rangle$ form a basis, all you can say is that after the measurement
$$|\Psi\rangle = p|\alpha_1\rangle + q|\alpha_2\rangle$$
with $p^*p + q^*q = 1$, but you don't know what $p$ and $q$ are.  If you want to determine them, you should find some other operator $B$ which commutes with $A$, so that $|\alpha_1\rangle$ and $|\alpha_2\rangle$ are eigenvectors of $B$, but have different eigenvalues.  Then measuring $B$ will allow you to determine the state completely.

A: The projection operator on to a subspace $E$ spanned by a set of orthogonal states $\{|e_k\rangle\}$ is
$$P_E = \sum_k \frac{|e_k\rangle\langle e_k|}{\langle e_k|e_k\rangle}$$
That was the easy part. But figuring out whether you have a pure state or a mixed state after a measurement is, in some sense, an issue of definitions.
Consider a single quantum system which starts in a pure state $|\psi\rangle$ or $\rho$ (if you prefer density operators). Suppose you measure an observable corresponding to the operator $A$. As a Hermitian operator, $A$ has eigenstates $|a^i_k\rangle$, associated with eigenvalues $a^i$, which form an orthonormal basis. Let's say the result you get is $a^0$; then this particular measurement projects the state of the system on to the subspace $A_0$ spanned by the eigenstates $|a^0_k\rangle$:
$$\begin{align}|\psi\rangle &\to P_{A_0}|\psi\rangle & \rho &\to P_{A_0}\rho P_{A_0}\end{align}$$
Evidently if you're dealing with a single measurement on a single system, assuming you started with a pure state, you can express the post-measurement state as a pure state.
But what if you instead have a large ensemble of systems, each prepared identically and then measured? After the measurement, for each possible result $a^i$, a fraction $p(a^i)$ of the systems will have produced the result $a^i$ and thus will be in the state $P_{A_i}|\psi\rangle$ or $P_{A_i}\rho P_{A_i}$. This is a mixture of systems in different pure states, and thus it corresponds to a mixed state
$$\rho \to \sum_i p(a^i)P_{A_i}\rho P_{A_i}$$
The key difference is that with a single system, you were able to know the result of the measurement, which was the knowledge you needed to "extract" a single pure state from the mixture. But in this case, you can't do that because you have many different result of the measurement.


text:
Q: How to autoscale elastic search in kubernates based on load? I am using Google Cloud and I am doing RnD whether we can apply HPA (Horizontal Pod Auto scaling) on elasticsearch in Kubernetes.
I did elasticsearch set up on Kubernetes : https://github.com/elastic/helm-charts/tree/master/elasticsearch
But I found one of the post on forum they say elasticsearch HPA is hard
https://discuss.elastic.co/t/how-to-scale-up-and-down-nodes-automatically/224089/2
So is it possible to do HPA on elasticsearch or not ?

A: I don't think it would work well and you'd be at risk of losing data.  HPA tends to respond to load changes on a scale of a minute or so, and can occasionally make large changes (scaling from 5 replicas to 2, for example).  For Elasticsearch you need to scale in one node at a time, monitor the state of the cluster before you can proceed, and it could take a long time before you can move from one node to the next.

Say you're running Elasticsearch in a StatefulSet.  Remember that each ES index is made up of shards; you will have some number of copies of the shards spread out across the nodes in the ES cluster.  So also let's say your index has 10 shards with 2 replicas each.
Scaling out is easy.  Increase the size of the StatefulSet as much as you want; configure each node to talk to es-0 for discovery.  ES will see that the cluster has grown and start moving shards on to the new nodes on its own.
Scaling in is hard.  You can only delete one node at a time.  Once that node is shut down and the cluster realizes it's missing, then the shards that used to be on that node will be under-replicated.  ES will create new replicas on the remaining nodes and copy the shard data there.  You can observe this happening through things like the /_cat/shards API.  The index status will be "yellow" as long as there are under-replicated shards, and then will switch back to "green" once the replication sequence finishes.
So say you currently have 8 nodes, and you want to scale down to 6.  There's some possibility the only two replicas of a given shard will be on es-6 and es-7 so you can't turn those both off together; you have to turn off es-7 first, wait for replication to catch up, then turn off es-6.  There's also some possibility that, when you turn off es-7, the new replicas will be created on the doomed node es-6.
You can also tell Elasticsearch to move shards off of a replica before removing it.  This avoids the cluster going into the "yellow" state, but it's harder to monitor.
Finally, the re-replication can take a long time depending on how much data is actually in the cluster.  (In a past cluster I maintained with a badly-designed index structure, it took multiple hours to shut down a node.)  That's a much slower operation than HPA is prepared for.


text:
Q: Accessing this in a forEach loop results in undefined I'm iterating through an array using forEach in one of my Class's methods. I need access to the instance of the class inside the forEach but this is undefined.
var aGlobalVar = {};

(function () {

    "use strict";

  aGlobalVar.thing = function() {
      this.value = "thing";
  }

  aGlobalVar.thing.prototype.amethod = function() {
      data.forEach(function(d) {
      console.log(d);
      console.log(this.value);
  });
}
})();

var rr = new aGlobalVar.thing();
rr.amethod();

I have a fiddle I'm working on here: http://jsfiddle.net/NhdDS/1/ .

A: Since you're using strict mode, when a function is called that isn't a property of an object, this will have the value undefined by default (not the global object).  You should store its value manually:
var aGlobalVar = {};

(function () {
    "use strict";

    aGlobalVar.thing = function () {
        this.value = "thing";
    };

    aGlobalVar.thing.prototype.amethod = function () {
        var self = this;
        data.forEach(function (element) {
          console.log(element);
          console.log(self.value);
        });
    };
})();

var rr = new aGlobalVar.thing();
rr.amethod();

Nowadays, with ES2015 you can also use arrow functions, which uses the this value of the outside function:
function foo() {
  let bar = (a, b) => {
    return this;
  };

  return bar();
}

foo.call(Math); // Math

T.J. Crowder's solution of using the second argument of forEach also works nicely if you don't like the idea of the temporary variable (ES5 code: works in pretty much any browser these days, except IE8-).

A: In strict mode if you call a function not through a property reference and without specifying what this should be, it's undefined.
forEach (spec | MDN) allows you to say what this should be, it's the (optional) second argument you pass it:
aGlobalVar.thing.prototype.amethod = function() {
  data.forEach(function(d) {
    console.log(d);
    console.log(this.value);
  }, this);
  // ^^^^
}

Alternately, arrow functions were added to JavaScript in 2015. Since arrows close over this, we could use one for this:
aGlobalVar.thing.prototype.amethod = function() {
  data.forEach(d => {
    console.log(d);
    console.log(this.value);
  });
}

A: What I had to to is add this in the every forEach that I was using (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach ). Binding in the constructor is not needed, as I am using arrow functions. So now my code is:
resetPressed = () => {
    this.transport_options.forEach(function (transport_option) {
        this.pressed_percentages.forEach(function (percentage) {
            filters[transport_option][percentage] = false;
        }, this)
    }, this);

    filters.isFilterActive = false;
    this.setState({
        filtersState: filters,
        opacity: filters.isFilterActive ? 1 : 0.5
    });

}

<TouchableHighlight
    underlayColor={'transparent'}
    onPress={this.resetPressed}
    style={styles.iconView}>


text:
Q: How to compare dataframe dates with the values of row and column keeping weekdays and holidays apart I have a dataframe that represents this:

I need to create another column 'Mark' and here is why it is complicated.
For the value 'C' execution day is Sunday 8/11/2018. The next day would be Monday 9/11/2018.
So I need to calculate the weekdays values of the previous week. For this case I need to calculate 1/11/2018,2/11/2018,3/11/2018,4/11/2018 and 5/11/2018.
However, if the next day of execution day is Friday or Saturday I would need to take the values of the previous week 'Friday' and 'Saturday'. For example, B executes on Thursday 12/11/2018'. The day after is 'Friday'. So I need to calculate the average of the previous week's Fridayand Saturday which are 6/11/2018 and 7/11/2018
Initially I did not had the Day column, which I added afterwords by using
df['Execution']=pd.to_datetime(df['Execution'])
df['Day']=df['Execution'].dt.weekday_name

And I can get to the point where it prints something if execution date matches with one of the column dates. Here is the code-
for j,row in df.iterrows():
x=str(row['Execution'])
x=x[slicing]

for i, val in enumerate (df.columns.values):
    print(df.columns[i])

    if i<l1:
        val=str(val)
        val=val[slicing]
        if x==val: #Execution date matches column date
            print('yay')

I am trying to learn python on my own and I have started by learning pandas dataframe.
However, Now I am lost and could not figure out the logic to proceed. Can anyone enlighten me the way?

A: Here is the code that worked for me with explanation:
for i,row in df.iterrows():
  for j, val in enumerate (range(0,l1-1)):   #l1 is the number of columns
               #subtracted 1 to not take last column in account as I only need the dates

    if df.columns[j+1]==row['Execution']: #to match the date of column execution,with the column dates

        a=pd.to_datetime(df.columns[j+1+1])
        a=a.day_name() #to convert the date in to weekday name
#As for friday I would need previous week's friday and saturday values.
#Therefore, I subtracted 7 and 8 to get the required value. For all the other days I calculated carefully this way so that I get the days right.
        if (a=='Friday'):
            mark=(df.iloc[i,(j+1+1-7)]+df.iloc[i,(j+1+1-6)])/2
#df.iloc(row,column) was used to get the values right
            markList.append(mark)
        elif (a=='Saturday'):
            mark=(df.iloc[i,(j+1+1-7)]+df.iloc[i,(j+1+1-8)])/2
            markList.append(mark)
        elif (a=='Sunday'):
            mark=(df.iloc[i,(j+1+1-7)]+df.iloc[i,(j+1+1-6)]+df.iloc[i,(j+1+1-5)]+MPDr.iloc[i,(j+1+1-4)]+df.iloc[i,(j+1+1-3)])/5
            markList.append(mark)
        elif (a=='Monday'):
            mark=(df.iloc[i,(j+1+1-7)]+df.iloc[i,(j+1+1-6)]+df.iloc[i,(j+1+1-5)]+df.iloc[i,(j+1+1-4)]+df.iloc[i,(j+1+1-8)])/5
            markList.append(mark)
        elif (a=='Tuesday'):
            mark=(df.iloc[i,(j+1+1-7)]+df.iloc[i,(j+1+1-6)]+df.iloc[i,(j+1+1-5)]+df.iloc[i,(j+1+1-8)]+df.iloc[i,(j+1+1-9)])/5
            markList.append(mark)
        elif (a=='Wednesday'):
            mark=(df.iloc[i,(j+1+1-7)]+df.iloc[i,(j+1+1-6)]+df.iloc[i,(j+1+1-8)]+df.iloc[i,(j+1+1-9)]+df.iloc[i,(j+1+1-10)])/5
            markList.append(mark)
        elif (a=='Thursday'):
            mark=(df.iloc[i,(j+1+1-7)]+df.iloc[i,(j+1+1-8)]+df.iloc[i,(j+1+1-9)]+df.iloc[i,(j+1+1-10)]+df.iloc[i,(j+1+1-11)])/5
            markList.append(mark)

df['mark']=markList #To add at the end of the dataframe


text:
Q: Golang Gmail API Error 400: Bad Request, failedPrecondition I'm attempting to send email using Gmail's API but I keep getting the error:
Unable to send googleapi: Error 400: Bad Request, failedPrecondition
exit status 1
I created a service account for this in the console.developers.google.com page and downloaded the private json file. Renamed it GmailService.json and searched through the docs on how to implement it. From what I can tell everything works except when it gets to the send method at the end of the code. Either the service email doesn't allow me to send email or the message is formatted wrong?
package main

import "golang.org/x/oauth2"
import "golang.org/x/oauth2/google"
import "google.golang.org/api/gmail/v1"
import "io/ioutil"
import "log"
import "encoding/base64"
import "strings"

func main() {

    data, err := ioutil.ReadFile("GmailService.json")
    if err != nil {
        log.Fatal(err)
    }

    conf, err := google.JWTConfigFromJSON(data, "https://www.googleapis.com/auth/gmail.send")
    if err != nil {
        log.Fatalf("conf: %v", err)
    }

    client := conf.Client(oauth2.NoContext)

    gmailService, err := gmail.New(client)
    if err != nil {
        log.Fatalf("gmailService: %v", err)
    }

    var message gmail.Message

    messageStr := []byte("From: service-email@gmail.com\r\n" +
        "To: recipient@gmail.com\r\n" +
        "Subject: Testing testing \r\n" +
        "\r\nThis message was created with an api")
    message.Raw = base64.StdEncoding.EncodeToString(messageStr)
    message.Raw = strings.Replace(message.Raw, "/", "_", -1)
    message.Raw = strings.Replace(message.Raw, "+", "-", -1)
    message.Raw = strings.Replace(message.Raw, "=", "", -1)

    _, err = gmailService.Users.Messages.Send("me", &message).Do()
    if err != nil {
        log.Fatalf("Unable to send %v", err)
    }

}


text:
Q: Create one exe file with buil-in static libraries I have project in openCV, created as Makefile application under eclipse (MinGW/Windows 8 os). I need to create one executable file so that there won't be required any other dlls while running app on other computer without openCV installed.
I have also compiled openCV sources as static library. That is what my Makefile (draft) looks like:
all:
    gcc -static -I"C:\opencv\build\include" -L"lib" main.c -lws2_32 -lopencv_core244.dll -lopencv_highgui244.dll -lopencv_imgproc244.dll -o bcast.exe

After building exec doesn't contain libs. What am i doing wrong?
Thanks in advance.

A: You're expected to link *.lib files, not *.dll (Dynamic-Link Library).
So, that should be :
g++ -I"C:\opencv\build\include" -L"lib" main.c -lws2_32 -lopencv_core244.lib -lopencv_highgui244.lib -lopencv_imgproc244.lib -o bcast.exe

(You should consider using g++ for this, it's a c++ library.) After that your makefile will produce 1 .exe file, no libs.
Honestly, did you really recompile the opencv libs statically (with -DBUILD_SHARED_LIBS=OFF)? I'm having doubts here.


text:
Q: Very basic JFrame not showing up I know that this question was asked many times and I've tried solutions mentioned there for last hour, but none of them worked for me. I have very basic frame and it just doesn't show up. No errors, after compilation just "Build succesful".
The whole code is:
import javax.swing.*;
import java.awt.*;

public class Frame extends JFrame
{
    public Frame()
    {
        super("Hello");
        this.setBounds(100, 500, 100, 100);
        this.setDefaultCloseOperation(3);
    }

    public static void main(String[] args)
    {
        new Frame().setVisible(true);
    }
}

Thanks in advance for your help.

A: I think your Frame instance in main is from package java.awt.* which you have imported.
Check it out.

A: I tried your program and the frame shows up fine for me. Couple of steps which you can try -

*

*After running the program, you should check in task manager whether a new Java process is visible and if so, expand it and you should see "Hello", try bringing it to front (right click on process -> Bring to front).

*From a code point of view, try adding this.pack(); after this.setDefaultCloseOperation and re-run the program.

A: Start by reading the Swing tutorial on How to Make Frames.
Download and test the FrameDemo example. It show you the proper way to create Swing components. One key is that Swing components should be created on modified on the Event Dispatch Thread (EDT).
If this code doesn't work then you probably have something wrong with your JDK. Try reinstalling.


text:
Q: VBA Cells vs Range - Why is Cells not working? I have the following code in an excel workbook module. Why don't both E106 and G106 turn yellow??
Sub Macro4()
    Worksheets("Thermal Data").Cells(7, 106).Interior.Color = 65535
    Worksheets("Thermal Data").Range("G106").Interior.Color = 65535
End Sub

A: You should be looking in the wrong cell somewhere. Take a look at this, it works:
Sub Macro4()
    Cells(1, 1).Interior.Color = 65535
    Range("A3").Interior.Color = 65535
End Sub

Hint - in the cell the first value is the row, then the column.


text:
Q: To reverse sentence in python Thank you for all the answers. I got why my code is wrong.
Please don't provide me with solutions because I do have a few but then I want to understand my code is not working.
I think it is due to while x <= -len(split_result):" but then the I think the logic is correct. What is wrong with my code?
O_string = ("Me name is Mr_T")
split_result = O_string.split()
print(split_result)

x=0
list=[]

while x <= -len(split_result):
    list.append(split_result[x-1])
    x = x-1

result=" ".join(list)
print (result)

A: You can reverse a list with [::-1]:
print(' '.join(O_string.split()[::-1]))

Output:
'Mr_T is name Me'

Here [::-1] means take everything from the beginning to the end with a step size of minus one.
Alternatively, you can use the built-in function reversed:
>>> ' '.join(reversed(O_string.split()))
'Mr_T is name Me'

About your algorithm. In my opinion it is always more difficult to think in negative indices. I would suggest to go positive:
O_string = ("Me name is Mr_T")
split_result = O_string.split()

res = []
x = len(split_result) - 1
while x >= 0:
    res.append(split_result[x])
    x = x-1

result=" ".join(res)
print (result)

Output:
'Mr_T is name Me'

Here:
x = len(split_result) - 1

gives you the last index of your list. We start indexing with 0. So you need to subtract 1 from the length of the list.
You count it down with:
x = x-1

and stop as soon as you get a negative index:
while x >= 0:

Hint: Don't use list as a variable name. It is a built-in and should better not be used for naming own objects. If you do, you cannot easily use list() anymore (in the same namespace).

A: can make use of the reverse function as well as str.join
O_string = ("Me name is Mr_T")
split_result = O_string.split()
split_result.reverse()
print " ".join(split_result)

A: In python, list[::-1] will give you the list in which all the elements of the list stored in reverse index position. ie.) reverseList1=list1[::-1] use this.

A: To answer "What is wrong with my code?", let's look at what happens in a shell:
>>> O_string = ("Me name is Mr_T")
split_result = O_string.split()
print(split_result)
['Me', 'name', 'is', 'Mr_T']
>>> x=0
>>> len(split_result)
4
>>> -len(split_result)
-4
>>> x
0
>>> 0 <= 4
True
>>> 0 <= -4
False
>>> x <= -len(split_result)
False
>>> while False: print('this will not get printed')

So, your while loop condition will never be true and the loop will never happen. Here is an example of what works:
x = -1
while x >= -len(split_result):
    list.append(split_result[x])

A: You can try:
>>> O_string = ("Me name is Mr_T")
>>> O_list = O_string.split()
>>> O_list.reverse()
>>> " ".join(O_list)
'Mr_T is name Me'

A: You can use reversed to reverse the sentence:
o_string = "Me name is Mr_T"
words = sentence.split()
o_string = " ".join(reversed(words))
print(o_string)


text:
Q: Android & Java: String.getBytes() not parsing escaped characters properly I have a Java String "Hi\n" that I would like to convert to a byte[], but when I have a variable whose content is "Hi\n" and I call variable.getBytes(StandardCharsets.UTF_8) the \ and n were parsed separately rather than together as a newline character, so I end up with 4 bytes in the array rather than the expected 3 bytes.
How can I perform this conversion correctly?
Edit: Screenshot added. I set a breakpoint where I'm calling getBytes() from, and evaluated the expression when payload is "hi\n", and the evaluation returned a byte[] of 4 bytes. When I do "hi\n".getBytes(StandardCharsets.UTF_8) directly however I get 3 bytes, which confuses me.

A: Rookie mistake on my part. The problem was because the "Hi\n" example was a user-inputted String coming from an Android EditText instead of a real String literal, so the backslash \ was already escaped as \\ and so the actual content of that String was ["H", "i", "\\", "n"]. I added some code to do input sanitization:
// Assume payload is content of an EditText which the user has entered "Hi\n" in
payloadInBytes = payload.replace("\\n", "\n").getBytes(StandardCharsets.UTF_8);

After this payloadInBytes is 3 bytes long as expected.


text:
Q: Laravel Passport pass additional value to return statement I have following IssueToken Class:
<?php

namespace App\Http\Controllers\Api\Auth;

use DB;
use App\Client;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

trait IssueTokenTrait
{
    public function issueToken(Request $request, $grantType, $scope = "")
    {
        $params = [
            'grant_type' => $grantType,
            'client_id' => $this->client->id, // php artisan passport:client --password
            'client_secret' => $this->client->secret,
            'scope' => $scope
        ];

        $request->request->add($params);

        $mail = $request->username;
        $clientTable = DB::table('clients')->where('email', $mail)->first();
        $client = Client::findOrFail($clientTable->id);
        $clientID = $client->id;

        $proxy = Request::create('oauth/token', 'POST');

        return Route::dispatch($proxy);         }
}

Which Returns a token type an expire in and Access token and a refresh token.
Now I want to add the Client_id to the reponse how do I do that?


text:
Q: UItableView Reload Problem I am using a UiTableView in our application.We have two tabs in controller one is add to shopping list where i add more than one items in our shopping list in database,other one is shopping list which shows items for shopping.
The problem is that when i add items from shopping list tab then items are successfully added in database but when i click on shopping list tab then any items not shown in shopping list.
How i reload data in UiTableView when i click on shopping list tab.

A: [shoppingTableView reloadData];

A: you will need to reload your tableview....[tableview reloadData]


text:
Q: How to use a custom class (which extends View class) in activity class to draw path without changing the other parts of the main layout in android I have the following two classes:
1. ImageGalleryDemoActivity (to import an image from gallery)
2. DrawClass (To draw a freehand path on the imported image)
public class ImageGalleryDemoActivity extends Activity {
    private static int RESULT_LOAD_IMAGE = 1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

        }

    }
}

and the following class to draw path on the imported image.
public class DrawClass extends View implements OnTouchListener {

    private Paint paint;
    List<Point> points;
    int DIST = 2;
    boolean flgPathDraw = true;

    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.id.imgView);

    public DrawClass(Context c  ) {
        super(c);
        setFocusable(true);
        setFocusableInTouchMode(true);

        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(2);
        paint.setColor(Color.BLACK);

        this.setOnTouchListener(this);
        points = new ArrayList<Point>();
    }
    public DrawClass(Context context, AttributeSet attrs) {
        super(context, attrs);
        setFocusable(true);
        setFocusableInTouchMode(true);

        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(2);
        paint.setColor(Color.BLACK);

        this.setOnTouchListener(this);
        points = new ArrayList<Point>();

    }

    public void onDraw(Canvas canvas)
    {
        canvas.drawBitmap(bitmap, 0, 0, null);

        Path path = new Path();
        boolean first = true;

        for (int i = 0; i < points.size(); i += 2)
        {
            Point point = points.get(i);
            if (first) {
                first = false;
                path.moveTo(point.x, point.y);
            } else if (i < points.size() - 1) {
                Point next = points.get(i + 1);
                path.quadTo(point.x, point.y, next.x, next.y);
            } else {
                path.lineTo(point.x, point.y);
            }
        }
        canvas.drawPath(path, paint);
    }

    public boolean onTouch(View view, MotionEvent event) {
        // if(event.getAction() != MotionEvent.ACTION_DOWN)
        // return super.onTouchEvent(event);
        Point point = new Point();
        point.x = (int) event.getX();
        point.y = (int) event.getY();

        if (flgPathDraw) {
            points.add(point);
        }

        invalidate();
        Log.e("Hi  ==>", "Size: " + points.size());

        return true;
    }
    public void fillinPartofPath()
    {
        Point point = new Point();
        point.x = points.get(0).x;
        point.y = points.get(0).y;

        points.add(point);
        invalidate();
    }
    public void resetView()
    {
        points.clear();
        paint.setColor(Color.WHITE);
        paint.setStyle(Style.STROKE);
        flgPathDraw=true;
        invalidate();
    }
}

class Point {
    public float dy;
    public float dx;
    float x, y;

    @Override
    public String toString() {
        return x + ", " + y;
    }
}

Now, problem is that I can change whole main layout using setContentView, but I want to keep  the original layout with the "Load Picture" button and draw a path on the image. So, how can I use the DrawClass class in the activity class keeping the original layout?

A: Make a Frame Layout or Relative Layout
which does not diturb the orginal View
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:CustomTexView="http://schemas.android.com/apk/res/com.example.testapp"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_blue_bright"
    android:orientation="vertical" >

    <CustomView
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </CustomView>

    <RelativeLayout
        android:id="@+id/youroriginalviewhere"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </RelativeLayout>

</RelativeLayout>

A: Create an inner class signature with the below code..
public class signature extends View {
        private static final float STROKE_WIDTH = 5f;
        private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
        private Paint paint = new Paint();
        private Path path = new Path();
        private float lastTouchX;
        private float lastTouchY;
        private final RectF dirtyRect = new RectF();
        public signature(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint.setAntiAlias(true);
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeWidth(STROKE_WIDTH);
        }
        @Override
        protected void onDraw(Canvas canvas) {
        canvas.drawPath(path, paint);
        }
        @Override
        public boolean onTouchEvent(MotionEvent event) {
        float eventX = event.getX();
        float eventY = event.getY();
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        path.moveTo(eventX, eventY);
        lastTouchX = eventX;
        lastTouchY = eventY;
        return true;
        case MotionEvent.ACTION_MOVE:
        case MotionEvent.ACTION_UP:
        resetDirtyRect(eventX, eventY);
        int historySize = event.getHistorySize();
        for (int i = 0; i < historySize; i++) {
        float historicalX = event.getHistoricalX(i);
        float historicalY = event.getHistoricalY(i);
        expandDirtyRect(historicalX, historicalY);
        path.lineTo(historicalX, historicalY);
        }
        path.lineTo(eventX, eventY);
        break;
        default:
        debug("Ignored touch event: " + event.toString());
        return false;
        }
        invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
        (int) (dirtyRect.top - HALF_STROKE_WIDTH),
        (int) (dirtyRect.right + HALF_STROKE_WIDTH),
        (int) (dirtyRect.bottom + HALF_STROKE_WIDTH));
        lastTouchX = eventX;
        lastTouchY = eventY;
        return true;
        }

        private void debug(String string) {
        }

        private void expandDirtyRect(float historicalX, float historicalY) {
        if (historicalX < dirtyRect.left) {
        dirtyRect.left = historicalX;
        } else if (historicalX > dirtyRect.right) {
        dirtyRect.right = historicalX;
        }
        if (historicalY < dirtyRect.top) {
        dirtyRect.top = historicalY;
        } else if (historicalY > dirtyRect.bottom) {
        dirtyRect.bottom = historicalY;
        }
        }
        private void resetDirtyRect(float eventX, float eventY) {
        dirtyRect.left = Math.min(lastTouchX, eventX);
        dirtyRect.right = Math.max(lastTouchX, eventX);
        dirtyRect.top = Math.min(lastTouchY, eventY);
        dirtyRect.bottom = Math.max(lastTouchY, eventY);
        }
    }

and create its object signature mSignature =new signature(this, null);

A: Finally I can manage to use DrawClass. I used FrameLayout in place of LinearLayout and use LayoutInflater for using my customView where I have kept a new XML. And in that XML I use a view to connect the DrawClass. The codes are given below, which perhaps will help someone.
View view;
FrameLayout flayout = (FrameLayout) findViewById(R.id.custom_frame);
view = getLayoutInflater().inflate(R.layout.draw, flayout,false);
flayout.addView(view);

in draw.XML
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/crop_content"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
<com.example.imageDrawTest.DrawClass
     android:layout_width="match_parent"
     android:layout_height="match_parent"/>
</FrameLayout>