Q: How to insert special HTML-symbols with HAML When I'm saying:
%p= item.price + " dollars"

I'm getting

50&nbsp ;dollars

instead of having non-breakable space symbol.
How to insert this and another special symbols using HAML ?

A: How about
%p= item.price + " dollars".html_safe

A: This answer is for a slightly different question but I found this question searching for it...
If you have a submit tag %input{ :type => "submit", :value => " dollars", :name => "very_contrived" } even if you throw an html_safe on the :value it will not evaluate the html.
The solution is to use the rails helper... duh
= submit_tag " dollars".html_safe

this is pretty obvious but it tripped me up.  Legacy code + rails upgrade = this kind of stuff :P

A: Use != instead of =
See "Unescaping HTML" in the haml reference: http://haml.info/docs/yardoc/file.REFERENCE.html#unescaping_html

A: The interpolation option:
%p= "#{item.price} dollars".html_safe

A: I tried using html_safe in different ways, but none worked. Using \xa0 as suggested by ngn didn't work, either, but it got me to try the Unicode escape of the non-breaking space, which did work:
"FOO\u00a0BAR"

and .html_safe isn't even needed (unless something else in the string needs that, of course).
The Ruby Programming Language, first edition, says: "In Ruby 1.9, double-quoted strings can include arbitrary Unicode escape characters with \u escapes.  In its simplest form, \u is followed by exactly four hexadecimal digits ..."

A: You could use \xa0 in the string instead of  .  0xa0 is the ASCII code of the non-breaking space.

A: I prefer using the character itself with the escaped HTML method with most symbols other than the whitespace characters. That way i don't have to remember all the html codes. As for the whitespace characters i prefer to use CSS, this is a much cleaner way.
%p&= "#{item.price} $%&#*@"


Q: Trying to replace values in a data frame with other values I have a list of vectors, L1, and a data frame, df2. I want to take values from df2 and replace the values of L1 with these. For example, when ABCC10 of L1 says "TCGA_DD_A1EG", I want to replace this with the value, 2.193205, from row 1 (ABCC10), column 3 (TCGA.DD.A1EG). I want to do this with every value.
L1 looks like this:
$ABCC10
[1] "TCGA_DD_A1EG" "TCGA_FV_A3R2" "TCGA_FV_A3I0" "TCGA_DD_A1EH" "TCGA_FV_A23B"

$ACBD6
[1] "TCGA_DD_A1EH" "TCGA_DD_A3A8" "TCGA_ES_A2HT" "TCGA_DD_A1EG" "TCGA_DD_A1EB"

df2 looks like this:
       TCGA.BC.A10Q TCGA.DD.A1EB TCGA.DD.A1EG TCGA.DD.A1EH TCGA.DD.A1EI TCGA.DD.A3A6 TCGA.DD.A3A8
ABCC10     2.540764    0.4372165     2.193205     3.265756    0.6060301     2.927072    0.6799514
ACBD6      1.112432    0.4611697     1.274129     1.802985   -0.0475743     1.071064    0.4336301
       TCGA.ES.A2HT TCGA.FV.A23B TCGA.FV.A3I0 TCGA.FV.A3R2
ABCC10  -0.08129554    2.2963764     3.196518    0.8595943
ACBD6    1.76935812    0.3644397     1.392206    1.0282030

A: One approach could be like
df1 = list(ABCC10 = c("TCGA_DD_A1EG", "TCGA_FV_A3R2", "TCGA_FV_A3I0", "TCGA_DD_A1EH", "TCGA_FV_A23B"),
           ACBD6 = c("TCGA_DD_A1EH", "TCGA_DD_A3A8", "TCGA_ES_A2HT", "TCGA_DD_A1EG", "TCGA_DD_A1EB"))

df2 = data.frame(TCGA.BC.A10Q = c(2.540764, 1.112432),
                 TCGA.DD.A1EB = c(0.4372165, 0.4611697),
                 TCGA.DD.A1EG = c(2.193205, 1.274129),
                 TCGA.DD.A1EH = c(3.265756, 1.802985),
                 TCGA.DD.A1EI = c(0.6060301, -0.0475743),
                 TCGA.DD.A3A6 = c(2.927072, 1.071064),
                 TCGA.DD.A3A8 = c(0.6799514, 0.4336301),
                 TCGA.ES.A2HT = c(-0.08129554, 1.76935812),
                 TCGA.FV.A23B = c(2.2963764, 0.3644397),
                 TCGA.FV.A3I0 = c(3.196518, 1.392206),
                 TCGA.FV.A3R2 = c(0.8595943, 1.0282030),
                 row.names = c('ABCC10', 'ACBD6'))

for(i in 1:length(df1)){
  for(j in 1:length(df1[[1]])){
    df1[names(df1)[i]][[1]][j] = df2[names(df1)[i],gsub("_",".",df1[names(df1)[i]][[1]][j])]
  }
}

Output is:
$ABCC10
[1] "2.193205"  "0.8595943" "3.196518"  "3.265756"  "2.2963764"

$ACBD6
[1] "1.802985"   "0.4336301"  "1.76935812" "1.274129"   "0.4611697"

Hope this helps!

A: Maybe the following will do it.
First, make up some data, a list and a data.frame.
df1 <- list(A = letters[1:3], B = letters[5:7])

df2 <- data.frame(a = rnorm(2), b = rnorm(2), c = rnorm(2),
                  e = rnorm(2), f = rnorm(2), g = rnorm(2))
row.names(df2) <- c('A', 'B')

Now the code.
for(i in seq_along(df1)){
    x <- gsub("_", ".", df1[[i]])
    inx <- match(x, names(df2))
    df1[[i]] <- df2[i, inx]
}
df1

In my tests it did what you want. If it doesn't fit your real problem, just say so.


Q: Binding value in JSP page I have a XML value in controller and i'm passing that value to jsp page and binding as shown in the below code.
 <input type="hidden" id="thisField" name="inputName" value='${xml}'/>

It is binding the value as shown in the below.
 <input type="hidden" id="thisField" name="inputName" value='
    <?xml version="1.0" encoding="UTF-8"?>
    <Esign AuthMode="1" aspId="ASPRBLBMUMTEST043" ekycId="448988431774" ekycIdType="A" ekycMode="U" organizationFlag="N" preVerified="n" responseSigType="pkcs7" responseUrl="http://10.80.49.41" sc="Y" ts="2018-01-19T11:42:55" txn="UKC:eSign:6539:20180119114250963" ver="2.0">
        <Docs>
            <InputHash docInfo="Signing pdf" hashAlgorithm="SHA256" id="1">30e3ed7f512da50206b8720d52457309c87f4edfee85d08f937aef3f955fb7af</InputHash>
        </Docs>
        <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
            <SignedInfo>
                <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
                <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
                <Reference URI="">
                    <Transforms>
                        <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
                    </Transforms>
                    <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
                    <DigestValue>kQEB9r4dd5hhdaPxc4sjPMG3SGM=</DigestValue>
                </Reference>
            </SignedInfo>
            <SignatureValue>MSgEXK2+GpwnRBr3vLNncqc9FOY0oDhjlhfyihOjrUPFZAL8eBms6jXdhoWGlrypaF6hE70ZltDQbQTArrk/mfCmoVvna7yEJN9gDh6gAHbh9Zj4BEBdWhd85DKbAdtSy8zYTKIeIjhFBzOItUAhSN7lFrEFVrTLV5wO38hswD7LlaY4ZBSNMWbpHPx+Io6ukdP8b4n95dqoB9iiqKxg3nK0RslhLRcPoe4B2AsdoiZ42iY/tZ4disOzyOCyCdE8nRxipJbP9HZS3psCSCar3CPSigXiNk6fY7+bDEFbJrfoqhHBk1hasx2m0TbxZVeOIPSUPRYpekHCm0sm4RvZhA==</SignatureValue>
            <KeyInfo>
                <X509Data>
                    <X509SubjectName>CN=AAA Bank Test,OU=AAA Bank IT Dept,O=AAA Bank,L=Delhi,ST=Delhi,C=91</X509SubjectName>
                    <X509Certificate>MIIDkTCCAnmgAwIBAgIEZNl4CjANBgkqhkiG9w0BAQsFADB5MQswCQYDVQQGEwI5MTETMBEGA1UECBMKTWFoYXJhc3RyYTEPMA0GA1UEBxMGTXVtYmFpMREwDwYDVQQKEwhSYmwgQmFuazEZMBcGA1UECxMQUkJMIEJhbmsgSVQgRGVwdDEWMBQGA1UEAxMNUmJsIEJhbmsgVGVzdDAeFw0xNzAzMDIxNDA4MTBaFw0xODAyMjUxNDA4MTBaMHkxCzAJBgNVBAYTAjkxMRMwEQYDVQQIEwpNYWhhcmFzdHJhMQ8wDQYDVQQHEwZNdW1iYWkxETAPBgNVBAoTCFJibCBCYW5rMRkwFwYDVQQLExBSQkwgQmFuayBJVCBEZXB0MRYwFAYDVQQDEw1SYmwgQmFuayBUZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsjsF71lv96Y+2DbuSgk1U/Bp3P+jPpKp9GpwiVuIAf4SsBc1bqR3x4JSnY4COdUlq2IkHYSGnufGkPS6tH4edoFpZrSBAiTo1D0WQQ4KoRWBzn9xptMGsJBoV7dcSovjjD1HhUJGNnfoxjBh3AmIe8ZySWhuouEA8cRtFcHoWunpSB1FOJreIZ1P/ZnJ7C4gu+E1ccXjkFPqCGI9RcdUSE72K+ovtI/yWIUPwXdj3O/k30iX2owxUVFKnCmIDFnKDJ/b96RDzlIB9FiH5IVQm4mcU6HiQKqknDI3bPKlwvfFfB+YI69vjRQf3dvsca2nZQsYT3iSgkxBwoiugsD59QIDAQABoyEwHzAdBgNVHQ4EFgQUwFYILDVGVtIJgYveFqZ9YRrRq4AwDQYJKoZIhvcNAQELBQADggEBAKygyzVE1sOaBxuj4IjGDmo2y5UOhPOzklRocZbsqycEApcBn5m/dVauvewqw7An1vrkvjTYbTUCjUKghNW/MdtiWbKKRDy3fA8DyEACcYuK0PpaaXMTJFjIjKxXko6Rmmp6CKFcmERgetiwrFreMfFjvCv9H1fk7FSR87d/17l/LsmAndFIvpZTF3Ruz4lZsoL2qWtBF+wnVjFW+yqf6nXDqE/Swxhiq7dZ+Dl0ilgEsh3Q1WOO/S/TBDkeURIHfIkc886p5M4u5iQdkO1fndptUhBNbaM1idMOW/5QUWFeIEChdSo3mrVVTWyvhQEkYls0GYJUSVSdaITcyE3xkJA=</X509Certificate>
                </X509Data>
            </KeyInfo>
        </Signature>
    </Esign>'/>

But i want to bind like below without spaces.
<input type="hidden" id="thisField" name="inputName" value='<?xml version="1.0" encoding="UTF-8"?><Esign AuthMode="1" aspId="ASPRBLBMUMTEST043" ekycId="448988431774" ekycIdType="A" ekycMode="U" organizationFlag="N" preVerified="n" responseSigType="pkcs7" responseUrl="http://10.80.49.41" sc="Y" ts="2018-01-19T11:42:55" txn="UKC:eSign:6539:20180119114250963" ver="2.0"><Docs><InputHash docInfo="Signing pdf" hashAlgorithm="SHA256" id="1">30e3ed7f512da50206b8720d52457309c87f4edfee85d08f937aef3f955fb7af</InputHash></Docs><Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/><Reference URI=""><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><DigestValue>kQEB9r4dd5hhdaPxc4sjPMG3SGM=</DigestValue></Reference></SignedInfo><SignatureValue>MSgEXK2+GpwnRBr3vLNncqc9FOY0oDhjlhfyihOjrUPFZAL8eBms6jXdhoWGlrypaF6hE70ZltDQbQTArrk/mfCmoVvna7yEJN9gDh6gAHbh9Zj4BEBdWhd85DKbAdtSy8zYTKIeIjhFBzOItUAhSN7lFrEFVrTLV5wO38hswD7LlaY4ZBSNMWbpHPx+Io6ukdP8b4n95dqoB9iiqKxg3nK0RslhLRcPoe4B2AsdoiZ42iY/tZ4disOzyOCyCdE8nRxipJbP9HZS3psCSCar3CPSigXiNk6fY7+bDEFbJrfoqhHBk1hasx2m0TbxZVeOIPSUPRYpekHCm0sm4RvZhA==</SignatureValue><KeyInfo><X509Data><X509SubjectName>CN=Rbl Bank Test,OU=AAA Bank IT Dept,O=AAA Bank,L=Delhi,ST=Delhi,C=91</X509SubjectName><X509Certificate>MIIDkTCCAnmgAwIBAgIEZNl4CjANBgkqhkiG9w0BAQsFADB5MQswCQYDVQQGEwI5MTETMBEGA1UECBMKTWFoYXJhc3RyYTEPMA0GA1UEBxMGTXVtYmFpMREwDwYDVQQKEwhSYmwgQmFuazEZMBcGA1UECxMQUkJMIEJhbmsgSVQgRGVwdDEWMBQGA1UEAxMNUmJsIEJhbmsgVGVzdDAeFw0xNzAzMDIxNDA4MTBaFw0xODAyMjUxNDA4MTBaMHkxCzAJBgNVBAYTAjkxMRMwEQYDVQQIEwpNYWhhcmFzdHJhMQ8wDQYDVQQHEwZNdW1iYWkxETAPBgNVBAoTCFJibCBCYW5rMRkwFwYDVQQLExBSQkwgQmFuayBJVCBEZXB0MRYwFAYDVQQDEw1SYmwgQmFuayBUZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsjsF71lv96Y+2DbuSgk1U/Bp3P+jPpKp9GpwiVuIAf4SsBc1bqR3x4JSnY4COdUlq2IkHYSGnufGkPS6tH4edoFpZrSBAiTo1D0WQQ4KoRWBzn9xptMGsJBoV7dcSovjjD1HhUJGNnfoxjBh3AmIe8ZySWhuouEA8cRtFcHoWunpSB1FOJreIZ1P/ZnJ7C4gu+E1ccXjkFPqCGI9RcdUSE72K+ovtI/yWIUPwXdj3O/k30iX2owxUVFKnCmIDFnKDJ/b96RDzlIB9FiH5IVQm4mcU6HiQKqknDI3bPKlwvfFfB+YI69vjRQf3dvsca2nZQsYT3iSgkxBwoiugsD59QIDAQABoyEwHzAdBgNVHQ4EFgQUwFYILDVGVtIJgYveFqZ9YRrRq4AwDQYJKoZIhvcNAQELBQADggEBAKygyzVE1sOaBxuj4IjGDmo2y5UOhPOzklRocZbsqycEApcBn5m/dVauvewqw7An1vrkvjTYbTUCjUKghNW/MdtiWbKKRDy3fA8DyEACcYuK0PpaaXMTJFjIjKxXko6Rmmp6CKFcmERgetiwrFreMfFjvCv9H1fk7FSR87d/17l/LsmAndFIvpZTF3Ruz4lZsoL2qWtBF+wnVjFW+yqf6nXDqE/Swxhiq7dZ+Dl0ilgEsh3Q1WOO/S/TBDkeURIHfIkc886p5M4u5iQdkO1fndptUhBNbaM1idMOW/5QUWFeIEChdSo3mrVVTWyvhQEkYls0GYJUSVSdaITcyE3xkJA=</X509Certificate></X509Data></KeyInfo></Signature></Esign>'/>

Is there any way to bind like as shown in the above?

A: You can perform a manipulation of the xml string in your controller with a little regex to eliminate the newlines and whitespace.
Here is a little java app to show the regex in work against your xml string.
public class StripXmlWhitespace {

       public static void main (String [] args) {
           String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "    <Esign AuthMode=\"1\" aspId=\"ASPRBLBMUMTEST043\" ekycId=\"448988431774\" ekycIdType=\"A\" ekycMode=\"U\" organizationFlag=\"N\" preVerified=\"n\" responseSigType=\"pkcs7\" responseUrl=\"http://10.80.49.41\" sc=\"Y\" ts=\"2018-01-19T11:42:55\" txn=\"UKC:eSign:6539:20180119114250963\" ver=\"2.0\">\n" +
                "        <Docs>\n" +
                "            <InputHash docInfo=\"Signing pdf\" hashAlgorithm=\"SHA256\" id=\"1\">30e3ed7f512da50206b8720d52457309c87f4edfee85d08f937aef3f955fb7af</InputHash>\n" +
                "        </Docs>\n" +
                "        <Signature xmlns=\"http://www.w3.org/2000/09/xmldsig#\">\n" +
                "            <SignedInfo>\n" +
                "                <CanonicalizationMethod Algorithm=\"http://www.w3.org/TR/2001/REC-xml-c14n-20010315\"/>\n" +
                "                <SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"/>\n" +
                "                <Reference URI=\"\">\n" +
                "                    <Transforms>\n" +
                "                        <Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\"/>\n" +
                "                    </Transforms>\n" +
                "                    <DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"/>\n" +
                "                    <DigestValue>kQEB9r4dd5hhdaPxc4sjPMG3SGM=</DigestValue>\n" +
                "                </Reference>\n" +
                "            </SignedInfo>\n" +
                "            <SignatureValue>MSgEXK2+GpwnRBr3vLNncqc9FOY0oDhjlhfyihOjrUPFZAL8eBms6jXdhoWGlrypaF6hE70ZltDQbQTArrk/mfCmoVvna7yEJN9gDh6gAHbh9Zj4BEBdWhd85DKbAdtSy8zYTKIeIjhFBzOItUAhSN7lFrEFVrTLV5wO38hswD7LlaY4ZBSNMWbpHPx+Io6ukdP8b4n95dqoB9iiqKxg3nK0RslhLRcPoe4B2AsdoiZ42iY/tZ4disOzyOCyCdE8nRxipJbP9HZS3psCSCar3CPSigXiNk6fY7+bDEFbJrfoqhHBk1hasx2m0TbxZVeOIPSUPRYpekHCm0sm4RvZhA==</SignatureValue>\n" +
                "            <KeyInfo>\n" +
                "                <X509Data>\n" +
                "                    <X509SubjectName>CN=AAA Bank Test,OU=AAA Bank IT Dept,O=AAA Bank,L=Delhi,ST=Delhi,C=91</X509SubjectName>\n" +
                "                    <X509Certificate>MIIDkTCCAnmgAwIBAgIEZNl4CjANBgkqhkiG9w0BAQsFADB5MQswCQYDVQQGEwI5MTETMBEGA1UECBMKTWFoYXJhc3RyYTEPMA0GA1UEBxMGTXVtYmFpMREwDwYDVQQKEwhSYmwgQmFuazEZMBcGA1UECxMQUkJMIEJhbmsgSVQgRGVwdDEWMBQGA1UEAxMNUmJsIEJhbmsgVGVzdDAeFw0xNzAzMDIxNDA4MTBaFw0xODAyMjUxNDA4MTBaMHkxCzAJBgNVBAYTAjkxMRMwEQYDVQQIEwpNYWhhcmFzdHJhMQ8wDQYDVQQHEwZNdW1iYWkxETAPBgNVBAoTCFJibCBCYW5rMRkwFwYDVQQLExBSQkwgQmFuayBJVCBEZXB0MRYwFAYDVQQDEw1SYmwgQmFuayBUZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsjsF71lv96Y+2DbuSgk1U/Bp3P+jPpKp9GpwiVuIAf4SsBc1bqR3x4JSnY4COdUlq2IkHYSGnufGkPS6tH4edoFpZrSBAiTo1D0WQQ4KoRWBzn9xptMGsJBoV7dcSovjjD1HhUJGNnfoxjBh3AmIe8ZySWhuouEA8cRtFcHoWunpSB1FOJreIZ1P/ZnJ7C4gu+E1ccXjkFPqCGI9RcdUSE72K+ovtI/yWIUPwXdj3O/k30iX2owxUVFKnCmIDFnKDJ/b96RDzlIB9FiH5IVQm4mcU6HiQKqknDI3bPKlwvfFfB+YI69vjRQf3dvsca2nZQsYT3iSgkxBwoiugsD59QIDAQABoyEwHzAdBgNVHQ4EFgQUwFYILDVGVtIJgYveFqZ9YRrRq4AwDQYJKoZIhvcNAQELBQADggEBAKygyzVE1sOaBxuj4IjGDmo2y5UOhPOzklRocZbsqycEApcBn5m/dVauvewqw7An1vrkvjTYbTUCjUKghNW/MdtiWbKKRDy3fA8DyEACcYuK0PpaaXMTJFjIjKxXko6Rmmp6CKFcmERgetiwrFreMfFjvCv9H1fk7FSR87d/17l/LsmAndFIvpZTF3Ruz4lZsoL2qWtBF+wnVjFW+yqf6nXDqE/Swxhiq7dZ+Dl0ilgEsh3Q1WOO/S/TBDkeURIHfIkc886p5M4u5iQdkO1fndptUhBNbaM1idMOW/5QUWFeIEChdSo3mrVVTWyvhQEkYls0GYJUSVSdaITcyE3xkJA=</X509Certificate>\n" +
                "                </X509Data>\n" +
                "            </KeyInfo>\n" +
                "        </Signature>\n" +
                "    </Esign>";
           String output = xmlString.replaceAll(">\\s+<", "><");
           System.out.println(xmlString);
           System.out.println(output);

       }

}

All you need in your controller is the regex.
xml = xmlString.replaceAll(">\\s+<", "><");

Essentially unformat the xml before you send it bind it to the view.  I hope that helps.


Q: REGEX to extract multiple name/value tokens (vbscript) Given a template that looks like this:
{*}Street Address:

     ^^ might be a space here, might not        ^^ always a space here

I need to read the name=value pairs out of the comment, plus the whole string so it can be replaced. Names could be any alpha-numeric with no spaces, values could contain anything except double quotes, will be short as possible, and will always be surrounded by double-quotes.
So, possible formats:

I've tried a dozen different variations, but the most successful I've been so far is to get the first name="value" pair and nothing else, or I get the whole page worth of stuff. So the desired matches are
[1]
[2] drinks
[3] yes, please
[4] breadsticks
[5] garlic, butter (lots); cheese

The closest I've come so far is

but it only returns the last pair, not all of them.

A: Implementation of the 2 step processes @sln mentioned in VBScript:
Option Explicit

Dim rCmt : Set rCmt = New RegExp
rCmt.Global = True
rCmt.Pattern = ""
Dim rKVP : Set rKVP = New RegExp
rKVP.Global = True
rKVP.Pattern = "(\w+)=""([^""]*)"""
Dim sInp : sInp = Join(Array( _
    "{*}Street Address:	" _
  , "" _
  , "" _
 , "	" _
 , "" _
), vbCrLf)

WScript.Echo sInp
WScript.Echo "-----------------"
WScript.Echo rCmt.Replace(sInp, GetRef("fnRepl"))
WScript.Quit 0

Function fnRepl(sMatch, nPos, sSrc)
  Dim d : Set d = CreateObject("Scripting.Dictionary")
  Dim ms : Set ms = rKVP.Execute(sMatch)
  Dim m
  For Each m In ms
      d(m.SubMatches(0)) = m.SubMatches(1)
  Next
  fnRepl = "a comment containing " & Join(d.Keys)
End Function

output:
cscript 45200777-2.vbs
{*}Street Address:

-----------------
{*}Street Address:

a comment containing template for prev

a comment containing pipapo rof prev

As Mr. Gates Doc for the .Replace method sucks, see 1, 2, 3.


Q: find out what instructions write to this memory address olly dbg cheat engine Is there an option in ollydbg to find out what pieces of code write to a memory address ? Just like Cheat Engine shows all the assembly instructions that write to a specific address.
"breakpoint --> memory" does not work.

A: Yes,
With olly open and debugging a certain program, go to View tab>Memory or Alt+M
then, find the memory address (first you have to choose the memory part of the program like .data or .bss) and then click on the address (or addresses selecting multiple with Shift) with the right mouse button and hover to Breakpoint then you'll be able to choose the to break the program when it writes or reads the address
A good thing to do is first find the address on cheatEngine then use the breakpoint on ollydbg.


Q: setNeedsDisplay not resulting in dirtyRect filling entire view I am having a confusing issue.  I try to draw a graph, and call setNeedsDisplay each time new data is added to the graph.
The graph receives new data via addData:(NSNotification*)theNote, which then tries several ways to call setNeedsDisplay to redraw the view.  The data does not get redrawn properly, however, at this time.  If I drag the window to another screen, or if I click on the graph and call setNeedsDisplay from mouseDown then the view is redrawn correctly.  By monitoring the size of dirtyRect using NSLog, I have tracked the problem to a too small dirtyRect.  But I cannot even guess how to correct this.  Any ideas out there?
//
//  graphView.m
//  miniMRTOF
//
//  Created by シューリ ピーター on 8/1/16.
//  Copyright © 2016 シューリ ピーター. All rights reserved.
//

#import "graphView.h"

@implementation graphView

- (id)initWithFrame:(NSRect)frame{
    self = [super initWithFrame:frame];
    if (self) {

        NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
        [nc addObserver:self selector:@selector(addData:) name:AddDataNotification object:nil];

        theData = [[NSMutableArray alloc] init];

        NSLog(@"graphView initialized");

    }
    return self;
}

-(void)addData:(NSNotification*)theNote{
    NSLog(@"graphView has gotten the note");

    NSMutableArray *theThermalArray = [[NSMutableArray alloc] init];

    theThermalArray = [[theNote userInfo] objectForKey:@"theThermals"];
    float ave = 0;
    int n = 0;
    for (int i=0; i<16; i++){
        float f_i = [[theThermalArray objectAtIndex:i] floatValue];
        ave += f_i;
        if(f_i != 0) n++;
    }
    ave /= n;

    [theData addObject:[NSNumber numberWithFloat:ave]];
    NSLog(@"graphView has added %0.3f and now has %lu components", ave, (unsigned long)[theData count]);
    [self setNeedsDisplay:YES];
    [[self.window contentView] setNeedsDisplay:YES];
    [self performSelectorOnMainThread:@selector(redraw) withObject:nil waitUntilDone:YES];
}

-(void)redraw{
    [self setNeedsDisplay:YES];
    [[self.window contentView] setNeedsDisplay:YES];

}

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];
    // Drawing code here.

    NSLog(@"dirtyRect: x:%0.2f, y:%0.2f, w:%0.2f, h:%0.2f", dirtyRect.origin.x, dirtyRect.origin.y, dirtyRect.size.width, dirtyRect.size.height);

    float xScale = ([self bounds].size.width)/((float)[theData count]+1e-3);//(maxX - minX);
    float yScale = [self bounds].size.height/(maxT - minT);

    [[NSColor whiteColor] set];
    NSRect fillArea = [self bounds];
    [NSBezierPath fillRect:fillArea];

    if(dirtyRect.size.height < 100){
        NSLog(@"small dirtyRect");
        [[NSColor grayColor] set];
        [NSBezierPath fillRect:dirtyRect];
    }
    dirtyRect = [self bounds];

    int dataCount = (int)[theData count];

    NSBezierPath *pathForFrame = [[NSBezierPath alloc] init];

    NSPoint P0 = {1,1};
    NSPoint P1 = {1, [self bounds].size.height};
    NSPoint P2 = {[self bounds].size.width, 1};

    [pathForFrame moveToPoint:P0];
    [pathForFrame lineToPoint:P1];
    [pathForFrame moveToPoint:P0];
    [pathForFrame lineToPoint:P2];

    [[NSColor redColor] set];
    [pathForFrame stroke];

    NSLog(@"drawing %i points", dataCount);

    NSBezierPath *pathForPlot = [[NSBezierPath alloc] init];
    if(dataCount<maxRawPlotData){
        if(dataCount>1){

            NSPoint p1;
            p1.y = [[theData objectAtIndex:0] floatValue];
            p1.x = (0-minX)*xScale;
            p1.y = (p1.y-minT)*yScale;
            [pathForPlot moveToPoint:p1];
            NSLog(@"point: %0.1f, %0.1f", p1.x, p1.y);
        }
        for(int i=1; i<dataCount; i++){

            NSPoint p;
            p.y = [[theData objectAtIndex:i] floatValue];
            p.x = (i-minX)*xScale;
            p.y = (p.y-minT)*yScale;
            [pathForPlot lineToPoint:p];
            NSLog(@"point: %0.1f, %0.1f", p.x, p.y);
        }
    }

    [[NSColor blackColor] set];
    [pathForPlot stroke];

    [txtMaxX setStringValue:[NSString stringWithFormat:@"%0.0f",maxX]];

}

-(void)controlTextDidEndEditing:(NSNotification *)obj{
    NSLog(@"controlTextDidEndEditing");
    if([[obj object] isEqualTo:txtMaxT]){
        maxT = [txtMaxT floatValue];
        [txtMidT setStringValue:[NSString stringWithFormat:@"%0.1f",0.5*(maxT+minT)]];
    }
    else if([[obj object] isEqualTo:txtMinT]){
        minT = [txtMinT floatValue];
        [txtMidT setStringValue:[NSString stringWithFormat:@"%0.1f",0.5*(maxT+minT)]];
    }
    else if([[obj object] isEqualTo:txtMaxX]){
        maxX = [txtMaxX floatValue];
    }
    else if([[obj object] isEqualTo:txtMinX]){
        minX = [txtMinX floatValue];
    }
    else NSLog(@"How'd we get here?");

    [[[obj object] window] makeFirstResponder:[[obj object] window].contentView];
    [self setNeedsDisplay:YES];
    [self display];
}

-(void)mouseDown:(NSEvent *)theEvent{
    NSLog(@"mousedown");
    [self setNeedsDisplay:YES];
}

@end


Q: Do eggs expire in Pokémon Go? I've been holding on to some eggs, waiting to get an incubator at level 25.  I thought I was sitting on two 10 km eggs. When I finally reached level 25, I noticed I only had one 10 km egg.
Was I mistaken about my eggs, or do eggs expire?

A: Eggs do not expire. Once you have 9 eggs, they will remain until one of them hatches through an incubator. Only then can you get a new one.
I'm guessing either:

*

*you hatched the egg and maybe don't remember hatching it since you got a new one (I personally don't always notice when I get a new one through pokestops if I get many objects during at that pokestop).

*There is a glitch and the 10km one got replaced?

However there is probably no fix for this, you're stuck with the eggs you have until you hatch them.
To answer your question: no, eggs don't expire.

A: It may be that the Egg which you are missing wasn't completely logged by the server. This has happened before with a few people I know who have GO.


Q: JIRA Xray Cloud - Import Execution Results using REST API Hi I am using JIRA Cloud and trying to import execution result using REST API.
End Point URL - https://xray.cloud.getxray.app/api/v1/import/execution
Request Type - POST
Content-Type - application/json
Authorization: Bearer ""
Body -
{
"info" : {
"project": "QAUT",
"summary" : "Execution of automated tests using UFT",
"description" : "This execution is automatically created when importing execution results from UFT",
"startDate" : "2022-09-19T11:47:35+01:00",
"finishDate" : "2022-09-19T11:53:00+01:00",
"testPlanKey" : "QAUT-1"
},
"tests" : [
{
"testKey" : "QAUT-3",
"start" : "2022-09-19T11:47:35+01:00",
"finish" : "2022-09-19T11:50:56+01:00",
"actualResult" : "Successful execution",
"status" : "PASSED"
}
]
}
I am getting below errors:
Response code - 400
Response Body -
{
"error": "Result is not valid Xray Format"
}


Q: Unexpected behavior Using React useState, Very strange output I am a newbie in React. I was experimenting around to see how things work,
and I found a very strange Behavior of React or useState whatever you want to call it.
Please, Someone, explain, what is going on and how this piece of coding is working.

const {useState} = React;

let referceGiver = 0;
function giveNewRef() {
  let a = referceGiver;
  console.log("Making New Reference | Ref = ", a);
  referceGiver++;
  return a;
}

function App() {
  let v = "10";
  console.log("%cIniside Function", "background-color:red", `| v = ${v}`);

  let [val, setVal] = useState('30');

  const currentReference = giveNewRef();
  console.log("Outer Function Reference = ", currentReference)

  console.log("Value of UseState Val = ", val);

  function clicked() {
    v += ' 20';
    console.log("Inner Function Reference = ", currentReference);
    console.log("Value of V = ", v);
    setVal(v);
  }
  console.log("%cGoing To Return", "background-color:green");
  console.log('-----------------------------')

  return (

{val + " " + Math.random()}

      <button onClick={clicked} > Click </button>

  );
}

ReactDOM.render(<App/>, document.querySelector('#mount'));

Output of the above code
Tell me why:

*

*inner and outer reference is different

*useState does not change 2 times but changes a third time

*giveNewRef() increasing value by 2


Q: Changing the shape of a new assigned variable in Tensorflow if you change a tf.Variable using tf.assign with validate_shape=False the shape is not updated.
But if I use set_shape to set the new (correct) shape I get a ValueError.
Here a quick example:
import tensorflow as tf

a = tf.Variable([3,3,3])

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    # [3 3 3]
    print(sess.run(a))

    sess.run(tf.assign(a, [4,4,4,4], validate_shape=False))
    # [4 4 4 4]
    print(sess.run(a))

# (3,)
print(a.get_shape())

# ValueError: Dimension 0 in both shapes must be equal, but are 3 and 4. Shapes are [3] and [4].
a.set_shape([4])

How do I change the shape of the Variable?
Note: I am aware that the code works if I use a = tf.Variable([3,3,3], validate_shape=False) but in my context I will not be able to initialize the variable myself.

A: Tell the static part of the graph that the shape is unknown from the start as well.
a = tf.Variable([3,3,3], validate_shape=False)

Now, to get the shape, you cannot know statically, so you have to ask the session, which makes perfect sense:
print(sess.run(tf.shape(a)))


Q: How to remove backup logs on application startup I have a RotatingFileHandler with mode=w, maxBytes=20000000 and backupCount=10 as shown below:
[loggers]
keys=root

[logger_root]
level=INFO
handlers=file

[formatters]
keys=simple

[formatter_simple]
format=[%(levelname)s] %(asctime)s : %(name)s - %(message)s
datefmt=%H:%M:%s

[handlers]
keys=file

[handler_file]
class=handlers.RotatingFileHandler
formatter=simple
level=INFO
args=(log_directory,'w', 20000000, 10)

This means that after a period of time, 11 distinct log files will be present ( test.log, test.log.1, ..., test.log.10 ). My requirement is when the application is started, I want to delete all of the backup log files (test.log.1, ..., test.log.10). The content of test.log (current) log file will be removed anyway because mode is set to w.

A: That task is not under logging scope, you should "manually" delete them upon application start. Use os or shutil.


Q: How to debug Spring Cloud Kubernetes Configuration Watcher when it is not working as expectted There are two components in my k8s namespace.

*

*The first component is a simple Spring Boot Web Service with actuator/refresh endpoint exposed. I have mannualy make post request to the endpoint and it will trigger a configuration context refresh succesfully.

*The second component is Spring Cloud Kubernetes Configuration Watcher which I pull the image per official document guidance and make it run in my k8s env. Per official spring document, it should detect the changes on configmap with label spring.cloud.kubernetes.config="true" and make post request to the actuator/refresh endpoint of the application whose spring.application.name is equal to the configmap name.
The second component is not working as expectted, and I don't know how to trouble shoot the root cause.
My Springboot application is called spring-boot-demo, the configmap is also named as spring-boot-demo. But I never find any mentions of "spring-boot-demo" in Spring Cloud Kubernetes Configuration Watcher's log and nor can I assure if it has sent post request to related endpoint.
I can only see the logs showed up repeatedly below:
2021-11-22 02:58:53.332  INFO 1 --- [192.168.0.1/...] .w.HttpBasedConfigMapWatchChangeDetector : Added new Kubernetes watch: config-maps-watch-event
2021-11-22 02:58:53.332  INFO 1 --- [192.168.0.1/...] .w.HttpBasedConfigMapWatchChangeDetector : Kubernetes event-based configMap change detector activated
2021-11-22 03:34:06.555  WARN 1 --- [192.168.0.1/...] .f.c.r.EventBasedConfigMapChangeDetector : ConfigMaps watch closed

io.fabric8.kubernetes.client.WatcherException: too old resource version: 5491278743 (5554041906)
        at io.fabric8.kubernetes.client.dsl.internal.AbstractWatchManager.onStatus(AbstractWatchManager.java:263) [kubernetes-client-5.5.0.jar:na]
        at io.fabric8.kubernetes.client.dsl.internal.AbstractWatchManager.onMessage(AbstractWatchManager.java:247) [kubernetes-client-5.5.0.jar:na]
        at io.fabric8.kubernetes.client.dsl.internal.WatcherWebSocketListener.onMessage(WatcherWebSocketListener.java:93) [kubernetes-client-5.5.0.jar:na]
        at okhttp3.internal.ws.RealWebSocket.onReadMessage(RealWebSocket.java:322) [okhttp-3.14.9.jar:na]
        at okhttp3.internal.ws.WebSocketReader.readMessageFrame(WebSocketReader.java:219) [okhttp-3.14.9.jar:na]
        at okhttp3.internal.ws.WebSocketReader.processNextFrame(WebSocketReader.java:105) [okhttp-3.14.9.jar:na]
        at okhttp3.internal.ws.RealWebSocket.loopReader(RealWebSocket.java:273) [okhttp-3.14.9.jar:na]
        at okhttp3.internal.ws.RealWebSocket$1.onResponse(RealWebSocket.java:209) [okhttp-3.14.9.jar:na]
        at okhttp3.RealCall$AsyncCall.execute(RealCall.java:174) [okhttp-3.14.9.jar:na]
        at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) [okhttp-3.14.9.jar:na]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_312]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_312]
        at java.lang.Thread.run(Thread.java:748) [na:1.8.0_312]
Caused by: io.fabric8.kubernetes.client.KubernetesClientException: too old resource version: 5491278743 (5554041906)
        ... 13 common frames omitted

2021-11-22 03:34:06.605  INFO 1 --- [192.168.0.1/...] .f.c.r.EventBasedConfigMapChangeDetector : Added new Kubernetes watch: config-maps-watch-event
2021-11-22 03:34:06.605  INFO 1 --- [192.168.0.1/...] .f.c.r.EventBasedConfigMapChangeDetector : Kubernetes event-based configMap change detector activated
2021-11-22 03:34:06.607  INFO 1 --- [192.168.0.1/...] s.c.k.f.c.Fabric8ConfigMapPropertySource : Loading ConfigMap with name 'spring-cloud-kubernetes-configuration-watcher' in namespace 'my-namespace'
2021-11-22 03:34:06.621  WARN 1 --- [192.168.0.1/...] o.s.c.k.f.config.Fabric8ConfigUtils      : config-map with name : 'spring-cloud-kubernetes-configuration-watcher' not present in namespace : 'my-namespace'
2021-11-22 03:34:06.625  WARN 1 --- [192.168.0.1/...] o.s.c.k.f.config.Fabric8ConfigUtils      : config-map with name : 'spring-cloud-kubernetes-configuration-watcher-kubernetes' not present in namespace : 'my-namespace'

The docker image I use is springcloud/spring-cloud-kubernetes-configuration-watcher:2.1.0-RC1
Any hint to debug this issue is appreciated.


Q: CSS mobile devices and hamburger menu I have designed a website that uses a CSS hamburger menu to activate a slidebar with a links to different webpages on the site.
I also have written an iPhone/andriod apps that need to have an hamburger menu that open a slider work that run swift and android code.
I want to add  to the iphone/android hamburger slidebar links to the website (which has it own hamburger menu)
How can I test on the website if it a mobile device or a PC, so I can turn off if "Website" hamburger if its a mobile, since I already have and need the hamburger menu on the mobile.
I have php on the website so I can remove the hamburger menu on the website if its a mobile.
This is the main page

<button class="w3-bar-item w3-button w3-large" onclick="w3_close()">Home</button>
Link 1
Link 2
Link 3

<button class="w3-button w3-teal w3-xlarge" onclick="w3_open()">☰</button>

My Page

Thanks

A: so there are a few ways of doing this, but a really simple one is something like this:
var width = $(window).width(); //jquery
var width = window.innerWidth; //javascript

if(width > 1000){do large screen width display)
else{handle small screen}

of course 1000 is just an arbitrary number. it gets tricky because when you consider tables, there really are screens of all sizes so its up to you to determine what belongs where

A:
How can I test on the website if it a mobile device or a PC, so I can
  turn off if "Website" hamburger if its a mobile,

If I understood you correctly, you could use CSS @media -rules, to setup CSS rules that only apply to smaller devices. Below is a simple code-snippet example of a CSS media-query.
@media (min-width: 700px), handheld
{
    .w3-sidebar
    {
        display: none;
    }
}


Q: 'i' symbol in TeX Consider:

I would like to know the LaTeX command for the symbol above. I searched for it online and tried Detexify, but I could not find it.

A: \documentclass{article}
\usepackage{bbm}
\begin{document}
$\mathbbm{i}$
\end{document}

One drawback, of course is that the bbm fonts are bitmapped.  There is a scalable alternative with the STIX fonts, but it looks slightly different.
\documentclass[border=10]{standalone}
\usepackage{amsmath}

\DeclareFontEncoding{LS1}{}{}
\DeclareFontSubstitution{LS1}{stix}{m}{n}

\newcommand{\bbi}{\text{\usefont{LS1}{stixbb}{m}{n}i}}

\begin{document}

$\bbi$
\end{document}

A: There is Unicode character U+1D55A (MATHEMATICAL DOUBLE-STRUCK SMALL I). If you
use a TeX-engine that allows you to use arbitrary fonts (like LuaLaTeX) and have a font that supports the glyph, you could use  directly, as it were.

A: If you have the option to use unicode math, you can also use \Bbbi (U+1D55A) or \mitBbbi (U+02148) for the italic one (Thanks to Ingmar who pointed this out). Below you see the result in some of the commonly used fonts. If the font does not have it a question mark is shown.


Q: NativeScript Typescript: JSON Array to Typescript Typed Array I need your help, I'm learning NativeScript, here I read the txt file which has JSON data below output. After I fetch them I want to assign it to Array countries. But no luck :(
public countries: Array
console.log(response)
console.log(JSON.parse(JSON.stringify(response)))
Output:
[
    {
        "name": "Afghanistan",
        "code": "AF"
    },
    {
        "name": "Albania",
        "code": "AL"
    }
]
Please help.
Regards,

A: This is an Array<any>:
[ { "name": "Afghanistan", "code": "AF" }, { "name": "Albania", "code": "AL" } ]
You need to convert it to a Array<Country>, Example:
result.forEach((e) => { countries.push(new Country(e.name, e.code))
That, or you can change the return of the function that reads the txt to Array<Country>

A: finally got it via below code...
                    let elements: Array<Country> = JSON.parse(JSON.stringify(response))
                    .map((item:Country) =>
                    {
                        console.log(item.name +  ' < - >' + item.code);
                    })

Thanks All :)


Q: Condition for differentiable functional - Why is it defined in this exact way? I'm kind of struggling to understand, why the condition

$$J\left[y+h\right]-J\left[y\right] = \Psi \left[h\right]+\varepsilon
 \left(h\right){\lVert}h{\rVert} $$
where $\Psi$ is a linear functional, and $\varepsilon(h)$ is a
functional such that $\varepsilon(h) \rightarrow 0 $ for
${\lVert}h{\rVert} \rightarrow 0$

is the condition to check if we want to know if our given functional $J\left[\cdot \right]$ is differentiable or not.
Should we divide both sides by $\varepsilon(h)$, and take the limit ${\lVert}h{\rVert} \rightarrow 0$, and see what happens?
Also, I know, that if $\varepsilon(h) \rightarrow 0 $ for  ${\lVert}h{\rVert} \rightarrow 0$, then $\varepsilon(h)$ is a continuous functional - but why? Shouldn't continuity be checked by taking the difference ${\lVert}\varepsilon(f_n) - \varepsilon (f){\rVert}$ and checking if it's $\rightarrow 0$ for ${\lVert}f_n - f{\rVert} \rightarrow 0$?

A: apping Ψ; typically denoted as DJy or dJy or in the calculus of variations, δJy, or simply δJ. Calculating Ψ means figuring out what is Ψ(h) for all possible h. One possible way of doing to is that Ψ(h)=DJy(h) (the Frechet derivative of J at h) and by the chain rule, this is equal to dds∣∣∣s=0J(y+sh)=lims→0J(y+sh)−J(y)s. i.e Ψ(h)=DJy(h)=dds∣∣∣s=0J(y+sh)=lims→0J(y+sh)−J(y


Q: jquery array confusion I have a web page with a bunch of tables decorated with the datatable jquery plugin. When the page is loaded, they're hidden. Then I have a function that toggles them based on the index:
function expand_job(i) {
    $(".dataTables_wrapper")[i].show();
}

But it didn't work. Browser complains that show() is not a function. As a work around, I'm doing something like this:
function expand_job(i) {
    $(".dataTables_wrapper").each( function(idx) {
        if ( i == idx ) {
            $(this).slideToggle(300);
        }
    });
}

That works fine but it's..... I just can't let this go.
So why did the first piece of code not work? Is it because [i] takes an jquery object into and normal JS object and as a result lost the jquery functionality?
Thanks,

A: Use .eq():
$(".dataTables_wrapper").eq(i).show();

jQuery arrays contain the underlying DOM elements at each index, so when you access them the DOM functions are available but not the jQuery methods.

A: $(".dataTables_wrapper")[i]

returns a std java script object, not a jQuery object so you could:
$($(".dataTables_wrapper")[i]).show()

or use nth child or similar


Q: How can I know whether my port is blocked by firewall or engaged with some other service I want to know whether the below 3388 port is blocked by firewall or it is engaged with some other services.
Could you please suggest on this.
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

D:\Documents and Settings\32323>telnet xfjdd.og.com 3388
Connecting To xfjdd.og.com...Could not open connection to the
host, on port 3388: Connect failed

D:\Documents and Settings\32323>

A: By no means a hard and fast rule but, typically, if it sits on the 'Connecting to...' message for a short while, it is blocked by the firewall; while if it instantly goes past that and says 'Connect failed', the server has actively decided not to respond (either because the port is not open, or the service rejects your initial connection).
An old Windows command-line app called PortQry (http://support.microsoft.com/kb/310099) used to do the job quite nicely, with a FILTERED response for blocked by firewall and a NOT LISTENING response for server rejection.
Otherwise, you should familiarise yourself with Nmap (http://nmap.org/); it uses FILTERED when blocked by a firewall and CLOSED when the server rejects.


Q: redux differentiation with context api My understanding is that React's Context API was essentially introduced for quick and dirty global state management, particularly before Redux Toolkit was introduced to simplify the overhead of implementing Redux.
My understanding is that one of the main downsides of Context API is that it any update to any property on it will re-render all component fields which are bound to Context API (full re-render).
I recently explained that downside to someone and he asked why that wouldn't be the case with Redux.  He said Redux uses the Context API under the covers which appears to be the case based on some googling:
https://react-redux.js.org/using-react-redux/accessing-store#:~:text=Internally%2C%20React%20Redux%20uses%20React's,object%20instance%20generated%20by%20React.
A few questions:
1 - Can you confirm that Context API does a full component re-render when any state value is changed on it?
2 - Can you confirm that Redux uses Context API under the covers?  And can you confirm if Redux Toolkit still uses Context API under the covers?
3 - I was under the impression that Context API was introduced to be a simpler alternative to tools like Redux.  But if Redux uses Context API then did Context API come first but maybe it wasn't exposed directly to the developer?
4 - If Redux does use Context API under the covers then can you provide any insight into how Redux avoids a full component re-render?  I would assume that there's somevtype of mapping layer but I'd be interested to get some more insight into the specific implementation details

A:
My understanding is that React's Context API was essentially introduced for quick and dirty global state management

That's a common misunderstanding. Context is not a state management system, any more than props is a state management system. Context (like props) is a way to get data from one component to another. The difference is that props always passes the data to direct children, while context makes the data available to whichever random components in a subtree are interested.

My understanding is that one of the main downsides of Context API is that it any update to any property on it will re-render all component fields which are bound to Context API (full re-render).

This is true. Similarly, if you change props, the component that receives those props must rerender

1 - Can you confirm that Context API does a full component re-render when any state value is changed on it?

Of the specific components that are listening to that context, yes.

2 - Can you confirm that Redux uses Context API under the covers? And can you confirm if Redux Toolkit still uses Context API under the covers?

React-redux does use context, yes. Pure redux and redux toolkit don't, since they're general purpose libraries not directly related to react, but I think you meant react-redux.
That <Provider store={store}> that you must render at the top of a react-redux app is there to provide a context to the components underneath it. Components that call hooks like useSelector or useDispatch then use the context to find the store that they should interact with.

3 - I was under the impression that Context API was introduced to be a simpler alternative to tools like Redux. But if Redux uses Context API then did Context API come first but maybe it wasn't exposed directly to the developer?

Context has existed for a long time, but it used to be an unofficial feature. They've also made it easier to use over time.

4 - If Redux does use Context API under the covers then can you provide any insight into how Redux avoids a full component re-render?

The context is only providing a minimal amount of things to the child components, most importantly the store object. The reference to the store object does not typically change, so since the context value does not change, the child components do not need to render. To see exactly what it's providing, see this code: https://github.com/reduxjs/react-redux/blob/master/src/components/Provider.tsx#L33
The contents of the store does change, but that's not what the context is providing. To get the contents of the store, the individual components subscribe to the store, using redux's store.subscribe, plus a special hook called useSyncExternalStore. Basically, redux fires an event when the store's state is updated, and then the individual components set their own local state if it's a change they care about. This local state change is what causes the rerender.

If you're writing code that uses context, you're rarely going to be doing things fancy enough to require useSyncExternalStore or a custom subscription system. So the main things you'll want to keep in mind are:

*

*Keep the context focused on a single task. For example, if you have a theme object to control your app's colors, and also a user object which describes who is currently logged in, put these in different contexts. That way a component that just cares about the theme doesn't need to rerender when the user changes, and vice versa.

*If your context value is an object, memoize it so it's not changing on every render (see this documentation)

A: I'm a Redux maintainer.  @NicholasTower gave a great answer, but to give some more details:
Context and Redux are very different tools that solve different problems, with some overlap.
Context is not a "state management" tool. It's a Dependency Injection mechanism, whose only purpose is to make a single value accessible to a nested tree of React components.  It's up to you to decide what that value is, and how it's created.  Typically, that's done using data from React component state, ie, useState and useReducer.  So, you're actually doing all the "state management" yourself - Context just gives you a way to pass it down the tree.
Redux is a library and a pattern for separating your state update logic from the rest of your app, and making it easy to trace when/where/why/how your state has changed.  It also gives your whole app the ability to access any piece of state in any component.
In addition, there are some distinct differences between how Context and (React-)Redux pass along updates.  Context has some major perf limitations - in particular, any component that consumes a context will be forced to re-render, even if it only cares about part of the context value.
Context is a great tool by itself, and I use it frequently in my own apps.  But, Context doesn't "replace Redux".  Sure, you can use both of them to pass data down, but they're not the same thing.   It's like asking "Can I replace a hammer with a screwdriver?". No, they're different tools, and you use them to solve different problems.
Because this is such a common question, I wrote an extensive post detailing the differences:
Why React Context is Not a "State Management" Tool (and Why It Doesn't Replace Redux)
To answer your questions specifically:

*

*Yes, updating a Context value forces all components consuming that context to re-render... but there's actually a good chance that they would be re-rendering anyway because React renders recursively by default, and setting state in a parent component causes all components inside of that parent to re-render unless you specifically try to avoid it.  See my post A (Mostly) Complete Guide to React Rendering Behavior, which explains how all this works.

*Yes, React-Redux does use Context internally... but only to pass down the Redux store instance, and not the current state value.  This leads to very different update characteristics.  Redux Toolkit, on the other hand, is just about the Redux logic and not related to any UI framework specifically.

*Context was not introduced to be an alternative to Redux.  There was a "legacy Context" API that existed in React well before Redux itself was created, and React-Redux used that up through v5.  However, that legacy context API was broken in some key ways.  The current React Context API was introduced in React 16.3 to fix the problems in legacy Context, not specifically to replace Redux.

*React-Redux uses store subscriptions and selectors in each component instance, which is a completely different mechanism than how Context operates.

I'd definitely suggest reading the posts I linked above, as well as these other related posts:

*

*Redux - Not Dead Yet!

*When (and when not) to Reach for Redux

*React, Redux, and Context Behavior.

A: Original blog post by Mark Erikson:
I'll just copy paste some info, but here's the original source and I recommend going directly here: https://blog.isquaredsoftware.com/2020/01/blogged-answers-react-redux-and-context-behavior/
More links here:

*

*https://github.com/markerikson/react-redux-links

*https://blog.isquaredsoftware.com/2018/11/react-redux-history-implementation/

*https://medium.com/async/how-useselector-can-trigger-an-update-only-when-we-want-it-to-a8d92306f559
An explanation of how React Context behaves, and how React-Redux uses Context internally
There's a couple assumptions that I've seen pop up repeatedly:

*

*React-Redux is "just a wrapper around React context"

*You can avoid re-renders caused by React context if you destructure the context value

Both of these assumptions are incorrect, and I want to clarify how they actually work so that you can avoid mis-using them in the future.
For context behavior, say we have this initial setup:
function ProviderComponent() {
    const [contextValue, setContextValue] = useState({a: 1, b: 2});

    return (
        <MyContext.Provider value={contextValue}>
            <SomeLargeComponentTree />
        </MyContext.Provider>
    )
}

function ChildComponent() {
    const {a} = useContext(MyContext);
    return <div>{a}</div>
}

If the ProviderComponent were to then call setContextValue({a: 1, b: 3}), the ChildComponent would re-render, even though it only cares about the a field based on destructuring. It also doesn't matter how many levels of hooks are wrapping that useContext(MyContext) call. A new reference was passed into the provider, so all consumers will re-render. In fact, if I were to explicitly re-render with <MyContext.Provider value={{a: 1, b: 2}}>, ChildComponent would still re-render because a new object reference has been passed into the provider! (Note that this is why you should never pass object literals directly into context providers, but rather either keep the data in state or memoize the creation of the context value.)
For React-Redux: yes, it uses context internally, but only to pass the Redux store instance down to child components - it doesn't pass the store state using context!. If you look at the actual implementation, it's roughly this but with more complexity:
function useSelector(selector) {
    const [, forceRender] = useReducer( counter => counter + 1, 0);
    const {store} = useContext(ReactReduxContext);

    const selectedValueRef = useRef(selector(store.getState()));

    useLayoutEffect(() => {
        const unsubscribe = store.subscribe(() => {
            const storeState = store.getState();
            const latestSelectedValue = selector(storeState);

            if(latestSelectedValue !== selectedValueRef.current) {
                 selectedValueRef.current = latestSelectedValue;
                 forceRender();
            }
        })

        return unsubscribe;
    }, [store])

    return selectedValueRef.current;
}

So, React-Redux only uses context to pass the store itself down, and then uses store.subscribe() to be notified when the store state has changed. This results in very different performance behavior than using context to pass data.
There was an extensive discussion of context behavior in React issue #14110: Provide more ways to bail out of hooks. In that thread, Sebastian Markbage specifically said:

My personal summary is that new context is ready to be used for low frequency unlikely updates (like locale/theme). It's also good to use it in the same way as old context was used. I.e. for static values and then propagate updates through subscriptions. It's not ready to be used as a replacement for all Flux-like state propagation.

In fact, we did try to pass the store state in context in React-Redux v6, and it turned out to be insufficiently performant for our needs, which is why we had to rewrite the internal implementation to use direct subscriptions again in React-Redux v7.
For complete detail on how React-Redux actually works, read my post The History and Implementation of React-Redux, which covers the changes to the internal implementation over time, and how we actually use context.


Q: ThreadPoolTaskExecutor giving ConnectionPoolTimeOutException Getting this error even though the total count of active thread is less than the corepoolsize.
ThreadPool which I have created :
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(1500);
    executor.setMaxPoolSize(2000);
    executor.setQueueCapacity(500);
    executor.setThreadNamePrefix("MakeShoppingRequest");
    executor.setKeepAliveSeconds(10);
    executor.setAllowCoreThreadTimeOut(true);
    executor.initialize();

Exception:
**org.springframework.ws.client.WebServiceIOException: I/O error: Timeout waiting for connection from pool; nested exception is org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool**
    at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:561)
    at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:390)
    at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:383)
    at jdk.internal.reflect.GeneratedMethodAccessor66.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.aop.interceptor.AsyncExecutionInterceptor.lambda$invoke$0(AsyncExecutionInterceptor.java:115)
    at java.base/java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.leaseConnection(PoolingHttpClientConnectionManager.java:316)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager$1.get(PoolingHttpClientConnectionManager.java:282)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:190)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:87)
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
    at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:66)
    at org.springframework.ws.transport.http.ClientHttpRequestConnection.onSendAfterWrite(ClientHttpRequestConnection.java:83)
    at org.springframework.ws.transport.AbstractWebServiceConnection.send(AbstractWebServiceConnection.java:48)
    at org.springframework.ws.client.core.WebServiceTemplate.sendRequest(WebServiceTemplate.java:658)
    at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:606)
    at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:555)
    ... 15 more


Q: What does the standard claim that detecting a closed universe would rule out the multiverse mean? The new article "Lorentzian Vacuum Transitions: Open or Closed Universes?" On page 41 reads:
"We believe that the possibility that the geometry of the bubble after nucleation corresponds to a closed FLRW universe, contrary to CDL, should be seriously considered. Indeed this is the natural implication of brane nucleation in string theory as we have argued in this paper. This may have important physical implications if our universe is described in terms of a bubble after vacuum transitions as discussed at the end of the previous section Besides the deep implications of having a finite against an infinite universe, with finite number of stars and galaxies, it may eventually be tested if there is a definite way of determining the curvature of the universe. For the string theory landscape, it will at least eliminate the standard claim that detecting a closed universe would rule out the multiverse. These are important cosmological questions that deserve further scrutiny ".
What does the standard claim that detecting a closed universe would rule out the multiverse mean? If cosmologists find that the universe is closed and finite, would that rule out the existence of the multiverse and other universes?
Article link: https://arxiv.org/abs/2011.13936

A: I've not read the full paper you listed there (and it definitely doesn't look like a quick read), but the following passage by Ellis seems most relevant:

The multiverse idea is testable, because it can
be disproved if we determine there are closed
spatial sections in the universe (for example, if
the curvature is positive).

The claim [above] is that only negatively curved FRW
models can exist in a multiverse based on chaotic inflation, either because Coleman–de Luccia tunnelling only gives negative curvature
or because a closed spatial section necessarily
implies a single universe. But the first argument
is disputed (there are already papers suggesting
that tunnelling to positively curved universes is
possible) and the second argument would not
apply if we lived in a high-density lump imbedded in a low-density universe (i.e. the extrapolation of positive curvature to very large scales
may not be valid)

taken from the article Universe or Multiverse, (bullet point 3), the whole of which may be worthwhile reading. As said in the quote, he's referring to a multiverse in the context of chaotic inflation, but within the article he makes reference to the string landscape, though I don't think I'll do it justice by picking out any more quotes.
From what I gather, the quote from your paper is saying that, the claim: a closed universe is inconsistent with a multiverse scenario, is no longer correct. Ellis also seems to be saying the same thing, except making the point that this implies the multiverse is not testable. Different arguments based on the same core idea. The reason why the claim does not apparently hold anymore is listed in my long quote from Ellis above (and references can be found therein that are more technical).
Related article: https://academic.oup.com/astrogeo/article-pdf/49/2/2.33/683010/49-2-2.33.pdf


Q: Is it necessary to hash REST API tokens? So I have a REST API and some socket APIs which use a common token validation module. Here are the things that the token module does:
function tokenManager() {
  this.generate = (db, userId, cacheManager) => {
    /*Generates a token for a user and stores it in a db, also puts it in a cache as token: userId key-
    value pair.*/
  }

  this.verify = async (db, token, cacheManager) => {
    /*Checks the cache if a user is present for the given token and returns the user id. If the token was
    not found in cache, it verifies it from database and puts it in cache.*/

    //Each time for a successful verification, the token validity is increased by one day.
  }
}

This approach works well, however the tokens are stored in database as plain text. If someone gains access to the database they could get the tokens and make API calls, although rate limiting is present, there is some data compromised. I was planning to hash the API tokens and store them, but a hash compare has to be done on literally every request putting extra computation load on server. (especially bad for node). Is there a better way to implement this? Or is it even necessary to hash API tokens?


Q: iOS Firebase ML Kit Simple Audio Recognition "Failed to create a TFLite interpreter for the given model" I have been trying to implement the Simple Audio Recognition Tensorflow sample in iOS using the Firebase's ML kit. I have successfully trained the model and converted it into a TFlite file. The model takes the Audio(wav) file path as input([String]) and gives the predictions as output(float32). My iOS code is fairly simple
func initMLModel(){

        /*Initializing local TFLite model*/
        guard let modelPath = Bundle.main.path(forResource: "converted_model", ofType: "tflite") else {
            return
        }

        let myLocalModel = LocalModelSource.init(modelName: "My", path: modelPath)
        let registrationSuccessful = ModelManager.modelManager().register(myLocalModel)

        let options = ModelOptions(cloudModelName: nil, localModelName: "My")

        let interpreter = ModelInterpreter.modelInterpreter(options: options)

        let ioOptions = ModelInputOutputOptions()
        do {
            try ioOptions.setInputFormat(index: 0, type: .unknown, dimensions: []) /*input is string path. Since string is not defined, setting it as unknown.*/
            try ioOptions.setOutputFormat(index: 0, type: .float32, dimensions: [1,38]) /* output is 1 of 38 labelled classes*/
        } catch let error as NSError {
            print("Failed to set IO \(error.debugDescription)")
        }

        let inputs = ModelInputs()
        var audioData = Data()

        let audiopath = Bundle.main.path(forResource: "audio", ofType: "wav")
        do {
            audioData = try Data.init(contentsOf: URL.init(fileURLWithPath: audiopath!))
            //try inputs.addInput(audioData) /*If the input type is direct audio data*/
            try inputs.addInput([audiopath])
        } catch let error as NSError {
            print("Cannot get audio file data \(error.debugDescription)")
            return
        }

        interpreter.run(inputs: inputs, options: ioOptions) { (outputs, error) in
            if error != nil {
                print("Error running the model \(error.debugDescription)")
                return
            }
            do {
                let output = try outputs!.output(index: 0) as? [[NSNumber]]
                let probabilities = output?[0]

                guard let labelsPath = Bundle.main.path(forResource: "conv_labels", ofType: "txt") else { return }
                let fileContents = try? String.init(contentsOf: URL.init(fileURLWithPath: labelsPath))
                guard let labels = fileContents?.components(separatedBy: "\n") else {return}

                for i in 0 ..< labels.count {
                    if let probability = probabilities?[i] {
                        print("\(labels[i]) : \(probability)")
                    }
                }

            }catch let error as NSError {
                print("Error in parsing the Output \(error.debugDescription)")
                return
            }
        }
    }

But when i run this i get the following error output Failed to create a TFLite interpreter for the given model. The Complete Log of the sample app is as below
    2019-01-07 18:22:31.447917+0530 sample_core_ML[67500:3515789]  - <AppMeasurement>[I-ACS036002] Analytics screen reporting is enabled. Call +[FIRAnalytics setScreenName:setScreenClass:] to set the screen name or override the default screen class name. To disable screen reporting, set the flag FirebaseScreenReportingEnabled to NO (boolean) in the Info.plist
    2019-01-07 18:22:33.354449+0530 sample_core_ML[67500:3515686] libMobileGestalt MobileGestalt.c:890: MGIsDeviceOneOfType is not supported on this platform.
    2019-01-07 18:22:34.789665+0530 sample_core_ML[67500:3515812] 5.15.0 - [Firebase/Analytics][I-ACS023007] Analytics v.50400000 started
    2019-01-07 18:22:34.790814+0530 sample_core_ML[67500:3515812] 5.15.0 - [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see )
    2019-01-07 18:22:35.542993+0530 sample_core_ML[67500:3515823] [BoringSSL] nw_protocol_boringssl_get_output_frames(1301) [C1.1:2][0x7f9db0701d70] get output frames failed, state 8196
    2019-01-07 18:22:35.543205+0530 sample_core_ML[67500:3515823] [BoringSSL] nw_protocol_boringssl_get_output_frames(1301) [C1.1:2][0x7f9db0701d70] get output frames failed, state 8196
    2019-01-07 18:22:35.543923+0530 sample_core_ML[67500:3515823] TIC Read Status [1:0x0]: 1:57
    2019-01-07 18:22:35.544070+0530 sample_core_ML[67500:3515823] TIC Read Status [1:0x0]: 1:57
    2019-01-07 18:22:39.981492+0530 sample_core_ML[67500:3515823] 5.15.0 - [Firebase/MLKit][I-MLK002000] ModelInterpreterErrorReporter: Didn't find custom op for name 'DecodeWav' with version 1
    2019-01-07 18:22:39.981686+0530 sample_core_ML[67500:3515823] 5.15.0 - [Firebase/MLKit][I-MLK002000] ModelInterpreterErrorReporter: Registration failed.
    Failed to set IO Error Domain=com.firebase.ml Code=3 "input format 0 has invalid nil or empty dimensions." UserInfo={NSLocalizedDescription=input format 0 has invalid nil or empty dimensions.}
    2019-01-07 18:22:40.604961+0530 sample_core_ML[67500:3515812] 5.15.0 - [Firebase/MLKit][I-MLK002000] ModelInterpreterErrorReporter: Didn't find custom op for name 'DecodeWav' with version 1
    2019-01-07 18:22:40.605199+0530 sample_core_ML[67500:3515812] 5.15.0 - [Firebase/MLKit][I-MLK002000] ModelInterpreterErrorReporter: Registration failed.
    Error running the model Optional(Error Domain=com.firebase.ml Code=2 "Failed to create a TFLite interpreter for the given model (/Users/minimaci73/Library/Developer/CoreSimulator/Devices/7FE413C1-3820-496A-B0CE-033BE2F3212A/data/Containers/Bundle/Application/868CB2FE-77D8-4B1F-8853-C2E17ECA63F2/sample_core_ML.app/converted_model.tflite)." UserInfo={NSLocalizedDescription=Failed to create a TFLite interpreter for the given model (/Users/minimaci73/Library/Developer/CoreSimulator/Devices/7FE413C1-3820-496A-B0CE-033BE2F3212A/data/Containers/Bundle/Application/868CB2FE-77D8-4B1F-8853-C2E17ECA63F2/sample_core_ML.app/converted_model.tflite).})

When looked at this line Didn't find custom op for name 'DecodeWav' I looked up on the custom supported ops and found that Tensorflow already supports this in the audio_ops.cc by default.
Details
My Tensorflow Version : 1.12.0
Environment : Conda
OS Version : Mac OSX Mojave 10.14.2
Deployment target : ios 12.0
Installation type : Pod Installation (pod 'Firebase/MLModelInterpreter')
But i ran my training model first in v1.9.0. Then updated the Tensorflow to latest v1.12.0 to run the TFLite Convertor. Both are master branch.
My TFLite Convertor code Python
import tensorflow as tf

graph_def_file = "my_frozen_graph.pb"
input_arrays = ["wav_data"]
output_arrays = ["labels_softmax"]
input_shape = {"wav_data" : [1,99,40,1]}

converter = tf.contrib.lite.TFLiteConverter.from_frozen_graph(
  graph_def_file, input_arrays, output_arrays, input_shape)
converter.allow_custom_ops = True
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)

A: I posted this same question in the firebase quickstart iOS repository, And i got the following response DecodeWav op is never supported by TensorFlowLite. So at present Tensorflow Lite does not support audio processing even-though Tensorflow itself supports audio processing.


Q: HTML link with GET parameters: load page html and javascript before executing ajax request When I paste the HTML link below in my address bar or press the browser "previous page" button my ajax GET request is executed before the html content is fully loaded resulting in my ajax returned content being displayed above my nav bar and therefore breaking my site.
If the same request gets executed from within the site then everything is fine.
How can I make sure the page HTML and javascript loads before the ajax request is fired?
EDIT: SOLVED (answer in post below)
HTML LINK
https://domainName/?action=listy&p=test
JS pushstate
var container = document.querySelector('.lnk');
var url = "";

container.addEventListener('click', function(e) {
  if (e.target != e.currentTarget) {
    e.preventDefault();

    if (e.target.getAttribute('name')) {
      var data = e.target.getAttribute('name')
      url = "?action=list&p=" + data;
      history.pushState(data, null, url);
    }

  }
  e.stopPropagation();
}, false);

window.addEventListener('popstate', function(e) {

  window.location.replace(url);

});

JQuery AJAX
$(document).ready(function() {
  // .....
  success: function(dataBack) {
    $('.content-area').html(dataBack);
  },
});

PHP
if(isset($_GET['action']) && !empty($_GET['action'])) {
$action = $_GET['action'];
$var = $_GET['p'];
switch($action) {

    case 'list' : list($var);break;

}
}

A: This works for me (Note this uses the jquery library):
$(document).ready(function () {
     Your code here...
});

This will wait for the page to load then run the function. I personally use this for animations but then the animations also take more time for me so I have to also include the setTimeout function like this:
setTimeout(function () {
       Your code here...
}, 1000);

It waits a specific amount of milliseconds before executing the function.

A: Turns out the issue was coming from my index.php structure;
I moved the php code in separate files and included it at the end of index.php instead of the top.
Now Im having other issues but the main question is resolved.


Q: Get random ID from DB on button click Hi guys (I'm a beginner so take it easy) I have this code which searches my database and brings up the title / artists and that works fine. I am required to make a button which when clicked it brings up a random ID from my database. I have looked around but can't find anything useful.Trying to come up with a lamda expression or something...
Thanks
CONTROLLER
public ActionResult Play(string searchTitle, string searchArtist, string shuffle)
{
    var media = from s in db.UploadTables select s;

    if (!string.IsNullOrEmpty(searchTitle))
    {
        media = media.Where(m => m.MediaTitle.Contains(searchTitle));
    }

    if (!string.IsNullOrEmpty(searchArtist))
    {
        media = media.Where(m => m.MediaArtist.Contains(searchArtist));
    }

    return View(media);
}

VIEW
@using (Html.BeginForm())
{

        Song Name: @Html.TextBox("searchTitle")
        <input type="submit" value="Search" />
        Artist: @Html.TextBox("searchArtist")
        <input type="submit" value="Search" />
        @Html.TextBox("shuffle")
        <input type="submit" value="Search" />

}

A: Random rand = new Random();
int total = db.UploadTables.Count();
var randomId = db.UploadTables.Skip(rand.Next(total)).First().Id;

Random.Next(Int32 maxValue) will get a number between 0 and maxValue-1.
IQueryable<TSource>.Skip(this IQueryable<TSource>, int count) will skip count entries.
You then take the First() of the remaining entries and tadaa you can access its Id field.
Obviously, this is only one way to do it, and as told by others, there are many ways to do that.


Q: Is it possible to develop apps for iOS with iPod? I develop games for Android, but now I want to try the iOS platform. Actually, I have Mac Mini, but I haven't enought money to buy iPhone, so I think about buying iPod Touch instead. Is it possible to develop games (Unity engine) using iPod? What about games performance? Sorry if I ask something stupid, I never developed for iOS before, thanks!

A: We use an iTouch for development (cheaper than buying iPad2's). So yes, you can definitely develop for iOS using an iTouch/iPod.
You will also need to join the Apple developer program before you can deploy to the iTouch - Apple has a $99 annual fee for an individual. Even if you purchase Unity you will need buy into the Apple dev program too.

A: same code will work in iphone,ipad ,ipod .so no problem.so that the name of IDE is xcode.but performance and image accuracy will be varied.
http://unity3d.com/company/news/iphone-press.html

A: Apple provides a SDK including a simulator. Never trust the simulator completely, but you can use it easily for day by day job, and test it on a real iphone, ipod touch or similar only from time to time.


Q: Django tagging migration to GAE I have a Django app that use a django-tagging. I need to port this application to GAE. So, the main problem is to migrate tagging part. It has a complicated model, that should be rewritten to work with Google store. I think tagging is very popular django app and someone has the same problem before. Has someone a rewritten model?

A: Check Nick's post about tagging blog posts. It covers all main tagging issues.

A: There is a modified django-tagging, probably it might work.


Q: How to add delay between jquery steps transition (jquery steps plugin) I am using http://www.jquery-steps.com/Examples#advanced-form plugin.
How can I add delay between the two steps?
I have tried adding the timeout function in onStepChanging and onStepChanged but it's not working.
Here's what my code looks like:
var form = $("#example-advanced-form").show();

form.steps({
    headerTag: "h3",
    bodyTag: "fieldset",
    transitionEffect: "slideLeft",
    onStepChanging: function (event, currentIndex, newIndex)
    {
        // Allways allow previous action even if the current form is not valid!
        if (currentIndex > newIndex)
        {
            return true;
        }
        // Forbid next action on "Warning" step if the user is to young
        if (newIndex === 3 && Number($("#age-2").val()) < 18)
        {
            return false;
        }
        // Needed in some cases if the user went back (clean up)
        if (currentIndex < newIndex)
        {
            // To remove error styles
            form.find(".body:eq(" + newIndex + ") label.error").remove();
            form.find(".body:eq(" + newIndex + ") .error").removeClass("error");
        }
        form.validate().settings.ignore = ":disabled,:hidden";
        return form.valid();
    },
    onStepChanged: function (event, currentIndex, priorIndex)
    {
        // Used to skip the "Warning" step if the user is old enough.
        if (currentIndex === 2 && Number($("#age-2").val()) >= 18)
        {
            form.steps("next");
        }
        // Used to skip the "Warning" step if the user is old enough and wants to the previous step.
        if (currentIndex === 2 && priorIndex === 3)
        {
            form.steps("previous");
        }
    },
    onFinishing: function (event, currentIndex)
    {
        form.validate().settings.ignore = ":disabled";
        return form.valid();
    },
    onFinished: function (event, currentIndex)
    {
        alert("Submitted!");
    }
}).validate({
    errorPlacement: function errorPlacement(error, element) { element.before(error); },
    rules: {
        confirm: {
            equalTo: "#password-2"
        }
    }
});

A: how about this
setTimeout(function(){ /*your function*/ }, 3000);

https://www.w3schools.com/JSREF/met_win_setTimeout.asp


Q: Using Reflection to determine which Fields are backing fields of a Property I'm using reflection to map out objects. These objects are in managed code but I have no visibility into their source code, underlying structure, etc. other than through reflection. The overarching goal of all this is a rudimentary memory map of an object (similar in functionality to SOS.dll DumpObject and !ObjSize commands). As such, I'm trying to determine which members are being "double counted" as both a field and a property.
For example:
public class CalendarEntry
{
    // private property
    private DateTime date { get; set;}

    // public field
    public string day = "DAY";
}

When mapped shows:

*

*Fields

*

*day

*k__BackingField

*Properties

*

*date

Where as a class like this:
public class CalendarEntry
{
    // private field
    private DateTime date;

    // public field
    public string day = "DAY";

    // Public property exposes date field safely.
    public DateTime Date
    {
        get
        {
            return date;
        }
        set
        {
                date = value;
        }
    }
}

When mapped shows:

*

*Fields

*

*day

*date

*Properties

*

*Date

At first glance there's nothing to tell you that the Date property's "backing field" is the field named date. I'm trying to avoid counting date twice in this scenario since that will give me a bad memory size approximation.
What's more confusing/complicated is I've come across scenarios where properties don't always have a corresponding field that will be listed through the Type.GetFields() method so I can't just ignore all properties completely.
Any ideas on how to determine if a field in the collection returned from Type.GetFields() is essentially the backing field of some corresponding property returned from Type.GetProperties()?
Edit- I've had trouble determining what conditions a property will not have a corresponding field in listed in the collection returned from Type.GetFields(). Is anyone familiar with such conditions?
Edit 2- I found a good example of when a property's backing field would not be included in the collection returned from Type.GetFields(). When looking under the hood of a String you have the following:

*

*Object contains Property named FirstChar

*Object contains Property named Chars

*Object contains Property named Length

*Object contains Field named m_stringLength

*Object contains Field named m_firstChar

*Object contains Field named Empty

*Object contains Field named TrimHead

*Object contains Field named TrimTail

*Object contains Field named TrimBoth

*Object contains Field named charPtrAlignConst

*Object contains Field named alignConst

The m_firstChar and m_stringLength are the backing fields of the Properties FirstChar and Length but the actual contents of the string are held in the Chars property. This is an indexed property that can be indexed to return all the chars in the String but I can't find a corresponding field that holds the characters of a string. Any thoughts on why that is? Or how to get the backing field of the indexed property?

A: The name of a property's backing field is a compiler implementation detail and can always change in the future, even if you figure out the pattern.
I think you've already hit on the answer to your question: ignore all properties.
Remember that a property is just one or two functions in disguise.  A property will only have a compiler generated backing field when specifically requested by the source code.  For example, in C#:
public string Foo { get; set; }

But the creator of a class need not use compiler generated properties like this.  For example, a property might get a constant value, multiple properties might get/set different portions of a bit field, and so on.  In these cases, you wouldn't expect to see a single backing field for each property.  It's fine to ignore these properties.  Your code won't miss any actual data.

A: You can ignore all properties completely. If a property doesn't have a backing field, then it simply doesn't consume any memory.
Also, unless you're willing to (try to) parse CIL, you won't be able to get such mapping. Consider this code:
private DateTime today;

public DateTime CurrentDay
{
    get { return today; }
}

How do you expect to figure out that there is some relation between the today field and the CurrentDay property?
EDIT: Regarding your more recent questions:
If you have property that contains code like return 2.6;, then the value is not held anywhere, that constant is embedded directly in the code.
Regarding string: string is handled by CLR in a special way. If you try to decompile its indexer, you'll notice that it's implemented by the CLR. For these few special types (string, array, int, …), you can't find their size by looking at their fields. For all other types, you can.

A: To answer your other question:Under what circumstances do properties not have backing fields?
public DateTime CurrentDay
{
    get { return DateTime.Now; }
}

or property may use any other number of backing fields/classes
public string FullName
{
    get {return firstName + " " + lastName;}
}


Q: "What' and 'which' difference Which one of the following sentence is grammatical?
1- What footballer has scored the most number of goals?
2- Which footballer has scored the most number of goals?

A: Although both are commonly used I would go with
What footballer has scored the most goals? (number of is not required).
Why? basically which is used when you are choosing between a small number of alternatives.
Which of your friends....
what student from your school...
which
determiner, pronoun
UK  /wɪtʃ/ US  /wɪtʃ/
which determiner, pronoun (QUESTION)
A1
(used in questions and structures in which there is a fixed or limited set of answers or possibilities) what one or ones:
what
determiner, pronoun, exclamation
UK  /wɒt/ US  /wɑːt/
what determiner, pronoun, exclamation (QUESTION)
A1
used to ask for information about people or things:
What time is it?
What books did you buy?
What did you wear?
What size shoes do you take?
What happened after I left?
all ref CED WHAT


Q: Como traer datos con php y mysqli pero que sean de los últimos 7 días tengo la siguiente consulta con mysqli que me trae registros de una base de datos:

                                    ESTADO
                                    FLOTA
                                    EQUIPO
                                    FECHA SALIDA
                                    CAMBIOS
                                    TRABAJO

<?php

$termi=mysqli_query($conn,"select * from `trabajos` where estado_kal='Finalizado' order by fecha DESC");
while($traterm = mysqli_fetch_array($termi)){

?>

                                    <?php echo $traterm['estado_kal']; ?>
                                    <?php echo $traterm['flota_kal']; ?
                                    <?php echo $traterm['equipo_kal']; ?>
                                    <?php echo $traterm['fecha_fin']; ?>
                                    <?php echo $traterm['cambios_kal']; ?>
                                    <?php echo $traterm['trabajo_kal']; ?>

<?php
            }
?>

Como puedo hacer para traer solo registros de los últimos 7 días comenzando desde los días jueves, ejemplo: la consulta debe traer todos los registros de los últimos 7 días comenzando desde el jueves y cuando termine los 7 días vuelve a comenzar desde el día jueves pero por supuesto una fecha posterior.
Me seria de gran utilidad cualquier ayuda que me puedan aportar. muchas gracias.

A: Puedes usar interval en tu consulta MySQL:
SELECT * FROM `trabajos` WHERE estado_kal='Finalizado'
AND fecha >= (DATE(NOW()) - INTERVAL 7 DAY)
ORDER BY fecha DESC


Q: Line below link on hover How can I add a short line below link ? The line should be visible only on hover.
I tried with border-bottom, but that way the line is 100% of the link width and I want the line to be shorter than the link .
Here is a example image of the effect that I try to make.

A: This is something I just thought of, check it out see what you think. So we use :after and create a line under the text. This only works if the parent has a width (for centering).
HTML:

Test

CSS:
div {
    width: 30px;
}
div:hover:after {
    content: "";
    display: block;
    width: 5px;
    border-bottom: 1px solid;
    margin: 0 auto;
}

DEMO

Updated CSS:
div {
    display: inline-block;
}

Not sure why I didnt think of this but you can just use inline-block to get it to center without the parent having a width.
DEMO HERE

Here is a link using the same method, just incase you got confused.
DEMO HERE

So I have now be told I should even point out the most obvious thing so here is an update just for the people that don't know width can be a percentage.
width: 70%;

Changed the width from 5px to 70% so it will expand with the width of the text.
DEMO HERE

A: Edit:
Ruddy's solution has the same result and is more elegant so based on that, I used it recently with addition of transition, making it a bit more eye catching and I thought it would be useful to share here:
 a {
   display: inline-block;
   text-decoration:none
 }
 a:after {
   content: "";
   display: block;
   width: 0;
   border-bottom: 1px solid;
   margin: 0 auto;
   transition:all 0.3s linear 0s;
 }

 a:hover:after {
   width: 90%;
 }

jsfiddle link
(Original answer below)
Check this i just came up with, playing in the fiddle:
 I am a link, hover to see

 a.bordered {
 text-decoration:none;
 position: relative;
 z-index : 1;
 display:inline-block;
 }

a.bordered:hover:before {
content : "";
position: absolute;
left    : 50%;
bottom  : 0;
height  : 1px;
width   : 80%;
border-bottom:1px solid grey;
margin-left:-40%;
}

Depending on the percentages, you may play with a.bordered:hover:before margin and left position.

A: Simply use this class:
.link:hover {
    background-image:url("YOUR-SMALL-LINE-BOTTOM.png")
}

like this, the line will appear when you hover over the element. And you can specify in the image, how small or big the line has to be.

A: Try creating another Div for border. And adjust the width of that div according to your choice. I hope this will help.

A: what about this?
a {text-decoration:none;position:relative;}
a:hover:before {content:"_";position:absolute;bottom:-5px;left:50%;width:10px;margin:0 0 0 -5px;}

check this fiddle for more: http://jsfiddle.net/h7Xb5/

A: You can try using ::after pseudo element:

a {
  position: relative;
  text-decoration: none;
}

a:hover::after {
  content: "";
  position: absolute;
  left: 25%;
  right: 25%;
  bottom: 0;
  border: 1px solid black;
}
Demo Link

A: use underline or if u want the line to be much shorter try scalar vector graphics(svg) with this you can have custom lines.
<svg id="line "height="40" width="40">
  <line x1="0" y1="0" x2="700" y2="20" style="stroke:rgb(125,0,0);stroke-width:2" />


Q: EF Insert Array into db With View I have something to ask , i 'm going to create a simple application that store value of student Below is my class which i have tried .
Class Data{
  public int Id {get;set;}
  public string Name {get;set;}
  public int[] ValuesStudent{get;set;}

}
And below is example of the data
id = 1
Name = Jhon
Values = 9,8,7,5,9,7,4,6,4

id = 2
Name = Uncle
Values = 4,7,8,4

id = 3
Name = Jhon
Values = 9,8,7,5,9,7

as you can see above example of the data i can insert multiple value as i need, Student has taken 3 examination so i must insert 3 values for him .
But what i'm confuse is how can i make insert new Data . enter image description here
Oke if you any link which refer about problem , and explain about it , you can directly comment it .


Q: Is there a property I can check to see if code is rendered using hydrate vs render? I have a React app (with SSR) and need to handle things differently for server vs browser renders.

A: I ended up using the following, but my gut feeling is there is a better way.
if (typeof window !== "undefined") {
  // This code is rendered in browser vs server
}


Q: How to abort processing a request in NodeJS http server I have your standard callback-hell http server like (simplified):
http.createServer((req, res) => {
    doSomething(() => {
        doMoreSomethings(() => {
            if (!isIt())
                // explode A

            if (!isItReally())
                // explode B

            req.on('data', (c) => {
                if (bad(c))
                  // explode C
            });

            req.on('end', () => {
                // explode D
            });
        });
    });
};

The only way I know of to end the request is res.end(), which is asynchronous, so stuff after you call that will run (as far as I can tell). Is there a way to do a pseudo-process.exit mid-flight and abort processing the request, so I don't waste time on other stuff? For example how can I stop at the above // explode lines and not process anything else? throw doesn't leap over scope boundaries. Basically, I think, I want to return or break out of the createServer callback from within a nested callback. Is the only way to do this to be able to have code with a single path and just not have more than one statement at each step? Like, horizontal coding, instead of vertical KLOCs.
I'm a Node noob obviously.
Edit: Maybe another way to ask the question is: Is it possible to abort at the // explode C line, not read any more data, not process the end event, and not process any more lines in the doMoreSomethings callback (if there were any)? I'm guessing the latter isn't possible, because as far as I know, doMoreSomethings runs to completion, including attaching the data and end event handlers, and only then will the next event in the queue (probably a data event) get processed, at which point doMoreSomethings is done. But I am probably missing something. Does this code just zip through, call isIt and isItReally, assign the event handlers, hop out of all the callbacks, the createServer callback finishes, and then all the extra stuff (data/end/etc.) runs from the event queue?

A: Typically you will use a return statement. When you call return any code below it will not get executed. Although, if your functions isIt() or isItReally() are asynchronous functions then you will be running into trouble as those are used in a synchronous fashion.


Q: Looking for a script/tool to dump a list of installed features and programs on Windows Server 2008 R2 The same compiled .Net / C++ / Com program does different things on two seemingly same computers. Both have DOZENS of things installed on them. I would like to figure out what the difference between the two is by looking at an ASCII diff. Before that I need to "serialize" the list of installed things in a plain readable format - sorted alphabetically + one item per line.
A Python script would be ideal, but I also have Perl, PowerShell installed.
Thank you.

A: You can get the list of installed programs from the registry. It's under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
If this is a once-off exercise you may not even need to write any code - just use Regedit to export the key to a .REG file. If you do want to automate it Python provides the _winreg module for registry access.

A: There are two tools from Microsoft that may be what you need: RegDump and RegDiff. You can download them from various places, including as part of the Microsoft Vista Logo Testing Toolkit.
Also, there is Microsoft Support article How to Use WinDiff to Compare Registry Files.
For a Pythonic way, here is an ActiveState recipe for getting formatted output of all the subkeys for a particular key (HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall for example).

A: Personally I always liked sysinternals' stuff (powerfull, light, actual tools - no need to install)
There is command line tool psinfo that can get you what you want (and then some) in various formats, distinguishing hotfixes and installed software, on local or remote computer (providing system policies allow it on remote).
You can also run it live from here, so though not strictly pythonic you could plug it in quite nicely.

A: Taken from List installed software from the command line:

If you want to list the software known to Windows Management
  Instrumentation (WMI) from the command line, use WMI command line
  (WMIC) interface.
To list all products installed locally, run the following
  command:
wmic product

Caveat: It seems that this command only list software installed through Windows Installer. See Win32_Product class


Q: Using Python CGI for a big HTML file I have a big html file named exercise.html, I need generate to one  som stuff by Python CGI.
I want to ask you what is the best way to print this HTML.
I know that it is possible by print method with using format methods %s, %i etc.:
print '''
<title>My first Python CGI app</title>

Hello, 'world'!

.
.

%s

.
.

''' % generated_text

But this HTML is really big,so is this only one solution?

A: You should consider using a templating language like Jinja2.
Here is a simple example straight from the link above:
>>> from jinja2 import Template
>>> template = Template('Hello {{ name }}!')
>>> template.render(name='John Doe')

Generally, though you save templates in a file, and then load / process them:
from jinja2 import Environment, PackageLoader
# The env object below finds templates that are lcated in the `templates`
# directory of your `yourapplication` package.
env = Environment(loader=PackageLoader('yourapplication', 'templates'))
template = env.get_template('mytemplate.html')
print template.render(the='variables', go='here')

As demonstrated above, templates let you put variables into the template.  Placing text inside {{ }} makes it a template variable.  When you render the template, pass in the variable value with a keyword argument.  For instance, the template below has a name variable that we pass via template.render

This is my {{name}}.

template.render(name='Jaime')

A: Also consider Python Bottle (SimpleTemplate Engine).  It is worth noting that bottle.py supports mako, jinja2 and cheetah templates.
The % indicates python code and the {{var}} are the substitution variables
HTML:

  % for item in basket:

{{item}}

  % end

Python:
with open('index.html', 'r') as htmlFile:
    return bottle.template(htmlFile.read(), basket=['item1', 'item2'])


Q: A nicer recurrence for the Eulerian polynomials. I was perusing the subject of Eulerian polynomials. I'm assuming the definition that the Eulerian polynomial is defined by $C_n(t)=\sum_{\pi\in S_n}t^{1+d(\pi)}$, where $d(\pi)$ is the number of descents.
The Eulerian polynomials satisfy a standard recurrence $C_n(t)=t(1-t)C'_{n-1}(t)+ntC_{n-1}(t)$. Apparently they also satisfy the more aesthetically pleasing relation
$$
C_n(t)=tC'_{n-1}(t)+t^nC'_{n-1}(t^{-1}).
$$
The generating function in $t^{-1}$ is troublesome to me. How can one derive this other recurrence relation? Thank you,

A: Write $C_{n-1}(t) = \sum_{k=1}^{n-1} a_k t^k$, and look eactly how each term contributes in $C_n(t)$ :
Your first recurrence relation says :
$C_n(t) = t(1-t)C'_{n-1}(t)+ntC_{n-1}t = (t-t^2)(\sum_{k=1}^{n-1} k a_k t^{k-1}) + nt(\sum_{k=1}^{n-1} a_k t^k) \\
 = \sum_{k=1}^{n-1} (k-kt+nt)a_k t^k = \sum_{k=1}^{n-1} (k + (n-k)t)a_k t^k $
Essentially, each term $t^k$ is turned into $k t^k + (n-k) t^{k+1}$
The second recurrence relation attempts to show this symmetric-looking separation :
$tC'_{n-1}(t) = \sum_{k=1}^{n-1} k a_k t^k$ : we recover the first half, which leaves us with the other half.
Since it is the same thing but in the other direction, we have to switch the coefficients of the polynomial around, differentiate, adjust the power of $t$, then switch them around again.
In fact, since the Euler polynomials are symmetric, $a_k = a_{n-k}$, we can skip the first step. The last switching around step explains why you see that $C'_{n-1}(t^{-1})$ :
$\sum_{k=1}^{n-1} (n-k) a_k t^{k+1} = \sum_{k=1}^{n-1} (n-k) a_{n-k} t^{k+1}
= \sum_{k=1}^{n-1} k a_k t^{n-k+1}  \\
 = t^n \sum_{k=1}^{n-1} k a_k (t^{-1})^{k-1} = t^n C'_{n-1}(t^{-1})$.
Even if you use $t^{-1}$, $t^n C'_{n-1}(t^{-1})$ is still a polynomial in $t$. It is a simple trick done to reverse the coefficients of a polynomial.
For example, stating that the polynomials are symmetric ($a_k = a_{n-k}$),
is the same as stating that $C_n(t) = t^{n+1} C_n(t^{-1})$


Q: Callback parameters gets shifted I have a video c++ callback function where the parameters get suddently shifted after a few hours. In debug, it will assert on this:
void CCameraInstance::VideoCallback(void *pContext, unsigned char *pBuffer, long nWidth, long nHeight, long nFrameErrorNo)
{
   assert(nWidth < 4000);
   CCameraInstance *pThis = (CCameraInstance*)pContext;
   pThis->PaintFrame(pBuffer, nWidth, nHeight, nFrameErrorNo);
}

When the debugger breaks on the assert, nWidth has a big invalid value. However, nHeight is 320 (the width value) and nFrameErrorNo is 240 (the nHeight value).
How can the parameters get shift that way?

A: The shift could be caused by the hidden this pointer. http://www.learncpp.com/cpp-tutorial/8-8-the-hidden-this-pointer/
From the code you have pasted here
void CCameraInstance::VideoCallback(void *pContext, unsigned char *pBuffer, long nWidth, long nHeight, long nFrameErrorNo)

I can see the callback function is a member of class CCameraInstance
I'm not sure whether you are defining the function as a static function or a normal one. But in theory it should be a static function to avoid the this pointer. Using a C++ class member function as a C callback function
However, I had a problem with C++/CLI even if i have define the member function as static. The this pointer/Handle still exist.
I think you can try to define your function as
void CCameraInstance::VideoCallback(CCameraInstance* test,void *pContext, unsigned char *pBuffer, long nWidth, long nHeight, long nFrameErrorNo)

and have try.
If you are using C++/CLI it would be
void CCameraInstance::VideoCallback(CCameraInstance^ test,void *pContext, unsigned char *pBuffer, long nWidth, long nHeight, long nFrameErrorNo)