Compare rows in two sheets

Question: I have 6 sheets in an Excel document.

I would like to compare two sheets.
Sheet 1 (Artikelstammdaten) has 8555 Lines

Sheet 2 (Warengruppen) has 232 Lines

My Code:
 Sub WorksheetLoop()

 Dim Current As Range
 Dim Element As Range
 Dim wgRow As Integer
 Dim wbRow As Integer
 Dim Warengruppe As String
 Dim Warengruppebezeichnung As String

 Dim Stamm1 As String
 Dim Stamm2 As String
 Dim Stamm3 As String
 Dim Summe As String

 wgRow = 2
 wbRow = 2

 For Each Element In Sheets("Artikelstammdaten").Range("R:R")

    Warengruppebezeichnung = Sheets("Warengruppen").Cells(wbRow, 1).Value
    Warengruppe = Sheets("Artikelstammdaten").Cells(wgRow, 18).Value

    If Warengruppe = Warengruppebezeichnung Then
        Stamm1 = Sheets("Warengruppen").Cells(wbRow, 2).Value
        Stamm2 = Sheets("Warengruppen").Cells(wbRow, 3).Value
        Stamm3 = Sheets("Warengruppen").Cells(wbRow, 4).Value
        Summe = Stamm1 + ">" + Stamm2 + ">" + Stamm3

       Sheets("Artikelstammdaten").Cells(wgRow, 18).Value = Summe

       wbRow = 2
       wgRow = wgRow + 1
    Else
        wbRow = wbRow + 1

    End If
    Next

 End Sub

It works but breaks off at line 1755.
Comment: Do you realize that you are likely processing several million blank cells?
Comment: What do you mean by **Breaks off**? Does it give you any error codes? Or is it no response?
Comment: When it "breaks off", do you get any error?
Comment: You are iterating through every cell in column "R", and assigning that cell to the variable `Element`. You never ever ever use that though... your iterations are 100% pointless. You might as well just do `For i = 1 to 1000000` and loop in that. I think you need to take a step back from this code and rethink it.
Comment: I disagree with _100% pointless_, OP uses `wgRow` for scanning through `Column R`. And I'm sure that this is the reason OP got only 1755 iterations. When `wbRow` is not matched, it cost 1 loop for searching next `wbRow`.
Comment: So I would say it is 80% pointless. :)
Comment: There is no error message - he just stops at line 1755. Everything is right up to the line what he does.
Comment: The reason it stops is because it gets to a point where there is no match found `Artikelstammdaten` for whatever `wbrow` it's on. It can never increment to the next `wgrow` since the incrementing of that row in `Artikelstammdaten` is held in the `IF` condition that there must be a match, and so it just iterated nearly a million times and then stops. Again... I really think you need to take a step back from this, explain what you are trying to accomplish here (share some sample data and desired results if you want us to help further) and rewrite. There is a lot of things not making sense here
Comment: Also that For loop is 100% pointless in that it could be replaced with `For 1 = 1 to 1000000` and the exact same logic would take place. At least writing it that way acknowledges that there is no good reason we are iterating through column R as part of this loop.
Answer: The reason you got only 1755 iterations is that you waste many loops to find the matching value in Sheets("Warengruppen"). Use a wiser way, Range.Find(What:=key) method returns a range object with the same key. Note it will return Nothing if nothing is matched, so we need to check if it is found or not for preventing an error.
Sub WorksheetLoop()
    'current is crying because you never call her :/
    Dim Current As Range
    Dim Element As Range
    Dim wbFound As Range

    Dim Stamm1 As String
    Dim Stamm2 As String
    Dim Stamm3 As String
    Dim Summe As String

    For Each Element In Sheets("Artikelstammdaten").Range("R:R")

        Set wbFound = Sheets("Warengruppen").Range("A:A").Find(What:=Element.Value)

        If wbFound Is Nothing Then
            Debug.Print "Not Found with Row# " & Element.Row
        Else
            Stamm1 = wbFound.Offset(0, 1)
            Stamm2 = wbFound.Offset(0, 2)
            Stamm3 = wbFound.Offset(0, 3)
            Summe = Stamm1 + ">" + Stamm2 + ">" + Stamm3

            Element.Value = Summe
        End If
    Next Element
End Sub

Comment: Thanks a lot, it works now for the whole lines.
However, he now also makes up to line 65535 always a ">>>" although in the lines nothing is in it.
Comment: You can set the range such as `Range("R2:R9000")` in stead of `Range("R:R")`. Further more, a `Range("R1:R" & UsedRagne.Rows`) or `Range("R1", Range("R" & Rows.Count).End(xlUp))` or anything can determine the last cell of column R will help.

Compare rows in two sheets


Test for Subgroup Difference Compared to Test for Moderator

Question: I have performed a proportional meta-analysis to evaluate the rate of procedural success for two medical procedures. The two procedures comprise the two subgroups in my meta-analysis (FNA and FNB). I am trying to understand whether or not there is a statistically significant difference between the rate of success between my subgroups.
This is the output from the meta-analysis using a REML random effects model, followed by meta-regression. The test for subgroup difference appears to show a statiistically significant difference between the subgroups (based on the common-effects difference for subgroups test), while the test for moderator shows no statistical significance.
Meta-Analysis:

Meta-Regression:

Any insight on how to reconcile these varying outcomes would be much appreciated. I have very minimal statistics background, so please let me know if there is anything I can clarify. Thanks.
Answer: The common effects model is a fixed effects model, which gives incorrect estimates and standard errors in the presence of heterogeneity (and you have lots of heterogeneity).
If you run your meta-regression as a fixed effects model, I imagine you'll get the same (incorrect) significant result.
Incidentally, please give us the code that you ran to get this result, and don't paste your code or as an image - it means I can't copy and paste parts of the code or output.
Comment: There is absolutely nothing wrong with using one of the fixed effects models in the presence of heterogeneity. See https://research-information.bris.ac.uk/ws/portalfiles/portal/146974606/FixedEffectsPaperRev3.pdf for details of the three models which underlie meta-analysis.
Comment: Thanks for the quick response. I suspected that this was the case. I want to develop some insight into why significant heterogeneity produces these false positives when using fixed-effects models. Do you have any suggestions for reading on this topic?

And this is the code I used...

metaprop.EUSTA=metaprop(Adequate,Total,Author,data=NGS_by_Type,sm="PFT",method.tau="REML",subgroup=Type,pscale=1); metaprop.EUSTAreg <- metareg(metaprop.EUSTA,~Type)


Perl: how to split string without storing into array and continue split?

Question: I guess this has been asked before, but I can't find it.
Say
my $string = "something_like:this-and/that";
my @w1 = split(/_/, $string);
my @w2 = split(/-/, $w1[1]);
my @w3 = split(/:/, $w2[0]);
print $w3[1]; #print out "this"

Is there anyway to avoid the temporary array variables @w1, @w2 and @w3 and get $w3[1] directly? I remember continue split works, but forget the syntax.
Thanks.
Answer: Yes, it's possible, but would be much harder to read, so isn't advised:
my $string = "something_like:this-and/that";
my $this = (split /:/, (split /-/, (split(/_/, $string))[1])[0])[1];
print $this; #print out "this"

Alternatively, you could use a regex in this instance, but don't think it adds anything:
my $string = "something_like:this-and/that";
my ($this) = $string =~ /.*?_.*?:([^-]*)/ or warn "not found";
print $this;

Comment: Got it. I missed a pair of (). Thanks.
Answer: Your own solution unnecessarily splits on underscores, unless your real data is significantly different from your example. You could write this
use strict;
use warnings;

my $string = "something_like:this-and/that";
my $value = (split /-/, (split /:/, $string)[1])[0];
print $value;

Or this solution uses regular expressions and does what you ask
use strict;
use warnings;

my $string = "something_like:this-and/that";
my ($value) = $string =~ /:([^_-]*)/;
print $value;

output
this

Comment: Given the OP's string is obviously fake data, I believe both your solutions assume too much.  Technically `$value = (split /[-:]/, $string)[1];` would also work for that exact data, but I'd not advise it.
Answer: This will modify $string in place:
my $string = "something_like:this-and/that";
$string =~ s/^.*:(.+)-.*/$1/;

Comment: That leaves `$string` set to `_like:this-and/that`


ldapsearch works for ldaps but getent passwd 'user' returns nothing on Centos 7 minimum openldap server

Question: I have installed openldap  on centos 7 minimum and added a user newuser01 to the database successfuly. ldapsearch works fine with both the master and the client using this format:
ldapsearch -H ldaps://provider.example.com -x -D "cn=Manager,dc=example,dc=com" -W
But getent passwd -s sss newuser01 or getent passwd newuer01 returns nothing on both client and master.
Here are the files that I looked at, I am not sure if they are correctly configured and if there are others I should look at, thank you so much for your efforts:

/etc/nsswitch.conf /etc/openldap/ldap.conf
/etc/sssd/sssd.conf
/etc/openldap/slapd.conf   # It is deprecated for centos 7
/etc/pam.d/system-auth

On Master:
/etc/nsswitch.conf contains:
passwd:     files sss
shadow:     files sss
group:      files sss
hosts:      files dns
bootparams: nisplus [NOTFOUND=return] files
ethers:     files
netmasks:   files
networks:   files
protocols:  files
rpc:        files
services:   files sss
netgroup:   files sss
publickey:  nisplus
automount:  files
aliases:    files nisplus

/etc/openldap/ldap.conf contains:
BASE            dc=example,dc=com
URI             ldaps://provider.example.com
TLS_CACERTDIR   /etc/openldap/certs
TLS_REQCERT     demand
SASL_NOCANON    on

/etc/sssd/sssd.conf  is empty on the server
/etc/pam.d/system-auth contains:
auth        required      pam_env.so
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 1000 quiet_success
auth        required      pam_deny.so
account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 1000 quiet
account     required      pam_permit.so
password    requisite     pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=
password    sufficient    pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password    required      pam_deny.so
session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
-session     optional      pam_systemd.so
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so

On the client:
/etc/nsswitch.conf  contains exactly as the server
/etc/openldap/ldap.conf  contains:
TLS_CACERTDIR /etc/openldap/cacerts
# Turning this off breaks GSSAPI used with krb5 when rdns = false
SASL_NOCANON    on
URI ldaps://provider.example.com:636
BASE dc=example,dc=com

/etc/sssd/sssd.conf contains:
[domain/default]
autofs_provider = ldap
cache_credentials = False
ldap_search_base = dc=example,dc=com
krb5_server = #
id_provider = ldap
auth_provider = ldap
chpass_provider = ldap
ldap_uri = ldaps://provider.example.com:636
ldap_id_use_start_tls = False
ldap_tls_cacertdir = /etc/openldap/cacerts
[sssd]
services = nss, pam, autofs
config_file_version = 2
domains = default
[nss]
homedir_substring = /home
[pam]
[sudo]
[autofs]
[ssh]
[pac]
[ifp]

/etc/pam.d/system-auth  seems to contain what the server does with this extra entry:
session     optional      pam_sss.so

Comment: Are you authenticating with a kerberos system or just local?
Comment: I have made self certificates, but do not know anything about Kerberos system.
Comment: I neglected to mention that I am running all these on Virtual box and both client and server are VM machines.
Comment: This authconfig I run on the client but no the server
Comment: authconfig \
--disablesmartcard \
--disablefingerprint \
--enablesssd \
--enablesssdauth \
--enablelocauthorize \
--disablemd5 \
--passalgo=sha512 \
--enablepamaccess \
--enableldap \
--enableldapauth \
--disableldaptls \
--ldapserver=ldaps://ldap.yourdomain.tld:636 \
--ldapbasedn=dc=domain,dc=tld \
--enablemkhomedir \
--disablecachecreds \
--disablekrb5 \
--disablekrb5kdcdns \
--disablekrb5realmdns \
--krb5kdc=" #" \
--updateall
Comment: Is there a reason you are using sss as a nss module instead of nss_ldap?
I am not sure if `sss` is actually a valid nss module or not.
Comment: sssd and nslcd are two ways to this on openldap. I am following a set of documentation for this
Comment: `sss` is a valid module.
Answer: this works for me using sssd-ldap against a freeipa ldap server (not using the built-in idm provider but the sssd-ldap provider as asked).

install sssd-ldap and authoconfig
run authconfig --enablesssd --enablesssdauth --enablelocauthorize --update
create the configuration file /etc/sssd/sssd.conf with your appropriate information:

[domain/default]

autofs_provider = ldap
ldap_schema = rfc2307bis
id_provider = ldap
auth_provider = ldap
chpass_provider = ldap
ldap_uri = ldap://your.ldap.host
ldap_id_use_start_tls = True
cache_credentials = True
ldap_tls_cacertdir = /etc/pki/tls/certs
ldap_tls_cacert = /etc/pki/tls/certs/ca-bundle.crt
ldap_default_bind_dn = uid=user1,cn=users,cn=accounts,dc=your,dc=domain,dc=tld
ldap_default_authtok_type = password
ldap_default_authtok = secretpassword
ldap_user_search_base = cn=users,cn=accounts,dc=your,dc=domain,dc=tld
ldap_group_search_base = cn=groups,cn=accounts,dc=your,dc=domain,dc=tld

[sssd]
services = nss, pam, autofs
config_file_version = 2

domains = default
[nss]
homedir_substring = /home

[pam]

[sudo]

[autofs]

[ssh]

[pac]

[ifp]

restart the sssd service: systemctl restart sssd
verify that sss is enabled in nsswitch.conf for passwd, groups and shadow. Do not use ldap in nsswitch.conf, it should be "files sss", not "files ldap"

If you do not need binding to get the list of users remove the ldap_default_bind_dn, ldap_default_authtok_type and ldap_default_authtok directives. If you do not require tls, remove those but you are authenticating users, so it should be enabled. Modify the paths to the cacertdir and cacert directives to match your situation, as the user and group search base.
In this blog: http://www.couyon.net/blog/enabling-ldap-usergroup-support-and-authentication-in-centos-6 you will find a similar howto. The official Red Hat documantation is here: https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System-Level_Authentication_Guide/Configuring_Domains.html#Configuring_Domains-Configuring_a_Native_LDAP_Domain
As always, the proof is in the pudding:
[root@localhost sssd]# grep user1 /etc/passwd
[root@localhost sssd]# getent passwd user1
user1:*:1076200004:1076200004:ipa user:/home/user1:/bin/sh

Comment: Thanks very much, I will have to do a clean server and client as my changes have messed things up. But I have a couple of questions: all these changes to be done on the client I take it, but what changes need to be done on the provider to activate getent passwd? I also have "--disableldaptls" is this correct or should this be --enableldaptls? Is the password your actual password or the encrypted one? Thanks again
Comment: all those settings are in the client. Please take a look a the man pages of man sssd-ldap to see what the options mean
Comment: inside my sssd.conf I have:
Comment: ldap_tls_cacertdir = /etc/openldap/cacerts while you have: ldap_tls_cacertdir = /etc/pki/tls/certs. I have the file ca.crt and ofcourse there is there is the file ca-bundle.crt not sure which to use?
Comment: It is not working. Is there a way I could paste my sssd.conf file the comment field does not allow it. ldapsearch ldaps:/// works fine. I made it as you suggested and only used authconfig and only touched sssd.conf manually
Comment: you should know which one you need. Where do you have the CA file for the CA that signed that certificate?
Comment: modify your question and improve the formatting, it's quite unreadable ;-)
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/41557/discussion-between-kevbuntu-and-natxo-asenjo).
Comment: @naxto One problem I am having with these documentations is that there is complete change from centos 6 to centos 7. For example slapd.conf is now deprecated and these notes talk about changes to slapd.conf, simply not sure.
Comment: I found this link very useful to debug this same issue in deep. [link](https://jhrozek.wordpress.com/2015/03/11/anatomy-of-sssd-user-lookup/)


Linux service account management

Question: We use Windows Active Directory for account management. As a security policy, we need to change password for service accounts at least every six months. What we are experiencing is, when we change the password on AD, the application breaks before we get to change the password on servers where the account is being used. I was wondering if any of you experienced this issue. How did you resolve this issue? Thanks
Comment: This could use some clarification... for example, what does Linux have to do with it?  Also, what's the problem here?  You update your AD passwords at the same time as you update the local servers/services.
Answer: Use correctly configured cache daemon on Linux server side.
SSSD works quite good with Active Directory.
Here is the link to RHEL Guide:
RHEL6 AD INTEGRATION AND SSSD GUIDE

Linux service account management


SwiftUI update data for parent NavigationView

Question: how can I update data in TextField that lives in the detail of a NavigationView? I want the data to be updated in the List of the parent View. Here is my code:
class Address: ObservableObject, Identifiable {
    let id = UUID()
    @Published var name: String
    @Published var age: String

    init(name: String, age: String) {
        self.name = name
        self.age = age
    }
}
class AddressBook: ObservableObject {
    @Published var addresses: [Address]

    init(addresses: [Address]) {
        self.addresses = addresses
    }
}
struct TestData {
    static let addressbook = AddressBook(addresses: [
        Address(name: "Person1", age: "39"),
        Address(name: "Person2", age: "22")
    ])
}
struct ContentView: View {
    @ObservedObject var addressbook = TestData.addressbook

    var body: some View {
        NavigationView {
            List (addressbook.addresses) {address in
                NavigationLink(destination: AddressDetail(address: address)) {
                    Text(address.name)
                }
            }
            .navigationBarTitle("Addressbook")
        }

    }
}

struct AddressDetail: View {
    @ObservedObject var address: Address

    var body: some View {
        Form {
            TextField("name", text: $address.name)

            TextField("age", text: $address.age)
        }

    }
}

This code doesn't work: If I go to the AddressDetail-View, change the TextField values and then go back, the changes don't update in the List-View.
Nico
Answer: The problem is that Address is a class, so if its published properties changed the reference in addresses is not changed, but ContentView view observes addressbook as a container of addresses.
Here is demo of possible approach (tested & works with Xcode 12b / iOS 14, also on 11.4 / iOS 13.4)
List (addressbook.addresses) {address in
    NavigationLink(destination: AddressDetail(address: address)) {
        Text(address.name)
            .onReceive(address.objectWillChange) { _ in
                self.addressbook.objectWillChange.send()
            }
    }
}

Alternate: based on Binding (requires much more changes, so, as for me, less preferable, but worth mention
struct Address: Identifiable, Hashable {
    let id = UUID()
    var name: String
    var age: String

    init(name: String, age: String) {
        self.name = name
        self.age = age
    }
}
class AddressBook: ObservableObject {
    @Published var addresses: [Address]

    init(addresses: [Address]) {
        self.addresses = addresses
    }
}
struct TestData {
    static let addressbook = AddressBook(addresses: [
        Address(name: "Person1", age: "39"),
        Address(name: "Person2", age: "22")
    ])
}

struct ContentView: View {
    @ObservedObject var addressbook = TestData.addressbook

    var body: some View {
        NavigationView {
            List (Array(addressbook.addresses.enumerated()), id: \.element) { i, address in
                NavigationLink(destination: AddressDetail(address: self.$addressbook.addresses[i])) {
                    Text(address.name)
                }
            }
            .navigationBarTitle("Addressbook")
        }

    }
}

struct AddressDetail: View {
    @Binding var address: Address

    @State private var name: String
    @State private var age: String

    init(address: Binding<Address>) {
        _address = address
        _name = State(initialValue: _address.wrappedValue.name)
        _age = State(initialValue: _address.wrappedValue.age)
    }
    var body: some View {
        Form {
            TextField("name", text: $name)

            TextField("age", text: $age)
        }
        .onDisappear {
            self.address.name = self.name
            self.address.age = self.age
        }
    }
}

Comment: Thank you, it works! But isn't there another solution for this problem? It seems to me, that an editing form behind a list in a navigation view is used very often. I'd like to pass the address-parameter as something like $address, but this doesn't seem to work inside a closure. How would you solve this with @environmentObject?
Comment: @Nico, `@EnvironmentObject` behaves the same as `@ObservedObject`, so original problem remains as described in first paragraph. Alternate is to use `@Binding` - see updated for usage.


How to correctly setup an Apache VirtualHost as HTTP and HTTPS?

Question: I am trying to setup a locally (for development/testing purposes) SSL site using Apache and mod_ssl and this is what I have in my VirtualHost files:
/etc/httpd/conf.d/local.conf
<VirtualHost *:80>
    ServerName reptool.dev

    DocumentRoot /var/www/html/magnific/reptooln_admin/web
    <Directory /var/www/html/magnific/reptooln_admin/web>
        # enable the .htaccess rewrites
        AllowOverride All
        Order allow,deny
        Allow from All
    </Directory>

    ErrorLog /var/log/httpd/reptool-error.log
    CustomLog /var/log/httpd/reptool-access.log combined
</VirtualHost>

/etc/httpd/conf.d/local-ssl.conf
<VirtualHost reptool.dev:443>
    ServerName reptool.dev:443

    DocumentRoot /var/www/html/magnific/reptooln_admin/web
    <Directory /var/www/html/magnific/reptooln_admin/web>
        # enable the .htaccess rewrites
        AllowOverride All
        Order allow,deny
        Allow from All
    </Directory>

    ErrorLog /var/log/httpd/reptool-error.log
    CustomLog /var/log/httpd/reptool-access.log combined

    SSLEngine on
    SSLCertificateFile /etc/pki/tls/certs/ca.crt
    SSLCertificateKeyFile /etc/pki/tls/private/ca.key
</VirtualHost>

The first (the non-SSL) works just fine but with the SSL one I got not error 404:
The requested URL /app_dev.php was not found on this server.

Why? What I am missing at configuration level?
Answer: Your ServerName "reptool.dev:443" doesn't look right to me, it should not have the port in it.  Try:
ServerName reptool.dev

Comment: Didn't work, still the same issue: 404 Not found
Comment: Try making a different log to see if requests are being picked-up by the HTTPS server:
CustomLog /var/log/httpd/reptool-access-https.log combined
Are you confident your ServerName matches your incoming requests?
Comment: Request are not beeing made to that URL I mean I can't see anything in logs, why?
Comment: Did you include your Listen and NameVirtualHost directives for port 443?
Listen 192.168.0.1:443
NameVirtualHost 192.168.0.1:443
Comment: I have in this way: `NameVirtualHost *:80 NameVirtualHost *:443` but that cause this error `Starting httpd: (98)Address already in use: make_sock: could not bind to address [::]:443` during HTTPD restart


Imprimir elemento de array associativo dentro de string sem concatenação

Question: Tenho de imprimir uma tag HTML através de um echo com o valor de um array associativo, porem não consigo fazer com que imprima ser o uso de concatenação.
Código .php (desta forma nao esta funcionando, creio que pelas aspas que envolve 'nome')
echo '{$video['nome']}'

Comment: @QMechanic73, isto funciona porem ao fazer: echo '{$video['nome']}' não é captado o valor do array na posição nome, é retornado um erro
Answer: Interpolação de string só funciona quando você usa aspas duplas. Mas tem o inconveniente de ter que usar aspas simples em outros lugares. Você também pode usar NowDoc. Veja os exemplos abaixo:
$video = array('nome' => 'teste');
echo "{$video['nome']}";
echo <<<FIM
{$video['nome']}
FIM;
echo '' . $video['nome'] . '';

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Documentação.
Eu já havia falando alguma coisa sobre isso nessa resposta.
Mas pensando bem, existe algum motivo para não fazer a concatenação? Acho que deveria rever esse requisito.
Comment: ,@bigown, desta forma teria alterar todas as aspas duplas presentes dentro do html como esta class='video' que você alterou de aspas duplas para simples
Comment: Exato. Estou vendo se há alguma outra solução.
Comment: ,@bigown, irei utilizar concatenação visto que é uma solução melhor que trocar todas as aspas simples por duplas. assim sendo a forma mais simples é: echo '.$video['nome'].'
Comment: @RicardoHenrique achei uma outra solução. Não sei se é vantagem para você mas agora você tem três opções.
Comment: ,@bigown, já havia verificado esta forma de se criar strings (com funcionamento semelhante as tags ) mas não havia pensando é utiliza-las para este já que raramente as vi sendo utilizadas
Answer: Segundo a documentação isso não é possível.

Para especificar uma única citação literal, escapar-lo com uma barra
  invertida (). Para especificar uma barra invertida, duas vezes (\).
  Todas as outras instâncias de barra invertida será tratado como uma
  barra invertida literal: isto significa que as outras seqüências de
  escape que você pode ser usado para, como o \ r ou \ n, será emitido
  literalmente, conforme especificado em vez de ter qualquer significado
  especial.
Nota: Ao contrário da sintaxe para aspas duplas e heredoc, variáveis e
  sequências de escape para caracteres especiais não serão substituídas
  quando elas ocorrerem dentro de strings entre aspas.

O que você pode fazer é usar concatenação mesmo.
$video['chave'] = "valor";
echo '{' .$video['chave'] .'}';


Normalizing Flows KL divergence equivalency

Question: This question is related to the normalizing flows concept in machine learning.
Let $X \sim P_X$ and $U \sim P_U$ be, respectively, the distribution of the data and a base distribution (e.g. an isotropic gaussian). We define a normalizing flow as $F: \mathcal{U} \rightarrow \mathcal{X}$ parametrized by $\theta$. Starting with $P_U$ and then applying $F$ will induce a new distribution $P_{F(U)}$ (used to match $P_X$). Since normalizing flows are invertible, we can also consider the distribution $P_{F^{-1}(X)}$.
How comes that in this case $D_{KL}[P_X || P_{F(U)}] = D_{KL}[P_{F^{-1}(X)} || P_U]$ ? $D_{KL}$ being the Kullback–Leibler divergence.
Let's say there are 2 scenarios:

you don't have samples from $p_X(x)$, but you can evaluate $p_X(x)$,

you have samples from $p_X(x)$, but you cannot evaluate $p_X(x)$.

Which divergence should be used in each scenario as the objective to optimize?
Answer: The answer to your first question follows from the fact that the Kullback-Leibler divergence is, under mild conditions, invariant under transformations. This is straightforward and is shown in the section "Properties" of the Wikipedia site that you have referred to.
The answer to your second question can be found in

Papamakarios, George, et al. "Normalizing flows for probabilistic modeling and inference." Journal of Machine Learning Research 22.57 (2021): 1-64.

in sections 2.3.1 and 2.3.2.
What it says is basically this: If you can sample from $P_X$, you should minimize the KL-divergence:
$$
D_{KL}[P_X \| P_{F(U)}] = -\mathbb{E}_{P_X}[\log P_{F(U)}] - H_{P_X},
$$
where $H_{P_X}$ is the entropy of $P_X$. For the optimization task of finding the parameters of $F$ and $P_U$, the entropy is irrelevant, since it is constant. You can approximate the expectation $\mathbb{E}_{P_X}[P_{F(U)}]$ if you have samples of $P_X$, so this is appropriate for your second scenario.
For your first scenario, you should switch the arguments of the KL-divergence, i.e. you should minimize:
$$
D_{KL}[P_{F(U)} \| P_X] = \mathbb{E}_{P_U}[\log P_U] - \mathbb{E}_{P_U}[\log P_{F^{-1}(X)}]
$$
and since $P_U$ is considered to be easy to use, your only problem is to evaluate $P_{F^{-1}(X)}$, but that is considered doable in your first scenario.
Answer: In short
The Kullback-Leibler divergence is the expectation value of the log-odds of two distributions
$$D_{KL}(A || B) = \textbf{E}_A\left[\log \left(\frac{P_A(x)}{P_B(x)} \right) \right]$$
or for continuous distributions
$$D_{KL}(A || B) = \textbf{E}_A\left[\log \left(\frac{f_A(x)}{f_B(x)} \right) \right]$$
When you transform both $A$ and $B$ in the same way with a one-to-one function, then the events in both transformed and non-transformed representations are exchangeable while the log-odds for specific events remain the same, and that is why the divergence remains the same.

Intuitive graphical view
The transformations used with normalizing flows are invertible and that requires that they are one-to-one functions. This means that volume under the curve of transformed elements remains fixed.
For example in the graph below the transformation is the quantile function of the standard normal which transforms the space $[0,1]$ to the line $\mathbb{R}$. The events $0.18<x<0.22$ and $0.45<x<0.49$ transform to respectively $-0.915<u<-0.772$ and $-0.126<u<-0.025$.
What you see is that the area under the curves relating to these events change width and height, but the total area remains the same.
In addition the relative ratio of the height two curves remains the same! The transformation changes the height of the distributions in the same way. The log-odds of events don't change.

The computation of the divergence will be an integral expressing a weighted sum/average of the log-odds $\log \left(\frac{f_A(x)}{f_B(x)}\right)$. For each contribution/weight of probability $f_A(x) dx$ you have an equivalent size weight $g_A(u) du$ with the same log-odds.
$$ \begin{array}{}
\int_{x \in \mathcal{X}} \log \left(\frac{f_A(x)}{f_B(x)}\right) f_A(x) dx &=& \int_{x \in \mathcal{X}} \text{LO}_X(x)  f_A(x) dx \\
&=&   \int_{u \in \mathcal{U}} \text{LO}_U(u)  f_A(x(u)) \frac{dx(u)}{du} du \\
&=&  \int_{u \in \mathcal{U}} \text{LO}_U(u)  g_A(u) du &=& \int_{u \in \mathcal{U}} \log \left(\frac{g_A(u)}{g_B(u)}\right) g_A(u) du \\
\end{array}$$
where $x(u)$ is the value of $x$ when we apply the reverse transformation to $u$.
One-to-one
An important requirement is that the transformation is one-to-one. This ensures that the transformation of the distribution density in terms of $x$ to the distribution density in terms of $u$ can be written as
$$g(u) = f(x(u)) \frac{dx(u)}{du} du $$
If multiple values of $x$ transform to a single $u$ then we would get a sum over all those values of $x$ that transform to $u$
$$g(u) = \sum_{i} f(x_i(u)) \left|\frac{\text{d}x_i(u)}{\text{d}u}\right|$$


Why do my (coefficients, standard errors & CIs, p-values & significance) change when I add a term to my regression model?

Question: Lots of people seem to be asking this. They often seem to get shallow answers that merely assert what is true, instead of drawing or explaining the mechanism. They also seem to not find each other -- if you don't know the answer, it's not obvious that these are all the same question.
Has someone given a high-quality answer that we can refer all these askers to? If not, give it your best shot below.
Here are some related questions. This list is incomplete. Feel free to edit and add to it.
Linear Regression Coefficient changes with additional variables
GAM Interactions : Individual and Combined Interactions are different
Nonsignificant interaction still causes main effect to flip?
Interpreting main effect coefficient in different models
Interactions make terms significant in regression when they should not be
Related but not bang on:
What if interaction wipes out my direct effects in regression?
Understanding Simpson's paradox: Andrew Gelman's example with regressing income on sex and height
Comment: Having written a lot about these issues for the last 10+ years, and always choosing to do so by deriving conclusions from definitions and first principles, I wonder why you don't seem to have come across any of those posts.  See, *e.g.*, https://stats.stackexchange.com/a/34813/919, https://stats.stackexchange.com/a/24529/919, https://stats.stackexchange.com/a/28493/919, https://stats.stackexchange.com/a/34523/919, https://stats.stackexchange.com/a/32237/919, https://stats.stackexchange.com/a/224958/919, https://stats.stackexchange.com/a/89766/919, *etc.*
Comment: I do everything I can in that regard, Eric, by routinely searching for duplicates, supplying links, and so on.  Unfortunately the SE system is not set up to motivate or reward such activities, so few undertake them.  If you have ideas about how to improve things here on CV, then please post them on Meta; if you have ideas about improving SE sites generally, then consider creating a thread on the [SE Meta site](https://meta.stackexchange.com).
Comment: I actually understand these topics pretty well, and I was mostly concerned about how to collect people landing on the site with similar issues who don't know how to find the right threads. But, it's pretty clear to me now that I am going about this in the wrong way. I will probably delete the question soon, though I might save all the links somewhere first.
Comment: Thanks -- if you post that as an answer, I will accept it.
Comment: This is more of a meta question, but do you think it is necessary to do more to help these threads find each other?
Comment: This is an important but perhaps too broad of a question, Eric. If instead you asked "Why would the coefficients NOT change when adding a term to a regression?" that would be a more targeted question. I'd be interested to know why you'd expect the coefficients not to change when you add a term to your regression. For example, do you have in mind a correctly identified causal/structural parameter or a more generic regression coefficient? If you wrote up your take on that, then it'd be clearer what aspect you're interested in and how we'd approach answering this question.
Comment: Related: In this question [why does the same variable have a different slope when incorporated into a linear model with multiple x variables](https://stats.stackexchange.com/questions/464170/why-does-the-same-variable-have-a-different-slope-when-incorporated-into-a-linea) I give several related links to this topic
Comment: As others, I have posted answers about this multiple times.  See, eg: [Estimating b1x1+b2x2
instead of b1x1+b2x2+b3x3](https://stats.stackexchange.com/q/58709/7290), & [Does adding more variables into a multivariable regression change coefficients of existing variables?](https://stats.stackexchange.com/q/52067/7290)
Comment: I agree that it might be useful to have some sort of community wiki about this that binds this all together.
Comment: We have a question about a slightly different but related topic [Standardization of variables and collinearity](https://stats.stackexchange.com/questions/425082/standardization-of-variables-and-collinearity) (the effect of translation on parameter point estimates and interval estimates) that is similarly asked many times in slightly different forms.
Answer: The ordinary least squares solution is simply given by:
$$\beta = (X'X)^{-1}X'y$$
Let's imagine we augment $X_{n\times p}$ with one or more variables $\tilde X_{n\times \tilde p}$, appending its corresponding values as columns, and call the resulting matrix ${X^*}_{n\times p^*}$, $p^* = p + \tilde p$.
Now, given enough degrees of freedom, coefficients will be given by:
$$\beta^* = ({X^*}'{X^*})^{-1}{X^*}'y$$
If $\left\{A\right\}_{k,:}$ represents the $k$-th row of a matrix $A$, the $k$-th coefficient in each vector corresponds to:
$$\beta_k = \left\{(X'X)^{-1}\right\}_{k,:}X'y$$
$$\beta^*_k = \left\{({X^*}'{X^*})^{-1}\right\}_{k,:}{X^*}'y$$
Since $X^* \neq X$, then there is no reason for $\beta_k$ and $\beta^*_k$ to be equal.
Notice, however, that it can still be true in a specific case.
If the added variables are orthogonal the original independent variables, then $(\beta_k = \beta^*_k | k\leq p)$.
This result can be achieved through:
$${X^*}'{X^*}=\left[
\matrix{
{X}'{X} & X' \tilde X \\
\tilde X' X & \tilde X' \tilde X
}
\right]$$
Rows from the inverse of this covariance matrix left multiply ${X^*}'$.
If $X' \tilde X = \tilde X' X = 0$ the covariance become a block matrix, and it can thus be inverted blockwise:
$$({X^*}'{X^*})^{-1}=\left[
\matrix{
{X}'{X} & \color{red}{0} \\
\color{red}{0} & \tilde X' \tilde X
}
\right]^{-1}=
\left[
\matrix{
({X}'{X})^{-1} & 0 \\
0 & (\tilde X' \tilde X) ^{-1}
}
\right]$$
The full solution becomes:
$$
\begin{align}
\beta^* &= ({X^*}'{X^*})^{-1}{X^*}'y=\\
&=
\left[
\matrix{
({X}'{X})^{-1} & 0 \\
0 & (\tilde X' \tilde X) ^{-1}
}
\right]
\left[\matrix{X'y \\ {\tilde X'y}}\right]=\\
&=\left[\matrix{({X}'{X})^{-1}X'y \\ {(\tilde X' \tilde X) ^{-1}\tilde X'y}}\right]=\left[\matrix{\beta \\ \tilde \beta}\right]
\end{align}
$$
Thus keeping the identity between both results, as the entries pertaining to $\tilde X$ do not affect the coefficients pertaining to the original $X$.
Since coefficients change, so do CIs and p-values. A more in-depth look into how express things in terms of the hat matrix will lead to it all as well.
Answer: Coefficient change
Let some there be some data distributed according to a quadratic curve:
$$y \sim \mathcal{N}(\mu = a+bx+cx^2, \sigma^2 = 10^{-3})$$
For instance with $x \sim \mathcal{U}(0,1)$ and $a=0.2$, $b=0$ and $c=1$. Then a linear curve and a polynomial curve will have very different coefficients for the linear term.

<code>set.seed(1)
x <- runif(100, 0,1)
y <- rnorm(100, mean = 0.2+0*x+1*x^2,
                sd = 10^-1.5)
plot(x,y, ylim = c(0,1.5),
     pch = 21, col = 1 , bg = 1, cex = 0.7)

mod1 <- lm(y~x)
mod2 <- lm(y~poly(x,2, raw =TRUE))

xs <- seq(0,10,0.01)
lines(xs,predict(mod1,newdata = list(x = xs)), lty = 2)
lines(xs,predict(mod2,newdata = list(x = xs)),lty =1)

legend(0,1.5,c("y = 0.009 + 1.023 x", "y = 0.193 + 0.016 x + 0.994 x^2"), lty = c(2,1))
</code>

Correlation
The reason is that the variables/regressors $x$ and $x^2$ correlate.
The coefficient estimates computed with a linear regression are not a simple correlation (perpendicular projection onto each regressor seperately):
$$\hat{\beta} \neq \alpha = \mathbf{X^t} y$$
(this would give coefficients $\alpha_1$ and $\alpha_2$ in the image below, and these coordinates/coefficients/correlations do not change when you add or remove other regressors)
Using the correlation/projection $\mathbf{X^t}y$ is wrong, because if there is a correlation between the vectors in $\mathbf{X}$, then there will be an overlap between some vectors. This part that overlaps will be redundant and added too much. The predicted value $\hat{y} = \alpha \mathbf{X}$ would be too large.
For this reason there is a correction with a term $(\mathbf{X^t}\mathbf{X})^{-1}$ that accounts for the overlap/correlation between the regressors. This might be clear in the image below which stems from this question: Intuition behind $(X^TX)^{-1}$ in closed form of w in Linear Regression

Intuitive view
So the regressors $x$ and $x^2$ both correlate with the data $y$ and they both will be able to express the variation in the dependent data. But when we use them together then we are not gonna add them according to their single independent effects (according to correlation with $y$) because that would be too much.
If we use both $x$ and $x^2$ in the regression then obviously the coefficient for the linear term $x$ should be very small since this is the same in the true relation.
However, when we are not using the quadratic term $x^2$ in the regression (or otherwise add a bias to the coefficient for the quadratic term), then the coefficient for $x$ which correlates somewhat with $x^2$ will partly take correct this (take over) and... the value of the estimate for the coefficient of the linear term will change.
Standard error change (and confidence intervals and p-values)
The errors of the variables may be correlated leading to very large errors in some coefficient when they strongly correlate with others. The matrix $(X^TX)^{−1}$
describes this correlation.
Error in the regression line
The image below shows intuitively how this changes when adding other regressors.
The intercept is the point where a regression line crosses $x=0$.

On the left the error of the intercept is the error of the mean of the population.
On the right the error of the intercept is the error of the regression line intercept.

Confidence regions for correlated parameters
The next image displays the confidence regions (contrasting with confidence intervals) of the above regression in a 2-D plot. Here it takes into account the correlation between the parameters.
The ellipse shows the confidence region which is a based on a multivariate distribution of the slope and intercept which may be related via a correlation matrix. For illustration an alternative type of region is also show. This is depicted by the box which is based on two single variate distributions assuming independence (now the confidence for the single variables is $\sqrt{0.95}$).
By changing the model from $y = a + bx$ to a shifted model $y = a + b(x-35.5)$ we see that the correlation between the slope and intercept changes. Now the "intercept" coincides with the standard error of the line around the point $x=35.5$ which you see in the image above is smaller.

<code>#used model and data
set.seed(1)

xt <- seq(0,40,0.1)
x <- c(1:10)+30
y <- 10+0.5*x+rnorm(10,0,3)
</code>
See also:

why does the same variable have a different slope when incorporated into a linear model with multiple x variables

regression with multiple independent variables vs multiple regressions with one independent variable

Why is the intercept in multiple regression changing when including/excluding regressors?

Why and how does adding an interaction term affects the confidence interval of a main effect?

Why is the intercept changing in a logistic regression when all predictors are standardized?

Intuition behind $(X^TX)^{-1}$ in closed form of w in Linear Regression

Does adding more variables into a multivariable regression change coefficients of existing variables?

Estimating $b_1 x_1+b_2 x_2$ instead of $b_1 x_1+b_2 x_2+b_3x_3$

Why do regression coefficients change when excluding variables?

Does the order of explanatory variables matter when calculating their regression coefficients?

Intercept changing after adding an interaction
Comment: I would have closed the question, but then it attracted nice contributions such as this -- a nicely intuitive answer with a helpful collection of related threads!


How do I exclude certain modules from a Maven build using the commandline

Question: Is there a way to exclude some modules from a big reactor build, similar to -pl ?
Here are a number of ways to do it persistently:
How to exclude a module from a Maven reactor build?
I want to do it from shell, or at least without modifying the poms, which I am not allowed to change.
Comment: Using profiles seems to be the easiest and most correct way to me.
Comment: @AndrewLogvinov can that be done in settings.xml ? Switching off tests per profile will not be appreciated in central poms. ;-)
Answer: Maven 3.2.1 has added this feature, you can use to specify the exact projects you want (or to exclude the projects you don't want) -pl or --projects Here's how to exclude two:
-pl "!<modulename>,!<modulename2>"

for exclude certain modules. This can be comma separated list of values that you want to include/exclude.
Update
For windows user following
> mvn clean [package|install] --projects \!groupId:artifactId

Comment: `` is the directory name of the submodule, not the artifactId
Comment: ! is not work in window. is there different key word ! for window?
Comment: @bNd on windows you have to mention '!:' of particular module even if it is a submodule
Answer: Another comment on the accepted answer, don't forget to escape the exclamation sign when running the command in bash:
> mvn clean install -pl \!module,\!module/submodule,\!groupId:artifactId

Comment: Single quotes ('), that is
Comment: thanks @dstibbe `mvn clean -pl '!module'` did the trick for me
Comment: or use `-` instead of `!`, i.e. `> mvn clean install -pl -module,-module/submodule,-groupId:artifactId`
Comment: or surround with quotes :)
Answer: As Yogesh_D wrote it can be done with the -pl argument with maven 3.2.1+
Here's an example:
> mvn clean install -amd -pl !module,!module/submodule

You need to list every sub-module (and sub-sub-module etc) manually, it does not exclude them recursively. Use the slash for package separation. It's the folder path, not the group or artifact id.
Answer: I don't believe this is currently possible from the command line.  There is an open feature request in maven3 for this very thing (https://issues.apache.org/jira/browse/MNG-5230).
Looks like your only option at this point is to modify the pom and create a new build profile that includes only the modules you want to build.
Comment: Jira link is dead
Comment: MNG-5230 - was resolved in version maven 3.2.1
Answer: Instead of using exclamation ! sign you can use minus - sign.
mvn clean -pl -module1

You can also exclude multiple modules.
mvn clean -pl -module1,-module2

or
mvn clean -pl -module1 -pl -module2

Tested with:

Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-17T20:33:14+02:00)
Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)

Excluded modules must be in reactor of current project, so we can't exclude no existing module.
mvn clean -pl -no-existing-module

currently will fail - https://issues.apache.org/jira/browse/MNG-7033
Answer: in 2019 it's
mvn install -pl !:module1

(Windows 10 cmd)
Answer: comma separated module name enclosed with double quotes.
 eg::
mvn install -pl "!Module1, !Module2"


Why do I get an AJAX error during installation?

Question: I tried to install Drupal 7.10. When the installation has installed 28/29 modules, I get the following error.

An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: http://localhost/drupal/install.php?profile=standard&locale=en&id=1&op=do
StatusText: OK
ResponseText: ( ! )
Fatal error: Maximum execution time of 30 seconds exceeded in C:\wamp\www\drupal\includes\database\mysql\database.inc on line 153

Can anyone help me to fix it?
Answer: The problem is the  maximum execution time being exceeded. To fix this, you should change the maximum execution time in your php.ini file. Click on the Wamp icon on the taskbar, select PHP -> php.ini, find "max_execution_time" and change it from 30 to like 100-300, to make sure even the slower scripts get their job done before the timeout.
Remember to restart the server after you change the settings.
Comment: Did you restart all services?
Comment: i checked and change it to 200, but it still displayed: Maximum execution time of **30** seconds exceeded
Answer: I was also getting a similar error during Drupal installation, with Drupal already installed as response text. I fixed the error by changing the following values in the php.ini file used for the site.
<code>max_execution_time = 180
max_input_time = 180
max_input_nesting_level = 300
memory_limit = 512M
</code>


A prize for picking a number goes to the entry closest to $2/3$ of the mean of all entries. What's the smart entry?

Question:
A newspaper launches a competition. It said that readers should submit one number between $1$ and $1000$. A £$2000$ prize would be awarded to the person that got the closest to $2/3$ of the mean of all the entries.

What would a smart entry be? What is the underlying principle behind this type of question. I know it involves game theory but I do not fully understand this type of problem yet. Can anyone draw the game theory tables involved / explain the Nash Equilibria?
Comment: By the way, is this homework?  Judging from your other question I'm guessing you're just looking through a book of puzzles or something, but it's nice to be sure.
Answer: The only Nash equilibrium is that everybody submits $1$.  To see this, consider any other set of strategies for all the players.  Suppose each player $i, 1 \le i \le n$ submits numbers with an expected value of $p_i$ and that at least one of the $p_i$ is greater than $1$.  Then the expected value of the mean of the entries is $\frac{p_1 + ... + p_n}{n}$, and there must be at least one player $j$ for which this mean is less than or equal to their number.  But then the expected value of $\frac{2}{3}$ of the mean must be strictly less than $p_j$, so player $j$ has an incentive to switch to a lower number.
This is a funny example.  Although the Nash equilibrium suggests that playing $1$ should be an optimal strategy, in practice you will always lose when you do this.  The issue, I think, is that it only makes sense to adopt the Nash equilibrium strategy if you expect everybody to be playing optimally, but in practice most people will not think this game through enough to actually find the Nash equilibrium strategy.  I've played this game a few times, and what seems to be the case in practice is that to most players you can associate a number $n$ such that the number they pick is $\left( \frac{2}{3} \right)^n$ times the maximum.  I like to think of $n$ as being a very rough measure of how far the players think ahead, since one can think of $n$ as being the number of times they recurse through the following argument:

Since the maximum you can play is $1000$, the maximum the average could be is $\frac{2}{3} \cdot 1000$, so I should never guess more than that.
But since nobody should guess more than $\frac{2}{3} \cdot 1000$, the maximum the average could be is $\left( \frac{2}{3} \right)^2 1000$, so I should never guess more than that.
But...

and so forth.  If the people you're playing with are smart enough, $n$ will actually measure something much more complicated: each player will be trying to guess how far everyone else will think ahead, and then guessing how far everyone else will guess how far everyone else thinks ahead, and then... this phenomenon, in my opinion, is much more interesting than Nash equilibria; I think it is related to the idea of common knowledge.
(The last time I played this game, the possible numbers were $0$ through $100$.  I and one other person submitted $100$ just to throw off the results.  The actual average ended up being something like $19$.  So here $n \approx 9.7$.)
Finally, here's a cute observation.  In general the existence of Nash equilibria can be proven using the Brouwer fixed point theorem.  The second argument I gave above establishes the existence (and uniqueness) of the Nash equilibrium using essentially the Banach fixed point theorem.
Comment: Also, I think there was a dinosaur comics about this.  Anyone have the link?
Comment: Hi, yes they are past interview questions
Comment: Nash equilibrium is the weakest sort of equilibrium (IIRC).  Its main selling point is that it always exists, but for dynamic sorts of games I don't think things have to converge to a Nash equilibrium.  A much stronger notion is that of a "dominant strategy", which is when you have a best choice *regardless* of what the other players choose.
Answer: When solving problems like this the first thing to do is (almost) always to try and reduce the problem to a simpler problem; in this case, for example, pretending the number of allowed numbers is 10, and not 1000, is a good first thing to do.
You may also simplify the problem by allowing everyone to know the current mean value. That way you'll see that everybody has an incentive to submit lower and lower numbers - resulting in Qiaochu's answer.
(as a "by the way", I'll recommend G. Polya's book "How to solve it", which talks about general problem solving techniques.)
EDIT: This problem reminds me of a "paradox" I read about yesterday:
"A prisoner is awating death sentence, and is told he will be executed withing this week (it's Monday now), but on a day he's not expecting it. The prisoner reasons that then he can't be executed on Sunday (because if he lives then, that must be the day), and the same reasoning tells us that he will not be executed on Saturday either, and so on. The prisoner concludes that he wont be executed after all. (without expecting it, he is executed on Monday)"
Comment: Yes, the unexpected hanging paradox (http://en.wikipedia.org/wiki/Unexpected_hanging_paradox) has a sort of similar flavor.


algorithm to control intensities of multiple lights

Question: We have multiple lights in 10x10 grid each of which we can control intensity 1 to 10. Target of those lights is a wall and our goal is to have uniform intensity within some range over wall image where user defines the intensity value.  One restriction is that only direct adjacent neighbor lights of given light will be affect the image intensity for the wall area the light directly shed on.
I think (and hope) that this is a known problem but couldn't find any good reference to solve this problem. Any tip or clue would be appreciated.
Comment: Would the light intensity be uniform if all lamps are turned to the same intensity?  Also, what is the affect of a lamp on the light intensity on the wall directly targeted by an adjacent lamp?
Comment: I would think the same light intensity would achieve uniformity but it does not in reality. Always center area is brighter than edge areas. About lamp, it has narrow beam so that only adjacent lamps can affects each other in terms of image intensity.
Comment: The edge might be less bright as there are less neighboring lamps around (especially at the corners).  To get a definitive answer (which I might not give), you should tell us how _specificly_ the lamps affect the lights of their neighbors (e.g. does it double, increase it by 10%).  Also, in real life the fact that the beams are narrow still might allow some effect on neighbors-of-neighbors
Answer: I suppose that resulting intensity is linear combination of some neigbour lamps. For example, I[x,y]=a*L[x,y]+b*(L[x-1,y]+L[x+1,y]+L[x,y-1]+L[x,y-1])+c*(L[x-1,y-1] +...), where a,b,c are some coefficients. So there is linear system of 100 equations with 100 unknowns variables. It may be solved, if coefficients are known.
More complex model  - convolution of lamp intensity matrix with point spread function. It  may require sophisticated methods of signal reconstruction
Answer: This cries out for a genetic algorithms approach:  Without too much trouble you can customize it to take into account your lamp characteristics, and any desired function of illumination on the wall.
Update:  To be more concrete, if the OP already has some information about the light intensity function due to one lamp, then the programming aspect will be tedious, but straightforward.  If not, then what's needed is a way to get that information.  One way to do this is to get a photodiode and just measure the light intensity from the center to the periphery, with one lamp turned on mounted the way it will be in the real application.  Use whatever sampling interval seems appropriate based on the physical set-up-- an inch, six inches, a foot, whatever.  Using that information, the OP can create a function of light intensity based on one lamp.
I have no particular photodiode to recommend, but they can't be that expensive, since Lego Mindstorms can take readings from them.  I did speak incorrectly in the comments below, though-- it might actually take one measurement for each of the ten intensity settings on the lamps, and I'm explicitly assuming that all the lamps have roughly the same performance.
From there, we can mathematically build the larger function of a light intensity pattern caused by 100 lamps at arbitrary intensities-- a function into which we can plug 100 numbers (representing the lamp settings) and get out a good approximation of the resulting light intensity.  Finally, we can use a genetic algorithm to optimize the inputs of that function such that uniform intensity patterns are highly fit.
Careful, though-- the true optimum of that statement is probably "all lamps turned off."
(If you're more confident in your photography than I am, a camera might work.  But either way, without a detailed knowledge of the intensity patterns of the lamp settings, this is not a solvable problem.)
Comment: You could solve this problem in genetic algorithm but it will really take long time and lots of image captures to find an optimum with given user-specified value.
Comment: No image captures involved.  One good measurement of the intensity pattern of one lamp, and a lot of calculations.
Comment: Maybe I misunderstood you but then how do you measure image intensities even with one lamp without image acquisition?


The sleep command executes not how i expected

Question: int main()
{
  printf("Whats up");
  sleep(3);
  printf("StackOverflow? All having a nice day? ");
}

Why is the output after 3 seconds "Whats up Stack.." and not first "Whats up" and then, 3 sec later the rest?
Answer: It's because stdout is usually line-buffered. So your C library buffers the output. You can flush this by using \n in printf() or by calling fflush(stdout).
  printf("Whats up\n");

or
fflush(stdout); // call after the printf

You can also turn off the buffering with setbuf():
setbuf(stdout, 0);

Comment: As a quick note that isnt directly related to OPs question but still relevant. If your on linux using the newline character to flush the buffer will only work on the terminal and wont work on file redirection


I need help evaluating the integral $\int_{-\infty}^{\infty} \frac{\log(1+e^{-z})}{1+e^{-z}}dz$

Question: I was playing around with the integral: $$\int_{-\infty}^{\infty} \frac{\log(1+e^{-z})}{1+e^{-z}}dz$$
I couldn't find a way of solving it, but I used WolframAlpha to find that the integral evaluated to $\zeta(2)$ or $\frac{\pi^2}{6}$.
How would I go around finding the solution?
My experience with integrals is very limited, but I think the solution can possibly be found using the polylogarithm (saw a similar integral use it), but I don't know much of the function so maybe someone on here could help me.
I initially tried rewriting the $\frac{1}{1+e^{-z}}$ as a geometric series, but I don't think that works.
Then I looked at finding the poles and drawing a contour, but I also don't think that works.
Is there some identity that can be used here, which I happen not to know?
Any help is appreciated, especially if you could show your working out step by step.
Answer: My immediate thought is to let
$$
u = 1+e^{-z} \implies du = -e^{-z} dz = (1-u)dz
$$
so
$$
\mathcal{I}:= \int_{-\infty}^{\infty} \frac{\log(1+e^{-z})}{1+e^{-z}}dz
= \int_{\infty}^{1} \frac{\log(u)}{u} \frac{du}{1-u}
= \int_{1}^{\infty} \frac{\log(u)}{u(u-1)} du
$$
Now let
$$
v = \log(u)
\implies
dv = \frac 1 u du
$$
giving us a perhaps more familiar integral:
$$
\mathcal{I}
= \int_{0}^{\infty} \frac{v}{ e^v-1 } dv
= \int_{0}^{\infty} \frac{ve^{-v}}{ 1-e^{-v} } dv
$$
Apply the geometric series to this: assuming the interchange of sum & integral is valid,
$$
\mathcal{I}
= \int_{0}^{\infty} ve^{-v} \sum_{n=0}^\infty e^{-nv} dv
= \sum_{n=0}^\infty \int_{0}^{\infty} ve^{-v} e^{-nv} dv
= \sum_{n=0}^\infty \int_{0}^{\infty} v  e^{-(n+1)v} dv
= \sum_{n=1}^\infty \int_{0}^{\infty} v  e^{-nv} dv
$$
The remainder is a standard integral. Apply integration by parts.
$$
\mathcal{I}
= \sum_{n=1}^\infty \frac{1}{n^2}
= \zeta(2)
$$
Comment: Thank you! Didn't think it would be as simple as this. Would this also work if all the $e^{-z}$s were $e^{z}$? And is there a way of generalizing this sort of integral for $ζ(2n)$, just some extra thoughts I've had relating to this. But again, thanks for answering.
Answer: Substitute $t=\frac1{1+e^{-z}}$ and then utilize $\int_0^1 \frac{\ln x}{x-1}dx=\frac{\pi^2}6 $ to obtain
$$\int_{-\infty}^{\infty} \frac{\log(1+e^{-z})}{1+e^{-z}}dz=\int_0^1 \frac{\ln t}{t-1}dt=\frac{\pi^2}6$$
Answer: $$
I \stackrel{y=1+e^{-z}}{=}  \int_1^{\infty} \frac{\log y}{y(1-y)} d y \stackrel{y\mapsto\frac{1}{y}}{=} -\int_0^1 \frac{\log y}{1-y} d y= -\sum_{n=0}^{\infty} \int_0^1 y^n \log y d y \stackrel{IBP}{=}   \zeta(2)=\frac{\pi^2}{6}
$$


functoriality of blow-ups

Question: Let $f:X\to Y$ be a finite map of varieties and let $BL_Z(Y)$ be the blow-up of a subscheme $Z\subset Y$. Is there a map $$\phi:BL_{f^{-1}(Z)}(X)\to  BL_{Z}(Y)?$$ If so, what can be said about $\phi$? Is it also finite?
Answer: You need more hypotheses for such a map to exist.  For example, suppose
that $X = pt$ and $Y = \mathbb A^2$ (over a field $k$, say) and $f$ is the map sending the point to the origin.  Now take $Z$ to be the origin of $Y$.  The preimage of $Z$ is all of $X$, and so the blow-up of $X$ at $f^{-1}(Z)$ is just $Z$ again.  On the other hand, there is no natural map from $X$ to the blow-up of $Y$ along $Z$.  (If there were we could pick out a distinguished point on the exceptional divisor, which we can't.)
If $f$ is finite and flat, then unless I am blundering the blow-up of $X$ along $f^{-1}(Z)$ will precisely equal the fibre product over $Y$ of the blow-up of $Y$ along $Z$ with $X$.  So in this case, there is a map $\phi$, it is just a base-change, and in particular it is again finite and flat.
If you like, the problem is that Proj (which is what appears in the definition of blow-ups) is not functorial in the most naive way.

functoriality of blow-ups


ngx-datatable - Returning Empty Table (Angular 6)

Question: I'm trying to populate a ngx-datatable via API response (async function). I've managed to get the functions working, however the rows in the table are blank (correct number of rows are created).

When i hover on the table, as expected it triggers the onActivate function to log the event and when i look at the event data i can see the data that's meant to be displayed on the table. This indicates that the data is passed to the table accurately but the issue is due to a rendering problem of sort.
HTML:

        <ngx-datatable class="bootstrap selection-cell"
          [rows]="rows"
          [columnMode]="'force'"
          [columns]="columns"
          [headerHeight]="50"
          [footerHeight]="50"
          [rowHeight]="'auto'"
          [limit]="20"
          [selected]="selected"
          [selectionType]="'multiClick'"
          (activate)="onActivate($event)"
          (select)='onSelect($event)'>
        </ngx-datatable>

component:
res_out = {}
  res_out_ = []
  rows = []
  loadingIndicator = true;
  reorderable = true;
  selected = [];

  columns = [
    { name: 'ID'},
    { name: 'FileID'},
    { name: 'SectionNum'}
  ];

  constructor() {

      this.fetchData((dt) => {
        this.rows = dt;
        setTimeout(() => { this.loadingIndicator = false; }, 1500);
      });

    };

  async fetchData(cb) {
    return await API.get(this.apiName, this.path, this.myInit).then(response => {
      response.forEach(element => {
        this.columns.forEach((el, i) => this.res_out[el.name] = element[i]);
        this.res_out_.push(this.res_out)
      });
      console.log(this.res_out_)
       cb(this.res_out_)
    }).catch(error => {
      this.res_out_ = [this.res_out]
      console.log(error.response)

    });
  }

I tried do populated the data via an Observable and async pipe still didn't work.
Any ideas?
Comment: Can you show what have you tried ? edit and include your source code to the question.
Comment: Just added the code bits you requested.
Answer: Add the "prop" definition to your columns definition in order to bind to a property


Show block in particular nodes having some string in title

Question: I have a block and I need to show this block only in some situations.
For example if title of node includes "abc", block will be visible else it won't.
From visibility settings of block I use this code snippet:
<?php
$match = FALSE;

$url = request_uri();
if (strpos($url, "myword")) {
  $match = TRUE;
}
?>

I'm sure that "myword" is included in full URL of node.
I tried to debug it by adding "echo $url" but it didn't write this line into page.
How can I solve this?
edit: in last line i forgot to add "return $match;" which returned always false.
Answer: Try:
if (strpos($url, 'myword') !== FALSE) {
  $match = TRUE;
}

strpos() returns the zero-based index of the first occurrence of the substring.
So if "myword" is at the start of the URI string strpos() will return 0, and since 0 == FALSE in terms of a conditional, it will fail.
I've just tested your code and it works fine with the slight change.


@ in XML tag name

Question: I want to export a database to XML, I use email address as key for the datas:
<?xml version="1.0"?>
<DS>
    <email@example.com>
        <name>remrem</name>
        <email>email@example.com</email>
        <datetime>2014-09-23 07:41:57</datetime>
        <lang>fr</lang>
    </firstname.lastname@example.com>
    <email@example.com>
        <name>remrem</name>
        <email>email@example.com</email>
        <datetime>2014-09-23 07:41:57</datetime>
        <lang>fr</lang>
    </firstname.lastname@example.com>
</DS>

But on read this export, I have always errors because of "@" in the key.
Somebody have a solution for me ?
escaping the "@" ?
use an another key ? (keep email key is better for me)
FYI, I use PHP (SimpleXMLElement)
Thanks !
Comment: Also this is not csv but xml
Comment: why not `test...` like this?, by the way, this is not a CSV, its an XML
Comment: Yeah CSV is comma separated values (Can actually be separated by another delimiter if you want). Show your PHP code.
Comment: oO, sorry, need more coffee ...
Answer: You should not use values in XML tags. The correct way would be:
<?xml version="1.0"?>
<DS>
    <userdetails>
        <name>remrem</name>
        <email>firstname.lastname@example.com</email>
        <datetime>2014-09-23 07:41:57</datetime>
        <lang>fr</lang>
    </userdetails>
    <userdetails>
        <name>remrem</name>
        <email>email@example.com</email>
        <datetime>2014-09-23 07:41:57</datetime>
        <lang>fr</lang>
    </userdetails>
</DS>

There are only five special characters in XML:  < (<), & (&), > (>), " ("), and ' ('). However, tag names have more restrictions. A tag name is a token beginning with a letter or one of a few punctuation characters, and continuing with letters, digits, hyphens, underscores, colons, or full stops, together known as name characters. Or more precise:
NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender
Name ::= (Letter | '_' | ':') (NameChar)*

It can get quite complicated, but for simplicity just stick to what you know from HTML and almost any programming language using variable names.
Use tags only to identify the type of content they hold.
Comment: can I have multiple  ?
Comment: @RemRem yes you can have

@ in XML tag name


Transformar e devolver uma string s centralizada em uma string de comprimento width

Question: Neste exercício devo passar para a função uma string, um tamanho e o caracter que desejo incluir na string, porem encontro problemas ao executa-lo, a string que deveria ficar centralizada acaba sendo preenchida pelos asteristicos.
<code>//Como deveria ficar:  asteristicos Apresentando os dados asteristicos

/*Transforma e devolve a string s centralizada em uma string
de comprimento width. O preenchimento é feito usando o
caractere especificado por fillchar. A string original
é devolvida se width for menor ou igual a strlen(s).*/

char * redefine(char * s, int width, char fillchar){
    int i;
    char aux;

    for(i = 0; i < 46 ; i++){
        aux = s[i];
        s[i] = fillchar;
    }

    printf("%s\n", s); //Teste para ver ser a string esta correta.
}

int main(){
    char str2[81] = "Apresentando os dados";

    // forma usada como teste.
    redefine(str2, 80, '*')
    // assim é a chamada da função printf("\"%s\"\n", redefine(str2, 80, '*'));

    return 0;
}
</code>
Answer: Primeiro você precisa calcular quantas posições tem que preencher. Preencha metade copie a string e preencha as posições restantes.
<code>#include <stdio.h>
#include <string.h>
char * redefine(char * s, int width, char fillchar){
    int i, n;
    char aux[width];
    if (strlen(s) >= width)
        return s;
    n = (width - strlen(s)) / 2;
    for(i = 0; i < n ; i++){
        aux[i] = fillchar;
    }
    aux[i] = '\0';
    strcat(aux, s);
    for (i=strlen(aux); i<width-1; i++) {
        aux[i] = fillchar;
    }
    aux[width-1] = '\0';
    strcpy(s, aux);
    return s;
}

int main(){
    char str2[81] = "Apresentando os dados";
    printf("\n[%s]\n", redefine(str2, 80, '*'));

    return 0;
}
</code>


Node.js stream write in loop

Question: I was trying to benchmark some node.js native functionalities lately and found out some creepy results I cannot understand. Here's a simple code that I benchmarked and benchmark results:
http://pastebin.com/0eeBGSV9
You can see that it did healthy 8553 requests per second on 100k requests with 200 concurrency. I was then instructed by a friend, that I shouldn't be using async in this case, as this loop isn't big enough to obstruct event loop of node, so I refactored code to use for loop and it increased the benchmark result even higher:
http://pastebin.com/0jgRPNEC
Here we have 9174 requests per second. Neat.
(for loop version was consistently faster than async version even when I changed the amount of iterations to 10k, curiously enough).
But then my friend wandered if this result could be pushed even further by use of streaming instead of dumping all data after loop has finished. Once again, I refactored code to use res.write to handle data output:
http://pastebin.com/wM0x5nh9
aaaaand we have 2860 requests per second. What happened here? Why is stream writing so sluggish? Is there some kind of error in my code or is this how node actually works with streams?
Node version is 0.10.25 on ubuntu with default settings from apt installation.
I also tested the same code against JXCore and HHVM (using async.js version of node code) in the beginning with results here: http://pastebin.com/6tuYGhYG and got a curious result of node cluster being faster than latest jxcore 2.3.2.
Any critique would be greatly appreciated.
EDIT: @Mscdex, I was curious if calling res.write() might have been the issue, so I changed the way I pushed out data to a new stream made for consumption by res. I believed, naively, that maybe this way node will somehow optimize output buffering and stream data in an effective way. While this solution worked too, it was even slower than before:
http://pastebin.com/erF6YKS5
Comment: FYI using async doesn't automatically make your code asynchronous. Your first benchmark was slower than a simple for-loop because it essentially was just a simple for-loop with the added overhead of the async library.
Comment: Yeah, I realized that after benchmarks. That however doesn't answer why streaming sucks. Just tested with backpressure detection via drain event and it's still around 2900 rps.
Answer: My guess would be the overhead involved with having many separate write() syscalls.
In node v0.12+, "corking" functionality has been added so that you can do res.write() as much as you want, but you can cork and uncork the stream so that all of those writes only result in a single write() syscall. This is essentially what you're doing now with the concatenating of the output, except the corking will do that for you. In some places in node core, this corking functionality may also be used automatically behind the scenes so that you don't have to explicitly cork/uncork to get good performance.
Comment: There's a reason I want to use stream - it's streaming. I don't want one single write() syscall, it's not streaming, it's sending the whole output in one piece. I want node to stream output as it gets it from the for loop, not buffer it (as I can simply concatenate everything in one variable and just use res.end()) and push to client.

Node.js stream write in loop


How to download wordcloud as picture in react-wordcloud?

Question: How to download wordcloud as picture in react-wordcloud? Or is there any react packages that can plot wordcloud and download the pic?
Answer: Here is a simple way to do it..
import React, {createRef} from 'react';
import ReactWordcloud from 'react-wordcloud';
import { saveSvgAsPng } from 'save-svg-as-png';
import {Button} from 'antd';

const saveWordCloudToImage= () => {
   const wordcloudRef = createRef();
//   const words = //your words object;

   const handleSave = () => {
        const svgElement = wordcloudRef.current.querySelector('svg');
        saveSvgAsPng(svgElement, 'wordcloud.png');
   };

   return (
      <>

             <ReactWordcloud  words={words}/>

          <Button onClick={handleSave}>Save</Button>
      </>
   )
};

Comment: Well, my code is the answer to your question. It actually downloads wordcloud as picture in react-wordcloud.
Comment: It's not my question. I'm just saying that doing "this is the answer" isn't as high of quality as "This the answer because ... and you need to avoid ..."
Comment: Here is a working example i made on stackblitz [link](https://stackblitz.com/edit/react-wvqsph)
Explaining what the code does, this method 'handleSave' is the key to save the picture, i created a reference and and linked to the span where ReactWordCloud component is so i can get access to the SVG dom element of it.
This line 'wordcloudRef.current.querySelector('svg')' is equivalent of js function 'GetElementByTagName', that means i selected the SVG element and converted to png using this library 'save-svg-as-png'.
Obs: I´m new here, sorry if my first comment didn´t answer your question.
Comment: If this is what you was looking for, can you upvote this solution?


Squid limit total bandwidth per user

Question:
Possible Duplicate:
Squid Proxy Server: limit total bandwidth

Is there any feature of squid to limit the total bandwidth for every user?
Comment: or this:  http://serverfault.com/questions/79824/limiting-bandwidth-dynamically-in-squid
Comment: There isn't a duplicate. I want to limit per user the bandwidth
Answer: http://www.howtoforge.com/squid-delay-pools-bandwidth-management
Limit total bandwidth use per user
try above links :)

Squid limit total bandwidth per user


Foreach loop through ObservableCollection

Question: In WPF app I use LINQ query to get values from ObservableCollection and update the state of some objects:
var shava = from clc in _ShAvaQuCollection where clc.xyID == "x02y02" select clc;

        switch (shava.First().Status)
        {
            case 1:
                x02y02.Status = MyCustControl.Status.First;
                break;
            case 2:
                x02y02.Status = MyCustControl.Status.Second;
                break;
           ...
         }

In fact, xyID is unique field in this ObservableCollection and its string value corresponds to names of objects in XAML (these objects are derived from a customer control  MyCustControl).
What I am trying to do is:
(1) to iterate through all of the records in _ShAvaQuCollection and, using xyID field, reference each particular objects, using shava as a result of query to each of the record:
MyCustControl sc = (MyCustControl)this.FindName(shava.First().xyID);

(2) and update the state of the object, using other values from this record, for example:
           switch (shava.First().Status)
        {
            case 1:
                sc.Status = MyCustControl.Status.First;
                break;
            case 2:
                sc.Status = MyCustControl.Status.Second;
                break;
           ...
         }

All these actions apart work well, but I cannot combine it to a working iteration method, something like this (it is an idea only, because I didn't manage to get a compyleable code):
public void ReadingCollection(System.Collections.Generic.IEnumerable<ShowAvaQu> coll)
{
   foreach (var xyid in coll)
        {
            //do my actions (1) and (2)
        }
}

Please, help me to organize such an iteration in this last piece of code inside the foreach loop. I'm experiencing problems with understanding how to make a query to each particular record of the collection inside the loop.
I described that all above just to make clear what I intend to do with results of such query inside this loop.
Comment: Sorry, maybe I not very coorectly formulated my problem. In fact, this very code compiles OK. I'm experiencing problems with quering each particular record inside the loop. Thank you, I will now correct my question.
Answer: It looks like you need to take a sequence of ShowAvaQu objects, turn it into a sequence of MyCustControl by using FindName, and update the status of each control based on the status of each ShowAvaQu.
First, let's associate the statuses and controls:
var shavaControls =
    from shava in coll
    select new
    {
        Status = shava.Status,
        Control = (MyCustControl) this.FindName(shava.xyID)
    };

Then, iterate that sequence, updating the statuses as necessary:
foreach(var shavaControl in shavaControls)
{
    switch(shavaControl.Status)
    {
        case 1:
        shavaControl.Control.Status = MyCustControl.Status.First;
        break;
        case 2:
        shavaControl.Control.Status = MyCustControl.Status.Second;
        break;
        //...
    }
}

Does that look right?
Comment: Yes, it does. I tried it and it works OK. For me, it is not only yet another way of doing things, but also the piece of code to learn from.
Thanks, Bryan! +1
Answer: It seems I managed to do this (and it works):
 public void ReadingCollection(System.Collections.Generic.IEnumerable<ShowAvaQu> coll)
   {
        foreach (var id in coll)
        {
            MyCustControl sc = (MyCustControl)this.FindName(id.xyID);
            switch (id.Status)
            {
                case 1:
                    sc.Status = MyCustControl.Status.First;
                    break;
                case 2:
                    sc.Status = MyCustControl.Status.Second;
                    break;
                case 3:
                    sc.Status = MyCustControl.Status.Third;
                    break;
                default:
                    break;
           }
        }
    }


How do I add a PKI certificate to a Go HTTP request?

Question: I'm trying to add a PKI certificate to an HTTP client, so that all requests made by it are authenticated to the services they are talking to.  I can instantiate an HTTP client by executing:
client := &http.Client{
    Transport: &http.Transport{
        Proxy:                 http.ProxyFromEnvironment,
        TLSClientConfig: &tls.Config{
            // TLS Implementation
        }
    }
}

This uses the default RoundTripper implementation, which includes a TLS configuration section.  However the TLS configuration appears to be shared between client and server.  Which of these settings do I need to add so that I can call other PKI services?
Comment: `Certificates` or `GetClientCertificate`, as documented: https://golang.org/pkg/crypto/tls/#Config
Answer: It appears that one only needs to add the Certificates attribute to the TLS configuration:
Certificates: []tls.Certificate{cert}

Where cert can be created using the helper function:
cert, err := tls.LoadX509KeyPair(*certFile, *keyFile)

Where certFile and keyFile are two strings which point to pem files on disk.  As mentioned by Peter, you can also implement GetClientCertificate, but that is unnecessary for implementing PKI support.


How to upload image through restful web services on server using Struts2 (error after deployed the server )

Question: HOW TO RETURN IMAGE IN RESTFUL
I had uploaded image in database but when I deployed the project on server it should not display the image on JSP pages.
how should I do the services for the upload and I wanted to display on jsp pages.
  <action name="saveGrid" method="saveGrid"
        class="com.rssquarz.png.action.GridAction">
        <interceptor-ref name="exception" />
        <interceptor-ref name="i18n" />
        <interceptor-ref name="fileUpload">
            <param name="allowedTypes">image/x-png,image/png,image/gif,image/jpeg,image/pjpeg</param>
            <param name="maximumSize">922240</param>
        </interceptor-ref>
        <interceptor-ref name="params">
            <param name="excludeParams">dojo\..*,^struts\..*</param>
        </interceptor-ref>
        <interceptor-ref name="validation">
            <param name="excludeMethods">input,back,cancel,browse</param>
        </interceptor-ref>
        <interceptor-ref name="workflow">
            <param name="excludeMethods">input,back,cancel,browse</param>
        </interceptor-ref>
        <result name="success">Grid.jsp</result>
        <result name="input">Grid.jsp</result>
        <result name="error">Grid.jsp</result>
    </action>

public class GridDao {

public int saveGrid(Grid grid) {
    {
        SessionFactory factory = null;
        Session session = null;
        System.out.println("you are in saveGrid ");
        try {
            factory = new Configuration().configure().buildSessionFactory();
            session = factory.openSession();
            Transaction t = session.beginTransaction();
            session.save(grid);
            t.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
    return 0;
}

public class GridAction extends ActionSupport {
/**
 *
 */
private static final long serialVersionUID = -4964110302586165626L;
private List<Grid> listGrid;
Grid grid = new Grid();

private File fileUpload;

private String fileUploadContentType;

private String fileUploadFileName;

private String ImgURL;

public String saveGrid() {
    try {
        String resultUpload = saveImage();
        if (resultUpload.equalsIgnoreCase("success")) {

            String address = Inet4Address.getLocalHost().getHostAddress();
            ImgURL = "http://" + address + ":8080/PngAppWebApp/temp/"
                    + fileUploadFileName;

            grid.setImageUrl(ImgURL);

            new GridDao().saveGrid(grid);

            return SUCCESS;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ERROR;

}

public String editGrid() {
    try {
        String resultUpload = saveImage();
        if (resultUpload.equalsIgnoreCase("success")) {

            String address = Inet4Address.getLocalHost().getHostAddress();

            ImgURL = "http://" + address + ":8080/PngAppWebApp/temp/"
                    + fileUploadFileName;

            grid.setImageUrl(getImgURL());

            new GridDao().editGrid(grid);
            return SUCCESS;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ERROR;
}

public String saveImage() throws IOException {

    try {

        ServletContext servletContext = ServletActionContext
                .getServletContext();
        String path = servletContext.getRealPath("/temp");
        System.out.println("Server path:" + path);
        String filePath = servletContext.getRealPath(path);
        System.out.println("path:" + filePath);
        File uploadDir = new File(filePath, fileUploadFileName);
        // if the folder does not exits, creating it
        if (uploadDir.exists() == false) {
            uploadDir.mkdirs();
        }
        File destFile = new File(path, fileUploadFileName);
        FileUtils.copyFile(fileUpload, destFile);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return ERROR;
    }
    return SUCCESS;
}

public String listGrid() {
    try {
        listGrid = new GridDao().listGrid();
        System.out.println("you are in ListUser");
        return SUCCESS;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ERROR;
}

public String preprEditGrid() {
    try {

        grid = new GridDao().preprEditGrid(grid);
        System.out.println("you are in editUser" + grid);
        return SUCCESS;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ERROR;
}

public String deleteGrid() {
    try {
        new GridDao().deleteGrid(grid);
        return SUCCESS;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return ERROR;

}

public List<Grid> getListGrid() {
    return listGrid;
}

public void setListGrid(List<Grid> listGrid) {
    this.listGrid = listGrid;
}

public Grid getGrid() {
    return grid;
}

public void setGrid(Grid grid) {
    this.grid = grid;
}

public File getFileUpload() {
    return fileUpload;
}

public void setFileUpload(File fileUpload) {
    this.fileUpload = fileUpload;
}

public String getFileUploadContentType() {
    return fileUploadContentType;
}

public void setFileUploadContentType(String fileUploadContentType) {
    this.fileUploadContentType = fileUploadContentType;
}

public String getFileUploadFileName() {
    return fileUploadFileName;
}

public void setFileUploadFileName(String fileUploadFileName) {
    this.fileUploadFileName = fileUploadFileName;
}

public String getImgURL() {
    return ImgURL;
}

public void setImgURL(String imgURL) {
    ImgURL = imgURL;
}

}

Comment: I've removed your request to treat this urgently, for a second time. Please remember that all questions here are answered by volunteers, and that no question is more important than another.
Answer: After the image is uploaded it's removed from the disk by Struts2.
When the image is stored to database it could be retrieved by the action for displaying purposes.
The image URL should be mapped to the action that returns an image via stream result. Make sure you specify the image/* content type properly.
Comment: but i had save the path in database ... after deploying the project on server its give the  problem (not display images on client machine )
Comment: After uploading an image it's destroyed from the disk. You have to copy the file to the folder from which you can serve the image.