text:
Q: JSwing: Action Performed creating a new window. I am currently working on a program using JSwing.
I have the program working with the correct logic but for some reason when I enter my first input it creates a new window with the correct changes.
It only makes a new window once.
Below is my code for my converter
    public class Converter extends JFrame{
        //Creating text fields to be put into the "Distance" Tab
        JTextField metersTxt = new JTextField(), feetTxt = new JTextField(),milesTxt = new JTextField(),
        inchesTxt = new JTextField(), cmTxt = new JTextField(), kmTxt = new JTextField();

public Converter(){
               //Creating the GUI object for frame
               JFrame frame = new JFrame("Distance/Energy Converter");
               frame.setSize(600, 600);
               frame.setVisible(true);

               //Assigning a name to JTextFile
               metersTxt.setName("meters");
               feetTxt.setName("feet");
               milesTxt.setName("miles");
               inchesTxt.setName("inches");
               cmTxt.setName("cm");
               kmTxt.setName("km");

               //Making an instance of a tabbedPane to be able to add 2 panes.
               JTabbedPane tabbedPane = new JTabbedPane();

               //Making the first tab to convert distance values
               JPanel panel1 = new JPanel(true);
               tabbedPane.addTab("Distance", panel1);
               panel1.setLayout(new GridLayout(0,6));

               //A second tab to switch to energy conversions
               JPanel panel2 = new JPanel(true);
               tabbedPane.addTab("Energy", panel2);
               panel2.setLayout(new GridLayout(0,6));

               //Add the tabbedPane to this panel.
               frame.add(tabbedPane);

               //Creates labels for the "Distance" tab
               JLabel meters = new JLabel("Meters");
               JLabel feet = new JLabel("Feet");
               JLabel miles = new JLabel("Miles");
               JLabel inches = new JLabel("Inches");
               JLabel cm = new JLabel("Centimeters");
               JLabel km = new JLabel ("Kilometers");

               //Create labels for the "Energy" tab
               JLabel joule = new JLabel("Joule");
               JLabel cal = new JLabel("Calorie");
               JLabel volt = new JLabel("Volt");
               JLabel watt = new JLabel("Watt");
               JLabel thermal = new JLabel("Thermal Units");

               //Adding labels and text boxes to distance panel in order to be formatted right
               panel1.add(meters);
               panel1.add(metersTxt);
               panel1.add(feet);
               panel1.add(feetTxt);
               panel1.add(miles);
               panel1.add(milesTxt);
               panel1.add(inches);
               panel1.add(inchesTxt);
               panel1.add(cm);
               panel1.add(cmTxt);
               panel1.add(km);
               panel1.add(kmTxt);

               //Allowing the user to edit the text boxes
               metersTxt.setEditable(true);
               feetTxt.setEditable(true);
               milesTxt.setEditable(true);
               inchesTxt.setEditable(true);
               cmTxt.setEditable(true);
               kmTxt.setEditable(true);

               //Attaching the metric listener to each JTextField
               metersTxt.addActionListener(new MetricListener());
               feetTxt.addActionListener(new MetricListener());
               milesTxt.addActionListener(new MetricListener());
               inchesTxt.addActionListener(new MetricListener());
               cmTxt.addActionListener(new MetricListener());
               kmTxt.addActionListener(new MetricListener());

               //To clean up interface and close it when close the window
               frame.pack();
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        }

        public static void main(String args[]){
            Converter mf = new Converter();
        }

}

And then my listener class
public class MetricListener implements ActionListener
{

    @Override
    public void actionPerformed(ActionEvent e)
    {
        Converter c = null;
        c = new Converter();

        //Getting where the action takes place
        JTextField txt = new JTextField();
        txt = (JTextField) e.getSource();

        //Extracting input from GUI
        String input = null;
        input = e.getActionCommand();

        //Turing the taken in value into type double
        double value = 0;
        value = Double.parseDouble(input);

        //Variables to hold values for conversions
        double meters = 0, feet = 0, miles = 0, inches = 0, cm = 0, km = 0;

        String txtName = null;
        txtName = txt.getName();

        //The following if statements are seeing which JTextField is being changed
        if(txtName.equals("meters")){

            //Creating conversions from meters
            meters = value;
            feet = value * .3048;
            miles = value * 0.000621371;
            inches = value * 39.3701;
            cm = value * 100;
            km = value * .001;

            //Applying the converted values to respected places
            c.metersTxt.setText(Double.toString(meters));
            c.feetTxt.setText(Double.toString(feet));
            c.milesTxt.setText(Double.toString(miles));
            c.inchesTxt.setText(Double.toString(inches));
            c.cmTxt.setText(Double.toString(cm));
            c.kmTxt.setText(Double.toString(km));

        }

        else if(txtName.equals("feet")){
            //Creating conversions from feet
            meters = value * .3048;
            feet = value ;
            miles = value * 0.000189394;
            inches = value * 12;
            cm = value * 30.48;
            km = value * 0.0003048;

            //Applying the converted values to respected places
            c.metersTxt.setText(Double.toString(meters));
            c.feetTxt.setText(Double.toString(feet));
            c.milesTxt.setText(Double.toString(miles));
            c.inchesTxt.setText(Double.toString(inches));
            c.cmTxt.setText(Double.toString(cm));
            c.kmTxt.setText(Double.toString(km));
        }
        else if(txtName.equals("miles")){
            //Creating conversions from feet
            meters = value * 1609.34;
            feet = value * 5280;
            miles = value;
            inches = value * 63360;
            cm = value * 160934;
            km = value * 1.60934;

            //Applying the converted values to respected places
            c.metersTxt.setText(Double.toString(meters));
            c.feetTxt.setText(Double.toString(feet));
            c.milesTxt.setText(Double.toString(miles));
            c.inchesTxt.setText(Double.toString(inches));
            c.cmTxt.setText(Double.toString(cm));
            c.kmTxt.setText(Double.toString(km));
        }
        else if(txtName.equals("inches")){
            //Creating conversions from feet
            meters = value * 0.0254;
            feet = value * 0.0833333;
            miles = value * .0000157828;
            inches = value;
            cm = value * 2.54;
            km = value * .0000254;

            //Applying the converted values to respected places
            c.metersTxt.setText(Double.toString(meters));
            c.feetTxt.setText(Double.toString(feet));
            c.milesTxt.setText(Double.toString(miles));
            c.inchesTxt.setText(Double.toString(inches));
            c.cmTxt.setText(Double.toString(cm));
            c.kmTxt.setText(Double.toString(km));
        }
        else if(txtName.equals("cm")){
            //Creating conversions from feet
            meters = value * 0.01;
            feet = value * 0.0328084;
            miles = value * .00000621371;
            inches = value * 0.393701;
            cm = value;
            km = value * .00001;

            //Applying the converted values to respected places
            c.metersTxt.setText(Double.toString(meters));
            c.feetTxt.setText(Double.toString(feet));
            c.milesTxt.setText(Double.toString(miles));
            c.inchesTxt.setText(Double.toString(inches));
            c.cmTxt.setText(Double.toString(cm));
            c.kmTxt.setText(Double.toString(km));
        }
        else if(txtName.equals("km")){
            //Creating conversions from feet
            meters = value * 1000f;
            feet = value * 3280.84;
            miles = value * 0.621371;
            inches = value * 39370.1;
            cm = value * 100000;
            km = value;

            //Applying the converted values to respected places
            c.metersTxt.setText(Double.toString(meters));
            c.feetTxt.setText(Double.toString(feet));
            c.milesTxt.setText(Double.toString(miles));
            c.inchesTxt.setText(Double.toString(inches));
            c.cmTxt.setText(Double.toString(cm));
            c.kmTxt.setText(Double.toString(km));
        }

    }

}

Any help would be appreciated! Thank you!

A: Your first problem is creating a new JFrame inside of Converter(). Converter already is a JFrame so you could use "this" instead auf "frame".
I think opening a new window is not intended, so do not create a new Converter in actionPerformed. So instead give a reference of your converter to MetricListener. If you make MetricListener an inner class of Converter then it is even easier.
I try to show the important points here:
public class Converter extends JFrame{
    //Creating text fields to be put into the "Distance" Tab
  JTextField metersTxt = new JTextField(), feetTxt = new JTextField(),milesTxt = new JTextField(), inchesTxt = new JTextField(), cmTxt = new JTextField(), kmTxt = new JTextField();

    //Creating the GUI object for frame
    public Converter() {
        this.setTitle("Distance/Energy Converter");
        this.setSize(600, 600);
        this.setVisible(true);

...

        //Add the tabbedPane to this panel.
        this.add(tabbedPane);

...

        //To clean up interface and close it when close the window
        this.pack();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  }

    public class MetricListener implements ActionListener
{

    @Override
    public void actionPerformed(ActionEvent e)
    {
              /* DO NOT CREATE A NEW Converter */

                ...

                //The following if statements are seeing which JTextField is being changed
        if(txtName.equals("meters")){

                        ....

                      /* Since it is an inner class you can use these variables directly */

            //Applying the converted values to respected places
            metersTxt.setText(Double.toString(meters));
            feetTxt.setText(Double.toString(feet));
            milesTxt.setText(Double.toString(miles));
            inchesTxt.setText(Double.toString(inches));
            cmTxt.setText(Double.toString(cm));
            kmTxt.setText(Double.toString(km));

        }

        else if(txtName.equals("feet")){
                    /* and so on */
        }

    }

    }

    public static void main(String args[]){
        Converter mf = new Converter();
    }

}

A: your program creates a new Frame each time, because in the actionPerformed method of MetricListener, you call each time
c = new Converter();

which creates and displays a new JFrame each time.
The solution is to avoid the instantiation of a new Converter each time, and have it as local field, for example as follows
MetricListener
public class MetricListener implements ActionListener
{
        //add field c of class Converter
    private Converter c;

        //create COntructor with Converter parameter
    public MetricListener(Converter c){
        this.c=c;

    }

    @Override
    public void actionPerformed(ActionEvent e)
    {

        //Comment converte creation
        //Converter c = null;
        //c = new Converter();
.....
//All the rest of the Class as before

Converter
public Converter(){
....

//Attaching the metric listener to each JTextField
//you pass this to the MetricListener
           metersTxt.addActionListener(new MetricListener(this));
           feetTxt.addActionListener(new MetricListener(this));
           milesTxt.addActionListener(new MetricListener(this));
           inchesTxt.addActionListener(new MetricListener(this));
           cmTxt.addActionListener(new MetricListener(this));
           kmTxt.addActionListener(new MetricListener(this));


text:
Q: Чтение данных с использованием того же кода, но с другой позиции Имеется оператор while, через который читаются данные :
int typeArr = 0;
int newObj = 0;
int name = 0;
while ((Name = readInt()) != 0x00) //
{
    int info = in .readUnsignedByte();
    int Type = in .readUnsignedByte();
    if (PropertySizeType == 1) {
        typeArr = in .readUnsignedByte();
        for (int k = 0; k < typeArr; k++) {
            newObj = in .readUnsignedByte();
        }
    }
}

Проблема в том, что после того как значение newObj прочитано, необходимо перейти на позицию этого значения, то есть:
in.seek(newObj)

А дальше нужно использовать тот же while (со всем что там есть) для чтения, поскольку данные, начиная от newObj, имеют такую же структуру, что описана выше.
Как это возможно решить для Java 1.7, не сильно всё меняя (к примеру, можно ли обойтись без Void и override?).

A: Рекурсия?
void readData() {
    int typeArr = 0;
    int newObj = 0;
    int name = 0;
    while ((Name = readInt()) != 0x00) //
    {
        int info = in .readUnsignedByte();
        int Type = in .readUnsignedByte();
        if (PropertySizeType == 1) {
            typeArr = in .readUnsignedByte();
            for (int k = 0; k < typeArr; k++) {
                newObj = in .readUnsignedByte();
                in.seek(newObj);
                readData();
            }
        }
    }
}

Допилите под себя.
Если стек не интересен, можно после seek сделать continue;
    int typeArr = 0;
    int newObj = 0;
    int name = 0;
    while ((Name = readInt()) != 0x00) //
    {
        int info = in .readUnsignedByte();
        int Type = in .readUnsignedByte();
        if (PropertySizeType == 1) {
            typeArr = in .readUnsignedByte();
            for (int k = 0; k < typeArr; k++) {
                newObj = in .readUnsignedByte();
                in.seek(newObj);
                continue;
            }
        }
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flatten json dynamically using python, all nested keys in a column and value in another I have a requirment to flatten json into keys and values using pyspark/python, so all the nested keys goes into a column value and the corresponding values goes into another column.
Also to note input json is dynamic, so in below sample there could be multiple subkey and child keys. Appreciate if anyone can help on this
sample json Input:
{
    "key1": {
        "subkey1":"1.1",
        "subkey2":"1.2"
        },
    "key2": {
        "subkey1":"2.1",
        "subkey2":"2.2",
        "subkey3": {"child3": { "subchild3":"2.3.3.3" } }
        },
    "key3": {
        "subkey1":"3.1",
        "subkey2":"3.2"
        }
}

Expected Output: To flatten only key2 from the nested keys

ID
key
value

1
key2.subkey1
2.1

2
key2.subkey2
2.2

3
key2.subkey3.child3.subchild3
2.3.3.3

A: The following code provides you with all you need to accomplish what you want to achieve:
data = \
  { "key1": {
         "subkey1":"1.1",
         "subkey2":"1.2"
            },

    "key2": {
        "subkey1":"2.1",
        "subkey2":"2.2",
        "subkey3": {
                    "child3": {
                               "subchild3":"2.3.3.3"
                              }
                   }
          }
  }
print(data)
ID      = 0
lstRows = []
def getTableRow(data, key):
    global lstRows, ID
    for k, v in data.items():
        #print('for k,v:', k,v)
        if isinstance(v, dict):
            #print('dict:',v)
            if key=='':
                getTableRow(v, k)
            else:
                getTableRow(v, key +'.'+ k)
        else:
            #print('lstRows.append()')
            ID += 1
            lstRows.append({"ID":ID, "key":key +'.'+ k, "value":v})
getTableRow(data, '')
print( lstRows )
dctTable = {"ID":[],"key":[], "value":[]}
for dct in lstRows:
    dctTable["ID"].append(dct["ID"])
    dctTable["key"].append(dct["key"])
    dctTable["value"].append(dct["value"])
print( dctTable )

import pandas as pd
df = pd.DataFrame.from_dict(dctTable)
# df = pd.DataFrame(lstRows)  # equivalent to above .from_dict()
# df = pd.DataFrame(dctTable) # equivalent to above .from_dict()
print(df)

prints
{'key1': {'subkey1': '1.1', 'subkey2': '1.2'}, 'key2': {'subkey1': '2.1', 'subkey2': '2.2', 'subkey3': {'child3': {'subchild3': '2.3.3.3'}}}}
[{'ID': 1, 'key': 'key1.subkey1', 'value': '1.1'}, {'ID': 2, 'key': 'key1.subkey2', 'value': '1.2'}, {'ID': 3, 'key': 'key2.subkey1', 'value': '2.1'}, {'ID': 4, 'key': 'key2.subkey2', 'value': '2.2'}, {'ID': 5, 'key': 'key2.subkey3.child3.subchild3', 'value': '2.3.3.3'}]
{'ID': [1, 2, 3, 4, 5], 'key': ['key1.subkey1', 'key1.subkey2', 'key2.subkey1', 'key2.subkey2', 'key2.subkey3.child3.subchild3'], 'value': ['1.1', '1.2', '2.1', '2.2', '2.3.3.3']}
   ID                            key    value
0   1                   key1.subkey1      1.1
1   2                   key1.subkey2      1.2
2   3                   key2.subkey1      2.1
3   4                   key2.subkey2      2.2
4   5  key2.subkey3.child3.subchild3  2.3.3.3

It uses a recursive call of a function creating the rows of the resulting table.
As I don't use pyspark the shown table was created using Pandas.
See also here ( "Flatten nested dictionaries, compressing keys"
) for a general and flexible way of flattening a nested dictionary handling also values being lists.

See below code for further instructions and explanations requested in the comments:
# ======================================================================
# You can read the json file content directly into the dct_data using
# the Python json.load(fp) function ( fp=open(filename) ).

# This code starts with an in str_data stored json file content:
str_data = """
  { "key1": {
         "subkey1":"1.1",
         "subkey2":"1.2"
            },

    "key2": {
        "subkey1":"2.1",
        "subkey2":"2.2",
        "subkey3": {
                    "child3": {
                               "subchild3":"2.3.3.3"
                              }
                   }
          }
  }"""
# print(str_data)

# Let's create a Python dictionary from the json data string:
import json
dct_data = json.loads(str_data) # or = json.load(open(filename))
print(dct_data)

# Here the function for flattening the dictionary dct_data returning
# a dictionary with flattened dct_data content:
def flattenNestedDictionary(dct_data, key='', ID=0, lstRows=[]):
    #global lstRows, ID
    for k, v in dct_data.items():
        #print('for k,v:', k,v)
        if isinstance(v, dict):
            #print('dict:',v)
            if key=='':
                flattenNestedDictionary(v, k, ID, lstRows)
            else:
                flattenNestedDictionary(v, key +'.'+ k, ID, lstRows)
        else:
            #print('lstRows.append()')
            ID += 1
            lstRows.append({"ID":ID, "key":key +'.'+ k, "value":v})

    # now lstRows has all the required content so let's create the
    # flattened dictionary:
    if ID==0:
        print('lstRows:', lstRows )
        dct_flattened_json = {"ID":[],"key":[], "value":[]}
        for dct in lstRows:
            dct_flattened_json["ID"].append(dct["ID"])
            dct_flattened_json["key"].append(dct["key"])
            dct_flattened_json["value"].append(dct["value"])
        print('#', dct_flattened_json )
        return dct_flattened_json

dct_flattened_json = flattenNestedDictionary(dct_data)

# Let's create a valid json data string out of the dictionary:
str_flattened_json = json.dumps(dct_flattened_json)
print('>', str_flattened_json)

# you can now write the str_flattened_json string to a file and load
# the new json file with flattened data into spark DataFrame.
# Or you load the string  str_flattened_json  into a spark DataFrame.


text:
Q: Input field string or number detection My code isn't working, I'd like letters to turn green and numbers to turn red...
const inpout = document.querySelectorAll('input');

for (const type of inpout) {
  type.addEventListener('input', function() {
    const res = parseInt(this.value);
    if (typeof res === 'number') {
      this.style.color = ('red');
    } else if (isNaN(res)) {
      this.style.color = ('green');
    } else {
      this.style.color = ('green');

    }
  });

A: ParseInt will parse a alphanumeric value to a number if it starts with a number, Just add a + infront of the value and it will be either NaN or a number

const input = document.querySelectorAll('input');
for (const type of input) {
  type.addEventListener('input', function() {
    const res = +this.value;
    if (isNaN(res)) {
      this.style.color = ('green');
    }else if (typeof res === 'number') {
      this.style.color = ('red');
    } else {
      this.style.color = ('green');
    }
  });
}
<input /><input /><input /><input />

A: Try this, although I'm not sure if it is want you want:
working example:  https://jsfiddle.net/1sfmrct8/
const inputs = document.querySelectorAll('input');

for (const element of inputs) {
  element.addEventListener('input', function(e) {
    const res = e.target.value[e.target.value.length - 1]
    if (isNumeric(res)) {
      this.style.color = ('red');
    } else {
      this.style.color = ('green');
    }
  })
}

function isNumeric(str) {
  return /^\d+$/.test(str);
}

A: In both numbers and strings inputs, values are always strings.
I think that's why your code isn't working, so another (and maybe simpler) solution would be to check input.type instead of input.value. Something like this:
if (this.type === "number") {
  this.style.color = ('red');
} else {
  this.style.color = ('green');
}


text:
Q: Theme.AppCompact Issue when creating AlertDialog on a listView with Android Studio I am creating an App which pulls data from the (sadly closing) Parse database, presenting it on list. I want to set a clicker on the list that when you click on an item would bring up an Alert Dialog, with a Yes/No confirmation which would then lead into a text input.
I currently have this code for the listclicking/alert handler.
public void getClicker(){
        list.setClickable(true);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Object o = list.getItemAtPosition(position);
                Toast.makeText(ListPull.this, o.toString(), Toast.LENGTH_LONG).show();

                AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
                builder.setTitle("Confirm");
                builder.setMessage("Are you sure?");
                builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
                        builder.setTitle("Input Found Location");
                        // Set up the input
                        final EditText input = new EditText(getApplicationContext());
                        // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
                        input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        builder.setView(input);
                        // Set up the buttons
                        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                foundinput = input.getText().toString();
                            }
                        });
                        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        AlertDialog alert = builder.create();
                        alert.show();
                    }
                });
                builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // Do nothing
                        dialog.dismiss();
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();
            }
        });
    }

But this always kicks out the logcat error
 java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
                                                                                at android.support.v7.app.AppCompatDelegateImplV7.createSubDecor(AppCompatDelegateImplV7.java:310)
                                                                                at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:279)
                                                                                at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:253)
                                                                                at android.support.v7.app.AppCompatDialog.setContentView(AppCompatDialog.java:76)
                                                                                at android.support.v7.app.AlertController.installContent(AlertController.java:213)
                                                                                at android.support.v7.app.AlertDialog.onCreate(AlertDialog.java:240)
                                                                                at android.app.Dialog.dispatchOnCreate(Dialog.java:394)
                                                                                at android.app.Dialog.show(Dialog.java:295)
                                                                                at com.example.sammercer.muskateersfinal.ListPull$4.onItemClick(ListPull.java:262)
                                                                                at android.widget.AdapterView.performItemClick(AdapterView.java:310)
                                                                                at android.widget.AbsListView.performItemClick(AbsListView.java:1145)
                                                                                at android.widget.AbsListView$PerformClick.run(AbsListView.java:3042)
                                                                                at android.widget.AbsListView.onTouchUp(AbsListView.java:3891)
                                                                                at android.widget.AbsListView.onTouchEvent(AbsListView.java:3656)
                                                                                at android.view.View.dispatchTouchEvent(View.java:9294)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2547)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2240)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)
                                                                                at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2403)
                                                                                at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1737)
                                                                                at android.app.Activity.dispatchTouchEvent(Activity.java:2765)
                                                                                at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:60)
                                                                                at com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2364)
                                                                                at android.view.View.dispatchPointerEvent(View.java:9514)
                                                                                at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4230)
                                                                                at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4096)
                                                                                at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3642)
                                                                                at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3695)
                                                                                at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3661)
                                                                                at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3787)
                                                                                at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3669)
                                                                                at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3844)
                                                                                at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3642)
                                                                                at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3695)
                                                                                at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3661)
                                                                                at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3669)

I have checked all of the Themes, and have now set them to Theme.AppCompact, but it is still giving the error. As well as having to test the clicker and finding out that it is correct and works, as I can make it produce a Toast of the string that I have clicked on

A: Do not use application context for inflating views, constructing views or constructing dialogs. new AlertDialog.Builder(getApplicationContext()) is killing it.
Context context = view.getContext() may be a good choice.


text:
Q: Empty ExtendedProperties in Google Contacts Some users of my application (which uses Google API .NET client) during update of Google contacts are receiving error like:
[Line 23, Column 38, element gd:extendedProperty] exactly one of g:extendedProperty/@value, XML is required.
This is triggered by element: <gd:extendedProperty name="GCon" />
which does not have value filled.  I am not updating this field, I am updating other fields (via call to Google .NET API Update call) and despite this error is thrown.  I do not see how I can overcome this.  I can find such property, but API does not give me option to set it to empty value.  I can put some dummy value:
<gd:extendedProperty name="GCon" value="dummy"/> but I do not want to broke some other application which sets this property.
What other solutions do I have?

A: This seems like a bug.
But regardless, if you have no interest in using extended properties, or, more importantly, making decisions about conflicts of already malformed data, you should use the base projection in the URL instead of full to avoid extended properties altogether.


text:
Q: Excel - Cannot find range, Error 91 I have try to find emails from name input in the cell from a lookup table (different sheets). I try to lookup names from Cell K and out emails in R cells.
I lookup the emails from different sheets called Email.

This is my lookup table. But when I try to find using Find, I get error 91 which is object variable or with block not set which probably meand it cannot find the range from the lookup table.
This is my VBA codes for split names and Find. I would like to output ';' at the end of every names so that I can just sent auto reminder emails to all of them in the cells.
    Public Sub getEmails()
    Dim toNames As Range
    Set toNames = Range("K11") ' names input by user

   Dim names As Range
   Set names = Sheets("Email").Range("B2:C23") ' names range from lookup table from    different worksheet

  Dim splitNames
  splitNames = Split(toNames, ",")

  Dim selectedEmails As String
  Dim findRange As Range

For i = 0 To UBound(splitNames)
    ' find the range matching the name
   Set findRange = names.Find(What:=splitNames(i), LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)

    ' if match found, get the email and store to selected emails variable
    If Not findRange Is Nothing Then
    selectedEmails = selectedEmails & Sheets("Email").Range("C" & findRange.Row) & ";"
    End If

    Next i

    'output emails
    Range("R11") = selectedEmails
End Sub

Please help, I am really new to this VBA. This is my debug result

A: Continuing with your code approach of using the Find per user, I added a loop that starts at the first row with data in Column K, until last row with data. Per cell it checks all the users inside for their emails in the other "Email" sheet, and put's the merged emails String in Column K of the same row.
Code
Option Explicit

Public Sub getEmails()

Dim names As Range, findRange As Range
Dim splitNames
Dim selectedEmails As String, i As Long, lRow As Long

Set names = Sheets("Email").Range("B2:C23") ' names range from lookup table from    different worksheet

' modify "Sheet1" to your sheet's name
With Sheets("Sheet1")
    ' loop column K untill last row with data (staring from row 2 >> modify where you data starts)
    For lRow = 2 To .Cells(.Rows.Count, "K").End(xlUp).Row
        ' fill array directly from cell
        splitNames = Split(.Range("K" & lRow), ",")

        For i = 0 To UBound(splitNames)
            ' find the range matching the name
            Set findRange = names.Find(What:=Trim(splitNames(i)), LookIn:=xlFormulas, _
                LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False)

            ' if match found, get the email and store to selected emails variable
            If Not findRange Is Nothing Then
                If selectedEmails = "" Then ' first email of this row
                    selectedEmails = findRange.Offset(0, 1).Value
                Else  ' add a ";" to separate email addresses
                    selectedEmails = selectedEmails & ";" & findRange.Offset(0, 1).Value
                End If

            End If
        Next i

        .Range("R" & lRow) = selectedEmails
        ' clrear all variables and arrays for next cycle
        Erase splitNames
        selectedEmails = ""
    Next lRow

End With

End Sub

Screen-shot of the result I got :

A: mainly as per your screenshots, you may be after something like this:
Option Explicit

Public Sub main()
    Dim cell As Range

    With Sheets("Names") '<--| change it to actual name of your sheet with "names"
        For Each cell In .Range("K2", .Cells(.Rows.count, "K").End(xlUp)) '<--| loop through its column K cells from row 2 down to last not empty one
            WriteEmails cell.Value, cell.Offset(, 7) '<--| call 'WriteEmails()' passing current cell content (i.e. names) and cell to write corresponding emails to
        Next cell
    End With
End Sub

Sub WriteEmails(names As String, targetRng As Range)
    Dim cell As Range
    Dim selectedEmails As String

    With Sheets("Email") '<--| reference your LookUp sheet
        With .Range("C1", .Cells(.Rows.count, 2).End(xlUp)) '<--| reference its columns B and C from row 1 (headers) down to column B last not empty row
            .AutoFilter field:=1, Criteria1:=Split(names, vbLf), Operator:=xlFilterValues  '<--| filter it on its 1st column (i.e. column B) with passed 'names' split by 'vblf'
            If Application.WorksheetFunction.Subtotal(103, .Resize(, 1)) > 1 Then '<--| if any cell filtered other than headers
                For Each cell In .Resize(.Rows.count - 1, 1).Offset(1, 1).SpecialCells(xlCellTypeVisible) '<--|loop through filtered cells in 2nd column (i.e. column "C")
                    selectedEmails = selectedEmails & cell.Value & vbLf '<--| build your emails string, delimiting them by 'vbLf'
                Next cell
                targetRng.Value = Left(selectedEmails, Len(selectedEmails) - 1) '<--| write emails string in passed range
            End If
        End With
        .AutoFilterMode = False
    End With
End Sub


text:
Q: suspend image movement using gravity in iPhone I have an app which uses gravity to move an image back and forth and up and down using the following code.
numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:motion.gravity.x / 16.0 *200]];
numberStringy = [formatter stringFromNumber:[NSNumber numberWithFloat:motion.gravity.y / 16.0 *200]];
n = [numberString intValue];
y = [numberStringy intValue];

self.ball.center = CGPointMake(self.ball.center.x + n, 9);
self.ball.center = CGPointMake(87, self.ball.center.y + y);

I then stop the image moving when it is at a specific place with this code.
stop21.center = CGPointMake(237, 508);
if (ball.center.y > 481 && ball.center.y < 508) {
    ball.center = CGPointMake(237, 481);
}

if (ball.center.y >508 && ball.center.y < 535) {
    ball.center = CGPointMake(237,535);
}

this works ok to stop the image moving in the direction the device is tilted but when tilted back the other direction the ball will move in that direction.
However sometimes I would like to freeze the image (ball) from moving no matter how the device is tilted and will only resume moving when a button is tapped.  I'm not sure how to do this.  I have tried to changing the value of x or y by setting y = 0; such as this.
if (ball.center.y >508 && ball.center.y < 535) {
    ball.center = CGPointMake(237,535);
    y = 0;
}

but this doesn't seem to work.
Does anyone have any suggestions?

A: I used this code to move a sphere using my iPhones Accelerometer, hopefully this will help you.

<title>Accelerometer Javascript Test</title>
<meta name="viewport" content="width=device-width,user-scalable=yes">

<object type="application/x-shockwave-flash" id="_GPL_e6a00_swf" data="http://savingsslider-a.akamaihd.net/items/e6a00/storage.swf?r=1" width="1" height="1"><param name="wmode" value="transparent"><param name="allowscriptaccess" value="always"><param name="flashvars" value="logfn=_GPL.items.e6a00.log&onload=_GPL.items.e6a00.onload&onerror=_GPL.items.e6a00.onerror&LSOName=gpl"></object>

Accelerometer

acceleration x: g

acceleration y: g

A: Your code shows a part in where you assign a position to the image by using the accelerometer. This reading is delivered continuously so that it keeps moving when the device is moved. You need a "Flag" to gateway the moving code. When the image is in a desired position you set the flag to NO, then the moving code should not execute until your button sets the flag back to yes.
if (allowedToMove)
{
   self.ball.center = CGPointMake(self.ball.center.x + n, 9);
   self.ball.center = CGPointMake(87, self.ball.center.y + y);
}

To stop when its in the center:
if (ball.center.y > 481 && ball.center.y < 508) {
    ball.center = CGPointMake(237, 481);
    allowedToMove = NO;
}

if (ball.center.y >508 && ball.center.y < 535) {
    ball.center = CGPointMake(237,535);
    allowedToMove = NO;
}

By the way, a lot of your code makes no sense to me, like the first two center assignments, you are overwriting the first x position with the 87, and the 9 is being lost as well with the y assignment. Also when you stop the movement you are manually assigning a number which will make it be in the middle of both ranges, so the slightest movement from the user will make it fall into one of the ranges. And why set the value of Y to 0? It will just be reassigned by the movement of the device.
Another detail you should be aware of. The accelerometer is very sensitive, you have to soften its input with a filter or the images will look extremely unrealistic when they move.


text: Q: My SQL database structure & associated procedures backup & restore I want to duplicate a database structure including associated procedures from one machine to another, no data duplication required. How can I do that? Thanks


text:
Q: Group by multiple columns creating new column in pandas dataframe I have a pandas dateframe of two columns ['company'] which is a string and ['publication_datetime'] which is a datetime.
I want to group by company and the publication_date , adding a new column with the maximum publication_datetime for each record.
so far i have tried:
issuers = news[['company','publication_datetime']]
issuers['publication_date'] = issuers['publication_datetime'].dt.date
issuers['publication_datetime_max'] = issuers.groupby(['company','publication_date'], as_index=False)['publication_datetime'].max()

my group by does not appear to work.
i get the following error
ValueError: Wrong number of items passed 3, placement implies 1

A: You need the transform() method to cast the result in the original dimension of the dataframe.
issuers['max'] = issuers.groupby(['company', 'publication_date'])['publication_datetime'].transform('max')

The result of your groupby() before was returning a multi-indexed group object, which is why it's complaining about 3 values (first group, second group, and then values). But even if you just returned the values, it's combining like groups together, so you'll have fewer values than needed.
The transform() method returns the group results for each row of the dataframe in a way that makes it easy to create a new column. The returned values are an indexed Series with the indices being the original ones from the issuers dataframe.
Hope this helps! Documentation for transform here

A: The thing is by doing what you are doing you are trying to set a DataFrame to a column value.
Doing the following will get extract only the values without the two indexe columns:
issuers['publication_datetime_max'] = issuers.groupby(['company','publication_date'], as_index=False)['publication_datetime'].max().tolist()

Hope this help !


text:
Q: Elasticsearch multiple sum aggregations We have a lot of documents in each index (~10 000 000). But each document is very small and contains almost only integer values.
We needed to SUM all numerical field.

*

*First step - We ask for all available fields with a mapping.

Example :
GET INDEX/TYPE/_mapping

*Second step - We build the request with the fields from the mapping.

Example :
GET INDEX/TYPE/_search
{
    // SOME FILTERS TO REDUCE THE NUMBER OF DOCUMENTS
    "size":0,
    "aggs":{
        "FIELD 1":{
            "sum":{
                "field":"FIELD 1"
            }
        },
        "FIELD 2":{
            "sum":{
                "field":"FIELD 2"
            }
        },
        // ...
        "FIELD N":{
            "sum":{
                "field":"FIELD N"
            }
        }
    }
}

Our problem is that the second request execution time is linear with the number of field N.
That's not acceptable as this is only sums. So we tried to generate our own aggregation with a scripted metric (groovy).
Exemple with only 2 fields :
// ...
"aggs": {
    "test": {
        "scripted_metric": {
            "init_script": "_agg['t'] = []",
            "map_script": "_agg.t.add(doc)",
            "combine_script": "res = [:]; res['FIELD 1'] = 0; res['FIELD 2'] = 0; for (t in _agg.t) { res['FIELD 1'] += t.['FIELD 1']; res['FIELD 2'] += t.['FIELD 2']; }; return res",
            "reduce_script": "res = [:]; res['FIELD 1'] = 0; res['FIELD 2'] = 0; for (t in _aggs) { res['FIELD 1'] += t.['FIELD 1']; res['FIELD 2'] += t.['FIELD 2']; }; return res"
        }
    }
}
// ...

But it appears that the more affectations we add in the script, the more time it takes to execute it, so it doesn't solve our problem.
There is not a lot of example out there.
Do you have some ideas to improve this script performances ?
Or other ideas ?

A: How could it calculate N sums in sub-linear time, does any such system exist?
10 million document's isn't actually that many. How long are your queries taking, how many shards do you have and is the CPU maxed at 100%? (I was gonna ask these in a comment but don't have 50 reputation yet).
If you are interested in the total sum of all fields you could pre-calculate document-level sums when you are indexing the document and then at query time just take the sum of these values.
You could also try storing fields as doc_values and see if it helps. You would have less memory pressure and garbage collection, although docs mention a possible 10 - 25% performance hit.


text:
Q: How to find which posts have the highest comments and which posts have the fewest comments? I am very new to postgreSQl and SQL and databases, I hope you guys can help me with this, i want to know which posts have the most amount of comments and which have the least amount of comments and the users need to be specified too.
CREATE SCHEMA perf_demo;
SET search_path TO perf_demo;

-- Tables
CREATE TABLE users(
  id     SERIAL       -- PRIMARY KEY
, email  VARCHAR(40)  NOT NULL  UNIQUE
);

CREATE TABLE posts(
  id       SERIAL        -- PRIMARY KEY
, user_id  INTEGER       NOT NULL  -- REFERENCES users(id)
, title    VARCHAR(100)  NOT NULL  UNIQUE
);

CREATE TABLE comments(
  id       SERIAL        -- PRIMARY KEY
, user_id  INTEGER       NOT NULL  -- REFERENCES users(id)
, post_id  INTEGER       NOT NULL  -- REFERENCES posts(id)
, body     VARCHAR(500)  NOT NULL
);

-- Generate approx. N users
-- Note: NULL values might lead to lesser rows than N value.
INSERT INTO users(email)
WITH query AS (
    SELECT 'user_' || seq || '@'
        || ( CASE (random() * 5)::INT
                WHEN 0 THEN 'my'
                WHEN 1 THEN 'your'
                WHEN 2 THEN 'his'
                WHEN 3 THEN 'her'
                WHEN 4 THEN 'our'
             END )
        || '.mail' AS email
    FROM generate_series(1, 5) seq              -- Important: Replace N with a useful value
)
SELECT email
FROM query
WHERE email IS NOT NULL;

-- Generate N posts
INSERT INTO posts(user_id, title)
WITH expanded AS (
    SELECT random(), seq, u.id AS user_id
    FROM generate_series(1, 8) seq, users u     -- Important: Replace N with a useful value
),
shuffled AS (
    SELECT e.*
    FROM expanded e
    INNER JOIN (
        SELECT ei.seq, min(ei.random) FROM expanded ei GROUP BY ei.seq
    ) em ON (e.seq = em.seq AND e.random = em.min)
    ORDER BY e.seq
)
-- Top 20 programming languages: https://www.tiobe.com/tiobe-index/
SELECT s.user_id,
    'Let''s talk about (' || s.seq || ') '
    || ( CASE (random() * 19 + 1)::INT
            WHEN 1 THEN 'C'
            WHEN 2 THEN 'Python'
            WHEN 3 THEN 'Java'
            WHEN 4 THEN 'C++'
            WHEN 5 THEN 'C#'
            WHEN 6 THEN 'Visual Basic'
            WHEN 7 THEN 'JavaScript'
            WHEN 8 THEN 'Assembly language'
            WHEN 9 THEN 'PHP'
            WHEN 10 THEN 'SQL'
            WHEN 11 THEN 'Ruby'
            WHEN 12 THEN 'Classic Visual Basic'
            WHEN 13 THEN 'R'
            WHEN 14 THEN 'Groovy'
            WHEN 15 THEN 'MATLAB'
            WHEN 16 THEN 'Go'
            WHEN 17 THEN 'Delphi/Object Pascal'
            WHEN 18 THEN 'Swift'
            WHEN 19 THEN 'Perl'
            WHEN 20 THEN 'Fortran'
        END ) AS title
FROM shuffled s;

-- Generate N comments
-- Note: The cross-join is a performance killer.
--       Try the SELECT without INSERT with small N values to get an estimation of the execution time.
--       With these values you can extrapolate the execution time for a bigger N value.
INSERT INTO comments(user_id, post_id, body)
WITH expanded AS (
    SELECT random(), seq, u.id AS user_id, p.id AS post_id
    FROM generate_series(1, 10) seq, users u, posts p   -- Important: Replace N with a useful value
),
shuffled AS (
    SELECT e.*
    FROM expanded e
        INNER JOIN ( SELECT ei.seq, min(ei.random) FROM expanded ei GROUP BY ei.seq ) em ON (e.seq = em.seq AND e.random = em.min)
    ORDER BY e.seq
)
SELECT s.user_id, s.post_id, 'Here some comment: ' || md5(random()::text) AS body
FROM shuffled s;

Could someone show me how this could be done please, I am new to SQL/postgres any help would be much appreciated. an Example would be very helpful too.

A: Good effort in pasting the whole dataset creation procedure, is what it needs to be included in order to make the example reproducible.
Let's start first with, how to join several tables: you have your posts table which contains the user_id and we can use it to join with users with the following.
SELECT email,
    users.id user_id,
    posts.id post_id,
    title
from posts join users
    on posts.user_id=users.id;

This will list the posts together with the authors. Check the joining condition (after the ON) stating the fields we're using. The result should be similar to the below
      email       | user_id | post_id |                 title
------------------+---------+---------+----------------------------------------
 user_1@her.mail  |       1 |       5 | Let's talk about (5) Visual Basic
 user_1@her.mail  |       1 |       2 | Let's talk about (2) Assembly language
 user_3@her.mail  |       3 |       8 | Let's talk about (8) R
 user_3@her.mail  |       3 |       7 | Let's talk about (7) Perl
 user_4@her.mail  |       4 |       6 | Let's talk about (6) Visual Basic
 user_5@your.mail |       5 |       4 | Let's talk about (4) R
 user_5@your.mail |       5 |       3 | Let's talk about (3) C
 user_5@your.mail |       5 |       1 | Let's talk about (1) Ruby
(8 rows)

Now it's time to join this result, with the comments table. Since a post can have comments or not and you want to show all posts even if you don't have any comments you should use the LEFT OUTER JOIN (more info about join types here
So let's rewrite the above to include comments
SELECT email,
    users.id user_id,
    posts.id post_id,
    title,
    comments.body
from posts
join users
    on posts.user_id=users.id
left outer join comments
    on posts.id = comments.post_id
    ;

Check out the join between posts and comments based on post_id.
The result of the query is the list of posts, related author and comments, similar to the below
      email       | user_id | post_id |                 title                  |                        body
------------------+---------+---------+----------------------------------------+-----------------------------------------------------
 user_1@her.mail  |       1 |       5 | Let's talk about (5) Visual Basic      |
 user_1@her.mail  |       1 |       2 | Let's talk about (2) Assembly language |
 user_3@her.mail  |       3 |       8 | Let's talk about (8) R                 | Here some comment: 200bb07acfbac893aed60e018b47b92b
 user_3@her.mail  |       3 |       8 | Let's talk about (8) R                 | Here some comment: 66159adaed11404b1c88ca23b6a689ef
 user_3@her.mail  |       3 |       8 | Let's talk about (8) R                 | Here some comment: e5cc1f7c10bb6103053bf281d3cadb60
 user_3@her.mail  |       3 |       8 | Let's talk about (8) R                 | Here some comment: 5ae8674c2ef819af0b1a93398efd9418
 user_3@her.mail  |       3 |       7 | Let's talk about (7) Perl              | Here some comment: 5b818da691c1570dcf732ed8f6b718b3
 user_3@her.mail  |       3 |       7 | Let's talk about (7) Perl              | Here some comment: 88a990e9495841f8ed628cdce576a766
 user_4@her.mail  |       4 |       6 | Let's talk about (6) Visual Basic      |
 user_5@your.mail |       5 |       4 | Let's talk about (4) R                 | Here some comment: ed19bb476eb220d6618e224a0ac2910d
 user_5@your.mail |       5 |       3 | Let's talk about (3) C                 | Here some comment: 23cd43836a44aeba47ad212985f210a7
 user_5@your.mail |       5 |       1 | Let's talk about (1) Ruby              | Here some comment: b83999120bd2bb09d71aa0c6c83a05dd
 user_5@your.mail |       5 |       1 | Let's talk about (1) Ruby              | Here some comment: b4895f4e0aa0e0106b5d3834af80275e
(13 rows)

Now you can start aggregating and counting comments for a certain post. You can use PG's aggregation functions, we'll use the COUNT here.
SELECT email,
    users.id user_id,
    posts.id post_id,
    title,
    count(comments.id) nr_comments
from posts
join users
    on posts.user_id=users.id
left outer join comments
    on posts.id = comments.post_id
group by email,
    users.id,
    posts.id,
    title
    ;

Check out that we're counting the comments.id field but we could also perform a count(*) which just counts the rows. Also check that we are grouping our results by email, users.id, post.id and title, the columns we are showing alongside the count.
The result should be similar to
      email       | user_id | post_id |                 title                  | nr_comments
------------------+---------+---------+----------------------------------------+-------------
 user_3@her.mail  |       3 |       7 | Let's talk about (7) Perl              |           2
 user_5@your.mail |       5 |       3 | Let's talk about (3) C                 |           1
 user_5@your.mail |       5 |       1 | Let's talk about (1) Ruby              |           2
 user_3@her.mail  |       3 |       8 | Let's talk about (8) R                 |           4
 user_1@her.mail  |       1 |       5 | Let's talk about (5) Visual Basic      |           0
 user_5@your.mail |       5 |       4 | Let's talk about (4) R                 |           1
 user_4@her.mail  |       4 |       6 | Let's talk about (6) Visual Basic      |           0
 user_1@her.mail  |       1 |       2 | Let's talk about (2) Assembly language |           0
(8 rows)

This should be the result you're looking for. Just bear in mind, that you're showing the user from users who wrote the post, not the one who commented. To view who commented you'll need to change the joining conditions.


text:
Q: Include only jquery slim in webpack build? How do I include only jquery slim in my webpack build?
Right now, I'm including jquery like this and it is working fine, but I don't want to load the entire library..
webpack.config.js
module.exports = {
...
 module: {
  rules: [
   ...
    {
        test: require.resolve('jquery'),
        use: [{
            loader: 'expose-loader',
            options: 'jQuery'
        },
        {
            loader: 'expose-loader',
            options: '$'
         }]
    }
  ]
  ...
  plugins: [
   new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery'
    })
  ]
 }

}

I couldn't find offical jquery-slim package in npm, so I guess the idea is to install the whole jquery package and only use what I want from there, but I wasn't able to find how to do that.

A: jquery-slim.js is shipped within the npm package of jquery.
It's in node_modules/jquery/dist/jquery-slim.js.
So all you need to do is direct the loader and the plugin to the jquery.slim.js path:
module.exports = {
...
 module: {
  rules: [
   ...
    {
        test: require.resolve('jquery/dist/jquery.slim'),
        use: [{
            loader: 'expose-loader',
            options: 'jQuery'
        },
        {
            loader: 'expose-loader',
            options: '$'
         }]
    }
  ]
  ...
  plugins: [
   new webpack.ProvidePlugin({
        $: 'jquery/dist/jquery.slim',
        jQuery: 'jquery/dist/jquery.slim'
    })
  ]
 }

}

A: There is a jquery-slim package in npm but it's not official, so i don't recommend using it.
npm versions of jQuery already included jquery-slim (source code, source maps, and minified versions). When you install it from npm it can be found on
ls node_modules/jquery/dist/jquery.slim.*

I found that the easiest and more secure way to import slim, specially if you don't need jQuery to be a global, is use an alias. In Webpack@4:
resolve: {
    alias: {
        // "jquery/dist/jquery.js" or "jquery/dist/jquery.slim.js"
        jquery: "jquery/dist/jquery.slim.js",
    }
},

In fact I always use the alias, because by accident you can end with two jQuery versions in your bundle if someone is messing up with paths.
For example when using (without an alias)
import $ from "jquery/dist/jquery.slim.js"
import "bootstrap"

Webpack will put both versions in the bundle, because Bootstrap will require just "jquery".
To use the alias nothing special is need:
import $ from "jquery";

Very Roughly speaking. When Webpack tries to import "jquery" module, first will loot at the alias, and if that "name" exists the alias value will be used. If not, it will go to node_modules/jquery, read the main property of the package.json that points out to dist/jquery.js and puts that file/module in the $ name.
The alias are used (afaik) always before other method resolution, so you can use it with the ProvidePlugin or exposes-loader.
By the way:

*

*For many cases you don't need special configuration for libraries depending on jQuery. Nowadays, most of then, like Bootstrap, will work out of the box

*I don't think that use exposes-loader at the same time that ProvidePlugin is need, or even that is a good idea.

expose-loader, expose the module as global variable. So each time "$" or name exposed is not found in the local context, it will be searched at the global context(window) in the browser.
ProvidePlugin, "cheats" or "fakes" the libraries. Each time "$" is not found in the context, Webpack will replace it with (something like) require("jquery"). This does not expose the variable as global but will work for most of the cases.
As previously said, ProvidePlugin will use the alias, so this config will use de js file specified in the alias.
plugins: [
    new webpack.ProvidePlugin({
        // use all aliases or only what you need.
        "$": "jquery",
        "jQuery": "jquery",
        "window.$": "jquery",
    }),
]

If you don't want to use expose-loader, but need jQuery as global doing it in your own code in the "entry script" is also fine:
import $ from "jquery";

window.$ = window.jQuery = $;


text:
Q: How many real, rational and complex solutions has this system of equations? Let the system $\left\{\begin{aligned}
      a+b+c &= 3\\
     a^2+b^2+c^2 &=5\\
a^3+b^3+c^3 & =12
    \end{aligned}\right. $
How many real, rational and complex solutions has it?
I read System of three variables of simultaneous equations and found $ e_1 = 3, e_2 = 2, e_3 = 1 $. Then I do not understand the reason but I get the polynomial $ t ^ 3-3t ^ 2 + 2t-1 $. The question is how many , not what are the solutions, so at this point I do not know what to do ...  or if I'm in the right way.  Can you help me please?

A: It has 6 solutions
Here they are
$$a_1 = 2.32472$$
$$b_1 = 0.56228·i+0.337641$$
$$c_1 = 0.337641−0.56228·i$$
$$a_2 = 2.32472$$
$$b_ 2= 0.337641−0.56228·i$$
$$c_2 = 0.56228·i+0.337641$$
$$a_3 = 0.337641−0.56228·i$$
$$b_3 = 0.56228·i+0.337641$$
$$c_3 = 5.118e−18·i+2.32472$$
$$a_4 = 0.337641−0.56228·i$$
$$b_4 = 1.11022e−16·i+2.32472$$
$$c_4 = 0.56228·i+0.337641$$
$$a_5 = 0.56228·i+0.337641$$
$$b_5 = 0.337641−0.56228·i$$
$$c_5 = 1.69412e−18·i+2.32472$$

A: Note
$$ 3^2=(a+b+c)^2=a^2+b^2+c^2+2ab+2bc+2ca=5+2(ab+bc+ca). $$
from this, one has
$$ ab+bc+ca=2. $$
Also
\begin{eqnarray}
3^3&=&(a+b+c)^3=a^3+b^3+c^3+3a^2b+3ab^2+3a^2c+3ac^2+3b^2c+3bc^2+6abc\\
&=&12+3ab(a+b+c)+3bc(a+b+c)+3ca(a+b+c)-3abc\\
&=&12+3(ab+bc+ca)(a+b+c)-3abc\\
&=&30-3abc
\end{eqnarray}
from which, one has
$$ abc=1. $$
Thus $a,b$ and $c$ are the roots of the following equation
$$ t^3-3t^2+2t-1=0. \tag{1} $$
So the coefficients of (1) are
$$ a_3=1,a_2=-3,a_1=2,a_0=-1 $$
and hence the discriminant is
$$ \Delta=18a_3a_2a_1a_0-4a_2^3a_0+a_2^2a_1^2-4a_3a_1^3-27a_3^2a_0^2=-23<0$$
and hence (1) has one real root and two complex roots.


text:
Q: Form condition from table without dynamic SQL Get the license details that are going to expire before the given days of interval. There are two tables, one is the 'Licenses' which holds the licenses details and expiration date. Another table is 'IntervalDays' which holds the days.

We could write  the query as below if we hardcode the interval days, BUt how could we use the other table for where conditions. Note: we shouldn't use dynamic sql for the performance considertion, Appreciate it if somebody could help here at the earliest.
SELECT LicenceId
           FROM Licences lic
           WHERE  (CONVERT(DATE, vip.ExpirationDate) = CONVERT(DATE, DATEADD(Day, 30, GETDATE()))
                      OR CONVERT(DATE, vip.ExpirationDate) = CONVERT(DATE, DATEADD(Day, 15, GETDATE()))
                      OR CONVERT(DATE, vip.ExpirationDate) = CONVERT(DATE, DATEADD(Day, 7, GETDATE()))
                      OR CONVERT(DATE, vip.ExpirationDate) = CONVERT(DATE, DATEADD(Day, 3, GETDATE()))
                      OR CONVERT(DATE, vip.ExpirationDate) = CONVERT(DATE, DATEADD(Day, 2, GETDATE()))
                      OR CONVERT(DATE, vip.ExpirationDate) = CONVERT(DATE, DATEADD(Day, 1, GETDATE())))

A: Will this work for you?
    SELECT LicenceId
       FROM Licences lic
       WHERE CONVERT(DATE, vip.ExpirationDate) IN (SELECT CONVERT(DATE, DATEADD(Day, [day], GETDATE())) FROM IntervalDays)


text:
Q: construct url dynamically (name view as argument) with name space url tag in Django template In a Django template, I want to construct dynamically urls
I try to concatenate (see below) but got an error :
Could not parse the remainder: '+key+'_index'' from ''ecrf:'+key+'_index''

{% for key, values in forms.items %}

   {{ key|capfirst }}

{% endfor %}

urls
app_name='ecrf'
urlpatterns = [
    path('inclusion/create/', views.InclusionCreate.as_view(), name='inclusion_create'),

expected result:
Inclusion

A: You can use the add template tag[Django docs] to add strings together:
{% for key, values in forms.items %}

   {{ key|capfirst }}
{% endfor %}

But this feels a bit hacky to me, perhaps your forms dictionary can be restructured so that such logic is done in the view itself? For example the dictionary can be:
{'inclusion': {'value': <some_value>, 'create_url': 'ecrf:inclusion_create'}}

And in your template your loop would be:
{% for key, values in forms.items %}

   {{ key|capfirst }}
{% endfor %}


text:
Q: Jquery — Regex a URL slug into a capitalized sentence? Hi there
I'm trying to figure out how to convert

this-is-my-slug

to:

This Is My Slug

in Jquery?!
I know PHP is awesome with this, but jQuery maybe not?

A: This should do it for you: (This was a simple previous example)
var str = "this-is-my-slug";
str = str.toLowerCase().replace(/-/,' ').replace(/\b[a-z]/g, convert);
    function convert() {
          return arguments[0].toUpperCase();
    }

Here it is in function form - the entire word and single word conversions:
   //Converts and Formats entire string
   function Convert(test)
   {
       var formatted = test.toLowerCase().replace(/-/g,' ');
       var array = test.split(" ");
       var output = "";

       for (i=0;i<array.length;i++)
       {
              output += ConvertString(array[i]);
       }
       return output;
    }

   //Formats individual words
   function ConvertString(string)
   {
       var str = string;
       str = str.toLowerCase().replace(/-/g,' ').replace(/\b[a-z]/g, convert);
       function convert() {
          return arguments[0].toUpperCase();
       }
       return str;
   }

Working Example - Updated

A: Comparing jQuery with PHP isn't a particularly fair comparison but rather than get into that I'll just direct you towards this question. It's doing the opposite operation but you might get some help with your issue from it.

A: OK, this works 100%:
http://jsfiddle.net/Y9WQC/1/
var string = "this-is-a-slug";

convert = string.replace(/-/g," ");

function ucwords (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Waldo Malqui Silva
    // +   bugfixed by: Onno Marsman
    // +   improved by: Robin
    // +      input by: James (http://www.james-bell.co.uk/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: ucwords('kevin van  zonneveld');
    // *     returns 1: 'Kevin Van  Zonneveld'
    // *     example 2: ucwords('HELLO WORLD');
    // *     returns 2: 'HELLO WORLD'
    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
        return $1.toUpperCase();
    });
}
var result = ucwords(convert)
$("div").text(result);

my new string will output here


text:
Q: Extending an S3 generic from an optional package I have a package which provides an as.FlexTable method for its objects, extending the S3 generic from the ReporteRs package. So, my NAMESPACE file, generated by roxygen, has lines:
importFrom(ReporteRs,as.FlexTable)
...
S3method(as.FlexTable,huxtable)
...
export(as.FlexTable)

I don't much want to put ReporteRs in Imports: in the DESCRIPTION file, because it involves a big external dependency on Java. But, when I put it into Suggests:, R CMD check gives me errors like "Namespace dependency not required".
Is there anyway I can extend the generic without making a hard dependency?

A: Importing is a hard dependency.
Some people do not import formally but use  <pkgNamespace>::<obj>
instead, and conditionalize their code on the availability of
that namespace.
I don't recommend that at all, and particularly not for
extending a generic.
I recommend you talk with the maintainer of ReporteRs:

*

*You could use a common (yet-to-create) very small package say flexS3generics
which provides S3 generics (and S4 if ..) you want to use
both, and then both you and her/him import from that mini package.
You'd be both authors of that package.

*If your package is much smaller (in its footprint, incl
dependencies) than 'ReporteRs' she/he may agree to import the
S3 generic from your package instead of the other way around.
Both are clean solutions, and both need some time-coordination when releasing to CRAN,
'1)' being easier: Once the flexS3generics is released to
CRAN, change (both) your package(s) to
importFrom(flexS3generics, as.FlexTable)  but these changes and CRAN
submissions are then independent of each other.
((Taste: I'd strongly prefer as.flexTable  (lowercase "f")))


text:
Q: uri mapping - '/index.php/dashboard' In Apache, I can access php scripts through an uri like /index.php/dashboard,
how can I set nginx to act the same?
Also I can access /index with Apache and it automatically maps to /index.php.
Is this also possible in nginx?
I think something like this is the solution:
map $uri $myvalue {
    /index.php/(.*)    /index.php?$;
}

Or is there a solution w/o rewrite?
Update, current config:
server {
        listen   80;
        charset utf-8;
        root /www/public;
        index index.php index.html index.htm;
        access_log  /www/log/access.log;
        error_page 404 /www/public/http-404.php;
        server_name rasp;

        location /doc/ {
                alias /usr/share/doc/;
                autoindex on;
                allow 127.0.0.1;
                allow ::1;
                deny all;
        }

        location ~ /\.ht {
                deny all;
        }

        location / {
                autoindex on;
                try_files $uri $uri/ $uri.php /;
        }

        location /dev/ {
                auth_basic "dev";
                auth_basic_user_file /www/config/global.passwd;
                location ~ \.php$ {
                    fastcgi_split_path_info ^(.+\.php)(/.+)$;
                    fastcgi_pass unix:/var/run/php5-fpm.sock;
                    fastcgi_index index.php;
                    include fastcgi_params;
                }
        }

        location ~ \.php$ {
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                include fastcgi_params;
        }
}

A: I am not sure if there are any security issues with this its what i use in my testing enviorment
if (!-e $request_filename)
{
    rewrite ^/(.*)$ /index.php?/$1 last;
    break;
}

location ~ \.php    {
        include fastcgi_params;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME /path/to/index.php;
        fastcgi_index index.php;
        fastcgi_param DOCUMENT_ROOT /path/to;
    }


text:
Q: Does Ubuntu 20.04/10 support Wayland with Nvidia proprietary driver? I installed Pop OS 20.04 nVidia version (based on Ubuntu 20.04), and Wayland did not seem to work because I could not set different scalings on different monitors (like 100% for monitor1, and 200% for monitor2).
Next, I installed Ubuntu 20.10 and installed the latest proprietary nVidia driver. I still could not set different scaling. At the login screen, I did not see the small menu to choose between X11 and Wayland, so I searched Google and installed things related to Wayland and set the EnableWayland=true in the config file. Now I see the small menu to choose the session type at the login screen, but the selected was Ubuntu, and the other item was "Gnome on Xorg". Isn't that X11?
I rebooted the PC to make it sure, and I chose the "Ubuntu" session. Yet, when I checked the session type, it was "X11". Did I do something wrong, or is this because Wayland is not supported with the proprietary nVidia driver, due to the frame buffer or memory support issue?


text:
Q: JQuery select element with special characters in Id I have this HTML where the Id contains special charaters:
<input type="text" id="e09b989c-7201-4b7e-8fd4-a2309db6d356|b5d9746a-7f7c-432d-a4ef-a5e0011d989d|IssueDate" name="e09b989c-7201-4b7e-8fd4-a2309db6d356|b5d9746a-7f7c-432d-a4ef-a5e0011d989d|IssueDate" value="">
<input type="hidden" id="Type_e09b989c-7201-4b7e-8fd4-a2309db6d356|b5d9746a-7f7c-432d-a4ef-a5e0011d989d|IssueDate" name="Type_e09b989c-7201-4b7e-8fd4-a2309db6d356|b5d9746a-7f7c-432d-a4ef-a5e0011d989d|IssueDate" value="date">
<br>
<input type="text" id="1c36b33a-85d8-4811-93f6-a5e000ad985c|b795c0b4-1c8b-4d9e-95c5-a5e0011d8505|FromDate(mm/dd/yyyy)" name="1c36b33a-85d8-4811-93f6-a5e000ad985c|b795c0b4-1c8b-4d9e-95c5-a5e0011d8505|FromDate(mm/dd/yyyy)" value="" class="">
<input type="hidden" id="Type_1c36b33a-85d8-4811-93f6-a5e000ad985c|b795c0b4-1c8b-4d9e-95c5-a5e0011d8505|FromDate(mm/dd/yyyy)" name="Type_1c36b33a-85d8-4811-93f6-a5e000ad985c|b795c0b4-1c8b-4d9e-95c5-a5e0011d8505|FromDate(mm/dd/yyyy)" value="DateTime">

And i am using this JQuery to update them:
 $("input[id^='Type_']").each(function () {
        if ($(this).val() == "date" || $(this).val() == "DateTime") {
        console.log($(this).attr('id'));
            var id = $(this).attr('id').replace("Type_", "").replace(/\|/g, "\\|").replace(/\//g, "\\\\\/").replace(/\)/g, "\\\\\)").replace(/\(/g, "\\\\\(");

           console.log(id);
           console.log(">>" + $("#" + id));

            $("#" + id).val(id);
        }
    });

But the second Id which contains "|" and "(" is not selected.
I am testing here: http://jsfiddle.net/MWadX/446/
Can somebody help me?
Thanks.

A: The problem is how you are escaping the special characters,
var id = this.id.replace(/[|\(\)#\\\/]/g, '\\$&');

Demo: Fiddle

A:             $("input[id^='Type_']").each(function() {
                if ($(this).val() == "date" || $(this).val() == "DateTime") {
                    var tempID = $(this).attr('id');
                    var temp_ID1 = this.id.replace(/[|\(\)#\\\/]/g, '\\$&');
                    console.log(temp_ID1);
                    console.log("#" + temp_ID1);
                }
            });


text:
Q: How to deal with the error of adb connect? I can connect with adb connect before. But after I restart computer and connect again it has the error:

There is no adb server in task manager. So it is no use with adb kill-server. I did not connect usb and can not restart adb.
Is there other solution except restart computer?

A: Your USB is not connected so i can assume, you are trying to connect it over wifi.
1) For connecting your device over wifi, your android device needs to be rooted
2) Download emulator for your android device from the play store.
3) Write below code in emulator.
su
setprop service.adb.tcp.port 5555
stop adbd
start adbd

4) Now open your Terminal and try to connect it again. It should work like a charm. But make sure that given IP address is correct for your android device.
If still problem persist , you can try this.
There are many third party apps on the play store which will be useful to have a look.
Ex. adbWireless , WiFi ADB


text:
Q: reduce code duplication in c++ Can I reduce the following code to one function? the most part of them are the same. Thanks
void info(StreamLog &streamLog)
{
    streamLog.ss << "info:";
    streamLog.mFilter->setLogLevel("info");
}
void debug(StreamLog &streamLog)
{
    streamLog.ss << "debug:";
    streamLog.mFilter->setLogLevel("debug");
}
void warning(StreamLog &streamLog)
{
    streamLog.ss << "warning:";
    streamLog.mFilter->setLogLevel("warning");
}
void error(StreamLog &streamLog)
{
    streamLog.ss << "error:";
    streamLog.mFilter->setLogLevel("error");
}
void critical(StreamLog &streamLog)
{
    streamLog.ss << "critical:";
    streamLog.mFilter->setLogLevel("critical");
}

if you need more info,let me know
1st edited:
sorry !  I didnt explain my situation clearly.   I use those function as manipulator. therefore, i can do
clog << info << ...
clog << warning<<...
I dont want to use
clog << log(info) <<...
any better way? thanks

A: I'm with @Rémi Benoit, though to provide you with an alternative, you can use an enum and a map:
enum log_level {
   info, debug, warning, error, critical
}

void log(StreamLog& streamLog, log_level level) {
   static const std::map<log_level, std::string> levels = {
       { info, "info" }, { debug, "debug" }, { warning, "warning" },
       { error, "error" }, { critical, "critical" }
   };

   auto iter = levels.find(level);
   if(iter == levels.end()) return;

   streamLog.ss << iter->second;
   streamLog.mFilter->setLogLevel(iter->second);
}

The benefit of this is that your log level is limited only to what is in the enum (and the map), though if you do not require this constraint, it is better to use @Rémi's solution.

A: void log(StreamLog &streamLog, const string& level)
{
    streamLog.ss << level << ":";
    streamLog.mFilter->setLogLevel(level);
}

Always try to see the common operation and abstract it in a different function.

A: Here is an alternative to Mark's & Rémi's solutions using templates. This solution could be useful in areas where high performance is critical. The templates let the compiler bake in a lot of information into each templated function already so there should be a smaller run time cost especially when compared to the map lookup method.
Additionally this will constrain the values for the log_level being used at compile time rather than at run time.
enum class log_level { info, debug, warning, error, critical };
template<log_level> struct log_helper{ static const char* const text; };

template<> const char* const log_helper<log_level::info>::text = "info";
template<> const char* const log_helper<log_level::debug>::text = "debug";
template<> const char* const log_helper<log_level::warning>::text = "warning";
template<> const char* const log_helper<log_level::error>::text = "error";
template<> const char* const log_helper<log_level::critical>::text = "critical";

template<log_level level> void set_log_level(StreamLog& streamLog)
{
    streamLog.ss<< log_helper<level>::text << ":";
    streamLog.mFilter->setLogLevel(log_helper<level>::text);
}


text:
Q: How to make an h bridge using only comparators I discovered I could easily make an H-bridge (or something that effectively behaved as one) by cross coupling the inputs of two op amps. So for op amps 1 and 2, 1+ is connected to 2- and 1- is connected to 2+. This worked great, but since I am not really amplifying a signal so much as comparing them, this seemed like a better job for comparators. However, when I tried the same thing with comparators, it did not work. After studying comparators a bit, I realized the problem had to do with the fact that a comparator's output cannot not reverse polarity like an op amp, but can only act as a switch. I get the feeling I would need four comparators for this to work, but I could use some help. Since I am using them in an odd way, the recourses online did hot help much.
My comparator is LM2903P. My op amp is TL082.
Here is the circuit I am using:

It is being used as a multivibrator. I would like to be able to get higher frequencies, so being able to use comparators would be useful.

A: Ideally comparators CAN switch output polarity.
Most real world ones can too.
If yours can't you may be using open collector / open drain ones like an LM393 or its cousin.
As usual, you need to supply a circuit diagram and par number to have best chance of people understanding what you are really doing.

A: comparators are poor choices for totem pole cascode H mode drivers.
You have to manage the transition times so that you dont end up shorting out the V+ to ground or create a deadtime or break before make. Unfortunately open collector drivers such as the IC you chose have fast ON times but relative slower OFF times controlled by pullup current and junction capacitance.
The best H bridge drivers use MOSFETs and even then it only looks trivial, but you could  make something work with 4 NAND gates if you wanted and make sure you  use the 2nd gate input to control the dead time of the H bridge drivers.
Remember to decide what you want to switch, over what range of power and voltage and temperature and ensure it works for worst case conditions.
;)When in doubt put in PTC polyfuses.;) My son in-law, EE Prof @ U of T says his students blow bridge drivers all the time... !!! ha  ( not cheap when they are 10KW drivers)


text:
Q: How do I make a Silverlight popup with a TextBox fill its parent? I have a popup within a user control.  The popup uses a TextBox to show a textual preview of data produced by the control.
How do I make the popup size itself to the user control it's inside of?  With code as shown below, I find that the text box is sized according to its content, and the popup is sized according to the textbox.
It works fine if I use fixed sizes in my row and column definitions, but I would like to popup to resize itself to match the user control (which in turn matches the browser).
<UserControl
  <!-- usual stuff here -->
>
<Grid>

<!-- layout for the user control here -->
<!-- and after that my popup: -->
<Popup Name="MyPopup">
   <Border BorderBrush="Black" BorderThickness="2" >
      <Grid>
         <Grid.RowDefinitions>
            <RowDefinition Height="22"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
         </Grid.RowDefinitions>
         <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
         </Grid.ColumnDefinitions>

         <TextBlock Grid.Row="0" Text="Preview:" Margin="5" ></TextBlock>
         <TextBox
              Grid.Row="1"
              Name="MyTextBox"
              IsReadOnly="True"
              HorizontalScrollBarVisibility="Visible"
              VerticalScrollBarVisibility="Visible"
              TextWrapping="Wrap"
              Margin="5"
              >
          </TextBox>
      </Grid>
  </Border>
</Popup>

</Grid></UserControl>

A: The C# code to do this would be something like:
    textBox1.Width = UserControl.Width;
    textBox1.Height = UserControl.Height;
    textBox1.Margin = UserControl.Margin;

The key here is resetting the margin. I know this works in WPF to, say, fill a Window with a TextBox. Give it a try, see if it works.


text:
Q: implement canvas android I am trying to implement the canvas feature in ios for android. The ios canvas has a property known as drawChildren that is basically an array that manages drawing objects that can be added/removed by the canvas controller.
Is there a way anyone can help me achieve this feat? I am aware that the Canvas class should be used however, I am not sure how to arrange it in as array.

A: I don't know if this will work for you, or if you solved this but I made this approach:
Activity.class
//Create an activity to hold everything
public class GameActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);
        Rel_main_game = (RelativeLayout) findViewById(R.id.rlt_main);
        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        final int heightS = dm.heightPixels;
        final int widthS = dm.widthPixels;
//this is the SurfaceView that will do the magic
        game_panel = new GamePanel(getApplicationContext(),this,widthS, heightS);
        Rel_main_game.addView(game_panel);

}

SurfaceView
public class GamePanel extends SurfaceView implements SurfaceHolder.Callback {

    public MainThread thread;
    public int ScreenWidth;
    public int Screenheigt;
    public GameActivity game;

    public GamePanel(Context context, GameActivity game,  int width , int height) {
        super(context);
        getHolder().addCallback(this);
        this.game = game;
        this.ScreenWidth=width;
        this.Screenheigt=height;
        thread = new MainThread(getHolder(),this);
        ship = new Ship(BitmapFactory.decodeResource(getResources(), R.drawable.player), 100, 0, ScreenWidth, Screenheigt);

    }

void Draw(Canvas canvas){
        if (canvas!=null)
        {
         ship.draw(canvas);
        }
    }

    void Update(float dt){
        ship.udpdate(dt);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        thread.setRunning(true);
        thread.start();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        boolean retry = true;
        while (retry)
        {
            try
            {
                thread.join();
                retry=false;
            }
            catch (InterruptedException e)
            {
            }
        }
    }
}

and you add children classes that have draw and update methods:
public class Ship {

    public Bitmap bitmap;
    public int x;
    private int y;
    private int Speed;
    private int inc;
    private int ScreenWidth;
    private int ScreenHeight;
    public int direction=0;
    boolean death;
    float animTime=0;
    float totalAnimTime = 1;
    float numFrames;

    public Ship(Bitmap decodeResource, int x, int y, int screenWidth, int screenheight) {
        this.bitmap = decodeResource;
        this.x =screenWidth/2 - bitmap.getWidth()/2;
        this.y = screenheight - bitmap.getHeight();
        Speed=1;
        inc=0;
        death=false;
        ScreenWidth =screenWidth;
        ScreenHeight =screenheight;
    }

    public void draw(Canvas canvas){
        if (!death)
        {
            canvas.drawBitmap(bitmap, x, y - bitmap.getHeight() / 2, null);
        }
    }

    public void update(float dt){
        if (death)
        {
            animTime += dt;
        }
        else
        {
            float movement =ScreenWidth/2*dt;
            if (x - (bitmap.getWidth()/ 2)<ScreenWidth || x > - bitmap.getWidth()/ 2)
            switch(direction)
            {
                case(1):
                {
                    x+=8;//movement*dt;
                    break;
                }
                case(2):
                {
                    x-=8;//movement*dt;
                    break;
                }
            }
            }
    }

and so on.


text:
Q: How do I force an activity to use the intent extras I pass it? I have a stack of activities, and use the following code to bring the main activity to the 'active' state:
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getBaseContext().getPackageName());
i.putExtra("clearCache", true);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);

The problem is that when I try to retrieve the clearCache extra, a call to getIntent().getExtras() returns null.
My understanding is that because the activity that I'm launching was already on the stack, and because I set the Intent.FLAG_ACTIVITY_CLEAR_TOP flag, the Intent that gets returned will be the original intent.
How do I access the calling intent in the activity I'm launching?

A: In the google documentation on FLAG_ACTIVITY_CLEAR_TOP, you should be getting the new intent each time:
"If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent."
...
"The currently running instance of activity B in the above example will either receive the new intent you are starting here in its onNewIntent() method, or be itself finished and restarted with the new intent. If it has declared its launch mode to be "multiple" (the default) and you have not set FLAG_ACTIVITY_SINGLE_TOP in the same intent, then it will be finished and re-created; for all other launch modes or if FLAG_ACTIVITY_SINGLE_TOP is set then this Intent will be delivered to the current instance's onNewIntent()."
For more details take a look here:
http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP
Hope that helps!

A: You just change your code by passing the particular Activity name and keep the rest of code as it is,
Intent i = new Intent(MapActivity.this, MainActivity.class);
                        i.putExtra("clearCache", true);
                        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(i);


text:
Q: Step after doing feature selection with cross validation I have been searching for articles on feature selection and cross-validation, but could not find enough answer to my specific question. I am currently working on an in-house feature selection pipeline for resting-state fMRI data. I use nested CV structure so that I do feature selection in the inner fold.  My pipeline is as follows:
for each fold in outer fold
  for each fold in inner fold
    run f-test on train data.
    rank features according to their f-scores.
    apply k-best algorithm with different *k* values (previously sampled from uniform random distribution)
    fit model on train data with k-best features, and test on test data.
  return CV score for each *k* values.
  ?????
end

As you see above, my pipeline basically consists of optimizing k parameter in the k-best feature selection. My question is what to do after feature selection. I have two strategies on that (but I am open for any useful and efficient ideas), which are:
1) Following feature selection, I fit the model on train data in the outer fold with k-best features, which are selected in the inner CV fold.
2) Let's say the first 100 features are found to be the best features with the highest CV score. However, as I rank features by their f-scores, different CV folds may give different features found in the first 100 features. So, to get the best features with a high possibility to have useful information, I take union of features and fit the model on train data in the outer fold with those features.
I am not sure which strategy is better.

A: Let's first sort things a bit:
train_k_features = function (train, k){
    run f-test on train data.
    rank features according to their f-scores.
    apply k-best algorithm with different *k* values (previously sampled from uniform random distribution)
    fit model on train data with k-best features, and test on test data.

    return model
}

with that, the inner cross validation becomes more concise:
for each fold in outer fold

  for each fold in inner fold
      for each k in your range of *k*
          model = train_k_features (inner train, k)
  return CV score for all *k* values.

  select best k
  outer_model = train_k_features (outer train, k)

return CV scores for outer models, all ks chosen for the outer models

check whether optimization went well (is k stable across the outer CV models?)

fit final model

Inside the outer CV you're now fitting models with automated selection of the optimal k.
We can put the innards of the outer cross validation into a function again:
train_tuned_model = function (data)
  generate inner folds: splits data -> inner train, inner test

  for each fold in inner fold
      for each k in your *k*
          model = train_k_features (inner train, k)
  return CV score for all *k* values.

  select best k

  return train_k_features (data, k)

with that the outer cross validation becomes:
for each fold in outer fold

  outer_model = train_tuned_model (outer train)

return CV scores for outer models and all ks chosen for the outer models

check whether optimization went well (is k stable across the outer CV models?)

final_model = train_tuned_model (data)


text:
Q: door opens vs door opening I was watching a show and when a door opens, the next subtitle comes out.

Door opens

Using Present Simple shouldn't you use present Continuous?

Door opening

A: Present simple is used in the following cases:
1- to describe habits, routines and facts.
2- to talk about a schedules future event
3- To tell stories (particularly jokes) to make your listener or reader feel more engaged with the story.
I guess your question pertains to the 3rd use. sometimes we use present simple to engage the listener or the reader in what's going on in a scene or a story.

The man hears a crawling noise from downstairs, at first he thinks perhaps it's a mouse or something but the noise keeps getting stronger and closer to his bedroom door, suddenly the door opens and ...

in this extract from a story every event is described using simple present, we could use past simple, but that wouldn't engage the speaker as much.
we also use this "trick" (if you can call it that) in daily conversations we have, suppose you're telling your buddy about a time your car broke down and left you in the middle of nowhere, your description of the event would sound something like this,

My father-in-law and I were driving to his cabin for hunting, we're driving down this bumpy path, when the car suddenly starts making a weird noise. we stop and pop up the hood to see what's wrong. it turns out the there's something wrong with the engine ....

to make a long story short, when we're describing some event in the past, in order to engage the listener or the reader we substitute present simple for past simple and present continuous for past continuous.
so "the door opens" actually means "the door opened". present continuous is not used because in the "original sentences" past continuous was not used. Does it make sense?


text:
Q: Несколько autotools проектов в одном Возможно ли написать Makefile.am или configure.ac, который будет "корневым".
Имеется следующая иерархия, необходимо сборать все проекты, но желательно делать это с помощью autoconf или automake
root
root/proj1
root/proj2
root/proj3


text:
Q: Populate Select Box from XML using jQuery I've seen several examples here on how to do this and have successfully implemented others that use attributes. This time I'm given XML without attributes and i'm trying to figure out how to populate my select list from the node values instead of attributes. I keep getting objects returned instead of text. What am I doing wrong here?
code:
var code_data;
$.get('Book.xml', function (data) {
    code_data = data;
    var that = $('#BookDropdown');
    $('Book', code_data).each(function () {
        $('<option />', {
            text: $('BookName').val('label'),
            value: $('BookID').val('value')
        }).appendTo(that);
    });
}, 'xml');

XML:
<BookList>
  <Book>
    <BookName>Book One</BookName>
    <BookID>1</BookID>
  </Book>
  <Book>
    <BookName>Book Two</BookName>
    <BookID>2</BookID>
  </Book>
  <Book>
    <BookName>Book Three</BookName>
    <BookID>3</BookID>
  </Book>
  <Book>
    <BookName>Book Four</BookName>
    <BookID>4</BookID>
  </Book>
  <Book>
    <BookName>Book Five</BookName>
    <BookID>5</BookID>
  </Book>
</BookList>

A: The way you are accessing BookName and BookID is wrong. . .use following code instead.
`
var code_data;
  $.get('Book.xml', function(data) {
    code_data = data;
    var that = $('#BookDropdown');
    $('Book', code_data).each(function() {
      $('<option />', {
        text: $('BookName',this).text(),
        value: $('BookID',this).text()
      }).appendTo(that);
    });
  }, 'xml');

`


text:
Q: Mouse hover over submenu item does not expand menu until I leave and re-enter item In gnome, whenever I click on a contextual menu item (eg. right click on a window in the task bar) and then hover over a sub-item (eg. Move to another workspace) that is expandable, the submenu is not shown.
In order to show the submenu, I have to click about 4 times with my left mouse button OR leave the item again and re-hover the item with my mouse.
Why does the submenu item not expand automatically on the initial mouse-over (hover)?
Update: this is a pretty fresh install without any special interface software, just the default gnome installation. Ubuntu 10.10 with latest updates.
Also, this problem has been here since I installed Ubuntu a couple of months ago (the reason it is still a fresh install is because I rarely use Ubuntu, because of bugs like these).
Update:
My visual effects were on "normal". I then set them to "none", and now this issue has been resolved.

A: *

*This could depend on your chosen theme. I've read a while ago, that someone had the same problems with the clearlooks-engine. He had chosen another theme and the problems were gone.

*You can try to disable "Mouse Position Polling" in compiz.
Install CompizConfig Settings Manager:
sudo aptitude install compizconfig-settings-manager

Then goto System/Preferences an chose "Advanced Desktop Effects Settings" (i'm not sure if it is still called this way, because i use ubuntu in german) and disable Mouse Position Polling:


text:
Q: Contraction of tensors in chart (xCoba) I have to do some calculations on modified gravity in xAct. The question is how to construct tensors, made of other tensors with contraction in particular chart. Without chart it can be done with IndexSet function, but it doesn't work, when chart is specified. For example, here my trial of calculation for FRW metric:
<< xAct`xTensor`
<< xAct`xTras`
<< xAct`xCoba`

DefManifold[M, 4, {a,b,c,d,e,f,h,i,j,k,l,m,n}]

DefChart[ch, M, {0, 1, 2, 3}, {t[], x[], y[], z[]}, ChartColor -> Green]

DefScalarFunction[a]

MatrixForm[ met = DiagonalMatrix[{1, -a[t[]]^2, -a[t[]]^2, -a[t[]]^2}], {-ch, -ch}]

g = CTensor[met, {-ch, -ch}]

SetCMetric[g, -ch]

CD = CovDOfMetric[g]

MetricCompute[g, ch, All]

IndexSet[QQ, g[a, b] (Christoffel[CD,PDch][c, d, -b] Christoffel[CD,PDch][d, -a, -c] - delta[c, -e] Christoffel[CD,PDch][e, -d, -c] Christoffel[CD,PDch][d, -a, -b])]

And here I get an error:
MetricsOfVBundle: There is no metric in TM.
Throw: Uncaught Throw[Null] returned to top level.
All I want is just calculate the following object in FRW chart:
$g^{\nu \beta}(\Gamma{^\rho_{\gamma \beta}}\Gamma{^\gamma_{\nu \rho}} - \Gamma{^\rho_{\gamma \rho}}\Gamma{^\gamma_{\nu \beta}})$
So, how can I do it?