text:
Q: Android List disappear after intent back to activity I have a CreateReceiptActivity and also QRScan activity, after intent to QR Scan and intent back to CreateReceiptActivity. The list or receipt item becomes empty again ( if I already add item to the list, after that I want to add item again using QR Scan, the item in the list becomes empty again). Can somebody help me with this issue ?

here's the code
public class CreateReceiptActivity extends AppCompatActivity {

    @BindView(R.id.receipt_date)
    TextView date;
    @BindView(R.id.receipt_invoice)
    TextView invoiceNumber;
    @BindView(R.id.btn_receipt_add_item)
    ImageButton addItem;
    @BindView(R.id.btn_receipt_print)
    ImageButton printItem;
    @BindView(R.id.receipt_view_recycler)
    RecyclerView recyclerView;
    @BindView(R.id.create_receipt_pb_loading)
    ProgressBar pbloading;

    private static final int QR_REQUEST_CODE = 1;
    List<ListAutoComplete> autoCompleteList;
    ListAutoComplete listAutoComplete;

    List<ListReceiptItem> receiptItemList;
    ListReceiptItem listReceiptItem;
    ArrayList temporaryList;
    ReceiptItemAdapter adapter;
    public String itemType, itemQty, itemPrice, itemDate, itemInvoice, lastInvoice, qrResult;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_receipt);
        ButterKnife.bind(this);

        receiptItemList = new ArrayList<>();
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ReceiptItemAdapter(this, receiptItemList);
        recyclerView.setAdapter(adapter);
        itemInvoice = invoiceNumber.getText().toString();
        itemDate = setDate(date);
        date.setText(this.getString(R.string.date, setDate(date)));

        printItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case DialogInterface.BUTTON_POSITIVE:
                                pbloading.setVisibility(View.VISIBLE);
                                cutStock();
                                break;

                            case DialogInterface.BUTTON_NEGATIVE:
                                //No button clicked
                                break;
                        }
                    }
                };

                Builder builder = new Builder(CreateReceiptActivity.this);
                builder.setMessage("Print Transaksi ?").setPositiveButton("Ya", dialogClickListener)
                        .setNegativeButton("Tidak", dialogClickListener).show();

            }
        });
        Bundle extras = getIntent().getExtras();
        if(extras != null && extras .containsKey("QRItemtype")){
            qrResult = extras.getString("QRItemtype");
            if (qrResult == null) {
                Toast.makeText(CreateReceiptActivity.this, "Scan gagal", Toast.LENGTH_SHORT).show();
            } else if (!(qrResult == null)) {
                Toast.makeText(CreateReceiptActivity.this, qrResult, Toast.LENGTH_SHORT).show();

            }
        }

        addItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openDialog();

            }
        });

    }

    private void cutStock() {
        final FirebaseFirestore db = FirebaseFirestore.getInstance();

        for (ListReceiptItem listreceiptItem : receiptItemList) {
            final String soldItemDate = date.getText().toString().trim();
            final String soldItemInvoice = invoiceNumber.getText().toString().trim();
            final String soldItemtype = listreceiptItem.getType();
            final String soldItemQty = listreceiptItem.getQty();
            final String soldItemPrice = listreceiptItem.getPrice();

            db.collection("watchlist").whereEqualTo("type", soldItemtype)
                    .get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            Log.d(Tag.ITEM, document.getId() + "=>" + document.getData());

                            String id = document.getString("id");
                            String oldqty = document.getString("qty");
                            Integer i = Integer.parseInt(oldqty) - Integer.parseInt(soldItemQty);
                            String newQty = String.valueOf(i);

                            Map<Object, String> map = new HashMap<>();
                            map.put("qty", newQty);
                            db.collection("watchlist").document(document.getId()).set(map, SetOptions.merge());

                            ArrayList<Map<String, Object>> list = new ArrayList<>();
                            Map<String, Object> receiptItem = new HashMap<>();
                            receiptItem.put("invoice", soldItemInvoice);
                            list.add(receiptItem);
                            receiptItem.put("date", soldItemDate);
                            list.add(receiptItem);
                            receiptItem.put("type", soldItemtype);
                            list.add(receiptItem);
                            receiptItem.put("qty", soldItemQty);
                            list.add(receiptItem);
                            receiptItem.put("price", soldItemPrice);
                            list.add(receiptItem);

                            final FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
                            firebaseFirestore.collection("sales").add(receiptItem).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                                @Override
                                public void onSuccess(DocumentReference documentReference) {
                                    Toast.makeText(CreateReceiptActivity.this, "Berhasil mencetak transaksi", Toast.LENGTH_SHORT).show();
                                    Integer i = Integer.parseInt(soldItemInvoice) + 1;
                                    String newInvoice = String.valueOf(i);
                                    invoiceNumber.setText(newInvoice);
                                    pbloading.setVisibility(View.GONE);

                                }
                            })
                                    .addOnFailureListener(new OnFailureListener() {
                                        @Override
                                        public void onFailure(@NonNull Exception e) {
                                            Toast.makeText(CreateReceiptActivity.this, "Gagal mencetak", Toast.LENGTH_SHORT).show();
                                            pbloading.setVisibility(View.GONE);
                                        }
                                    });
                        }
                    } else {
                        Toast.makeText(CreateReceiptActivity.this, "Barang tidak terdaftar", Toast.LENGTH_SHORT).show();
                        Log.w(Tag.ITEM, "error getting documents", task.getException());
                        pbloading.setVisibility(View.GONE);
                    }
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(CreateReceiptActivity.this, "Barang tidak terdaftar", Toast.LENGTH_SHORT).show();
                    pbloading.setVisibility(View.GONE);
                }
            });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        openDialog();
    }
    private void openDialog(){
        LayoutInflater li = CreateReceiptActivity.this.getLayoutInflater();

        final View v = li.inflate(R.layout.alertdialog_create_receipt, null);
        final Builder builder = new Builder(CreateReceiptActivity.this);
        builder.setView(v);
        final EditText addItemType = v.findViewById(R.id.alertdialog_receipt_type);
        final EditText addItemQty = v.findViewById(R.id.alertdialog_receipt_qty);
        final EditText addItemPrice = v.findViewById(R.id.alertdialog_receipt_price);
        Button btnSubmit = v.findViewById(R.id.alertdialog_receipt_submit);
        addItemType.setText(qrResult);

        final AlertDialog alertDialog = builder.create();
        alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {

                Button btnScan = v.findViewById(R.id.alertdialog_receipt_scanqr);
                btnScan.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent i = new Intent(CreateReceiptActivity.this, QRScannerActivity.class);
                        startActivityForResult(i, QR_REQUEST_CODE);
                    }
                });
            }
        });
        alertDialog.show();

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                itemType = addItemType.getText().toString().trim();
                itemQty = addItemQty.getText().toString().trim();
                itemPrice = addItemPrice.getText().toString().trim();
                listReceiptItem = new ListReceiptItem(itemType, itemQty, itemPrice, "0");
                receiptItemList.add(listReceiptItem);
                recyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                alertDialog.dismiss();
                qrResult = null;
                Toast.makeText(CreateReceiptActivity.this, "barang tertambah", Toast.LENGTH_SHORT).show();
            }
        });

    }

    public void getTypeList() {

        FirebaseFirestore db = FirebaseFirestore.getInstance();
        CollectionReference documentReference = db.collection("watchlist");
        documentReference.get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                Log.d(Tag.ITEM, document.getId() + "=>" + document.getData());

                                String type = document.getString("type");
                                listAutoComplete = new ListAutoComplete(type);
                                autoCompleteList.add(listAutoComplete);
                            }

                        } else {
                            Log.w(Tag.ITEM, "error getting documents", task.getException());
                        }
                    }
                });
    }

    public String setDate(TextView view) {

        java.util.Date today = Calendar.getInstance().getTime();//getting date
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");//formating according to my need
        String date = formatter.format(today);
        view.setText(date);
        return date;
    }

}

This is my QRScan activity:
public class QRScannerActivity extends AppCompatActivity implements View.OnClickListener {

    //View Objects
    private String itemTypeQR;

    //qr code scanner object
    private IntentIntegrator qrScan;

    private static final int QR_REQUEST_CODE = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.qrscanner_activity);

        //intializing scan object
        qrScan = new IntentIntegrator(this);
        qrScan.setOrientationLocked(false);
        qrScan.initiateScan();
    }

    //Getting the scan results
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);

        if (result != null) {
            //if qrcode has nothing in it
            if (result.getContents() == null) {
                Intent qrResult = new Intent(QRScannerActivity.this, CreateReceiptActivity.class);
                itemTypeQR = result.getContents();
                qrResult.putExtra("QRItemtype",itemTypeQR);
                startActivityForResult(qrResult,QR_REQUEST_CODE);
                finish();
            } else {
                //if qr contains data
                try {
                    //converting the data to json
                    JSONObject obj = new JSONObject(result.getContents());
                    //setting values to textviews
                    Intent qrResult = new Intent(QRScannerActivity.this, CreateReceiptActivity.class);
                    itemTypeQR = obj.getString("type");
                    qrResult.putExtra("QRItemtype",itemTypeQR);
                    setResult(RESULT_OK, qrResult);
                    startActivityForResult(qrResult,QR_REQUEST_CODE);
                    finish();
                } catch (JSONException e) {
                    e.printStackTrace();

                    itemTypeQR = result.getContents();
                    Intent qrResult = new Intent(QRScannerActivity.this,CreateReceiptActivity.class);
                    qrResult.putExtra("QRItemtype",itemTypeQR);
                    setResult(RESULT_OK, qrResult);
                    startActivityForResult(qrResult,QR_REQUEST_CODE);
                    finish();
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onClick(View view) {
        //initiating the qr code scan
        qrScan.initiateScan();
    }
}

A: Hi first make your ListReceiptItem implements Parcelable like below:
public class ListReceiptItem implements Parcelable {
      // please keep your methods and variables here as it is
}

Don't forget to write "writeToParcel" method in your ListReceiptItem class and below is only example of "writeToParcel" method. you have to google it if you doesn't know about Parcelable.
@Override
   public void writeToParcel(Parcel dest, int flags) {
    dest.writeLong(this.id);
    dest.writeString(this.name);
    dest.writeString(this.grade);
   }

Then copy paste below two classes as it is because i have just edited it where it passes list from QRScannerActivity to CreateReceiptActivity and after adding items from CreateReceiptActivity it will return that list in QRScannerActivity and we can found it in onActivityResult() of QRScannerActivity. Also don't call finish() after startActivityForResult().

QRScannerActivity

public class QRScannerActivity extends AppCompatActivity implements View.OnClickListener {

    //View Objects
    private String itemTypeQR;

    //qr code scanner object
    private IntentIntegrator qrScan;

    // newly added
    List<ListReceiptItem> receiptItemList = new List<ListReceiptItem>;

    private static final int QR_REQUEST_CODE = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.qrscanner_activity);

        //intializing scan object
        qrScan = new IntentIntegrator(this);
        qrScan.setOrientationLocked(false);
        qrScan.initiateScan();
    }

    //Getting the scan results
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == QR_REQUEST_CODE && resultCode == Activity.RESULT_OK){
            if(data != null && data.getExtras() != null){
                List<ListReceiptItem> receiptItemListNew = (List<ListReceiptItem>) bundle.getParcelable("mList");
                if(receiptItemListNew != null){
                    receiptItemList.clear();
                    receiptItemList.addAll(receiptItemListNew);
                }
            }
        }
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);

        if (result != null) {
            //if qrcode has nothing in it
            if (result.getContents() == null) {
                Intent qrResult = new Intent(QRScannerActivity.this, CreateReceiptActivity.class);
                itemTypeQR = result.getContents();
                qrResult.putExtra("QRItemtype",itemTypeQR);
                qrResult.putParcelable("mList", receiptItemList);
                startActivityForResult(qrResult,QR_REQUEST_CODE);

            } else {
                //if qr contains data
                try {
                    //converting the data to json
                    JSONObject obj = new JSONObject(result.getContents());
                    //setting values to textviews
                    Intent qrResult = new Intent(QRScannerActivity.this, CreateReceiptActivity.class);
                    itemTypeQR = obj.getString("type");
                    qrResult.putExtra("QRItemtype",itemTypeQR);
                    qrResult.putParcelable("mList", receiptItemList);
                    setResult(RESULT_OK, qrResult);
                    startActivityForResult(qrResult,QR_REQUEST_CODE);

                } catch (JSONException e) {
                    e.printStackTrace();

                    itemTypeQR = result.getContents();
                    Intent qrResult = new Intent(QRScannerActivity.this,CreateReceiptActivity.class);
                    qrResult.putExtra("QRItemtype",itemTypeQR);
                    qrResult.putParcelable("mList", receiptItemList);
                    setResult(RESULT_OK, qrResult);
                    startActivityForResult(qrResult,QR_REQUEST_CODE);

                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onClick(View view) {
        //initiating the qr code scan
        qrScan.initiateScan();
    }
}

CreateReceiptActivity

public class CreateReceiptActivity extends AppCompatActivity {

    @BindView(R.id.receipt_date)
    TextView date;
    @BindView(R.id.receipt_invoice)
    TextView invoiceNumber;
    @BindView(R.id.btn_receipt_add_item)
    ImageButton addItem;
    @BindView(R.id.btn_receipt_print)
    ImageButton printItem;
    @BindView(R.id.receipt_view_recycler)
    RecyclerView recyclerView;
    @BindView(R.id.create_receipt_pb_loading)
    ProgressBar pbloading;

    private static final int QR_REQUEST_CODE = 1;
    List<ListAutoComplete> autoCompleteList;
    ListAutoComplete listAutoComplete;

    List<ListReceiptItem> receiptItemList = new List<ListReceiptItem>;
    ListReceiptItem listReceiptItem;
    ReceiptItemAdapter adapter;
    public String itemType, itemQty, itemPrice, itemDate, itemInvoice, lastInvoice, qrResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_receipt);
        ButterKnife.bind(this);

        if(getIntent().getExtras() != null && getIntent().getExtras().contains("mList")){
            receiptItemList.clear();
            receiptItemList.addAll((List<ListReceiptItem>) getIntent().getExtras().getParcelableExtra("mList"));
        }

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ReceiptItemAdapter(this, receiptItemList);
        recyclerView.setAdapter(adapter);
        itemInvoice = invoiceNumber.getText().toString();
        itemDate = setDate(date);
        date.setText(this.getString(R.string.date, setDate(date)));

        printItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case DialogInterface.BUTTON_POSITIVE:
                                pbloading.setVisibility(View.VISIBLE);
                                cutStock();
                                break;

                            case DialogInterface.BUTTON_NEGATIVE:
                                //No button clicked
                                break;
                        }
                    }
                };

                AlertDialog.Builder builder = new AlertDialog.Builder(CreateReceiptActivity.this);
                builder.setMessage("Print Transaksi ?").setPositiveButton("Ya", dialogClickListener)
                        .setNegativeButton("Tidak", dialogClickListener).show();

            }
        });

        addItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LayoutInflater li = CreateReceiptActivity.this.getLayoutInflater();

                final View v = li.inflate(R.layout.alertdialog_create_receipt, null);
                final AlertDialog.Builder builder = new AlertDialog.Builder(CreateReceiptActivity.this);
                builder.setView(v);
                final EditText addItemType = v.findViewById(R.id.alertdialog_receipt_type);
                final EditText addItemQty = v.findViewById(R.id.alertdialog_receipt_qty);
                final EditText addItemPrice = v.findViewById(R.id.alertdialog_receipt_price);
                Button btnSubmit = v.findViewById(R.id.alertdialog_receipt_submit);

                final AlertDialog alertDialog = builder.create();
                alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                    @Override
                    public void onShow(DialogInterface dialog) {

                        Button btnScan = v.findViewById(R.id.alertdialog_receipt_scanqr);
                        btnScan.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent i = new Intent(CreateReceiptActivity.this, QRScannerActivity.class);
                                i.putParcelable("mList", receiptItemList);
                                startActivityForResult(i, QR_REQUEST_CODE);
                            }
                        });
                    }
                });
                alertDialog.show();
                btnSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        itemType = addItemType.getText().toString().trim();
                        itemQty = addItemQty.getText().toString().trim();
                        itemPrice = addItemPrice.getText().toString().trim();
                        listReceiptItem = new ListReceiptItem(itemType, itemQty, itemPrice, "0");
                        receiptItemList.add(listReceiptItem);
                        recyclerView.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                        Toast.makeText(CreateReceiptActivity.this, "barang tertambah", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            return;
        } else if (data != null) {
            if (requestCode == QR_REQUEST_CODE) {
                Bundle extras = getIntent().getExtras();
                    qrResult = extras.getString("QRItemtype");
                if (qrResult == null) {
                    Toast.makeText(this, "Scan gagal", Toast.LENGTH_SHORT).show();
                } else if (!(qrResult == null)) {
                    Toast.makeText(this, qrResult, Toast.LENGTH_SHORT).show();

                }
            }
        }
    }

    private void cutStock() {
        final FirebaseFirestore db = FirebaseFirestore.getInstance();

        for (ListReceiptItem listreceiptItem : receiptItemList) {
            final String soldItemDate = date.getText().toString().trim();
            final String soldItemInvoice = invoiceNumber.getText().toString().trim();
            final String soldItemtype = listreceiptItem.getType();
            final String soldItemQty = listreceiptItem.getQty();
            final String soldItemPrice = listreceiptItem.getPrice();

            db.collection("watchlist").whereEqualTo("type", soldItemtype)
                    .get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            Log.d(Tag.ITEM, document.getId() + "=>" + document.getData());

                            String id = document.getString("id");
                            String oldqty = document.getString("qty");
                            Integer i = Integer.parseInt(oldqty) - Integer.parseInt(soldItemQty);
                            String newQty = String.valueOf(i);

                            Map<Object, String> map = new HashMap<>();
                            map.put("qty", newQty);
                            db.collection("watchlist").document(document.getId()).set(map, SetOptions.merge());

                            ArrayList<Map<String, Object>> list = new ArrayList<>();
                            Map<String, Object> receiptItem = new HashMap<>();
                            receiptItem.put("invoice", soldItemInvoice);
                            list.add(receiptItem);
                            receiptItem.put("date", soldItemDate);
                            list.add(receiptItem);
                            receiptItem.put("type", soldItemtype);
                            list.add(receiptItem);
                            receiptItem.put("qty", soldItemQty);
                            list.add(receiptItem);
                            receiptItem.put("price", soldItemPrice);
                            list.add(receiptItem);

                            final FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
                            firebaseFirestore.collection("sales").add(receiptItem).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                                @Override
                                public void onSuccess(DocumentReference documentReference) {
                                    Toast.makeText(CreateReceiptActivity.this, "Berhasil mencetak transaksi", Toast.LENGTH_SHORT).show();
                                    Integer i = Integer.parseInt(soldItemInvoice) + 1;
                                    String newInvoice = String.valueOf(i);
                                    invoiceNumber.setText(newInvoice);
                                    pbloading.setVisibility(View.GONE);

                                }
                            })
                                    .addOnFailureListener(new OnFailureListener() {
                                        @Override
                                        public void onFailure(@NonNull Exception e) {
                                            Toast.makeText(CreateReceiptActivity.this, "Gagal mencetak", Toast.LENGTH_SHORT).show();
                                            pbloading.setVisibility(View.GONE);
                                        }
                                    });
                        }
                    } else {
                        Toast.makeText(CreateReceiptActivity.this, "Barang tidak terdaftar", Toast.LENGTH_SHORT).show();
                        Log.w(Tag.ITEM, "error getting documents", task.getException());
                        pbloading.setVisibility(View.GONE);
                    }
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(CreateReceiptActivity.this, "Barang tidak terdaftar", Toast.LENGTH_SHORT).show();
                    pbloading.setVisibility(View.GONE);
                }
            });
        }
    }

    public void getTypeList() {

        FirebaseFirestore db = FirebaseFirestore.getInstance();
        CollectionReference documentReference = db.collection("watchlist");
        documentReference.get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                Log.d(Tag.ITEM, document.getId() + "=>" + document.getData());

                                String type = document.getString("type");
                                listAutoComplete = new ListAutoComplete(type);
                                autoCompleteList.add(listAutoComplete);
                            }

                        } else {
                            Log.w(Tag.ITEM, "error getting documents", task.getException());
                        }
                    }
                });
    }

    public String setDate(TextView view) {

        java.util.Date today = Calendar.getInstance().getTime();//getting date
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");//formating according to my need
        String date = formatter.format(today);
        view.setText(date);
        return date;
    }

}


text:
Q: How to build many-to-many relations using SQLAlchemy: a good example I have read the SQLAlchemy documentation and tutorial about building many-to-many relation but I could not figure out how to do it properly when the association table contains more than the 2 foreign keys.
I have a table of items and every item has many details. Details can be the same on many items, so there is a many-to-many relation between items and details
I have the following:
class Item(Base):
    __tablename__ = 'Item'
    id = Column(Integer, primary_key=True)
    name = Column(String(255))
    description = Column(Text)

class Detail(Base):
    __tablename__ = 'Detail'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    value = Column(String)

My association table is (It's defined before the other 2 in the code):
class ItemDetail(Base):
    __tablename__ = 'ItemDetail'
    id = Column(Integer, primary_key=True)
    itemId = Column(Integer, ForeignKey('Item.id'))
    detailId = Column(Integer, ForeignKey('Detail.id'))
    endDate = Column(Date)

In the documentation, it's said that I need to use the "association object". I could not figure out how to use it properly, since it's mixed declarative with mapper forms and the examples seem not to be complete. I added the line:
details = relation(ItemDetail)

as a member of Item class and the line:
itemDetail = relation('Detail')

as a member of the association table, as described in the documentation.
when I do item = session.query(Item).first(), the item.details is not a list of Detail objects, but a list of ItemDetail objects.
How can I get details properly in Item objects, i.e., item.details should be a list of Detail objects?

A: Previous Answer worked for me, but I used a Class base approach for the table ItemDetail. This is the Sample code:
class ItemDetail(Base):
    __tablename__ = 'ItemDetail'
    id = Column(Integer, primary_key=True, index=True)
    itemId = Column(Integer, ForeignKey('Item.id'))
    detailId = Column(Integer, ForeignKey('Detail.id'))
    endDate = Column(Date)

class Item(Base):
    __tablename__ = 'Item'
    id = Column(Integer, primary_key=True)
    name = Column(String(255))
    description = Column(Text)
    details = relationship('Detail', secondary=ItemDetail.__table__, backref='Item')

class Detail(Base):
    __tablename__ = 'Detail'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    value = Column(String)
    items = relationship('Item', secondary=ItemDetail.__table__, backref='Detail')

A: From the comments I see you've found the answer. But the SQLAlchemy documentation is quite overwhelming for a 'new user' and I was struggling with the same question. So for future reference:
ItemDetail = Table('ItemDetail',
    Column('id', Integer, primary_key=True),
    Column('itemId', Integer, ForeignKey('Item.id')),
    Column('detailId', Integer, ForeignKey('Detail.id')),
    Column('endDate', Date))

class Item(Base):
    __tablename__ = 'Item'
    id = Column(Integer, primary_key=True)
    name = Column(String(255))
    description = Column(Text)
    details = relationship('Detail', secondary=ItemDetail, backref='Item')

class Detail(Base):
    __tablename__ = 'Detail'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    value = Column(String)
    items = relationship('Item', secondary=ItemDetail, backref='Detail')

A: Like Miguel, I'm also using a Declarative approach for my junction table. However, I kept running into errors like

sqlalchemy.exc.ArgumentError: secondary argument <class 'main.ProjectUser'> passed to to relationship() User.projects must be a Table object or other FROM clause; can't send a mapped class directly as rows in 'secondary' are persisted independently of a class that is mapped to that same table.

With some fiddling, I was able to come up with the following. (Note my classes are different than OP's but the concept is the same.)
Example
Here's a full working example
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import declarative_base, relationship, Session

# Make the engine
engine = create_engine("sqlite+pysqlite:///:memory:", future=True, echo=False)

# Make the DeclarativeMeta
Base = declarative_base()

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True)
    name = Column(String)
    projects = relationship('Project', secondary='project_users', back_populates='users')

class Project(Base):
    __tablename__ = "projects"

    id = Column(Integer, primary_key=True)
    name = Column(String)
    users = relationship('User', secondary='project_users', back_populates='projects')

class ProjectUser(Base):
    __tablename__ = "project_users"

    id = Column(Integer, primary_key=True)
    notes = Column(String, nullable=True)
    user_id = Column(Integer, ForeignKey('users.id'))
    project_id = Column(Integer, ForeignKey('projects.id'))

# Create the tables in the database
Base.metadata.create_all(engine)

# Test it
with Session(bind=engine) as session:

    # add users
    usr1 = User(name="bob")
    session.add(usr1)

    usr2 = User(name="alice")
    session.add(usr2)

    session.commit()

    # add projects
    prj1 = Project(name="Project 1")
    session.add(prj1)

    prj2 = Project(name="Project 2")
    session.add(prj2)

    session.commit()

    # map users to projects
    prj1.users = [usr1, usr2]
    prj2.users = [usr2]

    session.commit()

with Session(bind=engine) as session:

    print(session.query(User).where(User.id == 1).one().projects)
    print(session.query(Project).where(Project.id == 1).one().users)

Notes

*

*reference the table name in the secondary argument like secondary='project_users' as opposed to secondary=ProjectUser

*use back_populates instead of backref
I made a detailed writeup about this here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot get Custom Attribute Finder to appear in WSO2 Identity Server Console I did some development of a custom AttributeFinder for WSO2 4.6 several years ago, and I am trying to reproduce that old development on one of my original WSO2 4.6 instances, but I cannot get the AttributeFinder to appear in the WSO2 IS Console in Extensions.  I know that 4.6 is old, but I just want to get this working with 4.6 first.

*

*I've built the AttributeFinder in Eclipse successfully

*Put a copy of the JAR in E:\WSO2\wso2is-4.6.0\repository\components\lib

*Put copies of ojdbc6.jar and classes12.jar into E:\WSO2\wso2is-4.6.0\repository\components\lib

[This AttributeFinder is supposed to get the attributes from an Oracle DB]

*

*I've updated E:\WSO2\wso2is-4.6.0\repository\conf\security\entitlement.properties by adding:

PIP.AttributeDesignators.Designator.3=my.myAttributeFinder
  my.MyAttributeFinder.1=databaseUrl,jdbc:oracle:thin:@//192.168.0.xxx:1521/xxxorcl
  my.MyAttributeFinder.2=userName,hr
  my.MyAttributeFinder.3=password,XXXX
  my.MyACAttributeFinder.4=driverName,oracle.jdbc.driver.OracleDriver
  my.MyACAttributeFinder.5=dbTableName,DB_FILTERS

Then I restarted the WSO2 but when I got into the console and look at Extensions/Attributes, it is only showing the default attributes/attributefinder.
As I said, I had this working awhile ago, so I'm sure that the code I used to build the attribute finder class/jar is ok, and the lines I had to add into entitlement.properties above are ok, but it just looks like WSO2 IS doesn't even "know" that I have a custom attribute finder installed, so I think I must be missing some step or something.
Can anyone tell me what else I need to get WSO2 IS to "see" my custom attributes?
Thanks,
Jim

A: I just figure out what the problem was.  I had added my lines to the default, out-of-box entitlement.properties, and in particular, I had the Designator line:

PIP.AttributeDesignators.Designator.3=my.myAttributeFinder

In the default entitlement.properties, there was already only one other PIP Designator lines, something like:

...Designator.1=...

What I didn't realize is that, apparently, the Designator numbering has to be sequential!
So, when I changed the line to:

PIP.AttributeDesignators.Designator.2=my.myAttributeFinder

instead of:

PIP.AttributeDesignators.Designator.3=my.myAttributeFinder

Then, the WSO2 IS picked up my custom finder ok!


text:
Q: Determine the Tangent Space of a Submanifold Let $M:=\{(x_1,x_2,x_3)\in\mathbb{R}^3\colon x_1^2+x_2^2-2x_3^2=x_1+x_2+x_3-1=0\}$ be a given submanifold of $\mathbb{R}^3$. I want to compute $T_p(M)$ at $p=(1,1,-1)$.
My definition of the tangential is the following:
Let $Y$ be open in $\mathbb{R}^l$ and $f\in C^1(X,Y)$. Then the linear map
$T_pf\colon T_pX\longrightarrow T_{f(p)}Y, \ (p,v)\mapsto (f(p),\partial f(p)v)$
is called the tangential of $f$ at the point $p$.
Furthermore, i have that for a $(n-l)$-dimensional submanifold $M:=f^{-1}(c)$ where c is a regular value, that $T_pM=\ker(T_pf)=(T_pf)^{-1}(c)$.
What I could do is the following:
I set $\Phi\colon \mathbb{R}^3\longrightarrow \mathbb{R},\ (x_1,x_2,x_3)\mapsto ( x_1^2+x_2^2-2x_3^2,x_1+x_2+x_3-1)$
and already know that $\Phi^{-1}(0)$ is the submanifold in question.
I now need the matrix for $T_pf$ and I struggle to construct it. The Jakobi Matrix of $\Phi$ is no problem. Do I just have to compute $f(p),\partial f(p)$ and put it in the form $(f(p),\partial f(p)v)$ like mentioned above?

A: Let $f=x_1^2+x_2^2-x_3^2$ and $g=x_1+x_2+x_3-1$.
Being the intersection of the two 2-D Manifolds F given by  $f=0$ and G, given by $g=0$, the intersection (call it C) is a 1-D submanifold of the both of them. The point $p$ lies in C and we want to know a tangent vector to C at $p$ and that would define the tangent space entirely (since it is a 1-D space, knowing any vector in it fully specifies it). Note that because C lies in both F and G, a tangent vector to C at $p$ must be perpendicular to normals to both F and G (this tangent vector belongs in both tangent spaces $T_pF$ and $T_pG$). In other words, the cross product $$\nabla f \times \nabla g$$ must be in the tangent space of C at $p$.
The computation of the vector is trivial. So I'll leave it to you to take it from here.
Second approach
To use your defintions of the tangent space (kernel of the differential map). The tangent space of F at P is $(Df)^{-1}(0)$ and likewise for G. The tangent space of C is $  (Df)^{-1}(0) \cap (Dg)^{-1}(0) $. Noting that for $f:\mathbb{R}^3\to\mathbb{R}$, at the point $p$, $Df$ is given by the matrix $[2,2,4]$ and $Dg$ by the Jacobian $[1,1,1]$.  So, we are looking for tangent vectors of the form $\vec{t}=(u,v,w)$ that satisfy the matrix equation.
$$\left[\begin{array}{cc}1 &1&1\\2&2&4\end{array}\right] \left[\begin{array}{cc}u \\v\\w\end{array}\right]= \left[\begin{array}{cc}0\\0\end{array}\right] $$
That is, vectors proportional to $\vec{t}=(-1,1,0)$ make up the tangent space at $p$.  You can write down the coordinates of the tangent line if you want as $\vec{p}+s\vec{t}$ where you let the parameter $s$ take all values on the real line.


text:
Q: Google spreadsheet error TypeError: Cannot read property 'filter' of undefined I am taking data from a sheet and then converting it to json, so far all good. But when I am trying to take out specific data from arrays but it is making undefined if I get data from array, but when I use raw json data everything works fine
function doGet(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Users');
  var userData = getUser(ss);
  var array = userData.user.filter(function b(e) { return e.id == 11281 });

  console.log(array)
}

function getUser(ss){
  var usr = {};
  var usrArray = [];

  var data = ss.getRange(2,1,ss.getLastRow(), ss.getLastColumn()).getValues();

  for (var i=0, l=data.length; i<l; i++){
    var dataRow = data[i];
    var record = {};

    record['id'] = dataRow[1];
    record['name'] = dataRow[0];
    record['profession'] = dataRow[2];

    usrArray.push(record);
  }
  usr.user = usrArray;

  var result = JSON.stringify(usr);
  return result;
}

ERROR: TypeError: Cannot read property 'filter' of undefined
Error picture
Sheet data picture
If I console log the result directly the it is working fine like this: Output

A: JSON.stringify returns a string — the getUser function returns a string. And you're trying to read the user property from it which returns undefined.
You could do a JSON.parse in doGet but it's simpler to just return the usr object from getUser.
function getUser(ss) {
  const usr = {}
  const usrArray = []

  // populate usrArray
  usr.user = usrArray
  return usr
}

And there's another issue. You're setting record['id'] to dataRow[1] but it should be dataRow[0] since id is the first column (This is why the shared screenshot has the name in the id property). You could also refactor the code.
function getUser(ss) {
  const data = ss
    .getRange(2, 1, ss.getLastRow(), ss.getLastColumn())
    .getValues()

  const users = data.map((row) => ({
    id: row[0],
    name: row[1],
    profession: row[2],
  }))

  return {
    user: users,
  }
}

I would also recommend renaming the user property to users for clarity.


text:
Q: Can't retrieve session in Laravel Blade view I set up a controller to pass errors if validation fails and another message if passed it.
if ($v->fails()) {
    return redirect('tickets/create')->withInput()->withErrors($v->errors());
} else {
    $ticket_id = $this->salvataggio($request);

    return redirect('tickets/' . $ticket_id . '/edit')
        ->with(['status' => 'success']);
}

In the blade file of the view, I can read the error variable but I can't read the status.
@if(Session::has('status'))

{{Session::get('status')}}

@endif

I have read and tried many methods to retrieve Session but it seems doesn't work. I've already used this method on a previous project with Laravel 5 but in this version (8.11.0), has something has changed?

A: You have to create the session first...
// Via a request instance...
$request->session()->put('status', 'success');

// Via the global helper...
session(['status' => 'success']);

And then you can retrieve the session data...
// Via a request instance...
$value = $request->session()->get('status');

// Via the global helper...
$value = session(['status']);

A: You used the with method so you should change your code like below:
@if($status)

{{$status}}

@endif


text:
Q: php - use uploaded file as embedded image After searching Stack Overflow and the net for this answer, I am requesting assistance.  I  currently have a form that allows allows a user to upload a file.  It is my desire that once this file is uploaded, to then use it as an embedded image in an HTML email by phpmailer.  I can upload the file, but when I pass the info to the next page, the code is not picking up the file.
The form uses this label for the attachment (put spaces so code shows up):

  Attachment
    <input type="file" name="file_attach[]"/>

When the form is submitted, the action calls email4.php (which then sends the mail to a local postfix server.  In this code, I reference the file as a variable:
$mypromo = $_FILES['file_attach'];

Then I use that variable as the embedded image:
$mail->AddEmbeddedImage($mypromo, "my-attach", "tourney");

Once I send the email, the email comes thru, but no image.  Previously, the image shows up if I reference a file on the file system with a path/filename.  Is there a way I can use an uploaded file as an embedded image in phpmailer?


text:
Q: How do I use Ctrl + End to go to the last formatted cell? Using Ctrl + End on a excel worksheet goes to the last cell in the range (moves in the direction of the arrow) that has some content in it. This usually ignores formatted cells. That is, if you're in cell A1 and you have copied a formatting that goes down to A13, you can't use Ctrl + End to jump down to A13.
How do I do that?

A: You can use the buttons End Home.
In the screenshot, the last populated cell is B3, but the format has been copied into C6, which extends the used range to that cell. You can get to the end of the used range by pressing End Home directly after one another.
There's no keyboard shortcut to jump to the last formatted cell in a row or column. The  Ctrl  + arrow keys shortcut only jumps to the last cell that has content.


text:
Q: Which is better collection() or root element in cts:search option in MarkLogic In one of my projects, MarkLogic consultant advised me to use collection() in cts:search, and in another project, ML consultants have advised to use root element in cts:search. In both projects, we had the same volume of documents. Which one is better with respect to performance?
Let's say we have a document (I am taking a small document just to explain the scenario). It has collection named "demo":
<root>
<child1>ABC</child1>
<child2>DEF</child2>
<child3>GHI</child3>
<child4>JKL</child4>
</root>

Which case is better/more efficient:
cts:search(/root, cts:and-query((....some cts:queries..)))
cts:search(collection("demo"), cts:and-query((....some cts:queries..)))
Please help me with an explanation which one is better than other.

A: They are both single term lookups, as far as search execution goes, so performance should be the same.
The real distinction is about how you want to manage your content. You can have more than one collection on the same document, so you can slice the same content multiple way, but you can only have one root element. Collections also let you abstract away from the details of document structure: you could have multiple different root elements within the same collection.

A: As per MarkLogic documentation "MarkLogic's implementation of collections is designed to optimize query performance against large volumes of documents.". So, it means you can identify the difference on only huge database.
I tried to identify this by practical, so I created two XQuery, one with collection and one with element as you suggested. But, I put xdmp:query-trace(fn:true()) at the top of both the XQuery. I ran both the query one by one and analysed my MarkLogic log file.
If it is element XQuery:
2018-11-12 15:16:58.448 Info: App-Services: at 5:12: xdmp:eval("declare namespace sem = "http://marklogic.com/semantics&quo...", (), <options xmlns="xdmp:eval"><database>5310618057872024096</database>...</options>)
2018-11-12 15:16:58.448 Info: App-Services: at 5:12: Analyzing path for search: fn:collection()/sem:triples
2018-11-12 15:16:58.448 Info: App-Services: at 5:12: Step 1 is searchable: fn:collection()
2018-11-12 15:16:58.448 Info: App-Services: at 5:12: Step 2 is searchable: sem:triples
2018-11-12 15:16:58.448 Info: App-Services: at 5:12: Path is fully searchable.
2018-11-12 15:16:58.448 Info: App-Services: at 5:12: Gathering constraints.
2018-11-12 15:16:58.448 Info: App-Services: at 5:12: Step 2 contributed 1 constraint: sem:triples
2018-11-12 15:16:58.449 Info: App-Services: at 5:12: Search query contributed 1 constraint: cts:element-value-query(xs:QName("sem:object"), "taxonomy", ("lang=en"), 1)
2018-11-12 15:16:58.449 Info: App-Services: at 5:12: Executing search.
2018-11-12 15:16:58.464 Info: App-Services: at 5:12: Selected 65964 fragments to filter

and if it is collection XQuery:
2018-11-12 15:20:07.871 Info: App-Services: at 5:11: xdmp:eval("declare namespace sem = "http://marklogic.com/semantics&quo...", (), <options xmlns="xdmp:eval"><database>5310618057872024096</database>...</options>)
2018-11-12 15:20:07.871 Info: App-Services: at 5:11: Analyzing path for search: fn:collection("/triples")
2018-11-12 15:20:07.871 Info: App-Services: at 5:11: Step 1 is searchable: fn:collection("/triples")
2018-11-12 15:20:07.871 Info: App-Services: at 5:11: Path is fully searchable.
2018-11-12 15:20:07.871 Info: App-Services: at 5:11: Gathering constraints.
2018-11-12 15:20:07.871 Info: App-Services: at 5:11: Step 1 contributed 1 constraint: fn:collection("/triples")
2018-11-12 15:20:07.875 Info: App-Services: at 5:11: Search query contributed 1 constraint: cts:element-value-query(xs:QName("sem:object"), "taxonomy", ("lang=en"), 1)
2018-11-12 15:20:07.875 Info: App-Services: at 5:11: Executing search.
2018-11-12 15:20:07.891 Info: App-Services: at 5:11: Selected 65964 fragments to filter

The difference is clearly noticable. If we are using collection query, MarkLogic is doing everthing almost in single step "1" but if it is element query, MarkLogic is doing two step process.


text:
Q: how to discover where my app opens more files (Too many open files)? I did a script to execute every 10 minutes and when the files open on my Java app is greater than 10000 it will execute a jmap command to give to me a heapdump.
My intention is to discover which class of my app is not closing the files or where there is a memory leak or why I receive the message "Too many files open" after 20 hours executing it.
This is my script. Does anybody have other ways or tools to discover where my app is not closing the files? Thanks a lot!
#!/bin/bash

rm openfiles.log
flag=1
for (( ; ; ))
do
   sleep 10m
   files=`ps -A x |grep iscsi | awk '{print $1}' | xargs -I '{}' ls /proc/29192/fd  | wc -l`
   msg="open files: $files - date: `date`"
   echo "$msg     - infinite loops [ hit CTRL+C to stop]"
   echo $msg >> openfiles.log

   if [ $files -gt 10000 ] && [ $flag -eq 1 ]
   then
      jmap -F -dump:file=heapdump.hprof 29192
      flag=0;
      echo "############################################ heapdump of 29192" >> openfiles.log
   fi
   echo "" >> openfiles.log
done

A: Take a look at File Leak Detector written by Kohsuke Kawaguchi of Jenkins fame. It is a java agent that you attach to your java process.
There are also other ways to scan for them via FindBugs/PMD, etc. I'd take a look at SonarQube. There are rules specifically about not closing resources.


text:
Q: How to compare and display the data continuously from the text file? At first I am getting the month of event from the text file and from the SAP calendar. And then I am comparing the both month, if both are same then event of the same month should be displayed if I click the navigate button.
It's only displaying the events of the month which is last in the list of text file. I want to display all the events as month wise.
Here is my code:
     calendar.attachChangeCurrentDate(function(oEvent) {
     text= text.replace(/-/g,":");
      var amber=text.split(':');

      for (var j=1;j<amber.length;j+=4)
        {

        switch(amber[j]){
        case '01' : amber[j]="Jan";
        break;
        case '02' : amber[j]="Feb";
        break;
        case '03' : amber[j]="Mar";
            break;
        case '04' : amber[j]="Apr";
            break;
        case '05' : amber[j]="May";
            break;
        case '06' : amber[j]="Jun";
            break;
        case '07' : amber[j]="Jul";
            break;
        case '08' : amber[j]="Aug";
            break;
        case '09' : amber[j]="Sep";
            break;
        case '10' : amber[j]="Oct";
            break;
        case '11' : amber[j]="Nov";
            break;
        case '12' : amber[j]="Dec";
            break;
        default:"gokka makka";
            }
        }

        var comp=oEvent.getParameters().currentDate;
        var tmp=comp.split(' ');
        var disp="";
        for(var p=1;p<amber.length; p=p+4)
        {

        if(amber[p]==tmp[1])
        {
            disp+=amber[p-1]+amber[p]+amber[p+1]+":"+amber[p+2];
            msgLabel.setText(disp);

        }
        else
        {   msgLabel.setText("no Events");}
        }

        });


text:
Q: docker build command doesn't refresh my source files I made a typo in my source code and I noticed it after i run docker-compose up in my cli. I tried rebuilding the project but didn't change my index.js cached code.
This is my Dockerfile
FROM node:alpine

WORKDIR '/app'

COPY package.json .
RUN npm install
COPY . .

CMD [ "npm","start" ]

docker-compose.yml
version: '3'
services:
  redis-server:
    image: 'redis'
  node-app:
    build: .
    ports:
      - "4001:8081"

I recreated the image
$ sudo docker build -t phillalexakis/visits:latest .

and run
docker-composer up

It didn't change the source code at all, what have I completely missed? (I'm new with docker)

A: Docker-compose is looking for an image named [folder_name]_node-app, but the image you've built is tagged phillalexakis/visits.
Change your node-app service in docker-compose.yml file :
  node-app:
    build: .
    image: node-app

And use docker-compose to build the images:
docker-compose build or docker-compose up --build


text:
Q: javascript onclick scroll to div on middle page but with button when i press the button "continue"  , but i need with button
problem with that https://jsfiddle.net/ytgu1fbo/7/ , i dont know where can put the button image
https://gyazo.com/c5c62db350d09245e30e7452c0cb3362 example on internet
When i clicked the button , like continue button , go to middle page

Click here

A: Replace  tag with  tag will give the image button you want by specifying the dimensions.
<img src="image.jpg" alt="Click here" height="<px>" width="<px>" style="cursor: pointer;" onclick="scroll_to_contact_form_fn()" />


text:
Q: How to convert an ascii code to an actual character in Maya I am currently developing a mel script in Maya, but am unable to print a character based on its ascii code (for example 65 should print 'A'), as the char(xx) command in other languages.
How can I achieve that ?
Thanks !

A: The other way is to use a python command inside MEL script:
$n = 65;
print("BB" + python("chr("+$n+")") + "CC");

result:
BBACC

A: In case someone is looking for the same answer, the way I finally implemented it is to create a string containing all charaters and then picking the right character in the string using the substring command.


text:
Q: C# and Oracle, login Form: Operation is not valid due to the current state of the object   private void bLogIn(object sender, EventArgs e)
    {

        string logging = "select * from CLIENT where LOGIN='" + this.t_Login.Text + "' and PASSWORD='" + this.t_Password.Text + "' ;";

        OracleConnection conn = new OracleConnection("Data Source=XXX/orcl;User Id=XXX;Password=XXX;");
        OracleCommand cmd = new OracleCommand();

        cmd.CommandText = logging;
        cmd.Connection = conn;
        try
        {
            conn.Open();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        int count = 0;

        OracleDataReader reader = cmd.ExecuteReader();  // At this line there is the error: Operation is not valid due to the current state of the object

        while (reader.Read())
        {
           count = count + 1;
        }
        if (count == 1)
        {
        MessageBox.Show("Welcome");
        }
        else
        {
            MessageBox.Show("Wrong Password");
        }
        conn.Dispose();
    }

This is code that was working for MySQL, but after conversion to Oracle it's not working. What am I doing wrong? Where's the difference. It should be so easy as in MySQL, right?
Why "OracleDataReader reader = cmd.ExecuteReader();" causes error: "Operation is not valid due to the current state of the object" ???

A: You are not assingning the connection to cmd.. try code below
OracleCommand cmd = new OracleCommand();
cmd.connection = conn;
cmd.CommandText = logging;
int count = 0;
OracleDataReader reader = cmd.ExecuteReader();


text:
Q: Using NumPy in Visual Studio I downloaded http://pytools.codeplex.com/ (Python Tools for Visual Studio) so that I could write Python in Visual Studio.
The problem is when I try to use the most basic package "numpy" like so:
import numpy

It says "No module named 'numpy'."
How can I use NumPy and SciPy in Visual Studio?
Note: I am using Canopy Express on another machine which works perfectly; however, I don't want to install it on this machine since I already have Visual Studio installed.
I added the Python 3.3 environment to my Python "solution" by right-clicking Python environments and clicking add an environment. But, after right-clicking my environment and clicking install Python package, I typed in "numpy" and got this error when trying to install it:
...
creating build
creating build\src.win32-3.3
creating build\src.win32-3.3\numpy
creating build\src.win32-3.3\numpy\distutils
building library "npymath" sources
No module named 'numpy.distutils.msvccompiler' in numpy.distutils; trying from distutils
error: Unable to find vcvarsall.bat
----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 1 in c:\users\dom\appdata\local\temp\pip_build_Dom\numpy
Storing complete log in C:\Users\Dom\pip\pip.log
'numpy' failed to install. Exit code: 1

How can I install NumPy?

A: Two solutions worked for me:

*

*Going directly to my Python folder and installing the packages using pip.

*Creating a virtual environment in my project and installing packages from within Visual Studio.

A: In Visual Studio 2013 Community Edition with a Python 2.7 environment, the following worked for me:
Open the Python Environments menu in Solution Explorer, and click on "Install Python Package..."

Then write "numpy":

A: Consider using a more feature-rich Windows distribution of Python, like Anaconda. It comes with a boatload of packages included into the installer. This is quite handy for those who are new to Python, especially when they are using Windows.
Edit:
As of 2020, I would suggest using the python.org distribution of Python. Compiler issues on ms-windows have finally been fixed, so a lot of projects now provide binary packages (wheels) for ms-windows. Among others numpy, pandas, matplotlib, pillow, Cython and PyNaCl.
Note that wheel names ending in:

*

*win_amd64.whl are for 64-bit versions of ms-windows, and

*win32.whl are for 32-bit.

A: I actually ran into the same set of problems when trying to use Visual Studio for Python.
I managed to get things to work at the end - please see Using Visual Studio 2013 for Python (3.4) with NumPy and SciPy on Windows for details. Essentially you can either use the installer (if one is available) or use pip to do the installation.

A: Make sure C++ Common Tools are installed in Visual Studio:

A: From PTVS Installation:

2. Installing packages individually
Here are some recommended packages. Generally you want to install packages using pip or through the interface in Visual Studio (which uses pip), as this will ensure that you get the latest version that will work with your version of Python, as well as any dependencies.
Some packages have complex dependencies and need to be downloaded manually, either from the project's website or from Christoph Gohlke's package collection.

I installed numpy and scipy from these links, and it works perfectly with Visual Studio.

*

*numpy http://sourceforge.net/projects/numpy/files/NumPy/

*scipy http://sourceforge.net/projects/scipy/files/scipy/

*Matplotlib http://matplotlib.org/downloads.html

*Pandas http://pandas.pydata.org/getpandas.html

A: See under Extra in the Visual Studio (Extra-Python-Interactive Window).
It has the ability to switch the interactive console through a different platform/Python version (32-bit, 64-bit, Debug, and Anaconda (which has the NumPy package)).

A: Well, if anyone still has problem than what worked for me is:
C:/Users/DELL/AppData/Local/Programs/Python/Python39/python.exe -m pip install numpy

where the first part is simply the path of python.


text:
Q: How to fix "Function returned undefined, expected Promise or value" error when function loops I have an android application I developed, that allows the sign up of users. I wrote a firebase cloud function that triggers when a User is created, to generate a 5-digit random integer value for the user who just signed up and it stores the generated code in firebase real time database in the following structure.
MainProject
     |
     |-Codes
         |-UniqueUID_1
                |-code:72834
         |-UniqueUID_2
                |-code:23784

The function that I deployed in order to make sure that the code generation is in the backend, is as seen below. There is a value "checker" which is initialised as 0. I use this value to determine when to exit the while loop. Basically I want the function to generate a 5-digit random value, then check the real time database if that generated value exists in all entries under "Codes", then if it does not exist, append it to the Codes under the relevant UID. If it exists, checker remains zero and the loop continues.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

var checker = 0;
exports.createUserCode = functions.auth.user().onCreate(event => {

    while (checker == 0){
        var newRand = getUserCode(89999,10000);
        var userObject = {
            uCode : newRand
        };
        //run a db query to strategically check value generated
        return admin.database().ref("Codes/").orderByChild("uCode").equalTo(newRand).once("value",snapshot => {
            if (!snapshot.exists()){
                checker = 1;
                //add uCode into respective uid slot under Codes
                console.log(""+newRand+" : "+event.uid);
                return admin.database().ref('Codes/' + event.uid).set(userObject);

            }else{
                checker = 0;
                console.log("uCode "+newRand+" exists");
                console.log("uCode generation failed for: "+event.uid);
            }
        });
    }
});

function getUserCode(size, add){
    return Math.floor(Math.random()*size+add);
}

I tested it and it worked fine. I thought the problem was solved. However, on the 7th to 11th trial, it gave me a Function returned undefined, expected Promise or value error. I tried it again after a while, and it generated the code fine. Some one else tested it and it brought the same error.
How can I fix this issue to ensure it always works? Thanks in advance.

A: It's really not clear to me what this function is supposed to do, and the top-level while loop doesn't make sense to me.  However, I can see there are a few things wrong with what this code is doing.
First of all, it's depending on the global state checker too heavily.  This value will not be the consistent for all function invocations, because they all won't be running on the same server instance.  Each running server instance will see a different value of checker.  Please watch this video series for more information about how Cloud Functions runs code.
Second of all, when checker has a value of 1 when the function starts, the function will do exactly what the error message says - it will return undefined.  It should be pretty easy to see how this happens by reading the code.
To fix this, I suggest first coming up with a clear description of what this function is supposed to do when invoked.  Also, I would strongly suggest eliminating dependency on global variables, unless you are absolutely certain you understand what you're doing and the effect they have.

A: I had the same problem a while ago. ESLint won't allow the function to complete because it evaluates whether every part of your code returns a promise.
From what i can see the first part of the if does return something. Try returning a boolean in the else block.
if (!snapshot.exists()){
                checker = 1;
                //add uCode into respective uid slot under Codes
                console.log(""+newRand+" : "+event.uid);
                return admin.database().ref('Codes/' + event.uid).set(userObject);

            }else{
                checker = 0;
                console.log("uCode "+newRand+" exists");
                console.log("uCode generation failed for: "+event.uid);
return false;
            }


text:
Q: tar.bz2 7zip selective extract prformance We use tar.bz2 as our archive of server logs.  We also write tools that selectively parse these archived logs.  Many times I must regex-search one file's lines in the archive to determine if other logs contained in the same archive are relevant to the parsing needs.  (I have a regex match for the file name/path)
From a performance stand point I think I facing some limits.  But it could be that I have a gap in my knowledge.  I mostly script in python and have some basic bash skills.  The archives are large and stored on a mount.  I would like to avoid as much reading and local/temp storage as I can and especially when archives don't qualify for a full parsing.
Option 1 (waste bandwidth and cpu resources save local storage)

*

*Read the whole bz2 file to local disk.

*Uncompress the tar as I scan the file list.

*Uncompress again to search the first log file.

*Then if this archive qualifies uncompress again to extract the log that I must parse.

*Move on to the next archive

Or (waste local storage and waste less bandwidth)

*

*Read the whole bz2 file to local disk.

*Extract most of the files that meet a potential interesting criteria (would need to take most everything)

*Now every file is just on my local file system.  Scan the first log

*Then if it qualifies move on to the log that I must parse.

*Delete all the local storage and move on to next archive.

When I research compression tools like 7zip zip rar bz2…   Most links give me information about compression speed and compression size.   I would like to use something like 7zip because the compression size is important long term.  This is not the base of my question!
But I also 'think' that zip has the ability to expose the full file list and extract one file without decompressing the whole archive.  (Because the file list is in headers…)
But zip is not very native on Linux.
Is there a way to optimize the process using the existing tar.bz2?
What are some tools / methods I should consider?  (Switch out tar, use 7zip?)

A: zip is not native to linux, but if you have the source you probably should not care.
On the other hand 7zip and xz have better performance, and compressing a tar file of multiple entries with similar data is better for compression than zip which does essentially one file at a time. This makes it possible for zip to recover when one file is broken (due to corruption) where a compressed tar archive is often has more problems to recover and/or more unrecoverable.
If you have a chance to change the compressed bz2 file generation (likely otherwise you would not ask), do the following instead of generating the tar.bz2:

*

*generate an index.lst using find <list_of_files_to_archive> > index.lst

*generate a tar.xz from index.lst + list_of_files_to_archive

That way you can quickly extract the index.lst file without decompresing the whole archive and determine on the contents of index.lst if you have the right archive. I am not sure if standard tar stops after extracting index.lst (there could be another one in the archive), so use the python tar module to make sure you stop after extracting (and you immediately parse the index.lst file without need for storing on disk, extra speedup).


text:
Q: CLLocationManager updateLocation never called while app is in background I've read so many question here at stackoverflow and I am still having issues with CLLocationManager.I have already added keys in info.plist (NSLocationAlwaysAndWhenInUseUsageDescription,NSLocationWhenInUseUsageDescription,NSLocationAlwaysAndWhenInUseUsageDescription). My app supports ios 9.0 to 11.x.
Update:- I'm testing on iphone6 ios 11.0.3 physical device
My Approach -
 1. Start updating location after while using the app permission.
 2. When app goes into background stop location manager to remove Blue Banner (Banner Of Shame)
 3.Fire a periodic timer of 30 seconds and start location manager again.
This time I never got the delegate callback didUpdateLocation
I have a singleton class called LocationManager.
Here is my code from LocationManager and AppDelegate
LocationManager
- (void)startLocatingUser {
    //Locate User
    _locationMeasurements = [NSMutableArray array];
    self.geocoder = [[CLGeocoder alloc] init];

    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    self.locationManager.pausesLocationUpdatesAutomatically = NO;
    self.locationManager.activityType = CLActivityTypeAutomotiveNavigation;

    if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
        [self.locationManager setAllowsBackgroundLocationUpdates:YES];
    }

    if(IS_OS_8_OR_LATER) {
        if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [self.locationManager requestAlwaysAuthorization];
        }
    }

        if (@available(iOS 11.0, *)) {
            self.locationManager.showsBackgroundLocationIndicator = NO;
        }

    [self.locationManager startUpdatingLocation];

}

- (void)stopLocatingUser {

    if(self.locationManager) {
        [self.locationManager stopUpdatingLocation];
    }
}

AppDelegateCode
- (void)applicationWillResignActive:(UIApplication *)application {

    _isBackgroundMode = YES;
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    LocationManager* locationManager = [LocationManager sharedLocationManager];
    [locationManager stopLocatingUser];

    __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];

    self.bgTimer = [NSTimer scheduledTimerWithTimeInterval:30.0
                                                      target:self
                                                    selector:@selector(startTrackingBg)
                                                    userInfo:nil
                                                     repeats:YES];
}

-(void)startTrackingBg {
    dispatch_async(dispatch_get_main_queue(), ^{
        LocationManager* locationManager = [LocationManager sharedLocationManager];

        [locationManager startLocatingUser];
    });

    NSLog(@"App is running in background");
}

I am never getting this delegate callback in background once I stop and start location manager again.
- (void)locationManager:(CLLocationManager *)manager

     didUpdateLocations:(NSArray *)locations

What I simply want is whenever user puts the app in background. I want to hide the banner of shame and then I need periodic location updates in background and send them to server.


text:
Q: Making a label inside a user control click through-able for all mouse events? I have a custom button control. There is obviously a label inside it for the text, and when I click on the label it obviously doesn't trigger the buttons click, event, or mouseenter, or mouseleave. What I need to do is make the label act like its not even there (click-throughable) . What I used to do is:
base.Click += value;
foreach (Control i in Controls) {
    i.Click += value;
}

this used to work fine, but now I have my button's label be a different colco each time the mouse hovers over it, so i go over the button, it becomes one color (lets say red), then i go over the label and it becomes green, then back over to the label-free part, and its yellow. This looks pretty bad so I need it to ignore the label all together.

A: Don't use a label.  Too much of a pain and far too expensive.  Override the button's OnPaint() method to draw the text.

A: There is a way which can make the behaviour uniform, but it might look equally unconventional.
First set FlatStyle property of the button to Flat. So that takes away the default visual effects which happens on mouse hovering.
Second, set FlatAppearance.MouseDown and MouseHover properties (you can do it in designer) the color u prefer.
Third, since label's doesnt have FlatAppearance property, you have to set it manually by hooking the MouseHover and MouseLeave events of the label and set the colour u want. (Hope you will initially give the label the BackColor the same as button's when you dont have mouse over both button and label).
Fourth, You should also hook the Button MouseHover and MouseLeave events to set the label the required color too..
Pretty hackish.. I assume clicking part is ok for u now.


text:
Q: aSmack + Android : MultiUserChat class; getMembers, getModerators, etc not working? i'm using aSmack (Smack port for Android) to connect to and communicate with an XMPP server (Openfire 3.7.1).  i can get multi user chat to work as far as sending messages with the MultiUserChat class.  however, calling any method that lists the occupants of the room fails.  relevant code:
setDefaultConnection();
if(connection!=null) {
    mMuc = new MultiUserChat(connection, "hermitage_recycling@conference.jmartinw7");
    try {
        mMuc.join("chester");
        mMuc.getModerators();         //line 71
        ArrayList<Affiliate> dudes = new ArrayList<Affiliate>(mMuc.getMembers());
        Iterator<Affiliate> iter = dudes.iterator();
        while(iter.hasNext()) {
            Affiliate dude = iter.next();
            Log.w(this.getClass().getName(), dude.getNick());
        }
    } catch(XMPPException xmppe) {
        Log.w(this.getClass().getName(), "MUC error: "+xmppe.getMessage());
    }
}

logcat:
07-10 13:38:56.248: ERROR/AndroidRuntime(13003): FATAL EXCEPTION: main
    java.lang.ClassCastException: org.jivesoftware.smack.util.PacketParserUtils$2
    at org.jivesoftware.smackx.muc.MultiUserChat.getOccupants(MultiUserChat.java:1797)
    at org.jivesoftware.smackx.muc.MultiUserChat.getModerators(MultiUserChat.java:1761)
    at org.apache.android.xmpp.XMPPClient$1.onClick(XMPPClient.java:71)
    at android.view.View.performClick(View.java:2532)

is there something wrong with the library or am i doing something wrong?  getOccupants() seems to work.
MultiUserChat example and javadocs:
http://www.igniterealtime.org/builds/smack/docs/latest/javadoc/
http://www.igniterealtime.org/builds/smack/docs/latest/documentation/extensions/index.html
aSmack:
http://code.google.com/p/asmack/
http://code.google.com/p/asmack/issues/detail?id=72

A: I believe your problem is being caused by a failure for asmack to load the smack.providers file which tells asmack which classes to load. If you read the README it describes how to load the smack.providers file into asmack(Thanks Flow). You need to do this before starting any XMPP activity.
Try https://github.com/Flowdalic/asmack, as the version you are working off has not been updated in 2 years.

A: Please read the README of aSmack and follow the instructions about the ProviderManager.


text:
Q: get string from class to class i have class m1
that have inside it
new m2().execute();
        new m3().execute();
so
public class m1 extends Activity {

new m2().execute();
        new m3().execute();
 class m2 extends AsyncTask<String, String, String> {
 public void s {

                         String  id3 = map12.get("CourseID");
}
}
 class m3 extends AsyncTask<String, String, String> {
}//m3
}//m

how can i get the id3 to class m3 ? knowing it is change eachthime

A: Declare it as part of your constructor, and pass it along when you instantiate it (assuming you're calling it from m1.
private String id3;

public m3(String theId3) {
    id3 = theId3;
}

A: Make id3 public static in this class m1 and then access it diretly in class m3 like m1.id3.
     public class m1 extends Activity {
       public static String id3;
        //your code
          }

     public class m3 {
       m1 Object1=new m1();  //make object of class m1
       Object1.id3;  // You can access id3 in class m3
        //your code
          }


text:
Q: Once again: JS functions and objects So I am reading up on JS with Programming JS applications and JS the goodparts. Reading through objects and functions.. which are apparently the same. According to Crockford himself (and practically everybody). But then I ask: if they are the same then why if I have an object:
var myObject = {
    value: 0,
    increment: function (inc) {
        this.value += inc;
    }
};

I can add a function like so:
myObject.double = function () {
    this.value += this.value;
}

But when I have a constructor (a function..) :
var myConstructor = function() {
     this.value = 0;
     this.increment = function(inc){
         this.value += inc;
     };
};

I cannot add a function like this:
myConstructor.double = function(){
    this.value += this.value;
};

But only over the prototype like this:
myConstructor.prototype.double = function(){
    this.value += this.value;
};

Now how can anybody say that object and function are the same??
Interestingly, the assignment of the "double" method to the constructor does not give an error, only when you create an object afterwards with new and call the double method on this object does it give: "TypeError can not find".
Also, console.log on the constructor gives:
{ [Function] double: [Function] }

Notice the missing comma between "[Function]" and "double" by the way.. But this probably shows that really functions are actually objects because we just added the double property (a function) to this object.
But then the question becomes... why can I call new on myConstructor and not on myObject ?? How does JS distinguish between them? If they are both objects which can consists of properties, values and functions..?
EDIT: ok, so I get they are not the same, sorry for my imprecise wording. But one question remains: how does JS know the difference between an object with a function property and a constructor to which properties have been added?
var object = {
    property : "value",
    method: function(){

    }
};

console.log(object) outputs to:
{ property: 'asdf', method: [Function] }

and
var myConstructor = function() {
    this.property = "value";
    this.method = function(inc){

     };
};

myConstructor.property = "value";

console.log(myConstructor) outputs to:
{ [Function] property: 'value' }

So if an object has an anonymous function JS knows its a constructor? Or does it know that over the prototype maybe?

A:
How does JS know the difference between an object with a function
  property and a constructor to which properties have been added?

There are different terminologies:

*

*Functions are objects which are Function instances.

*Callable objects are objects with an internal [[Call]] method.

*Constructors are objects with an internal [[Construct]] method.

Usually they coincide, so it's usual to call them all functions.
Then it's easy:

*

*If you attempt to call an object and it has a [[Call]] method, that method will be called. Otherwise it's not callable, so error.

*If you attempt to instantiate an object and it has a [[Construct]] method, that method will be called. Otherwise it's not a constructor, so error.

Moreover, there is the [[Class]] internal property, which for functions is usually "Function".


text:
Q: Loading a wallpaper (or background layer) in a Cocoa app I have created a very minimal OS X install on a USB stick to use as emergency boot media. Basically what the install is, is a clone of the Mac OS X Install DVD with the installer and packages stripped out. I have my own launch daemon starting an app launcher when the install starts.
The problem right now is that the wallpaper is just a blank gray screen (like the background you get when you first boot OS X and you get the Setup Assistant). I would like to load a custom wallpaper. I've already tried using NSWorkspace's setDesktopImageURL:forScreen:options:error method. This method works when using a complete install of OS X, but not on my minimal one.
The one example I have of a wallpaper being loaded in this minimal interface is Apple's LCA.app (In the OS X Installer DVD/System/Installation/CDIS). It starts the language chooser when you boot the OS X DVD, and also loads a custom background wallpaper. I've taken a look at the binary for the app using otool, and I see that there are some methods for loading a wallpaper in there, but they seem to be private methods used by the app.
Does anyone have any ideas on how to do this? One possibility I can see is just loading a layer behind my app that acts as a wallpaper. Is it possible to do this?

A: Can you add your image at:
/System/Library/CoreServices/DefaultDesktop.jpg
?


text:
Q: How to split a single XML file into multiple based on tags I have an XML file that have tags. I want to split files like this.
<?xml version="1.0" encoding="UTF-8"?>
<EMPRMART CREATION_DATE="08/20/2018 18:06:44" REPOSITORY_VERSION="187.96">
<REPOSITORY NAME="REP_DEV" VERSION="187" CODEPAGE="UTF-8" DATABASETYPE="Sybase">
<FOLDER NAME="MC_DEV"
    <CONFIG DESCRIPTION ="Default ORDER configuration object" ISDEFAULT ="YES" NAME ="default_ORDER_config" VERSIONNUMBER ="1">
        <ATTRIBUTE NAME ="Advanced" VALUE =""/>
        <ATTRIBUTE NAME ="Order type" VALUE ="NO"/>
    </CONFIG>
    <ORDER DESCRIPTION ="" ISVALID ="YES"
        <ATTRIBUTE NAME ="Normal" VALUE =""/>
        <ATTRIBUTE NAME ="Order type" VALUE ="NO"/>
    </ORDER>
    <ORDER DESCRIPTION ="" ISVALID ="YES"
        <ATTRIBUTE NAME ="Medium" VALUE =""/>
        <ATTRIBUTE NAME ="Order type" VALUE ="NO"/>
    </ORDER>
    <ORDER DESCRIPTION ="" ISVALID ="YES"
        <ATTRIBUTE NAME ="Advanced" VALUE =""/>
        <ATTRIBUTE NAME ="Order type" VALUE ="NO"/>
    </ORDER>
    <LOCATION DESCRIPTION ="" ISENABLED ="YES"
    </LOCATION>
</FOLDER>
</REPOSITORY>
</EMPRMART>

Below is the code tried . But it is generating every single line into a new file
awk  '
    BEGIN { RS = "</ORDER>" }
    $0 ~ /[^[:blank:]\n]/ {
        printf "%s\n", $0 RS >> FILENAME "_" ++i ".xml"
    }
' test.xml

I want to split this file based on ORDER tags alone as mentioned below
File1.xml
    <ORDER DESCRIPTION ="" ISVALID ="YES"
        <ATTRIBUTE NAME ="Normal" VALUE =""/>
        <ATTRIBUTE NAME ="Order type" VALUE ="NO"/>
    </ORDER>
File2.xml
    <ORDER DESCRIPTION ="" ISVALID ="YES"
        <ATTRIBUTE NAME ="Medium" VALUE =""/>
        <ATTRIBUTE NAME ="Order type" VALUE ="NO"/>
    </ORDER>
File3.xml
<ORDER DESCRIPTION ="" ISVALID ="YES"
        <ATTRIBUTE NAME ="Advanced" VALUE =""/>
        <ATTRIBUTE NAME ="Order type" VALUE ="NO"/>
    </ORDER>

A: To achieve what you request, I would not make use of awk, but rather a good XML-parser such as xmlstarlet or xmlint. There is a single unknown here, and that is the total amount of nodes with the name ORDER. We could write down an advanced XPath for the selection, but we will keep it simple:
xmlstarlet sel -t -v 'count(//ORDER)' file.xml

Now that you have the count, you can loop over all cases and write them to the files:
#!/usr/bin/env bash
xmlfile=file.xml

n=$(xmlstarlet sel -t -v 'count(//ORDER)' file.xml)
for i in $(seq 1 $n); do
   xmlstarlet sel -t -m "//ORDER[${i}]" -c . $xmlfile > "File${i}.xml"
done

A: If you do use gnu awk this should give your requested result.
awk '/<ORDER>/ {f=1;++a} f {print > "file_"a".xml"} /<\/ORDER>/ {f=0}' file

It will print only lines from <ORDER> to </ORDER> as a section in files called file_1.xml, file_2.xml etc.

A: With any awk in any shell on every UNIX box:
awk '/<ORDER/{f=1; out="file_"(++c)".xml"} f{print > out} /<\/ORDER>/{close(out); f=0}' file

it's obviously fragile as it's just doing regexp matches against text, not parsing the XML, but it'll work for the sample you posted and any similar text.


text:
Q: Problems with branches, messed up my master on a fork I've gotten myself into a pickle with Git and I don't really know what I've done, or how to get back to where I expected to be.
I'll go through what I did and remember doing:

*

*I forked the F# Charting Repo and cloned it.

*I made a branch IsMarginVisibleSupport

*Made a single commit to the branch.

*Pushed the changes to my remote.

*Made a PR.

*Don Syme merged it into the F# Charting Repo.

*I deleted my branch on Git Hub.

*Checked out master and did a git up.

*Deleted the branch locally.

I thought all was good...
I then went to make another change

*

*Created another branch, IsMarginVisible-TestsAndComments

*Made 4 commits into it.

Things look OK on this branch.
I now tried to update my master with any changes that may have been made on the F# Charting remote. I'm not sure where or when in the process I did this and I'm not exactly sure what I did, I found stuff from various places but now I have a history that looks like this:

I have no idea what I've done...
Also at some point I have pushed my branch to GitHub: Also, I have pushed my branch to GitHub.
All I wanted was any changes off Git Hub in my branch before I sent a PR up again.
Any ideas how I can make it look as it should please?

A: It looks like you commited to master by accident ("Uncomment IsMarginVisible"). Therefore you could not perform a fast forward to upstream/master and created a new merge commit, cluttering your commit history.
You should reset your master:

*

*git checkout master

*git reset --hard upstream/master after verifying that you don't have any important uncommited changes. This will roll back any changes (commited and uncommited) to the state of upstream/master!

*Do not pull at this point.

*git push --force origin master
Your master now is in sync with the upstream master again and your fork/origin should have all the changes that were in the upstream master.
Remember, don't commit to master if you are working on forks for GitHub OSS projects, it makes life easier.

A: type git reflog on your local machine and you will see the whole history of what you have done so far.
From the graph that you showed here it look like your branch is not merged into master yet.
As long as you do not push no harm has been done, simply merge your local branches and verify the commit graph before you push.


text:
Q: $f(f(x)) = x \Longleftrightarrow f(x) = x$ if $f(x)$ is monotonically increasing. Can it work for monotonically decreasing $f(x)$ or $f(f(f(x)))$ If $f(x)$ is a monotonically increasing function, then equations  $f(f(x)) = x$ and  $f(x) = x$ are equivalent, meaning I can solve a simpler equation $f(x) = x$ instead of a more complex one $f(f(x)) = x$.
Here is an example of this: instead of solving $1 + \sqrt{1+\sqrt{x}} = x$ I can solve $1+\sqrt{x} = x$
The trick above is possible because $f(x) = 1+\sqrt{x}$  is a monotonically increasing function.
Question 1: the trick above needs strictly monotonic (strictly increasing) or weakly increasing (non-decreasing) would also work?
Question 2: is there any rule like that for $f(f(f(x))) = x$ or $f(f(f(f(x)))) = x$, etc  ($f$ being monotonically increasing)?
Question 3: can the trick above work for monotonically decreasing function? And how?  $f(f(x)) = x\Longleftrightarrow f(x) = -x$ ?
Question 4: is there any rule like that for $f(f(g(x))) = x$ or $f(g(g(x))) = x$ being $f$ or $g$ or both are monotonic?

A: It may help
Generally $f(f(x))=x$ means that the function $f(x)=f^{-1}(x)$ ($f(x)$
is self inverse if it is a a bijection). $f(x)=x$ happens to be a self inverse function.
So the double arrow in your title is not OK it works in reverse only.
Some interesting self inverse functions are $f(x)=\pm x, a/x, (1-x^k)^{1/k}, x\in [0,1], k>0, f(x)=\frac{ax+b}{cx-a}.$


text:
Q: PostgreSQL, function use? I have function like this :
CREATE OR REPLACE FUNCTION f_insert_account(usernames character varying, passwds
character varying, identitass integer, jeniss smallint, statuss smallint, cnames
character varying, unames character varying)
RETURNS character varying AS
$BODY$
DECLARE
iduserx int4;
usernamex varchar;
er int2:=0;
pesan varchar:='';
BEGIN
insert into t_account(username,passwd,identitas,jenis,status,cname,uname)
values(usernamex,f_encr(passwds),identitass,jeniss,statuss,cnames,unames);
RETURN pesan;
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;
ALTER FUNCTION f_insert_account(usernames character varying, passwds character
varying, identitass integer, jeniss smallint, statuss smallint, cnames character
varying, unames character varying) OWNER TO postgres;

GRANT EXECUTE ON FUNCTION f_insert_account(usernames character varying, passwds
character varying, identitass integer, jeniss smallint, statuss smallint, cnames
character varying, unames character varying) TO public;

GRANT EXECUTE ON FUNCTION f_insert_account(usernames character varying, passwds
character varying, identitass integer, jeniss smallint, statuss smallint, cnames
character varying, unames character varying) TO postgres;

then I use that like this :
select f_insert_account('dayat', 'dayat', 1, 1, 1, 'cname', 'uname')

Error like this always appear :
ERROR: function f_insert_account("unknown", "unknown", integer, integer, integer, "unknown", "unknown") does not exist
SQL state: 42883
Hint: No function matches the given name and argument types. You may need to add explicit type casts.
Character: 8
why is that ???
thanx,
Dayat

A: The smallint datatype is a bit of a gotcha, since you need to cast these:
select f_insert_account('dayat', 'dayat', 1, 1::smallint, 1::smallint, 'cname', 'uname')

If you want to avoid this, I suggest changing your function definition to use plain old integer types.


text:
Q: Trivializations of Tangent Bundle over 1-skeleton that do not extend to 2-skeleton, etc. Examples I am reading up on Stiefel-Whitney classes $w_k(T_M)$ on $m$-manifolds; $k=1,2,\dots,m$, which are described as obstacles to extending a trivialization of a bundle, from the $k$-skeleton (assume manifolds are nice-enough to admit a cell-decomposition); for $k=1$, it is just the obstruction to orientability (we just define $w_1$ over embedded circles $C$, and define $w_1(C)=0$ if $C$ preserves orientation, and $w_1(C)=1$ otherwise. A nowhere-zero vector field is equivalent to orientability)
Question: anyone know of an example of a manifold $M$, say for $\dim \leq4$ that admits a trivialization over its $1$-skeleton (i.e., $M$ is orientable), but so that the trivialization does not extend to the $2$-skeleton? (and, is this trivialization over the $1$-skeleton a line bundle as the restriction to the $1$-skeleton of the $\mathbb R^4$-bundle?)
Even better if there are examples of trivialization over $1$- and $2$-skeleton, but not $3$-skeleton, etc.
Thanks in Advance,
Jeff.

A: Well this has been open for a while, but you want a manifold with non-trivial second homology class right? What about $\mathbb{C}P^2$?


text:
Q: Underlining string in Groovy How to write a string to a flat text file and specify underlining using Groovy or Java?  Basically I'm converting a program from SQR to Groovy and SQR has this functionality but of course it uses a method that I do not have access to view so can't see how they're doing it.  The SQR output looks odd but it works when printed and unfortunately I can't copy and paste it here but here's an image:

The words CODE and TRAN DESC get underlined when printed.  I'm not sure what the whole BS thing is about other than it looks very much like a hard-coded carriage return character that I have used in previous programs.

A: You would have to write the backspaces there simply in their unicode representation.
println "____\u0008\u0008\u0008\u0008CODE"

This would print four underscores, four backspaces, and the word.
If you have to do this alot, then a helper would help like this:
String underline(String text) {
    "_"*text.size() + "\u0008"*text.size() + text
}

assert underline("CODE")=="____\u0008\u0008\u0008\u0008CODE"


text:
Q: How to keep floating action button anchored to my view after unlocking the lock screen? I have a FloatingButton anchored to a view in CoordinatorLayout, all ok, but if I lock the screen and unlock back, the FloatinButton loses its anchored property and stay floating at bottom for a while.
Source code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.user.myapplication.ScrollingActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/app_bar_height"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_scrolling" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|end"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

As you can see, floatingButton is anchored to app_bar view:

But, if the screen is locked and unlocked back with this activity running, I'm having this for a few seconds:

This issue occurs on Android 4.2 and above,
Some idea?

A: I found a solution finally, just set the FloatingActionButton´s visibility to GONE in activity´s onPause() method and then set its visibility to VISIBLE in activity´s onResume() method, works nice for this case cause the FloatingActionButton recover its anchored properties when is shown again,
Source code:
    @Override
    protected void onResume() {
        fab.setVisibility(View.VISIBLE);
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        fab.setVisibility(View.GONE);
    }

That´s all,
Hope it helps everybody with this weird issue.