Narrow confidence interval -- higher accuracy?

Question: I have two questions about confidence intervals:
Apparently a narrow confidence interval implies that there is a smaller chance of obtaining an observation within that interval, therefore, our accuracy is higher.
Also a 95% confidence interval is narrower than a 99% confidence interval which is wider.
The 99% confidence interval is more accurate than the 95%.
Can someone give a simple explanation that could help me understand this difference between accuracy and narrowness?
Comment: I think you mean "there is a smaller chance of obtaining an observation *outside* that interval". Unfortunately, a Confidence Interval may not mean what it appears to mean, due to technical, statistical issues, but in general the narrower the interval (at a given confidence level) the less uncertainty there is about the results. There are many threads on this site discussing what a Confidence Interval means (as opposed to, say, a Credible Interval). We're not even getting into Predictive Intervals...
Comment: @Wayne Why is not the statement be "there is a smaller chance of obtaining an observation *within*  that interval" ? Since narrow interval has a large type 1 error , it is more likely to reject the *true* null hypothesis , that is , my true null value is not contained in that interval . So , it seems to me `a narrow confidence interval implies that there is a smaller chance of obtaining an observation within that interval` is correct . Would you please explain me where am I doing the mistake ?
Comment: @user31466 your initial statement was correct in some cases (probably most). But it's not really a concern since confidence intervals aren't about individual observations. They're about making a range estimate of the population mean. What you need to care about is whether they contain that, ot any particular observation.
Answer: The 95% is not numerically attached to how confident you are that you've covered the true effect in your experiment. Perhaps recognizing that 95% is attached to the procedure that produced the interval, and not the interval itself, would help. Part of the procedure is that you decide that the interval contains the true value. You'll be right if you do that consistently 95% of the time.  But you really don't know how likely it is for your particular experiment without more information.
Q1:
Your first query conflates two things and misuses a term. A narrower confidence interval may be more precise but it's accuracy is fixed by the procedure backing it, be it 89%, 95%, etc. As long as that procedure was correctly designed, the true value will be contained in the interval at the prescribed rate. (see @Michael R Chernick's answer for a discussion on coverage and a different sense of accuracy)
Whether an observation falls in a CI isn't something to consider. A confidence interval is about estimating the mean. If you had an extraordinary large sample size and could estimate the mean very well then the chances of an observation being in the CI would be miniscule.
Nevertheless, your question does raise some points and it's important to think about why a CI is narrow. Just because it's narrow doesn't mean you're less likely to encounter an observation that falls within that CI. Keep in mind, a narrow CI can be achieved in one of three ways. The most common way researchers make the CI narrow is by increasing the sample size. Another way they can be narrow is because the experimental method or nature of the data yields very low variance. For example, the confidence interval around the boiling point of water at sea level is small, regardless of the sample size. Finally, it could be narrow because your sample is unrepresentative. In that case, you are actually more likely to have one of the 5% of intervals that do not contain the true value. It's a bit of a paradox regarding CI width that the ones in that 5% of misses tend to be narrow. It's something you should check by knowing the literature and how variable this data typically is.
Q2: A 99% confidence interval is wider than a 95%, all else being equal.  Therefore, it's more likely that it will contain the true value. See the distinction above between precise and accurate. If I make a confidence interval narrower with lower variability and higher sample size it becomes more precise because the values cover a smaller range. If I increase the coverage by using a 99% calculation it becomes more accurate because the true value is more likely to be within the range.
Comment: The variability of the mean (=what you are trying to estimate) in the population is zero.
Answer: For a given dataset, increasing the confidence level of a confidence interval will only result in larger intervals (or at least not smaller).  That's not about accuracy or precision but rather about how much risk you're willing to take about missing the true value.
If you're comparing confidence intervals for the same sort of parameter from multiple data sets and one is smaller than the other, you could say that the smaller one is more precise.  I prefer to talk about precision rather than accuracy in this situation (see this relevant Wikipedia article).
Comment: What is meant by "same sort of parameter" and  "multiple data sets" ? Say ,  a survey on illiteracy and the survey is carried out in different time , 1995, 1998 , etc . Then is the  "illiteracy rate"  same sort of parameter and  do the data sets of 1995, 1998 , etc indicate multiple data sets ?
Comment: For example, a set of confidence intervals, each for the mean of some population. Your example fits, too, I think.
Answer: First of all, a CI for a given confidence percentage (e.g.95%) means, for all practical purposes (though technically it is not correct) that you are confident that the true value is in the interval.
If this is interval is "narrow" (note that this can only be regarded in a relative fashion, so, for comparison with what follows, say it is 1 unit wide), it means that there is not much room to play: whichever value you pick in that interval is going to be close to the true value (because the interval is narrow), and you are quite certain of that (95%).
Compare this to a relatively wide 95% CI (to match the example before, say it is 100 units wide): here, you are still 95% certain that the true value will be within this interval, yet that doesn't tell you very much, since there are relatively many values in the interval (about a factor 100 as opposed to 1 - and I ask, again, of purists to ignore the simplification).
Typically, you are going to need a bigger interval when you want to be 99% certain that the true value is in it, than when you only need to be 95% certain (note: this may not be true if the intervals are not nested), so indeed, the more confidence you need, the broader the interval you will need to pick.
On the other hand, you are more certain with the higher confidence interval. So, If I give you 2 intervals of the same width, and I say one is a 95% CI and the other is a 99% CI, I hope you will prefer the 99% one. In this sense, 99% CIs are more accurate: you have less doubt that you will have missed the truth.
Comment: Nick, your first statement is wrong.  It's not a "technical issue", it's just not correct.  The confidence interval is a statement about what would happen in repeated experiments, that they would cover the true value 95% of the time.  A statement about the confidence that the true value is within my given range found in my given experiment is not the same as that at all.  If you removed the "that" in "that confident" and the parenthetical numerical amount then you'd be closer to the truth.  You could just say that it means you believe the true value likely to fall in the interval.
Comment: @John: I specifically avoided saying that the interval itself is the random variable, though my sentence does not imply it not to be (admittedly, it does suggest so). I know the issues involved, but found them irrelevant for the question. I have never seen a _practical_ situation where the difference mattered either, hence the "for all practical purposes".
Comment: Haven't encountered the issue?  That's like saying the p-value = the probability of the null and then saying that you've never encountered an issue with it.  You won't if you stay in the right journals.  It's just incorrect to say that you're 95% certain the the true value is in your current range.  Treating it as some esoteric matter just means now we'll have (at least) one more person walking around saying, "I'm 95% confident the value is in this range."  It would hardly change your answer to correct it.  The other issues you skirt could be ignored if you changed that one statement.
Comment: thanks! so then when they say that this new research on neutrinos being faster than light has a very small confidence interval (I guess this means narrow) then that means that they are more likely to be accurate then if it was a wide confidence interval? (disregarding all other aspects)
Comment: otherwise, the answer is pretty good...
Answer: I am adding to some good answers here that I gave upvotes to. I think there is a little more that should be said to completely clear up the conclusion. I like the terms accurate and correct as Efron defines them. I gave a lengthy discussion on this very recently on a different question. The moderator whuber really liked that answer. I will not go to the same length to repeat that here. However, to Efron accuracy relates to the confidence level and correctness of the width or tightness of the interval.  But you can't talk about tightness without considering accuracy first. Some confidence intervals are exact; those are accurate because they have the actual coverage that they advertise. A 95% confidence interval can also be approximate because it uses an asymptotic distribution.  Approximate intervals based on asymptotics are for a finite sample size $n$ not going to have the advertised coverage, which is the coverage you would get if the asymptotic distribution were the exact distribution.
So an approximate interval could undercover (i.e. advertise 95% when its actual coverage is only 91%) or in the rare but less serious case overcover (i.e. advertised coverage is 95% but actual in 98%).  In the former case, we worry about how close the actual coverage is to the advertised coverage).  A measure of closeness is the order of accuracy which could be say $1/\sqrt{n}$ or $1/n$.  If the actual confidence level is close, we call it accurate.  Accuracy is important with bootstrap confidence intervals which are never exact but some variants are more accurate than others.
This definition of accuracy may be different to the one the OP is referring to but it should be clear now what Efron's definition is and why it is important to be accurate.  Now if you have two methods that are exact, we can prefer one over the other if for any confidence level it has the smaller expected width.  A confidence interval that is best in this sense (sometimes called the shortest) would be the one to choose.  But this required exactness. If the confidence level is only approximate we could be comparing apples and oranges. One could be narrower than another only because it is less accurate and hence has a lower actual coverage than its advertised coverage.
If two confidence intervals are both very accurate or one is exact and the other very accurate comparing expected width may be okay because at least now we are looking at just two varieties of apples.
Answer: For a fixed dataset there is a trade-off between accuracy and confidence
Remember that when you have a fixed dataset, this give you a limited amount of information, and so you would expect that there is "no free lunch".  That is, for a fixed dataset you must get a trade-off between accuracy and confidence --- if you want more accuracy then you have to settle for less confidence, and if you want more confidence you have to settle for less accuracy.
This information constraint is the reason you observe the stated relationship between the width of the confidence interval (accuracy) and the confidence level (confidence).  If you increase the confidence level then you will get a wider confidence interval, making it less accurate.  Conversely, if you decrease the confidence level then you will get a narrower confidence interval, making it more accurate.  This is a general property of sensible confidence interval procedures that maximise use of the available information in the dataset.
It is possible to examine this relationship mathematically for a given confidence interval procedure.  Usually we have a procedure that leads to a $1-\alpha$ level confidence interval of the form:
$$\text{CI}(n,\alpha) \equiv [L(n,\alpha), U(n,\alpha)],$$
where $n$ is any a positive real sample size.$^\dagger$  Letting $W(n,\alpha) \equiv U(n,\alpha) - L(n,\alpha)$ denote the width of the confidence interval, this function will typically have the monotonicity properties:
$$\frac{\partial W}{\partial \alpha}(n,\alpha) < 0
\quad \quad \quad
\frac{\partial W}{\partial n}(n,\alpha) < 0.$$
The first monotonicity property means that when you decrease the confidence level (by increasing $\alpha$) you get a more accurate (narrower) confidence interval and vice versa.  The second monotonicity property means that when you get more sample data, you get a more accurate (narrower) confidence interval at each confidence level.
If you look at the relevant confidence interval formulae for a particular procedure, you will typically be able to confirm these monotonicity properties.  (In the rare case that one of these monotonicity properties does not hold, it would raise questions about the rationality of the confidence interval procedure.)  If you would like to see an example of analysis of monotonicity properties of a confidence interval procedure, see e.g., O'Neill (2021).

$^\dagger$ Of course, in practice the sample size is a positive integer but it is usually the case that the confidence interval formula can be extended to any positive real sample size in a natural way and then it can be examined using standard calculus methods.


Block Regions in node.html.twig

Question: How can i use block regions in my node.html.twig in drupal 8 ?
i tried this :
block_get_blocks_by_region

but function not found
Comment: Try \Drupal::entityManager()->getStorage('block')->loadByProperties(['region' => $region, 'theme' => \Drupal::theme()->getActiveTheme()->getName()]);
Comment: http://drupal.stackexchange.com/questions/153184/programatically-render-a-block-in-a-twig-template/153195#153195
Answer: Fixed by adding this function to my theme
function YOURTHEME_preprocess_node(&$variables) {

$block = \Drupal\block\Entity\Block::load('views_block__sidebar_meetings_group_page');
$variables['block_output'] = \Drupal::entityManager()
  ->getViewBuilder('block')
  ->view($block);

}

thanks @ivan jaros and @berdir

Block Regions in node.html.twig


php error "filename cannot be empty, expects parameter 1 to be resource, supplied argument is not a valid stream"

Question: I'm trying to use the following code to upload a csv file usually around 20,000 data into sql server database.
This code very rarely uploads successfully but usually i get the error below :
**Warning: fopen() [function.fopen]: Filename cannot be empty in C:\Inetpub\wwwroot\file.php on line 37
Warning: fgetcsv() expects parameter 1 to be resource, boolean given in C:\Inetpub\wwwroot\file.php on line 39
Warning: fclose(): supplied argument is not a valid stream resource in C:\Inetpub\wwwroot\file.php on line 40**
<?php
if(isset($_POST['SUBMIT']))
{
$filename =$_FILES['sel_file']['name'];
$checkextension = explode(".",$filename);

if($checkextension[1]) == "csv")
{
$filename1 = $_FILES['sel_file']['tmp_name'];
$handle=fopen($filename1,"r");
while($data=fgetcsv($handle,1000000)) { $records = count($data);  }
fclose($handle);
if($records==15) {
$handle=fopen($filename1,"r");
while (($data = fgetcsv($handle, 1000000,",")) !== FALSE) {
$sqlquery = "INSERT into dataupload (date, field1, field2,
field3, field4, field5, field6, field7, field8, field9,
 field10, field11, field12, field13, field14, field15)
 values ('$data[0]','$data[1]', '$data[2]','$data[3]','$data[4]',
'$data[5]', '$data[6]', '$data[7]', '$data[8]', '$data[9]',
 '$data[10]', '$data[11]', '$data[12]', '$data[13]', '$data[14]')";
 mssql_query($sqlquery); }
 fclose($handle);
 echo "imported successfuly"; } else { echo "--sorry it is not csv file..."; }
  } }

Answer: The temporary name in $_FILES['input_name']['tmp_name'] is not the name of the file you sent to the server.
It's a temporary name generated by PHP to make sure it can be stored in the temporary folder without overwriting other files.
$_FILES['input_name']['name'] should contain the original name.
This is the structure of the $_FILES array (when you upload one file only):
array(
    'name'     => 'Original file name.ext',
    'type'     => 'mime/type',
    'tmp_name' => 'random_name',
    'error'    =>
        UPLOAD_ERR_OK ||
        UPLOAD_ERR_INI_SIZE ||
        UPLOAD_ERR_FORM_SIZE ||
        UPLOAD_ERR_NO_TMP_DIR ||
        UPLOAD_ERR_CANT_WRITE ||
        UPLOAD_ERR_EXTENSION ||
        UPLOAD_ERR_PARTIAL,
    'size'     => $file['size'][$key],
);


Iteration with lambda in racket?

Question: This is probably a simple question, but I cannot seem to figure it out.
In the example below, I want to create a function list-of-obj that recursively creates a list of items.
Example:
> (list-of-obj 'a 5)
'(a a a a a)

The code:
#lang racket
(define (list-of-obj obj n)
  (letrec ((helper
           (lambda (obj n result)
             (if (> n 0)
               (helper obj (- n 1) (cons obj result))
               result))))
      helper obj n 0))

This, however results in output of 0. Any pointers? I'm new to racket/scheme.
Answer: The most idiomatic solution in Racket would be:
(make-list 5 'a)
=> '(a a a a a)

That is, you should not reinvent the wheel if a built-in function does what you want. But if you need to write it from scratch, this should do the trick:
(define (list-of-obj obj n)
  (letrec ((helper
            (lambda (obj n result)
              (if (> n 0)
                  (helper obj (- n 1) (cons obj result))
                  result))))
    (helper obj n '())))

There were two problems with your code:

The call to helper must be surrounded by (), because that's how you call a procedure in Scheme.
The initial value for the accumulator must be an empty list given that we're building a list as the output, not a 0 as you had it.

Iteration with lambda in racket?


2D pointer pointing 2D array in C

Question:
How to make a 2d pointer like **check point a 2d array like
mycheck[][]?
How to convert a 1d like check[16], to 2d array like mycheck[4][4]?

My attempt
float (*mycheck)[4] = (float (*)[4]) check;

But if second time I want to use mycheck again for some other 1d array, how can I do? My attempt:
float (*mycheck)[4] = (float (*)[4]) other1darray;

this will definitely give a re-declaration error.
Comment: Do you want C or C++? Or can I randomly slap haskell and python on that too?
Comment: I'm quite certain there is more code to this than that.
Comment: THe first question is strange, because a **check pointer is in essence an arrya if you allocate the memory
Answer: The answer to the first question is that you cannot do that. All you can do is allocate some memory and copy the data over.
The answer to the second question is very simple
mycheck = (float (*)[4]) other1darray;

You only have to declare variables once, after that just use the variable name.
Answer: Array a[] decays to a pointer to the first element when you drop the []. This does not happen recursively, in other words, it doesn't work for a[][].
Secondly, you can't assign arrays in C. You can ONLY initialize them. You will have to set each member yourself.
Answer: You can create a 2D array in C like this.
Use a typedef to make it easier.
typedef int **matrix;

matrix create2Darray(int row, int col)
{
    int idx;
    matrix m = malloc(row * sizeof(int*));
    for (idx = 0; idx < row; ++idx)
    {
        m[idx] = malloc(col * sizeof(int));
    }
    return m;
}

And then call this in another function;
matrix check = create2Darray(2, 2);

Comment: i get this sorts of error when i compile the code |In function 'int**create2Darray(int, int)':|
C:\Users\admin\Desktop\check.cpp|9|error: invalid conversion from 'void*' to 'matrix {aka int**}' [-fpermissive]|
C:\Users\admin\Desktop\check.cpp|12|error: invalid conversion from 'void*' to 'int*' [-fpermissive]|
||=== Build finished: 2 errors, 0 warnings (0 minutes, 0 seconds) ===|
"
Comment: that is cuz of your compiler. some compilers want you to cast the result of malloc which is a void  to the desired type. I don't tend to do that cuz gcc matches it normally, preventing me from making errors. In your case if you cast the outcome of malloc to (int**) and (int*) your fine
Comment: Ya i was foolish last time i forget to cast that and i figure it out as soon as i argue for the error message, but this time i am little bit confuse that with your declearatoin i can excess an array of size m[4][n]; where n being any number accepted by memory.......such as i can assign m[3][115] = 7; and can print it out but as i think i was suppose to excess up to m[row][col] where row = 4 and col = 4.
Answer: To assign a 1D array to a 2D array you can assign the pointers to the right position in the array. An example below. It also show how to create a 2D array dynamically, but I commented it out, since it is not needed for the example.
#include <stdio.h>
#include <stdlib.h>

int main()
{
    float **matrix;
    float *array;

    array = (float *) malloc(16 * sizeof(float));
    for (size_t idx = 0; idx != 16; ++idx)
    {
        array[idx] = idx;
    }

    matrix = (float **) malloc(4 * sizeof(float *));
    for (size_t idx = 0; idx != 4; ++idx)
    {
        // matrix[idx] = malloc(4 * sizeof(int));
        matrix[idx] = &array[idx * 4];
    }

    for (size_t row = 0; row != 4; ++row)
    {
        for (size_t col = 0; col != 4; ++col)
        {
            printf("%.1f ", matrix[row][col]);
        }
        printf("\n");
    }
}

Note: this makes the 1D array and 2D array point to the same memory. If you change something in the 1D it also changes in the 2D and vice-versa. If you don't want this, first copy the array.

2D pointer pointing 2D array in C


How to improve specificity with unbalanced data? (R caret package)

Question: I am working on a classification problem where my outcome variable is either "Approved" or "Denied". The % of approvals in my dataset is roughly 60% and the denials make up roughly 30%. I have tried multiple models (random forest, decision tree, neural network, and gradient boosting machine). The highest specificity that I can achieve is with the random forest of 0.69. I also tried to balance the data within the "train" function of the caret package by down sampling, over sampling, SMOTE, and ROSE. I performed the sampling only within the training dataset using cross validation (10 folds). I am pretty new to machine learning, so any advice is appreciated. Unfortunately, I cannot provide the datasets or any code that I have written, so I am just looking for general suggestions relating to unbalanced datasets.
Comment: ... what are the remaining 10%, after you've considered the 60% approvals and 30% denials?   And... this is hardly an unbalanced data set, not that unbalanced data is really a problem anyway: https://stats.stackexchange.com/questions/283170/when-is-unbalanced-data-really-a-problem-in-machine-learning
Comment: Sorry, it's really 68.731% approvals and 31.269% denials.
Comment: I actually tried running the same models without balancing the dataset and the specificity was worse than balancing.
Comment: How many observations & features do you have in your RF, roughly?
Comment: 23,348 rows for my training set. 24 features. 7 of those are continuous and the rest are categorical. The largest number of levels for my categorical variables is 28.
Comment: An alternative is to use weights on your observations.
Comment: Yes, I read about this but I couldn't find any application of it utilizing the caret package in R. I'm not sure exactly what I would set the weights too as well. Can you give an example? I can post the R code that I have for training the model if that would help too.
Answer: The easiest way to do this is to change the classification threshold. As you develop your machine learning knowledge, you will see that you destroy much potentially useful information by having any threshold at all, but for now, just changing the threshold sounds like a reasonable first idea.
When you run, for instance, a neural network, you get predictions on a continuum. The standard continuum in this situation is on the interval $[0,1]$. Many software functions turn these into hard classifications by setting a threshold of $0.5$: above the threshold gets classified as one category, and below the threshold gets classified as the other category.
However, you do not have to use $0.5$ as the threshold. If you want more specificity, so harder to be classified as positive, you might want to up the threshold. Perhaps set the threshold to $0.6$ or $0.8$ to get the specificity you desire.
This will improve your specificity at the expense of sensitivity. The tradeoff can be visualized in receiver-operator characteristic (ROC) curves, such as those implemented by pROC::roc in R software. This function even gives a printout of what sensitivity and specificity are achieved at each threshold. Below, I give a quick demonstration of this, and I discuss in more detail here.
library(pROC)
N <- 25
p <- rbeta(N, 1, 1)
y <- rbinom(N, 1, p)
r <- pROC::roc(y, p)
d <- data.frame(
  threshold = r$thresholds,
  sensitivity = r$sensitivities,
  specificity = r$specificities
)
d

################################################################################
#
# OUTPUT
#
################################################################################

    threshold sensitivity specificity
1        -Inf  1.00000000  0.00000000
2  0.03986668  1.00000000  0.07142857
3  0.05315755  1.00000000  0.14285714
4  0.07842079  1.00000000  0.21428571
5  0.12086679  1.00000000  0.28571429
6  0.14478513  1.00000000  0.35714286
7  0.16003195  1.00000000  0.42857143
8  0.21402721  1.00000000  0.50000000
9  0.26453714  1.00000000  0.57142857
10 0.31080317  1.00000000  0.64285714
11 0.35289509  0.90909091  0.64285714
12 0.37692100  0.90909091  0.71428571
13 0.43799047  0.81818182  0.71428571
14 0.49503947  0.81818182  0.78571429
15 0.54152179  0.81818182  0.85714286
16 0.58273907  0.81818182  0.92857143
17 0.60398583  0.72727273  0.92857143
18 0.63121729  0.63636364  0.92857143
19 0.66352988  0.63636364  1.00000000
20 0.73563750  0.54545455  1.00000000
21 0.84121309  0.45454545  1.00000000
22 0.89278788  0.36363636  1.00000000
23 0.92770504  0.27272727  1.00000000
24 0.96569430  0.18181818  1.00000000
25 0.98375395  0.09090909  1.00000000
26        Inf  0.00000000  1.00000000

(There are critics of ROC curves and even sensitivity and specificity in general, among them being Frank Harrell, whose criticisms of these are worth reading.)
Most "classifiers" actually make predictions on a continuum that are then binned according to some threshold to make categorical predictions. If caret does not allow you to access those continuous predictions, the package is less user-friendly than it first seems. (My guess is that you can get them, however.)


Can't get PID from backgrounded java job

Question: The PID file for this statement is created but it is always empty. When running the shell with -x I see that $! empty, yet at the end the java job is left running in the background as desired. Why is the pid missing?
<code> su - $USER -c "nohup java $rest_api_opts -jar $app_home/$app_name \
   > /dev/null 2>&1& echo $! > $PID"
</code>
Answer: Fixed. The trouble is that $! is expanded too early. So escaping it delayed the expansion
<code>su - $USER -c "nohup java $rest_api_opts -jar $app_home/$app_name \
   > /dev/null 2>&1& echo \$! > $PID"
</code>


Setting table value to macro variable SAS

Question: I need to store a value from a table into a variable. I've tried let, symputx, and select into. In the current version I try to use symputx, but the variable is not being updated. The products table contains type, price_floor, price_tier1, price_tier2.
%global price1;
%global price2;

%macro container();
DATA _null_;
    SET products;
    IF type = "Single" THEN DO;
       CALL SYMPUTX('price1', price_floor,'g');
    END;
    IF type = "Multi" THEN DO;
       CALL SYMPUTX('price1', price_tier1,'g');
       CALL SYMPUTX('price2', price_tier2,'g');
   END;
%PUT &=price1;
%PUT &=price2;
%mend;

Both price1 and price2 are null.
SYMBOLGEN: MACRO variable PRICE1 resolves to PRICE1=
SYMBOLGEN: MACRO variable PRICE2 resolves to PRICE2=

Answer: You don't have a run statement on your datastep, so your %put statement is being written to the log before the data step executes - so, the variables don't exist yet.  It won't be run until you do provide a run statement or step boundary, or SAS might do that politely for you when the program is finished, but either way it's not being run before the %put.
Usually, this kind of program is an anti-pattern in SAS; you don't provide sufficient context, so maybe it's okay, but this will only work if you have only one row in the dataset - otherwise it probably won't do anything useful.  The key word that's triggering me to write this is that you called this a "variable" - not a "macro variable" - in your question; SAS macro variables are not really "variables" and not meant to be used like a C variable or Python variable.
Comment: That was an error in my recreating the query for the post. There was a run, but I didn't know that about %put so thank you.
Answer: FYI to anyone interest, I decided to restructure the program as a whole. The original plan was to pass elements of a user defined array into %container, then use the assigned macro variables price1 and price2 as parameter in another macro call.
Instead of imbedding this data step in a macro, I created a table to contain all of the inputs I planned to pass into %container. Then I just used executes with the table variables concatenated within instead of direct macro calls.
data _null_;
    SET products;
    IF type = "Single" THEN DO;
       CALL execute('%split_prod('||price_floor||');');
    END;
    IF type = "Multi" THEN DO;
       CALL execute('%select_prod('||price1||','||price2||');');
    END;
run;

Comment: Definitely a better way to do this!
Answer: There isn't anything wrong with the code besides the RUN.
%global price1;
%global price2;

data products;
infile cards dlm=',';
input Type $ price_floor price_tier1 price_tier2;
cards;
Multi, 40, 20, 60
;;;;;

%macro container();
DATA _null_;
    SET products;
    IF type = "Single" THEN DO;
       CALL SYMPUTX('price1', price_floor,'g');
    END;
    IF type = "Multi" THEN DO;
       CALL SYMPUTX('price1', price_tier1,'g');
       CALL SYMPUTX('price2', price_tier2,'g');
   END;
RUN;

%mend;

%container();

%PUT &=price1;
%PUT &=price2;

LOG:
 96         %PUT &=price1;
 PRICE1=20
 97         %PUT &=price2;
 PRICE2=60

You never showed your call for %container() so not sure what the underlying issue is, but CALL EXECUTE is a better method as debugging macros is painful.


A class of children contains 14 boys and 12 girls. How many ways are there to choose a team of six children from the class if...

Question: A class of children contains 14 boys and 12 girls. How many ways are there to choose a team of six children from the class if it must contain at least two boys and at least two girls?
I already know the answer(191191), which was found by considering the cases of 2 boys + 4 girls, 3 boys + 3 girls and, 4 boys and 2 girls separately - then adding up the numbers.
However I am not sure why I can't do the following, so would like the error to be pointed out:
First choose 2 boys, then choose two girls, then choose any two pupils from the remaining 22. So
2 boys = 14C2 combinations = 91
2 girls = 12C2 combinations = 66
2 remaining pupils = 22C2 combinations = 231
Total number = 91*66*231 = 1387386
Answer: Your problem is that you count some teams several times.
The same set (Albert, Bill, Cindy, Daisy, Evan, Flint) will be counted 6 times by your method:

(Albert, Bill) + (Cindy, Daisy) + (Evan, Flint)
(Albert, Evan) + (Cindy, Daisy) + (Bill, Flint)
(Bill, Evan) + (Cindy, Daisy) + (Albert, Flint)

etc.
Answer: This is a frequent problem in combinatorics: You are overcounting (which you can see by your number that is too high) because the same choice is counted several times.
Because, call the boys $B_1,...B_{14}$ and the girls $G_1,...,G_{12}$, then in your way of counting, you could say:
I take $B_1$ and $B_2$, then $G_1$ and $G_2$. Now two arbitrary pupils, let's say $B_5$ and $G_7$.
But you could also start with the boys $B_2$ and $B_5$, then take the girls $G_1$ and $G_7$ and for the arbitrary pupils, take $B_1$ and $G_2$. Now you have the same overall team, but you counted as though they were different possibilities.
It is very difficult to correct such an overcounting, so it's better to start counting the right way.
Answer: You may understand what's wrong if you think of the following example. Say you want to choose 2 boys out of 4.
Then the correct way is $\binom{4}{2}=6$. But if you do it the way you are suggesting it will be $\binom{4}{1}\binom{3}{1}=12$. In other words, you take into account the order, hence you have more ways to choose them.
Answer: Try this
Conditions:
atleast 2 boys and atleast 2 girls and a team of 6 to be formed
Boys-2 ,girls -4
C(14,2) . C(12,4)=91 .495=45045
Boys-3, girls -3
C(14,3).C(12,3)=104 . 220= 80080
Boys-4,girls-2
C(14,4).C(12,2)=1001 . 66=66066
Adding all these possibilities
Answer=191191
Comment: I agreed and I corrected that
Comment: You have an issue with the numerical application. Anyway, this (correct) approach is already given in the original question...
Answer: I will explains you with simple example
Selecting 4 items from 6 items ok
Your way is c(6,2).c(4,2)=15 .6=90
But answer is c(6,4)=15
Think why it happens ...
You are counting the ways several times


What is the correct distribution?

Question: Let, I have the following Frequency Distribution:

Which one would be the correct Grouped frequency Table if class-width = $1.0$?
$Table\#1$

$Table\#2$

Explain "Why".
What would be the answer if $\#$ of groups = $5$?
Comment: Table#1 is the correct one, because # of groups = 6 in Table#2.
Comment: I think there are two questions: (a) The first interval of table #1 is effectively longer than the others. For five intervals of equal length you need intervals something like (0.00-0.92), (0.93-2.94), ..., (3.99-5.00), in which intervals are effectively a little longer than 1.00. (b) #2 has six intervals of effective length 1.00.
Answer: We use R statistical software to show five intervals of equal width
for the data in your Question.
You have data:
x = c(0, 2, 2.8,2.8,2.8, 3,3,3, 3.5, 4,4,4, 4.5, 5,5)
table(x)
x
0   2 2.8   3 3.5   4 4.5   5
1   1   3   3   1   3   1   2

You need six equally spaced boundary points for five intervals. One possible
choice of boundaries is shown below.
bdy = seq(-.09, 5.01, by=1.02);  bdy
[1] -0.09  0.93  1.95  2.97  3.99  5.01
diff(bdy)  # verify equal lengths 1.02
[1] 1.02 1.02 1.02 1.02 1.02

Make a frequency histogram of the data using these intervals. (Notice that
one of the intervals turns out to be empty.)
hist(x, br=bdy, col="skyblue2", label=T, ylim=c(0,7))
rug(x, col="red")

The statement rug puts red tick marks along the horizontal axis, showing
locations of observations. (Tied values are represented by only one tick mark.)

Here is a 'stripchart', which shows each individual observation. (The data values are exactly at the centers of the boxes.) Vertical lines show
the boundaries.
stripchart(x, method="stack")
abline(v=bdy, col="green3")

What is the correct distribution?


How to fix the error 'You cannot add children to a simple form. Maybe you should set the option "compound" to true?' php symfony

Question: I have made a form, but it gets an error message in the form. Here is some code:
class ForgotPasswordForm extends FormType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('email', EmailType::class, [
            'constraints' => [
                new NotBlank(),
                new Email(),

            ],
        ]);
    }
}

Code of the createform:
$form = $this->createForm(ForgotPasswordForm::class);

Comment: Just as a side note, there is already a library for resetting passwords: [*symfonycasts/reset-password-bundle*](https://github.com/SymfonyCasts/reset-password-bundle)
Answer: A form should extend AbstractType and not FormType
class ForgotPasswordForm extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        …
    }
}


Is there any method like substitute of MooTools in jQuery?

Question: This is MooTools code:
var myString = "{subject} is {property_1} and {property_2}.";
var myObject = {subject: 'Jack Bauer', property_1: 'our lord', property_2: 'savior'};
myString.substitute(myObject);

Does jQuery has this method or similar?
Comment: http://www.planabc.net/2011/05/31/simple_javascript_template_substitute/
https://github.com/yui/yui3/blob/master/src/substitute/js/substitute.js Here is YUI's solution.
Answer: No, but there's nothing preventing you from adding it yourself:
jQuery.substitute = function(str, sub) {
    return str.replace(/\{(.+?)\}/g, function($0, $1) {
        return $1 in sub ? sub[$1] : $0;
    });
};

// usage:
jQuery.substitute('{foo}', {foo:'123'});

Comment: For reference, this is how the MooTools substitute works:
`substitute: function(object, regexp){
        return String(this).replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name){
            if (match.charAt(0) == '\\') return match.slice(1);
            return (object[name] != null) ? object[name] : '';
        });`
Answer: Try this plugin https://github.com/trix/nano , the source is just a few lines
/* Nano Templates (Tomasz Mazur, Jacek Becela) */
(function($){
  $.nano = function(template, data) {
    return template.replace(/\{([\w\.]*)\}/g, function (str, key) {
      var keys = key.split("."), value = data[keys.shift()];
      $.each(keys, function () { value = value[this]; });
      return (value === null || value === undefined) ? "" : value;
    });
  };
})(jQuery);

You can use dot notation {user.name} , just simple and powerful.
Answer: The $.nano answer threw me for a loop because it errors if you have any typos in your template dot notation, and furthermore it doesn't allow all legal characters like a['foo bar'] so below is my version as a $.substitute plugin:
/*
 * JQuery Substitute method allows for simple templating using JS Object dot notation.
 * Contribute link: https://gist.github.com/danielsokolowski/0954fc2a767f441720b9
 *
 * @param strTemplate - string contain the replacement tokens
 * @param objData   - an Object represetnting your replacmenet values
 *
 *  Example:
 * var strTemplate = 'Hello {user.name}'
 * var strDatra = {'user': 'Daniel Sokolowski'}
 * alert($.substitute(strTemplate, objData)); // outputs 'Hello Daniel Sokolowski'
 *
 */
$.substitute = function(strTemplate, objData) {
    return strTemplate.replace(/\{([^{}]*)\}/g, function(math, subMatch1) {
        try {
            var keys = subMatch1.split(".");
            var value = objData[keys.shift()]; // return first element and update the original array
            while (keys.length !== 0) { // keep returning properties
                value = value[keys.shift()]
            }
            return String(value);
        } catch (err) { // return any errors as a string
            return String(value);
        }

    });
};

Comment: Sorry for the editing confusion, I just saw that you do a `split(".")` inside the plugin
Answer: There are some plugins that share a similar syntax to the String.Format method in .NET.
This one leverages the jQuery Validate plugin (commonly found on CDNs).
Example:
$("button").click(function () {
  var str = "Hello {0}, this is {1}";

  str = jQuery.validator.format(str, "World", "Bob");
  alert("'" + str + "'");
});

The second plugin is named .NET Style String Format.
Example:
var result = $.format("Hello, {0}", "world");

These may not be exactly what you're looking for, but they may be useful.


Are negative numbers that are left shifted *always* filled in with "1" instead of "0"?

Question: I'm independently studying bit-shifting by porting some C++ functions to .NET's BigInteger.  I noticed that when I shifted BigInteger the void was filled in with ones.
I believe this has to do with the negative number being stored in twos compliment form.
BigInteger num = -126;
compactBitsRepresentation = (uint)(int)(num << 16);

Here is what happened after the shift (most significant bit first)
10000010 will be shifted 16
11111111100000100000000000000000 was shifted 16

Should I always expect a similar bit-shift operation to act this way?  Is this consistent with different languages and implementations of "bigNumber" such as OpenSSL?
Answer: From the BigInteger.LeftShift operator docs:

Unlike the bitwise left-shift operation with integer primitives, the
  LeftShift method preserves the sign of the original BigInteger value.

So .NET guarantees the behavior that you see.
I'm not that familiar with bignum libraries, but the docs for OpenSSL's BIGNUM BN_lshift()` function says:

BN_lshift() shifts a left by n bits and places the result in r ("r=a*2^n"). BN_lshift1() shifts a left by one and places the result in r ("r=2*a").

Since the operation is defined in terms of multiplication by a power of two, if you convert the resulting BIGNUM to a two's complement number (I have no idea how BIGNUM represents numbers internally) then you'll see similar behavior to .NET.
I wouldn't be surprised if other bignum libraries behaved similarly, but you'd really need to check the docs if you want to depend on the behavior.  However, since shifting is very similar to multiplication or division by powers of two, you can probably get 'portable' behavior by using an appropriate multiplication or division instead of a shift.  Then all you'd need to ensure is that you can get the conversion to a two's complement representation (which is an issue that is really independent of the behavior of the shift operation).
Answer:
Should I always expect a similar bit-shift operation to act this way?

You should if the number format in question uses two's complement to represent negative numbers (and many do). To form the two's complement of a number, you invert all the bits and add one, so for example:
23 is represented as 00010111
-23 is represented as 11101001 (that is, 11101000 + 1)

Furthermore, when you convert a type to a larger type, the value is usually sign-extended, i.e. the leftmost bit is extended into the extra bits in the larger type. That preserves the sign of the number.
So yes, it's quite common for numeric representations to be "filled" with 1 for numeric values.
Answer: 10000010 is first changed to a bigger width. In this case, 4 bytes:
10000010 --> 11111111 11111111 11111111 10000010

You get 1s on the left since the number is negative.
Now the left shift simply inserts 0s from the right and throw bits from the left:
11111111 11111111 11111111 10000010 << 16 -->
11111111 10000010 00000000 00000000

Comment: Is it standard C++ behavior? IIRC it's implementation defined, not standard behavior.
Comment: It's actually undefined behavior to left shift a negative number in C or C++.
Comment: Yup, see http://stackoverflow.com/questions/3784996/why-does-left-shift-operation-invoke-undefined-behaviour-when-the-left-side-oper
Comment: @RichardJ.RossIII, I didn't know that. I didn't mean to use the phrase as "defined by the standard", but rather that "it's a C++ thing, and has nothing to do with .net or biginteger". Removed it nevertheless.


Bézier Curve and b spline curves.

Question: Well I am learning about curves. I have come across Bézier and Spline curves. I want to know which one should be learned first? Are their concepts independent? or I need to know about one before learning the other?
Answer: Bézier curves are more fundamental, so I'd suggest that you study these first. A b-spline curve is just a string of Bézier curves joined together, usually in a nice smooth way. So, understanding Bézier curves will help you understand b-spline curves.
A good place to start might be these notes.

Bézier Curve and b spline curves.


How to grant permissions for a member of two groups that have different permissions in windows?

Question: I have a windows 2008 server with file server role. Multiple shared folders are there, one for each group, so that each group has access to its own folder, but is denied access to other shared folders.
How do I go about granting access to users who belong to more than one group to all their respective folders ?
For example, if Group 1 has only access to Folder 1 and Group 2 has only access to Folder 2, how do a grant access to both Folder 1 and Folder 2 to a user that belongs to Group 1 and Group 2 ?
I haven't succeded so far and I've read that :

[...] if a user is a member of a group where full
  control is provided over a folder, and also a member of a second group
  where full control is specifically denied, the user will be denied
  full control regardless of the fact that it was granted in the first
  group.

(from TechTopia)
Comment: Stop using 'Deny' permissions, only add the groups that need access to the permissions on each folder and add your user to both appropriate groups.  And read up on NTFS permissions.  The deny entries are almost certainly unnecessary.
Answer: BlueCompute is right, but here is why:
'Deny' will usurp any 'grant' permissions, that is the point of deny permissions. By default a users dosn't have access to a resource it hasn't been granted access to. But if you grant it wide access and want to pin hole a resource and deny access, you use deny.
Comment: Yeah, the important point for you, ychaouche, is that you don't need to use 'Deny' to prevent a group from having access to a resource.  You prevent them from accessing it by simply not granting them any permissions at all on the resource, NOT by adding a Deny entry.
Comment: Agree with BlueCompute. Deny permissions should be used very sparingly and only in specific use cases. This is certainly not one of those cases. To prevent users or groups from accessing resources means making sure that they don't have any permissions (direct or inherited). Not by applying the Deny permission but by not applying any Allow permissions.


how to use AMD on a Single-page application to load only certain dependency

Question: From what I understand, one benefit of using AMD managing dependencies that get loaded, But in single-page application using require.js all of the dependencies will be loaded.
For example using backbone or something similar, lets say I have the following files

main.js requires router.js
  router.js requires view_a.js and view_b.js

router.js renders the views
routes: {
   "view_b":"b",
   "view_a":"a"
},
a:function{
  showView(new ViewA());
},
b:function{
  showView(new ViewB());
}

Now lets say I go to example.com/#view_b which only requires the code in view_b.js but doesn't use anything from view_a.js. Is there anyway to only loaded or prioritize the loading view_b.js using require.js or something similar?
Comment: Why not change `showView(new ViewB())` to `require("view_b", function(constr){ showView(new constr()); })`?
Comment: Why does your router require those view files?
Comment: @Bergi Because the router renders the view.
Comment: But only the one that is needed, doesn't it? So it should require it dynamically
Comment: @Bergi I just added the structure of router.js, since router handles rendering `showView`, It needs to included all of the views
Comment: @Bergi Yep thats what I was looking for. In hindsight its obvious, but I didn't realize that you could have nested require(). Thanks!
Answer: You can't because require.js need all dependencies of your file to be loaded before executing it.
I see two solutions to your problem:

Create two distinct Backbone.Router, like that you only "require" needed modules for each router (IMHO it's not the best solution)
Use require.js optimizer, this will combine all your Javascript files into one. Of course you only use it for production, not in development.


Write down an inverse matrix in terms of a matrix

Question: $B^3-2B^2+3B=0$
I need to write it down in terms of $B^{-1}$ (inverse of it)  I know how that $BB^{-1}=I$ but seems it wont help to find $B^{-1}$ what kind of method do i have to use ?
Comment: Which "it" do you need to write down in terms of $B^{-1}$?
Or do you mean you need to write down $B^{-1}$ in terms of $B$?
Comment: Ok, $B^3-3B^2+3B=0$, we multiply it by $B^{-3}$ an we got $I-3B^{-1}+3B^{-2}=0$. Is that it?
Comment: That equation need to be written down in terms of inverse of B^-1
Answer: Assuming $B^{-1}$ exists multiply both sides by $B^{-1}$ to get
$$B^{-1}B^3-2B^{-1}B^2+3B^{-1}B=B^{-1}0$$
this is the same as saying
$$B^2-2B+3I=0$$
Multiply again by $B^{-1}$ to get
$$B^{-1}B^2-2B^{-1}B+3B^{-1}I=B^{-1}0$$
The expression above is the same as
$$B-2I+3B^{-1}=0$$
This gives you the inverse in terms of the matrix itself
$$B^{-1}=\frac{1}{3}(2I-B)$$
Unless you want to convert the original equation in terms of $B^{-1}$ then following the same steps you would get to $$B^{-1}-2(B^{-1})^2+3(B^{-1})^3=0$$
Answer: Actually the method is just write the equation $3x=2x^2-x^3 \Rightarrow 1=\frac13(2x-x^2)$[if $B^{-1}$ exists then only]$=\frac13(2-x)x$ . From here put $x=B$ & $1=I$ then consider $B'=\frac13(2I-B)$ then see BB'=I=B'B. hence B is invertible and $B'=B^{-1}$.
Note all this process can only be done if $B^{-1}$ exists. It may be possible that $B^{-1}$ does not exist [just consider the $0$ matrix.]


Strong duality strictly convex quadratic problem

Question: Assume we have this strictly convex quadratic programming:
$$f(x) = x^\top A x + b^\top x,$$
$$Ax \leq b$$
$$ 0 \leq x \leq 1$$
Where $A$ is symmetric and positive definite, and the feasible set is nonempty.
Does strong duality and Slater's condition holds in this case.
Comment: you said the feasible set is nonempty, so I do not understand your first question (feasibility means that the optimal value is finite too)
Comment: you mean the second question, right, since the first one is about the duality? I removed the second question, how about the duality?
Comment: Slater's condition requires a strictly feasible solution.  If your linear equalities are such that (e.g.) there is a unique feasible solution then Slater's condition wouldn't be satisfied.  Depending on your constraints, other constraint qualifications, such as the linear independence constraint qualification (LICQ), might hold.
Comment: @Brian Borchers All the constraints are linear, that is a constraint qualification.  Slater's condition only pertains to nonlinear constraints, so you could say it is trivially satisfied in this case.
Comment: @MarkL.Stone yes, but I was hoping that the OP could find this out for themselves...
Answer: The feasible set is nonempty and compact. The objective is continuous. So by Weirstrass we have a finite optimal value.
The constraints and the objective are all convex functions.
Finally, since the feasible set is nonempty, we have a vector which satisfies the linear inequalities. Thus we have Slater's condition (linear inequalities do not require strict feasibility).
So we also have strong duality.
Comment: Thank you, Does this proof hold if we also have additional equality constraints $Cx = 1$.
Comment: Yes. Equality constraints do not change the compactness of the feasible set nor the fact that Slater's condition holds.
Comment: @Alex Shtoff, If the constraint is $\{\mathbf{x} \in C, G(\mathbf{x})\in K\}$. we say slater's condition holds, if exists $\mathbf{x} \in C$ such that $G(\mathbf{x}) \in \text{int}(K)$. So for this case is exists $0 \leq \mathbf{x} \leq 1$ such that
$A\mathbf{x}-\mathbf{b}<0$,  why linear inequalities do not require strict feasibility?
Comment: The proof isn't trivial, but that's indeed the case. Slater's conditions with linear inequalities do not require strict feasibility. See this book:https://archive.siam.org/books/mo19/


starting sshd: /etc/ssh/sshd_config: permission denied

Question: I am running a Centos machine in Amazon cloud. Suddenly, I can't ssh into it. Fortunately, there is R Studio running that includes an ability to run BASH shell. So, I see in /var/log/boot.log that sshd failed to start.
When I run it from the command line sudo service sshd start I get an error that Starting sshd: /etc/ssh/sshd_config: Permission denied. I tried to set sshd_config permissions to either 644 or 600 - but I get the same error. Also I tried sudo su - and then start service.
And it is not the limitation of the shell itself: I can start httpd without any problems.
I don't even know what else to try...
Comment: what is the perms on /etc/ssh `ls -ld /etc/ssh`? Is it executable?
Comment: yes, 755 `drwxr-xr-x. 2 root root 4096 Aug 24 02:05 /etc/ssh`
Comment: @Felix `sshd_config` should be chmoded to `600` or `u+rw,o=`. Make sure you check it using `ls -l sshd_config`  Also make sure that the problem is coming from `sshd_config` and not other misconfigured source.
Comment: verify that `sshd` did not lose its sticky bit, too
Comment: @sendmoreinfo - could you elaborate on it... I don't think sshd ever had sticky bit in the first place - why would you expect it to have it? Or maybe I misunderstand what you are saying
Answer: I was faced with the same issue, and thanks to Felix answer, I could confirm that it was also an SELINUX error :
# grep "sshd_config" /var/log/audit/audit.log
...
type=AVC msg=audit(1585907328.579:143): avc:  denied  { read } for  pid=1207 comm="sshd" name="sshd_config" dev="dm-0" ino=443439 scontext=system_u:system_r:sshd_t:s0-s0:c0.c1023 tcontext=system_u:object_r:unlabeled_t:s0 tclass=file
...

I was then able to solve the error by restoring the default contexts:
# restorecon /etc/ssh/sshd_config

That way SELINUX didn't need to be disabled.
Answer: This is what happened... There was a problem with the image (specifics here: https://bugzilla.redhat.com/show_bug.cgi?id=956531). So, as part of troubleshooting I mounted the EBS drive on a different machine, and "cleaned" sshd_config. That caused SELINUX to deny access to this file, and the error message was caused by SELINUX; not by file permissions. Once I disabled SELINUX, sshd came up fine.
World is saved :)


How to build composer from a source code?

Question: I have cloned repository from GitHub. So I am wondering how to build my own composer instance from the source files?
Answer: It also took me a while to find it, but the installation from source instructions are listed here in the Composer repository.
Basically you can install Composer from source with Composer, e.g. composer install. Very meta! Then you can use the Composer you've installed from source with path-where-you-cloned-composer/bin/composer. See the full instructions copied below:

Run git clone https://github.com/composer/composer.git
Download the composer.phar executable
Run Composer to get the dependencies: cd composer && php ../composer.phar install

You can run the test suite by executing vendor/bin/phpunit when
inside the composer directory, and run Composer by executing the
bin/composer. To test your modified Composer code against another
project, run php /path/to/composer/bin/composer inside that
project's directory.

(If you already have Composer installed globally, you don't need to do step 2.)


5 days - Up to now, is this a satisfactory private Beta?

Question: I say "5 days" because it has been 5 24-hour periods after I received notification from SE to join the private Beta.
I have no experience from other private Betas, and certainly  Q&A subjects differ in popularity (which affects also their private Beta experience). But as in Public Beta, there must be some accumulated experience as to whether the statistics of the Private Beta indicate a site that has better or worse options for a successful Public Beta and then on to eternity.
If there are users here that have participated in other private betas (and even better, in the private Beta of the previous failed attempt for the Economics site), or also, SE community managers that have a wider picture, it would be useful to share some thoughts: I am not asking for an oracle ("you will/you will not succeed"), just an indication as to where we stand at the moment.
Just please, marketing-speak to the effect "it is too early to tell", "keep on trying" etc is not suitable here -we are economists. I am specifically asking "is it satisfactory up to know", without saying that the fate has been sealed.
Me, I will provide the data, and some comments related to benchmarks for Public Beta (of course by the time you will read this, the running data may be a bit different).
A) Number of questions asked (using the time stamp of the site)
\begin{array}{| r | r | }
  \hline
   \text {day}& \text {Q's} \\
  \hline
\hline
  \text {Nov-18} & \text {13} \\
  \hline
 \text {Nov-19} & \text {38} \\
  \hline
\text {Nov-20} & \text {11} \\
  \hline
\text {Nov-21} & \text {16} \\
  \hline
\text {Nov-22} & \text {7} \\
  \hline
\text {Nov-23} & \text {11} \\
  \hline
\text {Total Q} & \text {96} \\
  \hline
  \hline
\end{array}
"Healthy Public Beta" is "15 questions per day".
B) Answers
\begin{array}{| r | r | }
  \hline
   \text {# of A's}& \text {# of Q's} \\
  \hline
\hline
  \text {Unanswered on Hold} & \text {8} \\
\hline
  \text {Unanswered active} & \text {14} \\
  \hline
 \text {1} & \text {36} \\
  \hline
\text {2} & \text {19} \\
  \hline
\text {3} & \text {11} \\
  \hline
\text {4} & \text {4} \\
  \hline
\text {5} & \text {2} \\
  \hline
\text {6} & \text {1} \\
  \hline
\text {10} & \text {1} \\
  \hline
\text {Total Q} & \text {96} \\
  \hline
  \hline
\end{array}
Two statistics here:
a) Questions Answered (excluding the "On hold Unanswered") is $74/88 = 84$%. Public Beta benchmark is $90$%.
b) Weighted "Answer ratio" = $149/96 = 1.55$. The benchmark for Public Beta is $2.5$.
C) Accepted Answers (Green checks)
\begin{array}{| r | r | r| r|}
  \hline
   \text {# of A's}& \text {with Green} & \text {Without Green}& \text {Totals}\\
  \hline
\hline
  \text {1 answer} & \text {8} & \text {28}  & \text {36} \\
\hline
  \text {2+ answer} & \text {16} & \text {22}  & \text {38}\\
  \hline
  \hline
\text {Totals } & \text {24} & \text {48} & \text {74}\\
  \hline
  \hline
\end{array}
There is no relevant benchmark value for Public Beta. It is obvious that having 2 or more answers increases the chance of the OP finding something useful. Still, 22 questions with $2+$ answers remain without an accepted answer. Just in case OPs are neglecting to act on the matter, please do.
D) Users
In "No rep points earned" are those users with rep $101$ or $1$.
\begin{array}{| r | r | }
  \hline
   \text {rep points Status}& \text {# of Users} \\
  \hline
\hline
  \text {rep points earned} & \text {64} \\
  \hline
 \text {NO rep points earned} & \text {154} \\
  \hline
\text {Total Users} & \text {218} \\
  \hline
  \hline
\end{array}
This is an indication of how many people are... "actively active" on the site. Of course from the 154 users with no rep earned here, there may be those that silently browse the site. Still, the "actively active" users are the engine of growth -let's just not put our hopes in the existence of a Solow residual.
Comment: Nice summary. Of all the metrics, I don't care at all about the accepted answers. I feel that leaving them unchecked invites more for new answers, and none of them was so satisfactory answered that no new answer could dominate them. I think the biggest lack are in questions, so I'll try to work on that again soonishly.
Comment: @jmbejara The very old fashioned way. Scrolled the list of questions, recording date of posting, number of answers and Green checks, and also scrolled the list of users and counting the total as well as those with the rep points mentioned. With 96 questions and 218 users, it wasn't worth searching the various queries available on SE instead.
Comment: I switched it to locked for historical significance, is that better?
Comment: @JasonNichols I absolutely agree with you that a) This question should be closed and remain "frozen" as a trace of our beginnings and b) that analogous questions regarding the public beta would be useful. So as for a) "Locked for historical significance" -it may even be a first for the SE world, so absolutely, yes, go ahead.
Comment: @JasonNichols I think historical lock is fine for all the private beta questions. If in doubt about how to use the mod tools, just ask in the mod-only [teachers' lounge](http://chat.stackexchange.com/rooms/4/teachers-lounge). NB you will have to make your Economics account into the "parent user" of your chat account, to get access. At the moment, your Area51 account is the parent user of your [chat account](http://chat.stackexchange.com/users/132641/jason-nichols) - you can change this on your chat profile.
Comment: @FooBar Thanks. Regarding the Green check, I am not so much seeing it as an "incentive mechanism" to attract answerers, but rather, as a possible signal to newcomers as to whether they will find "useful answers" here or not to their questions. But indeed, it is the least important metric.
Comment: Thanks for the summary. Just curious, how did you find this data?
Comment: Oh, ok. Yeah. Thanks for doing that!!
Comment: This question appears to be off-topic because it is about the private beta. Similar questions would be welcome about the public beta now.
Comment: @JasonNichols How can the history of the site be off-topic? You should find some other way to close this question. Putting it "on hold" is inaccurate, and worse, it creates the wrong impressions (about the OP, no less), since, whether we want it or not, the "on hold" in the title of the question says "this question is flawed" -and this question is not flawed.
Comment: honestly, feeling out the controls here, so please provide feedback.
Comment: @JasonNichols This thread appears to remain unlocked. What happened to the history laurels?!
Comment: Odd, I swear I locked it. I just locked it again, @AlecosPapadopoulos. Let me know if it gets unlocked again, please.
Answer: I wouldn't worry too much about those Area 51 benchmarks - they were set out years ago, and haven't been updated with what's been learnt in the intervening few years.
users
64 active  users isn't a huge amount: we could do with sending out more private beta invitations (see the box on the right, in the main site, labelled "Invite Fellow Experts".)

expertise
It's much easier to attract non-expert questions later, once we're known as a community of experts, than it is to attract expert answerers later, if the site has the appearance of being occupied by a bunch of novices.
Expert questions are getting posted, and generally getting answered, and that's great. It's OK to have some unanswered questions too: one of the grounds for sending a private beta out, is to link to an unanswered question, and ask the invitee if they're able to answer it; an interesting, challenging question can be a great way to hook new experts in.
We haven't done very well at getting the non-expert stuff closed and removed, which is a problem. We have some users that persist in posting non-expert content. I genuinely don't believe their intentions are of sabotage; perhaps they're just trying to hoover easy rep by asking foundational questions; or they're just so excited that they can't wait; but the result is detrimental.
activity in meta and chat
This meta is reasonably active, and that's a very good thing. Chat is active too - please do pop over and introduce yourself if you haven't already.
returning contributors
The really important metric, is do our experts contribute, and keep returning. There isn't a simple measure of that - it's more a question of looking at the content being generated, and looking at who's generated it.
patience
One of the SE Inc Community Team will be along shortly to review things, and give us some guidance on whether we're close to going to public beta or not.
I've seen private betas extended by a week or two.
It's not wise to hurry it. While we're in private beta, we've all got more privileges. It's easy to create tags. We can build a core community. We've got a protected space where we can invite experts to give questions and answers. Don't be in too much of a hurry to leave that behind, because if this site doesn't take off, the next opportunity for an Economics.SE private beta could be years away ...
Comment: In Experience We Trust.
Comment: So the private Beta period can be extended? That's _certainly_ a good thing - I was under the impression that private Betas last only for 7 days, and that's it.
Comment: Yes, I've seen private betas extended by a week or two. More than that, and it starts to look like a site won't make it out of private beta ...
Comment: So we got, let's say at most 10 days to improve things. 10 days that changed the -ok, not the world.
Comment: The Powers That Be may come by and love what they see, and send us public straight away. They've got WAY more experience than me of private betas - probably about 20-40 times as much - and it's their job to know this stuff. I expect that they also have access to loads of dev info and maybe customised internal stats. We'll find out what the word from the owners is in a day or three, I expect.
Comment: Yup, I trust their judgement. I'm here because I consider them to be the experts at running Q&A sites. (oh, and the two weeks I mentioned, was an additional two weeks on top of the nominal minimum of a 1-week private beta. So, I reckon we've got up to 16 more days to go public, but hopefully we'll do it in two days)
Comment: Just to note that apparently it's a public holiday in the USA, where most of the Community Team are sited, so any announcement about the arrival of, or the delay to, public beta status may not come until the start of next week.


Robot's keyPress() doesn't work as should

Question: I need help with Robot class in Java. I have the following code:
public static void main(String[] args) throws AWTException {
    Robot r = new Robot();
    r.delay(3000);
    r.keyPress(KeyEvent.VK_7);
    r.delay(5000);
    r.keyRelease(KeyEvent.VK_7);
}

From what I understand, this code has to press "7" and release it after 5 seconds. But it presses "7" and then releases it immediately. So, Robot class doesn't press and release after a while, but it fires the key once instead.
How do I make my Java application to hold a key for few seconds, then release?
Comment: What is exactly your problem? What do you mean by it presses only one time as you only call keyPress once
Comment: I'm sorry for incorrect question. I've corrected. So I mean that Robot doesn't hold the key in "down position". It press and relese after pressing without keyRelease() command
Comment: Any chance it is your keyboard? I mean, do you get different results if you manually hold the `7` key for a seconds from releasing it immediately?
Comment: As I can understand you want to hold down the key for an x amount of time maybe this link will be helpful: http://stackoverflow.com/questions/784414/simulate-a-key-held-down-in-java
Answer: So, after researching this topic closely, I have concluded that java.awt.Robot class just doesn't have the functionality to "hold" down the key.
The answer to a similar question (Simulate a key held down in Java), which recommended me to create a loop of constantly repeating keyPress events, didn't satisfy me, since I needed a real key-hold simulation.
I also tried using this library with no success:
Thread.sleep(3000);
Keyboard.sendKeyDown(KeyEvent.VK_7);
Thread.sleep(5000);
Keyboard.sendKeyUp(KeyEvent.VK_7);

Finally, I solved my issue via winKeyboard. But here's an important note:
I was developing a bot for a game, and was not trying to hold a key inside any text editor and see how it's continually filling the line with characters. If you'll try to test holding button within a text editor, it won't work, because text editors repeated key presses are working differently from normal keyboard events listeners in games. But it's a different topic.
Solution:
Keyboard keyboard = new Keyboard();

Thread.sleep(3000);
keyboard.winKeyPress(ScanCode.DIK_7);
Thread.sleep(5000);
keyboard.winKeyRelease(ScanCode.DIK_7);

Another thing to note is that sometimes, to make the bot work in games, you need to run your application as administrator, otherwise it might not work.


Prove that if A has eigenvalues then determinant of A is the product of eigenvalues

Question: How can I prove that if A has eigenvalues then determinant of A is the product of its eigenvalues?
Comment: Look at your the constant in the characteristic polynomial and use the relation between roots of equation and product of roots.
Answer: Hints:
1) Jordan Canonical Form
2) $\textrm{det}(AB) = \textrm{det}(A)\textrm{det}(B)$
Comment: Can you write a full proof ? @BaronVT


How can I convert a bitstring to the binary form in Julia

Question: I am using bitstring to perform an xor operation on the ith bit of a string:
string = bitstring(string ⊻ 1 <<i)

However the result will be a string, so I cannot continue with other i.
So I want to know how do I convert a bitstring (of the form "000000000000000000000001001") to (0b1001)?
Thanks
Answer: You can use parse to create an integer from the string, and then use string (alt. bitstring)to go the other way. Examples:
julia> str = "000000000000000000000001001";

julia> x = parse(UInt, str; base=2) # parse as UInt from input in base 2
0x0000000000000009

julia> x == 0b1001
true

julia> string(x; base=2) # stringify in base 2
"1001"

julia> bitstring(x) # stringify as bits (64 bits since UInt64 is 64 bits)
"0000000000000000000000000000000000000000000000000000000000001001"

Comment: would it still work if I do bitstring(x \xor 01001)?
Comment: `bitstring` is an alternative to `string(x; base=2)` if that is what you are asking, added that to the answer.
Answer: don't use bitstring. You can either do the math with a BitVector or just a UInt. No reason to bring a String into it.


How to access class members from a method?

Question: I want to access the engine from inside my eventReceiver object.  They are fellow members of the game class, but how do I reach it?
// game.h
class game
{
    public:
        game();
        3dEngine* engine;
        eventReceiver* receiver;
};

// eventReceiver.h
class eventReceiver
{
    public:
        eventReceiver () {}
        virtual bool OnEvent (const SEvent& event)
        {
            ...
            case QUIT_BUTTON_PRESSED:
>>>             engine->quit();     // how to access engine from here??
                return true;
            ...
        }
};

Should I use 'this' ? I don't understand why receiver can't see the engine.
Comment: You have a lot of unnecessary stuffs in your post. Narrow it down. Close to downvote.
Answer: Implement the class as a Singleton and write a getter for the engine property. Accessing code could then look like:
game::getInstance()->getEngine()->quit();

I would recommend you though, that you create a quite() method in the game class itself hiding implementation details and allowing you to handle overall application shutdown and not just of the 3dEngine:
game::getInstance()->quit();

If you dont want to implement the game class as singleton you could also pass a reference/pointer of a game object to the constructor of your event handler:
class CloseButtonHandler : public eventHandler {
    game& game;

public:

    CloseButtonHandler(game& game) : game(game) {
    }

    virtual bool OnEvent(const SEvent& event){
         ...
         game.getEngine()->quit();
    }
}

Comment: So the solution to access is making it a *global*? (*Singleton* is just a fancier name for *global* with the additional restriction that only one instance can be alive...)
Comment: @David Rodriguez A `game` class looks like a global class to me, doesnt it? Besides that Im showing a way to access it in a "normal" pattern. I  just hope this isnt getting another "Singleton - A Antipattern" discussion.
Comment: It all depends on the context... I am quite sure that in Facebook, there is no single global `Game`. At any rate, even if there is a single game in the application, it need not be global (it could be created in `main` and passed around to the types that need to use it...) Globals are almost always worse than any other option that makes do without them, as they hide dependencies (what in your application depends on `game`?) and make the code much harder to reason about (why and where did my `game` state change? *anywhere*?)
Comment: @DavidRodríguez-dribeas See, your opening a book here which doesnt fit into the limited comment space on stackoverflow. A Singleton is a commonly used pattern and i wouldnt know why not to propose it. Myself dont want to forward dozens of objects for configurations etc. Of course there are other ways. Just take a glance at EJBs and CDI. Im actually tired of fighting such abstract discussions without any substance. One just dont know the context of this question, so one has to guess and im still pretty sure that a singleton pattern fits quite good into this situation.
Answer: The eventReceiver shouldn't know anything about the engine. That's a bad design. There are a few solutions. One reasonable solution is to derive game from eventReceiver since game can clearly receive events. You can then implement the game-specific OnEvent handler in game itself. From there you can call engine->quit.
Comment: No, I dont think one has to separate that much. The game class looks actually like a singleton; atleast it seems to be a class involved in the application cycle. Therefor it would be a design issue to put logic to react to a concrete button in such a class. This is totally wrong!
Comment: How about I create them separately in main and just pass the receiver a pointer to myGame:  game myGame;  \n  eventReceiver receiver (&myGame);  ?
Comment: @Paranaix: I would say that it's entirely reasonable to code the `Quit` functionality in class `game`. After all, _you are trying to exit the game_ !
Comment: @MSalters Thats not my point. I would favor such a design. But implementing the actually event handler inside the game class is wrong.  A game class is not an event handler.
Comment: @oringe: A big part of the problem is that `EventReceiver` is a poorly chosen name, and that in turn makes reasoning about it more complex (different people can understand different things). Say that it was a `Controller` (that receives and acts on events), then most people would agree that having a reference to the controlled `engine` would make a lot of sense... In the same way, it is not clear what `Game` represents in your design.
Answer: I don't know how elegant this design is, but it works.
I just separated the receiver from the game class and gave its constructor a pointer to the instance of myGame. (Thanks to Paranaix)
class eventReceiver {
    public:
        eventReceiver (game* gameInstance) : gamei(gameInstance)
        virtual bool OnEvent (...)
            {...
            case QUIT_BUTTON_PRESSED:
                gamei.engine->quitGame();
            ...}
    private:
        game* gamei;
}

int main() {
    game myGame;
    eventReceiver receiver (&myGame);
}


How to run check on each page load?

Question: I would like to run a check on each page load.  This only concerns the front end and not the admin dashboard.
Basically what I would like to do is:
1) User hits a URL in the drupal site.
2) A server-side check is ran. If the check passes, run some logic.
How would I accomplish this?
I'm guessing that I can use a hook, but what hook would that be?
Thanks.
Answer: hook_init() is run on every page load except for cached pages, so depending on your use case that might be an option.
function MYMODULE_init() {
  // Custom logic
}

hook_boot() is run on every page, including cached pages, so might be more useful (again depending on your use case). However if you have complex logic to process this will obviously slow down the build of every page, even those that are cached.
function MYMODULE_boot() {
  // Custom logic
}

If you want to check whether or not the current path falls under '/admin' you can use a check like this in either function:
if (arg(0) == 'admin') {
  // ...
}

This won't work for node edit pages, for example, who's path doesn't have '/admin' in it; but short of invoking hook_admin_paths() and testing the current URL against each of the paths returned, I'm not sure how you'd reliably test for that anyway.
Comment: Thank you for the answer.  How do I limit this to run only for non-admin pages?
Answer: I wanted to contribute something additionally to this. I am not an advocate of hook_init() or hook_boot() for doing tasks like this but tend to look for specific hooks that accomplish what you want. These two hooks are very broad and while they do they job they are also sometimes called multiple times per page load.
An alternative I would propose is hook_page_build().
This will run on page builds and you don't have to worry about running things twice when you may not need to. I made a script for development sites where it would simply inject a bot restricting header line site-wide on pages. Likewise you could do the same as a check on each page load.
function my_module_page_build(&$page) {
  drupal_add_http_header('X-Robots-Tag', 'noindex,nofollow');
}

Similarly you could include a check for administrative pages
function my_module_page_build(&$page) {
  if (path_is_admin()) {
    foo();
  }
  else {
    bar();
  }
}

I prefer path_is_admin() as opposed to checking arbitrary arguments via arg(). Just my preference. Feels less hackish that way IMO.
Comment: @AyeshK -- Keep in mind the user was asking about users hitting pages - not AJAX requests. There is almost never a good reason to use hook_init(). It has been removed from Drupal 8 - so relying on this is not recommended.
Comment: hook_page_build/alters are fine to modify the content (headers, content, etc). But OP asked to run this on every page load, which includes Ajax calls that do not run hook_page_* hooks.
Comment: Does hook_page_build run on cached pages?
Comment: @Teegan -- I am not honestly sure and without digging into Drupal's core at the moment, I would guess that it does - possibly not if using Boost or some other static page caching.
Comment: hook_page_build is also removed in drupal 8, aparently there is now `hook_page_bottom` and `hook_page_top`, but they are not independend of the page caching.
Answer: Now with drupal 8 and 9, the approach outlined in this great blog post from chromatichq.com gives an excellent overview on how to execute code ignoring the cache.
If you require access to the user or session thou, it will also not help, as the http_middleware is very low level.
Comment: Please consider posting the gist of the linked article to your answer in order to remain relevant even if the link breaks in the future.
Comment: Hi @wranvaud, thx for the suggestion :) .Please feel free to edit the answer as you see fit

How to run check on each page load?


Views Data Export field format?

Question: I have created data export view. I need to include a date field in this format: Y-m-d (yyyy-mm-dd). I went to 'Date and Time', then added a new format and assigned it to the short format.
In views, I then select the date field, and select 'short' as the format. The new format (Y-m-d) displays in the view preview correctly.
I download the XLS and open it up, but the date field is defaulting to m/d/y (1/10/13). Why would the date appear correctly in the views preview but not in the download? I also verified all the correct formatters are set in the CCK date field settings. If I just show the fields in a plain old table view layout, it is also displayed correctly. the only incorrect format is in the XLS I download.
Please note: If I change the date field to include a 'From date' & 'To Date' and display both To and From dates in one column, the XLS then displays the dates correctly but unfortunately, I can't have these sets of dates in one column. I need them in 2 columns and in the 'Y-m-d' format.
To further troubleshoot, I also tried selecting the same date field in views and only displaying one date per column. One column to display From and the same date field to display To. This also results in m/d/y (1/10/13).
Is this a bug? I can replicate this on my local environment as well. Basically, the custom date formatters are not being portrayed on the export.
I am using:

Linux CentOS
PHP 5.3.3
MySQL 5.1.61
Drupal 6
Views 6.x-2.16
Views Export 6.x-2.0-beta6
Comment: Please write as answer what is the answer for the question you asked; answer and question should not be mixed up. Probably you cannot immediately write an answer, but you will be able in the next hours.
Comment: Have you tried downloading the file in a different format instead of `.xls`? It's **very** possible that Excel or OpenOffice (or whichever program you use to open the spreadsheet) is automatically changing the format of the dates displayed.
Answer: The date format was being set via the Operating System. OS X's default language and text preferences was re-formatting all dates I type.
With OS X 10.8.3 the preferences are on "System Preferences >> Language and Text >> Region >> Dates >> Customize." There, you can enter your preferred date format.

Views Data Export field format?


RAID-5 how can I guess how many disks was member?

Question: We have a server which we inherited from previous sysadmin. Now the RAID-5 (H/W based on IBM ServeRAID) now unusable, saying not enough disks to operate.
On ServeRAID Manager I can see three physical disks, and one logical volume. The logical volume properties says:
Data space: 698GB and Parity space: 232GB, from which I guess there should be four disks.
Am I right?
In the server there are three disks physically. (Each are 250GB disk.)
So now I should be sure the logical volume was built up originally from thee or four disks? How can be sure in it? I was unsure on proper meaning of Data space and Parity space in this terminology, if I have to sum them, it means four disks should have been there.
Comment: Your logic seems reasonable to me, but where are you going to go from there?  The controller says the RAID is non-functional, so if you need the data you'll have to restore from backups, and if you're going to zero out the array why do you care how many HDDs it used to comprise?
Comment: If it was three discs, the software probably wouldn't be saying "not enough discs to operate".
Comment: Thanks for all! We figured out it was three disks, one of them had bad sectors. All data was recovered from two of the three of RAID-5. It is very consfusing what IBM ServeRAID manager stated about data space and parity space, and not providing exact info about how many disks should be. Btw, we used reclaime.com to restore the image which was a VMFS, which we extract by http://glandium.org/projects/vmfs-tools/, then VMDK was mounted on Windows by official vmware software.
Comment: Well, two goals: I need evidence to report what happened, and get the consequences. Second, if it was three disks we can give a try of recovery software.
Comment: Here's what I don't get.  While your math seems to be on, if it were a RAID-5 array with 4 drives and one is now missing, the array would have been set by ServeRAID as "degraded" but would still function with that single drive missing, just without parity.  Another drive failure would cause total failure, but I'm surprised that you can't get the logical drive to boot or see the data on that drive if the existing 3 drives are online and part of the original array before you got it.
Comment: @TheCleaner Now two drives says: OK, and one says: Rebuilding. But seems do nothing. According manual Rebuilding will start itself if hot-spare is ready. There were no hot spare, and we did not fire a command to rebuild. However the ServeRAID manager states this. Our assumption is system was running degraded, and now another disk made errors, and now faulted. We have not noticed as Windows Server was running in ESXi, so WinServ didn't even know it runs on ServeRAID, so no errors come up.
Comment: Well, the ESXi hardware monitor would've said if a drive failed, but that's neither here nor there.  If you are just hoping to get the data, you could try booting into ServeRAID and marking all disks as "ONLINE" and hoping that the server boots by tricking it.  I've done this in the past with an xSeries server but I didn't try booting it, but instead used a Linux boot disk to then access the logical drive and move data off.
Comment: @TheCleaner Now we will try to clone the disks one-by-one and investigate those images by some Raid Recovery tools. The server is in two hours driving distance, so until my colleague arrive back, I just preparing. I am not brave enough to try force online without having a copy at least :)
Comment: Sure.  And if you have IBM hardware support on this, you can contact them as well.  They have some internal tools that can help.  I've had them assist in the past on a server that didn't have a good backup and 2 of 3 disks had failed.  This was years and years ago, so maybe they've gotten even better tools now.
Answer: Just a guess shot, but after reading the question and 8 comments this seems possible... One of the disks have failed, but removed was not that one. Possibly the admin's mistake. If you can get the missing one there's some hope.
Does ServeRAID use DDF metadata? If so, it may be worth trying Linux mdadm (ver. 3.0+) to re-assemble if hardware controller refuses to.


Warning meassage: number of items to replace is not a multiple of replacement length

Question: I got warnings when running this code.
For example, when I put
tm1<- summary(tmfit)[c(4,8,9)],
I can get the result, but I need to run this code for each $i$.
Why do I get this error?
Is there any way to do this instead of via a for loop?
Specifically, I have many regressants ($y$) with the same two regressors ($x$'s).
How I can get these results of regression analysis(to make some comparisons)?
dreg=read.csv("dayreg.csv")
fundr=read.csv("fundreturnday.csv")
num=ncol(fundr)
exr=dreg[,2]
tm=dreg[,4]
for(i in 2:num)
{
  tmfit=lm(fundr[,i]~exr+tm)
  tm1[i]<- summary(tmfit)[c(4,8,9)]
}

Any help is highly appreciated
Answer: Try storing your result into a list instead of a vector.
dreg=read.csv("dayreg.csv")
fundr=read.csv("fundreturnday.csv")
num=ncol(fundr)
exr=dreg[,2]
tm = list()
for(i in 2:num)
{
  tmfit=lm(fundr[,i]~exr+tm)
  tm1[[i]]<- summary(tmfit)[c(4,8,9)]
}

You can look at an element in the list like so
tm1[[2]]

Comment: @jsk.Thank you for your answer.Another qestion :you konw summary(tmfit) is a recursive list of length 11.I want save tm1(including three items :coefficients,r-aquared,adj.r-squared) into a csv file ,but I get the messy file.why ?code:write.csv(tm1,"tm_reg.csv")
Comment: Hi Jacky, please post this as a separate question on the site. Thanks


Complete and Sufficient Statistic for Discrete Distribution

Question: I have a single observation X from the following distribution:
$$(=−1)=\dfrac{}{3},(=0)=(1−),(=1)=\dfrac{2}{3}$$
I'm trying to find a complete and sufficient statistic for p based on the single observation X. My current attempt is $T=X^{2}$ but I'm unsure of my approach/reasoning:
$$f_{\theta}(X) = \left(p \right)^{1_{(X^{2}=1)}}\left(1-p \right)^{1_{(X^{2}=0)}}$$
By factorization $h(X) = 1$ and $g_{\theta}(T) = \left(p \right)^{1_{(X^{2}=1)}}\left(1-p \right)^{1_{(X^{2}=0)}}$, meaning that $T=X^{2}$ is sufficient. Then to show completeness I have:
$$E_{p}[a(T)] = P(X^{2}=1)a(1) + P(X^{2}=0)a(0)$$
$$=pa(1) + (1-p)a(0)=0 $$
which we can see implies that $a(T)=0$ and thus $T=X^{2}$ is complete. I just wanted to make sure that this looks okay, I'm a bit unsure about showing a statistic is sufficient and complete.
Answer: Your explanation for completeness is correct. For sufficiency, I think you need to be a little more careful with the probability mass function for $X$. What you wrote down, $f_\theta(x)$, is the p.m.f of $X^2$, not $X$ itself. It should be simple enough to show that,
$$f_\theta(x) = \left(\frac{2}{3}\right)^{\frac{x(x+1)}{2}}\left(\frac{1}{3}\right)^{\frac{x(x-1)}{2}}p^{x^2}(1-p)^{1-x^2}, \;\; x = -1, 0, 1 $$
Now you can use your Factorization Theorem argument and change $h(x)$ and $g_\theta(T(x))$ accordingly.


Angular js getting error must define $get factory method

Question: I am getting error in firebug.

Error: [$injector:modulerr] Failed to instantiate module autoQuote due to:
  [$injector:pget] Provider 'function prepareDtoFactory()' must define $get factory method.

My code fo angular js controller is as below.
<code>angular
.module("autoQuote")
.controller(dtoController)
.factory(prepareDtoFactory);

function dtoController(prepareDtoFactory){
     prepareDtoFactory.rc1Step1DTO(); //call function from your service, and do something with it
}

dtoController.$inject = ['prepareDtoFactory'];

function prepareDtoFactory(){

    var prepareAutoQuoteDTO = {
        postAutoQuoteObj         : $.getAutoQuoteObject(),
        initializeDriverObj: function(){
            var driverLocObj           = new Driver();
            driverLocObj.PersonInfo    = new PersonInfo();
            driverLocObj.DriverLicense = new DriverLicense();
            driverLocObj.Incident      = new Incident();
            return driverLocObj;
       },
       initializeAppInfo: function(){
           var appInfoLocObj           = new ApplicationInfo();
           appInfoLocObj.Discount      = new Discount();
           return appInfoLocObj;
       },
       /*
       * Initialize Vehicle object for autoQuoteDTO.js
       */
       initializeVehicleObj: function(){
           var vehicleLocObj = new Vehicle();
           return vehicleLocObj;
       },
       /*
       * store session info
       */
       rc1Step1DTO: function(){

            var emailId = $('#save_quote_email').val();
            if (typeof emailId  !== "undefined" && emailId && emailId != '' && emailId != 'Email Address'){
                var email           = new Email();
                email.EmailTypeCd   = 'PRIMARY';
                email.EmailAddress  = emailId;
                this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo =     this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo || new Contact();
                this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails = [];
                this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails.push(email);
            }
        }
    };
    return prepareAutoQuoteDTO;
}
</code>
created plunker with all files
Please help me to fix this error.
http://plnkr.co/edit/VJKrDRMJY3Q73bsCgVwX?p=preview
Comment: But demo doesn't represent error. Doesn't even have the improper controller as noted in answer. Hard to debug something that is working. See [mcve]. Somewhere you have an incorrect injection something like : `app.controller('A', function($scope,prepareDtoFactory()){` ... note the function in the injection argument
Comment: I don't get error opening demo in either chrome or firefox
Comment: I am getting error, when running this in local system.
Comment: prepared code in plunker and want to make it working. When I will submit from  step1 factory method should call. but getting even when included controller file i index.
Comment: No idea what that means or if demo reproduces problem now or not and if it does how to see it
Comment: please download plunker and error can be  reproduced in localhost. let me know ow to ineject factory and call factory method on form submit.
Comment: Have no interest in downloading plunker and setting up on localhost. Can do anything in plunker you can on localhost
Answer: The controller and factory functions with angular take two parameters: the name of the service or controller, and the function. Changing those to .controller('dtoController', dtoController) should help.


SQL Server select XML node by user define attribute value

Question: How to fetch the xml node by its attribute value which is user define
I want to replace 2 in query with @pagenumber_
Declare @pagenumber_ varchar(max);
Set @pagenumber_ = '2';

Select applicationdata.query('(/applicationdata/page[@number="2"])[1]')
From Applications

Comment: https://learn.microsoft.com/en-us/sql/xquery/xquery-extension-functions-sql-variable?view=sql-server-2016
Answer: Try this:
CREATE TABLE #Applications
(
    applicationdata XML
);

INSERT INTO #Applications (applicationdata)
VALUES ('<applicationdata><page number="1">page1</page><page number="2">page2</page></applicationdata>')

DECLARE @pagenumber_ VARCHAR(MAX);
SET @pagenumber_ = '2';

SELECT applicationdata.query('(/applicationdata/page[@number=sql:variable("@pagenumber_")])[1]')
FROM #Applications

DROP TABLE #Applications


Products Display

Question: I am working on converting commerce theme to Drupal Template and have difficulty understand how the Product attribute selection works in the product display.
i have one product display type for multiple products. There is wide variation of products(i.e. runner shoes, tennis shoes,etc). For each product display instance i have selected few of those variations(i.e for Runner shoes i have red runner shoes small , blue runner shoes small, blue runner shoes large, etc). It works nice where user are able to select the attributes and the particular product is displayed.
In the template.php, i load the product display instance:
<code>$node = $vars['node'];
</code>
This instance has reference to the products($node->field_product). So far so good:) The difficulty is to determine which product of these referenced is currently displayed. How can i do that? In what variable is the object or its id is stored? I see in the default html things like:
<code>attributes[field_template_type]
</code>
How is this all thing working? Any help or source of reference much appreciated
Answer: I'm not sure the currently displayed product would be found at the $node level in the template. Typically, when a page is first loaded, it's going to be the product referenced in the field at delta 0. This is alterable, though, so you could invoke the API function, commerce_product_reference_default_product(), in template.php and enrich the $node with that information.
After the page has been initially loaded and displayed, the "currently displayed product" may change based on user input. We store this as the "default product" in the form state variabel $form_state['default_product'] of the Add to Cart form. I assume you'd be able to propagate this from there through to your template somehow, likely through a combination of form alter and preprocess in your template file.

Products Display


Example of ASP.NET/C# using Facebook Connect Toolkit 3.0

Question: Are there any examples of fully functioning code with C# and Facebook Connect with version 3.0 of the toolkit?
NOTE: I am specifically interested in version 3.0 of the toolkit. There are plenty of 2.0 examples out there but the 3.0 toolkit deprecates many of the 2.0 objects which makes these examples useless. I am ONLY interested in examples with 3.0
Answer: Found this one:
http://www.rjygraham.com/archive/2009/11/22/using-facebook-connect-with-aspnet-mvc-and-the-facebook-developer-toolkit-3.aspx
Don't know how good it is yet...
Comment: Thanks for the heads up. Unfortunately I think the author is mistaken with that code. Version 3 of the toolkit does not support the "Api" object. So the code presented in that article wouldn't run. The author clearly claims that it should work with v3 but the code is not much different that then other v2 examples already out there.
Answer: Fortunately, I think v3 supports Api object. Check Facebook.Rest.Api !
Answer: Great example here asp-net-c-facebook-connect-api-example


Linear Systems Word application

Question: Bob leaves Jim's house at 9 am driving at 90 km/hr. At 10 am Jim realises Bob left his wallet and heads out at 110 km per hour. Assuming they take the same route, what time will they meet?
Comment: To solve these kinds of questions it's best to set a few variables (eg. let $s_B$ be Bob's speed) and form equations you can solve. All you need to know is that $\text{Speed}=\frac{\text{Distance}}{\text{time}}$
Comment: @Shuri2060 given distance traveled in that original time ( I know it), it can reduced a couple differences and an add.
Comment: okay a multiply, a subtract, a division, and an add actually.
Answer: Let set $t=0$ (in hour) for the moment Bob leave Jim's house.
Assuming he didn't burn from the instant acceleration from 0 to 90km/h, we have $d_{Bob}$ the distance bob travelled :
$$d_{Bob} = 90\cdot t$$
One hour later, at $t=1$, Jim leaves. So we got :
$$d_{Jim} = 110 \cdot (t-1) $$
Now since it is said that they left at the same point and took the same route, they will meet when $d_{Bob} = d_{Jim}$. Which is to say we have to solve for $t$:
$$90\cdot t = 110 \cdot (t-1)$$
Which gives $$t=5.5\text{ Hours or }t= 5\text{ Hours }30 \text{ Minutes }$$
Comment: to clarify this answer this t is from the time bob left not from when jim left.
Comment: *"Let set $t=0$ (in hour) for the moment Bob leave Jim's house."* I think this is pretty explicit ?
Comment: okay I guess I was just idiot proofing.  as you can do it from the time jim left as well.
Comment: Oh but yes indeed there's a lot of ways to do this, that's why you have specify when $t=0$ is. Sorry if I sounded rude mate.

Linear Systems Word application