问:
The specified child already has a parent. What am I missing
Hi I'm fairly new to android studio and I'm building an app for my school project.
I have an array list of ImageButtons that is generated and I need to assign them into rows in my TableView to make it look like a periodic table. However I keep receiving this error:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{ros_dhhiggins.example.com.periodictable/ros_dhhiggins.example.com.periodictable.PeriodicTableScreen}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                                                Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
                                                                                at android.view.ViewGroup.addViewInner(ViewGroup.java:3936)
                                                                                at android.view.ViewGroup.addView(ViewGroup.java:3786)
                                                                                at android.view.ViewGroup.addView(ViewGroup.java:3727)
                                                                                at android.view.ViewGroup.addView(ViewGroup.java:3700)
                                                                                at ros_dhhiggins.example.com.periodictable.PeriodicTableScreen.tableGen(PeriodicTableScreen.java:46)
                                                                                at ros_dhhiggins.example.com.periodictable.PeriodicTableScreen.onCreate(PeriodicTableScreen.java:18)
                                                                                at android.app.Activity.performCreate(Activity.java:5990)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</code>```

This is the Code for the Activity this is happening in:

```<code>package ros_dhhiggins.example.com.periodictable;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TableLayout;
import android.widget.TableRow;
public class PeriodicTableScreen extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_periodic_table_screen);
    TableLayout table = (TableLayout) findViewById(R.id.LayoutTable);
    createButtons newButtons = new createButtons(this);
    tableGen(table, newButtons);
}

public void tableGen(TableLayout table, createButtons newButtons) {
    ImageButton[] imageButtons;
    imageButtons = newButtons.build();
    for(int j = 1; j <= 7; j++){
            TableRow tempRow = new TableRow(this);
        if(j==1) {
            tempRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                    TableRow.LayoutParams.WRAP_CONTENT));

            for (int temp = 0; temp <= 17; temp++) {
                ImageButton tempButton = imageButtons[temp];
                tempButton.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                        TableRow.LayoutParams.WRAP_CONTENT));
                tempRow.addView(imageButtons[temp]);
            }
        }
        else if (j==2){
                for(int temp = 18; temp <=35; temp++){
                    TableRow rowOne = new TableRow(this);
                    rowOne.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                            TableRow.LayoutParams.WRAP_CONTENT));
                    ImageButton tempButton = imageButtons[temp];
                    tempButton.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                            TableRow.LayoutParams.WRAP_CONTENT));
                    tempRow.addView(imageButtons[temp-1]);
                }
        }
        else if (j==3){
            TableRow rowOne = new TableRow(this);
            rowOne.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                    TableRow.LayoutParams.WRAP_CONTENT));
                for(int temp = 36; temp <=53; temp++){
                    ImageButton tempButton = imageButtons[temp];
                    tempButton.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                            TableRow.LayoutParams.WRAP_CONTENT));
                    tempRow.addView(imageButtons[temp-1]);
                }
        }
        else if (j==4){
            TableRow rowOne = new TableRow(this);
            rowOne.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                    TableRow.LayoutParams.WRAP_CONTENT));
                for(int temp = 54; temp <=71; temp++){
                    ImageButton tempButton = imageButtons[temp];
                    tempButton.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                            TableRow.LayoutParams.WRAP_CONTENT));
                    tempRow.addView(imageButtons[temp-1]);
                }
        }
        else if (j==5){
            TableRow rowOne = new TableRow(this);
            rowOne.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                    TableRow.LayoutParams.WRAP_CONTENT));
                for(int temp = 72; temp <=89; temp++){
                    ImageButton tempButton = imageButtons[temp];
                    tempButton.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                            TableRow.LayoutParams.WRAP_CONTENT));
                    tempRow.addView(imageButtons[temp-1]);
                }
        }
        else if (j==6){

                for(int temp = 90; temp <=107; temp++){
                    ImageButton tempButton = imageButtons[temp];
                    tempButton.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                            TableRow.LayoutParams.WRAP_CONTENT));
                    tempRow.addView(imageButtons[temp-1]);
                }
        }
        else if (j==7){
                for(int temp = 108; temp <=125; temp++){
                    ImageButton tempButton = imageButtons[temp];
                    tempButton.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                            TableRow.LayoutParams.WRAP_CONTENT));
                    tempRow.addView(imageButtons[temp-1]);
                }
        }
        table.addView(tempRow, new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
                TableLayout.LayoutParams.WRAP_CONTENT));
        ((ViewGroup) tempRow.getParent()).removeView(tempRow);
    }
   }
}
</code>```

If there is any other info that would be useful let me know, thanks!

答:
Your issue might be because of following lines:

```<code>TableRow rowOne = new TableRow(this);
            rowOne.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                    TableRow.LayoutParams.WRAP_CONTENT));
</code>```

You are creating it repeatedly. You are not even using it. Try removing above lines from your loop and check. Let me know if you still face any problem.

Body:
Hi I'm fairly new to android studio and I'm building an app for my school project.
I have an array list of ImageButtons that is generated and I need to assign them into rows in my TableView to make it look like a periodic table. However I keep receiving this error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{ros_dhhiggins.example.com.periodictable/ros_dhhiggins.example.com.periodictable.PeriodicTableScreen}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                                                Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
                                                                                at android.view.ViewGroup.addViewInner(ViewGroup.java:3936)
                                                                                at android.view.ViewGroup.addView(ViewGroup.java:3786)
                                                                                at android.view.ViewGroup.addView(ViewGroup.java:3727)
                                                                                at android.view.ViewGroup.addView(ViewGroup.java:3700)
                                                                                at ros_dhhiggins.example.com.periodictable.PeriodicTableScreen.tableGen(PeriodicTableScreen.java:46)
                                                                                at ros_dhhiggins.example.com.periodictable.PeriodicTableScreen.onCreate(PeriodicTableScreen.java:18)
                                                                                at android.app.Activity.performCreate(Activity.java:5990)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

This is the Code for the Activity this is happening in:

package ros_dhhiggins.example.com.periodictable;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TableLayout;
import android.widget.TableRow;
public class PeriodicTableScreen extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_periodic_table_screen);
    TableLayout table = (TableLayout) findViewById(R.id.LayoutTable);
    createButtons newButtons = new createButtons(this);
    tableGen(table, newButtons);
}

public void tableGen(TableLayout table, createButtons newButtons) {
    ImageButton[] imageButtons;
    imageButtons = newButtons.build();
    for(int j = 1; j <= 7; j++){
            TableRow tempRow = new TableRow(this);
        if(j==1) {
            tempRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                    TableRow.LayoutParams.WRAP_CONTENT));

            for (int temp = 0; temp <= 17; temp++) {
                ImageButton tempButton = imageButtons[temp];
                tempButton.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                        TableRow.LayoutParams.WRAP_CONTENT));
                tempRow.addView(imageButtons[temp]);
            }
        }
        else if (j==2){
                for(int temp = 18; temp <=35; temp++){
                    TableRow rowOne = new TableRow(this);
                    rowOne.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                            TableRow.LayoutParams.WRAP_CONTENT));
                    ImageButton tempButton = imageButtons[temp];
                    tempButton.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                            TableRow.LayoutParams.WRAP_CONTENT));
                    tempRow.addView(imageButtons[temp-1]);
                }
        }
        else if (j==3){
            TableRow rowOne = new TableRow(this);
            rowOne.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                    TableRow.LayoutParams.WRAP_CONTENT));
                for(int temp = 36; temp <=53; temp++){
                    ImageButton tempButton = imageButtons[temp];
                    tempButton.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                            TableRow.LayoutParams.WRAP_CONTENT));
                    tempRow.addView(imageButtons[temp-1]);
                }
        }
        else if (j==4){
            TableRow rowOne = new TableRow(this);
            rowOne.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                    TableRow.LayoutParams.WRAP_CONTENT));
                for(int temp = 54; temp <=71; temp++){
                    ImageButton tempButton = imageButtons[temp];
                    tempButton.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                            TableRow.LayoutParams.WRAP_CONTENT));
                    tempRow.addView(imageButtons[temp-1]);
                }
        }
        else if (j==5){
            TableRow rowOne = new TableRow(this);
            rowOne.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                    TableRow.LayoutParams.WRAP_CONTENT));
                for(int temp = 72; temp <=89; temp++){
                    ImageButton tempButton = imageButtons[temp];
                    tempButton.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                            TableRow.LayoutParams.WRAP_CONTENT));
                    tempRow.addView(imageButtons[temp-1]);
                }
        }
        else if (j==6){

                for(int temp = 90; temp <=107; temp++){
                    ImageButton tempButton = imageButtons[temp];
                    tempButton.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                            TableRow.LayoutParams.WRAP_CONTENT));
                    tempRow.addView(imageButtons[temp-1]);
                }
        }
        else if (j==7){
                for(int temp = 108; temp <=125; temp++){
                    ImageButton tempButton = imageButtons[temp];
                    tempButton.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                            TableRow.LayoutParams.WRAP_CONTENT));
                    tempRow.addView(imageButtons[temp-1]);
                }
        }
        table.addView(tempRow, new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
                TableLayout.LayoutParams.WRAP_CONTENT));
        ((ViewGroup) tempRow.getParent()).removeView(tempRow);
    }
   }
}

If there is any other info that would be useful let me know, thanks!

Body:
Your issue might be because of following lines:

TableRow rowOne = new TableRow(this);
            rowOne.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                    TableRow.LayoutParams.WRAP_CONTENT));

You are creating it repeatedly. You are not even using it. Try removing above lines from your loop and check. Let me know if you still face any problem.


来源: stackexchange

问:
How to access form control from within ToString method of nested struct
I am building a small windows form application in C#.  Within the form code I define a public struct with a ToString method that must build part of its output from items in comboBoxes on the same form.  This doesn't sound like it should be difficult

```<code>public partial class Form1 : Form
{
 public struct OrderLineItem
    {
     string someString;
     int index;
     string ToString()
        {return someString + ActiveForm.sizeComboBox.Items[index].ToString();}
    }
}
</code>```

It complains that it cannot find a definition for sizeComboBox.  If I explicitly use the name of the form, it says an object reference is required for the static field...
I'm not quite sure what it means by that.  Using this.sizeComboBox refers to the struct, not the form.  Using just sizeComboBox, again, an object reference is required.

答:
You need to cast ActiveForm to Form1.

Something like this I think (don't have VS open now to check):

```<code>return someString + ((Form1)ActiveForm).sizeComboBox.Items[index].ToString();
</code>```

However, this is generally not a good way of going about things, you shouldn't make your methods in your classes and structs refer directory to controls since then you tie them together to closely. Try to send the data in to the struct instead or create a method on the form to return the data in some way.

ContentLicense: CC BY-SA 2.5

Body:
I am building a small windows form application in C#.  Within the form code I define a public struct with a ToString method that must build part of its output from items in comboBoxes on the same form.  This doesn't sound like it should be difficult

public partial class Form1 : Form
{
 public struct OrderLineItem
    {
     string someString;
     int index;
     string ToString()
        {return someString + ActiveForm.sizeComboBox.Items[index].ToString();}
    }
}

It complains that it cannot find a definition for sizeComboBox.  If I explicitly use the name of the form, it says an object reference is required for the static field...
I'm not quite sure what it means by that.  Using this.sizeComboBox refers to the struct, not the form.  Using just sizeComboBox, again, an object reference is required.

Body:
You need to cast ActiveForm to Form1.

Something like this I think (don't have VS open now to check):

return someString + ((Form1)ActiveForm).sizeComboBox.Items[index].ToString();

However, this is generally not a good way of going about things, you shouldn't make your methods in your classes and structs refer directory to controls since then you tie them together to closely. Try to send the data in to the struct instead or create a method on the form to return the data in some way.


问:
Loop a list of text files in same directory and findstr "keyword" in the txt file (batch script)
I would like to create a script where loop through all the .txt files in the same directory and search for keyword.

If keyword is found, echo the filename.txt and keyword found to a temp.txt

Else echo the filename.txt and keyword not found to a temp.txt

Current code:

```<code>for /r D:\Users\hi\Documents\bat_for_random %%X in (*.txt)
findstr "HELLO KEYWORD " %%X &&
(
echo "keyword found" %%X  >temp.txt
)
|| (
echo "keyword not found" %%X  >temp.txt
)
pause
</code>```

答:
Your for syntax is wrong, the do keyword is missing. In addition, you placed &&/|| and the parentheses wrongly, you need to put them in one line. Finally, your redirection operator > overwrites the text file temp.txt every time the loop iterates; using >> instead would append to the text file; or, even better, you can redirect all the lines once only. So here is the improved code:

> "temp.txt" (
    for /R "D:\Users\hi\Documents\bat_for_random" %%X in ("*.txt") do (
        > nul findstr /C:"HELLO KEYWORD " "%%~X" && (
            echo keyword found "%%~nxX"
        ) || (
            echo keyword not found "%%~nxX"
        )
    )
)
```

ContentLicense: CC BY-SA 3.0

Body:
I would like to create a script where loop through all the .txt files in the same directory and search for keyword.

If keyword is found, echo the filename.txt and keyword found to a temp.txt

Else echo the filename.txt and keyword not found to a temp.txt

Current code:

for /r D:\Users\hi\Documents\bat_for_random %%X in (*.txt)
findstr "HELLO KEYWORD " %%X &&
(
echo "keyword found" %%X  >temp.txt
)
|| (
echo "keyword not found" %%X  >temp.txt
)
pause


问:
Calling jython script from java
I am currently working on a simple hello world program using jython and java.

The program is designed in way that a jython method accepts a name parameter and returns welcome message.

My problem is whenever I am accessing the jython method from java, it shows nullponter exception

My jython Script (JythonHello.py):

```<code>class JythonHello:
    def __init__(self, name):
        self.name = name
    def sayHello(self):
        return "Hello "+ self.name
</code>```

and my java code:

```<code>public static void main(String[] args) {

    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.execfile("src/jython/JythonHello.py");

    PyObject callFunction = interpreter.get("sayHello");
    PyObject result = callFunction.__call__(new PyString("Boban"));
    String msg = (String) result.__tojava__(String.class);
    System.out.println("output: " + msg);
}
</code>```

Any suggestions?

答:
Looking at your code; your python code defines a class and a member method:

```<code>class JythonHello:
  def __init__(self, name): ...
  def sayHello(self): ...
</code>```

And it seems that you intend to call that method:

```<code> PyObject callFunction = interpreter.get("sayHello");
 PyObject result = callFunction.__call__(new PyString("Boban"));
</code>```

But please note: sayHello() doesn't take any arguments. That self parameter is an indication that you have to call it on an object; but without any other parameters!

So, in pure python you would say:

```<code>helloVar = JythonHello("Boban")
helloVar.sayHello()
</code>```

But your java code tries to call it like

```<code>sayHello("Boban")
</code>```

So, the real answer is: step back; and re-think what you really intend to do; and then write code that works that way.

I would start by not adding the "class" part on the python side; instead try to simply invoke a function that takes a string argument for example!

And finally: could it be that you are on the wrong path altogether? The main point of jython is to write simply python code to do "debug" work within a running JVM. You are writing complicated Java code to use a bit of python code on the other hand ...

Title: Calling jython script from java

Body:
I am currently working on a simple hello world program using jython and java.

The program is designed in way that a jython method accepts a name parameter and returns welcome message.

My problem is whenever I am accessing the jython method from java, it shows nullponter exception

My jython Script (JythonHello.py):

class JythonHello:
    def __init__(self, name):
        self.name = name
    def sayHello(self):
        return "Hello "+ self.name

and my java code:

public static void main(String[] args) {

    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.execfile("src/jython/JythonHello.py");

    PyObject callFunction = interpreter.get("sayHello");
    PyObject result = callFunction.__call__(new PyString("Boban"));
    String msg = (String) result.__tojava__(String.class);
    System.out.println("output: " + msg);
}

Any suggestions?

Body:
Looking at your code; your python code defines a class and a member method:

class JythonHello:
  def __init__(self, name): ...
  def sayHello(self): ...

And it seems that you intend to call that method:

 PyObject callFunction = interpreter.get("sayHello");
 PyObject result = callFunction.__call__(new PyString("Boban"));

But please note: sayHello() doesn't take any arguments. That self parameter is an indication that you have to call it on an object; but without any other parameters!

So, in pure python you would say:

helloVar = JythonHello("Boban")
helloVar.sayHello()

But your java code tries to call it like

sayHello("Boban")

So, the real answer is: step back; and re-think what you really intend to do; and then write code that works that way.

I would start by not adding the "class" part on the python side; instead try to simply invoke a function that takes a string argument for example!

And finally: could it be that you are on the wrong path altogether? The main point of jython is to write simply python code to do "debug" work within a running JVM. You are writing complicated Java code to use a bit of python code on the other hand ...


问:
COUNT function in Access 2016
I have a table in MS ACCESS 2016 which have two columns. 1st column represents two companies (assume A and B)and second column represents age of employees I need to count and display how many employees in each campany are less than 25 years. How can I accompolish that.Pics are attached.

答:
You can use an SQL query:

```<code>SELECT [Company],COUNT(*)
FROM [Table]
WHERE [Age Of Employee] < 25
GROUP BY [Company]</code>```

Where Table is the name of the table and Company and Age of Employee are the name of the columns (if the columns have a different name, you will have to alter the query a bit).

Title: COUNT function in Access 2016

Body:
You can use an SQL query:

SELECT [Company],COUNT(*)
FROM [Table]
WHERE [Age Of Employee] < 25
GROUP BY [Company]

Where Table is the name of the table and Company and Age of Employee are the name of the columns (if the columns have a different name, you will have to alter the query a bit).


问:
mongodb data recover: I just copy the /var/lib/mongodb folder
I just copy the /var/lib/mongodb folder  and the mongodb is running. Can i  copy the folder to the new server  just set the new mongo server data path to the folder?</p>

答:
Don't do directly copy running server db path, When you try to copy data path while running may be data crash/corrupting happend.

So please follow the below mentioned steps,

Stop the mongod server which one you want to copy data path server

Copy the the /var/lib/mongodb folder

Copy to new enviornment/Server

Remove the mongod.lock file

Start the new and currently stopped server

Now you check both places, your're having same data sets.


问:
using NDK for Android to write OpenGL code
So here is the deal.
I have been using OpenGL API on windows [Win32] for about 3 years.
I have written multiple shaders in the same.

Now I want to port my project on Android.
My question is, If I want to write the project using C++ [NDK], and use OpenGL ES is it possible?

Short answer I got was 'YES', but, is that a right way?
Am I better off using Java? Are there any performance degrade because I am using NDK, as I am aiming for a VR based OpenGL application performance is the main factor?

Yes its these are multiple questions, but they point at the similar problem, is it practical to use NDK for real-life projects.

答: The short answer is yes, you can use NDK for real-life projects. If you  use NativeActivity, you can have an app with no Java code at all. Many games are built with Unity engine and have all OpenGL done in C++ with no performance complaints. Actually, the opposite is true, but in real life the performance penalty of Java-to-GL wrapper is pretty low.</p>


问:
Docker pull shows "Unknown blob"
I'm trying to pull microsoft/aspnet image. It tries to download something and shows the progress. But then it shows an error - "Unknown blob".

How I can solve this?

P.S. I have docker client and server v1.12.2

答:
You must download and install latest docker from here

and switch to windows container.

read more

Title: Docker pull shows "Unknown blob"


问:
Open file from documents on Android Nougat
I'm using file helper class from this post https://stackoverflow.com/a/20559175/2281821 but it doesn't working properly in each case. I'm using Intent chooseIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT); to start file picker. I have Android Nougat and I'm receiving from onActivityResult uri: content://com.android.externalstorage.documents/document/home%3Aimage.png
What does this home: means? How can I get access to this file? I was trying with Environment.getExternalStorageDirectory() and System.getenv("EXTERNAL_STORAGE") but I can't get acess.

答:
You get access to a content scheme by opening for instance an InputStream on the uri.

```<code>InputStream is = getContentResolver().openInputStream(uri);
</code>```

BitmapFactory.decodeFromStream(is) will happily read from your stream.

Body:
You get access to a content scheme by opening for instance an InputStream on the uri.

InputStream is = getContentResolver().openInputStream(uri);

BitmapFactory.decodeFromStream(is) will happily read from your stream.


问:
PHP - file not uploaded into the database using prepared statements
I made an upload file code without prepared statements. The file is successfully uploaded. But when I add prepared statements to the code, the contents of the file is not uploaded. Only the file name, size and type and uploaded in the database.

This is the code:

PHP:

```<code><?php
include("config.php");
error_reporting( ~E_NOTICE );
if(isset($_POST['submit'])  ){

//user has the option whether to upload the file or not
if ($_FILES['upload']['size'] != 0 ){

$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);

$allowed =  array('zip','rar', 'pdf', 'doc', 'docx');
$ext = pathinfo($filename, PATHINFO_EXTENSION);

    if(in_array($ext, $allowed)){

        if($filesize < 2000000) {

            //$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')"; <- old code line

            $query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES (?,?,?,?)";

            $stmt = $con->prepare($query);
            $stmt->bind_param("sbsi", $filename, $filedata, $filetype,$filesize);
            $stmt->execute();

            if ($stmt->errno){
            echo "FAILURE!!! " . $stmt->error;
            } else {
            echo "<br>Inserted";
            }
            $stmt->close();

            /* if ($con->query($query) === TRUE) <- old code line
            {
            echo "Uploaded<br>";

            } else {
            echo "Error! <br>" . $con->error;
            }   */

        } else {

        $errorMsg = "Sorry, your file is too large. Only 2MB is allowed";
        }

    }else{
        $errorMsg = "Sorry, only zip, rar, pdf, doc & docx are allowed.";
    }

//if user has no file to upload then proceed to this else statement
} else {

$filename = $con->real_escape_string($_FILES['upload']['name']);
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);

//$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filetype','$filesize')"; <- old code line

$query = "INSERT INTO contracts(`filename`,`filetype`,`filesize`) VALUES (?,?,?)";

            $stmt = $con->prepare($query);
            $stmt->bind_param("ssi", $filename, $filetype,$filesize);
            $stmt->execute();

            if ($stmt->errno){
            echo "FAILURE!!! " . $stmt->error;
            } else {
            echo "<br>Inserted";
            }
            $stmt->close();

        /*  if ($con->query($query) === TRUE) <- old code line
            {
            echo "Uploaded<br>";

            } else {
            echo "Error! <br>" . $con->error;
            }   */

}

$con->close();
}

?>
</code>```

HTML:

```<code><html><head></head>
<body>

<form method="post" action="" enctype="multipart/form-data">
<?php echo $errorMsg; ?>
Upload File:
<input type="file" name="upload" /><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
</code>```

Why is the contents of the file is not uploaded and missing in the database with prepared statements? What is wrong with my code?

答:
If your database column type of filedata is long enough to accept file content, you can do this.

Check the field type of filedata.
Suggestion:make type of column filedata a text or blob

Now check if you file is actually uploaded to server. You can do this by printing the file content

Use following code to check if file is actually uploaded

```<code>if ($_FILES['upload']['size'] != 0 ){

$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);

$allowed =  array('zip','rar', 'pdf', 'doc', 'docx');
$ext = pathinfo($filename, PATHINFO_EXTENSION);

//Print the details to check if file is actually uploaded.
//Note: Remove this line after debugging
print_r([$filename, $filedata, $filetype, $filesize, $ext]); exit;
</code>```

Body:
I made an upload file code without prepared statements. The file is successfully uploaded. But when I add prepared statements to the code, the contents of the file is not uploaded. Only the file name, size and type and uploaded in the database.

This is the code:

PHP:

<?php
include("config.php");
error_reporting( ~E_NOTICE );
if(isset($_POST['submit'])  ){

//user has the option whether to upload the file or not
if ($_FILES['upload']['size'] != 0 ){

$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);

$allowed =  array('zip','rar', 'pdf', 'doc', 'docx');
$ext = pathinfo($filename, PATHINFO_EXTENSION);

    if(in_array($ext, $allowed)){

        if($filesize < 2000000) {

            //$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')"; <- old code line

            $query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES (?,?,?,?)";

            $stmt = $con->prepare($query);
            $stmt->bind_param("sbsi", $filename, $filedata, $filetype,$filesize);
            $stmt->execute();

            if ($stmt->errno){
            echo "FAILURE!!! " . $stmt->error;
            } else {
            echo "
Inserted";
            }
            $stmt->close();

            /* if ($con->query($query) === TRUE) <- old code line
            {
            echo "Uploaded
";

            } else {
            echo "Error!
" . $con->error;
            }   */

        } else {

        $errorMsg = "Sorry, your file is too large. Only 2MB is allowed";
        }

    }else{
        $errorMsg = "Sorry, only zip, rar, pdf, doc & docx are allowed.";
    }

//if user has no file to upload then proceed to this else statement
} else {

$filename = $con->real_escape_string($_FILES['upload']['name']);
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);

//$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filetype','$filesize')"; <- old code line

$query = "INSERT INTO contracts(`filename`,`filetype`,`filesize`) VALUES (?,?,?)";

            $stmt = $con->prepare($query);
            $stmt->bind_param("ssi", $filename, $filetype,$filesize);
            $stmt->execute();

            if ($stmt->errno){
            echo "FAILURE!!! " . $stmt->error;
            } else {
            echo "
Inserted";
            }
            $stmt->close();

        /*  if ($con->query($query) === TRUE) <- old code line
            {
            echo "Uploaded
";

            } else {
            echo "Error!
" . $con->error;
            }   */

}

$con->close();
}

?>

HTML:

<form method="post" action="" enctype="multipart/form-data">
<?php echo $errorMsg; ?>
Upload File:
<input type="file" name="upload" />

<input type="submit" name="submit" value="Submit"/>
</form>

Why is the contents of the file is not uploaded and missing in the database with prepared statements? What is wrong with my code?

Body:
If your database column type of filedata is long enough to accept file content, you can do this.

Check the field type of filedata.
Suggestion:make type of column filedata a text or blob

Now check if you file is actually uploaded to server. You can do this by printing the file content

Use following code to check if file is actually uploaded

if ($_FILES['upload']['size'] != 0 ){

$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);

$allowed =  array('zip','rar', 'pdf', 'doc', 'docx');
$ext = pathinfo($filename, PATHINFO_EXTENSION);

//Print the details to check if file is actually uploaded.
//Note: Remove this line after debugging
print_r([$filename, $filedata, $filetype, $filesize, $ext]); exit;


问:
What is the difference between getText() and getSelection() of SWT Spinner?
For a Spinner control in SWT, what is the difference between getText() and getSelection()? The only thing I can make out is the return type. However, I cannot enter any text, only numbers are allowed.

getText():
  Returns a string containing a copy of the contents of the receiver's text field, or an empty string if there are no contents.

getSelection():
  Returns the selection, which is the receiver's position.

So why do we have two different getters and which one should I use?

答:
Since the Spinner represents a numeric selection, you should go with getSelection() as it returns exactly what has been selected.

I don't know why getText() exists, but it'll return the String representation of the selected value, e.g. if getSelection() returns the int 7, getText() will return the String "7".


问:
Binding dropdownlist with database table and get selected item n MVC
I am new to asp.net mvc.

I have a employee registration view, where i have a dropdown-list for for department, I want to bind the dropdown-list with a database table tblDepartment and i have did it. But I don't know how to get the select item of the list on post-back.

Employee Controller

```<code>[HttpGet]
public ActionResult AddEmployee()
{
    ViewBag.Departments = new SelectList(_department.GetAll(), "id", "name");
    return View(_employee.Get());
}

[HttpPost]
public ActionResult AddEmployee(FormCollection data)
{
    var emp = _employee.Get();
    emp.name = data["name"];
    emp.age = Convert.ToInt32(data["age"]);
    emp.dept_id = Convert.ToInt32(data["dept_id"]); // return dept_id 0 always.
    emp.city = data["city"];
    _employee.Insert(emp);
    return RedirectToAction("Index");
}
</code>```

View

```<code>@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.name, "Name", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.age, "Age", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.age, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.age, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.dept_id, "Department", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("Departments", "Select Department")
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.city, "City", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.city, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.city, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}
</code>```

答:
You are defining your dropdownlist with name DropDownLists i.e. @Html.DropDownList("Departments" which will be the name of the drop-down list so it will be rendered like:

```<code><select name="Departments">
</select>
</code>```

and in form post the values are posted in key value pair and the key is the name of the input element.

But in post request you are finding the posted value in dept_id, you need to read from correct key in FormCollection which would be:

```<code>emp.dept_id = Convert.ToInt32(data["Departments"]);
</code>```

Side Note:

You should be using strongly typed helpers to post values directly to model and let the model binder do the magic for you, instead of populating the model manually.

For that your helper method would be DropDownListFor :

```<code>@Html.DropDownListFor(x=>x.dept_id ,ViewBag.Departments as SelectList, "Select Department")
</code>```

and in action method set the parameter to be mode object:

```<code>[HttpPost]
public ActionResult AddEmployee(Employee employee)
{
     If(ModelState.IsValid)
     {
        _employee.Insert(employee);
        return RedirectToAction("Index");
     }
     else
     {
         return View(employee);
     }
}
</code>```

Body:
I am new to asp.net mvc.

I have a employee registration view, where i have a dropdown-list for for department, I want to bind the dropdown-list with a database table tblDepartment and i have did it. But I don't know how to get the select item of the list on post-back.

Employee Controller

[HttpGet]
public ActionResult AddEmployee()
{
    ViewBag.Departments = new SelectList(_department.GetAll(), "id", "name");
    return View(_employee.Get());
}

[HttpPost]
public ActionResult AddEmployee(FormCollection data)
{
    var emp = _employee.Get();
    emp.name = data["name"];
    emp.age = Convert.ToInt32(data["age"]);
    emp.dept_id = Convert.ToInt32(data["dept_id"]); // return dept_id 0 always.
    emp.city = data["city"];
    _employee.Insert(emp);
    return RedirectToAction("Index");
}

View

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.name, "Name", htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.age, "Age", htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.age, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.age, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.dept_id, "Department", htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.DropDownList("Departments", "Select Department")

            @Html.LabelFor(model => model.city, "City", htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.city, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.city, "", new { @class = "text-danger" })

                <input type="submit" value="Create" class="btn btn-default" />

}

Body:
You are defining your dropdownlist with name DropDownLists i.e. @Html.DropDownList("Departments" which will be the name of the drop-down list so it will be rendered like:

<select name="Departments">
</select>

and in form post the values are posted in key value pair and the key is the name of the input element.

But in post request you are finding the posted value in dept_id, you need to read from correct key in FormCollection which would be:

emp.dept_id = Convert.ToInt32(data["Departments"]);

Side Note:

You should be using strongly typed helpers to post values directly to model and let the model binder do the magic for you, instead of populating the model manually.

For that your helper method would be DropDownListFor :

@Html.DropDownListFor(x=>x.dept_id ,ViewBag.Departments as SelectList, "Select Department")

and in action method set the parameter to be mode object:

[HttpPost]
public ActionResult AddEmployee(Employee employee)
{
     If(ModelState.IsValid)
     {
        _employee.Insert(employee);
        return RedirectToAction("Index");
     }
     else
     {
         return View(employee);
     }
}


问:
unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9
I am trying to run Selenium tests on Debian 7 but without success.

The error is:

```<code>unknown error: Chrome failed to start: exited abnormally   (Driver info: chromedriver=2.9.248316,platform=Linux 3.2.0-4-686-pae x86) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 60.55 seconds Build info: version: '2.33.0', revision: '4ecaf82108b2a6cc6f006aae81961236eba93358', time: '2013-05-22 12:00:17' System info: os.name: 'Linux', os.arch: 'i386', os.version: '3.2.0-4-686-pae', java.version: '1.7.0_25' Driver info: org.openqa.selenium.chrome.ChromeDriver
</code>```

I have chromedriver 29 with chrome 34.0.1847.76 beta running on Debian 7 32 bits. I am using selenium-java 2.33.0

Following this link, chromedriver 29 is the right version for chrome 34. And anyway, previous versions do not work on Debian 7 because of glibc version …

```
----------ChromeDriver v2.9 (2014-01-31)----------
Supports Chrome v31-34
```

[update 1]

I tried with with both java 7 and java 6, still the same problem. May be I should try with java 8 ^^

[update 2]

I am using this command to test the chrome driver, to make sure that is not an issue with jenkins:

```
curl -X POST -H "Content-Type: application/json; charset=utf-8" -d "{\"desiredCapabilities\":{\"platform\":\"ANY\",\"browserName\":\"chrome\",\"chromeOptions\":{\"args\":[],\"extensions\":[]},\"version\":\"\",\"chrome.switches\":[]}}" localhost:12495/session
```

I am getting the same error message:

```
{"sessionId":"210f3f837a798ee68cd91f089976d0c2","status":13,"value":{"message":"unknown error: Chrome failed to start: exited abnormally\n  (Driver info: chromedriver=2.9.248316,platform=Linux 3.2.0-4-686-pae x86)"}}
```

Any help to know what is going on would be appreciated.

Thanks

答:
Exporting the DISPLAY variable is definitely the solution but depending on your setup you may have to do this in a slightly different way.

In my case, I have two different processes: the first one starts Xvfb, the other one launches the tests. So my shell scripting knowledge is a bit rusty but I figured out that exporting the DISPLAY variable from the first process didn't make it available in the second process.

Fortunately, Selenium WebDriver allows you to 'redefine' your environment.
This is my function for creating a driver for Chrome in JS. Pretty sure the equivalent exists for your programming language:

const caps = require('selenium-webdriver/lib/capabilities');
const chrome = require('selenium-webdriver/chrome');
const chromedriver = require('chromedriver');

module.exports = function (cfg) {
    let serviceBuilder = new chrome.ServiceBuilder(chromedriver.path);
    let options = chrome.Options.fromCapabilities(caps.Capabilities.chrome());
    let service;
    let myENV = new Map();

    // 're-export' the `DISPLAY` variable
    myENV.set('DISPLAY', ':1');
    serviceBuilder.setEnvironment(myENV);

    service = serviceBuilder.build();

    options.addArguments('disable-setuid-sandbox');
    options.addArguments('no-sandbox');
    options.addArguments('allow-insecure-localhost');
    options.excludeSwitches('test-type');

    return chrome.Driver.createSession(options, service);
};
```

Body:
I am trying to run Selenium tests on Debian 7 but without success.

The error is:

unknown error: Chrome failed to start: exited abnormally   (Driver info: chromedriver=2.9.248316,platform=Linux 3.2.0-4-686-pae x86) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 60.55 seconds Build info: version: '2.33.0', revision: '4ecaf82108b2a6cc6f006aae81961236eba93358', time: '2013-05-22 12:00:17' System info: os.name: 'Linux', os.arch: 'i386', os.version: '3.2.0-4-686-pae', java.version: '1.7.0_25' Driver info: org.openqa.selenium.chrome.ChromeDriver

I have chromedriver 29 with chrome 34.0.1847.76 beta running on Debian 7 32 bits. I am using selenium-java 2.33.0

Following this link, chromedriver 29 is the right version for chrome 34. And anyway, previous versions do not work on Debian 7 because of glibc version …

----------ChromeDriver v2.9 (2014-01-31)----------
Supports Chrome v31-34

[update 1]

I tried with with both java 7 and java 6, still the same problem. May be I should try with java 8 ^^

[update 2]

I am using this command to test the chrome driver, to make sure that is not an issue with jenkins:

curl -X POST -H "Content-Type: application/json; charset=utf-8" -d "{\"desiredCapabilities\":{\"platform\":\"ANY\",\"browserName\":\"chrome\",\"chromeOptions\":{\"args\":[],\"extensions\":[]},\"version\":\"\",\"chrome.switches\":[]}}" localhost:12495/session

I am getting the same error message:

{"sessionId":"210f3f837a798ee68cd91f089976d0c2","status":13,"value":{"message":"unknown error: Chrome failed to start: exited abnormally\n  (Driver info: chromedriver=2.9.248316,platform=Linux 3.2.0-4-686-pae x86)"}}

Any help to know what is going on would be appreciated.

Thanks


问:
Excel chart's data is in Days, can I show the Series Data Lables in Months
My chart's range data ("A1:E6") looks is in the screen-shot below:

And this is my current Projects Timeline chart (Type Stacked-Bar):

As you can see, my Series Data Labels are in the same format as my Range, which is days.

Question: is there a way (without VBA) to format the Data Labels to be in months ?

For instance, for Project 3, Stage 1 (brown bar), instead of 90, it will display 3.

Is there a way to "out-smart" the screen below:

答:
You can use helper columns in your data to calculate the desired value you want to show in the labels, i.e. divide by 30 to arrive at the approximate month value for any given number of days.

Then, depending on your Excel version and/or preference and/or need for backwards compatibility, you can either

manually edit each data label, hit F2 to edit the data label, type a = sign and then click the cell that has the calculated month value. Repeat for each data label, or

if that sounds too tedious, download and install the free XY Chart Labeler tool by Rob Bovey, which automates the steps above. You can share the file with people who don't have the tool, since all label references will end up hard-coded. The tool just helps reduce the manual labour to link labels to the cells. Or

with Excel 2013 or higher, use the formatting option in the Data Labels side panel to use "Values from cells" and select the cells where the converted values are. This feature is not backwards compatible and will show placeholder text instead of the labels if the file is opened in Excel versions earlier than XL 2013.

Edit: By the way, the formatting section that you highlighted in your screenshot is for formatting the numbers that the label shows. A format can only change the display of a value, but not perform a calculation, like convert number of days into number of months. So, the format approach is a dead end from the get-go.


问:
How to hide mouse cursor using JOGL2?
I'm using JOGL2 and the NativeWindow APIs to write an app in Java. How can I  hide the mouse cursor?

[EDIT]

I'm not using JFrame to create a window but rather GLWindow from JOGL. GLWindow does not have a setCursor method. Is this still possible?

答: If mouse is in the area of application window you can set any image as a custom cursor. Use transparent image 1x1 pixel. I used it - works fine. It is regular API, no JOGL, no native code. </p>

ContentLicense: CC BY-SA 4.0

Title: How to hide mouse cursor using JOGL2?


问:
SuiteCommerce Advance: Create Custom Service to fetch the custom record from Netsuite's backend to backbone view
I have custom record created in netsuite's backend named Webstore Landing Data. Record is having below structure & columns

```<code>Record Id: customrecord_webstore_category_landing
Coloumns:
    i. custrecord_collection_name
    ii. custrecord_collection_sub_category
    iii. custrecord_collection_url
</code>```

And need to create service to fetch this record on backbone view. Help appreciated.

答:
Ok, Good question. This is the most important and required thing in SCA check below details-->

Note: Below steps is for SuiteCOmmerce Advance Vision(2016-17) release

You need to created below things-->

```<code>i.  SuiteScript Model
ii. SuiteScript Service
iii.JavaScript Model
iv. JavaScript view
v.  JavaScript Template
vi. Update distro.json
</code>```

Create custom folder(our custom module) under custom folder as

Modules/custom/Categorylanding@1.0.0

Create SuiteScript folder under above module

Create SuiteScript Service under 'SuiteScript' Folder as below-->

FileName & Path:    Modules/custom/Categorylanding@1.0.0/SuiteScript/Categorylanding.ServiceController.js

Code:

```<code> define(
    'Categorylanding.ServiceController'
,   [
        'ServiceController'
    ,   'Categorylanding.Model'
    ]
,   function(
        ServiceController
    ,   Categorylanding
    )
    {
        'use strict';

        return ServiceController.extend({

            name: 'Categorylanding.ServiceController'

           , get: function()
            {
               return Categorylanding.get();
            }
        });
    }
);
</code>```

Create SuiteScript Model under SuiteScript folder as below-->

FileName & Path:
Modules/custom/Categorylanding@1.0.0/SuiteScript/Categorylanding.Model.js

Code:

```<code>define('Categorylanding.Model',
  [
  'SC.Model'
  ],
  function (SCModel) {
    return SCModel.extend({
      name: 'Categorylanding',
      get: function()
      {
        var filters = new Array();
        var columns = new Array();
        columns[0] = new nlobjSearchColumn('custrecord_collection_name');
        columns[2] = new nlobjSearchColumn('custrecord_collection_url');
        var results = nlapiSearchRecord('customrecord_webstore_category_landing', null, filters, columns);

        var results_ = JSON.stringify(results);
        return results_;
      }
    });
  }
)
</code>```

Created ns package file

Filename & Path:

Modules/custom/Categorylanding@1.0.0/ns.package.json

Code:

```<code>{
    "gulp": {
        "javascript": [
            "JavaScript/*"
        ],
        "ssp-libraries": [
            "SuiteScript/*.js"
        ],
        "autogenerated-services": {
            "Categorylanding.Service.ss": "Categorylanding.ServiceController"
        },
        "templates": [
            "Templates/*"
        ],
        "images": [
            "Images/*"
        ],
        "sass": [
            "Sass/*.scss"
        ],
        "configuration": [
            "Configuration/*.json"
        ]
    }
}
</code>```

Update distro. json file as below

add your module under modules section as

```<code>"custom/Categorylanding": "1.0.0",
</code>```

and dependencies in

```<code>"ssp-libraries": {
            "entryPoint": "SCA",
            "dependencies": [

  "CategoryLanguage.ServiceController",
   "CategoryLanguage.Model",
],
</code>```

Deploy your code and once this is done you can able to see your data when in return call, you can call your service as below

http://yoursite.com/sca-dev-vinson/services/Categorylanding.Service.ss?c=4515330

Now the remaining part is how you can get this data on backbone view, to do this go to your view where you want this data

Before that create Javascript model under Same folder as below

Filename & Path :

Modules/custom/Categorylanding@1.0.0/JavaScript/Categorylanding.Model.js

Code:

```<code>define('Categorylanding.Model',
  [
  'Backbone',
  'underscore'
  ],
  function (Backbone, _) {
    return Backbone.Model.extend(
    {
        url: function()
        { var  urlRoot = _.getAbsoluteUrl('services/Categorylanding.Service.ss');
            return urlRoot;
      }
    });
  }
);
</code>```

Once this is done, you can call above javascript model on any view/router file to get the record data on backbone view

Define mode and use below code

```<code>    var collection = new CategorylandingModel();
    var view = new BrowseView({
                            translator: translator
                            ,   translatorConfig: self.translatorConfig
                            ,   application: self.application
                            ,   collection: collection
});

collection.fetch().done(function(data)  //again fetch Instagram service
                        {
                            console.log(data)                           //your service data will log here

                        });
</code>```

Now you can able to access your data on BrowseView(){} as

var recorddata = this.collection.attributes;

console.log(recorddata);

and Pass it handlebar. That's it.

Let me know if you want any help....

Body:
I have custom record created in netsuite's backend named Webstore Landing Data. Record is having below structure & columns

Record Id: customrecord_webstore_category_landing
Coloumns:
    i. custrecord_collection_name
    ii. custrecord_collection_sub_category
    iii. custrecord_collection_url

And need to create service to fetch this record on backbone view. Help appreciated.

Body:
Ok, Good question. This is the most important and required thing in SCA check below details-->

Note: Below steps is for SuiteCOmmerce Advance Vision(2016-17) release

You need to created below things-->

i.  SuiteScript Model
ii. SuiteScript Service
iii.JavaScript Model
iv. JavaScript view
v.  JavaScript Template
vi. Update distro.json

Create custom folder(our custom module) under custom folder as

Modules/custom/Categorylanding@1.0.0

Create SuiteScript folder under above module

Create SuiteScript Service under 'SuiteScript' Folder as below-->

FileName & Path:    Modules/custom/Categorylanding@1.0.0/SuiteScript/Categorylanding.ServiceController.js

Code:

 define(
    'Categorylanding.ServiceController'
,   [
        'ServiceController'
    ,   'Categorylanding.Model'
    ]
,   function(
        ServiceController
    ,   Categorylanding
    )
    {
        'use strict';

        return ServiceController.extend({

            name: 'Categorylanding.ServiceController'

           , get: function()
            {
               return Categorylanding.get();
            }
        });
    }
);

Create SuiteScript Model under SuiteScript folder as below-->

FileName & Path:
Modules/custom/Categorylanding@1.0.0/SuiteScript/Categorylanding.Model.js

Code:

define('Categorylanding.Model',
  [
  'SC.Model'
  ],
  function (SCModel) {
    return SCModel.extend({
      name: 'Categorylanding',
      get: function()
      {
        var filters = new Array();
        var columns = new Array();
        columns[0] = new nlobjSearchColumn('custrecord_collection_name');
        columns[2] = new nlobjSearchColumn('custrecord_collection_url');
        var results = nlapiSearchRecord('customrecord_webstore_category_landing', null, filters, columns);

        var results_ = JSON.stringify(results);
        return results_;
      }
    });
  }
)

Created ns package file

Filename & Path:

Modules/custom/Categorylanding@1.0.0/ns.package.json

Code:

{
    "gulp": {
        "javascript": [
            "JavaScript/*"
        ],
        "ssp-libraries": [
            "SuiteScript/*.js"
        ],
        "autogenerated-services": {
            "Categorylanding.Service.ss": "Categorylanding.ServiceController"
        },
        "templates": [
            "Templates/*"
        ],
        "images": [
            "Images/*"
        ],
        "sass": [
            "Sass/*.scss"
        ],
        "configuration": [
            "Configuration/*.json"
        ]
    }
}

Update distro. json file as below

add your module under modules section as

"custom/Categorylanding": "1.0.0",

and dependencies in

"ssp-libraries": {
            "entryPoint": "SCA",
            "dependencies": [

  "CategoryLanguage.ServiceController",
   "CategoryLanguage.Model",
],

Deploy your code and once this is done you can able to see your data when in return call, you can call your service as below

http://yoursite.com/sca-dev-vinson/services/Categorylanding.Service.ss?c=4515330

Now the remaining part is how you can get this data on backbone view, to do this go to your view where you want this data

Before that create Javascript model under Same folder as below

Filename & Path :

Modules/custom/Categorylanding@1.0.0/JavaScript/Categorylanding.Model.js

Code:

define('Categorylanding.Model',
  [
  'Backbone',
  'underscore'
  ],
  function (Backbone, _) {
    return Backbone.Model.extend(
    {
        url: function()
        { var  urlRoot = _.getAbsoluteUrl('services/Categorylanding.Service.ss');
            return urlRoot;
      }
    });
  }
);

Once this is done, you can call above javascript model on any view/router file to get the record data on backbone view

Define mode and use below code

    var collection = new CategorylandingModel();
    var view = new BrowseView({
                            translator: translator
                            ,   translatorConfig: self.translatorConfig
                            ,   application: self.application
                            ,   collection: collection
});

collection.fetch().done(function(data)  //again fetch Instagram service
                        {
                            console.log(data)                           //your service data will log here

                        });

Now you can able to access your data on BrowseView(){} as

var recorddata = this.collection.attributes;

console.log(recorddata);

and Pass it handlebar. That's it.

Let me know if you want any help....


问:
htmlspecialchars() expects parameter 1 to be string, array given php
so im trying to call this funktion in my tpl but i get the error massage:
Notice: Undefined offset: 1 in /var/www/virtual/www.eless.de/ivanovm/lib/data/Contract.class.php on line 342

Warning: htmlspecialchars() expects parameter 1 to be string, array given in /var/www/virtual/www.eless.de/ivanovm/templates/compiled/d9e0e5ca75d171cae06b57137aa1475b7f24e533_2.file.contractList.tpl.php on line 135
(line 135 is empty)

```<code>public function getYearlyConsumption()
    {
        $yearlyConsumption = [];
        $idx = 0;

        //company bestimmen und zugehörige consumption points aufrufen
        $company = System::getUser()->getCompany();
        $consumptionPoints = $company->getConsumptionPoints();

        foreach ($consumptionPoints as $consumptionPoint) {
            if ($consumptionPoint->status == 1) {
                $yearlyConsumption[$idx] += $consumptionPoint->getYearlyConsumptionInt();
                $idx++;

            }
        }
        return $yearlyConsumption;
    }
</code>```

here is the call in my template (this mistake pops up for every funnction i'm trying to call the code above is just one example

```<code>{foreach from=$data item=item}
                <tr>
                    <td>
                        <a href="{System::getLink('contractView')}"><input type="button" style="text-align: center"
                                                                           width="200em"
                                                                           value="»{$item->contractID}«"></a>
                    </td>
                    <td>
                        {$item->date|date_format:"%d.%m.%Y"}
                    </td>
                    <td>
                        {$item->selectedPrice}
                    </td>
                    <td>
                        {$item->getYearlyConsumption()}
                    </td>
                    <td>
                        {$item->getConsumptionPointsCount()}
                    </td>
                    <td>
                        {if $item->status == 0}
                            <span {literal}style="background-color:#ff9933"{/literal}>Wird Bearbeitet</span>
                        {/if}
                        {if $item->status == 1}
                            <span {literal}style="background-color:#33cc33"{/literal}>Abgeschlossen</span>
                        {/if}
                        {if $item->status == 2}
                            <span {literal}style="background-color:#ff0000"{/literal}>Stoniert</span>
                        {/if}
                    </td>
                </tr>
            {/foreach}
</code>```

答:
getYearlyConsumption() returns array and you trying to display array as string including it in {}.
{} tags call htmlspecialchars() function.</p>

Body:
so im trying to call this funktion in my tpl but i get the error massage:
Notice: Undefined offset: 1 in /var/www/virtual/www.eless.de/ivanovm/lib/data/Contract.class.php on line 342

Warning: htmlspecialchars() expects parameter 1 to be string, array given in /var/www/virtual/www.eless.de/ivanovm/templates/compiled/d9e0e5ca75d171cae06b57137aa1475b7f24e533_2.file.contractList.tpl.php on line 135
(line 135 is empty)

public function getYearlyConsumption()
    {
        $yearlyConsumption = [];
        $idx = 0;

        //company bestimmen und zugehörige consumption points aufrufen
        $company = System::getUser()->getCompany();
        $consumptionPoints = $company->getConsumptionPoints();

        foreach ($consumptionPoints as $consumptionPoint) {
            if ($consumptionPoint->status == 1) {
                $yearlyConsumption[$idx] += $consumptionPoint->getYearlyConsumptionInt();
                $idx++;

            }
        }
        return $yearlyConsumption;
    }

here is the call in my template (this mistake pops up for every funnction i'm trying to call the code above is just one example

{foreach from=$data item=item}

                        <input type="button" style="text-align: center"
                                                                           width="200em"
                                                                           value="»{$item->contractID}«">

                        {$item->date|date_format:"%d.%m.%Y"}

                        {$item->selectedPrice}

                        {$item->getYearlyConsumption()}

                        {$item->getConsumptionPointsCount()}

                        {if $item->status == 0}
                            Wird Bearbeitet
                        {/if}
                        {if $item->status == 1}
                            Abgeschlossen
                        {/if}
                        {if $item->status == 2}
                            Stoniert
                        {/if}

            {/foreach}


答:
As the documentation states, getText() returns the string as if is currently displayed, including possible non-numeric values or values outside the min/max range. getSelection() returns the current or last valid integer value.

Usually, you would want to use getSelection(). Does that answer your question?

Title: What is the difference between getText() and getSelection() of SWT Spinner?

Body:
For a Spinner control in SWT, what is the difference between getText() and getSelection()? The only thing I can make out is the return type. However, I cannot enter any text, only numbers are allowed.

getText():
  Returns a string containing a copy of the contents of the receiver's text field, or an empty string if there are no contents.

getSelection():
  Returns the selection, which is the receiver's position.

So why do we have two different getters and which one should I use?


问:
Memory leak when updating material index in function animate() - three.js r84
Inspired by ParametricGeometries ( @author zz85 ),  I have programmed an addon for three.js (named THREEf, updated 22.03.) to produce with only 9 properties, 18 functions and 1 array almost infinite many time-varying geometries:

```<code>geometry =  new THREE.Geometry();
geometry.createMorphGeometry = THREEf.createMorphGeometry; // insert the methode from THREEf.js
geometry.createMorphGeometry(); // apply the methode ( here without parameters: all default )
</code>```

After a while I noticed a memory leak. I thought I had made a mistake and searched the entire code. But nothing found! The error then suddenly disappeared when some code blocks were removed. The error occurs when the material index is renewed in the animate function.

```<code>geometry.faces[ index ].materialIndex  = geometry.materialCover( .. , .. , t ); // in THREEf
</code>```

respectively ( in animate() )

```<code>t = clock.getElapsedTime();
geometry.elementsNeedUpdate = true;  // sufficient
// geometry.colorsNeedUpdate = true;
// material.needsUpdate = true;
geometry.faces[ 0 ].materialIndex = Math.floor( 5 * t ) % 3;
</code>```

in the following very simple example that results in a fairly slow memory allocation.

'use strict'
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 2000 );
camera.position.set( 10, 20, 30 );

var renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( 0xdddddd, 1 );

var container = document.createElement( 'div' );
document.body.appendChild( container );
container.appendChild( renderer.domElement );

var orbit = new THREE.OrbitControls( camera, renderer.domElement );
orbit.enableZoom = true;

var clock  = new THREE.Clock( true );
var t; // time

var materials = [

  new THREE.MeshBasicMaterial( { color: 0xff0000, side: THREE.DoubleSide } ), // red
  new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } ), // green
  new THREE.MeshBasicMaterial( { color: 0x0000ff, side: THREE.DoubleSide } )  // blue

 ];

var material = new THREE.MultiMaterial( materials );

var geometry =  new THREE.Geometry();

geometry.vertices.push( new THREE.Vector3( -10, -10, -10 ) );
geometry.vertices.push( new THREE.Vector3(  10, -10,   0 ) );
geometry.vertices.push( new THREE.Vector3(  10,  10,  10 ) );

var face = new THREE.Face3( 0, 1, 2 );

geometry.faces.push( face );
scene.add( new THREE.Mesh( geometry, material ) );

animate();
//...............

function animate() {

 requestAnimationFrame( animate );

 t = clock.getElapsedTime();

 geometry.elementsNeedUpdate = true;
 //geometry.colorsNeedUpdate = true;
 //material.needsUpdate = true;

 geometry.faces[ 0 ].materialIndex = Math.floor( 5 * t ) % 3;

 renderer.render( scene, camera );
 controls.update();

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<!-- memory leak -->
<html lang="de"><head><title> memory leak </title>  <meta charset="utf-8" /></head>
<body>   memory leak when updating material index in function animate()</body>
<script src="../js/three.min.84.js"></script>
<script src="../js/OrbitControls.js"></script></code>```

See under http://threejs.hofk.de/memoryleak/memoryLeak.html

In my "function geometry", the browser crashes faster. You can try this at http://sandbox.threejs.hofk.de/ (currently only with Firefox)
and there is a way to basic examples - also other browsers.
There is a library of forms in progress.

I have looked in three.js but this is really great and I have too little knowledge to recognize something there.

How to fix the memory leak?

答:
After WestLangley had answered my Question ( to change the face colors ) I have looked for many examples.
I have found the following:
https://github.com/mrdoob/three.js/blob/master/examples/webgl_objects_update.html

And in this example the answer is.

To change the faces you need

```<code>geometry.elementsNeedUpdate = true;
</code>```

but to change the material index is used

```<code>geometry.groupsNeedUpdate = true;
</code>```

This update is not available in the documentation
"How to update things" where I've looked.
There is the enumeration

```<code>object.updateMatrix();
</code>```

...

```<code>geometry.elementsNeedUpdate = true;
</code>```

...

```<code>texture.needsUpdate = true;
</code>```

Then I looked in three.js revision 84 to the function DirectGeometry ().
I found  this.groupsNeedUpdate = ...
It can be seen that the material index is related to the group.

Conclusion:

I just had to change a single command instead
geometry.elementsNeedUpdate = true;
 now
geometry.groupsNeedUpdate = true;
and the sandbox has no memory leak anymore.

But if I want to change the faces as in the example https://github.com/mrdoob/three.js/blob/master/examples/webgl_objects_update.html
there is still a problem.

I used the test 50 (given 1000 slowly)

function animate() { setTimeout( animate, 50 ); ...

Then the memory leak occurs:

```<code>function randomizeFaces( object ) { ... geometry.elementsNeedUpdate = true; ...
</code>```

I think then you have to use shader.

Body:
Inspired by ParametricGeometries ( @author zz85 ),  I have programmed an addon for three.js (named THREEf, updated 22.03.) to produce with only 9 properties, 18 functions and 1 array almost infinite many time-varying geometries:

geometry =  new THREE.Geometry();
geometry.createMorphGeometry = THREEf.createMorphGeometry; // insert the methode from THREEf.js
geometry.createMorphGeometry(); // apply the methode ( here without parameters: all default )

After a while I noticed a memory leak. I thought I had made a mistake and searched the entire code. But nothing found! The error then suddenly disappeared when some code blocks were removed. The error occurs when the material index is renewed in the animate function.

geometry.faces[ index ].materialIndex  = geometry.materialCover( .. , .. , t ); // in THREEf

respectively ( in animate() )

t = clock.getElapsedTime();
geometry.elementsNeedUpdate = true;  // sufficient
// geometry.colorsNeedUpdate = true;
// material.needsUpdate = true;
geometry.faces[ 0 ].materialIndex = Math.floor( 5 * t ) % 3;

in the following very simple example that results in a fairly slow memory allocation.

'use strict'
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 2000 );
camera.position.set( 10, 20, 30 );

var renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( 0xdddddd, 1 );

var container = document.createElement( 'div' );
document.body.appendChild( container );
container.appendChild( renderer.domElement );

var orbit = new THREE.OrbitControls( camera, renderer.domElement );
orbit.enableZoom = true;

var clock  = new THREE.Clock( true );
var t; // time

var materials = [

  new THREE.MeshBasicMaterial( { color: 0xff0000, side: THREE.DoubleSide } ), // red
  new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } ), // green
  new THREE.MeshBasicMaterial( { color: 0x0000ff, side: THREE.DoubleSide } )  // blue

 ];

var material = new THREE.MultiMaterial( materials );

var geometry =  new THREE.Geometry();

geometry.vertices.push( new THREE.Vector3( -10, -10, -10 ) );
geometry.vertices.push( new THREE.Vector3(  10, -10,   0 ) );
geometry.vertices.push( new THREE.Vector3(  10,  10,  10 ) );

var face = new THREE.Face3( 0, 1, 2 );

geometry.faces.push( face );
scene.add( new THREE.Mesh( geometry, material ) );

animate();
//...............

function animate() {

 requestAnimationFrame( animate );

 t = clock.getElapsedTime();

 geometry.elementsNeedUpdate = true;
 //geometry.colorsNeedUpdate = true;
 //material.needsUpdate = true;

 geometry.faces[ 0 ].materialIndex = Math.floor( 5 * t ) % 3;

 renderer.render( scene, camera );
 controls.update();

}

<!DOCTYPE html>

<title> memory leak </title>  <meta charset="utf-8" />
   memory leak when updating material index in function animate()

See under http://threejs.hofk.de/memoryleak/memoryLeak.html

In my "function geometry", the browser crashes faster. You can try this at http://sandbox.threejs.hofk.de/ (currently only with Firefox)
and there is a way to basic examples - also other browsers.
There is a library of forms in progress.

I have looked in three.js but this is really great and I have too little knowledge to recognize something there.

How to fix the memory leak?

Body:
After WestLangley had answered my Question ( to change the face colors ) I have looked for many examples.
I have found the following:
https://github.com/mrdoob/three.js/blob/master/examples/webgl_objects_update.html

And in this example the answer is.

To change the faces you need

geometry.elementsNeedUpdate = true;

but to change the material index is used

geometry.groupsNeedUpdate = true;

This update is not available in the documentation
"How to update things" where I've looked.
There is the enumeration

object.updateMatrix();

...

geometry.elementsNeedUpdate = true;

...

texture.needsUpdate = true;

Then I looked in three.js revision 84 to the function DirectGeometry ().
I found  this.groupsNeedUpdate = ...
It can be seen that the material index is related to the group.

Conclusion:

I just had to change a single command instead
geometry.elementsNeedUpdate = true;
 now
geometry.groupsNeedUpdate = true;
and the sandbox has no memory leak anymore.

But if I want to change the faces as in the example https://github.com/mrdoob/three.js/blob/master/examples/webgl_objects_update.html
there is still a problem.

I used the test 50 (given 1000 slowly)

function animate() { setTimeout( animate, 50 ); ...

Then the memory leak occurs:

function randomizeFaces( object ) { ... geometry.elementsNeedUpdate = true; ...

I think then you have to use shader.


问:
mySQL: is it possible to make this query any faster?
I have a table "test" containing millions of entries. Each row contains a floating point "feature" and a "count" how often this feature is present in item "id". The primary key for this table is the combination of "id" and "feature", i.e. every item may have multiple features. There are usually a couple of hundred to a couple of thousand feature entries per item id.

```<code>create table test
(
    id      int not null,
    feature double not null,
    count   int not null
);
</code>```

The task is to find the 500 most similar items to a given reference item. Similarity is measured in number of identical feature values in both items. The query I have come up with is quoted below, but despite properly using indices its execution plan still contains "using temporary" and "using filesort", giving unacceptable performance for my use case.

```<code>select
    t1.id,
    t2.id,
    sum( least( t1.count, t2.count )) as priority
from test as t1
inner join test as t2
     on t2.feature = t1.feature
where t1.id = {some user supplied id value}
group by t1.id, t2.id
order by priority desc
limit 500;
</code>```

Any ideas on how to improve on this? The schema can be modified and indices added as needed.

答:
I would start with this... love to hear back on performance you are looking at.  I don't think you needed the LEAST( of t1 vs t2 counts ).  If you are first qualifying the where based on ID = {some value}, you will obviously get all those "features".  Then via a self-join to itself only concerned with the matching "features", you get a count.  Since you are breaking it down by by ID1 and ID2, each respective "feature" will be counted once.  At the end of this query, since I'm not expclicitly excluding t2.ID equal to the {some user value}, It's count should be the EXACT SAME count of features in t1, and anything else under that would be your other closest matches.

I would ensure I had an index on ID and FEATURE.

```<code>select STRAIGHT_JOIN
      t1.id,
      t2.id,
      count(*) as MatchedInBoth
   from
      test as t1,
      test as t2
   where
          t1.id = {some user value}
      and t1.feature = t2.feature
   group by
      t1.id,
      t2.id
   order by
      MatchedInBoth desc
   limit
      500;
</code>```

The result might give something like

```<code>t1            t2           MatchedInBoth
{user value}  {user value} 275
{user value}  Other ID 1   270
{user value}  Other ID 2   241
{user value}  Other ID 3   218
{user value}  Other ID 4   197
{user value}  Other ID 5   163, etc
</code>```

Body:
I have a table "test" containing millions of entries. Each row contains a floating point "feature" and a "count" how often this feature is present in item "id". The primary key for this table is the combination of "id" and "feature", i.e. every item may have multiple features. There are usually a couple of hundred to a couple of thousand feature entries per item id.

create table test
(
    id      int not null,
    feature double not null,
    count   int not null
);

The task is to find the 500 most similar items to a given reference item. Similarity is measured in number of identical feature values in both items. The query I have come up with is quoted below, but despite properly using indices its execution plan still contains "using temporary" and "using filesort", giving unacceptable performance for my use case.

select
    t1.id,
    t2.id,
    sum( least( t1.count, t2.count )) as priority
from test as t1
inner join test as t2
     on t2.feature = t1.feature
where t1.id = {some user supplied id value}
group by t1.id, t2.id
order by priority desc
limit 500;

Any ideas on how to improve on this? The schema can be modified and indices added as needed.

Body:
I would start with this... love to hear back on performance you are looking at.  I don't think you needed the LEAST( of t1 vs t2 counts ).  If you are first qualifying the where based on ID = {some value}, you will obviously get all those "features".  Then via a self-join to itself only concerned with the matching "features", you get a count.  Since you are breaking it down by by ID1 and ID2, each respective "feature" will be counted once.  At the end of this query, since I'm not expclicitly excluding t2.ID equal to the {some user value}, It's count should be the EXACT SAME count of features in t1, and anything else under that would be your other closest matches.

I would ensure I had an index on ID and FEATURE.

select STRAIGHT_JOIN
      t1.id,
      t2.id,
      count(*) as MatchedInBoth
   from
      test as t1,
      test as t2
   where
          t1.id = {some user value}
      and t1.feature = t2.feature
   group by
      t1.id,
      t2.id
   order by
      MatchedInBoth desc
   limit
      500;

The result might give something like

t1            t2           MatchedInBoth
{user value}  {user value} 275
{user value}  Other ID 1   270
{user value}  Other ID 2   241
{user value}  Other ID 3   218
{user value}  Other ID 4   197
{user value}  Other ID 5   163, etc


问:
Eval on tricky string forms of defaultdict
Somehow, I'm handed a text files of defaultdict saved using the str() method and the utf8 string reads:

```<code>defaultdict(<class 'set'>, {'protection': {'1058c_204062v_00:39:16->00:39:18_ko'}, 'protect': {'50c_45523v_00:01:22->00:01:24_ko', '5457c_150765v_00:08:34->00:08:37_ko', '5457c_144739v_00:34:25->00:34:28_ko', '1058c_204062v_00:39:36->00:39:39_ko', '504c_68856v_00:15:47->00:15:49_ko'}})
</code>```

When I use eval(), it throws:

```<code>Traceback (most recent call last):
  File "consolidate.py", line 9, in <module>
    print (eval(translation_counter), ast.literal_eval(location))
  File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ast.py", line 46, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 1
    defaultdict(<class 'set'>, {'protection': {'1058c_204062v_00:39:16->00:39:18_ko'}, 'protect': {'50c_45523v_00:01:22->00:01:24_ko', '5457c_150765v_00:08:34->00:08:37_ko', '5457c_144739v_00:34:25->00:34:28_ko', '1058c_204062v_00:39:36->00:39:39_ko', '504c_68856v_00:15:47->00:15:49_ko'}})
                ^
SyntaxError: invalid syntax
</code>```

According to https://stackoverflow.com/a/4020564/610569 , I've also tried ast.literal_eval() and it throws the same error as above.

Then I tried to somehow escape it using `.replace('_', '_') and it threw this:

```<code>Traceback (most recent call last):
  File "consolidate.py", line 9, in <module>
    print (eval(translation_counter), ast.literal_eval(location.replace('_', r'\_')))
  File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ast.py", line 46, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 1
    defaultdict(<class 'set'>, {'protection': {'1058c\_204062v\_00:39:16->00:39:18\_ko'}, 'protect': {'50c\_45523v\_00:01:22->00:01:24\_ko', '5457c\_150765v\_00:08:34->00:08:37\_ko', '5457c\_144739v\_00:34:25->00:34:28\_ko', '1058c\_204062v\_00:39:36->00:39:39\_ko', '504c\_68856v\_00:15:47->00:15:49\_ko'}})
                ^
SyntaxError: invalid syntax
</code>```

The full code:

```<code># -*- coding: utf-8 -*-

from collections import defaultdict, Counter
import ast

with open('related.txt', 'r', encoding='utf8') as fin:
    for line in fin:
        location = line.strip()
        print (eval(location))
</code>```

And the head -n1 related.txt looks like this:

```<code>defaultdict(<class 'set'>, {'protection': {'1058c_204062v_00:39:16->00:39:18_ko'}, 'protect': {'50c_45523v_00:01:22->00:01:24_ko', '5457c_150765v_00:08:34->00:08:37_ko', '5457c_144739v_00:34:25->00:34:28_ko', '1058c_204062v_00:39:36->00:39:39_ko', '504c_68856v_00:15:47->00:15:49_ko'}})
</code>```

Body:
Somehow, I'm handed a text files of defaultdict saved using the str() method and the utf8 string reads:

defaultdict(<class 'set'>, {'protection': {'1058c_204062v_00:39:16->00:39:18_ko'}, 'protect': {'50c_45523v_00:01:22->00:01:24_ko', '5457c_150765v_00:08:34->00:08:37_ko', '5457c_144739v_00:34:25->00:34:28_ko', '1058c_204062v_00:39:36->00:39:39_ko', '504c_68856v_00:15:47->00:15:49_ko'}})

When I use eval(), it throws:

Traceback (most recent call last):
  File "consolidate.py", line 9, in <module>
    print (eval(translation_counter), ast.literal_eval(location))
  File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ast.py", line 46, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 1
    defaultdict(<class 'set'>, {'protection': {'1058c_204062v_00:39:16->00:39:18_ko'}, 'protect': {'50c_45523v_00:01:22->00:01:24_ko', '5457c_150765v_00:08:34->00:08:37_ko', '5457c_144739v_00:34:25->00:34:28_ko', '1058c_204062v_00:39:36->00:39:39_ko', '504c_68856v_00:15:47->00:15:49_ko'}})
                ^
SyntaxError: invalid syntax

According to https://stackoverflow.com/a/4020564/610569 , I've also tried ast.literal_eval() and it throws the same error as above.

Then I tried to somehow escape it using `.replace('_', '_') and it threw this:

Traceback (most recent call last):
  File "consolidate.py", line 9, in <module>
    print (eval(translation_counter), ast.literal_eval(location.replace('_', r'\_')))
  File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ast.py", line 46, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 1
    defaultdict(<class 'set'>, {'protection': {'1058c\_204062v\_00:39:16->00:39:18\_ko'}, 'protect': {'50c\_45523v\_00:01:22->00:01:24\_ko', '5457c\_150765v\_00:08:34->00:08:37\_ko', '5457c\_144739v\_00:34:25->00:34:28\_ko', '1058c\_204062v\_00:39:36->00:39:39\_ko', '504c\_68856v\_00:15:47->00:15:49\_ko'}})
                ^
SyntaxError: invalid syntax

The full code:

# -*- coding: utf-8 -*-

from collections import defaultdict, Counter
import ast

with open('related.txt', 'r', encoding='utf8') as fin:
    for line in fin:
        location = line.strip()
        print (eval(location))

And the head -n1 related.txt looks like this:

defaultdict(<class 'set'>, {'protection': {'1058c_204062v_00:39:16->00:39:18_ko'}, 'protect': {'50c_45523v_00:01:22->00:01:24_ko', '5457c_150765v_00:08:34->00:08:37_ko', '5457c_144739v_00:34:25->00:34:28_ko', '1058c_204062v_00:39:36->00:39:39_ko', '504c_68856v_00:15:47->00:15:49_ko'}})

Body:
That's because <class 'set'> can not be eval'd.
You will need to extract the class from it

p = re.compile(r"^defaultdict\(<class '(\w+)'>")
c = p.findall(s)[0]

and then replace it with the name of the class

new_s = s.replace("<class '%s'>"% c, c)

That string should be able to eval with this result

defaultdict(set,
        {'protect': {'1058c_204062v_00:39:36->00:39:39_ko',
          '504c_68856v_00:15:47->00:15:49_ko',
          '50c_45523v_00:01:22->00:01:24_ko',
          '5457c_144739v_00:34:25->00:34:28_ko',
          '5457c_150765v_00:08:34->00:08:37_ko'},
         'protection': {'1058c_204062v_00:39:16->00:39:18_ko'}})