问:
Generic and non-generic interfaces and inheritance - ambiguity while accessing
I have the following setup

Base class

```<code>public class Fruit
{

}
</code>```

Inherited class

```<code>public class Apple : Fruit
{

}
</code>```

Generic Base interface

```<code>public interface IFruitsBase<T> where T : Fruit
{
    T GetItem();
    void ProcessItem(T fruit);
    void Check();
}
</code>```

Non generic Interface that inheritates from generic interface with the base class as the generic

```<code>public interface IFruits : IFruitsBase<Fruit>
{

}
</code>```

Specific interface of the correspoing class

```<code>public interface IApples : IFruitsBase<Apple>, IFruits
{
    void MakeAppleJuice(IEnumerable<Apple> apples);
}
</code>```

Base implementation class

```<code>public class Fruits<T> : IFruitsBase<T>, IFruits where T : Fruit
{
    public T GetItem()
    {
        return null;
    }
    public void ProcessItem(T fruit)
    {

    }
    public void Check()
    {

    }

    Fruit IFruitsBase<Fruit>.GetItem()
    {
        return this.GetItem();
    }
    void IFruitsBase<Fruit>.ProcessItem(Fruit fruit)
    {
        ProcessItem((T)fruit);
    }
}
</code>```

Specific implementation

```<code>public class Apples : Fruits<Apple>, IApples
{
    public void MakeAppleJuice(IEnumerable<Apple> apples)
    {

    }
}
</code>```

The problem I am facing, is at that part:

```<code>public interface IApples : IFruitsBase<Apple>, IFruits
{
    void MakeAppleJuice(IEnumerable<Apple> apples);
}
</code>```

Here I am getting the message:

Possible ambiguity while accessing by this Interface Apple IFruitsBase<Apple> Get() Fruit IFruitsBase<Fruit>.Get()

To fix the problem I could remove the interface IFruits from IApples, but this gives other errors as in:

```<code>public class Context
{
    public IApples Apples { get; set; }

    public Context()
    {
        this.Apples = new Apples();
    }

    public IFruits GetFruits(Type type)
    {
        return this.Apples; //simplified the code here, it should actually get the member of this that fits the type
    }
}

public class Foo
{
    public void Main()
    {
        var context = new Context();
        Check(new IFruits[] { context.Apples }); //can't do that since context.Apples doesnt inherit from IFruits, to fix the above ambiguity
    }

    public void Check(IEnumerable<IFruits> fruits)
    {
        foreach (var fruit in fruits)
            fruit.Check();
    }
}
</code>```

My goal is if someone accesses the objects with:

```<code>var context = new Context();
context.Apples.[only apple relevant methods should be accessable]
</code>```

if someone access it with:

```<code>var context = new Context();
context.GetFruits(item.GetType()).[only fruit relevant methods should be accessable]
</code>```

and no matter if one got it with method a or b, all should be passable to methods with a signature of

```<code>void Foo(IFruits fruits);
</code>```

答:
I think if you unpack what you're trying to do here, a solution presents itself.

First, I dislike using plural classes to represent a list. i.e.

```<code>Apple
Apples : List<Apple>
</code>```

That's not exactly what you were doing, but its basically the same thing. IMO doing this creates harder to maintain code and can obscure what you're trying to do. Instead I've replaced it with extension methods on arrays of Apple

I also pulled out everything I wasn't using, so I may have missed something, but I tried to include everything it seemed like you were asking for. This is what I would go with based off what you have.

```<code>public class Context
{
    public Apple[] Apples { get; set; }

    public IFruit[] GetFruits()
    {
        return null;
    }
}

public interface IFruit
{

}

public class Apple : IFruit
{

}

public class Banana : IFruit
{

}

public static class Apples
{
    public static void MakeAppleJuice(this Apple[] apples)
    {

    }

    public static void ProcessItem(this Apple[] apples, Apple fruit)
    {
    }
}

class Program
{
    static void Foo(IFruit[] fruits)
    {

    }

    static void Main(string[] args)
    {
        var context = new Context();
        context.Apples.MakeAppleJuice();
        context.GetFruits();
        Foo(context.Apples); //Dangerous call, but legal.
        Foo(context.GetFruits());
        context.Apples.ProcessItem(new Banana()); // Does not compile.
    }
}
</code>```

Body:
I have the following setup

Base class

public class Fruit
{

}

Inherited class

public class Apple : Fruit
{

}

Generic Base interface

public interface IFruitsBase<T> where T : Fruit
{
    T GetItem();
    void ProcessItem(T fruit);
    void Check();
}

Non generic Interface that inheritates from generic interface with the base class as the generic

public interface IFruits : IFruitsBase<Fruit>
{

}

Specific interface of the correspoing class

public interface IApples : IFruitsBase<Apple>, IFruits
{
    void MakeAppleJuice(IEnumerable<Apple> apples);
}

Base implementation class

public class Fruits<T> : IFruitsBase<T>, IFruits where T : Fruit
{
    public T GetItem()
    {
        return null;
    }
    public void ProcessItem(T fruit)
    {

    }
    public void Check()
    {

    }

    Fruit IFruitsBase<Fruit>.GetItem()
    {
        return this.GetItem();
    }
    void IFruitsBase<Fruit>.ProcessItem(Fruit fruit)
    {
        ProcessItem((T)fruit);
    }
}

Specific implementation

public class Apples : Fruits<Apple>, IApples
{
    public void MakeAppleJuice(IEnumerable<Apple> apples)
    {

    }
}

The problem I am facing, is at that part:

public interface IApples : IFruitsBase<Apple>, IFruits
{
    void MakeAppleJuice(IEnumerable<Apple> apples);
}

Here I am getting the message:

Possible ambiguity while accessing by this Interface Apple IFruitsBase<Apple> Get() Fruit IFruitsBase<Fruit>.Get()

To fix the problem I could remove the interface IFruits from IApples, but this gives other errors as in:

public class Context
{
    public IApples Apples { get; set; }

    public Context()
    {
        this.Apples = new Apples();
    }

    public IFruits GetFruits(Type type)
    {
        return this.Apples; //simplified the code here, it should actually get the member of this that fits the type
    }
}

public class Foo
{
    public void Main()
    {
        var context = new Context();
        Check(new IFruits[] { context.Apples }); //can't do that since context.Apples doesnt inherit from IFruits, to fix the above ambiguity
    }

    public void Check(IEnumerable<IFruits> fruits)
    {
        foreach (var fruit in fruits)
            fruit.Check();
    }
}

My goal is if someone accesses the objects with:

var context = new Context();
context.Apples.[only apple relevant methods should be accessable]

if someone access it with:

var context = new Context();
context.GetFruits(item.GetType()).[only fruit relevant methods should be accessable]

and no matter if one got it with method a or b, all should be passable to methods with a signature of

void Foo(IFruits fruits);

Body:
I think if you unpack what you're trying to do here, a solution presents itself.

First, I dislike using plural classes to represent a list. i.e.

Apple
Apples : List<Apple>

That's not exactly what you were doing, but its basically the same thing. IMO doing this creates harder to maintain code and can obscure what you're trying to do. Instead I've replaced it with extension methods on arrays of Apple

I also pulled out everything I wasn't using, so I may have missed something, but I tried to include everything it seemed like you were asking for. This is what I would go with based off what you have.

public class Context
{
    public Apple[] Apples { get; set; }

    public IFruit[] GetFruits()
    {
        return null;
    }
}

public interface IFruit
{

}

public class Apple : IFruit
{

}

public class Banana : IFruit
{

}

public static class Apples
{
    public static void MakeAppleJuice(this Apple[] apples)
    {

    }

    public static void ProcessItem(this Apple[] apples, Apple fruit)
    {
    }
}

class Program
{
    static void Foo(IFruit[] fruits)
    {

    }

    static void Main(string[] args)
    {
        var context = new Context();
        context.Apples.MakeAppleJuice();
        context.GetFruits();
        Foo(context.Apples); //Dangerous call, but legal.
        Foo(context.GetFruits());
        context.Apples.ProcessItem(new Banana()); // Does not compile.
    }
}


来源: stackexchange

问:
How to insert quotation marks properly into SQL Server in C# code behind
In SQL Server Management Studio, the query that I created is

```<code>CREATE TABLE MyTable
(
    EmployeeID int,
    EmployeeDivision varchar(25),
    EmployeeFName varchar(25),
    EmployeeLName varchar(25),
    EmployeeBudget1 int,
    EmployeeBudget2 int,
    EmployeeBudget3 int,
    EmployeeBudget4 int,
    EmployeeBudget5 int,
    EmployeeBudget6 int,
    EmployeeBudget7 int,
    EmployeeBudget8 int,
    EmployeeBudget9 int,
    EmployeeBudget10 int,
    EmployeeBudget11 int,
    EmployeeBudget12 int,
    EmployeeBudget13 int,
    EmployeeBudget14 int,
    EmployeeBudget15 int
);

INSERT INTO MyTable ('12345','DIVISION','FIRST','LAST','' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' );
</code>```

My question is, how do I write this in C#?

I only created 4 set of textbox that will get that value of ID, Division, First Name, Last Name of each employee, and the rest will be null for Budgets 1-15

Here's my code:

```<code>SqlCommand cmd = new SqlCommand("insert into BUDGETTING_A values (' " + txtBoxEmpID.Text + "', + '" + cmbBoxDivision.Text + "','" + txtBoxFamilyName.Text + "', '" + txtBoxFirstName.Text + ' " +  '','','','','','','','','','','','','','','"')"+, con);
</code>```

I am having trouble in terms of doing this, any instructions in writing these off?

答:
The safest and best way is to use SqlParameter like the following example :

```<code>SqlCommand cmd = new SqlCommand("insert into BUDGETTING_A values (@BoxEmpID ,....) ",con);
cmd.Parameters.AddWithValue("@BoxEmpID", txtBoxEmpID.Text);
cmd.Parameters.AddWithValue("@OtherField", OtherValue);
.
.
.
cmd.ExecuteNonQuery();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In SQL Server Management Studio, the query that I created is

CREATE TABLE MyTable
(
    EmployeeID int,
    EmployeeDivision varchar(25),
    EmployeeFName varchar(25),
    EmployeeLName varchar(25),
    EmployeeBudget1 int,
    EmployeeBudget2 int,
    EmployeeBudget3 int,
    EmployeeBudget4 int,
    EmployeeBudget5 int,
    EmployeeBudget6 int,
    EmployeeBudget7 int,
    EmployeeBudget8 int,
    EmployeeBudget9 int,
    EmployeeBudget10 int,
    EmployeeBudget11 int,
    EmployeeBudget12 int,
    EmployeeBudget13 int,
    EmployeeBudget14 int,
    EmployeeBudget15 int
);

INSERT INTO MyTable ('12345','DIVISION','FIRST','LAST','' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' );

My question is, how do I write this in C#?

I only created 4 set of textbox that will get that value of ID, Division, First Name, Last Name of each employee, and the rest will be null for Budgets 1-15

Here's my code:

SqlCommand cmd = new SqlCommand("insert into BUDGETTING_A values (' " + txtBoxEmpID.Text + "', + '" + cmbBoxDivision.Text + "','" + txtBoxFamilyName.Text + "', '" + txtBoxFirstName.Text + ' " +  '','','','','','','','','','','','','','','"')"+, con);

I am having trouble in terms of doing this, any instructions in writing these off?

Body:
The safest and best way is to use SqlParameter like the following example :

SqlCommand cmd = new SqlCommand("insert into BUDGETTING_A values (@BoxEmpID ,....) ",con);
cmd.Parameters.AddWithValue("@BoxEmpID", txtBoxEmpID.Text);
cmd.Parameters.AddWithValue("@OtherField", OtherValue);
.
.
.
cmd.ExecuteNonQuery();


问:
Some form checkbox combinations do not work
I have this code and can't figure out what seems to be the problem: if i select 1 & 2, 1 & 3 it's working.
But if I select 2 or 3 only then it's not working.
What seems to be the problem?
I would like to select multiple at the same time.

i think I need to put some if and else here?
But don't really know and sure how?

This is the code:

```<code><div style="background-color:#CCDFED">
<form method="post" action="[~[*id*]~]">
   <input type="hidden" name="formid" value="registrationForm" />
    <table>
    <tr>
     <td>
       <label for="termine" style="margin:0.5em">Termine:</label>
     <td>
     <td>
       <input type="checkbox" name="termine1" value="Montag 4. Oktober 2010"    eform="Termine::1"/>	Montag 4. Oktober 2010 <br/>
       <input type="checkbox" name="termine2" value="Mittwoch 13. Oktober 2010" />	Mittwoch 13. Oktober 2010 <br/>
       <input type="checkbox" name="termine3" value="Freitag 22. Oktober 2010"  />	Freitag 22. Oktober 2010 <br/>
     </td>
    </tr>
    <tr>
      <td><label for="email" style="margin:0.5em">Email:</label></td>
      <td><input type="text" name="email" size="60" maxlength="60" eform="Email:email:1" /><td>
    </tr>
    <tr>
    <td>
       <label style="margin:0.5em; display:block" for="kopieren" >Bitte kopieren Sie den Anti-Spam Code ein: </label>
       <img src="[+verimageurl+]" alt="verification code" border="1" style="margin:0.5em"/></td>
     </td>
     <td valign="top"><input type="text" name="vericode" size="20" /> </td>
    </tr>
    <tr>
      <td rowspan="3" valign="right">
         <input align="right" type="submit" name="submit" style="margin:0.5em" value="Register" />
      </td>
    </tr>
</table>
</form>
</div>
</code>```

答:
This might because of label is not attaching with your, checkbox, just provide Id to checkbox, please refer below

```<code> <input type="checkbox" id="termine1" name="termine1" value="Montag 4. Oktober 2010" eform="Termine::1" />
        <label for="termine1">	Montag 4. Oktober 2010</label>
</code>```

Hope this will resolve your issue.

ContentLicense: CC BY-SA 4.0

Body:
I have this code and can't figure out what seems to be the problem: if i select 1 & 2, 1 & 3 it's working.
But if I select 2 or 3 only then it's not working.
What seems to be the problem?
I would like to select multiple at the same time.

i think I need to put some if and else here?
But don't really know and sure how?

This is the code:

<form method="post" action="[~[*id*]~]">
   <input type="hidden" name="formid" value="registrationForm" />

       Termine:

       <input type="checkbox" name="termine1" value="Montag 4. Oktober 2010"    eform="Termine::1"/>	Montag 4. Oktober 2010

       <input type="checkbox" name="termine2" value="Mittwoch 13. Oktober 2010" />	Mittwoch 13. Oktober 2010

       <input type="checkbox" name="termine3" value="Freitag 22. Oktober 2010"  />	Freitag 22. Oktober 2010

      Email:
      <input type="text" name="email" size="60" maxlength="60" eform="Email:email:1" />

       Bitte kopieren Sie den Anti-Spam Code ein:

     <input type="text" name="vericode" size="20" />

         <input align="right" type="submit" name="submit" style="margin:0.5em" value="Register" />

</form>

Body:
This might because of label is not attaching with your, checkbox, just provide Id to checkbox, please refer below

 <input type="checkbox" id="termine1" name="termine1" value="Montag 4. Oktober 2010" eform="Termine::1" />
        <label for="termine1">&#09;Montag 4. Oktober 2010</label>

Hope this will resolve your issue.


问:
Installing Java libraries
As I'm quite new to Java, I would like to know the proper procedure of installing new libraries (those that are no available in my linux dist repositories).
Where should I place them? and how to install them?
For instance, I downloaded openCsv (http://opencsv.sourceforge.net/), and I have no idea how to install it.</p>

答: Java libraries don't really need to be 'installed' like other applications.  All you need to do is put the jar file in a specific location, and add the jar file to your classpath.  How you do that depends on the linux distro you are using.  If you are making a web application in eclipse, you can drop the .jar file in the WebRoot/web-inf/lib folder, and it will be bundled in with your project.</p>

Title: Installing Java libraries

ContentLicense: CC BY-SA 2.5


问:
How to Fix Permissions on Home-brew on MacOS High Sierra
When I tried to install python onto homebrew it downloaded it and then an error message popped up at the end that stopped it from completing. When I try to do it again it asks me to do:

```<code>$ brew link python
</code>```

After entering that the same error message appears:

```permission denied @ dir_s_mkdir - /usr/local/lib```

I have tried to do:

```<code>$ sudo chown -R $(whoami) /usr/local
</code>```

And I get an error message that reads:

chown: /usr/local: Operation not permitted

答:
macOS provides a number of ways to control access to files, beyond the traditional permissions for user, group, and other. This includes access control lists (ACLs), file flags, extended attributes (xattrs), and, more recently, Apple's System Integrity Protection.

I'm betting that if you run ls -lO /usr/, to list the flags, you'll see uchg in front of /usr/local, which instructs the system to make the file immutable by any user. (The u in uchg means that the file owner may modify this flag. Neither the owner nor any other user may modify the file itself.)

To solve the problem, you'll first need to remove the flag by running: chflags nouchg /usr/local. This should remove the uchg flag, which you should verify again with ls -lO. If another flag, such as schg is set, use noschg, or no<flag> in general, but you'll need to sudo the commands when the flag starts with s.

At this point, you may still need to chown the directory, with sudo chown -R $(whoami) /usr/local. You should now own the directory, and Homebrew tools should work fine.

Body:
When I tried to install python onto homebrew it downloaded it and then an error message popped up at the end that stopped it from completing. When I try to do it again it asks me to do:

$ brew link python

After entering that the same error message appears:

permission denied @ dir_s_mkdir - /usr/local/lib

I have tried to do:

$ sudo chown -R $(whoami) /usr/local

And I get an error message that reads:

chown: /usr/local: Operation not permitted


问:
Nginx real client IP to TCP stream backend
I'm trying to use Nginx as proxy for my TCP daemon, to make Nginx be SSL/TLS frontend, as well as load control.

My backend app needs real client IP, and this is a problem.

```<code>stream {
    server {
        listen     3333;
        proxy_pass 127.0.0.1:2222;
    }
}
</code>```

I found one solution in docs:

```<code>proxy_bind $remote_addr transparent;
</code>```

But it's too complicated:

"In order for this parameter to work, it is necessary to run nginx
  worker processes with the superuser privileges and configure kernel
  routing table to intercept network traffic from the proxied server."

Is there any other way to pass $remote_addr to backend?

I tried modify client message body using sub_filter, send http headers, etc. But all of this can work only with http context, not with stream unfortunately.

答:
"set_real_ip_from" directive should be the address/CIDR of the edge device</p>

```<code>stream {
    server {
        listen            3333 proxy_protocol;
        proxy_pass        127.0.0.1:2222;
        proxy_protocol    on;
        set_real_ip_from  10.0.0.0/8;
    }
}
</code>```

Body:
I'm trying to use Nginx as proxy for my TCP daemon, to make Nginx be SSL/TLS frontend, as well as load control.

My backend app needs real client IP, and this is a problem.

stream {
    server {
        listen     3333;
        proxy_pass 127.0.0.1:2222;
    }
}

I found one solution in docs:

proxy_bind $remote_addr transparent;

But it's too complicated:

"In order for this parameter to work, it is necessary to run nginx
  worker processes with the superuser privileges and configure kernel
  routing table to intercept network traffic from the proxied server."

Is there any other way to pass $remote_addr to backend?

I tried modify client message body using sub_filter, send http headers, etc. But all of this can work only with http context, not with stream unfortunately.

Body:
"set_real_ip_from" directive should be the address/CIDR of the edge device

stream {
    server {
        listen            3333 proxy_protocol;
        proxy_pass        127.0.0.1:2222;
        proxy_protocol    on;
        set_real_ip_from  10.0.0.0/8;
    }
}


问:
Why my email sender does not update when I change the settings in env laravel on staging server?
I use laravel 5.3 and I change env on the staging server on the forge (https://forge.laravel.com)

I change like this :

```<code>#MAIL_HOST=smtp.gmail.com
#MAIL_PORT=587
#MAIL_USERNAME=mygmail@gmail.com
#MAIL_PASSWORD=secret
#MAIL_ENCRYPTION=tls

MAIL_HOST=mail.myshop.id
MAIL_PORT=587
MAIL_USERNAME=contact@myshop.id
MAIL_PASSWORD=secret
MAIL_ENCRYPTION=tls
</code>```

If I try send mail in my system, the email sender is mygmail@gmail.com

Should the email sender contact@myshop.id

How can I solve this problem?

答:
MAIL CONFIGURATION on your ENV doesn't mean that will be your sender email to be display on the recipient that will just be the credentials to be used in order the email service work, if you want you may configure it using the mail.php configuration file in config folder or directly to the Mail function of laravel.</p>

```<code>$mail->from(YOUR_EMAIL_ADDRESS,YOUR_DISPLAY_NAME);
</code>```

Body:
I use laravel 5.3 and I change env on the staging server on the forge (https://forge.laravel.com)

I change like this :

#MAIL_HOST=smtp.gmail.com
#MAIL_PORT=587
#MAIL_USERNAME=mygmail@gmail.com
#MAIL_PASSWORD=secret
#MAIL_ENCRYPTION=tls

MAIL_HOST=mail.myshop.id
MAIL_PORT=587
MAIL_USERNAME=contact@myshop.id
MAIL_PASSWORD=secret
MAIL_ENCRYPTION=tls

If I try send mail in my system, the email sender is mygmail@gmail.com

Should the email sender contact@myshop.id

How can I solve this problem?

Body:
MAIL CONFIGURATION on your ENV doesn't mean that will be your sender email to be display on the recipient that will just be the credentials to be used in order the email service work, if you want you may configure it using the mail.php configuration file in config folder or directly to the Mail function of laravel.

$mail->from(YOUR_EMAIL_ADDRESS,YOUR_DISPLAY_NAME);


问:
Add line break to WordPress post using a function
I'm trying to add a line break to my WordPress post titles.

I only want the line break to appear on the single.php page when it finds this symbol "|" (without quotes) in the title.

This post and others like it here on SO say it can be done by using this inside my template:

```<code><?php echo str_replace(' | ', '<br />', get_the_title()); ?>
</code>```

But in my case I cannot edit the single.php page directly so I need to add this functionality via some code in the functions.php file.

Do you know what code I should be using?

I tried the code below, but I'm new to this and just hacked it together from what I found online, needless to say it does not work...

```<code>function line_break_for_posts_filter($title){
  str_replace(' | ', '<br />', get_the_title());
  }
add_filter('the_title', 'line_break_for_posts_filter');
</code>```

答:
You've forgotten to return the filtered result in your line_break_for_posts_filter function. Try this:

```<code>function line_break_for_posts_filter($title){
    if ( is_singular() ) {
        return str_replace(' | ', '<br />', $title);
    } else {
        return str_replace(' | ', '', $title);
    }
}
add_filter('the_title', 'line_break_for_posts_filter');
</code>```

Body:
I'm trying to add a line break to my WordPress post titles.

I only want the line break to appear on the single.php page when it finds this symbol "|" (without quotes) in the title.

This post and others like it here on SO say it can be done by using this inside my template:

<?php echo str_replace(' | ', '
', get_the_title()); ?>

But in my case I cannot edit the single.php page directly so I need to add this functionality via some code in the functions.php file.

Do you know what code I should be using?

I tried the code below, but I'm new to this and just hacked it together from what I found online, needless to say it does not work...

function line_break_for_posts_filter($title){
  str_replace(' | ', '
', get_the_title());
  }
add_filter('the_title', 'line_break_for_posts_filter');

Body:
You've forgotten to return the filtered result in your line_break_for_posts_filter function. Try this:

function line_break_for_posts_filter($title){
    if ( is_singular() ) {
        return str_replace(' | ', '<br />', $title);
    } else {
        return str_replace(' | ', '', $title);
    }
}
add_filter('the_title', 'line_break_for_posts_filter');


问:
How to display a different image based on button clicks with pygame?
I am coding a game for a school project. I have coded it so that I use wasd to move my character. I have four different images: one facing left, one right, one forwards, and one backwards. I need to change the image being displayed as the character based on which button I press. I have a function defining each image, and I try to call that function based on which button is pressed, and then when the button goes back up, I want to display the front facing image again. All it does is every time I press, the corresponding facing image is displayed, goes away, and then the front facing image is displayed and then goes away very quickly. This is just the part that actually deals with the character:</p>

```<code>howieImg = pygame.image.load('howie front.PNG')
howieImg_back = pygame.image.load('howie back.PNG')
howieImg_left = pygame.image.load('howie left.PNG')
howieImg_right = pygame.image.load('howie right.PNG')

def howie(x, y):
gameDisplay.blit(howieImg, (x, y))
def howie_back(x, y):
gameDisplay.blit(howieImg_back, (x, y))
def howie_left(x, y):
gameDisplay.blit(howieImg_left, (x, y))
def howie_right(x, y):
gameDisplay.blit(howieImg_right, (x, y))

while not gameExit:
        startx = (display_width/2)
        starty = (display_height/2)
        thing_width = 25
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w and y > 0:
                    howie_back(x, y)
                    y_change = -3
                if event.key == pygame.K_s and y < display_height - character_height:
                    howie(x, y)
                    y_change = 3
                if event.key == pygame.K_a and x > 0:
                    howie_left(x, y)
                    x_change = -3
                if event.key == pygame.K_d and x < display_width - character_width:
                    howie_right(x, y)
                    x_change = 3
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_w or event.key == pygame.K_s:
                    howie(x, y)
                    y_change = 0
                if event.key == pygame.K_a or event.key == pygame.K_d:
                    howie(x, y)
                    x_change = 0

        x += x_change
        y += y_change

        if x > display_width - character_width or x < 0:
            x_change = 0
        if y > display_height - character_height or y < 0:
            y_change = 0

        clock.tick(60)
        gameDisplay.blit(background1Img, [0, 0])
        button1()
        howie(x, y)
        things_collected(collected)
        pygame.display.update()
</code>```

答:
I'd get rid of the functions and just store the current image in a variable (howieImg in the example below). When the user presses one of the keys, you can simply assign one of the other images to the current image variable.

```<code>import pygame

pygame.init()
gameDisplay = pygame.display.set_mode((800, 600))

# These are just replacement images that allowed me to test the code.
# howieImg_front = pygame.Surface((50, 50))
# howieImg_front.fill((0, 0, 255))
# howieImg_back = pygame.Surface((50, 50))
# howieImg_back.fill((255, 255, 0))
# howieImg_left = pygame.Surface((50, 50))
# howieImg_left.fill((255, 0, 0))
# howieImg_right = pygame.Surface((50, 50))
# howieImg_right.fill((0, 255, 0))

howieImg_front = pygame.image.load('howie front.PNG').convert_alpha()
howieImg_back = pygame.image.load('howie back.PNG').convert_alpha()
howieImg_left = pygame.image.load('howie left.PNG').convert_alpha()
howieImg_right = pygame.image.load('howie right.PNG').convert_alpha()

# Assign the current howie image to this variable.
howieImg = howieImg_front

x = 200
y = 300
x_change = 0
y_change = 0
clock = pygame.time.Clock()

gameExit = False
while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                howieImg = howieImg_back
                y_change = -3
            if event.key == pygame.K_s:
                howieImg = howieImg_front
                y_change = 3
            if event.key == pygame.K_a:
                howieImg = howieImg_left
                x_change = -3
            if event.key == pygame.K_d:
                howieImg = howieImg_right
                x_change = 3
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_w or event.key == pygame.K_s:
                howieImg = howieImg_front
                y_change = 0
            if event.key == pygame.K_a or event.key == pygame.K_d:
                howieImg = howieImg_front
                x_change = 0

    x += x_change
    y += y_change

    gameDisplay.fill((30, 30, 30))
    # Just blit the current `howieImg`.
    gameDisplay.blit(howieImg, (x, y))
    pygame.display.update()
    clock.tick(60)

pygame.quit()
</code>```

Body:
I am coding a game for a school project. I have coded it so that I use wasd to move my character. I have four different images: one facing left, one right, one forwards, and one backwards. I need to change the image being displayed as the character based on which button I press. I have a function defining each image, and I try to call that function based on which button is pressed, and then when the button goes back up, I want to display the front facing image again. All it does is every time I press, the corresponding facing image is displayed, goes away, and then the front facing image is displayed and then goes away very quickly. This is just the part that actually deals with the character:

howieImg = pygame.image.load('howie front.PNG')
howieImg_back = pygame.image.load('howie back.PNG')
howieImg_left = pygame.image.load('howie left.PNG')
howieImg_right = pygame.image.load('howie right.PNG')

def howie(x, y):
gameDisplay.blit(howieImg, (x, y))
def howie_back(x, y):
gameDisplay.blit(howieImg_back, (x, y))
def howie_left(x, y):
gameDisplay.blit(howieImg_left, (x, y))
def howie_right(x, y):
gameDisplay.blit(howieImg_right, (x, y))

while not gameExit:
        startx = (display_width/2)
        starty = (display_height/2)
        thing_width = 25
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w and y > 0:
                    howie_back(x, y)
                    y_change = -3
                if event.key == pygame.K_s and y < display_height - character_height:
                    howie(x, y)
                    y_change = 3
                if event.key == pygame.K_a and x > 0:
                    howie_left(x, y)
                    x_change = -3
                if event.key == pygame.K_d and x < display_width - character_width:
                    howie_right(x, y)
                    x_change = 3
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_w or event.key == pygame.K_s:
                    howie(x, y)
                    y_change = 0
                if event.key == pygame.K_a or event.key == pygame.K_d:
                    howie(x, y)
                    x_change = 0

        x += x_change
        y += y_change

        if x > display_width - character_width or x < 0:
            x_change = 0
        if y > display_height - character_height or y < 0:
            y_change = 0

        clock.tick(60)
        gameDisplay.blit(background1Img, [0, 0])
        button1()
        howie(x, y)
        things_collected(collected)
        pygame.display.update()

Body:
I'd get rid of the functions and just store the current image in a variable (howieImg in the example below). When the user presses one of the keys, you can simply assign one of the other images to the current image variable.

import pygame

pygame.init()
gameDisplay = pygame.display.set_mode((800, 600))

# These are just replacement images that allowed me to test the code.
# howieImg_front = pygame.Surface((50, 50))
# howieImg_front.fill((0, 0, 255))
# howieImg_back = pygame.Surface((50, 50))
# howieImg_back.fill((255, 255, 0))
# howieImg_left = pygame.Surface((50, 50))
# howieImg_left.fill((255, 0, 0))
# howieImg_right = pygame.Surface((50, 50))
# howieImg_right.fill((0, 255, 0))

howieImg_front = pygame.image.load('howie front.PNG').convert_alpha()
howieImg_back = pygame.image.load('howie back.PNG').convert_alpha()
howieImg_left = pygame.image.load('howie left.PNG').convert_alpha()
howieImg_right = pygame.image.load('howie right.PNG').convert_alpha()

# Assign the current howie image to this variable.
howieImg = howieImg_front

x = 200
y = 300
x_change = 0
y_change = 0
clock = pygame.time.Clock()

gameExit = False
while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                howieImg = howieImg_back
                y_change = -3
            if event.key == pygame.K_s:
                howieImg = howieImg_front
                y_change = 3
            if event.key == pygame.K_a:
                howieImg = howieImg_left
                x_change = -3
            if event.key == pygame.K_d:
                howieImg = howieImg_right
                x_change = 3
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_w or event.key == pygame.K_s:
                howieImg = howieImg_front
                y_change = 0
            if event.key == pygame.K_a or event.key == pygame.K_d:
                howieImg = howieImg_front
                x_change = 0

    x += x_change
    y += y_change

    gameDisplay.fill((30, 30, 30))
    # Just blit the current `howieImg`.
    gameDisplay.blit(howieImg, (x, y))
    pygame.display.update()
    clock.tick(60)

pygame.quit()


问:
How to read a space delimited file into pandas?
I have an input file that is like a table separated with ' '.

How do I read this space delimited file into my pandas dataframe?

I only know read_csv and read_excel.

Body:
IIUC

There is an Pandas DataFrame df,

import pandas as pd

example = {'col1':[1 ,2 ,5 ,7 ,2 ,3 ,2 ,4 ,8 ,9],
        'col2':[120 ,99 ,55 ,23 ,87 ,31 ,149 ,45 ,32 ,55],
        'col3':[999 ,3741 ,8893 ,5321 ,1987 ,9299 ,573 ,4732 ,4536 ,4032]}

df = pd.DataFrame(example)

As follows,

df.dtypes

Output:

col1      int64
col2      int64
col3      int64
dtype: object


问:
In python,why use function to get class member?

Hi, recently I read some codes of others , and found the differences between others and mine is that they often write a function to get class member. Like

```<code>def GetHeight
    return self.height
</code>```

instead of just using

```<code>self.height
</code>```

in the program.

I mean, in C++, I know the function of this is to get private member.

In python, though everything is set as public (in normal cases) ,

Why it has reason to be used in python? Is that just bad code?
Or something else I ignore?

I am kinda new to python, so I will appreciate it if you give some advice.

EDIT:

Similar Question It seems my question has been identified as the duplicate of another one. I checked the answer and found the answer of that is more like general advice instead of pythonic programming.

While the answer below introduces a feature of python -- property

That possibly cannot be learned from that question, so it's the reason I think my question is unique.

答: it's a matter of preference.  python lets the programmer be OO or imperative as suits.  the whole notion of accessors and mutators is old fashioned for some and beloved by others.</p>

Body:
Hi, recently I read some codes of others , and found the differences between others and mine is that they often write a function to get class member. Like

def GetHeight
    return self.height

instead of just using

self.height

in the program.

I mean, in C++, I know the function of this is to get private member.

In python, though everything is set as public (in normal cases) ,

Why it has reason to be used in python? Is that just bad code?
Or something else I ignore?

I am kinda new to python, so I will appreciate it if you give some advice.

EDIT:

Similar Question It seems my question has been identified as the duplicate of another one. I checked the answer and found the answer of that is more like general advice instead of pythonic programming.

While the answer below introduces a feature of python -- property

That possibly cannot be learned from that question, so it's the reason I think my question is unique.


问:
String to date() function not return correct ISO Date
```<code>                {
                 $addFields: {
                   date: {$substr : ["$visits.visit_date", 0,10]}
                 }
               },
                {
                    $project:{
                        now: new Date(),
                        returns: new Date("2017-09-14"),
                        visit_date: "$visits.visit_date",
                        //dateDifference: { $subtract: [ new Date(), "$visits.visit_date" ] },

                        split: "$date",
                        dates: new Date("$date")
                    }
                }
</code>```

This project return

```<code>    {
    "_id" : ObjectId("5a26856f462c9616abc98d60"),
    "now" : ISODate("2017-12-06T22:21:31.499-06:30"),
    "returns" : ISODate("2017-09-13T17:30:00.000-06:30"),
    "visit_date" : "2017-09-14 18:37:58",
    "split" : "2017-09-14",
    "dates" : ISODate("1969-12-31T17:30:00.000-06:30")
}
</code>```

see this here i get trouble it's not a correct output

"dates" : ISODate("1969-12-31T17:30:00.000-06:30")

because i get correct output while manually add a string

"returns" : ISODate("2017-09-13T17:30:00.000-06:30"),

答:
Unfortunately, your code in the top box is incomplete.

Are you trying to set date at one place in the structure at the same time as using it elsewhere?

Body:
                {
                 $addFields: {
                   date: {$substr : ["$visits.visit_date", 0,10]}
                 }
               },
                {
                    $project:{
                        now: new Date(),
                        returns: new Date("2017-09-14"),
                        visit_date: "$visits.visit_date",
                        //dateDifference: { $subtract: [ new Date(), "$visits.visit_date" ] },

                        split: "$date",
                        dates: new Date("$date")
                    }
                }

This project return

    {
    "_id" : ObjectId("5a26856f462c9616abc98d60"),
    "now" : ISODate("2017-12-06T22:21:31.499-06:30"),
    "returns" : ISODate("2017-09-13T17:30:00.000-06:30"),
    "visit_date" : "2017-09-14 18:37:58",
    "split" : "2017-09-14",
    "dates" : ISODate("1969-12-31T17:30:00.000-06:30")
}

see this here i get trouble it's not a correct output

"dates" : ISODate("1969-12-31T17:30:00.000-06:30")

because i get correct output while manually add a string

"returns" : ISODate("2017-09-13T17:30:00.000-06:30"),


答:
new Date("$date") evaluated before this is passed to mongodb aggregation pipeline and till then "$date" is just a normal string to javascript engin

for mongodb 3.6 you can use

```<code>db.coll.aggregate([
{
  $project:{

  date:{
         $dateFromString: {
            dateString: "$visits.visit_date"
         }
      }
  }
}
</code>```

Title: String to date() function not return correct ISO Date

Body:
new Date("$date") evaluated before this is passed to mongodb aggregation pipeline and till then "$date" is just a normal string to javascript engin

for mongodb 3.6 you can use

db.coll.aggregate([
{
  $project:{

  date:{
         $dateFromString: {
            dateString: "$visits.visit_date"
         }
      }
  }
}


问:
jQuery Year Picker
I have one form in that I have Year of passed out field for that I need to show only years drop down.

Is it possible to show only years in jQuery datepicker?? Otherwise is there any angular directive to show only years in drop down?

```<code>$("#date").datepicker({
  changeMonth: false,
  changeYear: true,
  dateFormat: 'dd/mm/yy',
  duration: 'fast',
  stepMonths: 0
});
</code>```

fiddle: http://jsfiddle.net/LttVe/628/

答:
Okay this is a bit of a hack..with CSS (If you add this it removes the calendar section)
Also if you need to apply it to only a particular datepicker,enclosed in a div, add a class and then use this with that class.

```<code>.ui-datepicker-calendar {
       display: none;
    }
    .ui-datepicker-month {
       display: none;
    }
    .ui-datepicker-prev{
       display: none;
    }
    .ui-datepicker-next{
       display: none;
    }
</code>```

Edit:

```<code>$("#date").datepicker({
  changeMonth: false,
  changeYear: true,
  dateFormat: 'yy',
  duration: 'fast',
  stepMonths: 0,
  onChangeMonthYear: function (e) {
    console.log(e);
        $("#date").val(e);
        $('.ui-datepicker').css("display","none").blur();
  }
});
</code>```

Use the onChangeMonthYear event, in e we are getting the selected year.
You just need to set in the text and hide the datepicker.

Title: jQuery Year Picker

Body:
I have one form in that I have Year of passed out field for that I need to show only years drop down.

Is it possible to show only years in jQuery datepicker?? Otherwise is there any angular directive to show only years in drop down?

$("#date").datepicker({
  changeMonth: false,
  changeYear: true,
  dateFormat: 'dd/mm/yy',
  duration: 'fast',
  stepMonths: 0
});

fiddle: http://jsfiddle.net/LttVe/628/

Body:
Okay this is a bit of a hack..with CSS (If you add this it removes the calendar section)
Also if you need to apply it to only a particular datepicker,enclosed in a div, add a class and then use this with that class.

.ui-datepicker-calendar {
       display: none;
    }
    .ui-datepicker-month {
       display: none;
    }
    .ui-datepicker-prev{
       display: none;
    }
    .ui-datepicker-next{
       display: none;
    }

Edit:

$("#date").datepicker({
  changeMonth: false,
  changeYear: true,
  dateFormat: 'yy',
  duration: 'fast',
  stepMonths: 0,
  onChangeMonthYear: function (e) {
    console.log(e);
        $("#date").val(e);
        $('.ui-datepicker').css("display","none").blur();
  }
});

Use the onChangeMonthYear event, in e we are getting the selected year.
You just need to set in the text and hide the datepicker.


问:
Div tag's layering question
Suppose i am having two Div layer

```<code><div id="div1"> One </div>
<div id="div2"> Two </div>
</code>```

I want them both to be overlapped

and when i click the Button
i want that the Div1 layer to go in the background and the top layer should become Div2.

How can i achieve it through JavaScript ?

答:
Vertical positioning is controlled in CSS using the "z-index" parameter.  You can set this with javascript by accessing the element's "style" parameter.

Here's a full example, with comments indicating tricky spots to watch out for:

```<code><!DOCTYPE html>
<html>
    <head>
        <style type='text/css'>
            .container {
               /* Needs explicit positioning for "absolute" positioning of
                  child elements to work properly */
               position: relative;
               /* Need to set height, because absolute-positioned child elements take up no space */
               height: 50px;
            }
            #div1, #div2 {
                position: absolute;
                left: 0;
                top: 0;
                width: 100px;
                height: 50px;
                /* without a background color, you'll see div1 through div2. */
                background-color: white;
                /* border makes it easier to see while testing */
                border: 1px solid red;
            }
        </style>
        <script type='text/javascript'>
            function swapDivs() {
                var div1 = document.getElementById('div1');
                var div2 = document.getElementById('div2');
                // swap zIndex values.
                var temp = div1.style.zIndex;
                div1.style.zIndex = div2.style.zIndex;
                div2.style.zIndex = temp;
            }
        </script>
    </head>
    <body>
        <div class='container'>
            <div id="div1" style='z-index: 0;'> One </div>
            <div id="div2" style='z-index: 1;'> Two </div>
        </div>
        <input id='switch' type='button' value='switch' onclick='swapDivs();' />
    </body>
</html>
</code>```

Title: Div tag's layering question

Body:
Suppose i am having two Div layer

 One

 Two

I want them both to be overlapped

and when i click the Button
i want that the Div1 layer to go in the background and the top layer should become Div2.

How can i achieve it through JavaScript ?

Body:
Vertical positioning is controlled in CSS using the "z-index" parameter.  You can set this with javascript by accessing the element's "style" parameter.

Here's a full example, with comments indicating tricky spots to watch out for:

<!DOCTYPE html>
<html>
    <head>
        <style type='text/css'>
            .container {
               /* Needs explicit positioning for "absolute" positioning of
                  child elements to work properly */
               position: relative;
               /* Need to set height, because absolute-positioned child elements take up no space */
               height: 50px;
            }
            #div1, #div2 {
                position: absolute;
                left: 0;
                top: 0;
                width: 100px;
                height: 50px;
                /* without a background color, you'll see div1 through div2. */
                background-color: white;
                /* border makes it easier to see while testing */
                border: 1px solid red;
            }
        </style>
        <script type='text/javascript'>
            function swapDivs() {
                var div1 = document.getElementById('div1');
                var div2 = document.getElementById('div2');
                // swap zIndex values.
                var temp = div1.style.zIndex;
                div1.style.zIndex = div2.style.zIndex;
                div2.style.zIndex = temp;
            }
        </script>
    </head>
    <body>
        <div class='container'>
            <div id="div1" style='z-index: 0;'> One </div>
            <div id="div2" style='z-index: 1;'> Two </div>
        </div>
        <input id='switch' type='button' value='switch' onclick='swapDivs();' />
    </body>
</html>


问:
Setting a Loading Screen Within the Theme.res CodenameOne
I'm trying to make a loading screen that pops up for my app for purely cosmetic reasons. I have read these two articles https://www.codenameone.com/javadoc/com/codename1/ui/InfiniteContainer.html https://www.codenameone.com/javadoc/com/codename1/components/InfiniteProgress.html
but neither have really addressed what I want to create. I want to create a small loading symbol (infinite progress) on top of a logo and then have it disappear after a certain amount of time and display the rest of the app (this whole operation preferably built in to my theme). Is this possible? </p>

答:
The infinite progress is meant for in-app progress. You just want a splash screen which you can do like this:</p>

```<code>Form myForm = new Form(new BorderLayout());
myForm.add(CENTER, new ScaleImageLabel(myLogoImage));
myForm.add(SOUTH, new InfiniteProgress());
myForm.show();
UITimer.timer(4000, false, myForm, () -> showNextForm());
</code>```

Body:
The infinite progress is meant for in-app progress. You just want a splash screen which you can do like this:

Form myForm = new Form(new BorderLayout());
myForm.add(CENTER, new ScaleImageLabel(myLogoImage));
myForm.add(SOUTH, new InfiniteProgress());
myForm.show();
UITimer.timer(4000, false, myForm, () -> showNextForm());


问:
Abstract Class and Async, should I make a new base class?
I have a base class that I will be using to iterate though files and directories as shown here:

```<code>public abstract class FileRecursionBase
{
    protected DirectoryInfo Info;

    protected FileRecursionBase(string sourceDirectory, string targetDirectory)
    {
        SetSourceDirectory(sourceDirectory);
        TargetDirectory = targetDirectory;
    }

    private string _sourceDirectory;

    protected string GetSourceDirectory()
    {
        return _sourceDirectory;
    }

    protected void SetSourceDirectory(string value)
    {
        _sourceDirectory = value;
        Info =  new DirectoryInfo(value);
    }

    protected string TargetDirectory { get; set; }

    protected abstract void ProcessFile(FileInfo file);
    protected abstract void ProcessDirectory(DirectoryInfo directory);

    protected void EnumerateFiles()
    {
        foreach (var file in Info.EnumerateFiles())
        {
            ProcessFile(file);
        }
    }

    protected void EnumerateDirectories()
    {
        foreach (var directory in Info.EnumerateDirectories())
        {
            ProcessDirectory(directory);
        }
    }

    public virtual void Initialize()
    {
        EnumerateDirectories();
    }
}
</code>```

And for simplicity let's make a simple counting class that implements this class

```<code>public class FileCounter : FileRecursionBase
{
    protected ICounter Counter;

    public FileCounter(string sourceDirectory, string targetDirectory, ICounter counter) : base(sourceDirectory, targetDirectory)
    {
        Counter = counter;
    }

    protected override void ProcessFile(FileInfo file)
    {
        Counter.Files++;
        Counter.FileSize += file.Length;
    }

    protected override void ProcessDirectory(DirectoryInfo directory)
    {
        SetSourceDirectory(directory.FullName);
        try
        {
            EnumerateFiles();
            EnumerateDirectories();
        }
        catch (Exception)
        {
            //ignore
        }
    }
}
</code>```

The class works as intended and recursively enumerates based off the ProcessDirectory and ProcessFiles methods.

However, what can I do for cases where I wanted to ProcessFiles asynchronously?
Since the abstract class is using protected methods, I cannot await a void on the Initialization.

Would I have to change the entire base class to use Tasks, even if the class
has children that isn't asynchronous?

Or is the correct way is to just create a new base class that uses Tasks and copy and paste most of the code?  Just seeing if anyone had ideas or if I am overlooking something.

答:
Actually on second thought, there really isn't a scenario where I would need  to make the base methods asynchronous.

I can simply make both ProcessFile and ProcessDirectory async in the child class.

The vast majority of async tasks are I/O bound in nature, so it should not lock the UI thread.

If in the event it does, by best practice I would call the blocking code in a Task.Run since it is CPU bound code at that point; changing the base class to Task methods wouldn't help any at all because it's running in a separate thread at that point.

Sorry, for wasting people's time.

Body:
I have a base class that I will be using to iterate though files and directories as shown here:

public abstract class FileRecursionBase
{
    protected DirectoryInfo Info;

    protected FileRecursionBase(string sourceDirectory, string targetDirectory)
    {
        SetSourceDirectory(sourceDirectory);
        TargetDirectory = targetDirectory;
    }

    private string _sourceDirectory;

    protected string GetSourceDirectory()
    {
        return _sourceDirectory;
    }

    protected void SetSourceDirectory(string value)
    {
        _sourceDirectory = value;
        Info =  new DirectoryInfo(value);
    }

    protected string TargetDirectory { get; set; }

    protected abstract void ProcessFile(FileInfo file);
    protected abstract void ProcessDirectory(DirectoryInfo directory);

    protected void EnumerateFiles()
    {
        foreach (var file in Info.EnumerateFiles())
        {
            ProcessFile(file);
        }
    }

    protected void EnumerateDirectories()
    {
        foreach (var directory in Info.EnumerateDirectories())
        {
            ProcessDirectory(directory);
        }
    }

    public virtual void Initialize()
    {
        EnumerateDirectories();
    }
}

And for simplicity let's make a simple counting class that implements this class

public class FileCounter : FileRecursionBase
{
    protected ICounter Counter;

    public FileCounter(string sourceDirectory, string targetDirectory, ICounter counter) : base(sourceDirectory, targetDirectory)
    {
        Counter = counter;
    }

    protected override void ProcessFile(FileInfo file)
    {
        Counter.Files++;
        Counter.FileSize += file.Length;
    }

    protected override void ProcessDirectory(DirectoryInfo directory)
    {
        SetSourceDirectory(directory.FullName);
        try
        {
            EnumerateFiles();
            EnumerateDirectories();
        }
        catch (Exception)
        {
            //ignore
        }
    }
}

The class works as intended and recursively enumerates based off the ProcessDirectory and ProcessFiles methods.

However, what can I do for cases where I wanted to ProcessFiles asynchronously?
Since the abstract class is using protected methods, I cannot await a void on the Initialization.

Would I have to change the entire base class to use Tasks, even if the class
has children that isn't asynchronous?

Or is the correct way is to just create a new base class that uses Tasks and copy and paste most of the code?  Just seeing if anyone had ideas or if I am overlooking something.


答:
In Python it is unnecessary to create a getter method (especially if the getter simply returns the attribute value with no checks or modifications). You can implement meaningful get and set methods but they should actually do something. The preferred approach is to use property decorators as described here: How does the @property decorator work?

```<code>class Building(object):
    def __init__(self):
        self._height = 100

    @property
    def height(self):
        return self._height

    @height.setter
    def height(self, value):
        if 0 < value < 1000:
            self._height = value
        else:
            raise ValueError('Attribute: height must be between 0 and 1000.')
</code>```

Then the property methods are used when reading from or assigning to the attribute:

```<code>b = Building()

print(b.height)
100

b.height = 90
print(b.height)
90

b.height = 2000
print(b.height)
90
</code>```

By convention, reserved attributes are preceded by a single underscore and private attributes by a double underscore. However, this is more to alert users of the class that the attributes should be handled with care and nothing prevents them from accessing the attributes.

Title: In python,why use function to get class member?

Body:
In Python it is unnecessary to create a getter method (especially if the getter simply returns the attribute value with no checks or modifications). You can implement meaningful get and set methods but they should actually do something. The preferred approach is to use property decorators as described here: How does the @property decorator work?

class Building(object):
    def __init__(self):
        self._height = 100

    @property
    def height(self):
        return self._height

    @height.setter
    def height(self, value):
        if 0 < value < 1000:
            self._height = value
        else:
            raise ValueError('Attribute: height must be between 0 and 1000.')

Then the property methods are used when reading from or assigning to the attribute:

b = Building()

print(b.height)
100

b.height = 90
print(b.height)
90

b.height = 2000
print(b.height)
90

By convention, reserved attributes are preceded by a single underscore and private attributes by a double underscore. However, this is more to alert users of the class that the attributes should be handled with care and nothing prevents them from accessing the attributes.


问:
How to access headers from a HttpClient response? (Angular / Ionic)
I'm using a login endpoint that returns a bearer token as a response header, as I can see in the "Network" Chrome inspect window:

```<code>Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:8100
Authorization:Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJuZWxpby5jdXJzb3NAZ21haWwuY29tIiwiZXhwIjoxNTEyNzA3OTQ3fQ.pOR4WrqkaFXdwbeod1tNlDniFZXTeMXzKz9uU68rLXEWDAVRgWIphvx5F_VCsXDwimD8Q04JrxelkNgZMzBgXA
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:188
(etc...)
</code>```

However, when I try to print "headers" from the response using a HttpClient instance:

```<code>  authenticate(credentials) {
    let creds = JSON.stringify(credentials);
    let contentHeader = new HttpHeaders({"Content-Type": "application/json"});
    this.http.post(this.LOGIN_URL, creds, { headers: contentHeader, observe: 'response'})
      .subscribe(
        (resp) => {
          console.log("resp-ok");
          console.log(resp.headers);
        },
        (resp) => {
          console.log("resp-error");
          console.log(resp);
        }
      );
  }
</code>```

I get a completely different structure:

```<code>HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
lazyInit : ƒ ()
lazyUpdate : null
normalizedNames : Map(0) {}
</code>```

I also tried the get(headerName) method and got null. What am I missing? How can I get that "Authorization" header from my response?

答:
try like this :</p>

```<code>authenticate(credentials) {
    let creds = JSON.stringify(credentials);
    let contentHeader = new HttpHeaders({ "Content-Type": "application/json" });
    this.http.post(this.LOGIN_URL, creds, { headers: contentHeader, observe: 'response' })
        .subscribe(
        (resp) => {
            let header: HttpHeaders = resp.headers;
            console.log(header.get('Authorization'))
        },
        (resp) => {
            console.log("resp-error");
            console.log(resp);
        }
        );
}
</code>```

Body:
I'm using a login endpoint that returns a bearer token as a response header, as I can see in the "Network" Chrome inspect window:

Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:8100
Authorization:Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJuZWxpby5jdXJzb3NAZ21haWwuY29tIiwiZXhwIjoxNTEyNzA3OTQ3fQ.pOR4WrqkaFXdwbeod1tNlDniFZXTeMXzKz9uU68rLXEWDAVRgWIphvx5F_VCsXDwimD8Q04JrxelkNgZMzBgXA
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:188
(etc...)

However, when I try to print "headers" from the response using a HttpClient instance:

  authenticate(credentials) {
    let creds = JSON.stringify(credentials);
    let contentHeader = new HttpHeaders({"Content-Type": "application/json"});
    this.http.post(this.LOGIN_URL, creds, { headers: contentHeader, observe: 'response'})
      .subscribe(
        (resp) => {
          console.log("resp-ok");
          console.log(resp.headers);
        },
        (resp) => {
          console.log("resp-error");
          console.log(resp);
        }
      );
  }

I get a completely different structure:

HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
lazyInit : ƒ ()
lazyUpdate : null
normalizedNames : Map(0) {}

I also tried the get(headerName) method and got null. What am I missing? How can I get that "Authorization" header from my response?

Body:
try like this :

authenticate(credentials) {
    let creds = JSON.stringify(credentials);
    let contentHeader = new HttpHeaders({ "Content-Type": "application/json" });
    this.http.post(this.LOGIN_URL, creds, { headers: contentHeader, observe: 'response' })
        .subscribe(
        (resp) => {
            let header: HttpHeaders = resp.headers;
            console.log(header.get('Authorization'))
        },
        (resp) => {
            console.log("resp-error");
            console.log(resp);
        }
        );
}


问:
Lagom Publish message with Kafka
Only one way of publishing is described here.
There is another way?
The example I need to make a publication with dynamic topic id and custom event without persistentEntityRegistry?
And how do I can publish the event with eventId?

```<code> @Override
  default Descriptor descriptor() {
    return named("helloservice").withCalls(
        pathCall("/api/hello/:id",  this::hello),
        pathCall("/api/event/:id", this::pushEventWithId) // id - eventId
      )
      .withTopics(
        topic(GREETINGS_TOPIC, this::greetingsTopic)
      )
      .withAutoAcl(true);
  }
</code>```

Processing request.

```<code>public ServiceCall<RequestMessage, NotUsed> pushEventWithId(String eventId) {
    return message -> {
        // Here I need push this message to kafka with eventId. Another service should be subscribed on this eventId

    }
}
</code>```

Lagom version: 1.3.10

答:
This is not currently supported. What you can do is instantiate the Kafka client directly yourself (this is not hard to do) to publish messages imperatively like that.

While support will be added for publishing messages imperatively in the future, one reason Lagom hasn't added support yet is that very often when people want to do this, they're actually introducing anti patterns into their system, such as the opportunity for inconsistency. For example, if you have service that updates some database, then publishes a message to Kafka, you've got a problem, because if the database update succeeds, but the message publish fails, then nothing is going to get that update, and your system will be in an inconsistent state. What this presentation for a detailed look into why this is a problem, and how publishing events from an event log solves it.

Title: Lagom Publish message with Kafka

Body:
Only one way of publishing is described here.
There is another way?
The example I need to make a publication with dynamic topic id and custom event without persistentEntityRegistry?
And how do I can publish the event with eventId?

 @Override
  default Descriptor descriptor() {
    return named("helloservice").withCalls(
        pathCall("/api/hello/:id",  this::hello),
        pathCall("/api/event/:id", this::pushEventWithId) // id - eventId
      )
      .withTopics(
        topic(GREETINGS_TOPIC, this::greetingsTopic)
      )
      .withAutoAcl(true);
  }

Processing request.

public ServiceCall<RequestMessage, NotUsed> pushEventWithId(String eventId) {
    return message -> {
        // Here I need push this message to kafka with eventId. Another service should be subscribed on this eventId

    }
}

Lagom version: 1.3.10


问:
Change text in HTML that I'm grabbing from a text file
What I'm doing is grabbing the HTML code for my header from a text file.

But once a User logs in I want it to say Welcome "Username" at the top, which is a dropdown to account settings, cart, etc...

So since I'm inserting the HTML into a DIV on page load, I don't actually have access to any of the elements inside in C#.

How would I go about doing this? Is there any way to access something like a (p id="name")'s inner text, after its loaded in from the text file?

Would like to do this with C# not JS please.

Edit: I have a work around for now, but I am still interested in better answers.

 headerText = headerText.Replace("::Username::", Session["Username"] as string);
```

<p>Here is my code for grabbing the HTML and pasting it in.</p>

```string headerText = File.ReadAllText(Server.MapPath("~/global/header.html"));
        string footerText = File.ReadAllText(Server.MapPath("~/global/footer.html"));

        headerText = headerText.Replace("::Username::", Session["Username"] as string);

        divHeader.InnerHtml = headerText;
        divFooter.InnerHtml = footerText;
```

<p>To be more clear, is there anyway to access something like</p>

``` <asp:Panel ID="panelAccount" runat="server">
```

which is stored in another HTML file.

答:
I have done similar work in C# earlier, I use HTMLAgilityPack for doing this kind of works. Later I start using Anglesharp since it has a very good CSS selector based support.

Try anglesharp and you can modify the HTML tag like you do in jQuery.

Body:
What I'm doing is grabbing the HTML code for my header from a text file.

But once a User logs in I want it to say Welcome "Username" at the top, which is a dropdown to account settings, cart, etc...

So since I'm inserting the HTML into a DIV on page load, I don't actually have access to any of the elements inside in C#.

How would I go about doing this? Is there any way to access something like a (p id="name")'s inner text, after its loaded in from the text file?

Would like to do this with C# not JS please.

Edit: I have a work around for now, but I am still interested in better answers.

 headerText = headerText.Replace("::Username::", Session["Username"] as string);

Here is my code for grabbing the HTML and pasting it in.

string headerText = File.ReadAllText(Server.MapPath("~/global/header.html"));
        string footerText = File.ReadAllText(Server.MapPath("~/global/footer.html"));

        headerText = headerText.Replace("::Username::", Session["Username"] as string);

        divHeader.InnerHtml = headerText;
        divFooter.InnerHtml = footerText;

To be more clear, is there anyway to access something like

 <asp:Panel ID="panelAccount" runat="server">

which is stored in another HTML file.