send REQUEST_URI with header location redirect via settings.php

Question: I'm in predicament where I must use settings.php to do what I'd normally just do via mod_rewrite... the site is being hosted on Pantheon and I am referring to this article: http://helpdesk.getpantheon.com/customer/portal/articles/368354
I need to send the original requested path for reference. Trying to pass a the SERVER_URI as a parameter via header location in setting.php gets me an infinite loop.
My code:
if (preg_match('/article\/[0-9]?[0-9]\/[0-9]?[0-9]\/[aA-zZ].+/', $_SERVER['REQUEST_URI'])) {
    header('HTTP/1.0 301 Moved Permanently');

    header("Location: http://answers3x-ec-core-community.gotpantheon.com/catchall/?dest=" . urlencode($_SERVER["REQUEST_URI"]));  exit;
}

Anybody have any suggestions as to how I might accomplish passing the $_SERVER["REQUEST_URI"] via header location from settings.php without an infinite loop?
Comment: Change your regex string to start with `/^`. Or maybe `/^\/` depending on your web server setup. That should stop the loop
Comment: Why don't you just use [Path redirect](https://www.drupal.org/project/path_redirect) module? Why does it *have to be settings.php*? Doing it inside PHP I can understand, forcing it into settings when there is perfectly fine, if a bit undermaintained, module seems weird.
Comment: I would use path redirect or similar D7 version, but haven't found one that would work - have custom module intended to catch this 1st redirect to rewrite the path alias using tokens after identifying the old path pattern (which why I need reference REQUEST_URI) and then 2nd redirect to final location.
Comment: D7 version was moved to a new project, my bad. But the link is there on D6 page. Here it is, for future reference: https://www.drupal.org/project/redirect. As far as I remember, it was pretty workable.
Comment: thank you Clive, I at last got chance to test this and it did indeed limit what I needed.
Answer: While it's technically possible to use Drupal contrib to perform the redirect, it's faster and more efficient to redirect without having to fully bootstrap your web application.
For web only actions, like redirects, check for the existence of $_SERVER['PANTHEON_ENVIRONMENT'] - if it exists, it will contain a string with the current environment (dev, test or live).
To perform redirection for the pattern you've supplied, make sure to only match for it at the beginning of the URI in order to avoid an infinite loop problem:
// Pantheon - web only.
if (isset($_SERVER['PANTHEON_ENVIRONMENT'])) {
    // Check if you only want redirection from the live web environment.
    if ($_SERVER['PANTHEON_ENVIRONMENT'] == 'live') {
        if (preg_match('/^\/article\/[0-9]?[0-9]\/[0-9]?[0-9]\/[aA-zZ].+/', $_SERVER['REQUEST_URI'])) {
            header('HTTP/1.0 301 Moved Permanently');
            header('Location: http://answers3x-ec-core-community.gotpantheon.com/catchall/?dest=' . $_SERVER["REQUEST_URI"]);
            exit();
        }
    }
}

Sources:
Configuring settings.php
PHP preg_match() Examples
preg_match
Comment: thanks for the Pantheon details Suzanne - Clive was right on with my need to delimit by caret
Answer: In the end what really I needed to accomplish was a way to grep for a contained (not beginning) directory name in the path that wouldn't bomb into an infinite loop continually calling settings.php. What worked for me was to negate the regex like so:
if(preg_match('/^((?!catchall).)*$/', $_SERVER['REQUEST_URI'])) {

since 'catchall' is the directory I am redirecting to including the old path as a parameter, it allows for the redirect to get to this page (and custom module to handle it) without an infinite loop. I basically surrounded the above check first around all preg_match checks for the particular patterns I needed to find.


How do I limit the number of columns of a basic table field?

Question: I have a basic table field.
I only need three columns but it displays more.
How do I limit it to three?
And how do I set the width of the columns?
Answer: If you have a 600 pixel wide field named "Data" with tab delimited data;
set the tabStops of field "Data" to "200,400,600"

will set the column widths.  The last tab stop at 600 throws any content beyond the third column outside of the visible area of the field.
Answer: set the tabStops of fld "Data" to 100,0,150,0,0

will hide column 2 and 4, 5, 6, ..., n.
If you want to hide the column, set it's width to 0. If the last parameter is 0 then the rest of columns will be not visible, and it'll be missing vertical line of last visible column. If you want vertical line after last field, add additional 0 [set ... to 100,0,200,0,0]
Comment: `set the tabStops of fld "Data" to 200,100,50, 0` gives three columns of the width 200, 100 and 50. Thank you.
Comment: I prefer this answer because I do not need to add up the columns widths and I do not need to be concerned about the width which is used to display the grid.


How to determine if a matrix is a subspace of M_2x2 and provide its basis?

Question: This is a question from my linear algebra homework that I don't really understand, so I'm not completely sure how to ask a good question about it.

Let  $$ \{A \subset \mathcal{M}\ _{2x2} :
  \begin{bmatrix}
    1\\
    2
  \end{bmatrix} \subset \mathbf{N} (A) \}
 $$ Determine if $A$ is a subspace of $\mathcal{M}\ _{2x2}$ and, if it is, find a basis.

I'm not really sure where to start at all, so any hints about how to think about it and get started would be really helpful.
Answer: Hint
Write $$A=\begin{pmatrix}a_{11}&a_{12}\\a_{21}& a_{22}\end{pmatrix}.$$
Now, $$\begin{pmatrix}1 \\ 2\end{pmatrix}\in N(A)\iff \begin{pmatrix}a_{11}&a_{12}\\a_{21}& a_{22}\end{pmatrix}\begin{pmatrix}1 \\ 2\end{pmatrix}=\begin{pmatrix}0 \\ 0\end{pmatrix}.$$
So, $$a_{11}+2a_{12}=a_{21}+2a_{22}=0.$$ That is
$$A=\begin{pmatrix}-2a_{12}&a_{12}\\-2a_{22}& a_{22}\end{pmatrix}.$$
Can you find now a basis?
Comment: Let's call by W the set. Is the zero matrix in W? Is the sum of two matrices in W an element of W? Is it the product of a scalar and a matrix in W still in W?
Comment: How do I determine if it is a subspace of M_{2x2}?


Export to PDF script only exports the last worksheet

Question: I have an Excel VBA script that exports the contents of a worksheet to PDF. It worked fine with a single worksheet, but now I've been asked to have it include a second worksheet. However, using the script below now only includes the second worksheet and not the first. Can anyone advise why the first worksheet of the pair is not included?
Dim sheetsToPrint as Variant(1)
sheetsToPrint(0) = FirstWorksheet.Name
sheetsToPrint(1) = SecondWorksheet.Name

FirstWorksheet.PageSetup.PrintArea = Union(FirstWorksheet.Range("B2:I10"), FirstWorksheet.UsedRange).Address

With FirstWorksheet.PageSetup
    .LeftMargin = Application.InchesToPoints(0.75)
    .RightMargin = Application.InchesToPoints(0.75)
    .TopMargin = Application.InchesToPoints(1)
    .BottomMargin = Application.InchesToPoints(1)
    .HeaderMargin = Application.InchesToPoints(0.5)
    .FooterMargin = Application.InchesToPoints(0.5)
    .PrintHeadings = False
    .PrintGridlines = False
    .PrintComments = xlPrintNoComments
    .PrintQuality = -4
    .CenterHorizontally = False
    .CenterVertically = False
    .Orientation = xlPortrait
    .Draft = False
    .PaperSize = xlPaperA4
    .Order = xlDownThenOver
    .BlackAndWhite = False
    .Zoom = False
End With

SecondWorksheet.PageSetup.PrintArea = Union(secondPage.Range("B2:I10"), secondPage.UsedRange).Address

With SecondWorksheet.PageSetup
    .LeftMargin = Application.InchesToPoints(0.75)
    .RightMargin = Application.InchesToPoints(0.75)
    .TopMargin = Application.InchesToPoints(1)
    .BottomMargin = Application.InchesToPoints(1)
    .HeaderMargin = Application.InchesToPoints(0.5)
    .FooterMargin = Application.InchesToPoints(0.5)
    .PrintHeadings = False
    .PrintGridlines = False
    .PrintComments = xlPrintNoComments
    .PrintQuality = -4
    .CenterHorizontally = False
    .CenterVertically = False
    .Orientation = xlPortrait
    .Draft = False
    .PaperSize = xlPaperA4
    .Order = xlDownThenOver
    .BlackAndWhite = False
    .Zoom = False
End With

saveAndClose sheetsToPrint

The saveAndClose function is defined like this:
Private Sub saveAndClose(ByRef sheetsToPrint() As Variant)

    Sheets(sheetsToPrint).Select

    Dim primarySheetName As String
    primarySheetName = CStr(sheetsToPrint(0))

    Application.DisplayAlerts = False
            ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=outputDirectoryPath & ":" & primarySheetName & ".pdf"
            Sheets(sheetsToPrint).Delete
    Application.DisplayAlerts = True

End Sub

This is part of a batch process, so I haven't copied all of my code, but this is the part that currently exports a PDF containing only the information from sheetsToPrint(1) but not sheetsToPrint(0). I've been banging my head on this all afternoon since as far as I can see, it's the same as every example on the internet of how to export multiple sheets to PDF.
Can anyone spot where I've gone wrong?
Comment: I ussualy have trouble working with arrays in VBA, and the problem ussualy dissapears when I use normal variables. Have you tried using variables and calling `saveAndClose` twice instead of once using arrays?
Comment: Thanks for the suggestion @NicholasKemp but I'd like these sheets to be exported into the same PDF file, not two separate ones. Each time this runs, it will be generating one report with two pages.
Answer: Can you set it up like this:
Dim sheetsToPrint As Sheets
Set sheetsToPrint = Sheets(Array("Blad1", "Blad2", "Blad3"))

And then use sheetsToPrint.select in the saveandclose sub
Comment: Isn't that effectively what my current script does? At the point when the PDF if exported, I have already selected the sheets I want to print. I can confirm by throwing in a break point just before the export that the sheets I want are selected. It's just that only one is exported.
Comment: I'm sorry, I thought that the selection went wrong maybe. The only other difference I can find is that in a code I use for a similar function I use `Application.ActiveSheet.ExportAsFixedFormat` instead of only ActiveSheet...


Why does this code that type-checked in GHC 7.10 no longer type check in GHC 8.0.1?

Question: I have the following code:
<code>{-# LANGUAGE DefaultSignatures#-}

import Control.Monad.Trans.Class
import Control.Monad.Trans.Maybe

class Monad m => MonadMaybe m where
  liftMaybe :: Maybe a -> m a
  default liftMaybe :: (MonadTrans t, MonadMaybe m) => Maybe a -> t m a
  liftMaybe = lift . liftMaybe

instance MonadMaybe m => MonadMaybe (MaybeT m)
</code>
Using The Glorious Glasgow Haskell Compilation System, version 18.104.22.16861117, this fails to compile:
<code>foo.hs:11:10: error:
    • Couldn't match type 'm' with 'MaybeT m'
      'm' is a rigid type variable bound by
        the instance declaration at foo.hs:11:10
      Expected type: Maybe a -> MaybeT m a
        Actual type: Maybe a -> MaybeT (MaybeT m) a
    • In the expression: Main.$dmliftMaybe @MaybeT m
      In an equation for 'liftMaybe':
          liftMaybe = Main.$dmliftMaybe @MaybeT m
      In the instance declaration for 'MonadMaybe (MaybeT m)'
    • Relevant bindings include
        liftMaybe :: Maybe a -> MaybeT m a (bound at foo.hs:11:10)
</code>
However in GHC 7.10, this compiles without a problem.
Is GHC 8 correct, or have I found a bug?
Comment: @AlexisKing, that's essentially the issue. Occurrences of the head of the class declaration (here `m`) are always scoped in the body, otherwise there would be no relation between `m` and the type of the methods!
Comment: Your code also typechecks in the stable release of GHC 8.0.1 .
Comment: Out of curiosity, does it work if you change the `m` in the default signature to another type variable, like `n`, or add an explicit `forall`? I'm wondering if GHC is treating `m` as a scoped type variable here for some reason.
Comment: @ReidBarton Right, of course, that makes sense—it seems obvious in retrospect. :)
Answer: Despite GHC 7.10 accepting it, your code actually makes no sense. See https://ghc.haskell.org/trac/ghc/ticket/12784 for discussion.


Creating trigger function in Postgres

Question: I was developing my own customized module in Drupal 7. Is there any way I can create at run-time a trigger function in PostgresSQL? A sample scenario is when after successfully deleting a record in a particular table.
Comment: Drupal doesn't offer any helper function for creating database triggers. What you use for that is plain PHP.
Answer: You can use the db_query() function for that:

Executes an arbitrary query string against the active database.

e.g.
db_query('postgres-specific SQL here');

Note: if the DBMS you're connected to at any point isn't pg, and it doesn't understand the statement you're executing, that code will throw an exception. Probably best to catch that and handle if your module needs to be portable.

Creating trigger function in Postgres


About how to calculate prime numbers (additional content: add calculation methods, questions you want to ask, etc.)

Question: Sorry for the previous question. This is my first post and I didn't write anything special because I wasn't sure if it was worth showing to others. Also, since I am not good at English, I use machine translation. Therefore, please forgive me if there are some parts that are unsightly.
This time, I am prepared to be embarrassed as I write the contents. 1 and 5 are the standard. Add 6 to 1 and 5. Then 7 and 11 will appear first. Adding 6 again yields 13 and 17. Adding 6 again yields 19 and 23. Adding 6 again yields 25 and 29. Adding 6 again yields 31 and 35. By repeating this process endlessly, so far only prime numbers up to 527 have appeared based on this law.
The first thing to pay attention to in this rule is 25, 35, etc. These can be calculated by multiplying 5×5 and 5×7 by the prime numbers that appear in the table. The next thing you should pay attention to is 7×7 and 5×11、11×11. These appear in the table as 49, 55, and 121.
All numbers other than prime numbers that appear in the table can be predicted by multiplying the prime numbers that have appeared in the table up to that point. There is also an order in which numbers other than prime numbers appear, so 7x5, then 7x7, then 7x11, then 7x13, then 7x19, etc. Prime numbers greater than 7, such as 11 and 13, are also 11×5, 13×5, 11×7, 13×7 It will appear on the table as 11×11, 13×13, etc.

enter image description here
yellow is for prime numbers.
For colors other than yellow,
for example, red is a multiple of 5,
green is a multiple of 7, etc.
The image is calculated by adding 12 based on 1, 5, 7, and 11. However, this is the same as continuing to add 6 based on 1 and 5 mentioned earlier.
If you look at the image, you will understand that there is a law of appearance for all numbers other than the prime numbers that appear in this table.
I don't think it's necessary to say that 2, 3, and multiples of 2 and 3 are not prime numbers. If the law I described holds true, then by combining it with the law for numbers other than prime numbers that appears in the table earlier, it would be possible to calculate all numbers other than prime numbers. Also, as I mentioned earlier, if a number that shares a rule based on two numbers with different standards is a prime number, then it can be explained to some extent why twin prime numbers exist.
I would like to take this opportunity to explain the following four points.
① If you keep adding 6 to each of 1 and 5 as a standard, only prime numbers and numbers multiplied by prime numbers will appear.
② There is a rule for prime numbers that appear by continuously adding 6 to each of 1 and 5 as a standard, and numbers multiplied by prime numbers.
③ If you remove the numbers that satisfy the rule ② from the numbers that appear according to the rule ①, only the prime numbers will remain.
④ By adding rule ② and multiples of 2 and multiples of 3, numbers other than prime numbers can also be predicted.
I would like to know if the above content has already been published or not. As I mentioned earlier, I don't have enough knowledge to know whether this law has already been discovered or not. I even created a table of the ideas that came to my mind and the things I noticed while looking at the prime numbers in a calculation formula. If this already exists, please laugh at it and dismiss it as nonsense from an ignorant person.
Comment: This is a bit hard to follow.  I believe you have just noticed that every prime $≥5$ is either of the form $6k-1$ or the form $6k+1$. Starting with $5,1$ you will get every prime $≥5$ if you keep adding $6$.  Indeed, you will get every natural number of the form $6k\pm 1$.
Comment: thank you for your reply. So it was very embarrassing. In my ignorance, I didn't even know if this was a known fact. That's why I asked.
Comment: If I can confirm that this is something that everyone knows as common sense, then I think it was worth taking this opportunity to ask, even if I was prepared to be embarrassed.
Comment: Yes, this is well known.  Indeed:  every natural number is of the form $N=6k+r$ for some $r\in \{0,1,2,3,4,5\}$.  Now, if $r\in \{0,2,4\}$ then $N$ is even, hence not prime (if you exclude $N=2$).  If $N=3$, then $N$ is divisible by $3$, hence not prime (if you exclude $N=3$).  That just leaves $r=1$ and $r=5$.  A little work shows that numbers of the form $6n+5$ can also be written as $6k-1$.
Comment: But don't apologize for the question. There's no harm in asking things.
Comment: Thank you for teaching me something very valuable.
This is a shame, but there is something missing from the above explanation.
⑤All numbers other than prime numbers that appear in the table are composite numbers or parallel numbers of the prime numbers that have appeared in the table up to that point, and there are rules for the appearance of composite numbers of prime numbers.
For example, after 7×5, 7×7 appears. There is a rule that the next one is 7x11, the next one is 7x13, the next one is 7x19, the next one is 7x23, the next one is 7x29.
Comment: What I wanted to say was that I was getting carried away thinking that everything could be calculated using the rules ① to ⑤.
And of course everyone knows that much! I am very happy that I was able to reconfirm this fact. I would like to express my gratitude once again. Thank you for your reply.
Comment: I asked ChatGPT about what you taught me, and I was able to understand a little bit. I think it's probably just a little.
My heart goes out to you. I'm glad I asked and received an answer.
I would like to once again express my gratitude. Thank you.
Answer: To summarize the discussion in the comments;
Every prime $≥5$ is of the form $6k\pm 1$, so the process described will certainly hit all the primes other than $2,3$ as it hits every natural number of the form $6k\pm 1$.
To see that every prime $≥5$ is of the form $6k\pm 1$, note that the usual division algorithm with remainder tells us that any natural number $N$ can be written as $6n+r$ for some $r\in \{0,1,2,3,4,5\}$.  Now, if $r\in \{0,2,4\}$, then $N$ would be even, hence not prime (excluding $N=2$). And if $r=3$, then $N$ is divisible by $3$, hence not prime (excluding $N=3$).  Thus if $N$ is prime and $≥5$ we must have $r\in \{1,5\}$.  A little caluclation shows that numbers of the form $6n+5$ can also be written as $6m-1$ (just let $m=n+1$), and we are done.


Understanding a plot of composite numbers against the ordinal position of their prime factors

Question: I was toying with primes factors of natural numbers and I have found a graph which caught my interest but one, which I am struggling to understand better.
Let us take the composite number $N$=391721.

First, find its prime factors which are: 11, 149, 239.
Next, note the ordinal number of each prime factors.  Here for example:

11 is the 5th prime
149 is the 35th prime
239 is the 52nd prime.

Then plot on the x-y plane: for each composite number $N$, Plot $N^{e/\pi}$ on the $x$-axis and the ordinal position of each of its prime factors on the $y$ axis.  So in the example above, I get the three pairs:

x=391721^(E/PI) , y=5
x=391721^(E/PI) , y=35
x=391721^(E/PI) , y=52

This yields the following graph:

So:
x-axis is the natural number line ^ (E/PI)
y-axis is the order of the prime factors
Question:

how do I interpret the graph based on what is known about Prime number distribution.
Is the steepest line observed in the graph the steepest possible line or is this the steepest line observed at this scale
Another way to frame "2" is that is there a known upper bound on (order-of-prime)/numeric-value-of-prime

Thanks.
Comment: What's the E/PI for?  Where do you get the 140 and 229?  What do 5, 35 and 52 have to do with the graph?
Comment: Hi @RobertIsrael, I was trying to get the lines to be as linear as possible so I was trying to pick a ration and I tried E/PI and it seemed to get me the most linear graph.
Comment: @RobertIsrael so the y axis the the order of the prime like 2 is 1, 3, is 2, ..., 11 is 5, 149 is 35, etc. -- I'll update the question with this clarificaiton
Comment: So those y values should be 5, 35 and 52, not 11, 140 and 229?
Comment: @RobertIsrael -- yes to " 5, 35 and 52, not 11, 140 and 229?" -- I just realized my question text was wrong -- corrected -- thanks
Answer: So with $c = e/\pi$ you're plotting $[n^c, y]$ whenever $p_y$ divides $n$, where $p_y$ is the $y$'th prime.
The $k$'th curve from the top comes from the points where $n = k p$ where $p$ is prime (i.e. in the top curve $n$ is prime, in the second it's twice a prime, etc).  Thus this is a plot of $[n^c, \pi(n/k)]$ where $\pi(x)$ is the number of primes $\le x$.  Asymptotically, $\pi(x) \sim x/\ln(x)$, but over the range you're plotting the ratio of this to $x^c$ is not too far from constant.
Comment: Many thanks for the answer Robert -- I'll comeback and try to digest the answer in a bit -- you have to forgive me my math brain cells have been receding for a while


What's the simplest way to create a beanplot in MATLAB?

Question: What is the simplest script for generating a beanplot (see article published in the Journal of Statistical Software) in MATLAB?
Comment: This kind of plot takes a few seconds to make in R, after you've imported your data. Is it important that it's in matlab?
Comment: [Mathworks](http://www.mathworks.co.uk/searchresults/?c[]=entiresite&q=beanplot) seems not to have an entry for `beanplot` or `bean plot`. This is not a good sign.
Comment: a combination of `ksdensity` and `fill` should work.
Answer: I found an excellent series of plot tools on Matlab File Exchange that creates bean plots among several other distribution plots.
http://www.mathworks.com/matlabcentral/fileexchange/23661-violin-plots-for-plotting-multiple-distributions-distributionplot-m
Answer: I know this isn't necessarily what you are looking for, but I suggested to the "improvement request" folks at my work that they ask for variation on the bean plot as option for variability plots in one of MATLAB's competitors.  We are a relatively big customer so a useful proportion of our requests actually do get implemented in the product.  It sometimes takes a year or three before it is rolled out.
I see the bean plot as having good value for EDA in my work environment.  If their competitors have it and their competitors customers are using it for good value then there is incentive for MathWorks to implement it in MATLAB.  Eventually there is good incentive, it takes time.
That is how to make it happen natively inside MATLAB.  That is not how to hack it to work with existing MATLAB methods.
Comment: I agree broadly with your opening statement, but in this case I think the company has used exactly the same name for decades: the prevalence of mutant versions needs another explanation. You're free to regard my edit as trivial or unnecessary just as I am free to prefer a correct name to a slightly incorrect one. I agree strongly that your intended meaning was entirely clear. Intended meanings are often clear but that doesn't rule out edits to clean up small glitches, which is what many of us do.
Comment: @Nick Cox - for five decades it was "MatLab", short for Matrix Laboratory.  It was the successful wrapping of two Fortran Libraries (linpack, eispack?) into a new and marketable product.  The change to "MATLAB" is relatively recent, and likely to be relatively short-lived compared to half a century.  It is a branding change and the market is always in motion.
Comment: The proprietary and registered name is still MATLAB. The website www.mathworks.com uses that name and I see it in the company's documentation. It's clear that the origin is as you describe, as a confection based on two words, and it's most unlikely that an all-caps name would be introduced now. Also, many writers now write Matlab (which I see much more commonly than MatLab, FWIW). But no matter: The principle for CV, I suggest, is that the proprietary names are those most to be respected.
Comment: (Oddly, I am more usually editing the bizarre misspelling STATA, a name not used by its company for 30 years, back to the standard spelling Stata.)
Comment: @NickCox - If we have to go back and edit the content every time the name chances, then in my personal opinion, that introduces more work than it solves.  The purpose of language is to communicate ideas.  In this case, with or without capitalization, the intended audience understood the idea with minimal overhead and thus it achieved its purpose.
Comment: I read http://uk.mathworks.com/company/newsletters/articles/the-origins-of-matlab.html as implying that the name MATLAB has been in use for many years.


Linux, where are the return codes stored of system daemons and other processes?

Question: How do i know, if a process has completed its execution without any errors?
How do i know, if a C++ program has returned success to OS?
If i run it via shell, then i could use $?, however if i am checking the status of a process, initiated by other user, how could i check the status?
Say i started a process in morning, and it got terminated at noon. i have been workign on some other activities till evening, and prior leaving, i would like to check what the processes has returned to OS.  how could i acheve that, programatically. Running through syslog would help, but looking for alternatives.
i could run through the OS's process table and read this information, however it sounds a bit complicated for my requirement. Do we have something like syslog, where all errors of processes are recorded?
Any other ways to retrieve errors reported by terminated processes (of other users too)?
Comment: What about just wrapping the process in a shell script or C program that wrote the information out to the filesystem? You could then modify the calling program to execute the script rather than the process directly. That said, if you don't have those types of permissions that might be difficult.
Comment: I cannot do that for all system processes. Also, i am trying to fetch the return values of processes, which were invoked by other users too. I cant insist all to wrap in a script.
Answer: When a process terminates its parent process must acknowledge this using the wait or waitpid function. These functions also return the exit status. After the call to wait or waitpid the process table entry is removed, and the exit status is no longer stored anywhere in the operating system. You should check if the software you use to start the process saves the exit status somewhere.
If the parent process has not acknowledged that the child has terminated you can read its exit status from the /proc file system: it is the last field in /proc/[pid]/stat. It is stored in the same format that wait returns it, so you have to divide by 256 to get the exit code. Also you probably have to be root.
Comment: IIRC you can read that file if you are the same uid as the process, or `root`.
Comment: You can read the file, but you need an extra permission to see the exit code. See the test that sets `permitted` in the `do_task_stat` function here: https://github.com/torvalds/linux/blob/master/fs/proc/array.c Do you know how to get that extra permission without becoming root?
Comment: I think having the same `uid/gid` automatically grants these permissions; see http://lxr.free-electrons.com/source/kernel/ptrace.c#L225
Comment: I tested it, with my normal user account the exit code is printed as 0 (Ubuntu 13.04). Tracing further into the code it looks like it may depend on having `CAP_SYS_PTRACE` but I haven't confirmed if that's necessary or sufficient.


How to play bass part in Yann Tiersen's "Comptine d'ete no. 2"?

Question: How to play bass part (left hand) in Yann Tiersen's "Comptine d'ete no. 2" piano piece? Here the two sample bars (other bars has similar bass part):

I'm confused in strange notation, look at arrows. Does this mean that I should lift sustain pedal up on this notes?
Answer: When notated like this, it generally means that you will hold down the note with one finger while the other fingers play the 8th notes.  Play the E with your little finger and hold it down, then use your index finger and thumb to play the B, high E, and B. Repeat for the F and so on.  I don't see any pedal markings, so no pedal should be used.
Comment: With the caveat that _touch_ of syncope pedal between the 4th and 5th quavers of the second bar is probably useful to help with the illusion that the low A is a semibreve (seeing how he will actually need to play it as two minims to articulate the second LH figure).


REMOVER PONTOS E VIRGULAS VB.NET

Question: Amigos, o Mysql não grava corretamente os valores com pontos e virgulas no formato de moeda! eu uso VB.net e  preciso de uma função para remover pontos e virgulas, antes de armazenar o valor no banco de dados!!
exemplo: de 1.200,23 para 120023
Ou seja gostaria de usar a mascara de moeda, e usar uma função para remover os pontos e virgulas antes de armazenar o valor no banco de dados!! espero que alguém compreenda meu problema, e me ajude!
Comment: `Replace`? https://docs.microsoft.com/en-us/dotnet/api/system.string.replace?view=netframework-4.8
Comment: Porque você não utiliza o tipo certo, tanto no banco quanto em sua aplicação?
Answer: Você pode fazer o seguinte para remover os pontos e vírgulas.
<code> Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim dblValor As Double = 10000.58

    MsgBox(dblValor.ToString.Replace(",", "")) 'Tira a vírgula
    MsgBox(dblValor.ToString.Replace(".", "")) 'Tira o ponto
End Sub
</code>

REMOVER PONTOS E VIRGULAS VB.NET


What does it mean when during neural network training validation loss AND validation accuracy drop after an epoch?

Question: I have a simple question which I cannot find a straight answer to. I am training a neural network to classify some medical images. I initially focused on validation accuracy after each epoch (to determine how the network was generalising) and then after that, test accuracy on an unseen dataset.
But I see that validation loss is also important - and sometimes my validation loss drops even thought for that epoch, the validation accuracy also goes down slightly. Ultimately test accuracy is going to be the gold standard I guess, but thats no use for guiding training and adjusting parameters. Obviously if the the validation loss starts to go up and validation accuracy starts to drop it indicates overfitting. But what about when both validation loss and validation accuracy drop after an epoch?
Comment: validation loss and validation accuracy are correlated, well, but not perfectly correlated. Perfect correlation is a myth! There could be one off (outlying) sample in your validation set, that shows this.
Comment: Ok, but the question is asking how one might interpret these in terms of which might best reflect generalizability of the algorithm.
Comment: "loss is in your hand" (that's what you are optimizing!). "accuracy is God's business".
Answer: Expanding on my comment, The main goal of your training algorithm is to decrease the net loss. So as long as your validation loss is decreasing, your algorithm is doing good, and is generalizing well. But the validation accuracy is not improving or getting worse, consider relooking at the loss function you are optimizing, it indicates that the loss function is not suitable for the task, rather than training algorithm/model being defective. Go for some other loss function, and then select a model/algorithm that is suitable for that loss function.


Depois da atualização 0.7.0 do firebase_auth não consigo mais fazer login com o Google. Como que prossigo para logar com o google+firebase?

Question: Depois que o usuario usava a opção de login do Google usava esse codigo, mas após atualizar a bibliote do firebase_auth para a versão 0.8.0+1 esse codigo quebrou:
var fUser = await fAuth.linkWithGoogleCredential(
        idToken: userGoogleAuthentication.idToken,
        accessToken: userGoogleAuthentication.accessToken);

e retorna o seguinte erro:
Error: The method 'linkWithGoogleCredential' isn't defined for the class 'FirebaseAuth'.
 - 'FirebaseAuth' is from 'package:firebase_auth/firebase_auth.dart'

Não achei no github da lib como fazer, lá está mo mostrando exatamente como estou fazendo.
Answer: Depois de olhar no código fonte da lib vi que o metodo linkWithGoogleCredential foi substituido por linkWithCredential que recebe um AuthCredential a lib fornece algumas classes que retornam um AuthCredential.
Que são:

GoogleAuthProvider
FacebookAuthProvider
PhoneAuthProvider
EmailAuthProvider
GitHubAuthProvider
TwitterAuthProvider

Agora com a alteração o código ficou assim:
import 'package:firebase_auth/firebase_auth.dart';

var fUser = await fAuth.linkWithCredential(GoogleAuthProvider.getCredential(
            idToken: userGoogleAuthentication.idToken,
            accessToken: userGoogleAuthentication.accessToken));


How can I set pixel value on Magick++ 7?

Question: I'm able to get the values using MagickCore::Quantum, but I'm still not able to set RGB values for a pixel.
Answer: I'm assuming you are getting the pixels into a cache with Magick::Image.getPixels.
After editing the Quantum values, just call Magick::Image.syncPixels to copy the values back.
Magick::Image img("rose:");
// Create cache of pixel data
Magick::Quantum * pixels = img.getPixels(5, 5, 1, 1);
// Set values
Magick::Color green("GREEN");
pixels[0] = green.quantumRed();
pixels[1] = green.quantumGreen();
pixels[2] = green.quantumBlue();
// Copy cache back.
img.syncPixels();
img.write("output.png");

Comment: Thanks, @emcconville!


Formal notation of group count

Question: I want to write down following group count operation. I am creating variable in dataset called countpd equal to count of observation points grouped by variables countid and day. i stands for observation point number. Is logic in the attached equation correct?
$countpd_i=\sum_{i=1}^n \mathbb{1}_{B_j}$
where $B_j = \{ pid=pid_i \wedge day=day_i \}, j=\{1,2,...n\}$
Comment: The image is too small to read the subscript easily, can you edit it into your question as a formula?
Comment: Sure, done. Sorry, at first wasn't aware how editor handles latex expressions.
Answer: Your approach is correct, you can write count in terms of sums of indicator functions, Inverson brackets, or Kronecker deltas. The only problem with your notation is that you index $B_j$ by $j$ and then, inside of your definition $j$ does not appear anywhere, so it is not clear what is the $j$ index. It is hard to suggest better notation without knowing your problem in greater detail, but you would need to tell your readers what $j$ index is about, e.g.
$$
\mathrm{countpd}_{j} = \sum_{i=1}^n  [ \mathrm{pid}_i = \mathrm{pid}_j \,\land\,  \mathrm{day}_i = \mathrm{day}_j ]
$$
Comment: Thank you. Let me make sure that I understand the logic corretly. If I would to apply similar grouping, but on lagged variable $day$ lagged, would following equation be correct?
$countpd_j=\sum_{i=1}^n[pid_i=pid_j \wedge day_i = day_{j+1}]$
Or should I rather specify double indexation given 2 variables tham I'm grouping on like:
$countpd_{p,d}=\sum_{i=1}^n[pid_p=pid_p \wedge day_d = day_{d+1}]$
Comment: @Aleksander I'd rather use the second formulation. In the first one it is unclear that $j+1 = i+1$, i.e. it is a lagged variable. But this *really* depends on your problem and what you are aiming to show. My point is: make the indexing explicit.

Formal notation of group count


Como rodar server com loopback?

Question: Tenho acesso a um projeto backend e gostaria de saber como faço para rodar esse projeto. Ele utiliza loopback e ao ler a documentação do loopback, na instrução 4 diz:

Start the web server.

Qual comando deveria usar no Ubuntu para começar esse webserver com o loopback?
Após rodar o comando npm install -g loopback-clie tentar rodar o sistema com node . ou node server.js aparece esse ERRO no terminal:
Comment: `node server.js` corre o ficheiro, ou queres saber como o ter autónomo para se auto iniciar quando tiver problemas ou o servidor fizer reboot?
Comment: Vê se isto aqui http://loopback.io/getting-started/ e isto https://loopback.io/doc/en/lb3/Running-and-debugging-apps.html ajuda
Comment: @Sergio quando tento `node server.js` aparece a mensagem: _modulos 'loopback' não encontrados_
Comment: Podes colocar o erro na pergunta?
Comment: @Tmc eu instalei o loopback como fala no primeiro link e tentei rodar utilizando o `node .` porém diz que o _módulo 'loopback' não foi encontrados_. Sabe o que pode ser? E eu rodei o comando `npm install -g loopback-cli`
Comment: @Sergio sim, um instante!
Comment: @Sergio pergunta editada!
Comment: Tens esse pacote no `package.json`? Se não faz `npm install --save loopback`. Se tens faz `npm install`.
Comment: @Tmc eu editei a pergunta postando o erro.
Comment: @Sergio eu precisava ter rodado o `npm install` mesmo! Funcionou, obrigado!
Comment: @Tmc funcionou quando li essa perguntar que você mandou, obrigado!
Answer: Como mencionado pelo @Sergio nos comentários, basta executar o seguinte comando:
npm install

Pode ver mais informações no StackOverflow.
Answer: O loopback é uma aplicação em node que utiliza de packages como dependências sendo os mesmos controlados via npm. Sendo assim, a aplicação precisa de suas dependências para ser inicializada.
Para instalar as dependências de uma aplicação em NodeJS, você pode executar o comando npm install, que irá instalar todas as dependências da aplicação.
Ou em caso de produção, recomendo o npm install --production, o que evita a instalação de packages necessários apenas para dev.
Após executar a instalação das dependências, você pode executar a aplicação via node . ou npm start.
Recomendo a utilização do npm start em caso de dev., pois o mesmo pode ter scripts extras para execução correta do mesmo (Você pode analizar isso olhando para package.json, na sessão scripts -> start.

Como rodar server com loopback?


Groovy - How can I compare part of a list to a string

Question: I have a list which contains two types of text. One type is used for authorization while other type is used for all other purposes.
The type used for authorization always uses the same text + some code after it.
I would like to compare content of these two types of text and separate them based on content.
My idea is to look for pattern in authorization type and if it matches the pattern then this would be marked as authorization, otherwise it would be marked as "other".
I researched about comparison of patterns in Groovy, but all variations I tried did not work for me. Here is the part which should do the comparison, I am obviously doing something wrong but I don't know what.
<code>  jdbcOperations.queryForList(sql).collect { row ->
     if(assert (row['MSG'] ==~ /token/)){
  mark as authorization
 }
 else{
      mark as other
    }
  }
</code>
Sorry for the vague code, I can not share more than this.
Comment: I think the problem is in the very first line of your question: why do you have that list mixed together in the first place? That smells of bad design and (since you're talking about authorization) like the recipe of a security problem (when you have false positives or false negatives).
Answer: I think you just missing the match for the rest of the text, since you are looking only for the first part to match.
<code>assert ("abc" ==~ /abc/) == true
assert ("abcdefg" ==~ /abc/) == false
assert ("abcdefg" ==~ /abc(.*)/) == true // <--- This can also be made more complicated
</code>


How to combine confidence intervals for a variance component of a mixed-effects model when using multiple imputation

Question: The logic of multiple imputation (MI) is to impute the missing values not once but several (typically M=5) times, resulting in M completed datasets. The M completed datasets are then analyzed with complete-data methods upon which the M estimates and their standard errors are combined using Rubin's formulas to obtain the "overall" estimate and its standard error.
Great so far, but i'm not sure how to apply this recipe when variance components of a mixed-effects model are concerned. The sampling distribution of a variance component is asymmetrical - therefore the corresponding confidence interval can't be given in the typical "estimate ± 1.96*se(estimate)" form. For this reason the R packages lme4 and nlme don't even provide the standard errors of the variance components, but only provide confidence intervals.
We can therefore perform MI on a dataset and then get M confidence intervals per variance component after fitting the same mixed-effect model on the M completed datasets. The question is how to combine these M intervals into one "overall" confidence interval.
I guess this should be possible - the authors of an article (yucel & demirtas (2010) Impact of non-normal random effects on inference by MI) seem to have done it, but they don't explain exactly how.
Any tips would be much obliged!
Cheers, Rok
Comment: One other thing: i'm not sure that a proper analytical solution to this problem even exists. I've looked at some additional literature, but this problem is elegantly looked over everywhere. I've also noticed that yucel&demirtas (in the article i mentioned, page 798) write:"These multiply imputed datasets were used to estimate the model […] using the R package lme4 leading to 10 sets of (beta, se(beta)), (sigma_b, se(sigma_b)) which were then combined using the MI combining rules defined by Rubin."
Comment: A very interesting question. I look forward to hearing from your results, if you want to share them...
Comment: @chl: I can send you the tables with the results when I'm done, but I won't be inventing anything new really. So far I'm just planning to compare MI under a two-level imputation model (R package pan) to MI under a simple normal model (ignoring the two-level structure, R package norm) and listwise deletion. Under different sample sizes, values of the variance component etc. This should be enough for the seminar (I'm a PhD student), but not exactly groundbreaking. If you have any ideas on how to "jazz up" the simulation study, i'd love to hear.
Comment: It seems they used some kind of shortcut to estimate the SE of the variance component (which is, of course, inappropriate, since the CI is asymmetrical) and then applied the classic formula.
Comment: Ok, thx for that. Can you put your comments into an answer so that it can be voted?
Answer: This is a great question! Not sure this is a full answer, however, I drop these few lines in case it helps.
It seems that Yucel and Demirtas (2010) refer to an older paper published in the JCGS, Computational strategies for multivariate linear mixed-effects models with missing values, which uses an hybrid EM/Fisher scoring approach for producing likelihood-based estimates of the VCs. It has been implemented in the R package mlmmm. I don't know, however, if it produces CIs.
Otherwise, I would definitely check the WinBUGS program, which is largely used for multilevel models, including those with missing data. I seem to remember it will only works if your MV are in the response variable, not in the covariates because we generally have to specify the full conditional distributions (if MV are present in the independent variables, it means that we must give a prior to the missing Xs, and that will be considered as a parameter to be estimated by WinBUGS...). It seems to apply to R as well, if I refer to the following thread on r-sig-mixed, missing data in lme, lmer, PROC MIXED. Also, it may be worth looking at the MLwiN software.
Comment: Thanks a lot for your reply! In principle i'm also interested in how to solve a concrete problem like the one i described (thus thanks for the WinBUGS tip). But at the moment i'm trying to do a simulation study for a seminar paper in which i'd examine the performance (coverage rates etc.) of MI under model misspecification. I suppose i'll just forget about the variance components if I can't find a solution and focus on the fixed effects, but it's frustrating to give up.
Comment: @Rok Great idea for the simulation! I'll look forward for this particular issue. I suppose you already search on the r-sig-mixed mailing and Gelman's book on multilevel regression...
Comment: I looked now, tanks for the references! Unfortunately, there's nothing on MI in the r-sig-mixed archives; and Gelman only gives the basic formula on how to combine inferences from MI when we have variation within and between imputations given (§25.7).
Answer: Repeated comment from above:
i'm not sure that a proper analytical solution to this problem even exists. I've looked at some additional literature, but this problem is elegantly overlooked everywhere. I've also noticed that Yucel & Demirtas (in the article i mentioned, page 798) write:

These multiply imputed datasets were
  used to estimate the model […] using
  the R package lme4 leading to 10
  sets of (beta, se(beta)), (sigma_b,
  se(sigma_b)) which were then combined
  using the MI combining rules defined
  by Rubin.

It seems they used some kind of shortcut to estimate the SE of the variance component (which is, of course, inappropriate, since the CI is asymmetrical) and then applied the classic formula.
Comment: "Elegantly overlooked"... that's a useful phrase for reviewing the literature if ever I've heard one.
Comment: I appreciate you came back to share your experience with this problem. Unfortunately, I have no real solution but maybe other suggestions will come up.
Answer: Disclaimer: This idea might be foolish &  I'm not going to pretend to understand the theoretical implications of what I'm proposing.
"Suggestion"  :  Why don't you simply impute 100 (I know you normally do 5) datasets, run the lme4 or nmle, get the confidence intervals (you have 100 of them) and then:
Using a small interval width (say range / 1000 or something), test over the range of possible values of each parameter and include only those small intervals which appear in at least 95 of the 100 CIs.  You would then have a Monte Carlo "average" of your confidence intervals.
I'm sure there are issues (or perhaps theoretical problems) with this approach.  For instance, you could end up with a set of disjoint intervals.  This may or may not be a bad thing depending on your field. Note that this is only possible if you have at least two completely non-overlapping confidence intervals which are separated by a region with less than 95% coverage.
You might also consider something closer to the Bayesian treatment of missing data to get a posterior credible region which would certainly be better formed & more theoretically support than my ad-hoc suggestion.


Rodar serviço mesmo que o app não esteja aberto

Question: Estou criando um app de despertador e nos testes gostaria que ele despertasse(nesse exemplo ainda apenas vibra), porém não estou conseguindo fazer com que ele rode em background e por isso não acaba despertando, como posso fazer com que mesmo que o app tenha sido destruido ele continue verificando o tempo e se o horario bater então ele se manifeste, do jeito que o código está vejo dois problemas: ele está esperando um certo gatilho para poder ser ativado e acaba não despertando se a tela estiver em sleep mesmo que o app estiver em aberto, e consequentemente não roda a validação da hora se o app estiver encerrado, apenas instalado como um despertador mesmo:
AndroidManifest.xml
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service android:name="com.rafah.screenstate.LockService">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </service>
</application>

MainActivity.class
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //starting the service Class
    startService(new Intent(getApplicationContext(), LockService.class));

   }
}

LockService.class
public class LockService extends Service {

   @Nullable
   @Override
   public IBinder onBind(Intent intent) {
       return null;
   }

   @Override
   public void onCreate() {
       super.onCreate();
   }

   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
       final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
       filter.addAction(Intent.ACTION_SCREEN_OFF);
       filter.addAction(Intent.ACTION_USER_PRESENT);

       //Calling the BroadCast
       final BroadcastReceiver mReceiver = new ScreenReceiver();
       registerReceiver(mReceiver, filter);

       return super.onStartCommand(intent, flags, startId);
   }

   //AINDA NÃO SEI PARA QUE SERVE
   public class LocalBinder extends Binder{
       LockService getService(){
           return LockService.this;
       }
   }

}

ScreenReceiver.class
public class ScreenReceiver extends BroadcastReceiver {

public static boolean wasScreenOn = true;

@Override
public void onReceive(Context context, Intent intent) {
    Log.e("test", "onReceive Broadcast");

    SimpleDateFormat Dformat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    Date date = new Date();

    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    Date data_atual = cal.getTime();
    String sysdate  = Dformat.format(data_atual);

    if (sysdate.equals("03/04/2018 22:09:02")){
        //Vibrate test
        Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(6000);
     }

   }
}

O que eu preciso é que ele vibre no horario pré-programado mesmo o app tenha passado pelo estado destroy.
Comment: Veja a resposta do Ramaral neste link https://pt.stackoverflow.com/questions/281880/alarmmanager-não-executa-no-intervado-configurado .... as vezes responde sua pergunta.
Comment: Veja esta [pergunta](https://pt.stackoverflow.com/q/281750/2541)
Answer: Tente colocar esse atributo na sua tag.
<service android:name="service" android:stopWithTask="true"/>

Comment: A resposta só deve ser fornecida quando se há certeza que ela resolverá a questão, caso contrário use os comentários....
Comment: Andrey, a menos que você mude a configuração do stackoverflow para que eu possa comentar tendo criado minha conta há 15 minutos, vou postar a resposta mesmo. E a solução funcionou para mim.
Comment: Amigo, a menos que vc leia as normas de utilização do SOpt, fica difícil te ajudar. Não estou te criticando, nem negativei sua resposta, apenas lhe mostrando como atuar aqui no site.
E não, você não deve usar subterfúgios para dar um comentário se vc ainda não tem permissão para tal. Aprenda a lidar com críticas construtivas...
Comment: Obrigada, foi muito construtivo.


Need a good reference on Levy-Ito decomposition and martingale spaces

Question: I am currently using Appelbaum but it does not go into too much detail how we deal with the part with small jumps.
Can someone please recommend a good text book? I have Bertoin at my disposal, but I do not see to find anything in the index.
Also an intro of martingale spaces is appreciated. Appelbaum mentioned Rudin.(which rudin's book is it?) Is there any other?
Answer: Lévy Processes and Infinitely Divisible Distributions by Ken-Iti Sato is a great source to Lévy processes and characterizations of such. It describes both the Lévy-Khintchine formula and the Lévy-Itô decomposition.


Drupal admin area and login, Securing them with HTTPS

Question: I've been reading a lot about this and trying many of the methods I've found and haven't yet been able to get anything working properly.
I want to be able to secure the admin area and associated login pages. So anything in example.com/admin/* or example.com/user/* etc, needs to go over SSL/TLS. We'd like this to apply to each site withing the multisite setup. So example1.com, example2.com, example3.com are all on the same server/user account.
The Setup

Drupal 7 multi site
Clean URLs enabled
PHP 5.3
MySQL v14 d5
Apache2

Notes

Securepages is not an option, as there's no stable Drupal 7 release, and using the existing dev version requires patching Drupal Core, which goes against our policy
Have tried Session 443 with no success
Have tried Secure Login with no success
An SSL cert (a self-signed one for now, while testing) is installed and works on the server for other purposes, just not Drupal.
I've read all the docs on Drupal.org about enabling HTTPS and have attempted to follow the directions there with little success
I've toggled the $conf['https'] setting in settings.php with no discernable results.

The Questions
If I enable HTTPS for everything on a site, I get a 404 for anything attempting to go through https://, which leads me to think that the rewrite rules aren't applying for the https pages. What am I missing here? Is there a rewrite condition/rule I can add to htaccess to fix this?
Is this not a solved problem in the Drupal community? Are people just leaving their admin areas unsecured, with user passwords being sent in the clear? I find this hard to believe, yet it seems that there's no built-in or commonly known solution to the problem.
Comment: Probably the best bet is to help test and push the two core patches required towards approval.  They both have updates from this week...
Comment: Good question. You have read this one? http://drupal.stackexchange.com/questions/23149/redirect-user-login-to-https-all-other-requests-to-http
Comment: @undersound Thank you. Yes I have read that one. We're really interested in securing all administrative tasks over HTTPS, not just the sign-in event.
Comment: Drupal should work without a problem on both http and https. I'd guess your problem lies in the Apache configuration (maybe SSL site points to a different DocumentRoot). Could you please post your Apache config and Drupal's .htaccess for further analysis?
Answer: It's not the question you asked, but the simplest answer is you should just change your policy.
"Hacking" core (patching it) and running unstable releases is reality of running a website.
The two patches needed for securepages frequently need re-rolls, reviews, or improvements. Get involved in that cycle and help get them stable.
Answer: I used the following settings pull this off... and didn't need a module to do it.
1) httpd.conf
<code>#APACHE stuff...
Listen 443
NameVirtualHost *:443
Include conf.d/vhosts/*.conf #Need this for multi-site and subdomains

<IfModule mod_header.c>
#enable HSTS
Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains"
</IfModule>

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>
2) conf.d/vhosts/site1.conf
<code><VirtualHost *:443>
#APACHE stuff...
SSLEngine on
RewriteCond %{HTTP_HOST} !^www\. [NC] #Force www... be careful with subdomains
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</VirtualHost>
</code>
3) settings.php
<code>$base_url = 'https://www.example.com';  // NO trailing slash!
</code>
And voooala!! this will make all http traffic travel over https including resources like js and css. If you want subdomains, be sure to add the appropriate ServerAlias directives in the vhosts file(s).
Answer: I use the Ubercart SSL module which is a fantastic module, though it is horribly named. You do not need to be running Ubercart to take advantage of this module which is very stable and easy to use.


Unable to install mysq on ubuntu

Question: I am trying to install mysql on ubuntu using following command.
sudo apt-get install mysq-server.
Then, tried run following command. But, no luck
sudo apt-get update
The above commands are tried with corporate netwrok(office). But, when tried with wifi(through mobile hotspot), it is working fine.
Comment: Maybe because you forgot to type "l" in "mysql"?
Comment: The error messages you're getting are probably more descriptive than just "no luck".  Why do you keep them a secret? :p
Comment: And remember, that you can always run `apt search ` to get a list of installable software from the apt repository. In your case it would be `apt search mysql`.
Answer: Normally, in corporate offices they might block you from installing softwares using firewall. contact your network administrator for help in installing by getting proper permissions.
Answer: It seems you are doing a typo you are typing mysq instead of mysql..
use following command
    sudo apt-get install mysql-server
Hope this helps.

Unable to install mysq on ubuntu


Load JSON data stream from text file into objects C#

Question: I'm using Newtonsoft.Json.Linq and I'd like to load the data into objects (or structs) that I define and put the objects into a list or collection.
Currently I'm pulling out the JSON properties with indexes to the names.
filename = openFileDialog1.FileName;

StreamReader re = File.OpenText(filename);
JsonTextReader reader = new JsonTextReader(re);
string ct = "";

JArray root = JArray.Load(reader);
foreach (JObject o in root)
{
    ct += "\r\nHACCstudentBlogs.Add(\"" + (string)o["fullName"] + "\",\"\");";
}
namesText.Text = ct;

The object is defined as follows, and sometimes the JSON won't contain a value for a property:
class blogEntry
{
    public string ID { get; set; }
    public string ContributorName { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string CreatedDate { get; set; }
}

Comment: Also those properties could be auto properties rather than being backed by a private field.
Comment: The question is how do I put the jSON object into an instance of my object?
Answer: You can deserialize a JSON stream into real objects using the JsonSerializer class.
var serializer = new JsonSerializer();
using (var re = File.OpenText(filename))
using (var reader = new JsonTextReader(re))
{
    var entries = serializer.Deserialize<blogEntry[]>(reader);
}

Answer: You can use JsonConvert.DeserializeObject<T>:
[TestMethod]
public void CanDeserializeComplicatedObject()
{
    var entry = new BlogEntry
    {
        ID = "0001",
        ContributorName = "Joe",
        CreatedDate = System.DateTime.UtcNow.ToString(),
        Title = "Stackoverflow test",
        Description = "A test blog post"
    };

    string json = JsonConvert.SerializeObject(entry);

    var outObject = JsonConvert.DeserializeObject<BlogEntry>(json);

    Assert.AreEqual(entry.ID, outObject.ID);
    Assert.AreEqual(entry.ContributorName, outObject.ContributorName);
    Assert.AreEqual(entry.CreatedDate, outObject.CreatedDate);
    Assert.AreEqual(entry.Title, outObject.Title);
    Assert.AreEqual(entry.Description, outObject.Description);
}


How to identify good tin whistles?

Question: I am planning to buy a tin whistle. However I do not know whether it is proper. I would like to know how I can identify whether a tin whistle is faulty or not. What are the characteristics of a good tin whistle?
Answer: The first thing I'll say is that players of whistles, flutes, bagpipes, and similar instruments have a fabulous forum going at www.chiffandfipple.com. Check out that site, and search through the forum archives. There is also a buyer's guide. It's a few years old, but still useful, and way more detailed than anything I could write.
The single most important thing to look for is a whistle that is in tune with itself as you play a scale. If it isn't, it's not good for anything but a window prop. This can be tested by playing it with a tuner, if your ears aren't up to the task. You can find a tuner app for android of an iphone, or borrow one from just about any musician.
You also need to decide what key. The key in this context means the note that is played when all the finger holes are covered, and varies between instruments. If you want to play Irish stlye music, get a whistle in D. If you are playing with others in some other genre, as them what keys they usually use. If they can't easily answer, just get the D whistle to keep it simple for yourself. A whistle can easily play in its own key, and in a key with one fewer sharps, or one more flat. So a D whistle can play easily in D and G, while a C whistle can play is C and F. C and D whistles are easy to find, anything else is hard. If you are planning to play alone, it doesn't matter.
A whistle that can be tuned is a nice plus, but not essential for a beginner. As you get good enough to play with others, you'll need to be able to tune so that you aren't slightly off key from them, or just be willing to irritate them by playing out of tune. But as a beginner, if you are playing only with yourself, or with someone who can tune to you, you can get by with an untunable, cheap whistle.
Make sure you like the sound of the whistle. If you don't, you won't play it.
Comment: There is a wonderful German site "https://www.tinwhistle.de/" explaining the different types of whistles.

The company produces and sells wonderful whistles and as well provides training material. Great for first experiences.

And by the way you find sound-examples for the different types of whistles.
Answer: There's no such thing. I think the only way you're going to like the sound of a tin whistle straight out of the box is if you're going for a raw, unpolished sound.
You have to file the holes on the tin whistle yourself until you like the sound you get out of them; that's what Chris Collins did. It's kind of like the same situation with toy pianos, you have to take a file to them, too.
Answer: A tin whistle is good if:

the notes 'speak' well
it sounds good (this is subjective)
it plays in tune

The only way to judge that a whistle is good is to have it tested by a competent player. A good quality hand-made whistle will have been tested by the whistle-maker. Cheap whistles will not have been tested and there is always a considerable variation in quality from one instrument to the next. It's often necessary to try several and choose the best one.
Experts can often improve a whistle by tweaking the fipple or the finger holes.

How to identify good tin whistles?


Gray out non-business hours in jQuery week calendar plugin

Question: I am using the jQuery weekcalendar plugin to show a web based calendar with events. How can I gray out non-business hours? The whole row should be gray, when it is out of the business hours:
businessHours: {start: 8, end: 19, limitDisplay: false},

Comment: No the parameter is existing and is set. Now I just want to gray out the non-business hours with CSS.
Comment: Are you saying that product has a parameter named `businessHours` and it is not working? Or that you would like to have such a parameter?
Comment: I see. I guess the easiest way would be to use the "Inspect element" feature in your browser to see what classes the business/non-business hours have set, and then to address those classes using CSS. Do they have classes set? Or some other feature that helps tell them apart?
Answer: First, you need to use global variables for your business hours like so:
var timeStart = 8
var timeEnd = 19

businessHours: {start: timeStart , end: timeEnd , limitDisplay: false},

Then, try adding this to the jquery javascript on document ready (after the calendar is created):
$('.wc-time-slot').each(function(index, element) {
    if (index<6*timeStart||index>=6*timeEnd) {
        $(this).css('background-color','#eee')
    }
});

There are six rows per hour so that's why you're multiplying by 6.
Comment: Genius! Thank you. The bounty is blocked for the next 11h. I will award it when it is not blocked anymore!
Answer: Edit: Incomplete answer. It doesn't highlight the whole row.
Thanks to Phekka I found this in the Inspect element section:
Non-Business-Hours:

Business-Hours:

Answer: It's a little bit hard. I think you have to manage with
td.wc-day-column background properties and add a css3 gradient with calculated pixel or percent value.
Good luck.


GRPC protobuff compiler

Question: Although I followed all the steps of the the GRPC documentation, when I try to compile my proto files  it doesn't work.
by the way when run the command protoc-gen-go, I get the message: command not found.
following it is my .bash_profile
Answer: After trying to find a solution, I discovered that the lines on my .bash_profile, were on a incorrect sequence, following is my bash now:

GRPC protobuff compiler


How do I tell if word frequencies are changing over time?

Question: I have a collection of texts that span about 1000 years. I am interested in the frequency of a particular word in these texts. Specifically, I want to know whether the frequency of the word increased or decreased over time. The challenge is that the frequency of the word varies a lot according to the type of text.
Here is a sample of made-up data:
TEXT   TEXT_TYPE  FREQUENCY_WORD TOTAL_TOKENS DATE_TEXT CENTURY_BIN
Name-1 Diary      10             10000        1600      1
Name-2 History    1              500          1700      2
Name-3 Procedural 15             1000         ?         3
Name-4 Speech     75             100000       1900      4
Name-5 Diary      20             2000         1925      4
Name-6 History    100            5000         1850      3

There are two columns for the date of the texts since in some cases the year of the text is not known although the century or relative date is known. So in the table above the year of the text in row 3 is not known, but it is known that it was composed at some point between the text in row 2 and the text in row 4.

What is the best way to answer the question of whether the frequency of a word is due to time or due to text type?

I first created a mixed-effects regression model with the log frequency (i.e., log(FREQUENCY_WORD/TOTAL_TOKENS) of the word as the dependent variable and DATE_TEXT as the predictor variable with a random intercept for TEXT_TYPE.)
lm(LOG_FREQUENCY ~ DATE_TEXT, data=data)

One problem with this is that I have to throw out the data points for which the date of the text is unknown. I could use CENTURY_BIN as the predictor variable but I will be throwing out a lot of information about the chronology.
I also tried a Poisson regression (and negative binomial) model in which the response variable was the count in the WORD_FREQUENCY column. I used the log of TOTAL_TOKENS as an offset to take account of the differing lengths of the texts:
    glm(formula = FREQUENCY_WORD ~ YEAR + offset(log(SUM_TOKENS)),
        family = "poisson", data = data)

I run into the problem again of not knowing the year for each text and also do not know how to include random intercepts for TEXT_TYPE with a Poisson regression model.

How do I decide whether to model TEXT_TYPE as a covariate or as a mixed effect (random intercept)?

I would be grateful for any advice on how to approach this question.
Answer: You could treat the date variable as interval-censored, see the tag interval-censoring. OK, that concept is most often used with response variables, while date is a predictor in your model. here is a paper about interval censoring in both response and predictors. There is an R package icenReg for interval censoring. You could also, simpler, try to impute some value in the interval.
I would go for your Poisson regression model (or, if necessary, negative binomial).  There are many examples on this site of Poisson regression models with random effects, for instance High GLMER dispersion parameters
It is a strong assumption to assume the effect of YEAR is linear, I would maybe spline that.
Comment: This is very helpful, thank you! After looking into interval-censoring, I think the best way to handle the uncertainty with the dates might be multiple imputation.


Expectation of arrival times

Question:
Let $(N_t)_t$ be a Poisson process with parameter λ = 2. By $τ_k$ denote the time of the k-th arrival (k = 1, 2, . . .), and by $ρ_k = τ_k −τ_{k−1}$ - the interarrival time between the (k−1)th and kth arrival (k = 1, 2, . . .), with $τ_0 = 0$ (as in the construction of Poisson process).
Find the following:
(a) $E(N_3N_4)$
  (b) $E(ρ_3ρ_4)$
  (c) $E(τ_3τ_4)$

I can understand (a), and (b). But, couldn't understand (c).
I collected the following from a friend:
(c)
$
E(τ_3τ_4) \\
= E[τ_3(τ_3+ρ_4)] \\
= E(τ^2_3 + ρ_4) \\
= E(τ^2_3) + E(ρ_4) \\
= (k/\lambda)^2 + 1/ \lambda
$
First of all, is this a correct solution? If not, what is the correct one?
The processing of $τ_3$ doesn't look okay to me.
It seems to me that $ρ_4$ is introduced here because $τ_3$ and $τ_4$ are not independent. Why are not they independent?
Suppose, the 3rd item arrived at 9:05 AM and the 4th one arrived at 9:10 AM. If the process started at 9:00 AM, the 3rd one took 5 minutes and the 4th one took 10 minutes to arrive. How are they not independent?
Answer: $\tau_3$ and $\tau_4$ are not independent because these are arrival times and they proceed additively, i.e. $\tau_4=\tau_3+\rho$. For example, if you know that $\tau_3=20$, it means $\tau_4\geq20$.
$\tau_3$ is Gamma distributed with $(3,\lambda)$ because it is sum of $\rho_1,\rho_2,\rho_3$, which are iid exponentially distributed RVs. In general sum of $\alpha$ iid exponentials is Gamma with $(\alpha,\lambda)$. For a Gamma RV, we have  $E[X^2]=\frac{k+k^2}{\lambda^2}$, so here $E[\tau_3^2]=\frac{12}{\lambda^2}$.
Comment: What are $N_3$ and $N_4$ in this context? I mean what are their relationships with $\tau_3$ and $\tau_4$?
Comment: What is $t$'s relationship with $\tau$?
Comment: Speaking generally, $N_t$ refers to *number of arrivals which occur by time t*. t is just a variable, just like k. And, it's not a random variables. You shouldn't seek for t's relation to $\tau$.
Comment: So, $t$ is just an index, like what we use in programming arrays?
Comment: similar, except that it is continuous. One can say $N_{3.512}$ for example, which will mean the number of events by $t=3.512$.
Comment: You don't even know how much that helped me!!   Thanks man! God bless.

Expectation of arrival times


Variável não definida em Class PHP

Question: Criei uma classe PHP para fazer um update nos dados de um registro em uma tabela no banco de dados mysql:
<?php

class InsertAccess{

public function insert_access($reg){

    require_once('../conn/conecta.php');

    $status = '1';

    try{
        $sql = "UPDATE `tab_login` SET `last_access` = :date_access, `status` = :sts WHERE `registro` = :reg";
        $access = $conecta->prepare($sql);
        $access->bindParam(":reg", $reg, PDO::PARAM_STR);
        $access->bindParam(":date_access", date('Y-m-d H:i:s'), PDO::PARAM_STR);
        $access->bindParam(":sts", $status, PDO::PARAM_STR);
        $access->execute();

    }catch (Exception $ex){
        echo 'ERRO: '.$ex;
    }
  }
}
?>

Está me dando uma mensagem de variável não definida:
Notice: Undefined variable: conecta in C:\wamp64\www\my_dir\actions\class_access.php on line 13

Alguém pode me dizer qual a forma correta de se usar uma classe php para realizar esse tipo de ação?
conecta.php
try {
    $servidor = 'localhost';
    $usuario  = 'root';
    $senha    = '';
    $banco    = 'my_db';

    $conecta = new PDO("mysql:host=$servidor;dbname=$banco", $usuario , $senha, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
    $conecta->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch(PDOException $e) {
    echo 'ERRO DE CONEXÃO: ' . $e->getMessage();
}

Chamada da função
$access_class = new InsertAccess();
$access_class->insert_access($item);

A classe InsertAccess é um arquivo php separado, sendo que estou utilizando-a em outro arquivo php fazendo a instância como mostrado acima.
Comment: O que tem nesse require no início do método?
Comment: @rray Arquivo que faz a conexão com o banco de dados utilizando PDO.
Comment: Com certeza essa váriavel não está declarada no conecta.php
Comment: **CONECTA**
`$conecta = new PDO("mysql:host=$servidor;dbname=$banco", $usuario , $senha, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));`
`$conecta->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );`
Comment: @Henqsan Esse código (acima) é todo o conteúdo do aroquivo `conecta.php`?
Comment: @ValdeirPsr editei a pergunta e inclui o código todo do conecta.php
Comment: @Henqsan Substitua `echo 'ERRO DE CONEXÃO: ' . $e->getMessage();` por `die('ERRO DE CONEXÃO: ' . $e->getMessage());`, faz mais sentido. Aparece algum erro de conexão ao acessar o método da classe `InsertAccess`?
Comment: @ValdeirPsr não há erro de conexão.
Comment: Por que criar uma classe que serve só para executar um insert no banco?
Comment: @GuilhermeCostamilam, achei melhor fazer dessa forma, uma vez que posso reutilizar a classe.
Comment: Você poderia fazer apenas uma função sem a classe, conhece o padrão DAO?
Comment: @GuilhermeCostamilam, na verdade não sou expert em php, mas vou dar uma pesquisada sobre o padrão DAO.
Answer: Problema apresentado na questão foi resolvido utilizando ao invés de require_once() o require():
class InsertAccess{

public function insert_access($reg){

require('../conn/conecta.php');

$status = '1';
$data_access = date('Y-m-d H:i:s');

try{
    $sql = "UPDATE `tab_login` SET `last_access` = :date_access, `status` = :sts WHERE `registro` = :reg";
    $access = $conecta->prepare($sql);
    $access->bindParam(":reg", $reg, PDO::PARAM_STR);
    $access->bindParam(":date_access", $data_access, PDO::PARAM_STR);
    $access->bindParam(":sts", $status, PDO::PARAM_STR);
    $access->execute();

}catch (Exception $ex){
    echo 'ERRO: '.$ex;
}
}
}

Agradeço a todos pelo ponto negativo na questão e pela extrema e gratificante ajuda.

Variável não definida em Class PHP


Erro: Most Middleware em app nodejs

Question: Executando aplicação nodejs. recebi esse erro:
executei minha aplicação com o comando node app.js
Versões:
node: 8.9.2
npm: 5.5.1
express: 4.15.5

Código app.js:
/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');

//load customers route
var customers = require('./routes/customers');
var app = express();

var connection  = require('express-myconnection');
var mysql = require('mysql');

// all environments
app.set('port', process.env.PORT || 4300);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());

app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

/*------------------------------------------
    connection peer, register as middleware
    type koneksi : single,pool and request
-------------------------------------------*/

app.use(

    connection(mysql,{

        host: 'localhost',
        user: 'root',
        password : '',
        port : 3306, //port mysql
        database:'nodejs'

    },'pool') //or single

);

app.get('/', routes.index);
app.get('/customers', customers.list);
app.get('/customers/add', customers.add);
app.post('/customers/add', customers.save);
app.get('/customers/delete/:id', customers.delete_customer);
app.get('/customers/edit/:id', customers.edit);
app.post('/customers/edit/:id',customers.save_edit);

app.use(app.router);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

codigo custumer.ejs
<%- include layouts/header.ejs %>

           <button onClick="addUser();">+ Add</button>

                    No
                    Name
                    Address
                    Phone
                    Email
                    Action

                <% if(data.length){

                 for(var i = 0;i < data.length;i++) { %>

                    <%=(i+1)%>
                    <%=data[i].name%>
                    <%=data[i].address%>
                    <%=data[i].phone%>
                    <%=data[i].email%>

                        <a class="a-inside edit" href="../customers/edit/<%=data[i].id%>">Edit
                        <a class="a-inside delete" href="../customers/delete/<%=data[i].id%>">Delete

            <% }

             }else{ %>

                    No user

            <% } %>

<%- include layouts/footer.ejs %>

codigo do costumer.js
/*
 * GET customers listing.
 */
exports.list = function(req, res){
  req.getConnection(function(err,connection){

     connection.query('SELECT * FROM customer',function(err,rows)     {

        if(err)
           console.log("Error Selecting : %s ",err );

            res.render('customers',{page_title:"Customers - Node.js",data:rows});

         });

    });

};
exports.add = function(req, res){
  res.render('add_customer',{page_title:"Add Customers-Node.js"});
};
exports.edit = function(req, res){

  var id = req.params.id;

  req.getConnection(function(err,connection){

     connection.query('SELECT * FROM customer WHERE id = ?',[id],function(err,rows)
        {

            if(err)
                console.log("Error Selecting : %s ",err );

            res.render('edit_customer',{page_title:"Edit Customers - Node.js",data:rows});

         });

    });
};
/*Save the customer*/

    exports.save = function(req,res){

        var input = JSON.parse(JSON.stringify(req.body));

        req.getConnection(function (err, connection) {

            var data = {

                name    : input.name,
                address : input.address,
                email   : input.email,
                phone   : input.phone

            };

            var query = connection.query("INSERT INTO customer set ? ",data, function(err, rows)
            {

              if (err)
                  console.log("Error inserting : %s ",err );

              res.redirect('/customers');

            });

           // console.log(query.sql); get raw query

        });
    };/*Save edited customer*/
    exports.save_edit = function(req,res){

        var input = JSON.parse(JSON.stringify(req.body));
        var id = req.params.id;

        req.getConnection(function (err, connection) {

            var data = {

                name    : input.name,
                address : input.address,
                email   : input.email,
                phone   : input.phone

            };

            connection.query("UPDATE customer set ? WHERE id = ? ",[data,id], function(err, rows)
            {

              if (err)
                  console.log("Error Updating : %s ",err );

              res.redirect('/customers');

            });

        });
    };

    exports.delete_customer = function(req,res){

         var id = req.params.id;

         req.getConnection(function (err, connection) {

            connection.query("DELETE FROM customer  WHERE id = ? ",[id], function(err, rows)
            {

                 if(err)
                     console.log("Error deleting : %s ",err );

                 res.redirect('/customers');

            });

         });
    };

Comment: Qual a versão do express?
Comment: A última versão. Baixei ontem.
Answer: A mensagem de erro já diz tudo, o middleware não está mais disponível nativo no express e deve ser instalado separadamente. Acredito que esteja indicando devido o uso do logger aqui app.use(express.logger('dev')), o que você pode fazer é usar um logger separado.
Exemplo com express 4:
Instalar
npm install morgan

Uso
var logger = require('morgan');
app.use(logger('dev'));

Comment: Fiz a instalação porém o erro continua...
Comment: a mensagem agora: like json is no longer bundled with Express
Comment: agora o erro é outro: Most middleware (like urlencoded) is no longer bundled with Express and must be installed separately.
Comment: quais os pacote que tenho de instalar ?
Comment: Segue os exemlos do link que passei para Express 4, ali tem a forma certa do `urlencoded`, e caso apareça outros vai substituindo conforme o que estiver lá.

Erro: Most Middleware em app nodejs


dkim signature not present or bad format

Question: I'm going mad with dkim-filter + postfix. My message are signed but Gmail notify me errors like "dkim=neutral(no signature)" or "dkim=neutral(bad format)"
I don't know what is wrong. I've generated public and private key, and I'm using the right selector.  My dns entry looks like that:
default._domainkey.accessdev-mail.com.       IN TXT   "v=DKIM1; g=*; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDaSlf0l7scGWVaOlPlPX4C8Mce
v3C7QpDBdwcJ+rw36GVlcJaJ2QU2yfh/VXr81DhmNbmBGyCH8EzK/FT42vAw7rp3
NqnEH9DFNDx7SDVql/liDKKSBWDfZu+QjhU4qPdEuL8bZ0EW3wTmAc2WNnQY7M+t
A8ryjVM7qonJLY78YwIDAQAB"

Comment: Note that if you send the e-mails out via PHP mail() this could be causing trouble as well. Unfortunately I cannot remember exactly what fixed it and the server I used it on does not exist any longer.
Comment: If accessdev-mail.com is your real domain, your DNS is in bad shape. The DNS servers according to `whois` are `SD2.ACCESS-DEV.FR` which returns no results for any queries (including SOA) about the accessdev-mail.com domain, and `SDNS2.OVH.NET` which I can't seem to get that TXT record from.
Answer: first. are you using yours DNS server or some VPS? there were trables that IPS DNS servers makes yours IN TXT entry to lowercase.
second. try to remove g=*
Check yours TXT records from outside your server,some external resource
Comment: I m on a dedicated server , not VPS. my dns server is bind9 , i removed g=* but still the same problem (bad format)
Comment: look like yours provided info is right. try to recreate yours keys private and public
Comment: Can you check yours dns records from external source with dig or nslookup by txt fields?


Register an object with the Service Container and give it a setRequest() (get base url)

Question: I'm looking for a way to get the hostname of a multisite, and I've found several answers about it.
One of the solutions was to use:
Answer link
$host= \Drupal::request()->getHost();

  or
\Drupal::request()->getSchemeAndHttpHost();

Per also a user comments that the use of the Request object can be dangerous, as mentioned in the following link.
The comment warning say: Url to documentation

Note: The use of this wrapper in particular is especially discouraged.
  Most code should not need to access the request directly. Doing so
  means it will only function when handling an HTTP request, and will
  require special modification or wrapping when run from a command line
  tool, from certain queue processors, or from automated tests.
If code must access the request, it is considerably better to register
  an object with the Service Container and give it a setRequest() method
  that is configured to run when the service is created. That way, the
  correct request object can always be provided by the container and the
  service can still be unit tested.
If this method must be used, never save the request object that is
  returned. Doing so may lead to inconsistencies as the request object
  is volatile and may change at various times, such as during a
  subrequest.

I have a custom module and I have a service, is it possible to implement it in a service?
My question is according to the comment and recommendation of the API, how is it that it should be implemented?
Thanks.
Comment: The `ViewExecutable` class follows that pattern. The factory service (`ViewExecutableFactory`) instantiates a View object based on the current HTTP request (from the injected request_stack service), and passes it through to the View. I would go with that approach
Answer: Here's an example (extracted from real code I just wrote in for Drupal 10.1) of getting the current request from the request_stack service in a plugin. Another service would just be wired into your module.services.yml instead of using the create() method:
<?php

namespace Drupal\my_module\Plugin\MyPlugin;

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;

class MyPlugin extends implements ContainerFactoryPluginInterface {

  /**
   * Resoruce Manager service.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * {@inheritdoc}
   */
  public function __construct(RequestStack $requestStack,
                              array $configuration,
                              $plugin_id,
                              $plugin_definition) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->requestStack = $requestStack;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $container->get('request_stack'),
      $configuration,
      $plugin_id,
      $plugin_definition
    );
  }

  function doSomething() {
    $request = $this->requestStack->getCurrentRequest();
    ...
  }

}

And here's the Symfony documentation that basically says the same thing.


What is the difference between NFI and IR?

Question: Lawrence Tynes was placed on the non-football injury (NFI) list by the Tampa Bay Buccanneers due to a staph infection he claims he got at their training facilities. They are paying his salary, but he does not accrue a year for retirement.
Why would the team do this instead of putting him on injured reserve (IR)? He is getting paid.
Comment: In Tynes's case, IR suggests his MRSA infection was the fault of the Buccaneers. http://profootballtalk.nbcsports.com/2013/08/31/buccaneers-to-put-lawrence-tynes-on-nfi-with-pay/
Answer: They likely put him on the NFI so that he could possibly return to the team if the MRSA infection clears up (as well as possible legal reasons).  Being put on IR ends your season since you cannot participate in any games (regular or post season).  The NFI is most similar to the PUP list.  This link explains how NFI and PUP are different than IR: http://en.wikipedia.org/wiki/Physically_unable_to_perform.


You are given distances between $A$ and $B$ at different coords of $A$. How do I find the coords of $B$?

Question: It's not as easy as it sounds.
Basically I can move $A$ and check the distance to $B$.
However there is a $\pm0.015$ error range , in other words if the real distance is $0.29$, it will get rounded to $0.3$.
So the possible values are : $0.03$, $0.06$, $0.09$ and so on
I tried drawing two circles and finding the intersection but the thing in the square root is negative. I assume this is because of the rounding - the circles don't actually overlap.
Is there a method to find the coords of $B$ given the error margin?  (note the coords need to be accurate in a circle of $0.05$ around the real coords)
I can move $A$ at any point I want and get the rounded distance - can I increment until the value changes and derive the actual real distance from that?
Answer: For each point $A$ that you choose, you get a ring of thickness 0.3. Your problem is that even if two such rings intersect, their approximating circles don't always intersect.
But this only happens if the two rings graze each other (either internally or externally). If each ring passes through the other ring completely, into its interior, then the approximating circles will always intersect (in two points).
To make sure this happens, you want to choose your first point $A_1$ to be far enough away from $B$ that the ring has a large interior -- say, a distance of 5 or more. Of course you don't know where $B$ is, but if your first choice is too close, just choose another point at a distance of 10 from the first-choice point.
Suppose the resulting distance is $d$. Now choose your second point $A_2$ at a distance $2d$ from $A_1$. If the distance from $B$ to this new point is too close to $d$ or $3d$, then the two rings will graze (or almost graze, which is bad because the intersecting regions are too long); so choose another point at the same distance from $A_1$, but in a direction at right angles to the original direction.
Now your two approximating circles will intersect cleanly in two points. To find out which of them approximates $B$, just choose your third point $A_3$ to be one of these two points.
Comment: Thanks Tony , but that would be way to complicated to implement. If it rounds up , can I find a real value of the distance? I.E if it skips from 0.03 to 0.06 then I just crossed 0.015 right? Is that true and can I then use the cosine rule or something to find the coords? I tried but it seems the resulting values do not form a triangle...
Comment: Way too complicated?! I give up...
Comment: Sorry if I haven't made it clear , I will need to program this. I'm a student and I've never done anything regarding rings and I have a bit of trouble understanding your method...Either way , thanks for your time.
Comment: I've given you an explicit algorithm. I urge you to take the trouble to understand it! Draw some pictures if it helps.


addEventListener code is not working after i added click too

Question: var numofDrumButton = document.querySelectorAll(".drum").length;

for (var i = 0 ; i<numofDrumButton; i++){

  document.querySelector(".drum")[i].addEventListener("click", function() {

     var audio = new Audio("sounds/tom-1.mp3");
     audio.play();

  });
}

Answer: Change your code to this:
var drumButton = document.querySelectorAll(".drum");
for (var i = 0; i < drumButton.length; i++){
   drumButton[i].addEventListener("click", function() {
      var audio = new Audio("sounds/tom-1.mp3");
      audio.play();
   });
}

You have to use the same variable in the for loop :)
Comment: thank you Shannon. But what did i do worng?
Comment: You used a different variable inside of the for loop than the one in for `(var i = 0 ; i Statement 1. Ask any questions if you are unsure. Also, please accept my answer if I helped you.


Time series with SARIMA, how to understand the right seasonality parameter

Question: I'm on my way learning the Time series forecast, but have some doubts.

As for the ARIMA model, parameters like the p, q can be inferred from the ACF and PACF plotting.
As for d, this work in combination with the degree of differencing. And, unless I misunderstand, can be left to 0 if the dataserie is already differenced before (e.g. data.diff())

More or less, with the approach above, I am getting decent outputs, but still not very close.
The best I was able to get using the SARIMA model, but I couldn't really find any decent explanation on how to seek for the parameters.
So the logic I used (whether correct or wrong, please tell me) is to use the p parameter as usual, but move the q to Q.
Then, there is the s parameter, which more or less I pick in relation of the data. With daily data, I normally look at the peaks and then use a multiple of 7 according to the best performance.
But what for the weekly aggregated data? I had an instance of a dataset where the resulting RSME was getting better only with parameter like p=46 that doesn't sound normal.
Can you please feed me in with some explanation or guide(s) I can use to fill the gaps?
Below there are the initial ACF and PACF plots, for which a p=46 and q=8 demonstrate better prediction than a p=1 and q=8.

Thanks
Answer: The simplest way of detecting seasonality is to look for repeated patterns in the ACF/ PACF function, in combination with domain knowledge. For example, a time-series with hourly resolution and daily seasonality (i.e. 24 hours) will show spikes (with exponential decay) at lags 24, 48, 72, etc. I think the correct way to model this is first to model the seasonal component, then examine ACF/ PACF for remaining autocorrelations.
Forecasting: Principles and Practices is a great introductory textbook, accompanied by the forecast package in R. This includes the auto.arima() function, which will automatically find a good (S)ARIMA model to fit your data based on some in-sample criterion such as Akaike's Information Criterion.


How does the log zeta function turn into an integral involving J(x)

Question: After using the Euler Product formula for the Riemann zeta function and taking the log on both sides and expanding using the Taylor series of log, this sum comes out and is fairly well known:
$$\log\zeta(s) = \displaystyle\sum_p\sum_n\frac{1}{n}p^{-ns} = \sum_p\sum_n\frac{1}{n}s\int_{p^n}^\infty x^{-s-1}dx = s\int_0^\infty J(x)x^{-s-1}dx$$
Where
$$J(x) = \displaystyle\sum_n \frac{1}{n}\pi(x^{\frac{1}{n}})$$
Where $\pi(x)$ is the prime counting function and the sums are carried out for p prime. My question is where the second integral from 0 to inf comes from and how the 2 sums got absorbed into it and somehow the inclusion of the J function.
Comment: Any function $f(x)=\sum\limits_{n=1}^x a(n)$ can also be evaluated as $f(x)=\sum\limits_{n=1}^\infty a(n)\ \theta(x-n)$ and $s \int\limits_0^\infty \theta(x-n) \ x^{-s-1}\, dx=n^{-s}$, so term-wise integration leads to $F(s)=s \int\limits_0^\infty f(x) \ x^{-s-1}\, dx=\sum\limits_{n=1}^\infty a(n)\,n^{-s}$. If $f(x)$ corresponds to Riemanns prime-power counting function $J(x)$ (also referred to as $\Pi(x)$), then $F(s)$ corresponds to $\log\zeta(s)$ and the result is valid for $\Re(s)>1$.
Comment: For the case $f(x)=J(x)$ the coefficient corresponds to $a(1)=0$ and $a(n)=\frac{\Lambda(n)}{\log n}$ for $n>1$ where $\Lambda(n)$ is the Von Mangoldt function (see https://en.wikipedia.org/wiki/Von_Mangoldt_function), so the Dirichlet series may be evaluated as $\log\zeta(s)=\sum\limits_{n=2}^\infty \frac{\Lambda(n)}{\log n}\,n^{-s}$ which is valid for $\Re(s)>1$.
Comment: Thanks for the replies, I stumbled across something similar but slightly different after going down a rabbit hole of the big pi function. $\displaystyle \sum_{n=1}^\infty a_n n^{-s} = s\int_1^\infty (\sum_{n \le x} a_n) x^{-s-1}$ Is what I found and I did some manipulation using the double sum to get $\displaystyle s\int_1^\infty \bigg(\sum_{n}\sum_{p^n\le x}\frac{1}{n}\bigg) x^{-s-1}$ where the double sum is the big pi function. Not sure if this is entirely correct but it seems to work
Comment: The Heaviside step function can be defined as $\theta (x)=\left(\left\{\begin{array}{cc}
 0 & x<0 \\
 1 & x\ge0 \\
\end{array}\right.\right)$, so $s \int\limits_0^\infty \theta(x-n) \ x^{-s-1}\, dx=s \int\limits_n^\infty x^{-s-1}\, dx=n^{-s}$.
Comment: Since $f(x)=\sum\limits_{n=1}^x a(n)=0$ for $x<1$, $F(s)$ can be evaluated as $F(s)=s \int\limits_1^\infty f(x)\ x^{-s-1}\, dx$ (the lower integration limit can be changed from $0$ to $1$). But $\Pi(x)=\sum\limits_{n=2}^x \frac{\Lambda(n)}{\log(n)}=0$ for $x<2$, so in this case $\log\zeta(s)$ can be evaluated as $\log\zeta(s)=s \int\limits_2^\infty \Pi(x)\ x^{-s-1}\, dx$ (the lower integration limit can be changed to $2$).
Comment: The double sum $\Pi(x)=\sum\limits_{k}\sum\limits_{p^k\le x}\frac{1}{k}$ is sometimes written more compactly as $\Pi(x)=\sum\limits_{p^k\le x}\frac{1}{k}$ where $p$ is a prime and $k$ is a positive integer which is equivalent to $\Pi(x)=\sum\limits_{n=2}^x \frac{\Lambda(n)}{\log n}=\sum\limits_{p^k\le x} \frac{\log(p)}{\log(p^k)}=\sum\limits_{p^k\le x} \frac{1}{k}$ since $\log(p^k)=k\,\log(p)$.
Comment: The Mellin transform of $f(x)$ is defined as $\mathcal{M}_x[f(x)](s)=\int\limits_0^{\infty} f(x)\, x^{s-1} \, dx$, so $\log\zeta(s)$ is $s$ times the Mellin transform of $\Pi(x)$ evaluated at $-s$:  $\log\zeta(s)=s\, \mathcal{M}_x[\Pi(x)](-s)=s\, \int\limits_0^{\infty } \Pi(x)\, x^{-s-1} \, dx$.
Comment: Thanks for clearing this up, I thought that there was something related to the mellin transform, but couldnt find it.
Answer: It's a consequence of the following general fact:

Theorem: Let $a_n$ be some sequence of complex numbers and
$$
A(x)=\sum_{n\le x}a_n.
$$
Then
$$
F(s)=\sum_{n\ge1}{a_n\over n^s}=s\int_1^\infty{A(x)\over x^{s+1}}\mathrm dx.
$$
whenever both side converges absolutely at some $s$ on the right half plane.

To prove this, notice that Riemann-Stieltjes integration gives
$$
\sum_{n\le T}{a_n\over n^s}
=\int_{1^-}^T{\mathrm dA(x)\over x^s}
=A(T)T^{-s}+s\int_1^T{A(x)\over x^{s+1}}\mathrm dx.
$$
Since $F(s)$ converges absolutely at $s$, we know for sure that $\sum_{n\le x}|a_n|=o(x^{\Re(s)})$, which indicates that $A(T)=o(T^{\Re(s)})$. Consequently, making $T\to\infty$ gives the desired result.
To answer the question, we just need to notice that when
$$
a_n=
\begin{cases}
1/k & n=p^k, p\text{ prime},\\
0 & \text{otherwise},
\end{cases}
$$
we have
$$
\sum_{n\le x}a_n=\sum_{k\ge1}\sum_{p\le x^{1/k}}\frac1k=\sum_{k\ge1}{\pi(x^{1/k})\over k}=J(x)
$$
and
$$
\sum_{n\ge1}{a_n\over n^s}=\sum_p\sum_{k\ge1}{1\over kp^{ks}}=\sum_p\log{1\over1-p^{-s}}=\log\zeta(s).
$$
Comment: $\sum\limits_{n\ge1}{a_n\over n^s}$ "converges absolutely at $\Re(s)>0"$?
Comment: @StevenClark I just edited the answer. I was trying to say the series converges absolutely at some complex number $s$ with its real part $>0$.