问:
Corret way to set up inline function
I want to define an inline function in c++. For example, in the header file of this function fun.h I had

```<code>#ifndef FUN_H
#define FUN_H

void fun(int);

#endif // FUN_H
</code>```

and in the source file fun.cpp I had

```<code>#include "fun.h"

inline void fun(int a){
    return ++a;
}
</code>```

I know this is one way to define an inline function but I did see plenty of people saying that the implementation of an inline function should directly be in the header file fun.h, which means the following pattern,

```<code>#ifndef FUN_H
#define FUN_H

inline void fun(int a){
    return ++a;
}

#endif // FUN_H
</code>```

However, I do not want to squeeze all the codes together so I coded like this,

```<code>#ifndef FUN_H
#define FUN_H

void fun(int);

inline void fun(int a){
    return ++a;
}
#endif // FUN_H
</code>```

Is this a correct style so that the function can be thought as an inline function?

Btw, someone told me that if I put the definition of an inline function in a source file, it may cause an “undefined reference to” problem when linking. I did encounter this problem once and the solution is to delete the "inline" keyword in the source file. However, there are still some functions that have their definitions in the source file with inline keywords. This functions did not trigger any linking errors so I am confused now about the right way to use the "inline" keyword.

Does anyone have some ideas on it?

答:
The inline keyword tells the compiler that the function can be defined in multiple compilation units so long as all of the definitions are exactly the same.  That's it.  Nothing more, nothing less.

What this means is that marking a function that's defined in a .cpp file inline doesn't really do anything, unless you're planning to manually copy/paste that definition into multiple .cpp files (which you obviously shouldn't be doing).

As for having vs. not having a separate declaration: that's entirely a matter of style.  I find it redundant, but some people like to forward-declare all of their functions so they never have to worry about defining them in the right order if some of the call others.

Title: Corret way to set up inline function

Body:
I want to define an inline function in c++. For example, in the header file of this function fun.h I had

#ifndef FUN_H
#define FUN_H

void fun(int);

#endif // FUN_H

and in the source file fun.cpp I had

#include "fun.h"

inline void fun(int a){
    return ++a;
}

I know this is one way to define an inline function but I did see plenty of people saying that the implementation of an inline function should directly be in the header file fun.h, which means the following pattern,

#ifndef FUN_H
#define FUN_H

inline void fun(int a){
    return ++a;
}

#endif // FUN_H

However, I do not want to squeeze all the codes together so I coded like this,

#ifndef FUN_H
#define FUN_H

void fun(int);

inline void fun(int a){
    return ++a;
}
#endif // FUN_H

Is this a correct style so that the function can be thought as an inline function?

Btw, someone told me that if I put the definition of an inline function in a source file, it may cause an “undefined reference to” problem when linking. I did encounter this problem once and the solution is to delete the "inline" keyword in the source file. However, there are still some functions that have their definitions in the source file with inline keywords. This functions did not trigger any linking errors so I am confused now about the right way to use the "inline" keyword.

Does anyone have some ideas on it?


来源: stackexchange

问:
C# Compare two lists with objects
i'm making simple program, and i'm stuck on simple question. How can i compare two lists with objects , find that object and print all class elements that belongs to that object?

```<code> List<Skaitytojas> MyObjectList = new List<Skaitytojas>();
 List<Knyga> KnyguList = new List<Knyga>();

 private void button2_Click(object sender, EventArgs e)
    {
        Reader reader = new Reader();

        reader._surname = Convert.ToString(textBox1.Text);
        reader._id = Convert.ToInt32(textBox2.Text);

        MyObjectList.Add(reader);
        MessageBox.Show("you created new user");
    }

private void button4_Click(object sender, EventArgs e)
    {
        Book new_book = new Book();

       new_book.book_id = Convert.ToInt32(textBox3.Text);
        new_book.date1 = Convert.ToString(textBox4.Text);
        new_book.date2 = Convert.ToString(textBox5.Text);
        new_book.date3 = Convert.ToString(textBox6.Text);
       new_book._id2 = Convert.ToInt32(textBox7.Text);

        BookList.Add(new_book);
        MessageBox.Show("you added new book!");
    }
</code>```

I want to compare reader._id with new_book.id2, its gonna be same number , and if i find it i want to print all information about it: book id,date1,date2 etc.
But i don't know how to do it, i tried it this way:

```<code>public void print_book(int x, ListBox f)
    {
        List<Book> BookList = new List<Book>();
        foreach (var k in BookList)
        {
            if (x == k._id2)
            {
                f.Items.Add(x);
            }
        }
    }
</code>```

Call function with button

```<code>private void button3_Click(object sender, EventArgs e)
    {

        int x = Convert.ToInt32(textBox2.Text);
        Metodai m = new Metodai();
        m.print_book(x, this.listBox1);
    }
</code>```

When i try to do this function the list is still empty, whats wrong with it? Maybe there is another way to do it? Can you help me?

答:
You created a function variable 'BookList' with the same name as that of instance variable.

There are two ways to fix it.

```<code>// Fix #1
public void print_book(int x, ListBox f)
{
    //List<Book> BookList = new List<Book>(); // Comment this line
    foreach (var k in BookList)
    {
        if (x == k._id2)
        {
            f.Items.Add(x);
        }
    }
}

// Fix #2
public void print_book(int x, ListBox f)
{
    List<Book> BookList = new List<Book>(); // 'BookList' has never been used
    foreach (var k in this.BookList) // Add 'this'
    {
        if (x == k._id2)
        {
            f.Items.Add(x);
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: C# Compare two lists with objects

Body:
i'm making simple program, and i'm stuck on simple question. How can i compare two lists with objects , find that object and print all class elements that belongs to that object?

 List<Skaitytojas> MyObjectList = new List<Skaitytojas>();
 List<Knyga> KnyguList = new List<Knyga>();

 private void button2_Click(object sender, EventArgs e)
    {
        Reader reader = new Reader();

        reader._surname = Convert.ToString(textBox1.Text);
        reader._id = Convert.ToInt32(textBox2.Text);

        MyObjectList.Add(reader);
        MessageBox.Show("you created new user");
    }

private void button4_Click(object sender, EventArgs e)
    {
        Book new_book = new Book();

       new_book.book_id = Convert.ToInt32(textBox3.Text);
        new_book.date1 = Convert.ToString(textBox4.Text);
        new_book.date2 = Convert.ToString(textBox5.Text);
        new_book.date3 = Convert.ToString(textBox6.Text);
       new_book._id2 = Convert.ToInt32(textBox7.Text);

        BookList.Add(new_book);
        MessageBox.Show("you added new book!");
    }

I want to compare reader._id with new_book.id2, its gonna be same number , and if i find it i want to print all information about it: book id,date1,date2 etc.
But i don't know how to do it, i tried it this way:

public void print_book(int x, ListBox f)
    {
        List<Book> BookList = new List<Book>();
        foreach (var k in BookList)
        {
            if (x == k._id2)
            {
                f.Items.Add(x);
            }
        }
    }

Call function with button

private void button3_Click(object sender, EventArgs e)
    {

        int x = Convert.ToInt32(textBox2.Text);
        Metodai m = new Metodai();
        m.print_book(x, this.listBox1);
    }

When i try to do this function the list is still empty, whats wrong with it? Maybe there is another way to do it? Can you help me?

Body:
You created a function variable 'BookList' with the same name as that of instance variable.

There are two ways to fix it.

// Fix #1
public void print_book(int x, ListBox f)
{
    //List<Book> BookList = new List<Book>(); // Comment this line
    foreach (var k in BookList)
    {
        if (x == k._id2)
        {
            f.Items.Add(x);
        }
    }
}

// Fix #2
public void print_book(int x, ListBox f)
{
    List<Book> BookList = new List<Book>(); // 'BookList' has never been used
    foreach (var k in this.BookList) // Add 'this'
    {
        if (x == k._id2)
        {
            f.Items.Add(x);
        }
    }
}


问:
Regex: Get everything after the first occurrence of a space after a word
I need to get all the characters after the first space after a string.
E.g. I need to get {'s':'2'} from a string that is of format:

```<code>a=1 session=<value> {'s'='2'}
</code>```

The value will be of random length without space and there will be space before {'s'='2'}. So {'s'='2'} will always occur after the string 'session=' and the first space after that and there will be variable number of key value pairs like a=1 before session.

E.g.

```<code>From: a=1 b=2 session=sdasdsadsa {'foo':'2'}         # I need to get {'foo':'2'}
From: a=1 b=2  c=3 session=s2312dssdaa {'bar':'3'}   # I need to get {'bar':'3'}
</code>```

答:
Simple one liner:

```<code>print(string.split(substr)[1][1:])
</code>```

Where string is your string and substr is the substring.

This breaks the string into lists then joins the second to last values with a space again.

Output:

```<code>>>> string = "a=1 session=<value> {'s'='2'}"
>>> substr = "session=<value>"
>>> print(string.split(substr)[1][1:])
{'s'='2'}
>>>
</code>```

Body:
I need to get all the characters after the first space after a string.
E.g. I need to get {'s':'2'} from a string that is of format:

a=1 session=<value> {'s'='2'}

The value will be of random length without space and there will be space before {'s'='2'}. So {'s'='2'} will always occur after the string 'session=' and the first space after that and there will be variable number of key value pairs like a=1 before session.

E.g.

From: a=1 b=2 session=sdasdsadsa {'foo':'2'}         # I need to get {'foo':'2'}
From: a=1 b=2  c=3 session=s2312dssdaa {'bar':'3'}   # I need to get {'bar':'3'}

Body:
Simple one liner:

print(string.split(substr)[1][1:])

Where string is your string and substr is the substring.

This breaks the string into lists then joins the second to last values with a space again.

Output:

>>> string = "a=1 session=<value> {'s'='2'}"
>>> substr = "session=<value>"
>>> print(string.split(substr)[1][1:])
{'s'='2'}
>>>


问:
Sed only one-liner
I need to use sed to parse out some text.  I can't use cut because of some syntax it causes with Ansible in this particular case.  I was hoping to achieve this just with sed.  This is a single line of text.

```<code>    "_ref": "record:host/ZG5zLmhvc3QkLl9kZWZhdWx0Lm5ldC5kdHZvcHMuYW5keXRlc3QwMg:pootest02.catt.net/Internal"
</code>```

I need to print out everything after the third "(quote) and before the third :(colon).

My expected outcome should be:

```<code>    record:host/ZG5zLmhvc3QkLl9kZWZhdWx0Lm5ldC5kdHZvcHMuYW5keXRlc3QwMg
</code>```

Any help or direction is greatly appreciated.

答:
This is what ended up working beautifully:

sed -n -e 's#.*\(record:[^:]\+\):.*#\1#p'

Title: Sed only one-liner

Body:
I need to use sed to parse out some text.  I can't use cut because of some syntax it causes with Ansible in this particular case.  I was hoping to achieve this just with sed.  This is a single line of text.

    "_ref": "record:host/ZG5zLmhvc3QkLl9kZWZhdWx0Lm5ldC5kdHZvcHMuYW5keXRlc3QwMg:pootest02.catt.net/Internal"

I need to print out everything after the third "(quote) and before the third :(colon).

My expected outcome should be:

    record:host/ZG5zLmhvc3QkLl9kZWZhdWx0Lm5ldC5kdHZvcHMuYW5keXRlc3QwMg

Any help or direction is greatly appreciated.


问:
Errors using any Heroku command
Any time I use any Heroku command I get this error. So far the commands have still worked so I haven't thought much about it:

```<code>/Library/Ruby/Site/1.8/rubygems/custom_require.rb:31: command not found:  git config heroku.remote
</code>```

However now when I try heroku db:pull, I get this error. Not sure if the two are related, but either way I could use help solving one or both.

```<code>/Library/Ruby/Gems/1.8/gems/taps-0.3.15/bin/schema:3:in `require': no such file to load -- rubygems (LoadError)
    from /Library/Ruby/Gems/1.8/gems/taps-0.3.15/bin/schema:3
Schema:        100% |==========================================| Time: 00:00:08
Receiving indexes
/Library/Ruby/Gems/1.8/gems/taps-0.3.15/bin/schema:3:in `require': no such file to load -- rubygems (LoadError)
    from /Library/Ruby/Gems/1.8/gems/taps-0.3.15/bin/schema:3
schema_migrat: 100% |==========================================| Time: 00:00:00
Receiving data
13 tables, 6,957 records
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4/lib/sqlite3/errors.rb:62:in `check': SQLite3::SQLException: PRIMARY KEY must be unique (Sequel::DatabaseError)
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4/lib/sqlite3/resultset.rb:56:in `check'
</code>```

答:
Heroku has some information on this here (down at the bottom):

Troubleshooting

Command not found

On some machines your path may not be
  set correctly to run binary gems. If
  you get a command not found error, you
  need to add the rubygems executable
  directory to your path. You can find
  the EXECUTABLE_DIRECTORY by running

$ gem environment

And then setting
  your path to include the appropriate
  directory:

$ export PATH=/opt/ruby-enterprise-1.8.6-20090201/bin:$PATH

And it links back to this StackOverflow article (how meta): How do I use gems with Ubuntu?

Title: Errors using any Heroku command

Body:
Any time I use any Heroku command I get this error. So far the commands have still worked so I haven't thought much about it:

/Library/Ruby/Site/1.8/rubygems/custom_require.rb:31: command not found:  git config heroku.remote

However now when I try heroku db:pull, I get this error. Not sure if the two are related, but either way I could use help solving one or both.

/Library/Ruby/Gems/1.8/gems/taps-0.3.15/bin/schema:3:in `require': no such file to load -- rubygems (LoadError)
    from /Library/Ruby/Gems/1.8/gems/taps-0.3.15/bin/schema:3
Schema:        100% |==========================================| Time: 00:00:08
Receiving indexes
/Library/Ruby/Gems/1.8/gems/taps-0.3.15/bin/schema:3:in `require': no such file to load -- rubygems (LoadError)
    from /Library/Ruby/Gems/1.8/gems/taps-0.3.15/bin/schema:3
schema_migrat: 100% |==========================================| Time: 00:00:00
Receiving data
13 tables, 6,957 records
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4/lib/sqlite3/errors.rb:62:in `check': SQLite3::SQLException: PRIMARY KEY must be unique (Sequel::DatabaseError)
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4/lib/sqlite3/resultset.rb:56:in `check'

ContentLicense: CC BY-SA 2.5


问:
Is the iOS Local Notification Limit Per Day?
I'm working on an app where I need to send a good amount of notifications to the user daily. Around 5-40 depending on the user.

I'm using local notifications to send it, but I know there is a 64 notification limit. Does this mean 64 notifications per day, or in total?

答:
It means simultaneously scheduled for future delivery. You can send as many as you want per day, provided they don't overlap.

If you add more than 64 requests (under UserNotifications) or scheduled (under UIApplication/UILocalNotification), the older ones will be dropped and not delivered.


问:
JS - Object Constructor Methods
I am trying to make an object that includes the teams points (as shown below where it says "this.update"). When I run the program it does not seem to give the points to the teams and it does not seem to even evaluate both teams' goals.

I want the team1Points and team2Points properties to be derived from an IF statement like the one above or another solution would help, akin to the 1 point to both teams for a draw, 3 points for a win, 0 for a loss.

teamsArray = ["Blue Team", "Red Team"];

function match(team1Name, team2Name, team1Goals, team2Goals) {
  this.team1Name = team1Name;
  this.team1Goals = team1Goals;
  this.team2Name = team2Name;
  this.team2Goals = team2Goals;
  this.update = function() {
    if (team1Goals > team2Goals) {
      team1Points = 3;
      team2Points = 0;
    } else if (team2Goals > team1Goals) {
      team2Points = 3;
      team1Points = 0;
    } else if (team1Goals == team2Goals) {
      team1Points = 1;
      team2Points = 1;
    }
  };
  this.update();
}

testMatch();

function testMatch() {
  var match1 = new match(teamsArray[0], teamsArray[1], 2, 0);
  console.log(match1);
}```

答:
teamsArray = ["Blue Team", "Red Team"];

function match(team1Name, team2Name, team1Goals, team2Goals) {
  this.team1Name = team1Name;
  this.team1Goals = team1Goals;
  this.team2Name = team2Name;
  this.team2Goals = team2Goals;
  this.update = function() {
    if (team1Goals > team2Goals) {
      this.team1Points = 3;
      this.team2Points = 0;
    } else if (team2Goals > team1Goals) {
      this.team2Points = 3;
      this.team1Points = 0;
    } else if (team1Goals == team2Goals) {
      this.team1Points = 1;
      this.team2Points = 1;
    }
  };
  this.update();
}

testMatch();

function testMatch() {
  var match1 = new match(teamsArray[0], teamsArray[1], 2, 0);
  console.log(match1);
}```

Title: JS - Object Constructor Methods


问:
Twilio call usage paging
I am trying to get a paged list of call records from Twilio

```<code>var records = Twilio.Rest.Api.V2010.Account.CallResource.Read(pageSize: 10).ToList();
</code>```

But nowhere is there anywhere to specify what the page number to retrieve is? How would I do this?

答:
Sales Engineer at Twilio here.

There isn't a way to go to a specific page. You can navigate through the pages using the previous_page_uri and next_page_uri fields. I think the philosophy is that pages are a very implicit/arbitrary way of navigating your data. It's better to be explicit about what you're actually looking for, e.g., "Records from this date to this date" by using query parameters like this:

Category=calls&StartDate=2017-10-13&EndDate=2017-10-13"

Title: Twilio call usage paging

Body:
I am trying to get a paged list of call records from Twilio

var records = Twilio.Rest.Api.V2010.Account.CallResource.Read(pageSize: 10).ToList();

But nowhere is there anywhere to specify what the page number to retrieve is? How would I do this?


问:
Getline not reading from file correctly?
Working on a project where I need to fill a file with numbers and use a getline to read those numbers line by line and then display the total, average, max, and min from each line. Everything's in place except my getline doesn't seem to be working as the output for the total, average, etc, is always 0. Any help at all is appreciated. Thanks!</p>

```<code>#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ofstream myfile;
    myfile.open("file.txt");
    if(!myfile)
    {
        cout << "Unable to open file\n";
        return 0;
    }
    if(myfile.is_open())
    {
        myfile << "Numbers: \n";
        myfile << "90 63 84 52 21 93 77 46\n";
        myfile << "90 22 26 34 39 44 75 98\n";
        myfile << "28 28 85 57 28 33 66 100\n";
        myfile << "16 80 74 62 42 84 42 56\n";
        myfile << "85 44 76 97 16 64 80 14\n";
        myfile << "41 85 13 88 78 8 18 38\n";
        myfile << "53 49 71 79 75 57 93 62\n";

        fstream infile;
        infile.open("file.txt");
        int total, average, max=0, min=0, num;
        while(!infile.eof())
        {
            string line;
            getline(infile, line);
            int a, b, c, d, e, f, g, h, i;
            infile >> a >> b >> c >> d >> e >> f >> g >> h >> i;
            total = a+b+c+d+e+f+g+h+i;
            average = total/7;
            while(infile>>num)
            {
                max = num;
                min = num;
                if(max<num)
                {
                    max = num;
                }
                if(min > num)
                {
                    min = num;
                }
            }
            myfile << "                               TOTAL        AVERAGE      MAX      MIN\n";
            myfile << "90 63 84 52 21 93 77 46    " << total << "  " << average << "  " << max << "  " << min << endl;
            myfile << "90 22 26 34 39 44 75 98\n";
            myfile << "28 28 85 57 28 33 66 100\n";
            myfile << "16 80 74 62 42 84 42 56\n";
            myfile << "85 44 76 97 16 64 80 14\n";
            myfile << "41 85 13 88 78 8 18 38\n";
            myfile << "53 49 71 79 75 57 93 62\n";
        }
        infile.close();
    }
    myfile.close();
    return 0;
}
</code>```

答:
all sorts of funky things going on here

First opening a file for writing, then opening it for reading and writing to it while reading might work but looks odd. Better to write a new file out in the second phase

Second, you write 8 numbers , read 9 and divide total by 7 to get mean. Thats surely broken.

The style is odd, using a while loop and then inside that loop running out to end of file with another while loop. Is that really what you mean? That while on min and max will read the whole file

in your max and min, you should set min to a very large number, not 0. Other wise min>num will never be true

Body:
Working on a project where I need to fill a file with numbers and use a getline to read those numbers line by line and then display the total, average, max, and min from each line. Everything's in place except my getline doesn't seem to be working as the output for the total, average, etc, is always 0. Any help at all is appreciated. Thanks!

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ofstream myfile;
    myfile.open("file.txt");
    if(!myfile)
    {
        cout << "Unable to open file\n";
        return 0;
    }
    if(myfile.is_open())
    {
        myfile << "Numbers: \n";
        myfile << "90 63 84 52 21 93 77 46\n";
        myfile << "90 22 26 34 39 44 75 98\n";
        myfile << "28 28 85 57 28 33 66 100\n";
        myfile << "16 80 74 62 42 84 42 56\n";
        myfile << "85 44 76 97 16 64 80 14\n";
        myfile << "41 85 13 88 78 8 18 38\n";
        myfile << "53 49 71 79 75 57 93 62\n";

        fstream infile;
        infile.open("file.txt");
        int total, average, max=0, min=0, num;
        while(!infile.eof())
        {
            string line;
            getline(infile, line);
            int a, b, c, d, e, f, g, h, i;
            infile >> a >> b >> c >> d >> e >> f >> g >> h >> i;
            total = a+b+c+d+e+f+g+h+i;
            average = total/7;
            while(infile>>num)
            {
                max = num;
                min = num;
                if(max<num)
                {
                    max = num;
                }
                if(min > num)
                {
                    min = num;
                }
            }
            myfile << "                               TOTAL        AVERAGE      MAX      MIN\n";
            myfile << "90 63 84 52 21 93 77 46    " << total << "  " << average << "  " << max << "  " << min << endl;
            myfile << "90 22 26 34 39 44 75 98\n";
            myfile << "28 28 85 57 28 33 66 100\n";
            myfile << "16 80 74 62 42 84 42 56\n";
            myfile << "85 44 76 97 16 64 80 14\n";
            myfile << "41 85 13 88 78 8 18 38\n";
            myfile << "53 49 71 79 75 57 93 62\n";
        }
        infile.close();
    }
    myfile.close();
    return 0;
}


问:
Angular universal styling FOUC on server to client transition
I have an issue with my universal app, where when the server side app is swapped for the client side app, there is a moment when there is no styling for the components which are part of my routed component for that page. This results in the page loading correctly, then momentarily displaying a flash of unstyled content (FOUC) and looking horrible, before sorting itself out.

The styling for my website header and footer components look fine the whole time, but the components that load inside the <router-outlet> element are the ones that do not have the correct styling.

I am using Preboot to manage the server > client transition and not doing anything outside of the standard configuration. I have experimented using @ngx-universal/state-transfer and @ngx-cache libraries, but I don't think they are what I need.

I am using lazy loaded routes, but I have experimented with removing these and the error is the same. I have also tried setting { initialNavigation: 'enabled' } in my routing config.

I use webpack to build my server side app, and the Angular CLI for the client side one, mostly based on this project, and I use the AOT compiler. Any ideas would be very appreciated, thanks!

答:
So the solution I ended up going with here was to create a StyleStateTransferService which utilises the @ngx-universal/state-transfer library.

In the server side app, I pull the angular styles out of the head and add them into the state transfer service. In the client side app I get the styles out of the transferred state and add them into the head. Once Angular has finished bootstrapping I then go through and remove the ones I added in, just so there's no duplicates hanging around.

I don't know if it is the best solution, maybe someone has a better one, I was initially hoping there was just some configuration I was missing from preboot, but it doesn't seem so.

Service:

```<code>@Injectable()
export class StyleStateTransferService {
  document: any;
  window: Window;
  renderer: Renderer2;
  ngStyleId = 'ng_styles';

  constructor(private stateTransferService: StateTransferService,
              @Inject(DOCUMENT) document: any,
              private winRef: WindowRef,
              private rendererFactory: RendererFactory2) {
    this.window = winRef.nativeWindow;
    this.document = document;
    this.renderer = rendererFactory.createRenderer(this.document, null);
  }

  addStylesToState() {
    const styles: string[] = this.document.head.children
      // elements have a weird structure on the server
      // this filters to style tags with the ng-transition attribute that have content
      .filter(el =>
        el.name === 'style' && el.attribs['ng-transition'] && el.firstChild && el.firstChild.data)
      // extract the css content of the style tags
      .map(el => el.firstChild.data.replace(/\n/g, ' '));

    this.stateTransferService.set(this.ngStyleId, styles);
    this.stateTransferService.inject();
  }

  injectStylesFromState() {
    const styles = _.get(this.window, `${DEFAULT_STATE_ID}.${this.ngStyleId}`, []);
    styles.forEach(content => {
      const styleEl = this.renderer.createElement('style');
      // set this attribute so we can remove them later
      this.renderer.setAttribute(styleEl, 'ng-state-transfer', null);
      this.renderer.setProperty(styleEl, 'innerHTML', content);
      this.renderer.appendChild(this.document.head, styleEl);
    });
  }

  cleanupInjectedStyles() {
    Array.from(<HTMLElement[]>this.document.head.children)
      .filter(htmlEl => htmlEl.tagName === 'STYLE' && htmlEl.hasAttribute('ng-state-transfer'))
      .forEach(styleEl => this.renderer.removeChild(this.document.head, styleEl));
}
</code>```

Using it in server and browser modules (clean up happens in app component but didn't seem worth showing):

```<code>export class AppServerModule {
  constructor(private appRef: ApplicationRef,
              private styleStateTransferService: StyleStateTransferService) {
    // waits until the app has fully initialised before adding the styles to the state
    this.appRef.isStable
      .filter(isStable => isStable)
      .first()
      .subscribe(() => {
        this.styleStateTransferService.addStylesToState();
      });
  }
}

export class AppBrowserModule {
  constructor(private styleStateTransferService: StyleStateTransferService) {
    this.styleStateTransferService.injectStylesFromState();
  }
}
</code>```

Body:
So the solution I ended up going with here was to create a StyleStateTransferService which utilises the @ngx-universal/state-transfer library.

In the server side app, I pull the angular styles out of the head and add them into the state transfer service. In the client side app I get the styles out of the transferred state and add them into the head. Once Angular has finished bootstrapping I then go through and remove the ones I added in, just so there's no duplicates hanging around.

I don't know if it is the best solution, maybe someone has a better one, I was initially hoping there was just some configuration I was missing from preboot, but it doesn't seem so.

Service:

@Injectable()
export class StyleStateTransferService {
  document: any;
  window: Window;
  renderer: Renderer2;
  ngStyleId = 'ng_styles';

  constructor(private stateTransferService: StateTransferService,
              @Inject(DOCUMENT) document: any,
              private winRef: WindowRef,
              private rendererFactory: RendererFactory2) {
    this.window = winRef.nativeWindow;
    this.document = document;
    this.renderer = rendererFactory.createRenderer(this.document, null);
  }

  addStylesToState() {
    const styles: string[] = this.document.head.children
      // elements have a weird structure on the server
      // this filters to style tags with the ng-transition attribute that have content
      .filter(el =>
        el.name === 'style' && el.attribs['ng-transition'] && el.firstChild && el.firstChild.data)
      // extract the css content of the style tags
      .map(el => el.firstChild.data.replace(/\n/g, ' '));

    this.stateTransferService.set(this.ngStyleId, styles);
    this.stateTransferService.inject();
  }

  injectStylesFromState() {
    const styles = _.get(this.window, `${DEFAULT_STATE_ID}.${this.ngStyleId}`, []);
    styles.forEach(content => {
      const styleEl = this.renderer.createElement('style');
      // set this attribute so we can remove them later
      this.renderer.setAttribute(styleEl, 'ng-state-transfer', null);
      this.renderer.setProperty(styleEl, 'innerHTML', content);
      this.renderer.appendChild(this.document.head, styleEl);
    });
  }

  cleanupInjectedStyles() {
    Array.from(<HTMLElement[]>this.document.head.children)
      .filter(htmlEl => htmlEl.tagName === 'STYLE' && htmlEl.hasAttribute('ng-state-transfer'))
      .forEach(styleEl => this.renderer.removeChild(this.document.head, styleEl));
}

Using it in server and browser modules (clean up happens in app component but didn't seem worth showing):

export class AppServerModule {
  constructor(private appRef: ApplicationRef,
              private styleStateTransferService: StyleStateTransferService) {
    // waits until the app has fully initialised before adding the styles to the state
    this.appRef.isStable
      .filter(isStable => isStable)
      .first()
      .subscribe(() => {
        this.styleStateTransferService.addStylesToState();
      });
  }
}

export class AppBrowserModule {
  constructor(private styleStateTransferService: StyleStateTransferService) {
    this.styleStateTransferService.injectStylesFromState();
  }
}


问:
Extract all values from data in JSON
I have a json response with multiple movie titles in "data". Is there a way to quickly extract them? I need an array with just movie titles.

```<code>{
  "page": "2",
  "per_page": 10,
  "total": 13,
  "total_pages": 2,
  "data": [{
    "Poster": "N/A",
    "Title": "They Call Me Spiderman",
    "Type": "movie",
    "Year": 2016,
    "imdbID": "tt5861236"
  }, {
    "Poster": "N/A",
    "Title": "The Death of Spiderman",
    "Type": "movie",
    "Year": 2015,
    "imdbID": "tt5921428"
  }, {
    "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BZDlmMGQwYmItNTNmOS00OTNkLTkxNTYtNDM3ZWVlMWUyZDIzXkEyXkFqcGdeQXVyMTA5Mzk5Mw@@._V1_SX300.jpg",
    "Title": "Spiderman in Cannes",
    "Type": "movie",
    "Year": 2016,
    "imdbID": "tt5978586"
  }]
}
</code>```

答:
```<code>var data = new Dictionary<string, string>();
data.Add("foo", "baa");

JavaScriptSerializer ser = new JavaScriptSerializer();
var JSONString = ser.Serialize(data); //JSON encoded

var JSONObj = ser.Deserialize<Dictionary<string, string>>(JSONString); //JSON decoded
Console.Write(JSONObj["foo"]); //prints: baa
</code>```

Title: Extract all values from data in JSON

Body:
I have a json response with multiple movie titles in "data". Is there a way to quickly extract them? I need an array with just movie titles.

{
  "page": "2",
  "per_page": 10,
  "total": 13,
  "total_pages": 2,
  "data": [{
    "Poster": "N/A",
    "Title": "They Call Me Spiderman",
    "Type": "movie",
    "Year": 2016,
    "imdbID": "tt5861236"
  }, {
    "Poster": "N/A",
    "Title": "The Death of Spiderman",
    "Type": "movie",
    "Year": 2015,
    "imdbID": "tt5921428"
  }, {
    "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BZDlmMGQwYmItNTNmOS00OTNkLTkxNTYtNDM3ZWVlMWUyZDIzXkEyXkFqcGdeQXVyMTA5Mzk5Mw@@._V1_SX300.jpg",
    "Title": "Spiderman in Cannes",
    "Type": "movie",
    "Year": 2016,
    "imdbID": "tt5978586"
  }]
}


答:
```<code>teamsArray = ["Blue Team", "Red Team"];

function match(team1Name, team2Name, team1Goals, team2Goals) {
  this.team1Name = team1Name;
  this.team1Goals = team1Goals;
  this.team2Name = team2Name;
  this.team2Goals = team2Goals;
  this.update = function() {
    if (team1Goals > team2Goals) {
      team1Points = 3;
      team2Points = 0;
      return "team1 win"
    } else if (team2Goals > team1Goals) {
      team2Points = 3;
      team1Points = 0;
      return "team2 win"
    } else if (team1Goals == team2Goals) {
      team1Points = 1;
      team2Points = 1;
      return "draw"
    }
  };
}

testMatch();

function testMatch() {
  var match1 = new match(teamsArray[0], teamsArray[1], 2, 0);

  console.log(match1.update());
}
</code>```

Title: JS - Object Constructor Methods

Body:
I am trying to make an object that includes the teams points (as shown below where it says "this.update"). When I run the program it does not seem to give the points to the teams and it does not seem to even evaluate both teams' goals.

I want the team1Points and team2Points properties to be derived from an IF statement like the one above or another solution would help, akin to the 1 point to both teams for a draw, 3 points for a win, 0 for a loss.

teamsArray = ["Blue Team", "Red Team"];

function match(team1Name, team2Name, team1Goals, team2Goals) {
  this.team1Name = team1Name;
  this.team1Goals = team1Goals;
  this.team2Name = team2Name;
  this.team2Goals = team2Goals;
  this.update = function() {
    if (team1Goals > team2Goals) {
      team1Points = 3;
      team2Points = 0;
    } else if (team2Goals > team1Goals) {
      team2Points = 3;
      team1Points = 0;
    } else if (team1Goals == team2Goals) {
      team1Points = 1;
      team2Points = 1;
    }
  };
  this.update();
}

testMatch();

function testMatch() {
  var match1 = new match(teamsArray[0], teamsArray[1], 2, 0);
  console.log(match1);
}


问:
Adding a string to highcharts tooltip based on a separate data series
I am trying to create a bar chart in highcharts using data from a django database back-end

the bar chart is plotting fine however, I need to show the ‘contact_note’ string in addition to the y-values upon hovering in the tooltip

The data from the database is being served in the following json format

```<code>{
  "chart_data": {
    "dates": [
      "12/12/16",
      "01/28/17",
      "02/10/17",
    ],
    "values": [
      9.0,
      47.0,
      13.0,
    ],
    "contact_notes": [
      "aa",
      "bb",
      "cc"
    ]
  }
}
</code>```

the dates represent the x-axis, the 'values' are the y-axis and I would like the tooltip to include the contents of the 'contact_note' field

Here’s my highcharts code:

```<code><script>

$(document).ready(function() {

     var options = {
        chart: {
            renderTo: 'chart_panel',
            type: 'column',
        },
        legend: {enabled: false},
        title: {text: 'Days Between Meetings'},
        tooltip: {
        formatter: function () {
            return "<span style='color:" + this.point.color + "'>\u25CF</span> " + this.series.name + " : <b>" + this.point.y + "</b> " +  contact_notes[this.point.index] + "<br/>";
        }},
        xAxis: {title: {text: null}, labels: {rotation: -45}},
        yAxis: {title: {text: null},
        plotLines: [{
                value: 20,
                color: 'orange',
                dashStyle: 'shortdash',
                width: 1.5}]
        },
        plotOptions: {column: {dataLabels: {enabled: true}}},
        series: [{}],
    };

    var chartDataUrl = "{% url 'chart_data' pk %}"

    $.getJSON(chartDataUrl,
        function(data) {
            options.xAxis.categories = data['chart_data']['dates'];
            options.series[0].name = 'Days between contacts';
            options.series[0].data = data['chart_data']['values'];

            var contact_notes = data['chart_data']['contact_notes'];

            var chart = new Highcharts.Chart(options);
    });

} );

</script>
</code>```

Is there a simple way for me to append the contact notes to the series tooltip?

Thanks so much

答:
Sure, save the data from the backend somewhere (I just left it in your returned data object) and use the tooltip formatter function.  The point is passed into the formatter and it has an index that you can use to index into your array.

http://jsfiddle.net/yjL551vp/

```<code>  tooltip: {
        formatter: function () {
            return "<span style='color:" + this.point.color + "'>\u25CF</span> " + this.series.name + " : <b>" + this.point.y + "</b> " +  data.chart_data.contact_notes[this.point.index] + "<br/>";
        }
    },
</code>```

EDIT:
Your current problem is that contact_notes is defined within your getJSON function, so it's out of scope in the formatter function.  Define the var outside the getJSON function

```<code>   var chartDataUrl = "{% url 'chart_data' pk %}"
   var contact_notes = [];
    $.getJSON(chartDataUrl,
        function(data) {
            options.xAxis.categories = data['chart_data']['dates'];
            options.series[0].name = 'Days between contacts';
            options.series[0].data = data['chart_data']['values'];

            contact_notes = data['chart_data']['contact_notes'];

            var chart = new Highcharts.Chart(options);
    });
</code>```

Body:
I am trying to create a bar chart in highcharts using data from a django database back-end

the bar chart is plotting fine however, I need to show the ‘contact_note’ string in addition to the y-values upon hovering in the tooltip

The data from the database is being served in the following json format

{
  "chart_data": {
    "dates": [
      "12/12/16",
      "01/28/17",
      "02/10/17",
    ],
    "values": [
      9.0,
      47.0,
      13.0,
    ],
    "contact_notes": [
      "aa",
      "bb",
      "cc"
    ]
  }
}

the dates represent the x-axis, the 'values' are the y-axis and I would like the tooltip to include the contents of the 'contact_note' field

Here’s my highcharts code:

Is there a simple way for me to append the contact notes to the series tooltip?

Thanks so much

Body:
Sure, save the data from the backend somewhere (I just left it in your returned data object) and use the tooltip formatter function.  The point is passed into the formatter and it has an index that you can use to index into your array.

http://jsfiddle.net/yjL551vp/

  tooltip: {
        formatter: function () {
            return "<span style='color:" + this.point.color + "'>\u25CF</span> " + this.series.name + " : <b>" + this.point.y + "</b> " +  data.chart_data.contact_notes[this.point.index] + "<br/>";
        }
    },

EDIT:
Your current problem is that contact_notes is defined within your getJSON function, so it's out of scope in the formatter function.  Define the var outside the getJSON function

   var chartDataUrl = "{% url 'chart_data' pk %}"
   var contact_notes = [];
    $.getJSON(chartDataUrl,
        function(data) {
            options.xAxis.categories = data['chart_data']['dates'];
            options.series[0].name = 'Days between contacts';
            options.series[0].data = data['chart_data']['values'];

            contact_notes = data['chart_data']['contact_notes'];

            var chart = new Highcharts.Chart(options);
    });


问:
cURL PUT Request with Nextcloud / owncloud API
I tried to update an existing Nextcloud user through their API. When I do it directly via shell it works

```<code>curl -u user:pass -X PUT "https://example.org/ocs/v1.php/cloud/users/admin" -H "OCS-APIRequest: true" -d key="quota" -d value="5GB"
</code>```

But when I try to do it via PHP with the following code it always returns "failure 997"

```<code>$url = 'https://' . $ownAdminname . ':' . $ownAdminpassword . '@example.org/ocs/v1.php/cloud/users/admin';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$fields = array("quota" => "5GB");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'OCS-APIRequest: true'
    ));
$response = curl_exec($ch);
curl_close($ch);
echo "Response: ".$response;
</code>```

答:
The difference between the cURL command and the PHP code you pasted lies in a poorly designed user provisioning API.

Using these cURL arguments:

```<code>-d key="quota" -d value="5GB"
</code>```

... is not equivalent to the fields you're posting:

```<code>$fields = array("quota" => "5GB");
</code>```

... but rather:

```<code>$fields = array(
    'key' => 'quota',
    'value' => '5GB',
);
</code>```

The explanation for the 997 code you're getting can be found in https://github.com/owncloud/core/blob/v10.0.3/apps/provisioning_api/lib/Users.php#L269-L272: since there's no "key" key in the data submitted ($parameters['_put']['key'] will evaluate as null) and hence the error.

Body:
I tried to update an existing Nextcloud user through their API. When I do it directly via shell it works

curl -u user:pass -X PUT "https://example.org/ocs/v1.php/cloud/users/admin" -H "OCS-APIRequest: true" -d key="quota" -d value="5GB"

But when I try to do it via PHP with the following code it always returns "failure 997"

$url = 'https://' . $ownAdminname . ':' . $ownAdminpassword . '@example.org/ocs/v1.php/cloud/users/admin';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$fields = array("quota" => "5GB");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'OCS-APIRequest: true'
    ));
$response = curl_exec($ch);
curl_close($ch);
echo "Response: ".$response;

Body:
The difference between the cURL command and the PHP code you pasted lies in a poorly designed user provisioning API.

Using these cURL arguments:

-d key="quota" -d value="5GB"

... is not equivalent to the fields you're posting:

$fields = array("quota" => "5GB");

... but rather:

$fields = array(
    'key' => 'quota',
    'value' => '5GB',
);

The explanation for the 997 code you're getting can be found in https://github.com/owncloud/core/blob/v10.0.3/apps/provisioning_api/lib/Users.php#L269-L272: since there's no "key" key in the data submitted ($parameters['_put']['key'] will evaluate as null) and hence the error.


问:
Using :hover to trigger @keyframes animation when the element uses multiple animations
I have a set of icons that transition from the center of the page to a set point, and then remain there. What I want to do is set them to transition to have a thicker border and scale to 130x130px whenever I mouse over one of them, but only the initial animation occurs

CSS:

```<code>.iconborder {
border-width: 5px;
border-style: solid;
border-radius: 100em;
border-color: white;
}

.iconborder:hover {animation-name: icongrow; animation-duration: 0.2s; animation-timing-function: cubic-bezier;}

@keyframes icongrow {
0% {
    border-width: 5px;
    width: 100px;
    height: 100px;
}

100% {
    border-width: 10px;
    width: 130px;
    height: 130px;
}
}

#FTPSlideOut
{
position: fixed;
width: 100px;
height: 100px;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
z-index: 6;
visibility: hidden;

animation-name: FTPSlideOut;
animation-duration: 0.4s;
animation-timing-function: cubic-bezier;
animation-delay: 1s;
animation-fill-mode: forwards;

}

@keyframes FTPSlideOut {
0% {
    transform: translate(0px, 0px);
    visibility: visible;
}

100% {
    transform: translate(-300px, -150px);
    visibility: visible;
}
}
</code>```

And HTML:

```<code>    <body style="background-color:#D4D4D4;height:100%;width:100%">
        <img id="SlideUp" class="dropshadow" src="picCenterDotFinalwText.png">
        <a href="/net2ftp"><img id="FTPSlideOut" class="dropshadow iconborder" src="FTP.png"></a>
        <img id="PicturesSlideOut" class="dropshadow iconborder" src="Pictures.png">
        <img id="VideosSlideOut" class="dropshadow iconborder" src="Videos.png">
        <img id="MusicSlideOut" class="dropshadow iconborder" src="Music.png">
        <img id="DocumentsSlideOut" class="dropshadow iconborder" src="Documents.png">
        <a href="https://www.gmail.com"><img id="EmailSlideOut" class="dropshadow iconborder" src="Email.png"></a>
</body>
</code>```

Any clues?

答:
Just put your animation in the class pseudo selector with the hover in it? like this</p>

```<code>.clickMes {
    color: white;
    font-size: 17pt;
    text-decoration: none;
}

.clickMes:active {
    color: cyan;
}

.clickMes:hover {
    animation: clickmes 1.3s infinite;
}

@keyframes clickmes {
    0% {
        background-color: none;
    }
    50% {
        background-color: cyan;
    }
    100% {
        background-color: none;
    }
}
</code>```

Body:
I have a set of icons that transition from the center of the page to a set point, and then remain there. What I want to do is set them to transition to have a thicker border and scale to 130x130px whenever I mouse over one of them, but only the initial animation occurs

CSS:

.iconborder {
border-width: 5px;
border-style: solid;
border-radius: 100em;
border-color: white;
}

.iconborder:hover {animation-name: icongrow; animation-duration: 0.2s; animation-timing-function: cubic-bezier;}

@keyframes icongrow {
0% {
    border-width: 5px;
    width: 100px;
    height: 100px;
}

100% {
    border-width: 10px;
    width: 130px;
    height: 130px;
}
}

#FTPSlideOut
{
position: fixed;
width: 100px;
height: 100px;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
z-index: 6;
visibility: hidden;

animation-name: FTPSlideOut;
animation-duration: 0.4s;
animation-timing-function: cubic-bezier;
animation-delay: 1s;
animation-fill-mode: forwards;

}

@keyframes FTPSlideOut {
0% {
    transform: translate(0px, 0px);
    visibility: visible;
}

100% {
    transform: translate(-300px, -150px);
    visibility: visible;
}
}

And HTML:

Any clues?

Body:
Just put your animation in the class pseudo selector with the hover in it? like this

.clickMes {
    color: white;
    font-size: 17pt;
    text-decoration: none;
}

.clickMes:active {
    color: cyan;
}

.clickMes:hover {
    animation: clickmes 1.3s infinite;
}

@keyframes clickmes {
    0% {
        background-color: none;
    }
    50% {
        background-color: cyan;
    }
    100% {
        background-color: none;
    }
}


问:
Extract time from JS Date object without offsetting the Time zone
So we have multiple clients, that are in multiple time zones. I'm pulling some dates from an API, and the dates/times that are in this string are exactly what I need to display. I've been researching this, and digging for some time, and still haven't come up with a clear answer. The string coming in is formatted as such:

```<code>"2017-12-29T20:00:00"
</code>```

What I'm wanting is to extract both the date and time as is, into two strings (no timezone offsetting, no matter where the viewer is located) but am having some issues doing so. Also hoping to format it in the correct fashion as well. Example:

```<code>"M/d/yyyy"
"hh:mm AM/PM" (12 hour)
</code>```

I've tried numerous ways to battle this, and don't really want to just grab substrings, but am half tempted to do so. Any help is appreciated.

答:
Consider just reformatting the string, it avoids all issues with the built-in parser and timezones:

function reformatTimestamp(s) {
  function z(n){return (n<10?'0':'')+ +n}
  var b = s.split(/\D/);
  var h = b[3]%12 || 12;
  var ap = b[3] < 12? 'AM':'PM';
  return b[1] + '/' + b[2] + '/' + b[0] +
         ' ' + z(h) + ':' + z(b[4]) + ' ' + ap;
}

console.log(reformatTimestamp('2017-12-29T20:00:00')) // 12/29/2017 08:00 PM```

I think it would be better to pad the month and day with a leading zero (but I'd also use an unambiguous date format like DD-MMM-YYYY rather than the peculiar m/d/y).

Body:
So we have multiple clients, that are in multiple time zones. I'm pulling some dates from an API, and the dates/times that are in this string are exactly what I need to display. I've been researching this, and digging for some time, and still haven't come up with a clear answer. The string coming in is formatted as such:

"2017-12-29T20:00:00"

What I'm wanting is to extract both the date and time as is, into two strings (no timezone offsetting, no matter where the viewer is located) but am having some issues doing so. Also hoping to format it in the correct fashion as well. Example:

"M/d/yyyy"
"hh:mm AM/PM" (12 hour)

I've tried numerous ways to battle this, and don't really want to just grab substrings, but am half tempted to do so. Any help is appreciated.

Body:
Consider just reformatting the string, it avoids all issues with the built-in parser and timezones:

function reformatTimestamp(s) {
  function z(n){return (n<10?'0':'')+ +n}
  var b = s.split(/\D/);
  var h = b[3]%12 || 12;
  var ap = b[3] < 12? 'AM':'PM';
  return b[1] + '/' + b[2] + '/' + b[0] +
         ' ' + z(h) + ':' + z(b[4]) + ' ' + ap;
}

console.log(reformatTimestamp('2017-12-29T20:00:00')) // 12/29/2017 08:00 PM

I think it would be better to pad the month and day with a leading zero (but I'd also use an unambiguous date format like DD-MMM-YYYY rather than the peculiar m/d/y).


问:
Regexp for URL cache in Java
I need to match a certain Regexp pattern in Java and I think I'm very close, could anyone with more experience help? I have been testing it for at least a few hours and couldn't come to a solution yet.

This Regexp is mounted based on a URL, and must represent a "key" to this URL, since depending on the source it may change a lot, but a few stuff is always there... Already mapped Strings to match:

http://fictionalURL:8080/servlet/TPCW_new_products_servlet;jsessionid=865266C8B1231C35FEDEAA9D66400074?subject=POLITICS

http://fictionalURL.:8080/servlet/TPCW_buy_request_servlet;jsessionid=6FA80FDC52BB22518DB7D587E0876D63?RETURNING_FLAG=Y&UNAME=OGREREBABAREAT&PASSWD=ogrerebabareat&C_ID=1440046&SHOPPING_ID=171

http://localhost:8080/servlet/;jsessionid=865266C8B1231C35FEDEAA9D66400074?subject=POLITICS

my code is built so that the part that represents the URL pattern is built on runtime:

```<code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test_regexp {
    public static void main (String[] args){

        String testString = "http://ec2-54-158-62-71.compute-1.amazonaws.com:8080/servlet/TPCW_buy_request_servlet;jsessionid=6FA80FDC52BB22518DB7D587E0876D63?RETURNING_FLAG=Y&UNAME=OGREREBABAREAT&PASSWD=ogrerebabareat&C_ID=1440046&SHOPPING_ID=171";
        int beginIndex = testString.indexOf("servlet");
        int endIndex = testString.indexOf("jsessionid");
        CharSequence cs = new String(testString);
        String patt = "\\(?=.*:8080/.*)(?=.*jsessionid=).*";
        System.out.println("Pattern: "+patt);
        Pattern teste = Pattern.compile(patt);

        System.out.println(teste.matcher(cs).matches());
    }
}
</code>```

but at the end the pattern should look something like this:

Pattern: ((?=.:8080/.)(?=.jsessionid=).)

PS: The pattern must include the URL full endpoint (with parameters), but not the sessionId and other stuff

EDIT: I forgot to mention, the regexp must also have the subject parameter, which is after the session ID, I have only realized it while writing this...

For those who want to know what's my purpose on all that, I'm making a LRU cache based on Regexp Patterns stored in a HashSet.

I would apprecite the help very much! This is the last task to finish the project!

Thanks in advance.

答:
Double check your pattern. I'm not sure what the backslash out front is for.

```<code>"\\(?=.*:8080/.*)(?=.*jsessionid=).*"
</code>```

Your pattern would also happily match jsessionid=10:8080/

Title: Regexp for URL cache in Java

Body:
I need to match a certain Regexp pattern in Java and I think I'm very close, could anyone with more experience help? I have been testing it for at least a few hours and couldn't come to a solution yet.

This Regexp is mounted based on a URL, and must represent a "key" to this URL, since depending on the source it may change a lot, but a few stuff is always there... Already mapped Strings to match:

http://fictionalURL:8080/servlet/TPCW_new_products_servlet;jsessionid=865266C8B1231C35FEDEAA9D66400074?subject=POLITICS

http://fictionalURL.:8080/servlet/TPCW_buy_request_servlet;jsessionid=6FA80FDC52BB22518DB7D587E0876D63?RETURNING_FLAG=Y&UNAME=OGREREBABAREAT&PASSWD=ogrerebabareat&C_ID=1440046&SHOPPING_ID=171

http://localhost:8080/servlet/;jsessionid=865266C8B1231C35FEDEAA9D66400074?subject=POLITICS

my code is built so that the part that represents the URL pattern is built on runtime:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test_regexp {
    public static void main (String[] args){

        String testString = "http://ec2-54-158-62-71.compute-1.amazonaws.com:8080/servlet/TPCW_buy_request_servlet;jsessionid=6FA80FDC52BB22518DB7D587E0876D63?RETURNING_FLAG=Y&UNAME=OGREREBABAREAT&PASSWD=ogrerebabareat&C_ID=1440046&SHOPPING_ID=171";
        int beginIndex = testString.indexOf("servlet");
        int endIndex = testString.indexOf("jsessionid");
        CharSequence cs = new String(testString);
        String patt = "\\(?=.*:8080/.*)(?=.*jsessionid=).*";
        System.out.println("Pattern: "+patt);
        Pattern teste = Pattern.compile(patt);

        System.out.println(teste.matcher(cs).matches());
    }
}

but at the end the pattern should look something like this:

Pattern: ((?=.:8080/.)(?=.jsessionid=).)

PS: The pattern must include the URL full endpoint (with parameters), but not the sessionId and other stuff

EDIT: I forgot to mention, the regexp must also have the subject parameter, which is after the session ID, I have only realized it while writing this...

For those who want to know what's my purpose on all that, I'm making a LRU cache based on Regexp Patterns stored in a HashSet.

I would apprecite the help very much! This is the last task to finish the project!

Thanks in advance.

Body:
Double check your pattern. I'm not sure what the backslash out front is for.

"\\(?=.*:8080/.*)(?=.*jsessionid=).*"

Your pattern would also happily match jsessionid=10:8080/


问:
How to override default dependencies with Mockbox and Wirebox
I have a logger service that has a ScopeStorage and a LoggerServiceDAO dependency and in my unit test I need to override these to use mock objects I have created. I am using Wirebox AOP to trigger the logging events so I can not just create a mock object and pass it into the constructor of the CustomerContact object

Here is the mocks I am creating:

```<code>scopeStorageMock = mockBox.createMock('system.ScopeStorage').$('get', 111);
loggerServiceDAOMock = mockBox.createMock('system.services.daos.loggerServiceDAO').$('insertLog');
</code>```

Inside my Wirebox binder I have the following mappings:

```<code>map('CustomerContact').to('models.Customer.CustomerContactBean');
map('LoggerServiceDAO').to('system.Services.DAOs.LoggerServiceDAO');
map('ScopeStorage').to('system.ScopeStorage');
map('CustomerContactLogger').to('models.customer.loggers.CustomerContactLogger');
mapAspect("CustomerAspect").to('models.CustomerAspect');
bindAspect(classes=match().mappings("CustomerContact"), methods=match().methods(['create','delete', 'update']), aspects="CustomerContactLogger");
</code>```

Is there a way in my unit test to tell Wirebox that when it gets an instance of the CustomerAspect object to use the two mock objects I created with Mockbox?

答:
I found the solution although it seems somewhat hacky but it works. Basically what I do is I tell Wirebox to unmap the existing CustomerContactLogger and then create a CustomerContactLoggerMock and inject all the Mocked properties. After that I create a new mapping of the CustomerContactLogger and set the value equal to the mocked object.

```<code>injector.getBinder().unMap('customercontactLogger');
customerContactLoggerMock = mockBox.createMock('models.customer.loggers.CustomerContactLogger');
customerContactLoggerMock.$property(propertyName='scopeStorage', mock=scopeStorageMock).$property(propertyName='loggerServiceDAO', mock=loggerServiceDAOMock);injector.getBinder().map('CustomerContactLogger').toValue(customerContactLoggerMock);
injector.getBinder().map('CustomerContactLogger').toValue(customerContactLoggerMock);
</code>```

Body:
I have a logger service that has a ScopeStorage and a LoggerServiceDAO dependency and in my unit test I need to override these to use mock objects I have created. I am using Wirebox AOP to trigger the logging events so I can not just create a mock object and pass it into the constructor of the CustomerContact object

Here is the mocks I am creating:

scopeStorageMock = mockBox.createMock('system.ScopeStorage').$('get', 111);
loggerServiceDAOMock = mockBox.createMock('system.services.daos.loggerServiceDAO').$('insertLog');

Inside my Wirebox binder I have the following mappings:

map('CustomerContact').to('models.Customer.CustomerContactBean');
map('LoggerServiceDAO').to('system.Services.DAOs.LoggerServiceDAO');
map('ScopeStorage').to('system.ScopeStorage');
map('CustomerContactLogger').to('models.customer.loggers.CustomerContactLogger');
mapAspect("CustomerAspect").to('models.CustomerAspect');
bindAspect(classes=match().mappings("CustomerContact"), methods=match().methods(['create','delete', 'update']), aspects="CustomerContactLogger");

Is there a way in my unit test to tell Wirebox that when it gets an instance of the CustomerAspect object to use the two mock objects I created with Mockbox?

Body:
I found the solution although it seems somewhat hacky but it works. Basically what I do is I tell Wirebox to unmap the existing CustomerContactLogger and then create a CustomerContactLoggerMock and inject all the Mocked properties. After that I create a new mapping of the CustomerContactLogger and set the value equal to the mocked object.

injector.getBinder().unMap('customercontactLogger');
customerContactLoggerMock = mockBox.createMock('models.customer.loggers.CustomerContactLogger');
customerContactLoggerMock.$property(propertyName='scopeStorage', mock=scopeStorageMock).$property(propertyName='loggerServiceDAO', mock=loggerServiceDAOMock);injector.getBinder().map('CustomerContactLogger').toValue(customerContactLoggerMock);
injector.getBinder().map('CustomerContactLogger').toValue(customerContactLoggerMock);


问:
Angular Material mandatory form inputs pop up alert
I'm creating a Material form and have a couple required fields that are rendering correctly after following the examples found on here:  https://material.angularjs.org/latest/demo/input

However, in their example, when required inputs aren't filled out and a user presses Submit, a popup alert shows up and I'm not sure how this is done:

My code looks like this:

```<code><div ng-switch-when="choice">
   <md-input-container class="md-block">
      <label style="font-size: 130%; white-space: normal;" for="{{element.section_element_name}}">{{element.section_element_label}}</label>
      <md-select ng-if="element.mandatoryFlag==1" required id = {{element.section_element_name}} type="selectbasic" value={{element.q_value}} ng-model="element.answer">
         <md-option ng-repeat="option in element.section_element_choices" value="{{option.element_choice_value}}" >
            {{option.element_choice_label}}
         </md-option>
      </md-select>
      <div ng-messages="element.answer.$error" role="alert">
         <div ng-message="required" class="my-message">Please provide an answer.</div>
      </div>
      <md-select ng-if="element.mandatoryFlag==0" id = {{element.section_element_name}} type="selectbasic" value={{element.q_value}} ng-model="element.answer">
         <md-option ng-repeat="option in element.section_element_choices" value="{{option.element_choice_value}}" >
            {{option.element_choice_label}}
         </md-option>
      </md-select>
   </md-input-container>
</div>
<md-button ng-click="submit()" class="md-fab  md-mini">
   <md-tooltip md-direction="top">Save or Submit Form</md-tooltip>
   <i class="material-icons" style="vertical-align:middle;">send</i>
</md-button>
</code>```

What do I have to do for that pop up to show up if things aren't filled out onSubmit?

答:
There is a lot of discussion related to this in Chrome popup Please Fill Out this Field. However this isn't a duplicate as you are asking a bit of the opposite question.

The answer to this is that the HTML5 required attribute behavior for <input> elements is different than the required behavior for <select> elements.

This CodePen demonstrates the popup working for a <select> element, but not working for the <md-select> element.

One issue is that the Material Select doesn't have a blank entry for the first option. However, even adding that doesn't make the popup appear.

The second issue is that the required is not applied to the hidden <select> element in the DOM. So the browser can't add the popup.

```<code><select class="md-visually-hidden" name="type" aria-hidden="true" tabindex="-1">
    <option value="app">Application</option>
    <option value="web">Website</option>
    <option ng-value="project.type" selected="" aria-checked="false"></option>
</select>
</code>```

After all of this, you may just want to handle validation messages in the Material Design style and disable the popup completely using the steps included in the first link in this answer.

Body:
I'm creating a Material form and have a couple required fields that are rendering correctly after following the examples found on here:  https://material.angularjs.org/latest/demo/input

However, in their example, when required inputs aren't filled out and a user presses Submit, a popup alert shows up and I'm not sure how this is done:

My code looks like this:

   <md-input-container class="md-block">
      {{element.section_element_label}}
      <md-select ng-if="element.mandatoryFlag==1" required id = {{element.section_element_name}} type="selectbasic" value={{element.q_value}} ng-model="element.answer">
         <md-option ng-repeat="option in element.section_element_choices" value="{{option.element_choice_value}}" >
            {{option.element_choice_label}}
         </md-option>
      </md-select>

Please provide an answer.

      <md-select ng-if="element.mandatoryFlag==0" id = {{element.section_element_name}} type="selectbasic" value={{element.q_value}} ng-model="element.answer">
         <md-option ng-repeat="option in element.section_element_choices" value="{{option.element_choice_value}}" >
            {{option.element_choice_label}}
         </md-option>
      </md-select>
   </md-input-container>

<md-button ng-click="submit()" class="md-fab  md-mini">
   <md-tooltip md-direction="top">Save or Submit Form</md-tooltip>
   send
</md-button>

What do I have to do for that pop up to show up if things aren't filled out onSubmit?

Body:
There is a lot of discussion related to this in Chrome popup Please Fill Out this Field. However this isn't a duplicate as you are asking a bit of the opposite question.

The answer to this is that the HTML5 required attribute behavior for <input> elements is different than the required behavior for <select> elements.

This CodePen demonstrates the popup working for a <select> element, but not working for the <md-select> element.

One issue is that the Material Select doesn't have a blank entry for the first option. However, even adding that doesn't make the popup appear.

The second issue is that the required is not applied to the hidden <select> element in the DOM. So the browser can't add the popup.

<select class="md-visually-hidden" name="type" aria-hidden="true" tabindex="-1">
    <option value="app">Application</option>
    <option value="web">Website</option>
    <option ng-value="project.type" selected="" aria-checked="false"></option>
</select>

After all of this, you may just want to handle validation messages in the Material Design style and disable the popup completely using the steps included in the first link in this answer.


问:
List comprehension Python with multiple control flow
I am trying to convert this function:

```<code>templist = []
for each in characters:
    if each in vowels:
        templist.append('v')
    elif (each in alphabet) & (each not in vowels):
        templist.append('c')
    else:
        templist.append('?')
characters = templist
print(characters)
</code>```

into list comprehension

```<code>modified_list = ['v' for each in characters for item in vowels
                     if item in vowels
                 else 'c' if (item in alphabet) & (item not in vowels)
                 else '?']`
</code>```

Kinda stuck here! Can't figure out what I am doing wrong.

答:
just a line breaking style mention: Is it possible to break a long line to multiple lines in Python shows some options

the list comp brackets in this case make \ unnecessary

sometimes I play with leading space inside the line continuation to indicate logical hiearchy - the leading space is syntactically ignored inside a code line continuation

```<code>['v' if each in vowels
     else ('c' if each in alphabet
               else '?')
 for each in characters]
</code>```

Body:
I am trying to convert this function:

templist = []
for each in characters:
    if each in vowels:
        templist.append('v')
    elif (each in alphabet) & (each not in vowels):
        templist.append('c')
    else:
        templist.append('?')
characters = templist
print(characters)

into list comprehension

modified_list = ['v' for each in characters for item in vowels
                     if item in vowels
                 else 'c' if (item in alphabet) & (item not in vowels)
                 else '?']`

Kinda stuck here! Can't figure out what I am doing wrong.

Body:
just a line breaking style mention: Is it possible to break a long line to multiple lines in Python shows some options

the list comp brackets in this case make \ unnecessary

sometimes I play with leading space inside the line continuation to indicate logical hiearchy - the leading space is syntactically ignored inside a code line continuation

['v' if each in vowels
     else ('c' if each in alphabet
               else '?')
 for each in characters]


问:
how to draw a rectangle by specifying its 4 corners
I am using OpenCV4Android version 2.4.11. I am reading frames from the camera and I detect any rectangular shapes in the frame. Then I try to draw a semi-transparent rectangle around a detected object.

what i want to do is, to draw a semi-transparent rectangale given the four corners of the detected object. But, in openCV you can draw a rectangle by spcifying only two points of it "the topLeft and BottomRight".

please let me know how to draw a rectangle by spcifying the the four corners of it NOT ONLY by spcifying the topLeft and BottomRight corners.

the below posted image is to show you my attempts and to show you that what i want is to draw a rectangle around the four detected corners "red, green, blue, white"

image:

答:
Same idea as @Saransh, but compiles for me:</p>

```<code>auto x1 = std::min(tlx, std::min(trx, std::min(brx, blx))); // top-left pt. is the leftmost of the 4 points
auto x2 = std::max(tlx, std::max(trx, std::max(brx, blx))); // bottom-right pt. is the rightmost of the 4 points
auto y1 = std::min(tly, std::min(try, std::min(bry, bly))); //top-left pt. is the uppermost of the 4 points
auto y2 = std::max(tly, std::max(try, std::max(bry, bly))); //bottom-right pt. is the lowermost of the 4 points
</code>```

Body:
Same idea as @Saransh, but compiles for me:

auto x1 = std::min(tlx, std::min(trx, std::min(brx, blx))); // top-left pt. is the leftmost of the 4 points
auto x2 = std::max(tlx, std::max(trx, std::max(brx, blx))); // bottom-right pt. is the rightmost of the 4 points
auto y1 = std::min(tly, std::min(try, std::min(bry, bly))); //top-left pt. is the uppermost of the 4 points
auto y2 = std::max(tly, std::max(try, std::max(bry, bly))); //bottom-right pt. is the lowermost of the 4 points


问:
output parameter
how to get output parameter from stored procedure of one table and by using that value how to insert data in another table which is in realation with that table? </p>

答:
After your first insert you'll want something like this:

```<code>SELECT @parameter_goes_here = SCOPE_IDENTITY()
</code>```

Which will give you the identity of the just entered row.  Then just use that value as the parameter in your next insert.

If you need a whole example...let me know

OwnerDisplayName: Amit

Title: output parameter

Body:
After your first insert you'll want something like this:

SELECT @parameter_goes_here = SCOPE_IDENTITY()

Which will give you the identity of the just entered row.  Then just use that value as the parameter in your next insert.

If you need a whole example...let me know

OwnerDisplayName: GregD


问:
How do I find the top N batters per year?
I'm playing around with the Lahman Baseball Database in a MySQL instance.  I want to find the players who topped home runs (HR) for each year.  The Batting table has the following (relevant parts) of its schema:

```<code>+-----------+----------------------+------+-----+---------+-------+
| Field     | Type                 | Null | Key | Default | Extra |
+-----------+----------------------+------+-----+---------+-------+
| playerID  | varchar(9)           | NO   | PRI |         |       |
| yearID    | smallint(4) unsigned | NO   | PRI | 0       |       |
| HR        | smallint(3) unsigned | YES  |     | NULL    |       |
+-----------+----------------------+------+-----+---------+-------+
</code>```

For each year, every player has an entry (between hundreds and 12k per year, going back to 1871).  Getting the top N hitters for a single year is easy:

```<code>SELECT playerID,yearID,HR
FROM Batting
WHERE yearID=2009
ORDER BY HR DESC LIMIT 3;
+-----------+--------+------+
| playerID  | yearID | HR   |
+-----------+--------+------+
| pujolal01 |   2009 |   47 |
| fieldpr01 |   2009 |   46 |
| howarry01 |   2009 |   45 |
+-----------+--------+------+
</code>```

But I'm interested in finding the top 3 from every year.  I've found solutions like this, describing how to select the top from a category and I've tried to apply it to my problem, only to end up with a query that never returns:

```<code>SELECT
    b.yearID, b.playerID, b.HR
FROM
    Batting AS b
LEFT JOIN
    Batting b2
    ON
    (b.yearID=b2.yearID AND b.HR <= b2.HR)
GROUP BY b.yearID HAVING COUNT(*) <= 3;
</code>```

Where have I gone wrong?

答:
Wow, random. I happened to be doing the same query (for salaries though) on the Lahman Baseball DB using an article on emulating Oracle Analytic functions. This version of the query is snappy, but not so intuitive.

```<code>select *
from (

select
    b.yearID as year,
    b.teamID as team,
    m.nameFirst as first,
    m.nameLast as last,
    find_in_set(b.HR, x.teamRank) as rank,
    b.HR as HR

from
    Batting b
    inner join Master m on m.playerID = b.playerID
    inner join (select yearID, group_concat(distinct HR order by HR desc) as teamRank from Batting group by yearID) x on x.yearID = b.yearID

) x

where
    rank <= 10 and rank > 0

order by
    year desc, rank
</code>```

Or the top 5 HR totals per team for the year 2010...

```<code>select *
from (

select
    b.yearID as year,
    b.teamID as team,
    m.nameFirst as first,
    m.nameLast as last,
    b.HR as HR,
    find_in_set(b.HR, x.teamRank) as rank

from
    Batting b
    inner join Master m on m.playerID = b.playerID
    inner join (select teamID, group_concat(distinct HR order by HR desc) as teamRank from Batting where yearID = 2010 group by teamID) x on x.teamID = b.teamID
where
    b.yearID = 2010
) x

where
    rank <= 5 and rank > 0

order by
    team, rank

limit 12
</code>```

Shows these results...

```<code>year    team    first   last        HR  rank
2010    ARI Mark    Reynolds    32  1
2010    ARI Chris   Young       27  2
2010    ARI Kelly   Johnson     26  3
2010    ARI Adam    LaRoche     25  4
2010    ARI Justin  Upton       17  5
2010    ATL Brian   McCann      21  1
2010    ATL Jason   Heyward     18  2
2010    ATL Troy    Glaus       16  3
2010    ATL Martin  Prado       15  4
2010    ATL Eric    Hinske      11  5
2010    BAL Luke    Scott       27  1
2010    BAL Ty      Wigginton   22  2
</code>```

Body:
I'm playing around with the Lahman Baseball Database in a MySQL instance.  I want to find the players who topped home runs (HR) for each year.  The Batting table has the following (relevant parts) of its schema:

+-----------+----------------------+------+-----+---------+-------+
| Field     | Type                 | Null | Key | Default | Extra |
+-----------+----------------------+------+-----+---------+-------+
| playerID  | varchar(9)           | NO   | PRI |         |       |
| yearID    | smallint(4) unsigned | NO   | PRI | 0       |       |
| HR        | smallint(3) unsigned | YES  |     | NULL    |       |
+-----------+----------------------+------+-----+---------+-------+

For each year, every player has an entry (between hundreds and 12k per year, going back to 1871).  Getting the top N hitters for a single year is easy:

SELECT playerID,yearID,HR
FROM Batting
WHERE yearID=2009
ORDER BY HR DESC LIMIT 3;
+-----------+--------+------+
| playerID  | yearID | HR   |
+-----------+--------+------+
| pujolal01 |   2009 |   47 |
| fieldpr01 |   2009 |   46 |
| howarry01 |   2009 |   45 |
+-----------+--------+------+

But I'm interested in finding the top 3 from every year.  I've found solutions like this, describing how to select the top from a category and I've tried to apply it to my problem, only to end up with a query that never returns:

SELECT
    b.yearID, b.playerID, b.HR
FROM
    Batting AS b
LEFT JOIN
    Batting b2
    ON
    (b.yearID=b2.yearID AND b.HR <= b2.HR)
GROUP BY b.yearID HAVING COUNT(*) <= 3;

Where have I gone wrong?

Body:
Wow, random. I happened to be doing the same query (for salaries though) on the Lahman Baseball DB using an article on emulating Oracle Analytic functions. This version of the query is snappy, but not so intuitive.

select *
from (

select
    b.yearID as year,
    b.teamID as team,
    m.nameFirst as first,
    m.nameLast as last,
    find_in_set(b.HR, x.teamRank) as rank,
    b.HR as HR

from
    Batting b
    inner join Master m on m.playerID = b.playerID
    inner join (select yearID, group_concat(distinct HR order by HR desc) as teamRank from Batting group by yearID) x on x.yearID = b.yearID

) x

where
    rank <= 10 and rank > 0

order by
    year desc, rank

Or the top 5 HR totals per team for the year 2010...

select *
from (

select
    b.yearID as year,
    b.teamID as team,
    m.nameFirst as first,
    m.nameLast as last,
    b.HR as HR,
    find_in_set(b.HR, x.teamRank) as rank

from
    Batting b
    inner join Master m on m.playerID = b.playerID
    inner join (select teamID, group_concat(distinct HR order by HR desc) as teamRank from Batting where yearID = 2010 group by teamID) x on x.teamID = b.teamID
where
    b.yearID = 2010
) x

where
    rank <= 5 and rank > 0

order by
    team, rank

limit 12

Shows these results...

year    team    first   last        HR  rank
2010    ARI Mark    Reynolds    32  1
2010    ARI Chris   Young       27  2
2010    ARI Kelly   Johnson     26  3
2010    ARI Adam    LaRoche     25  4
2010    ARI Justin  Upton       17  5
2010    ATL Brian   McCann      21  1
2010    ATL Jason   Heyward     18  2
2010    ATL Troy    Glaus       16  3
2010    ATL Martin  Prado       15  4
2010    ATL Eric    Hinske      11  5
2010    BAL Luke    Scott       27  1
2010    BAL Ty      Wigginton   22  2


问:
Overriding inherited method without name mangling
Note: similar question here, but I don't believe it's an exact duplicate given the specifications.

Below, I have two classes, one inheriting from the other.  Please note these are just illustrative in nature.

In _Pandas.array(), I want to simply wrap a pandas DataFrame around the NumPy array returned from _Numpy.array().  I'm aware of what is wrong with my current code (_Pandas.array() gets redefined, attempts to call itself, and undergoes infinite recursion), but not how to fix it without name mangling or quasi-private methods on the parent class.

```<code>import numpy as np
import pandas as pd

class _Numpy(object):
    def __init__(self, x):
        self.x = x
    def array(self):
        return np.array(self.x)

class _Pandas(_Numpy):
    def __init__(self, x):
        super(_Pandas, self).__init__(x)
    def array(self):
        return pd.DataFrame(self.array())

a = [[1, 2], [3, 4]]
_Pandas(a).array()    # Intended result - pd.DataFrame(np.array(a))
                      # Infinite recursion as method shuffles back & forth
</code>```

I'm aware that I could do something like

```<code>class _Numpy(object):
    def __init__(self, x):
        self.x = x
    def _array(self):            # Changed to leading underscore
        return np.array(self.x)

class _Pandas(_Numpy):
    def __init__(self, x):
        super().__init__(x)
    def array(self):
        return pd.DataFrame(self._array())
</code>```

But this seems very suboptimal.  In reality, I'm using _Numpy frequently--it's not just a generic parent class--and I'd prefer not to preface all its methods with a single underscore.  How else can I go about this?

答:
Uhm... just want to check why in _Pandas class you don't call super directly?

```<code>class _Pandas(_Numpy):
    def __init__(self, x):
        super(_Pandas,self).__init__(x)
    def array(self):
        return pd.DataFrame(super(_Pandas,self).array())
</code>```

I tried that and got the below result, don't know if it's what you wanted or I have missed anything

```<code>a = [[1, 2], [3, 4]]
_Pandas(a).array()
  0  1
0  1  2
1  3  4
</code>```

Body:
Note: similar question here, but I don't believe it's an exact duplicate given the specifications.

Below, I have two classes, one inheriting from the other.  Please note these are just illustrative in nature.

In _Pandas.array(), I want to simply wrap a pandas DataFrame around the NumPy array returned from _Numpy.array().  I'm aware of what is wrong with my current code (_Pandas.array() gets redefined, attempts to call itself, and undergoes infinite recursion), but not how to fix it without name mangling or quasi-private methods on the parent class.

import numpy as np
import pandas as pd

class _Numpy(object):
    def __init__(self, x):
        self.x = x
    def array(self):
        return np.array(self.x)

class _Pandas(_Numpy):
    def __init__(self, x):
        super(_Pandas, self).__init__(x)
    def array(self):
        return pd.DataFrame(self.array())

a = [[1, 2], [3, 4]]
_Pandas(a).array()    # Intended result - pd.DataFrame(np.array(a))
                      # Infinite recursion as method shuffles back & forth

I'm aware that I could do something like

class _Numpy(object):
    def __init__(self, x):
        self.x = x
    def _array(self):            # Changed to leading underscore
        return np.array(self.x)

class _Pandas(_Numpy):
    def __init__(self, x):
        super().__init__(x)
    def array(self):
        return pd.DataFrame(self._array())

But this seems very suboptimal.  In reality, I'm using _Numpy frequently--it's not just a generic parent class--and I'd prefer not to preface all its methods with a single underscore.  How else can I go about this?

Body:
Uhm... just want to check why in _Pandas class you don't call super directly?

class _Pandas(_Numpy):
    def __init__(self, x):
        super(_Pandas,self).__init__(x)
    def array(self):
        return pd.DataFrame(super(_Pandas,self).array())

I tried that and got the below result, don't know if it's what you wanted or I have missed anything

a = [[1, 2], [3, 4]]
_Pandas(a).array()
  0  1
0  1  2
1  3  4


问:
Changing old store to new store
I want to change the old store to new store by using the query in MSSQL. For example,

Staff_Id Name Transaction_Date New_Store Old_Store

1        AA   1.1.2017         1

1        AA   1.2.2017         2

1        AA   1.3.2017         3

1        AA   1.4.2017         1

1        AA   1.5.2017         4

I want to change the table to following like that

Staff_Id Name Transaction_Date New_Store Old_Store

1        AA   1.1.2017         1         NULL

1        AA   1.2.2017         2         1

1        AA   1.3.2017         3         2

1        AA   1.4.2017         1         3

1        AA   1.5.2017         4         1

I wrote the query like that, but it's not true, it's output randomly Update EC1 SET EC1.Old_Store=EC.New_Store
 From Employee_Change EC , Employee_Change EC1
WHERE EC.Staff_Id=EC1.Staff_Id
AND EC.Transaction_Date>=EC1.Transaction_Date

答:
```<code> UPDATE EC SET Old_Store =
(SELECT TOP 1 New_Store FROM Employee_Change As EC1
WHERE EC1.Staff_Id = EC.Staff_Id And EC1.Transaction_Date < EC.Transaction_Date
ORDER BY EC1.Transaction_Date DESC)
FROM Employee_Change As EC
</code>```

Title: Changing old store to new store

ContentLicense: CC BY-SA 4.0


问:
OnBecomeVisible for Canvas UI Objects
I was searching for method similar to OnBecameVisible for Canvas UI.
MonoBehaviour.OnBecameVisible()

So that I can load and unload image resources based on requirements. But I can't able to find anything useful in this.
I have this kind of page exist which contains 250+ flowers information so I have to manage my texture resources for this.

If I disable Image component then page loaded correctly in game otherwise game get crashed in iPhone device when I load this page because of too much graphics memory requirements.

So for managing resources loading and unloading, I need some way.

答:
There is no direct solution provided by Unity at the moment. But since the visible area is rectangular and related to screen space, you can easily check if your element contained in it.

Here is some post from forums about a helper script and its usage about this situation which should be able to solve your problem:
https://forum.unity.com/threads/test-if-ui-element-is-visible-on-screen.276549/#post-2978773

Title: OnBecomeVisible for Canvas UI Objects