Cadastro no foreach php

Question: tudo bem? Estou tentando cadastrar vários registros no bd conforme o número de parcelas solicitado, porém não estou conseguindo. Meu código:
php:
 $Conn = parent::getConn();
    try {
        foreach ($this->Data as $pr):
            $Query = $Conn->prepare("INSERT INTO c022vdpr (dta_pedido, nro_pedido, cod_cliente, vlr_parcela, vct_parcela, nro_parcela, quitacao) VALUES (:dtaped, :nroped, :codcli, :vlrpar, :vctpar, :nropar, :quit)");
            $Query->execute(array(':dtaped' => $pr['dta_pedido'], ':codcli' => $pr['cod_cliente'], ':nroped' => $pr['nro_pedido'], ':vlrpar' => $pr['vlr_parcela'], ':vctpar' => $pr['vct_parcela'], ':nropar' => $pr['nro_parcela'], ':quit' => $pr['quitacao']
            ));
            $this->Result = true;
            $this->Error = ["Atualizado!", ACCEPT];
        endforeach;
    } catch (PDOException $e) {
        $this->Result = false;
        $this->Error = [$e->getMessage(), ERROR];
    }

error = Erro na Linha : # 168 # :: Illegal string offset
var_dump:
object(AdminProd)[2]
private 'Data' =>
array (size=7)
  'dta_pedido' => string '2017-07-03' (length=10)
  'nro_pedido' => int 477037
  'cod_cliente' =>
    array (size=3)
      0 => string '5' (length=1)
      1 => string '5' (length=1)
      2 => string '5' (length=1)
  'vlr_parcela' => float 132.5
  'vct_parcela' =>
    array (size=3)
      0 => string '2017-08-31' (length=10)
      1 => string '2017-09-30' (length=10)
      2 => string '2017-10-31' (length=10)
  'nro_parcela' =>
    array (size=3)
      0 => string '1' (length=1)
      1 => string '2' (length=1)
      2 => string '3' (length=1)
  'quitacao' => string 'N' (length=1)
   private 'CatId' => null
   private 'Error' =>
array (size=2)
  0 => string 'SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '2' for column 'dta_pedido' at row 1' (length=105)
  1 => string 'error' (length=5)
  private 'Result' => boolean false

Comment: tem um erro ali,
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '2' for column 'dta_pedido' at row 1' (length=105)
Comment: então o formato da data esta correto pois já consegui cadastra assim em outras tabelas :(
Answer: A propriedade $this->Data parece ser um array associativo. Embora o PHP não faça a distinção entre array associativo e array indexado, seu código faz. Tente remover o foreach do código, e deve ter o resultado esperado:
try {
    $Query = $Conn->prepare("INSERT INTO c022vdpr (dta_pedido, nro_pedido, cod_cliente, vlr_parcela, vct_parcela, nro_parcela, quitacao) VALUES (:dtaped, :nroped, :codcli, :vlrpar, :vctpar, :nropar, :quit)");
    $Query->execute(array(':dtaped' => $this->Data['dta_pedido'], ':codcli' => $this->Data['cod_cliente'], ':nroped' => $this->Data['nro_pedido'], ':vlrpar' => $this->Data['vlr_parcela'], ':vctpar' => $this->Data['vct_parcela'], ':nropar' => $this->Data['nro_parcela'], ':quit' => $this->Data['quitacao']
    ));
    $this->Result = true;
    $this->Error = ["Atualizado!", ACCEPT];
} catch (PDOException $e) {
    $this->Result = false;
    $this->Error = [$e->getMessage(), ERROR];
}

UPDATE
Como mencionou nos comentários, utilizou o foreach para gravar na base os dados do clientes + dados de cada parcela, criando linhas distintas na base para cada parcela. Consegue utilizar a propriedade nro_parcela no foreach para gravar os dados da forma que pretende:
try {
    foreach ($this->Data['nro_parcela'] as $k => $v):
        $Query = $Conn->prepare("INSERT INTO c022vdpr (dta_pedido, nro_pedido, cod_cliente, vlr_parcela, vct_parcela, nro_parcela, quitacao) VALUES (:dtaped, :nroped, :codcli, :vlrpar, :vctpar, :nropar, :quit)");
        $Query->execute(array(':dtaped' => $this->Data['dta_pedido'], ':codcli' => $this->Data['cod_cliente'][$k], ':nroped' => $this->Data['nro_pedido'], ':vlrpar' => $this->Data['vlr_parcela'], ':vctpar' => $this->Data['vct_parcela'][$k], ':nropar' => $v, ':quit' => $this->Data['quitacao']
        ));
        $this->Result = true;
        $this->Error = ["Atualizado!", ACCEPT];
    endforeach;
} catch (PDOException $e) {
    $this->Result = false;
    $this->Error = [$e->getMessage(), ERROR];
}

Espero ter ajudado.
Comment: O erro de antes foi resolvido, porem como acho que voce reparou que dentro do meu array no debug eu possuo mais 3 array bidimensionais que seria o numero das parcelas e cada data de vencimento em relação a quantidade de parcelas, agora me aparece isso 'Erro na Linha : # 169 # :: Array to string conversion' essa linha é a do execute!
Comment: eu estava usando foreach justamente pra cadastra todos os registros tipo 5 parcelas, então 5 registros!
Comment: Entendi. Um dos campos que define a quantidade de parcelas é o `nro_parcela`, correto?
Comment: Isso mesmo 'nro_parcela' =>
    array (size=3)
      0 => string '1' (length=1)
      1 => string '2' (length=1)
      2 => string '3' (length=1)
Comment: nesse caso é 3 parcela, mas, pode ser 5 6 7 até 12.
Comment: Muito obrigado!

Cadastro no foreach php


How can I learn Cuban/AfroCuban and Latin Jazz piano?

Question: I'm wondering if some people can point me towards some learning material that they may have enjoyed for learning Cuban style Latin Jazz.
Ideally I'd like something I can learn on my own time -- online resources like PDFs available for download would be great but also some DVD material could be great too. I'd like to at least learn the scales to navigate and get familiar with.
Comment: Found this which looks like it could be quite nice: http://www.musicnotes.com/sheetmusic/book.asp?ppn=BKHL2500729
Comment: I've edited the question to better fit [our rules for recommendations](http://meta.music.stackexchange.com/questions/161/community-wiki-list-recommendation-questions-and-you). Hope you don't mind, and please feel free to add some more criteria for what you're looking for.
Answer: I think this might interest you.
The most important part in Cuban music/Latin Jazz is the rythmic pattern known as Clave.

This is in essence what defines the music. Harmonically, you often do very simple V-I or I-IV-V-I or II-V-I over this pattern. The piano is essentially used as a percussive instrument and for providing the harmonic background. So when you play a montuno, which is how the part of the piano is called, you often do that in octaves (i.e. left hand imitates right hand). Of course this is all true except for the possibility of improvised solos, or if you want to play an entire song piano solo.
Here's something useful to practice with: a recording of a clave.
Comment: The document in the scribd link has been deleted. It's difficult for me to understand how to decipher the "I-IV-V-I" chord progression notation for latin music. In C major, I-IV-V-I equals to C-F-G-C. The problem is C-F-G-C does not sound latin, eg I play C maj for a whole note duration, F maj for whole, G for whole and C for whole. This doesn't sound latin obviously. Is there some intrinsic meaning in C-F-G-C? Like "first play the C for a half note, then D and E as quarter notes" (in C major, the first chord)


Migrate VM from Virtual to Physical Server

Question: I'm after viewpoints on my situation from my fellow sysadmins.  I think I have thought of the points, but want someone else's opinion.
I have an ESXi5 Cluster consisting of 5 Physical machines: 4 in DRS Pool and 1 spare for DR. Nothing sits on this in case we need to Vmotion to spread the load during a spike we can. It's also quite handy for maintenance windows.
We have a Database server that is starting to getting more use as the business grows (A good thing!). It is gotten to the point now where I want to take the Database server out of the cluster and move it to its own separate physical hardware, because I can't give it enough virtualized resources currently.  I'm of two minds whether to install ESXi onto this, as the ESXi Hypervisor has very little overhead and then I can add this machine as part of our cluster so should anything go wrong we still have another server to back this up.
On the other hand, I am thinking I could just install Windows 2008R2 and use a MSSQL Database to host this on its own as over time I think we may go down the route of database replication. There will be no local storage as this is all SAN based.
Can anyone foresee any problems with hosting this as a virtual host?
EDIT
Edit I have accepted Jeremy's Answer as this has provoked some of my thoughts and has led me to a solution. I will be keeping this as a VM below is what I plan to do.
I will be  adding another ~100GB RAM into 2 of our Servers, so in case one fails there is still enough resources in the cluster.
I will be setting DRS to apply affinity's to  this and allow for more vCPU's and also network traffic and constrain this to a single host unless in failure.
Comment: What is your current bottleneck for the database server?
Comment: So in both scenarios would the hardware specs be the same?
Comment: This might be of interest to you: http://serverfault.com/questions/339007/virtualizing-microsoft-sql-database-server
Comment: There are organizations that have deployed almost all of their VMWare hosts with single guests simply for ease of portability.  Are you planning to utilize directpath or similar to otherwise optimize I/O? These kinds of measures may limit portability and such...
Comment: RAM ANd network IO.  Already have an additional nic ind the servers for residency of storage (ISCI). Yea hardware would be the same.
Answer: This is a case of examining the database server's metrics. Do you have any performance graphs to share? Fill in some of the information about your setup.

What is the resource footprint of the DB server? RAM? Number of vCPUs?
How are you currently handling storage for the DB virtual machine? VMDK? RDM?
What are the specifications of your ESXi hosts? CPU type? CPU speed? RAM?
What else is running in the cluster?
What are the specifications of the storage array?

You're using VMWare Distributed Resource Scheduling (DRS), so I'm assuming the load for the vSphere cluster has been balanced effectively. Given that, what would you gain by isolating the server onto its own hardware (as a VM)? That's assuming that the resources allocated to the database VM are a small subset of what's available in the machine. The presence of DRS also means that you have the ability to give 8 vCPU and 64GB of RAM to the database VM.
Where's the bottleneck from the application side?
Answer: After writing my mini-analysis below, I think you should keep it virtual, and add that DR host to the cluster to boot (there is no real advantage of a hot-spare in ESXi that I can really think of)
Advantages to keeping the DB server as a VM:

Greater availability (VM can run on any host, providing the host can provide enough resources)
Greater flexibility (DR is easier, backup may be easier depending on how you currently do your backups)
Server OS's lifetime is extended, because it is not tied to physical hardware. Of course you can P2P or P2V anything but that adds additional complexity down the road.

These reasons above are some of the standard, well-known and accepted advantages of virtualization.
Since the DB server's storage is SAN based, we can take that out of the equation for the most part.
The disadvantage to keeping it virtual is that you have to pay VMWare licensing for its resources. On a physical box you just install Windows and you are done.
If your DB server is constrained for network I/O you can upgrade the NICs in just one ESXi host and set a DRS affinity rule to run that VM on that host unless the host is unavailable.
If you are constrained for RAM, you have to add more RAM anyway.


StrongSwan on Amazon Linux with RADIUS

Question: I'm trying to run strongSwan on an Amazon Linux instance with authentication against RADIUS but I receive an error when trying to start strongSwan
charon[9518]: 00[CFG] RADIUS initialization failed, HMAC/MD5/RNG required
To install strongSwan I ran
yum install strongswan
# swanctl --version
strongSwan swanctl 5.7.1

# swanctl --stats
loaded plugins: charon pkcs11 tpm aesni aes des rc2 sha2 sha1 md4 md5 mgf1 random nonce x509 revocation constraints acert pubkey pkcs1 pkcs7 pkcs8 pkcs12 pgp dnskey sshkey pem openssl gcrypt fips-prf gmp curve25519 chapoly xcbc cmac hmac ctr ccm gcm curl sqlite attr kernel-netlink resolve socket-default farp stroke vici updown eap-identity eap-sim eap-aka eap-aka-3gpp eap-aka-3gpp2 eap-md5 eap-gtc eap-mschapv2 eap-dynamic eap-radius eap-tls eap-ttls eap-peap xauth-generic xauth-eap xauth-pam xauth-noauth dhcp led duplicheck unity counters
cat <<EOF > /etc/strongswan/strongswan.d/charon/eap-radius.conf
eap-radius {
    load = yes
    nas_identifier = ${DNSNAME}
    retransmit_timeout = 30
    retransmit_tries = 1
    servers {
        primary {
            preference = 99
            address = ${RADIUSFQDN}
            auth_port = 1812
            secret = ${RADIUSPSWD}
            sockets = 5
        }
    }
}
EOF

Complete startup log
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 06[MGR] tried to checkin and delete nonexisting IKE_SA
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 06[IKE] unable to resolve %any, initiate aborted
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 06[CFG] received stroke: initiate 'pod'
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 05[CFG] added configuration 'pod'
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 05[CFG]   loaded certificate "CN=vpn.test.dev.poddev.naimuri.uk" from 'vpnserver.crt'
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 05[CFG] adding virtual IP address pool 192.168.250.0/24
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 05[CFG] received stroke: add connection 'pod'
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal strongswan[10484]: charon (10493) started after 60 ms
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal ipsec_starter[10484]: charon (10493) started after 60 ms
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 00[JOB] spawning 16 worker threads
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 00[LIB] loaded plugins: charon pkcs11 tpm aesni aes des rc2 sha2 sha1 md4 md5 mgf1 random nonce x509 revocation const
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 00[CFG] no script for ext-auth script defined, disabled
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 00[CFG] HA config misses local/remote address
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 00[CFG] loaded 0 RADIUS server configurations
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 00[CFG] loading RADIUS server 'primary' failed, skipped
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 00[CFG] RADIUS initialization failed, HMAC/MD5/RNG required
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 00[CFG] opening triplet file /etc/strongswan/ipsec.d/triplets.dat failed: No such file or directory
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 00[CFG] sql plugin: database URI not set
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 00[CFG]   loaded RSA private key from '/etc/strongswan/ipsec.d/private/vpnserver.key'
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 00[CFG] loading secrets from '/etc/strongswan/ipsec.secrets'
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 00[CFG] loading crls from '/etc/strongswan/ipsec.d/crls'
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 00[CFG] loading attribute certificates from '/etc/strongswan/ipsec.d/acerts'
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 00[CFG] loading ocsp signer certificates from '/etc/strongswan/ipsec.d/ocspcerts'
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 00[CFG] loading aa certificates from '/etc/strongswan/ipsec.d/aacerts'
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 00[CFG]   loaded ca certificate "C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3" from '/etc/strongswan/ipsec.d/
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 00[CFG] loading ca certificates from '/etc/strongswan/ipsec.d/cacerts'
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 00[LIB] openssl FIPS mode(2) - enabled
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 00[CFG] PKCS11 module '<name>' lacks library path
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal charon[10493]: 00[DMN] Starting IKE charon daemon (strongSwan 5.7.1, Linux 4.14.72-73.55.amzn2.x86_64, x86_64)
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal ipsec_starter[10484]: Starting strongSwan 5.7.1 IPsec [starter]...
Nov 13 14:14:34 ip-10-0-0-218.eu-west-2.compute.internal strongswan[10484]: Starting strongSwan 5.7.1 IPsec [starter]...

Comment: How did you configure strongSwan to authenticate to RADIUS?
Comment: @MichaelHampton Added the config to the question
Comment: Try promoting the _hmac_ plugin by setting `load=-1` in `/etc/strongswan/strongswan.d/charon/hmac.conf`.
Comment: @ecdsa Still the same.
Comment: Ah, sorry, it's the other way around. See my answer.
Answer: The problem is that you are using OpenSSL in FIPS mode, which disables MD5 as that's not FIPS-approved.
While you do have both the md5 and hmac plugins loaded, the latter is ordered after the openssl plugin, which still registers its own implementation of HMAC_MD5_128. This implementation can even be instantiated, as the plugin's HMAC constructor really only checks if there is a static EVP_MD instance for the given hash algorithm, which, unfortunately, is the case for MD5 even in FIPS mode. However, using that instance with HMAC_INIT_ex() later fails (what triggers the error is trying to set the key on the HMAC instance).
To avoid this you could either disable FIPS mode (via charon.plugins.openssl.fips_mode), or make sure that the HMAC implementation provided by the hmac plugin is used instead of that of the openssl plugin.
The latter can be achieved by modifying the load setting of either of these plugins in their respective config snippet in /etc/strongswan/strongswan.d/charon in order to either demote the openssl plugin (set it to a negative numeric value), or by promoting the hmac plugin (set it to a value > 1). After a restart, the plugin order seen in swanctl --stats should be changed accordingly, and the output of swanctl --list-algs should show that the hmac plugin is providing HMAC_MD5_128.
Comment: I took your idea of the FIPS and in the openssl.conf file there is an option to disable FIPS which I set to 0 and now it's loaded the RADIUS configuration. Thank you!

StrongSwan on Amazon Linux with RADIUS


why Apache's setEnvIf doesn't set correct header and how to debug it

Question: I have the following in my .htaccess file:
<IfModule mod_headers.c>
    SetEnvIf Origin "http(s)?:\/\/(www\.)?(inreado\.local|testenv\.inreado\.com|inreado\.com)$" AccessControlAllowOrigin=$0$1
    Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    Header set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
    Header set Access-Control-Allow-Credentials true
</IfModule>

I'm trying to set Access-Control-Allow-Origin header if host is one of the three allowed domains specified in the regexp. But it never does set this header. Here is the request and response:
REQUEST
GET http://inreado.local:8080/ HTTP/1.1
Host: inreado.local:8080
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en,en-US;q=0.8,ru;q=0.6

RESPONSE
HTTP/1.1 404 Not Found
Date: Sun, 22 Mar 2015 09:44:17 GMT
Server: Apache/2.4.10 (Win64) PHP/5.6.3
X-Powered-By: PHP/5.6.3
Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS
Access-Control-Allow-Credentials: true
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8

I've tested regexp against http://inreado.local string here and it should match, so I don't understand where the problem is.
Update
SetEnvIf Origin "http(s)?://(www\.)?(inreado\.local:8080)$" AccessControlAllowOrigin=$1$2
Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin

Answer: UPDATE : Obviously the first thing to do is to send the Origin header in your request ...
Your regex is "http(s)?:\/\/(www\.)?(inreado\.local|testenv\.inreado\.com|inreado\.com)$"
But I believe it doesn't match at all because you need to add the port to this URL regex (since inreado.local and inreado.local:8080 are two distinct origins). Thus your header directive is skipped since the env variable is not set.
So :

Add the relevant Origin header in your request.
Add the port to your regex.

By the way escaping slashes is not necessary in your regex.
Comment: @Maximus Well, didn't see that but it looks like you are not sending the `Origin` header at all in your request ...
Comment: thanks a lot!!! missing `origin` in request caused the problem. By the way, with `AccessControlAllowOrigin=$1$2` `Access-Control-Allow-Origin` header returns empty string, but with `$0$1` it works OK.
Comment: Thanks, I've figure that out myself. However, I also have [this question](http://serverfault.com/questions/677405/why-apache-returns-error-message-in-body-while-returning-200-status-code), maybe you'll be able to help here. Thanks!


change the enddate choice with jquery datepicker

Question: I have 2 textboxes: StartDate and endDate
How can I make so the user will be able to pick from the endDate only the dates starting from the startDate text box and ending 24 hours after the startDate?
I tried this but it didnt work:
$("#startDate").change(function() {
    test = $(this).datepicker('getDate');

    $("#endDate").datepicker("option", "minDate", test);

});

Thanks in advance!
Greg
Answer: You can set the minDate to 1 day later than the chosen #startDate like this:
$("#startDate").change(function() {
  var test = $(this).datepicker('getDate');
  test.setDate(test.getDate() + 1);
  $("#endDate").datepicker("option", "minDate", test);
});

You can test it out here.


Does there exist a projective module over $k[x_1,...,x_n]$ which is not free?

Question: I know that finitely generated projective modules over $k[x_1,...,x_n]$ are free does this result hold for any projective module?

Does there exist a projective module over $k[x_1,...,x_n]$ which is not free?
Comment: I think this is a corollary of the Theorem 4.3 from [this paper](https://projecteuclid.org/download/pdf_1/euclid.ijm/1255637479) of Bass.
Comment: @spohreis Bass' theorem shows that all projective modules over $k[x_1,...,x_n]$ are free. What do you want more then this?
Comment: Please add this as an answer.
Answer: A CW answer to remove this from the unanswered list: All projective modules are free; this is the main result of this paper by Hyman Bass.
Comment: According to the paper, shouldn't the answer to the question in the title be 'no'?, i.e. non-f.g. projectives over polynomials rings *are* free?
Comment: Edited, thanks!


How to extract text from PDF and get translation between coordinates in page and string position?

Question: I want to extract plain text from a PDF and run it through a named entity recognition function that spits out text and string positions.
I'm thinking of using pdfminer to extract text from my PDF. And I wonder if it's possible to translate back to page coordinates from string positions. For example, if my extracted text were 'Hello World', how do I get the page coordinates of 'World' given its string positions [5:11]?
Thank you!
Comment: PyMuPDF will allow you to iterate all text, and give you page coordinates down to a line of text, then down to the individual characters. So you could search any line for "Hello World", then iterate through the characters of that line, keeping track of the bounding boxes for the chars that make up "World". The doc has a very nice visual reference for how span relates to line, and how line relates to the page: https://pymupdf.readthedocs.io/en/latest/textpage.html#structure-of-dictionary-outputs
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Answer: How to reverse PDF Word positions is not easy so lets use a basic example

%PDF-1.4
1 0 obj <</Type /Catalog /Pages 2 0 R>>
endobj
2 0 obj <</Type /Pages /Kids [3 0 R] /Count 1>>
endobj
3 0 obj<</Type /Page /Parent 2 0 R /Resources 4 0 R /MediaBox [0 0 500 800] /Contents 6 0 R>>
endobj
4 0 obj<</Font <</F1 5 0 R>>>>
endobj
5 0 obj<</Type /Font /Subtype /Type1 /BaseFont /Helvetica>>
endobj
6 0 obj
<</Length 44>>
stream
BT /F1 24 Tf 175 720 Td (Hello World!)Tj ET
endstream
endobj
xref
0 7
0000000000 65535 f
0000000009 00000 n
0000000056 00000 n
0000000111 00000 n
0000000212 00000 n
0000000250 00000 n
0000000317 00000 n
trailer <</Size 7/Root 1 0 R>>
startxref
406
%%EOF

So here it is very clear the Helvetica string is at x=175 y=720 (i.e. near the  top of a default page) but the page is 800 units high not a more natural 842 pt so first problem is what do you mean by co-ordinates and what projection/transformation is at play?
So we can easily say the x value for World! will usually be positive from the left edge, but the origin could be top right of that media thus World! would be negative both in x and y.
For everyday PDF pages we work with default origin for text as bottom left corner of crop box or media box, unless we see stated otherwise. Likewise for images their origin is normally calculated from Top Left corner, but that may be outside their crop boundary. Libraries will help give you relative values, which with luck are simplified to one common origin and scale, with little conflict due to transformation.
In this case we could expect for bottom left of World! x = 236 & y = 80 (800-720).
However a simple HTML conversion may use top:94px;left:263px for the two words together.

Hello World!

If you need a precise position for text then a Printer Trace of components gives the most accurate printout answer
mutool trace hello.pdf
<fill_text colorspace="DeviceGray" color="0" transform="1 0 0 -1 0 800">

        <g unicode="H" glyph="H" x="175" y="720" adv=".722"/>
        <g unicode="e" glyph="e" x="192.328" y="720" adv=".556"/>
        <g unicode="l" glyph="l" x="205.672" y="720" adv=".222"/>
        <g unicode="l" glyph="l" x="211" y="720" adv=".222"/>
        <g unicode="o" glyph="o" x="216.328" y="720" adv=".556"/>
        <g unicode=" " glyph="space" x="229.672" y="720" adv=".278"/>
        <g unicode="W" glyph="W" x="236.344" y="720" adv=".944"/>
        <g unicode="o" glyph="o" x="259" y="720" adv=".556"/>
        <g unicode="r" glyph="r" x="272.344" y="720" adv=".333"/>
        <g unicode="l" glyph="l" x="280.336" y="720" adv=".222"/>
        <g unicode="d" glyph="d" x="285.664" y="720" adv=".556"/>
        <g unicode="!" glyph="exclam" x="299.008" y="720" adv=".278"/>

</fill_text>

So W of World starts at x="236.344" y="720"
We can also calculate the Width of that Wor[l]d either by adding each advance
Total Advance for World = 2.611 units which transformed by 24 = 62.664 wide = 22.10647 mm
or we can do it by simpler subtraction since we know ! is at 299.008 so -236.344 also = 62.664
Comment: I appreciate the explanation. Does seem more complex than it appears. I figured I'll just compromise and use search instead of using string indices. https://stackoverflow.com/questions/47497309/find-text-position-in-pdf-file
Answer: You can extract text from pdf using Python fitz module
import fitz
doc = fitz.open("yourpdffilepath")
text = ""
for page in doc:
    text+=page.get_text()


Conversão de tipo dando errado

Question: Estou com um problema de conversão de dados quando passa pelo For Each, acusa que o item "vl_maodeobra" não pode ser convertido de String para o tipo Integer. O prolema é que não importa a conversão que eu tente fazer da o mesmo erro, só mudando a mensagem, por exemplo: não pode ser convertido de String para Double ou para Decimal.
O item "vl_maodeobra" retorna números com virgula, decimais e a Query abaixo retorna os dados corretamente. O erro só aparece quando passa na linha vl_mo_total += mObra.Rows("vl_maodeobra").ToString().
Eu estou tentando Somar o valor da mão de obra para cada linha que retornar da query.
SB = New System.Text.StringBuilder
SB.Append(" Select a.vl_maodeobra ")
SB.Append(" from garantia a ")
SB.Append(" where a.dt_exclusao is null ")
SB.Append(" and a.dt_inclusao >= to_date('01/01/2013', 'dd/mm/yyyy') ")
SB.Append(" and a.cd_laudo = 21 ")
SB.Append(" and cd_tipo_garantia <> 'C' ")
SB.Append(" and a.vl_total > 0 ")
SB.Append(" and a.nu_lote = " & LO.ToString & " ")
SB.Append(" and a.cd_concessionario = 5 ")
Dim mObra As DataTable = DB.CreateDataTable(SB.ToString)

If mObra.Rows.Count >= 1 Then
   Dim vl_mo_total As Double = 0
   For Each currow2 As DataRow In mObra.Rows
      vl_mo_total += mObra.Rows("vl_maodeobra").ToString()
   Next

Answer: Experimenta isto:
If mObra.Rows.Count >= 1 Then
   Dim vl_mo_total As Double = 0
   For Each currow2 As DataRow In mObra.Rows
      vl_mo_total += Convert.ToDouble(currow2("vl_maodeobra")) //esta é uma forma simplificada
   Next
End If

Coloquei no GitHub para referência futura.
Pode ser que precisa de alguma adaptação na conversão dependendo do que você precisa e de como esta dado é retornado.
Mas ainda fica a questão, você trabalha com valor monetário com o tipo Double? Espero que tenha sido apenas um teste.
Comment: Então use `Decimal`. `Double` é **proibitivo** para valores monetários, ele tem problemas de precisão. Ele funciona bem para cálculos científicos, mas é péssimo para valores financeiros que não pode ter diferenças de centavos. veja: http://pt.stackoverflow.com/a/38140/101 Leia tudo. Seu código pode causar problemas financeiros e até mesmo legais para a empresa.
Comment: Por enquanto estou só testando, mas assim que funcionar e o cliente aprovar subirei para produção. Dessa forma funcionou, mas você não recomenda o tipo Double para valor monetário ? Porque em alguns casos passará de 100 resultados e cada resultado terá um valor diferente, podendo ser bem alto o valor.
Comment: Irei trocar para decimal. Muito Obrigado !
Comment: Posso estar errado, mas acho que se no banco de dados essa coluna não é obrigatória é necessário testar se o valor é nulo (DbNull).

Conversão de tipo dando errado


How to bind textarea id to tiptap editor?

Question: I'm kinda new to Tiptap. I want to use textarea element from another component(FormComponent) instead of using the content property(editor option). Is this even possible?
const TiptapEditor = () => {
  const editor = useEditor({
    element: document.getElementById('description'), // It didn't work.
    extensions: [StarterKit],
    content: 'Hello World! ', // I don't want this
  })

  return <EditorContent editor={editor} />
}

export default TiptapEditor

Another component where the textarea element is.
const FormComponent = () => {
  const {
    register,
    handleSubmit,
    watch,
    formState: { errors, isSubmitting, isSubmitted, isDirty, isValid },
  } = useForm<ExampleType>({
    mode: 'onChange',
    resolver: zodResolver(ExampleSchema),
    defaultValues: {
      description: '',
    },
  })
  return (
    <form onSubmit={handleSubmit(submit)} noValidate>
      <TiptapEditor /> // obviously, this does not work at the moment.
      <textarea
          id="description" // I want to use this textarea so that I don't have to add another styling.
          placeholder={DESCRIPTION_PLACEHOLDER}
          {...register('description')}
        />
      <button></button>
    </form>
  )
}

I can't really find examples or documentation related to this issue.
Any ideas?
Answer: Could you expand on why you do not want to use the content field?
I use Tiptap in forms, with react hook forms. Rather than using register I use controller:
const CompactNotepadController: React.FC<CompactNotepadControllerProps> = ({
  name,
  required = false,
  readOnly = false,
  active = !readOnly,
  value,
  label,
  contacts,
}) => {
  return (
    <Controller
      name={name}
      rules={{ required }}
      render={({ field: { onChange, value: rhfValue, ref } }) => {
        return (
          <Input.Wrapper ref={ref} label={label} required={required}>
            <Box
              sx={{
                border: active ? "1px solid #ced4da" : "1px solid transparent",
                borderRadius: "4px",
                "&:focus-within": {
                  borderColor: "#fd7e14",
                },
              }}
            >
              <Notepad
                initialValue={rhfValue}
                onChange={onChange}
                readOnly={readOnly}
                contacts={contacts}
              />
            </Box>
          </Input.Wrapper>
        );
      }}
    />
  );
};

The content field is just used as initial value, and the editor will handle the state and I just feed back the changes to the form.
If you could share more info about why the content field is your problem, I could try to expand on my answer.
Edit
This is how the notepad component could look like
interface NotepadProps {
  readOnly?: boolean;
  initialValue?: string;
  onChange?: (value: string) => void;
}

export const Notepad: React.FC<NotepadProps> = ({
  readOnly = false,
  initialValue = "",
  onChange,
}) => {
  const preProcessedValue = useMemo(() => {
    return preProcesseInitialContent(initialValue);
  }, [initialValue]);

  const editor = useEditor({
    onUpdate: ({ editor }) => {
      onChange?.(postProcessContent(editor.getHTML()));
    },
    extensions: [StarterKit],
    content: preProcessedValue,
  });

  // Force set content on edit/read only change
  useEffect(() => {
    if (!editor) {
      return undefined;
    }

    if (editor.isEditable !== !readOnly) {
      editor.commands.setContent(preProcessedValue);
      editor.setEditable(!readOnly);
    }
  }, [editor, preProcessedValue, readOnly]);

  return (
    <>
      {editor && !readOnly && <NotepadCornerMenu editor={editor} />}
      <EditorContent editor={editor} />
    </>
  );
};

Comment: Thanks for the answer Disco. Maybe I should try with the controller not the register. I'd like to know how the Notepad component looks like.
Comment: Updated the answer with a example of how the notepad component could look like. Let me know if you have more questions.
Comment: @Disco what's `preProcesseInitialContent` function? How it works? I am trying implement resetting the content after submit. However, it is not resetting and I also wrapped it inside `Controller`
Comment: `preProcesseInitialContent`is just a function that I run to change some of the html to make sure it can be picked up by my custom extensions. Its more of a hack that I used since I could not get tables to work the way I wanted.
If you want to reset the content in the editor, you will have to force it with setContent as I do when I switch between readonly/editable.
You can also just change the `key` of the component in the parent to force a rerender that should reinit the editor and set it to the initial value.


Login failure for VSTS (localDb)

Question: I am trying to get my integration tests included in my CI build.
I would like to deploy a database project to the VSTS (localDB) instance so I can run my unit tests.
So far I have the SQL local db installed during the build this helped
I also found this PS script to deploy the dacpac to the localDb (works fine locally).
However the login is failing when I run the script.

I tried changing the connection string to IntegratedSecurity=True - but that didn't work.
How do I go about adding the login for the test database?
Answer: I ended up figuring this out.  Turns out my error was in the last part of the PS script that I found.

I simply removed it (it only surfaces the details of the table created).
Bottom line is I get the (localDb)\v12.0 created and the database project deployed (dacpac) during the build process so all of my integration tests can run in VSTS CI.
One last note to anyone who trips up on this - remove the Integrated Security=True from the dac service connection:

you connection should read "Data Source=(localDb)\v12.0;Pooling=False;"

Login failure for VSTS (localDb)


Find integer solutions to $7236x + 3283y = 201$

Question:
Find integer solutions to $$7236x + 3283y =  201$$ and show no solutions exist if $x \ge 0$ and $y \ge 0$.

This boils to $108x + 49y = 3$ Taking mods, we get:
$10x \equiv 3 \pmod{49}$, which means $x \equiv 15 \pmod{49}$ so $x = 15 + 49k$. That means $y = 3 - 1620 - 5292k = -1617 - 5292k$.
Thus, $(x, y) = (15 + 49k, -1617 - 5292k)$.
Suppose $x \ge 0$ then, $k \ge 0$, which implies that $-5292k < 0$ thus $-1617 - 5292k < 0$. Suppose $y \ge 0$ then $-5292k \ge 1617 \implies k \le -1$ which implies $15 + 49k < 0$.
Complete?
Answer: By your calculation, there is a suitable $y$ if $x=15$. Substituting in the equation $108x+49y=3$ we get $y=-33$.
You showed that the general solution for $x$ is $x=15+49k$, where $k$ ranges over the integers. The appropriate $y$ for $x=15+49k$ is $y=-33-108k$.
As to solutions with $x$ and $y$ both $\ge 0$, looking at the original equation shows us there cannot be any. For $(0,0)$ does not work, and if one or both of $x$ or $y$ is $\ge 1$, then $7236x+3283y$ is much larger than $201$.


Dúvida sobre o funcionamento do BaseAdapter e da ListView

Question: Meu código é o seguinte: no método getView do meu BaseAdapter, eu adiciono todas as views criadas à uma lista (preciso disso para fazer uma certa coisa). Nesse mesmo BaseAdapter, eu tenho um método getQuantViews que retorna quantas views foram adicionadas à essa lista.
No meu fragment, eu uso o listview.setAdapter para criar as views e em seguida, eu chamo o tal método getQuantViews do meu BaseAdapter para saber quantas views foram adicionadas e exibo isso em um Log.
Ao carregar o ListView, percebo no log que a ordem dos processos não está acontecendo corretamente, pois no log, primeiro é chamado o getQuantViews e depois que se entra no getView.
Cometi algum erro na ordem dos processos? Pois, ao meu ver, primeiro ele entraria no getView ao usar o setAdapter e só depois que ele chamaria o getQuantViews. Tentei também separar os processos, colocando o setAdapter no onStart e depois chamar o getQuantViews no onResume, mas o resultado foi o mesmo.
No Base Adapter:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    Trial t = listTrial.get(position);
    View layout;

    if(convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        layout = inflater.inflate(R.layout.item_trial, null);
    } else {
        layout = convertView;
    }

    DecimalFormat df = new DecimalFormat("####.00");

    linkViews(layout);

    tv_trial_name.setText(t.getName());
    tv_trial_date.setText(t.getDate());
    tv_trial_hour.setText(t.getHour());
    tv_peak_force.setText(
            layout.getResources().getString(R.string.text_peak_force) + ":  " + df.format(t.getPeakForce()));
    tv_comments.setText(t.getComment());

    this.listViews.add(layout);
    Log.v("Bio", "listViews size: " + this.listViews.size());

    return layout;
}

public int getQuantViews() {
    return this.listViews.size();
}

No Fragment:
@Override
public void onStart() {
    loadTrials();
    super.onStart();
    Log.v("Bio", "onStart");
}

@Override
public void onResume() {
    super.onResume();
    Log.v("Bio", "onResume");
    check();
}

O método loadTrials seta o baseadapter:
private void loadTrials() {
    tAdapter = new TrialAdapter(view.getContext(), list_trials);
    lv_trials.setAdapter(tAdapter);
}

O método check mostra a quantidade de views da lista
public void check() {
    Log.v("Bio", "Retorno: " + tAdapter.getQuantViews());
}

Comment: Mesmo não sabendo o que você quer fazer com essa lista suponho que, preenche-la no método `getView()`, não irá fazer o que você quer já que ele é chamado sempre que é necessário fazer o *display* de uma linha. Sempre que for feito *scroll* o método será chamado e serão adicionados novos itens, ela irá crescer indefinidamente e terá itens repetidos.
Comment: O método `getView()` do *Adapter* só é chamado quando a *ListView* necessita de fazer o *display* de uma linha na tela e não quando o `setAdapter() é chamado.
Comment: A dúvida é se o `onResume` deveria rodar antes do `onStart`? Acho que não, isso não acontece por causa do ciclo de vida da [Activity](http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle). Além disso o `getView` é chamado pelo `ListView` e isso é feito em alguma das primeiras passadas de layout (não garanto que seja a primeira).
Comment: Não, a dúvida é porque ele está chamando o .getQuantViews() se antes ele teria que passar pelo GetView do BaseAdapter para criar os layouts
Comment: então como eu faria para chamar meu método *getQuantViews* depois que todos os itens fossem exibidos?
Answer: Você pode utilizar o metodo getCount do base adapter e verificar se a posicao atual do getView é igual ao valor retornado pelo getCount, caso seja igual você terá chegado no fim da lista. Essa comparação seria feita dentro do próprio getView onde vc poderia estar exibindo o log de acordo com sua necessidade.


How to resolve error Code 403 from Cowin Public API in android studio?

Question: Here's the link to the Cowin Public API:

https://apisetu.gov.in/public/marketplace/api/cowin#/
https://cdn-api.co-vin.in/api/v2/admin/location/states

I have been trying to get the state details from the 2nd link in android studio using retrofit library. But every time I run the app it's showing error 403. Any help would be appreciated!! Adding my code below:

On create activity:

    Retrofit retrofit = new Retrofit.Builder().baseUrl("https://cdn-api.co-vin.in/api/").addConverterFactory(GsonConverterFactory.create()).build();

        CovidAPI covidAPI = retrofit.create(CovidAPI.class);

        Call<StateMainModel> call = covidAPI.getAllIndiaStates();

        call.enqueue(new Callback<StateMainModel>() {
            @Override
            public void onResponse(Call<StateMainModel> call, Response<StateMainModel> response) {
                if(!response.isSuccessful())
                {
                    Toast.makeText(getApplicationContext(),"Error!!Code: "+response.code()+response.toString(),Toast.LENGTH_SHORT).show();
                    tv.setText(response.toString());
                    return;
                }
                else
                {
                    StateMainModel stateMainModel = response.body();

                    int size = stateMainModel.getStates().size();

                    for(int i=0;i<size;i++)
                    {
                        stateList.add(stateMainModel.getStates().get(i).getState_name());
                    }

                    stateAutoCompleteTextView.setAdapter(stateAdapter);
                }

            }

            @Override
            public void onFailure(Call<StateMainModel> call, Throwable t) {
                Toast.makeText(getApplicationContext(),"Error!! Response: "+t.getMessage(),Toast.LENGTH_LONG).show();
            }
        });

API Interface

@GET("v2/admin/location/states")
    Call<StateMainModel> getAllIndiaStates();

StateMainModel Model Class

private ArrayList<StateIdNameModel> states;
    private Integer ttl;

    public StateMainModel() {
    }

    public StateMainModel(ArrayList<StateIdNameModel> states,Integer ttl) {
        this.states = states;
        this.ttl = ttl;
    }

    public ArrayList<StateIdNameModel> getStates() {
        return states;
    }

    public void setStates(ArrayList<StateIdNameModel> states) {
        this.states = states;
    }

    public Integer getTtl() {
        return ttl;
    }

    public void setTtl(Integer ttl) {
        this.ttl = ttl;
    }

Answer: You first need to create an object of class OkHttpClient and then you will have to add interceptor to it since it requires key to access the api
Answer: You have to set the User-Agent in your request to get a successful response. See the below Kotlin code:
val okHttpClientBuilder = OkHttpClient.Builder()
val logger = HttpLoggingInterceptor().apply { level = Level.BODY}
okHttpClientBuilder.addNetworkInterceptor { chain ->
                    chain.proceed(chain.request()
                        .newBuilder()
                        .header("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36")
                        .build())
}.addNetworkInterceptor(logger)
val retrofit = Retrofit.Builder()
                .baseUrl("https://cdn-api.co-vin.in/api/v2/")
                .client(okHttpClientBuilder.build())
                .addConverterFactory(MoshiConverterFactory.create())
                .build()

Comment: Okay, that is something new to which I came across today. Do you have any idea how do I set user-agent in Java?
Comment: See the answer here: https://stackoverflow.com/a/63996219/6147653
Comment: Thanks buddy!! It worked. btw why do we need to use this?
Comment: They have restricted the API only for browsers, So I tried it with the browser user agent and it worked.
Answer: Here's the Java Code that worked for me:
OkHttpClient client = new OkHttpClient();

        client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {

                Request originalRequest = chain.request();
                Request requestWithUserAgent = originalRequest.newBuilder().header("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36").build();
                return  chain.proceed(requestWithUserAgent);

            }
        }).build();


How to make URL arguments available as tokens in Rewrite Results of a Field in a View?

Question: Is it possible to make URL arguments, e.g.
http://mysite.com/arg1/arg2/arg3

available as tokens in the rewrite results settings for a field in views e.g. for the above these would be available for use (among other existing tokens) as:
[arg1] [arg2] [arg3]

Background
I am developing Views using OpenLayers maps with filtered items place in an overlay on them. When the user interacts with the map to remove items, I want to retain the position of the map (an not have it revert to a default zoom and position) when the page reloads. By being able to access the URL arguments i.e. longitude and latitude, I can then rewrite the filter URL so that these are sent back to the page.
But I'm sure there are other scenarios that don't use maps that people would find answers to the question useful for.
Answer: If you do not want to actually use a contextual filter, you can use a "Global: Null" contextual filter, use the Contextual filters options to assign the value from the argument position you are interested in and then that becomes available as a %1/!1 replacement token without actually affecting the query.
Answer: If arg2 and arg3 are, or can be, arguments/contextual filters in the View in question, you should be able to use !1 and !2 in the rewrite.
I am ignoring arg1 as that really can't easily be dynamic.
ADDITION:
This could be another case of my assuming D7 hasn't gotten rid of D6 features, but a quick screen grab here (I don't have a D7 testbed handy right at this sec, sorry) shows this as part of rewrite when arguments are present:

This is a quick View with two arguments, a node nid and type, and when I rewrite this field (the title), I can put in Hello [title] where nid is !1 and type is !2 and it works.
2ND ADDITION:
Even though this answer no longer is valid to the issue at hand (see abounding comments on both answers), @Molot did confirm that these replacement patterns are available in D7:

so perhaps this and his answer will help someone else looking out there.
Comment: http://i.stack.imgur.com/e5X2y.png - screenshot from D7 - works. NID is forst contextual filter there
Comment: Ah.  Well let us all know if we can take another whack at it.  If it is something like `www.yourhost.com/some/path#latlong` the `#latlong` is in fact being sent to the backend, that's an anchor tag, it will just be basically ignored if it doesn't exist on the server (but it certainly can be seen by drupal).  Cheers!
Comment: Jimajamma so would I, for example, put !2 or [!2] directly in the text box for 'rewrite this field' - as in: http://i44.tinypic.com/4rrgy0.png - this doesn't seem to work, as this screen shot shows - !2 or [!2] is output. By the way I am (necessarily) using aggregation so don't know whether this is interfering - see screenshot: http://i44.tinypic.com/2vmc84m.png Reason for aggregation here: http://drupal.stackexchange.com/a/79064/1082 (thanks for your input so far Jimajamma)
Comment: I've never seen the !2 or !3 notation before as tokens in the rewrite results for a view, I have to admit though I hope it works with some advice on where I am going wrong with using it as per last comment.
Comment: Thanks Mołot (+1) and Jimajamma - this has now started to appear and I'll experiment further to confirm - I think something is a bit 'flakey' with my setup as these did not show before. If all's well I would like to accept Jimajamma's answer (thanks Mołot - I'll upvote all your posts, when I come back to confirm...)
Comment: Hope to still accept this answer, once again thank you Jimajamma for your answer, Mołot for supporting it and also input from Clive. Update: although I can see the `!1` etc. in the available rewrite tokens, I get this output literally in the URL `%211` for `!1` or `%212` for `!2` I think I'll come back to it later for another look, with a fresh pair of eyes.
Comment: I've also just realised that my particular situation does not apply - I wanted the long lat part of the URL for openlayer maps to be passed back in - 2 issues: 1) the long lat part of the URL is preceded by a # (which is never passed to the server-side (upon which Drupal runs), remains on the browser but Javascript can see it) and 2) this long lat part doesn't 'belong' to any particular content queried by the view so another approach is needed (try to alter the way the URL for an openlayer map is constructed so that this is visible to the server). Nonetheless your answers are much appeciated.
Answer: Assuming arguments you want to use are not views arguments or contextual filters, if you wantthem as tokens, you basically need to create a module that implements hook_tokens() and hook_token_info(), as described in the API. I don't think anyone did it already.
Here is how I'd do it:
function yourmodule_token_info() {
  $type = array(
    'name' => t('GET'),
    'description' => t('Tokens related to $_GET superglobal.'),
  );
  $tokens = array();
  foreach($_GET as $key => $val) { //discard $val now
    $tokens[$key] = array(
      'name' => $key,
      'description' => "\$_GET['$key']",
    );
  }
  return array(
    'types' => array('get' => $type),
    'tokens' => array('get' => $tokens),
  );
}

function yourmodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  if($type == 'get') {
    $replacements = array();
    foreach ($tokens as $name => $original) {
        $replacements[$original] = (string)$_GET[$name];
    }
    return $replacements;
  }
}

Of course code above is not production ready, it ignores proper type handling, security issues and so on. It's meant to set you on the right track, but you need to apply your own sanity before deploying it. I take no responsibility for abuse. Read about the reasons it was removed in the first place before you decide to add it back, and be careful to restore only what you really need.
If you want parameters accesible by arg() instead of $_GET, of course in hook_tokens iterate over them with while:
function yourmodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  if($type == 'arg') {
    $replacements = array();
    $i = 0;
    while ( NULL !== ($arg = arg($i))) {
        $replacements["arg:$i"] = (string)$arg;
    }
    return $replacements;
  }
}

Change yourmodule_token_info() accordingly.
Comment: if arg2 and arg3 are actually arguments or contextual filters for the View in question, you should be able to just use `!2,` `!3` in the rewrite (I am ignoring arg1 as that really can't easily be dynamic)
Comment: @therobyouknow http://i.stack.imgur.com/e5X2y.png D7 supports this too, just tested it. Dunno why it does not work for you. Jimajamma's answer is OK if arguments are in contextual filters. At least works for me. (LOL 'm fighting against my answer being accepted)
Comment: @therobyouknow DO NOT SERIAL UPVOTE ME! And honestly, upvotes on this post earned me 2x more rep than acceptance would, so no need to worry ;) After all I asked Jimajamma to post his comment as an answer, right? And I was fighting to prove his way is easier :P So it should be obvious I don't mind his post to be accepted.
Comment: +1 thank you very much @Mołot So, had this feature been considered for views by the developers involved, in the past and decided against? It is likely I will accept your answer, I'll give the code you gave a try.
Comment: @therobyouknow tokens from $_GET are costly and messes with cache, afaik. And see my updated answer before you'll try.
Comment: @Jimajamma my mistake - I assumed it's not about that. Blindness to the obvious. If you'll post it as an answer I'll gladly upvote.
Comment: Thanks also for your input Jimajamma - but I'm not sure if I have used your `!2` etc. suggestion correctly - the string `!2` gets output directly from my View - see my comments (and screenshots below your answer)
Comment: Just nit-picking, but you should really `switch ($name)` inside the `foreach` loop in `hook_tokens()`; as it is, even if you define several token types in the `_info()` hook, they'll all be subject to exactly the same replacement logic
Comment: Clive thanks for your input I will bear that in mind. By the way, are you familar with using `!2` and `!3` notation in rewrite results to obtain URL arguments for the output of a field in a View? I've never seen this before and tried Jimajamma's suggestion above but I just get `!2 `output itself as a string!
Comment: @Clive I meant it as an outline, hence *"It's meant to set you on the right track, but you need to apply your own sanity before deploying it."* - but feel free to edit my code and add that check too. I admit at the moment I don't have time to rewrite it :( Will try to remember and do it tomorrow, if you will not.
Comment: @therobyouknow Sorry no, I've only ever used/seen `%1` etc for Views placeholders. Bearing in mind the various formats [`format_string()`](https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/format_string/7) provides, though, it kind of makes sense. Though (hypothetically) the `!` would pass the string through unsanitized which might not be desirable
Comment: @Mołot You're right you've disclaimed that pretty well - I just breezed through the code :)
Comment: Clive, to be exact, `!` as in exclamation mark character followed directly by the numeral 2 i.e. `!2` not percentage character followed by numeral 2 i.e. `%2`. I'm really scratching my head on this one, what did Jimajamma mean (please come back and advise) also Mołot concurs with using `!2` etc. Mołot do you know what Jimajamma meant by using `!2` ?!
Comment: @therobyouknow Did you read the `format_string()` docs I linked to?
Comment: @Clive yes, that `format_string()` is worth knowing - it's like a kind of `printf()` in the `C` language but I think it is rather that Jimajamma's answer is assuming that such notations `!1` and `!2` in rewrite results in views in D6 have been carried forward into D7, as he explains in his [edited answer](http://drupal.stackexchange.com/a/79147/1082). As `format_string()` shows, `!2` is inserting the value of the variable `2` as is but that variable has to be defined in the first place, i.e. for my case, this variable `2` would be the arg2 of the URL.
Comment: Yep might well be that, I didn't really use Views in Drupal 6 so I can't help there I'm afraid
Comment: Clive yes seems like this is the case, sadly. So Mołot's answer would likely be the accepted one once I try it out and if successful. Though apparently this may have been considered in the past and discounted on the grounds of security - Mołot welcome your further thoughts on this when you can. Thanks everyone so far. Most appreciated.
Comment: Thanks Mołot (+1) and Jimajamma - this has now started to appear and I'll experiment further to confirm - I think something is a bit 'flakey' with my setup as these did not show before. If all's well I would like to accept Jimajamma's answer (thanks Mołot - I'll upvote all your posts...)


Is it possible to input an address to a pointer from stdin?

Question: Not that long ago, I had an idea for some simple inter-process comunication: one process outputs an address to a pointer, I copy that to the input of another process, and that changes the original variable.
I implemented it like this:
<code>#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    bool p;
    cin>>p;
    if(p){
        int n;
        n=0;
        cout<<&n;
        cin.get();
            cin.get();
            cout<<n;
        }else{
            int *point,n;
            scanf("%p",&point);
            cout<<point;
            cin>>n;
            *point+=n;
        }
        return 0;
    }
</code>
I used scanf because cin complained, and wouldn't compile. I tried to run it, with two processes, but after I launched the second instance, and input the pointer's address, as outputed by the first, it froze. As I only have access to Windows, I have no idea as to whether it got a SIGSEGV, or if it did something completely diferent.
Is it just me trying to change the value of another process's variable that is crashing it, or is it something else that is stopping me?
Comment: This won't work, but there is a Windows API for doing stuff like this - see [ReadProcessMemory](https://msdn.microsoft.com/en-us/library/windows/desktop/ms680553(v=vs.85).aspx)/[WriteProcessMemory](https://msdn.microsoft.com/en-us/library/windows/desktop/ms681674(v=vs.85).aspx) *et al*.
Answer: You cannot do this that way because first process will not have access to the second process' memory address space (in common operating systems, including Windows and Linux).
Comment: ^ In some operating systems, that is. OP's idea would work in MS-DOS
Comment: Thanks, I added it to my answer to make it more precise.
Answer: Each process has its own memory, completely separate from that of other processes. A pointer value is meaningless in context of a different process, even if you manage to get it across.


Setting Account Lockout Threshold in MS SQL Server 2008

Question: I have to set Account Lockout Threshold to some specific value In MSSQL Server 2008. How can i do this? I have googled and not able to find the exact solution how to do it.
Whether SQL server account uses default Windows threshold to lock the sql account?
Thanks in advance...
Santhosha
Answer: SQL Server 2008 uses the password policy enforcement settings from the domain or local machine. To set it you need to edit the domain policy that applies to the SQL server if the SQL server is joined to a domain, or edit the local machine policy if the SQL server is not joined to a domain.
Answer: You can not. SQL Server has no account lockout threshhold for it's user management. For trusted connections it also has none - because you have to come through a trusted connection, which means wherever you got your trust from (outside) the value was taken into account.
Comment: Then how the behavior "Account Locked out" is  decided?
Answer: SQL server has 2 possible authentication modes, Mixed and Windows authentication only.  In mixed mode accounts may be stored inside sql server and may have a different complexity setting as well as logins using windows accounts.  In windows authentication only windows accounts can be used and user account information is not stored in sql server.  Regardless of authentication type account lockout behaviour is defined by the security policy that affects the account in question for local accounts local ecurity policy applies and for domain accounts domain group policy applies


Is there a way to impute chi-square data?

Question: I've tried looking here, as well as the go-to book Flexible Imputation of Missing Data, but cannot seem to find any reliable information on how to simulate chi-square missingness (as well as imputing it with multiple imputation). I tried simulating some data like so. Note that while I have NA listed explicitly, I also tried with NA as a character value and it didn't change the outcome.
#### Load Library and Set Seed ####
library(mice)
library(miceadds)
set.seed(123)

#### Create Data ####
color <- c("blue","green","purple","red",
                 "orange","black","gray",NA)
choice <- c("yes","no",NA)

#### Sample ####
color.sample <- sample(color, size= 100, replace = T)
choice.sample <- sample(choice, size = 100, replace = T)
df <- data.frame(color.sample,choice.sample)

If you run head(df), it will look something like this:
   color.sample choice.sample
1           red           yes
2           red            no
3         black          <NA>
4        orange           yes
5          gray          <NA>
6           red            no
7          blue            no
8        purple          <NA>
9        purple          <NA>
10         gray            no
11        black          <NA>
12       orange            no
13         blue           yes
14       purple          <NA>
15         blue            no
16        black            no
17       purple            no
18          red            no
19        black            no
20       orange          <NA>

Then all that's left is imputation...
#### Impute ####
imp <- mice(df)

Once I get to this last step, no matter how many ways I alter the factor data, I get this error:
Error in edit.setup(data, setup, ...) :
  `mice` detected constant and/or collinear variables. No predictors were left after their removal.

This doesn't make much sense to me. I would think that if my data is randomly sampled, there should be no collinearity issues. What could be causing this and is there a solution? I looked in the categorical data section of Buuren's book, but the polyr, polyreg, pmm, and logreg methods all seem to not work.
Answer: mice does not implicitly coerce character variables in your data.frame into categorical factor variables.  You can check the format of your variables using str(df)
This works:
df <- data.frame(factor(color.sample),
                 factor(choice.sample))

imp <- mice(df)

Comment: Wow that worked like a charm and simple to do. Thanks a bundle.


Is This a Bug? Can't Specify form id using form_for in Padrino

Question: I have this form_for tag:
= form_for @food, :autocomplete => "off", :id => "food" do |f|

This is the tag it generates:
<form action-autocomplete="off" action-id="food" accept-charset="UTF-8" method="post">

How can I specify the html form id attribute from the form_for tag?  Note that padrino has added an "action" before the autocomplete attribute as well.
This looks like a bug to me.  I'm using version 0.12.2 of Padrino.
Answer: You need to specify the URL as the second parameter in case you want to use a custom id. The code should be:
= form_for @food, '/path/to/create/', id: 'food' do |f|

code for form_for
This is a similar pattern adopted from Rails. In Rails, however, you don't have to specify the URL as the second argument and the HTML-based settings go in to the html option key. Worth opening an issue for this.
Comment: Apparently using the empty string for the url parameter will suffice for posting back to the same url.


Partial derivatives and continuity of function in two variable

Question: Can we use the increment theorem for proving that functions with bounded partial derivatives is continuous ?
(There is one question similar to this asked in 2013.But I want to know what is wrong with this proof)
$\delta z= f_{x}\delta x+f_{y}\delta y+\epsilon_{1}\delta x+\epsilon_{2}\delta y$ where $\epsilon_{1} $ $\epsilon_{2}$ tends to $0 $ as $\delta x,\delta y$ tends to $0$
But $\delta z =f(x+\delta x,y+\delta y)-f(x,y)$ Applying boundedness of partial derivatives $f_{x} $and  $ f_{y}$ we get as $limit f(x+\delta x,y+\delta y)=f(x,y) $ as $\delta x,\delta y$ tends to $0$.
Answer: You do not know $f$ is differentiable just because it has partial derivatives. Of course, differentiability always implies continuity.
EDIT: To clarify, your stipulation that $\epsilon_i\to 0$ requires that $f$ be differentiable. We don't have that.
Comment: Can we say that ? There are functions whose partial derivatives exist but functions are discontinuous.
Comment: Right. Those functions are not differentiable!


Wget Minimum Download Rate

Question: Can anyone help with the parameter that ensures that wget will fetch the file at a minimum specified  download rate?
Comment: This doesn't seem theoretically possible.  If I have a 1Mb connection and I set the minimum to 10Mb/s, how is `wget` going to achieve that?  Did you mean "maximum" instead of "minimum"?
Answer: You can not set minimum download rate. You can set the maximum download rate using <code>--limit-rate=amount</code> option. Amount is expressed in bytes per second.

Wget Minimum Download Rate


Images and CSS effect not showing

Question: Hello I'm using Drupal 6 and I've successfully finished with the site. However, after I uploaded the site to the server, I realised the the header image which is the logo is not showing even though the path is correct in the theme logo path.
Also there is a slide show which was made with Dynamic Display Block module and its images does not show up even though their path is present and correct.
The css style I applied to the three column under the DD Block is also not showing.
This still persists even if I change theme.
Does anyone know what's wrong under the hood?
Thank you
Comment: check file permissions and double check if file exists in specified location
Comment: I have crosschecked all permission especially uploaded files with respect to the problem at hand. All files exists in their respective directories and the path to each is very correct, yet problem still persists. :(
Comment: if you request the path of the logo image directly in the address bar of your browser, does it show up ?
Comment: It mustn't be possible for people to do that due security purposes. However, I did that anyway, and it wasn't successful.  It returned:

Access forbidden!

You don't have permission to access the requested object. It is either read-protected or not readable by the server.

Also, you cannot see the images when you use firebug debugger!
Answer: I think you should check the permission of "sites" and "files" folders. You cannot access to the folder.
I think something happened when you uploaded the website. Usually I do a fresh installation of drupal then I upload the files inside "all" folder and the files insidethe "files" folder inside "default". In the end through Backup and Migrate module I upload the db.
It must be a permission problem if you see the images there.
Let me know.
Comment: I did all that, just as you do yours, and yet problem still persists! :(
Comment: Awesome! It worked! It's from the hosting company! I spoke to them, and I got them fix it!

Images and CSS effect not showing


Groovy vs Groovyc

Question: I am new in Groovy and I do not understand the difference between groovy and groovyc. So if I have this file,
hello.groovy
println "Hello World"

If I run groovy hello.groovy it prints "Hello World"
If I run groovyc hello.groovy it generates a .class file and if I then run groovy hello it prints "Hello World"
Now coming from ruby, this confuses me. Is groovy a compiled of interpreted language?
Comment: It can be treated as both, as you've seen
Answer: Groovy is a compiled language, but it allows you to execute scripts.  Calling groovy like you did compiles and runs the script.  Calling groovyc only compiles your code.
See: http://www.javalobby.org/articles/groovy-intro1/
Answer: Groovy is a language which is derived from Java. groovyc is the Groovy compiler which is able to produce JVM bytecode that can be executed as any normal Java compiled program.
In both circumstances the code is compiled, either with groovy and groovyc but in the first case it is dynamically compiled into bytecode and executed while with the standalone compiler just the bytecode is generate (and saved for later use)

Groovy vs Groovyc


Is there a term for a finite state machine that is guaranteed to halt?

Question: I was having a discussion earlier about a state machine, and there was a question as to whether it might not halt on some input.  It seems like a property of state machines that is important and frequently mentioned, but I can't for the life of me figure out what the name of that property is.  Is there such a term? Is it "haltable", "not-infinitely-loopy", or something else?
Comment: Had to give it +1 for "not-infinitely-loopy"
Answer: A machine that always halts is called a decider.
A decider need only be a machine that halts on all inputs. For example, all DFAs are deciders, as are DPDAs.
Comment: Ah, yes, that was it exactly!  Thank you very much!
Comment: Cool! Didn't know that. I'll leave my previous answer below just in case people are interested in the Halting Problem.
Answer: My guess would be "halting", derived from the famous "halting problem", which is similar to your question, namely whether it will halt on a given input. An important consideration is that a machine is not defined as "halting" in general, but rather for a specific input. The general case is proven to be unsolvable (by Turing himself).


Measure on Locally Compact, Separable metric space

Question: Simon (Geometric Measure Theory) says:
If $X$ is a locally compact, separable metric space and $\mu(K) < \infty$ for all $K$ compact, then $X=\cup_{i=1}^\infty U_i$ where $U_i$ are open and $\mu(U_i) < \infty$.
I tried showing this by using separability $X=\cup_{i=1}^\infty B(x_i,r)$ for some $r>0$. However, I am unable to prove that each of the open balls $B(x_i,r)$ is contained in a finite union of compact sets (using the local compactness property). This would ensure that the measures of the open balls are finite and so the assertion will be ture. In $\mathbb{R}^n$ this can be done.
I am not sure if this is true in general metric spaces. Any help on how to prove this assertion generally is much appreciated.
Answer: Hint: Since $X$ is locally compact and separable, there exists a countable basis $\{U_i\}_{i=1}^{\infty}$ for the topology such that $\overline{U}_i$ is compact for every $i$...
Comment: Tom: In this case, I am not sure how to show that $X=\cup_{i=1}^\infty U_i$.
Comment: @jpv You're right! It needn't be the case. I'll edit my response (along the same lines, but without this oversight).
Comment: Tom: Thanks for the edit. I think this proves. I hope I will be able to get a proof of this somewhere.
Comment: Tom: I was unable to find a proof of this. Could you provide a reference?
Comment: I found the way: A separable metric space is Lindelof. Now, $X$ can be covered by a union of balls centered at every point of $X$. These balls are taken from the local compactness of $X$. This way, we get a countable cover of $X$ by the balls and hence by the compact sets.


In how many ways can a number be chosen from 1 to 20 such that it is a multiple of 2 or 3?

Question:
In how many ways can a number be chosen from $1$ to $20$ such that it is a multiple of $2$ or $3$?

Numbers that are multiple of $2=\{4,6,8,10,12,14,16,18,20\}$ $=>9$ choices
Numbers that are multiple of $3=\{6,9,12,15,18\}$ $=>5$ $=>5$ choices
Hence there are $14$ choices. But this answer is scored as the wrong answer. How to solve this problem correctly?
Comment: 2 is considered a multiple of 2.  i.e. $2 = 2\cdot 1.$  (And, 0 is a multiple of everything.)   By the same logic 3 is a multiple of 3.
Comment: and besides 6 in both lists - there's also 12 and 18 in both
Comment: Problems of enumeration should be tagged combinatorics.
Comment: Well $6$ appears in both lists ...
Comment: I am not even able to understand if it is a problem of enumeration or probability, this question has been asked as a part of Permutations and Combinations.
Answer: There are $10$ numbers,$[\frac{20}{2}]=10$, can divisible by $2$
There are $6$ numbers,$[\frac{20}{3}]=6$  can divisible by $3$
There are $3$ numbers,$[\frac{20}{6}]=3$,  can divisible by $6=2\times 3$
by inclusion-exclusion princible
$n(A\cup B) = n(A)+n(B)-n(A \cap B)= 10+6-3=13$


App crashes on performSegue in viewDidAppear

Question: This problem never occurred before and worked on previous apps before I updated to the mac osx 10.10 beta. Now, if I call <code>[self performSegueWithIdentifier:@"segueName" sender:self];</code> in the viewDidAppear method I receive this error message,

<code>"Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: 'Receiver
(SecondViewController: 0x15d9ddc0) has no segue with identifier
'segueName''"
</code>

The segue exists and works fine as long as it's not in the viewDidAppear method. The only exception to this is if the destination view controller isn't attached to a class in the storyboard.
Comment: I didn't know the segue feature is also available for Mac OS X.
Comment: I don't know either I'm working with iOS :P
Comment: You sure the controller has loaded via the storyboard? If it hasn't there may not be a segue to load. Also, double check you haven't got the ID strings wrong, there's always a chance you've missed something. Lastly, if you're acquiring the ID String from somewhere else, output it to the console just to make sure it's being sent through correctly. EDIT: Didn't read the last bit where you say it's in the storyboard, so without seeing more I'm at a loss. Sorry.
Comment: The segue works perfectly fine as well if the second view controller isn't linked to a view controller class
Comment: You sending any parameters through in the prepareForSegue?
Answer: Well I feel kinda stupid now I was subclassing the view controllers under the default ViewController class automatically generated by apple instead of the UIViewController class.


Issue importing custom Python modules in Jupyter notebooks with SparkMagic and AWS Glue endpoint

Question: I'm encountering an issue while attempting to run ETL scripts in Jupyter notebooks using SparkMagic, which is connected to an AWS Glue endpoint via SSH. I followed the tutorial provided in the AWS Glue documentation (link: https://docs.aws.amazon.com/glue/latest/dg/dev-endpoint-tutorial-local-jupyter.html) and successfully set up the connection. I can run Pyspark without any problems.
However, I'm facing difficulties when trying to import custom Python modules that I created. I have ensured that I uploaded my files to the Glue endpoint and placed them in a file directory that I appended to the Jupyter notebook's search path. When attempting to import the module using the following code:
from test.base.text import DataFields

It fails to import because the Python interpreter is set to use /usr/bin/python3 by default. Instead, I need to use the /usr/bin/gluepython3 interpreter.
sys.executable

returns
'/usr/bin/python3'

I have tried several steps to make it use the correct Python interpreter, including:

Configuring sparkmagic to use gluepython3:

%%configure -f
{
    "conf": {
        "spark.pyspark.python": "/usr/bin/gluepython3"
    }
}

Setting the PYSPARK_PYTHON environment variable in the notebook:

alias python="/usr/bin/gluepython3"

Modifying the .bashrc file on the Glue endpoint and creating an alias for Python to point to gluepython3:

alias python="/usr/bin/gluepython3"

Despite trying these approaches, I have only been able to successfully import the module when running the code outside of Jupyter notebook using an SSH shell and manually invoking the Python file on the endpoint:
/usr/bin/gluepython3 /location/to/file.py

Any suggestions or guidance on how to resolve this issue and make the custom module import work within Jupyter notebooks using SparkMagic and the AWS Glue endpoint would be greatly appreciated.
Thank you in advance!
Answer: I'd recommend using notebook in Glue Studio (i.e., interactive session) instead. The Glue doc also suggest migrating away from dev endpoint.
Next, you can upload the files to S3 and add the Python files via %extra_py_files or the wheel file with %additional_python_modules.

Ref: https://docs.aws.amazon.com/glue/latest/dg/interactive-sessions-magics.html

To have greater control, use the local Docker development using Docker image method, which provides access via REPL shell and Jupyter Lab.


Significant difference/ANOVA test when some values occure only once

Question: I have fake dataframe with neighbrhood codes and prices of houses in those neighbrhoods, with this amount of values for each negihborhood:
df['neighb'].value_count()

>>>
a    17
b    5
c    3
d    2
e    2
f    1
g    1
f    1

I need to check if there is significant difference in the prices between the neighbrhoods. The problem is that some neighbrhoods have price of only one house, so I don't have group of values as I only have data regard this one house specifically.
Assuming that I cannot get more data regard house prices, (in this task)
Is there any way I can calcualte if there is significant difference in the prices between the different groups? I wanted to use ANOVA but as the groups are really little I find it problematic (also regard the assumption of normal distribution etc).
*clarification : my real database is not prices of houses, is somethiing that I cannot get more data then what I want but I do need to check if there is significant differences between different neighbrhoods when some have alamost no observations.
Comment: If you have only one price for some groups, I wonder whether you you can do an ANOVA that includes these groups. In your data, maybe you can combine (f,g,h) into a group called 'other'.
Answer: Consider the following simulated data. Notice that standard deviations
differ by group, so I use the oneway.test procedure, which uses a
Saterthwaite approximation to give a reasonable P-value.
set.seed(2021)
a = rnorm(17, 1000, 10)
b = rnorm( 5, 800,  10)
c = rnorm( 3, 2000, 15)
d = rnorm( 2,  500,  8)
e = rnorm( 2, 1100, 10)
fgh = rnorm( 3, 800, 20)
x = c(a,b,c,d,e,fgh)
g = rep(1:6, c(17,5,3,2,2,3))

This one-way ANOVA procedure works fine, and finds a highly significant
difference among groups in my simulated data.
oneway.test(x ~ g)

    One-way analysis of means
    (not assuming equal variances)

data:  x and g
F = 2317.8, num df = 5.0000, denom df = 5.1515, p-value = 1.298e-08

Using the Bonferroni method to protect against 'false discovery' in ad hoc
tests on these data, you might reject two-sample Welch t tests only
for P-values below 1%.
It is not surprising to find a sigificant difference ad hoc between
a and b because of the difference in sample means and 'reasonable'
sample sizes of 17 and 5.
t.test(a,b)$p.val
[1] 5.717784e-09

But some pairs of groups with very small sample sizes are also significantly
different. For example,
t.test(c,e)$p.val
[1] 0.0001867002

Of course, I cannot say what will happen with your real data, but at least
we know that oneway.test with ad hoc comparisons using Welch t tests
is not automatically doomed to failure. I would say that comparisons of
the group fgh of 'leftovers' might be difficult to interpret, but you
really don't have meaningful data there.
Comment: thank you for your answer. so if I understood you correct, you reccoment to use the one-way ANOVA test even if I cannot check the assumptions, and use the Bonferroni method in order to make sure I select the best a value? and also , you were assuming that groups with one observations  can create new group together? (im working with python so i'm appologize if I did not understood some things you did)


Get the PATH in htaccess using $_GET in PHP

Question: Let's suppose that my site is example.com/pageone.
How can I rewrite my htaccess to get the pageone name using $_GET with PHP?
For example, in my code, I want to do something like this:
if($_GET['page'] === 'pageone' && file_exists('./pages/' . $_GET['page'] . '.php')) {
   require_once './pages/' . $_GET['page'] . '.php';
} else {
   require_once './pages/home.php';
}

Answer: This should work for your case
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.+)$ index.php?page=$1 [QSA,L]

Now you should be able to get page requested using $_GET['page']


How find the matrix $X$ such $e^{X}$ is give it

Question:
Question:
let matrix $$X=\begin{bmatrix}
a&b\\
c&d
\end{bmatrix} ,e^{X}=\begin{bmatrix}
-1&2\\
0&-1
\end{bmatrix}$$
  and such $a+d=0$,
Find the matrix $X$
  my idea
  $$e^{Tr{(X)}}=det{(e^{X})}$$
  so
  $$1=1$$ is true

I think we can find the matrix function: $e^X$,but I have find this is ver ugly,so I think this problem have other methods
Comment: https://en.wikipedia.org/wiki/Matrix_exponential
Answer: Firstly, since the eigenvalues of $e^X$ are the exponentials of the eigenvalues of $X$, $X$ can only have eigenvalues of the form $i(\pi+2n\pi)$. Since $e^X$ is not diagonalizable, neither is $X$, so $X$ only has one eigenvalue, say $i\pi$. So we can try $X=\begin{bmatrix} i\pi&z\\ 0&i\pi\end{bmatrix}$. Then, $e^X=e^{i\pi I}e^{\begin{bmatrix} 0&z\\0&0\end{bmatrix}}=-I\left(I+\begin{bmatrix} 0&z\\ 0&0\end{bmatrix}\right)=\begin{bmatrix} -1&-z\\ 0&-1\end{bmatrix}$. So, we can let $z=-2$, and then we see that $\exp\left({\begin{bmatrix} i\pi&-2\\ 0&i\pi\end{bmatrix}}\right)=\begin{bmatrix} -1&2\\ 0&-1\end{bmatrix}$.
Comment: I like your approach a lot. It's definitely cleaner than mine. I'd made the diagonalizability connection but didn't piece it together the way you did. Very nice!
Comment: Thanks. I'm not sure if the OP wanted a real $X$, but I suspect there is no real matrix logarithm of the given matrix.
Answer: Here's a sketch. Since $d = -a$, you can write $X = \left(\begin{array}{rr} a & b \\ c & -a\end{array}\right)$, which gives
$$X^2 = \left(\begin{array}{cc} a^2 + bc & 0 \\ 0 & a^2 + bc\end{array}\right) = (a^2+bc)I.$$
This allows you to write a general expression for $X^n$: $X^{2n} = (a^2+bc)^n I$ and likewise $X^{2n+1} = (a^2+bc)^nX$.
With these two in hand, we can evaluate the exponential:
$$\exp X = \sum_{n=0}^{\infty} \frac{1}{n!} X^n = \sum_{n=0}^{\infty} \frac{1}{(2n)!} X^{2n} + \sum_{n=0}^{\infty} \frac{1}{(2n+1)!}X^{2n+1}.$$
Making use of our above observation:
$$\exp X = \sum_{n=0}^{\infty} \frac{(a^2+bc)^n}{(2n)!}\, I+ \sum_{n=0}^{\infty} \frac{(a^2+bc)^n}{(2n+1)!}\,X.$$
Since $\exp X = \left(\begin{array}{rr} -1 & 2 \\ 0 & -1\end{array}\right)$, we see that $c= 0$, so that
$$\exp X = \sum_{n=0}^{\infty} \frac{a^{2n}}{(2n)!}\, I+\sum_{n=0}^{\infty} \frac{a^{2n}}{(2n+1)!}\,X.$$
From here, if you equate terms, you will find that $a = i\pi+2k\pi$ for some $k\in\Bbb Z$ and $b = -2$ as Nishant derived.


Calendar Module Shows Two Month Links

Question: So I have a view of a calendar with some events listed on it.  I also have this calendar setup to be a block on a page.
The block is on www.example.com/subsite
When I click the block it takes me to the month view of the calendar at
www.example.com/subsite/month
Now, on this view, there are tabs at the top of the calendar in the following order with their respective links:
Month - www.example.com/subsite/month
Month - www.example.com/subsite
Week - www.example.com/subsite/week
Day - www.example.com/subsite/day
Year - www.example.com/subsite/year
So... That second Month link is obviously wrong.  How do I get rid of it and/or change the title to Home?  If I make the Month view not show on the settings page, it removes the Month link that actually goes to the Month view.
Any help would be awesome, thank you.
Comment: Calendar module?
Comment: Yes, http://www.drupal.org/project/calendar
Answer: Two tabs of Month came up in the first place don't make sense. It never happened to me. I would suggest to recreate this Calendar view, it's actually pretty easy if you "add view from template". (Consider you've installed the Calendar Module)
Make sure to select "A calendar view of the 'field_date' field in the 'node' base table." on the list of views/add-template
Comment: This is what managed to fix the second month link.  Additionally, the month link was still wrong but that was because of the way the calendar module creates the month link.  If you have a page at example.com/subsite, you can't have your calendar structure be example/subsite/(day:week:month:year), it needs to be something else, otherwise your month link will link to example/subsite.
Answer: Are you using Quicktabs to create the tabs? If so, you can go to structure > Quicktabs > Configure > Edit. At the bottom of the page, you'll see that you can select your block. You could try checking "Hide the title of this block" for whichever block you are using.

Calendar Module Shows Two Month Links


How can a cross-level interaction be random in a 2-level mixed-model?

Question: I was wondering why m below is a legitimate model? If it is, what is the meaning of its random part?
ses is a level-1 predictor and sector a level-2 predictor making their combinations a cross-level interaction.
In other words, I'm asking how a cross-level interaction can be taken to be random in a 2-level model?
UPDATE: How about model mm with sector in the random part?
library(lme4)

hsb <- read.csv('https://raw.githubusercontent.com/rnorouzian/e/master/hsb.csv')

m <- lmer(math ~ ses*sector + (ses:sector | sch.id), data = hsb)

mm <- lmer(math ~ ses+sector  + (sector | sch.id), data = hsb) #UPDATE

Answer: It's important to remember that an interaction is the product of the two variables.
For example if we have
sch.id  ses  sector
1        1     1
1        2     1
2        3     2
2        4     2

..then the interaction for ses:sector will be:
sch.id  ses  sector  ses:sector
1        1     1        1
1        2     1        2
2        3     2        6
2        4     2        8

So, although sector does not vary with sch.id, the interaction that includes it does, because the other variable, ses, does vary within school.
As such, there is no technical reason why random slopes for such an interaction cannot be included - however it would be odd to fit the first model in the OP - that is, a model with random slopes only for the interaction, since it is impossible to vary an interaction independently of both main effects - so a more appropriate model (provided it is supported by the data) is:
math ~ ses*sector + (ses + ses:sector | sch.id)

Comment: You can try to estimate that model, but it doesn't make much sense as Rob nicely showed in the answer to your previous question - https://stats.stackexchange.com/questions/490919/visualizing-the-folly-of-fitting-random-slopes-for-variables-that-dont-vary-wit
Comment: Yes, that model would not make sense due to the presence `sector` in the random slopes part.


How can I transfer http header to another page?

Question: I would like to know if it is possible to transfer a defined header to another page.  For example in PHP, I want to send http header value to a new page.
I don't know if it's possible.  PHP or JavaScript is fine.
Comment: Transfer header? may be if you could share the purpose, will explain the question
Comment: You could call a page with a curl call and send a header like that, if that's what you mean.
Comment: no idea what you are asking
Comment: It may help to understand what HTTP is and how it works.  http://www.silicon-press.com/briefs/brief.http/brief.pdf
Answer: Yes, you can. Let's say you have some data that you want to send to another file via HTTP, you could do something like I have shown below.
FirstFile.php
<?php
    $someVar = "SomeValue";
    header("Location: SecondFile.php?someVar=" . $someVar);
?>

So, in the above code, you learn how to transmit data to a new file, now to retrieve and utilize that data, you should do the following as I have done.
SecondFile.php
<?php
    $someVar = $_GET['someVar'];
?>

You use the $_GET to achieve this. You can know more about this here.
Comment: I don't think this is what he trying to do.  The question says "HTTP headers" not "GET".
Comment: Yeah, so, does it not look like that he want's to send some variables in the HTTP Header to another page? Perhaps, a flag would be good for this question because the question is itself not very clear.
Comment: well don't answer, just vote to close
Comment: He has accepted this as the answer @Dagon
Comment: @RocketHazmat he has accepted.


Why is the Moore spectrum $S\mathbf{Z}_{(J)}$ a ring spectrum?

Question: Let $J$ be a set of primes and consider the Moore spectrum $S\mathbf{Z}_{(J)}$. In his paper 'The localization of spectra with respect to homology', Bousfield writes that $S\mathbf{Z}_{(J)}$ is a ring spectrum. Why is this the case? I first thought that it would be possible to apply the construction $S(-)$ to the multiplication map $\mathbf{Z}_{(J)} \otimes_{\mathbf{Z}} \mathbf{Z}_{(J)} \to \mathbf{Z}_{(J)}$, but then realized that $S(-)$ is not a functor.
Answer: Indeed Moore spectra need not be ring spectra, or at least $E_n$-ring spectra, see for example
here and here. In your case, your spectra are $E_\infty$-ring spectra because they are the localizations of the sphere spectrum. Indeed you can notice that $$\mathbb S_{(T)}\simeq M(\mathbb Z_{(T)})$$
for $T$ a set of primes, and $M(A)$ the Moore spectrum of the abelian group $A$. By the properties of localization, they all carry an $E_\infty$ stucture induced from that of $\mathbb S$ (essentially because localization commutes with smash product).


Give an example of a $3$-dimensional subspace of $P_4$ which contains the polynomials...

Question: Give an example of a $3$-dimensional subspace of $P_4$ which contains the polynomials $3$+$2t^2$, $t^4$, and $1+2t+3t^3$.
I have no idea how to even get started with this problem. Can I get some help? (Studying)
Answer: If the three polynomials $p_1(t)= 3+2 t^2$, $p_2(t) = t^4$ and $p_3(t) = 1 + 2t + 3 t^3$ are linearly independent, then the can be used as a basis to form a 3 dimensional subspace.
To show that they are linearly independent, I need to show that if $\sum_{k=1}^3 \alpha_k p_k = 0$, then the $\alpha_k = 0$. This gives $\sum_{k=1}^3 \alpha_k p_k(t) = (3 \alpha_1+\alpha_2)+2 \alpha_2 t + 2 \alpha_1 t^2+3 \alpha_2 t^3 + \alpha_3 t^4  = 0$. If  we differentiate 4 times, we get that $\alpha_3 = 0$. If  we differentiate 3 times and set $t=0$, we get that $\alpha_2 = 0$. Just setting $t=0$ gives $\alpha_1=0$, hence these three polynomials are linearly independent.
So, a three dimensional space that contains the given polynomials is given by $S = \text{sp} \{p_k\}_{k=1}^3 = \{ \sum_{k=1}^3 \alpha_k p_k \}_{\alpha \in \mathbb{R}^3}$, where $p_1,p_2,p_3$ are given by above.
Comment: Just curious if I'm missing the obvious, but where does the + 4t^4 come from? Did you combine the first two polynomials?
Comment: My apologies, I misread the question, I thought there were two polynomials. I will fix the response.
Comment: OK, I fixed it, sorry about that!
Comment: No prob! Just making sure. I'm reading your solution now. Thank you so much for your insight.
Comment: This answer was fantastic, albeit a bit over my head. I believe this is an Einstein Summation? I'm assuming part of what it does can be labeled synonymous with the definition of linear independent if it = 0. I will study until I understand.
Comment: Well, no, the summation convention you refer to is just a convention to avoid a proliferation of $\sum$ symbols, but that is not an issue here. The dimension of a subspace is the maximum number of linearly independent vectors that you can find in that space. A set of vectors $v_k$  is linearly independent iff the only solution to $\sum_k \alpha_k v_k = 0$ is $\alpha_k = 0$.
Answer: Perhaps $\text{span}\{ 3+2t^2,t^4,1+2t+3t^3 \}$? I suppose you need to argue that the set in question is indeed linearly independent, but that shouldn't be hard.
Comment: What exactly is P_4?
Comment: I'd expect that someone asking a question here would *at least* understand the symbols he's using...anyway, $\,P_4\,$ *usually* denotes the set of all the polynomials of degree less than or equal $\,4\,$, over some fixed and given field (usually, the reals)
Comment: Ah, that's pretty straight forward. It was unclear to me. Is the fact that the subspace must be 3-dimensional significant to the answer, or would I just span the polynomials and/or prove that they are linearly (in)dependent?
Comment: @LearningPython The question is a bit strange. It seems too simple. Maybe you are supposed to see this as a subspace for some other reason? The kernel of some map, the image of another? Any span is a subspace so my answer is true, but maybe there is a more interesting one...


hook_file_download not triggered

Question: I set the private file system to /system/files/export , I create a file in private directory programmatically and it not belong to any field ,and show link to user , I implement Hook_file_download , I want check some condition in it but when user click on link to download the file created in private path it return me Forbidden and mymodule_file_download not tirggered ( I put some code to it , even die but never called).
I clear cache but noting changes,
the link that showed for user is http://localhost/mytestdrupal/system/files/export/Export-couponcards-1393307265.csv
where is problem?
Part of my code to create file in submit
function mymodule_export_form_submit($form, $form_state) {
    $temp1 = variable_get('file_private_path');
    if (!file_prepare_directory($temp1, FILE_CREATE_DIRECTORY)) {
        drupal_set_message(t('Problem in write file in directory'), 'error');
        return;
    }
    $filename = 'Export-file'. '.csv';
    $filepath = $temp1 . '/' . $filename;
    $df = fopen($filepath, 'w');
    if (!$df) {
        drupal_set_message(t('Can not write file in') . $filepath, 'error');
        return;
    }
            fputcsv($df, array('code', 'name'));
            fputcsv($df, array('test','test'));

    fclose($df);
    $path = file_create_url($filepath);
    drupal_set_message(t('Export done. ') . '' . t('Download export file') . '');
}

Comment: Can you post link shown to user ? It should be system/files/***
Comment: link is `http://localhost/mytestdrupal/system/files/export/Export-couponcards-1393307265.csv`
Comment: Can you post the hook implementation ? That will give us better idea what you are doing and why you are getting forbidden message ..
Comment: 1. Are folder and files permissions correct? 2. check virtual host's (.htaccess) configuration. 3. Check server log, may be you can find something interesting.
Comment: Maybe I'm missing something obvious but it looks like the above code is saving a file to the public directory `variable_get('file_public_path');` not the private file path. Note also the menu callback uses `system/files` but your private folder path should probably be different, e.g `sites/default/files/private` or somewhere outside the webroot.
Comment: @xurshid29 I am working on local , in wamp,
Comment: @DavidThomas sorry after It not worked for me , I change it to public in our module, after `Anil Sagar` ask me to come code in question I copy it from new version and forgot revert it to `private`.
Answer: hook_file_download working perfectly, List of steps which worked for me

I made File System to Private
Created a File Field in Article Content Type and marked it as Private In Settings
Uploaded a PDF File
Link to file is something link below

http://example.com/d7/system/files/**.pdf
Created a custom module with hook_file_download, When ever i access above URL and visit any page i can see drupal set message "Hi"
function drup_custom_file_download($uri) {
  drupal_set_message("Hi");
}

Comment: I said I created file programmatically ,and not belong to any field
Comment: How did you created programatically ? Can you post the code. It should be through file API so that any entry exist in file Table.
Comment: I update question with part of my code that create file
Comment: Can you save your file using https://api.drupal.org/api/drupal/includes%21file.inc/function/file_save_data/7 and try the same ?
Comment: It doesn't have to be in a file field or the drupal managed files table. If you want access to be controlled by file_file_download() then you do but if you have your own hook_file_download() implementation you don't.
Comment: @rooby but I implement hook_file_download , but it not work.
Comment: @AnilSagar ,yes I can,but what is relation between file table and hook_file_download, as its documentation its work according uri
Answer: First you need to verify your file is being saved to the correct place.
You say you want to save to a sub-directory 'export' but that is not what your code is doing.
You should be saving to the private file system, not the public one. So variable_get('file_private_path', '') instead of variable_get('file_public_path').
Then append you export directory, so it would be:
$temp1 = variable_get('file_private_path', '') . '/export';

Then if you file is successfully saved at /sites/default/files/private/export (or wherever your private files should be), then you are ready for the next step.
When making the link to the file you have to pass in a uri, so
$path = file_create_url($filepath);

should be something like:
$path = file_create_url('private://export/' . $filename);

Using the 'private' stream wrapper means that internal links match to /sites/default/files/private (or whatever you have variable_get('file_private_path', '') set to) and external links generate like www.example.com/system/files/...
For more information see: DrupalPrivateStreamWrapper
Comment: sorry, after private not worked , I changed it to public and paste here without notice that it is change to public, it public , I set the private file system to 'system/files/export' ;
Comment: Private file system should be something like sites/default/files/private, unless you actually have a directory on the file system that is system/files. system/files is a drupal url, not an actual directory on the file system.
Comment: First I set it to something if 'defaults/files/private/` after I chnage it to `/system/files/export` there are exist directory and file create correctly (I check it)

hook_file_download not triggered