How to load an include file from Drupal's include folder?

Question: I am experiencing a problem with the GlobalRedirect module in that it seems like it is not loading the locale.inc which it relies upon. I tried using the module_load_include function but did not work as locale.inc isn't apart of a module.
I know I can use:
include(DRUPAL_ROOT."/includes/locale.inc");

Is there a Drupal specific function call to load include files for Drupal? I am curious if there is.
Thanks
Answer: require_once DRUPAL_ROOT . '/includes/actions.inc';

is the correct way.
Using 'content' just worked, because there is no module named content and just did work due to a side-effect. It also caused silent performance problems on Drupal versions < 7.50.
There is no Drupal specific function to load a core include file, and this is how it is done in includes/common.inc line 5242.

Fabianx, Drupal 7 core branch maintainer and core committer
Comment: > 7.50 you'll end up with "The following module is missing from the file system: content" errors
Answer: With the help of module_load_include() method you can include the core files from the include directory the only thing is you need to pass "content" in the second parameter (i.e: module name).
Working Example on including a file from drupal core includes directory,
module_load_include('inc', 'content', 'includes/actions');

Comment: This approach causes the warnings "The following module is missing from the file system: content", and is not the correct approach.  See @LionsAd's solution instead for the right way.
Comment: Never realized I could include these files using `module_load_include`
Comment: It was the 'content' keyword that I was missing. Thanks.
Comment: it seems to me the OPs original method is fine (and shorter) - what am I missing?


erro no full calendar

Question: Eu tenho um calendário completo e quando eu mudo o idioma para portugues, ele me retorna esse erro.
Uncaught TypeError: Cannot read property 'defineLocale' of undefined
   $('#calendar').fullCalendar({
                header: {
                    left: 'prev,next today',
                    right: 'month,agendaWeek'
                },
                defaultView: 'month',
                viewRender: function (view) {
                    var title = view.title;
                    $(".taskElementCalendar").html(title);
                }
            });

            $(".taskElementPrev").click(function () {
                $("#calendar").fullCalendar('prev');
            });
            $(".taskElementNext").click(function () {
                $("#calendar").fullCalendar('next');
            });
            $(".taskElementToday").click(function () {
                $("#calendar").fullCalendar('today');
            })

Answer: Você importou corretamente o locale específico?
De acordo com a documentação:

How to use other locales
You will need to load the locale JavaScript data file in order to use
  it. These files are included with the FullCalendar download in the
  locale/ directory. They must be loaded via a  tag after the
  main FullCalendar library is loaded.

Se você importar o locale específico, não é necessário passar nenhuma option.
Agora se você importar o arquivo JS que possui todos os locais, então você pode colocar a options locale quando estiver inicializando o fullCalendar.
Ficaria mais ou menos assim:

Espero ter ajudado.
Qualquer dúvida, é só comentar.

erro no full calendar


Function whose integral is equal to the function

Question: Let $\lambda \in \mathbb{R}$ be a constant, $\lambda \neq 0$. Is there a function $f \in C[0,1]$, $f \neq 0$, that satisfies the following relation:
$$\lambda f(s) = \int_0^s f(t) \, dt$$
Attempt at a solution:
Applying Fundamental Theorem of Calculus, one gets $ \lambda f(s) = F(s) - F(0)$, which implies that $f(0) = 0$. It follows that $f$ cannot be differentiable, because if it were, then taking the dervative on both sides gives $\lambda f'(s) = f(s)$, which gives together with the boundary condition $f(s) = \exp[\frac{s}{\lambda}] - 1$, but this function does not satisfy the relation. Hence if such a function exists, then it cannot be differentiable on $[0,1]$.
Comment: But $f$ must be differentiable in order for a multiple of $f$ to equal that integral since you assumed $f$ to be continuous.
Comment: The function whose value is everywhere $0$ satisfies this equation.
Comment: @MichaelHardy: Yes, therefore I assumed $f \neq 0$.
Comment: @Imray : it's not because you didn't understand the question, it's because you wrote something that didn't make sense. $3 e^s = \int_0^s e^x \, dx$ is false, even if you did a typo ; in other words, $f(x) = e^x$ doesn't work here. It's as simple as :
$$
\int_0^s e^x dx = e^s - 1 \neq \lambda e^x
$$
whatever the value of $\lambda$ you choose.
Comment: What about $3e^x = \int_0^3 e^x dt$?
Comment: @Tobias: So why is that?
Comment: The fundamental theorem you yourself mentioned says that if $f$ is continuous then that integral is differentiable.
Comment: If $f$ is continuous then the primitive of $f$, $F$ is differentiable, but that does not imply that $f$ is differentiable, right?
Comment: Correct. But you are also assuming that $f$ equals a multiple of its own integral, which is what then makes $f$ differentiable. Note that if you change the lower bound on the integral to $-\infty$ then such $f$ do exist, namely the exponential functions.
Comment: Ok, I see, so I guess I have a proof by contradiction that such a function does not exist?
Comment: ...and if $\lambda f(s) = \int_0^s(\text{some continuous function})\,dt$ then that implies $f$ is differentiable.
Comment: @Imray : Just try to evaluate for any $x$ : your example doesn't work.
Comment: @PatrickDaSilva Actually the problem seems to be that Imray is taking $s$ to be the constant $3$, which is doubly strange considering that $f$ is only defined on $[0,1]$.
Comment: No I was taking $f$ to be $e^x$ and $\lambda$ to be 3. I thought that worked but I guess I didn't understand the question.
Comment: @Imray Your right-hand side clearly assumes that $s=3$.  The relation is supposed to hold for all $0 \le s \le 1$ (it is not stated explicitly so the natural convention is to require it for all applicable $s$).
Answer: Let $M(r) = \max \{|f(x)|: 0 \le x \le r\}$.
 Then $|\lambda| |f(x)| \le M(r) x \le M(r) r$ for $0 \le x \le r$, so $|\lambda| M(r) \le M(r) r$. Thus if $r < \lambda$ we have $M(r)=0$, i.e. $f(x) = 0$ for $0 \le x < |\lambda|$.
Let $t$ be the greatest $r$ such that $M(r) = 0$.  I claim $t = 1$.  If not,
for $t \le x \le t+r$ (where $t + r \le 1$) we have
$|\lambda| |f(x)| = \left|\int_t^x f(x)\ dx \right| \le M(t+r) r$, so $|\lambda| M(t+r) \le M(t+r) r$, and if $r < |\lambda|$ we again get $M(t+r) = 0$, contradicting the maximality of $t$.
Answer: Since $f$ is continuous, it follows from the given relation that it is $C^1$ and solves the DE
$$
y'=\lambda^{-1}y,
$$
i.e.
$$
f(t)=c\exp(\lambda^{-1}t) \quad  t \in [0,1],
$$
where $c$ is a constant. Since $c=f(0)=0$, we have $f \equiv 0$. Hence there is no such function.
Comment: @Imray Obviously your question has nothing to do with the question we are discussing!
Comment: Why won't $3e^x = \int_0^3 e^x dt$ work?
Comment: Can you please explain why the given condition imply that f is $ C^1$
Comment: Since $f\in C[0,1]$, and $f'=\lambda^{-1}f \in C[0,1]$ it follows that $f \in C^{1}[0,1]$


Monaco editor for vue generates lots of .js files

Question: I am implementing vue-monaco plugin inside Laravel application using Vue.
The steps are rather easy, I install the vue-monaco like:
npm install vue-monaco

Then in my Vue file I import the monaco editor like:
import MonacoEditor from 'vue-monaco'

I don't even use it, just import it and then run npm run watch. This result in npm creating exactly 63 files in my public folder, like in the image below (first 15 are shown, 63 are being created).
Why does this happen and how can I bypass it?
Comment: Just speculating but might they be webpack bundle chunks that misplaced?
Comment: How can I check that?
Answer: vue-monaco is basically a VScode in your webview, right ? If it's the case, it's probably creating some configuration files for it to work and this is totally normal.
What's the content of those files and the content of your package.json (npm run watch) ?
If you want to custom some options for this plugin, it looks like that you will need to dive into those settings: https://microsoft.github.io/monaco-editor/api/modules/monaco.editor.html#create and pass it as props to vue-monaco (this info is taken from the doc itself).
Otherwise, creating a simple vue project can help debug things too IMO, see if the files are created in public too or if it's more of a laravel configuration issue. Then, you could maybe try the github issue of the main JS project: https://github.com/microsoft/monaco-editor/issues?q=is%3Aissue
Comment: Tried going with the configuration options, nothing seems to help. The files being generated are actually formatters for the different languages the editor supports (like html, css, js, rust, go etc.). I don't need them, but I can not find a way to eliminate them from pollution my public folder.
Comment: They are maybe required to use the plugin. That way, you don't need to link them to the editor since they are available in the public directory.


Distribution question Discrete Math

Question: In how many ways can we distribute 20 balls into 5 distinct boxes when it is required that no box remain empty and box number 2 will have no more than 10 balls?
Can someone explain me the steps to answer this question?
Thanks
The final answer should be 19choose4 - 9choose4, if you can explain why it would really help.
Comment: Can you show us what you've tried? :)
Answer: This can be rephrased as the number of non-negative integral solutions to the system:
$$\begin{cases}x_1+x_2+x_3+x_4+x_5=20\\1\leq x_1\\1\leq x_2\color{blue}{\leq 10}\\1\leq x_3\\1\leq x_4\\1\leq x_5\end{cases}$$
Approach with stars-and-bars.  First find the number of solutions where you ignore the upperbound on $x_2$.  Then subtract away the number of those solutions which were bad, i.e. the solutions where instead $11\leq x_2$.  Find the number of those by perhaps using a change of variable.

Edit: Since the OP edited his question after my post was already made, he apparently didn't fully understand.  Further, since the OP already has the answer and just doesn't understand it, I feel confident that this isn't for a test, so will elaborate.
The number of ways of distributing $A$ balls into $O$ boxes (I'm using $A$ and $O$ in order to hopefully avoid the confusion caused by using $n,k,r$ as different articles use these for different things) where each box gets at least one ball can be seen via stars-and-bars to be $\binom{A-1}{O-1}$.
Alternatively worded, the number of positive integer solutions to the system $\begin{cases}x_1+x_2+\dots+x_O=A\\1\leq x_i~~\forall i\end{cases}$ is again $\binom{A-1}{O-1}$
We can see this by laying the balls out in a line (the stars).  We then choose where to place dividers (the bars) between the balls to denote which balls will go into which box.  Note that the condition that every box gets at least one ball makes it so that the dividers must be placed in different locations.  For small example, with $5$ balls and $3$ boxes we could have $\star\mid\star\star\mid\star\star$ denoting that the first box gets one ball while the second and third boxes both get two.  As there are $A-1$ spaces between the balls and we wish to place $O-1$ dividers, we arrive at the result.

For your specific problem, if we temporarily ignore the upper bound, we have $20$ balls and $5$ boxes, each box must get at least one ball.  By using the logic above, this gives us $\binom{20-1}{5-1}=\binom{19}{4}$ outcomes.
Some of these are bad however in that they violated the upperbound we ignored earlier.  I.e. they are those outcomes corresponding to solutions to the system
$$\begin{cases}x_1+x_2+x_3+x_4+x_5=20\\1\leq x_1\\11\leq x_2\\1\leq x_3\\1\leq x_4\\1\leq x_5\end{cases}$$
(Note, I use here $11\leq x_2$ rather than $10<x_2$ to keep things consistent.  Since we were looking specifically at integer solutions, these are effectively the same)
By changing variables, letting $y_i=x_i$ for $i=1,3,4,5$ and by letting $y_2=x_2-10$, we get that this is equivalent to the system:
$$\begin{cases}y_1+y_2+y_3+y_4+y_5=10\\1\leq y_i~~\forall i\end{cases}$$
which is again in the form that we know how to deal with, having $\binom{9}{4}$ solutions.  Remember again these are the bad solutions that we needed to remove from our earlier calculation to account for the upper bound.
This gives us a final calculation of
$$\binom{19}{4}-\binom{9}{4}$$
Comment: This is the explanation I was looking for! I am studying for the final exam and I have issues with this kind of question. Thanks!!
Answer: There is a more complex way of doing this using generating functions, but simply speaking if there are $f(n,k)$ ways to distribute $n$ balls into $k$ boxes without restrictions, you have 11 cases.
Case $x$ is, the special box #2 will contain exactly $x$ balls, with $x$ an integer in $[0,10]$.

Find the desired number of ways in terms of $f(n.k)$ for each case.
Compute $f(n,k)$.
Add the $11$ cases to get your answer.

Distribution question Discrete Math


Intercepts (reference) in linear mixed effect model, what to choose?

Question: I am working on a study that examines word processing with native and non-native speakers. We have three independent variables: Groups (NSs and NNS), word types (five conditions), and word relatedness (related and unrelated words), and one dependent variable; Reaction Time.
I have successfully ran linear mixed effects model in R using (lme4) package and I was able to understand the output. However, there is something that I do not understand, the intercepts (reference level). Could someone explain what does the intercept or reference means? Does it mean all levels of the variables are compared to it? If so, should I adjust the intercept level or let lme4 uses the default?
I am struggling to make this decision and I need reasons to back up any choice I make.
Note that that the Word Types are not related to each other, but they are compared with regard to Word Relatedness. Interestingly, when I change the intercept level the whole output changes. If you see below the Related:WordType also changes when the intercept is changed -- shouldn't this be the same in the two outputs?
<code>> contrasts(NS$WordType)     # default intercept by R
 2 3 4 5
 1 0 0 0 0
 2 1 0 0 0
 3 0 1 0 0
 4 0 0 1 0
 5 0 0 0 1

Linear mixed model fit by REML ['lmerMod']
Formula: RT ~ Related * WordType * (1 | Item) + (1 | Subject)
   Data: NS

REML criterion at convergence: 59570.13

Random effects:
 Groups   Name        Variance Std.Dev.
 Item     (Intercept)  1099     33.15
 Subject  (Intercept)  4002     63.26
 Residual             16153    127.10
Number of obs: 4737, groups: Item, 120; Subject, 43

Fixed effects:
                    Estimate Std. Error t value
(Intercept)          681.373     13.179   51.70
Related2              13.655      8.379    1.63
WordType2             1.220     12.729    0.10
WordType3             5.700     12.709    0.45
WordType4             5.199     12.696    0.41
WordType5           -48.050     12.690   -3.79
Related2:WordType2  -20.925     11.862   -1.76
Related2:WordType3   -6.780     11.869   -0.57
Related2:WordType4  -19.746     11.854   -1.67
Related2:WordType5   28.870     11.859    2.43

NS$WordType <- relevel(NS$WordType,"4")     # Changed the intercept to word type 4
contrasts(NS$PrimeType)
  1 2 3 5
4 0 0 0 0
1 1 0 0 0
2 0 1 0 0
3 0 0 1 0
5 0 0 0 1

Linear mixed model fit by REML ['lmerMod']
Formula: RT ~ Related * WordType * (1 | Item) + (1 | Subject)
   Data: NS

REML criterion at convergence: 59570.13

Random effects:
 Groups   Name        Variance Std.Dev.
 Item     (Intercept)  1099     33.15
 Subject  (Intercept)  4002     63.26
 Residual             16153    127.10
Number of obs: 4737, groups: Item, 120; Subject, 43

Fixed effects:
                    Estimate Std. Error t value
(Intercept)         686.5723    13.1779   52.10
Related2             -6.0911     8.3859   -0.73
WordType1           -5.1994    12.6957   -0.41
WordType2           -3.9794    12.7283   -0.31
WordType3            0.5006    12.7083    0.04
WordType5          -53.2497    12.6895   -4.20
Related2:WordType1  19.7457    11.8541    1.67
Related2:WordType2  -1.1791    11.8656   -0.10
Related2:WordType3  12.9659    11.8734    1.09
Related2:WordType5  48.6158    11.8662    4.10
</code>
I have also came across afex package -- first intended to calculate p-values. I noticed it controlled and chooses a different default when running the model.
<code>> contrasts(NS$WordType)     # default intercept by afex
  [,1] [,2] [,3] [,4]
1    1    0    0    0
2    0    1    0    0
3    0    0    1    0
4    0    0    0    1
5   -1   -1   -1   -1

Linear mixed model fit by REML ['lmerMod']
Formula: RT ~ Related * WordType * (1 | Item) + (1 | Subject)
   Data: NS

REML criterion at convergence: 59583.5

Random effects:
 Groups   Name        Variance Std.Dev.
 Item     (Intercept)  1099     33.15
 Subject  (Intercept)  4002     63.26
 Residual             16153    127.10
Number of obs: 4737, groups: Item, 120; Subject, 43

Fixed effects:
                    Estimate Std. Error t value
(Intercept)         679.1560    10.2793   66.07
Related1             -4.9693     1.8766   -2.65
WordType1            9.0442     7.0943    1.27
WordType2           -0.1982     7.0930   -0.03
WordType3           11.3543     7.1003    1.60
WordType4            4.3708     7.0972    0.62
Related1:WordType1  -1.8580     3.7485   -0.50
Related1:WordType2   8.6044     3.7544    2.29
Related1:WordType3   1.5319     3.7579    0.41
Related1:WordType4   8.0148     3.7509    2.14
</code>
When I saw the negative numbers in the contrasts, I wonder if I could produce the same output as afex when I adjust the intercepts.
<code>> NS$WordType <- relevel(NS$WordType,"5")   # changed the intercept to word type 5
> NS$Related <- relevel(NS$Related, "2")          # changed word relatedness to 2 (unrelated)
> contrasts(NS$WordType)                               # both adjusted to mimic afex output
  1 2 3 4
5 0 0 0 0
1 1 0 0 0
2 0 1 0 0
3 0 0 1 0
4 0 0 0 1

Linear mixed model fit by REML ['lmerMod']
Formula: RT ~ Related * WordType * (1 | Item) + (1 | Subject)
   Data: NS

REML criterion at convergence: 59570.13

Random effects:
 Groups   Name        Variance Std.Dev.
 Item     (Intercept)  1099     33.15
 Subject  (Intercept)  4002     63.26
 Residual             16153    127.10
Number of obs: 4737, groups: Item, 120; Subject, 43

Fixed effects:
                    Estimate Std. Error t value
(Intercept)         675.8473    13.1857   51.26
Related1            -42.5247     8.3944   -5.07
WordType1           19.1802    12.6920    1.51
WordType2           -0.5246    12.6622   -0.04
WordType3           18.1004    12.7000    1.43
WordType4            4.6339    12.7001    0.36
Related1:WordType1  28.8701    11.8595    2.43
Related1:WordType2  49.7949    11.8727    4.19
Related1:WordType3  35.6499    11.8805    3.00
Related1:WordType4  48.6158    11.8662    4.10
</code>
As you can see, the output is different from afex output.
To summarize, my questions are as follows:
What is the intercept in Linear mixed effects models?
What do I need to know in order to make a wise decision in adjusting the intercept?
Why afex package differ in choosing the intercept? Would it be the "best" approach in choosing the intercept for this type of design?
Answer: The intercept is the predicted value of the dependent variable when all the independent variables are 0. Since all your IVs are categorical, the meaning of an IV being 0 depends entirely on the coding of the variable, and the default is not necessarily going to be the most useful. You can figure out what each program uses as a default from the documentation.
The reasons to select a particular reference level could be substantive (e.g. one group is likely to be seen as the "default") or statistical (e.g. one reasonable choice is to use the level with the lowest (or highest) level of the predicted value, to make all the comparisons to that level.
When a categorical variable has only two levels, changing the default will simply flip the sign (e.g. if boys are 5 inches taller than girls, then girls are 5 inches shorter than boys) but when there are more levels the changes are not as intuitively obvious.
Comment: Statistically, if I choose to use a level with the highest predicted value as the reference, it will mean that all other levels are compared to that reference. Right? In that case, the results interpretation will be based on how other levels are compared or significantly differ (or not) from the reference level. Would that be a good way to go about it?
Comment: Yes, that is correct.


Disabling text field for all users / roles

Question: is there an easy way to disable (readonly) fields in the backend for ALL users and roles (also superadmin).
I already found a module -> https://www.drupal.org/project/disable_field but this module allows superadmins to edit the fields.
Why do i need this?
Because the 5star rating module isn't ported to D8 yet i need a solution to realize a 5star voting in D8 with the vote data (5star rating) from an old drupal installation.
My thought was to work with a field collection, where i want to import the main 5star rating values from the old site into the new installation.
Afterwards i want to build a custom 5star voting.
The users should not be able to change this values in the field collection.
Any ideas?
Regards
M.
Comment: What about removing the fields in *Manage form display* of the field collection? If you want to be sure, you can set `$form['field_name']['#access'] = FALSE;` in a form alter hook.
Comment: ahhhhhhhhhh sounds nice... i've totally forgotten that i could handle it this way! thx for the hint! i'll give it a try :)
Answer: I don't know why would you need to disable any fields in the first place (that's not turns out from your post), but if you need 5 voting field, you could easily create it:
You may need just a part of them or all of them:
Creating a custom Field
Comment: It's quite easy:
Disabeling the fields therefore, that nobody can change the vote results.

I don't want to add a new field, i want to work with existing fields, like text etc. combined with the field collection module.

Now it looks like this:
https://www.dropbox.com/s/7xp3xyx8o5m5vai/Screenshot%202016-09-21%2014.23.35.png?dl=0


Model with interaction completely different than without

Question: I have a regression model with 2 numeric independent variables and I set up a model without an interaction term. This is the result:
<code>            Estimate Std. Error t value Pr(>|t|)
(Intercept)  1.27443    0.76675   1.662    0.105
Var1         1.00115    0.17742   5.643 1.76e-06 ***
Var2        -0.08345    0.10929  -0.764    0.450
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5374 on 38 degrees of freedom
Multiple R-squared:  0.4815,    Adjusted R-squared:  0.4542
F-statistic: 17.65 on 2 and 38 DF,  p-value: 3.802e-06
</code>
The result is as expected. One positive and effect significant, the other not significant.
Then I tried the same model with an interaction term.
The result:
<code>                 Estimate Std. Error t value Pr(>|t|)
(Intercept)        7.0820     3.7597   1.884   0.0675 .
Var1              -0.2013     0.7823  -0.257   0.7983
Var2              -1.6966     1.0288  -1.649   0.1076
Var1:Var2          0.3300     0.2093   1.577   0.1234
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5272 on 37 degrees of freedom
Multiple R-squared:  0.5142,    Adjusted R-squared:  0.4748
F-statistic: 13.05 on 3 and 37 DF,  p-value: 5.763e-06
</code>
The regression coefficients are completely different and I don't understand why.
I don't think there is an interaction effect and I expected almost the same model as the first and a (very) small coefficient for the interaction term. Do you have an idea why this is not the case?
I'm sorry I can't provide the data ...
This is the correlation between the variables:
<code>                 Var1      Var2 Interaction Dependent
Var1        1.0000000 0.4321173   0.7010085 0.6881562
Var2        0.4321173 1.0000000   0.9425496 0.2169298
Interaction 0.7010085 0.9425496   1.0000000 0.4325696
Dependent   0.6881562 0.2169298   0.4325696 1.0000000
</code>
Comment: Perhaps it would be worth answering why you think the models should be similar.
Comment: I've edited my question
Answer: With the introduction of the interaction term, you now have three terms that 'share' the correlation. What used to be the significant correlation of Var1 is now shared between Var1 and Var1:Var2, with the result that both correlations are now not significant anymore (and the coefficient for Var1 even flips from plus 1 to minus 0.2).
To better understand these results, I suggest to run a univariate correlation for all three terms independently, that is between Var1 and your dependent variable, between Var2 and your dependent variable, and between 'Var1:Var2' (that would be the product of Var1 and Var2, Var1 x Var2) and your dependent variable. That should give you a hint whether to include Var1:Var2 or not.
(some additional thoughts added)

The fact that the coefficients of a three-variable LR look totally different from the coefficients of a two-variable LR does not mean that the Model itself 'is totally different' or renders totally different results. To check this, compare the residuals of your first model with those of the 2nd model (e.g., in a scatter plot).
Also, if you don't have a 'subject matter' justification to include the interaction term, don't include it.
Based on the univariate analysis, why not exclude Var2 and try a model with only Var1 and Var1:Var2?
In the end, it is you who has to decide whether you want the mathematically best fit (e.g., the highest R² - but there are lot of other measures) - which may include counterintuitive negative coefficients -  or a model that can still be explained and where the coefficients 'make common sense'.
Have you used the train data / test data concept to test your model? You need to avoid overfitting.
Comment: Thank you! I've added the correlation matrix to my question. Do you have an idea?
Comment: I have edited my response.


Pequena dúvida com operações numéricas

Question: Estava fazendo uma função em python que me retorne os resultados(x' e x") da fórmula de bhaskara, só pra treinar a lógica um pouquinho. E brincando um pouco no shell, acabei descobrindo uma coisa estranha. Não é nada de mais, mas me deixou curioso.
Se eu elevar um número negativo ao quadrado, o esperado é que o resultado seja positivo, né?
>>> -7 ** 2
-49

Não é o que acontece se eu fizer da forma acima. Entretanto, se eu atribuir o -7 a uma variável x, por exemplo, e tentar elevar x ao quadrado...
>>> x  = -7
>>> x ** 2
49

...o resultado sai como o esperado. Por que o python não fez a operação corretamente do primeiro modo?
Answer: Pelo que parece o operador ** possui precedência maior que o operador unário -, ou seja, primeiro o interpretador calcula a potência e depois a negativa. Assim sendo a expressão -7 ** 2 seria equivalente a -(7 ** 2), o que resulta em -49.
Se você for pensar bem, é o que ocorre normalmente quando estamos operando expressões matemáticas, numa folha de papel:

-72 é de fato -49
(-7)2 esse sim seria 49
Comment: É uma questão de notação matemática mesmo. A potência possui maior precedência. Se o sinal de negativo tivesse maior precedência, então **-x²** seria igual a **(-x)²** que seria igual a **x²**. Se isso fosse verdade uma equação que normalmente se escreve **-x² = -1**, teria de ser escrita como **-(x²) = -1**.
Comment: Entendi, mas ainda sim acho estranho, pois eu não explicitei os parênteses para deixar o sinal negativo de fora. Eu achava até que isso poderia ser algum tipo de bug.

Pequena dúvida com operações numéricas


IIS Express won't download .coffee files

Question: I just enabled source maps because, sure why not, I'd like to try them out. However, I'm finding that IISExpress will not download .coffee files so it doesn't work.
I'm sure it's a simple web.config modification, I'm just not sure which one. How do I configure it to serve these?
Answer: All of IIS Express's configuration is done through the configuration files; in this case you want
C:\Users\[user]\Documents\IISExpress\config\applicationhost.config

In that file, there's a list of all of the static content types that IIS Express knows about and is willing to serve. You just need to add your extension to that list. The list starts about 1/2 down the file, in this XML element:
<staticContent lockAttributes="isDocFooterFileName">

It should be pretty obvious what to do from there: just map.coffee files to the correct mime type.
    <mimeMap fileExtension=".coffee" mimeType="text/plain" />

This element is found within the system.webServer element, which is one of the ones that supports delegation to individual web.config files, so you should be able to add a similar XML block to your project's configuration file:
<system.webServer>
    <staticContent>
        <mimeMap fileExtension=".coffee" mimeType="text/plain" />
    </staticContent>
</system.webServer>

Comment: BTW: an excellent reference for what can and cannot go into web.config: http://www.iis.net/configreference
Comment: Can I not add this somewhere in my project so that it works out of the box without every dev having to configure this?
Comment: I believe so; it's inside the `` element, which you can delegate to child configuration files. I haven't tried but I'll explain how it "should" work.
Comment: Ah yes, that pointed me in the right direction. https://support.gearhost.com/hc/en-us/articles/200342605-Adding-Custom-MIME-types-to-your-site


Prevent postback on button click and multiple client function

Question: I have an asp.net button to update database
<code><asp:Button ID="btnSave" runat="server" Text="SaveChanges" OnClick="btnSave_Click"
        CssClass="saveButton" ValidationGroup="answer" OnClientClick="return ValidateUserNameBeforeSubmitting();" />

<script type="text/javascript">
    $(document).ready(function () {
        $("#<%=TextUserName.ClientID%>").blur(function () {
            ValidateUserNameAfterBlur();
        });
    });

    function ValidateUserName() {
        var returnValue;
        $.ajax({ type: "POST",
            url: "../UserNameWebService.asmx/ValidateUserName",
            data: JSON.stringify({ strUsername: $("#<%=TextUserName.ClientID%>").val() }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            async: false,
            success: function (data) {
                returnValue=data.d;
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });
        return returnValue;
    }
    // to prevent postback when click save button.
    function ValidateUserNameBeforeSubmitting() {
        var isValid = ValidateUserName();
        return isValid;
    }

    function ValidateUserNameAfterBlur() {
        var isValid = ValidateUserName();
        $('#TextUserNameError').toggle(!isValid);
    }
</script>
</code>
The function is to validate a textbox for an username. But I have a few textbox to be validated.
Each one will display different error. Can I have multiple client side call on the button?
Thanks.
Comment: what do you mean by __Can I have multiple client side call on the button?__
Comment: I want something like OnClientClick="return function1(),return function2()" etc. oR OnClientClick1=... OnClientClick2=...
Answer: Of course you can have multiple client-side functions:
<code>$("#<%=TextUserName.ClientID%>").blur(function () {
    ValidateUserNameAfterBlur();
    ValidatePasswordAfterBlur();
    ValidateFoo();
    PhoneYourWife();
    ...
});
</code>

If you want to submit only when they are all valids:
<code>$("#<%=btnSave.ClientID%>").click(function () {
    if (ValidateUserNameAfterBlur() &&
        ValidatePasswordAfterBlur() &&
        ValidateFoo()               &&
        PhoneYourWife())

    submitTheData();
});
</code>
Comment: This is only blurring on TextUserName textbox, but I have other textbox to be blurred.
Comment: @Love. O.K. attach those textboxes blur callbacks, where is the problem?
Comment: How about ValidateUserNameBeforeSubmitting, I need several similar functions for different textbox? How can we put them together?
Comment: @Love. I'm having real difficulties understanding your needs.
Comment: You are right. But my submitting data is in code behind, which is on the server side. What kind of code likely?


Issue with image retrieval on Wordpress 3.5.1

Question: I' developing my own wordpress theme. I have an issue with the retrieval of posts' images.
I'm using the following code:
if ($images = get_children(array(
'post_parent' => $postid,
'post_type' => 'attachment',
'numberposts' => '1',
'post_mime_type' => 'image', )))
foreach($images as $image) {
$thumbnail=wp_get_attachment_image_src($image->ID, $size);
?>
<?php echo get_image_path($thumbnail[0]); ?>
}
else ....// retrieve a default error image

This code works fine if I upload a new image and i attach it into the post, but i fails if I attach an old image taken from the media Library.
I can't figure out where is the problem. Accord to the Wordpress's Function Reference, both get_children() and get_image_path() shold not be deprecated.
I'm using the latest avaible verison of Wordpress (3.5.1)
Comment: Are those old images attached to the post in question (`$postid`)? Or are they un-attached / attached to other post?
Comment: I discovered that if i select an image from the media library and put inside a post, it isn't considered attached to the post.
So i was wondering how i can get the images inserted inside a post ( attached or not attached).
Comment: Not quite possible without querying all posts and checking for the attachement URL inside `post_content`...
Answer: Yes, WordPress has no way of working out whether an image you inserted into a post was actually attached to the post or not - it could be something you added from an external website for all it knows, it's just HTML code in the editor.
As I think you have already identified, get_children will only find attachments - ie. photos that were uploaded for this post and not just inserted from the media library.
The only way to achieve what you are trying to do is to explicitly upload photos from with each post - meaning that if more than one post uses the same image, you'll need to upload it again for each post. Not ideal, but at the moment that is the only way to "attach" an image to a post so that get_children works.
The only other way I could suggest to do it would be to use a custom field to manually store the post ID of the images you want to use as thumbnails (regardless of whether they are attached or not) and then iterate through those IDs when you want to display the thumbnail images for them. It's a bit clunky, but would allow you to only upload photos once.

However, if all you are trying to do is show the post thumbnail, there is an easier way to do this. You can now separately specify an image to use as a "featured image" (any image from the library, doesn't have to be attached to the post or displayed in the post).
First, make sure you add support for post thumbnails:
add_theme_support( 'post-thumbnails' );

Then go into your post, click "Add Media", and choose "Set Featured Image" from the left menu. You can choose any image already in the library or upload a new one and it will be set at the post thumbnail.
In your template you can then just do something like this in the loop:
if ( has_post_thumbnail() ) {
    the_post_thumbnail();
}

If you are working outside the loop, you can get the thumbnail ID for a specific post:
$post_thumbnail_id = get_post_thumbnail_id( $post_id );

... or just get the thumbnail HTML directly:
get_the_post_thumbnail( $post_id, $size, $attr );

Unfortunately, you can only have one featured image, so if you need more, you'll need to go back to your original code and explicitly attach images to the post.
See more: Post Thumbnails


AWS DMS: Resuming the AWS DMS CDC after migrating DB to another server

Question: We are in the process of migrating our Oracle 19c DB to another server. The DB is a source DB for AWS DMS replication.
After the migration of our DB to another server ( using Datapump Export/Import), can we resume the AWS DMS CDC job using SCN of the new DB. The SCN is when the new DB was opened for transaction processing to all the users.
Before migration we log out all the users from the source DB and lock all the user accounts. As such, n there are no transactions happening on the source DB. After that we log out the the Oracle user account used by DMS.
The AWS DMS job resumes replicating data from the new migrated DB. Bur we do see some gaps in the records on the target DB.
Answer: You should resume CDC from the time you started your datapump export.(may feel counter intutive). but here is how DMS will handle. In DMS when you tell CDC to start from when  full load (in your case data pump export /import) , any changes that happened during the time of datapump export will be ignored (like duplicate etc) you can see that in cloudwatch logs with filtering with "W]".
This setup of CDC only works if your table(s) has primary key defined.
Also updates and deletes are also handled correcltly if you use the starttime same as start of datapump export


Why these are isomorphic each other for given these rings?

Question: For the ring $\mathbb{Z}_{15}[x]$ and its ideal $<3x^2 + 5x>$
Find the order of the $\mathbb{Z}_{15}[x]/<3x^2 + 5x>$

In my answer sheet it said
$\mathbb{Z}_{15}[x]/<3x^2 + 5x> \simeq (\mathbb{Z}_{3}[x]/<5x>) \times (\mathbb{Z}_{5}[x]/<3x^2>)$
Hence the order is 75.
I don't understand Why does $\mathbb{Z}_{15}[x]/<3x^2 + 5x> \simeq (\mathbb{Z}_{3}[x]/<5x>) \times (\mathbb{Z}_{5}[x]/<3x^2>)$.
Why those are isomorphic each other?
Answer: As Chris hinted, it is easy to lift up  $\,\Bbb Z_{15} \cong \Bbb Z_3\times \Bbb Z_5\,$ by CRT. Let's examine the idea more closely.
Notice  in $\,R = \Bbb Z/15\!:\   (3)+(5)=(1)\,\Rightarrow\, (3)\cap (5) = (3)(5) = (0)$ $\smash{\overset{\small\rm CRT}\Rightarrow}\, R^{\phantom{|^|}}\!\!\! \cong R/3\times R/5$
The above ideal equalities extend to $\,E = R[x]/(3x^3+5x),\,$ thus also $\smash{\overset{\small\rm CRT}\Rightarrow}\, E^{\phantom{|^|}}\!\!\! \cong E/3\times E/5$
Ring isomorphism theorems $\Rightarrow E/3  \cong \Bbb Z_3[x]/5x,\,$ $\,E/5  \cong \Bbb Z_5[x]/3x^2$

For variety here's another way: we apply CRT in $R=\Bbb Z_{\color{#c00}{15}}[x]\,$  with $\,I+J=(3,5x) + (5,3x^2) \supseteq (5,3)= (1).\,$ By ring isomorphism theorems $\,R/I = R/(3,5x)^{\phantom{|^|}}\!\!\! \cong \Bbb Z_3[x]/(5x),\,$ $\,R/J = R/(5,3x^2) \cong \Bbb Z_5[x]/(3x^2)$
$I\!+\!J=(1)\,\Rightarrow\,I\cap J = IJ = (3,5x)(5,3x^2) =(9x^2,-5x)= (3x^2,5x)\,$ by $\,2(9x^2)=3x^2$
hence $\,IJ =(3x^2,5x)=(3x^2\!+\!5x)\ $ by $\ (6,-5)(3x^2\!+\!5x)=(3x^2,5x)\,$ by $\,\color{#c00}{15=0}\,$ in $\,R$.
Conclude $\ R/(3x^2\!+\!5x) = R/(I\cap J)\overset{\rm\small CRT_{\phantom |}\!} = R/I\times R/J = \Bbb Z_3[x]/(5x)\times \Bbb Z_5[x]/(3x^2)$
Comment: @se-hyuckyang $\ I=(3,5x)\,$ and $\,J = (5,3x^2)\,$ denote ideals in $\,R = \Bbb Z_{15}[x]\ \ \ $
Comment: @se-h Let $\,f=3x^2\!+\!5x,\,$ so $\,(3,f)=(3,5x).\,$ By the [Second Isomorphism Theorem](https://en.wikipedia.org/wiki/Isomorphism_theorems#Rings) we have, $$(R[x]/f)/(3,f)/f \,\cong\, R[x]/(3,f) \,\cong\, \Bbb Z_{15}[x]/(3,5x) \,\cong\, \Bbb Z_3[x]/5x\,$$ where the final isomorphism is by $\,\Bbb Z_{15}[x] \to  \Bbb Z_3[x] \to \Bbb Z_3[x]/5x\,$ is onto with kernel $\,(3,5x)$
Comment: Does your $I$ and $J$ are $I \lhd \mathbb{Z}_3[x]$ and $J \lhd \mathbb{Z}_5[x]$?
Comment: Hmm.. I see. I'll try again. :)
Comment: Mr. @Bill Dubuque, How did you find the $(3,5x) (5,3x^2) = (x^2, 5x) = (3x^2 + 5x)$?[I mean what motivation or hint make you find  those?] Plus could you more explain for me the reason why $(x^2,5x) = (3x+5x)$?
Comment: @se- CRT yields $\,R/I \times R/J\, \cong\, R/IJ\! =\! R/(x^2,5x).\, $ To show  $\,R/IJ\,\cong\, R/K\! =\! R/(3x^2\!+\!5x)\,$ it suffices to show $\,IJ \!=\! (x^2,5x) = (3x^2\!+\!5x)\!=\!K.\,$ $\,IJ\supseteq K\,$ is clear. $\,IJ\subseteq K\,$ is proved above.
Comment: How did you conclude the $(3,5x)(5,3x^2) = (x^2,5x)$? When I tried this, $(3f_1 +5xf_2)(5f_3 + 3x^2 f_4) = 9x^2g_1 + 10xg_2  = (9x^2,10x)[\forall f_i, g_i  \in \mathbb{Z}_{15}[x]]$ So I couldn't more doing any process for taking out the $(x^2,5x)$. :(
Comment: @se- $\bmod 15\!:\ IJ \equiv (-6x^2,-5x) \equiv (6x^2,5x) \equiv (6x^2\!-\!(5x)x,\,5x) = (x^2,5x)\ \ \ $
Comment: Ah! Yes! you saved my life :)
Comment: Where is the Chris's method?
Comment: @se-hyuckyang They deleted their answer (I assumed they would undelete it after answering your question).
Comment: @se-hyuckyang Chris never expanded on their answer so I prepended this simpler approach to my answer (I didn't do so originally since I presumed Chris was going to eaborate after addressing your question in the comments).


Replace duplicate content of span using javascript

Question: I have button in my html page and lots of jquery libraries included on this page I am getting a issue like when I open page on live server then its changing the html text and making duplicate text like I have on html:
<input type="submit" value="Get Quote" name="submit">

After live it its converting into:
Get Quote <input type="submit" value="Get Quote" name="submit">

Span automatically coming even its not in code.
And
<select id='list' name='list'>
    <option value='0'>Select Numbers</option>
    <option value='my number'>my Number</option>
</select>

Its coming on live like this:
Select Numbers
<select id='list' name='list'>
<option value='0'>Select Numbers</option>
<option value='my number'>my Number</option>
</select>

How can I fix it ?
Comment: Answering this depends on why the `` is appearing in the first place.
Comment: What do you mean by "open page as live"?
Comment: I mean when I run it on live server
Comment: That is my question actually
Comment: There may be some javascripts(like jquery libs) generating `` automaticly
Comment: `and lots of jquery libraries included on this page` btw this question is not clear. You certainly may have to look into plugins, Maybe one of your plugins is adding it on input elements.
Comment: Might be possible but how can I check which one is generating  and how can I stop them ?
Answer: You could use JS to remove the text.

var inputs = document.getElementsByTagName("input");
var z = new Array();
for(var x = 0; x < inputs.length; ++x){
    if(inputs[x].parentNode.textContent.trim() == inputs[x].value.trim()){
        var input = inputs[x];
        input.parentNode.parentNode.replaceChild(input, input.parentNode);
    }
}
Text <input type="button" value="Text" />

Some Field Name <input type="button" value="Some Field Name" />

However, figuring out why the span is appearing in the first place, and removing that part of the code would be a much better and cleaner idea.
Comment: Are you putting it after your page has loaded? It can't remove something that isn't there yet.
Comment: I tried to put it before head tag close its not working then I try to put it before body tag close but still not working.
Answer: I fixed it by just removing the library from my page;
http://www.hccmis.com/wp-content/themes/hccmis-2/js/waypoints.min.js

And its working for me.


Why can't the decimal fraction part of $\frac{1}{d}$, $d \in \mathbb{N}^\ast$ have a recurring cycle of length greater than $d$?

Question: I am trying to solve problem 26 from project euler which asks Find the value of $d < 1000$ for which $1/d$ contains the longest recurring cycle in its decimal fraction part.
I noticed that all the cycle lengths are smaller than $d$ (at least for numbers $d < 1'000'000$), and I was wondering why this seems to be true. Is there a deep reason for this, or is this just something trivial I am not seeing?
Comment: Are you familiar with the ordinary long division algorithm? The one people might learn in school for dividing numbers by hand?
Comment: Yes I am familiar with this algorithm
Comment: Longest cycle has to do with $10$ being a primitive root of $d$.
Answer: Because there is maximum of $d-1$ possible remainders when dividing $1 \cdot 10, 2 \cdot 10 , ... (d-1) \cdot 10$ by $d$ and eventually in the process of division you divide some of these numbers with $d$ again and then all repeats.
Comment: Okay that makes sense! Thank you. I have to wait 7 min before accepting your answer. Remind me if I forget.
Comment: Wouldn't there be $d$ possible remainders when dividing $0 \cdot 10, 1 \cdot 10,...(d-1) \cdot 10$?
Comment: @GreyMatters I think that technically yes, but if the remainder is $0$, the division is over and there is no cycle, so we only have to consider non zero remainder.
Answer: Seing as you are familiar with the long division algorithm, I'll give a reason based on that (at least the way I hope you're used to doing it, something similar to this video, only you keep going after the decimal point). During the long division algorithm, after you've "pulled down" all the non-zero digits, and start pulling down zeroes, note that whatever remainder you get (the result of the "subtraction" part, before you pull down the next $0$) will entirely dictate how all the rest of the divisions go. For this discussion I will assume that you've gotten to this point of the long division already (as the periodic nature won't appear until you start pulling down only $0$'s).
Say, for instance, you're calculating $10\div7$, you've gotten to the answer $1.4$, and a ramainder of $2$. You pull down a $0$, get $20$, write a $2$ in the answer, subtract $20-14 = 6$. So if one remainder is $2$, the next digit in the answer will always be $2$, and the next remainder will always be $6$.
Continuing, we see that any time the remainder is $6$, the next digit of the answer will be $8$ and the remainder will be $4$. And any time the remainder is $4$... I assume you can see how this continues. Whenever we reach a remainder we've had before, the pattern will start repeating.
Since we never get a remainder of $0$ (since that would mean the division doesn't give an infinite expansion), and you will never get a remainder equal to or larger than $7$ (as long as you do things corerctly), there are only $6$ possible remainders. Which means that the repeating pattern of remainders, and therefore the repeating pattern of decimals in the answer, can at most be $6$ long.
This discussion will, of course, work for any other number than $7$ as well. Note, however, that this does not prove that the expansion will always be $d-1$ long. Only that $d-1$ is the longest it can possibly get.
For instance, with $d = 9$, the remainder never changes (at least in base ten). If you are calculating $10\div 9$, and you've gotten to $1.1$ with a remainder of $1$, you pull down a $0$, get the next digit $1$, and a remainder of $1$ again. The pattern jsut repeats immediately.


Template file naming with alias

Question: I have a few template node overrides in my theme using Drupal 7.
For example: page--node--53.tpl.php
This might be a lazy request, but is there anyway to name these files instead with the alias I have chosen rather then using the node number? That way I don't have to memorize all of the associated pages.
For example page--node--about.tpl.php
Answer: In THEMENAME_preprocess_page (in template.php located in your themes directory) you can set as many template hook suggestions as you wish. Drupal then goes through the list from bottom to top and once it finds the existing template suggestion, it stops and uses that one.
function THEMENAME_preprocess_page(&$vars) {
  // Add theme hook suggestions based on path for nodes only.
  if (isset($vars['node'])) {
    // get whatever you want here into $path variable
    $path = $vars['node']['type'];
    $vars['theme_hook_suggestions'][] = 'page__node__' . $path;
  }
}

in the $vars there should be the node object that you can check for
$vars['node']. also don't forget to sanitize anything you are adding there. good choice would be to use the drupal_clean_css_identifier function
Answer: Something like this in template.php should do the trick:
function MYMODULE_preprocess_page(&$vars) {
  if ($node = menu_get_object()) {
    $alias = drupal_get_path_alias("node/$node->nid");

    // Remove slashes from the potential filename
    $clean_alias = str_replace('/', '__', $alias);

    $vars['theme_hook_suggestions'][] = 'page__node__' . $clean_alias;
  }
}

You might need to massage your $clean_alias variable a bit more to handle any punctuation you're allowing into aliases (e.g. with Pathauto).
A node with an alias like about/about-us would then use a template file called page--node--about--about-us.tpl.php.
Comment: this worked great for me as well.  just made one change because hyphen weren't working for me in the name (e.g. about-us):     $clean_alias = str_replace('-', '_', str_replace('/', '__', $alias));
Answer: You should look at this thread in which someone has implemented this kind of template suggestions.

Template file naming with alias


How to simplify geodetic distance formula?

Question: Question is also related to programming, but maybe I can solve it here.
I am using distance calculation using Haversine method(probably it's not important, but I will post the function):
double GeoDistance(GeoCoordinate* p1, GeoCoordinate* p2)
{
  const float two=2.0;

  double lat1 = p1->lat * factor;
  double lon1 = p1->lon * factor;
  double lat2 = p2->lat * factor;
  double lon2 = p2->lon * factor;

  return RADIUS_METER * two * asin(sqrt(square(sin((lat1-lat2)/two)) + cos(lat1)*cos(lat2)*square(sin((lon2-lon1)/two))));
}

This gives me suitable precision. Since I am using this code in tiny microcontroller for number of geo points, I need to optimize this function with some other, which will work faster but precision can suffer. To give an idea on how much precision can suffer I will tell that the approximate distance I am calculating is about 200-400m and it can easily be +- 100m.
Comment: "The approximate distance I am calculating is about 200-400m and it can easily be +- 100m." Eureka! Always return 300. :)
Comment: hehe :) Can't do that "always", need some simple formula to tell me when exactly to return 300 :) Hope the one mentioned by dmuir is good enough.
Answer: For distances less than a kilometre the C code below gives the same answer as the haversine formula to within 4.5 cm ( and 4.5m for distances up to 10km)
(lats and longs in radians; R is the radius of the earth)
double dlat = lat2-lat1;
double dlon = remainder( lon2-lon1, 2.0*PI);
    return R*hypot( dlat, dlon*cos(lat1));

(Note that the complex calculation of difference of longitude is required in case the points lie on opposite sides of 180 degrees east).


Time Series Regressor Selection

Question: I am interest in a (multivariate) algorithm to identify relevant regressors (which are itself time series) to forecast a time series of interest. The question is worded in general terms because this algorithm should be applied on different kinds of time series.
With classical data, I would use for example LASSO and use those variables which non-zero coefficients but I am not really sure how to do that in a (general-purpose) time series context. The reason is that here each indicator may be relevant with a different lag. Furthermore it might be important to take a priori unknown seasonality pattern into account (the method should at best work for time series on an hourly level as well as an monthly level).
Similar questions have already been raised here at CrossValidated, for example,
here or
here or
here or
here
but I did not find a satisfactory answer. I hope it is therefore okay to post a similar question again.
Random Forest has been suggested in this answer. As with LASSO, it is however not clear to me how to optimally apply these methods in a time series context with arbitrary seasonality patterns.
I do not want to use cross-correlation (as suggested in this answer) because I want to take into account the covariance between the regressors.
tsfresh has been suggested in this answer but I do not see how I can get the most relevant features (meaning variables/regressores plus lags) from that package.
Any hints for Python or R libraries are welcome.
Answer: "I do not want to use cross-correlation (as suggested in this answer) because I want to take into account the covariance between the regressors."
The role of pre-whitening is to INITIALLY identify the nature of the input series transfer function structures/lags. This easily gets redefined via tests of necessity and tests of sufficiency via cross-correlation tests of the current model residuals and the pre-whitened X's.
As an over-arching comment you have totally ignored the impact of latent deterministic structure such as level shifts, seasonal pulses , pulses AND time trends.
Your target should be https://autobox.com/pdfs/SARMAX.pdf
Comment: Also see https://stats.stackexchange.com/questions/353491/how-to-use-dynamic-regression-models-in-r-to-forecast-future-sales/353906#353906 for some literature references
Comment: Could you elaborate on what SARMAX exactly is? [I only find references from you here on CrossValidated on SARMAX](https://stats.stackexchange.com/search?q=sarmax). Some literature reference would be appreciated.
Comment: Look for armax ( N.B. the S just stands for possible SEASONAL structure) . Also look for Transfer Function OR Autoregressive Distributed  Lags or Polynomial Distributed Lags. They are nearly synonyms. https://stats.stackexchange.com/search?q=user%3A3382+transfer+Function is a good place to start. Fundamentally it is ARIMA plus Exogenous variables both pre-specified and waiting to be found.
Comment: "Is there a forecasting function which allows both multiple predictors and multiple seasonalities?" you asked elsewhere. Yes by developing a model for Daily Totals and then using it as an input to predict for higher frequencies.. such as 15 minute intervals.
Comment: This question has been asked by [Haroon Rashid](https://stats.stackexchange.com/users/60072/haroon-rashid), and not by me, see [here](https://stats.stackexchange.com/questions/213192/forecasting-with-multiple-predictors-and-with-multiple-seasonalities-in-r). Still and interesting question :-)
Answer: Dynamic Factor Models, introduced among others by Stock and Watson (2002) seem to do that I am looking for

This article studies forecasting a macroeconomic time series variable using a large number of predictors.
The predictors are summarized using a small number of indexes constructed by principal component
analysis. An approximate dynamic factor model serves as the statistical framework for the estimation of
the indexes and construction of the forecasts. The method is used to construct 6-, 12-, and 24-monthahead forecasts for eight monthly U.S. macroeconomic time series using 215 predictors in simulated real
time from 1970 through 1998. During this sample period these new forecasts outperformed univariate
autoregressions, small vector autoregressions, and leading indicator models.

There are implementation in Python, R or Stata, for example.

Time Series Regressor Selection


Adding quotation mark to a string

Question: The title might be misleading, But i'm fairly new to JavaScript and the quotation marks is already killing me.
While page is loaded, I'm trying to add an edit button to the view and alert the random number when clicked, Like this:
 var docid = OSZVMeFDJ0eNaCNMffDTji5cf2I3 // random string
 $("#tableUser").append('<button type="button" class="btn btn-danger" onclick="loadUser('+ docid +')"> Edit User</button>');

And:
function loadUser(id) {
   console.log(id);
        alert(id);
}

But this code neither prints, or alerts. Is it because it doesn't have quotation marks? isn't the function parameters could be anything from an Integer to String?
Update
turns out i had put onlick() into the i which means the edit icon, now i removed & added it to the button but getting this on the console:

ReferenceError: Can't find variable: OSZVMeFDJ0eNaCNMffDTji5cf2I3
Comment: Can you create a minimal demo that reproduces your problem (see: https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do)? Also, read the "*[mcve]*" and "*[ask]*" guidelines.
Comment: If it neither prints nor alerts it's not being called. As to why, can't help yet.
Comment: thank you so much @DaveNewton, i was putting the onlick in the `i` variable, Could you also look at my updated question?
Comment: You probably need double quotes around your `docId`, but be aware to escape them correctly or use escaped single quotes like that: `loadUser(\'' + docId + '\'">)`
Comment: If docId can be anything but numbers then it should be quoted.
Comment: How can i ? please edit your answer :)
Comment: @DaveNewton that's exactly my question i'm coming from mobile programming and this was never a problem :D
Comment: You already been asked to, provide a [mcve] that reproduce the issue you describe.
Answer: OSZVMeFDJ0eNaCNMffDTji5cf2I3 is not a string it should be 'OSZVMeFDJ0eNaCNMffDTji5cf2I3'. Java script behaves with OSZVMeFDJ0eNaCNMffDTji5cf2I3 as a variable name and sees that it is undefined.
Comment: How do i do this inside the onlick function?
Comment: I think  var docid = " 'OSZVMeFDJ0eNaCNMffDTji5cf2I3' " would work.
Answer: You can acheive this with new ES6 feature called template literals or ticks.
 $("#tableUser").append(`<button type="button" class="btn btn-danger" onclick="loadUser(${docid})"><i class="fas fa-user-edit"></i> Edit User</button>`);

Comment: How do i do this inside the onlick function?
Comment: `SyntaxError: Unexpected token '{'. Expected ')' to end an argument list.` that didn't work
Comment: it will work .. you may have copy pasted it. let me create a js fiddle
Comment: anyway i'm pretty sure .. you are making syntax error now. Your loadUser wont be defined. Because you are attaching it later. User scripts operates in isolated world and  onclick operated in target page scope and cannot see your script function. so, add event listener to that edit and and try this again .. copy above code. Don't forget to use quotations on your string otherwise it will be undefined.
Answer: The problem is that OSZVMeFDJ0eNaCNMffDTji5cf2I3 isn't a string. JavaScript sees that and assume it's a variable. The way to fix your issue is by simply wrapping those characters in double " or single ' quotes - then JavaScript will recognize the string.

//The function we will call when the button is clicked.
function loadUser(id) {
  console.log(`docid is: ${id}`);
}

//Add the event listener
document.querySelector('#docIdBtn').addEventListener('click', function() {
  //Notice how the string is wrapped in quotation marks
  var docid = "OSZVMeFDJ0eNaCNMffDTji5cf2I3";
  //Call the function you defined above, pass in the "id" arg.
  loadUser(docid);
});
<button id="docIdBtn">Click</button>

Reading regarding String syntax.
Comment: How do i do this inside the onlick function?
Comment: I updated the code to and attached a click handler to the button. Now when it's clicked it will execute `loadUser`. Let me know if you need any other explanation.
Answer: var docid = OSZVMeFDJ0eNaCNMffDTji5cf2I3

should be
var docid = "OSZVMeFDJ0eNaCNMffDTji5cf2I3"

Otherwise you are trying to use OSZVMeFDJ0eNaCNMffDTji5cf2I3 as a variable, which does not exist.
If you are learning JavaScript programming from scratch, a few other pointers:

Don't use var. Use const or let, depending if it's a constant or a variable.
Avoid jQuery. It was a good library, a decade ago. With today's JavaScript is unnecessary and will hinder your learning. Specially when you jump to any of todays frameworks and libraries.
Use template strings, `with this quotes`. You can then interpolate any variable with ${variable}.
`loadUser(${docid})`
Comment: How do i do this inside the onlick function?
Comment: $("#tableUser").append(\` Edit User`);
Comment: Did you change the declaration of docid?
Answer: You're missing the
 in your string in order to create valid HTML
EDIT
You have to put quotes around docId as it is a string not a number
Comment: Sorry just removed that :)
Comment: And is `tableUser` an HTML table element?

Adding quotation mark to a string


Calculate $\lim\limits_{n\to\infty}\int_\mathbb{R}f_nd\lambda.$

Question: Exercise: Let $\lambda$ be the Lebesgue measure and let $f:\mathbb{R}\to\mathbb{R}$ be an integrable function. Suppose that we have the function $f_n(x):\mathbb{R}\to\mathbb{R}$ given by $f_n(x) = f(x)(1 + (\sin x)^n)$. Calculate the following limit: $$\lim\limits_{n\to\infty}\int_\mathbb{R}f_nd\lambda$$
What I've tried: If I can show that $f_n$ is measurable and integrable then I can use the dominated convergence theorem. I know that $f_n$ is continuous, which means that if $\int_{-\infty}^\infty\left|f_n(x)\right|dx$ exists as an improper Riemann integral then $f_n$ is integrable. I don't really know how to apply this theorem here though.
Let's assume that $f_n$ is integrable. We have that $\left|f_n\right|\leq 2\left|f\right|$, where $2\left|f\right|$ is integrable. The dominated convergence theorem tells us that we have $$\lim\limits_{n\to\infty}\int_\mathbb{R}f_nd\lambda = \int_\mathbb{R}fd\lambda$$ where $\lim\limits_{n\to\infty}f_n =f$ pointwise. Now, $\lim\limits_{n\to\infty}f(x)(1+(\sin x)^n) = f(x)$, for $x \neq k\pi$, with $k\in\mathbb{N}$. There are however, infinitely many $x\in\mathbb{R}$ for which $\left|\sin x\right| = 1$. So I don't think I can conclude that $$\lim\limits_{n\to\infty}\int_\mathbb{R}f_nd\lambda = \lim_{n\to\infty}\int_{\mathbb{R}\backslash X}f_nd\lambda$$ where $X = \{x\in \mathbb{R}: \left|\sin x\right| = 1\}$.
Question: How do I solve this exercise?
Thanks!
Answer: For those $x$ such that $|\sin x|=1$ are of countably many, so they form a set of measure zero, that is, $f_{n}(x)\rightarrow f(x)$ a.e. is satisfied, so Lebesgue Dominated Convergence Theorem still applies.
One may check for Theory of Measure and Integration, J Yeh, page 180, for the assertion:
$|f_{n}(x)|\leq g(x)$ a.e., $f_{n}(x)\rightarrow f(x)$ a.e., $g\in L^{1}$, then $\lim_{n}\displaystyle\int f_{n}(x)dx=\int f(x)dx$.
Comment: Thanks for your reply! Could you explain why $f_n$ is integrable?
Comment: Because $|f_{n}|\leq 2|f|$ and $2|f|\in L^{1}$, then the integral of $|f_{n}|$ is controlled by $2|f|$ and is then $<\infty$ by integrals comparison rule.


File "abc1234.py", line 9 time.sleep(3) ^ IndentationError: expected an indented block

Question: I am new to programming, I was trying to run this python program using terminal and getting the error: File "abc1234.py", line 9 time.sleep(3)
IndentationError: expected an indented block
       ^
import webbrowser
import time
time_total=3
time_count=0
print (" the current time is " +time.ctime())
while(time_count<time_total):
time.sleep(3)
webbrowser.open("https://www.youtube.com/results?search_query=raabta+song+deepika")
time_count= time_count+1

Answer: Not sure how you formatted it based off your entry.
But your code should look like this:
import webbrowser
import time
time_total = 3
time_count = 0
print (" the current time is " + time.ctime())
while(time_count < time_total):
    time.sleep(3)
    webbrowser.open("https://www.youtube.com/results?search_query=raabta+song+deepika")
    time_count = time_count + 1

You must indent all the code inside the while block. You must've not properly indented the time.sleep(3) on line 9. The interpreter was expecting at least one indented line following the colon of the while loop.
Comment: that code worked. however I am using the text editor "TextWrangler" and while using "while loop" do I have to manually add the spaces because after the : in the while loop it directly takes me to the next line without adding space like you have in your while loop
Comment: You can trying using the tab key perhaps? However, I would think that if it has python language support, somewhere in the preferences you would be able to enable auto-indent and define it to be 4 spaces. I'm not sure though, as I don't use TextWrangler personally.
Comment: that works .. Thank you @dor-ron
Comment: Sure thing glad to help


Unable to take multiple String input using scanner in java

Question: I have been trying to do a program in which i have to concat three strings in java.I am taking input from user using Scanner.It compiles perfect but when i run it,it gives me this error:
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at Night.main(Night.java:10)

This is my code:

import java.lang.*;
import java.util.*;

class Demo {
 public static void main(String[] args) {
  String fn;
  String mn;
  String ln;
  String fmn, lmn;
  Scanner sc = new Scanner(System.in);
  fn = sc.nextLine();
  mn = sc.nextLine();
  ln = sc.nextLine();
  fmn = fn.concat(mn);
  lmn = fmn.concat(ln);
  System.out.println("The Full name of candidate is : " + lmn);
 }
}
Answer: Your code works fine. Remove the [] near class declaration.
class VecDemo
{

public static void main(String[] args)
{
    String fn;
    String mn;
    String ln;
    String fmn,lmn;
    Scanner sc = new Scanner(System.in);
    fn=sc.nextLine();
    mn=sc.nextLine();
    ln=sc.nextLine();
    fmn=fn.concat(mn);
    lmn=fmn.concat(ln);
    System.out.println("The Full name of candidate is : " + lmn);
}
}

Refer the attachment.
Answer: I believe your current code in Demo class is working fine. Can you check again?! The exception is from Night.main(Night.java:10). If you still have the same error, can you check if there is any Night class in your working space?!
Hope this help.
Comment: It Worked guys.It was just a silly mistake ,I Saved the program by name "Night.java" though my class name was VecDemo. Thank you All members for your help..Highly appreciated
Comment: Haha. That's fine. :)


Improve our Cricket Team

Question: I am captain of cricket team in my college our team performance is very well but some team members are play only for fun at that result our team lose best performance at regional level matches.
Actually those members are my best friends therefore I do not react on his performance. My friends played very well but some time he plays out of rules. How to improve our team discipline. What should I do with my friends to achieve our team goal.
Answer:
What should I do with my friends to achieve our team goal.

What is your team goal? It seems that the members of your team have at least two, and maybe three different goals:

Your friends who are playing for fun. They care less about whether they win or lose and more about enjoying themselves.
Your one teammate who is prepared to break the rules (actually cheat?) in order to win.
You, who are somewhere in the middle and want to win but fairly?

With the exception of any actual cheating, none of these are wrong. It's perfectly valid to play for fun, it's perfectly valid to play to win... but it's very hard to have a happy team if the members have different goals.

Improve our Cricket Team


What is the standard way of providing a servery busy lockout page when server is overloaded?

Question: We have the need to lockout users from our service when its under load to avoid degraded user experience. We have implemented a very rough and ready version of this by detecting errors or timeouts on ajax requests and displaying a popup saying we are experiencing issues and redirect the user to the lockout page. But I get far too many false negatives on this, and just refreshing the page cause the popup to show because the ajax requests are aborted etc.
How do websites normally go about this sort of stuff? Is it handled server side, client side or by apache etc?
Thanks
Comment: Are you trying to lockout ALL users, or only a portion of them?  Do you are WHICH users get locked out, or is it just any random % of users until the errors stop?
Comment: Ideally we only lock out new users and the users that got through can continue on the server, it would be nice to detect the point just before a server is overloaded so current users aren't effected
Answer: In a heavy duty production environment there will usually be some sort of load balancer in front of the apache server. There are both software and hardware varieties. They can be configured to do a recurring health check on the apache server, and when the server doesn't answer, all new requests can be sent to a separate webserver that only gives the error page.


How to enable Local Machine debug in Visual Studio UWP?

Question: I've downloaded existing UWP project and I wanna to start it on local machine in Visual Studio. But now I only can debug on Device or Remote machine.
How can I add local machine debug mode to the project?
Comment: Did you install Win10 SDK? Otherwise you need to reinstall VS. The `Local Machine` option is listed in debug option.
Comment: @Vincent yes, Windows 10 SDK (10.0.18362.0) is installed. There isn't `Local Machine ` in debug option.
Comment: If you create a new blank uwp app, can it run on local machine? In addition, are you building x86 or ARM?
Comment: @Faywang-MSFT I've changed building platform from ARM to x64 in exiting project and `Local Machine` option appears. Thanks!
Answer: When You build for ARM, then it can only run on an ARM device, so it only shows the Device or Remote machine options. If you want to debug the project on local machine, you can click the drop down to build x86 or x64.


Should we document AJAX-callback parameters?

Question: Considering the PHPCS warning:

phpcs: Hook implementations should not duplicate @param documentation

Is there any way to tell PHPCS that the function is an AJAX-callback (so that such warnings are generated)?
Or, Should we document all AJAX-callback parameters, with @param PHPDoc?

Background:
There was a discussion in our company about the below AJAX-callback function:
/**
 * Prevents popup's redirection from dashboard to another link.
 *
 * Users were redirected to another page as soon as the Event-creation
 * popup form was submitted, just added an AJAX handler to submit button
 * which prevents the redirect using ajax,
 * and when there is any error on the form, the message is sent to the popup.
 */
function _MYMODULE_popup_submit(array &$form, FormStateInterface $formState) {
  // ...
}

Where one developer insisted on adding @param PHPDoc comments to each AJAX-callback like:
/**
 * Prevents popup's redirection from dashboard to another link.
 *
 * Users were redirected to another page as soon as the Event-creation
 * popup form was submitted, just added an AJAX handler to submit button
 * which prevents the redirection using ajax,
 * and when there is any error on the form, the message is sent to the popup.
 *
 * @param array &$form
 *   All data of the form.
 * @param \Drupal\Core\Form\FormStateInterface $formState
 *   State of the form.
 *
 * @return \Drupal\Core\Ajax\AjaxResponse
 *   Returns the data back as AjaxResponse object.
 */
function _amt_dayview_popup_submit(array &$form, FormStateInterface $formState) {
  // ...
}

And the other considered it as understandable and that it should not be documented:

... remember that PHPCS will warn you every time we use @param on any hook, like "phpcs: Hook implementations should not duplicate @param documentation", and just because PHPCS can not differ AJAX-callback from normal functions it does not mean that we should do this ...

Edit: The feature request is created for this on Drupal.org.
Comment: Custom functions and code that have custom functionality like this should be commented like above. Six months from now no one will remember what it does or why, or that it's specifically for an AJAX callback. As for the params, these are pretty standard for a form submit hook. They aren't necessary here really, but most editors will just add it automatically. Verbose yes, but doesn't hurt much. Perhaps you hire new dev interns someday - it's helpful downstream.
Comment: OK, take your point.
Comment: @Kevin, I found the docs about [Callback definitions and implementation](https://www.drupal.org/docs/develop/standards/api-documentation-and-comment-standards#callback-def) (which suggests "`Implements callback_descriptive_name`"),  but the problem now is that there was nothing like `callback_form_ajax` in any `*.api.php` file !!
Comment: Is "`./modules/custom/MYMODULE\MYMODULE.api.php`" the right place for our own custom callback definitions? because *PHPCS* doesn't seem to recognize any of them.
Comment: Just checked and *PHPCS* even ignores "`Implements callback_batch_finished`" (which is in the "`./core/lib/Drupal/Core/Form/form.api.php`" file), so, this feature seems to be not yet supported by *PHPCS* for now.
Comment: This is not a hook implementation in the sense intended by the documentation. That's only for MYMODULE_name_of_hook or MYTHEME_name_of_hook functions. So if you write an implementation of hook_entity_access, for example, you do not document its parameters.
Comment: Callbacks are not hook implementations, even though their parameters are documented somewhere else. And they do not belong in your api.php file.
Comment: @AlfredArmstrong, Please read the docs which I [linked above](https://www.drupal.org/docs/develop/standards/api-documentation-and-comment-standards#callback-def), you will see they are clearly about **`callback`** (not hook, although they are near each other), and of course, they do not belong in my personal `*.api.php` file, but that is just a workaround to prevent copy/paste until Drupal's own `*.api.php` files are more complete.
Answer:
Is there any way to tell PHPCS that the function is an AJAX-callback (so that such warnings are generated)?

Yes, it's as simple as implementing hooks except that instead of "Implements hook_", it starts with "Implements callback_".
The only problem is that currently (August 2019) it is not supported by Drupal's PHPCS standard and you don't get any warnings yet.

Or, Should we document all AJAX-callback parameters, with @param PHPDoc?

That too is an option, for your newly hired dev interns, but especially when there was no official definition in any existing *.api.php file and when you do not want to write your own *.api.php file.
Source:
In Drupal's Official-documentation of August 2019, we can find below Callback implementation:
/**
 * Implements callback_batch_finished().
 */
function _node_mass_update_batch_finished($success, $results, $operations) {
  // …
}

Note: Unlike hooks any callback starts with an underscore (i.e. it is "_MYMODULE_descreptive_name").

Callback definition example:
In our case, because Drupal's own *.api.php files did not cover AJAX-callbacks, we added our own *.api.php file to prevent copy/paste until Drupal's own *.api.php files cover that section as well, something like below:
<?php

/**
 * @file
 * Callbacks and hooks related to MYPROJECT system.
 */

/**
 * @addtogroup callbacks
 * @{
 */

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Form\FormStateInterface;

/**
 * Callback for AJAX events.
 *
 * AJAX callback functions can be used to update existing or
 * add new form fields, update values in form fields and more,
 * while users can still interact with the form.
 *
 * @param array &$form
 *   All data of the form.
 * @param \Drupal\Core\Form\FormStateInterface $formState
 *   State of the form.
 *
 * @return \Drupal\Core\Ajax\AjaxResponse
 *   Returns the data back as AjaxResponse object.
 */
function callback_form_ajax(array &$form, FormStateInterface $formState) {
  // Here we do something meaningful with the results.
  $response = new AjaxResponse();
  $response->addCommand(new HtmlCommand('#message-box', 'my message.'));
  return $response;
}

/**
 * @} End of "addtogroup callbacks".
 */

/**
 * @addtogroup hooks
 * @{
 */

/* Place any hook definitions here. */

/**
 * @} End of "addtogroup hooks"
 */

Callback implementation example:
/**
 * Implements callback_form_ajax().
 *
 * Prevents popup's redirection from dashboard to another link.
 *
 * Users were redirected to another page as soon as the Event-creation
 * popup form was submitted, just added an AJAX handler to submit button.
 * which prevents the redirect using ajax,
 * and when there is any error on the form, the message is sent to the popup.
 */
function _amt_dayview_popup_submit(array &$form, FormStateInterface $formState) {
  // ...
}


Selecting address records within a range in IBM SQL

Question: I am working with SQL via IBM's iNavigator.  I have the following query:
SELECT
PWGEOADDR AS ADDRESS,
POSSTR(PWGEOADDR, ' ')-1 AS FIRSTWORDCHARS,
SUBSTR(PWGEOADDR, 1, POSSTR(PWGEOADDR, ' ')-1) AS HOUSECHAR,
INTEGER(SUBSTR(PWGEOADDR, 1, POSSTR(PWGEOADDR, ' ')-1)) AS HOUSENUMBER
FROM DSDLIB.PWPPERMITS

In my results pane, I see results like this:
ADDRESS                 FIRSTWORDCHARS   HOUSECHAR             HOUSENUMBER
----------------------------------------------------------------------------
1730 West 800 South    4                 1730                           1730
273 E Heather Road     3                 273                             273
56 N State Street      2                 56                               56
2080 S. Main           4                 2080                           2080
Across Oakcrest Dr.    6                 Across               ++++++++++++++
123 North Main         3                 123                             123

The + characters are literal characters I see in the SQL window.  I copied and pasted them as-is.
My problem is this: I cannot query ADDRESS records that have a HOUSENUMBER in a given range, such as BETWEEN 30 AND 50.  I want to ignore rows that cannot be successfully cast.  Whenever I add a WHERE statement that compares the result of the CAST to ANYTHING, I get the following error from the AS/400:
SQL State: 22023
Vendor Code: -802
Message: [SQL0802] Data conversion or data mapping error.
Cause . . . . . :   Error type 6 has occurred.

Error types and their meanings are:
1 -- Arithmetic overflow.

2 -- Floating point overflow.

3 -- Floating point underflow.

4 -- Floating point conversion error.

5 -- Not an exact result.

6 -- Numeric data that is not valid.

7 -- Double-byte character set (DBCS) or UTF-8 data that is not valid.

8 -- Division by zero.

9 -- Hash value cannot be computed for the requested query.

10 -- User-defined function returned a mapping error.

11 -- Not valid length found in a varying-length column returned from an array result set.

12 -- Result of a concatenation operation on a varying-length field exceeded the maximum allowed length of the result type. If the error occurred when assigning a value to a host variable of a FETCH, embedded SELECT, SET, or VALUES INTO statement, the host variable name is *N and the relative position of the host variable in the INTO clause is 0. If the host variable name is *N, the error occurred when attempting to resolve a search condition. If more than one data mapping error occurred, this is a description of the first error that occurred.  For a description of any other data mapping errors, see the previously listed messages in the job log. Recovery  . . . :   The error was caused by data that was not valid or that was too large.  Look at the previously listed messages in the job log (DSPJOBLOG command) or press F10 (Display messages in job log) on this display to determine what row and columns were involved in the error.  Correct the data and then try the request again.

What I've already tried is comparing the CAST against NULL, SNAN, INFINITY, and ++++++++++++++.
Answer: I think the following will work.  This tests to see if the first word is a number by eliminating the numbers in the word (using translate()) and checking the length of the string.  The result is then turned into an integer:
SELECT PWGEOADDR AS ADDRESS, POSSTR(PWGEOADDR, ' ')-1 AS FIRSTWORDCHARS,
       SUBSTR(PWGEOADDR, 1, POSSTR(PWGEOADDR, ' ')-1) AS HOUSECHAR,
       (case when LENGTH(RTRIM(TRANSLATE(SUBSTR(PWGEOADDR, 1, POSSTR(PWGEOADDR, ' ')-1), '*', '0123456789'))) = 0
             then INTEGER(SUBSTR(PWGEOADDR, 1, POSSTR(PWGEOADDR, ' ')-1))
        end) AS HOUSENUMBER
FROM DSDLIB.PWPPERMITS;

For use in a where clause, you would want to make this a subquery:
select t.*
from (SELECT PWGEOADDR AS ADDRESS, POSSTR(PWGEOADDR, ' ')-1 AS FIRSTWORDCHARS,
             SUBSTR(PWGEOADDR, 1, POSSTR(PWGEOADDR, ' ')-1) AS HOUSECHAR,
             (case when LENGTH(RTRIM(TRANSLATE(SUBSTR(PWGEOADDR, 1, POSSTR(PWGEOADDR, ' ')-1), '*', '0123456789'))) = 0
                   then INTEGER(SUBSTR(PWGEOADDR, 1, POSSTR(PWGEOADDR, ' ')-1))
              end) AS HOUSENUMBER
      FROM DSDLIB.PWPPERMITS
     ) t
where housenumber between 10 and 15;

Comment: Thank you for pointing me in the right direction.  My final query is as follows, where I perform a TRANSLATE using the asterix character, but also pad it with the asterix character.  I then compare the asterix string against a REPEAT of asterix's.  The query is as follows:
Comment: SELECT * FROM
    (SELECT
    PWPERMIT,
    PWGEOADDR AS ADDRESS,
    CHAR(SUBSTR(PWGEOADDR, 1, POSSTR(PWGEOADDR, ' ')-1), 10) AS HOUSECHAR,
    (CASE WHEN REPEAT('*', LENGTH(SUBSTR(PWGEOADDR, 1, POSSTR(PWGEOADDR, ' ')-1)))=TRANSLATE(SUBSTR(PWGEOADDR, 1, POSSTR(PWGEOADDR, ' ')-1), '*', '0123456789','*')
      THEN INTEGER(SUBSTR(PWGEOADDR, 1, POSSTR(PWGEOADDR, ' ')-1))
    END) AS HOUSENUMBER,
    CHAR(TRANSLATE(SUBSTR(PWGEOADDR, 1, POSSTR(PWGEOADDR, ' ')-1), '**********', '0123456789','-'), 10) AS STARS
    FROM DSDLIB.PWPPERMITS
    ) AS PERMITS
    WHERE
    HOUSENUMBER < 100


Problema para alinhar horizontalmente layout responsivo usando Bootstrap

Question: Agora com o cabeçalho deu certo. Preciso criar uma segunda ROW (linha)
Ela sera 4|4|4 e deverá ter uma imagem, e as outras 2 partes de texto.
Porém tenho 2 dúvidas. A primeira é, não sei o que faço para que a imagem fique menor que o tamanho original (por exemplo: uma imagem 1920x1080 fique ocupando o espaço de 200x200px) e seja responsiva.
A outra dúvida é que o texto fique alinhado ao lado dela como no Cabeçalho o formulario de busca e o texto LOGOUT ficaram:
Segue o código abaixo:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"/>
    <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>

                    <form class="navbar-form" role="search">

                            <input type="text" class="form-control" placeholder="Search" name="q">

                                <button class="btn btn-default" type="submit">

                                </button>

                    </form>

LOGOUT

 TEXTO DIV 5 a 8

 TEXTO DIV 9 A 12

Answer: Para deixar suas imagens responsivas usando o padrão do bootstrap, você pode usar a classe "img-fluid" ficando assim:

E para modificar o tamanho você pode forçar via css, assim:
img {width: 200px; height: 200px;}

Sobre o outro ponto, você precisa falar pra div que ela é um container, dessa forma:

Asssim, diferente da div de cima, essa será encaixotada, se quiser fluída também, basta adicionar o container-fluid, mas de qualquer forma, pra usar a estrutura do bootstrap, você precisa informar qual quer usar.
Maiores informações veja:
https://getbootstrap.com/docs/4.1/content/images/#responsive-images


Restrict a role in postgres to access some schemas in a database and don't list any other databases

Question: I'm using PostgreSQL 8.3 under ubuntu 9.04. I access my database server using a console client or Pgadmin III.
Currently, I need to restrict access to only a couple of schemas in a database and also don't show other databases in the server.
For example, my current postgres server has the following databases:
postgres-8.3-server
|-- db1
|   |-- sch_a
|   |-- sch_b
|   |-- sch_c
|   `-- sch_d
|-- db2
|   |-- sch_e
|   |-- sch_f
|   `-- sch_g
`-- db3
    `-- sch_h

I need to restrict role "joe" to access only db2's sch_e and shc_g, and also don't show the other schemas in the same database.
When listing databases the output should be:
postgres-8.3-server
|-- db2
    |-- sch_e
    `-- sch_g

My current solution restricts schema and database access but I can still see the database name list. When I try to access any of them (except the one I'm allowed to) I receive a message about a specific entry not found at pg_hba.conf file, which is good but not ideal.
I'm currently checking the manual and googling for more information.
Thanks in advance
Answer: You can't restrict the ability to see which databases exist. Why does that matter, though, since you can restrict the ability to connect?
If you prefer a different error message, you might try letting people through pg_hba.conf and then restricting the CONNECT permission on the database itself (REVOKE CONNECT ON DATABASE foo FROM public; GRANT CONNECT ON DATABASE foo TO somerole;")
Comment: Thanks Magnus. The databases names are important because they have client names appended to them. Restricting database access with pg_hba.conf and the revoking connect are great but only gives database level restriction. Is there a way to restrict visibility per schema? To only list some "visible" schemas that the user (role) has privileges.


Evaluating a seemingly simple integral

Question: I'm trying to evaluate the following integral, which arised while attempting to find the sum of a series :
$$\int_{0}^{1} \frac{\ln(x)}{x-1} \ln(1+\sqrt{x})\text{d}x$$
I've tried unsuccessfully some substitutions, integration by parts, feynman integration... I'm not familiar with more advanced integration techniques like residues theorem etc. ,so maybe that's the way to go.
Any hint, solution or partial solution would be nice !
Comment: *Mathematica* gives the value $$\frac{1}{4}(\pi^2 \log 4 - 9 \zeta(3)),$$ which suggests that one might be able to rewrite the integrand in a clever way, but I don't have a solution at this time.
Comment: Not relevant, but this integral is not "simple" at the first glimpse…
Comment: @heropup. What is funny is that the antiderivative seems to exist in terms of polylogarithms. Would you check that Mathematica gives it ? Thanks.
Comment: When I saw the zeta(3) in the value you just gave me, I immediatly thought that there's ought to be some trilogarithm hidden in there... Thank you by the way. I don't have a mathematica lisence though, and wolfram is unable to proceed it
Comment: @ClaudeLeibovici Yes, it does, but it is quite lengthy and its evaluation at the endpoints requires some delicacy as it appears to involve taking limits.  I think an approach specific to the definite integral is more likely to be fruitful.
Answer: You can reduce your integral to two integrals which have already been solved on this site:
Let $x=t^2$, perform a partial fraction decomposition and integrate by parts in the second integral to find
\begin{align}
I &\equiv \int\limits_0^1 \frac{-\ln(x) \ln(1+\sqrt{x})}{1-x} \, \mathrm{d}x \\
&= 4 \int \limits_0^1 [-\ln(t) \ln(1+t)] \frac{t}{(1-t)(1+t)} \, \mathrm{d}t \\
&= 2 \int \limits_0^1 \frac{-\ln(t) \ln(1+t)}{1-t} \, \mathrm{d} t - 2 \int \limits_0^1 \frac{-\ln(t) \ln(1+t)}{1+t} \, \mathrm{d} t \\
&= 2 \int \limits_0^1 \frac{-\ln(t) \ln(1+t)}{1-t} \, \mathrm{d} t - \int \limits_0^1 \frac{\ln^2 (1+t)}{t} \, \mathrm{d} t \\
&\equiv 2 I_1 - I_2 \, .
\end{align}
In this question $I_2 = \frac{\zeta(3)}{4}$ is proved (FDP's answer does not use contour integration or the polylogarithm). $I_1 = \frac{\pi^2}{4} \ln(2) - \zeta(3)$ is derived here (the answer relies on contour integration though and it would be nice to have a simpler proof). Thus we obtain the result suggested in the comments:
$$ I = 2 \left(\frac{\pi^2}{4} \ln(2) - \zeta(3)\right) - \frac{\zeta(3)}{4} = \frac{\pi^2}{2} \ln(2) - \frac{9}{4} \zeta(3) \, . $$

Evaluating a seemingly simple integral


Runge-Kutta method to numerically solve a second order non-linear differential equation - Octave

Question: So I have this analytically unsolvable non-linear second order differential equation:
x''=(-1/x)((x')²+gx-gh+ax')
to which I've been trying to apply the Runge-Kutta method in Octave for a while without getting good results. This is the code I've been using:
graphics_toolkit('gnuplot')

to=0
tf=2.8
N=150
dt=[tf-to]/N

b=2.65
g=9.81
h=0.07

y(1)=0.015
z(1)=0
t(1)=to
for i=1:N-1
  y(i+1)= y(i) - dt.*z(i)
  z(i+1)= z(i) - dt.*[z(i).**2 + g.*y(i) - g.*h + b.*z(i)]./y(i)
  t(i+1)= t(i) + dt
endfor

plot(y,t)
title=('Numerical solution')
xlabel=('Time')
ylabel=('Position')

Frankly, I'm unable to tell where the issue is, maybe there's something about the method I'm not getting, or maybe is my code missing something important.
Thanks for your time and attention.
Answer: The realization of
y' = z

in the Euler method is
  y(i+1)= y(i) + dt.*z(i)

note the addition instead of the subtraction.
Comment: Indeed that solved my problem, thank you very much!


How to extract base64 src from a video using just Javascript?

Question: With we have a mp4 file how can we create a base64 src from it using just javascript?
For example, if he have a mp4 file named example.mp4 located at /assets/video/example.mp4, how can extract the base64 data from it using Javascript to create a html tag like the example below?
<video id="video" width="740" controls>
  <source type="video/mp4" src="data:video/mp4;base64,[VIDEO BASE64 DATA HERE]">
</video>

Instead of this:
<video id="video" width="740" controls>
  <source type="video/mp4" src="/assets/video/example.mp4">
</video>

The motivation to do this is because I need to transfer a encrypted file (for example a video, or a image, etc.) from one place to another. So I need using Javascript, extract the data, encrypt it and then transfer. How can we do this?
Comment: I wouldn't do that with JS... JS really isn't made to handle things like that.
Comment: What do you mean by encrypt/decrypt? Why can't the file just stay encrypted for the transferral?
Comment: The user will indicate the file, browsing it. The file will not be encrypted, it will be encrypted after this.
Answer: This is probably an answer, but I didn't tested yet: (MooTools)
http://jsfiddle.net/eliseosoto/JHQnk/

        Choose or drag a file:

        <input type="file" id="filePicker">

Base64 encoded version

        <textarea id="base64textarea" placeholder="Base64 will appear here" cols="50" rows="15"></textarea>

var handleFileSelect = function(evt) {
    var files = evt.target.files;
    var file = files[0];

    if (files && file) {
        var reader = new FileReader();

        reader.onload = function(readerEvt) {
            var binaryString = readerEvt.target.result;
            document.getElementById("base64textarea").value = btoa(binaryString);
        };

        reader.readAsBinaryString(file);
    }
};

if (window.File && window.FileReader && window.FileList && window.Blob) {
    document.getElementById('filePicker').addEventListener('change', handleFileSelect, false);
} else {
    alert('The File APIs are not fully supported in this browser.');
}

Answer: Have you been able to adapt that code so that it is not necessary for a user to give a file?
This is, to be able to encode like you initially wanted, by knowing the location of the file and do that automatically, without intervention from the user.


How to make a forest plot with Excel?

Question: A friend of mine asked me on how to do it in excel, and after playing with it a bit (and googling it) I gave up.
Does any one have a suggestion on how it might be done?
Answer: This web page ("Forest plots : Introduction and explanation") explains how to draw simple forest plots in MS-Excel.
Is your friend conducting a meta-analysis? In that case s/he might be interested in the following two pages:

MIX 2.0 - Meta-Analysis made easy
MetaEasy Excel add-in
Comment: Thanks for the links Bernd.  The first link I found by myself but was not able to reproduce the example.  The other links might be worthwhile exploring - thanks.
Answer: Excel gets a bad rap (I suspect because of those horrible 3d graphs and inappropriate pie charts), but this is fairly easily accomplished in Excel charts. It simply takes knowing how to arrange elements on the chart.
This example by Jon Peltier on how to make box plots in Excel can be very easily adapted to forest plots. In fact he has a free utility to make error bars, although doing it yourself is not all that difficult.
If you plan on doing work in Excel and that involves making charts, it would do everyone good to peruse the work on Jon's blog.
Answer: Or alternately Forest Plot Viewer http://ntp.niehs.nih.gov/index.cfm?objectid=52A197EE-F1F6-975E-7D16E68BE5E723A5 , which while being a stand-alone program is free, and probably less stress than wrestling with Excel.
Comment: Not the answer to the question - but still a good answer:  +1
Comment: Thanks :) The hope was indeed to provide resources for the future, as the question seemed to be answered already.
Answer: I had the same question a while back and ended up writing a article explaining some of it.

Neyeloff, JL, Fuchs, SC, & Moreira, LB (2012).  Meta-analyses and Forest plots using a microsoft excel spreadsheet: step-by-step guide focusing on descriptive data analysis.  BMC Research Notes, 5:52.

Here is the sample Excel file from the article with the forest plot.

How to make a forest plot with Excel?


Select element after an element with a particular child

Question: Consider this HTML:

Foo

Bar

Baz

Is there any way in CSS to select "the p element after a p element containing a br element"?
I know I can fall back to using JavaScript for this, but I was curious to see if there was some funky combination of sibling selectors, or some magical pseudoclass I'm yet to come across.
Comment: In case you're interested, [here's a deep dive into how parent selectors play into this and the unidirectionality of Selectors](https://stackoverflow.com/questions/28708741/how-do-i-select-an-element-based-on-the-state-of-another-element-in-the-page-wit/28793064#28793064) despite what it might seem.
Comment: NB: Sure a parent selector could work, but not exactly what I'm asking here. Parent selectors are slightly against the grain of CSS, which only ever acts in a single direction down the DOM. In my case, the element I want to act on is still after all the other things I need to know about, so there would be no need to go back up the DOM or perform a second pass, etc.
Comment: it is still called a *parent selector* ... you want to look what is inside your element, so you need to first go down then go up again, which is actually not possible with CSS (read the duplicate and you will find that you need the `:has()` selector) ... basically you want this : start from `br`, check if the parent is `p`, if yes selector it then select the `p` after it .. which is the same as : select the `p` that contains the `br` then select the p after it
Comment: Yeah. I guess I was more fishing for if I'd missed something like `:blank` that would have solved this, but I guess it's back to JS then.
Answer: In this given code
`Foo

Bar
Baz`
If you want to select the 3rd p then you can use a Pseudo Class :nth-child()
So the answer would be p:nth-child(3)
If these p tags are inside a container than use that as combinator for the desired result otherwise it would select all the 3rd p tags in the html document