问:
Unable to build unity app - issue not clear
Need help when i am trying to build my unity project its giving below error.
But i could not rectify error due to same. Any help will be useful.

Error 1

```<code>Error: Failed to add D:\jbINTEG\Temp\StagingArea\bin\classes.dex

UnityEditor.HostView:OnGUI()
</code>```

Error 2

```<code>CommandInvokationFailure: Failed to build apk. See the Console for details.
C:/Program Files/Java/jdk1.8.0_121\bin\java.exe -Xmx2048M -Dcom.android.sdkmanager.toolsdir="C:/Program Files (x86)/Android/android-sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[
Error: Failed to add D:\jbINTEG\Temp\StagingArea\bin\classes.dex
]
stdout[

]
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.HostView:OnGUI()
</code>```

Error 3

```<code>Error building Player: CommandInvokationFailure: Failed to build apk. See the Console for details.
C:/Program Files/Java/jdk1.8.0_121\bin\java.exe -Xmx2048M -Dcom.android.sdkmanager.toolsdir="C:/Program Files (x86)/Android/android-sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[
Error: Failed to add D:\jbINTEG\Temp\StagingArea\bin\classes.dex
]
stdout[

]
</code>```

答:
Thank you all for thinking over to my question.

Got it working. Actually found issue.
Its related to antivirus in my machine. When i tried over building it for android platform. Kaspersky Antivrus was terminating packaging of apk via aapt tool.
So at the end above issue was coming over again and again.

As soon as i paused antivirus protection and rebuild unity project. Everything started working fine without any issue.

Body:
Need help when i am trying to build my unity project its giving below error.
But i could not rectify error due to same. Any help will be useful.

Error 1

Error: Failed to add D:\jbINTEG\Temp\StagingArea\bin\classes.dex

UnityEditor.HostView:OnGUI()

Error 2

CommandInvokationFailure: Failed to build apk. See the Console for details.
C:/Program Files/Java/jdk1.8.0_121\bin\java.exe -Xmx2048M -Dcom.android.sdkmanager.toolsdir="C:/Program Files (x86)/Android/android-sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[
Error: Failed to add D:\jbINTEG\Temp\StagingArea\bin\classes.dex
]
stdout[

]
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.HostView:OnGUI()

Error 3

Error building Player: CommandInvokationFailure: Failed to build apk. See the Console for details.
C:/Program Files/Java/jdk1.8.0_121\bin\java.exe -Xmx2048M -Dcom.android.sdkmanager.toolsdir="C:/Program Files (x86)/Android/android-sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[
Error: Failed to add D:\jbINTEG\Temp\StagingArea\bin\classes.dex
]
stdout[

]


来源: stackexchange

问:
Spark dataset reduce with null values?
I'm creating data frame with this code:

```<code>  val data = List(
    List(444.1235D),
    List(67.5335D),
    List(69.5335D),
    List(677.5335D),
    List(47.5335D),
    List(null)
  )

  val rdd = sparkContext.parallelize(data).map(Row.fromSeq(_))
  val schema = StructType(Array(
    StructField("value", DataTypes.DoubleType, true)
  ))

  val df = sqlContext.createDataFrame(rdd, schema)
</code>```

Then I apply my udf to it:

```<code>val multip: Dataset[Double] = df.select(doubleUdf(df("value"))).as[Double]
</code>```

and then I'm trying to use reduce on this dataset:

```<code>val multipl = multip.reduce(_ * _)
</code>```

And here I got 0.0 as a result.
Also I tried to filter nulls out

```<code>val multipl = multip.filter(_ != null).reduce(_ * _)
</code>```

with the same result.
If I remove null value from data everything works as it should. How can I make reduce work with null values?

My udf is defined like this:

```<code>val doubleUdf: UserDefinedFunction = udf((v: Any) => Try(v.toString.toDouble).toOption)
</code>```

答:
First, I would ask why you are even dealing with null at all. I would evaluate the way I'm reading the data to ensure that doesn't happen.

Then I would note you can eliminate the null from your in-memory List before you even get to the RDD level like this for example:

data.flatMap(Option(_)).flatten

But if you must deal with null at the RDD level, you have options (no pun intended):

sparkContext.parallelize(data).filter(!_.contains(null))

or

sparkContext.parallelize(data).map(_.flatMap(Option(_))).filter(_.nonEmpty)

I prefer the latter. I don't like looking at null in Scala code.

I would stay away from a UDF-based solution since Spark can't optimize UDFs, and it is a shame to lose Spark's optimization capabilities over something as lame as null.

ContentLicense: CC BY-SA 3.0

Title: Spark dataset reduce with null values?

Body:
I'm creating data frame with this code:

  val data = List(
    List(444.1235D),
    List(67.5335D),
    List(69.5335D),
    List(677.5335D),
    List(47.5335D),
    List(null)
  )

  val rdd = sparkContext.parallelize(data).map(Row.fromSeq(_))
  val schema = StructType(Array(
    StructField("value", DataTypes.DoubleType, true)
  ))

  val df = sqlContext.createDataFrame(rdd, schema)

Then I apply my udf to it:

val multip: Dataset[Double] = df.select(doubleUdf(df("value"))).as[Double]

and then I'm trying to use reduce on this dataset:

val multipl = multip.reduce(_ * _)

And here I got 0.0 as a result.
Also I tried to filter nulls out

val multipl = multip.filter(_ != null).reduce(_ * _)

with the same result.
If I remove null value from data everything works as it should. How can I make reduce work with null values?

My udf is defined like this:

val doubleUdf: UserDefinedFunction = udf((v: Any) => Try(v.toString.toDouble).toOption)


问:
Average cells within a range updates automatically, based on row values
I have attached a sample file below. Can you help?

I'm looking for a formula to show the calculated average in cell B1 of the included sample, were the range (currently B2:B3) updates automatically when a new row is inserted at row 4 and the value 1.3 is shown in cell A4.

The range of the average formula in Cell B1, should update to show B2:B4... etc and continue to automatically update as new rows are added and additional numbers are added (1.4 in cell A5, average range updates to B2:B5, 1.5 in A6, average range updates to B2:B6 and so on...)

Thanks in advance for your help

Sample

答:
Okay, finally I got what you mean. But your sheet looks not very efficient. Why not set A1 to 1, and A2 to =A1+0.1, and so on? For now A column has very long formulae which is hard to read.

Anyway... to use averageif() on 1.1, 2.1, etc, it'll be easier to make A column to text. So add another column(say C) and set C1 to =text(a1, "#") and drag down. Now that C1 is text, you can use averageif() with wildcard(*). set B1 like this:

```<code>=AVERAGEIF(C2:C99, C1&"*", B2:B99)
</code>```

Of course, you should copy B1 and paste onto B4 and so on manually. Sample Excel file is here.

Body:
Okay, finally I got what you mean. But your sheet looks not very efficient. Why not set A1 to 1, and A2 to =A1+0.1, and so on? For now A column has very long formulae which is hard to read.

Anyway... to use averageif() on 1.1, 2.1, etc, it'll be easier to make A column to text. So add another column(say C) and set C1 to =text(a1, "#") and drag down. Now that C1 is text, you can use averageif() with wildcard(*). set B1 like this:

=AVERAGEIF(C2:C99, C1&"*", B2:B99)

Of course, you should copy B1 and paste onto B4 and so on manually. Sample Excel file is here.


问:
Is the order in which function arguments are resolved guaranteed?
say I have this:

function write3(a, b, c) {
  document.write(a + " " + b + " " + c);
}

var arr = [1, 2, 3];
var i = 0;

write3(arr[i++], arr[i++], arr[i++]);```

It results in 1 2 3 as expected, however, I'm not sure that this is guaranteed behavior. Could the arguments passed to write3 hypothetically be resolved in any other order than left to right?

答:
Afterwords. If you use ES6 you can write:</p>

```<code>write3(...arr)
</code>```

Body:
say I have this:

function write3(a, b, c) {
  document.write(a + " " + b + " " + c);
}

var arr = [1, 2, 3];
var i = 0;

write3(arr[i++], arr[i++], arr[i++]);

It results in 1 2 3 as expected, however, I'm not sure that this is guaranteed behavior. Could the arguments passed to write3 hypothetically be resolved in any other order than left to right?

Body:
Afterwords. If you use ES6 you can write:

write3(...arr)


问:
Wrong variable posts via mysql_query
I have a table gquestions with columns id,answer,date. I'm trying to update string in table with this HTML form and PHP queries:

HTML

```<code><form action="/reply" method="post">
    <textarea name="answer"></textarea><br>
    <input type="submit" value="Reply">
</form>
</code>```

PHP

```<code>$p_answer = $_POST["answer"];
$time = time();
mysql_query("UPDATE gquestions SET answer='$p_answer' AND date='$time' WHERE id='1'");
echo "UPDATE gquestions SET answer='$p_answer' AND date='$time' WHERE id='1'";
</code>```

Okay, in form I'm typing in textarea Test and clicking Reply and get this result in page:

UPDATE gquestions SET answer='Test' AND date='1490982467' id='1'

but in table I get 0 instead of Test in answer column. Why I'm getting 0 in my column?

答:
update your code

```<code>UPDATE gquestions SET answer='Test' AND date='1490982467' id='1'
</code>```

to

```<code>UPDATE gquestions SET answer='Test' , date='1490982467' id='1'
</code>```

this is common format

```<code>  UPDATE table_name
  SET column1 = value1, column2 = value2, ...
  WHERE condition;
</code>```

Title: Wrong variable posts via mysql_query

Body:
I have a table gquestions with columns id,answer,date. I'm trying to update string in table with this HTML form and PHP queries:

HTML

<form action="/reply" method="post">
    <textarea name="answer"></textarea>

    <input type="submit" value="Reply">
</form>

PHP

$p_answer = $_POST["answer"];
$time = time();
mysql_query("UPDATE gquestions SET answer='$p_answer' AND date='$time' WHERE id='1'");
echo "UPDATE gquestions SET answer='$p_answer' AND date='$time' WHERE id='1'";

Okay, in form I'm typing in textarea Test and clicking Reply and get this result in page:

UPDATE gquestions SET answer='Test' AND date='1490982467' id='1'

but in table I get 0 instead of Test in answer column. Why I'm getting 0 in my column?

Body:
update your code

UPDATE gquestions SET answer='Test' AND date='1490982467' id='1'

to

UPDATE gquestions SET answer='Test' , date='1490982467' id='1'

this is common format

  UPDATE table_name
  SET column1 = value1, column2 = value2, ...
  WHERE condition;


问:
Understanding MapReduce in Hadoop 1.x
I am bit confused on what does the term "MapReduce" with respect to Hadoop 1.x. With respect to this, I come across various terms like: JobTracker , TaskTracker (the daemons in MapReduce). Now when we say MapReduce does it refer to these daemons  or the API which a developer uses to code MapReduce applications?

Does the user application execute on TaskTracker , JobTracker? Is MapReduce itself a run-time environment?

Can anyone please help me understand this in simple words?

答:
MapReduce is the programming model for data processing (in Hadoop).

Its implementation in Hadoop-1.x is often referred as the Classic MapReduce Implementation (or MapReduce v1) which uses JobTracker and TaskTrackers of Hadoop for the execution of Jobs and its corresponding APIs (user-facing client-side features) for writing them.

JobTracker coordinates the Job run.

TaskTrackers run the tasks that the job has been split into.

To sum up, the MapReduce APIs determine how the MapReduce programming model has to be written whereas the Implementation determine how the Job written using this programming model is executed.

The YARN implementation (MapReduce v2) of MapReduce programming model differs in its APIs used for writing it and the daemons (ResourceManager, ApplicationMaster and NodeManagers) used for execution.

Title: Understanding MapReduce in Hadoop 1.x


问:
Robot - Move Mouse to Position with RGB Value
I'm currently using the Java Robot class to move mouse to coordinates:

```<code>Robot bot = new Robot();

bot.mouseMove(x, y);
</code>```

The issue is that I need to move mouse to a coordinate in order to click on a specific button in popup window and the window can move from one position to another each time it appears (it is not always in the same position). (In my specific case I'm sending Ctrl + P to Notepad and then clicking the "Print" button in popup window).

I was thinking of retrieving the RGB value of the button I want to click via:

```<code>Color color = bot.getPixelColor( MouseInfo.getPointerInfo().getLocation().x
                    , MouseInfo.getPointerInfo().getLocation().y);

System.out.println(color.getRGB());
</code>```

and then somehow moving the mouse to the position with the given RGB value but I am not exactly sure how to implement this.

Or is there an alternative solution that I did not think of?

Thanks!

Update:

I realized that moving mouse using RGB value may not be the best solution bec if there's more than one coordinate with the same RGB value it could detect the wrong point.. is there a way around this?

答:
The only solution I thought was a kind of screen scan looking for the desired color, and then you have to decide to where the mouse pointer has to move.

But scanning pixel by pixel would take a lot of time, so you may want to skip some pixels. Here's the solution I've come out:

```<code>//Look for some color on Screen, skiping or not a value of pixels
    public static void scanScreen(Color matchColor, int skipPixel){

        try {
            Robot r = new Robot();

            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            double width = screenSize.getWidth();
            double height = screenSize.getHeight();

            //Scan the screen pixel by pixel
            for(int pixelX = 0; pixelX<= width;pixelX = pixelX + skipPixel){
                for(int pixelY = 0; pixelY<=height;pixelY = pixelY + skipPixel){

                    Color currentColor = r.getPixelColor(pixelX, pixelY);
                    System.out.println(pixelX+","+pixelY+": " + currentColor.getRGB());
                    if(matchColor.getRGB()==currentColor.getRGB()){
                        //TODO Do whatever you want with the location found

                        System.out.println("Found color: " + matchColor.getRGB() + " at "+ pixelX + ","+pixelY);
                    }

                }
            }
        } catch (AWTException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

public static void main(String[] args) {
            Color c = new Color(-1972490);
            scanScreen(c, 100);
    }
</code>```

Hope it helps. Good luck!

EDIT1: You can use this solution along with what Jorge Campos suggested in his comment.

Body:
I'm currently using the Java Robot class to move mouse to coordinates:

Robot bot = new Robot();

bot.mouseMove(x, y);

The issue is that I need to move mouse to a coordinate in order to click on a specific button in popup window and the window can move from one position to another each time it appears (it is not always in the same position). (In my specific case I'm sending Ctrl + P to Notepad and then clicking the "Print" button in popup window).

I was thinking of retrieving the RGB value of the button I want to click via:

Color color = bot.getPixelColor( MouseInfo.getPointerInfo().getLocation().x
                    , MouseInfo.getPointerInfo().getLocation().y);

System.out.println(color.getRGB());

and then somehow moving the mouse to the position with the given RGB value but I am not exactly sure how to implement this.

Or is there an alternative solution that I did not think of?

Thanks!

Update:

I realized that moving mouse using RGB value may not be the best solution bec if there's more than one coordinate with the same RGB value it could detect the wrong point.. is there a way around this?

Body:
The only solution I thought was a kind of screen scan looking for the desired color, and then you have to decide to where the mouse pointer has to move.

But scanning pixel by pixel would take a lot of time, so you may want to skip some pixels. Here's the solution I've come out:

//Look for some color on Screen, skiping or not a value of pixels
    public static void scanScreen(Color matchColor, int skipPixel){

        try {
            Robot r = new Robot();

            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            double width = screenSize.getWidth();
            double height = screenSize.getHeight();

            //Scan the screen pixel by pixel
            for(int pixelX = 0; pixelX<= width;pixelX = pixelX + skipPixel){
                for(int pixelY = 0; pixelY<=height;pixelY = pixelY + skipPixel){

                    Color currentColor = r.getPixelColor(pixelX, pixelY);
                    System.out.println(pixelX+","+pixelY+": " + currentColor.getRGB());
                    if(matchColor.getRGB()==currentColor.getRGB()){
                        //TODO Do whatever you want with the location found

                        System.out.println("Found color: " + matchColor.getRGB() + " at "+ pixelX + ","+pixelY);
                    }

                }
            }
        } catch (AWTException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

public static void main(String[] args) {
            Color c = new Color(-1972490);
            scanScreen(c, 100);
    }

Hope it helps. Good luck!

EDIT1: You can use this solution along with what Jorge Campos suggested in his comment.


问:
How to pass arguments automatically in LiveScript
How I can simplify line 3 (onChange property):</p>

```<code>Input do
  name: \input
  onChange: (event, value) ~> @limitInput { type: \string }, event, value
</code>```

答:
You can use a bound partial application, documented here. Example:</p>

```<code>Input do
  name: \input
  onChange: @~limitInput({type: \string}, _, _)
</code>```

Body:
How I can simplify line 3 (onChange property):

Input do
  name: \input
  onChange: (event, value) ~> @limitInput { type: \string }, event, value

Body:
You can use a bound partial application, documented here. Example:

Input do
  name: \input
  onChange: @~limitInput({type: \string}, _, _)


问:
Best way to storage positions after click in button inside Recycler View
I have Recycler View like in this picture.
After click to button (B in picture) i want to get position id and storage this positions in best possible way to access and list data in other activity. After all I want to send all positions in ArrayList (for example) by Retrofit to backend.

Any solution?

答:
First make one callback listener like   btnClickedListener

Set it through RecyclerView Adapter and implement it to the activity with position parameter

Then make an array list of positions in the activity and send it to the next activity by using Gson or String

ContentLicense: CC BY-SA 4.0


问:
How to call a function from within another function?
I am creating a simple GUI program to manage priorities. I am having troubles with accessing a function from within another function. In my program, I tried to create an instance of the GuiPart class and then calling g.addItem but it doesn't seem to work like that. I am getting an error:

```<code>/usr/bin/python3.5 /home/cali/PycharmProjects/priorities/priorities.py
Traceback (most recent call last):
 File "/home/cali/PycharmProjects/priorities/priorities.py", line 70, in > <module>
   g.display()
 File "/home/cali/PycharmProjects/priorities/priorities.py", line 39, in > display
   command = g.addItem)
 File "/usr/lib/python3.5/tkinter/__init__.py", line 2077, in grid_configure
   + self._options(cnf, kw))
_tkinter.TclError: bad option "-command": must be -column, -columnspan, -in, > -ipadx, -ipady, -padx, -pady, -row, -rowspan, or -sticky
</code>```

Here is what I have done:

```<code># priorities.py
#   GUI program to manage priorities

from tkinter import *

class Priority:

    def __init__(self, subject, priority):
        self.subject = subject
        self.priority = priority

    def subject(self):
        return self.subject

    def priority(self):
        return self.priority

class GuiPart:

    def __init__(self):
        self.root = self.createWindow()

    def createWindow(self):

        root = Tk()
        root.resizable(width = False, height = False)
        root.title("Priorities")

        return root

    def createWidgets(self):

        listBox = Listbox().grid(row=1)

        buttonAdd = Button(text = "Add").grid(row = 2,
                                  column = 0,
                                  sticky = W,
                                  command = g.addItem)

        buttonRemove = Button(text="Remove").grid(row = 2,
                                   column = 0,
                                   sticky = W,
                                   command = g.removeItem)

        buttonEdit = Button(text="Edit").grid(row = 2,
                                 column = 0,
                                 sticky = E,
                                 command = g.editItem)

        textBox = Text().grid(row = 3)

    def addItem(self, item):
        item = Priority(item.subject, item.priority)
        item.subject = g.textBox.get("1.0", 'end-1c')

        g.listBox.insert(END, self)

    def removeItem(self):
       pass

    def editItem(self):
        pass

class Client:
    pass

if __name__ == "__main__":
    g = GuiPart()
    g.createWidgets()
    g.root.mainloop()
</code>```

答:
See this:

```<code>buttonAdd = Button(text = "Add").grid(row = 2,
                             column = 0,
                             sticky = W,
                             command = g.addItem)
#                                   ^^^^^^^^^

buttonRemove = Button(text="Remove").grid(row = 2,
                             column = 0,
                             sticky = W,
                             command = g.removeItem)
#                                    ^^^^^^^^^^^^

buttonEdit = Button(text="Edit").grid(row = 2,
                            column = 0,
                            sticky = E,
                            command = g.editItem)
#                                   ^^^^^^^^^^
</code>```

You are not calling functions you are assigning them.
In order to call them you have to pass parameter to them.

A small example explaining what happened:

```<code>>>> id(print)
1769760
>>> some_var = print
>>> id(some_var)
1769760
>>> some_var
<built-in function print>
>>> some_var('we assigned the built-in function "print" to the variable
... some_var')
we assigned the built-in function "print" to the variable some_var
</code>```

Body:
I am creating a simple GUI program to manage priorities. I am having troubles with accessing a function from within another function. In my program, I tried to create an instance of the GuiPart class and then calling g.addItem but it doesn't seem to work like that. I am getting an error:

/usr/bin/python3.5 /home/cali/PycharmProjects/priorities/priorities.py
Traceback (most recent call last):
 File "/home/cali/PycharmProjects/priorities/priorities.py", line 70, in > <module>
   g.display()
 File "/home/cali/PycharmProjects/priorities/priorities.py", line 39, in > display
   command = g.addItem)
 File "/usr/lib/python3.5/tkinter/__init__.py", line 2077, in grid_configure
   + self._options(cnf, kw))
_tkinter.TclError: bad option "-command": must be -column, -columnspan, -in, > -ipadx, -ipady, -padx, -pady, -row, -rowspan, or -sticky

Here is what I have done:

# priorities.py
#   GUI program to manage priorities

from tkinter import *

class Priority:

    def __init__(self, subject, priority):
        self.subject = subject
        self.priority = priority

    def subject(self):
        return self.subject

    def priority(self):
        return self.priority

class GuiPart:

    def __init__(self):
        self.root = self.createWindow()

    def createWindow(self):

        root = Tk()
        root.resizable(width = False, height = False)
        root.title("Priorities")

        return root

    def createWidgets(self):

        listBox = Listbox().grid(row=1)

        buttonAdd = Button(text = "Add").grid(row = 2,
                                  column = 0,
                                  sticky = W,
                                  command = g.addItem)

        buttonRemove = Button(text="Remove").grid(row = 2,
                                   column = 0,
                                   sticky = W,
                                   command = g.removeItem)

        buttonEdit = Button(text="Edit").grid(row = 2,
                                 column = 0,
                                 sticky = E,
                                 command = g.editItem)

        textBox = Text().grid(row = 3)

    def addItem(self, item):
        item = Priority(item.subject, item.priority)
        item.subject = g.textBox.get("1.0", 'end-1c')

        g.listBox.insert(END, self)

    def removeItem(self):
       pass

    def editItem(self):
        pass

class Client:
    pass

if __name__ == "__main__":
    g = GuiPart()
    g.createWidgets()
    g.root.mainloop()

Body:
See this:

buttonAdd = Button(text = "Add").grid(row = 2,
                             column = 0,
                             sticky = W,
                             command = g.addItem)
#                                   ^^^^^^^^^

buttonRemove = Button(text="Remove").grid(row = 2,
                             column = 0,
                             sticky = W,
                             command = g.removeItem)
#                                    ^^^^^^^^^^^^

buttonEdit = Button(text="Edit").grid(row = 2,
                            column = 0,
                            sticky = E,
                            command = g.editItem)
#                                   ^^^^^^^^^^

You are not calling functions you are assigning them.
In order to call them you have to pass parameter to them.

A small example explaining what happened:

>>> id(print)
1769760
>>> some_var = print
>>> id(some_var)
1769760
>>> some_var
<built-in function print>
>>> some_var('we assigned the built-in function "print" to the variable
... some_var')
we assigned the built-in function "print" to the variable some_var


问:
Sequlize.js: .update does not return affected rows
I need to change the status and get back the affected row:

```<code>db.Member.update({
            status: 0
        }, {
                where: {
                    id: member.id,
                    group_id: member.group_id,
                }
            }).then((updatedMember) => {
                console.log("Member" + updatedMember)
                // This returns 'Member 1',
                // and the in the DB, the status field does change to 0

            }).catch((err) => {
                console.log("err " + err)
            })
</code>```

inside the .then block, I get updatedMember as 1.  Also, if I change the status to something else that's not a field in the table, i.e. joe: 0, updatedMemberstill returns a 1.

Question:

Can .update return the affected object?

If I am trying to change a field that doesn't exist in the table, should I get an error?

答:
If you are using postgres, and only if, ...

According to the documentation (http://sequelize.readthedocs.io/en/v3/api/model/#updatevalues-options-promisearrayaffectedcount-affectedrows), the update function returns an array of two objects, the first is the number of affected rows, and the second is the actual affected row (but only if you are using postgres). If you are using mysql, it won't work.

Thus, I think you can change your code to the following and it should work:

```<code>db.Member.update({
        status: 0
    }, {
            where: {
                id: member.id,
                group_id: member.group_id,
            }
        }).then((updatedMember) => {

            //updatedMember[0] will now be 1, updatedMember[1] should be the affected row

            console.log("Member" + updatedMember[1])

        }).catch((err) => {
            console.log("err " + err)
        })
</code>```

Body:
I need to change the status and get back the affected row:

db.Member.update({
            status: 0
        }, {
                where: {
                    id: member.id,
                    group_id: member.group_id,
                }
            }).then((updatedMember) => {
                console.log("Member" + updatedMember)
                // This returns 'Member 1',
                // and the in the DB, the status field does change to 0

            }).catch((err) => {
                console.log("err " + err)
            })

inside the .then block, I get updatedMember as 1.  Also, if I change the status to something else that's not a field in the table, i.e. joe: 0, updatedMemberstill returns a 1.

Question:

Can .update return the affected object?

If I am trying to change a field that doesn't exist in the table, should I get an error?

Body:
If you are using postgres, and only if, ...

According to the documentation (http://sequelize.readthedocs.io/en/v3/api/model/#updatevalues-options-promisearrayaffectedcount-affectedrows), the update function returns an array of two objects, the first is the number of affected rows, and the second is the actual affected row (but only if you are using postgres). If you are using mysql, it won't work.

Thus, I think you can change your code to the following and it should work:

db.Member.update({
        status: 0
    }, {
            where: {
                id: member.id,
                group_id: member.group_id,
            }
        }).then((updatedMember) => {

            //updatedMember[0] will now be 1, updatedMember[1] should be the affected row

            console.log("Member" + updatedMember[1])

        }).catch((err) => {
            console.log("err " + err)
        })


答:
Let's take a look at part of your code...

```<code>    buttonAdd = Button(text = "Add").grid(row = 2,
                              column = 0,
                              sticky = W,
                              command = g.addItem)
</code>```

The primary problem here is that command is a parameter to the Button() constructor, not the .grid() method.  That's where your current error is coming from.

The second problem is that the value you're assigning to buttonAdd is the result of .grid() (which is always None), NOT the button itself.  If you actually need a reference to the button for later use (often, you don't), this would have to be split up into two statements:

```<code>    buttonAdd = Button(text = "Add", command = g.addItem)
    buttonAdd.grid(row = 2,
                   column = 0,
                   sticky = W)
</code>```

Title: How to call a function from within another function?

Body:
Let's take a look at part of your code...

    buttonAdd = Button(text = "Add").grid(row = 2,
                              column = 0,
                              sticky = W,
                              command = g.addItem)

The primary problem here is that command is a parameter to the Button() constructor, not the .grid() method.  That's where your current error is coming from.

The second problem is that the value you're assigning to buttonAdd is the result of .grid() (which is always None), NOT the button itself.  If you actually need a reference to the button for later use (often, you don't), this would have to be split up into two statements:

    buttonAdd = Button(text = "Add", command = g.addItem)
    buttonAdd.grid(row = 2,
                   column = 0,
                   sticky = W)


问:
Query sqlite every 10s vs using timeout vs node-cron
I have an sqlite flavor DB which contains one table, its has about 10k items with 5 columns. In one of the columns I have a 'timer' basically a number I have given and the purpose of it is to decrease it as time (ideally every second) goes by till it reaches zero. When it reaches zero I want to perform an action.

Thought process

1st: I can update my db for every item needed (probably for the 2k out of the 10k) every 10s (setInternal) -as to not stress it- and check whether any items reached zero. I am reluctant about this way as I feel it might not be so efficient.

2nd: Since I am on nodejs I can use timeouts. Read once my DB get all the wanted users, and for every one of them create a setTimeout method. After a minute or so update the DB, nested-setInternal Since each of the setTimeout take about 35bytes of the nodejs heap its not a bad method. -Right now I think this is the wat to go.

3rd: I found out this https://github.com/kelektiv/node-cron github, which basically is a task scheduler. After looking at its code for a bit I dont think its bad but I really dont think I have to use an external package here.

Note: Whatever of the above methods where I to use in case the process crashed they would be resetted (loses completely the point) without updating my DB periodically so I guess I cant avoid that.

Question: What should I do to efficiently update a timer in my DB every few seconds-(so all the time my process is alive)- without draining my resources?

Sorry to those that read the whole thing and feel they lost their time.

答:
Flow can be as follow

On Starting server one method is called which will check the timer field in table if found zero for any record it will just perform your operation. (use promise in operation).

When promise get over call another function and in that function wait for some second then again call previous function.

You can use recursive function calling with some time delay. This delay is just for reducing database load or deadlocks.


问:
Drupal: rogrammatically change file system path
Is there a way to change the files directory path, using a function from the drupal api?

Thanks in advance,

—Albe

答: Not sure about this exactly, but the module http://drupal.org/project/uploadpath lets you specify a different upload directory per node type.</p>

ContentLicense: CC BY-SA 2.5


问:
Searching data inside multiple Apache-Kafka log files using DumpLogSegments
Background

Need to search data for validation in kafka log files. Not trying to use command line consumer.

Tool

Using Dump Log Segment Tool

Problem

The --files parameter requires file to be , separated

```<code>--files <file1, file2, ...>             REQUIRED: The comma separated list of
                                        data and index log files to be dumped
</code>```

Is there any way to look at all the files under a directory ? Tried *log but it looks only at first file in the directory.

Or

Scripting a small program is the only option ?

答:
I hacked up some random script which worked for my purpose.

Checking data per file

```<code>#!/bin/bash

dirname="$1"
tosearch="$2"
files=""

if [[ -s $dirname ]] ; then
    for filename in $(ls -d $dirname/*log); do
            count=$(bin/kafka-run-class.sh kafka.tools.DumpLogSegments --files "$filename" --print-data-log | grep "$tosearch" | wc -l)
            echo "$filename : $count"
    done
fi
</code>```

Checking data in all files collectively

```<code>#!/bin/bash

dirname="$1"
tosearch="$2"
files=""

if [[ -s $dirname ]] ; then
    for filename in $(ls -d $dirname/*log); do
            files+="$filename,"
    done
    newfiles=$(echo "$files" | sed 's/,$//')
    count=$(bin/kafka-run-class.sh kafka.tools.DumpLogSegments --files "$files" --print-data-log | grep "$tosearch" | wc -l)
    echo "$count"
fi
</code>```

Body:
Background

Need to search data for validation in kafka log files. Not trying to use command line consumer.

Tool

Using Dump Log Segment Tool

Problem

The --files parameter requires file to be , separated

--files <file1, file2, ...>             REQUIRED: The comma separated list of
                                        data and index log files to be dumped

Is there any way to look at all the files under a directory ? Tried *log but it looks only at first file in the directory.

Or

Scripting a small program is the only option ?

Body:
I hacked up some random script which worked for my purpose.

Checking data per file

#!/bin/bash

dirname="$1"
tosearch="$2"
files=""

if [[ -s $dirname ]] ; then
    for filename in $(ls -d $dirname/*log); do
            count=$(bin/kafka-run-class.sh kafka.tools.DumpLogSegments --files "$filename" --print-data-log | grep "$tosearch" | wc -l)
            echo "$filename : $count"
    done
fi

Checking data in all files collectively

#!/bin/bash

dirname="$1"
tosearch="$2"
files=""

if [[ -s $dirname ]] ; then
    for filename in $(ls -d $dirname/*log); do
            files+="$filename,"
    done
    newfiles=$(echo "$files" | sed 's/,$//')
    count=$(bin/kafka-run-class.sh kafka.tools.DumpLogSegments --files "$files" --print-data-log | grep "$tosearch" | wc -l)
    echo "$count"
fi


问:
Tkinter, pause after select Combobox
I am trying to create a ttk.Combobox. After user select one value, the drop down list will disappear and pause for one second before showing the result.

I tried x.after(1000) on several different location. It will be either a pause when GUI opens or a pause on drop down list (i.e the drop down list will not disappear until 1000 ms).

Is it possible to pause after the value is selected and drop down disappeared?

```<code>import tkinter as tk
from tkinter import ttk

class App():

    def __init__(self, root):

        # Main Frame
        frame = ttk.Frame(root)
        frame.grid(column=0, row=0, sticky='WESN')

        self.test_lf = ttk.LabelFrame(frame, text='Test')
        self.test_lf.grid(column=0, row=0, padx=5, sticky='WE')

        self.selection = tk.StringVar()
        self.selection.trace('w', self.result)

        options = ttk.Combobox(self.test_lf, textvariable=self.selection, width=10)
        options['values'] = ('A', 'B', 'C')
        options.grid(column=0, row=0, sticky='WE', columnspan=2)
        # options.after(1000)    # Pause when open

        result_label = ttk.Label(self.test_lf, text='Result:')
        result_label.grid(column=0, row=2, sticky='W')

    def result(self, *args):
        selection_value=self.selection.get()
        selection_result = ttk.Label(self.test_lf, text=selection_value)
        selection_result.grid(column=1, row=2)
        # selection_result.after(1000) # Pause on drop down list

root = tk.Tk()
root.title('Sample')
app = App(root)
root.mainloop()
</code>```

答:
You have the right idea, you just need to give the after method the code to run to show the result.

```<code>import tkinter as tk
from tkinter import ttk

class App(ttk.Frame):
    def __init__(self, root):
        ttk.Frame.__init__(self, root) # this class is itself the main frame

        self.test_lf = ttk.LabelFrame(self, text='Test')
        self.test_lf.grid(column=0, row=0, padx=5, sticky='WE')

        self.selection = tk.StringVar()
        self.selection.trace('w', self.result)

        options = ttk.Combobox(self.test_lf, textvariable=self.selection, width=10)
        options['values'] = ('A', 'B', 'C')
        options.grid(column=0, row=0, sticky='WE', columnspan=2)

        result_label = ttk.Label(self.test_lf, text='Result:')
        result_label.grid(column=0, row=2, sticky='W')

        self.selection_result = ttk.Label(self.test_lf)
        self.selection_result.grid(column=1, row=2)

    def result(self, *args):
        self.after(1000, self.show_result)

    def show_result(self, *args):
        selection_value=self.selection.get()
        self.selection_result.config(text=selection_value)

root = tk.Tk()
root.title('Sample')
app = App(root)
app.grid(column=0, row=0, sticky='WESN')
root.mainloop()
</code>```

I also made some other improvements to your code that you should use, like subclassing Frame and updating a variable, not creating a new one, when something changes.

Title: Tkinter, pause after select Combobox

Body:
I am trying to create a ttk.Combobox. After user select one value, the drop down list will disappear and pause for one second before showing the result.

I tried x.after(1000) on several different location. It will be either a pause when GUI opens or a pause on drop down list (i.e the drop down list will not disappear until 1000 ms).

Is it possible to pause after the value is selected and drop down disappeared?

import tkinter as tk
from tkinter import ttk

class App():

    def __init__(self, root):

        # Main Frame
        frame = ttk.Frame(root)
        frame.grid(column=0, row=0, sticky='WESN')

        self.test_lf = ttk.LabelFrame(frame, text='Test')
        self.test_lf.grid(column=0, row=0, padx=5, sticky='WE')

        self.selection = tk.StringVar()
        self.selection.trace('w', self.result)

        options = ttk.Combobox(self.test_lf, textvariable=self.selection, width=10)
        options['values'] = ('A', 'B', 'C')
        options.grid(column=0, row=0, sticky='WE', columnspan=2)
        # options.after(1000)    # Pause when open

        result_label = ttk.Label(self.test_lf, text='Result:')
        result_label.grid(column=0, row=2, sticky='W')

    def result(self, *args):
        selection_value=self.selection.get()
        selection_result = ttk.Label(self.test_lf, text=selection_value)
        selection_result.grid(column=1, row=2)
        # selection_result.after(1000) # Pause on drop down list

root = tk.Tk()
root.title('Sample')
app = App(root)
root.mainloop()

Body:
You have the right idea, you just need to give the after method the code to run to show the result.

import tkinter as tk
from tkinter import ttk

class App(ttk.Frame):
    def __init__(self, root):
        ttk.Frame.__init__(self, root) # this class is itself the main frame

        self.test_lf = ttk.LabelFrame(self, text='Test')
        self.test_lf.grid(column=0, row=0, padx=5, sticky='WE')

        self.selection = tk.StringVar()
        self.selection.trace('w', self.result)

        options = ttk.Combobox(self.test_lf, textvariable=self.selection, width=10)
        options['values'] = ('A', 'B', 'C')
        options.grid(column=0, row=0, sticky='WE', columnspan=2)

        result_label = ttk.Label(self.test_lf, text='Result:')
        result_label.grid(column=0, row=2, sticky='W')

        self.selection_result = ttk.Label(self.test_lf)
        self.selection_result.grid(column=1, row=2)

    def result(self, *args):
        self.after(1000, self.show_result)

    def show_result(self, *args):
        selection_value=self.selection.get()
        self.selection_result.config(text=selection_value)

root = tk.Tk()
root.title('Sample')
app = App(root)
app.grid(column=0, row=0, sticky='WESN')
root.mainloop()

I also made some other improvements to your code that you should use, like subclassing Frame and updating a variable, not creating a new one, when something changes.


问:
about synchronization with two threads
Say one singleton instance accessed by two threads. Two threads are accessing the same function called doTask().

```<code>public class MySingleton {
    Object lock = new Object();
    // I omit the constructor here.

    public void doTask() {
         //first non-synchronized code

         synchronize(lock) {
             //some heavy task
         }

         //final non-synchronized code
    }
}
</code>```

If thread B is doing the heavy task, when thread A access doTask(), I know Thread A will run the //first non-synchronized code, then thread A noticed the lock is acquired by Thread B, so it can't run synchronized //some heavy task. But would thread A skip the synchronized heavy task continue run //final non-synchronized code or will thread A wait for the lock without even executing the //final non-synchronized code?

(I know I can try it out, but currently I don't have a proper development environment...)

答: When one thread acquires the monitor of synchronous object, then the remaining threads will also try to acquire it and this process is termed as POLLING. Because all the remaining threads try to acquire the monitor of that object by repeatedly checking the monitor lock status. The moment when the lock is released it can be acquired by any thread. It's actually decided by the scheduler.</p>

Title: about synchronization with two threads

Body:
Say one singleton instance accessed by two threads. Two threads are accessing the same function called doTask().

public class MySingleton {
    Object lock = new Object();
    // I omit the constructor here.

    public void doTask() {
         //first non-synchronized code

         synchronize(lock) {
             //some heavy task
         }

         //final non-synchronized code
    }
}

If thread B is doing the heavy task, when thread A access doTask(), I know Thread A will run the //first non-synchronized code, then thread A noticed the lock is acquired by Thread B, so it can't run synchronized //some heavy task. But would thread A skip the synchronized heavy task continue run //final non-synchronized code or will thread A wait for the lock without even executing the //final non-synchronized code?

(I know I can try it out, but currently I don't have a proper development environment...)


问:
printing out the number of times a number repeats itself in an Array (ArrayIndexOutofBoundException)
what I'm trying to do is filling an array of 20 integers with random numbers, and then printing out the number of times each integer repeats itself. I'm getting an error when trying to print out the number of repetitions... Here's my code:

```<code>package nivel3;

import java.util.Random;

public class exercicio3 {

    public static void main(String[] args) {
        int[] numeros;
        int i=0;

        numeros=new int[20];

        Random rand=new Random();
        System.out.println("FILLING ARRAY WITH 20 RANDOM INTEGERS (FROM 0-9) \n");
        do {
            for (i=0; i<20; i++) {
                numeros[i]=rand.nextInt(10);
                System.out.printf("position"+i+of numeros[20]: "+numeros[i]+"\n\n");
            }
        } while (i<20);

        System.out.println("--------------------------------------------------------------------- \n");
        System.out.println("SHOWING THE REPEATED POSITIONS (FOR EACH POSITION OF THE ARRAY)\n");

            for(int j=0; j<20; j++) {
                int k=0;
                do {
                    k++;
                    if (numeros[j]==numeros[k])
                        System.out.printf("the integer in the ["+j+"] position is equal to the integer in the ["+k+"] position \n");

                }while (k<20);
           }
    }
}
</code>```

Here's the error code:

```<code>Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
    at nivel3.exercicio3.main(exercicio3.java:29)
</code>```

答:
I see two problems here.

The first one is that this has no sense for me.

```<code>do {
    for (i=0; i<20; i++) {
        numeros[i]=rand.nextInt(10);
        System.out.printf("position"+i+of numeros[20]: "+numeros[i]+"\n\n");
    }
} while (i<20);
</code>```

You should do only the "for".

The second problem I see is that line "k++" should be under the "if". Remember arrays starts from 0 to size-1 (this means you can access from numeros[0] to numeros[19]).

So in your code, when k = 19, it enters again to the for, then you add +1 so k =20.. and numeros[20] this throws ArrayIndexOutOfBoundsException

Body:
what I'm trying to do is filling an array of 20 integers with random numbers, and then printing out the number of times each integer repeats itself. I'm getting an error when trying to print out the number of repetitions... Here's my code:

package nivel3;

import java.util.Random;

public class exercicio3 {

    public static void main(String[] args) {
        int[] numeros;
        int i=0;

        numeros=new int[20];

        Random rand=new Random();
        System.out.println("FILLING ARRAY WITH 20 RANDOM INTEGERS (FROM 0-9) \n");
        do {
            for (i=0; i<20; i++) {
                numeros[i]=rand.nextInt(10);
                System.out.printf("position"+i+of numeros[20]: "+numeros[i]+"\n\n");
            }
        } while (i<20);

        System.out.println("--------------------------------------------------------------------- \n");
        System.out.println("SHOWING THE REPEATED POSITIONS (FOR EACH POSITION OF THE ARRAY)\n");

            for(int j=0; j<20; j++) {
                int k=0;
                do {
                    k++;
                    if (numeros[j]==numeros[k])
                        System.out.printf("the integer in the ["+j+"] position is equal to the integer in the ["+k+"] position \n");

                }while (k<20);
           }
    }
}

Here's the error code:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
    at nivel3.exercicio3.main(exercicio3.java:29)

Body:
I see two problems here.

The first one is that this has no sense for me.

do {
    for (i=0; i<20; i++) {
        numeros[i]=rand.nextInt(10);
        System.out.printf("position"+i+of numeros[20]: "+numeros[i]+"\n\n");
    }
} while (i<20);

You should do only the "for".

The second problem I see is that line "k++" should be under the "if". Remember arrays starts from 0 to size-1 (this means you can access from numeros[0] to numeros[19]).

So in your code, when k = 19, it enters again to the for, then you add +1 so k =20.. and numeros[20] this throws ArrayIndexOutOfBoundsException


问:
Why would I get a "Promise is not defined." error on Node v5.7.0
Im using autoprefixer with postcss and after moving to a new linux server something must be wrong but I cant figure out what this one could be. I'm getting the error:

```<code>/home/ec2-user/Enviziion/Muveoo/Server/node_modules/postcss/lib/lazy-result.js:157
        this.processing = new Promise(function (resolve, reject) {
                              ^
ReferenceError: Promise is not defined
</code>```

Which is triggered by:

```<code>var autoprefixer = require('autoprefixer');
var postCSS = require('postcss');

function prefix(css, res, type, fullPath) {
    postCSS([autoprefixer]).process(css).then(function(result) {
        var css = result.css;
        var length = css.length;
        res.writeHead(200, {
            'Content-Length' : length,
            'Content-Type' : type
        });
        res.write(css);
        res.end();
    });
}
</code>```

I researched this problem but all of the occurrences of the issue seem to be for extremely early versions of node.js, for example:

Native Support for Promises in Node.js

https://github.com/postcss/postcss-nested/issues/30

And the solution always seems to be "Update Node".

But mine seems to be up to date:

```<code>[ec2-user@ip-172-31-22-79 Server]$ node -v
v5.7.0
</code>```

What might my issue be here?

答: Upgrading node to latest version(v4.5.0) did resolved this issue.</p>

Body:
Im using autoprefixer with postcss and after moving to a new linux server something must be wrong but I cant figure out what this one could be. I'm getting the error:

/home/ec2-user/Enviziion/Muveoo/Server/node_modules/postcss/lib/lazy-result.js:157
        this.processing = new Promise(function (resolve, reject) {
                              ^
ReferenceError: Promise is not defined

Which is triggered by:

var autoprefixer = require('autoprefixer');
var postCSS = require('postcss');

function prefix(css, res, type, fullPath) {
    postCSS([autoprefixer]).process(css).then(function(result) {
        var css = result.css;
        var length = css.length;
        res.writeHead(200, {
            'Content-Length' : length,
            'Content-Type' : type
        });
        res.write(css);
        res.end();
    });
}

I researched this problem but all of the occurrences of the issue seem to be for extremely early versions of node.js, for example:

Native Support for Promises in Node.js

https://github.com/postcss/postcss-nested/issues/30

And the solution always seems to be "Update Node".

But mine seems to be up to date:

[ec2-user@ip-172-31-22-79 Server]$ node -v
v5.7.0

What might my issue be here?


问:
Update html meteor?
I am trying to output an estimated time based off the number of items (people) within my database (this is a wait list). Currently I save a value in the quick form called countNumber. This is just set to 1 everytime. I then get the count of all the items by finding the all items that have countNumber = 1 (all of them). I then try updating the html using getElementById().

The problem I am having is that when I add a person to the database the estimated time will go up appropriately. However when I refresh the page the html resets to 0 like the initial html that is put in.

How do I fix this so that the html will always display the appropriate time even when the page is refreshed?

Html code:

```<code><head>
    <title>Wait List</title>
</head>

<template name= "home">
    <body>
        <h2 id="insert">Approximate Wait Time: 0 Minutes</h2>
        <div class="col-lg-6 col-lg-offset-3">
            {{>quickForm id="studentForm" collection="Students" type="insert" template="bootstrap3-horizontal" label-class="col-sm-3" input-col-class="col-sm-9"}}
        </div>
    </body>
</template>
</code>```

js code:

```<code>AutoForm.hooks({
    studentForm:
{
    onSuccess: function (insert,result) {
        var totalCount = Students.find({countNumber:1}).count();
        var waitTime = "Approximate Wait Time: " + totalCount*15 +" Minutes";
        document.getElementById("insert").innerHTML = waitTime;

        ...

    },
}
});
</code>```

答:
You should put this into a helper instead of a hook.

```<code>Template.home.helpers({
   waitTime: function(){
       var totalCount = Students.find({countNumber:1}).count();
       var waitTime = totalCount*15;
       return waitTime;
   }
});
</code>```

and change the
 line in the html to this.

```<code><h2 id="insert">Approximate Wait Time: {{waitTIme}} Minutes</h2>
</code>```

Title: Update html meteor?

Body:
I am trying to output an estimated time based off the number of items (people) within my database (this is a wait list). Currently I save a value in the quick form called countNumber. This is just set to 1 everytime. I then get the count of all the items by finding the all items that have countNumber = 1 (all of them). I then try updating the html using getElementById().

The problem I am having is that when I add a person to the database the estimated time will go up appropriately. However when I refresh the page the html resets to 0 like the initial html that is put in.

How do I fix this so that the html will always display the appropriate time even when the page is refreshed?

Html code:

    <title>Wait List</title>

<template name= "home">

Approximate Wait Time: 0 Minutes

            {{>quickForm id="studentForm" collection="Students" type="insert" template="bootstrap3-horizontal" label-class="col-sm-3" input-col-class="col-sm-9"}}

</template>

js code:

AutoForm.hooks({
    studentForm:
{
    onSuccess: function (insert,result) {
        var totalCount = Students.find({countNumber:1}).count();
        var waitTime = "Approximate Wait Time: " + totalCount*15 +" Minutes";
        document.getElementById("insert").innerHTML = waitTime;

        ...

    },
}
});

Body:
You should put this into a helper instead of a hook.

Template.home.helpers({
   waitTime: function(){
       var totalCount = Students.find({countNumber:1}).count();
       var waitTime = totalCount*15;
       return waitTime;
   }
});

and change the <h2> line in the html to this.

<h2 id="insert">Approximate Wait Time: {{waitTIme}} Minutes</h2>


问:
Java-Abstract method not overridden
Can you help with one of the true/false questions asked in my test today:

If an abstract method is inherited by a subclass but is not overridden the whole subclass becomes abstract. Would this be true or false?

答:
Just because it's true/false doesn't mean you can't attach an explanation.  Assuming your teacher knows what he is doing and is fair (which might not be a valid assumption) then a clear explanation of why you chose the answer you did would probably help.  If the test is online or scantron and you can't put an explanation right in the margins of the test itself, send him an email.

I would choose "true" with the explanation that it doesn't actually make the class abstract, but it does make it necessary that the class be abstract.  If the teacher is looking for "true" on a poorly written question, then you've answered "true".  If the teacher is looking for "false" on a trick question, then you've shown that you've seen the trick.  I think this maximizes the chance that you'll get credit.

Title: Java-Abstract method not overridden


问:
Xamarin.Android CustomActionBar(Toolbar) Layout Issue
I've a very interesting issue about xamarin.android in toolbar.
I was created navigation drawer toggle without problem.

After this i need to popup menu so inflated popup menu in 'OnCreateOptionsMenu' of Activity.

Then i saw that problem

There is an image

Activity

```<code>    mToolbar = FindViewById<SupportToolbar>(Resource.Id.toolbar);
    mDrawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
        SetSupportActionBar(mToolbar);
        SupportActionBar.SetTitle(Resource.String.ApplicationName);

        mDrawerToggle = new MyActionBarDrawerToggleHelper(
            this,                           //Host Activity
            mDrawerLayout,                  //DrawerLayout
            Resource.String.openDrawer,     //Opened Message
            Resource.String.closeDrawer     //Closed Message
        );

        mDrawerLayout.AddDrawerListener(mDrawerToggle);
        SupportActionBar.SetDisplayHomeAsUpEnabled(true);
        SupportActionBar.SetDisplayShowTitleEnabled(false);
        SupportActionBar.SetHomeButtonEnabled(true);
        mDrawerToggle.SyncState();
</code>```

AXML

```<code>    <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
    android:layout_height="@dimen/abc_action_bar_default_height_material"
            android:background="@android:color/holo_blue_light"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Dark"
            android:minWidth="25px"
            android:minHeight="25px" />
</code>```

答:
Try to set these parameters instead:</p>

```<code>android:layout_height="?actionBarSize"
android:minHeight="?attr/actionBarSize"
</code>```

Body:
I've a very interesting issue about xamarin.android in toolbar.
I was created navigation drawer toggle without problem.

After this i need to popup menu so inflated popup menu in 'OnCreateOptionsMenu' of Activity.

Then i saw that problem

There is an image

Activity

    mToolbar = FindViewById<SupportToolbar>(Resource.Id.toolbar);
    mDrawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
        SetSupportActionBar(mToolbar);
        SupportActionBar.SetTitle(Resource.String.ApplicationName);

        mDrawerToggle = new MyActionBarDrawerToggleHelper(
            this,                           //Host Activity
            mDrawerLayout,                  //DrawerLayout
            Resource.String.openDrawer,     //Opened Message
            Resource.String.closeDrawer     //Closed Message
        );

        mDrawerLayout.AddDrawerListener(mDrawerToggle);
        SupportActionBar.SetDisplayHomeAsUpEnabled(true);
        SupportActionBar.SetDisplayShowTitleEnabled(false);
        SupportActionBar.SetHomeButtonEnabled(true);
        mDrawerToggle.SyncState();

AXML

    <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
    android:layout_height="@dimen/abc_action_bar_default_height_material"
            android:background="@android:color/holo_blue_light"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Dark"
            android:minWidth="25px"
            android:minHeight="25px" />

Body:
Try to set these parameters instead:

android:layout_height="?actionBarSize"
android:minHeight="?attr/actionBarSize"


问:
Auto remove class seconds after it becomes active
I have a script working so that the background image of a div switches at a certain distance from the top of the page. What I want is for it to switch back to the original after say 2 seconds.

The following removes the class 170px later:

```<code><script>
jQuery(document).scroll(function(){
var fromTopPx = 2800; // distance to trigger
var scrolledFromtop = jQuery(document).scrollTop();
if(scrolledFromtop > fromTopPx){
    jQuery('#image').addClass('scrolled');
}else{
    jQuery('#image').removeClass('scrolled');
}
var fromTopPx = 2970; // distance to trigger
var scrolledFromtop = jQuery(document).scrollTop();
if(scrolledFromtop > fromTopPx){
    jQuery('#image').removeClass('scrolled');
}
});
</script>
</code>```

but I was hoping for it to switch back automatically:

```<code><script>
jQuery(document).scroll(function(){
var fromTopPx = 2800; // distance to trigger
var scrolledFromtop = jQuery(document).scrollTop();
if(scrolledFromtop > fromTopPx){
    jQuery('#neediioneimg').addClass('scrolled');
}else{
    jQuery('#neediioneimg').removeClass('scrolled');
}
setTimeout(function(){
$('.scrolled').removeClass('scrolled');
},2000);
});
</script>
</code>```

I'm not sure about the setTimout part, does anyone have an idea?

答:
So what's the question? Does this code work? Yes. Does this code work properly? No. It will set a new timeout many and many times while you scroll the page, it doesn't check if you're 2800px from top, or if class if set, or if another timeout is in the queue, it will just set a new timeout every pixel of scroll. You should do something like that:

```<code><script>
  // did we got back if previously scrolled more than triggerDistance
  var readyToHandleScrolling = true;

  // save the timer
  var timer = undefined

  $(document).on('scroll', function(){
    // distance from top to react on
    var triggerDistance = 2800;

    // current distance from top
    var currentDistance = $(document).scrollTop();

    if (currentDistance >= triggerDistance) {
      // ignore if we haven't get above triggerDistance yet
      if (!readyToHandleScrolling) return;

      $('#neediioneimg').addClass('scrolled');

      timer = setTimeout(function(){
        $('#neediioneimg').removeClass('scrolled');
      }, 2000);

      readyToHandleScrolling = false;
    } else {
      // if we got above triggerDistance
      // clear timeout
      clearTimeout(timer);

      // remove class
      $('#neediioneimg').removeClass('scrolled');

      // show we are ready to handle a new event
      readyToHandleScrolling = true;
    }
  });
</script>
</code>```

Body:
I have a script working so that the background image of a div switches at a certain distance from the top of the page. What I want is for it to switch back to the original after say 2 seconds.

The following removes the class 170px later:

but I was hoping for it to switch back automatically:

I'm not sure about the setTimout part, does anyone have an idea?

Body:
So what's the question? Does this code work? Yes. Does this code work properly? No. It will set a new timeout many and many times while you scroll the page, it doesn't check if you're 2800px from top, or if class if set, or if another timeout is in the queue, it will just set a new timeout every pixel of scroll. You should do something like that:

<script>
  // did we got back if previously scrolled more than triggerDistance
  var readyToHandleScrolling = true;

  // save the timer
  var timer = undefined

  $(document).on('scroll', function(){
    // distance from top to react on
    var triggerDistance = 2800;

    // current distance from top
    var currentDistance = $(document).scrollTop();

    if (currentDistance >= triggerDistance) {
      // ignore if we haven't get above triggerDistance yet
      if (!readyToHandleScrolling) return;

      $('#neediioneimg').addClass('scrolled');

      timer = setTimeout(function(){
        $('#neediioneimg').removeClass('scrolled');
      }, 2000);

      readyToHandleScrolling = false;
    } else {
      // if we got above triggerDistance
      // clear timeout
      clearTimeout(timer);

      // remove class
      $('#neediioneimg').removeClass('scrolled');

      // show we are ready to handle a new event
      readyToHandleScrolling = true;
    }
  });
</script>


问:
Cannot convert from 'initializer-list' to UserController
I have this class:

```<code>class UserController
{
private:
    Repo repo;
    Repo adoption;
public:
    UserController(const Repo& r, const Repo& a) : repo(r), adoption(a) {}

    Dog get(int index) { return this->repo.get(index); };
};
</code>```

When I try to create an object of type UserController, like this:

```<code>UserController controller{ repo1, repo2 };
</code>```

it gives me the error: "error C2440: 'initializing' : cannot convert from 'initializer-list' to 'UserController'". Why?

答:
You need c++11 to compile this code.

Below I am compiling without C++11 support and with (which succeeds).

```<code>Georgioss-MacBook-Pro:~ gsamaras$ g++ main.cpp
main.cpp:14:20: error: no matching constructor for initialization of
      'UserController'
    UserController controller{ repo1, repo2 };
                   ^
main.cpp:2:7: note: candidate constructor (the implicit copy constructor) not
      viable: requires 1 argument, but 0 were provided
class UserController
      ^
main.cpp:8:5: note: candidate constructor not viable: requires 2 arguments, but
      0 were provided
    UserController(const Repo& r, const Repo& a) : repo(r), adoption(a) {}
    ^
main.cpp:14:30: error: expected ';' at end of declaration
    UserController controller{ repo1, repo2 };
                             ^
                             ;
2 errors generated.
Georgioss-MacBook-Pro:~ gsamaras$ g++ -std=c++0x main.cpp
Georgioss-MacBook-Pro:~ gsamaras$
</code>```

Body:
I have this class:

class UserController
{
private:
    Repo repo;
    Repo adoption;
public:
    UserController(const Repo& r, const Repo& a) : repo(r), adoption(a) {}

    Dog get(int index) { return this->repo.get(index); };
};

When I try to create an object of type UserController, like this:

UserController controller{ repo1, repo2 };

it gives me the error: "error C2440: 'initializing' : cannot convert from 'initializer-list' to 'UserController'". Why?

Body:
You need c++11 to compile this code.

Below I am compiling without C++11 support and with (which succeeds).

Georgioss-MacBook-Pro:~ gsamaras$ g++ main.cpp
main.cpp:14:20: error: no matching constructor for initialization of
      'UserController'
    UserController controller{ repo1, repo2 };
                   ^
main.cpp:2:7: note: candidate constructor (the implicit copy constructor) not
      viable: requires 1 argument, but 0 were provided
class UserController
      ^
main.cpp:8:5: note: candidate constructor not viable: requires 2 arguments, but
      0 were provided
    UserController(const Repo& r, const Repo& a) : repo(r), adoption(a) {}
    ^
main.cpp:14:30: error: expected ';' at end of declaration
    UserController controller{ repo1, repo2 };
                             ^
                             ;
2 errors generated.
Georgioss-MacBook-Pro:~ gsamaras$ g++ -std=c++0x main.cpp
Georgioss-MacBook-Pro:~ gsamaras$


问:
Automation of UPDATE of column-level statistics on Azure SQL Data Warehouse
I am planning to automate the refresh (i.e., UPDATE) of column level statistics on my Azure SQL Data Warehouse databases.  I plan to log the operations in a site-specific table and then dynamically generate SQL to refresh the statistics using the following approach:

DATE columns refreshed daily,

ID/code primary/foreign-key columns refreshed bi-weekly,

Indicator/boolean columns refreshed monthly, and

QTY/AMT (fact) columns refreshed quarterly.

I reviewed the STATS_DATE function at https://msdn.microsoft.com/library/ms190330.aspx, but this function does not appear to support the detail necessary for column-level statistics.  For example the output for one of my tables that has three columns which had statistics collected shows NULL for STATS_DATE:

```<code>SELECT
  s.object_id,
  s.name,
  s.stats_id,
  s.user_created,
  STATS_DATE(object_id, stats_id) AS statistics_date
FROM sys.stats s
where object_id = 107141;
</code>```

Returns

```<code>  object_id         name                   stats_id user_created statistics_date
 107,141            MySchema_MyTable_Col1         2         1          [NULL]
 107,141            MySchema_MyTable_Col2         3         1          [NULL]
 107,141            MySchema_MyTable_Col3         4         1          [NULL]
</code>```

Did I overlook or misunderstand this function and should I be able to use STATS_DATE to manage my columns' statistics?

Following is a more complete demonstration:

```<code> --Create a columnar demonstration table
 create table My_Schema.steve_test_table_columnar (c1_c integer, c2_c smallint,   c3_c date, c4_c decimal(18,2) ) ;
--Create a heap demonstration table
create table My_Schema.steve_test_table_heap (c1_h integer, c2_h smallint, c3_h date, c4_h decimal(18,2) ) with (HEAP) ;

-CREATE STATISTICS statements:
CREATE STATISTICS My_Schema_STEVE_TEST_TABLE_COLUMNAR_C1_C ON My_Schema.STEVE_TEST_TABLE_COLUMNAR ( C1_C ) ;
CREATE STATISTICS My_Schema_STEVE_TEST_TABLE_COLUMNAR_C2_C ON My_Schema.STEVE_TEST_TABLE_COLUMNAR ( C2_C ) ;
CREATE STATISTICS My_Schema_STEVE_TEST_TABLE_COLUMNAR_C3_C ON My_Schema.STEVE_TEST_TABLE_COLUMNAR ( C3_C ) ;
CREATE STATISTICS My_Schema_STEVE_TEST_TABLE_COLUMNAR_C4_C ON My_Schema.STEVE_TEST_TABLE_COLUMNAR ( C4_C ) ;
CREATE STATISTICS My_Schema_STEVE_TEST_TABLE_HEAP_C1_H ON My_Schema.STEVE_TEST_TABLE_HEAP ( C1_H ) ;
CREATE STATISTICS My_Schema_STEVE_TEST_TABLE_HEAP_C2_H ON My_Schema.STEVE_TEST_TABLE_HEAP ( C2_H ) ;
CREATE STATISTICS My_Schema_STEVE_TEST_TABLE_HEAP_C3_H ON My_Schema.STEVE_TEST_TABLE_HEAP ( C3_H ) ;
CREATE STATISTICS My_Schema_STEVE_TEST_TABLE_HEAP_C4_H ON My_Schema.STEVE_TEST_TABLE_HEAP ( C4_H ) ;

--UPDATE (aka "REFRESH") STATISTICS statements:
UPDATE STATISTICS My_Schema.STEVE_TEST_TABLE_COLUMNAR ( My_Schema_STEVE_TEST_TABLE_COLUMNAR_C3_C ) ;
UPDATE STATISTICS My_Schema.STEVE_TEST_TABLE_HEAP ( My_Schema_STEVE_TEST_TABLE_HEAP_C3_H ) ;
UPDATE STATISTICS My_Schema.STEVE_TEST_TABLE_COLUMNAR ( My_Schema_STEVE_TEST_TABLE_COLUMNAR_C2_C ) ;
UPDATE STATISTICS My_Schema.STEVE_TEST_TABLE_HEAP ( My_Schema_STEVE_TEST_TABLE_HEAP_C2_H ) ;
UPDATE STATISTICS My_Schema.STEVE_TEST_TABLE_COLUMNAR ( My_Schema_STEVE_TEST_TABLE_COLUMNAR_C1_C ) ;
UPDATE STATISTICS My_Schema.STEVE_TEST_TABLE_COLUMNAR ( My_Schema_STEVE_TEST_TABLE_COLUMNAR_C1_C ) ;
UPDATE STATISTICS My_Schema.STEVE_TEST_TABLE_HEAP ( My_Schema_STEVE_TEST_TABLE_HEAP_C1_H ) ;
UPDATE STATISTICS My_Schema.STEVE_TEST_TABLE_COLUMNAR ( My_Schema_STEVE_TEST_TABLE_COLUMNAR_C4_C ) ;
UPDATE STATISTICS My_Schema.STEVE_TEST_TABLE_HEAP ( My_Schema_STEVE_TEST_TABLE_HEAP_C4_H ) ;

--Validation Steps

select s.[schema_id] , s.[name] from sys.[schemas] s where s.[name] = 'My_Schema';

--Results:
schema_id name
24        My_Schema

--Get Table Object ID
select t.[object_id] , t.[name] from sys.[tables] t
inner join sys.[schemas] s
on t.[schema_id] = s.[schema_id]
where s.[name] = 'My_Schema' and t.[name]  in ('STEVE_TEST_TABLE_HEAP' , 'STEVE_TEST_TABLE_COLUMNAR');

--Results:
object_id   name
516,196,889 steve_test_table_columnar
532,196,946 steve_test_table_heap

--Get Columnd IDs
select t.[object_id] , c.[column_id], t.[name] , c.[name] as Column_Name
from
     sys.[tables] t
inner join
     sys.[schemas] s
on
     t.[schema_id] = s.[schema_id]
INNER JOIN
     sys.[columns] c
ON
     t.[object_id]       = c.[object_id]
where
     s.[name] = 'My_Schema'
 and t.[name]  in ('STEVE_TEST_TABLE_HEAP' , 'STEVE_TEST_TABLE_COLUMNAR')

--Results:
object_id   column_id   name                       Column_Name
516,196,889 1           steve_test_table_columnar   c1_c
516,196,889 2           steve_test_table_columnar   c2_c
516,196,889 3           steve_test_table_columnar   c3_c
516,196,889 4           steve_test_table_columnar   c4_c
532,196,946 1           steve_test_table_heap       c1_h
532,196,946 2           steve_test_table_heap       c2_h
532,196,946 3           steve_test_table_heap       c3_h
532,196,946 4           steve_test_table_heap       c4_h

--Final review of statistics metadata
select t.[object_id] , c.[column_id], t.[name] as table_name
, c.[name] as Column_Name  ,st.stats_id , st.name   as Stats_Name
,stc.stats_column_id
,STATS_DATE(st.object_id, st.stats_id) AS statistics_date
from
     sys.[tables] t
inner join
     sys.[schemas] s
on
     t.[schema_id] = s.[schema_id]
INNER JOIN
     sys.[columns] c
ON
     t.[object_id]       = c.[object_id]
INNER JOIN
     sys.stats st
ON
     st.[object_id]      = t.[object_id]
 and user_created = 1
INNER JOIN
  sys.[stats_columns] stc
on
     st.stats_id = stc.stats_id
 and st.[object_id] = stc.[object_id]
 and c.[column_id] = stc.[column_id]
where
     s.[name] = 'My_Schema'
 and t.[name]  in ('STEVE_TEST_TABLE_HEAP' , 'STEVE_TEST_TABLE_COLUMNAR')
 ;

object_id   column_id   table_name                  Column_Name stats_id    Stats_Name                                  stats_column_id statistics_date
516,196,889 1           steve_test_table_columnar   c1_c         2             My_Schema_STEVE_TEST_TABLE_COLUMNAR_C1_C 1               [NULL]
516,196,889 2           steve_test_table_columnar   c2_c         3             My_Schema_STEVE_TEST_TABLE_COLUMNAR_C2_C 1               [NULL]
516,196,889 3           steve_test_table_columnar   c3_c         4             My_Schema_STEVE_TEST_TABLE_COLUMNAR_C3_C 1               [NULL]
516,196,889 4           steve_test_table_columnar   c4_c         5             My_Schema_STEVE_TEST_TABLE_COLUMNAR_C4_C 1               [NULL]
532,196,946 1           steve_test_table_heap       c1_h         2             My_Schema_STEVE_TEST_TABLE_HEAP_C1_H     1               [NULL]
532,196,946 2           steve_test_table_heap       c2_h         3             My_Schema_STEVE_TEST_TABLE_HEAP_C2_H     1               [NULL]
532,196,946 3           steve_test_table_heap       c3_h         4             My_Schema_STEVE_TEST_TABLE_HEAP_C3_H     1               [NULL]
532,196,946 4           steve_test_table_heap       c4_h         5             My_Schema_STEVE_TEST_TABLE_HEAP_C4_H     1               [NULL]
</code>```

答: I confirmed that if the tables are loaded, the return value of STATS_DATE(id,id) is not null.  My experiment had involved only creating the tables.</p>

Body:
I am planning to automate the refresh (i.e., UPDATE) of column level statistics on my Azure SQL Data Warehouse databases.  I plan to log the operations in a site-specific table and then dynamically generate SQL to refresh the statistics using the following approach:

DATE columns refreshed daily,

ID/code primary/foreign-key columns refreshed bi-weekly,

Indicator/boolean columns refreshed monthly, and

QTY/AMT (fact) columns refreshed quarterly.

I reviewed the STATS_DATE function at https://msdn.microsoft.com/library/ms190330.aspx, but this function does not appear to support the detail necessary for column-level statistics.  For example the output for one of my tables that has three columns which had statistics collected shows NULL for STATS_DATE:

SELECT
  s.object_id,
  s.name,
  s.stats_id,
  s.user_created,
  STATS_DATE(object_id, stats_id) AS statistics_date
FROM sys.stats s
where object_id = 107141;

Returns

  object_id         name                   stats_id user_created statistics_date
 107,141            MySchema_MyTable_Col1         2         1          [NULL]
 107,141            MySchema_MyTable_Col2         3         1          [NULL]
 107,141            MySchema_MyTable_Col3         4         1          [NULL]

Did I overlook or misunderstand this function and should I be able to use STATS_DATE to manage my columns' statistics?

Following is a more complete demonstration:

 --Create a columnar demonstration table
 create table My_Schema.steve_test_table_columnar (c1_c integer, c2_c smallint,   c3_c date, c4_c decimal(18,2) ) ;
--Create a heap demonstration table
create table My_Schema.steve_test_table_heap (c1_h integer, c2_h smallint, c3_h date, c4_h decimal(18,2) ) with (HEAP) ;

-CREATE STATISTICS statements:
CREATE STATISTICS My_Schema_STEVE_TEST_TABLE_COLUMNAR_C1_C ON My_Schema.STEVE_TEST_TABLE_COLUMNAR ( C1_C ) ;
CREATE STATISTICS My_Schema_STEVE_TEST_TABLE_COLUMNAR_C2_C ON My_Schema.STEVE_TEST_TABLE_COLUMNAR ( C2_C ) ;
CREATE STATISTICS My_Schema_STEVE_TEST_TABLE_COLUMNAR_C3_C ON My_Schema.STEVE_TEST_TABLE_COLUMNAR ( C3_C ) ;
CREATE STATISTICS My_Schema_STEVE_TEST_TABLE_COLUMNAR_C4_C ON My_Schema.STEVE_TEST_TABLE_COLUMNAR ( C4_C ) ;
CREATE STATISTICS My_Schema_STEVE_TEST_TABLE_HEAP_C1_H ON My_Schema.STEVE_TEST_TABLE_HEAP ( C1_H ) ;
CREATE STATISTICS My_Schema_STEVE_TEST_TABLE_HEAP_C2_H ON My_Schema.STEVE_TEST_TABLE_HEAP ( C2_H ) ;
CREATE STATISTICS My_Schema_STEVE_TEST_TABLE_HEAP_C3_H ON My_Schema.STEVE_TEST_TABLE_HEAP ( C3_H ) ;
CREATE STATISTICS My_Schema_STEVE_TEST_TABLE_HEAP_C4_H ON My_Schema.STEVE_TEST_TABLE_HEAP ( C4_H ) ;

--UPDATE (aka "REFRESH") STATISTICS statements:
UPDATE STATISTICS My_Schema.STEVE_TEST_TABLE_COLUMNAR ( My_Schema_STEVE_TEST_TABLE_COLUMNAR_C3_C ) ;
UPDATE STATISTICS My_Schema.STEVE_TEST_TABLE_HEAP ( My_Schema_STEVE_TEST_TABLE_HEAP_C3_H ) ;
UPDATE STATISTICS My_Schema.STEVE_TEST_TABLE_COLUMNAR ( My_Schema_STEVE_TEST_TABLE_COLUMNAR_C2_C ) ;
UPDATE STATISTICS My_Schema.STEVE_TEST_TABLE_HEAP ( My_Schema_STEVE_TEST_TABLE_HEAP_C2_H ) ;
UPDATE STATISTICS My_Schema.STEVE_TEST_TABLE_COLUMNAR ( My_Schema_STEVE_TEST_TABLE_COLUMNAR_C1_C ) ;
UPDATE STATISTICS My_Schema.STEVE_TEST_TABLE_COLUMNAR ( My_Schema_STEVE_TEST_TABLE_COLUMNAR_C1_C ) ;
UPDATE STATISTICS My_Schema.STEVE_TEST_TABLE_HEAP ( My_Schema_STEVE_TEST_TABLE_HEAP_C1_H ) ;
UPDATE STATISTICS My_Schema.STEVE_TEST_TABLE_COLUMNAR ( My_Schema_STEVE_TEST_TABLE_COLUMNAR_C4_C ) ;
UPDATE STATISTICS My_Schema.STEVE_TEST_TABLE_HEAP ( My_Schema_STEVE_TEST_TABLE_HEAP_C4_H ) ;

--Validation Steps

select s.[schema_id] , s.[name] from sys.[schemas] s where s.[name] = 'My_Schema';

--Results:
schema_id name
24        My_Schema

--Get Table Object ID
select t.[object_id] , t.[name] from sys.[tables] t
inner join sys.[schemas] s
on t.[schema_id] = s.[schema_id]
where s.[name] = 'My_Schema' and t.[name]  in ('STEVE_TEST_TABLE_HEAP' , 'STEVE_TEST_TABLE_COLUMNAR');

--Results:
object_id   name
516,196,889 steve_test_table_columnar
532,196,946 steve_test_table_heap

--Get Columnd IDs
select t.[object_id] , c.[column_id], t.[name] , c.[name] as Column_Name
from
     sys.[tables] t
inner join
     sys.[schemas] s
on
     t.[schema_id] = s.[schema_id]
INNER JOIN
     sys.[columns] c
ON
     t.[object_id]       = c.[object_id]
where
     s.[name] = 'My_Schema'
 and t.[name]  in ('STEVE_TEST_TABLE_HEAP' , 'STEVE_TEST_TABLE_COLUMNAR')

--Results:
object_id   column_id   name                       Column_Name
516,196,889 1           steve_test_table_columnar   c1_c
516,196,889 2           steve_test_table_columnar   c2_c
516,196,889 3           steve_test_table_columnar   c3_c
516,196,889 4           steve_test_table_columnar   c4_c
532,196,946 1           steve_test_table_heap       c1_h
532,196,946 2           steve_test_table_heap       c2_h
532,196,946 3           steve_test_table_heap       c3_h
532,196,946 4           steve_test_table_heap       c4_h

--Final review of statistics metadata
select t.[object_id] , c.[column_id], t.[name] as table_name
, c.[name] as Column_Name  ,st.stats_id , st.name   as Stats_Name
,stc.stats_column_id
,STATS_DATE(st.object_id, st.stats_id) AS statistics_date
from
     sys.[tables] t
inner join
     sys.[schemas] s
on
     t.[schema_id] = s.[schema_id]
INNER JOIN
     sys.[columns] c
ON
     t.[object_id]       = c.[object_id]
INNER JOIN
     sys.stats st
ON
     st.[object_id]      = t.[object_id]
 and user_created = 1
INNER JOIN
  sys.[stats_columns] stc
on
     st.stats_id = stc.stats_id
 and st.[object_id] = stc.[object_id]
 and c.[column_id] = stc.[column_id]
where
     s.[name] = 'My_Schema'
 and t.[name]  in ('STEVE_TEST_TABLE_HEAP' , 'STEVE_TEST_TABLE_COLUMNAR')
 ;

object_id   column_id   table_name                  Column_Name stats_id    Stats_Name                                  stats_column_id statistics_date
516,196,889 1           steve_test_table_columnar   c1_c         2             My_Schema_STEVE_TEST_TABLE_COLUMNAR_C1_C 1               [NULL]
516,196,889 2           steve_test_table_columnar   c2_c         3             My_Schema_STEVE_TEST_TABLE_COLUMNAR_C2_C 1               [NULL]
516,196,889 3           steve_test_table_columnar   c3_c         4             My_Schema_STEVE_TEST_TABLE_COLUMNAR_C3_C 1               [NULL]
516,196,889 4           steve_test_table_columnar   c4_c         5             My_Schema_STEVE_TEST_TABLE_COLUMNAR_C4_C 1               [NULL]
532,196,946 1           steve_test_table_heap       c1_h         2             My_Schema_STEVE_TEST_TABLE_HEAP_C1_H     1               [NULL]
532,196,946 2           steve_test_table_heap       c2_h         3             My_Schema_STEVE_TEST_TABLE_HEAP_C2_H     1               [NULL]
532,196,946 3           steve_test_table_heap       c3_h         4             My_Schema_STEVE_TEST_TABLE_HEAP_C3_H     1               [NULL]
532,196,946 4           steve_test_table_heap       c4_h         5             My_Schema_STEVE_TEST_TABLE_HEAP_C4_H     1               [NULL]


问:
Swift 3 un-flip front camera pictures
I have an issue with front camera, it flips the pictures for some reason. I tried to use imageView.transform = CGAffineTransform(scaleX: -1, y: 1) to avoid this problem and it worked. But I realized that I'm flipping the back camera as well. Any solutions?

ImagePreviewViewController:

```<code>    @IBAction func close(_ sender: Any) {

    let cameraViewController = storyboard?.instantiateViewController(withIdentifier: "CameraViewController") as! CameraViewController
    navigationController?.pushViewController(cameraViewController, animated: true)

}
@IBOutlet weak var close: UIButton!
var capturedImage : UIImage?

@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    imageView.image = capturedImage
            close.setImage(UIImage(named: "Close.png"), for: UIControlState.normal)
    //imageView.transform = CGAffineTransform(scaleX: -1, y: 1)
}
</code>```

CameraViewController:

```<code>@IBOutlet var cameraView: UIView!
let session = AVCaptureSession()
var stillImageOutput: AVCaptureStillImageOutput = AVCaptureStillImageOutput()
var camera : AVCaptureDevice?
var cameraPreviewLayer : AVCaptureVideoPreviewLayer?
var cameraCaptureOutput : AVCapturePhotoOutput?
var frontCamera: Bool = false

override func viewDidLoad() {
    super.viewDidLoad()
    session.sessionPreset = AVCaptureSessionPresetPhoto
    frontCamera(frontCamera)
        if camera != nil{

            beginSession()

    }
    initializeCaptureSession()
    shoot.setImage(UIImage(named: "Shoot.png"), for: UIControlState.normal)
    // Do any additional setup after loading the view, typically from a nib.
}

func beginSession(){

    cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
    self.cameraView.layer.addSublayer(cameraPreviewLayer!)
    cameraPreviewLayer?.frame = self.cameraView.layer.bounds
    cameraPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
    session.startRunning()
    stillImageOutput.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]
    if session.canAddOutput(stillImageOutput){
        session.addOutput(stillImageOutput)

    }
}

func frontCamera(_ front: Bool){

    let devices = AVCaptureDevice.devices()

    do{

        try session.removeInput(AVCaptureDeviceInput(device: camera))

    } catch {

        print("error")
    }

    for device in devices!{

        if((device as AnyObject).hasMediaType(AVMediaTypeVideo)) {
            if front{
                if (device as AnyObject).position == AVCaptureDevicePosition.front {

                    camera = device as? AVCaptureDevice

                    do{
                        try session.addInput(AVCaptureDeviceInput(device: camera))
                    } catch {

                    }
                    break

                    }
            } else {

            }
            }

    }
}

func displayCapturedPhoto(capturedPhoto : UIImage) {

    let imagePreviewViewController = storyboard?.instantiateViewController(withIdentifier: "ImagePreviewViewController") as! ImagePreviewViewController
    imagePreviewViewController.capturedImage = capturedPhoto
    navigationController?.pushViewController(imagePreviewViewController, animated: true)
}

@IBOutlet weak var shoot: UIButton!
@IBAction func takePicture(_ sender: Any) {

    takePicture()

}

func initializeCaptureSession() {

    session.sessionPreset = AVCaptureSessionPresetHigh
    camera = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)

    do {
        let cameraCaptureInput = try AVCaptureDeviceInput(device: camera!)
        cameraCaptureOutput = AVCapturePhotoOutput()

        session.addInput(cameraCaptureInput)
        session.addOutput(cameraCaptureOutput)

    } catch {
        print(error.localizedDescription)
    }

    cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
    cameraPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
    cameraPreviewLayer?.frame = view.bounds
    cameraPreviewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait

    view.layer.insertSublayer(cameraPreviewLayer!, at: 0)

    session.startRunning()
}

func takePicture() {
    let settings = AVCapturePhotoSettings()
    settings.flashMode = .off
    cameraCaptureOutput?.capturePhoto(with: settings, delegate: self as AVCapturePhotoCaptureDelegate)
}

@IBOutlet weak var flash: UIButton!
@IBAction func flash(_ sender: Any) {

    }

@IBAction func switchCamera(_ sender: Any) {

    frontCamera = !frontCamera
    session.beginConfiguration()
    let inputs = session.inputs as! [AVCaptureInput]
    for oldInput: AVCaptureInput in inputs{
        session.removeInput(oldInput)

    }
    frontCamera(frontCamera)

    session.commitConfiguration()
}
</code>```

}

extension CameraViewController : AVCapturePhotoCaptureDelegate {

```<code>func capture(_ captureOutput: AVCapturePhotoOutput, didFinishProcessingPhotoSampleBuffer photoSampleBuffer: CMSampleBuffer?, previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) {

    if let unwrappedError = error {
        print(unwrappedError.localizedDescription)
    } else {

        if let sampleBuffer = photoSampleBuffer, let dataImage = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: sampleBuffer, previewPhotoSampleBuffer: previewPhotoSampleBuffer) {

            if let finalImage = UIImage(data: dataImage) {

                displayCapturedPhoto(capturedPhoto: finalImage)
            }
        }
    }
}

override var prefersStatusBarHidden: Bool {
    return true
}
</code>```

}

答:
Try setting the isVideoMirrored property of the connection to true. This will flip the image.  </p>

```<code>func initializeCaptureSession() {

...

cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
cameraPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
cameraPreviewLayer?.frame = view.bounds
cameraPreviewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait
cameraPreviewLayer?.connection.isVideoMirrored = true

view.layer.insertSublayer(cameraPreviewLayer!, at: 0)

session.startRunning()
</code>```

<p>}</p>

Title: Swift 3 un-flip front camera pictures

Body:
I have an issue with front camera, it flips the pictures for some reason. I tried to use imageView.transform = CGAffineTransform(scaleX: -1, y: 1) to avoid this problem and it worked. But I realized that I'm flipping the back camera as well. Any solutions?

ImagePreviewViewController:

    @IBAction func close(_ sender: Any) {

    let cameraViewController = storyboard?.instantiateViewController(withIdentifier: "CameraViewController") as! CameraViewController
    navigationController?.pushViewController(cameraViewController, animated: true)

}
@IBOutlet weak var close: UIButton!
var capturedImage : UIImage?

@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    imageView.image = capturedImage
            close.setImage(UIImage(named: "Close.png"), for: UIControlState.normal)
    //imageView.transform = CGAffineTransform(scaleX: -1, y: 1)
}

CameraViewController:

@IBOutlet var cameraView: UIView!
let session = AVCaptureSession()
var stillImageOutput: AVCaptureStillImageOutput = AVCaptureStillImageOutput()
var camera : AVCaptureDevice?
var cameraPreviewLayer : AVCaptureVideoPreviewLayer?
var cameraCaptureOutput : AVCapturePhotoOutput?
var frontCamera: Bool = false

override func viewDidLoad() {
    super.viewDidLoad()
    session.sessionPreset = AVCaptureSessionPresetPhoto
    frontCamera(frontCamera)
        if camera != nil{

            beginSession()

    }
    initializeCaptureSession()
    shoot.setImage(UIImage(named: "Shoot.png"), for: UIControlState.normal)
    // Do any additional setup after loading the view, typically from a nib.
}

func beginSession(){

    cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
    self.cameraView.layer.addSublayer(cameraPreviewLayer!)
    cameraPreviewLayer?.frame = self.cameraView.layer.bounds
    cameraPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
    session.startRunning()
    stillImageOutput.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]
    if session.canAddOutput(stillImageOutput){
        session.addOutput(stillImageOutput)

    }
}

func frontCamera(_ front: Bool){

    let devices = AVCaptureDevice.devices()

    do{

        try session.removeInput(AVCaptureDeviceInput(device: camera))

    } catch {

        print("error")
    }

    for device in devices!{

        if((device as AnyObject).hasMediaType(AVMediaTypeVideo)) {
            if front{
                if (device as AnyObject).position == AVCaptureDevicePosition.front {

                    camera = device as? AVCaptureDevice

                    do{
                        try session.addInput(AVCaptureDeviceInput(device: camera))
                    } catch {

                    }
                    break

                    }
            } else {

            }
            }

    }
}

func displayCapturedPhoto(capturedPhoto : UIImage) {

    let imagePreviewViewController = storyboard?.instantiateViewController(withIdentifier: "ImagePreviewViewController") as! ImagePreviewViewController
    imagePreviewViewController.capturedImage = capturedPhoto
    navigationController?.pushViewController(imagePreviewViewController, animated: true)
}

@IBOutlet weak var shoot: UIButton!
@IBAction func takePicture(_ sender: Any) {

    takePicture()

}

func initializeCaptureSession() {

    session.sessionPreset = AVCaptureSessionPresetHigh
    camera = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)

    do {
        let cameraCaptureInput = try AVCaptureDeviceInput(device: camera!)
        cameraCaptureOutput = AVCapturePhotoOutput()

        session.addInput(cameraCaptureInput)
        session.addOutput(cameraCaptureOutput)

    } catch {
        print(error.localizedDescription)
    }

    cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
    cameraPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
    cameraPreviewLayer?.frame = view.bounds
    cameraPreviewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait

    view.layer.insertSublayer(cameraPreviewLayer!, at: 0)

    session.startRunning()
}

func takePicture() {
    let settings = AVCapturePhotoSettings()
    settings.flashMode = .off
    cameraCaptureOutput?.capturePhoto(with: settings, delegate: self as AVCapturePhotoCaptureDelegate)
}

@IBOutlet weak var flash: UIButton!
@IBAction func flash(_ sender: Any) {

    }

@IBAction func switchCamera(_ sender: Any) {

    frontCamera = !frontCamera
    session.beginConfiguration()
    let inputs = session.inputs as! [AVCaptureInput]
    for oldInput: AVCaptureInput in inputs{
        session.removeInput(oldInput)

    }
    frontCamera(frontCamera)

    session.commitConfiguration()
}

}

extension CameraViewController : AVCapturePhotoCaptureDelegate {

func capture(_ captureOutput: AVCapturePhotoOutput, didFinishProcessingPhotoSampleBuffer photoSampleBuffer: CMSampleBuffer?, previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) {

    if let unwrappedError = error {
        print(unwrappedError.localizedDescription)
    } else {

        if let sampleBuffer = photoSampleBuffer, let dataImage = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: sampleBuffer, previewPhotoSampleBuffer: previewPhotoSampleBuffer) {

            if let finalImage = UIImage(data: dataImage) {

                displayCapturedPhoto(capturedPhoto: finalImage)
            }
        }
    }
}

override var prefersStatusBarHidden: Bool {
    return true
}

}

Body:
Try setting the isVideoMirrored property of the connection to true. This will flip the image.

func initializeCaptureSession() {

...

cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
cameraPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
cameraPreviewLayer?.frame = view.bounds
cameraPreviewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait
cameraPreviewLayer?.connection.isVideoMirrored = true

view.layer.insertSublayer(cameraPreviewLayer!, at: 0)

session.startRunning()

}