问:
I can't seem to get Fail2ban to successfully ban IP addresses that are trying to authenticate against our email server
Recently, my manager installed fail2ban on our ubuntu 10.04 email server to ban ip addresses that failed to authenticate to our email server. As we monitor the system, we don't see the IPs that continually try to authenticate on our system banned by fail2ban. What are we doing wrong? Below are the conf files:

fail2ban.conf

```<code># Fail2Ban configuration file
#
# Author: Cyril Jaquier
#
# $Revision: 629 $
#

[Definition]

# Option:  loglevel
# Notes.:  Set the log level output.
#          1 = ERROR
#          2 = WARN
#          3 = INFO
#          4 = DEBUG
# Values:  NUM  Default:  3
#
loglevel = 3

# Option:  logtarget
# Notes.:  Set the log target. This could be a file, SYSLOG, STDERR or STDOUT.
#          Only one log target can be specified.
# Values:  STDOUT STDERR SYSLOG file  Default:  /var/log/fail2ban.log
#
logtarget = /var/log/fail2ban.log

# Option: socket
# Notes.: Set the socket file. This is used to communicate with the daemon. Do
#         not remove this file when Fail2ban runs. It will not be possible to
#         communicate with the server afterwards.
# Values: FILE  Default:  /var/run/fail2ban/fail2ban.sock
#
socket = /var/run/fail2ban/fail2ban.sock
</code>```

jail.conf  Enabled postfix and sasl filters only

```<code># Fail2Ban configuration file.
#
# This file was composed for Debian systems from the original one
#  provided now under /usr/share/doc/fail2ban/examples/jail.conf
#  for additional examples.
#
# To avoid merges during upgrades DO NOT MODIFY THIS FILE
# and rather provide your changes in /etc/fail2ban/jail.local
#
# Author: Yaroslav O. Halchenko <debian@onerussian.com>
#
# $Revision: 281 $
#

# The DEFAULT allows a global definition of the options. They can be override
# in each jail afterwards.

[DEFAULT]

# "ignoreip" can be an IP address, a CIDR mask or a DNS host

# 12/17/19 added to line below: /8
ignoreip = 127.0.0.1/8
bantime  = -1
maxretry = 3

# "backend" specifies the backend used to get files modification. Available
# options are "gamin", "polling" and "auto".
# yoh: For some reason Debian shipped python-gamin didn't work as expected
#      This issue left ToDo, so polling is default backend for now

# 12/17/19 changed from: polling  to: auto
backend = auto

#
# Destination email address used solely for the interpolations in
# jail.{conf,local} configuration files.
destemail = root@localhost

#
# ACTIONS
#

# Default banning action (e.g. iptables, iptables-new,
# iptables-multiport, shorewall, etc) It is used to define
# action_* variables. Can be overriden globally or per
# section within jail.local file
banaction = iptables-multiport

# email action. Since 0.8.1 upstream fail2ban uses sendmail
# MTA for the mailing. Change mta configuration parameter to mail
# if you want to revert to conventional 'mail'.
mta = sendmail

# Default protocol
protocol = tcp

#
# Action shortcuts. To be used to define action parameter

# The simplest action to take: ban only
action_ = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s]

# ban & send an e-mail with whois report to the destemail.
action_mw = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s]
              %(mta)s-whois[name=%(__name__)s, dest="%(destemail)s", protocol="%(protocol)s]

# ban & send an e-mail with whois report and relevant log lines
# to the destemail.
action_mwl = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s]
               %(mta)s-whois-lines[name=%(__name__)s, dest="%(destemail)s", logpath=%(logpath)s]

# Choose default action.  To change, just override value of 'action' with the
# interpolation to the chosen action shortcut (e.g.  action_mw, action_mwl, etc) in jail.local
# globally (section [DEFAULT]) or per specific section
action = %(action_)s

#
# JAILS
#

# Next jails corresponds to the standard configuration in Fail2ban 0.6 which
# was shipped in Debian. Enable any defined here jail by including
#
# [SECTION_NAME]
# enabled = true

#
# in /etc/fail2ban/jail.local.
#
# Optionally you may override any other parameter (e.g. banaction,
# action, port, logpath, etc) in that section within jail.local

[ssh]

enabled = false
port    = ssh
filter  = sshd
logpath  = /var/log/auth.log
maxretry = 6

# Generic filter for pam. Has to be used with action which bans all ports
# such as iptables-allports, shorewall
[pam-generic]

enabled = false
# pam-generic filter can be customized to monitor specific subset of 'tty's
filter  = pam-generic
# port actually must be irrelevant but lets leave it all for some possible uses
port = all
banaction = iptables-allports
port     = anyport
logpath  = /var/log/auth.log
maxretry = 6

[xinetd-fail]

enabled   = false
filter    = xinetd-fail
port      = all
banaction = iptables-multiport-log
logpath   = /var/log/daemon.log
maxretry  = 2

[ssh-ddos]

enabled = false
port    = ssh
filter  = sshd-ddos
logpath  = /var/log/auth.log
maxretry = 6

#
# HTTP servers
#

[apache]

enabled = false
port    = http,https
filter  = apache-auth
logpath = /var/log/apache*/*error.log
maxretry = 6

# default action is now multiport, so apache-multiport jail was left
# for compatibility with previous (<0.7.6-2) releases
[apache-multiport]

enabled   = false
port      = http,https
filter    = apache-auth
logpath   = /var/log/apache*/*error.log
maxretry  = 6

[apache-noscript]

enabled = false
port    = http,https
filter  = apache-noscript
logpath = /var/log/apache*/*error.log
maxretry = 6

[apache-overflows]

enabled = false
port    = http,https
filter  = apache-overflows
logpath = /var/log/apache*/*error.log
maxretry = 2

#
# FTP servers
#

[vsftpd]

enabled  = false
port     = ftp,ftp-data,ftps,ftps-data
filter   = vsftpd
logpath  = /var/log/vsftpd.log
# or overwrite it in jails.local to be
# logpath = /var/log/auth.log
# if you want to rely on PAM failed login attempts
# vsftpd's failregex should match both of those formats
maxretry = 6

[proftpd]

enabled  = false
port     = ftp,ftp-data,ftps,ftps-data
filter   = proftpd
logpath  = /var/log/proftpd/proftpd.log
maxretry = 6

[wuftpd]

enabled  = false
port     = ftp,ftp-data,ftps,ftps-data
filter   = wuftpd
logpath  = /var/log/auth.log
maxretry = 6

#
# Mail servers
#

[postfix]
# Enabled line below on 12/17/19 by Jesus
enabled  = true
port     = smtp,ssmtp
filter   = postfix
logpath  = /var/log/mail.log

[couriersmtp]

enabled  = false
port     = smtp,ssmtp
filter   = couriersmtp
logpath  = /var/log/mail.log

#
# Mail servers authenticators: might be used for smtp,ftp,imap servers, so
# all relevant ports get banned
#

[courierauth]

enabled  = false
port     = smtp,ssmtp,imap2,imap3,imaps,pop3,pop3s
filter   = courierlogin
logpath  = /var/log/mail.log

[sasl]
enabled  = true
port     = smtp,ssmtp,imap2,imap3,imaps,pop3,pop3s
filter   = sasl
# You might consider monitoring /var/log/warn.log instead
# if you are running postfix. See http://bugs.debian.org/507990
logpath  = /var/log/mail.log

# DNS Servers

# These jails block attacks against named (bind9). By default, logging is off
# with bind9 installation. You will need something like this:
#
# logging {
#     channel security_file {
#         file "/var/log/named/security.log" versions 3 size 30m;
#         severity dynamic;
#         print-time yes;
#     };
#     category security {
#         security_file;
#     };
# };
#
# in your named.conf to provide proper logging

# Word of Caution:
# Given filter can lead to DoS attack against your DNS server
# since there is no way to assure that UDP packets come from the
# real source IP
[named-refused-udp]

enabled  = false
port     = domain,953
protocol = udp
filter   = named-refused
logpath  = /var/log/named/security.log

[named-refused-tcp]

enabled  = false
port     = domain,953
protocol = tcp
filter   = named-refused
logpath  = /var/log/named/security.log
</code>```

postfix.conf

```<code># Fail2Ban configuration file
#
# Author: Cyril Jaquier
#
# $Revision: 728 $
#

[Definition]

# Option:  failregex
# Notes.:  regex to match the password failures messages in the logfile. The
#          host must be matched by a group named "host". The tag "<HOST>" can
#          be used for standard IP/hostname matching and is only an alias for
#          (?:::f{4,6}:)?(?P<host>[\w\-.^_]+)
# Values:  TEXT
#
failregex = reject: RCPT from (.*)\[<HOST>\]: 554

# Option:  ignoreregex
# Notes.:  regex to ignore. If this regex matches, the line is ignored.
# Values:  TEXT
#
ignoreregex =
</code>```

sasl.conf

```<code># Fail2Ban configuration file
#
# Author: Yaroslav Halchenko
#
# $Revision: 728 $
#

[Definition]

# Option: failregex
# Notes.: regex to match the password failures messages in the logfile. The
#          host must be matched by a group named "host". The tag "<HOST>" can
#          be used for standard IP/hostname matching and is only an alias for
#          (?:::f{4,6}:)?(?P<host>[\w\-.^_]+)
# Values: TEXT
#
failregex = (?i): warning: [-._\w]+\[<HOST>\]: SASL (?:LOGIN|PLAIN|(?:CRAM|DIGEST)-MD5) authentication failed(: [A-Za-z0-9+/]*={0,2})?$

# Option:  ignoreregex
# Notes.:  regex to ignore. If this regex matches, the line is ignored.
# Values:  TEXT
#
ignoreregex =
</code>```

iptables show the following:

```<code>$ sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
fail2ban-sasl  tcp  --  anywhere             anywhere            multiport dports smtp,ssmtp,imap2,imap3,imaps,pop3,pop3s
fail2ban-postfix  tcp  --  anywhere             anywhere            multiport dports smtp,ssmtp

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain fail2ban-postfix (1 references)
target     prot opt source               destination
RETURN     all  --  anywhere             anywhere

Chain fail2ban-sasl (1 references)
target     prot opt source               destination
RETURN     all  --  anywhere             anywhere
</code>```

Partial log file entries(/var/log/mail.log)

```<code>Dec 29 06:39:16 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:16 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:16 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:16 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:17 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:17 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:17 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:17 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:18 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:18 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:18 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:18 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:18 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:19 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:19 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:19 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:19 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:19 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:19 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:19 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:20 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:20 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:20 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:20 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:21 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:21 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:21 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:21 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:22 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:22 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:22 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:22 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:22 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:23 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:23 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:23 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:23 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:23 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:23 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:24 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:24 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:24 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:24 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:24 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:25 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:25 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:25 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:25 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:26 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:26 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:26 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:26 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:26 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:27 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:27 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
</code>```

答:
To make changes safe from being overwritten, place them in jail.d subfolder. Do it something like this:

cat << EOF | sudo tee /etc/fail2ban/jail.d/postfix-sasl.local
[postfix-sasl]
enabled  = true
EOF
```

<p>Also, to enable a protection against really annoying and persistent bots:</p>

<pre class="lang-sh prettyprint-override"><code>cat << EOF | sudo tee /etc/fail2ban/jail.d/recidive.local
[recidive]
enabled  = true ; enable jail for repeated bans
EOF
</code>```

For some unknown reason, the suggested solution from above (https://stackoverflow.com/a/59843252/586898), on version >0.10, didn't work for me? I've created a file in jail.d/postfix-aggressive.local with the following content, but it didn't work?

```<code>[postfix]
mode = aggressive
</code>```

Body:
Recently, my manager installed fail2ban on our ubuntu 10.04 email server to ban ip addresses that failed to authenticate to our email server. As we monitor the system, we don't see the IPs that continually try to authenticate on our system banned by fail2ban. What are we doing wrong? Below are the conf files:

fail2ban.conf

# Fail2Ban configuration file
#
# Author: Cyril Jaquier
#
# $Revision: 629 $
#

[Definition]

# Option:  loglevel
# Notes.:  Set the log level output.
#          1 = ERROR
#          2 = WARN
#          3 = INFO
#          4 = DEBUG
# Values:  NUM  Default:  3
#
loglevel = 3

# Option:  logtarget
# Notes.:  Set the log target. This could be a file, SYSLOG, STDERR or STDOUT.
#          Only one log target can be specified.
# Values:  STDOUT STDERR SYSLOG file  Default:  /var/log/fail2ban.log
#
logtarget = /var/log/fail2ban.log

# Option: socket
# Notes.: Set the socket file. This is used to communicate with the daemon. Do
#         not remove this file when Fail2ban runs. It will not be possible to
#         communicate with the server afterwards.
# Values: FILE  Default:  /var/run/fail2ban/fail2ban.sock
#
socket = /var/run/fail2ban/fail2ban.sock

jail.conf  Enabled postfix and sasl filters only

# Fail2Ban configuration file.
#
# This file was composed for Debian systems from the original one
#  provided now under /usr/share/doc/fail2ban/examples/jail.conf
#  for additional examples.
#
# To avoid merges during upgrades DO NOT MODIFY THIS FILE
# and rather provide your changes in /etc/fail2ban/jail.local
#
# Author: Yaroslav O. Halchenko <debian@onerussian.com>
#
# $Revision: 281 $
#

# The DEFAULT allows a global definition of the options. They can be override
# in each jail afterwards.

[DEFAULT]

# "ignoreip" can be an IP address, a CIDR mask or a DNS host

# 12/17/19 added to line below: /8
ignoreip = 127.0.0.1/8
bantime  = -1
maxretry = 3

# "backend" specifies the backend used to get files modification. Available
# options are "gamin", "polling" and "auto".
# yoh: For some reason Debian shipped python-gamin didn't work as expected
#      This issue left ToDo, so polling is default backend for now

# 12/17/19 changed from: polling  to: auto
backend = auto

#
# Destination email address used solely for the interpolations in
# jail.{conf,local} configuration files.
destemail = root@localhost

#
# ACTIONS
#

# Default banning action (e.g. iptables, iptables-new,
# iptables-multiport, shorewall, etc) It is used to define
# action_* variables. Can be overriden globally or per
# section within jail.local file
banaction = iptables-multiport

# email action. Since 0.8.1 upstream fail2ban uses sendmail
# MTA for the mailing. Change mta configuration parameter to mail
# if you want to revert to conventional 'mail'.
mta = sendmail

# Default protocol
protocol = tcp

#
# Action shortcuts. To be used to define action parameter

# The simplest action to take: ban only
action_ = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s]

# ban & send an e-mail with whois report to the destemail.
action_mw = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s]
              %(mta)s-whois[name=%(__name__)s, dest="%(destemail)s", protocol="%(protocol)s]

# ban & send an e-mail with whois report and relevant log lines
# to the destemail.
action_mwl = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s]
               %(mta)s-whois-lines[name=%(__name__)s, dest="%(destemail)s", logpath=%(logpath)s]

# Choose default action.  To change, just override value of 'action' with the
# interpolation to the chosen action shortcut (e.g.  action_mw, action_mwl, etc) in jail.local
# globally (section [DEFAULT]) or per specific section
action = %(action_)s

#
# JAILS
#

# Next jails corresponds to the standard configuration in Fail2ban 0.6 which
# was shipped in Debian. Enable any defined here jail by including
#
# [SECTION_NAME]
# enabled = true

#
# in /etc/fail2ban/jail.local.
#
# Optionally you may override any other parameter (e.g. banaction,
# action, port, logpath, etc) in that section within jail.local

[ssh]

enabled = false
port    = ssh
filter  = sshd
logpath  = /var/log/auth.log
maxretry = 6

# Generic filter for pam. Has to be used with action which bans all ports
# such as iptables-allports, shorewall
[pam-generic]

enabled = false
# pam-generic filter can be customized to monitor specific subset of 'tty's
filter  = pam-generic
# port actually must be irrelevant but lets leave it all for some possible uses
port = all
banaction = iptables-allports
port     = anyport
logpath  = /var/log/auth.log
maxretry = 6

[xinetd-fail]

enabled   = false
filter    = xinetd-fail
port      = all
banaction = iptables-multiport-log
logpath   = /var/log/daemon.log
maxretry  = 2

[ssh-ddos]

enabled = false
port    = ssh
filter  = sshd-ddos
logpath  = /var/log/auth.log
maxretry = 6

#
# HTTP servers
#

[apache]

enabled = false
port    = http,https
filter  = apache-auth
logpath = /var/log/apache*/*error.log
maxretry = 6

# default action is now multiport, so apache-multiport jail was left
# for compatibility with previous (<0.7.6-2) releases
[apache-multiport]

enabled   = false
port      = http,https
filter    = apache-auth
logpath   = /var/log/apache*/*error.log
maxretry  = 6

[apache-noscript]

enabled = false
port    = http,https
filter  = apache-noscript
logpath = /var/log/apache*/*error.log
maxretry = 6

[apache-overflows]

enabled = false
port    = http,https
filter  = apache-overflows
logpath = /var/log/apache*/*error.log
maxretry = 2

#
# FTP servers
#

[vsftpd]

enabled  = false
port     = ftp,ftp-data,ftps,ftps-data
filter   = vsftpd
logpath  = /var/log/vsftpd.log
# or overwrite it in jails.local to be
# logpath = /var/log/auth.log
# if you want to rely on PAM failed login attempts
# vsftpd's failregex should match both of those formats
maxretry = 6

[proftpd]

enabled  = false
port     = ftp,ftp-data,ftps,ftps-data
filter   = proftpd
logpath  = /var/log/proftpd/proftpd.log
maxretry = 6

[wuftpd]

enabled  = false
port     = ftp,ftp-data,ftps,ftps-data
filter   = wuftpd
logpath  = /var/log/auth.log
maxretry = 6

#
# Mail servers
#

[postfix]
# Enabled line below on 12/17/19 by Jesus
enabled  = true
port     = smtp,ssmtp
filter   = postfix
logpath  = /var/log/mail.log

[couriersmtp]

enabled  = false
port     = smtp,ssmtp
filter   = couriersmtp
logpath  = /var/log/mail.log

#
# Mail servers authenticators: might be used for smtp,ftp,imap servers, so
# all relevant ports get banned
#

[courierauth]

enabled  = false
port     = smtp,ssmtp,imap2,imap3,imaps,pop3,pop3s
filter   = courierlogin
logpath  = /var/log/mail.log

[sasl]
enabled  = true
port     = smtp,ssmtp,imap2,imap3,imaps,pop3,pop3s
filter   = sasl
# You might consider monitoring /var/log/warn.log instead
# if you are running postfix. See http://bugs.debian.org/507990
logpath  = /var/log/mail.log

# DNS Servers

# These jails block attacks against named (bind9). By default, logging is off
# with bind9 installation. You will need something like this:
#
# logging {
#     channel security_file {
#         file "/var/log/named/security.log" versions 3 size 30m;
#         severity dynamic;
#         print-time yes;
#     };
#     category security {
#         security_file;
#     };
# };
#
# in your named.conf to provide proper logging

# Word of Caution:
# Given filter can lead to DoS attack against your DNS server
# since there is no way to assure that UDP packets come from the
# real source IP
[named-refused-udp]

enabled  = false
port     = domain,953
protocol = udp
filter   = named-refused
logpath  = /var/log/named/security.log

[named-refused-tcp]

enabled  = false
port     = domain,953
protocol = tcp
filter   = named-refused
logpath  = /var/log/named/security.log

postfix.conf

# Fail2Ban configuration file
#
# Author: Cyril Jaquier
#
# $Revision: 728 $
#

[Definition]

# Option:  failregex
# Notes.:  regex to match the password failures messages in the logfile. The
#          host must be matched by a group named "host". The tag "<HOST>" can
#          be used for standard IP/hostname matching and is only an alias for
#          (?:::f{4,6}:)?(?P<host>[\w\-.^_]+)
# Values:  TEXT
#
failregex = reject: RCPT from (.*)\[<HOST>\]: 554

# Option:  ignoreregex
# Notes.:  regex to ignore. If this regex matches, the line is ignored.
# Values:  TEXT
#
ignoreregex =

sasl.conf

# Fail2Ban configuration file
#
# Author: Yaroslav Halchenko
#
# $Revision: 728 $
#

[Definition]

# Option: failregex
# Notes.: regex to match the password failures messages in the logfile. The
#          host must be matched by a group named "host". The tag "<HOST>" can
#          be used for standard IP/hostname matching and is only an alias for
#          (?:::f{4,6}:)?(?P<host>[\w\-.^_]+)
# Values: TEXT
#
failregex = (?i): warning: [-._\w]+\[<HOST>\]: SASL (?:LOGIN|PLAIN|(?:CRAM|DIGEST)-MD5) authentication failed(: [A-Za-z0-9+/]*={0,2})?$

# Option:  ignoreregex
# Notes.:  regex to ignore. If this regex matches, the line is ignored.
# Values:  TEXT
#
ignoreregex =

iptables show the following:

$ sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
fail2ban-sasl  tcp  --  anywhere             anywhere            multiport dports smtp,ssmtp,imap2,imap3,imaps,pop3,pop3s
fail2ban-postfix  tcp  --  anywhere             anywhere            multiport dports smtp,ssmtp

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain fail2ban-postfix (1 references)
target     prot opt source               destination
RETURN     all  --  anywhere             anywhere

Chain fail2ban-sasl (1 references)
target     prot opt source               destination
RETURN     all  --  anywhere             anywhere

Partial log file entries(/var/log/mail.log)

Dec 29 06:39:16 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:16 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:16 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:16 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:17 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:17 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:17 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:17 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:18 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:18 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:18 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:18 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:18 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:19 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:19 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:19 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:19 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:19 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:19 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:19 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:20 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:20 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:20 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:20 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:21 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:21 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:21 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:21 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:22 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:22 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:22 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:22 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:22 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:23 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:23 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:23 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:23 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:23 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:23 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:24 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:24 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:24 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:24 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:24 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:25 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:25 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:25 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:25 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:26 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:26 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:26 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:26 mail postfix/smtpd[19460]: connect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:26 mail postfix/smtpd[19460]: warning: 38-155-190-109.dsl.ovh.fr[109.190.155.38]: SASL LOGIN authentication failed: authentication failure
Dec 29 06:39:27 mail postfix/smtpd[19460]: lost connection after AUTH from 38-155-190-109.dsl.ovh.fr[109.190.155.38]
Dec 29 06:39:27 mail postfix/smtpd[19460]: disconnect from 38-155-190-109.dsl.ovh.fr[109.190.155.38]

Body:
To make changes safe from being overwritten, place them in jail.d subfolder. Do it something like this:

cat << EOF | sudo tee /etc/fail2ban/jail.d/postfix-sasl.local
[postfix-sasl]
enabled  = true
EOF

Also, to enable a protection against really annoying and persistent bots:

cat << EOF | sudo tee /etc/fail2ban/jail.d/recidive.local
[recidive]
enabled  = true ; enable jail for repeated bans
EOF

For some unknown reason, the suggested solution from above (https://stackoverflow.com/a/59843252/586898), on version >0.10, didn't work for me? I've created a file in jail.d/postfix-aggressive.local with the following content, but it didn't work?

[postfix]
mode = aggressive


来源: stackexchange

问:
How can I develop for iPhone using a Windows development machine?
Is there any way to tinker with the iPhone SDK on a Windows machine? Are there plans for an iPhone SDK version for Windows?

The only other way I can think of doing this is to run a Mac VM image on a VMWare server running on Windows, although I'm not too sure how legal this is.

答:
Yes and you don't need to learn Objective-C and buying Apple software and hardware.

Adobe have created compilator from ActionScript 3 to program for iOS. And later Apple approved this method of application creation.

This is best way to create Apple applications under Windows or Linux/BSD (and another one for MacOS-X)

OwnerDisplayName: ryanmcc

ContentLicense: CC BY-SA 3.0


问:
Don't get result when I try to read console output error in java
I'm using NetBeans to build a java project, I try to read every error shown in the console and put it in frame to be shown to user.
I searching for a way to do that I found Console c=System.console() to take every output written in console so I try first to test this command by read errors and put them in a file

```<code>  if(c.readLine().equals("")){
        System.out.println("OK!!!");
    }else{
         System.out.println("not OK!!!");
        try {
         FileWriter myWriter = new FileWriter("Error.txt");
         myWriter.write(""+c.readLine().toString());
         myWriter.close();
         System.out.println("Successfully wrote to the file.");
      } catch (IOException e) {
         System.out.println("An error occurred.");
         e.printStackTrace();
       }
    }
</code>```

But I get this error exceptionException in thread "AWT-EventQueue-0" java.lang.NullPointerException

And this error exception still even after I put System.out.println("Something here");in main project to see if this exception shown because I don't put nothing in console but gone when I scanner something in console, but this is not what I looking for so how can I read error from console?

答:
if you want to write the output of an Exception into a file, you have to mention that in the catch() block. (if you have multiple catch blocks, you can create a method that contains the writing process and call it each time, to avoid repeating the same code each time )

```<code>try
{
   //... some code...
}
catch (Exception e)
{
     FileWriter myWriter = new FileWriter("Error.txt",true);
     PrintWriter pw = new PrintWriter (myWriter);
     e.printStackTrace (pw);
     System.out.println("Successfully wrote to the file."); //this will be only shown in the console,
                                                           // but never printed in the file
}
</code>```

this way, you no longer need the code that you provided which is totally wrong. you can just remove it

ContentLicense: CC BY-SA 4.0

Body:
I'm using NetBeans to build a java project, I try to read every error shown in the console and put it in frame to be shown to user.
I searching for a way to do that I found Console c=System.console() to take every output written in console so I try first to test this command by read errors and put them in a file

  if(c.readLine().equals("")){
        System.out.println("OK!!!");
    }else{
         System.out.println("not OK!!!");
        try {
         FileWriter myWriter = new FileWriter("Error.txt");
         myWriter.write(""+c.readLine().toString());
         myWriter.close();
         System.out.println("Successfully wrote to the file.");
      } catch (IOException e) {
         System.out.println("An error occurred.");
         e.printStackTrace();
       }
    }

But I get this error exceptionException in thread "AWT-EventQueue-0" java.lang.NullPointerException

And this error exception still even after I put System.out.println("Something here");in main project to see if this exception shown because I don't put nothing in console but gone when I scanner something in console, but this is not what I looking for so how can I read error from console?

Body:
if you want to write the output of an Exception into a file, you have to mention that in the catch() block. (if you have multiple catch blocks, you can create a method that contains the writing process and call it each time, to avoid repeating the same code each time )

try
{
   //... some code...
}
catch (Exception e)
{
     FileWriter myWriter = new FileWriter("Error.txt",true);
     PrintWriter pw = new PrintWriter (myWriter);
     e.printStackTrace (pw);
     System.out.println("Successfully wrote to the file."); //this will be only shown in the console,
                                                           // but never printed in the file
}

this way, you no longer need the code that you provided which is totally wrong. you can just remove it


问:
How to Loop through a ListTile from ListView.builder in flutter

I am trying to display a list tile in flutter based on list of data from cloud firestore. I want the leading icon to change for each tile when the tile is tapped. My problem is whenever I tap any tile, the whole list changes. I want only the tapped tile to change. Here is my code:

```<code> StreamBuilder(
                        stream: Firestore.instance
                            .collection('Recharge_Card')
                            .snapshots(),
                        //print an integer every 2secs, 10 times
                        builder: (context, snapshot) {
                          if (!snapshot.hasData) {
                            return Text("Loading..");
                          }
                          return SizedBox(
                            height: _height / 1.9,
                            child: ListView.builder(
                              // itemExtent: 80.0,
                              itemCount: snapshot.data.documents.length,
                              itemBuilder: (context, index) {
                                DocumentSnapshot myCards =
                                    snapshot.data.documents[index];

                                return Card(
                                  elevation: 20.0,
                                  child: ListTile(
                                    onTap: () {
                                      setState(() {
                                        x = Text('Tapped');
                                      });
                                    },
                                    leading: x,
                                    title: Text(myCards['CardPin']),
                                    trailing: Text(myCards['Value']),
                                  ),
                                );
                              },
                            ),
                          );`
                        },
                      ),
</code>```

答:
Thats happens because the x is the same for all cards, you need separate this guy, my suggestion is put the x inside DocumentSnapshot, so u can change only tapped card, something like this:

StreamBuilder(
    stream: Firestore.instance
        .collection('Recharge_Card')
        .snapshots(),
    //print an integer every 2secs, 10 times
    builder: (context, snapshot) {
        if (!snapshot.hasData) {
        return Text("Loading..");
        }
        return SizedBox(
        height: _height / 1.9,
        child: ListView.builder(
            // itemExtent: 80.0,
            itemCount: snapshot.data.documents.length,
            itemBuilder: (context, index) {
            DocumentSnapshot myCards =
                snapshot.data.documents[index];

            return Card(
                elevation: 20.0,
                child: ListTile(
                onTap: () {
                    setState(() {
                        myCards['x'] = Text('Tapped');
                    });
                },
                leading: myCards['x'],
                title: Text(myCards['CardPin']),
                trailing: Text(myCards['Value']),
                ),
            );
            },
        ),
        );`
    },
),
```

Body:
I am trying to display a list tile in flutter based on list of data from cloud firestore. I want the leading icon to change for each tile when the tile is tapped. My problem is whenever I tap any tile, the whole list changes. I want only the tapped tile to change. Here is my code:

 StreamBuilder(
                        stream: Firestore.instance
                            .collection('Recharge_Card')
                            .snapshots(),
                        //print an integer every 2secs, 10 times
                        builder: (context, snapshot) {
                          if (!snapshot.hasData) {
                            return Text("Loading..");
                          }
                          return SizedBox(
                            height: _height / 1.9,
                            child: ListView.builder(
                              // itemExtent: 80.0,
                              itemCount: snapshot.data.documents.length,
                              itemBuilder: (context, index) {
                                DocumentSnapshot myCards =
                                    snapshot.data.documents[index];

                                return Card(
                                  elevation: 20.0,
                                  child: ListTile(
                                    onTap: () {
                                      setState(() {
                                        x = Text('Tapped');
                                      });
                                    },
                                    leading: x,
                                    title: Text(myCards['CardPin']),
                                    trailing: Text(myCards['Value']),
                                  ),
                                );
                              },
                            ),
                          );`
                        },
                      ),


问:
Compare complex object and get difference C# .NET Core 3.1
I have two object of the class Profile and I want to compare it to get the difference. To explain better:

```<code>    public partial class Profile
    {
        public long Id { get; set; }
        public long VisitorId { get; set; }
        public string Description { get; set; }
        public long Age { get; set; }
        public DateTime? LastUpdate { get; set;}
    }
</code>```

I want to know in my method the differences between the object oldProfile and newProfile to make a changelog.

For example, if oldProfile had Age = 10 and Description = "old" and newProfile has Age = 11 and Description = "new", I would now this differences to make two different insert in my database:

```<code>public void PostChangelogProfileDetail(Profile oldProfile, Profile newProfile)
{
    ProfileDetailChangeLog profileDetailChangeLog = new ProfileDetailChangeLog();

    //COMPARE oldProfile AND newProfile

    foreach ( //difference resulted in the compare)
    {
        profileDetailChangeLog.VisitorId = newProfile.VisitorId;
        profileDetailChangeLog.ModifiedRecord = //name of the attribute modified (Age, Description, etc...)

        _profileDetailChangeLog.Create(profileDetailChangeLog);
    }
}
</code>```

答:
You are likely looking to use EF Cores Metadata about an object it is tracking to determine the changes to it. I have done something similar to the stackoverflow solution myself in .net core 3 which makes me believe 3.1 should work as well.

There are articles describing approaches for this in the following articles:
Getting all changes made to an object in the Entity Framework & ChangeTracker in Entity Framework Core.

Body:
I have two object of the class Profile and I want to compare it to get the difference. To explain better:

    public partial class Profile
    {
        public long Id { get; set; }
        public long VisitorId { get; set; }
        public string Description { get; set; }
        public long Age { get; set; }
        public DateTime? LastUpdate { get; set;}
    }

I want to know in my method the differences between the object oldProfile and newProfile to make a changelog.

For example, if oldProfile had Age = 10 and Description = "old" and newProfile has Age = 11 and Description = "new", I would now this differences to make two different insert in my database:

public void PostChangelogProfileDetail(Profile oldProfile, Profile newProfile)
{
    ProfileDetailChangeLog profileDetailChangeLog = new ProfileDetailChangeLog();

    //COMPARE oldProfile AND newProfile

    foreach ( //difference resulted in the compare)
    {
        profileDetailChangeLog.VisitorId = newProfile.VisitorId;
        profileDetailChangeLog.ModifiedRecord = //name of the attribute modified (Age, Description, etc...)

        _profileDetailChangeLog.Create(profileDetailChangeLog);
    }
}


问:
Conditional isn't working while checking input type int
Well I'm very very new to python programming and still learning.So I tried to create a function where I used len to count the number of letters in a string.But since, len  doesn't work for integers I set up conditionals so that it would return a message saying "integers don't have length".
But I'm not getting the message even when I type an integer. please help me to solve this.
here is my code:

```<code>def Length_String(L):
    if type(L) == int:
        return "sorry,integers don't have length"
    else:
        return len(L)
x = input()
y = Length_String(x)
print(y)
</code>```

It's not that important but still I want to know what is causing the conditional not to work. please help me.

答: They input function in Python returns a value of type str even if what you type in is an integer value.

Body:
Well I'm very very new to python programming and still learning.So I tried to create a function where I used len to count the number of letters in a string.But since, len  doesn't work for integers I set up conditionals so that it would return a message saying "integers don't have length".
But I'm not getting the message even when I type an integer. please help me to solve this.
here is my code:

def Length_String(L):
    if type(L) == int:
        return "sorry,integers don't have length"
    else:
        return len(L)
x = input()
y = Length_String(x)
print(y)

It's not that important but still I want to know what is causing the conditional not to work. please help me.


问:
Laravel: one to one relationship becomes one to many relationship
When I create a one-to-one relationship migration, laravel creates a one-to-many relationship.

PHP 7.1 & MySQL 5.7

The models are: Persona & User.

Persona:

```<code>public function user()
{
    return $this->hasOne('App\User', 'persona_id', 'id');
}
</code>```

User:

```<code>public function persona()
{
    return $this->belongsTo('App\Persona', 'persona_id', 'id');
}
</code>```

Migrations:

```<code>Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('persona_id')->unsigned();
    $table->foreign('persona_id')->references('id')->on('personas')->onDelete('cascade');
    $table->unique(['persona_id', 'id']);
    $table->string('email')->nullable()->unique();
    $table->string('password')->nullable();
    $table->rememberToken();
    $table->timestamps();
});

Schema::create('personas', function (Blueprint $table) {
    $table->increments('id');
    $table->string('tipo');
    $table->integer('cedula')->unsigned()->unique();
    $table->string('primer_nombre');
    $table->string('segundo_nombre')->nullable();
    $table->string('primer_apellido');
    $table->string('segundo_apellido')->nullable();
    /* Agregar demas campos que se requieran */
    $table->timestamps();
});
</code>```

How can I make the relationship created in the database one by one and not one to many?
Currently this is allowing me to save more than one user per person.

Thanks.

答:
I would just replace:

```<code>$table->integer('persona_id')->unsigned();
$table->unique(['persona_id', 'id']);
</code>```

by

```<code>$table->integer('persona_id')->unique();
</code>```

Body:
When I create a one-to-one relationship migration, laravel creates a one-to-many relationship.

PHP 7.1 & MySQL 5.7

The models are: Persona & User.

Persona:

public function user()
{
    return $this->hasOne('App\User', 'persona_id', 'id');
}

User:

public function persona()
{
    return $this->belongsTo('App\Persona', 'persona_id', 'id');
}

Migrations:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('persona_id')->unsigned();
    $table->foreign('persona_id')->references('id')->on('personas')->onDelete('cascade');
    $table->unique(['persona_id', 'id']);
    $table->string('email')->nullable()->unique();
    $table->string('password')->nullable();
    $table->rememberToken();
    $table->timestamps();
});

Schema::create('personas', function (Blueprint $table) {
    $table->increments('id');
    $table->string('tipo');
    $table->integer('cedula')->unsigned()->unique();
    $table->string('primer_nombre');
    $table->string('segundo_nombre')->nullable();
    $table->string('primer_apellido');
    $table->string('segundo_apellido')->nullable();
    /* Agregar demas campos que se requieran */
    $table->timestamps();
});

How can I make the relationship created in the database one by one and not one to many?
Currently this is allowing me to save more than one user per person.

Thanks.

Body:
I would just replace:

$table->integer('persona_id')->unsigned();
$table->unique(['persona_id', 'id']);

by

$table->integer('persona_id')->unique();


问:
How do I play audio from POST response?
I'm making an ajax call to website that generates audio file for me.

```<code>    $.ajax({
        type: "POST",
        url: "http://localhost/download",
        data: "data",
        success: (response=>{
        console.log(response)
        const w = new Audio(response);
        w.play()
    })

})
</code>```

I get the response with filesize as expected (I can check it in Network tab) but when I'm trying to assign the response as a new Audio, it ends up with error

```<code>Invalid URI. Load of media resource ID3� failed.
</code>```

答:
You need to set the source of the audio after creating an ObjectURL from the blob:</p>

```<code>$.ajax({
  type: "POST",
  url: "http://localhost/download",
  data: "data",
  success: (response) => {
    console.log(response);
    var url = window.URL.createObjectURL(response.value); //where value is the blob
    const w = new Audio();
    w.src = url;
    w.play();
  },
});
</code>```

Title: How do I play audio from POST response?

Body:
I'm making an ajax call to website that generates audio file for me.

    $.ajax({
        type: "POST",
        url: "http://localhost/download",
        data: "data",
        success: (response=>{
        console.log(response)
        const w = new Audio(response);
        w.play()
    })

})

I get the response with filesize as expected (I can check it in Network tab) but when I'm trying to assign the response as a new Audio, it ends up with error

Invalid URI. Load of media resource ID3� failed.

Body:
You need to set the source of the audio after creating an ObjectURL from the blob:

$.ajax({
  type: "POST",
  url: "http://localhost/download",
  data: "data",
  success: (response) => {
    console.log(response);
    var url = window.URL.createObjectURL(response.value); //where value is the blob
    const w = new Audio();
    w.src = url;
    w.play();
  },
});


问:
Is there a way in c++ to make sure that class member function isnt changing any of the class data members?
Lets say that I have a </p>

```<code>class Dictionary
{
vector<string> words;
void addWord(string word)//adds to words
{
/...
}
bool contains(string word)//only reads from words
{
//...
}
}
</code>```

<p>Is there a way to make compiler check that contains isnt changing words vector. Ofc this is just an example with one class data member, I would like it to work with any number of data members.
P.S. I know i have no public: and private:, I left it out intentionally to make code shorter and problem clearer. </p>

答:
Usually declaring the method as "const" achieves this:

```<code>bool contains(string word) const
// ...
</code>```

The compiler will tell you if you use any method on the class members that is not also const. Note also that you could pass the string by reference to avoid copying (making the word parameter std::string const&).

Body:
Lets say that I have a

class Dictionary
{
vector<string> words;
void addWord(string word)//adds to words
{
/...
}
bool contains(string word)//only reads from words
{
//...
}
}

Is there a way to make compiler check that contains isnt changing words vector. Ofc this is just an example with one class data member, I would like it to work with any number of data members.
P.S. I know i have no public: and private:, I left it out intentionally to make code shorter and problem clearer.

Body:
Usually declaring the method as "const" achieves this:

bool contains(string word) const
// ...

The compiler will tell you if you use any method on the class members that is not also const. Note also that you could pass the string by reference to avoid copying (making the word parameter std::string const&).


问:
Java variable initializates only once
I have following code:

```<code>String test = "Test" + System.currentTimeMillis();
</code>```

When I print out this string several times it shows me exactly the same value.

```<code>System.out.println(test);
Thread.sleep(1000L);
System.out.println(test);
</code>```

The result is following:

```<code>Test1591096276651
Test1591096276651
</code>```

Why it didn't print result with difference in one second?

Is this JVM cache or something like that?
How does variable initialization work?
How does JVM know that it has been initialized and how to force it to reinitialize?

It would be great to read some documentation/specification to clarify why it works like it works.

答:
When you assign a value to variable it evaluate anything dynamic at that particular instance and doesn't re-evaluate it unless you assign it again.

String test = "Test" + System.currentTimeMillis();
print -- test
test = "Test" + System.currentTimeMillis();
printe --test

Is there any specific requirement?

Title: Java variable initializates only once

Body:
I have following code:

String test = "Test" + System.currentTimeMillis();

When I print out this string several times it shows me exactly the same value.

System.out.println(test);
Thread.sleep(1000L);
System.out.println(test);

The result is following:

Test1591096276651
Test1591096276651

Why it didn't print result with difference in one second?

Is this JVM cache or something like that?
How does variable initialization work?
How does JVM know that it has been initialized and how to force it to reinitialize?

It would be great to read some documentation/specification to clarify why it works like it works.


问:
Display Image using Image Path isn't Working
I saved user image to a folder in my wwwroot folder and saved the image path to my database, Razor Pages, now i want to display the same image using the image path, its not working.

Here is my code to save the image

```<code>if (Imagefile != null && Imagefile.Length > 0)
            {
                var imgpath = @"\Upload\pkgimages\";
                var uploadpth = _env.WebRootPath + imgpath;

                //Create Directory
                if (!Directory.Exists(uploadpth))
                {
                    Directory.CreateDirectory(uploadpth);
                }
                //create file
                var uniqueFilename = Guid.NewGuid().ToString();
                var filename = Path.GetFileName(uniqueFilename + "." + Imagefile.FileName.Split(".")[1].ToLower());
                string fullPath = Path.Combine(uploadpth, filename);
                using (var filestream = new FileStream(fullPath, FileMode.Create))
                {
                    Input.ImagePath = fullPath;
                    await Imagefile.CopyToAsync(filestream);
                }
            }

            var today = DateTime.Now;
            var exp = today.AddDays(Input.Duration);
            Input.expDate = exp;
            var pkg= new UserPackages
            {
                Title = Input.Title,
                BeginDate = DateTime.Now,
                ExpDate=Input.expDate,
                Status = "Pending",
                PackageID = pckID,
                UserID = Loginuser,
                ImagePath = Input.ImagePath
            };
            await _userPackageDataService.AddUserPackage(pkg)
</code>```

It saves everything correctly to their respective places now to retrieve the these details back and display the uploaded image

here is my code

```<code> public async Task OnGetAsync(string ID)
    {
        Guid _pkgID = Guid.Parse(ID);
        var package= await _userPackageDataService.ReviewPackage(_pkgID);
        var result= _mapper.Map<packageDTO>(package);
        UserPackage= result;
    }
</code>```

then in my chtml file I have this markup

```<code>  <div class="col-sm-6">
            <img src="@Model.UserPackage.ImagePath" alt="Image" style="width:200px; height:200px;" />
        </div>
</code>```

I have also tried

```<code> <div class="col-sm-6">
            <img src="@Uri.Content(Model.UserPackage.ImagePath)" alt="Image" style="width:200px; height:200px;" />
        </div>
</code>```

It returns the full image path wish was saved to the database but image is not rendered on the browser, please what am i missing out here?
Thanks

答:
A workaround to this would be to save the path to the database without the root path. Then in your razor page,

```<code><img src="~/@Model.UserPackage.ImagePath" />
</code>```

Look at the new way I added. The root path notation should be added to your path

Body:
I saved user image to a folder in my wwwroot folder and saved the image path to my database, Razor Pages, now i want to display the same image using the image path, its not working.

Here is my code to save the image

if (Imagefile != null && Imagefile.Length > 0)
            {
                var imgpath = @"\Upload\pkgimages\";
                var uploadpth = _env.WebRootPath + imgpath;

                //Create Directory
                if (!Directory.Exists(uploadpth))
                {
                    Directory.CreateDirectory(uploadpth);
                }
                //create file
                var uniqueFilename = Guid.NewGuid().ToString();
                var filename = Path.GetFileName(uniqueFilename + "." + Imagefile.FileName.Split(".")[1].ToLower());
                string fullPath = Path.Combine(uploadpth, filename);
                using (var filestream = new FileStream(fullPath, FileMode.Create))
                {
                    Input.ImagePath = fullPath;
                    await Imagefile.CopyToAsync(filestream);
                }
            }

            var today = DateTime.Now;
            var exp = today.AddDays(Input.Duration);
            Input.expDate = exp;
            var pkg= new UserPackages
            {
                Title = Input.Title,
                BeginDate = DateTime.Now,
                ExpDate=Input.expDate,
                Status = "Pending",
                PackageID = pckID,
                UserID = Loginuser,
                ImagePath = Input.ImagePath
            };
            await _userPackageDataService.AddUserPackage(pkg)

It saves everything correctly to their respective places now to retrieve the these details back and display the uploaded image

here is my code

 public async Task OnGetAsync(string ID)
    {
        Guid _pkgID = Guid.Parse(ID);
        var package= await _userPackageDataService.ReviewPackage(_pkgID);
        var result= _mapper.Map<packageDTO>(package);
        UserPackage= result;
    }

then in my chtml file I have this markup

I have also tried

It returns the full image path wish was saved to the database but image is not rendered on the browser, please what am i missing out here?
Thanks

Body:
A workaround to this would be to save the path to the database without the root path. Then in your razor page,

<img src="~/@Model.UserPackage.ImagePath" />

Look at the new way I added. The root path notation should be added to your path


问:
How to create getters and setters for all sub-properties of a Vuex state property efficiently?
I couldn't find the answer anywhere.

Let's say we have Vuex store with the following data:

Vuex store

state: {
  dialogs: {
    dialogName1: {
      value: false,
      data: {
        fileName: '',
        isValid: false,
        error: '',
        ... 10 more properties
      }
    },
    dialogName2: {
      value: false,
      data: {
        type: '',
        isValid: false,
        error: '',
        ... 10 more properties
      }
    }
  }
}
```

<h2>Dialogs.vue</h2>

<pre class="lang-html prettyprint-override"><code><div v-if="dialogName1Value">
  <input
    v-model="dialogName1DataFileName"
    :error="dialogName1DataIsValid"
    :error-text="dialogName1DataError"
  >

  <v-btn @click="dialogName1Value = false">
    close dialog
  </v-btn>
</div>
<!-- the other dialogs here -->
</code>```

Question

Let's say we need to modify some of these properties in Dialogs.vue.

What's the best practices for creating a getter and setter for every dialog property efficiently, without having to do it all manually like this:

computed: {
  dialogName1Value: {
    get () {
      return this.$store.state.dialogs.dialogName1.value
    },
    set (value) {
      this.$store.commit('SET', { key: 'dialogs.dialogName1.value', value: value })
    }
  },
  dialogName1DataFileName: {
    get () {
      return this.$store.state.dialogs.dialogName1.data.fileName
    },
    set (value) {
      this.$store.commit('SET', { key: 'dialogs.dialogName1.data.fileName', value: value })
    }
  },
  dialogName1DataIsValid: {
    get () {
      return this.$store.state.dialogs.dialogName1.data.isValid
    },
    set (value) {
      this.$store.commit('SET', { key: 'dialogs.dialogName1.data.isValid', value: value })
    }
  },
  dialogName1DataIsError: {
    get () {
      return this.$store.state.dialogs.dialogName1.data.error
    },
    set (value) {
      this.$store.commit('SET', { key: 'dialogs.dialogName1.data.error', value: value })
    }
  },
  ... 10 more properties
```

And this is only 4 properties...

I suppose I could generate those computed properties programmatically in created(), but is that really the proper way to do it?

Are there obvious, commonly known solutions for this issue that I'm not aware of?

答:
getters can be made to take a parameter as an argument - this can be the 'part' of the underlying state you want to return. This is known as Method-style access. For example:

```<code>getFilename: (state) => (dialogName) => {
    return state.dialogs[dialogName].data.fileName
}
</code>```

You can then call this getter as:

```<code>store.getters.getFilename('dialogName1')
</code>```

Note that method style access doesn't provide the 'computed property' style caching that you get with property-style access.

Body:
I couldn't find the answer anywhere.

Let's say we have Vuex store with the following data:

Vuex store

state: {
  dialogs: {
    dialogName1: {
      value: false,
      data: {
        fileName: '',
        isValid: false,
        error: '',
        ... 10 more properties
      }
    },
    dialogName2: {
      value: false,
      data: {
        type: '',
        isValid: false,
        error: '',
        ... 10 more properties
      }
    }
  }
}

Dialogs.vue

  <input
    v-model="dialogName1DataFileName"
    :error="dialogName1DataIsValid"
    :error-text="dialogName1DataError"
  >

  <v-btn @click="dialogName1Value = false">
    close dialog
  </v-btn>

Question

Let's say we need to modify some of these properties in Dialogs.vue.

What's the best practices for creating a getter and setter for every dialog property efficiently, without having to do it all manually like this:

computed: {
  dialogName1Value: {
    get () {
      return this.$store.state.dialogs.dialogName1.value
    },
    set (value) {
      this.$store.commit('SET', { key: 'dialogs.dialogName1.value', value: value })
    }
  },
  dialogName1DataFileName: {
    get () {
      return this.$store.state.dialogs.dialogName1.data.fileName
    },
    set (value) {
      this.$store.commit('SET', { key: 'dialogs.dialogName1.data.fileName', value: value })
    }
  },
  dialogName1DataIsValid: {
    get () {
      return this.$store.state.dialogs.dialogName1.data.isValid
    },
    set (value) {
      this.$store.commit('SET', { key: 'dialogs.dialogName1.data.isValid', value: value })
    }
  },
  dialogName1DataIsError: {
    get () {
      return this.$store.state.dialogs.dialogName1.data.error
    },
    set (value) {
      this.$store.commit('SET', { key: 'dialogs.dialogName1.data.error', value: value })
    }
  },
  ... 10 more properties

And this is only 4 properties...

I suppose I could generate those computed properties programmatically in created(), but is that really the proper way to do it?

Are there obvious, commonly known solutions for this issue that I'm not aware of?

Body:
getters can be made to take a parameter as an argument - this can be the 'part' of the underlying state you want to return. This is known as Method-style access. For example:

getFilename: (state) => (dialogName) => {
    return state.dialogs[dialogName].data.fileName
}

You can then call this getter as:

store.getters.getFilename('dialogName1')

Note that method style access doesn't provide the 'computed property' style caching that you get with property-style access.


问:
How to print Array smart in java?
I want print single variable, array and maybe double array,
I use following code, add a type when I need it,
but ... as you see ... it works but not smart.

So, question is "Is there a smart way to print Arrays?"

import java.util.Arrays;

class Rec{
    int val;
    public String toString(){
        return "" + val;
    }
    Rec(int val){this.val=val;}
}
public class Main
{
    public static void main(String[] args) {
        Rec r = new Rec(0);
        Boolean[] ba = new Boolean[]{true, false, true, true};
        Rec[] ra = new Rec[]{new Rec(1), new Rec(2), new Rec(3)};
        int[][] iaa = new int[][]{{1,2,3}, {3,4,5}};
        System.out.printf("r=%s ba=%s ra=%s iaa=%s \n", s(r), s(ba), s(ra), s(iaa));
    }

    static <T> String  s(T n)   {
        if(n instanceof int[]){
            return Arrays.toString((int[])n);
        }else if(n instanceof int[][]){
            return Arrays.deepToString((int[][])n);
        }else if(n instanceof boolean[]){
            return Arrays.toString((boolean[])n);
        }else if(n instanceof boolean[][]){
            return Arrays.deepToString((boolean[][])n);
        }else if(n instanceof Boolean[]){
            return Arrays.toString((Boolean[])n);
        }else if(n instanceof Rec[]){
            return Arrays.toString((Rec[])n);
        //}else if(n instanceof T[]){             // error: illegal generic type for instanceof
        //  return Arrays.toString((T[])n);
        }else{
            return "" + n;
        }
    }
}

```

答:
If you really want to customize your printing for variable arrays then why not do the following:

```<code>    public static String s(Object s) {
        return s.toString();
    }
    public static String s(Object[] s) {
        return Arrays.toString(s);
    }
    public static String s(Object[][] s) {
         return Arrays.deepToString(s);
    }
    // For each primitive type of your single or multi dimension
    // declare the following for either single or multi dimensional
    public static String s(int[][] s) {
        return Arrays.deepToString(s);
    }
    public static String s(int[] s) {
        return Arrays.toString(s);
    }
</code>```

But keep in mind you are basically repackaging what the API already does.

Title: How to print Array smart in java?

Body:
If you really want to customize your printing for variable arrays then why not do the following:

    public static String s(Object s) {
        return s.toString();
    }
    public static String s(Object[] s) {
        return Arrays.toString(s);
    }
    public static String s(Object[][] s) {
         return Arrays.deepToString(s);
    }
    // For each primitive type of your single or multi dimension
    // declare the following for either single or multi dimensional
    public static String s(int[][] s) {
        return Arrays.deepToString(s);
    }
    public static String s(int[] s) {
        return Arrays.toString(s);
    }

But keep in mind you are basically repackaging what the API already does.


问:
How can I assign an integer value to a button using React and JSX?
So basically I am practicing React and trying to make simple components communicate with the parent component. I have come to an issue where I can't figure out how to change the value of a button into an integer so I can make simple calulations. I have tried setting the value with parseInt and without it as well, but I can't seen to understand, pressing the "add" button gives me a NaN. Could anyone help me?
This is what I have in my App.js

```<code>import './App.css';
import Input from "./Components/Input"

class App extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      number: 10
    }
  }

  number1 = (event) => {
    this.setState({number: event.target.value})

  }

  number2 = (event) => {
    this.setState({number: event.target.value})
    if (this.state.number < 1){
      this.setState({number: 0})
    }

  }

  add = (event) => {
    this.setState({number: this.number+1})

  }

  render() {
    return (
      <div>
        <Input  number={this.state.number}
                number1={this.number1}
                number2={this.number2}
                add={this.add} />
      </div>
    );
  }
}

export default App;
</code>```

and this is what I have in Input.js

```<code>let numberValue1= parseInt("8")
let numberValue2= parseInt("17")

const Input = ({number, number1, number2, add}) =>{
    return(
        <div>
            <h1>{number}</h1>
            <button value={numberValue1} onClick={number1}>Add</button>
            <button value={numberValue2} onClick={number2}>Subtract</button>
            <button  onClick={add}>Subtract</button>
        </div>
    );
}

export default Input;```

```

答:
What you're trying to do is fundamentally a bit strange - you probably shouldn't be assigning values to button elements, as it's doesn't really make sense for them to have one (if I were to ask you "what is this button's value?" what would you think I meant?).

Instead, it makes more sense to pass a function to the button that accepts an argument.

For example:

const ParentComponent = ()=> {
  const [number, setNumber] = useState(0);
  const add = (amount)=> {
    setNumber(number + amount);
  };

  return (
    <MyInput number={number} onAddButtonClicked={add} />
  )
}

const MyInput = ({number, onAddButtonClicked}) => {

{number}

    <button onClick={ ()=> onAddButtonClicked(1) }>Add</button>
    <button onClick={ ()=> onAddButtonClicked(-1) }>Subtract</button>

}

```

Body:
So basically I am practicing React and trying to make simple components communicate with the parent component. I have come to an issue where I can't figure out how to change the value of a button into an integer so I can make simple calulations. I have tried setting the value with parseInt and without it as well, but I can't seen to understand, pressing the "add" button gives me a NaN. Could anyone help me?
This is what I have in my App.js

import './App.css';
import Input from "./Components/Input"

class App extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      number: 10
    }
  }

  number1 = (event) => {
    this.setState({number: event.target.value})

  }

  number2 = (event) => {
    this.setState({number: event.target.value})
    if (this.state.number < 1){
      this.setState({number: 0})
    }

  }

  add = (event) => {
    this.setState({number: this.number+1})

  }

  render() {
    return (

        <Input  number={this.state.number}
                number1={this.number1}
                number2={this.number2}
                add={this.add} />

    );
  }
}

export default App;

and this is what I have in Input.js

let numberValue1= parseInt("8")
let numberValue2= parseInt("17")

const Input = ({number, number1, number2, add}) =>{
    return(

{number}

            <button value={numberValue1} onClick={number1}>Add</button>
            <button value={numberValue2} onClick={number2}>Subtract</button>
            <button  onClick={add}>Subtract</button>

    );
}

export default Input;```

Body:
What you're trying to do is fundamentally a bit strange - you probably shouldn't be assigning values to button elements, as it's doesn't really make sense for them to have one (if I were to ask you "what is this button's value?" what would you think I meant?).

Instead, it makes more sense to pass a function to the button that accepts an argument.

For example:

const ParentComponent = ()=> {
  const [number, setNumber] = useState(0);
  const add = (amount)=> {
    setNumber(number + amount);
  };

  return (
    <MyInput number={number} onAddButtonClicked={add} />
  )
}

const MyInput = ({number, onAddButtonClicked}) => {
  <div>
    <h1>{number}</h1>
    <button onClick={ ()=> onAddButtonClicked(1) }>Add</button>
    <button onClick={ ()=> onAddButtonClicked(-1) }>Subtract</button>
  </div>
}


问:
Conditional row number Pandas
I need to add row number to my dataframe based on certain condition, below is the image input data frame.

I need a row number column in my dataframe as illustrated in below image(Rank column).

so when ever "RequestResubmitted" value is found within group I want reset rank to 1 again.

答:
Let us try cumsum create the cub key and groupby + cumcount

```<code>s=df.groupby([df['Word Order Code'],df['Status Code'].eq('Request Submitted').cumsum()]).cumcount()+1
df['rank']=s
</code>```

Title: Conditional row number Pandas

Body:
Let us try cumsum create the cub key and groupby + cumcount

s=df.groupby([df['Word Order Code'],df['Status Code'].eq('Request Submitted').cumsum()]).cumcount()+1
df['rank']=s


答:
Mark them as const:

```<code>bool contains(string word) const
//                        ^^^^^^
</code>```

Another positive thing: You can only call other const member functions! :)
Yet another good thing: You're allowed to call those functions on const objects of your class, example:

```<code>void foo(const Dictionary& dict){
  // 'dict' is constant, can't be changed, can only call 'const' member functions
  if(dict.contains("hi")){
    // ...
  }
  // this will make the compiler error out:
  dict.addWord("oops");
}
</code>```

Title: Is there a way in c++ to make sure that class member function isnt changing any of the class data members?

Body:
Mark them as const:

bool contains(string word) const
//                        ^^^^^^

Another positive thing: You can only call other const member functions! :)
Yet another good thing: You're allowed to call those functions on const objects of your class, example:

void foo(const Dictionary& dict){
  // 'dict' is constant, can't be changed, can only call 'const' member functions
  if(dict.contains("hi")){
    // ...
  }
  // this will make the compiler error out:
  dict.addWord("oops");
}


问:
React Native Action Button - Unable to Add buttons Dynamically
Unable to Add ActionButton Items dynamically.

I have the following setup --

```<code><ActionButton>
    <ActionButton.item name={constant_btn1} />
    <ActionButton.item name={constant_btn2} />
</ActionButton>
</code>```

I want to add dynamic buttons to this list. (The list is received from backend)

I have created a function that returns me views of these buttons.

```<code>getDynamicBtns() {
    return dynamicButtonsList.map(item, key) => {(
        return <ActionButton.item name={item.btnName} />;
    )};
}
</code>```

and I have used it in this way -->

```<code><ActionButton>
    <ActionButton.item name={constant_btn1} />
    <ActionButton.item name={constant_btn2} />
    {this.getDynamicBtns()}
</ActionButton>
</code>```

So this is rendering my constant buttons, but not the dynamic buttons.

EDIT -
I am returning the map from the getDynamicBtns() function and calling invoking the function call too from within render(). This is just some simplified sample code that I have wriiten.

EDIT2 -
To prevent any confusion, changing original question's code.

答:
I figured it out.
The problem was that the .map function returns an array of Objects.

So the final element that was going to be rendered was a React element ActionButton.

The ActionButton had only 3 children, irrespective of the size of my dynamic list.

```<code>ActionButton.children: [
    staticButton1,
    staticButton2,
    [dynamicButton1, dynamicButton2, dynamicButton3, ....]
];
</code>```

As a solution, I took them into separate lists and found a union of the lists.
And then rendered the list inside <ActionButton>

Something like this ->

```<code>let listA = [<ActionButton.Item name='staticBtn1.name' />];

let listB = this.getDynamicBtns();

let finalList = _.union(listA, listB);
</code>```

And then rendered it as -->

```<code><ActionButton>
    {finalList}
</ActionButton>
</code>```

Body:
Unable to Add ActionButton Items dynamically.

I have the following setup --

<ActionButton>
    <ActionButton.item name={constant_btn1} />
    <ActionButton.item name={constant_btn2} />
</ActionButton>

I want to add dynamic buttons to this list. (The list is received from backend)

I have created a function that returns me views of these buttons.

getDynamicBtns() {
    return dynamicButtonsList.map(item, key) => {(
        return <ActionButton.item name={item.btnName} />;
    )};
}

and I have used it in this way -->

<ActionButton>
    <ActionButton.item name={constant_btn1} />
    <ActionButton.item name={constant_btn2} />
    {this.getDynamicBtns()}
</ActionButton>

So this is rendering my constant buttons, but not the dynamic buttons.

EDIT -
I am returning the map from the getDynamicBtns() function and calling invoking the function call too from within render(). This is just some simplified sample code that I have wriiten.

EDIT2 -
To prevent any confusion, changing original question's code.

Body:
I figured it out.
The problem was that the .map function returns an array of Objects.

So the final element that was going to be rendered was a React element ActionButton.

The ActionButton had only 3 children, irrespective of the size of my dynamic list.

ActionButton.children: [
    staticButton1,
    staticButton2,
    [dynamicButton1, dynamicButton2, dynamicButton3, ....]
];

As a solution, I took them into separate lists and found a union of the lists.
And then rendered the list inside <ActionButton>

Something like this ->

let listA = [<ActionButton.Item name='staticBtn1.name' />];

let listB = this.getDynamicBtns();

let finalList = _.union(listA, listB);

And then rendered it as -->

<ActionButton>
    {finalList}
</ActionButton>


答:
Install package from nugget
Install-Package ObjectsComparer

And then imply compare :
var cmpr = new Comparer();
/* compare
isSame  is the booleab variable and will return true if both objects are same
  */
IEnumerable diff;

bool isSame = cmpr.Compare(obj1, obj2, out diff);

Title: Compare complex object and get difference C# .NET Core 3.1

Body:
I have two object of the class Profile and I want to compare it to get the difference. To explain better:

    public partial class Profile
    {
        public long Id { get; set; }
        public long VisitorId { get; set; }
        public string Description { get; set; }
        public long Age { get; set; }
        public DateTime? LastUpdate { get; set;}
    }

I want to know in my method the differences between the object oldProfile and newProfile to make a changelog.

For example, if oldProfile had Age = 10 and Description = "old" and newProfile has Age = 11 and Description = "new", I would now this differences to make two different insert in my database:

public void PostChangelogProfileDetail(Profile oldProfile, Profile newProfile)
{
    ProfileDetailChangeLog profileDetailChangeLog = new ProfileDetailChangeLog();

    //COMPARE oldProfile AND newProfile

    foreach ( //difference resulted in the compare)
    {
        profileDetailChangeLog.VisitorId = newProfile.VisitorId;
        profileDetailChangeLog.ModifiedRecord = //name of the attribute modified (Age, Description, etc...)

        _profileDetailChangeLog.Create(profileDetailChangeLog);
    }
}


问:
any real MVC library in PHP (for GUI apps)
I'm wondering if there are any abstraction frameworks for one of the PHP gui libraries. We have PHP-GTK, a PHP/Tk interface, and seemingly also PHP-QT. (Not tried any.)

I know that writing against the raw Gtk+ interface in Python is just bearable, and it therefore seems not very enticing for PHP. I assume it's the same for Qt, and Tk is pretty low-level too. So I'm looking for something that provides a nicer object structure atop any of the three. Primarily TreeViews are always a chore and php-gtk callbacks are weird in PHP, so I'd like a simplification for that. If it eases adding the GUI/View atop my business logic without much control code, that might already help.

And so since GUI apps are an area where MVC or MVP would actually make sense, I'd like to know if any library for that exists.

Still open for answers.

  (There will probably be a second bounty round. It's an uncommon topic, so needs more research.)

答:
Now there are a few options that work on newer versions of php. Some of these do not provide you with MVC out of the box, but you can use them to make GUI application in php.

There is the very easy to use php-gui. It does not require any special php extentions, you can just install it with composer like any other php library or framework you depend on. It is geared toward simple, standard user interfaces.

If you need to make something very custom and graphically advanced, and are willing to use an API that was designed to make games in C (or if you want to make a game in php), you could use OpenGL via SDL via FFI via ffi-sdl. It currently (as of 6/1/2020) requires php 7.4 or greater as it uses the recently added ffi feature of php. Even though this relies on the ffi extension, php-ffi is still easy to add to your project. It is still sort of extensionless (like php-gui) because there are no extensions tailor made just for this for it to work. Unlike some other extensions, there is not much chance ffi will not be maintained since it is a feature of php itself. Most people will just need to add ff-sdl to their project using composer, and possibly enable ffi in their php.ini.

I just learned you could also use PeachPie. It allows you to compile and run php code for/on .NET, so you would gain access to .NET GUI libraries, including MVC ones.

ContentLicense: CC BY-SA 2.5


问:
How to add a border to the last angular components (list-group-item) generated with *ngFor
I have a list of nested component generated in a *ngFor loop.
The hierarchy is :
*ngFor categories of products -> *ngFor list of products
The item components have a 1px border, which turns into 2px when there is two close to each other.
I removed the bottom border for all the elements, but i can't manage to getan additional bottom border for the last component. This is what i have so far :

Here is the loop who generate my categories :

    <app-product-category
      *ngFor="let groupOfProduct of productGroups | keyvalue"
      [category]="groupOfProduct.key"
      [products]="groupOfProduct.value">
    </app-product-category>

```

<p>And the loop who generate the items inside the app-product-category component :</p>

<pre class="lang-html prettyprint-override"><code><div class="collapse mb-2" id="collapseProducts{{category}}">
  <app-product-item
    *ngFor="let product of products; index as i; last as isLast"
    [product]="product"
    [index]="i"
    [ngClass]="{'last-child' : isLast}">
  </app-product-item>
</div>
</code>```

And the css:

.list-group-item {
  border-bottom: 0;
}

.last-child>.list-group-item{
  border-bottom: 1px solid black;
}
```

The last component  get the good class, but the border doesn't display. Any idea ?
Thanks a lot !

答:
Your current code isn't working because your css selector is wrong. it should just be .last-child .list-group-item for a class descendant style.

but, if you want, you can get rid of the last-child class and not worry about the ngFor variable, and just use the css :last-child pseudo selector:

```<code>.list-group-item:last-child {
  border-bottom: 1px solid black;
}
</code>```

which will just apply the styles to the last matching element in a given group of sibling elements.
 this is preferable for a number of reasons, most importantly though that if you reuse the list-group-item class in other lists, you won't have to replicate the ngFor template logic to apply the class everywhere you want this styling.

more on the selector: https://developer.mozilla.org/en-US/docs/Web/CSS/:last-child

Body:
I have a list of nested component generated in a *ngFor loop.
The hierarchy is :
*ngFor categories of products -> *ngFor list of products
The item components have a 1px border, which turns into 2px when there is two close to each other.
I removed the bottom border for all the elements, but i can't manage to getan additional bottom border for the last component. This is what i have so far :

Here is the loop who generate my categories :

    <app-product-category
      *ngFor="let groupOfProduct of productGroups | keyvalue"
      [category]="groupOfProduct.key"
      [products]="groupOfProduct.value">
    </app-product-category>

And the loop who generate the items inside the app-product-category component :

  <app-product-item
    *ngFor="let product of products; index as i; last as isLast"
    [product]="product"
    [index]="i"
    [ngClass]="{'last-child' : isLast}">
  </app-product-item>

And the css:

.list-group-item {
  border-bottom: 0;
}

.last-child>.list-group-item{
  border-bottom: 1px solid black;
}

The last component  get the good class, but the border doesn't display. Any idea ?
Thanks a lot !

Body:
Your current code isn't working because your css selector is wrong. it should just be .last-child .list-group-item for a class descendant style.

but, if you want, you can get rid of the last-child class and not worry about the ngFor variable, and just use the css :last-child pseudo selector:

.list-group-item:last-child {
  border-bottom: 1px solid black;
}

which will just apply the styles to the last matching element in a given group of sibling elements.
 this is preferable for a number of reasons, most importantly though that if you reuse the list-group-item class in other lists, you won't have to replicate the ngFor template logic to apply the class everywhere you want this styling.

more on the selector: https://developer.mozilla.org/en-US/docs/Web/CSS/:last-child


问:
Efficient way to count unique pairs in int array
This is my first post, hope it complies with posting guidelines of the site.
First of all a generic thanks to all the community: reading you from some months and learned a lot :o)

Premise: I'm a first years student of IT.

Here's the question: I'm looking for an efficient way to count the number of unique pairs (numbers that appear exactly twice) in a given positive int array (that's all I know), e.g. if:

```<code>int[] arr = {1,4,7,1,5,7,4,1,5};
</code>```

the number of unique pairs in arr is 3 (4,5,7).

I have some difficulties in... evaluating the efficiency of my proposals let's say.

Here's the first code I did:

```<code>int numCouples( int[] v ) {
int res = 0;
int count = 0;
for (int i = 0 ; i < v.length; i++){
    count = 0;
    for (int j = 0; j < v.length; j++){
        if (i != j && v[i] == v[j]){
            count++;
        }
    }
    if (count == 1){
        res++;
    }
}
return res/2;
}
</code>```

This shoudn't be good cause it checks the whole given array as many times as the number of elements in the given array... correct me if I'm wrong.

This is my second code:

```<code>int numCouples( int[] v) {
int n = 0;
int res = 0;
for (int i = 0; i < v.length; i++){
    if (v[i] > n){
        n = v[i];
    }
}
int[] a = new int [n];
for (int i = 0; i < v.length; i++){
    a[v[i]-1]++;
}
for (int i = 0; i < a.length; i++){
    if (a[i] == 2){
        res++;
    }
}
return res;
}
</code>```

I guess this should be better than the first one since it checks only 2 times the given array and 1 time the n array, when n is the max value of the given array. May be not so good if n is quite big I guess...

Well, 2 questions:

am I understanding good how to "measure" the efficiency of the code?

there's a better way to count the number of unique pairs in a given array?

EDIT:
Damn I've just posted and I'm already swamped by answers! Thanks! I'll study each one with care, for the time being I say I don't get those involving HashMap: out of my knowledge yet (hence thanks again for the insight:o) )

答:
```<code>var sampleArray = ['A','B','C','D','e','f','g'];
 var count = 0;
 for(var i=0; i<=sampleArray.length; i++) {
    for(var j=i+1; j<sampleArray.length; j++) {
        count++;
        console.log(sampleArray[i] , sampleArray[j]);
    }
 }
 console.log(count);
</code>```

This is the simple way I tried.

Body:
This is my first post, hope it complies with posting guidelines of the site.
First of all a generic thanks to all the community: reading you from some months and learned a lot :o)

Premise: I'm a first years student of IT.

Here's the question: I'm looking for an efficient way to count the number of unique pairs (numbers that appear exactly twice) in a given positive int array (that's all I know), e.g. if:

int[] arr = {1,4,7,1,5,7,4,1,5};

the number of unique pairs in arr is 3 (4,5,7).

I have some difficulties in... evaluating the efficiency of my proposals let's say.

Here's the first code I did:

int numCouples( int[] v ) {
int res = 0;
int count = 0;
for (int i = 0 ; i < v.length; i++){
    count = 0;
    for (int j = 0; j < v.length; j++){
        if (i != j && v[i] == v[j]){
            count++;
        }
    }
    if (count == 1){
        res++;
    }
}
return res/2;
}

This shoudn't be good cause it checks the whole given array as many times as the number of elements in the given array... correct me if I'm wrong.

This is my second code:

int numCouples( int[] v) {
int n = 0;
int res = 0;
for (int i = 0; i < v.length; i++){
    if (v[i] > n){
        n = v[i];
    }
}
int[] a = new int [n];
for (int i = 0; i < v.length; i++){
    a[v[i]-1]++;
}
for (int i = 0; i < a.length; i++){
    if (a[i] == 2){
        res++;
    }
}
return res;
}

I guess this should be better than the first one since it checks only 2 times the given array and 1 time the n array, when n is the max value of the given array. May be not so good if n is quite big I guess...

Well, 2 questions:

am I understanding good how to "measure" the efficiency of the code?

there's a better way to count the number of unique pairs in a given array?

EDIT:
Damn I've just posted and I'm already swamped by answers! Thanks! I'll study each one with care, for the time being I say I don't get those involving HashMap: out of my knowledge yet (hence thanks again for the insight:o) )

Body:
var sampleArray = ['A','B','C','D','e','f','g'];
 var count = 0;
 for(var i=0; i<=sampleArray.length; i++) {
    for(var j=i+1; j<sampleArray.length; j++) {
        count++;
        console.log(sampleArray[i] , sampleArray[j]);
    }
 }
 console.log(count);

This is the simple way I tried.


答:
Make the member function const:</p>

```<code>bool contains(string word) const
{
//...
}
</code>```

Body:
Lets say that I have a

class Dictionary
{
vector<string> words;
void addWord(string word)//adds to words
{
/...
}
bool contains(string word)//only reads from words
{
//...
}
}

Is there a way to make compiler check that contains isnt changing words vector. Ofc this is just an example with one class data member, I would like it to work with any number of data members.
P.S. I know i have no public: and private:, I left it out intentionally to make code shorter and problem clearer.

Body:
Make the member function const:

bool contains(string word) const
{
//...
}


问:
Possible ways to avoid BAD WRITES in MySql
Suppose we have one Transaction -

Transaction T1

```<code>S1=>   id1 = select id, colA, colB, colC from table A where colA = 'A1';

S2=>   update table A set colB = 'B1' where id = 'id1'
</code>```

Above, I want to change colB to B1, only if colA value is A1

Transaction T2

```<code> S3=>  update  table A set colA = 'A2' where colA = 'A1';
</code>```

Above Transaction sets colA value to A2

So, in the above scenario, if  S1 from T1 happens, and then S3 from T2 happens, then S2 from T1, then it will be wrong, as after execution of S3, value of colA is A2, so i don't want  S2 to be a success.

How can I avoid this?

Possible solutions -

Use Optimistic / Pessimistic locking : I will go for this, only if no other option works

Use SELECT for UPDATE: Like update table A set colB = 'B1' where id = 'id1' and colA = 'A1'

Use Transaction Isolation level SERIALIZABLE

Can I achieve what I want using 3? Which one will be better out of these 2?

答:
I want to change colB to B1, only if colA value is A1

Then make that part of the WHERE clause

```<code>update table A
    set colB = 'B1'
where id = 'id1'
AND colA = 'A1'
</code>```

Body:
Suppose we have one Transaction -

Transaction T1

S1=>   id1 = select id, colA, colB, colC from table A where colA = 'A1';

S2=>   update table A set colB = 'B1' where id = 'id1'

Above, I want to change colB to B1, only if colA value is A1

Transaction T2

 S3=>  update  table A set colA = 'A2' where colA = 'A1';

Above Transaction sets colA value to A2

So, in the above scenario, if  S1 from T1 happens, and then S3 from T2 happens, then S2 from T1, then it will be wrong, as after execution of S3, value of colA is A2, so i don't want  S2 to be a success.

How can I avoid this?

Possible solutions -

Use Optimistic / Pessimistic locking : I will go for this, only if no other option works

Use SELECT for UPDATE: Like update table A set colB = 'B1' where id = 'id1' and colA = 'A1'

Use Transaction Isolation level SERIALIZABLE

Can I achieve what I want using 3? Which one will be better out of these 2?

Body:
I want to change colB to B1, only if colA value is A1

Then make that part of the WHERE clause

update table A
    set colB = 'B1'
where id = 'id1'
AND colA = 'A1'