text:
Q: Adding data to arraylist Please help.
After developing an interface to communicate between fragments "Calculator" (Sending Info) and "ShoppingList" (Receiving Info) I can't seem to get the information to be added to my ArrayList. I know the information was sent over but I just can't seem to get it added to the list in order to incorporate it in my listview.
Also, I should not. If I hardcode the information in
eg: myItems.add(new ListItems(R.drawable.thrash, "Cornflakes", 1, 50.00, 60.00));
it works fine
Please Help.
Calculator.java
public class Calculator extends Fragment {

private static EditText ItemText, Editcost, Editquantity, Calcost, Rtax;
private static RadioGroup rgroup;

CalculatorListener activityCommander;

public interface CalculatorListener{
   public void addtoCart(String itemName, int qty, double beforeTax, double afterTax);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try{
        activityCommander = (CalculatorListener) context;
    }catch (ClassCastException e){
        throw new ClassCastException(context.toString());
    }
}

public Calculator() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_calculator, container, false);

    Editcost = (EditText)view.findViewById(R.id.editcost);
    ItemText = (EditText)view.findViewById(R.id.itemText);
    Editquantity = (EditText)view.findViewById(R.id.editquantity);
    Calcost = (EditText)view.findViewById(R.id.calcost);
    Rtax = (EditText)view.findViewById(R.id.rtax);

    rgroup = (RadioGroup)view.findViewById(R.id.rgroup);

    final ImageButton FieldButton = (ImageButton)view.findViewById(R.id.FieldButton);
    final ImageButton TaxButton = (ImageButton)view.findViewById(R.id.TaxButton);
    final ImageButton CalButton = (ImageButton)view.findViewById(R.id.CalButton);

    Rtax.setEnabled(false);
    Calcost.setEnabled(false);

    ItemText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                                          @Override
                                          public void onFocusChange(View v, boolean hasFocus) {
                                              if (!hasFocus) {
                                                  v.setBackgroundResource(R.drawable.edittxt);
                                              } else {
                                                  v.setBackgroundResource(R.drawable.edittxtfocus);
                                              }
                                          }
                                      }
    );

    Calcost.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                                         @Override
                                         public void onFocusChange(View v, boolean hasFocus) {
                                             if (hasFocus) {
                                                 v.setBackgroundResource(R.drawable.edittxtfocus);
                                             } else {
                                                 v.setBackgroundResource(R.drawable.edittxt);
                                             }
                                         }
                                     }
    );

    Editcost.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                                          @Override
                                          public void onFocusChange(View v, boolean hasFocus) {
                                              if (hasFocus) {
                                                  v.setBackgroundResource(R.drawable.edittxtfocus);
                                              } else {
                                                  v.setBackgroundResource(R.drawable.edittxt);
                                              }
                                          }
                                      }
    );
    Editquantity.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                                              @Override
                                              public void onFocusChange(View v, boolean hasFocus) {
                                                  if (hasFocus) {
                                                      v.setBackgroundResource(R.drawable.edittxtfocus);
                                                  } else {
                                                      v.setBackgroundResource(R.drawable.edittxt);
                                                  }
                                              }
                                          }
    );

    CalButton.setOnClickListener(
            new View.OnClickListener(){
                public void onClick(View v){
                    results(v);
                }

            }
    );

    return view;

}

public void results (View view)
{

    double taxValue = Double.parseDouble(Rtax.getText().toString()), cost = 0, newCost = 0;

    int quantity = 1, radiobuttonID = rgroup.getCheckedRadioButtonId(), index;

    String item = ItemText.getText().toString();

    //FIELD VALIDATIONS
    if(Editcost.getText().toString().isEmpty())
    {
        Toast show = Toast.makeText(getActivity(), "Cost is required!", Toast.LENGTH_SHORT);
        show.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
        show.show();
    }

    //CHECKS THE TAX VALUE IF IT NEEDS TO BE CONVERTED
    if (taxValue > 1)
    {
        taxValue = taxValue / 100;
    }
    else
    {
        taxValue = taxValue * 1;
    }

    //CUSTOM VALIDATOR FOR QUANTITY FIELD
    if (Editquantity.getText().toString().isEmpty())
    {
        quantity = 1;
    }
    else if (!Editquantity.getText().toString().isEmpty())
    {
        quantity = Integer.parseInt(Editquantity.getText().toString());
    }

    //DECIDE WHETHER TO USE TAX INCLUDED OR EXCLUDED
    View radioButton = rgroup.findViewById(radiobuttonID);
    index = rgroup.indexOfChild(radioButton);

    if(index == 0)
    {
        newCost = (((cost = Double.parseDouble(Editcost.getText().toString())) * taxValue) + cost) * quantity;
    }
    else if (index == 1)
    {
        newCost = ((cost = Double.parseDouble(Editcost.getText().toString())) * quantity);
    }

    //PRINTS NEW COST TO SCREEN
    Calcost.setText("" + newCost);

    //CUSTOM HINT POP UP
    if(!item.isEmpty())
    {
        Toast show = Toast.makeText(getActivity(), item+" was added to cart", Toast.LENGTH_LONG);
        show.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        activityCommander.addtoCart(item, quantity, cost, newCost);
        show.show();

    }else if(item.isEmpty() & !Editcost.getText().toString().isEmpty())
    {
        if (index == 0 || index == 1)
        {
            Toast show = Toast.makeText(getActivity(),"Item was added to cart", Toast.LENGTH_LONG);
            show.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            activityCommander.addtoCart(item, quantity, cost, newCost);
            show.show();
        }

    }

}

}
Core.java
public class Core extends AppCompatActivity implements Calculator.CalculatorListener{

Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;

@Override
protected  void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.core);
    toolbar = (Toolbar)findViewById(R.id.toolBar);
    setSupportActionBar(toolbar);
    tabLayout = (TabLayout)findViewById(R.id.tabLayout);
    viewPager = (ViewPager)findViewById(R.id.viewPager);
    viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
    viewPagerAdapter.addFragments(new Calculator(),"Calculator");
    viewPagerAdapter.addFragments(new ShoppingList(), "Shopping Cart");
    viewPager.setAdapter(viewPagerAdapter);
    tabLayout.setupWithViewPager(viewPager);

}

@Override
public void addtoCart(String itemName, int qty, double beforeTax, double afterTax) {
    ShoppingList mShoppingList = (ShoppingList) getSupportFragmentManager().findFragmentById(R.id.ShopFrag);
    if(mShoppingList != null)
    {
        mShoppingList.populatelist(itemName, qty, beforeTax, afterTax);
    }
    else{
        Log.e(Tag,"Cart is Null");
    }

}

ShoppingList.java
    package com.sta.salestaxaccumulator;

import android.app.LauncherActivity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class ShoppingList extends Fragment {

    public List<ListItems> myItems = new ArrayList<ListItems>();

    public ShoppingList() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {

        View view = inflater.inflate(R.layout.fragment_shopping_list, container, false);
        populatelistview(view);
        //setCart();
        return view;

    }

    public void populatelist(String itemName, int qty, double beforeTax, double afterTax)
    {

        myItems.add(new ListItems(R.drawable.thrash, itemName, qty, beforeTax, afterTax));
        //myItems.add(new ListItems(R.drawable.thrash, "Cornflakes", 1, 50.00, 60.00));

        /*Toast show = Toast.makeText(getActivity(),itemName+" is here", Toast.LENGTH_LONG);
        show.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
        show.show();*/
    }

    /*public void setCart(String itemName, int qty, double beforeTax, double afterTax)
    {
        //myItems.add(new ListItems(R.drawable.thrash, "Cornflakes", 1, 50.00, 60.00));
        //myItems.add(new ListItems(R.drawable.thrash, "Cheese", 1, 80.00, 90.00));
        //myItems.add(new ListItems(R.drawable.thrash, "Rice", 1, 40.00, 70.00));
        //myItems.add(new ListItems(R.drawable.thrash, "Oatmeal", 2, 35.00, 62.00));
    }*/

    public void populatelistview(View view)
    {
        ArrayAdapter<ListItems> adapter = new MyListAdapter();
        ListView listView = (ListView)view.findViewById(R.id.listView);
        listView.setAdapter(adapter);
    }

    private class MyListAdapter extends ArrayAdapter<ListItems>
    {
        public MyListAdapter()
        {
            super(getActivity(), R.layout.custom_row, myItems);
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            //Ensures we have a view to work with (may have been given null)
            View itemView = convertView;
            if (itemView == null) {
                itemView = getActivity().getLayoutInflater().inflate(R.layout.custom_row, parent, false);
            }

            //Finds the item to work with
            ListItems currentitem = myItems.get(position);

            //Fills the view
            ImageView imageView = (ImageView) itemView.findViewById(R.id.Thrash);
            imageView.setImageResource(currentitem.getIconID());

            //Item Name
            TextView name = (TextView) itemView.findViewById(R.id.ItemName);
            name.setText(currentitem.getItemName());

            //Item Qty
            TextView qty = (TextView) itemView.findViewById(R.id.QuantityValue);
            qty.setText("" + currentitem.getQty());

            //Before Tax
            TextView btax = (TextView) itemView.findViewById(R.id.BeforeTaxValue);
            btax.setText("" + currentitem.getBeforeTax());

            //After Tax
            TextView atax = (TextView) itemView.findViewById(R.id.AfterTaxValue);
            atax.setText("" + currentitem.getAfterTax());

            imageView.setTag(currentitem);

            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    myItems.remove(myItems.get(position));
                    notifyDataSetChanged();
                }

            });

            return itemView;
        }

    }

}

ListItems.java
    package com.sta.salestaxaccumulator;

public class ListItems {
    private int IconID;
    private String ItemName;
    private int Qty;
    private double BeforeTax, AfterTax;

    public ListItems(int iconID, String itemName, int qty, double beforeTax, double afterTax) {
        IconID = iconID;
        ItemName = itemName;
        Qty = qty;
        BeforeTax = beforeTax;
        AfterTax = afterTax;
    }

    public int getIconID() {
        return IconID;
    }

    public String getItemName() {
        return ItemName;
    }

    public int getQty() {
        return Qty;
    }

    public double getBeforeTax() {
        return BeforeTax;
    }

    public double getAfterTax() {
        return AfterTax;
    }

}

Core.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    xmlns:tools2="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.sta.salestaxaccumulator.Core">

    <android.support.design.widget.AppBarLayout
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:id="@+id/AppBarFrag">

        <include
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            layout="@layout/toolbar_layout"/>

        <android.support.design.widget.TabLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/tabLayout"
            app:tabMode="fixed"
            app:tabGravity="fill">

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

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

    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/viewPager"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/AppBarFrag">

        <fragment
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:name="com.sta.salestaxaccumulator.Calculator"
            tools2:layout="@layout/fragment_calculator"
            android:id="@+id/CalcuFrag" />

        <fragment
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:name="com.sta.salestaxaccumulator.ShoppingList"
            tools2:layout="@layout/fragment_shopping_list"
            android:id="@+id/ShopFrag"/>

    </android.support.v4.view.ViewPager>

</RelativeLayout>

ViewPagerAdapter.java
    public class ViewPagerAdapter extends FragmentPagerAdapter{

    ArrayList<Fragment> fragments = new ArrayList<>();
    ArrayList<String> tabTitles = new ArrayList<>();

    public void addFragments(Fragment fragments, String titles)
    {
        this.fragments.add(fragments);
        this.tabTitles.add(titles);

    }

    public ViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return tabTitles.get(position);
    }
}

A: You should check if your cart is null before calling one of it's methods.
ShoppingList cart = (ShoppingList)getSupportFragmentManager().findFragmentById(R.id.shoppinglistfrag);
if(cart != null){
    cart.setCart(view,itemName,qty,beforeTax,afterTax);
}
else{
    Log.e(TAG, "null cart");
}

From the FragmentManager docs:

Finds a fragment that was identified by the given id either when
  inflated from XML or as the container ID when added in a transaction.
  This first searches through fragments that are currently added to the
  manager's activity; if no such fragment is found, then all fragments
  currently on the back stack associated with this ID are searched.

So, it seems as though you have never created or used the ShoppingList fragment, so the FragmentManager can't find it.
Try adding the ShoppingList to your Activity as a local variable and initializing it in your MainActivity onCreate...
public class Core extends AppCompatActivity implements Calculator.CalculatorListener{

    Toolbar toolbar;
    TabLayout tabLayout;
    ViewPager viewPager;
    ViewPagerAdapter viewPagerAdapter;
    ShoppingList mShoppingList;

    @Override
    protected  void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        ...

        mShoppingList = new ShoppingList();

    }

    @Override
    public void addtoCart(View view,String itemName, int qty, double beforeTax, double afterTax) {
        mShoppingList.setCart(view,itemName,qty,beforeTax,afterTax);
    }
}

Edit:
As for your ShoppingList class, make your ListView and ArrayAdapter class variables. Then you can access them from your populatelist() method. After adding the items to your your list, call adapter.notifyDataSetChanged().
Note:
In the future, ask a new question, don't completely change the existing question. It gets confusing for others coming to look for answers in the future.


text:
Q: Typescript: How to transform function chain to Tagged Template literal? Till now I have this (missing implementation is not important here):

interface Context {
  User:     "OK"      | "KO"                    //  | "..."
  Password: "valid"   | "invalid"               //  | "..."
  Message:  "Welcome" | "Invalid credentials"   //  | "..."
  // ...
}

// I = Input, O = Output, H = Header
declare var I :Context , O :Context

interface Examples<H extends unknown[]> { // by @jcalz :)
  (...rows: H): Examples<H>
}

// this syntax is function chain with type safety and autocomplete
declare function Examples<H extends unknown[]>(...rows: H): Examples<H>

Examples
( I.User , I.Password , O.Message             )
( "OK"   , "valid"    , "Welcome"             )
( "KO"   , "invalid"  , "Invalid credentials" )

declare var ExamplesTTL_ideal: any

// and this is ideal syntax sample with TTL - where first param is header and rest should be rows of type header

ExamplesTTL_ideal `
${[ I.User , I.Password , O.Message              ]}
${[ "OK"   , "valid"    , "Welcome"              ]}
${[ "KO"   , "invalid"  , "Invalid credentials"  ]}
`

Here it is all in Typescript Playground
The question is - what should be declaration of ExampleTTL_ideal instead of :any ?
Regards.

A: My approach here would look like this:
declare function ExamplesTTL<H extends string[]>(
  text: TemplateStringsArray, ...rows: [...H][]): ExamplesTTL<H>;

interface ExamplesTTL<H extends string[]> {
  (text: TemplateStringsArray, ...rows: [...H][]): ExamplesTTL<H>;
}

The function is generic in H, intended to be a tuple of string literal types (or unions of string literals).  We want rows to be an array of such tuples.  If we're lucky, the compiler will use the first element in the rows array to infer H, and then check that subsequent elements in the array conform to it.
Note that in order to give the compiler a hint that H should be a tuple, we use the variadic tuple type [...H].
Since you want the function to return a function of the same type except that H is no longer generic, I defined the ExamplesTTL<H> generic type.  Conceptually, the ExamplesTTL<H> type is equivalent to typeof ExamplesTTL<H> instantiation expression, but I've given it a new name so as to avoid a vicious circularity (see ms/TS#51202).

Let's test it out:
const x = ExamplesTTL`
${[I.User, I.Password, O.Message]}
${["OK", "valid", "Welcome"]}
${["KO", "invalid", "Invalid credentials"]}
`;
// const x: ExamplesTTL<["OK" | "KO", "valid" | "invalid",
//   "Welcome" | "Invalid credentials"]>

x`${["OK", "valid", "Welcome"]} ${["oops"]}`; // error!
// ------------------------------> ~~~~~~
//Type '"oops"' is not assignable to type '"OK" | "KO"'.(2322)

const y = ExamplesTTL`
${["a", "b", "c"]}${["a", "b", "d"]}`; // error!
// --------------------------> ~~~
// Type '"d"' is not assignable to type '"c"'.(2322)

Looks good.  The type of x is inferred as ExamplesTTL<["OK" | "KO", "valid" | "invalid", "Welcome" | "Invalid credentials"]> as desired, and thus subsequent calls to x constrain its input to that type (so ["oops"] is bad).  And if you try to call ExamplesTTL with inconsistent tuple types, any inconsistency in the subsequent array entries are marked as an error.
Playground link to code

redpajama_set_name: RedPajamaStackExchange


text:
Q: Closing of a messagebox with space Simple question but can't figure out how to do this.
I have a messagebox with just one single "OK" Button, which appears by catching invalid datatypes/formats on inputs.
I want that the "OK" Button will be pushed after pressing Space (and only Space)
I guess I need some sort of event, which checks if the space button is pressed (but only) on this messagebox. But somehow it sounds a bit to inconvinient for such a simple task.

A: Well, guessing from your tags. I think you are talking about Window Forms in C#.
Yes, there is a way to do that. But not as simple as a message box. All you have to do is:

*

*Create a Form and Design it like a MessageBox

*Override the PreviewKeydown event handler ( or overriding KeyPress event handler will also work)

*And then match the case when Space key is pressed.

A Sample code is below to give you an idea:
switch (e.KeyCode)
{
    case Keys.Space:
       //Call The Event handler for Ok Button
        e.Handled = true;
        e.Suppressed = true;
        break;
}

(Note: You can also create new event handler for PreviewKeyDown Event instead of overriding. )

*

*As you want to show it as a messagebox use ShowDialog() when showing the form instead of Show() method.


text:
Q: What installer solution does the JDownloader project uses to create it's installer? I'm in the search for a installer solution for my application and I like the installer used by JDownloader.
What installer solution does the JDownloader project uses to create it's installer?

A: It uses Install4j: http://www.ej-technologies.com/products/install4j/overview.html


text:
Q: Sharing image with Facebook from Windows Store App I'm developing an application that must share a picture with Facebook.
Following the guidelines of Windows 8, I must use the Share Charm (text, html, image and file). Basically the idea is to build sources apps they can share information and target apps that are capable of receiving this information.
Turning the sample from Microsoft, which allows sharing of information types is only possible to share links with Facebook using People app.
I found three possible solutions to this problem:
1 - Wait for Facebook to launch an official app for Windows 8 to receive all these information types;
2 - Wait for Microsoft to include sharing these types of information in the People app.
3 - Create a target application that implements the Facebook API.
Finally, I would like to know if you have had this kind of problem and how they solved.

A: Have you tried using this library... Facebook C# SDK
I think it will give you what you want


text:
Q: Update autoselect value option dynamically using Ajax.InPlaceCollectionEditor I'm using Scripaculous' in place collection editor to present the user a with list of customers to assign to a contact dynamically.  I am passing a value parameter as detailed in the documentation so when the select is generated it will auto-select the current associated customer (if there is not one already the default is provided.)
This works well except when the user clicks on the 'edit me' field a second time the original value is selected, not the customer that was selected most recently.  This is because the original call to InPlaceCollectionEditor is unchanged.  My question is whether there is any way to update the autoselect value without dynamically updating the entire scriptaculous call (this would mean selecting all the customers again via ajax, which is possible but not ideal.)
Here is the code:

Test 1

Is this a limitation of InPlaceCollectionEditor or is there some other way around this?

A: Pass a variable instead of the hardcoded number as 'value'. Set that variable to the initial or selected value right before making the call.


text:
Q: iPod Touch will charge but won't play when connected to a Sony docking system I bought a Sony ICF-CS15iP docking system and my iPod will charge when I connect it, but it will not play music through the speakers. This is my 3rd docking system and I have had the same problem with the others - it will charge but not play.  I'm assuming it is my iPod that has something wrong with it. Should I call Sony and or Apple?? Thanks!
Note* I have a 4th gen iPod Touch

A: I found a product description on the Best Buy website:

The ICF-CS15IP is Compatible with most iPod® and iPhone® models, including iPhone 4. Works with: iPod touch® 2nd, 3rd, & 4th generations, iPod nano® 3rd (video), 4th (video), 5th (video camera), & 6th generations, iPod classic®, iPhone® 4, iPhone 3GS, and iPhone 3G.

Your 4th generation iPod Touch is listed as supported by this device, so you should contact Sony and expect them to help you.

A: Just bought the sony ipod docking station for my daughter for Christmas.  Her IPOD Touch 4th generation will charge, but the music will not come out of the docking speakers.  My son has an older IPOD Touch and it worked fine.  I called Sony and they told me I had to reinstall the operating system on the IPOD touch 4th generation for it to work.  I went through the hassel of resetting back to factory settings.  Still did not work.

A: The easiest way to test a docking station for operation is to test several iPhone / iPod that you know work with other dock connectors and see that they all work with your dock speakers.
The easiest way to test an iPod is to use it with several dock chargers and speakers.
Once you have done one of these tests it should be easy to know which piece isn't working reliably. Both Sony and Apple should be able to support you in these basic activities and once you know which item isn't working.
Also look for Apple's MFi logo to indicate that the device is designed to work with all Apple products as an indication that you won't need any extra apps or connectors to make things work. Lastly, peek into the physical connectors to be sure that lint or other problems are not lurking and making the electrical connection unreliable or impossible to be completed.

A: My iPod Touch 4th Gen also doesn't work with this Sony model.  It does work with my similar, older Sony clock radio dock station though.  I downloaded the d-sappli app but that didn't help.  Going to return the Sony tomorrow.

A: There is an app you have to download to make it play. It popped up when I put it on there the very first time, and I accidentally hit ignore. Need info.


text:
Q: Security vulnerability caused by unicode escapes in decoupled JSON service? Have a look at this simple JSON system composed of a user facing service that talks to a back end:
import java.util.*;
import com.json.parsers.*;
import org.json.simple.*;

class Main{static {
    String s = new java.util.Scanner(System.in).useDelimiter("\\A").next();
    UserFacingService.handleMessage(s);
}}

class UserFacingService {
    static void handleMessage(String s) {
        JSONParser parser = JsonParserFactory.getInstance().newJsonParser();
        Map js = parser.parseJson(s);
        if (commandAllowed(js))
            Backend.handleMessage(s);
        else
            System.out.println("unauthorized!");
    }
    static boolean commandAllowed(Map js) {
        if (js.get("cmd").equals("bad stuff"))
            return false;
        return true;
    }
}

class Backend {
    static void handleMessage(String s) {
        JSONObject js = (JSONObject) JSONValue.parse(s);
        String cmd = (String)js.get("cmd");
        if (cmd.equals("bad stuff")) {
            doBadStuff();
        } else if (cmd.equals("ping")) {
            doPong();
        }
    }
    static void doBadStuff() { System.out.println("doing bad stuff"); }
    static void doPong() { System.out.println("doing pong"); }
}

The user facing service (using quick-json) prevents the user from making the backend (using json-simple) do bad stuff. To simulate the user, I'm using stdin from Main. In a real scenario, Backend would be on another server, or some old legacy / binary code, so we can't simply change it to accept Java objects. The design is that authorization is done separately from Backend. This could be elaborated by making another class called AdminFacingService that only the admin has access to, or by putting if (userIsAdmin) return true; at the top of UserFacingService.commandAllowed.
As you can see, it works as intended:
$ CP=.:json-simple-1.1.1.jar:quick-json-1.0.2.3.jar
$ javac -cp $CP A.java && echo '{"cmd": "ping"}' | java -cp $CP Main
doing pong
Exception in thread "main" java.lang.NoSuchMethodError: main

Sending {"cmd": "bad stuff"} should cause the user facing service to reject the command:
$ CP=.:json-simple-1.1.1.jar:quick-json-1.0.2.3.jar
$ javac -cp $CP A.java && echo '{"cmd": "bad stuff"}' | java -cp $CP Main
unauthorized!
Exception in thread "main" java.lang.NoSuchMethodError: main

That works as well. But then if the user sends {"cmd": "bad\u0020stuff"}, bad stuff happens:
$ CP=.:json-simple-1.1.1.jar:quick-json-1.0.2.3.jar
$ javac -cp $CP A.java && echo '{"cmd": "bad\u0020stuff"}' | java -cp $CP Main
doing bad stuff
Exception in thread "main" java.lang.NoSuchMethodError: main

But how? Why isn't the user facing service catching this?

A: Right, I see. You're using two different parsers. Originally I though these were lenient in different ways. "Postel's Law" is great for UIs but dangerous for programming interfaces. In particular, hairy parsing is great for creating vulnerabilities.
Looking (again!) at RFC4627, \u notation is legal in JSON. One of your parsers appears to be broken and interprets the data incorrectly.
Generally only parse once - quite a few bugs come from multiple parsing. If you need the data in JSON again, extract and re-encode using a formatter that is clearly within spec and any buggy implementations you have to deal with.
It's kind of interesting, that even though is supposed to be really simple, text formats are susceptible to this sort of thing. So, prefer simple (not ASN.1) binary formats and use quality libraries.

Original answer, in which I wrongly assumed you were starting a new process every time with user data on the command line:

This is nothing to do with parsing JSON and everything to do with what
  you put on the command line. It's a bad idea to put untrusted data on
  the command line. This is in the "injection" class of vulnerabilities,
  along with SQL injection, XSS, LDAP injection, HTTP request/response
  splitting and many others. Most of these vulnerabilities can be solved
  by a tight formatting library. Command lines are all over the place,
  so it's best to either avoid them completely or go for something like
  Base64 encoding.
OWASP have a page on Command Injection.
The "Secure Coding Guidelines for the Java Programming Language,
  Version 4.0" has Guideline 3-4: Avoid any untrusted data on the
  command line.
(You're also very easily leaving yourself open to a DoS attack if you
  start a new Java process for every request.)

A: With bad\u0020stuff as an input, the first parser returns an object js where js.get("cmd") returns the string bad\u0020stuff, so commandAllowed returns true. The second parser returns an object js where js.get("cmd") returns bad stuff (it converts \u0020 to a space). Thus the bad stuff command is executed.
The first parser is not following RFC4627, because it's not interpreting unicode escapes.

A: It seems likely to me that it's a bug in quick-json.
quick-json doesn't escape \ properly:https://code.google.com/p/quick-json/issues/detail?id=6
Therefore I reckon that it doesn't unescape it properly either. So stick to json-simple which is more compliant with the spec.

A: If you're unable to use a JSON library that properly follows the spec then ...
org.apache.commons3.lang.StringEscapeUtils.unescapeJava(cmd).equals("bad stuff")

Check this SO question How to unescape a Java string literal in Java?


text:
Q: how use a application-dev.yml from Jhipster on local path Im trying to use the file application.yml, application-dev.yml and application-prod.yml that jhipster has in the proyect, but i dont want to use this file from the proyect i want to use those file from a local path. for example C://path
Please help me
Thanks

A: This is purely a spring-boot mechanism not specific to JHipster.
Look at spring-boot doc for all possibilities.
In your case, you could use:
java -jar myproject.jar --spring.config.location=file:///C:/path/application-dev.yml

but the simplest is to put your yaml file in same directory as your jar file, this is what is often used in production.


text:
Q: How can output additional headers in flask-restful get handler? I have implemented a flask-restful get handler that returns a number of records in an array. I want to set the header "x-total-count" to the number of records returned. I was able to add a header for every request using @api.representation but I am looking for a way to add the header in my get handler as it is specific to that particular endpoint.
@api.representation('application/json')
def output_json(data, code, headers=None):
    resp = make_response(json.dumps(data), code)
    headers = dict(headers) if headers else {}
    headers["X-Total-Count"] = str(len(data))
    resp.headers.extend(headers)
    return resp

class Customers(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('page', type=int, required=True)
        parser.add_argument('per-page', type=int, required=True)

        args = parser.parse_args()

        page_num = args['page']
        per_page = args['per-page']

        cxn = sqlite3.connect('chinook.db')
        sql = 'SELECT CustomerId, FirstName, LastName, Address, City, PostalCode, State FROM customers ' + \
              'WHERE CustomerId not in (SELECT CustomerId from customers ' + \
              'ORDER BY LastName ASC LIMIT ' + str((page_num-1) * per_page) + ')' + \
              'ORDER BY LastName ASC LIMIT ' + str(per_page)

        data = []
        for row in cxn.execute(sql):
            data.append({
                "id": row[0], "first-name": row[1], "last-name": row[2], "address": row[3],
                "city": row[4], "state": row[5], "postal-code": row[6] })

        cxn.close()
        return data


text:
Q: Q.How to Retrieve File/Image from Database And Display in JSP web page using Hibernate , MySQL Database? I need a code that can help me to retrieve my image/file from Mysql database and also display it on the webpage(.jsp) by using HIbernate and Servlet JSP. Q.How to Retrieve File/Image from Database And Display in JSP web page using Hibernate , MySQL Database?, Here's My Code...
`/**Employee and Login Registration*/

private void saveEmp(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Employee emp = new Employee();
Part part = request.getPart("image");
InputStream is = null;

if(part != null) {
    is = part.getInputStream();
    byte[] data = new byte[is.available()];
    is.read();
    emp.setImage(data);

boolean status = MainServices.saveEmp(emp);
        if(status)
        {
            MainServices.saveLoginData(login);
            request.setAttribute("msg", "Form Submitted Successfully...");
            request.getRequestDispatcher("adminHome.jsp").include(request, response);
        }
        else
        {
            request.setAttribute("msg","Email or Mobile Number is already Registered with us....");
            request.getRequestDispatcher("empForm.jsp").include(request, response);
        }
    }
}


text:
Q: How to have windows 10 send email upon unlocking? I followed the tutorial How To Get Email Notifications Whenever Someone Logs Into Your Computer, but it doesn't take care of PC unlocking (log in after Win+L). Did I miss anything? Thanks for any input!

A: The unlock operation doesn't count as a logon. As such your tutorial doesn't cover that case. If you go ahead and check the available Triggers for Tasks created by the Task Scheduler you will find that there is also a Trigger for workstation lock/unlock that you might use.


text:
Q: Brackets - unable to edit defaultPreferences.json file (trying to set linting to jshint but not jslint) I am running Brackets on a macbook pro and when I press cmd+, and try to edit the defaultPreferences.json file, it does not allow me to make any changes to the file (nothing happens when I type). If I restart Brackets I can edit the file, but after closing and re-opening the preferences file, the changes are reverted.
I have tried editing the json file with TextEdit while Brackets is closed, but Brackets still likes to reverse the changes.

A: I had similar issue , and i did open issue at Bracket's GitHub repository and here is the solution from its developers:-

defaultPreferences.json is a read-only file: take the options you
  want to modify and copy them to the brackets.json file on the other
  pane. This will override the defaults. You will also see code hints
  while typing the values in to brackets.json which will help picking
  the correct options.

A: Now it is also available to install brackets-preferences plugin and edit from there. Once installed go to View -> Preferences in your Brackets interface to edit preferences.


text:
Q: Saving ManyToMany with @ChangeTracking relation throws PersistenceException When I am trying to save a ManyToMany relation I get a database exception:
Exception in thread "main" javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.2.v20151217-774c696): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.h2.jdbc.JdbcSQLException: NULL not allowed for column "INVERSES_ID"; SQL statement:
INSERT INTO m2m_owner_inverse (inverses_ID, owners_ID) VALUES (?, ?) [23502-184]
Error Code: 23502
Call: INSERT INTO m2m_owner_inverse (inverses_ID, owners_ID) VALUES (?, ?)
    bind => [null, 1]

It is strange since I see in the log that both of the instances are inserted:
[EL Fine]: sql: 2016-02-22 13:18:32.67--ClientSession(1546269015)--Connection(1894667608)--INSERT INTO M2MOWNER (NAME) VALUES (?)
    bind => [null]
[EL Fine]: sql: 2016-02-22 13:18:32.676--ClientSession(1546269015)--Connection(1894667608)--CALL IDENTITY()
[EL Fine]: sql: 2016-02-22 13:18:32.716--ClientSession(1546269015)--Connection(1894667608)--INSERT INTO M2MINVERSE (NAME) VALUES (?)
    bind => [null]
[EL Fine]: sql: 2016-02-22 13:18:32.718--ClientSession(1546269015)--Connection(1894667608)--CALL IDENTITY()

The ChangeTracking is an eclipselink feature and the application needs a javaagent to run:
java -javaagent:eclipselink.jar

Without ChangeTracking and the agent it works as expected, the insertion happens.
It also works if I save the owner side (see the commented line)
The files can be found on github: https://github.com/zbiro/many2many
The sample can be started with
gradle start

The java files:
public class M2MTest {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("m2m-pu");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();

        M2MOwner owner = em.merge(new M2MOwner());
        em.flush();

        M2MInverse inverse = new M2MInverse();
        owner.getInverses().add(inverse);
        inverse.getOwners().add(owner);
        inverse = em.merge(inverse); // does not work if agent is used
        //owner = em.merge(owner); // works in all cases
        em.flush();

        em.getTransaction().commit();
        em.close();
        emf.close();
    }
}

@Entity
@ChangeTracking(ChangeTrackingType.ATTRIBUTE)
public class M2MOwner {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    @ManyToMany(cascade={CascadeType.ALL})
    @JoinTable(name="m2m_owner_inverse")
    private Set<M2MInverse> inverses = new HashSet<>();

    public Set<M2MInverse> getInverses() {
        return inverses;
    }
}

@Entity
@ChangeTracking(ChangeTrackingType.ATTRIBUTE)
public class M2MInverse {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    @javax.persistence.ManyToMany( cascade = { CascadeType.ALL }, mappedBy="inverses")
    private Set<M2MOwner> owners = new HashSet<>();

    public Set<M2MOwner> getOwners() {
        return owners;
    }
}

persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
    <persistence-unit name="m2m-pu" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>

        <class>M2MOwner</class>
        <class>M2MInverse</class>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:tests;LOCK_TIMEOUT=10000" />
            <property name="javax.persistence.jdbc.user" value="sa" />
            <property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
            <property name="eclipselink.ddl-generation.output-mode" value="database" />
            <property name="eclipselink.logging.parameters" value="true" />
            <property name="eclipselink.logging.level.sql" value="FINEST" />
        </properties>
    </persistence-unit>
</persistence>

build.gradle
apply plugin: "java"

repositories {
    mavenCentral()
}

configurations {
    eclipseLink { transitive = false }
}

ext.libs = [:]
libs.eclipseLink = 'org.eclipse.persistence:eclipselink:2.6.2'

dependencies {
    compile 'com.h2database:h2:1.4.191'
    compile libs.eclipseLink
    eclipseLink libs.eclipseLink
}

task start(type: JavaExec) {
    dependsOn build
    classpath = sourceSets.main.runtimeClasspath
    main = 'M2MTest'
    jvmArgs = ["-javaagent:${configurations.eclipseLink.singleFile}"]
}

My question is why it is happening and how I could avoid it.


text:
Q: Is it possible to Connect to all databases/schemas at once via RMySQL? In R, I am trying to connect to a particular host that currently has 3 schemas with an N number of tables each. I want to connect to all of the schemas at the same time, instead of cycling through each of them every time.
With the packages RMySQL, the usual way to connect to a particular database is the following:
 library(RMySQL)
 con <- dbConnect(MySQL(), dbname="dbhere", username = "userhere", password = "pwdhere", host="host.here")

This allows me to connect to one particular schema (via dbname) and do whatever I need with the tables there. I could write a for loop to cycle through the schemas each time, but every time a new schema is added it would have to be updated manually in R.
The following also do not work:
#here I changed paramets in dbname
con <- dbConnect(MySQL(), dbname=NULL, username = "userhere", password = "pwdhere", host="host.here")

con <- dbConnect(MySQL(), dbname=ALL, username = "userhere", password = "pwdhere", host="host.here")

con <- dbConnect(MySQL(), dbname="ALL", username = "userhere", password = "pwdhere", host="host.here")

con <- dbConnect(MySQL(), dbname=all, username = "userhere", password = "pwdhere", host="host.here")

con <- dbConnect(MySQL(), dbname="all", username = "userhere", password = "pwdhere", host="host.here")

From the RMySQL manual, the argument dbname is described as 'string with the database name or NULL. If not NULL, the connection sets the
default daabase to this value.'


text:
Q: PhoneGap Android plugin for higher quality audio recording? The PhoneGap media API provides a mechanism to record audio in a cross-platform way which works on android, but the audio quality is completely horrible -- 8 kHz sampling rate and perhaps some highly lossy codec as well.  I understand from this SO question that with java code it's possible to get higher quality audio recording.
Anybody know of a PhoneGap plugin for Android that allows for higher quality audio recording?

A: For anyone interested, what we did was dropping support for anything less than Android 2.3 and modify the Cordova native code ourselves.
If you are using Cordova 3+, I forked the project with the code changes here
For previous releases, just modify AudioPlayer.java (this is from Cordova 2.9)
 // support only 2.3.3+ to be able to record AAC with 44100 audio sampling
 this.recorder.setAudioSamplingRate(44100);
 this.recorder.setAudioEncodingBitRate(96000);
 this.recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
 this.recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);

 //this.recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);// THREE_GPP);
 //this.recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);// //AMR_NB);

A: You will have to write your own plugin unfortunately.
Here a list of current plugins: https://github.com/phonegap/phonegap-plugins/tree/master/Android
For IOS there is an older audio record one. Maybe you can have a look there:
https://github.com/phonegap/phonegap-plugins/tree/master/iOS/AudioRecord
Creating a plugin is not such a big deal though. Here some code for the actual recording:
http://www.androiddevblog.net/android/android-audio-recording-part-2
http://developer.android.com/reference/android/media/AudioRecord.html


text:
Q: Inventory tracking ideas My bench is overflowing with stuff ... I have several racks of little drawers, and another bench that has heaps of stuff on it. My label maker works hard. And yet, stuff gets temporarily lost all the time.
How do you keep track of all your parts?
If you have any ideas on how to keep track of your inventory, please share. This is driving me nuts and spending money to solve the problem is certainly on the table. My latest idea is to have everything ordered by supplier part number, and use a database to look them up. Any better ideas?
(My goal is to optimize findability, not (say) everything being reachable - walking around and collecting stuff is OK).

A: I had exactly the same problem. In the end I gave in to my warehousing instinct and assigned each physical drawer, box, etc a location code. For example, I have ten of those 20-compartment boxes, so they are referenced as 1.1, 10.6 (e.g. box 10, compartment 6). Then everything went into a spreadsheet with tabs for different categories (capacitors, LEDs, relays etc).
Each item has a column with part number, type, value, max voltage, RoHS, quantity in stock, min quantity for reorder, etc., plus preferred supplier part number etc.
Then I can just use 'find' on the spreadsheet to look something up, or run a simple procedure to check for things to reorder.
The only thing that isn't given a location is resistors, but each value is in a separate zip-lock bag, in numerical order over three shoe boxes.
One day I will port the lot in Access, but couldn't be bothered at this stage. :)

A: I use a database (Postgres).
I wouldn't use the supplier part number. If you change suppliers you will need to
change your tables. You could use manufacturer/manufacturer part number. If you
decide to expand your application to do ordering you can create a table
that maps manufacturer/manufacturer_part_number to supplier/supplier_part_number.
Recently I have added an internal part numbering system so that parts with identical
form/function can be mapped to multiple manufacturer/manufacturer_part_number records.
For example RES-1K00-0W125 (1K 1/8W resistor) can map to parts made by Xicon, Yageo,
Stackpole, etc. This is a lot more work to setup but is not difficult to maintain.

A: I hated having search for datasheets over and over, so I threw together a little web app that keeps track of my inventory and datasheets. ('guest@mailinator.com' and 'guest' if anyone wants to play around with it - be nice).  It's basically a database with a front end so I can get to it from anywhere.  For physical parts storage, I keep most of my SMD stuff in 4 1/4 x 2 1/2 envelopes in plastic bins.  The envelopes are cheap enough that I can use one for each value of small part, and big enough to hold most of my SMD stuff.  Through-hole parts are still in little plastic divided containers, but that's only because I haven't moved them to envelopes yet.

A: If you are looking for a web application for tracking your electronic components you have to check out http://partkeepr.org/.  I was so happy to have stumbled across it.  You won't be disappointed.

A: I started with a spreadsheet a long time ago. Then I used to use PartKeepr, which is great, until I ran into some limitations — in particular, I needed to keep some parts in multiple storage locations (such as resistors on cut tape, but also a full reel somewhere). I decided I'd create my own solution, and so PartsBox https://partsbox.io/ was born.
Disclaimer: I am (obviously) the founder and creator of this app. But since it is free for hobbyists/makers I thought this was relevant here and deserved posting.


text:
Q: How to run a keyboard shortcut via a file? Certain programs for Windows have specific keyboard shortcuts that execute specific functions. I was wondering if there is a way to create a small file that can activate any shortcut by clicking on it?
Example: Win+C opens up the charms bar in Windows 8. Can I create a file to click on that opens this function for me?
(I want this file to activate a different keyboard shortcut, not the one mentioned above in my example.)

A: It looks like you are trying to create a desktop shortcut.
To do so:

*

*Use My Computer or Windows Explorer to locate the object to which
you want to create a shortcut.

*Right-click the object, and then
click Create shortcut.

*Drag the new shortcut to an open area on the
desktop.

*You can also create a keyboard shortcut that will open or do whatever that shortcut would do if you opened it.   See properties.

Reference: https://support.microsoft.com/en-us/kb/140443 (page no longer available since Windows 10)


text:
Q: c# winform - how to delete multiple DataGridViewRows Here is my code:
foreach (DataGridViewRow r in dgv01.Rows)

if (r.Cells[0].Value.ToString() == abc)

{

dgv01.Rows.Remove(r);

//dgv01.CurrentCell = dgv01.Rows[0].Cells[0]; - **also tried**

}

But only some rows are deleted - not all specified !?
Why - foreach - does not mean - foreach ?

A: I have to remind you that it is dangerous to use a foreach block when you want to modify/remove the data being traversed. The removal messes up with the index of the foreach iterator.
Solution? Use a reverse for loop instead.

A: First of all it is not a good idea to change collection inside foreach loop. Secondly foreach is not behaving how you want because once the first row is removed then second row will become the first row but because in foreach the checking will be done on second row which is actually a third row. so, checking on the second row has been skipped. The best way to do is use for loop in a reverse order.
to know why foreach is not behaving like foreach try this simple example.
 private List<int> list = Enumerable.Range(0, 10).ToList<int>();
 for(int i=0;i<list.Count;++i)
       {
           if (list[i] < 5)
               list.RemoveAt(i);
       }

       list.ForEach(x => Console.Write(x));

Output:
    1356789

A: When you iterate over a collection using foreach, the collection should not be modified otherwise, in the best of scenarios, you end up not covering the entire collection. Most of the time, however, modifying the collection while within a foreach block, the iteration will fail.
In order to remove the rows from the DataGridView, you'll have to use a for iteration block or a two-step process both of which I display below.

for Iteration Block
This procedure uses an index to traverse the collection, modifying the collection as you go. The thing you need to know here is that if you intend to modify the collection, you do not have the index increment (go forward through the collection); you decrement the index (go backwards through the collection). If you modify (remove or add items) the collection while iterating forwards, you may not end up visiting all the items in the collection.
Here is code to remove rows from the DataGridView. Remember, we iterate backwards.
for (int i = dgv01.Rows.Count - 1; i >= 0; i--)
{
    if (dgv01.Rows[i].Cells[0].Value.ToString() == "abc")
    {
        dgv01.Rows.RemoveAt(i);
    }
}

foreach Iteration Block
This procedure uses a two-step approach. The first step finds the items to be removed and the second step removes the items from the collection. This two-step process is necessary for the reasons I explained earlier.
Now the code. Remember, it is a two-step process.
// step 1. find the items to be removed

//items to be removed will be added to this list
var itemsToRemove = new List<DataGridViewRow>();
foreach (DataGridViewRow r in dgv01.Rows)
{
    if (r.Cells[0].Value.ToString() == "abc")
    {
        itemsToRemove.Add(r);
    }
}

//step 2. remove the items from the DataGridView
foreach (var r in itemsToRemove)
{
    // this works because we're not iterating over the DataGridView.
    dgv01.Rows.Remove(r);
}

One last thing you should know is that the procedures I have demonstrated here do not apply to the DataGridViewRowCollection class only; it applies to all collections that implement the IList<T> or the ICollection<T> interface. So, yes, the process can be used for Lists, Dictionaries, ControlCollections and all other similar classes.

A: do a descending sorting on column[0] then from bottom u can delete the rows. Once abc is over u can break the loop also.
Other wise u can put a row filter on dataTable u are using.
((DataTable)this.datagrid1.DataSource).DefaultView .RowFilter

A: Whenever I have to modify a collection inside a foreach I usually make a new collection which I fill with the data I want to modify, and then loop through this second collection to do the actual changes to the main collection. In this way I never modify a collection while looping it, so I avoid the situation described by MChicago.
In your case I usually would write this kind of code:
List<DataGridViewRow> toDel = new List<DataGridViewRow>();
foreach (DataGridViewRow r in dgv01.Rows)
    if (r.Cells[0].Value.ToString() == "abc")
        toDel.Add(r);

foreach (DataGridViewRow aRow in toDel)
    dgv01.Rows.Remove(aRow);


text:
Q: How to prune triangles in output mesh of Surface Reconstruction of Point Cloud I have an open surface represented by a point cloud which I've put through the steps described in the Point Set Processing and Surface Reconstruction tutorial.  However, applying any of the 3 discussed Reconstruction algorithms results in a closed mesh with extreme extraneous polygons, especially along the "enclosing dome" of the atmosphere around the point cloud model.  See attached pictures at the bottom of this question for visual context.
Is there an accurate, or canonically correct within CGAL, method to prune both the large and small triangles which do not intersect with the original point cloud?  I have tried iterating over the faces in the output mesh and removing the faces which satisfy either of two conditions:  (1) Any length of a given face is longer than the average spacing computed for the origin point cloud, and (2) The given area of the face is larger than some threshold.  Either filtering condition results in a model which is not viewable as a mesh in PLY format given the various viewers I've tried.  Here is some code which I've considered, but apparently does not do the job:
for (face_descriptor faced : output_mesh.faces()) {
        //std::cout << faced << std::endl;
        std::vector<double> lengths;

        // Get edges from face descriptor
        //    - NOTE :> Assume three total half-edges because triangles.  Not guaranteed, tho.
        for (halfedge_descriptor hed : CGAL::halfedges_around_face( output_mesh.halfedge(faced), output_mesh )) {

            vertex_descriptor target_vertex = output_mesh.target(hed);
            Point_3& target_point = output_mesh.point(target_vertex);

            halfedge_descriptor hed_next = output_mesh.next(hed);
            vertex_descriptor target_next = output_mesh.target(hed_next);
            Point_3& target_point_next = output_mesh.point(target_next);

            double length = CGAL::sqrt(CGAL::squared_distance(target_point, target_point_next));
            lengths.push_back(length);
            simplex.push_back(target_point);
        }

        // if edge length greater than limit threshold based on average_spacing,
        // mark for removal?
        for (double length : lengths) {
            if (length > average_spacing) {

                output_mesh.remove_face(faced);
                //CGAL::Euler::remove_face( output_mesh.halfedge(faced), output_mesh );

                std::cout << "Removed face " << faced << " with lengths: ";
                // List out the lengths found:
                for (double length : lengths) {
                    std::cout << length << ", ";
                }
                std::cout << std::endl;
                continue;
            }
        }
    }

    // clear faces marked as removed
    output_mesh.collect_garbage();
    //output_mesh.is_valid();

Thanks for your insights in advance!  This has had me going in circles for weeks.

A: Following @sloriot 's comment, using Advancing Front Surface Reconstruction is the correct way of handling this, in addition to the hole-filling and fairing steps.
Due to the contiguous nature of advancing front, however, there are still some extraneous facets generated.  A solution we've worked out involves projecting various points onto each facet; calculating the distance to the plane of the facet (simplex) and the barycentric coordinates of each point, as filtering criteria.  This allows facets which do not match any point clouds to be removed.  It is recommended to do this prior to hole filling/fairing or potentially applying other algorithms from the Polygon Mesh Processing set to perform some additional "fixing" for our application.
Thanks so much for the help!


text:
Q: Why is my docker container not executing my cron job? I have a node script that I want to run periodically so I created the following Dockerfile to run it from a cron task:
FROM node:8

RUN apt-get update && apt-get install -y cron

# ensure the node packages are installed in the image
WORKDIR /usr/src/app
COPY package.json .
RUN npm install

# copy the node task to working directory
COPY db-update.js .

# copy the script which will start cron to the working directory
COPY startcron.sh .

# copy the cron task to the cond.d directory
COPY crontask /etc/cron.d/crontask

# give execution rights on the cron job and script
RUN chmod 0644 /etc/cron.d/crontask && chmod 777 ./startcron.sh

# apply the cron job
RUN crontab /etc/cron.d/crontask

# create the log file to be able to run tail
RUN touch /var/log/cron.log

# execute the command in the foreground
CMD /usr/src/app/startcron.sh

In startcron.sh bash script I have the following:
#!/bin/bash
set -e

printenv | sed 's/^\(.*\)$/export \1/g' > /tmp/env.sh

echo 'Starting cron' # <- ONLY THIS APPEARS IN MY CONTAINER LOGS
cron -f

I needed to create /tmp/env.sh to export the environmental variables my node script requires. This script should then start cron in the foreground. My crontask should "source" those environmental variables and run my node script. If I have set up everything correctly I expect to see the output from my node script in the logs of my Docker container.
# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12)
# │ │ │ │ ┌───────────── day of week (0 - 6) (Sunday to Saturday;
# │ │ │ │ │                                       7 is also Sunday on some systems)
# │ │ │ │ │
# │ │ │ │ │
# * * * * *  command to execute
# DOES THIS COMMAND EXECUTE SUCCESSFULLY, IF NOT WHY NOT?
*/5 * * * * . /tmp/env.sh /usr/local/bin/node /usr/src/app/db-update.js > /proc/1/fd/1 2>/proc/1/fd/2
# need to leave an empty line

This is a snippet from my node script:
const sftpclient = require('ssh2-sftp-client');
const expressGraphQL = require('express-graphql');
const mongoose = require('mongoose');
const fs = require('fs');

console.log('now executing db-update');
const IN_PRODUCTION = (process.env.NODE_ENV === 'production' ? true : false);
console.log('what is node env: ', process.env.NODE_ENV);
console.log('what is env: ', process.env);

When I run this container, however, the only output I am seeing in my container logs is the echo command from my bash script "Starting Cron". I don't see any output from the node script but the container continues to run. How can I ensure that the node script runs or that the container fails if it doesn't?

A: To make your life much more easier I would recommend to change strategy to use simple infinite loop with sleep instead of cron
so in CMD just place
while true; sleep 300; execute-node-program || exit 1; done
In such strategy:

*

*You have all output of your node program in docker logs

*Container will fail if your program fail

It will be hard to achieve that by using cron as you will need probably to place systemd for 2 processes:

*

*One process for cron

*Second process to observe what is node program output and kill systemd if needed, print logs, etc. <--- that sounds really bad

Edit:
So to give you idea how to deal with killing your container when cron job fails:

*

*Start your container with --init flag e.g. docker run --init... - that's really important and will allow you to kill main container's process from within container

*Use similar crontab record: */5 * * * * bash -c "/tmp/env.sh && /usr/local/bin/node /usr/src/app/db-update.js || pkill -9 -f cron" > /proc/1/fd/1 2>/proc/1/fd/2


text:
Q: javascript keeps skipping my if statement thats inside two loops Ok so im talking in some unput from the user, it must be 4 numbers, and the digits must not be the same. so everything is working accept the part where i check the 4 numbers against each other. i put the string into an array and then compare the array, by
checking the first one against the 2nd, 3rd, 4th,
then i check the second one against the 3rd, and 4th
then i check the third number against the 4th
My issue is the if statement will not work no matter what i try it gets bypassed everytime. I add random returns into the code to see where it goes and it always returns 12 no matter what even if the numbers i enter are 1111 it still passes.
Ive spent hours trying different stuff please help me!!
function validate(guess){

var user_guess = guess;
var valid = true;
var counter = 0;

parseFloat(user_guess);

if(user_guess.length == 4){

    if((user_guess == null) || (isNaN(user_guess))){

        validation_alert();

    }else{

        var guess_string = toString(user_guess);
        var guess_array = guess_string.split('');
        var guess_array2 = guess_array;

        for(var i = 0; i < 3; i++){

            counter = i + 1;

            for(c = counter; c < 4; c++){

                if(guess_array[i] == guess_array2[c]){

                    return 11;
                    valid = false;
                    validation_alert();

                }

            }

        }

        if(valid == true){

        return 12;

        }else{

            return 13;
            validation_alert();

        }

    }//if null

}else{

    validation_alert();

}//if 4 end tag

}// function close

A: Just to prove to you that JavaScript uses function scope and not block scope (if else for ...) which means every var you declare moves automatically to the top of the current function it's running in.
Also note that when you return something you will exit the current function and not execute anything after that.
If you check against length you can be sure it's going to be a number so use === instead which checks against it's type (number, string, bool) as well.
Your 2 first if statements should be reversed I think. In anycase user_guess == null will never validate as the previous if checks on the length === 4.
Normally when you use return every block scope should return something. I haven't edited this but that's expected in strict javascript.
It seems more logical to start with valid=false and you will only set it to true when you are sure it's true. I'll leave that up to you.
function validate(guess){
    var user_guess = parseFloat(guess),
        guess_string,
        guess_array,
        guess_array2,
        valid = true,
        counter = 0,
        i = 0,
        c;

    if (!user_guess || isNaN(user_guess)){
        validation_alert();
    } else {
        if (guess.length === 4){
            guess_string = user_guess.toString();
            guess_array = guess_string.split('');
            guess_array2 = guess_array;

            for (i; i < 3; i++){
                counter = i + 1;
                c = counter;
                for (c; c < 4; c++){
                    if (guess_array[i] == guess_array2[c]){
                        valid = false;
                        validation_alert();
                        return 11;
                    }
                }
            }

            if (valid){
                return 12;
            } else {
                validation_alert();
                return 13;

            }
        } else {
            validation_alert();
        }
    }
}

A: If you just need to check if the string has 4 unique number digits its much easier this way:
function isValid(str){
    var unique={};
    for(var i=0;i<str.length;i++){//for each character in the string
        unique[str[i]]=true;//we add the character as a key in unique object(the =true doesnt really matter)
    }
    var chars=Object.keys(unique);//we get an array with the keys in the object(we get an array with the unique characters)
    if(chars.length != 4) return false; //if the unique chracters are different than 4, its not valid so return false
    chars.sort();//we order the array in lexicographical order
    if(chars[0]>= '0' && chars[0] <='9' && chars[3]>= '0' && chars[3] <='9') return true;//if the first character and the last ones are digits, then the ones in the middle wil be digits as well because of the sort we made. If they are, return true
    return false;//if they are not both digits, return false
}
console.log(isValid('1111'))//false
console.log(isValid('9230'))//true
console.log(isValid('1343'))//false
console.log(isValid('a412'))//false
console.log(isValid(''))//false


text:
Q: Roll a die. And construct three events that are not independent but each is independent of the intersection of the other two. The question is actually from Billingsley's Probability and Measure problem 4.6.
The full question: In a space of six equally likely points (a die is rolled) find three events that are not independent even though each is independent of the intersection of the other two.

A: What about rolling a six, rolling a five and rolling a four?
Rolling a four and a five is trivially independent to rolling a four since it is impossible. But Rolling a four and rolling six, or rolling a four and rolling five are mutually exclusive.

A: Hint: any event is independent of the empty set.


text:
Q: Ladder Operators for this Hamiltonian $\widehat{H}$ how to find the ladder operators for this hamiltonian:
$$\widehat{H}=a\widehat{A}^2 + b\widehat{B}^2$$
where $a$ and $b$ are two real and positive constants.
And how to write the hamiltonian in function of the two ladder operators?
Actually the answer is:$$a_-=\frac{1}{\sqrt{2a}}\widehat{A}+i\frac{1}{\sqrt{2b}}\widehat{B}$$ and $$a_+=\frac{1}{\sqrt{2a}}\widehat{A}-i\frac{1}{\sqrt{2b}}\widehat{B}$$
And the condition on the commutator $\widehat{A}$ and $\widehat{B}$ for having: $[a_-,a_+]=\widehat{1}$, I found: $$[\widehat{A},\widehat{B}]=i\sqrt{ab}$$
but I couldn't reach them.
Thank you in advance.

A: Moving this to an answer as in is too long for a comment:
Given a generic Hamiltonian $a\widehat{A}^2 + b\widehat{B}^2$ is not enough information to construct ladder operators. There is no reason to expect that the commutation relation of two conjugate linear combinations of $A,B$ is 1. So you need to be supplied with either the commutation relations of $[A,B]$ or the explicit construction of $A,B$ in terms if $a_{+},a_{-}$.
In the question you say that
$a_-=\frac{1}{\sqrt{2a}}\widehat{A}+i\frac{1}{\sqrt{2b}}\widehat{B}$
$a_+=\frac{1}{\sqrt{2a}}\widehat{A}-i\frac{1}{\sqrt{2b}}\widehat{B}$
So you can plug back in and get the Hamiltonian in terms of $a_{+}, a_{-} $ but the Hamiltonian will now contain mixed terms:
$\alpha a_{+}^2+\beta a_{-}^2+\gamma a_{+} a_{-}+\delta a_{-} a_{+}$ for some parameters $\alpha,\beta,\gamma,\delta$.
on the other hand, if you are given $[\widehat{A},\widehat{B}]=i\sqrt{ab}$ , then the construction of a pair of conjugate operators that have a commutation of $1$ is also direct.


text:
Q: Linux partitions deleted after Windows 10 Update (Version 1909) I have a dual boot with Ubuntu and Windows 10. I have only booted into Windows a handful of times over the last 2 years or so. I left Windows logged in overnight and it decided to update. The next morning I was greeted with grub rescue.
Following the instructions of similar questions on here, I went through each partition looking for signs of Linux using ls and then ls (hd#,msdos#) for each partition shown. Nothing.  I then used a bootable Windows USB drive to get to the command prompt and tried the following. I don't remember if I ran the bcdedit or bootrec command first.
bcdedit /set {bootmgr} path \EFI\ubuntu\grubx64.efi

bootrec /fixmbr
bootrec /fixboot
bootrec /rebuildbcd

This didn't fix anything and I used the Windows startup repair tool to get into Windows.  Once in Windows I created a bootable Ubuntu USB drive, and booted into a live Ubuntu session.  I ran the recommended function of the Boot-Repair utility and foolishly didn't save the Pastebin link. It completed successfully, but did not fix the Ubuntu boot partition and also broke ability to boot into Windows. I used the bootable Windows USB drive once again to run the startup repair tool to get back into Windows.
From here I ran the testdisk utility which sees the partition, but is unable to recover it.  Testdisk partition table backup:
#1611976403 Disk /dev/sdb - 500 GB / 465 GiB - CHS 60801 255 63
 1 : start=     2048, size=  1124352, Id=07, *
 2 : start=  1126400, size=346499072, Id=07, P
 3 : start=347625472, size=104857600, Id=83, P
 4 : start=452483072, size=524288000, Id=05, E

(I initially had individual screenshots for each step below but then realized I cannot post more than 8 links without enough reputation points so here is the whole album  https://imgur.com/a/PnCivbn )
Windows Disk Manager sees this as free space. (see screenshot)
Gparted gives an "invalid partition table --wrong signature" error when loading.  If I ignore this error it shows unknown/unallocated spaces. (see screenshot)
fdisk -l returns similar results (see screenshot)
If I understand correctly, sbd5 is the result of moving partitions around in the past?  TestDisk also has a "The hard disk seems too small" error (see screenshot).
The Disk tool shows an extended partition 4 alongside Free space. However, the sizes are incorrect.  Windows disk management, GParted, and fdisk correctly show sizes of 250GB and 50GB for the two inaccessible partitions, the Ubuntu disk tool shows 268GB and 58GB. (see screenshot)
TestDisk Analyse shows:
https://imgur.com/59MFlIK
TestDisk Quick Search results in a partition that cannot be recovered and an error that the hard disk seems too small (remnants of adjusting partition sizes in the past?):

Continuing to the next screen:

Quick search results:

I can view files in the FAT32 LBA and Linux partitions, though the Linux partition is obviously missing a lot of files.
The next screen displays "No partition found or selected for recovery."  After the deeper search I see the same "hard disk seems too small", "following partition can't be recovered", and warning about the number of heads per cylinder as the quick search (screenshots above), then:

The first Linux partition is the same as one shown in the quick search, the others all say "No file found, filesystem may be damaged."
If I go to geometry and change the number of heads to 128 as suggested, I see the following in Analyze.

And then get the same results as before with the quick search and deep search, except for warnings regarding a mismatch in number of heads/cylinder.
I booted back into the Ubuntu live instance and reran Boot-Repair, but just ran the Boot-Info option this time since I figured that running the boot-repair again would just have the same results as above (breaking the windows boot and having to rerun the Windows repair utility - potentially making matters worse?), but this time I saved the Pastebin log.
At this point I don't know what else to try. Am I screwed?  I have not written any changes to the partition tables with TestDisk nor have I made any changes with fdisk. Is there any way to recover the Linux partition(s) or at least (some of) the data contained within?  I was able to create an image of the 250GB partition in question using TestDisk.


text:
Q: Why does the main document extend sprite in AS3? What is the purpose/benefits of this extending sprite:

public class Main extends Sprite

A: The document class is added automatically as a child of the Stage when your app starts. In consequence it needs to be a DisplayObject. It also need to be a DisplayObjectContainer so that DisplayObject can be added to its display list.


text:
Q: Cisco ASA5505 compatible RAM I have a Cisco ASA5505 which I've acquired. It boots up first time successfully, and works without issue, however as soon as I reboot, it fails to boot with the flashing light sequence which indicates a RAM fault.
Fairly sure that replacing the RAM module will resolve the issue, however I'd rather not spend £120 on the official upgrade kit to replace the RAM, as it's only really something I'll be testing in a lab environment.
What alternate compatible RAM can I use in the device without spending a fortune? It's got a 256MB module at the moment.

A: I'd buy the RAM from eBay... Either the official kit or find something listed as "compatible".


text:
Q: How to gracefully close an Async Server Socket? C# I've seen a lot of questions about handling Sockets without object disposed exceptions, so I've decided to take a crack at it and see if it could be done. Here are my findings.
Problem?
You have a piece of code that uses a Socket from System.Net.Sockets that is a server socket. The problem is you want to close the socket and every time you try you get an ObjectDisposedException.
Your code may look something like this:
    private static ManualResetEvent allDone = new ManualResetEvent(false);
    private Socket ear;
    public void Start()
    {
        new Thread(() => StartListening()).Start();
    }

    private void StartListening()
    {
        IP = Dns.GetHostAddresses(Dns.GetHostName()).Where(address => address.AddressFamily == AddressFamily.InterNetwork).First();
        port = 11221;
        IPEndPoint localEndPoint = new IPEndPoint(IP, Port);
        ear = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        ear.Bind(localEndPoint);
        ear.Listen(100);
        try
        {

            while (true)
            {
                allDone.Reset();
                ear.BeginAccept(new AsyncCallback(AcceptCallback), ear);
                allDone.WaitOne();
            }
        }
        catch (ObjectDisposedException e)
        {
            Console.WriteLine("Socket Closed");
        }
    }

    private void AcceptCallback(IAsyncResult ar)
    {
        allDone.Set();
        Socket listener = (Socket)ar.AsyncState;
        Socket handler = listener.EndAccept(ar);

        StateObject state = new StateObject();
        state.workSocket = handler;
        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
    }
    public static void ReadCallback(IAsyncResult ar)
    {
        String content = String.Empty;

        StateObject state = (StateObject) ar.AsyncState;
        Socket handler = state.workSocket;

        int bytesRead = handler.EndReceive(ar);

        if (bytesRead > 0) {
            state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));

            content = state.sb.ToString();
            if (content.IndexOf("<EOF>") > -1) {
                Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content );
            }
            else
            {
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReadCallback), state);
            }
        }
    }

    public void Stop()
    {
        ear.Close();
    }

Running a Code similar to above will give you an error in the AcceptCallback went trying to end the receive. Even if you catch that, you still get an error in the StartListening() Method.

A: So Here is how I fixed it:
First I added a Boolean called IsListening.
Next I changed condition that keeps the ear listening to While(IsListening).
In the stop method, I put set the IsListening variable to false before calling ear.close() and lastly I do a check for the ear inside of the AcceptCallback after the Manual SetEvent.
The end result looks like this:
    private static ManualResetEvent allDone = new ManualResetEvent(false);
    private Socket ear;
    public void Start()
    {
        new Thread(() => StartListening()).Start();
    }

    private void StartListening()
    {
        IP = Dns.GetHostAddresses(Dns.GetHostName()).Where(address => address.AddressFamily == AddressFamily.InterNetwork).First();
        port = 11221;
        IPEndPoint localEndPoint = new IPEndPoint(IP, Port);
        ear = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        ear.Bind(localEndPoint);
        ear.Listen(100);

        IsListening = true;

        while (IsListening)
        {
            allDone.Reset();
            ear.BeginAccept(new AsyncCallback(AcceptCallback), ear);
            allDone.WaitOne();
        }
        Console.WriteLine("Socket Closed");
    }

    private void AcceptCallback(IAsyncResult ar)
    {
        allDone.Set();
        if (IsListening == false) return;
        Socket listener = (Socket)ar.AsyncState;
        Socket handler = listener.EndAccept(ar);

        StateObject state = new StateObject();
        state.workSocket = handler;
        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
    }
    public static void ReadCallback(IAsyncResult ar)
    {
        String content = String.Empty;

        StateObject state = (StateObject) ar.AsyncState;
        Socket handler = state.workSocket;

        int bytesRead = handler.EndReceive(ar);

        if (bytesRead > 0) {
            state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));

            content = state.sb.ToString();
            if (content.IndexOf("<EOF>") > -1) {
                Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content );
            }
            else
            {
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReadCallback), state);
            }
        }
    }

    public void Stop()
    {
        IsListening = false;
        ear.Close();
    }

The exception is now gone. I hope this helps someone else!


text:
Q: Add Reference 4.0 Dll to 4.0 ClientProfile application in VS2012 I am working on Multiple versioned projects. One is 4.0 Version and another is 4.0 ClientProfile.
   How could i add 4.0 Assembly to 4.0 ClientProfile.

   If i adding like normal reference means its not adding properly or the classes i cannot access it.

Tried Solution: I changed 4.0 client to 4.5 means its working fine. But My project support only for 4.0 clientProfile.How can i achieve this?
TanQ,
Saars.

A: If i directly changing the project version 4.0 ClientProfile to 4.0 Means the application not running.
But if we Add the Reference of system.web means it will automatically converts to 4.0 .
So it supported to 4.0 version assembly reference too. Now Project is running good.


text:
Q: UWP Tab close confirmation for page I'm trying to make a close confirmation content dialog for closing the current tab.
Expected behavior: the app should ask the user if they want to save, and after, close the tab
Actual behavior: the dialog isn't shown. Here is the code:
MainPage (the one inside the tab):
    public bool IsCloseRequestComplete = false;

    public async void RequestClose()
    {
        if (TXTFile != null) { try { RAS = await TXTFile.OpenAsync(FileAccessMode.ReadWrite); } catch { } }
        var Value = GetText(REB);
        var SecValue = GetText(RTB);
        if (Value != SecValue)
        {
            //Remember the user to save the file
            ContentDialog ED2 = FileSaveDialog;
            ED2.PrimaryButtonClick += ED2_PrimaryButtonClick;
            ED2.SecondaryButtonClick += ED2_SecondaryButtonClick;
            ED2.CloseButtonClick += ED2_CloseButtonClick;
            try { await ED2.ShowAsync(); } catch { }
            void ED2_PrimaryButtonClick(ContentDialog SenderSec, ContentDialogButtonClickEventArgs DialogEvArgs)
            {
                if (TXTFile != null)
                {
                    //Save and close in the background
                    RAS.Dispose();
                    SaveCloseBackground();
                }
                else SaveClose();
            }
            void ED2_SecondaryButtonClick(ContentDialog SenderSec, ContentDialogButtonClickEventArgs DialogEvArgs)
            {
                //Close
                if (TXTFile != null) RAS.Dispose();
                IsCloseRequestComplete = true;
            }
            void ED2_CloseButtonClick(ContentDialog SenderSec, ContentDialogButtonClickEventArgs DialogEvArgs) { }
        }
        else if (Value == SecValue)
        {
            //If the file is saved, close the app
            if (TXTFile != null && RAS != null) { try { RAS.Dispose(); } catch { } }
            IsCloseRequestComplete = true;
        }
        return;
    }

(SaveClose, SaveCloseBackground, GetText are custom methods)
TabbedMainPage (the tabbed page aka host page):
    private void TabbedView_TabCloseRequested(TabView sender, TabViewTabCloseRequestedEventArgs args)
    {
        MainPage MP = new MainPage();
        MP.RequestClose();
        if (MP.IsCloseRequestComplete == true)
            TabbedView.TabItems.Remove(args.Tab);
        else { MP.RequestClose(); }
        return;
    }

A: You don't need to put the ContentDialog  on the MainPage. You need to put it on the Page which hosts the TabView. Then show the ContentDialog in the TabCloseRequested.
I made a simple demo about this and please check the following code.
Xaml:
        <muxc:TabView x:Name="MyTabView" AddTabButtonClick="TabView_AddTabButtonClick"
           TabCloseRequested="TabView_TabCloseRequested">
        <muxc:TabViewItem Header="new header">
        </muxc:TabViewItem>
    </muxc:TabView>

MainPage(hosts the TabView)
        public ContentDialog noWifiDialog { get; set; }
    public muxc.TabViewItem targetTab { get; set; }
    public MainPage()
    {

        this.InitializeComponent();

        noWifiDialog = new ContentDialog()
        {
            Title = "No wifi connection",
            Content = "Check connection and try again.",
            PrimaryButtonText="OK"
        };
        noWifiDialog.PrimaryButtonClick += NoWifiDialog_PrimaryButtonClick;
    }

    private void NoWifiDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
    {
        // do the work you want

        Debug.WriteLine("Remove");

        //remove the item
        MyTabView.TabItems.Remove(targetTab);

        // clear the target item
        targetTab = null;
    }

    // Remove the requested tab from the TabView
    private async void TabView_TabCloseRequested(muxc.TabView sender, muxc.TabViewTabCloseRequestedEventArgs args)
    {
        //record the target tab
        targetTab= args.Tab;
        // show the contentDialog. The close event of the ContentDialog is handled
        await noWifiDialog.ShowAsync();
    }

    // Add a new Tab to the TabView
    private void TabView_AddTabButtonClick(muxc.TabView sender, object args)
    {
        var newTab = new muxc.TabViewItem();

        newTab.Header = "New Document";

        // The Content of a TabViewItem is often a frame which hosts a page.
        Frame frame = new Frame();
        newTab.Content = frame;
        frame.Navigate(typeof(Page1));

        sender.TabItems.Add(newTab);
    }


text:
Q: Hiding BottomAppBar while Scrolling WebView I have the following code on my home layout activity.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

    <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@+id/bottom_navigation"
        style="@style/Widget.MaterialComponents.BottomAppBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_gravity="bottom"
        app:backgroundTint="@android:color/white"
        app:fabCradleMargin="16dp"
        app:fabCradleRoundedCornerRadius="8dp"
        app:hideOnScroll="true"
        app:itemBackground="@color/colorPrimary"
        app:itemIconTint="@android:color/white"
        app:itemTextColor="@android:color/white"
        app:elevation="0dp"
        android:elevation="0dp"
        app:layout_scrollFlags="scroll|enterAlways"
        tools:ignore="BottomAppBar">

        <include
            android:id="@+id/nav_bar"
            layout="@layout/bottom_navigation_bar" />
    </com.google.android.material.bottomappbar.BottomAppBar>

</RelativeLayout>

I want to hide the bottom app bar on scrolling the webview. I have of course included the hideOnScroll and set it true. Unfortunately, it never hides on scrolling. Am I missing out something?

A: Try this :
webView.setOnTouchListener(new View.OnTouchListener() {
     public boolean onTouch(View v, MotionEvent event) {
       if(event.getAction() == MotionEvent.ACTION_MOVE){
         //Your Code to hide bottom bar
       }
     }
 });


text:
Q: How is the 'notes' field implemented in iOS Contacts App? I need to create something very similar to the notes field in iOS Contacts application.
Does anyone know how to create the auto-resizing effect. I presume that the cell contains a UILabel on the left and an editable UITextView on the right.

I am aware that this question has been already asked before however the answer posted was not detailed enough and I cannot leave a comment to ask for more detail.
Any thoughts are welcome. Thanks.

A: Start with the accepted answer to this thread.
You'll set some object, possibly the table view's delegate, as the delegate of the text field in the cell. When the text view delegate gets a – textView:shouldChangeTextInRange:replacementText: message (or perhaps just -textViewDidChange:) it can calculate the required height of the text view and, if that's different from the current height, call the table's -reloadRowsAtIndexPaths:withRowAnimation: method. This will cause the table to reload the row, effectively changing the height.


text:
Q: Youtube API 401 Error I'm using the Youtube API to try some things out and I can't get to do anything without getting the error. Expected response code is 200, got 401: User authentication required.
I have authenticated my Youtube channel though
session_start();

$clientLibraryPath = 'Youtube/library';
$oldPath = set_include_path(get_include_path() . PATH_SEPARATOR . $clientLibraryPath);

require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_YouTube');
$yt = new Zend_Gdata_YouTube();
Zend_Loader::loadClass('Zend_Gdata_AuthSub');

function getAuthSubRequestUrl()
{
$next = 'LINK';
$scope = 'http://gdata.youtube.com';
$secure = false;
$session = true;
return Zend_Gdata_AuthSub::getAuthSubTokenUri($next, $scope, $secure, $session);
}

function getAuthSubHttpClient()
{
if (!isset($_SESSION['sessionToken']) && !isset($_GET['token']) ){
    echo 'Login!';
    return;
} else if (!isset($_SESSION['sessionToken']) && isset($_GET['token'])) {
  $_SESSION['sessionToken'] =   Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);

}

$httpClient = Zend_Gdata_AuthSub::getHttpClient($_SESSION['sessionToken']);
return $httpClient;
}
getAuthSubHttpClient();

$cID = "Client ID";
$aID = "App ID";
$dK = "DEV KEY"; // Hidden
$yt = new Zend_Gdata_YouTube($httpClient, $aID, $cID, $dK);

Anyone know what I'm doing wrong here to login into my account?

A: Make sure you have your code hosted in the exact same URL as you set in the Google Code Console
If your javascript origins is set to http://example.com, make sure your code isn't being hosted at http://example.com/something or http://something.example.com! This seemed to work for me :)


text:
Q: set background color of single ListView element and forget it when the new element is clicked [Android] I know how to change a background color of single listView item but i want to if the another row will be clicked, the color of previous element dissapeared and reappeared in to newly selected item.
It's my method:
public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    v.setBackgroundColor(Color.parseColor("#222222"));
}

Can you help me?

A: not tested but still try it
//reset all the listView items background colours before we set the clicked one..

        for (int i=0; i<l.getChildCount(); i++)
        {
            l.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
        }
        //and then reset color for single row
        v.setBackgroundColor(Color.parseColor("#222222"));

A: I found a solution to this question. Maybe somebody will use it.
private void changeChoosenRowSettings(ListView l, int position) {
        l.getChildAt(position).setBackgroundColor(Color.GREEN);

        if (save != -1 && save != position){
            l.getChildAt(save).setBackgroundColor(Color.WHITE);
        }

        save = position;

    }


text:
Q: Django poll with many options how to limit visibility? I am building voting apps in django. I have little experience in programming and in django in particular. And here is the problem I ran into. My application should be able to receive an answer to three types of question:

*

*one answer

*multiple answer options

*your answer (free text)

Depending on the conditions of the survey, the user should see one of the answer options. But when I post a survey, the user sees all three answer options. How can I fix this? I hope for your help
models.py
class Poll(models.Model):
    title = models.CharField(max_length=256)
    start_date = models.DateField(auto_now_add=True)
    end_date = models.DateField()
    description = models.TextField(max_length=1024, blank=True)

    def __str__(self):
        return self.title

TYPES_OF_POLLS = (
    ('free_text', 'free text input'),
    ('option', 'only one choice'),
    ('options', 'many choices'),
)

class Question(models.Model):
    poll = models.ForeignKey(Poll, on_delete=models.CASCADE)
    text = models.CharField(max_length=250)
    poll_type = models.CharField(max_length=50, choices=TYPES_OF_POLLS, verbose_name='Types of polls')

    def __str__(self):
        return str(self.text)

class Option(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    text = models.CharField(max_length=256)

    def __str__(self):
        return f'{self.question} - {self.text}'

class Answer(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    one_option = models.ForeignKey(Option, on_delete=models.CASCADE, null=True, related_name='option', blank=True)
    many_options = models.ManyToManyField(Option, null=True, blank=True)
    text_input = models.TextField(null=True, blank=True)
    user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, blank=True, null=True)

    def __str__(self):
        return f'{self.question} - {self.one_option} - {self.many_options} - {self.text_input}  '

forms.py
class AnswerForm(ModelForm):
    class Meta:
        model = Answer
        fields = ['one_option', 'many_options', 'text_input']

views.py
def home(request):
    polls = Poll.objects.all
    context = {'polls':polls}
    return render (request, 'poll_app/home.html', context)

def vote(request, poll_id):
    form = AnswerForm()
    if request.method == 'POST':
        form = AnswerForm(request.POST)
        if form.is_valid():
            new_vote = form.save(commit=False)
            new_vote.user = request.user
            new_vote.save()
            return redirect('home')

    context = {
        'form':form
    }
    return render(request, 'poll_app/vote.html', context)

A: Firstly since a Survey should have only one question your ForeignKey should be a OneToOneField:
class Question(models.Model):
    poll = models.OneToOneField(Poll, on_delete=models.CASCADE, related_name="question")
    # Remaining fields

Now About your answer form you have two ways:

*

*Have multiple Answer models which you select according to the Question's poll_type field.

*Set the needed fields in the forms __init__ method.

Method 1 would be a little long for the answer. But I would suggest using that. Currently in the answer I would show how to use Method 2. You would also need some parts of this in method 1 as your current implementation lacks those things.
First we will override the forms __init__ method and accept the Question instance as a keyword argument, this is also needed to set the queryset of your fields that select options:
class AnswerForm(ModelForm):
    class Meta:
        model = Answer
        fields = ['one_option', 'many_options', 'text_input']

    def __init__(self, *args, **kwargs):
        question = kwargs.pop('question')
        super().__init__(*args, **kwargs)
        if question.poll_type == 'free_text':
            del self.fields['one_option']
            del self.fields['many_options']
        elif question.poll_type == 'option':
            del self.fields['many_options']
            del self.fields['text_input']
            self.fields['one_option'].queryset = question.option_set.all()
        elif question.poll_type == 'options':
            del self.fields['one_option']
            del self.fields['text_input']
            self.fields['many_options'].queryset = question.option_set.all()

Now in your view you need to pass the Question to the form:
from django.shortcuts get_object_or_404

def vote(request, poll_id):
    question = get_object_or_404(Question, poll_id=poll_id)
    form = AnswerForm(question=question)
    if request.method == 'POST':
        form = AnswerForm(request.POST, question=question)
        if form.is_valid():
            form.instance.user = request.user
            form.instance.question = question
            form.save()
            return redirect('home')

    context = {
        'form':form
    }
    return render(request, 'poll_app/vote.html', context)

Note: This current implementation would render your options in a select tag, perhaps you would find it better to use the RadioSelect and CheckboxSelectMultiple widgets, in that case you should declare the field yourself inside __init__ method of the form and specify the widget there.


text:
Q: Read csv based on header(first row in the csv) and map the value Iam new to process CSV, I have to handle scenario like below CSV

"TestPaymentClientX.csv"
id,date,amount,currency,status,clientId
1,20220504,100,USD,success,X1
2,20220504,10,USD,success,X11

"TestPaymentClientY.csv"
id,amount,date,status,currency,name,clientId
1,100,20220504,success,USD,test1,Y1
2,10,20220504,success,USD,test2,Y11

I want to read this CSV and assign value to the Generic model

class Payment{
String Status;
Long id;
BigDecimal amount;
Long paymentDate;
String paymentCurrency:
}

My Module has fixed name and number of properties. but each client will send CSV file with more or less number of header/value in CSV.
for some client few property is optional, so in their CSV it will not be there some client may send in different order(so based on header, need to map the value to object)
Let me know for efficient and flexible approaches to handle this