问:
How to create a makefile that will place object code in different folder
I am very new to Makefile. I had build the following makefile(Which don't work).I wan't put genarated object codes in differnt folder(the folder is in current directory).

```<code>$ ls
main.cpp  Makefile  object_code  Time.cpp  Time_.h
</code>```

how can I do this ??

```<code>VER = Debug
CC = g++

OBJECTFIELS = ./object_code/main.o ./object_code/Time.o

../$(VER)/main: $(OBJECTFIELS)
    $(CC) $(OBJECTFIELS) -o $@

$(OBJECTFIELS): Time_.h

./object_code/main.o: main.cpp

./object_code/Time.o: Time.cpp

clean:
    rm $(OBJECTFIELS) main
</code>```

this is error.

```<code>$ make
g++ ./object_code/main.o ./object_code/Time.o -o ../Debug/main
g++: error: ./object_code/main.o: No such file or directory
g++: error: ./object_code/Time.o: No such file or directory
g++: fatal error: no input files
compilation terminated.
Makefile:8: recipe for target '../Debug/main' failed
make: *** [../Debug/main] Error 1
</code>```

please this is last question.

答:
I don't see how you can possibly get that output given the makefile you've posted here.

Either the object files already exist in which case the link will succeed rather than printing that error.

Or the object files don't exist in which case make will complain because it doesn't know how to make them.  There must be some difference between the makefile you're using and the one you've posted here.

In any event, make knows how to build a file foo.o from a file foo.cpp for any string foo.  There's a built-in rule that tells it how to do that.

But, make doesn't know how to build a file ./object_code/foo.o from a file foo.cpp, regardless of foo.  There's no built-in rule that tells make how to build object files in some random other directory.  If you want make to do that, you'll have to tell it how.  You should remove the lines:

```<code>./object_code/main.o: main.cpp

./object_code/Time.o: Time.cpp
</code>```

and replace them with a pattern rule describing how to build object files into the object_code directory (I'm using CXX as the compiler variable here: by convention CC is the C compiler and CXX is the C++ compiler, and you should always stick with convention unless there's a good reason not to):

```<code>VER = Debug
CXX = g++

OBJECTFIELS = ./object_code/main.o ./object_code/Time.o

../$(VER)/main: $(OBJECTFIELS)
        $(CXX) $(OBJECTFIELS) -o $@

$(OBJECTFIELS): Time_.h

./object_code/%.o : %.cpp
        $(CXX) -c -o $@ $<

clean:
        rm $(OBJECTFIELS) main
</code>```

Body:
I am very new to Makefile. I had build the following makefile(Which don't work).I wan't put genarated object codes in differnt folder(the folder is in current directory).

$ ls
main.cpp  Makefile  object_code  Time.cpp  Time_.h

how can I do this ??

VER = Debug
CC = g++

OBJECTFIELS = ./object_code/main.o ./object_code/Time.o

../$(VER)/main: $(OBJECTFIELS)
    $(CC) $(OBJECTFIELS) -o $@

$(OBJECTFIELS): Time_.h

./object_code/main.o: main.cpp

./object_code/Time.o: Time.cpp

clean:
    rm $(OBJECTFIELS) main

this is error.

$ make
g++ ./object_code/main.o ./object_code/Time.o -o ../Debug/main
g++: error: ./object_code/main.o: No such file or directory
g++: error: ./object_code/Time.o: No such file or directory
g++: fatal error: no input files
compilation terminated.
Makefile:8: recipe for target '../Debug/main' failed
make: *** [../Debug/main] Error 1

please this is last question.

Body:
I don't see how you can possibly get that output given the makefile you've posted here.

Either the object files already exist in which case the link will succeed rather than printing that error.

Or the object files don't exist in which case make will complain because it doesn't know how to make them.  There must be some difference between the makefile you're using and the one you've posted here.

In any event, make knows how to build a file foo.o from a file foo.cpp for any string foo.  There's a built-in rule that tells it how to do that.

But, make doesn't know how to build a file ./object_code/foo.o from a file foo.cpp, regardless of foo.  There's no built-in rule that tells make how to build object files in some random other directory.  If you want make to do that, you'll have to tell it how.  You should remove the lines:

./object_code/main.o: main.cpp

./object_code/Time.o: Time.cpp

and replace them with a pattern rule describing how to build object files into the object_code directory (I'm using CXX as the compiler variable here: by convention CC is the C compiler and CXX is the C++ compiler, and you should always stick with convention unless there's a good reason not to):

VER = Debug
CXX = g++

OBJECTFIELS = ./object_code/main.o ./object_code/Time.o

../$(VER)/main: $(OBJECTFIELS)
        $(CXX) $(OBJECTFIELS) -o $@

$(OBJECTFIELS): Time_.h

./object_code/%.o : %.cpp
        $(CXX) -c -o $@ $<

clean:
        rm $(OBJECTFIELS) main


来源: stackexchange

问:
How to prevent tableview section head from sticking while scrolling?
I have a tableview with many sections. I am using an actual tableview cell which I dequeue to use as a custom section header. The issue I am having is when I scroll the section header "sticks" to the top of the table until the next section appears.

How can I prevent this from happening and actually have it scroll up like normal?

Here is my code

```<code>func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == 3 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! HeaderTableViewCell
        return cell
    }
    return UIView()
}
</code>```

答: Instead of UIHeaderViewCell, You should use a UITableViewCell. Make section header height as 0 and for every 0th item in that section , display a UITableViewCell with heading on it

ContentLicense: CC BY-SA 3.0

Body:
I have a tableview with many sections. I am using an actual tableview cell which I dequeue to use as a custom section header. The issue I am having is when I scroll the section header "sticks" to the top of the table until the next section appears.

How can I prevent this from happening and actually have it scroll up like normal?

Here is my code

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == 3 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! HeaderTableViewCell
        return cell
    }
    return UIView()
}


问:
Why does this output 10 for each loop? Isn't int a value type?
I was browsing through some C# examples and came upon this:

```<code>using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        delegate void Printer();

        static void Main()
        {
            List<Printer> printers = new List<Printer>();

            for (int i = 0; i < 10; i++)
            {
                printers.Add(delegate { var d = i; Console.WriteLine(d); });
            }

            foreach (var printer in printers)
            {
                printer();
            }
            Console.ReadLine();
        }
    }
}
</code>```

I expected this to output 0 through 9, since an int is a value type and d should be set to whatever i is at that time.

However, this outputs 10 ten times.

Why is this? Is the int not a reference instead inside the delegate?

Note: I am not trying to solve a problem here, just understand how this works, in a way that is re-applicable.

Edit: Example of my confusion

```<code>int i = 9;
int d = 8;
d = i;
i++;
Console.WriteLine(d);
</code>```

This would show that i is passed as a value, and not a reference. I expected the same inside the closure, but was surprised.

Thanks for the comments, I understand more now, the code in the delegate isn't executed till after and it uses i that exists outside of it in a generic class made by the compiler?

In javascript this same kind of code outputs 1-9, which is what I expected in C#. https://jsfiddle.net/L21xLaq0/2/.

答:
You may be interested to see how this code is actually rewritten by compiler, because it helps to understand what's going on. If you compile and then view dll in some decompiler (like dotPeek) with disabled "fancy view", you will see this (some names are changed because they are not readable):</p>

```<code>class Program {
    delegate void Printer();

    private static void Main() {
        List<Program.Printer> printerList = new List<Program.Printer>();
        // closure object which holds captured variables
        Program.DisplayClass10 cDisplayClass10 = new Program.DisplayClass10();
        int i;
        // loop assigns field of closure object
        for (cDisplayClass10.i = 0; cDisplayClass10.i < 10; cDisplayClass10.i = i + 1) {
            // your delegate is method of closure object
            printerList.Add(new Program.Printer(cDisplayClass10.CrypticFunctionName));
            i = cDisplayClass10.i;
        }
        // here, cDisplayClass10.i is 10
        foreach (Program.Printer printer in printerList)
            printer();
        Console.ReadLine();
    }

    // class for closure object
    [CompilerGenerated]
    private sealed class DisplayClass10 {
        public int i;

        internal void CrypticFunctionName() {
            Console.WriteLine(this.i);
        }
    }
}
</code>```

Body:
I was browsing through some C# examples and came upon this:

using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        delegate void Printer();

        static void Main()
        {
            List<Printer> printers = new List<Printer>();

            for (int i = 0; i < 10; i++)
            {
                printers.Add(delegate { var d = i; Console.WriteLine(d); });
            }

            foreach (var printer in printers)
            {
                printer();
            }
            Console.ReadLine();
        }
    }
}

I expected this to output 0 through 9, since an int is a value type and d should be set to whatever i is at that time.

However, this outputs 10 ten times.

Why is this? Is the int not a reference instead inside the delegate?

Note: I am not trying to solve a problem here, just understand how this works, in a way that is re-applicable.

Edit: Example of my confusion

int i = 9;
int d = 8;
d = i;
i++;
Console.WriteLine(d);

This would show that i is passed as a value, and not a reference. I expected the same inside the closure, but was surprised.

Thanks for the comments, I understand more now, the code in the delegate isn't executed till after and it uses i that exists outside of it in a generic class made by the compiler?

In javascript this same kind of code outputs 1-9, which is what I expected in C#. https://jsfiddle.net/L21xLaq0/2/.

Body:
You may be interested to see how this code is actually rewritten by compiler, because it helps to understand what's going on. If you compile and then view dll in some decompiler (like dotPeek) with disabled "fancy view", you will see this (some names are changed because they are not readable):

class Program {
    delegate void Printer();

    private static void Main() {
        List<Program.Printer> printerList = new List<Program.Printer>();
        // closure object which holds captured variables
        Program.DisplayClass10 cDisplayClass10 = new Program.DisplayClass10();
        int i;
        // loop assigns field of closure object
        for (cDisplayClass10.i = 0; cDisplayClass10.i < 10; cDisplayClass10.i = i + 1) {
            // your delegate is method of closure object
            printerList.Add(new Program.Printer(cDisplayClass10.CrypticFunctionName));
            i = cDisplayClass10.i;
        }
        // here, cDisplayClass10.i is 10
        foreach (Program.Printer printer in printerList)
            printer();
        Console.ReadLine();
    }

    // class for closure object
    [CompilerGenerated]
    private sealed class DisplayClass10 {
        public int i;

        internal void CrypticFunctionName() {
            Console.WriteLine(this.i);
        }
    }
}


问:
View with editable textviews (onClick)
I have a view with several textView. I want them to be editable on Click.
Following code seems not to do what is supposed to do:

```<code>    textView1 = (TextView) findViewById(R.id.tv1);
    textView1.setText(tv1);
    runEditListener(textView1);

    textView2 = (TextView) findViewById(R.id.tv2);
    textView2.setText(tv2);
    runEditListener(textView1);
</code>```

.......

```<code>    private void runEditListener(TextView textView) {

    dialog = new AlertDialog.Builder(this).create();
    editText = new EditText(this);
    dialog.setTitle("Edit");
    dialog.setView(editText);
    dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Save", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) { textView.setText(editText.getText());

        }
    });

    textView.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            editText.setText(textView.getText());
            dialog.show();
        }
    });

}
</code>```

I probably should only run once the runEditListener() method and get on which TextView the user clicked but I don't really find how to do that.

答:
Create OnClickListener with your code from runEdit... then set it to yours textviews like textview.onClickLiatener(yourListener);
you can do it by implementing OnClickListener for your activity class and then use text1.onClickListener(this);
text2.onClickListener(this); etc...

Title: View with editable textviews (onClick)

Body:
I have a view with several textView. I want them to be editable on Click.
Following code seems not to do what is supposed to do:

    textView1 = (TextView) findViewById(R.id.tv1);
    textView1.setText(tv1);
    runEditListener(textView1);

    textView2 = (TextView) findViewById(R.id.tv2);
    textView2.setText(tv2);
    runEditListener(textView1);

.......

    private void runEditListener(TextView textView) {

    dialog = new AlertDialog.Builder(this).create();
    editText = new EditText(this);
    dialog.setTitle("Edit");
    dialog.setView(editText);
    dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Save", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) { textView.setText(editText.getText());

        }
    });

    textView.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            editText.setText(textView.getText());
            dialog.show();
        }
    });

}

I probably should only run once the runEditListener() method and get on which TextView the user clicked but I don't really find how to do that.


问:
What is the best way to create a java.util.Enumeration out of a java stream?
My best solution is currently:

```<code>Collections.enumeration(stream.collect(Collectors.toList()))
</code>```

Hoping for a more concise method than this.

答:
There is also an apache commons based solution IteratorUtils.asEnumeration</p>

```<code>IteratorUtils.asEnumeration(stream.iterator());
</code>```

Body:
My best solution is currently:

Collections.enumeration(stream.collect(Collectors.toList()))

Hoping for a more concise method than this.

Body:
There is also an apache commons based solution IteratorUtils.asEnumeration

IteratorUtils.asEnumeration(stream.iterator());


问:
Display and Style a Selected Value From an Array
I am trying to style what is selected from my array, however when I run my code I get a syntax error and it has to do with my h1 styling I believe. Im trying to Echo a h1 that displays the color name and uses the color name to style the color of the h1 using inline styling to set the color. </p>

```<code><body>
    <form id = '' name = '' action='php 07 array 01.php' method='post' class = ''>
        <select id = 'colorNumber' name = 'colorNumber'>

            <option value = '0'>0</option>
            <option value = '1'>1</option>
            <option value = '2'>2</option>
            <option value = '3'>3</option>
            <option value = '4'>4</option>
            <option value = '5'>5</option>
            <option value = '6'>6</option>
            <option value = '7'>7</option>
            <option value = '8'>8</option>
            <option value = '9'>9</option>
        </select>
        <input type = 'submit' value = 'GO' class = '' id = 'go'>
    </form>
</body>

<?php

$colorArray = array("sepia", "gold", "carrot", "orange", "yellow", "blue", "pink", "purple", "black", "warmgrey");

$colorEfx = $_POST['colorNumber'];

$differentColor = $colorArray[$colorEfx];

echo <h1 style = 'color:$differentColor; '>$differentColor</h1>;

?>
</code>```

答:
your echo statement is wrong, it should be surrounded by "":

echo "
$differentColor
;"

Body:
I am trying to style what is selected from my array, however when I run my code I get a syntax error and it has to do with my h1 styling I believe. Im trying to Echo a h1 that displays the color name and uses the color name to style the color of the h1 using inline styling to set the color.

    <form id = '' name = '' action='php 07 array 01.php' method='post' class = ''>
        <select id = 'colorNumber' name = 'colorNumber'>

            <option value = '0'>0</option>
            <option value = '1'>1</option>
            <option value = '2'>2</option>
            <option value = '3'>3</option>
            <option value = '4'>4</option>
            <option value = '5'>5</option>
            <option value = '6'>6</option>
            <option value = '7'>7</option>
            <option value = '8'>8</option>
            <option value = '9'>9</option>
        </select>
        <input type = 'submit' value = 'GO' class = '' id = 'go'>
    </form>

<?php

$colorArray = array("sepia", "gold", "carrot", "orange", "yellow", "blue", "pink", "purple", "black", "warmgrey");

$colorEfx = $_POST['colorNumber'];

$differentColor = $colorArray[$colorEfx];

echo
$differentColor
;

?>

Body:
your echo statement is wrong, it should be surrounded by "":

echo "<h1 style = 'color:$differentColor; '>$differentColor</h1>;"


问:
C++ unwanted destruction
Can somebody explain why when c finishes construction, the destructor of b (member of c) is called, while d is destructed - as expected - when c's destructor is called ?

```<code>#include <iostream>

using namespace std;

class A
{
public:
    int a, b;
};

class B
{
public:
    A* array[10];
    B()
    {
        for(int i = 0 ; i < 10 ; i++)
            array[i] = new A();
    }
    ~B()
    {
        for(int i = 0 ; i < 10 ; i++)
            delete array[i];
    }
};

class C
{
public:
    B b;
    B* d;
    C()
    {
        b = B();
    }
    ~C()
    {
            delete d;
    }
};

int main()
{
    B b = B();
    C c = C();
    cout << "Ashlamish" << endl;
    system("pause");
    return 0;
}
</code>```

答:
I think you want to declare c like this:

```<code>C c;
</code>```

This will construct an object named c which will be destructed on scope exit.
On the other hand, what you have;

```<code>C c = C();
</code>```

will construct an anonymous object of type C, copy construct c with it and immediately destruct the anonymous object. c will still be destructed at the end of the scope.

ContentLicense: CC BY-SA 2.5

Title: C++ unwanted destruction

Body:
Can somebody explain why when c finishes construction, the destructor of b (member of c) is called, while d is destructed - as expected - when c's destructor is called ?

#include <iostream>

using namespace std;

class A
{
public:
    int a, b;
};

class B
{
public:
    A* array[10];
    B()
    {
        for(int i = 0 ; i < 10 ; i++)
            array[i] = new A();
    }
    ~B()
    {
        for(int i = 0 ; i < 10 ; i++)
            delete array[i];
    }
};

class C
{
public:
    B b;
    B* d;
    C()
    {
        b = B();
    }
    ~C()
    {
            delete d;
    }
};

int main()
{
    B b = B();
    C c = C();
    cout << "Ashlamish" << endl;
    system("pause");
    return 0;
}

Body:
I think you want to declare c like this:

C c;

This will construct an object named c which will be destructed on scope exit.
On the other hand, what you have;

C c = C();

will construct an anonymous object of type C, copy construct c with it and immediately destruct the anonymous object. c will still be destructed at the end of the scope.


问:
How do I track the time a person goes to a place?
I'm working on creating a database for a gym to track the members info. I want to be able to track the times that people go so you will be able to see when it is busiest. I'm not sure how to go about this. Do I need to make a new table for the information of when a member goes or do I add it into the members or gyms table?</p>

答:
Think in terms of "domain" models. From your question it appears you already have Member and Gym models.

I suggest introducing an Attendance model.

```<code>Attendance
  - UserId
  - CheckInDateTime
</code>```

This would translate to a new database table called "attendance" with the corresponding columns.

In order to see when is the busiest time - I would execute a "select count" statement on the attendance table and "group by" the check_in_date column (truncate the time portion).

A note on persisting datetime values. It is recommended to store the datetime value in UTC timezone. Then you can have your application convert the timezone accordingly when viewing the data.

Body:
Think in terms of "domain" models. From your question it appears you already have Member and Gym models.

I suggest introducing an Attendance model.

Attendance
  - UserId
  - CheckInDateTime

This would translate to a new database table called "attendance" with the corresponding columns.

In order to see when is the busiest time - I would execute a "select count" statement on the attendance table and "group by" the check_in_date column (truncate the time portion).

A note on persisting datetime values. It is recommended to store the datetime value in UTC timezone. Then you can have your application convert the timezone accordingly when viewing the data.


答:
Did you see which line the error is?

Try this:

```<code>echo "<h1 style=\"color:$differentColor\">$differentColor</h1>";
</code>```

Title: Display and Style a Selected Value From an Array

Body:
Did you see which line the error is?

Try this:

echo "<h1 style=\"color:$differentColor\">$differentColor</h1>";


问:
application insights analytics events: grouping rows in a table
so I am analyzing the Events of my Users and separate them by name. That works really well, but the problem accusing to me is that some of the event namen are quite the same action. For example if azure tracks an "Added Scan:" it always includes the filename "Added Scan: T-885_J...." and separates it in a different row. So what I am trying to figure out is, how can I "merge" more than one same action like"Added Scans" to one row and keep the rest separated.
I tried it with e. g. "name startswith("Added")", but with this I only can merge one row.
I would be really grateful if somebody has an idea!
Cheers,
Marleen

```<code>let added =
   customEvents
    | where timestamp > ago(1d);
added
    | summarize adoc=count(), adli = makelist(name), b = makeset(user_Id) by name
    | extend sumname = substring(adli, 2, 10)
    | project sumname, adoc, adli, b
</code>```

for example:

答:
one way would be to add either iff or case statements to break up ones you know to contain only the things you need.

so you could change the names of events to "fix" them up.

```<code> | extend name = iff(name startswith("Added scan"), substring(name, 0,10), name)
</code>```

in this case, if name started with "Added scan", it is truncated to only that, otherwise, it is left alone.

and you can use extend to "overwrite" an existing field if you need.

are you not in control of the thing making that telemetry?  if you are, you should really change the code to not put all that extra content into the event names, and instead put that inside custom properties.  if you aren't, you should talk to the people who are :)

Then, other tools like application insights tools like users and flows and funnels would work a LOT better for you.

Body:
so I am analyzing the Events of my Users and separate them by name. That works really well, but the problem accusing to me is that some of the event namen are quite the same action. For example if azure tracks an "Added Scan:" it always includes the filename "Added Scan: T-885_J...." and separates it in a different row. So what I am trying to figure out is, how can I "merge" more than one same action like"Added Scans" to one row and keep the rest separated.
I tried it with e. g. "name startswith("Added")", but with this I only can merge one row.
I would be really grateful if somebody has an idea!
Cheers,
Marleen

let added =
   customEvents
    | where timestamp > ago(1d);
added
    | summarize adoc=count(), adli = makelist(name), b = makeset(user_Id) by name
    | extend sumname = substring(adli, 2, 10)
    | project sumname, adoc, adli, b

for example:

Body:
one way would be to add either iff or case statements to break up ones you know to contain only the things you need.

so you could change the names of events to "fix" them up.

 | extend name = iff(name startswith("Added scan"), substring(name, 0,10), name)

in this case, if name started with "Added scan", it is truncated to only that, otherwise, it is left alone.

and you can use extend to "overwrite" an existing field if you need.

are you not in control of the thing making that telemetry?  if you are, you should really change the code to not put all that extra content into the event names, and instead put that inside custom properties.  if you aren't, you should talk to the people who are :)

Then, other tools like application insights tools like users and flows and funnels would work a LOT better for you.


问:
Select full row based on MAX value and GROUP BY
Here's the scenario. I have employees and they evaluated yearly for different categories. I need: the full row of the latest evaluation for each category.

Example:

Employee Table:

```<code>EmpID  Name
454    John
</code>```

Evals Table:

```<code>id EmpID  Category  EvalDate     Note
1  454       A      2016-01-01   Excellent
2  454       A      2017-02-15   Not so good
3  454       B      2016-01-01   Poor
4  454       B      2017-02-01   Good
</code>```

I need a query that returns the latest eval (the full row) for each category:

```<code>EmpID  Category  EvalDate     Note
454       A      2017-02-15   Not so good
454       B      2017-02-01   Good
</code>```

My query so far:

```<code>SELECT
    evals.EmpID,
    evals.Category,
    evals.Note,
    MAX(evals.EvalDate) as LatestEval
FROM
    evals
WHERE
    evals.EmpID = 454
GROUP BY
    evals.Category
</code>```

This unfortunately returns the latest date for each category but the note field from older evals.

答:
You might give this a try:</p>

```<code>SELECT
    evals.EmpID,
    evals.Category,
    evals.Note,
    evals.EvalDate
FROM Employee emp
JOIN Evals evals
ON emp.EmpID = evals.EmpID
AND eval.EvalDate =
    (SELECT MAX(EvalDate)
    FROM Evals a
    WHERE a.Category = evals.category
        AND a.EmpID = emp.EmpID GROUP BY e.EmpID,e.Category)
GROUP BY evals.EmpID,evals.Category
</code>```

Body:
Here's the scenario. I have employees and they evaluated yearly for different categories. I need: the full row of the latest evaluation for each category.

Example:

Employee Table:

EmpID  Name
454    John

Evals Table:

id EmpID  Category  EvalDate     Note
1  454       A      2016-01-01   Excellent
2  454       A      2017-02-15   Not so good
3  454       B      2016-01-01   Poor
4  454       B      2017-02-01   Good

I need a query that returns the latest eval (the full row) for each category:

EmpID  Category  EvalDate     Note
454       A      2017-02-15   Not so good
454       B      2017-02-01   Good

My query so far:

SELECT
    evals.EmpID,
    evals.Category,
    evals.Note,
    MAX(evals.EvalDate) as LatestEval
FROM
    evals
WHERE
    evals.EmpID = 454
GROUP BY
    evals.Category

This unfortunately returns the latest date for each category but the note field from older evals.

Body:
You might give this a try:

SELECT
    evals.EmpID,
    evals.Category,
    evals.Note,
    evals.EvalDate
FROM Employee emp
JOIN Evals evals
ON emp.EmpID = evals.EmpID
AND eval.EvalDate =
    (SELECT MAX(EvalDate)
    FROM Evals a
    WHERE a.Category = evals.category
        AND a.EmpID = emp.EmpID GROUP BY e.EmpID,e.Category)
GROUP BY evals.EmpID,evals.Category


问:
Running an expensive method in the view VS in the controller - Rails
Running the risk of being tagged as "too broad", but this is an authentic doubt.

Say I have
@my_model.complex_calculation_result to show in a view.

What are the pros and cons of:

1 - Calculating the value on the controller and send it to the view

Controller:

@result = @my_model.complex_calculation_result # caching the value in the controller

View:

<%= @result %>

2 - Calculating it directly in the view

<%= @my_model.complex_calculation_result %>

I know the last alternative represents less code and I have one less instance variable hanging around.

But are there performance diferences?

Guess 1 - the view already takes more memory to render it all, so the calculation can take longer from inside the view if it is memory expensive.

Any light shed on this and comments will be highly appreciated. :)

答:
TL;DR

In case of memory I think the only one possibility to 'slow it down' is when you exceed your memory and starting to use swap file. I haven't researched rails so deep, but if we take your thoughts into account and think that average controller execution takes X memory and average view takes 1.3 * X (absolutely random coefficient from my head), then chances to get into swap from view will be slightly bigger, then from the controller. If my thoughts are correct, then controller is better in technical side.

On conceptual side. Views are just for rendering results and in your case I would definitely move this heavy method outside the view. You are concerned about 'additional instance variable' and your concerns are correct...

My team follows Sandy Metz's rules. One of the state:

Pass only one single instance interface(variable) to the view. If you
  need multiple instance variables, then wrap the whole logic with
  Facade pattern and let this facade provide all the interfaces you need.

So... I would setup a facade and wrap this heavy method into one of it's property.

So we have 2-0 to put it into controllers.

PS: I have strong concerns about lazy loading and so on.... I think that facade method will be calculated only after it's real call (not during instance initialization), so for real your slow logic will still get be called only in view (during first real refer to this method). I think you can prevent this by making all the calculations inside Facade constructor initialize and put the result into instance variable and then refer from view, this variable with result.... But...

I am not even sure, that variable will be calculated before first real usage (it's possible that there are also such mechanism for optimization to not execute, what is not yet used. As ActiveRecord does such thing during methods chaining. No real SQL executed unless you really refer to one of the object). So I have concerns, that even moving this method into Facade constructor can still end up with it being calculated only in view. But you can check it with logs/debuggers to be sure


问:
Oracle stored procedure help
HI am new to stored procedure.
Am using a dynamic sql with

```<code>select * from table into var
</code>```

var is a variable.the var contains more than one value ,when i try to run the proc with inputs i get an error:

```<code>ORA-01422: exact fetch returns more than requested number of rows
</code>```

Is there a way such that the variable can hold more than one row using dynamic sql.

答:
Use collection variables:</p>

```<code>DECLARE
        TYPE tt_int IS TABLE OF INTEGER;
        var tt_int;
BEGIN
        SELECT  id
        BULK COLLECT
        INTO    var
        FROM    table;
END;
</code>```

Title: Oracle stored procedure help

Body:
HI am new to stored procedure.
Am using a dynamic sql with

select * from table into var

var is a variable.the var contains more than one value ,when i try to run the proc with inputs i get an error:

ORA-01422: exact fetch returns more than requested number of rows

Is there a way such that the variable can hold more than one row using dynamic sql.

Body:
Use collection variables:

DECLARE
        TYPE tt_int IS TABLE OF INTEGER;
        var tt_int;
BEGIN
        SELECT  id
        BULK COLLECT
        INTO    var
        FROM    table;
END;


问:
Segmentation Fault from Split String Function
I am required to write a function that splits a string into individual words.

My first parameter is a string.  We assume that the words in the string are separated by single spaces, with no spaces before the first word or after the second word. Punctuation like spaces for example is part of a word. My second parameter is an address of an integer in which the function gives it the value of the number of words in the string. The return value is a pointer that points of an array of strings containing the individual words in the sentence. I need to allocate it memory from the heap and have one word in each index of the array. The strings are copies of the original words, not pointers. Here is my code :

```<code>char** splitString(char theString[], int *arraySize) {
  *arraySize = countSpaces(theString) + 1; //Points to the number of words in the string.
  char** pointerToArrayOfStrings = malloc(*arraySize * sizeof(char *)); //Allocated memory for '*arraySize' character pointers
  int characters = 0;
  for (int i = 0; i < *arraySize; i++) {
    while (theString[characters] != ' ' || theString[characters] != '\0') {
      characters++;
    }
    characters++;
    pointerToArrayOfStrings[i] = (char *)malloc(characters);
    pointerToArrayOfStrings[i][characters] = '\0';
  }
  for (int word = 0; word < *arraySize; word++) {
    int ch = 0;
    while (ch < strlen(pointerToArrayOfStrings[word])) {
      pointerToArrayOfStrings[word][ch] = theString[ch];
    }
    ch+=2;
  }
  return pointerToArrayOfStrings;
}
</code>```

This is immediately giving me segmentation faults. I am very new to pointers, so my method is to first allocate the array with the amount of memory for "numberOfWords" character pointers. Then I allocated each character pointer with the size of the corresponding word. After, I filled the slots with the characters from the original string. I don't know what I'm missing.

答:
The comments have already addressed your questions about seg-faults etc. But since you did not say it was required how you split the string, I wanted to suggest looking at another approach.

Consider these steps:

1) Walk through string counting occurrences of white space (words) and track longest word found.

2) Knowing count, and longest word, you have what you need to allocate memory.  Do it.

3) In a for loop, use strtok() with the delimiters of: , \n, \t etc. to tokenize the string.

4)  Using strcpy() (also in the loop) to transfer each token into the string array.

5) Return array. Use array.  Free all allocated memory.

Example code to do these steps:

```<code>char** splitString(const char theString[], int *arraySize);
char ** create_str_array(int strings, int longest) ;

int main(void)
{
    int size;
    char ** string = splitString("here is a string", &size);

    return 0;
}

char** splitString(const char theString[], int *arraySize)
{
    *arraySize = strlen(theString) + 1; //Points to the number of words in the string.
    char *tok;
    char *dup = strdup(theString);//create copy of const char argument

    char** pointerToArrayOfStrings = NULL;
    int characters = 0;
    int len = 0, lenKeep = 0, wordCount = 0, i;

    /// get count of words and longsest string
    for(i=0;i<*arraySize;i++)
    {
      if((!isspace(theString[i]) && (theString[i])))
      {
          len++;
          if(lenKeep < len)
          {
              lenKeep = len;
          }
      }
      else
      {
        wordCount++;
        len = 0;
      }
    }

    /// create memory. (array of strings to hold sub-strings)
    pointerToArrayOfStrings = create_str_array(wordCount, lenKeep);
    if(pointerToArrayOfStrings)// only if memory creation successful, continue
    {
        /// parse original string into sub-strings
        i = 0;
        tok = strtok(dup, " \n\t");
        if(tok)
        {
            strcpy(pointerToArrayOfStrings[i], tok);
            tok = strtok(NULL, " \n\t");
            while(tok)
            {
                i++;
                strcpy(pointerToArrayOfStrings[i], tok);
                tok = strtok(NULL, " \n\t");
            }
        }
    }

    /// return array of strings
    return pointerToArrayOfStrings;
}

char ** create_str_array(int strings, int longest)
{
    int i;
    char ** a = calloc(strings, sizeof(char *));
    for(i=0;i<strings;i++)
    {
        a[i] = calloc(longest+1, 1);
    }
    return a;
}
</code>```

Body:
I am required to write a function that splits a string into individual words.

My first parameter is a string.  We assume that the words in the string are separated by single spaces, with no spaces before the first word or after the second word. Punctuation like spaces for example is part of a word. My second parameter is an address of an integer in which the function gives it the value of the number of words in the string. The return value is a pointer that points of an array of strings containing the individual words in the sentence. I need to allocate it memory from the heap and have one word in each index of the array. The strings are copies of the original words, not pointers. Here is my code :

char** splitString(char theString[], int *arraySize) {
  *arraySize = countSpaces(theString) + 1; //Points to the number of words in the string.
  char** pointerToArrayOfStrings = malloc(*arraySize * sizeof(char *)); //Allocated memory for '*arraySize' character pointers
  int characters = 0;
  for (int i = 0; i < *arraySize; i++) {
    while (theString[characters] != ' ' || theString[characters] != '\0') {
      characters++;
    }
    characters++;
    pointerToArrayOfStrings[i] = (char *)malloc(characters);
    pointerToArrayOfStrings[i][characters] = '\0';
  }
  for (int word = 0; word < *arraySize; word++) {
    int ch = 0;
    while (ch < strlen(pointerToArrayOfStrings[word])) {
      pointerToArrayOfStrings[word][ch] = theString[ch];
    }
    ch+=2;
  }
  return pointerToArrayOfStrings;
}

This is immediately giving me segmentation faults. I am very new to pointers, so my method is to first allocate the array with the amount of memory for "numberOfWords" character pointers. Then I allocated each character pointer with the size of the corresponding word. After, I filled the slots with the characters from the original string. I don't know what I'm missing.

Body:
The comments have already addressed your questions about seg-faults etc. But since you did not say it was required how you split the string, I wanted to suggest looking at another approach.

Consider these steps:

1) Walk through string counting occurrences of white space (words) and track longest word found.

2) Knowing count, and longest word, you have what you need to allocate memory.  Do it.

3) In a for loop, use strtok() with the delimiters of: , \n, \t etc. to tokenize the string.

4)  Using strcpy() (also in the loop) to transfer each token into the string array.

5) Return array. Use array.  Free all allocated memory.

Example code to do these steps:

char** splitString(const char theString[], int *arraySize);
char ** create_str_array(int strings, int longest) ;

int main(void)
{
    int size;
    char ** string = splitString("here is a string", &size);

    return 0;
}

char** splitString(const char theString[], int *arraySize)
{
    *arraySize = strlen(theString) + 1; //Points to the number of words in the string.
    char *tok;
    char *dup = strdup(theString);//create copy of const char argument

    char** pointerToArrayOfStrings = NULL;
    int characters = 0;
    int len = 0, lenKeep = 0, wordCount = 0, i;

    /// get count of words and longsest string
    for(i=0;i<*arraySize;i++)
    {
      if((!isspace(theString[i]) && (theString[i])))
      {
          len++;
          if(lenKeep < len)
          {
              lenKeep = len;
          }
      }
      else
      {
        wordCount++;
        len = 0;
      }
    }

    /// create memory. (array of strings to hold sub-strings)
    pointerToArrayOfStrings = create_str_array(wordCount, lenKeep);
    if(pointerToArrayOfStrings)// only if memory creation successful, continue
    {
        /// parse original string into sub-strings
        i = 0;
        tok = strtok(dup, " \n\t");
        if(tok)
        {
            strcpy(pointerToArrayOfStrings[i], tok);
            tok = strtok(NULL, " \n\t");
            while(tok)
            {
                i++;
                strcpy(pointerToArrayOfStrings[i], tok);
                tok = strtok(NULL, " \n\t");
            }
        }
    }

    /// return array of strings
    return pointerToArrayOfStrings;
}

char ** create_str_array(int strings, int longest)
{
    int i;
    char ** a = calloc(strings, sizeof(char *));
    for(i=0;i<strings;i++)
    {
        a[i] = calloc(longest+1, 1);
    }
    return a;
}


问:
Extracting a text file from tar with tarfile module in python3
Is there a simple way to extract a text file from a tar file as a file object of text I/O in python 3.4 or later?

I am revising my python2 code to python3, and I found TarFile.extractfile, which used to return a file object with text I/O, now returns a io.BufferedReader object which seems to have binary I/O. The other part of my code expects a text I/O, and I need to absorb this change in some way.

One method I can think of is to use TarFile.extract and write the file to a directory, and open it by open function, but I wonder if there is a way to get the text I/O stream directly.

答:
you can use getmembers()

```<code>import  tarfile
tar = tarfile.open("test.tar")
tar.getmembers()
</code>```

After that, you can use extractfile() to extract the members as file object. Just an example

```<code>import tarfile,os
import sys
os.chdir("/tmp/foo")
tar = tarfile.open("test.tar")
for member in tar.getmembers():
    f=tar.extractfile(member)
    content=f.read()
    // do operations with your content
    sys.exit()
tar.close()
</code>```

Body:
you can use getmembers()

import  tarfile
tar = tarfile.open("test.tar")
tar.getmembers()

After that, you can use extractfile() to extract the members as file object. Just an example

import tarfile,os
import sys
os.chdir("/tmp/foo")
tar = tarfile.open("test.tar")
for member in tar.getmembers():
    f=tar.extractfile(member)
    content=f.read()
    // do operations with your content
    sys.exit()
tar.close()


问:
How can I remove the 'Update Strategy: No Reboots' message on CoreOS/Container Linux?
I am running a Kubernetes cluster on CoreOS and using coreos/container-linux-update-operator to update each node in a controlled way. When I ssh into one of the nodes however I am getting the message Update Strategy: No Reboots, presumably because I have disabled and masked locksmithd.service (as it is no longer needed).

How can I stop that message from appearing? It isn't actually true since update-operator is handling updates instead.

答:
This message is generated when /etc/profile.d/coreos-profile.sh is run.  /etc/profile.d/coreos-profile.sh is a symlink to /usr/share/baselayout/coreos-profile.sh you should be able to remove the symlink in order to disable the message.

Note that this file is also runs this code to show a list of failed units, at logon.

```<code>FAILED=$(systemctl list-units --state=failed --no-legend)
if [[ ! -z "${FAILED}" ]]; then
    COUNT=$(wc -l <<<"${FAILED}")
    echo -e "Failed Units: \033[31m${COUNT}\033[39m"
    awk '{ print "  " $1 }' <<<"${FAILED}"
fi
</code>```

If this was a show stopper you could copy this functionality to some other script in /etc/profile.d/

You can discover quite a lot about CoreOS Container linux by looking though the baselayout repository that contains a lot of the scripts and config files https://github.com/coreos/baselayout. You can find the script in question here: https://github.com/coreos/baselayout/blob/master/baselayout/coreos-profile.sh and the config used to generate the symlink here: https://github.com/coreos/baselayout/blob/master/tmpfiles.d/baselayout-etc.conf

Body:
This message is generated when /etc/profile.d/coreos-profile.sh is run.  /etc/profile.d/coreos-profile.sh is a symlink to /usr/share/baselayout/coreos-profile.sh you should be able to remove the symlink in order to disable the message.

Note that this file is also runs this code to show a list of failed units, at logon.

FAILED=$(systemctl list-units --state=failed --no-legend)
if [[ ! -z "${FAILED}" ]]; then
    COUNT=$(wc -l <<<"${FAILED}")
    echo -e "Failed Units: \033[31m${COUNT}\033[39m"
    awk '{ print "  " $1 }' <<<"${FAILED}"
fi

If this was a show stopper you could copy this functionality to some other script in /etc/profile.d/

You can discover quite a lot about CoreOS Container linux by looking though the baselayout repository that contains a lot of the scripts and config files https://github.com/coreos/baselayout. You can find the script in question here: https://github.com/coreos/baselayout/blob/master/baselayout/coreos-profile.sh and the config used to generate the symlink here: https://github.com/coreos/baselayout/blob/master/tmpfiles.d/baselayout-etc.conf


问:
How to get the output of dense layer as a numpy array using keras and tensorflow backend?
I am new to Keras and Tensorflow. I am working on a face recognition project using deep learning. I am getting the class label of a subject as an output using this code (output of softmax layer) and the accuracy is 97.5% for my custom dataset of 100 classes.

But now I'm interested in the feature vector representation, so I want to pass the test images through the network and extract the output from activated dense layer before softmax (last layer). I referred Keras documentation, but nothing seemed to work for me. Can anyone please help me how to extract the output from the dense layer activation and save as a numpy array? Thanks in advance.

```<code>class Faces:
    @staticmethod
    def build(width, height, depth, classes, weightsPath=None):
        # initialize the model
        model = Sequential()
        model.add(Conv2D(100, (5, 5), padding="same",input_shape=(depth, height, width), data_format="channels_first"))
        model.add(Activation("relu"))
        model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2),data_format="channels_first"))

        model.add(Conv2D(100, (5, 5), padding="same"))
        model.add(Activation("relu"))
        model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), data_format="channels_first"))

        # 3 set of CONV => RELU => POOL
        model.add(Conv2D(100, (5, 5), padding="same"))
        model.add(Activation("relu"))
        model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2),data_format="channels_first"))

        # 4 set of CONV => RELU => POOL
        model.add(Conv2D(50, (5, 5), padding="same"))
        model.add(Activation("relu"))
        model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2),data_format="channels_first"))

        # 5 set of CONV => RELU => POOL
        model.add(Conv2D(50, (5, 5), padding="same"))
        model.add(Activation("relu"))
        model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), data_format="channels_first"))

        # 6 set of CONV => RELU => POOL
        model.add(Conv2D(50, (5, 5), padding="same"))
        model.add(Activation("relu"))
        model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), data_format="channels_first"))

        # set of FC => RELU layers
        model.add(Flatten())
        #model.add(Dense(classes))
        #model.add(Activation("relu"))

        # softmax classifier
        model.add(Dense(classes))
        model.add(Activation("softmax"))

        return model

ap = argparse.ArgumentParser()
ap.add_argument("-l", "--load-model", type=int, default=-1,
    help="(optional) whether or not pre-trained model should be loaded")
ap.add_argument("-w", "--weights", type=str,
    help="(optional) path to weights file")
args = vars(ap.parse_args())

path = 'C:\\Users\\Project\\FaceGallery'
image_paths = [os.path.join(path, f) for f in os.listdir(path)]
images = []
labels = []
name_map = {}
demo = {}
nbr = 0
j = 0
for image_path in image_paths:
    image_pil = Image.open(image_path).convert('L')
    image = np.array(image_pil, 'uint8')
    cv2.imshow("Image",image)
    cv2.waitKey(5)
    name = image_path.split("\\")[4][0:5]
    print(name)
    # Get the label of the image
    if name in demo.keys():
        pass
    else:
        demo[name] = j
        j = j+1
    nbr =demo[name]

    name_map[nbr] = name
    images.append(image)
    labels.append(nbr)
print(name_map)
# Training and testing data split ratio = 60:40
(trainData, testData, trainLabels, testLabels) = train_test_split(images, labels, test_size=0.4)

trainLabels = np_utils.to_categorical(trainLabels, 100)
testLabels = np_utils.to_categorical(testLabels, 100)

trainData = np.asarray(trainData)
testData = np.asarray(testData)

trainData = trainData[:, np.newaxis, :, :] / 255.0
testData = testData[:, np.newaxis, :, :] / 255.0

opt = SGD(lr=0.01)
model = Faces.build(width=200, height=200, depth=1, classes=100,
                    weightsPath=args["weights"] if args["load_model"] > 0 else None)

model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"])
if args["load_model"] < 0:
    model.fit(trainData, trainLabels, batch_size=10, epochs=300)
(loss, accuracy) = model.evaluate(testData, testLabels, batch_size=100, verbose=1)
print("Accuracy: {:.2f}%".format(accuracy * 100))
if args["save_model"] > 0:
    model.save_weights(args["weights"], overwrite=True)

for i in np.arange(0, len(testLabels)):
    probs = model.predict(testData[np.newaxis, i])
    prediction = probs.argmax(axis=1)
    image = (testData[i][0] * 255).astype("uint8")
    name = "Subject " + str(prediction[0])
    if prediction[0] in name_map:
        name = name_map[prediction[0]]
    cv2.putText(image, name, (5, 20), cv2.FONT_HERSHEY_PLAIN, 1.3, (255, 255, 255), 2)
    print("Predicted: {}, Actual: {}".format(prediction[0], np.argmax(testLabels[i])))
    cv2.imshow("Testing Face", image)
    cv2.waitKey(1000)
</code>```

答:
See https://keras.io/getting-started/faq/ How can I obtain the output of an intermediate layer?

You'll need to name the layer you want the output from by adding a 'name' argument to your definition. Like.. model.add(Dense(xx, name='my_dense'))

You can then define an intermediate model and run it by doing something like...

```<code>m2 = Model(inputs=model.input, outputs=model.get_layer('my_dense').output)
Y = m2.predict(X)
</code>```

Body:
I am new to Keras and Tensorflow. I am working on a face recognition project using deep learning. I am getting the class label of a subject as an output using this code (output of softmax layer) and the accuracy is 97.5% for my custom dataset of 100 classes.

But now I'm interested in the feature vector representation, so I want to pass the test images through the network and extract the output from activated dense layer before softmax (last layer). I referred Keras documentation, but nothing seemed to work for me. Can anyone please help me how to extract the output from the dense layer activation and save as a numpy array? Thanks in advance.

class Faces:
    @staticmethod
    def build(width, height, depth, classes, weightsPath=None):
        # initialize the model
        model = Sequential()
        model.add(Conv2D(100, (5, 5), padding="same",input_shape=(depth, height, width), data_format="channels_first"))
        model.add(Activation("relu"))
        model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2),data_format="channels_first"))

        model.add(Conv2D(100, (5, 5), padding="same"))
        model.add(Activation("relu"))
        model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), data_format="channels_first"))

        # 3 set of CONV => RELU => POOL
        model.add(Conv2D(100, (5, 5), padding="same"))
        model.add(Activation("relu"))
        model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2),data_format="channels_first"))

        # 4 set of CONV => RELU => POOL
        model.add(Conv2D(50, (5, 5), padding="same"))
        model.add(Activation("relu"))
        model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2),data_format="channels_first"))

        # 5 set of CONV => RELU => POOL
        model.add(Conv2D(50, (5, 5), padding="same"))
        model.add(Activation("relu"))
        model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), data_format="channels_first"))

        # 6 set of CONV => RELU => POOL
        model.add(Conv2D(50, (5, 5), padding="same"))
        model.add(Activation("relu"))
        model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), data_format="channels_first"))

        # set of FC => RELU layers
        model.add(Flatten())
        #model.add(Dense(classes))
        #model.add(Activation("relu"))

        # softmax classifier
        model.add(Dense(classes))
        model.add(Activation("softmax"))

        return model

ap = argparse.ArgumentParser()
ap.add_argument("-l", "--load-model", type=int, default=-1,
    help="(optional) whether or not pre-trained model should be loaded")
ap.add_argument("-w", "--weights", type=str,
    help="(optional) path to weights file")
args = vars(ap.parse_args())

path = 'C:\\Users\\Project\\FaceGallery'
image_paths = [os.path.join(path, f) for f in os.listdir(path)]
images = []
labels = []
name_map = {}
demo = {}
nbr = 0
j = 0
for image_path in image_paths:
    image_pil = Image.open(image_path).convert('L')
    image = np.array(image_pil, 'uint8')
    cv2.imshow("Image",image)
    cv2.waitKey(5)
    name = image_path.split("\\")[4][0:5]
    print(name)
    # Get the label of the image
    if name in demo.keys():
        pass
    else:
        demo[name] = j
        j = j+1
    nbr =demo[name]

    name_map[nbr] = name
    images.append(image)
    labels.append(nbr)
print(name_map)
# Training and testing data split ratio = 60:40
(trainData, testData, trainLabels, testLabels) = train_test_split(images, labels, test_size=0.4)

trainLabels = np_utils.to_categorical(trainLabels, 100)
testLabels = np_utils.to_categorical(testLabels, 100)

trainData = np.asarray(trainData)
testData = np.asarray(testData)

trainData = trainData[:, np.newaxis, :, :] / 255.0
testData = testData[:, np.newaxis, :, :] / 255.0

opt = SGD(lr=0.01)
model = Faces.build(width=200, height=200, depth=1, classes=100,
                    weightsPath=args["weights"] if args["load_model"] > 0 else None)

model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"])
if args["load_model"] < 0:
    model.fit(trainData, trainLabels, batch_size=10, epochs=300)
(loss, accuracy) = model.evaluate(testData, testLabels, batch_size=100, verbose=1)
print("Accuracy: {:.2f}%".format(accuracy * 100))
if args["save_model"] > 0:
    model.save_weights(args["weights"], overwrite=True)

for i in np.arange(0, len(testLabels)):
    probs = model.predict(testData[np.newaxis, i])
    prediction = probs.argmax(axis=1)
    image = (testData[i][0] * 255).astype("uint8")
    name = "Subject " + str(prediction[0])
    if prediction[0] in name_map:
        name = name_map[prediction[0]]
    cv2.putText(image, name, (5, 20), cv2.FONT_HERSHEY_PLAIN, 1.3, (255, 255, 255), 2)
    print("Predicted: {}, Actual: {}".format(prediction[0], np.argmax(testLabels[i])))
    cv2.imshow("Testing Face", image)
    cv2.waitKey(1000)

Body:
See https://keras.io/getting-started/faq/ How can I obtain the output of an intermediate layer?

You'll need to name the layer you want the output from by adding a 'name' argument to your definition. Like.. model.add(Dense(xx, name='my_dense'))

You can then define an intermediate model and run it by doing something like...

m2 = Model(inputs=model.input, outputs=model.get_layer('my_dense').output)
Y = m2.predict(X)


问:
Centered UL won't expand horizontally in Firefox/Opera (works in Safari, IE6/7/8)
I have a centered ul (styled like a table ala cssplay) that is having li elements added to it after page render, and it seems to work beautifully in everything but Firefox and Opera.

The desired effect is to have the row of li elements centered even if there's only one or two of them. This example simulates the issue with jQuery adding a li two seconds after the page is ready.

For whatever reason, it seems like Firefox 3.05 and Opera 9.63 keep the ul at the initial draw width after the third li is added, even though there is no width specified anywhere in the CSS.

This is, of course, absolutely murdering me, and any help would be appreciated.

http://deadguy.reliccommunity.com/stuffbox/testinggrounds/display-table.html

答:
The table-* display types are still quite underdefined, and so it's no surprise that you're getting different behavior here. In my experience, FF also has some issues with applying certain rules to inserted content. Luckily, though, there is a more intuitive way to code this page that also happens to work.

Rather than setting the
 to display:table, leave it as display:block (the default) and give it text-align:center. You don't actually care that the
 shrinkwraps the inline tables in this case (which is the net result that your code is achieving), you just want the tables themselves to be centered.

As a bonus, this allows you to remove the wrapping
, since it's only there to provide a boundary for the
's margins to push off of. Since you aren't using those margins anymore, you can simply use the
 as the containing block, and give it the border instead.

Body:
The table-* display types are still quite underdefined, and so it's no surprise that you're getting different behavior here. In my experience, FF also has some issues with applying certain rules to inserted content. Luckily, though, there is a more intuitive way to code this page that also happens to work.

Rather than setting the <ul/> to display:table, leave it as display:block (the default) and give it text-align:center. You don't actually care that the <ul/> shrinkwraps the inline tables in this case (which is the net result that your code is achieving), you just want the tables themselves to be centered.

As a bonus, this allows you to remove the wrapping <div/>, since it's only there to provide a boundary for the <ul/>'s margins to push off of. Since you aren't using those margins anymore, you can simply use the <ul/> as the containing block, and give it the border instead.

OwnerDisplayName: Xanthir


问:
Android EditText data entry in lowercase determined at runtime
I was rather surprised that this was not a native function of EditText, but I can't find any mechanism that will convert inputs to lower case as they are entered into an EditText field. The EditText field determines whether to be lowercase at runtime, so I can't have this in the XML, it needs to be fired as I allocate the EditText. I have tried:

1) Negating the ALL Caps:

```<code> mEntry.setInputType(InputType.TYPE_CLASS_TEXT |  ~InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS);
</code>```

2) Creating a listener:

private TextWatcher textWatcher = new TextWatcher() {

```<code>@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

    if (!Utilities.stringIsBlank(mField.getFormat()) && Field.LOWER.equalsIgnoreCase(mField.getFormat())) {
        if (!Utilities.stringIsBlank(s.toString()) && !s.toString().equals(s.toString().toLowerCase()) ) {
            mEntry.setText(s.toString().toLowerCase());
            mEntry.setSelection(start+1);
        }
    }
}
</code>```

}

The problem with this is that when I call the setText() it recursively calls back to the onTextChange event, which messes with the location of cursor, depending on what it is changing.

Anyone have a simple solution that I have somehow missed?

答:
Check the text inside your if statement like this

if(mEntry.getText().toString().equals( mEntry.getText().toString().toLowerCase() )
return;

```<code>@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

    if (!Utilities.stringIsBlank(mField.getFormat()) && Field.LOWER.equalsIgnoreCase(mField.getFormat())) {
        if (!Utilities.stringIsBlank(s.toString()) && !s.toString().equals(s.toString().toLowerCase()) ) {
if (mEntry.getText().toString().equals(mEntry.getText().toString().toLowerCase())return;
            mEntry.setText(s.toString().toLowerCase());
            mEntry.setSelection(start+1);
        }
    }
}
</code>```

Body:
I was rather surprised that this was not a native function of EditText, but I can't find any mechanism that will convert inputs to lower case as they are entered into an EditText field. The EditText field determines whether to be lowercase at runtime, so I can't have this in the XML, it needs to be fired as I allocate the EditText. I have tried:

1) Negating the ALL Caps:

 mEntry.setInputType(InputType.TYPE_CLASS_TEXT |  ~InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS);

2) Creating a listener:

private TextWatcher textWatcher = new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

    if (!Utilities.stringIsBlank(mField.getFormat()) && Field.LOWER.equalsIgnoreCase(mField.getFormat())) {
        if (!Utilities.stringIsBlank(s.toString()) && !s.toString().equals(s.toString().toLowerCase()) ) {
            mEntry.setText(s.toString().toLowerCase());
            mEntry.setSelection(start+1);
        }
    }
}

}

The problem with this is that when I call the setText() it recursively calls back to the onTextChange event, which messes with the location of cursor, depending on what it is changing.

Anyone have a simple solution that I have somehow missed?

Body:
Check the text inside your if statement like this

if(mEntry.getText().toString().equals( mEntry.getText().toString().toLowerCase() )
return;

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

    if (!Utilities.stringIsBlank(mField.getFormat()) && Field.LOWER.equalsIgnoreCase(mField.getFormat())) {
        if (!Utilities.stringIsBlank(s.toString()) && !s.toString().equals(s.toString().toLowerCase()) ) {
if (mEntry.getText().toString().equals(mEntry.getText().toString().toLowerCase())return;
            mEntry.setText(s.toString().toLowerCase());
            mEntry.setSelection(start+1);
        }
    }
}


问:
Closing Case in Acumatica through API
I want to close the case in Partners Portal remotely using Web API, whenever I close the case in my (client) side. I was able to implement the code but ran into below issue.

It is changing the status and resolution of the case in Partners Portal but Close Case button is enabled and it is visible in My Open Case bucket. Please let me know if I can close the case remotely using Web API or if I am missing anything.

protected virtual void CRCase_RowPersisting(PXCache cache, PXRowPersistingEventArgs e)
{
 var caseRow = (CRCase)e.Row;
 if (caseRow != null)
 {
  if (caseRow.Status == "C")  // Closed
  {
   string cloud9CaseCD = null;

   cloud9CaseCD = CRCaseForCreate.Current.CaseCD;

   string acumaticaCaseCD = string.Empty;

   CSAnswers aCCaseNoAttribute = PXSelect<CSAnswers,
     Where<CSAnswers.refNoteID, Equal<Required<CSAnswers.refNoteID>>,
     And<CSAnswers.attributeID, Equal<Required<CSAnswers.attributeID>>>>>.Select(new PXGraph(), CRCaseForCreate.Current.NoteID, "ACCASENO");
   if (aCCaseNoAttribute != null)
   {
    acumaticaCaseCD = aCCaseNoAttribute.Value;

    if(!string.IsNullOrEmpty(acumaticaCaseCD))
    {
     SP203000WS.Screen context = new SP203000WS.Screen();
     context.CookieContainer = new System.Net.CookieContainer();
     context.AllowAutoRedirect = true;
     context.EnableDecompression = true;
     context.Timeout = 1000000;
     context.Url = "https://sso.acumatica.com/Soap/SP203000.asmx";

     PartnerPortalCreds loginCreds = GetCreds();
     string username = loginCreds.PARTPRTUSE;
     string password = loginCreds.PARTPRTPAS;

     SP203000WS.LoginResult result = context.Login(username, password);

     SP203000WS.Content CR306000 = context.GetSchema();
     context.Clear();
     SP203000WS.Content[] CR306000Content = context.Submit
      (
       new SP203000WS.Command[]
       {
        new SP203000WS.Value
        {
         Value = acumaticaCaseCD,
         LinkedCommand = CR306000.Case.CaseID
        },
         new SP203000WS.Value
        {
         Value = "C",
         LinkedCommand = new SP203000WS.Field { FieldName="Status", ObjectName="Case"}
        },
        new SP203000WS.Value
        {
         Value = "RD",
         LinkedCommand = new SP203000WS.Field { FieldName="Resolution", ObjectName="Case"}
        },
        CR306000.Actions.Submit,
        CR306000.Case.CaseID
       }
     );

     context.Logout();
    }
   }
  }
 }
}```
</div>
</div>
</p>

<p>Tried below code using CloseCase Action: -</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>protected virtual void CRCase_RowPersisting(PXCache cache, PXRowPersistingEventArgs e)
{
 var caseRow = (CRCase)e.Row;
 if (caseRow != null)
 {
  if (caseRow.Status == "C")  // Closed
  {
   string cloud9CaseCD = null;

   cloud9CaseCD = CRCaseForCreate.Current.CaseCD;

   string acumaticaCaseCD = string.Empty;

   CSAnswers aCCaseNoAttribute = PXSelect<CSAnswers,
     Where<CSAnswers.refNoteID, Equal<Required<CSAnswers.refNoteID>>,
     And<CSAnswers.attributeID, Equal<Required<CSAnswers.attributeID>>>>>.Select(new PXGraph(), CRCaseForCreate.Current.NoteID, "ACCASENO");
   if (aCCaseNoAttribute != null)
   {
    acumaticaCaseCD = aCCaseNoAttribute.Value;

    if (!string.IsNullOrEmpty(acumaticaCaseCD))
    {
     SP203010WS.Screen context = new SP203010WS.Screen();
     context.CookieContainer = new System.Net.CookieContainer();
     context.AllowAutoRedirect = true;
     context.EnableDecompression = true;
     context.Timeout = 1000000;
     context.Url = "https://sso.acumatica.com/Soap/SP203010.asmx";

     PartnerPortalCreds loginCreds = GetCreds();
     string username = loginCreds.PARTPRTUSE;
     string password = loginCreds.PARTPRTPAS;

     SP203010WS.LoginResult result = context.Login(username, password);

     SP203010WS.Content CR306000 = context.GetSchema();
     context.Clear();

     var commands1 = new SP203010WS.Command[]
     {
      new SP203010WS.Value
       {
        Value = acumaticaCaseCD,
        LinkedCommand = CR306000.Case.CaseID
       },
      new SP203010WS.Value
       {
        Value = "Yes",
        LinkedCommand = CR306000.Case.ServiceCommands.DialogAnswer, Commit = true
       },
      CR306000.Actions.CloseCase
     };

     var data = context.Submit(commands1);

     context.Logout();

    }
   }
  }
 }
}</code>```

In the below image you can see that the case is already closed but Close Case menu button is still visible.

Close Case Confirmation Dialogbox on Partners Portal. How should I answer this dialogbox programatically while closing the case using Web API.

答: Finally found the solution. Updated the code for CloseCase (second code snippet). This will mark the case as Pending Closure in Partners Portal.</p>

Title: Closing Case in Acumatica through API

Body:
I want to close the case in Partners Portal remotely using Web API, whenever I close the case in my (client) side. I was able to implement the code but ran into below issue.

It is changing the status and resolution of the case in Partners Portal but Close Case button is enabled and it is visible in My Open Case bucket. Please let me know if I can close the case remotely using Web API or if I am missing anything.

protected virtual void CRCase_RowPersisting(PXCache cache, PXRowPersistingEventArgs e)
{
 var caseRow = (CRCase)e.Row;
 if (caseRow != null)
 {
  if (caseRow.Status == "C")  // Closed
  {
   string cloud9CaseCD = null;

   cloud9CaseCD = CRCaseForCreate.Current.CaseCD;

   string acumaticaCaseCD = string.Empty;

   CSAnswers aCCaseNoAttribute = PXSelect<CSAnswers,
     Where<CSAnswers.refNoteID, Equal<Required<CSAnswers.refNoteID>>,
     And<CSAnswers.attributeID, Equal<Required<CSAnswers.attributeID>>>>>.Select(new PXGraph(), CRCaseForCreate.Current.NoteID, "ACCASENO");
   if (aCCaseNoAttribute != null)
   {
    acumaticaCaseCD = aCCaseNoAttribute.Value;

    if(!string.IsNullOrEmpty(acumaticaCaseCD))
    {
     SP203000WS.Screen context = new SP203000WS.Screen();
     context.CookieContainer = new System.Net.CookieContainer();
     context.AllowAutoRedirect = true;
     context.EnableDecompression = true;
     context.Timeout = 1000000;
     context.Url = "https://sso.acumatica.com/Soap/SP203000.asmx";

     PartnerPortalCreds loginCreds = GetCreds();
     string username = loginCreds.PARTPRTUSE;
     string password = loginCreds.PARTPRTPAS;

     SP203000WS.LoginResult result = context.Login(username, password);

     SP203000WS.Content CR306000 = context.GetSchema();
     context.Clear();
     SP203000WS.Content[] CR306000Content = context.Submit
      (
       new SP203000WS.Command[]
       {
        new SP203000WS.Value
        {
         Value = acumaticaCaseCD,
         LinkedCommand = CR306000.Case.CaseID
        },
         new SP203000WS.Value
        {
         Value = "C",
         LinkedCommand = new SP203000WS.Field { FieldName="Status", ObjectName="Case"}
        },
        new SP203000WS.Value
        {
         Value = "RD",
         LinkedCommand = new SP203000WS.Field { FieldName="Resolution", ObjectName="Case"}
        },
        CR306000.Actions.Submit,
        CR306000.Case.CaseID
       }
     );

     context.Logout();
    }
   }
  }
 }
}

Tried below code using CloseCase Action: -

protected virtual void CRCase_RowPersisting(PXCache cache, PXRowPersistingEventArgs e)
{
 var caseRow = (CRCase)e.Row;
 if (caseRow != null)
 {
  if (caseRow.Status == "C")  // Closed
  {
   string cloud9CaseCD = null;

   cloud9CaseCD = CRCaseForCreate.Current.CaseCD;

   string acumaticaCaseCD = string.Empty;

   CSAnswers aCCaseNoAttribute = PXSelect<CSAnswers,
     Where<CSAnswers.refNoteID, Equal<Required<CSAnswers.refNoteID>>,
     And<CSAnswers.attributeID, Equal<Required<CSAnswers.attributeID>>>>>.Select(new PXGraph(), CRCaseForCreate.Current.NoteID, "ACCASENO");
   if (aCCaseNoAttribute != null)
   {
    acumaticaCaseCD = aCCaseNoAttribute.Value;

    if (!string.IsNullOrEmpty(acumaticaCaseCD))
    {
     SP203010WS.Screen context = new SP203010WS.Screen();
     context.CookieContainer = new System.Net.CookieContainer();
     context.AllowAutoRedirect = true;
     context.EnableDecompression = true;
     context.Timeout = 1000000;
     context.Url = "https://sso.acumatica.com/Soap/SP203010.asmx";

     PartnerPortalCreds loginCreds = GetCreds();
     string username = loginCreds.PARTPRTUSE;
     string password = loginCreds.PARTPRTPAS;

     SP203010WS.LoginResult result = context.Login(username, password);

     SP203010WS.Content CR306000 = context.GetSchema();
     context.Clear();

     var commands1 = new SP203010WS.Command[]
     {
      new SP203010WS.Value
       {
        Value = acumaticaCaseCD,
        LinkedCommand = CR306000.Case.CaseID
       },
      new SP203010WS.Value
       {
        Value = "Yes",
        LinkedCommand = CR306000.Case.ServiceCommands.DialogAnswer, Commit = true
       },
      CR306000.Actions.CloseCase
     };

     var data = context.Submit(commands1);

     context.Logout();

    }
   }
  }
 }
}

In the below image you can see that the case is already closed but Close Case menu button is still visible.

Close Case Confirmation Dialogbox on Partners Portal. How should I answer this dialogbox programatically while closing the case using Web API.


问:
Grav CMS page names
I have been experimenting with Grav for a few days now and find it a real breath of fresh air for someone who has only ever used WordPress.  However, there is one thing that bothers me.  The folder structure driven flat file page hierarchy used by Grav can easily end up with a folder structure like the one below

```<code>01.home
 |
 --- default.en.md
     |
     01.sub-page-1
                 |
                  --- default.en.md
     |
     02.sub-page-2
                 |
                  --- default.en.md
</code>```

There in lies the problem. I prefer to edit my markdown in Visual Studio Code via SFTP, not in the Grav Admin panel.  However, that means that I can end up with multiple default.en.md files open at the same time and that is a disaster waiting to happen.  Is it possible to rename the markdown files to something more logical?

答:
You can actually.

By default, grav pulls the template type from the markdown file's name. However, you can override this behavior by setting the template variable in your page's YAML header. So we could easily have something like:

```<code>01.home
 |
 --- homepage.en.md
     |
     01.sub-page-1
                 |
                  --- home.subpage1.en.md
</code>```

If we simply have a header of

```<code>---
title: blah
template: default
...
---
</code>```

ContentLicense: CC BY-SA 4.0

Title: Grav CMS page names

Body:
I have been experimenting with Grav for a few days now and find it a real breath of fresh air for someone who has only ever used WordPress.  However, there is one thing that bothers me.  The folder structure driven flat file page hierarchy used by Grav can easily end up with a folder structure like the one below

01.home
 |
 --- default.en.md
     |
     01.sub-page-1
                 |
                  --- default.en.md
     |
     02.sub-page-2
                 |
                  --- default.en.md

There in lies the problem. I prefer to edit my markdown in Visual Studio Code via SFTP, not in the Grav Admin panel.  However, that means that I can end up with multiple default.en.md files open at the same time and that is a disaster waiting to happen.  Is it possible to rename the markdown files to something more logical?

Body:
You can actually.

By default, grav pulls the template type from the markdown file's name. However, you can override this behavior by setting the template variable in your page's YAML header. So we could easily have something like:

01.home
 |
 --- homepage.en.md
     |
     01.sub-page-1
                 |
                  --- home.subpage1.en.md

If we simply have a header of

---
title: blah
template: default
...
---


问:
Is AWS Aurora for PostgreSQL not available in ca-central-1 region?
I'm trying to set up an Aurora PostgreSQL database in ca-central-1 (Canada) through Amazon's web interface, but the dashboard only gives me the option of picking Aurora MySQL.

Are Aurora PostgreSQL-compatible instances not available in Canada yet, or is this a bug in Amazon's web interface?

答: The Aurora Postgres SQL Compatible instances are not available in Canada yet. You can refer the pricing page to find out the availability for respective database engines.</p>


问:
Python - What is a simple way to update elements in a list?
Here is an example to illustrate what I am trying to do:

```<code>class bar:
    pass

list1 = []
for i in range(10):
    bar1 = bar()
    bar1.foo = 0
    list1.append(bar1)

# update list1

for i in range(10):
    print(list1[i].foo)
</code>```

I want the output of the code above to be

```<code>10
10
10
10
10
10
10
10
10
10
</code>```

At the # update list1 part, if I were doing this in C#, I could do

```<code>list1.ForEach(x=>x.foo = 10)
</code>```

And I know in Python I can do

```<code>for x in list1:
    x.foo = 10
</code>```

But how can I do it in Python in a way similar to the way in C#?

答:
Just trying to provide an alternative here, but it's also possible to use map if you define an update function before-hand. This may or may not be suitable for your needs but I wanted to explore this myself :)</p>

```<code>def update_bar(my_bar):
    my_bar.foo = 10
    return my_bar

list1 = list(map(update_bar, list1))
</code>```

Body:
Here is an example to illustrate what I am trying to do:

class bar:
    pass

list1 = []
for i in range(10):
    bar1 = bar()
    bar1.foo = 0
    list1.append(bar1)

# update list1

for i in range(10):
    print(list1[i].foo)

I want the output of the code above to be

10
10
10
10
10
10
10
10
10
10

At the # update list1 part, if I were doing this in C#, I could do

list1.ForEach(x=>x.foo = 10)

And I know in Python I can do

for x in list1:
    x.foo = 10

But how can I do it in Python in a way similar to the way in C#?

Body:
Just trying to provide an alternative here, but it's also possible to use map if you define an update function before-hand. This may or may not be suitable for your needs but I wanted to explore this myself :)

def update_bar(my_bar):
    my_bar.foo = 10
    return my_bar

list1 = list(map(update_bar, list1))


问:
Hover effect on only one element and not affect the others
How to animate only one element (div) each time, having class .box and not affect the other elements with same class. Something like this :

```<code>$(.box).hover(function() {
        $(.box).animate({ fontSize : '2rem' });
        $(.box).removeClass("main");
        // other things...
</code>```

html:

```<code><div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</code>```

I tried with .next() and .find() but I did not succeed because of my basic level in jQuery.

答:
EDIT

Due to correct comment this answer has been edited. You could try the following in case you would want to bind different, multiple (e.g. mouseover focus) events, benefit of using .on().

$(".box").on({
  mouseover: function() {
      $(this).animate({ fontSize : '2rem' }).addClass('red');
  },
  mouseleave: function() {
      $(this).animate({ fontSize : '1rem' }).removeClass('red');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.red {
color:#f00;
}</code>```

1

2

3

4

5
```
</div>
</div>
</p>

<p>In case you specifically want to use <code>.hover( handlerIn, handlerOut )</code> then the above snippet would be re-written like in the below snippet...</p>

<blockquote>
  <p>Notice the <code>handlerIn</code> and <code>handlerOut</code> functions being used.</p>
</blockquote>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$( ".box" ).hover(
  function() {
    $( this ).animate({ fontSize : '2rem' }).addClass('red');
  }, function() {
    $( this ).animate({ fontSize : '1rem' }).removeClass('red');
  }
);</code>```

.red {
color:#f00;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="box">5</div></code>```

Body:
How to animate only one element (div) each time, having class .box and not affect the other elements with same class. Something like this :

$(.box).hover(function() {
        $(.box).animate({ fontSize : '2rem' });
        $(.box).removeClass("main");
        // other things...

html:

I tried with .next() and .find() but I did not succeed because of my basic level in jQuery.

Body:
EDIT

Due to correct comment this answer has been edited. You could try the following in case you would want to bind different, multiple (e.g. mouseover focus) events, benefit of using .on().

$(".box").on({
  mouseover: function() {
      $(this).animate({ fontSize : '2rem' }).addClass('red');
  },
  mouseleave: function() {
      $(this).animate({ fontSize : '1rem' }).removeClass('red');
  }
});

.red {
color:#f00;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="box">5</div>

In case you specifically want to use .hover( handlerIn, handlerOut ) then the above snippet would be re-written like in the below snippet...

Notice the handlerIn and handlerOut functions being used.

$( ".box" ).hover(
  function() {
    $( this ).animate({ fontSize : '2rem' }).addClass('red');
  }, function() {
    $( this ).animate({ fontSize : '1rem' }).removeClass('red');
  }
);

.red {
color:#f00;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="box">5</div>


问:
What is a good separation between UI and logic?
I am trying to create some n-tier application and I am having difficulties separating the UI and the logic and I am wondering what belongs to the UI and what belongs to the logic.

For example a simple application which allows you to login and then asks the user to fill in a form or display a list of previous forms. I can think of two possible solutions:

The logic tells the UI it needs to login, the UI then asks the user for the username and password and sends it to the logic. The logic then tells the UI it needs to ask the user if they want to fill in a form or display the previous forms. The UI then sends this choice to the logic and the logic tells the UI to display a form or to display the list.
Here the UI has no state and is really dumb, basically the logic has to tell the UI what to show and when to show it.

The UI shows a login form and when the user enters the username/password, the UI sends those to the logic to login. If the login was successfull, the UI asks the user what to do, if the user wants to show the form it displays the form, if it wants to display the list, the UI asks the logic for a list of items to display.
Here the UI has state and makes decisions about what to show next on its own. The logic is only used for providing information to the UI and for processing information send by the UI. The logic has no state and just does what the UI tells it to do.

I like 1 because the UI is stateless and if the UI crashes (but not the logic which runs in a different process) you can restart the UI and continue in the same place before it crashed. It makes the UI very light weight and simple. But I am wondering which is better:
put the state about what the user is doing in the UI or in the logic.

edit:

I found a document describing where to put logic but it is mainly on  logic and data, not the UI. Is there a similar document describing the logic and UI part?

答: What you are looking for is probably MVC (en.wikipedia.org/wiki/MVC), that being said, the composition and the display of an UI (view) should be separated from the business rules and ultimately, these should be separated from the data itself.</p>


问:
How to create a class that only refresh in Puppet
It is possible to create a class that only executes when receives a notification event? I want to do exactly what "exec" does with "refreshonly", I could not find how to do this. Specifically, what I want to do is:

I have an archive resource, that downloads a file, with a "create" attribute:

```<code>archive { "/opt/service/service-${version}.jar":
    source        => "http://[ARTIFACT_URL]/service-${version}.jar",
    creates       => "/opt/service/service-${version}.jar",
    cleanup       => false,
}
</code>```

I would like to do this:

```<code>Archive["/opt/service/service-${version}.jar"] ~> Some_custom_class['some_title']
</code>```

But "Some_custom_class" can only execute when the archive downloads the file, that is when a notification event is triggered.

Thanks!

答:
It is possible to create a class that only executes when receives a notification event?

No.  And for that reason, it is best to avoid conceptualizing Exec resources as behaving as you describe.  Every resource declared in a node's catalog is synced with the node on each run, except inasmuch as a resource failure may prevent other resources from being synced, according to established relationships.  Resources that are successfully synced and that also receive an event from another resource are also refreshed, though for many resource types, the refresh action is a no-op.

There are no exceptions, or at least it is comfortable and consistent to conceptualize Puppet's behavior that way.  To that end, we can reconcile the effect of refreshonly => true on an Exec resource by interpreting it as declaring unconditionally that the resource is initially in sync, instead of whether it is initially in sync being determined in accordance with its onlyif, unless, and creates parameters (and defaulting to "no").  Since such an Exec is already in sync at the start of a run, syncing it does not involve taking any action.  Classes have no analogous feature.

As for what you are trying to achieve, I recommend a combination of declaring Exec resources belonging to the class as being refreshonly (which might be conveniently achieved by declaring that as a resource default) and allowing other resources to sync.

Body:
It is possible to create a class that only executes when receives a notification event? I want to do exactly what "exec" does with "refreshonly", I could not find how to do this. Specifically, what I want to do is:

I have an archive resource, that downloads a file, with a "create" attribute:

archive { "/opt/service/service-${version}.jar":
    source        => "http://[ARTIFACT_URL]/service-${version}.jar",
    creates       => "/opt/service/service-${version}.jar",
    cleanup       => false,
}

I would like to do this:

Archive["/opt/service/service-${version}.jar"] ~> Some_custom_class['some_title']

But "Some_custom_class" can only execute when the archive downloads the file, that is when a notification event is triggered.

Thanks!


问:
how much data to hold in memory when looping through large dataset
I am trying to create a trading simulator to test strategies over long periods of time.

I am using 1 minute data points. So if I were to run a simulation for say 10 years that would be approx 3,740,000 prices (Price class shown below). A simulation could be much longer than 10 years but using this an example.

```<code>     class Price
     {
          DateTime DatePrice
          double Open
          double High
          double Low
          double Close
     }
</code>```

My simulator works however I can't help feeling the way I'm doing it isn't very optimal.

So currently what I do is to grab a years worth of prices from my SQL database so approx 374,400 prices. I do this because I don't want to use too much memory (this might be misguided have no idea).

Now when looping through time the code will also make use of the previous lets say 10 prices. So at 2.30am the code will look back the prices from 2.20am, all the prices previous to this are now redundant. So it seems somewhat wasteful to me if I hold 374,400 prices in memory.

```<code>            time       Close
            00:00      102
            00:01      99
            00:02      100
            ...
            02:20      84
            02:21      88
</code>```

So I have a loop that will loop through from my start date to my end date, checking at each step if I need to download additional prices from the database.

```<code>   List<Price> PriceList = Database.GetPrices(first years worth or prices)

   for(DateTime dtNow = dtStart; dtNow < dtEnd; dtNow = dtNow.AddMinutes(1))
   {
         // run some calculations which doesn't take long

         // then check if PriceList[i] == PriceList.Count - 1
         // if so get more prices from the database and obviously reset i to zero but baring in mind I need to keep the previous 10 prices
   }
</code>```

What is the best solution for this kind of problem? Should I be getting prices from the database on another thread or something?

答:
Lets do some math

```<code>class Price
{
    DateTime DatePrice;
    double Open;
    double High;
    double Low;
    double Close;
}
</code>```

has a size of 8(DateTime)+4*8(double) = 40 alone for the members. Since it is a reference type you need a method table pointer and a SyncBlock pointer which add 16 byte additionally. Since you need to keep the pointer to the object (8 bytes on x64) somewhere we get a total size per instance of 64 bytes.

If you want to have a 10 year history with 3,7 million instances you will need  237 MB of memory which is not much in todays world.

You can shave off some overhead by switching from double to floats which will need only 4 bytes and if you go with a struct

```<code>struct Price
{
    DateTime DatePrice;
    float Open;
    float High;
    float Low;
    float Close;
}
</code>```

You will need only 24 bytes with no big loss of precision since the value range of stocks are not so high and you are interested in a long term trend or pattern and not 0,000000x fractions.

With this struct your 10 year time horizon will cost you only 88MB and it will keep the garbage collector off your data because it is opaque for the GC (no reference types inside your struct).

That simple optimization should be good enough for time horizons which span hundreds of years even with todays computers and memory sizes. It would even fit into an x86 address space but I would recommend running this on x64 because I suspect you will check not only one stock but several ones in parallel.

Body:
I am trying to create a trading simulator to test strategies over long periods of time.

I am using 1 minute data points. So if I were to run a simulation for say 10 years that would be approx 3,740,000 prices (Price class shown below). A simulation could be much longer than 10 years but using this an example.

     class Price
     {
          DateTime DatePrice
          double Open
          double High
          double Low
          double Close
     }

My simulator works however I can't help feeling the way I'm doing it isn't very optimal.

So currently what I do is to grab a years worth of prices from my SQL database so approx 374,400 prices. I do this because I don't want to use too much memory (this might be misguided have no idea).

Now when looping through time the code will also make use of the previous lets say 10 prices. So at 2.30am the code will look back the prices from 2.20am, all the prices previous to this are now redundant. So it seems somewhat wasteful to me if I hold 374,400 prices in memory.

            time       Close
            00:00      102
            00:01      99
            00:02      100
            ...
            02:20      84
            02:21      88

So I have a loop that will loop through from my start date to my end date, checking at each step if I need to download additional prices from the database.

   List<Price> PriceList = Database.GetPrices(first years worth or prices)

   for(DateTime dtNow = dtStart; dtNow < dtEnd; dtNow = dtNow.AddMinutes(1))
   {
         // run some calculations which doesn't take long

         // then check if PriceList[i] == PriceList.Count - 1
         // if so get more prices from the database and obviously reset i to zero but baring in mind I need to keep the previous 10 prices
   }

What is the best solution for this kind of problem? Should I be getting prices from the database on another thread or something?

Body:
Lets do some math

class Price
{
    DateTime DatePrice;
    double Open;
    double High;
    double Low;
    double Close;
}

has a size of 8(DateTime)+4*8(double) = 40 alone for the members. Since it is a reference type you need a method table pointer and a SyncBlock pointer which add 16 byte additionally. Since you need to keep the pointer to the object (8 bytes on x64) somewhere we get a total size per instance of 64 bytes.

If you want to have a 10 year history with 3,7 million instances you will need  237 MB of memory which is not much in todays world.

You can shave off some overhead by switching from double to floats which will need only 4 bytes and if you go with a struct

struct Price
{
    DateTime DatePrice;
    float Open;
    float High;
    float Low;
    float Close;
}

You will need only 24 bytes with no big loss of precision since the value range of stocks are not so high and you are interested in a long term trend or pattern and not 0,000000x fractions.

With this struct your 10 year time horizon will cost you only 88MB and it will keep the garbage collector off your data because it is opaque for the GC (no reference types inside your struct).

That simple optimization should be good enough for time horizons which span hundreds of years even with todays computers and memory sizes. It would even fit into an x86 address space but I would recommend running this on x64 because I suspect you will check not only one stock but several ones in parallel.