Trouble in fitting data to a curve (NLS)

Question: I got a time series dataset from the lab and would like to fit my data to a curve (using R package):
$$
P_{1}(t)=y_{0}-a_{1}e^{-b_{1}t}-a_{2}e^{-b_{2}t}, b_{2}>b_{1}  \tag{A}
$$
I plotted the data:

I think I need to start with good initial values to get a better estimate when fitting to the curve.So I start with a simpler curve:
$$
P_{2}(t)=a_{1}e^{-b_{1}t}  \tag{B}
$$
and I got:
Call:
lm(formula = log(P1_1) ~ time)

Coefficients:

(Intercept)        time
   4.084148        0.002703

That is, $a_{1}=54, b_{1}=0.003$ (roughly).
So I set the starting value $y_{0}=30, a_{1}=20, b_{1}=0.002, b_{1}=30, b_{2}=0.003$ and then did:
nls_fit <- nls(X1r_1_green~-y0+A1*exp(tau1*Time)+A2*exp(tau2*Time),
               start=list(y0=35, A1=20, A2=30, tau1=.02, tau2=.03), data=data1, trace=T)

However, it returns errors that I could not figure out how to fix, such as:

step factor 0.000488281 reduced below 'minFactor' of 0.000976562
  singular gradient matrix at initial parameter estimates

After digging into some posts online, the error might be the poor initial values. After many times attempts at different initial values I've still had no luck, though. Do you have any suggestions?
The data is as follows:
       Time X1r_1_green
1    11.333     14.1060
2    12.443     21.6894
3    13.450     26.5231
4    14.457     33.0356
5    15.463     36.4517
6    16.471     37.6585
7    17.478     44.5417
8    18.485     46.3301
9    19.492     51.2111
10   20.499     51.2094
11   21.505     51.3405
12   22.513     54.6848
13   23.520     55.8172
14   24.527     61.5436
15   25.534     62.5158
16   26.541     62.5279
17   27.547     62.8395
18   28.555     61.9790
19   29.562     65.7806
20   30.569     66.7353
21   31.576     64.3837
22   32.583     64.7834
23   33.589     68.8058
24   34.597     70.6975
25   35.604     73.2809
26   37.597     74.2578
27   38.707     69.5155
28   39.714     75.3023
29   40.721     76.5360
30   41.727     74.0348
31   42.735     76.6561
32   43.742     79.1025
33   44.749     79.2463
34   45.756     79.4334
35   46.763     79.4644
36   47.769     81.9903
37   48.776     78.4627
38   49.784     81.7913
39   50.791     84.2073
40   51.798     82.0027
41   52.805     83.6003
42   53.811     82.0862
43   54.818     80.9991
44   55.826     81.0088
45   56.833     80.6877
46   57.840     84.4431
47   58.847     81.8827
48   59.853     82.3165
49   60.861     84.3172
50   61.868     83.6584
51   63.862     81.0175
52   64.972     83.9112
53   65.979     84.7511
54   66.986     83.3383
55   67.993     85.2289
56   68.999     84.1657
57   70.007     83.5959
58   71.014     86.6437
59   72.021     86.1192
60   73.028     86.5437
61   74.034     89.5566
62   75.041     86.0854
63   76.049     85.1923
64   77.056     86.5120
65   78.063     87.7273
66   79.070     84.8408
67   80.076     87.7706
68   81.083     89.3330
69   82.091     86.4411
70   83.098     88.4944
71   84.105     86.3283
72   85.112     85.8619
73   86.118     85.1758
74   87.125     88.8349
75   88.133     86.4028
76   89.140     85.1487
77   90.147     85.0808
78   91.154     84.1891
79   92.160     79.2782
80   93.167     83.9142
81   94.175     77.9845
82   95.182     76.1993
83   96.189     76.3565
84   97.196     79.3567
85   98.202     78.5809
86   99.210     78.2514
87  100.217     78.5353
88  101.224     82.9957
89  102.231     79.0445
90  103.237     80.5854
91  104.244     80.3490
92  105.252     77.5888
93  106.259     78.3460
94  107.266     80.4607
95  108.273     79.6868
96  109.279     82.5708
97  110.287     81.7843
98  111.294     81.2645
99  112.301     84.0419
100 113.308     83.5896
101 114.315     87.6291
102 115.321     86.3707
103 116.329     84.7563
104 117.336     86.4180
105 118.343     81.4442
106 119.350     83.6793
107 120.357     83.8090
108 121.363     82.8488
109 122.371     86.8810
110 123.378     83.4640
111 124.385     86.9706
112 125.392     86.5779
113 126.398     85.8226
114 127.406     89.9185
115 128.413     88.6702
116 129.420     87.5920
117 130.427     91.5657
118 131.434     90.5003
119 132.440     88.6852
120 133.448     88.8704
121 134.455     94.9899
122 135.462     89.8719
123 136.469     89.0472
124 137.477     85.9579
125 138.483     89.7549
126 139.490     88.1925
127 140.497     90.3598
128 141.504     87.4038
129 142.511     88.8794
130 143.518     89.6318
131 144.525     87.6712
132 145.532     91.8890
133 146.539     87.8800
134 147.546     91.4838
135 148.553     88.9816
136 149.560     87.4804
137 150.567     87.5171
138 151.574     86.1898
139 152.581     85.5146
140 153.588     86.2422
141 154.595     90.9029
142 155.602     88.2005
143 156.609     84.7370
144 157.616     90.0859
145 158.623     83.5787
146 159.630     87.1796
147 160.637     90.1887
148 161.644     82.7800
149 162.651     82.8887
150 163.658     83.5638
151 164.665     82.8934
152 165.672     81.3959
153 166.679     83.2340
154 167.686     80.5834
155 168.693     81.9224
156 169.700     85.8687
157 170.707     82.0637
158 171.714     85.9917
159 172.722     78.8532
160 173.728     83.0037
161 174.735     84.7516
162 175.742     84.4288
163 176.749     90.4443
164 177.757     83.3640
165 178.764     86.1808
166 179.770     84.2887
167 180.777     87.9906
168 181.784     84.4754
169 182.791     85.7398
170 183.798     87.0640
171 184.805     86.6323
172 185.812     83.0898
173 186.819     86.8609
174 187.826     87.7454
175 188.833     86.8763

Comment: Asking for code / help with error messages is off topic here. But are you sure you have the right model? (That isn't off topic here.) Why not just fit a spline?
Comment: @Liz maybe you should specify why you want to fit this model. Do these parameters have any interpretations? Given the plot, this model does not look like a good choice.
Comment: @Gung and Guðmundur Einarsson, thanks for your time. the model is coming from this paper: http://www.ncbi.nlm.nih.gov/pubmed/25540829. My advisor asked me to use the model suggested in that paper. I told my advisor the question I ran into (as described), he told me to keep working on it. However, I tried all I can do but no luck. I heard about nonlinear regression but have never used it before. Starting from zero, and 10 days I only got this far. I'm wondering if I did something due to lack of statistician intuition and training  that I didn't realize it....
Comment: my question is not limited to the error given by R, it is more like is there any approach I can take to fit the data to that model, or is there any suggestion about what step I should take next based on my work. May I know why this model is not a good choice for the given data? Thank you!
Comment: If you post the data I can show you how to solve it.
Comment: @davefournier, I just have the data posted. Thanks in advance.
Answer:
I wish I had a dollar for every hour people have wasted trying to do
nonlinear parameter estimation with R.
Here is the solution to your problem together with the estimated std devs calculated
by the delta method and plot of solution is above.
y0 85.557909  3.0989e-01

a1 125.20943 1.3766e+01

a2 1394.155 4.4952e+03

b1 0.062640298 4.1774e-03

b2 0.43392314 2.9936e-01

I used the same AD Model Builder code as I posted there, but modified slightly for
your problem.  As I stated there this is a general technique for
attacking these sorts of problems.
How to choose initial values for nonlinear least squares fit
This is the AD Model Builder code for your problem.
DATA_SECTION
  init_int n
  int mid
 !! mid=75;
  init_matrix data(1,n,1,3)
  vector t(1,n)
  vector P(1,n)
 !! t=column(data,2);
 !! P=column(data,3);   //use column 3
  number tmax
  number Pmax
 !! tmax=max(t);
 !! Pmax=max(P);
 !! t/=tmax;
 !! P/=Pmax;

PARAMETER_SECTION
  init_number L1(3)     //(3) means estimate in phase 3
  init_number Lmid(3)
  init_number Ln(3)

  vector L(1,3)
  init_number log_b1       // estimate in phase 1
  init_number log_diff    // estimate in phase 2
  sdreport_number b1
  sdreport_number b2
  matrix M(1,3,1,3);
  objective_function_value f
  sdreport_vector v(1,3)
  sdreport_number real_y0
  sdreport_number real_a1
  sdreport_number real_a2
  sdreport_number real_b1
  sdreport_number real_b2
  vector pred(1,n);
PROCEDURE_SECTION
  L(1)=L1;
  L(2)=Lmid;
  L(3)=Ln;
  b1=exp(log_b1);    // this parameterization ensures that b1<b2
  b2=b1+exp(log_diff);
  M(1,1)=exp(-b1*t(1));
  M(1,2)=exp(-b2*t(1));
  M(1,3)=1;
  M(2,1)=exp(-b1*t(mid));
  M(2,2)=exp(-b2*t(mid));
  M(2,3)=1;
  M(3,1)=exp(-b1*t(n));
  M(3,2)=exp(-b2*t(n));
  M(3,3)=1;

  v=solve(M,L);  // solve for standard parameters
                 // v is vector corresponding to the parameters b_1 b_2 P_0

  pred=v(3)-v(1)*exp(-b1*t)-v(2)*exp(-b2*t);
  if (current_phase()<4)
    f+=norm2(P-pred);
  else   // use concentrated likelihood so that Hessian is correct
    f+=0.5*n*log(norm2(P-pred)); //concentrated likelihood

  real_y0=v(3)*Pmax;
  real_a1=v(1)*Pmax;
  real_a2=v(2)*Pmax;
  real_b1=b1/tmax;
  real_b2=b2/tmax;

REPORT_SECTION
  dvar_matrix tmp(1,2,1,n);
  dvar_vector real_t=t*tmax;
  dvar_vector real_pred=real_y0-real_a1*exp(-real_b1*real_t)
    -real_a2*exp(-real_b2*real_t);

  tmp(1)=real_t;
  tmp(2)=real_pred;

  ofstream ofs1("pred");
  ofs1 << trans(tmp)<< endl;

  tmp(2)=P*Pmax;

  ofstream ofs2("obs");
  ofs2 << trans(tmp)<< endl;

  report << "y0 " << setprecision(8) << real_y0 << endl;
  report << "a1 " << setprecision(8) << real_a1 << endl;
  report << "a2 " << setprecision(8) << real_a2 << endl;
  report << "b1 " << setprecision(8) << real_b1 << endl;
  report << "b2 " << setprecision(8) << real_b2 << endl;

Comment: wow!! it's quite something I need to digest a little bit, good to my long weekend. :) Thank you so much! I just googled and learned that AD builder is a software built for nonlinear regression. thanks a million!!
Answer: EDITED TO REMOVE THE ORIGINAL SECOND POINT, WHICH WAS WRONG.
Two comments:

Looking at the data, something strange is happening at about 80 seconds and 140 seconds. If these are experimental artefacts, then it won't make sense to fit a complicated model. If those data show a real trend (not an experimental artefact), then you'll need a sinusoidal model to fit those twists and bends. Fitting the biexponential model assumes all variation is Gaussian, but those trends at 80 and 140 seconds seem too large to just be random variation.
Here are the results from GraphPad Prism, which are very similar to those that Dave got with ADBuilder (Prism file):

a. Look at the confidence intervals for A2 and tau2. They cross into negative values, which are impossible, and are quite wide. Your data really don't define these parameters.
b. The P value from the runs test is tiny. This means that the data systematically deviate from the curve. Whether a point is above or below the curve is not entirely random. This goes along with point 1 above.
c. If you try to extrapolate the curve down to Time=0, the Y values get very negative. Depending on the scientific context, this may suggest the model is not very sensible. Perhaps the model should include a (X - X0) term, where X0 is a constant (maybe 11.33, your first time point)?
Comment: yes I fit transformed data, but then I transformed them back to produce the plots. I carefully did this all in the REPORT_SECTION to make sure I did not mix apples with oranges.  Anyway I'm happy to answer any objections you may have.
Comment: In my original posting, my second point was completely wrong. I had said that the equation with Davr's parameters didn't follow the shape of the data. My mistake. I omitted a minus sign). I've removed that point entirely, and replaced with other comments.
Comment: @Harvey, thanks so much for the comments. By looking at Harvey's comment, especially the confidence interval. Actually I tried to use NLIN procedure in SAS, and it gave me large CI as well, however,  estimates with such huge variation doesn't make sense to me.
Comment: Regarding comment 2c, good point! I've never considered the extrapolate issue. It might be another way to handle it by subtracting the baseline value from each observed value, and then fit the model.
Answer: NB in my discussion, I'll ignore the obvious lack of fit of the model and focus on the issues with getting estimates.
A model like this one can sometimes have a few issues (because of a ridge in the parameter space) but there seems to be no such difficulty here.
I did a one-exponential fit first, as you did. Then the very first two-exponential fit I tried worked.
Here's what I did, in order:
First, I tried plotting curves for a few values for y0, a1 and b1 until I found something that worked okay:
Step 0: find some values for a one-exponential model by trial and error
#Leaving out the values I tried that didn't work as well, I got to here:
 plot(X1r_1_green~Time,data1)
 t=10:189
 f1=90-100*exp(-0.05*t)
 lines(t,f1,col=4)

Step 1: fit a one-exponential model:
fit1exp=nls(X1r_1_green ~ y0-a1*exp(-b1*Time),
                   data=data1,start=c(y0=90,a1=100,b1=.05))
summary(fit1exp)

Formula: X1r_1_green ~ y0 - a1 * exp(-b1 * Time)

Parameters:
    Estimate Std. Error t value Pr(>|t|)
y0 8.542e+01  3.007e-01  284.11   <2e-16 ***
a1 1.447e+02  7.140e+00   20.26   <2e-16 ***
b1 6.804e-02  2.707e-03   25.13   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 3.271 on 172 degrees of freedom

Number of iterations to convergence: 4
Achieved convergence tolerance: 3.197e-06

Step 2: Shrink those a little toward 0, put in rough guesses for the second parameter set (I made them in the ballpark of 15-20% of the first set, but it pays to be imprecise about this):
 fit2exp=nls(X1r_1_green~ y0-a1*exp(-b1*Time)-a2*exp(-b2*Time),
                  data=data1,start=c(y0=80,a1=120,b1=.06,a2=20,b2=.01))

 summary(fit2exp)

Formula: X1r_1_green ~ y0 - a1 * exp(-b1 * Time) - a2 * exp(-b2 * Time)

Parameters:
    Estimate Std. Error t value Pr(>|t|)
y0 8.771e+01  1.205e+01   7.281 1.18e-11 ***
a1 1.509e+02  9.122e+00  16.539  < 2e-16 ***
b1 7.379e-02  7.828e-03   9.427  < 2e-16 ***
a2 5.132e+00  6.504e+00   0.789    0.431
b2 6.429e-03  3.356e-02   0.192    0.848
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 3.261 on 170 degrees of freedom

Number of iterations to convergence: 22
Achieved convergence tolerance: 4.992e-06

I did not expect that second model to work first try; usually you'd have to fiddle about a bit with a model like that one (or even better, use subject area knowledge to build better guesses -- but I don't have any of that).
Plotting that fit on the same plot as the initial fit:

Original by-eye fit of single exponential in blue, final two-exponential nls-fit in red. There's also a single-exponential nls-fit in green, but it's almost entirely overlapped by the red curve -- i.e. the second exponential adds almost nothing to the fit here.)
I spent longer editing your post than I did getting that fit working, and most of that was simply finding the blue curve by eye.
[While this seemed to work just fine, it definitely does pay to try other starting values and see whether you've converged to a local optimum, or perhaps got stuck in a really stretched out ridge and ended up some distance from where you might be. I'd normally try changing the default convergence criteria as well.]
Comment: thanks for helping me. So happy to know that R also works. I was planning to install AD Builder and just had my laptop upgrade to meet the minimum requirement for AD Builder installation last night. I think I could play with this two to finish my task. there are like 30 datasets like the posting one that need to be fitted to the model. Thank you!
Comment: Fortunately there is an objective way to measure the quality of fits to the data.  For your fit the residual sum of squares can be calculated by
Comment: Fortunately there is an objective way to measure the quality of fits to the data.  For your fit the residual sum of squares can be calculated by > sum(resid(fit2exp)^2)
[1] 1807.572
I refitted the data using nls with my solution as the starting values.  fit3exp=nls(X1r_1_green~ y0-a1*exp(-b1*Time)-a2*exp(-b2*Time),
                  data=data1,start=c(y0=85.557909,a1=125.20943,
             b1=0.062640298,a2=1394.1548,b2=0.43392313))                                     > sum(resid(fit3exp)^2)
[1] 1791.52
 So your fit had not really converged.  I would not rely on nls.
Comment: I should also add that I generated my starting values automatically without looking at the data.
Comment: @davefournier, thanks for the comments. the question for how good is a good fit just came to my mind, and I saw your comment. :) In addition, I'm so happy to know ADMB, it is the highlight of this weekend!!
Comment: @Liz Sugar  If you want help with ADMB you should post on the AD Model Builder user's list and I will assist you.
Answer: If you realize that your model is partial linear, the whole task gets very simple. You only need starting values for the non-linear parameters and since these are related to the half-life, it's easy to make a decent guess from a plot:
tau1_ini <- log(2) / 18
tau2_ini <- log(2) / 180

Then you can fit:
fit <- nls(X1r_1_green ~ cbind(1, exp(-tau1 * Time), exp(-tau2 * Time)),
           data = DF, algorithm = "plinear",
           start = list(tau1 = tau1_ini, tau2 = tau2_ini))

summary(fit)

#Formula: X1r_1_green ~ cbind(1, exp(-tau1 * Time), exp(-tau2 * Time))
#
#Parameters:
#        Estimate Std. Error t value Pr(>|t|)
#tau1   7.379e-02  7.828e-03   9.427  < 2e-16 ***
#tau2   6.429e-03  3.356e-02   0.192    0.848
#.lin1  8.771e+01  1.205e+01   7.280 1.18e-11 ***
#.lin2 -1.509e+02  9.122e+00 -16.539  < 2e-16 ***
#.lin3 -5.132e+00  6.505e+00  -0.789    0.431
#---
#Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#
#Residual standard error: 3.261 on 170 degrees of freedom
#
#Number of iterations to convergence: 19
#Achieved convergence tolerance: 6.29e-06

That's the same result as in @Glen_b's answer.
Note that the parameter estimates are strongly correlated. You data doesn't really support such a complex model.
Comment: @davefournier That's a strong statement. Different optimizers can give different results. Also, you could set `control = nls.control(tol = 1e-7)` to reduce the sum of squares slightly to 1807.572, but that has no important impact on the parameter estimates. I would rather say, that the data doesn't really support a 2-pools-model.
Comment: @davefournier and I could write such a routine with R (as you have done with your rather lengthy code). The point is that doing so is a waste of time. One should use a different model.
Comment: However as I demonstrated above this is not the correct answer. nls is just not up to solving this problem reliably.
Comment: The correct sum of squares at the minimum is  1791.52 not 1807.572.
Comment: I don't think you should use the word "correct" here. What you claim might be the global optimum (something to prove). However, looking at the data it would probably be even more "correct" to include variance and autocorrelation structures in the model or even to exclude data after `Time`s of about 90 because something unexpected is going on after that. Unfortunately, the model includes already too many parameters as it is. The size and decay of the second pool can not really be estimated with any good accuracy and a single-pool-model should be used.
Comment: Of course you can not easily prove that a solution is the global minimum. but you can prove that a solution is not the global minimum by exhibiting a better solution. Your solution was not the global minimum. It seems to be a common characteristic of R users that when their software fails to find the correct answer, they blame the data. I agree that the parameters are badly determined for this data set. That is why you need a more robust routine than nls.


How to update taxonomy field in a node?

Question: node_load($nid);
$node->mytaxonomyfield['und'][0]['tid']=$data;
node_save($nid)

my corresponding terms : online,offline,pre-online  and the corresponding tid : 1,2,3
my question : what the program will be that changing the field data by words instead of tid
Answer: You can't (at least not directly). Don't forget that multiple taxonomy terms may have the same name so they need to be identified by their tid or you'd get clashes.
You have a couple of options to load a taxonomy term by name, but for each you'll need to know the vid of the term's vocabulary.
The first option is to use the deprecated $conditions parameter of the taxonomy_term_load_multiple() function:
$terms = taxonomy_term_load_multiple(array(), array('name' => 'online', 'vid' => $vid));
$first_term = array_shift($terms);
$tid = $first_term->tid;

As you can see it's limited to loading just one term at a time.
The second (much better) way is to use an EntityFieldQuery:
$terms = array(
  'online',
  'offline',
  'pre-online'
);

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition('vid', $vid)
  ->propertyCondition('name', $terms, 'IN');

$results = $query->execute();

if (isset($results['taxonomy_term'])) {
  // Get an array of tids
  $tids = array_keys($results['taxonomy_term']);
}

That way you can load multiple terms in one go, and take advantage of non-SQL field storage solutions if you need to.
If you're worried about speed you could also go directly into the taxonomy_term table to get this data; but I don't advise doing this unless you really know what you're doing.
Comment: thx a lot,my problem is fixed!

How to update taxonomy field in a node?


Set default values for a field from a node

Question: In Drupal, when you create a field, you can specify the default value for a field.
For example, if you have a field called price, you can set the default value to be 400.
When the user creates a new node, 400 is the default value, but s/he can change it to whatever s/he wants.
Is there a way to link this default value to a node field value.
For example, lets say on node/12 I have a field called "price default". If the user enters 500 on this field (on node/12), the default value of the price field (for all new nodes) will change from 400 to 500.
Answer: Ahmed was close, but to take it all the way you need to fetch the field's value:
function MODULENAME_form_alter(&$form, $form_state, $form_id) {
  if ($form_id = 'YOUR_FORM_ID_HERE') {
    // Fetch node that has default value
    $node = node_load($nid);
    // Fetch the value from price field
    $node_wrapper = entity_metadata_wrapper('node', $node);
    $field_val = $node_wrapper->field_price->value();
    // Set fetched value as default
    $form['field_price'][LANGUAGE_NONE][0]["value"]['#default_value'] = $field_val;
  }
}

I am itching for a clean way to avoid having ['und'][0] in there,  as these values can change with localisation, but this would still work.
Comment: Use of the LANGUAGE_NONE constant over 'und' is preferred.
Comment: Yes sir. This is indeed best practice. Corrected the answer with your suggestion, thanks friend.
Answer: You can use hook_form_alter to set default value of your field by select the last value of it
function MODULENAME_form_alter(&$form, $form_state, $form_id) {
    $form['account']['status']['#default_value'] = '0';
}

Answer: You actually can. Before setting the price field's default value, do a node_load($nid) (You must know the node's id), it should return the complete node object inclusive of the fields. You can find the value of price_default from that and set the default value of price field accordingly.


Algebraic proof of finiteness of von Dyck groups?

Question: The von Dyck groups are quotients of the free group on two generators defined as $$D(l, m, n) = \langle  x, y | x^l = y^m = (xy)^n = 1\rangle$$ where $l, m, n \geq 2$. These groups are the symmetries of a particular triangulation of a (possibly non-Euclidean) surface with triangles of angles $\pi/l, \pi/m, \pi/n$, and  are finite if and only if $$\frac{1}{l} + \frac{1}{m} + \frac{1}{n} > 1,$$ in which case the surface is a sphere, which obviously has a finite set of symmetries. (The possible values of $(l, m, n)$ are $(2, 2, n)$ where $n \geq 2$ and $(2, 3, n$) where $3 \leq n \leq 5$, plus permutations.)
There was a question yesterday from someone who asked if $D(2, 3, 5)$ was finite and couldn't find a proof working from the group presentation alone. Is there an argument distinguishing the finite from the infinite von Dyck groups that works purely algebraically, rather than appealing to geometric properties of the group action? I suspect that these arguments would be difficult to find because the finite and infinite groups have superficially similar presentations, but I can't shake the feeling that there should be one.
Comment: If I may borrow from the subtitle of Stanley Kubrick's movie [Dr. Strangelove](https://www.imdb.com/title/tt0057012), I can only suggest that one learn to stop worrying and love the Poincare Polygon Theorem.
Comment: In a more serious vein, the geometric methods of proof are important and useful. The geometric tools behind the von Dyck groups and other examples arising from the hyperbolic, euclidean, and spherical geometry have given rise to entire sub-branches of group theory, including [small cancellation theory](https://en.wikipedia.org/wiki/Small_cancellation_theory), Gromov's theory of [hyperbolic groups](https://en.wikipedia.org/wiki/Small_cancellation_theory), and [geometric group theory](https://en.wikipedia.org/wiki/Geometric_group_theory).
Comment: Even [combinatorial group theory](https://en.wikipedia.org/wiki/Combinatorial_group_theory) itself is infected with those geometric ideas.
Comment: The finiteness proof for the dihedral groups is easy, and the other examples ((2,3,3), (2,3,4), (2,3,5)) can be proved finite by hand using coset enumeration,  but the geometric argument is more general and uniform.
Answer: Consider the Coxeter group
$$G=G(\ell,m,n)=\langle u,v,w\mid u^2=v^2=w^2=(uv)^\ell=(uw)^m=(vw)^n=1\rangle.$$
Consider the homomorphism onto $\mathbf{Z}/2\mathbf{Z}$ mapping each generator to $1(\neq 0)$. Just using that $u,v,w$ square to $1$, its kernel $K$ is generated by $uv$, $uw$, $vw$.
Now let's change the presentation changing $(v,w)$ with $(x,y)$, for $x=vu$, $y=uw$ (so $K$ is generated by $(x,y,xy)$. It gives
$$G=\langle u,x,y\mid u^2=(xu)^2=(uy)^2=x^\ell=y^m=(xy)^n=1\rangle,$$
rewritten
$$G=\langle u,x,y\mid u^2=1,\quad x^\ell=y^m=(xy)^n=1,\quad uxu^{-1}=x^{-1},uyu^{-1}=y^{-1}\rangle.$$
We identify the presentation of a semidirect product $\mathbf{Z}/2\mathbf{Z}\ltimes D(\ell,m,n)$. In other words, the index 2 subgroup $K$ of $G$ is isomorphic (through $(x,y)\mapsto (x,y)$) to $D(\ell,m,n)$.
This is not a proof of finiteness, but reduces the finiteness of $D(\ell,m,n)$ to that of the above Coxeter group $G(\ell,m,n)$, and this is (now!(*)) a much more documented result.
(*) I guess von Dyck studied these groups in the 1880s, much before Coxeter groups were introduced.
Comment: This answer would benefit if somebody can suggest some reference of algebraic/combinatorial flavor for the classification of finite Coxeter groups.


accessing image from public_html not possible

Question: I am using Cyberhost.in to host a JSF application. The problem that I am facing is that whenever I am trying to access image files from public_html folder I am getting a 404 error. I have kept my war file in webapps folder. I am using c-panel, the thing is that I want to take backup of files for my website so I have kept them in public_html folder. Initially I was saving the files under webapps/[WAR FILE NAME] but when ever I was trying to overwrite webapps/[WAR FILE NAME] I was getting permission denied error.
Answer: You should upload image files on their location that you have mentioned in your code, otherwise you should change the location in website code of the same.
Also check permissions/ownership of files


Executar programa no linux de uma maneira mais fácil (gerado pelo electron)

Question: fiz o build com esse comando
ng build --prod && electron-packager . gitrun --platform=linux --arch=x64 --icon=assets/icons/logo.png
Para execultar o aquivo tenho que entrar na pasta do projeto abrir o terminal e rodar ./gitrun
tem alguma maneira de facilitar isso para passar o programa para usuarios.
Answer: Conforme a documentação: https://electronjs.org/docs/tutorial/application-distribution
Primeiro deve baixar os binários pré-compilados: https://github.com/electron/electron/releases
Depois copiar a pasta do teu projeto para dentro da pasta ./resources dos pré-compilados
A estrutura em MacOSX deve estar:
electron/Electron.app/Contents/Resources/app/
├── package.json
├── main.js
└── index.html

E Windows ou Linux assim:
electron/resources/app
├── package.json
├── main.js
└── index.html

A pasta ./app é o teu projeto no caso, depois notará na pasta acima em Windows o electron.exe no linux será apenas electron sem extensão, mas é um executável, ambos podem ser renomeados para o nome do teu programa ou como desejar.
No Mac a propria pasta Electron.app é um aplicativo (é assim que funciona no Mac).
Você também pode compactar em ASAR conforme dito em: https://electronjs.org/docs/tutorial/application-distribution#distribuindo-seu-app-como-apenas-um-arquivo
Para empacotar instale globalmente o asar:
npm install -g asar

E depois aponte a pasta do teu projeto no comando trocando <pasta do projeto> pela sua pasta:
asar pack <pasta do projeto> app.asar

Em linux e windows deve colocar dentro do pré-compilado assim:
electron/resources/
└── app.asar

E o processo é o mesmo, em linux execute o arquivo electron no windows execute o electron.exe (mais uma vez ambos podem ser renomeados)
Em Mac deve ser este o caminho:
electron/Electron.app/Contents/Resources/
└── app.asar

Para facilitar existe o https://www.npmjs.com/package/electron-packager

Nota: Não testei, talvez no fim de semana eu teste com calma e faça uma revisão

Para instalar:
npm install electron-packager -g

Então execute o comando conforme o ambiente desejado:
electron-packager <sourcedir> <appname> --platform=<platform> --arch=<arch>

sourcedir é a pasta do projeto, appname é o nome do app desejado, platform a plataforma de destino, no caso platform e arch podem ser omitidos se for usar o parametro --all que irá gerar para todas plataformas disponíveis
Você também pode instalar o electron-packager como devDependencies diretamente no teu projeto e adicionar no package.json no build, algo semelhante a isto
  "scripts": {
    ...
    "build": "electron-packager ."
  },

A resposta esta em edição/melhorias

Controvérsias e opinião pessoal
Um grande problema que muitos devs sofrem é a engenharia reversa, ainda mais quando os apps tem dados sensíveis, tipo chaves privadas para autenticação, o Electron não é nem de longe um ambiente seguro visto deste ponto de vista, sabendo bem o que faz, isolando uma chave por pessoa evitando de criar uma comunicação com seu back-end de forma exposta o Electron não vai ser um problema, mas se não tiver conhecimento de segurança razoável qualquer pessoa com algum conhecimento vai poder extrair o asar (um baita aZar/aSar, desculpem a piada) e analisar o código para ver como explorar brechas.
Quase todos "EXEs da vida" podem sofrer com isto, mas o formato asar é imensamente mais fácil de sofrer com isto.
Existe soluções que considero paliativas ou chame como pequenos reforços como o pacote: https://www.npmjs.com/package/uglify-js (não cheguei a testar), talvez o Electron já possua algo próprio, faz algum tempo que não trabalho com ele (mudei para outra plataforma), mas mesmo isto não é solução é apenas um reforço. Então deve sempre pensar nestes detalhes.
O texto até o momento não é para sugerir soluções mirabolantes, mágicas ou qualquer coisa assim, porque engenharia reversa não é algo que tem solução, o que podemos fazer é dificultar ou criar um ambiente (como chaves) para cada pessoa, fazendo assim o único responsável ser o próprio usuário, mas não vou entrar em detalhes porque isto pode confundir muita gente e realmente precisarei revisar o texto no texto no futuro.

Em edição para o futuro, irei sugerir ferramenta(s) que fazem um pack completo em um arquivo único executável que pode ajudar, mas não é infalível contra engenharia reversa


Reactive's Monad and Applicative instances in Conal Elloit's FRP

Question: Conal Elliott's paper has the following definitions:
Future a = (Time, a)
Stepper :: a -> Event a -> Reactive a
Ev :: Future (Reactive a) -> Event a
never : Event a
instance Monad Reactive

rA :: Reactive String
rA = "IA" `Stepper` (Ev (1, "1A" `Stepper` never))

rB :: Reactive String
rB = "IB" `Stepper` (Ev (1, "1B" `Stepper` never))

rC1 :: Reactive String
rC1 = (++) <$> rA <*> rB
rC1 = "IAIB" `Stepper` (Ev (1, "IA1B" `Stepper` never))

I believe the above is correct.
rC2 :: Reactive String
rC2 = rA >>= (\a -> (a++) <$> rB)

Should rC1 = rC2?
Based on the definition in the paper it appears that "IA1B" and "1AIB" would be included in between "IAIB" and "1A1B" in rC2.
Doesn't that violate a Monad law (<*>) = ap? Shouldn't rC1 = rC2? Or I am misunderstanding something.
Here is the Idris code I am using
Comment: @trpnd `(<*>) = ap` where `ap m1 m2 = m1 >>= (\x1 -> m2 >>= \x2 -> return (x1 x2))`
Comment: Technically, that's more of a convention than a law. Though in the cases where it's violated, it is expected that there is some sense in which the two things are equivalent, even if not identical. See things like [haxl](https://simonmar.github.io/posts/2015-10-20-Fun-With-Haxl-1.html) for instance, where `(<*>)` can run things in parallel but `ap` can't.
Comment: It still seems like we should only get 2 values in `rC2`, since the monad chooses the first arriving future and discards the other. How did you compute `rC2`? Could you show your work? (I don't *necessarily* doubt you, I just need to see more detail and am out on my phone not in a position to do the calculation myself.)
Comment: Which monad law do you think that violates? The monad laws do not tell us anything about the relationship between `>>=` and `<*>`, only about the structure of the monadic operations (just `>>=` and `return`)
Comment: @trpnd, it's actually listed as an Applicative law in the documentation, iirc, but we generally do require conherence between monad and Applicative
Comment: Could you show the monad instance you are consulting to compute `rC2`?  It looks like maybe you are using `Event`'s monad instead of `Reactive`'s
Comment: @luqui see section 7.1.3 on [the paper](http://conal.net/papers/push-pull-frp/push-pull-frp.pdf)
Comment: @luqui I may very well be reading the pseudocode wrong
Comment: @luqui Idris code I used to compute it. https://pastebin.com/3RcS3Hrd
Answer: There's two bugs in this story. The example given by the question actually only exposes the first one, but while working through it I found another more serious bug in the definition of join.
The first bug is minor: it is about handling simultaneous events. Your race function allows you to merge simultaneous events. This is taken advantage of in (<*>), but then in your definition of join, the These case pretends that the left (inner) event happens first. So if you think of implementing (<*>) using join, and the two behaviors have simultaneous events, join will not merge them.
In the case of reactive behaviors, two simultaneous events are undistinguishable from two events that happen very close to each other in time, and in any case, the last one wins, so it should not matter whether the previous one appears in the stream or not. This would break down if you start counting events for example, and from that I would simply conclude that such an operation should not be allowed on behaviors.
I think the = symbol that appears in laws is often taken too syntactically (if you allow me to call it so), whereas there are various situations, such as this, where it's just more flexible to read it semantically. Often they coincide, so it's also hard to really see the point unless you're used to think about it formally.
From that point of view, it would be reasonable to ignore this as "not a bug". It still seems possible to fix the implementation so that the laws do hold syntactically; that would make everyone happy at any rate.

To understand the second bug, you must take another look at the meaning of join :: Reactive (Reactive a) -> Reactive a.
A r :: Reactive (Reactive a) is an evolving behavior. At some time you get behavior x (whose inner variations are not shown), then behavior y, then behavior z... So schematically it looks like a stream of behaviors
xxxxx...
yyyyy...
zzzzz...
...

If we think of behaviors as functions of time r :: Time -> (Time -> a), join samples r at time t, that's another  behavior r t :: Time -> a, which itself gets sampled at time t: (join r) t = r t t. In other words, you take the diagonal behavior:
x
 y
  z

Thus, if we look back to the event-driven definition of Reactive, it is only natural to forget events as soon as a new behavior appears. And indeed, the definition of join as it appears in the paper does that by racing with join <$> urr, which forgets about the inner behavior ur. However that only accounts for one side of the diagonal:
x
yy
zzz

Because Reactive behaviors are streams of events, inner streams of a Reactive (Reactive a) can contain events that occur before the stream's own appearance. Thus, when you get a Future (Reactive a), you also need a way to truncate events from before the Future happens:
actualize :: Future (Reactive a) -> Future (Reactive a)
-- Exercise for the reader

and use that somewhere in join.
Comment: Using actualize gave me the desired behavior
Comment: Feel free to edit my answer to show the correct definition of join.


Can not install Net::SSH2 module Perl

Question: I am getting the following log while trying to install Net::SSH2 module in my debian machine. I don have libssh2-dev installed but still Im getting this error. also it says "Couldn't find your C compiler". Im pretty sure I do have C compiler installed. how do I fix this ?
cpan Net::SSH2
CPAN: Storable loaded ok (v2.20)
Going to read '/root/.cpan/Metadata'
  Database was generated on Wed, 07 Jan 2015 22:53:20 GMT
Running install for module 'Net::SSH2'
CPAN: Data::Dumper loaded ok (v2.124)
'YAML' not installed, falling back to Data::Dumper and Storable to read prefs '/root/.cpan/prefs'
Running make for R/RK/RKITOVER/Net-SSH2-0.53.tar.gz
CPAN: Digest::SHA loaded ok (v5.47)
CPAN: Compress::Zlib loaded ok (v2.02)
Checksum for /root/.cpan/sources/authors/id/R/RK/RKITOVER/Net-SSH2-0.53.tar.gz ok
CPAN: Archive::Tar loaded ok (v1.52)
Net-SSH2-0.53/
Net-SSH2-0.53/.gitignore
Net-SSH2-0.53/BUILDING.WIN32
Net-SSH2-0.53/Changes
Net-SSH2-0.53/example/
Net-SSH2-0.53/fallback/
Net-SSH2-0.53/inc/
Net-SSH2-0.53/lib/
Net-SSH2-0.53/Makefile.PL
Net-SSH2-0.53/MANIFEST
Net-SSH2-0.53/MANIFEST.SKIP
Net-SSH2-0.53/META.yml
Net-SSH2-0.53/MYMETA.json
Net-SSH2-0.53/MYMETA.yml
Net-SSH2-0.53/ppport.h
Net-SSH2-0.53/README
Net-SSH2-0.53/SSH2.xs
Net-SSH2-0.53/t/
Net-SSH2-0.53/TODO
Net-SSH2-0.53/typemap
Net-SSH2-0.53/t/Net-SSH2.t
Net-SSH2-0.53/lib/Net/
Net-SSH2-0.53/lib/Net/SSH2/
Net-SSH2-0.53/lib/Net/SSH2.pm
Net-SSH2-0.53/lib/Net/SSH2/Channel.pm
Net-SSH2-0.53/lib/Net/SSH2/Dir.pm
Net-SSH2-0.53/lib/Net/SSH2/File.pm
Net-SSH2-0.53/lib/Net/SSH2/Listener.pm
Net-SSH2-0.53/lib/Net/SSH2/PublicKey.pm
Net-SSH2-0.53/lib/Net/SSH2/SFTP.pm
Net-SSH2-0.53/inc/Devel/
Net-SSH2-0.53/inc/Module/
Net-SSH2-0.53/inc/Module/Install/
Net-SSH2-0.53/inc/Module/Install.pm
Net-SSH2-0.53/inc/Module/Install/Base.pm
Net-SSH2-0.53/inc/Module/Install/Can.pm
Net-SSH2-0.53/inc/Module/Install/CheckLib.pm
Net-SSH2-0.53/inc/Module/Install/Fetch.pm
Net-SSH2-0.53/inc/Module/Install/Makefile.pm
Net-SSH2-0.53/inc/Module/Install/Metadata.pm
Net-SSH2-0.53/inc/Module/Install/Win32.pm
Net-SSH2-0.53/inc/Module/Install/WriteAll.pm
Net-SSH2-0.53/inc/Devel/CheckLib.pm
Net-SSH2-0.53/fallback/const-c.inc
Net-SSH2-0.53/fallback/const-xs.inc
Net-SSH2-0.53/example/read.pl
CPAN: File::Temp loaded ok (v0.22)

  CPAN.pm: Going to build R/RK/RKITOVER/Net-SSH2-0.53.tar.gz

Subroutine checklibs redefined at inc/Module/Install/CheckLib.pm line 11.
Subroutine assertlibs redefined at inc/Module/Install/CheckLib.pm line 25.
Subroutine _author_side redefined at inc/Module/Install/CheckLib.pm line 39.

The libssh2 library is required by this module.  If you don't have it, you can
download it from http://www.libssh2.org; you may also need OpenSSL, which can
be obtained from http://www.openssl.org , or libgcrypt, which can be obtained
from http://www.gnupg.org .

Debian:   sudo aptitude install libssh2-1-dev
OpenSUSE: sudo zypper in libssh2-1 libssh2-devel

You can pass your libssh2 lib and include dirs (and extra link args) on the
command line. E.g.:

    perl Makefile.PL lib=$HOME/libssh2/lib inc=$HOME/libssh2/include \
        ldargs="-lz"

These can also be set through the LIBSSH2_LIB/LIBSSH2_INCLUDE/LIBSSH2_LDARGS
environment variables.

To build with libgcrypt instead of OpenSSL, pass 'gcrypt' as a parameter to
Makefile.PL, e.g.:

    perl Makefile.PL gcrypt

If you want to build on Windows, see the file BUILDING.WIN32 in the
distribution.

Couldn't find your C compiler
Compilation failed in require at inc/Module/Install/CheckLib.pm line 17.
Warning: No success on command[/usr/bin/perl Makefile.PL INSTALLDIRS=site]
Warning (usually harmless): 'YAML' not installed, will not store persistent state
  RKITOVER/Net-SSH2-0.53.tar.gz
  /usr/bin/perl Makefile.PL INSTALLDIRS=site -- NOT OK
Running make test
  Make had some problems, won't test
Running make install
  Make had some problems, won't install
Could not read '/root/.cpan/build/Net-SSH2-0.53-S94ijz/MYMETA.yml'. Falling back to other methods to determine prerequisites

Comment: Installing through the package manager is typically recommended...
Answer: As you say you are on Debian the easiest way is
aptitude install libnet-ssh2-perl

But if you really really wish to install it from CPAN instead make sure you've got all the development tools and libraries and also the SSH library installed:
aptitude install build-essential libssh2-1-dev

The you can install the module from CPAN - just verified on a minimal Debian installation with the above steps.

Can not install Net::SSH2 module Perl


Can anyone suggest why these two Server 2008 machines won't talk to each other?

Question: I have a Server 2008 R2 x64 installation (we'll call it MARS) that will not communicate with one of my Server 2008 R2 x64 Hyper-V hosts (we'll call it VENUS) or any of its guests.

They're both on the same VLAN and plugged into the same switch.
All other nodes on the network can connect to both MARS and VENUS (+ guests) including other Server 2008 R2 x64 servers and Hyper-V hosts.
The firewalls for all network profiles are disabled on both servers.
I have rebuilt MARS and the problem persists.
VENUS is our only Hyper-V host running on a full installation of Server 2008 R2 Datacenter edition. The other hosts are running 2008 R2 Server Core with the Hyper-V role installed.
VENUS has 4 teamed HP NC382i NICs.

We plan to migrate all guests off VENUS and rebuild it on Server Core. That might resolve the problem, but I was curious if anyone had encountered anything like this before.
Comment: Break out the sniffer and start looking at what's hitting the wire. Wireshark is your friend, and looking at the wire is the surest way to understand what's happening.
Comment: In this case I'd propose netmon 3.4 instead of wireshare..
Comment: I second the Wireshark suggestion. It's the best way to identify a whole range of network hinkyness.
Comment: also are the nic's teamed?
Comment: VENUS has 4 teamed HP NC382i NICs. Can't believe I forgot that bit.
Comment: All 4 NICs in 1 team?
Answer: Since both NICs are on the same switch & VLAN, start looking at Layer 2. What occurs on either ARP tables as the result of a simple "ping" from either direction? Does the corresponding MAC show up on the opposite end's ARP table? If the ARP entries are correct, then move up to Layer 3 by checking for IP level filters as the next stop/step up the OSI model (heading towards the Event Logs as needed).
Comment: It turns out about half of our servers were using a /16 subnet mask, and the other half were using /24. Switched them all to /24 and everything is working.
Comment: MARS shows up in the VENUS arp table when I ping MARS from VENUS, but VENUS doesn't show up in the MARS arp table when I ping VENUS from MARS.
Comment: You might check the behavior of VENUS against other systems to ensure it is not a side-affect of the NIC teaming, as well as verifying heuristics against MARS. If "cross/control" checks show up as one would normally expect between MARS and VENUS, then start by looking for possible MAC filtering from MARS towards the switching environment.
Comment: So it was layer 3, but going through the other systems helped identify the configuration mis-match. Good deal...
Answer: It turns out that even if Windows Firewall defaults block pings, the pinging machine shows up in the recieving machine's ARP table.
My fix, since the network was completely internal was to shut down the Windows firewall on the private network and then be sure the associated NICs point to that external network.
(Earlier posting on virtual networks (virtual switches) at
 IPv6 problem in Hyper-V)
Answer: I've seen this problem with teamed NICs - one dodgy switch port that the team doesn't recognize as failed but is either misconfigured or slightly broken may only affect traffic to\from specific host pairs not all hosts pairs. It can be very confusing.
e.g.:
Server X can talk happily to Server A
Server X can talk happily to Server B
But Server A and Server B can't talk to each other.
I haven't seen this with Hyper-V but I've seen it more than once with VMware ESX - although in that case the problem wasn't consistent across all VM's on the host as it is in your case.


How can one integrate with respect to a function not in the integrand?

Question: I cannot comprehend
$$\int_a^bf(\gamma(t))d|\gamma|(t).$$
Context (brackets mine):

Let $\gamma:[a,b]\to\mathbb C$ be a rectifiable path and for $a\leq t\leq b$, let $|\gamma|(t)$ be $V(\gamma;[a,t])$ (in words, I think this means something like "the total variation of $\gamma$ restricted to $[a,t]$"). That is,
  $$
|\gamma|(t)=\sup\left\{\left.\sum_{k=1}^n|\gamma(t_k)-\gamma(t_{k-1})|\ \right| \{t_0, \dots, t_n\} \text{ is a partition of } [a, t]\right\}.
$$
  Clearly $|\gamma|(t)$ is increasing and so $|\gamma|:[a,b]\to\mathbb R$ is of bounded variation. If $f$ is continuous on $\{\gamma\}$ (the trace of $\gamma$) define
  $$
\int_{\gamma}f|dz|=\int_a^bf(\gamma(t))d|\gamma|(t).
$$
  Conway, JB. 1978. Functions of one complex variable I. (2nd ed.). New York: Springer. p. 64.

Which leads to my question, about the last integral expression. We are integrating with respect to $|\gamma|(t)$, a function, but I do not understand how one is to do that when the function $|\gamma|(t)$ does not feature in the integrand $f(\gamma(t))$. Basically, it went over my head.
Comment: Looks like a [Riemann-Stieltjes integral](https://en.wikipedia.org/wiki/Riemann%E2%80%93Stieltjes_integral) to me.
Answer: You can think of it like this: fix $t$ then calculate $y = \gamma(t)$ and $x = |\gamma|(t)$. Since $x$ is monotonic you can find its inverse, so if you are given $x$ you can calculate $t$ and then $y$. Say in another words given $x$ you can always find $y(x)$. The integral is then
$$
\int dx\;f(y(x))
$$
which I guess will make more sense to you


Find MGF for $f(x) = \frac{\theta^x e^{-\theta}}{x!}, x=0,1,2,3,.. $

Question: Given the following probability distribution $$f(x) = \frac{\theta^x e^{-\theta}}{x!}, x=0,1,2,3,.. $$
Find the moment generating function, MGF, then find mean of random variable $Y=(X+1)^3$
To my knowledge $$M_x(t) = \sum{e^{tx}f(x)}$$
$$\sum{\frac{\theta^x e^{tx-\theta}}{x!}}, x=0,1,2,..$$
How to solve this summation ? then I am supposed to get MGF for $Y$, but I don't know what to do with power ?
Comment: Hint: $\sum_{k=0}^\infty\frac{z^k}{k!} = e^z$ and try $z = \theta e^t$.
Answer: $$M_X(t) = \mathbb{E}[e^{tX}] = \sum_{x=0}^{+\infty} e^{tx} \frac{\theta^x e^{-\theta}}{x!} = e^{-\theta}\sum_{x=0}^{+\infty}  \frac{\theta^x e^{tx}}{x!} =  e^{-\theta}\sum_{x=0}^{+\infty}  \frac{(\theta e^{t})^x}{x!}.$$
As suggested by @Imaosome:
$$\sum_{k=0}^\infty\frac{a^k}{k!} = e^a.$$
Hence:
$$M_X(t) = e^{-\theta}e^{\theta e^{t}} = e^{\theta(e^t - 1)}.$$

For the mean of $Y = (X+1)^3$....
$$\mathbb{E}[Y] = \mathbb{E}[(X+1)^3] = \mathbb{E}[X^3 + 3X^2 + 3X + 1] = \mathbb{E}[X^3] + 3\mathbb{E}[X^2] + 3\mathbb{E}[X] + \mathbb{E}[1] = \\
= \left(\frac{d^3}{dt^3}M_X(t)\right)_{t=0} + 3\left(\frac{d^2}{dt^2}M_X(t)\right)_{t=0} + 3\left(\frac{d}{dt}M_X(t)\right)_{t=0} + 1 = ...\\$$


Trying to pass icon into the menu

Question: I am trying to use the icon API to pass an icon to the menu - I would use the icon menu module, but I want the icon to switch based on programmatic logic.
Here's what I have so far:
/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  global $user;
  $icon = theme('icon', array('bundle' => "fontawesome", 'icon' => "envelope"));
  $items = array();
  $items['user/' . $user->uid . '/messages'] = array(
    'access callback' => 'user_is_logged_in',
    'title callback' => FALSE,
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
    'title' => $icon . t('Messages'),
    'page callback' => 'views_embed_view',
    'page arguments' => array('message_private', 'page_1'),
    'file path' => drupal_get_path('module', 'views'),
    'file' => 'views.module',
        'options' => array('attributes' => array(
       'html' => true
       )),
  );
  return $items;
}

However this just seems to get the escaped icon HTML in the menu.
How do I get the actual item from the icon API?
Is there some way to tell hook_menu to pass everything as it is?
Answer: by hook_menu you are just registering a path to Drupal.

Define menu items and page callbacks.

To get this printed with icon you can try contributed modules like

Menu Icons
Icon API

Icon API module is able to apply your programmatic logic

Trying to pass icon into the menu


Criar tabela verdade em C#

Question: Possuo uma função de testes que deve receber diferentes combinações de entrada, para definir estes padrões irei utilizar uma tabela verdade.
Porém, estou com dificuldades em gerar a tabela verdade, fiz um protótipo inicial, que funciona bem com até 11 entradas, a partir disso fica muito lento.
Fiz da seguinte forma:
Utilizando o objeto Random gero números binários para cada uma das entradas. Por exemplo: se o programa tiver 5 entradas, gero 5 números aleatórios (entre 0 e 1).
Estes números são unidos numa string para formar a combinação e então jogados numa lista (caso seja único ou já não tenha sido descoberto anteriormente). A partir do número de entradas, consigo saber o número total de combinações a serem geradas, então ao completar o total, o programa se encerra.
Porém, por ficar tentando descobrir cada combinação de forma aleatória, ao ser necessário uma tabela verdade com 20 entradas, por exemplo, (o que geraria mais de 1 milhão de combinações), o programa se torna extremamente lento para finalizar a tarefa. Pois ao final, se repetem muitas combinações que já foram criadas e a descoberta de novas combinações se torna extremamente difícil. Há outra forma mais eficiente de resolver este problema?
public void GerarTabela(int entradas)
    {
        double TotalDeLinhas = Math.Pow(2,Convert.ToDouble(entradas)); // Calcula o total de linhas a serem geradas;
        int[] linha = new int[entradas]; // Cada elemento da linha é jogado em uma posição do vetor
        int LinhasGeradas = 0;
        string LinhaString = ""; // Do vetor, os elementos são unidos nesta String
        List<string> linhas = new List<string>();
        Random randNum = new Random();

        while (LinhasGeradas < TotalDeLinhas) //Permanece no loop enquanto não completar todas as combinações.
        {
            for (int i=0; i < Entradas; i++) // Gera uma combinação
            {
                   linha[i] = new int();
                   linha[i] = randNum.Next(0, 2); //Gera um num. aleatório entre 0 e 1;
            }

            for (int i=0; i < Entradas; i++) //Transforma o vetor de combinações em uma única string. (Ex: 0 - 1 - 0 - 1)
            {
                if (i == Entradas - 1) // Se for o ultimo número da combinação, não irá ter traço após ele.
                {
                    LinhaString += linha[i];
                } else
                {
                    LinhaString += linha[i] + " - ";
                }
            }

            if (!linhas.Contains(LinhaString)) // Se não tiver esta combinação na lista, adiciona ela.
            {
                linhas.Add(LinhaString);
                LinhasGeradas++;
            }
            LinhaString = "";
        }
        MessageBox.Show("Tabela verdade gerada com sucesso!","Concluído!");
    }
}

Comment: Pode colocar o código C# na sua pergunta, por favor?
Comment: Esse caminho aleatório está muito esquisito. Tem alguma motivação para usá-lo?
Comment: Conforme solicitado, incluí o código aqui.
Comment: Foi uma gambiarra, pois meu conhecimento lógico é limitado, mas já removi.
Answer: Voce pode fazer o seguinte:
As combinações da tabela verdade podem ser interpretadas como um numero binário em que cada algarismo é uma variável.
Exemplo:
A | B
0   0 >> 0 binario
0   1 >> 1 binario
1   0 >> 2 binario
1   1 >> 3 binario

Assim.. voce pode gerar a sequencia de números binários e atribuir cada algarismo a cada variável que voce possui.
Para garantir que o numero tenha 5 algarismos, voce pode converter o numero para String utilizando o metodo String.PadLeft(quantidade_variaveis,"0")
E apos ter o numero binario como String.. voce atribui cada algarismo dele para cada variavel sua, assim terá todas as combinações da tabela verdade.
Exemplo de código:
For i As Integer = 0 to (quantidade_variaveis - 1)
  string binario = Convert.ToString(i, 2)
  binario = binario.PadLeft(quantidade_variaveis,"0")
  char[] arr = binario.toCharArray(0, binario.length)
  //variavel 1 = arr[0]
  //variavel 2 = arr[1]
  ...

End For

Comment: Isso resolveu a gambiarra que eu havia criado, pois agora não uso mais o Random. Porém, a velocidade para criar as tabelas maiores, por incrível que pareça, é semelhante.

Criar tabela verdade em C#


CK Editor styles not working

Question: I am using CK Editor 4.5 as text editor in my form.
I have pasted my html code including "style" tags to the editor. But when saving the data it automatically removes the style tags from the code.
I have tried to turn off Automatic Content Filtering by add this to config file
config.allowedContent = true;

But it still remove the style tags. The editor also removes the text color, text align styles added.
How can i add style tags using CK Editor.?
Answer: My apologies. Its not the issue of ckeditor.
I am using codeigniter for server scripts. It removes inline style on form submit.
Answer: I'm using Rails and met the same issue, it turns out that I'm using sanitize to render content, which will remove the inline styles.

CK Editor styles not working


My __str__ is too long, best way to write it

Question: I've this __str__  method in one of my classes but in my opinion it looks a bit too long in my code for python conventions and autopep is not giving me any hints.
So I was wondering what would be the most pythonic way to type it.
I need the break lines because solution and table shapes are 52 and 52x52 respectively.
def __str__(self):
    return "Cost solution : " + str(self.cost) + "\nSolution: " + str(self.solution) + "\n\nTable:" + str(self.table)

Comment: "Most pythonic" is certainly subjective, but since you have multiple lines, I'd probably go with some sort of `return "\n".join([])`
Comment: python 3.6 allows f-strings. short & easy to read
Comment: @jewards Should've asked it better at the end I just want a solution that's under PEP8's limit per line.
Thanks for your answer.
Answer: def __str__(self):
    pattern = '''
    Cost solution: {}
    Solution: {}
    Table: {}
    '''
    return pattern.format(self.cost, self.solution, self.table)

If you don't want extra tabs in output while using multiline strings you need to remove tabs in your code in them.
class Test(object):
    pattern = '''
Cost solution: {}
Solution: {}
Table: {}
'''
    def __init__(self):
        self.cost = 0;
        self.solution = 'StackOverflow'
        self.table = '1|2|3|4'

    def __str__(self):
        return self.pattern.format(self.cost, self.solution, self.table)

print Test()

Comment: btw I think the OP wants a blank line before `Table:`.
Comment: @quamrana I think he can figurate this out
Comment: This one looks really nice, but sadly it's taking the tabs before the text giving a weird [display](https://i.imgur.com/djZiAOz.png). nevermind you noticed first.
Answer: Python 3.6 introduced f-strings, which allow for short strings & format
class foo:
  def __init__(self):
    self.cost = 12
    self.solution = "easy"
    self.table = "no"
  def __str__(self):
    return f"Cost: {self.cost}\nSolution: {self.solution}\nTable: {self.table}"

f = foo()
print(str(f))

Comment: I like the readability, better than messing up with the indentation in my opinion thanks!.
Comment: as long as you don't run this code on less than python 3.6 you'll be fine :) and performance is also better (less parameter/variable lookups)
Answer: You can use the str.format method to combine strings in a more pythonic way, but it is still quite long.
def __str__(self):
    return "Cost solution: {}\nSolution: {}\n\nTable {}".format(self.cost, self.solution, self.table)

You can split it over two lines after the end of the format string if you need to by using the backward slash.


Error while running TensorFlow wide_n_deep Tutorial

Question: I encountered the error:

AttributeError: 'NoneType' object has no attribute 'bucketize'

The full error is as follows:
Traceback (most recent call last):
  File "wide_n_deep_tutorial_1.py", line 214, in <module>
    train_and_eval()
  File "wide_n_deep_tutorial_1.py", line 203, in train_and_eval
    m.fit(input_fn=lambda: input_fn(df_train), steps=FLAGS.train_steps)
  File "C:\Python35\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\dnn_linear_combined.py", line 711, in fit
    max_steps=max_steps)
  File "C:\Python35\lib\site-packages\tensorflow\python\util\deprecation.py", line 191, in new_func
    return func(*args, **kwargs)
  File "C:\Python35\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\estimator.py", line 355, in fit
    max_steps=max_steps)
  File "C:\Python35\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\estimator.py", line 699, in _train_model
    train_ops = self._get_train_ops(features, labels)
  File "C:\Python35\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\estimator.py", line 1052, in _get_train_ops
    return self._call_model_fn(features, labels, model_fn_lib.ModeKeys.TRAIN)
  File "C:\Python35\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\estimator.py", line 1019, in _call_model_fn
    params=self.params)
  File "C:\Python35\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\dnn_linear_combined.py", line 504, in _dnn_linear_combined_model_fn
    scope=scope)
  File "C:\Python35\lib\site-packages\tensorflow\contrib\layers\python\layers\feature_column_ops.py", line 526, in weighted_sum_from_feature_columns
    transformed_tensor = transformer.transform(column)
  File "C:\Python35\lib\site-packages\tensorflow\contrib\layers\python\layers\feature_column_ops.py", line 869, in transform
    feature_column.insert_transformed_feature(self._columns_to_tensors)
  File "C:\Python35\lib\site-packages\tensorflow\contrib\layers\python\layers\feature_column.py", line 1489, in insert_transformed_feature
    name="bucketize")
  File "C:\Python35\lib\site-packages\tensorflow\contrib\layers\python\ops\bucketization_op.py", line 48, in bucketize
    return _bucketization_op.bucketize(input_tensor, boundaries, name=name)
AttributeError: 'NoneType' object has no attribute 'bucketize'

Answer: I got the same issue, it seems that on windows, we just got None, sourcecode,
try to run this code on linux, or try to remove the bucketization and the column crossing, for example. change the line:
flags.DEFINE_string("model_type","wide_n_deep","valid model types:{'wide','deep', 'wide_n_deep'")

to
flags.DEFINE_string("model_type","deep","valid model types:{'wide','deep', 'wide_n_deep'")

follow this issue for update: issue


Why is LSTM so ineffective at this ridiculously simple sequence?

Question: I am trying to predict the the sequence  $(0.1, 0.05, …, 1.1)$ from the sequence $(0, 0.05, 0.1, …, 1)$. I thought this would be the only item in a toy dataset.
Now I implemented a long-short term memory LSTM model in PyTorch and I can't figure out why it trains so badly.
With learning rate $10^{-3}$ and $10^3$ iterations on this single data point it fails to converge effectively. Results are bad.
With learning rate $10^{-4}$ and $10^4$ loss decreases more, and results are slightly better
Here is the code:
import torch import numpy as np

lstm = torch.nn.LSTM(input_size=1, hidden_size=100, num_layers=1, batch_first=True).to(torch.double)
linear = torch.nn.Linear(100,1).to(torch.double)
criterion = torch.nn.MSELoss()
params = list(lstm.parameters()) + list(linear.parameters())
optimizer = torch.optim.Adam(params, 1e-3)

L = 21

x = torch.tensor(np.arange(L)/20, dtype=torch.double).unsqueeze(0).unsqueeze(2)
y = torch.tensor(np.arange(2,L+2)/20,  dtype=torch.double)

for j in range(1000):
    hidden = (torch.zeros((1,1,100), dtype=torch.double), torch.zeros((1,1,100), dtype=torch.double))
    x = x
    y = y
    output, hidden = lstm(x, hidden)
    loss = 0.0
    for i in range(L):
        o = linear(output[:,i,:].squeeze())
        loss += criterion(o, y.squeeze()[i])
    print(loss)
    loss.backward()
    optimizer.step()

out_seq = torch.empty((L)) for i in range(L):
    o = linear(output[:,i,:].squeeze())
    out_seq[i] = o
     print("output (expected): ", y) print("output:", out_seq)

It seems unreasonable to me that it requires to spend so much time on a single data sequence to figure out it has just to add 0.1 to each element. So I'd appreciate any insight on how to improve that.
Comment: I think the target sequence is supposed to be $(0.1,0.15,…,1.1)$ instead of $(0.1,0.05,…,1.1)$.
Comment: it doesn't even look like a sequential problem. How does knowledge about previous element in the sequence will effect prediction for the next element? Each element of the sequence can be trained independently from one another
Answer: You have bug in the code. It looks like torch accumulates gradients and before making backpropagation you need to clean them (set to zero)
optimizer.zero_grad()  # add this line
loss.backward()
optimizer.step()

I added this fix in your code and I get progress during the training. I got loss equal to 0.0005 after 1000 iterations with step 1e-3.
Check this answer from the stackoverflow. You can also check this RNN tutorial on github
Answer: In principle, the network should learn to entirely by-pass the LSTM cell(s), ie., close their output gate(s) forever. Adding 0.1 to the input needs only a bias weight (that is, a constant) added to the input. So, you don't even need a hidden layer at all. Some of the earlier LSTM work improved results dramatically by choosing the "right" bias weights for the LSTM gates. After all, you have a large network with many degrees-of-freedom and only few data points, so it may be tricky for the network to converge to that solution from your starting values.


IIS6 wont compress js and css

Question: So recently I configured IIS6 to compress files I now have most files compressing apart from my JavaScript and CSS files. Does anyone have an idea what maybe causing them not to be compressed.
I know this due to Yslow Add-on and the compression directory I have set(see below) is empty
Service Tab Settings:

Compress application files: checked
Compress static files: checked
Temporary directory: %windir%\IIS Temporary Compressed Files
Max temporary directory size: unlimited

Metabase.xml Snippet:
<code><IIsCompressionScheme   Location ="/LM/W3SVC/Filters/Compression/deflate"
        HcCompressionDll="%windir%\system32\inetsrv\gzip.dll"
        HcCreateFlags="0"
        HcDoDynamicCompression="TRUE"
        HcDoOnDemandCompression="TRUE"
        HcDoStaticCompression="TRUE"
        HcDynamicCompressionLevel="5"
        HcFileExtensions="htm
            html
            txt
            ppt
            xls
            xml
            pdf
            xslt
            doc
            xsl
            htc
            js
            css"
        HcOnDemandCompLevel="10"
        HcPriority="1"
        HcScriptFileExtensions="asp
            dll
            exe
            aspx
            asmx
            axd"
    >
</IIsCompressionScheme>
<IIsCompressionScheme   Location ="/LM/W3SVC/Filters/Compression/gzip"
        HcCompressionDll="%windir%\system32\inetsrv\gzip.dll"
        HcCreateFlags="1"
        HcDoDynamicCompression="TRUE"
        HcDoOnDemandCompression="TRUE"
        HcDoStaticCompression="TRUE"
        HcDynamicCompressionLevel="5"
        HcFileExtensions="htm
            html
            txt
            ppt
            xls
            xml
            pdf
            xslt
            doc
            xsl
            htc
            js
            css"
        HcOnDemandCompLevel="10"
        HcPriority="1"
        HcScriptFileExtensions="asp
            dll
            exe
            aspx
            asmx
            ashx
            axd"
    >
</IIsCompressionScheme>
</code>
I have also given IUSR_{machinename} write permissions to "%windir%\IIS Temporary Compressed Files"
What I'm I missing?
Thanks for any help
Answer: Removed the js and css extensions from HcFileExtensions and added them to HcScriptFileExtensions
restarted IIS and its all working
Answer: Follow all the steps in this tutorial and you should be good:
http://engineering.leads360.com/post/9301650692/http-compression-gzip-on-iis-6

IIS6 wont compress js and css


Making a carousel (image slider) moved over on a webpage

Question: This is the code to my carousel (image slider). I would like to know how to reposition the whole slider on my webpage. I basically want to move it a bit to the left as a whole. The website if link to this slider is http://www.menucool.com/javascript-image-slider and i also made a jsfiddle here http://jsfiddle.net/lasquish/cynar4ug/. Website code fiddle http://jsfiddle.net/lasquish/Low0emf1/
-Thanks for the help!

        Click me: To start selling and trading!.

Answer: your fiddle isn't loading for me, but based in this code it would be like this:
#sliderFrame {
    position: relative;
    width: 960px;
    margin: 0px auto;
    left: -30px;
}

where -30px is the amount of pixels to the left you want to move the slider. An even better option would be to add the slider inside a container like

        Click me: To start selling and trading!.

Now in your CSS, you add this:
.slide_contain {
    position:relative;
    width:960px;
    height:auto;
    min-height:300px
}
#sliderFrame {
    position: absolute;
    width: 960px;
    margin: 0px auto;
    left: -30px;
}

This method will allow you to have better control and avoid problems when moving the sliderFrame div
Comment: This worked great. But the carousel is now static. I would like to make it stay positioned in the place it is but move as i make the webpage width smaller or bigger. Almost like it is centered but it is centered while being moved over.
Comment: do you mean responsive?
Comment: Yes that is what i mean.
Comment: well, for this you'll need to get a responsive slider, which this  one isn't
Comment: Can you send me a link to a responsive slider? Also without active x control.
Comment: http://designscrazed.net/free-responsive-jquery-image-sliders/ . There you have 26 sliders, you'll have to decide which one works best for you and your needs


TypeError: argument should be string, bytes or integer, not PosixPath

Question: My code works perfectly on my Raspberry Pi 4 system (Raspbian) but throws this strange error in a Petalinux system even though I'm using a string. The path exists and I'm logged in as root.
Code
import os
from pathlib import Path
...
@app.route("/api/stopRecording")
def stopRecording():
    recording_end_datetime = datetime.today().strftime('%m-%d-%Y-%H-%M-%S.mp4')
    recordings_folder = '/home/pi/Documents/Recordings/'
    f = open("run.pid", "r")
    pidnum = int(f.readline())
    os.system('kill -15 ' + str(pidnum))
    video_filename = str((sorted(Path('/home/pi/Documents/Recordings').iterdir(), key=os.path.getctime))[-1])
    if "---.mp4" in video_filename: # No stop timing has been set
        os.system('mv "' + video_filename + '" "' + video_filename[:-4] + ' ' + recording_end_datetime + '"')
    else: # Stop timing was set
        os.system('mv "' + video_filename + '" "' + video_filename[:-24] + ' ' + recording_end_datetime + '"')
    return jsonify({'response': 'recording off'})

@app.route("/api/loadRecordings")
def loadRecordings():
    paths = sorted(Path('/home/pi/Documents/Recordings').iterdir(), key=os.path.getctime)
    spaths = []
    for p in paths:
        spaths.append(str(p).replace('/home/pi/Documents/Recordings/','').replace('.mp4',''))
    return jsonify(listToDict(spaths))

Error
[2020-06-03 21:01:55,591] ERROR in app: Exception on /api/loadRecordings [GET]
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.5/dist-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "Backend/filetest.py", line 94, in loadRecordings
    paths = sorted(Path('/root/web_gui/Recordings').iterdir(), key=os.path.getctime)
  File "/usr/lib/python3.5/genericpath.py", line 65, in getctime
    return os.stat(filename).st_ctime
TypeError: argument should be string, bytes or integer, not PosixPath

PS: I already tried with '//root//web_gui//Recordings' but got the same error
Answer: Solved by updating Python to 3.6+ !
It appears that os.path.getctime function is a bit different in version 3.5
Answer: Quick Summary
This might be a problem with other code in your file. I've copied your code and it seems to work for me. (I've replaced some pathing with ...)
>>> str((sorted(Path('/Users/.../Desktop').iterdir(), key=os.path.getctime))[-1])
'/Users/.../Desktop/Programming'

What next?

Try adding more of your code to this question. I think you've correctly identified that this is a platform-specific issue.

Works fine on online Linux
>>> str((sorted(Path('/home').iterdir(), key=os.path.getctime))[-1])
'/home/user'

Comment: Thank you for your response. I included the full function now, but I don't think there's an error elsewhere.
Comment: @AlaaTriki thanks for adding more of the code. According to the error message, the issue is with `/api/loadRecordings`. Could you please show that too? I'm having trouble recreating the error. Thanks.
Comment: My apologies @Thomas, I have included the loadRecordings function now too


Knowing the particular solution $y_1 = \frac{\sin(x)}{x}$ solve: $y'' + \frac{2}{x}y' + y = 0$

Question: Knowing the particular solution $y_1 = \frac{\sin(x)}{x}$ solve: $$y'' + \frac{2}{x}y' + y = 0$$
I set the substitution $y = vy_1 = v\frac{\sin(x)}{x}$. I get the following:
$$y' = v' \frac{\sin(x)}{x} +v\frac{x\cos(x) - \sin(x)}{x^2}$$
$$y'' = v''\frac{\sin(x)}{x} + 2v'\frac{\cos(x)}{x}-2v'\frac{\sin(x)}{x^2}-2v\frac{\cos(x)}{x^2}-v\frac{\sin(x)}{x}-v\frac{2\sin(x)}{x^3}$$
Which results in:
$$v'' + v'(2\cot(x)) = \frac{4}{x^2}$$
Now, this linear differential is not very clean, and I am not sure if there is an error somewhere, or if this approach is invalid.
Answer: $$y'' + \frac{2}{x}y' + y = 0$$
The DE is simply:
$$(xy)''+xy=0$$
$$\implies r^2+1=0 \implies r=\pm i$$
$$xy=c_1\cos x +c_2\sin x$$
$$y(x)=\dfrac 1 x (c_1\cos x +c_2\sin x)$$

You made a little mistake you should get:
$$(xy)''+xy=0$$
$$(v\sin x)''+v \sin x=0$$
$$v'' \sin x +2v' \cos  x=0$$
$$v''+2 v'\cot x=0$$


Hausdorff Spaces Subsets open?

Question: 'Given a Hausdorff space $X$ with finitely many elements, show all subsets of $X$ are open in $X$.'
I let $U$ be an arbitrary subset of $X$
Since every subset of a Hausdorff space is a Hausdorff space, then $U$ is also Hausdorff.
This means that any two points in $U$ $x \ne y$ have disjoint neighbourhoods.
Does this imply every point of $U$ has a neighbourhood lying in $U$ hence prove open? This seems trivial. Where does finitely many elements come into it?
Answer: Let $X=\{x_1,...,x_n\}$. Given $x_i$, for $j\ne i$ let $U_{i,j}$ be an open neighborhood of $x_i$ that doesn't contain $x_j$. Then $U_i = \bigcap_{j\text{:  } j\ne i}U_{i,j}$ is a finite intersection open neighborhood of $x_i$ that contains no other $x_j$, so it's open. But $U_i = \{x_i\}$.
So all singletons $\{x_i\}$ are open. Every subset of $X$ is a union of singletons, so every subset is open.
Comment: That's great, thanks!
Comment: @jimbobeanz You're welcome. We all appreciate tips, ya know ;/
Answer: In a finite Hausdorff $X=\{x_1, \ldots, x_n\}$ space you can show that every singleton $\{x_i\}$ is open. Hence every subset is open since it is union of open sets.
To see that $\{x_i\}$ is open, we know that for every $j\neq i$, we have disjoint neighborhoods $U_j, V_j$ of $x_i, x_j$ respectively.
Take $$U = \bigcap_{j\neq i} U_j$$
Then $U = \{x_i\}$, which is open since it is finite intersection of open sets.
Comment: But if there are infinitely many elements of $X$, an infinite union of open sets is still open?
Comment: Right, but the fact that $X$ is finite plays a key role to show that the singletons are open.
Comment: Ohh okay, thank you :)
Answer: We only need that singletons are closed (because then all finite sets are closed, and so all sets are open)...
Comment: But singletons are closed in $\Bbb R$ and yet the usual topology isn't discrete. Of course that works in this case, because $X$ is finite. Just that it might be confusing to OP..
Comment: @BrianO Yes, finiteness was used: complements of sets are all finite as well...
Comment: Sure, I realized that. I wasn't saying your proof had any problems.
Answer: Just for interest, here is a simpler solution to the question I asked.
We want to prove any subset $U$ in a Hausdorff space with finitely many elements is open.
If $X$ is Hausdorff, then by definition every finite subset of $X$ is closed. Take $X-U$. Since $X$ has finitely many elements, then so does $X-U$, which implies $X-U$ is closed. Therefore $U$ is open.
Answer: Let $X$ be a finite topological space with a hausdorff topology. Observe that the topology must be discrete, and consequently, every subset is both, open and closed.

Hausdorff Spaces Subsets open?


Regular expression to match a string starting with some characters and following with some symblos

Question: I would like to match a string which starts with character sequence 49. The string i get to evaluate will be like 49/1.0  or 49/2.0 etc. If I use ^49 it is not matching with the string i receive (ie: 49/1.0). My expression matches with the string if I receive 49XX only. I do not sure what are the symbols will follow the  49 character.
How can i define regular expression for this?
Comment: Did you try `^49.*` ?
Comment: Try with this `^49.*`
Comment: @Ratha `^` asserts that we are at the start. `49` matches the string `49` plus `.*` zero or more characters.
Comment: Which language are you using?
Comment: @shree.pat18 It is javabased server.
Comment: @AvinashRaj Thanks Avinash for the detailed explanation.
Answer: Try this: ^49.* this regex.
explain
^  # start of the string;
49  # match first 49
.*  # match any char in zero to multiple time..


What is the difference between an Embedding Layer with a bias immediately afterwards and a Linear Layer in PyTorch

Question: I am reading the "Deep Learning for Coders with fastai & PyTorch" book. I'm still a bit confused as to what the Embedding module does. It seems like a short and simple network, except I can't seem to wrap my head around what Embedding does differently than Linear without a bias. I know it does some faster computational version of a dot product where one of the matrices is a one-hot encoded matrix and the other is the embedding matrix. It does this to in effect select a piece of data? Please point out where I am wrong. Here is one of the simple networks shown in the book.
class DotProduct(Module):
    def __init__(self, n_users, n_movies, n_factors):
        self.user_factors = Embedding(n_users, n_factors)
        self.movie_factors = Embedding(n_movies, n_factors)

    def forward(self, x):
        users = self.user_factors(x[:,0])
        movies = self.movie_factors(x[:,1])
        return (users * movies).sum(dim=1)

Answer: Embedding

[...] what Embedding does differently than Linear without a bias.

Essentially everything. torch.nn.Embedding is a lookup table; it works the same as torch.Tensor but with a few twists (like possibility to use sparse embedding or default value at specified index).
For example:
import torch

embedding = torch.nn.Embedding(3, 4)

print(embedding.weight)

print(embedding(torch.tensor([1])))

Would output:
Parameter containing:
tensor([[ 0.1420, -0.1886,  0.6524,  0.3079],
        [ 0.2620,  0.4661,  0.7936, -1.6946],
        [ 0.0931,  0.3512,  0.3210, -0.5828]], requires_grad=True)
tensor([[ 0.2620,  0.4661,  0.7936, -1.6946]], grad_fn=<EmbeddingBackward>)

So we took the first row of the embedding. It does nothing more than that.
Where is it used?
Usually when we want to encode some meaning (like word2vec) for each row (e.g. words being close semantically are close in euclidean space) and possibly train them.
Linear
torch.nn.Linear (without bias) is also a torch.Tensor (weight) but it does operation on it (and the input) which is essentially:
output = input.matmul(weight.t())

every time you call the layer (see source code and functional definition of this layer).
Code snippet
The layer in your code snippet does this:

creates two lookup tables in __init__
the layer is called with input of shape (batch_size, 2):

first column contains indices of user embeddings
second column contains indices of movie embeddings

these embeddings are multiplied and summed returning (batch_size,) (so it's different from nn.Linear which would return (batch_size, out_features) and perform dot product instead of element-wise multiplication followed by summation like here)

This is probably used to train both representations (of users and movies) for some recommender-like system.
Other stuff

I know it does some faster computational version of a dot product
where one of the matrices is a one-hot encoded matrix and the other is
the embedding matrix.

No, it doesn't. torch.nn.Embedding can be one hot encoded and might also be sparse, but depending on the algorithms (and whether those support sparsity) there might be performance boost or not.
Answer: TL;DR

nn.Embedding is for categorical input.
nn.Linear is for ordinal input.

Explanation
You use nn.Embedding when dealing with categorical data, e.g., class labels (0, 1, 2, ...). Because in a lookup table, the value would not be proportional to the key. This behavior suits categorical data, whose value has nothing to do with the semantics.
On the other hand, nn.Linear, being a matrix multiplication, does not provide the aforementioned behavior. The input and output are proportional due to the natural of multiplication. Therefore, you use nn.Linear for ordinal data.
Answer:
What is the difference between an Embedding Layer with a bias immediately afterwards and a Linear Layer in PyTorch

There is no difference and we can prove this as follows:
Consider a (m,n) linear layer without bias. Such layer is equivalent to the function  y=Wx where x is a column vector with dimensions (n,1) and y is a column vector with dimensions (m,1).
You can easily show that the result from this takes the form y[i] = dot(A[i,:],x) which means that if x is one-hot vector with a one at the kth index then y[i]= A[i,k] which implies that y=A[:,k]. This shows that multiplying by a one-hot with a one at the kth index vector extracts the kth column from the weight matrix (or the kth row for y=x^TW).
This implies there are (at least) two ways to implement an embedding layer:

Assume x is a one-hot vector, perform the matrix multiplication (i.e., use a linear layer without bias)
Assume x is the index (k) where the one-hot vector is 1 and directly return the kth column/row.

You learn the same weight matrix whether you implement is via (1) or (2) but one of these seems more efficient.


What happens when SPF includes domain that does not have SPF but A record instead

Question: A company whose mail servers we occasionally use to send emails has asked us to include their domain in our SPF record as follows: v=spf1 [...] include:app.sgizmo.eu ~all.
Now it turns out that there is actually no SPF record on the domain we're pointing to app.sgizmo.eu. The only records there are A records that change all the time (probably cloudflare).
From all I know about SPF, the absence of SPF records on the app.sgizmo.eu means that our include has absolutely no impact. It's as if it wasn't there.
What confuses me is that the SPF check tool spf-record.com lists the IPs that appear in the app.sgizmo.eu A record as allowed for email sending with the following wording:

Additional, external SPF records.
We could find other records authorized in the SPF record: app.sgizmo.eu
A records: 184.108.40.206
  220.127.116.11
  126.96.36.199
  126.96.36.199

Is that a bug of the tool? Or is my understanding of SPF wrong and lack of SPF record means that A records count as accepted IPs?
Answer: You're understanding is correct and this seems to be a bug in the tool. Or perhaps it is common practice to deviate from the RFC for SPF and allow this behaviour.
If you use the Dmarcian tool, it will fail, as it should following the SPF RFC.
The RFC states the include mechanism should reference a valid SPF (TXT) record. In case none is found, it should return a PERMERROR.
For this to work, you may add a:app.sgizmo.eu, if these are indeed the IP addresses used to send out emails on your behalf.
Comment: Thank you so much, that's splendid feedback!


Certificate Error: Mismatched Address

Question: I installed certificate with the details:
Issued To: mnit.xyz.com

and I have actually 4 sites. that use this domain:
home.mnit.xyz.com

register.mnit.xyz.com

research.mnit.xyz.com

contact.mnit.xyz.com

I try to open: https://home.mnit.xyz.com [link name changed] and I get the certificate error.
I have 2 Questions:

Can I certificate be used for these sites?
Is my certificate wrong?

Please help. Thanks.
I had had a multiple site certificate " Multiple Site ".
Comment: If you are trying to use the same certificate for multiple subdomains, you need a [wildcard SSL certificate](https://uk.godaddy.com/help/what-is-a-wildcard-ssl-certificate-567).
Answer: Ok, I see your problem. You have been issued a wildcard certificate for *.xyz.com which allows infinite subdomains, however you are trying to access a subdomain of a subdomain which the certificate is not valid for.
mnit.xyz.com would be valid home.mnit.xyz.com is not valid.
Answer: It depends on what certificate you have.
You could have a wildcard certificate and then it should work if it is issued for mnit.xyz.com or xyz.com. Most likely though you don't, and then you need to issue seperate cerificates for every domain.
Comment: I inquired in my company and they said we have a multiple site certificate ? I s that even a type?
Comment: That could be referring to a SAN certificate where you explicitly specify multiple domains which are covered by the certificate e.g. `www.example.com`, `example.com`, `www.example.net`
Answer: To check the Subject Alternative Name (SAN) that MarkoPolo mentioned, open the certificate and view the details. The specific field name might vary a bit, but it should be something like Subject Alternative Name or Certificate Subject Alt Name. You'll see a list of alternate names for that certificate.

Certificate Error: Mismatched Address


$f$ is a continuous function from $[0,1]$ to $\mathbb{R}$ s.t. $f(0)=f(1)$, prove $\exists c$ in $[0,\frac{1}{2}]$ such that $f(c)=f(c+ \frac{1}{2})$

Question: $f$ is a continuous function from $[0,1]$ to $\mathbb{R}$ and $f(0)=f(1)$, prove that exists $c$ in $[0,\frac{1}{2}]$ such that $f(c)=f(c+ \frac{1}{2})$
I have no idea about this question,anyone could help me?
Answer: We wish to prove the function $g(x)=f(x)-f(x+\frac{1}{2})$ defined in $[0,\frac{1}{2}]$ is zero at some point. Notice this function is continuous. Assume the function is never zero. Then it must always be positive or always negative (since otherwise we can apply the intermediate value theorem and find a zero).
We do the case when it is always positive.
Then $f(0)>f(\frac{1}{2})$ and $f(\frac{1}{2})>f(1) \implies f(0)>f(1)$ a
contradiction!
the other case is analogous.

As an extra, the problem can be solved similarly when $2$ is replaceed by $n$  a natural number and the interval is changed from $[0,\frac{1}{2}]$ to $[0,\frac{n-1}{n}]$. And it turns to be false for any $\alpha$ that is not a natural number(although the construction for a counter-example is rather erratic)
Comment: The answer is very clear, thanks
Answer: Hint: Consider the function $g(x) = f(x+1/2) - f(x)$. If $g(0) = 0$ you're done. If not, then ...
Answer: Consider the function $g:[0,\frac{1}{2}]\to\mathbb{R}$ defined as
$$g(x)=f(x)-f(x+\frac{1}{2}).$$
Then $g$ is continuous since $f$ is continuous, and $g(0)=f(0)-f(\frac{1}{2})$ and $g(\frac{1}{2})=f(\frac{1}{2})-f(1)=f(\frac{1}{2})-f(0)$ by assumption.
Now if $f(0)=f(\frac{1}{2})$, then we can take $c=0$ and $f(c)=f(c+ \frac{1}{2})$. If $f(0)-f(\frac{1}{2})\neq 0$, then $g(0)$ and $g(\frac{1}{2})$ have opposite sign, by intermediate value theorem, there exists $c\in[0,\frac{1}{2}]$ such that $g(c)=0$, i.e. $f(c)=f(c+ \frac{1}{2})$


How to change the title of the button in the user profile form in Drupal 7?

Question: How do I change the name of the button in the user_profile_form in Drupal 7?
I alter the user profile using hook_form_alter().
function userform_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_profile_form' ) {
    // I define a submit button like:
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Continue'),
    );

    //Then I can change it with this code:
    // Change 'Continue' to 'Sign in'.
    $form['submit']['#value'] = t('Sign in');
  }
}

It works for all elements (buttons) I define myself, but it doesn't work for the default button in the user profile form.
This the rendered HTML for the "Save" button:
<input id="edit-submit" class="form-submit" type="submit" value="Save" name="op">

Answer: Try using profile_form_alter


Java language-detection returning different probabilities given the same input

Question: I'm using the Java language-detection library in the following way:
Detector detector = DetectorFactory.create(); //profiles are in the default location
detector.append("What language is this text?");
List<Language> languages = detector.getProbabilities();
Language mostProbable = languages.get(0);
System.out.println(mostProbable.lang + " - " + mostProbable.prob);

The prob value varies slightly from execution to execution given the exact same input. Is that "normal"? What does that depend on?
Comment: *"The prob value varies slightly from execution to execution"* ***How***? Show us.
Comment: What @T.J.Crowder said, show us the input and the slightly diff prob values.
Comment: The input is secret :) The results are: 0.9999945454065466, 0.9999943739537236, 0.9999949374128473, 0.9999944875939283, 0.9999945975357323, 0.9999945125325345, 0.9999944234173573, 0.9999945984572353, 0.9999945351465767, 0.9999945596853r53, and so on....
Answer: If the algorithm / method the library is using is not deterministic then the values may vary per execution.
For example, some algorithms need to be given an initial seed to begin. In a lot of cases, this seed is (pseudo)-randomly chosen. This can affect the final output.
EDIT: It looks like that library is using Naive Bayesian Classifiers (which can probably be either or).
Comment: A quick scan over the source code appears to confirm this; line 246 of Detector.java uses random numbers to update the language probability.


Changing php.ini location for localhost

Question: I'm using localhost to run a website locally;
my problem is that I can't get the correct php.ini to load.
I have set the Directory and DocumentRoot fields in /etc/apache2/sites-available/default, and restarted the apache2 server.
But running phpinfo() in my localhost still tells me I'm loading the ini file at /etc/php5/apache2/php.ini.
Why?
How can I change which php.ini file gets loaded?
Comment: Please don't change the question to something completely different, since it becomes really hard to follow the discussion, and the answers start to sound terribly unrelated.
Answer: On ubuntu, while working on localhost, the php.ini file which gets load is located in your php(say latest php5) folder, path is /etc/php5/apache2/php.ini, this file basically controls the memory for localhost, like if you want to increase the db upload size or increase your memory limit on your localhost, then you need to edit this file.
Comment: Yes but in that file I changed the auto_prepend line to the following: auto_prepend_file = "/media/d1/website/csite/auto_prepend.html". But that auto_prepend file still doesn't get automatically prepende like on server and my other localhost system.
Comment: now have changed the question..
what is the error, can you specify??
Comment: There is an auto_prepend option in the php.ini file which I have set and for some reason nothing gets appended to the files on localhost.
Answer: The pre-appended file should be a php file IIRC, unless you are parsing html as php.
Comment: well prepending this html file this way has worked in other Ubuntu systems already so it's gotta be ok.
Answer: This question seems to be mutating as you dig deeper into the problem (as is right and proper, and often the case!) so I'll bite.  The location of php.ini is embedded at compile time for the module, via the options --with-config-file-path= and --with-config-file-scan-dir=.  Both the value of these compile-time options, and the actual php.ini it finds and parses as a result, can be seen into the output of phpinfo().  For the avoidance of doubt: php doesn't look into the DocumentRoot for this file, as your current question presumes.
You can have it look anywhere you want it to, but you'll have to recompile the module yourself.
Comment: Then I submit you are confused, and do not currently know whether the issue is that php is not picking up the .ini file, or that what you've added to it is not a valid statement for the setup of php on this machine.  Until you know what your problem is, it will be hard to solve.  And if I may presume, just because what you're trying to do worked on another machine is **no reason whatsoever** that it should work on this machine.  The number of compile-time options that can be set (see `phpinfo()` output) should give you some indication of how much PHP can vary from one machine to another.
Comment: Ok so where do I change those --with-config-file options? And how do I recompile the module?
Comment: Sorry, how to do stuff like that is beyond the scope of a simple SF answer.  You'll need to do a bunch of research, or get someone who knows about Linux to do it for you.  If you're not familiar with this stuff, then your life will be much simpler if you just put `php.ini` where it's supposed to go.  If you don't have privilege to do that, you also don't have privilege to insert a recompiled module, so you can't do any of this.
Comment: Yes but even when i put the php.ini where it's supposed to go, the auto_append still doesn't work.

Changing php.ini location for localhost


Was Nina Simone really refused admission to Julliard on racial grounds even though she passed the audition?

Question: I recently watched the movie 'Green Book'. While I was watching it I was reminded of someone who once told me that Nina Simone was refused entry to Julliard on racial grounds. Is this accurate and if so has Julliard ever had any official response to this potentially less-than-savoury part of their past?
We may think that we in the liberal arts sphere are a bit more liberal than, but it is unfortunate to learn that the liberal arts schools were unfortunately not immune to the prejudices of the day.
I personally have no ideological drum to beat, I'm just wondering how segregated the arts really was at one stage in time?
Comment: Neil - I'm unsure. I feel it is not quite on topic here or on academic.SE - possibly skeptics.SE is the best place. Let's see whether votes come in on migrating it.
Comment: I'm voting to close this question because it makes sense for skeptics.se to verify a claim and does not seem to be about music practice or theory.
Comment: This question may be suited to the academic.SE. I await assistance from a mod.
Comment: I'm voting to close this question because this is an excellent fit for Music Fans.
Answer: Nina Simone enrolled at Juillard, but was turned down by the Curtis Institute.
According to Wikipedia:

She applied for a scholarship to study at the Curtis Institute of Music in Philadelphia, where she was denied admission despite a well-received audition, which she attributed to racial discrimination. In 2003, just days before her death, the Institute awarded her an honorary degree.

It wasn't neccessarily racism. According to an article in the Philadelphia Enquirer, Curtis had been admitting Black students for years. It's more likely that she wasn't good enough (the year she applied they only accepted three out of 72 applications)..


TypeError when writing data to Influx with None values using Python's aioinflux user defined schema

Question: So I have a schema that I defined and use with aioinflux library to write data from Python to InfluxDB:
from datetime import datetime
from aioinflux import lineprotocol, TIMEDT, TAG, FLOAT, MEASUREMENT, INT
from dataclasses import dataclass
from typing import Optional

@lineprotocol(
    schema=dict(
        timestamp=TIMEDT,
        measurement=MEASUREMENT,
        object_id=INT,
        dt=TAG,
        weight=FLOAT,
        width=FLOAT,
        size=FLOAT,
        risk=TAG,
        confidence=FLOAT,
    )
)
@dataclass
class CbdrDebugPoint:
    timestamp: datetime
    object_id: int
    dt: str
    weight: float
    size: Optional[float]
    width: Optional[float]
    risk: Optional[str]
    confidence: Optional[float]
    measurement: str = "my_table_name"

but if any of my Optional fields get value equal to None the writing to influx fails with the following error:
TypeError("Invalid variable type: value should be str, int or float, got None")

but for sure it is possible to write null values to influx, so any idea why does this error appear?
Comment: You can't pass null via http api, you will have to skip the null fields some how if the library you are using doesn't support this.
Answer: So after digging in the aioinflux package, it seems that is has this werid behavior:

If you try to write the data using the dictionary format it does accept None in the dictionary and it simply omits them from writing them to influx so you get the desired behavior
-If you use the use defined schema with the dataclass it does not have the same behavior, isntead it tries to actually write None to Influx and it fails

So a way around it was for me to keep the user defined schema as short of documentation where the dataclass easily describes the model and it can be easily maintained but then I just added a to_dict method to make the dictionary that aioinflux expects as shown below:
from datetime import datetime
from aioinflux import lineprotocol, TIMEDT, TAG, FLOAT, MEASUREMENT, INT
from dataclasses import dataclass
from typing import Optional

@lineprotocol(
    schema=dict(
        timestamp=TIMEDT,
        measurement=MEASUREMENT,
        object_id=INT,
        dt=TAG,
        weight=FLOAT,
        width=FLOAT,
        size=FLOAT,
        risk=TAG,
        confidence=FLOAT,
    )
)
@dataclass
class CbdrDebugPoint:
    timestamp: datetime
    object_id: int
    dt: str
    weight: float
    size: Optional[float]
    width: Optional[float]
    risk: Optional[str]
    confidence: Optional[float]
    measurement: str = "my_table_name"

    def to_dict(self):
        return {
            "measurement": "my_table_name",
            "fields": {
                "object_id": self.object_id,
                "weight": self.weight,
                "size": self.size,
                "width": self.width,
                "confidence": self.confidence,
            },
            "tags": {
                "dt": self.dt,
                "risk": self.risk,
            },
            "time": self.timestamp,
        }

and then before writing to Influx I produce this dictionary. It is a hack but given that the library does not support writing None for user defined schema it is an acceptable solution.