Convert multipage PDF to PNG and back (Linux)

Question: I have a lot of PDF documents that I want to convert to PNG, edit in Gimp, and then save back to the multipage Acrobat file.  I'm filling out forms and adding scanned signature, trying to avoid printing, signing, then scanning back in, with the ability to type the information I need to enter.
I've been trying to use Imagemagick to convert to png files, which seems to work fine.  I use the command   convert -quality 100 -density 300x300 multipage.pdf single%d.png
(I'm not really sure if the quality parameter is right for png).
But I'm having problems with saving back to PDF.  Some of the files have the wrong page size, and I've tried every command and procedure I can find, but there are always a few odd sizes.  The resolution seems to vary so that it looks good at a certain zoom level, but either a few pages are specified at about 2" wide, or they are 8.5x11 but the others are about 35" wide.  I've tried making sure Gimp had the canvass size and resolution correct, and to save the resolution in the file, but that doesn't seem to matter.
The command I use to save the files is convert -page letter -adjoin single*.png multipage.pdf   I've tried other parameters, but none seemed to matter.
If anyone has any ideas or alternatives, I'd appreciate it.
Comment: I think you can edit the PDFs directly with GIMP.
Comment: If what you want to do is add a signature image as a overlay to the pdf page, you can do with that with some of the pdf tools without converting to png.
Comment: @Blender: Gimp imports PDFs, but doesn't actually save to PDF; it will, on Linux at least, print to PDF, but only single images, not the multi-page PDFs that I desire.
Comment: @Dan D: I need to add signature and date, and it needs to be in different locations on each file, not at all similar.  But if you know of other tools that might work well, I'd like to know about them.
Answer:
"I'm not really sure if the quality parameter is right for PNG."

For PNG output, the -quality setting is very unlike JPEG's quality setting (which simply is an integer from 0 to 100).
For PNG it is composed by two single digits:

The first digit (tens) is (largely) the zlib compression level, and it may go from 0 to 9.
(However the setting of 0 has a special meaning: when you use it you'll get Huffman compression, not zlib compression level 0. This is often better... Weird but true.)
The second digit is the PNG data encoding filter type (before it is compressed):

0 is none,
1 is "sub",
2 is "up",
3 is "average",
4 is "Paeth", and
5 is "adaptive".

In practical terms that means:

For illustrations with solid sequences of color a "none" filter (-quality 00) is typically the most appropriate.
For photos of natural landscapes an "adaptive" filtering (-quality 05) is generally the best.

"I'm having problems with saving back to PDF. Some of the files have the wrong page size, and I've tried every command and procedure I can find [...] but either a few pages are specified at about 2" wide, or they are 8.5x11 but the others are about 35" wide."

Not having available your PNG files, I created a few simple ones with different dimensions to verify the different commands (as I wasn't sure myself any more). Indeed, the one you used:
convert -page letter -adjoin single*.png multipage.pdf

does create all PDF pages in (same) letter size, but it places my sample of (differently sized) PNGs always on the lower left corner of the PDF page. (Should a PNG exceed the PDF page size, it does scale them down to make them fit -- but it doesn't scale up smaller PNGs to fill the available page space.)
The following modification to the command will place the PNGs into the center of each PDF page:
convert           \
  -page letter    \
  -adjoin         \
   single*.png    \
  -gravity center \
   multipage.pdf

If this is still not good enough for you, you can enforce a (possibly non-proportional!) scaling to almost fill the letter area by adding a -scale '590!x770!' parameter (this will leave a border of 11 pt at each edge of the page):
convert              \
  -page letter       \
  -adjoin            \
   single*.png       \
  -gravity center    \
  -scale '590!x770!' \
   multipage.pdf

To leave away the extra border, use -scale '612!x792!'. -- Should you want only upward scaling to happen if required while keeping the aspect ratio of the PNG, use -scale '590<x770<':
convert              \
  -page letter       \
  -adjoin            \
   single*.png       \
  -gravity center    \
  -scale '590<x770<' \
   multipage.pdf

Comment: Thanks.  I'm just starting my vacation now, but when I get back, I'll try out some of your suggestions and see how they work, but you deserve an upvote for the effort even if it doesn't work. :)
Comment: Heh :-) -- But I'm pretty sure that it works. If only I'd always get upvotes 'for the effort', I'd be rich man by now  :-)
Answer: Why not just use Xournal? That's what I use to annotate PDFs
Comment: Thanks, the reason I don't use it is that I never heard of it before.  It sounds promising, though, and I will definitely look into it when I get back from my vacation.  I'll revisit this topic in a couple of weeks.


Generating a sample from Epanechnikov's kernel

Question: So I am really struggling with this problem and could use some help.
Consider the Epanechnikov kernel given by
$$f_e(x)=\frac{3}{4}\left( 1-x^2 \right)$$
According to Devroye and Gyorfi's "Nonparametric Density Estimation: The $L_1$ View", to generate a sample of a distribution having $f_e$ as its density function we can use the following method (see p.236):

Generate iid $U_1$,$U_2$,$U_3$ ~ Uniform(-1,1).
If $\left| U_3\right| \geq \left| U_2\right|$ and $\left| U_3\right| \geq \left| U_1\right|$, deliver $U_2$; otherwise deliver $U_3$.

I have to prove this works. I thought this was related to either the acceptance-rejection method or maybe order statistics. I have spent a fair bit of time trying both approaches but I am stuck. Any pointers will be greatly appreciated.
Comment: A very quick indication, for I am in a hurry: the probability of not being the highest $|U_i|$ and less than $u$ is proportional to$$\mathbb{P}(U\le u)-\frac{1}{3}\mathbb{P}(U_{(3)}\le u)=u-\frac{u^3}{3}$$whose derivative gets you $f_e(u)$.
Comment: Note that - like many of Luc's books that are out of print - the book is available in pdf form from his luc.devroye.org web page.
Comment: An accept-reject algorithm would simulate $U,V\sim\mathcal{U}(0,1)$ and take $X=\pm U$ if $V\le U^2$. Else it would repeat the simulation.
Answer: Consider this alternative description of the same algorithm:

Generate iid $X_1, X_2, X_3$ with Uniform$(0,1)$ distributions.
Select one of the two smallest of the $X_i$ at random, with equal probability.  Call this value $X$.
Randomly negate $X$ with probability $1/2$.

Parts (1) and (3) reflect the fact that a Uniform$(-1,1)$ variate is the random negation of a Uniform$(0,1)$ variate.  Part (2) is a restatement of step (2) in the question.
It comes down to computing the distribution of $X$.  To this end, let $0 \le t \le 1$.  The event that $X \le t$ decomposes into two disjoint possibilities:

At least two of the $X_i$ lie in $[0, t]$, guaranteeing that $X$ (which must be among them) will lie in $[0, t]$.  This is a binomial probability given by  $$\binom{3}{2}t^2(1-t) + \binom{3}{3}t^3 = t^2(3-2t).$$
Exactly one of the $X_i$ lies in $[0, t]$ and it is the one randomly chosen.  The random choice multiplies the chance (another binomial probability) by $1/2$, giving $$\binom{3}{1}t(1-t)^2 \times \frac{1}{2} = \frac{3}{2}t(1-t)^2.$$

Therefore the distribution function is
$$F(t) = t^2(3-2t) + \frac{3}{2}t(1-t)^2 = \frac{3}{2} t - \frac{1}{2}t^3,$$
whence the density function is
$$f(t) = F^\prime(t) = \frac{3}{2}(1 - t^2).$$

The blue shaded area represents $f$ while the red shaded area shows how it is extended symmetrically about $0$ to define a distribution supported on the interval $[-1,1]$ with density $f_e = \frac{1}{2}f$.
Extending $f$ to the domain $[-1,1]$ by symmetry (which is what part (3) does) will not change its functional form (which is already symmetric about $0$, since $(-t)^2 = t^2$) but must halve the height to maintain its normalization, whence
$$f_e(t) = \frac{1}{2}\left(\frac{3}{2}(1 - t^2)\right) = \frac{3}{4}(1-t^2).$$

By the way, a simpler way to generate such a sample is to take the median of three iid Uniform$(0,2)$ variates.  Here's R code:
n <- 1e5
x <- apply(matrix(runif(3*n, -1, 1), 3), 2, median)

(It takes two or three seconds to generate 100,000 values.)  Comparing the histogram of this sample to the kernel confirms its accuracy:
Answer: Although it only is a too long comment that comes a day late and a dollar short, my explanation, which is highly related to the more detailed and to the point answer by whuber, is that the outcome of Devroye's algorithm with those three uniforms is indeed distributed from the mixture of the distributions of the first order statistic and of the second order statistic for three uniforms on (0,1), since it is not the third order statistic,$$f^*(u)=\frac{1}{2}f_{(1:3)}(u)+\frac{1}{2}f_{(2:3)}(u)$$Given that the generic density for an order statistic is$$f_{(k:n)}(x)=(k-1)!(n-k-1)!\,F(x)^{k-1}\,(1-F(x))^{n-k-1}(x)\,f(x),$$we get$$f^*(u)=\frac{1}{2} 3(1-x)^2 + \frac{1}{2} 6x(1-x)=\frac{3}{2}-\frac{3x^2}{2}$$


iOS Programmatically go to Tab AND Push View Controller

Question: My app is connected with Facebook Deep Link for Open Graph.  When the open graph story is clicked in Facebook app, it goes back to my app.  I want it to go back to my app in the 2nd tab, and subsequently present a new view controller onto the screen.
In my appDelegate, when the action is completed from Facebook, I have:
 NSString *objectId = [[[call appLinkData] targetURL].path substringFromIndex:1];
 NSString *nameofhtml = [[objectId lastPathComponent] stringByDeletingPathExtension];
// now handle the deep link
// write whatever code you need to show a view controller that displays the object, etc.

      if (_webViewController == nil) {
          self.webViewController = [[PrayerGifts alloc] init];
       }
     _webViewController.fromFacebook = nameofhtml;
      [self.tabBarController setSelectedIndex:1];
      [_webViewController viewPrayer];

This successfully sets the tab where I want it, but the method in _webViewController named viewPrayer never gets called.  That method is:
Prayer *gonow = [[Prayer alloc] init];
    gonow.currentURL = fromFacebook;
    [self.navigationController pushViewController:gonow animated:YES];
    [gonow release];

How can I get it to come back into the app, change the tab bar, and launch the correct view from that tab
Comment: Your question isn't understandable. Is the question why isn't viewPrayer  getting called, or is it how to get it to come back (whatever "it" is and whatever "come back" means, neither of which isn't clear what these are, nor what is the focus of the question).
Comment: @MartinH see my edited question for clarification.
Comment: From the code there's no reason why viewPrayer is not getting called, therefore I doubt the code you have posted is being executed. How have you confirmed its not getting called? Have you put a breakpoint in viewPrayer and another at the line [_webViewController viewPrayer]?
Comment: I haven't been able to use the console.  Everytime I run it on my 5S, it installs it and runs, but Xcode never detects that, and ends the debug sessino
Comment: Its a bit pointless posting a question at the moment, you need to first learn how to debug using Xcode. The code you posted isn't even being called (I mean the first bit of code), so that is obviously why viewPrayer is not getting called. Nobody can answer why not. You have to learn how to debug code and learn how to use Xcode, then come have here if you have more info.
Comment: If I could answer the question "Why is this code not being called" I wouldn't have asked the question, "Why is this code not working"  I am asking why it is not getting called.
Comment: @MartinH I got Xcode working better.  I added an NSLog in viewPrayer method.  The method is definitely getting called, it's just not performing right.
Comment: Or it was showing up in the NSLog, but not it isn't again.
Comment: "Why is this code not being called". You asked why is viewPrayer not getting called. I answered that viewPrayer is not getting called because the code that is calling it is itself not getting called (i.e. the code in the first block in your question is not itself getting called). There, question answered. As to why the code that is calling viewPraryer is itself not getting called is impossible to answer as there is no code showing how that code is called. I'd recommend starting a new question showing more context and code so its possible to get a bigger picture of how your app is behaving.
Comment: @MartinH that code IS GETTING CALLED.  In that whole block, every line of code is called EXCEPT viewPrayer
Comment: Check _webViewController is not nil at the point of the call. You are assigning the alloc result to self.webViewController, not to _webViewController. They presumably are the same but maybe not if there is something unconventional in the way you have declared them.
Comment: If _webViewController is not nil, there there is no explanation for why viewPrayer is not getting called. Unless the viewPrayer method does not exist for a class of type PrayerGifts. But if that were the case you would be getting a runtime error with an "unrecognized selector" message in Xcode.
Comment: Header file declares in the iVar as _webViewController with property of _webViewController and I synthesize webViewController = _webViewController
Answer: Swift 3.1
func goToChatViewController(){
    DispatchQueue.main.async(execute: { () -> Void in
        self.tabBarController?.selectedIndex = 3
        if let storyboard = self.storyboard {
            let helpViewController = storyboard.instantiateViewController(withIdentifier: "HelpViewController") as! HelpViewController
            let settingsRootNavigationController = self.tabBarController?.viewControllers![3] as! UINavigationController

            settingsRootNavigationController.popToRootViewController(animated: false)
            settingsRootNavigationController.pushViewController(chatController, animated: true)
        }
    })
}

Answer: I just ran into this problem today and found a simple solution that worked for me. I have a TabBarController with 4 tabs. I need to get from a deep view controller hierarchy in tab 2 to a nested view controller in tab 4. Here is how I do it.
  func goToHelpViewController(){
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.tabBarController?.selectedIndex = 3
                let settingsStoryBoard = UIStoryboard(name: "SettingsSection", bundle: nil)
                let helpViewController = settingsStoryBoard.instantiateViewControllerWithIdentifier("HelpViewController") as! HelpViewController
                let settingsRootNavigationController = self.tabBarController?.viewControllers![3] as! UINavigationController

      settingsRootNavigationController.popToRootViewControllerAnimated(false)
                settingsRootNavigationController.pushViewController(helpViewController, animated: true)
            })
        }

I tested this and you must set the selected index before getting the navigation controller from the desired tab. After setting the index, you get the navigation controller for the desired tab and push it onto your navigation controller stack for the desired tab.The reason I call popToRootViewController on settingsRootNavigationController is to always keep that stack fresh on the first view controller in its navigation stack. However, your requirements for that may not be the same as mine.


Translate custom string from programatically defined block

Question: Alright, this one is probably easy but I found online documentation only little helpful and couldn't figure it out myself.
I run a custom module that renders a custom block programatically via function hook_block_view(). Assume that $block['content'] = 'Hello';. The custom string 'Hello' does not appear in the list of translatable strings (config/regional/translate/translate) but I want to display it in, say, Spanish ('Hola') when the site language is set to Spanish.
How do I translate it / make it appear in the list?
Answer: In order to make strings translation possible you need to pass it through the t function.
$block['content'] = t('Hello');

Comment: Thank you, this works. Unfortunately, if I use the same English string in two places it automatically uses the same Spanish translation in both places, which might not always be feasible. What is the right way to distinguish between two `t('Hello')`'s when I want to have two translations of the same word? I tried to add a custom context via `t('Hello', array(), array('context' => 'custom context'))` but the string does not appear on the translation interface when I search for it. Do I have to create custom contexts somewhere else before I can use them?
Comment: And even better, could I assign all strings from my custom module to a new text group "Custom Module" and still distinguish all strings from my custom module into contexts? Something like `t('Hello', array(), array('textgroup' => 'custom module', 'context' => 'custom context'))`?


Double summation with a variable stopping point

Question: I am interested in calculating the following double summation:
$\sum_{n=2}^ \infty \sum_{k =0}^{n-2}\frac{1}{4}^k \frac{1}{2}^{n-k-2}$
I don't really know where to start, so I was hoping someone could point me to some resource where I could learn the terminology/methodology associated with solving such problems.
The summation arose when trying to describe the probability of never reaching a certain state in a finite markov chain. I really was just inquiring about the algebra which is why I didn't provide the context previously.
Comment: Please give more [context](http://meta.math.stackexchange.com/a/9960). Providing context not only assures that this is not simply copied from a homework assignment, but also allows answers to be better directed at where the problem lies and to be within the proper scope. Please [avoid "I have no clue" questions](https://math.meta.stackexchange.com/a/27933). Defining keywords and trying a simpler, similar problem often helps.
Comment: The summation arose when trying to describe the probability of never reaching a certain state in a finite markov chain. I really was just inquiring about the algebra which is why I didn't provide the context. I will make sure to do so in the future.
Comment: I have added the comment as context to your question. Thank you for doing this in the future.
Answer: $$
\begin{align}
\sum_{n=2}^\infty\sum_{k=0}^{n-2}\left(\frac14\right)^k\left(\frac12\right)^{n-k-2}
&=\sum_{n=0}^\infty\sum_{k=0}^n\left(\frac14\right)^k\left(\frac12\right)^{n-k}\tag1\\
&=\sum_{k=0}^\infty\sum_{n=k}^\infty\left(\frac14\right)^k\left(\frac12\right)^{n-k}\tag2\\
&=\sum_{k=0}^\infty\sum_{n=0}^\infty\left(\frac14\right)^k\left(\frac12\right)^n\tag3\\
\end{align}
$$
Explanation:
$(1)$: substitute $n\mapsto n+2$
$(2)$: switch order of summation ($n\ge k$)
$(3)$: substitute $n\mapsto n+k$
Does this look easier?
Answer: \begin{aligned}
\sum_{n=2}^ \infty \sum_{k =0}^{n-2}\left(\frac{1}{4}\right)^k \left(\frac{1}{2}\right)^{n-k-2} &= \sum_{n=2}^ \infty \sum_{k =0}^{n-2}\left(\frac{1}{2}\right)^{2k} \left(\frac{1}{2}\right)^{n-k-2} \\
&= \sum_{n=2}^ \infty \sum_{k =0}^{n-2}\left(\frac{1}{2}\right)^{n+k-2} \\
&= \sum_{n=2}^ \infty \left(\frac{1}{2}\right)^{n-2}\sum_{k =0}^{n-2}\left(\frac{1}{2}\right)^{k}  \\
&= \sum_{n=2}^ \infty \left(\frac{1}{2}\right)^{n-2} \frac{1-\left(\frac 12\right)^{n-1}}{1-\frac 12} \\
&= \sum_{n=2}^ \infty\left(\frac{1}{2}\right)^{n-3} - \left(\frac{1}{2}\right)^{2n-4} \\
&= 2 \sum_{n=0}^ \infty\left(\frac{1}{2}\right)^n -\sum_{n=0}^{\infty}\left(\frac{1}{4}\right)^n \\
&= 2 \frac{1}{1-\frac 12}-\frac{1}{1-\frac 1 4} \\
&= \frac 8 3
\end{aligned}
Answer: This problem involves sums of geometric sequences for which there is a well-known formula:
$$\sum_{n=0}^{m-1} r^n = \frac{1-r^m}{1-r}.$$
Applying this to your summation and using a little algebra you get:
$$\begin{equation} \begin{aligned}
\sum_{n=2}^\infty \sum_{k=0}^{n-2} \Big( \frac{1}{4} \Big)^k \Big( \frac{1}{2} \Big)^{n-k-2}
&= \sum_{n=2}^\infty \Big( \frac{1}{2} \Big)^{n-2}  \sum_{k=0}^{n-2} \Big( \frac{1}{4} \Big)^k \Big( \frac{1}{2} \Big)^{-k} \\[6pt]
&= \sum_{n=2}^\infty \Big( \frac{1}{2} \Big)^{n-2}  \sum_{k=0}^{n-2} \Big( \frac{1}{2} \Big)^k \\[6pt]
&= \sum_{n=2}^\infty \Big( \frac{1}{2} \Big)^{n-2} \cdot \frac{1-(\tfrac{1}{2})^{n-1}}{1-\tfrac{1}{2}} \\[6pt]
&= 2 \Bigg[ \sum_{n=2}^\infty \Big( \frac{1}{2} \Big)^{n-2} - \sum_{n=2}^\infty \Big( \frac{1}{2} \Big)^{2n-3} \Bigg] \\[6pt]
&= 2 \Bigg[ \sum_{n=0}^\infty \Big( \frac{1}{2} \Big)^{n} - \frac{1}{2} \sum_{n=0}^\infty \Big( \frac{1}{4} \Big)^{n} \Bigg] \\[6pt]
&= 2 \Bigg[ \frac{1}{1-\tfrac{1}{2}} - \frac{1}{2} \cdot \frac{1}{1-\tfrac{1}{4}} \Bigg] \\[6pt]
&= 2 \Bigg[ 2 - \frac{1}{2} \cdot \frac{4}{3} \Bigg] \\[6pt]
&= 2 \Bigg[ 2 - \frac{2}{3} \Bigg] \\[6pt]
&= 2 \cdot \frac{4}{3} \\[6pt]
&= \frac{8}{3} = 2.6\bar{6}. \\[6pt]
\end{aligned} \end{equation}$$


Concatenar String em C sem uso de função strcat()

Question: preciso de uma ajuda, precisava resolver este exercicio de linguagem de programação, seria concatenar uma string, no caso STRING_B na STIRNG_A, sem uso de função pronta, por metodo de ponteiros.
exemplo:
ENTRADAS >> "CASA " - "BAHIA"

SAIDA >> CASA BAHIA

segue o codigo...
#include <stdio.h>
#include <string.h>
/*escreva uma funcao em c que recebe a referencia de duas strings e concatena
a segunda na primeira sem usar funcao strcat()*/

void ptr(char *string_a, char *string_b)
{
    int i;
    do{
        string_a++;
    }while(*string_a!='\0');
    do{
        string_a=*string_b;
        string_b++;
    }while(*string_b!='\0');
}
int main (void)
{
    char string_a[250];
    char string_b[250];
    puts(" -- DIGITE UMA PALAVRA -- ");
    gets(string_a);
    puts(" -- DIGITE UMA PALAVRA -- ");
    gets(string_b);
    ptr(string_a,string_b);
    puts(string_a);
    return 0;
}

Answer: Não tem o porque usar o do_while e depois incrementar, se o for foi feito para isso, seu código está um pouco confuso para mim, fiz de uma maneira um pouco mais simples:
char* ptr(char *string_a, char *string_b)
{
    int i;
   for(i=0; string_a[i]!='\0'; ++i); //Percorre toda a string_a, para saber o tamanho da mesma
   for(int j=0; string_b[j]!='\0'; ++j, ++i) //Percorre toda a string_b, para concatena-la
   {
      string_a[i]=string_b[j];
   }
    string_a[i]='\0';
    return string_a;
}
int main (void)
{
    char string_a[250];
    char string_b[250];
    puts(" -- DIGITE UMA PALAVRA -- ");
    gets(string_a);
    puts(" -- DIGITE UMA PALAVRA -- ");
    gets(string_b);
    puts(ptr(string_a,string_b));
    return 0;
}

Veja funcionando no Ideone.
Com while:
char* ptr(char *string_a, char *string_b)
{
    int i = 0, j = 0;
    while(string_a[i]!='\0') { ++i; }
    while(string_b[j]!='\0')
    {
        string_a[i]=string_b[j];
        j++; i++;
    }
    string_a[i]='\0';
    return string_a;
}

Veja funcionando no Ideone.
Comment: Error] 'for' loop initial declarations are only allowed in C99 or C11 mode; apresentou este erro!
Comment: @AGenaro Não sei o porque do erro, mas sendo assim faça com while mesmo, editei minha resposta.
Comment: @Francisso Agora deu certo ! Obrigado. so no sue codigo que mandou por ultimo faltou Ponto e virgula depois do '++i'


How to set a node reference programmatically?

Question: I'm creating a new node and attempting to the values of the fields programmatically. I cannot seem to figure out how to set a value for a node reference field, the widget type is autocomplete and it is set to unlimited values.
Here is my code to create the new node and an entity metadata wrapper
// Create the communication node and set the current user as the author
$new_comm = entity_create('node', array('type' => 'comm', 'uid' => $uid));
// create a wrapper for the new communication
$nc_wrapper = entity_metadata_wrapper('node', $new_comm);
// then I set some other field values via the $nc_wrapper

I cannot seem to set the value for the node reference field field_comm_relationship. I have tried all manner of setting the value including the following ($oc_wrapper wraps a different node type that also has a node reference):
I tried inserting it straight from the $oc_wrapper
$nc_wrapper->field_comm_relationship = $oc_wrapper->field_call_site_ref->value();

I tried using the set method
$nc_wrapper->field_comm_relationship->set($oc_wrapper->field_call_site_ref->value());

I tried both of the previous while accessing the actual nid value
$nc_wrapper->field_comm_relationship->set($oc_wrapper->field_call_site_ref->value()->nid);

and
$nc_wrapper->field_comm_relationship = $oc_wrapper->field_call_site_ref->value()->nid;

I tried to make the input an array
$site_nid = ['und' => [ 0 => ['nid' => (int) $oc_wrapper->field_call_site_ref->value()->nid]]];
$nc_wrapper->field_comm_relationship = $site_nid;

I tried using the node_load function instead of EMW
$node = node_load('node', $nc_wrapper->nid->value());
$site_nid = $oc_wrapper->field_call_site_ref->value()->nid;
$node->field_comm_relationship['und'][0]['nid'] = $site_nid;
node_save($node);

As suggested I do call save() later in my code, but it's not making it there because it hits a fatal error. For instance if I run this code
$nc_wrapper->field_comm_relationship = (int) $oc_wrapper->field_call_site_ref->value()->nid;

I get this error
EntityMetadataWrapperException: Invalid data value given.
Be sure it matches the required data type and format.
Value at node()->field_comm_relationship: 713511. in EntityMetadataWrapper->set()
(line 122 of /vagrant/sites/all/modules/contrib/entity/includes/entity.wrapper.inc)

Comment: What is an example value for `$oc_wrapper->field_call_site_ref->value()`?
Comment: Is it an int? an array? an object?
Comment: It's an object. Specifically the node object of the node being referenced.
Comment: You get that same error when you do `$nc_wrapper->field_comm_relationship = $oc_wrapper->field_call_site_ref->value();` `$nc_wrapper->save();`? Is `field_comm_relationship` a multivalue field?
Comment: If I run that code I get an SQL error:  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '), ('node', '713866', '1158104', 'comm', 'field_site_handset_serial', 'und', 'Ar' at line 1: INSERT INTO {field_data_field_comm_relationship} (entity_type, entity_id, revision_id, bundle, delta, language, field_comm_relationship_nid) VALUES...` and then it lists a BUNCH of values.
Answer: After updating the value in your entity metadata wrapper you need to be sure to also call the save() method to save your change. See this documentation on drupal.org.
Since you have an object, and not an id, the following should work.
// Set value for a single value field.
$nc_wrapper->field_comm_relationship = $oc_wrapper->field_call_site_ref->value();

or
// Set value for a multivalue field. Make sure to pass an array of objects.
$nc_wrapper->field_comm_relationship = [$oc_wrapper->field_call_site_ref->value()];

or
// Append an additional value to a multivalue field.
$nc_wrapper->field_comm_relationship[] = $oc_wrapper->field_call_site_ref->value();

and finally
// Save the host entity.
$nc_wrapper->save();

If you have ids, check out this answer. You can get an id instead of an object from the entity metadata wrapper like $oc_wrapper->field_call_site_ref->raw() instead of ->value();
Additional info for entity metadata wrappers can be found in this Death to Field Arrays! article.
Comment: `$nc_wrapper->field_comm_relationship[] = $oc_wrapper->field_call_site_ref->value();` that got it. Thanks!
Comment: Thanks for the thoughtful response. I do call `save()` later in my code, but it's not making it that far before a fatal error. I have updated my question.
Comment: I've updated this answer. I hope this resolves this for you. I think your issues were because your field is a multivalue field and not a single value field.


Não consigo realizar meu dropdown menu

Question: Nessa situação não consigo posicionar os elementos
 abaixo de informática de forma responsiva. Estou a fim de criar um dropdown menu mas não faço ideia de como posicionar os
 abaixo do meu botão informática e então fazê-los aparecerem e desaparecem no hover.
Isso também quebra o alinhamento de todos os outros itens
Se possível execute o código em "Página Toda"

 body{
    background-color: #151515;
}

/* Parâmetros da Navegação */
nav{
    width: 100%;
    height: 4.5rem;
    background-color: #232323;
    border-bottom: solid 5px #8B46A3;
}

li, a{
    font-family: "Montserrat", sans-serif;
    font-weight: 500;
    font-size: 1.5rem;
    color: white;
    text-decoration: none;
}

#nav-content{
    display: flex;
    justify-content: space-evenly;
    list-style: none;

}

#nav-content li{
    display: flex;
    align-items: center;
    padding-top: 0.70rem;
}

<svg width="50" height="50" viewBox="0 0 50 50" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M21.875 35.9375H6.25C5.4212 35.9375 4.62634 35.6083 4.04029 35.0222C3.45424 34.4362 3.125 33.6413 3.125 32.8125V18.75C3.125 17.9212 3.45424 17.1263 4.04029 16.5403C4.62634 15.9542 5.4212 15.625 6.25 15.625H21.875" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M21.875 42.1875H12.5" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M40.625 14.0625H34.375" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M40.625 20.3125H34.375" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M45.3125 7.8125H29.6875C28.8246 7.8125 28.125 8.51206 28.125 9.375V40.625C28.125 41.4879 28.8246 42.1875 29.6875 42.1875H45.3125C46.1754 42.1875 46.875 41.4879 46.875 40.625V9.375C46.875 8.51206 46.1754 7.8125 45.3125 7.8125Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M17.1875 35.9375V42.1875" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M37.5 37.5C38.7944 37.5 39.8438 36.4507 39.8438 35.1562C39.8438 33.8618 38.7944 32.8125 37.5 32.8125C36.2056 32.8125 35.1562 33.8618 35.1562 35.1562C35.1562 36.4507 36.2056 37.5 37.5 37.5Z" fill="white"/>
            </svg>
            INFORMÁTICA

PEÇAS (HARDWARE)

PERIFÉRICOS E ACESSÓRIOS

COMPUTADORES MONTADOS

<svg width="50" height="50" viewBox="0 0 50 50" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M29.6875 21.0938H35.9375" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M14.0625 21.0938H20.3125" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M17.1875 17.9688V24.2188" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M33.5973 10.8867L16.4071 10.9375C14.0193 10.9377 11.7078 11.779 9.87845 13.3137C8.0491 14.8484 6.8188 16.9784 6.40351 19.3299L6.40518 19.3302L3.209 35.7682C3.00712 36.9136 3.17564 38.0935 3.69007 39.1366C4.2045 40.1797 5.03806 41.0317 6.06968 41.5687C7.1013 42.1057 8.27727 42.2999 9.42679 42.1231C10.5763 41.9462 11.6395 41.4075 12.462 40.5852L12.4617 40.5849L20.9061 31.25L33.5973 31.1992C36.2909 31.1992 38.8742 30.1292 40.7789 28.2245C42.6836 26.3199 43.7536 23.7366 43.7536 21.043C43.7536 18.3494 42.6836 15.7661 40.7789 13.8614C38.8742 11.9567 36.2909 10.8867 33.5973 10.8867V10.8867Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M43.5993 19.2793L46.7928 35.7682C46.9947 36.9136 46.8262 38.0935 46.3118 39.1366C45.7973 40.1797 44.9638 41.0316 43.9322 41.5687C42.9005 42.1057 41.7246 42.2999 40.575 42.123C39.4255 41.9462 38.3623 41.4075 37.5398 40.5851L37.5402 40.5848L29.1016 31.2172" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>CONSOLES

<svg width="50" height="50" viewBox="0 0 50 50" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M25 31.25C31.9036 31.25 37.5 25.6536 37.5 18.75C37.5 11.8464 31.9036 6.25 25 6.25C18.0964 6.25 12.5 11.8464 12.5 18.75C12.5 25.6536 18.0964 31.25 25 31.25Z" stroke="white" stroke-width="2" stroke-miterlimit="10"/>
                <path d="M6.05249 42.1857C7.97351 38.8606 10.7357 36.0996 14.0616 34.18C17.3876 32.2605 21.1601 31.25 25.0002 31.25C28.8403 31.25 32.6128 32.2606 35.9386 34.1803C39.2645 36.0999 42.0267 38.8609 43.9476 42.1861" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            SUPORTE

<svg width="50" height="50" viewBox="0 0 50 50" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M17.1875 31.25C22.7966 31.25 27.3438 26.7029 27.3438 21.0938C27.3438 15.4846 22.7966 10.9375 17.1875 10.9375C11.5784 10.9375 7.03125 15.4846 7.03125 21.0938C7.03125 26.7029 11.5784 31.25 17.1875 31.25Z" stroke="white" stroke-width="2" stroke-miterlimit="10"/>
                <path d="M30.354 11.3158C31.7509 10.9222 33.216 10.8326 34.6504 11.0529C36.0849 11.2732 37.4555 11.7983 38.67 12.5929C39.8844 13.3876 40.9145 14.4332 41.6908 15.6594C42.4671 16.8856 42.9716 18.264 43.1703 19.7016C43.3691 21.1393 43.2574 22.6028 42.8429 23.9936C42.4284 25.3845 41.7207 26.6704 40.7674 27.7646C39.8141 28.8589 38.6373 29.7362 37.3164 30.3375C35.9955 30.9387 34.5611 31.2498 33.1098 31.25" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M3.12427 38.554C4.71047 36.2978 6.81624 34.4563 9.26382 33.1851C11.7114 31.9138 14.4289 31.2501 17.1869 31.25C19.945 31.2499 22.6625 31.9134 25.1102 33.1844C27.5579 34.4555 29.6638 36.2968 31.2502 38.553" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M33.1099 31.25C35.8681 31.248 38.5863 31.9107 41.0342 33.1819C43.482 34.4531 45.5875 36.2955 47.1724 38.553" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            QUEM SOMOS

Answer: Position: relative;
Tente usar a posição relativa, isso torna o posicionamento absoluto ficar de acordo com o tamanho do pai (que nesse caso é a li que engloba o submenu).
Adicione o CSS abaixo:
#nav-content > li {
    position: relative;
    /* com o position: relative; tudo que tiver dentro da li, vai levar em consideração seu tamanho para se posicionar */
}

#nav-content > li:hover .ul-submenu {
    opacity: 1;
}

.ul-submenu {
    /* com o position: absolute; você poderá posicionar o submenu de acordo com com o tamanho da li (seu pai) lembrando que para isso, é necessário o position: relative; no seu pai (li no caso) */
    position: absolute;
    top: 100%;
    width: max-content;
    opacity: 0;
    transition: all 0.3s ease-in-out;
}

Não consigo realizar meu dropdown menu


Search distinct date parts fast in mysql

Question: I've got a database of ~10 million entries, each of which contains a date stored as DATE.
I've indexed that column using a non-unique BTREE.
I'm running a query that counts the number of entries for each distinct year:
SELECT DISTINCT(YEAR(awesome_date)) as year, COUNT(id) as count
FROM all_entries
WHERE awesome_date IS NOT NULL
GROUP BY YEAR(awesome_date)
ORDER BY year DESC;

The query takes about 90 seconds to run at the moment, and the EXPLAIN output demonstrates why:
id | select_type | table        | type  | possible_keys | key | key_len | ref | rows     | Extra
----------------------------------------------------------------------------------------------------------------------------------------
1  | SIMPLE      | all_entries  | ALL   | awesome_date  |     |         |     | 9759848  |  Using where; Using temporary; Using filesort

If I FORCE KEY(awesome_date) that drops the rows count down to ~8 million and the key_len = 4, but is still Using where; Using temporary; Using filesort.
I also run queries selecting DISTINCT(MONTH(awesome_date)) and DISTINCT(DAY(awesome_date)) with the relevant WHERE conditions restricting them to a particular year or month.
Other than storing the year, month and day information in separate columns, is there a way of speeding up this query and/or avoiding temporary tables and filesort?
Answer: Without splitting the date to 3 columns, you could:

First, you should remove the DISTINCT, it is useless. – ypercube 1 min ago edit
Remove the ORDER BY year, it would help improve speed (a bit). Change the Group By to: GROUP BY YEAR(awesome_date) DESC (this works in MySQL dialect only).
Change the COUNT(id) to COUNT(*) (assuming that id can never be NULL, this is faster in many MySQL versions).

In all, the query will become:
SELECT YEAR(awesome_date) AS year
     , COUNT(*) AS cnt              --- not good practise to use reserved words
                                    --- for aliases
FROM all_entries
WHERE awesome_date IS NOT NULL
GROUP BY YEAR(awesome_date) DESC ;

Even better (faster) solutions are:

your proposal to split the column into 3 (year, month, day)
change from MySQL to MariaDB (that is a MySQL fork) and use VIRTUAL PERISTENT column for the year, and add an index on that virtual column.
stay in MySQL and add a persistent year column yourself - by using triggers.


unable to find mojo sonar (or one of its component) in the plugin org.sonarsource.scanner.maven:sonar-maven-plugin

Question: I am implementing sonar in my existing maven project.I am getting this error :

unable to find mojo sonar (or one of its component) in the plugin org.sonarsource.scanner.maven:sonar-maven-plugin

Following are my configs:

Maven version:2.2.1
Java version:1.6
sonar-maven-plugin version:3.0.2
sonarcube version:6.4
sonar java version: 220.127.116.1160

I have updated:

pom.xml
settings.xml
sonar-project.properties

to mentioned my intended java version in it.
Comment: Please [edit] your question to include SonarQube version (found in the page footer) and SonarJava version (found in **Administration > System > Update Center**)
Comment: I setup a local project with your exact same setup and cannot reproduce the issue.
Comment: @G.Ann-SonarSourceTeam I have updated as u said.
Comment: @slartidan thanks for commenting. Is your maven sonar build successfully completing?
Comment: I tried with Maven 3, Java 1.6, SonarQube 6.4 and sonar-java 126.96.36.19960. Actually I did not try with Maven 2. Maybe @g-ann-sonarsource-team is right...
Answer: Upgrade to Java 7 and Maven 3, and this should work.


SQL: count customer that never bought a product, in a group by

Question: I have just this MySQL table:
Order(customer_id, wine_id, price)
An example
wine_id |   customer_id |   price
1       |   1           |   13€
1       |   2           |   13€
1       |   3           |   13€
2       |   1           |   17€
2       |   3           |   16€
3       |   4           |   15€
3       |   2           |   15€

and want to get number of customer who never bought a product, per product.
So there are 3 wines and 4 customers. All the customers in this table bought at least a bottle of wine.
In the example above, I expect the following:
wine_id |   count(distinct customer)
1       |   1
2       |   2
3       |   2

In fact the wine with id 1 has been bought by 3 customer out of 4 total customers ... so since I want the customer who never bought the product the expected result is 1.
I thought about this:
SELECT
    o1.wine_id,
    COUNT(DISTINCT o1.customer_id)
FROM
    order o1
WHERE
    customer_id NOT IN (SELECT
            o2.customer_id
        FROM
            order o2
        WHERE
            o2.wine_id = o1.wine_id)
GROUP BY o1.wine_id;

The idea is to get into the subquery the customers that bought a wine, and then put this in the where clause passing the grouped wine. But clearly there is something wrong in this assumption. It returns 0 row. Why can't I access a value in the sub-query?
Can you guys help me with this query?
Comment: Give a sample data and expected result.
Comment: From this table, you can just get number of customer who ever bought per product. If you want get who never bought, you should tell us where you store you customer. Or all of customers are in this table?
Comment: @Forward, thank you for your reply. All the customers are in this table. I'll add this information in the question
Comment: then where is your expected result? the second one?
Answer: Try this:
select
    wine_id,
    cus_num - count(distinct customer_id) never_bought_num
from yourtable
join (select count(distinct customer_id) as cus_num from yourtable) t
group by wine_id

See demo in sqlfiddle.
In your case, you should count all the customers in table order, this is total number, then minus number of customer who bought product, you will get never bought number.
Edit:
Two ways can solve your sql error.
1) Set your sql_mode without only_full_group_by;
2) Replace group by wine_id to group by wine_id, cus_num.
Why this issue???
Check official doc Server SQL Modes.
Comment: thank you! Works fine in sqlfiddle, as expected. But on my MySQL it gives me the error:
`Error Code: 1055. Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 't.cus_num' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by`


Integração projeto asp net mvc com sql server

Question: Como posso fazer a conexão do visual studio com o sql server galera? Fiz uma tela de cadastro, mas não faço idéia de como posso fazer com que meu site mande esses dados pro sql server?
Answer: Olá, boa tarde!
Segue um tutorial em português da próxima Microsoft que vai te ajudar passo a passo como fazer o que precisa.
Tutorial: Introdução ao EF Core em um aplicativo Web ASP.NET MVC
Answer: O EF (Entity Framework) Core é uma versão leve, extensível, de software livre e multiplataforma da popular tecnologia de acesso a dados do Entity Framework.
EF Core pode servir como um mapeador relacional de objeto (O/RM), que:
Permite que os desenvolvedores do .NET trabalhem com um banco de dados usando objetos .NET.
Elimina a necessidade da maior parte do código de acesso a dados que normalmente precisa ser gravado.
O EF Core é compatível com vários mecanismos de banco de dados, consulte detalhes em Provedores de Banco de Dados.
https://docs.microsoft.com/pt-br/ef/core/
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Volume of ellipsoid bounded by cylinder and four planes

Question: I'm looking for a part of the volume of an oblate ellipsoid ($a=b>c$)
$$ \frac{x^2}{a^2} + \frac{y^2}{a^2} + \frac{z^2}{c^2} =1 $$
The part is formed by a cylinder $ x^2 + y^2 = r^2 $ and two couples of planes:

couple 1: $ y = \frac{L}{2} $ and $ y = \frac{-L}{2} $
couple 2: $ z = -c\sqrt{1-\frac{r^2}{a^2}} $ and $ z = -c\sqrt{1-\frac{r^2}{a^2}} + H $ with $H>0$ (attention: this is not symmetrical as in couple 1)

I'm only interested in the part of the volume in the positive $x$-axes (positive a) lying between the cylinder (core drilled out from the ellipsoid) and the rest of the ellipsoid.
I already tried to calculate this volume by a triple integration
$$\int_{-L/2}^{L/2}\int_{-c\sqrt{1-\frac{r^2}{a^2}}}^{-c\sqrt{1-\frac{r^2}{a^2}} + H}\int_{\sqrt{r^2-y^2}}^{a\sqrt{1-\frac{y^2}{a^2}-\frac{z^2}{c^2}}}dxdzdy$$
but the integral becomes to complicated in Cartesian coordinates.
Is there another way (perhaps via spherical coordinates or by splitting up in different sections)?
Comment: Are you assuming $L < 2r$? If not, you'll have to add an extra integral:

$$2 \int_r^{L/2}\int_{-c\sqrt{1-\frac{r^2}{a^2}}}^{-c\sqrt{1-\frac{r^2}{a^2}} + H}\int_0^{a\sqrt{1-\frac{y^2}{a^2}-\frac{z^2}{c^2}}}dxdzdy$$
Comment: Indeed $ L<2r $
Answer: You're integrating over a rectangle, so a coordinate change can't really help you here. You can split it into two parts, but that won't make it much easier.
If you make some simple linear substitutions, and ignore the easier $\sqrt{r^2 - y^2}$ term, you can reduce the integral to the volume bounded by an arbitrary rectangle and the unit sphere:
$$\int \int \sqrt{1 - x^2 - y^2} dx dy.$$
This is an elementary function but it's still too long to be practical. Mathematica insists on expressing it with logs and complex numbers, but I managed to simplify it to this:
$$\frac{1}{6} \left(2 x y \sqrt{-x^2-y^2+1}-y \left(y^2-3\right) \tan ^{-1}\left(\frac{x}{\sqrt{-x^2-y^2+1}}\right)-x \left(x^2-3\right) \tan ^{-1}\left(\frac{y}{\sqrt{-x^2-y^2+1}}\right)+\tan ^{-1}\left(\frac{-x^2-y+1}{x \sqrt{-x^2-y^2+1}}\right)-\tan ^{-1}\left(\frac{-x^2+y+1}{x \sqrt{-x^2-y^2+1}}\right)\right)$$
Comment: Hi,
This is indeed a very interesting way. But I'm not an expert, how do I have to fill in the boundaries in this solution: x1 and x2, y1 and y2? Is it possible to add the upper and lower limits in this solution as well?
Comment: Call the long function I posted above $F(x,y)$. Then you can use the fundamental theorem of calculus to write out the definite integral in terms of the boundary. You can answer your original question by making the substitutions $z' = z/c$ and $y' = y/a$. The final answer will be very long and won't simplify. It may not be a good use of your time to express the integral as a function of the constants in this way, depending on what you need the answer for.


What exactly is a modulus of continuity?

Question: This is my first post on here, so forgive me if I am ignorant of certain customs.
I am currently reading Courant & John's Introduction to Calculus and Analysis Volume I. Unfortunately, I have stumbled upon an ambiguous notation on page 41.
It begins:

Our definition of continuity of the function $f(x)$ at $x_0$ requires that for every degree of precision $\epsilon > 0$ there exists quantities $\delta \gt 0$ (so-called moduli of continuity) such that $|f(x)-f(x_0)| < \epsilon$ for all $x$ in the domain of $f$ for which $|x-x_0| < \delta$.

He then goes on to say that (for "regular continuity"):

In general, as our example show, this $\delta = \delta(\epsilon)$ depends not only on $\epsilon$ but also on the value of $x_0$.

What exactly is meant by a modulus of continuity and how is it related to $\delta(\epsilon)$?
Edit - Upon further inspection I have noted that the "modulus of continuity" depends on both $x_0$  and $\epsilon$ for "regular continuity", however only depends on $\epsilon$ for uniform continuity. I believe that some of the confusion has been cleared by the notation of $\delta(\epsilon)$. However, he states that moduli of continuity are simply quantities $\delta > 0$. Is this "it", or is there further discussion to be had?
Comment: Thank you for your response. I was also uncertain as to whether this was a definition, however the Wikipedia article seems to be much clearer. Likewise, using $\omega$ seems more useful as $\delta(\epsilon)$ led to my confusion.
Answer: The definition of continuity of a function $f$ at $x_0$ is: For any $\varepsilon >0$ there exists $\delta >0$ such that $|f(x)-f(x_0)|<\varepsilon $ provided that $|x-x_0|<\delta $.
We thus say that for every $\varepsilon $ there is a corresponding $\delta $, in the sense that the above statement holds. The thing to notice is that
1) The precise value of $\delta$ may depend on both $\varepsilon $ and the point $x_0$.
2) For any given $\varepsilon >0 $ and $x_0$, there may be many choices for $\delta$ as above.
Any choice of $\delta$ for a given $\varepsilon $ and $x_0$ is called a modulus of continuity for $f$ at $x_0$ corresponding to $\varepsilon $. Moduli of continuity are not unique.
Comment: Ittay Weiss explained very well what Courant means, but the notion of *modulus of continuity* is frequently used in other, nearly *inverse* sense. It is a function that permits to estimate the difference of the values of a function for a given $\delta$. See [link](https://en.wikipedia.org/wiki/Modulus_of_continuity) and [link](http://www.encyclopediaofmath.org/index.php/Continuity,_modulus_of).
Comment: @Ittay Weiss: You are right, my phrase that the *notions have nearly inverse sense* is wrong. The two functions carry almost the same information, like $\sin$ and $\arcsin$.
Comment: Ah! Thank you for the elaboration. The confusion stemmed from the use of $\delta(\epsilon)$ to indicate a dependence upon $\epsilon$ and $x_0$. So the author is using this notation to indicate a modulus of continuity?
Comment: @EgorMaximenko in which sense do you see the notion of modulus of continuity in the links you provide to be any different (let alone inverse) to what is described above?
Comment: @Ittay Weiss: In Courant, $\delta$ is a function of $\varepsilon$ and $x_0$. In EncyclopediaOfMath, the uniform modulus of continuity $\omega$ is a function of $\delta$ defined as the sup of $|f(x)-f(y)|$ over all pairs $x,y$ satisfying $|x-y|\le\delta$. For example, if $f(x)=x/5$, then $\delta(\varepsilon)$ can be $5\varepsilon$, and $\omega(\delta)=\delta/5$. In this simple example the inverse of $\omega$ can be used as Courant's $\delta$.
Comment: I disagree that the notions are inverse to each other. If $w$ is a modulus of continuity, and $\varepsilon >0$ is given, then there is some $\delta >0 $ with $w(\delta) < \varepsilon$. This $\delta $ is then a corresponding modulus of continuity in the above sense. I don't see any significant difference between the notions.
Comment: Courant considers $\delta$ as a function of $\varepsilon$, and $\omega$ calculates $\varepsilon$ for each $\delta$ (roughly speaking). In the case if $\omega$ is continuous and strictly increasing, then its *inverse* can be used as a $\delta$. For example, if $f$ is defined on $[0,+\infty)$ by $f(x)=\sqrt{x}$, then $\omega(\delta)=\sqrt{\delta}$. If $x_0=0$ and $\varepsilon\in(0,1)$, then we can't put $\delta=\omega(\varepsilon)$, but we can put $\delta=\epsilon^2=\omega^{-1}(\varepsilon)$. I agree that both functions, $\omega$ and $\omega^{-1}$, relate $\delta$ with $\varepsilon$.
Comment: @EgorMaximenko I think I might have misinterpreted your saying that the two notions are inverse to each other to mean they express different things. I think we agree they essentially carry the same (or almost the same) information, but in somewhat different ways.
Comment: Okay so Modulus of continuity for a function f, can be thought of as a function $ m:\mathbb R^{+}\times \mathbb R^{+}\to \mathbb R^{+}$, as $m_f(x_0,\epsilon)$


How many irreducible components can an affine algebraic set have?

Question: Let $X$ be an affine algebraic set, i.e. $X=V(I)$ is the zero set of some ideal $I\subseteq k[T_1,\ldots T_k]$. $X$ must not necessarily be irreducible.
Is there a finite decomposition into irreducible algebraic sets, i.e.
$$ X = U_1\sqcup \ldots \sqcup U_n?$$
Comment: 1) This depends on your definition of algebraic set. You should specify your definition. 2) Do you really mean $\sqcup$? For instance, for $V(xy)\subset \Bbb A^2$, would you want $V(x)$ and $V(y)$, or does the fact that they intersect mean you don't want this?
Comment: This was part of my confusion. So every affine algebraic set can be written as a finite union of affine varieties (irreducible) using the *Lasker-Noether primary decomposition theorem*, but this needn't be disjoint, as your example shows, yes?
Comment: @Lukas Correct!
Answer: Summarizing @KReisers and my comments:
When $X=V(I)$ is an algebraic set, i.e. the zero locus of an ideal $I\subseteq k[T_1,\ldots T_k]$, it can be expressed as the finite union of irreducible algebraic varieties
$$ X=\bigcup U_i$$
where $U_i=V(P_i)$ are the zero loci of prime ideals $P_i\subset k[T_1,\ldots T_k]$. This is a consequence of the Lasker-Noether primary decomposition.
However, this union need not be disjoint. Consider $X=V(xy)$ for $(xy)\subseteq k[x,y]$. Then $V(xy)=V(x)\cup V(y)$, where  both $V(x)$ and $V(y)$ are irreducible. However, they are not disjoint, as $(0,0)$ is a common point.


How to check a user's current userpoints balance with Rules?

Question: I am interested in creating a rule that checks a user's userpoints and then the rule performs an action.
Currently the Rules module doesn't have such condition. I read that this is possible to do with a Rules Component, that is used as a Rules Condition.
Could someone help me on this please?
Answer: I finally found a solution:
I created a rule set,where I add two rules:
1)Load the user points
2)Data comparison of user points
After creation of the Rule set,I created the main rule where I added as an action the Rule Set.Done!
Answer: You're right, there is no Rules Condition to check a user's current userpoints balance.
Have a look at this Rules example (in Rules export format):
<code>{ "rules_display_userpoints_after_updating_content" : {
    "LABEL" : "Display userpoints after updating content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules", "rules_conditional" ],
    "ON" : { "node_update" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "total-points" ], "op" : "\u003C", "value" : "20" } },
            "DO" : [
              { "drupal_message" : { "message" : "You have sufficient points (you still have [total-points:value] ...)." } }
            ]
          },
          { "ELSE" : [
              { "drupal_message" : { "message" : "You DO NOT have sufficient points (you only have [total-points:value] ...)." } }
            ]
          }
        ]
      }
    ]
  }
}
</code>
It does retrieve, as the very first Rules Action (not Rules Condition!) the current amount of user points of a user. If the amount is at least 20, it will display a message starting with "You have sufficient points ...", otherwise the message starts with "You DO NOT have sufficient points ...".
In this example I'm using the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module.
So the clue to make this rule work is the very first Rules Action "Load user points of a user".


Does decreasing regularisation parameter always decrease loss

Question: For a training problem with some loss function $L(w) = \frac{1}{N}\sum_{i=1}^N l(w, x_i, y_i) + \lambda ||w||^2_2$, where $l(w, x_i, y_i)$ is something like least squares and the global minimum of $L(w)$ can always be found, how can I show that decreasing $\lambda$ always decreases $L(w)$?
Answer: Suppose $w'$ is the optimal $w$ with a smaller $\lambda$ (say $\lambda'$) and $w$ is the optimal with the larger $\lambda$
We know $L(w',\lambda')\leq L(w,\lambda')$ because $w'$ is optimal (by definition), and $L(w,\lambda')\leq L(w,\lambda)$ because $L$ is increasing in $\lambda$.
The first inequality is actually stronger than you asked for; it says that decreasing $\lambda$ decreases not just the penalised loss $L(w)$ but the unpenalised loss $\frac{1}{N}\sum_i l(w; x_i,y_i)$.
Another way to see this is that minimising $\frac{1}{N}\sum_i l(w; x_i,y_i)+\lambda\|w\|_2^2$ is equivalent to minimising
$\frac{1}{N}\sum_i l(w; x_i,y_i)$ subject to some constraint on $\|w\|^2_2$, and that smaller $\lambda$ means a looser constraint. Minimising subject to a looser constraint means a lower minimum.
Unfortunately, this is only for the in-sample loss (or 'apparent loss'). The out-of-sample loss (which is what you usually care most about) can go up or down as $\lambda$ decreases
Comment: @CamilleGontier  Yes. Or apparent error and actual error
Comment: If we know that those first two inequalities are true, does that prove that $L(w', \lambda') < L(w, \lambda)$? And how do we know that $L(w, \lambda') < L(w, \lambda)$?
Comment: @steven-seagull Yes.  And we know the second inequality because the only thing that is different on the two sides is lambda, and it's bigger on the right.
Comment: I think that's a very nice answer. Just a small comment : what you call "in-sample loss" (resp. "out-of-sample loss") is what is usually called training error (resp. test error), am I right ?


Given a set of SQL queries, how do I list all the required tables and fields?

Question: I have about 400 separate SQL files, each with is own select into my database. I want to list the tables and columns from where they extract the information.
I was thinking to upload them to my testing database and then use some system table to get the metadata. Not sure if this would be the better approach.
Comment: Read the files is the best way.
Comment: You could use something like Python/bash to parse the .sql files and save the table names to some file and take a unique on that.
Answer: Yeah, I would also create views with the corresponding sql and then use DBA_DEPENDENCIES to extract the used database objects.
Comment: Then you can use functions or packages instead of views. It's allways better to use the pl/sql compiler of Oracle then to do it by hand...
Comment: what if the files have updates and inserts.  the only way to do this is to read the files -- should take less than four hours.


How to edit content of panels Custom text that was made reusable?

Question: I'v created a Custom text element for page manager and made it reusable, and I'm not able to edit it now in Panels. Is it possible to edit such Panels elements after they were made reusable?
Thanks
Comment: I'v updated the question because I'v found how to view the content, it is very easy just click on the triangle inside the element and you will see its content.
Answer: If you go into the panels from the structure menu... you will see "Manage custom content" on the top right.


Lattices in vector space over local field contained in a common lattice

Question: Let $A=\mathbb{F}_q[t]$, let $v_\infty$ be the usual valuation on $k=\mathbb{F}_q(t)$ such that $ v_\infty(1/t)=1$, and let $k_\infty=\mathbb{F}_q((t^{-1}))$ the completion of $k$ with respect to this valuation. Let $V$ be a finite dimensional $k_\infty$- vector space. I found the following claim which I don't know how to prove:
Take a $\mathbb{F}_q[t]$-lattice $\Lambda_1\subset V$ (since $A$ is PID, $\Lambda_1 $is of the form $\Lambda_1= v_1A+...+v_rA$, where $r=\dim_{k_\infty} V$). Then the set of lattices $\Lambda_2$ such that there is a lattice $\Lambda$ containing both $\Lambda_1$ and $\Lambda_2$ is dense in the set of all latices $\mathcal{L}(V)$.
Any help towards proving this will be greatly appreciated
Comment: Please make more efforts in your questions, and define the relevant stuffs.
Answer: What is a $\mathbb{F}_q[t]$-lattice in $k_\infty{}^n$, a free discrete $\mathbb{F}_q[t]$-submodule such that $k_\infty{}^n/\Lambda$ is compact ?
If so then (being a PID) any finitely generated $\mathbb{F}_q[t]$-submodule is free, and $k_\infty{}^n/\Lambda$ is compact iff $k_\infty \Lambda=k_\infty^n$.
(if $k_\infty \Lambda$ is smaller than $k_\infty^n$ then the quotient contains a copy of $k_\infty$, it is not compact, if $k_\infty \Lambda=k_\infty^n$ then up to a $k_\infty$-linear transformation it reduces to a quotient of $k_\infty{}^n / \Bbb{F}_q[t]^n$ which is $\cong t^{-1} \Bbb{F}_q[[t^{-1}]]^n$ as topological groups)
So it remains to check the discreteness.
Let $\Lambda_1$ be a lattice which is of rank $n$ as a $\Bbb{F}_q[t]$-module. With a $k_\infty$-linear transformation we can assume that $\Lambda_1=\Bbb{F}_q[t]^n$.
Then $\Lambda_1+ \Bbb{F}_q[t] u$ is discrete iff $u\in \Bbb{F}_q(t)^n$: look at the image of $\Bbb{F}_q[t] u$ in the compact set $k_\infty{}^n/\Lambda_1$, for it to have no accumulation point we need that the image of $\{ t^au, a\ge 0\}$ is a finite set whence $(t^a-t^b) u \in \Lambda_1$ for some $a>b$.
Conversely if $u\in \Bbb{F}_q(t)^n$ then the image of $\Bbb{F}_q[t] u$ in $k_\infty{}^n/\Lambda_1$ is a $\Bbb{F}_q[t]/(f(t))$ module, where $f$ is the denominator of $u$, so it is a finite set.
Therefore take any lattice $\Lambda_2$ and approximate it by a lattice $\Lambda_2'$ in $\Bbb{F}_q(t)^n$ to obtain that $\Lambda_1+\Lambda_2'$ is a lattice.
Comment: Sorry for the details that I missed. I understand your claim and I am currently thinking about how to approximate $\Lambda_2$. Thanks
Comment: So, if I understood correctly, given any lattice $\Lambda_2$, you can approximate it  using that $k$ is dense in $k_{\infty}$ by a lattice $\Lambda_2$ in k^n, and then you showed that $\Lambda_1+\Lambda_2'$ is a lattice (and it obviously contains both).


What am I missing in jsFiddle for AngularJS example

Question: I am trying to run some AngularJS code in jsFiddle but nothing is showing. I must be missing something:

            <my-customer></my-customer>

Javascript:
angular.module('myApp', [])
    .controller('Controller', ['$scope', function ($scope) {
    $scope.customer = {
        name: 'Naomi',
        address: '1600 Amphitheatre'
    };
}])
    .directive('myCustomer', function () {
    return {
        restrict: 'E',
        templateUrl: 'my-customer.html'
    };
});

http://jsfiddle.net/AndroidDev/Wd72j/5/
EDIT:
I came across this example which does show AngularJS working:
http://jsfiddle.net/dakra/U3pVM/
But what I don't understand is why there is an additional version of AngularJS listed in the dropdown list whereas in mine it doesn't exist.
Answer: I guess you haven't take a look into console output
you had a templateUrl but no file was attached so it simply couldn't be loaded
http://jsfiddle.net/Wd72j/6/
Comment: I copied that code straight from angularjs.org website not realizing that the templateUrl was invalid. I also discovered that you also need to use the "no wrap - in " option, otherwise AngularJS will not work at all.


Difficulty in Installing Windows Azure Access Control Services filter plugin for java in eclipse

Question: I'm trying to install the ACS plugin using this link http://msdn.microsoft.com/en-us/library/windowsazure/hh690946.aspx
But, I'm getting this error.
Cannot complete the install because some dependencies are not satisfiable
  com.microsoftopentechnologies.acsfilter.feature.feature.group [0.2.0.201211010928] cannot be installed in this environment because its filter is not applicable.
Any idea what needs to be done?
I've Eclipse Juno
Answer: Are you on Windows or non-Windwows OS? As documented here this plugin requires Windows Azure SDK 1.8 in the machine and without it you will hit error:
<code>This plugin requires Windows Azure SDK 1.8. This can be downloaded using the Web Platform Installer (WebPI) at http://go.microsoft.com/fwlink/?LinkID=252838. However, if you don't have it installed, when you create your first Windows Azure deployment project, the plugin will automatically install Windows Azure SDK 1.8.
</code>
You can get an test Windows machine to give a try first and then learn how you can port the code to other machine. Not a clean way to achieve what you want but at least you have some option.


Dedicated server issues with SSL and IPs, content showing on wrong site

Question: We have a number of sites on this dedicated server. Pages from one site are showing up on another site. Example:

clientsite1.com (right site, no SSL installed)
clientsite2.com (forwards to SSL, shows right site)
clientsite1.com (no SSL installed, WRONG site, shows clientsite2 after "untrusted connection" message)

Now I'm in WHM and this is what I see:
The one that says "Is primary website on IP address?" is the one that's showing up improperly across all non-SSL domains. I am assuming this is because the OTHER domain on our IP address has "Web SNI" enabled, which apparently allows you to use multiple certificates on one IP?
To fix this problem, would someone confirm these steps please?

Get each site on own dedicated IP.
Delete the SSL host for each site in WHM.
Re-add the SSL host for each site in WHM, with new dedicated IP address.

Or I can somehow also enable "Web SNI" for the domain that is currently showing improperly? Not sure how to do that, but I'll look it up if someone can confirm it will fix the problem.
I found another question on here with this comment but I'm not sure if it applies to my situation: "... at least on Apache a properly setup name-based virtualhost should display the correct content, even with SSL (I've used this myself). You'll get the "this is a bogus cert" warning, but if the client accepts the cert, the client will still send the Host header to the server, which Apache should use to select a VirtualHost block and show the correct content, not someone else's site." Is that the case here? If this is the case, what can I say to my webhost that will make them understand (and fix!) the problem?
Comment: [Administration panels are off topic](http://serverfault.com/help/on-topic). [Even the presence of an administration panel on a system,](http://meta.serverfault.com/q/6538/118258) because they [take over the systems in strange and non-standard ways, making it difficult or even impossible for actual system administrators to manage the servers normally](http://meta.serverfault.com/a/3924/118258), and tend to indicate low-quality questions from *users* with insufficient knowledge for this site.
Comment: Sorry and thanks -- is there somewhere else I can post this where it'd fit better?
Comment: [Pro Webmasters, maybe](http://webmasters.stackexchange.com/).
Comment: @Hopeless are you going to migrate it? I've got an answer already posted against the Q that i'd like left associated if possible.
Comment: I already reposted to Pro Webmasters but I'll delete if this is migrated? Here's the [link](http://webmasters.stackexchange.com/questions/78794/dedicated-server-issues-with-ssl-and-ips-content-showing-on-wrong-site) to it if that helps.
Answer: Your listed third option is when clientsite1 is accessed via https. The certificate error is because your SSL certificate is (only) for clientsite2. Here are your options:

You want clientsite1 to be accessible via SSL, via a single IP

You need a multidomain SSL certificate that has both clientsite1 and clientsite2 listed.
Your SSL vHost configuration needs to route by name, just like your non-SSL configuration already does

You want clientsite1 to be accessible via SSL, via multiple IPs

You need an SSL certificate for each clientsite1 and clientsite2
Your SSL Host configuration can be bound by IP address to the single clientsite1 or clientsite2 (no vHost configuration required)

You don't want clientsite1 to be accessible via SSL

Stop accessing clientsite1 via https
Use a second IP address to handle clientsite1 so that there is nothing listening on the https port
Comment: #3 for sure. We don't need clientsite1 accessible via SSL. But us not accessing clientsite1 over HTTPS won't stop Google accessing over SSL (we are getting backlinks etc. for the wrong site). But there are a lot of other sites on that same server -- so we should, instead of moving all those sites onto their own IPs, move clientsite2 (the SSL site) to a dedicated IP?


Issue with TypeError: list indices must be integers or slices, not dict

Question: For the below code snippet, I receive the error: TypeError: list indices must be integers or slices, not dict.
coin['orderBooks'][i] is indeed a dict, but how can I remove/delete it then? I need to remove from my dataset for further analysis.
#check if bid_price or ask_price exists, if not remove it from orderbooks
for coin in orderbooks:
    for i in coin['orderBooks']:
        bid_price = i['orderBook']['bids']
        ask_price = i['orderBook']['asks']
        if bid_price == [] or ask_price == []:
            del coin['orderBooks'][i]

Traceback (most recent call last):

  File "<ipython-input-47-07d8008d3d9c>", line 6, in <module>
    del coin['orderBooks'][i]

TypeError: list indices must be integers or slices, not dict

Answer: You're misunderstanding, the coin['orderBooks'][i] is not a dict (it even throws the error), the i is an error, you should name it differently, as you access i['orderBook'] you see it's a dict, and to delete it you may use it's index in the array
It would be like :
for coin in orderbooks:
    for idx, val in enumerate(coin['orderBooks']):
        bid_price = val['orderBook']['bids']
        ask_price = val['orderBook']['asks']
        if not bid_price or not ask_price:
            del coin['orderBooks'][idx]

But as remove while iterating is not a really good idea, you may keep the good ones, with a loop comprehension that's easy
for coin in orderbooks:
    coin['orderBooks'] = [val for val in coin['orderBooks']
                              if val['orderBook']['bids'] and val['orderBook']['askas']]

Also you can check for empty list directly with its bool value (bool([]) == False)
Comment: I think deleting entries as you iterate through the list will cause problems. Best to build a new list with only good values.


Intersection of two planes and another plane parallel to the intersection.

Question: I have two questions:
$1)$ How can I find the line of intersection between the planes
$$x+ 2y +z =4 \\ \mathrm{and}  \\ 2x+y-z=5$$
$2)$ How do I find an equation for a line that goes through $A = (2,0,2)$ and $B = (4,1,0)$ that is parallel to the answer in the first question?
I find the intuition on these problems really difficult, so if you describe how you do it, I would be very grateful.
Comment: Some feedback never hurts!
Answer: For the first one, you want to solve the system $$\begin{cases} x+ 2y +z =4 \\ 2x+y-z=5\end{cases}$$ for $(x,y,z)$. For example, summing I am getting that $x+y=3$. Then I am getting that $z=1-y$, so that $$(x,y,z)=(3-y,y,1-y)=(3,0,1)+y(-1,1,-1)$$ Thus, the intersection is a line $$\mathscr L:(3,0,1)+t(-1,1,-1)\;\;;\; t\in\Bbb R$$
For the second one, suppose we can write your line as $$\mathscr L':w+tv\;\;;\;t\in\Bbb R$$ for some vectors $v,w$. Saying that $\mathscr L'$ is parallel to the line we found above means their directions are parallel. Any line is fully determined by a point and a direction, you should be able to obtain what $\mathscr L'$ is. It seems the exercise wants two lines, one that goes through $A$ and one through $B$.
Recall that if we have a line $v+tw$ and we already know what $w$ is, and know that $v'$ is a point in it, we may let say $t=1$ so that $v+w=v'\implies w=v'-v$, that is, we may let $w$ be $v'$ plus any scalar multiple of the direction we want.
Comment: Thank you very much!

But how do you go from " x+y=3. Then I am getting that z=−y, so that " to giving the values 0 to both z and y?

My book gives the answers "1) x=t y=3-t og Z=-2+t" and "2) x+4y+3z-8=0"
Comment: @KaizervonMaanen Note that by replacing $x=3-y$ we get $3-y+2y+z=4$ so that $y+z=1\implies z=1-y$. Sorry about the slip. =)
Comment: @KaizervonMaanen Your book "solved for $x$", that is, it is getting $(x,y=3-x,z=x-2)$.
Comment: Thank you... how do I represent the second equation (the line A-B) as a parametric equation?
Comment: @KaizervonMaanen A line passing through $v$ with direction $w$ has equation $p(t)=v+wt$
Comment: can you explain it a bit simpler? What steps do I have to do with two points A =(1,0,0) and B =(2,3,3) for example, to represent the line A-B.
Comment: @KaizervonMaanen As I just said, I think the exercise wants you to write the equation of two lines, one passing trough $A$, another passing through $B$, but both with direction paralell to $(-1,1-1)$.


Understanding partial expectation.

Question: I am new to probability and statistics, I am reading an article on survival analysis and when defining the expectation of a parametric model, log-normal distribution, the author used the partial expectation. I did a research and found nothing significant, or rather nothing that provide me with a good understanding, so what is that partial expectation, definition, properties. Thankful
Answer: I would consider the Wikipedia article section on partial expectation of the lognormal distribution to be a superior reference, since it:

gives a clear mathematical definition
is not paywalled
fits with the original question's context in regard to survival models and lognormal distributions
is presumably more stable as a link for future reference than a publisher's link to an abstract.

For the sake of completeness, the partial expectation of a continuous random variable $X$ is given by $$\operatorname{E}[X \mid X > k]\Pr[X > k] = \int_{x=k}^\infty x f_X(x) \, dx.$$
Answer: The partial expectation is a measure concerning a portion of the standard normal distribution; either on the right-hand side or on the left-hand side of the standard normal.
you can read more in this link.

Understanding partial expectation.


Can't execute Kotlin scripts from Rust

Question: I'm trying to run kotlinc from within Rust on Windows. Here is a small snippet of my code:
let mut script_number: u32 = 0;
let script_path: String = format!("run/script-{script_number}.kts");

println!("Running Script: {script_number}");

let mut file = OpenOptions::new()
    .read(true)
    .write(true)
    .create(true)
    .open(script_path.clone())
    .expect("Could not create file");

file.write_all(
    self.editor
        .buffer()
        .expect("Couldn't read buffer.")
        .text()
        .as_bytes(),
)
.expect("Could not write to file");

let mut child = Command::new("./kotlinc")
    .arg("-script")
    .arg(script_path.clone())
    .stdout(Stdio::piped())
    .spawn()
    .expect("Could not execute script");

let stdout = child.stdout.take().expect("Could not read output");

let lines = BufReader::new(stdout).lines();

for line in lines {
    println!("{}", line.unwrap());
}

script_number += 1;

I get the following output and error:
Running Script: 0

thread 'main' panicked at 'Could not execute script: Os { code: 5, kind: PermissionDenied, message: "Access is denied." }', src\main.rs:265:30
stack backtrace:
   0: std::panicking::begin_panic_handler
             at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library\std\src\panicking.rs:575
   1: core::panicking::panic_fmt
             at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library\core\src\panicking.rs:65
   2: core::result::unwrap_failed
             at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library\core\src\result.rs:1791
   3: enum2$<core::result::Result<std::process::Child,std::io::error::Error> >::expect<std::process::Child,std::io::error::Error>
             at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943\library\core\src\result.rs:1070
   4: gui_editor::App::launch
             at .\src\main.rs:260
   5: gui_editor::main
             at .\src\main.rs:291
   6: core::ops::function::FnOnce::call_once<void (*)(),tuple$<> >
             at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943\library\core\src\ops\function.rs:251
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.

I suspect it's that the file created does not have execute permissions, however, after scouring the internet I cannot seem to find a way that gives the file execute permissions. Some answers online reference a mode function however that function doesn't seem to exist when I try to run it.
Just for context, the run directory stores scripts that have been scheduled to run by the program, and both it and the kotlinc (a copy of the Kotlin compiler) directories are sibling directories of the Rust src directory.
Comment: This might be of help: https://stackoverflow.com/questions/67276504/rust-imageioreader-permission-denied
Comment: This worked in removing this error, however now I have another error. Here is some debug output along with the error at the very end: Running Script: 0 File { handle: 0x39c, path: "\\\\?\\D:\\Files\\Documents\\gui-editor\\script-0.kts" }

The current directory is D:\Files\Documents\gui-editor

File exists: true

thread 'main' panicked at 'Could not execute script: Os { code: 2, kind: NotFound, message: "The system cannot find the file specified." }', src\main.rs:271:30
Answer: I've found the answer after digging around in the kotlinc file. The file that needs to be run is ./kotlinc/bin/kotlinc.bat i.e.:
std::process::Command::new("./kotlinc/bin/kotlinc.bat")
        .arg("-version")
        .stdout(Stdio::piped())
        .spawn()
        .expect("Could not execute script");

Can't execute Kotlin scripts from Rust


I need php function to get time from browser not server

Question: I am programming forum script and I have problem in time because the server time defrent from my country time;
I tried to use this own function but the problem transferred to my friends in other countries hhhhh:
<code>function ftime($time, $reg = false)
{
    $time = $time ;
    $mytime = protect($_SESSION['mytime']);
    $time = $time + $mytime;
    $time2 = time() - 3600  + $mytime;
}
</code>
** note : this not all of my function
Comment: You need javascriot for this
Comment: @JohnConde --> how to do that??
Answer: PHP is a server side language and can not directly get client's Time. You will have to check for timezones and write your own function with a little help from client side scripts.
Comment: thank you,, is there a free ready function or class for that??
Comment: Yeah there will be plenty. Just google 'javascript get client time' and you will get many
Answer: exactly, you need some help from js to determine the timezone.
check this ones:
How to get client's timezone?
Determine a User's Timezone


Como executo um algoritmo quando o usuario deixa de tocar na tela?

Question: Gostaria de, quando o usuário pressionar a tela, abrir um menu horizontal com 4 opções onde a opção a qual ele soltar o dedo em cima será a selecionada.
O evento de pressionar eu ja sei.
seria este:
btn_operacao.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            //algoritmo . . .
            return true;
        }
    });

Qual seria o evento para pegar o momento em que o usuário remove seu dedo da tela?
Answer: O OnLongClickListener não serve para isso. Ele é para todos os passos que formam um evento de clique longo (aquele que costuma ser usado para trazer o menu de contexto).
Você precisa ir para um nível mais baixo-- usar o OnTouchListener, em conjunto com as ações ACTION_DOWN e ACTION_UP
minhaView.setOnTouchListener(new OnTouchListener () {
  public boolean onTouch(View view, MotionEvent event) {
    if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
      // mostre o menu que aparece quando o usuário toca na tela
    } else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
      // o usuário soltou o toque. Execute a lógica de decidir qual opção foi selecionada
    }
    return true;
  }
});

Também pode ser interessante tratar o caso do ACTION_CANCEL, que é quando o usuário (de alguma forma) cancelou o toque sem soltar o dedo na sua View. Nesse caso, trate como se nenhuma opção tivesse sido escolhida.
Comment: Verdade. Consertado. :)
Comment: Obrigado, funcionou! Fecha ali no fim do códico com um ); Abraço!


Is my entropy calculation correct? Clustering entropy example

Question: I would like to calculate entropy of this example scheme
http://nlp.stanford.edu/IR-book/html/htmledition/evaluation-of-clustering-1.html

Equation of entropy
Then the entropy is (the first line)

So entropy is for this scheme
For the first cluster - ( (5/6)*Log(5/6) + (1/6)*Log(1/6) )
For the second cluster  - ( (1/6)*Log(1/6) + (1/6)*Log(1/6) + (4/6)*Log(4/6) )
For the third cluster  - ( (2/5)*Log(2/5) + (3/5)*Log(3/5) )

Final entropy is :
 FirtCluster_Entropy + SecondCluster_Entropy  + ThirdCluster_Entropy

Am i correct?
Answer: One step is missing, you must do the overall computation:
(N1/N)*FirtCluster_Entropy + (N2/N)*SecondCluster_Entropy  + (N3/N)*ThirdCluster_Entropy

Where N1=6, N2=6 and N3=5 correspond to length of each cluster, and N=17 is the total amount of objects. Then
H = (6/17)(0.650022421648) + (6/17)(1.25162916739) + (5/17)(0.970950594455)
 = 0.956744853323706


Odd Meter Transcription Practices

Question: I've occasionally found myself listening to music that's not always in standard meter.  Either through odd time signatures, syncopation, or a combination of the two, certain music seems hard to imagine what the time signature may be for the purposes of transcription.  What exercises exist to help identify these oddities?  In particular, I'm looking at:

Which note gets the beat (denominator in time signature)
How you identify syncopation vs. odd time signatures
How you identify time signatures
Comment: Sometimes there is not one answer to those questions. Even at a very basic level, the difference between 2/4 and 4/4 can be subtle. Also 5/4 versus 2/4 followed by 3/4 is almost a matter of preference if there isn't an obvious rhythm. A good rule of thumb is to go with what feels best at a macroscopic level. For instance, if you think the piece is more of a march feel, then you would go 2/4 instead of 4/4, all other things being equal.
Comment: The original version of Stravinsky's *Rite of Spring* has many changing meters to notate the complex-sounding rhythms. Later, Stravinsky revised it and just put most of it into standard meters like 4/4 to make it easier to conduct. It sounds exactly the same in either version.
Comment: 'For the purpose of transcription' - if it's for you to replay, then it's not going to be so important as to whether you change the time sig. or just add accents when you think necessary. Even if it's for others, often the end result will be the same in performance. A time sig. is going to be decided when a piece has a regular number of beats per bar. Generally beat one is recognised as the most prominent, but that's nowhere near true in a lot of songs or styles. Todd mentioned 5/4: if the rhythm is similar throughout, then it makes sense to leave at 5/4 rather than alternate every other bar.
Comment: @AndrewCashner - as I wrote my comment, 'Rite of Spring' sprang to mind. I often thought that there was perhaps a different - better- way to write it.
Comment: @Tim, it's for the purpose of playing, but more archival than that.  Also, what I intend on transcribing has quite a bit to do with rhythm.  I think a closer-to-original transcription in written form is worth the few extra practice sessions to get multiple time signatures down, than some oddly syncopated common-time transcription.
Answer: As Todd states in his comment, there isn't "one way" to notate rhythms. After all, notation is just a partial representation of the sounds produced, and several may be possible and equally correct. I have an answer over here for more on this.
Therefore, the best notation will be the clearest expression of artistic intent. Some guidelines I suggest:

Which note gets the beat?

I'd start instead by determining which notes are the most common and near the middle of the used durations. Most pieces rely heavily on about three durations - make these your quarter notes, eighths, and sixteenths if it's a faster feeling piece, and halves, quarters, and eighths if it feels slower. You want to make as many of the notes as possible easy to count, so if you have some much faster notes than "average", use that to inform your decision.
Once you get the rhythm of a passage roughed in, hopefully you'll start to see patterns. Your ear will tell you if a particular bit of music feels the same as another, so you can start to put in your barlines. If not, go on to the next question and come back to this.

How do you identify syncopation vs odd time signatures?

Go for simplicity here. If the pattern keeps changing chances are you're looking at syncopation. If it's more regular, you'd be better off writing in that meter. You may try it with two time signatures and see which is easier to read.
Don't forget about time signatures such as 3+3+2/8. At slow speeds, this could feel like the meter is constantly shifting between 3 and 2, but with careful notation it can be clearer to read as 4/2 or 4/4. Also remember that it is possible to have a hemiola going through many measures, but that the underlying pulse might be the same.
When in doubt, choose the voice with the most repetition of pitches to look for clues as to what's going on. If you have a percussion or bass part, they usually are providing a rhythmic structure for other voices. If multiple voices keep having cross rhythms, at least one of them is syncopated.

How do you identify time signatures?

In one ethnomusicology class, we were introduced to an eastern dance form in 5 that was described indigenously "limping dance". This has stuck with me as a way to identify odd time signatures - can a passage be danced in a "limping" way with some regularity? For example, a dance in slow five (think Mars) would feel like two dance steps with a limping third. A faster five might feel like two uneven steps.
Once you figure out whether you're dealing with an odd time signature or not, start tapping along. How many pulses are there in the measure? Are some strong and weak? If you're not sure, tap at double the speed of the main rhythmic progression and use that as the subdivision of the beat.
The number on the bottom of the time signature is determined by legibility. Are there a whole pile of notes in a measure? It's x/2 or x/4. Lots of notes that cover whole measures? x/8. Keep it easy to read.
Ultimately it all comes down to communicating intent effectively. It make take a few tries and some time away from the piece to get it right.

Odd Meter Transcription Practices


Interpretations of time-series data with standard errors

Question: I have plotted time-series data on estimates of pollutant emissions superimposed with standard errors of the means. See the figure below. In reality, quantities of emissions should be non-negative. However, the data I presented here were calculated from different data sources. So in the figure, the means are all non-negative, however, when superimposed with standard errors, the lower bounds of SE before 1950 might become negative, which is unreal and indicates that there is a possibility that the emissions did not happen. So I just want to understand the possibility of no emissions, can I say that

before 1915, the possibility of no emissions is nearly 50%.
from 1915 to 1950, the possibility of no emissions is at least 15.8% and at most 50%.
from 1950 onwards, the possibility of having pollutant emissions is at least 84.2%, and conclude that this period is significantly different from the period pre-1950 because the lower bounds are above zero which is unreal.
Comment: What pollutant is this?
Answer: All these are incorrect because of misunderstandings about what probabilities, error bars and confidence bands mean. I recommend reading a good textbook about them, and this paper specifically about interpreting error bars: Error bars in experimental biology.

No, this is wrong for multiple reasons. (i) The line does not appear to go exactly to zero, just some low positive value. (ii) A standard error is not the same thing as a probability. (iii) There are issues relating to detection limits and data quality which get worse the further back in time we go. (iv) It's unclear what pollutant this figure refers to, but if you dig far enough, you will almost certainly find examples of emissions before the date you have chosen. For example, the internal combustion engine was invented in the 19th century. Even if we could not detect its effects on the atmosphere till much later, we know for a fact that pollution was not precisely zero, which refutes your claim ("possibility of no emissions is 50%").
No. Again, this conflates estimates of uncertainty with probability of a quantity being zero.
No. Aside from the same conflation issue, there are different types of error bars and they mean different things.

Finally, there is a fundamental problem here. Your estimates of uncertainty are assuming that pollutant emissions can go negative, which is not logically possible unless you assume that we can and did pull pollutants out of the environment (which may be true, but is unlikely and cannot be judged based on your question).
[Edited in response to question edit]
A better approach to displaying and assessing uncertainty would consider what the distribution should look like. It would certainly be asymmetric, but it probably would not look like just a truncated version of the above plot. Zero might well be a very unlikely value when the appropriate distribution is used.
Comment: @Elizabeth 1) Possibility is not the same thing as probability. Probability has a technical, mathematical meaning while possibility does not. 2) Switching to confidence intervals does not fix the problem. The confidence interval also *expresses uncertainty in the mean value*. A [credible interval](https://en.wikipedia.org/wiki/Credible_interval) is closer to what you need. But I really recommend reading a good text about these first.
Comment: thank you for your reply, I have amended my question according to the confusions you had. It is all because I simplified the explanation. The emissions are always non-negative. But before a certain time, the emissions indeed non-exist, thus equal to zero. I would like to know when emissions become above zero. My biggest puzzle is the interpretation of the standard errors. You have pointed out SE does not equal to probability. Is that true I have to convert SE to confidential intervals to have a possibility-wise understanding.


How to access a contributed module Information from drupal.org

Question:
Is there any API to access Information about a contributed module
from drupal.org site?
How does Update Manager access information
from drupal.org?

By finding this I think I too could access other data similarly and I also need Hook API documents to be accessed from drupal.org in my site.
Did anyone do this before? If so please guide me.
Answer: An update URL is formatted as:
http://updates.drupal.org/release-history/[project-name]/[api-version]

So for Views v7, for example, that would be:
http://updates.drupal.org/release-history/views/7.x

I think that's as much information as Drupal.org makes available about modules via its API. You won't find a structured way to query information about hooks, for the same reasons we talked about in your similar recent question


$R^n$ satisfies the second axiom of countability

Question: I proved it but I'm not sure if it's right. The definition of the basis for the euclidean topology on $R^n$ is $\beta = \{<x_1,x_2,...,x_n>\in R^n\, : \, a_i<x_i<b_i,\, i = 1,2,...,n\}$. So my proof is:

Put the basis $\beta' = \{<x_1,x_2,...,x_n>\, : \, n<x_i<n+1,\, n\in Z\, and\, i = 1,2,...,n\}$, then $R^n$ satisfies the second axiom of countability.

Because $\beta'$ contains a countable number of elements.
I think $\beta'$ is not a basis, what's wrong?
Comment: Each element of $\beta'$ is too big to form a basis. That's the reason why $\beta'$ is not a basis for $\mathbb{R}^n$.
Answer:
The set of real number $\mathbb{R}$ with the standard topology is second countable. For example,
  $$
\mathscr{B}=\{ (a,b) \subset \mathbb{R} \mid a<b,\ a,b\in\mathbb{Q} \}
$$
  is a countable basis of $\mathbb{R}$, where $\mathbb{Q}$ is the set of rational numbers.

If you agree with the fact above, it is easy to find a countable basis for $\mathbb{R}^n$, for example,
$$
\mathscr{B}'=\{ (a_1,b_1)\times(a_2,b_2)\times\dotsb\times(a_n,b_n) \subset \mathbb{R}^n \mid a_i<b_i,\ a_i,b_i\in\mathbb{Q} \text{ for all $1\leq i\leq n$} \}
$$


General Steinitz exchange lemma

Question: Where can I find a proof of the following general Steinitz exchange lemma:

Let $B$ be a basis of a vector space $V$, and $L\subset V$ be linearly independent. Then there is an injection $j:L\rightarrow B$ such that $L\cup(B\setminus j(L))$ is a disjoint union and a basis of the vector space $V$.

Or can someone suggest a proof of this result? Probably using Zorn's lemma.
Thank you!
Comment: @Censi LI: The axiom of choice tag is for questions asking specifically about the role of the axiom of choice in a proof, or what sort of statement are consistently true without the axiom. This question does not seem to fit into that tag. Similarly, this is not a set theory question.
Comment: @Censi LI: No need to apologize. Just for future reference.
Comment: @AsafKaragila I'm so sorry...
Comment: [Here](https://specksofmath.wordpress.com/2016/04/23/the-steinitz-replacement-theorem-for-modules/) you can find a blogpost about a very general replacement theorem of Steinitz for modules.
Answer: Let $W$ denote the subspace generated by $L$, $\mathcal B$ denote the set of subsets of $B$ whose images in $V/W$ are linearly independent. There is an obvious partial order on $\mathcal B$, namely the one induced by inclusion. Apply Zorn's Lemma to obtain a maximal element of $\mathcal B$, denoted by $C$, then the disjoint union $C\cup L$ forms a basis of $V$, just as $B=C\cup(B\setminus C)$ do. So there must be a bijection $j:L\xrightarrow{\sim}B\setminus C$. This $j$ will fulfill the requirement.
Comment: It is not true that every chain in $\mathcal{L}$ has an upper bound--see my answer at https://math.stackexchange.com/questions/2341188/steinitz-exchange-lemma-proof-help.  The problem is that at each step of the chain you are removing new elements of your spanning set since $j(L')$ is getting larger, and the limit may end up not spanning.
Comment: @EricWofsey Thank you, I've reworked the proof.
Comment: Minor correction (after choosing $C$): both $L$ and $B \setminus C$ form bases of $V / \sum C$, from which the asserted bijection follows.Note that is not true for infinite sets that, when you remove two sets in bijection, what remains remains in bijection.
Comment: Oh, I guess you can argue that the bijection can be made so that it fixes the intersection of the two bases pointwise.
Answer: Choose (by using Zorn's Lemma) a subset $B'$ of $B$ maximal with the property that $\langle L\rangle\cap \langle B'\rangle=0$. Then $\langle L\rangle+\langle B'\rangle=V$: if $b\in B-B'$ then $\langle L\rangle\cap \langle B'\cup\{b\}\rangle\ne0$ hence there are $l_i\in L$, and $b_i'\in B'$ such that $\sum\alpha_il_i=\sum_i\beta_ib_i'+\beta b$ with $\beta\ne0$, so $b\in \langle L\rangle+\langle B'\rangle$.
Now use that any two bases of a vector space are equipotent. Let $V'=\langle B'\rangle$. The quotient vector space $V/V'$ has the following bases: $L$ and $B\setminus B'$. Then there is a bijection $f:L\to B\setminus B'$ which composed by the inclusion $i:B\setminus B'\to B$ gives us the desired injection, that is, $j=i\circ f$.

General Steinitz exchange lemma


D7 - does drush rr ALSO clear cache?

Question: Someone just told me that in D7, drush rr and drush cc all do the same thing. I can't find anything that explicitly states the difference, nor can I find anything that supports such a claim. Additionally, I've noticed there are some changes that seem to only show up with a drush cc all, particularly changes to code. Do drush rr and drush cc all actually implement the same functionality?
Answer: See https://drushcommands.com/drush-7x/registry-rebuild/registry-rebuild
drush rr has the option:
--no-cache-clear : Rebuild the registry only, do not clear caches.
drush rr rebuild the registry + clear the caches.
drush cc clear the caches only.

D7 - does drush rr ALSO clear cache?


How to draw the graph of $8x^3 -6x+1=0$?

Question: How to draw the graph of $8x^3 -6x+1=0$?
Any generalization of a graph of polynomials of degree 3 is helpful.
Comment: You can use Wolfram Alpha to plot $$8x^3-6x+1$$
Comment: Usually, you create a value-table. If you know the critical points and the roots, you can already estimate how the graph will look like.
Comment: @Peter I want to determine the range of the roots from the graph. So, can you please elaborately explain how to draw it?
Comment: https://math.stackexchange.com/questions/2157643/how-can-i-solve-the-equation-x3-x-1-0 and https://math.stackexchange.com/questions/2203364/solve-the-following-equation-x3-3x-sqrtx2
Comment: @Rhea If you find values $x_1$ and $x_2$ such that $f(x_1)$ and $f(x_2)$ have distinct signs , then you can conclude that there must be at least one root between $x_1$ and $x_2$. To estimate the roots ONLY from a graph, a value table with sufficiently many $x$-values is usually the best way.
Answer: A good method I use to plot graphs:
A) Domain
B) Intercepts $x,y=0?$
C) Symmetry/Periodicity:
Symmetry: If $f(-x)=f(x)$ on the domain then it is EVEN (symmetric about y axis).
Or $f(-x)=-f(x)$ on domain then it is ODD (symmetric about the origin).
Can be neither odd or even.
Periodicity: Where $f(x+p)=f(x)$ where $p$ is a positive constant.
D) Asymptotes (horizontal/vertical)
E) Intervals of increase or decrease ($f'(x)$)
F) Local Min/Max or Inflection ($f'(x)=0$)
G) Concavity ($f''(x)$)
Comment: If you need any more details then please let me know I can elaborate!