Copy database from one azure subscription to another subscription

Question: I am trying to copy a database from production to development environment. Both the servers are in Azure, I have made the credentials same in both the server, but I am getting below while executing in SSMS.
Msg 45134, Level 16, State 1, Line 4
The remote partner server name 'XXXXXXXXXX.database.windows.net.database.windows.net' could not be resolved.
I am executing the script from master database in target database.
Answer: Copying a database to a different subscription has worked for me using the following procedure:
(1) Create a new Azure SQL Server on a different resource group.
New-AzureSqlDatabaseServer -Location "East US" -AdministratorLogin "AdminLogin"  -AdministratorLoginPassword "AdminPassword"

(2) Copy the source database to the newly created Azure SQL Server.
Start-AzureSqlDatabaseCopy -ServerName "SourceServer" -DatabaseName "Orders" -PartnerServer "NewlyCreatedServer" -PartnerDatabase "OrdersCopy"

(3) Move the resource group of the Newly created Azure SQL Server to another subscription.
Move-AzureRmResource -DestinationResourceGroupName [-DestinationSubscriptionId ] -ResourceId [-Force] [-ApiVersion ] [-Pre] [-DefaultProfile ] [-InformationAction ] [-InformationVariable ] [-WhatIf] [-Confirm] []

Comment: Is this powershell script?
Comment: Yes, it is PowerShell.
Comment: Cant we do it in SSMS?
Comment: To my knowledge there is no way to move a resource group using Transact-SQL on SSMS. T-SQL does not have a statement for that.
Answer: It is possible to copy an Azure SQL Database using T-SQL as described in the docs but it requires you to use the short server name. E.g:
CREATE DATABASE [Database1] AS COPY OF [server1].[Database1]

If you used the full server name, like in:
CREATE DATABASE [Database1] AS COPY OF [server1.database.windows.net].[Database1]

you will see the error you encountered.


How to tell if my features improve model performance?

Question: Setup

Task: binary classification
Models: logistic regression, SVM, ELM, neural networks - anything that can do classification
Dataset: 10 basic features + 6 my own features

Question
How do I see whether training some model with my 6 new features results in better performance (say, higher accuracy) than training the same model without these features?
EDIT: whenever I say "compare scores" or something like this, I mean "compare scores using out-of-sample/holdout/unseen data". In all 3 points described below, I mean that all comparisons are performed on a holdout set or using cross-validation.
Ways of doing this

The simplest way of doing it is to train a "basic" model using just the 10 basic features, and another model - using all 16 features. Then compute and compare their scores on the respective holdout sets or use cross-validation.

However, the model fitted using 16 features will have more parameters than the basic model. Thus, it could be more "powerful" than the basic model, simply because it has more parameters. This seems especially true for neural networks, where the basic model will have the first layer's weight matrix of shape, say, (45, 10), while the second model's matrix will have shape (45, 16), and elements of these matrices will interact with all features at once.
Thus, I will be comparing a bigger and potentially more powerful model to a smaller one, so I won't be able to tell why the second model outperforms the basic one: is it because the model is more complex? or is it because my features help?
Or is this concern safe to ignore?

I can do several things to ensure that both models have the same number of parameters:

DatasetBasic = 10 basic + 6 zeros and DatasetMine = 10 basic + 6 mine, so essentially I'll be comparing performance of models fitted to some data and zeros vs fitted to the same data and my new features. The number of features in both datasets is the same, so the number of parameters in both models will be the same too.
Or, similarly, use noise instead of zeros: DatasetBasic = 10 basic + 6 random noise and DatasetMine = 10 basic + 6 mine
In general, compare 6 nonsensical features to the 6 features I created and argue that my features result in better scores than the nonsensical ones.
Does it make sense to compare my features against noise or zeros? Won't the presence of noise "confuse" the model and result in poor performance, so I'll end up comparing to an a priori bad ("confused") model?
Also, the accuracy of my SVM model sometimes increases when I add a randomly generated feature, even though the feature is clearly nonsensical. Thus, according to the model, the random feature is not nonsensical, even though I specifically created it to be useless.

I can also use feature importance and argue that since the importance of my features is positive, they indeed increase the score of the model.

However, when computing feature importances, I train the model using DatasetMine = 10 basic + 6 mine, so I'm using my features anyway. But I'd like to see whether adding (somehow; I don't really know how to do this properly) my features to the training set improves performance, not whether permuting these features in the validation set affects something or not.

What are some standard, well-known, widely used, go-to methods of testing whether my features increase the performance of a particular model?
Comment: I'm not sure why you don't like the "simplest way of doing this"

It's absolutely fine to compare two models of very different power/complexity's performance, provided they are being compared on a test set which was not seen during training.

Things might look a little different if you think that in production, your data distribution might drift from your training distribution. In this case, you might still want to penalise more complex models. Even so, this would be a fudge factor, would be better to do time-sensitive cross-validation to quantify this effect.
Answer: This is what an out-of-sample test set reveals. In fact, machine learning tends not to care much about in-sample ("training set") performance, since you can play connect-the-dots and memorize the data, but that models coincidences in the data (noise) instead of the true trend (signal). When you say that your SVM model has its performance improve when you add a feature of pure randomness, I suspect that you will see a drop in performance if you assess that on some out-of-sample data.
Particularly for generalized linear models like logistic regressions, you might also be interested in various information criteria like Akaike (AIC) and Bayes (BIC) that penalize the model for having many parameters in order to keep the higher-parameter model from having an advantage.
This answer of mine discusses how feature removal may or may not result in improved importance and is worth a read, even if it is somewhat tangential.
Finally, "accuracy" is a surprisingly poor performance metric. I will include the usual links I post on this topic.
Are unbalanced datasets problematic, and (how) does oversampling (purport to) help?
https://www.fharrell.com/post/class-damage/
https://www.fharrell.com/post/classification/
https://stats.stackexchange.com/a/359936/247274
Proper scoring rule when there is a decision to make (e.g. spam vs ham email)
Why is it that if you undersample or oversample you have to calibrate your output probabilities?
https://twitter.com/f2harrell/status/1062424969366462473?lang=en
Comment: As some further clarification, the question isn't about testing model performance in general, but more concerned with testing the effect of my _new features_ on some metric of (out-of-sample) performance, be it accuracy, AUC-ROC or whatever else.
Comment: "assess that on some out-of-sample data" - maybe I didn't spell it out well enough, but I'm already doing _all_ comparisons using out-of-sample data. Of course, since I'm interested in some kind of predictive performance, I should be testing on holdout (previously unseen)  data. That's what I'm already doing in all 3 cases I described. "I suspect that you will see a drop in performance if you assess that on some out-of-sample data" - I was expecting the same, but I sometimes got increases in performance anyway...


Segmentation fault when signing a message using OpenSSL, SWIG, and Perl

Question: We were using SWIG to make a C cryptographic utility library available to Perl. We are able to generate keys, create digests, but the signing code causes a segmentation fault, which we believe may be in the OpenSSL code itself but it's difficult to be sure.
This problem only comes up when running the code with SWIG, the native C code works.
In Perl, we call this:
$signature = key_utils::mysignMessageWithPem($pem, $message);

Which calls this code in the .i file:
%newobject mysignMessageWithPem;

%inline %{
  char *mysignMessageWithPem(char *pem, char *message) {
    char *ret = malloc(145);
    char *err = malloc(5);
    int errorCode;

    memcpy(err, "ERROR", 5);

    errorCode = signMessageWithPem(pem, message, &ret);
    char *signature = ret;

    if (errorCode == NOERROR) {
      return signature;
    } else {
      return err;
    }

  }
%}

Which calls this C code:
int signMessageWithPem(char *message, char *pem, char **signature) {

unsigned int meslen = strlen(message);
unsigned char *messagebytes = calloc(meslen, sizeof(unsigned char));
ECDSA_SIG *sig = NULL;
memcpy(messagebytes, message, meslen);

EC_KEY *key = NULL;
BIO *in = NULL;
unsigned char *buffer = NULL;

char *sha256ofMsg = calloc(SHA256_HEX_STRING, sizeof(char));
unsigned char *outBytesOfsha256ofMsg = calloc(SHA256_STRING, sizeof(unsigned char));

digestOfBytes(messagebytes, &sha256ofMsg, "sha256", meslen);
sha256ofMsg[64] = '\0';
createDataWithHexString(sha256ofMsg, &outBytesOfsha256ofMsg);

in = BIO_new(BIO_s_mem());
BIO_puts(in, pem);
PEM_read_bio_ECPrivateKey(in, &key, NULL, NULL);

sig = ECDSA_do_sign((const unsigned char*)outBytesOfsha256ofMsg, SHA256_DIGEST_LENGTH, key);
int verify = ECDSA_do_verify((const unsigned char*)outBytesOfsha256ofMsg, SHA256_DIGEST_LENGTH, sig, key);

if(verify != 1) {
    return ERROR;
}

int buflen = ECDSA_size(key);
buffer = OPENSSL_malloc(buflen);

int derSigLen = i2d_ECDSA_SIG(sig, &buffer);

char *hexData = calloc(derSigLen, sizeof(char));
memcpy(hexData, buffer-derSigLen, derSigLen);

char *hexString = calloc(derSigLen*2+1, sizeof(char));

hexString[derSigLen * 2] = '\0';
toHexString(hexData, derSigLen, hexString);

memcpy(*signature, hexString, derSigLen*2);
signature[derSigLen * 2] = '\0';

EC_KEY_free(key);

BIO_free_all(in);
free(sha256ofMsg);
free(outBytesOfsha256ofMsg);
free(hexData);
free(hexString);

return NOERROR;
}

And returns Segmentation Fault. The most informative error we have gotten is perl crashed with SIGSEGV in EC_KEY_get_key_method_data()
The full code is here: https://github.com/aleitner/bitpay-perl/tree/stack-overflow-question
Is this a bug with SSL, or are we doing this wrong?
Answer: The answer to this question is: we were calling the arguments in the wrong order.
Seriously. The line:
$signature = key_utils::mysignMessageWithPem($pem, $message);
needed to be:
$signature = key_utils::mysignMessageWithPem($message, $pem);
We were in fact doing something wrong. I was tempted to remove the question, but maybe the answer can serve as a cautionary tale or something.
Comment: Don't remove it, someone will get use of it sooner or later


Determining the consistency of two measurements

Question: Suppose there are two independent measurements, $x_1 \pm \sigma_1$ and $x_2 \pm \sigma_2$, both of which purport to measure the same underlying quantity $X$ (which is apriori unknown). For simplicity, we can take these to be Gaussian distributed measurements (but I'd like to be a bit more general if possible).
In the frequentist framework, how does one assess the consistency (or otherwise) of these measurements? That is, how does one make quantitative statements about whether the data are indeed consistent with measuring the same quantity $X$? Of course, intuitively, for $x_1$ and $x_2$ which are far apart (relative to something like $\sqrt{\sigma_1^2 + \sigma_2^2}$), we would like to say they become less and less consistent.
I understand how to approach this problem from a Bayesian perspective: evaluate the Bayesian evidence for two models, one in which the measurements are derived from the same underlying quantity $X$, and one in which they are generated by different underlying quantities ($X_1$ and $X_2$, say). Of course this requires specification of priors on $X$, $X_1$ and $X_2$ (and also priors on the two models).
Attempted solution
Define a null hypothesis in which they do indeed come from the same underlying quantity $X$. Calculate the probability $p(X) = p_1(X)p_2(X)$ of observing 'more extreme' measurements under this model. This can be done analytically for Gaussian distributed measurements, yielding a product of two complementary error functions. The answer is a function of the true (unknown apriori) $X$.
Should one then pick the maximum likelihood $\hat{X}$, plug this into $p(\hat{X})$ and compare that p-value to some threshold $\alpha = 0.05$ (say)? This $\hat{X}$ is in general different from the $X$ which maximises $p(X)$.
Thanks!
Answer: You are almost there.
Say we are measuring the observable $X$ with the accuracy given by variance $\sigma_1^2$. If the true value of $X$ is $\mu$, then the measured value should be random variable whose probability density function (PDF) is given by the Gaussian distribution $N(\mu,\sigma_1)$. Since we do not know the true value of $X$, the best thing we can give as the result of the measurement is to say: the most probable value of $X$ is the one we measure (call it $\mu_1$), the error of the measurement is $\sigma_1$ and, hence, the true value of $X$ is described with the probability density function $N(\mu_1,\sigma_1)$.
So far I said nothing special. Now, let's consider two independent estimates of the same variable $X$. If the errors of the two measurements are $\sigma_1$ and $\sigma_2$, then the measured values $\mu_1$ and $\mu_2$ are random variables given with PDFs $N(\mu,\sigma_1)$ and $N(\mu,\sigma_2)$. Here you can have any other PDF depending on the measurements, procedures and methods used for the estimates. I am taking the normal distributions as an example. We do not know the true value $\mu$, but we can calculate the probability for an absolute difference of the two measured values. Let's call it $y=x_1-x_2$, where $x_1$ and $x_2$ are the two possible values of $\mu_1$ and $\mu_2$. Then the probability for any value of $y$ results to
$p(y)=\int_{-\infty}^{\infty}\int_{-\infty}^{\infty}p(x_1)p(x_2)\delta(y-x_1+x_2)dx_1dx_2=\int_{-\infty}^{\infty}p(x_1)p(x_1-y))dx_1$.
In the case of the Gaussian variables we get $p(y)=N\left(0,\sqrt{\sigma_1^2+\sigma_2^2}\right)$.
This result does not depend on $\mu$ and you can easily calculate the probability that the two measurements differ by the value $|\mu_1-\mu_2|$ or higher, which is the integral of the tails of $p(y)$ distribution. If this probability is lower than 5% (or 1%) you can say that the two measurements disagree or are in tension. Usually, however, the tension is expressed in numbers of $\sigma$, which is simply the ratio $(\mu_1-\mu_2)\left/\sqrt{\sigma_1^2+\sigma_2^2}\right.$. It is simply telling you the position of the value $\mu_1-\mu_2$ on the distribution of this derived observable. If this number is smaller than, say, 1.7, I would not even call it a tension. Otherwise, you can say that, e.g. the estimates are in $2\sigma$ tension, or $2.3\sigma$ away from each other.


Evaluating von-Mangoldt sum of the form $\sum_{1\leq x\leq m} \sum_{1\leq y\leq n}\Lambda(x)\Lambda(y)$, for $m\neq n$

Question: I am unable to understand this since several months.
Let $Λ$ be the von-Mangoldt function.
Then we know the following: $\sum_{1\leq x\leq n}\Lambda(x)^{2}\sim n \log n$.
Then for $m\neq n$ and $x\neq y $ is the following true?\begin{equation}
 \sum_{1\leq x\leq m} \sum_{1\leq y\leq n}\Lambda(x)\Lambda(y) \sim m n.
\end{equation}
Comment: The condition $x\neq y$ does not make much sense. If you do not have that restriction, this is just a simple consequence of the prime number theorem, since your expression is $\psi(m) \psi(n)$ where $\psi$ is the Chebyshev function.
Comment: @Gary, since, $\sum_{1\leq x\leq y\leq n} \Lambda(x)\Lambda(y)\sim n^2$, for $x\neq y$,  I thought I may write like this: $\sum_{1\leq x\leq m} \sum_{1\leq y\leq n}\Lambda(x)\Lambda(y)$
Comment: $\psi(m)\psi(n) \sim mn$
Answer: Your sum is
\begin{align*}
& \left( {\sum\limits_{1 \le x \le m} {\Lambda (x)} } \right)\left( {\sum\limits_{1 \le y \le n} {\Lambda (y)} } \right) - \sum\limits_{1 \le z \le k} {\Lambda ^2 (z)} \\ & = (m + o(m))(n + o(n)) - k\log k+o(k\log k)
\\ & = mn + o(mn) - k\log k+o(k\log k) =mn+o(mn),
\end{align*}
where $k=\min(m,n)$.
Comment: thank you very much indeed ; but how did you get that expression? I m much new to analytic number theory..
Comment: thank you got it


Oracle Store Procedure lendo XML

Question: Preciso fazer uma stored procedure que leia um arquivo XML e grave em uma tabela do meu banco, mas não faço ideia de como fazer isso...
Alguém pode me ajudar?
 tenho 2 horas para entregar isto.
Comment: Eu ia começar a falar sobre CLOB, XMLType e UTL_FILE... Mas 2 horas? O.o
Comment: Pow cara agora tenho até segunda feira, AHUHEAUEHE
Comment: Eu já criei um diretório, uma tabela e tenho um exemplo de xml que eu fiz, agora preciso fazer a procedure que leia o xml e grava na minha tabela, se ela ler os 10 campos ela lê também 1000, fiquei com isso pra resolver neste fds :T
Answer: Caros amigos, encontrei esta solução.
Minhas tabelas são :

Temporária "INFO_XML"
Tabela Final: "TAB_XML"

Tenho apenas 10 dias no mundo Oracle, espero não estar muito equivocado, mas aprendi que um delete antes de mais nada para limpar a tabela, seguido de um commit para que ação seja feita, um cursor é necessário para que ele faça o trajeto, um insert para inserir os valores, extract value para pegar um arquivo externo do banco e colocar dentro das  minhas tabelas.

create or replace PACKAGE BODY PACK_GWP0009
AS
  -- PARAMETROS PARA TESTE : CARGA_CSV , funcionarios.xml
  CURSOR C1
  IS
    SELECT NVL (MAX(Id),0)+1 AS ID FROM INFO_XML;
  CURSOR C2  IS
  SELECT
     EXTRACTVALUE (value(func), '/Transaction/Order/MerchantID') MerchantID
    ,EXTRACTVALUE (value(func), '/Transaction/Order/RequestID') RequestID
    ,EXTRACTVALUE (value(func), '/Transaction/Order/TransactionDate') TransactionDate
    ,EXTRACTVALUE (value(func), '/Transaction/Order/MerchantReferenceNumber') MerchantReferenceNumber
    ,EXTRACTVALUE (value(func), '/Transaction/Customer/BillTo/FirstName') FirstName
    ,EXTRACTVALUE (value(func), '/Transaction/Customer/BillTo/LastName') LastName
    ,EXTRACTVALUE (value(func), '/Transaction/Customer/BillTo/Address1') Address1
    ,EXTRACTVALUE (value(func), '/Transaction/Customer/BillTo/City') City
    ,EXTRACTVALUE (value(func), '/Transaction/Customer/BillTo/State') State
    ,EXTRACTVALUE (value(func), '/Transaction/Customer/BillTo/PostalCode') PostalCode
    ,EXTRACTVALUE (value(func), '/Transaction/Customer/BillTo/Country') Country
    ,EXTRACTVALUE (value(func), '/Transaction/Customer/BillTo/Phone') Phone
    ,EXTRACTVALUE (value(func), '/Transaction/Customer/BillTo/Email') Email
    ,EXTRACTVALUE (value(func), '/Transaction/Customer/BillTo/CustomerID') CustomerID
    ,EXTRACTVALUE (value(func), '/Transaction/Payment/CardType') CardType
    ,EXTRACTVALUE (value(func), '/Transaction/Payment/CardScheme') CardScheme
    ,EXTRACTVALUE (value(func), '/Transaction/Payment/CardIssuer') CardIssuer
    ,EXTRACTVALUE (value(func), '/Transaction/Payment/CardBIN') CardBIN
    ,EXTRACTVALUE (value(func), '/Transaction/Payment/CardBINCountry') CardBINCountry
    ,EXTRACTVALUE (value(func), '/Transaction/Payment/OrderAmount') OrderAmount
    ,EXTRACTVALUE (value(func), '/Transaction/Payment/OrderCurrency') OrderCurrency
    ,EXTRACTVALUE (value(func), '/Transaction/Payment/LocalOrderAmount') LocalOrderAmount
    ,EXTRACTVALUE (value(func), '/Transaction/AFSInformation/Score') Score
    ,EXTRACTVALUE (value(func), '/Transaction/AFSInformation/Factors') Factors
    ,EXTRACTVALUE (value(func), '/Transaction/AFSInformation/InfoCodeString') InfoCodeString
    ,EXTRACTVALUE (value(func), '/Transaction/AFSInformation/IPInformation/IPAddress') IPAddress
    ,EXTRACTVALUE (value(func), '/Transaction/AFSInformation/IPInformation/IPRoutingMethod') IPRoutingMethod
    ,EXTRACTVALUE (value(func), '/Transaction/AFSInformation/IPInformation/IPCountry') IPCountry
    ,EXTRACTVALUE (value(func), '/Transaction/AFSInformation/IPInformation/IPState') IPState
    ,EXTRACTVALUE (value(func), '/Transaction/AFSInformation/IPInformation/IPCity') IPCity
    ,EXTRACTVALUE (value(func), '/Transaction/TravelData/CompleteRoute') CompleteRoute
    ,EXTRACTVALUE (value(func), '/Transaction/TravelData/DepartureDateTime') DepartureDateTime
    ,EXTRACTVALUE (value(func), '/Transaction/TravelData/JourneyType') JourneyType
    ,EXTRACTVALUE (value(func), '/Transaction/TravelData/NumberOfPassengers') NumberOfPassengers
   -- ,EXTRACTVALUE (value(func), '/Transaction/TravelData/Passenger/FirstName') FirstName
   -- ,EXTRACTVALUE (value(func), '/Transaction/TravelData/Passenger/LastName') LastName
   -- ,EXTRACTVALUE (value(func), '/Transaction/TravelData/Passenger/PassengerType') PassengerType
    ,EXTRACTVALUE (value(func), '/Transaction/MerchantDefinedData/Field1') Field1
    ,EXTRACTVALUE (value(func), '/Transaction/MerchantDefinedData/Field2') Field2
    ,EXTRACTVALUE (value(func), '/Transaction/MerchantDefinedData/Field3') Field3
    ,EXTRACTVALUE (value(func), '/Transaction/MerchantDefinedData/Field4') Field4
    ,EXTRACTVALUE (value(func), '/Transaction/MerchantDefinedData/Field5') Field5
    ,EXTRACTVALUE (value(func), '/Transaction/MerchantDefinedData/Field6') Field6
    ,EXTRACTVALUE (value(func), '/Transaction/MerchantDefinedData/Field7') Field7
    ,EXTRACTVALUE (value(func), '/Transaction/MerchantDefinedData/Field9') Field9
    ,EXTRACTVALUE (value(func), '/Transaction/MerchantDefinedData/Field10') Field10
    ,EXTRACTVALUE (value(func), '/Transaction/MerchantDefinedData/Field11') Field11
    ,EXTRACTVALUE (value(func), '/Transaction/MerchantDefinedData/Field12') Field12
    ,EXTRACTVALUE (value(func), '/Transaction/MerchantDefinedData/Field14') Field14
    ,EXTRACTVALUE (value(func), '/Transaction/MerchantDefinedData/Field15') Field15
    ,EXTRACTVALUE (value(func), '/Transaction/MerchantDefinedData/Field16') Field16
    ,EXTRACTVALUE (value(func), '/Transaction/MerchantDefinedData/Field17') Field17
    ,EXTRACTVALUE (value(func), '/Transaction/MerchantDefinedData/Field21') Field21
    ,EXTRACTVALUE (value(func), '/Transaction/MerchantDefinedData/Field25') Field25
    ,EXTRACTVALUE (value(func), '/Transaction/MerchantDefinedData/Field26') Field26
    ,EXTRACTVALUE (value(func), '/Transaction/CaseManagement/Profile/Active/Name') Name
    ,EXTRACTVALUE (value(func), '/Transaction/CaseManagement/Profile/Active/Decision') Decision
    ,EXTRACTVALUE (value(func), '/Transaction/CaseManagement/Profile/Active/NumberOfRules') NumberOfRules
    ,EXTRACTVALUE (value(func), '/Transaction/DeviceFingerprint/Fingerprint') Fingerprint
    ,EXTRACTVALUE (value(func), '/Transaction/DeviceFingerprint/SmartID') SmartID
    ,EXTRACTVALUE (value(func), '/Transaction/DeviceFingerprint/SmartIDConfidenceLevel') SmartIDConfidenceLevel
    ,EXTRACTVALUE (value(func), '/Transaction/DeviceFingerprint/ScreenResolution') ScreenResolution
    ,EXTRACTVALUE (value(func), '/Transaction/DeviceFingerprint/TrueIPAddress/Address') Address
    ,EXTRACTVALUE (value(func), '/Transaction/DeviceFingerprint/TrueIPAddress/Country') Country
    ,EXTRACTVALUE (value(func), '/Transaction/DeviceFingerprint/TrueIPAddress/City') City
FROM INFO_XML, TABLE (XMLSEQUENCE(EXTRACT(conteudo, '/funcionarios/Transaction'))) func;

PROCEDURE load_xml(
    p_id       IN NUMBER,
    p_filename IN VARCHAR2)
IS
  v_ID INFO_XML.ID%type;
  v_MERCHANTID TAB_XML.MERCHANTID%type;
  v_REQUESTID TAB_XML.REQUESTID%type;
  v_TRANSACTIONDATE TAB_XML.TRANSACTIONDATE%type;
  v_MERCHANTREFERENCENUMBER TAB_XML.MERCHANTREFERENCENUMBER%type;
  v_FIRSTNAME TAB_XML.FIRSTNAME%type;
  v_LASTNAME TAB_XML.LASTNAME%type;
  v_ADDRESS1 TAB_XML.ADDRESS1%type;
  v_CITY TAB_XML.CITY%type;
  v_STATE TAB_XML.STATE%type;
  v_POSTALCODE TAB_XML.POSTALCODE%type;
  v_COUNTRY TAB_XML.COUNTRY%type;
  v_PHONE TAB_XML.PHONE%type;
  v_EMAIL TAB_XML.EMAIL%type;
  v_CUSTOMERID TAB_XML.CUSTOMERID %type;
  v_CARDTYPE TAB_XML.CARDTYPE%type;
  v_CARDSCHEME TAB_XML.CARDSCHEME%type;
  v_CARDISSUER TAB_XML.CARDISSUER%type;
  v_CARDBIN TAB_XML.CARDBIN%type;
  v_CARDBINCOUNTRY TAB_XML.CARDBINCOUNTRY%type;
  v_ORDERAMOUNT TAB_XML.ORDERAMOUNT%type;
  v_ORDERCURRENCY TAB_XML.ORDERCURRENCY%type;
  v_LOCALORDERAMOUNT TAB_XML.LOCALORDERAMOUNT%type;
  v_SCORE TAB_XML.SCORE%type;
  v_FACTORS TAB_XML.FACTORS%type;
  v_INFOCODESTRING TAB_XML.INFOCODESTRING%type;
  v_IPINFORMATION TAB_XML.IPINFORMATION%type;
  v_IPADDRESS TAB_XML.IPADDRESS%type;
  v_IPROUTINGMETHOD TAB_XML.IPROUTINGMETHOD%type;
  v_IPCOUNTRY TAB_XML.IPCOUNTRY%type;
  v_IPSTATE TAB_XML.IPSTATE%type;
  v_IPCITY TAB_XML.IPCITY%type;
  v_COMPLETEROUTE TAB_XML.COMPLETEROUTE %type;
  v_DEPARTUREDATETIME TAB_XML.DEPARTUREDATETIME%type;
  v_JOURNEYTYPE TAB_XML.JOURNEYTYPE%type;
  v_NUMBEROFPASSENGERS TAB_XML.NUMBEROFPASSENGERS%type;
  v_PASSENGER TAB_XML.PASSENGER%type;
  v_FIRSTNAME_1 TAB_XML.FIRSTNAME_1%type;
  v_LASTNAME_1 TAB_XML.LASTNAME_1%type;
  v_PASSENGERTYPE TAB_XML.PASSENGERTYPE%type;
  v_FIELD1 TAB_XML.FIELD1%type;
  v_FIELD2 TAB_XML.FIELD2%type;
  v_FIELD3 TAB_XML.FIELD3%type;
  v_FIELD4 TAB_XML.FIELD4%type;
  v_FIELD5 TAB_XML.FIELD5%type;
  v_FIELD6 TAB_XML.FIELD6%type;
  v_FIELD7 TAB_XML.FIELD7%type;
  v_FIELD8 TAB_XML.FIELD8%type;
  v_FIELD9 TAB_XML.FIELD9%type;
  v_FIELD10 TAB_XML.FIELD10%type;
  v_FIELD11 TAB_XML.FIELD11%type;
  v_FIELD12 TAB_XML.FIELD12%type;
  v_FIELD13 TAB_XML.FIELD13%type;
  v_FIELD14 TAB_XML.FIELD14%type;
  v_FIELD15 TAB_XML.FIELD15%type;
  v_FIELD16 TAB_XML.FIELD16%type;
  v_FIELD17 TAB_XML.FIELD17%type;
  v_FIELD18 TAB_XML.FIELD18%type;
  v_FIELD19 TAB_XML.FIELD19%type;
  v_FIELD20 TAB_XML.FIELD20%type;
  v_FIELD21 TAB_XML.FIELD21%type;
  v_FIELD22 TAB_XML.FIELD22%type;
  v_FIELD23 TAB_XML.FIELD23%type;
  v_FIELD24 TAB_XML.FIELD24%type;
  v_FIELD25 TAB_XML.FIELD25%type;
  v_FIELD26 TAB_XML.FIELD26%type;
  v_FIELD27 TAB_XML.FIELD27%type;
  v_FIELD28 TAB_XML.FIELD28%type;
  v_PROFILE TAB_XML.PROFILE%type;
  v_ACTIVE TAB_XML.ACTIVE%type;
  v_NAME TAB_XML.NAME%type;
  v_DECISION TAB_XML.DECISION%type;
  v_NUMBEROFRULES TAB_XML.NUMBEROFRULES%type;
  v_NAME_1 TAB_XML.NAME_1%type;
  v_DECISION_1 TAB_XML.DECISION_1%type;
  v_FINGERPRINT TAB_XML.FINGERPRINT%type;
  v_SMARTID TAB_XML.SMARTID%type;
  v_SMARTIDCONFIDENCELEVEL TAB_XML.SMARTIDCONFIDENCELEVEL%type;
  v_SCREENRESOLUTION TAB_XML.SCREENRESOLUTION%type;
  v_TRUEIPADDRESS TAB_XML.TRUEIPADDRESS%type;
  v_ADDRESS TAB_XML.ADDRESS%type;
  v_COUNTRY_1 TAB_XML.COUNTRY_1%type;
  v_CITY_1 TAB_XML.CITY_1%type;
  v_TIMEONPAGE TAB_XML.TIMEONPAGE%type;
BEGIN
  OPEN C1;
  LOOP
    FETCH C1 INTO v_ID;
    EXIT
  WHEN C1%NOTFOUND;
  END LOOP;
  CLOSE C1;
  v_ID:=1;

  -- INSERE NA TABELA INFO_XML O .XML INTEIRO EM UMA COLUNA XMLTYPE
  DELETE
  FROM INFO_XML;
  COMMIT;
  INSERT
  INTO INFO_XML
    (
      ID,
      DATA_ALTERACAO,
      CONTEUDO
    )
    VALUES
    (
      v_ID,
      SYSDATE,
      XMLTYPE(BFILENAME('CARGA_CSV', 'fornecedores.xml'), NLS_CHARSET_ID('AL32UTF8'))
    );
  COMMIT;

 -- EXCLUSÂO DA TAB_XML
 DELETE FROM TAB_XML;
 COMMIT;

  --INCLUSÃO NA TABELA TAB_XML
  OPEN C2;
  LOOP
    FETCH C2
    INTO v_MERCHANTID, v_REQUESTID, v_TRANSACTIONDATE, v_MERCHANTREFERENCENUMBER
    ,v_FIRSTNAME, v_LASTNAME, v_ADDRESS1, v_CITY, v_STATE, v_POSTALCODE
    ,v_COUNTRY, v_PHONE, v_EMAIL, v_CUSTOMERID, v_CARDTYPE, v_CARDSCHEME
    ,v_CARDISSUER, v_CARDBIN, v_CARDBINCOUNTRY, v_ORDERAMOUNT, v_ORDERCURRENCY
    ,v_LOCALORDERAMOUNT, v_SCORE, v_FACTORS, v_INFOCODESTRING, v_IPADDRESS
    ,v_IPROUTINGMETHOD, v_IPCOUNTRY, v_IPSTATE, v_IPCITY, v_COMPLETEROUTE
    ,v_DEPARTUREDATETIME, v_JOURNEYTYPE, v_NUMBEROFPASSENGERS, v_FIELD1, v_FIELD2
    ,v_FIELD3, v_FIELD4, v_FIELD5, v_FIELD6, v_FIELD7, v_FIELD9, v_FIELD10
    ,v_FIELD11, v_FIELD12, v_FIELD14, v_FIELD15, v_FIELD16, v_FIELD17, v_FIELD21
    ,v_FIELD25, v_FIELD26, v_NAME,v_DECISION, v_NUMBEROFRULES, v_FINGERPRINT
    ,v_SMARTID, v_SMARTIDCONFIDENCELEVEL, v_SCREENRESOLUTION, v_ADDRESS,v_COUNTRY_1
    ,v_CITY_1;

    INSERT INTO TAB_XML (MERCHANTID,REQUESTID,TRANSACTIONDATE,MERCHANTREFERENCENUMBER
    ,FIRSTNAME,LASTNAME,ADDRESS1,CITY,STATE,POSTALCODE,COUNTRY,PHONE,EMAIL,CUSTOMERID
    ,CARDTYPE,CARDSCHEME,CARDISSUER,CARDBIN,CARDBINCOUNTRY,ORDERAMOUNT,ORDERCURRENCY
    ,LOCALORDERAMOUNT,SCORE,FACTORS,INFOCODESTRING,IPADDRESS,IPROUTINGMETHOD,IPCOUNTRY
    ,IPSTATE,IPCITY,COMPLETEROUTE,DEPARTUREDATETIME,JOURNEYTYPE,NUMBEROFPASSENGERS
    ,FIELD1,FIELD2,FIELD3,FIELD4,FIELD5,FIELD6,FIELD7,FIELD9,FIELD10,FIELD11,FIELD12
    ,FIELD14,FIELD15,FIELD16,FIELD17,FIELD21,FIELD25,FIELD26,NAME,DECISION,NUMBEROFRULES
    ,FINGERPRINT,SMARTID,SMARTIDCONFIDENCELEVEL,SCREENRESOLUTION,ADDRESS,COUNTRY_1,CITY_1)
    VALUES (v_MERCHANTID, v_REQUESTID, v_TRANSACTIONDATE, v_MERCHANTREFERENCENUMBER
    ,v_FIRSTNAME, v_LASTNAME, v_ADDRESS1, v_CITY, v_STATE, v_POSTALCODE
    ,v_COUNTRY, v_PHONE, v_EMAIL, v_CUSTOMERID, v_CARDTYPE, v_CARDSCHEME
    ,v_CARDISSUER, v_CARDBIN, v_CARDBINCOUNTRY, v_ORDERAMOUNT, v_ORDERCURRENCY
    ,v_LOCALORDERAMOUNT, v_SCORE, v_FACTORS, v_INFOCODESTRING, v_IPADDRESS
    ,v_IPROUTINGMETHOD, v_IPCOUNTRY, v_IPSTATE, v_IPCITY, v_COMPLETEROUTE
    ,v_DEPARTUREDATETIME, v_JOURNEYTYPE, v_NUMBEROFPASSENGERS, v_FIELD1, v_FIELD2
    ,v_FIELD3, v_FIELD4, v_FIELD5, v_FIELD6, v_FIELD7, v_FIELD9, v_FIELD10
    ,v_FIELD11, v_FIELD12, v_FIELD14, v_FIELD15, v_FIELD16, v_FIELD17, v_FIELD21
    ,v_FIELD25, v_FIELD26, v_NAME,v_DECISION, v_NUMBEROFRULES, v_FINGERPRINT
    ,v_SMARTID, v_SMARTIDCONFIDENCELEVEL, v_SCREENRESOLUTION, v_ADDRESS,v_COUNTRY_1
    ,v_CITY_1);
  COMMIT;

  EXIT WHEN C2%NOTFOUND;
  END LOOP;
  CLOSE C2;
  DBMS_OUTPUT.PUT_LINE ('PROCEDURE CRIADA COM SUCESSO !!!');
END load_xml;
END PACK_GWP0009;

Oracle Store Procedure lendo XML


How to fix "Unsafe interpretation of method return type" in Eclipse null annotation analysis

Question: Using Eclipse 2019-12.
I'm defining a method like this:
public static <T> T execute(@NonNull Supplier<T> action) {
  return action.get();
}

Now, if I do this:
public @NonNull String foo() { return ""; }

public String doSomething() {
  return MyClass.execute(() -> foo());
}

Eclipse shows an info/warning message on doSomething body saying:
Unsafe interpretation of method return type as '@NonNull' based on substitution 'T=@NonNull String'. Declaring type 'MyClass' doesn't seem to be designed with null type annotations in mind

So, I can understand that having MyClass.execute(Supplier) returning T and passing a Supplier<T> where T is @NonNull doesn't necessarily mean that the return type is also @NonNull, because in general MyClass.execute(Supplier) could be implemented like this:
public static <T> T execute(Supplier<T> action) {
  if(action.getClass().getSimpleName().startsWith("a"))
    return null;
  return action.get();
}

in which case, even if the specified Suppliers T type variable is @NonNull, MyClass.execute(Supplier) still returns null in some cases (and Map.get(Object) is a concrete example, where it can return null if the specified key is missing, even if the Map is defined to have a @NonNull value type).
But now, since MyClass.execute(Supplier) is under my control, I would like to understand if there's a way to write it to express without ambiguities that its return type is non-null if the specified Supplier has a @NonNull return value, while it's nullable if the specified Supplier has a @Nullable return value.
Also, it's not clear to me why this does NOT generate the above info/warning:
public String doSomething() {
  return MyClass.execute(() -> "");
}

that is, I simply inlined the foo() method call in the above example.
Comment: Update to 2020-06 and you will see that your question no longer applies. I just checked that and no info/warning message on `doSomething` is shown.
Comment: It does not make sense to use annotation-based null analysis only partially. Make sure, your Eclipse is not outdated and not to ignore _Unsafe conversion of annotated parameterized type to less-annoted type_ problems.
Comment: How do you conclude that I'm using annotation-based null analysis only partially? I don't think it's the case here, at least not on purpose. I'm using Eclipse 2019-12, not the latest version but quite recent. I don't find the option you mention among those regarding annotation-based null analysis.
Comment: Without `@NonNullByDefault` (e.g. on package level), everything that goes into a method and comes out must be annotated, otherwise it is only partially annotated (like in your examples). In Eclipse 2020-03 (4.15) annotation-based null analysis has been improved and the mentioned option has been added (see [here](https://www.eclipse.org/eclipse/news/4.15/jdt.php#null-legacy-interface), [this blog post for details](https://objectteams.wordpress.com/2020/02/06/interfacing-null-safe-code-with-legacy-code/) and [watch my video showing this in action](https://youtu.be/XoUvOTiVaDc?t=150)).
Comment: @howlger I will give 2020-03 a try, thanks, still I don't understand how I should change my code. `public static <@Nullable T> T execute(Supplier action)` and `public static <@NonNull T> T execute(Supplier action)` would be both wrong, because what I would like to express is that the return type `T` is nullable or not depending on whether the `T` in `Supplier` is itself nullable or not. Which is the essence of generic methods.
Answer: The message was shown incorrectly in Eclipse 2019-12 (4.14) and before.
In Eclipse 2020-03 (4.15) annotation-based null analysis has been improved. A new check (Unsafe conversion of annotated parameterized type to less-annoted type) has been added and several fixes have been made that also affect your example.
There are no messages shown in the following code anymore:
public static <T> T execute(@NonNull Supplier<T> action) {
    return action.get();
}

public @NonNull String foo() {
    return "";
}

public @NonNull String doSomething() {
    return MyClass.execute(() -> foo());
}

But if you change foo() to return a @Nullable value, in the line return Foo.execute(() -> foo()); the following problem is correctly shown:
Null type safety (type annotations): The expression of type 'String' needs unchecked conversion to conform to '@NonNull String'

For the new Unsafe conversion of annotated parameterized type to less-annoted type option see:

Eclipse 4.15 - New and Noteworthy
Blog post Interfacing null-safe code with legacy code by Stephan Herrmann
My video showing this in action
Comment: So I was cheated by a buggy implementation in Eclipse 2019-12. In Eclipse 2020-06, indeed, I see a much more reasonable behaviour of annotation-based null analysis. Thanks for your help to track this down. Still I don't understand why someone downvoted my question, after all I was not crazy...


Finite union of $k$-dimensional rectangles

Question:
Definition
If a set $A\subset\mathbb{R}^k$ satisfying $B\subset A\subset\overline{B}$, then we call $A$ a  $k$-dimensional standard rectangle.

Here $B$ is an open $k$-dimensional rectangle, that's to say,
$$B=(a_1,b_1)\times(a_2,b_2)\times\cdots\times(a_k,b_k)$$
We can see
$$\overline{B}=[a_1,b_1]\times[a_2,b_2]\times\cdots\times[a_k,b_k]$$
Using my topology knowledge, I have proved that for a $k$-dimensional standard rectangle $A$, we have $\operatorname{Int}\,\overline{A}=\operatorname{Int}\,A$, and   $\overline{\operatorname{Int}\,A}=\overline{A}$.
But if we let $P$ be a finite union of some $k$-dimensional standard rectangles, (I call it a "simple figure") I can only prove $\overline{\operatorname{Int}\,P}=\overline{P}$.
Question: I believe that  $\operatorname{Int}\,\overline{P}=\operatorname{Int}\,P$ (or $\partial\overline{P}=\partial P$) is also correct, but I cannot give a strict proof. Any help would be appreciated.
Answer: That is actually untrue. Let us work in $\mathbb {R} $. Take $ P = ]0,1 [ \cup ]1,2 [$. This clearly is a union of open rectangles. Clearly, $\overline{P} = [0,2]$. Thus, $ {Int}\overline {P} = ]0,2 [ \ \neq ]0,1 [ \cup ]1,2 [ = {Int} P $.
Comment: Thank you very much. I have restricted myself to the high dimensional conditions, and ignored some simple examples. No wonder I cannot prove it.


Using Toggle() to show an HTML content using jQuery

Question: i'm trying to learn some jQuery and i need some help on this little program, like you see i have a header which contains some text and i need to make sure that it expands to it's HTML content once been clicked using Toggle().
This my HTML

             Click me to see my HTML content

Here is my jQuery code

Comment: It's not exactly clear what you want to achieve. Do you want some more content to appear beneath the heading when we click the heading text? and disappear when we click heading again?
Comment: "expands to it's HTML content" ?? can you explain more what you are trying to achieve, as of now if i click the header, its getting replaced by the same text.
Comment: @NikhilNanjappa An empty HTML page with only a Text, when i click that text it change to show me it's HTML content with tags etc using Toggle() event.
Comment: Instead of all that code, you can just make use of `$('#hh').toggleClass("hide");`
Answer: The line $(this).html(h1); is not valid in your case, it will look for a variable named h1 not create a
 tag, the html() function takes only a string as an input so change your function to
$(".tog").click(function (){
  // you don't need any of the previous lines

  console.log($('#hh').html()); //this would show the comments as well

  if ($(this).text() == "Click me to see my HTML content ")
    $(this).html("
 Click me to see my HTML content
");
  else
    $(this).text("Click me to see my HTML content ");
});

Check here
Comment: Hello sir, thank you for answering
Your answer is correct but this Toggle shows how the HTML design looks in the page, is there anyway if i click it shows me the tags and what is inside like the comment and the span tag etc once i click
Comment: Yes a simple `$('#hh').html();` would show you all the html contents including the comments inside it as well. Updated the answer & codepen
Comment: Ohh i see, thank you so much for your help!


Different network speeds from servers on same subnet

Question: I have a pretty strange issue, I'm looking for advice on how I can debug it.
I have two servers (A) and (B) on the same subnet and switch.  Server A->B transfers at a full 12MB/s and vice-versa.
However, to an external site, Server A transfers at 4MB/s while Server B is only transferring at 500KB/s.  Same file, same end server, same outbound route, same transfer method (SCP & HTTP).   There is no rate limiting on our end, iptables is shut down for testing purposes, both hosts are running CentOS 6.
How can I figure out what is causing the speed difference?
Answer: It may be a problem with how TCP window interact with the NIC driver.
First, check that TCP window scaling is enabled, issuing sysctl -a | grep net.ipv4.tcp_window_scaling. If it is not enabled, activate it using sysctl net.ipv4.tcp_window_scaling=1 and retry your test.
If it does not work, you may be in need of manual tuning of TCP parameters. As it can be quite complex, see here for more information.
As a last resort, if TCP window scaling was enabled and you continue to have bad performance, try disabling it using sysctl net.ipv4.tcp_window_scaling=0
Comment: Thanks for the advice.  I tried tuning sysctl setting and did get up to ~1.3MB/s.  Still not close to the 4MB/s of the other server though.


#DocuSignAPI and using the CRCL parameter

Question: I have a question about the CRCL parameter in a Custom Related List using the #DocuSignAPI.
Besides the example listed in the documentation, does anyone have any examples to share?  Does this mean this button can be put on a related list in Salesforce and be able to mass send?  Does it mass send to all at once??
Answer: Sounds like you are referring to Custom Button Logic in DocuSign for Salesforce. The CRCL parameter allows the selection of recipients from a custom list related to the object where the button is placed.
The parameters do not affect the placement of the button. This is handled by placing the button in the Salesforce "layout".
If your goal is to send documents to many recipients you can either hard code the recipients in the CRL parameter, load default contacts from the object or use CRCL to define recipients from a custom list related to the object.
Here is Custom Button code sample to send to multiple hard coded
recipients using the CRL parameter.
<code>{!REQUIRESCRIPT("/apex/dsfs__DocuSign_JavaScript")}
//********* Option Declarations (Do not modify )*********//
var RC = '';var RSL='';var RSRO='';var RROS='';var CCRM='';var CCTM='';var CCNM='';var CRCL=''; var CRL='';var OCO='';var DST='';var LA='';var CEM='';var CES='';var STB='';var SSB='';var SES='';var SEM='';var SRS='';var SCS ='';var RES='';
//*************************************************//
CCRM = 'Signer 1~Signer 1;Signer 2~Signer 2;Signer 3~Signer 3';
CCTM =  'Signer 1~Signer;Signer 2~Signer;Signer 3~CarbonCopy';
CRL = 'email@example.com;FirstName~Sam;LastName~Sample;Role~Signer 1;RoutingOrder~1;Email~{!Opportunity.OwnerEmail};FirstName~Sally;LastName~Simple;Role~Signer 2;RoutingOrder~2;firstname.lastname@example.com;FirstName~Sue;LastName~Simple;Role~Signer 3;RoutingOrder~3';

//********* Page Callout (Do not modify) *********//
window.location.href = "/apex/dsfs__DocuSign_CreateEnvelope?DSEID=0&SourceID={!Opportunity.Id}&RC="+RC+"&RSL="+RSL+"&RSRO="+RSRO+"&RROS="+RROS+"&CCRM="+CCRM+"&CCTM="+CCTM+"&CRCL="+CRCL+"&CRL="+CRL+"&OCO="+OCO+"&DST="+DST+"&CCNM="+CCNM+"&LA="+LA+"&CEM="+CEM+"&CES="+CES+"&SRS="+SRS+"&STB="+STB+"&SSB="+SSB+"&SES="+SES+"&SEM="+SEM+"&SRS="+SRS+"&SCS="+SCS+"&RES="+RES;
//*******************************************//
</code>
Comment: I posted this question way back months ago before I really new much about the Custom Button Logic.  I was looking for alternative method in sending the same document to Multiple recipients - instead of using the Bulk Sending feature with a CSV file that you have to upload to DocuSign.  The Custom Button Javascript button will not do that.

We could use Conga Composer and their mass email functionality, but I was trying to avoid another app being installed.

The only option is to use the CSV file, upload to DocuSign and have custom fields that send data back to Salesforce.


Why won't RHC tell me what all apps are available?

Question: I write rhc apps and the reply is...
...
  Deployment: auto (on git push)

  php-5.4 (PHP 5.4)
  -----------------
    Gears: 1 small

←[32mYou have access to 2 applications.←[0m

but it won't tell me their names.  How can I get a verbatim list of the application names?
Answer: Strange.. ! but when i tried my machine with that command i got the list of apps .
Try these commands also
rhc apps -l <your login>

rhc apps --mine


How prove the left hand side

Question: How can I prove that (the left hand side)
For any two subsets A and B of X prove that
$ (A\setminus B)\cup B=A \iff  B\subset A $
Comment: you need to prove two implications. Equality of sets is proven by showing two inclusions hold. Inclusions are shown by taking an element in a set and proving it is contained in the other set.
Comment: @Student I know that but how about this (A\B) union B
Answer: $(A\setminus B)\cup B=A \implies  B\subset A$
We need to show that $b\in B \implies b\in A$
Suppose it is not true.
Choose a $b\in B$ that is not in $A$
$b\in (A\setminus B)\cup B\\
(A\setminus B)\cup B \ne A$
Contradiction.
$B\subset A \implies (A\setminus B)\cup B=A$
All $b \in B$ are in $A$
if $b\in B$ then $(A\setminus B)\cup B$
if $a$ in $A$ but  in $B$ then $a\in(A\setminus B)$
Comment: Thanks , but why you wrote in the line 5 and 6 (A\B) union A not union B same the question?
Comment: @user510071 typo.  Thanks, fixed.
Answer: $B \subset X\cup B$ for any set.
So $A = X\cup B$ means $B \subset A$ for any $X$ and is true for $X = A\setminus B$ and where $A = (A\setminus B) \cup B$.  So $\implies$ is done.
If $B \subset A$ then $B\setminus A = \emptyset$ and $B \cap A = B$. So $(A\setminus B) \cup B = (A\setminus B)\cup (A\cap B) = (A\cap B^c) \cup (A\cap B) = A \cap (B^c \cup B) = A \cap U = A$ (where $U$ is the universal set).  So $\Leftarrow$ is done.

How prove the left hand side


How do I replace drush_set_error()?

Question: Just updating a module for Drupal 9 and Drush 10 and drush_set_error() no longer appears as a function in the Drush code (as far as I can see). What should I be using instead?
Comment: @leymannx I think this is a fair question.  In addition to helping out people who aren't so good with code, having questions like this show up in Google searches makes it easier for everyone to update their code quickly.
Comment: I am glad I asked this question as now the exact answer to the search phrase comes up in the Google results. I know a lot of people who have a lot of anxiety when reaching out and asking for help because of the condescending and often rude responses they get back. It's great that you are helping people on here @leymannx but you should think about how you phrase such replies.  You might not realise it but you can have a drastic effects on other people's confidence, self esteem and mental health.
Comment: You are right, and I apologise, I should have phrased my initial comment differently.
Comment: @PatrickKenny – I totally agree with you. It's just I don't like one sentence questions not showing minimal effort to solve a problem on their own. Like: What have you tried so far etc. There are probably a thousand D9 ready contrib modules out there, maybe 25% of them providing their own Drush commands. Devel foremost. Looking a bit around shouldn't be too high of a hurdle. Hitting Google for that exact function brings up https://weitzman.github.io/blog/port-to-drush9 with an answer to that question.
Answer: drush_set_error() has basically been deprecated in Drush 8 and has been removed in Drush 10. Hitting up Google for drush_set_error() will give you a blog post by one of the maintainers: Porting Commands to Drush 9. In there the following is stated.

Replace drush_set_error() with throw new \Exception()

Now let's compare a sample command in Drush 8 and in Drush 10 – the xkcd command.
In Drush 8 there's the following line:
drush_set_error('DRUSH_XKCD_SEARCH_FAIL', dt('The search failed or produced no results.'));

In Drush 10 this line became:
throw new \Exception(dt('The search failed or produced no results.'));

One more.
When you search the pull requests for drush_set_error() you'll find the following: Replace drush_set_error() and drush_log() via Drush::logger() #3810. In there drush_set_error() has been replaced by Drush::logger()->error().
Now what's the difference between Drush::logger()->error() and throw new \Exception()?

throw new \Exception(dt('My error messsage.')); is the last thing you do before Drush quits.
Drush::logger()->error(dt('My error message')); gives you the chance to print out multiple error messages and let your code continue.

How do I replace drush_set_error()?


Understanding vec2var conversion in R

Question: I'm using Bernhard Pfaff's packages {urca} and {vars} to analyze 3 time series.  Each is I(1) and cointegrated with $r =2$ cointegrating relationships.
The vec2var() command should make the conversion from the ca.jo object (my VECM) to its VAR representation in levels.  But I do not understand the output from vec2var(), nor how to perform VAR analyses on this output (i.e., send the data to the VAR() function to get a varest object).
That is, after converting from VECM to VAR what do I send to the VAR() function (which performs the standard VAR estimates)?
Should it be:
var.form$A%*%var.form$datamat[ , c(6:11)] + var.form$deterministic%*%var.form$datamat[ , c(4:5)]

where dimensions in the code above are because I have $K=3$ variables, $p=2$ lags, a constant term and a deterministic trend.
But the formulation from vec2var() [on which I've based the above R code] is something like
\begin{equation}
  Y_t = A_1 Y_{t-1} + A_2 Y_{t-2} + \Phi D_t  + \mu + \epsilon_t
\end{equation}
That is, a basic VAR(2) with a deterministic time trend and constant.
But this is what I'm confused about: The VAR form of the long-run VECM (equation 4.8a, in Pfaff's Analysis of Integrated and Co-Integrated Time Series with R. useR!, and elsewhere e.g. Lütkepohl eq'n 7.1.1) is:
\begin{equation}
     \Delta y_t  = \Gamma_1 \cdot \Delta y_{t-1} + \Gamma_2 \cdot \Delta y_{t-2} + \Pi \cdot y_{t-2} + \Phi \cdot D_t  + \mu + \epsilon_t
\end{equation}
To get the proper VAR level representation do I have to take the data from vec2var() and manipulate it myself? (i.e. find the difference series and then multiply by the appropriate cointegration matrix)?  If this is the case then which [in R code please!] coefficient matrices should multiply which vectors?
I feel like there's a disconnect from the theory and mathematical formalism and these R packages... but more likely I'm missing something pretty basic.
Here's the basic R code set up:
library(urca)
library(vars)

vecm <- ca.jo(mydata, ecdet = "trend", type = "trace",  spec = "longrun")
var.form <- vec2var(vecm, r= 2)
# The output data I get can be seen from names(var.form), but the key parts are:

var.form$y          # my original data
var.form$datamat    # original data organized with the three variables (starting at t = 2), the constant term, trend term and then six columns with two lagged levels at t=1 and t=0.

# the coefficients for the regressors on the endogenous variables (A) and deterministic components are:
     var.form$A             # lagged variable coefficients (levels only, I think)
     var.form$deterministic     # constant and time trend coefficients

Comment: What you call "The VAR form of the long-run VECM" may not be what you say it is. To me it looks like another (equivalent) representation of the VECM model. There are two common representations of VECM: (1) where the error correction term is lagged by 1; (2) where the error correction term is lagged by  and by p, where p is the number of lags of the first difference terms in the VECM. And the VAR you want to get from the VECM should look like any other VAR, thus no need to be confused.
Comment: Tony, I, too, stick to a problem very similar to your problem. VEC -> VAR transformation is important. Using VAR even in the case of cointegrated VAR (via a VECM->VAR transformation) is very advantagous for ">2"-variable systems in which one blasts interaction/confounding effects.
Comment: Tony, look at [here](http://blog.csdn.net/littlely_ll/article/details/54866181)  The example here, especially towards the bottom of the page, may provide you essential hints via its matrix representations. A very rare and complete example, indeed. The matrix structures for 5 different cases of Juselius are really cumbersome. Once I get a systematic way to present them, I will give them here as well. MARTIN 2012 "Econometric Modelling with Time Series" is the BEST reference to explain the 5 cases (see page 705 and earlier). Matrix structures changes acc. to these 5 cases in urca/var apps.
Comment: Look at [ca.jomoni](https://github.com/hannes101/CointegrationAnalysis/blob/master/ca.jomoni.R) and [here](https://github.com/hannes101/CointegrationAnalysis) where you can find  the connection with "the theory and mathematical formalism" and "R functions" more properly.
Answer: The vec2var() function will provide an object of class vec2var.
You cannot convert it further to the class varest for standard VAR, but there are still many methods that will work on it, check it with:
methods(class = "vec2var")

Will return:

[1] fevd      fitted    irf       logLik    Phi       plot     predict   print     Psi       residuals

So you can run irf(), fevd() and so on, to "perform VAR analyses on this output" as you want. For exampe, if you want to run the IRF, do:
plot(irf(vec2var(x)))

The only thing you cannot get easily are standard errors for the coefficients of the (constrained) VAR representation.

Understanding vec2var conversion in R


Binding Parsed conent to a hyperlink button

Question: This is relating to Windows Phone 8.0
I have parsed some data relating to a dynamic store logo and a dynamic URL.
The Logo is displayed via :
<Image Source="{Binding StoreLink}" />

The URL as text is displayed via :
<TextBlock Name="DLlink" Text="{Binding DLlink}" />

However, as that is a TextBlock it can't be used as a URL.
Ideally, I would like to combine the two somehow. So the user would tap the {Binding StoreLink} image and be directed to the {Binding DLlink} URL.
However, I have tried the following with no success :
<HyperlinkButton Content="Download Link" NavigateUri="{Binding Name=DLlink}" />

and;
<TextBlock>
<Hyperlink NavigateUri="{Binding DLlink}" />
</TextBlock>

What I am doing incorrectly here?
Answer: Modify your Hyperlink Button to this..
<HyperlinkButton Content="Download Link"
                 NavigateUri="{Binding DLlink}"
                 TargetName="_blank" />

This should work.
Comment: +1 To expand on this, could also throw both his image and his text into the content of the HyperlinkButton so he'd get his combination of the two that he's looking for.
Comment: Error : The member "Name" is not recognized or is not accessible - code would not run. Changed to Elementname and the code ran, showed the button but on click nothing happened.
Comment: remove the name part from the binding. Its my mistake i copied it from your code. You should derectly bind the Property `DLlink` to the `NavigateUri`. It works i have tested it.
Answer: Try registering TouchUp event for your image where you can naviagte to your DLink url from code.
Or you can try this.
<HyperlinkButton
    NavigateUri={Binding Name="DLink"}>
    <HyperlinkButton.Content>
       <Image Source={ Binding Name="StoreLink"} />
    </HyperlinkButton.Content>
</HyperlinkButton>

Comment: Error : The property 'Name' was not found in type 'Binding'.  I tried ElementName and it ran the code but did not display anything.
Comment: Changed to
Comment: Can you please edit the answer for what worked for you. And ya. Remove name and keep it just Binding DLink


Does someone know why the image doesn't get uploaded

Question: As title says, does someone know why the image doesn't get uploaded?
I'm trying to make a propic image upload page but image doesn't get uploaded.
This is the HTML form:
<form enctype="multipart/form-data" method="POST" action="../php/modifica-profilo.php">

    Immagine profilo
    <input type="file" name="propic" class="form-control-file" accept="image/x-png,image/jpeg">
    Solo immagini .png e .jpg - Dimensione massima 4 MB

    <button class="btn btn-primary btn-block" type="submit" name="dettagliBtn">Salva modifiche</button>

And this is the php script part "modifica-profilo.php":
if(!empty($_POST['propic'])){
            $dimensioneFile = $_FILES['propic']['size'];
            $tipoFile = $_FILES['propic']['type'];
            $tmp_name = $_FILES['propic']['tmp_name'];

            $dir = "../img/propic-utenti/";

            $estensione = image_type_to_extension(IMAGETYPE_PNG);
            $estensione = image_type_to_extension(IMAGETYPE_JPEG);

            $propic = md5($uid).$estensione;

            if($dimensioneFile > 4000000){
                echo "Il file è troppo grande";
            }else{
                move_uploaded_file($tmp_name,$dir.$propic);
            }
        }else{
            $prendoPropic = "SELECT propic FROM clienti WHERE id='$uid';";
            $rpp = $conn->query($prendoPropic);
            $p = $rpp->fetch_assoc();

            if($p['propic'] == "p-default.png"){
                $propic = "p-default.png";
            }else{
                $propic = $p['propic'];
            }
        }

        $aggiornodb = "UPDATE clienti SET cognome='$cognome', nome='$nome', email='$email', propic='$propic' WHERE id='$uid';";
        $risultato = $conn->query($aggiornodb);

Comment: Have you get some errors? are the data saved correctly in the database?
Comment: no errors, all data gets saved on db except for propic
Comment: You have to check if $_FILES['propic'] is empty or not
Comment: I dont recommend the Question title, we can imagine what others will input in their search engine so they can find this kind of reference.
Comment: Also check if  move_uploaded_file()  return true or false
Answer: It is because, $_POST['propic'] will always been empty,
this should be $_FILES['propic']
You better use this
if(!empty($_POST['dettagliBtn'])){
//since you only have 1 data on $_POST which is the button. Because you have given it a name attribute.

Instead of this
if(!empty($_POST['propic'])){
// this will always get false

Make sure also, the submit button is inside your form.
Comment: I check the button at file start
Comment: now, propic name gets saved on database, but image still not gets saved on folder
Comment: The image doesn't saves in the folder because you check the input in the wrong way, as @Jovylle Bermudez says you have to check  if(!empty($_FILES['propic']){ instead of $_POST['propic']
Comment: @Sfili_81 I did, still nothing ->  if(!empty($_FILES['propic'])){
Comment: Since you can now proceed on the submission, can you trace it again. You might get it work this time.


Edit token template

Question: I am using "Send mail with Variable" module and my variable contains the token [commerce-order:commerce-email-order-items], which returns me
. I need other CSS styles.
 Because it is a body of a e-mail, I can use only inline styles. Where I can find a template of this token?
Answer: There isn't any template used to populate that token. The function that is called to generate the content of that token is commerce_email_order_items(), which then calls theme_commerce_email_order_items().
To alter the content of the token, you have two options:

Override the theme function. It's easier, but it could change the output also in other contexts.
Implement hook_tokens_alter() to alter the output of that token. It's not as easier as the previous solution, but it's more specific, and you are sure you are not going to alter the output of theme('commerce_email_order_items') done from other modules and in other circumstances.

This is the involved code used by the module.
/**
 * Implements hook_tokens().
 */
function commerce_email_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $url_options = array('absolute' => TRUE);

  if (isset($options['language'])) {
    $url_options['language'] = $options['language'];
    $language_code = $options['language']->language;
  }
  else {
    $language_code = NULL;
  }

  $sanitize = !empty($options['sanitize']);

  $replacements = array();

  if ($type == 'commerce-order' && !empty($data['commerce-order'])) {
    $order = $data['commerce-order'];

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'commerce-email-order-items':
          $order_items = commerce_email_order_items($order);
          $replacements[$original] = $order_items;
          break;
      }
    }
  }
  return $replacements;
}

/**
 * Returns a rendered email of the commerce order
 * or an array of the table details
 *
 * @param $order
 *   The commerce order object
 *
 * @param $theme
 * (optional) Defaults to TRUE
 *   Flag to return the contents of the order
 *   as a themed html table or an array suitable for theme('table' ...)
 *
 * @return
 *   String containing the rendered order table
 *   or an array suitable for theme('table' ...)
 */
function commerce_email_order_items($order, $theme = TRUE) {
  $wrapper = entity_metadata_wrapper('commerce_order', $order);

  if ($theme) {
    return theme('commerce_email_order_items', array('commerce_order_wrapper' => $wrapper));
  }
  else {
    return commerce_email_prepare_table($wrapper);
  }
}

/**
 * Theme function for the commerce order.
 */
function theme_commerce_email_order_items($variables) {
  $table = commerce_email_prepare_table($variables['commerce_order_wrapper']);
  return theme('table', $table);
}

/**
 * Returns a table header and rows for theming.
 *
 * @param $wrapper
 *   A metadata-wrapped commerce_order entity
 *
 * @return array
 *   Array suitable for use by theme('table' ...)
 */
function commerce_email_prepare_table($wrapper) {
  $currency_code = $wrapper->commerce_order_total->currency_code->value();
  $amount = number_format(commerce_currency_amount_to_decimal($wrapper->commerce_order_total->amount->value(), $currency_code), 2);

  $header = array(
    array('data' => t('Product'), 'style' => array('text-align: left;')),
    array('data' => t('Qty'), 'style' => array('text-align: left;')),
    array('data' => t('Price (@currency_code)', array('@currency_code' => $currency_code)), 'style' => array('text-align: left;'))
  );

  $rows = array();
  foreach ($wrapper->commerce_line_items as $delta => $line_item_wrapper) {

    switch ($line_item_wrapper->type->value()) {
      case 'product':
        // Special treatment for a product, since we want to get the title from
        // from the product entity instead of the line item.
        $title = htmlentities($line_item_wrapper->commerce_product->title->value(), ENT_QUOTES, "UTF-8");
        $title .= commerce_email_order_item_attributes($line_item_wrapper->commerce_product->product_id->value());

        $rows[] = array(
          'data' => array(
            array('data' => $title, 'style' => array('text-align: left;')),
            array('data' => $line_item_wrapper->quantity->value(), 'style' => array('text-align: left;')),
            array('data' => number_format(commerce_currency_amount_to_decimal($line_item_wrapper->commerce_unit_price->amount->value(), $currency_code), 2), 'style' => array('text-align: left;')),
          )
        );
        break;
      default:
        // Use this for any other line item.
        $rows[] = array(
          'data' => array(
            array('data' => htmlentities($line_item_wrapper->line_item_label->value(), ENT_QUOTES, "UTF-8"), 'style' => array('text-align: left;')),
            array('data' => 1, 'style' => array('text-align: left;')),
            array('data' => number_format(commerce_currency_amount_to_decimal($line_item_wrapper->commerce_unit_price->amount->value(), $currency_code), 2), 'style' => array('text-align: left;')),
          )
        );
        break;
    }
  }

  $data = $wrapper->commerce_order_total->data->value();
  if (!empty($data['components'])) {

    foreach ($data['components'] as $key => &$component) {

      if ($data['components'][$key]['name'] == 'base_price') {
        $rows[] = array(
          'data' => array(
            ' ',
            array('data' => t('Subtotal:'), 'style' => array('font-weight: bold; text-align: right;')),
            array('data' => number_format(commerce_currency_amount_to_decimal($data['components'][$key]['price']['amount'], $currency_code), 2), 'style' => array('font-weight: bold; text-align: left;')),
          )
        );
      }
      elseif (preg_match('/^tax\|/', $data['components'][$key]['name'])) {
        $rows[] = array(
          'data' => array(
            ' ',
            array('data' => $data['components'][$key]['price']['data']['tax_rate']['display_title'] . ':', 'style' => array('font-weight: bold; text-align: right;')),
            array('data' => number_format(commerce_currency_amount_to_decimal($data['components'][$key]['price']['amount'], $currency_code), 2), 'style' => array('font-weight: bold; text-align: left;')),
          )
        );
      }
    }
  }

  $rows[] = array(
    'data' => array(
      ' ',
      array('data' => t('Total:'), 'style' => array('font-weight: bold; text-align: right;')),
      array('data' => $amount, 'style' => array('font-weight: bold; text-align: left;')),
    )
  );

  return array('header' => $header, 'rows' => $rows, 'attributes' => array('style' => array('width: 50%; border: 1px solid #ddd;')));
}

Edit token template


What is the probability of drawing 4 aces while drawing 5 cards in a deck of 52 without replacement?

Question: I have come with the following analytical result:
$$
\frac{(52+51+50+49)\times 4!}{C_5^{52}}\approx 0.0023
$$
However a monte carlo simulation in python gives me another answer (that I find very low):
<code>import numpy as np

deck = [i for i in range(52)]
iter = 1000000
victory = 0

for _ in range(iter):
    hand = np.random.choice(deck, 5, replace=False)
    if np.isin([1, 2, 3, 4], hand).sum() == 4:
        victory += 1

print(victory / iter)
</code>
1.3e-05
Does someone know where is my mistake?
Answer: It's actually $$p=\frac{48}{C_{52}^5}\approx 1.8469e-05$$ because you choose all the aces, and you're left with $48$ choices for the last card. In other words, you can choose 4 aces and a card with 48 different ways.
Note: When I run your simulation, I got $1.9e-5$.
Comment: Ok thank you for the clarification it works indeed. My mistake was my enumeration at the denominator, we actually only count the draw in term of set.
Answer: Here, we can have 4 aces and one of any other cards for success. One case is when 4 cards are ace and the last one is not i.e AAAAX. This can happen in 432148 ways; the first card can be any of the 4 aces, the second can be any of the remaining 3 aces, the third card can be either of the remaining 2 aces, the fourth card is the last remaining ace and the fifth card can be any of the 48 non-ace or remaining cards. But the non-ace card can be drawn in any of the five trials (XAAAA, AXAAA, AAXAA, AAAXA), so the total number of ways for success is 5*(432148) or 5!48.
Similarly, we can draw 5 cards from 52 cards in
52515049*48 or (52!)/(47!) ways.
So the required probability will be 5!\cdot\frac{48!}{52!}=1.8468926×10−5.


Help with the chain rule (physics example)

Question: I post this topic here, because I need help with the math.
I having problem with the chain rule in the derivation of the effective mass. I don't understand one step in the last equation below. Thanks in advance!
The derivation: Given:
$$E=\frac{\hbar k^2}{2m} \text{,}  \qquad F=\hbar\frac{dk}{dt}$$
$$ k=\frac{2\pi}{\lambda}\text{,}\qquad v_g=\frac{1}{\hbar}\frac{dE}{dk}$$
The constant $\hbar$ is $\frac{h}{2\pi}$.
Take derivative of $v_g$ with respect to $t$ so
$$
\frac{dv_g}{dt}=\frac{1}{\hbar}\frac{d}{dt}\frac{dE}{dk}=\frac{1}{\hbar}\underbrace{
\frac{{d^2E}}{dk^2}\frac{dk}{dt}
}_\text{Why and how?}
=\frac{1}{\hbar^2}\frac{d^2E}{dk^2}F$$
Answer: Recall that the chain rule states that if $y = g(x)$, then $$\left.\frac{d}{dx}(f\circ g)\right|_{x_0} = \left.\frac{df}{dy}\right|_{g(x_0)}\cdot \left.\frac{dg}{dx}\right|_{x_0}$$

In your setup, $k$ is implicitly a function of time $t$.  So let's make it a little more explicit.  Let $\color{blue}{k} = \color{red}{k}(t)$ (that is we're "overloading" the symbol $k$ so that it can represent a $\color{blue}{\text{variable}}$ or a $\color{red}{\text{function}}$ -- this is so I don't have to make up a new variable name).
Then we have $$\frac{d}{dt}\left.\left(\frac{dE}{d\color{blue}{k}}\circ \color{red}{k}\right)\right|_{t} = \frac{d}{d\color{blue}{k}}\left.\left(\frac{dE}{d\color{blue}{k}}\right)\right|_{\color{red}{k}(t)}\cdot\left.\frac{d\color{red}{k}}{dt}\right|_{t} = \left.\frac{d^2E}{d\color{blue}{k}^2}\right|_{\color{red}{k}(t)}\cdot\left.\frac{d\color{red}{k}}{dt}\right|_{t}$$
by the chain rule.
Comment: If my color-coding has just made this more confusing, let me know and I'll define a new variable to represent the argument of $E$.
Comment: Thank you! This was very confusing and no book clarified that $k$ was a function of $t$. I thought [$k$ always was a scalar](https://en.wikipedia.org/wiki/Wavenumber#Definition). Your color-coding was great! Just for curiosity, what do you mean with define a new variable for E? Never seen that alternative in any books.
Comment: With your $k=k(t)$, is it correct to write the given expressions explicit as $E=E(k)=\frac{\hbar k(t)^2}{2m},
F=F(t)=\hbar\frac{dk(t)}{dt}$ and $
v_g=v_g(t)=\frac{1}{\hbar}\frac{dE(k)}{dk}$?
Comment: You can call the argument of a function whatever you like.  So for instance $E(k) = \frac{\hbar k^2}{2m}$ (mathematically) means exactly the same thing as $E(q) = \frac{\hbar q^2}{2m}$.  The name of the argument has no real meaning.  $k$ would normally be fine as a variable name, except that we're also using it as the name of a function.  So I could have distinguished between the two different meanings of the $k$'s in your problem better if I had changed your $E(k)$ formula to my $E(q)$ formula.
Comment: It's a little abusive of the notation to write $E(k)=\frac{\hbar k(t)^2}{2m}$ as the LHS is a function of $k$ but the RHS is a function of $t$.  But (speaking as a physicist) physicists don't usually worry about being absolutely rigorous with our statements.  So the equations you've given are fine.
Comment: Ah okey! For a beginner the lack of rigor is sometimes confusing. Speaking of abusive of the notation, is $E(t)$ a more correct notation or even $E$?
Comment: $(E\circ k)(t)$ or $\left.E\right|_{k(t)}$ would be the best notations, but you'll never see that in physics.  Most often you'll see $E(t)$ (even sometimes in math you'll see this).
Answer: This is what I thought;
$$ \frac{dv_g}{dt}=\frac{d}{dt}(\frac{dE}{dk}) \cdot \frac{1}{\hbar} $$
As $k$ is a function of $t$ (by the statements initially stated),then the chain rule may be applied;
$$ \frac{dv_g}{dt}=\frac{d}{dk}(\frac{dE}{dk}) \cdot \frac{dk}{dt} \cdot \frac{1}{\hbar} $$
$$\frac{dE}{dk} =f(k),\\
\therefore \frac{d}{dk}(\frac{dE}{dk}) = \frac{d^2E}{dk^2}$$
Hence the overall problem may be reduced to;
$$ \frac{dv_g}{dt}= \frac{d^2E}{dk^2} \cdot \frac{dk}{dt} \cdot \frac{1}{\hbar} $$
As $\frac{dk}{dt}=\frac{F}{\hbar}$, the overall result becomes;
$$ \frac{dv_g}{dt}= \frac{d^2E}{dk^2} \cdot \frac{F}{\hbar^2} \equiv \frac{1}{\hbar^2} \cdot \frac{d^2E}{dk^2} \cdot F $$
I think this is correct.
Hope this helps.


Como remover a borda da imagem?

Question: Eu tenho esta imagem:
1)

2)

que está a ser usada com icon para um <input>:
' <input type="button" class=" button_add" />'

Com o CSS adicionei-a a uma li:
input.button_add {
    float: right;
    height: 40px;
    padding-left: 36px;
    background: url("../img/Arrow_Circle_Right-32.png") no-repeat;
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

No ponto 2) dá para verificar que a imagem não tem bordas nenhumas, mas no resultado final a imagem aparece-me assim:

É possivel fazer essas bordas desaparecerem?
Obrigado pela atenção
Comment: Coloque o seu código e não imagens com o mesmo..
Comment: @CesarMiguel já está alterado
Answer: Você deve usar:
border: none;
background: url("../img/Arrow_Circle_Right-32.png") transparent no-repeat;

o transparent do background é pra evitar que sites mais antigos implementem cor no bg.... Uma dica legal, é voce clicar com o botao direito no navegador, em cima do objeto, ir em inspecionar elemento e ao lado, ou embaixo será exibido todo css dele, quase todo navegador moderno permite que você manipule o css do input exibido, dai você pode 'brincar' com o código, adicionar parâmetro, remover, até que atenda sua necessidade.
Comment: o transparent do background é pra evitar que sites mais antigos implementem cor no bg.... Uma dica legal, é voce clicar com o botao direito no navegador, em cima do objeto, ir em inspecionar elemento e ao lado, ou embaixo será exibido todo css dele, quase todo navegador moderno permite que você manipule o css do input exibido, dai você pode 'brincar
Comment: Funcionou. Obrigado. 3min para aceitar como resposta.

Como remover a borda da imagem?


Combobox query in Access 03 database showing on some pc's limited data

Question: I have a combobox which looks at a table and displays it's 5 columns of data via a query to be used like a search, on most pc's all 5 columns populate with data but on some only the last 3 columns populate and it displays blank FirstName and Surname columns, any idea how this could happen or how to fix it?
Also the combobox isn't used to select just to confirm that searched for people are in the database so there are no events and it is all setup in the combobox properties.
Edit- I bet a post topic like this could stack up those tumbleweed badges if one could get more than 1 of em.
Comment: Lot's of us still work in A2003.
Comment: Guessing nobody remembers too well how to use access 03.
Comment: I remember how to use Access, but this is very odd indeed. What happens if you run a query to extract the same data as the combo?
Comment: it all displays perfectly fine in the query table just in the combo is fails to load Surname and FirstName but has no issue with DOB and 2 other fields which are text types just like F/S name.
Comment: All I can suggest is continuing to test by creating a combo on a blank form that references the same query string. Presumably these guys have the same copy of the front-end as the guys with a working combo? Does everyone have the same version of Access?
Comment: yep everybody is using the same copy in the same network drive and with access03 but some machines just don't want to show the F/S name columns of data.
Comment: I have just noticed that I am also taking to you in another thread :) Is this the same DAP stuff? If it is an Access front-end, people should have their own copy, only the back-end data should be shared.
Answer: There could be two causes.
One possibility is that the number of rows being returned in a query is not the same as the combo box Column Count property.  If you are changing the combo box Row Source property make sure the updates have the same number of columns.    MS fixed this bug but I'm not sure when it was fixed.
More likely though is that the PCs in question don't have the following hotfix installed.
Description of the Access 2003 post-Service Pack 3 hotfix package: December 18, 2007
Comment: I'd think it to be the hotfix since nothing get changed with the db to get it to work on 1 pc and partially not on another
Comment: Seems my admin permissions don't extend to the laptop I can test it out on so in the mean time I'll be looking for alternatives.
Comment: mananged to install the hotfix and that resolved everything, thx for the help.


Using an authorization header with Fetch in React Native

Question: I'm trying to use fetch in React Native to grab information from the Product Hunt API. I've obtained the proper Access Token and have saved it to State, but don't seem to be able to pass it along within the Authorization header for a GET request.
Here's what I have so far:
var Products = React.createClass({
  getInitialState: function() {
    return {
      clientToken: false,
      loaded: false
    }
  },
  componentWillMount: function () {
    fetch(api.token.link, api.token.object)
      .then((response) => response.json())
      .then((responseData) => {
          console.log(responseData);
        this.setState({
          clientToken: responseData.access_token,
        });
      })
      .then(() => {
        this.getPosts();
      })
      .done();
  },
  getPosts: function() {
    var obj = {
      link: 'https://api.producthunt.com/v1/posts',
      object: {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + this.state.clientToken,
          'Host': 'api.producthunt.com'
        }
      }
    }
    fetch(api.posts.link, obj)
      .then((response) => response.json())
      .then((responseData) => {
        console.log(responseData);
      })
      .done();
  },

The expectation I have for my code is the following:

First, I will fetch an access token with data from my imported API module
After that, I will set the clientToken property of this.state to equal the access token received.
Then, I will run getPosts which should return a response containing an array of current posts from Product Hunt.

I am able to verify that the access token is being received and that this.state is receiving it as its clientToken property. I am also able to verify that getPosts is being run.
The error I'm receiving is the following:

{"error":"unauthorized_oauth", "error_description":"Please supply a valid access token. Refer to our api documentation about how to authorize an api request. Please also make sure you require the correct scopes. Eg \"private public\" for to access private endpoints."}

I've been working off the assumption that I'm somehow not passing along the access token properly in my authorization header, but don't seem to be able to figure out exactly why.
Comment: As noted in [this SO](https://stackoverflow.com/a/5259004), headers are intended to be **lowercase** (some servers respect this, others do not.)  I only share because I was bitten by it not knowing myself (and wasted time trying to debug the issue.)  It is unfortunate that so many projects, examples, and articles do not seem to respect this.
Comment: 5.5 years later and I was setting a fetch header just like the OP:
`'Authorization': 'Bearer ' + myJWT,`

Turns out myJWT was getting wrapped in double quotes!
`Authorization: Bearer "yadda.yadda.yadda"`

After many attempts at a solution, I filtered the double quotes on my back-end.
Comment: @t.j. Header names are not case sensitive, and that's exactly what the accepted + top answer says on the question you linked.
Answer: Example fetch with authorization header:
fetch('URL_GOES_HERE', {
    method: 'post',
    headers: new Headers({
        'Authorization': 'Basic '+btoa('username:password'),
        'Content-Type': 'application/x-www-form-urlencoded'
    }),
    body: 'A=1&B=2'
});

Comment: This is not working for me.  The `'Authorization'` header silently fails to attach per firebug.  I've even tried including `credentials: 'include'` in the optional object.
Comment: @RonRoyston are you looking at the OPTIONS call? if the API endpoint doesn't have CORS enabled (Access-Control-Allow-Origin: * if accessing from a different domain), then it might fail at the OPTIONS call.
Comment: Re the issue @RonRoyston is seeing, **you need to import the btoa library**, which is not native to node.  (It's a port of a browser lib.)  Otherwise auth header creation silently fails.  We were experiencing the same thing.
Comment: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch per docs, need to wrap headers with `new Headers()`
Comment: api endpoint does not have CORS enabled, so that's probably why it didn't work for me.  Thanks.  I ended up installing 'cors everywhere' add-on for firefox and it worked.
Comment: Shouldn't the Authorization header format for Token based authentication look like `Authorization: Token token=123123123`? [reference](https://www.codeschool.com/blog/2014/02/03/token-based-authentication-rails/)
Comment: @RonRoyston I used your 'cors everywhere' addon suggestion and was able to send the authorization header and get response. My question is: my application will be accessed by the customer and I do not want to ask them to download the addon in order to use my app. How can I solve my issue, without having to download the addon.
Comment: you will have to proxy the request from a secure server environment, such as a Node.js/Express.js server.
Comment: @Marklar `Authorization: "Basic {}"` would mean `Authorization: "Token 123123123"`
Comment: Note: If "grant_type=client_credentials" is part of your request, the "Basic" token is likely not supposed to be accessible to the public. Client credentials are used for machine-to-machine communication. More info here: https://auth0.com/docs/applications/confidential-and-public-applications
Comment: VSCode says `The signature '(data: string): string' of 'btoa' is deprecated.` with TypeScript
Comment: @kaushalpranav apparently you need to use `window.atob` instead https://github.com/microsoft/TypeScript/issues/45566#issuecomment-905059122
Comment: could you please check my post here. Was not able to get an answer until now.. https://stackoverflow.com/questions/75235933/flask-jwt-extended-exceptions-noauthorizationerror-missing-authorization-header
Answer: It turns out I was using the fetch method incorrectly.
fetch accepts two parameters: an endpoint to the API, and an optional object which can contain body and headers.
I was wrapping the intended object within a second object, which did not get me any desired result.
Here's how it looks on a high level:
    fetch('API_ENDPOINT', options)
      .then(function(res) {
        return res.json();
       })
      .then(function(resJson) {
        return resJson;
       })

I structured my options object as follows:
    var options = {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Origin': '',
        'Host': 'api.producthunt.com'
      },
      body: JSON.stringify({
        'client_id': '(API KEY)',
        'client_secret': '(API SECRET)',
        'grant_type': 'client_credentials'
      })
    }

Comment: Done, hope it's helpful
Comment: Oh i've been on your personal site with that example! That's how I modeled mine the first time. I figured out my issue though, it was just that my url was wrong. It required a `/` at the end that I was missing...
Comment: Thanks, this was helpful.  Worth noting that while the fetch documentation points out that fetch doesn't handle cookies, you can manually add cookies to the header with this code as well.  Just save the uid and key and do something like: var obj = {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Cookie': 'uid='+uid+'; key='+key
            });
Comment: could you perhaps provide the now working code? I'm trying to use fetch with an authorization header and I don't think my auth code is being passed as a header, because I'm getting a `401` response.
Comment: @RichardKho could you please check my post here. Was not able to get an answer until now.. https://stackoverflow.com/questions/75235933/flask-jwt-extended-exceptions-noauthorizationerror-missing-authorization-header
Answer: The following code snippet should work if you're using the bearer token :
const token = localStorage.getItem('token')

const response = await fetch(apiURL, {
    method: 'POST',
    headers: {
        'Content-type': 'application/json',
        'Authorization': `Bearer ${token}`, // notice the Bearer before your token
    },
    body: JSON.stringify(yourNewData)
})

Answer: I had this identical problem, I was using django-rest-knox for authentication tokens. It turns out that nothing was wrong with my fetch method which looked like this:
...
    let headers = {"Content-Type": "application/json"};
    if (token) {
      headers["Authorization"] = `Token ${token}`;
    }
    return fetch("/api/instruments/", {headers,})
      .then(res => {
...

I was running apache.
What solved this problem for me was changing WSGIPassAuthorization to 'On' in wsgi.conf.
I had a Django app deployed on AWS EC2, and I used Elastic Beanstalk to manage my application, so in the django.config, I did this:
container_commands:
  01wsgipass:
    command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'

Comment: `django.config` its in a project or in apache config?
Answer: completed = (id) => {
    var details = {
        'id': id,

    };

    var formBody = [];
    for (var property in details) {
        var encodedKey = encodeURIComponent(property);
        var encodedValue = encodeURIComponent(details[property]);
        formBody.push(encodedKey + "=" + encodedValue);
    }
    formBody = formBody.join("&");

    fetch(markcompleted, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: formBody
    })
        .then((response) => response.json())
        .then((responseJson) => {
            console.log(responseJson, 'res JSON');
            if (responseJson.status == "success") {
                console.log(this.state);
                alert("your todolist is completed!!");
            }
        })
        .catch((error) => {
            console.error(error);
        });
};


Using Observable.interval to wait for remote data or timeout

Question: I need to wait for a condition or timeout. I came up with the following approach, but there are too many things happening. How can i compress this.
import io.reactivex.Observable;
import java.util.concurrent.TimeUnit;
import io.reactivex.schedulers.Schedulers;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.ThreadLocalRandom;

public class Test{
  public static void main(String[] args)throws InterruptedException{
    AtomicBoolean toggle = new
    java.util.concurrent.atomic.AtomicBoolean(true);
    Observable.interval(0,50, TimeUnit.MILLISECONDS)
            .takeWhile(l->l<(20000/50))
            .takeWhile(l-> toggle.get())
            .observeOn(Schedulers.io())
            .map(l->{ return (l>ThreadLocalRandom.current()
                            .nextInt(5, 20 + 1))?true:false;})
             // The above map will call a remote function to check for some condition
            .observeOn(Schedulers.computation())
            .filter(exist->exist)
            //.takeWhile(exist->!exist)
            .map(l->{toggle.set(false);return l;})
            .map(l->{System.out.println("Called at "+l);return l;})
            .blockingSubscribe();
    }
}

Answer: Here is code. You can use firstElement to get the first item.
import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

public class Q44234633 {
  public static void main(String[] args) throws InterruptedException {
    Observable.interval(50, TimeUnit.MILLISECONDS)
        .takeWhile(l -> l < 400)
        .observeOn(Schedulers.io())
        .filter(l -> isConditionTrue(l))
        .observeOn(Schedulers.computation())
        .firstElement()
        .doOnSuccess(System.out::println)
        .isEmpty()
        .filter(empty -> empty)
        .doOnSuccess(b -> System.out.println("TimeOut"))
        .blockingGet();
  }

  private static boolean isConditionTrue(long time) {
    return time > ThreadLocalRandom.current().nextInt(5, 20 + 1);
  }
}

There are also two tips for you.

You can use doOnNext rather than map if you actually don't map the value.
BooleanValue? true : false can be written BooleanValue directly.
Comment: Thanks the tips. I was looking for 1.
Comment: onOnSuccess is called if isConditionTrue returns true. How do i find out if this timed out?
Comment: @JaganVeeraraghavan You can use `Maybe.isEmpty`.
Comment: It works. But `switchIfEmpty` resume the `Observable`, you need to judge it is success or timeout. It likes default value.


how to have a another page.tpl.php file in drupal with different regions and blocks?

Question: Well, here is the problem. In my site I want to create a plain template and add my own regions and my own blocks. So when the user visits for example www.example.com/register-now the blocks will be different from the main page. I dont like disabling the blocks because when you open Firebug the blocks can be still be seen.
So I have read in this article that you have to create a new .tpl.php file.  So in my case I created the page__register-now.tpl.php file. and put that under drupal/sites/all/themes/ninesixty/ directory.
Then I opened the template.php file and tried the below code:
function ninesixty_preprocess_page(&$vars, $hook) {
  $path=drupal_get_path_alias();

  if($path == 'register-now'){
    $variables['theme_hook_suggestion'] = 'node__register';
  }
}

Comment: If finding the right name for the template is the problem the [theme developer module](http://drupal.org/project/devel_themer) is very helpfull.
Answer: If your path to the register page is www.example.com/register-now then you only need to name the page template file appropriately and Drupal should do the rest, you shouldn't need to add anything to template.php.
From what you've written, the name of the page template file is wrong. It needs to be renamed to: page--register-now.tpl.php (notice the underscores turned to dashes).
After you rename the file (usually after adding any additional template files), make sure to clear all caches from admin/config/development/performance.
EDIT: If your page is a node, you can't use the Alias path in the template file, it actually has to be the internal path to the node, e.g. page--node--123.tpl.php where 123 is your node's ID.

The rest are based on the internal path of the current page. Do not confuse the internal path to path aliases which are not accounted for.

See here
Comment: Ok i see. So i don't need to add anything to my tempate.php file. I will remove the inputted code then from my template.php file and try that again.
Comment: ok I renamed the file to page--register-now.tpl.php remove the code added to template.php and clear the cache and saved the configuration. After that, i clicked on content and created a new basic page and added the html code for the display, entered tha url path alias as register-now and nothing happened. Is this because i am creating the page through the content tab and drupal gets the page.tpl.php theme ???
Comment: Right, if your page is a node, it actually has to have the internal path, e.g. `node/24` in the template file name. So find out your node's ID (hover over the `edit` link and it should say `node/24/edit` where 24 is your node id. Then name your page template file as `page--node--24.tpl.php` replacing 24 with your actual node's id.
Comment: Frustrating but GENIUS. Millions of thanks:):)
Comment: One last question for a multilingual site is there a way to create just one page--node--24.tpl.php file?? Or maybe add some conditions to the template.php file??
Comment: I don't know too much about multilingual, but I think if you have multilingual options set correctly in Drupal then you shouldn't need to worry about having different templates for different languages, as long as the pages look same except the main content.
Comment: Well the multilingual settigns are correct i think. Because translating other pages using the page.tpl.php file worked like a charm. But creating and using the page--node--24.tpl.php for example does not. As when a translation is being added a new node is created which is connected to the original translation. For example node/25 links to other language for node/24 . Anyhow thank you for your help. I might have to think of asking this question in another thread. :)


Uniqueness of Left Adjoint

Question: On nLab, it says that the left adjoint of a functor is unique, but it does not give a proof. Most of the proofs I have seen use the Yoneda lemma, but the book I am using states this fact (without proof) before stating the Yoneda lemma. How is this fact proven?
Answer: The left adjoint is unique up to natural isomorphism. To see this, let $G : \mathcal{D} \to \mathcal{C}$ be a functor and suppose $F,F' : \mathcal{C} \to \mathcal{D}$ with are two left adjoints for $G$. Let $(\eta,\varepsilon)$ and $(\eta',\varepsilon')$ be the units and counits of the adjunctions $F \dashv G$ and $F' \dashv G$, respectively.
Define natural transformations $\alpha : F \to F'$ and $\beta : F' \to F$ by
$$\alpha = \varepsilon_{F'} \circ F\eta' : F \xrightarrow{F\eta'} FGF' \xrightarrow{\varepsilon_{F'}} F'$$
$$\beta = \varepsilon'_F \circ F'\eta : F' \xrightarrow{F'\eta} F'GF \xrightarrow{\varepsilon'_F} F$$
We now verify that $\alpha$ and $\beta$ are mutually inverse. Consider the following diagram:
\begin{matrix}
&& FGF && \xrightarrow{=} && FGF && \\
& {\scriptsize F\eta} \nearrow && \searrow{\scriptsize F\eta'_{GF}} &&  {\scriptsize FG\varepsilon'_F}\nearrow && \searrow {\scriptsize \varepsilon_F} & \\
F && {\scriptsize \text{nat. } \eta'} && FGF'GF && {\scriptsize \text{nat. } \varepsilon} && F \\
& {\scriptsize F\eta'}\searrow && \nearrow{\scriptsize FGF'\eta} && {\scriptsize \varepsilon_{F'GF}} \searrow && \nearrow{\scriptsize \varepsilon'_F} & \\
&& FGF' && {\scriptsize \text{nat. } \varepsilon} && F'GF && \\
& && \searrow{\scriptsize \varepsilon_{F'}} && {\scriptsize F'\eta} \nearrow && & \\
&& && F' && && \\
\end{matrix}
Analysing this, we see that:

The composite from $F$ to $F$ along the bottom is $\beta \circ \alpha$;
The left, middle-bottom and right squares commute by naturality of the various units and counits as indicated in the diagram;
The top triangle commutes by the triangle identity for $F' \dashv G$.

Hence the whole diagram commutes.
Finally, composite from $F$ to $F$ along the top is $\mathrm{id}_F$ by the triangle identity for $F \dashv G$. It follows that $\beta \circ \alpha = \mathrm{id}_F$.
A similar diagram proves $\alpha \circ \beta = \mathrm{id}_{F'}$, so that $F \cong F'$.
A dual argument proves uniqueness (up to natural isomorphism) of right adjoints.
Comment: Drawing the string diagrams corresponding to the different paths makes it quite easy to see the usages of the different naturalities, units and counits.

Uniqueness of Left Adjoint


Inherited Abstract Classes in python

Question: In python, can I define an interface (abstract class) by inheritance from another abstract class?
If I try:
import abc
ABC = abc.ABCMeta('ABC', (object,), {})

class interface(ABC):
    @abc.abstractmethod
    def method(self, message):
        return

class InterfaceExtended(ABC, interface):
    @abc.abstractmethod
    def NewMethod(self, message):
        return

I get an error on the  "InterfaceExtended" class :
TypeError: Error when calling the metaclass bases
Cannot create a consistent method resolution
order (MRO) for bases ABC, Interface

Comment: Note: If you're on Python 3.4+ then you could use `ABC` class from `abc` module itself instead of re-defining it.
Comment: no, I forgot to state that I'm in python 2.7
Answer: Don't inherit from ABC in your second class. The interface it derives from already inherits ABC

Inherited Abstract Classes in python