Ribbon Invalidate makes my outlook add-in crash

Question: I have a pretty large outlook add-in with following ribbon.xml:
<?xml version="1.0" encoding="UTF-8"?>
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="Ribbon_Load">
  <ribbon>
    <tabs>
      <tab idMso="TabMail">
    <group id="groupViewHome" label="View tasks">
      <toggleButton id="buttonToggleHistoryHome" getLabel="getLabelToggleHistory" imageMso="ControlToggleButton" onAction="toggleHistory_Click" size="large" getPressed="getEnabledToggleHistory" />
    </group>
      </tab>
      <tab idMso="TabAddIns" label="DCP">
    <group id="groupCreateTask" label="Create a task">
      <button id="buttonNewTask" label="New Task" imageMso="QueryAppend" onAction="buttonNewTask_Click" size="large" getEnabled="getMailSelected" />
    </group>
    <group id="groupEdit" label="Edit a task">
      <button id="buttonAddSelection" label="Copy selection to task" imageMso="QueryUpdate" onAction="selectedText_Click" size="large" getEnabled="getMailAndIDSelected"/>
    </group>
    <group id="groupView" label="View tasks">
      <button id="buttonTaskHistory" imageMso="FileDocumentInspect" onAction="taskInfo_Click" getLabel="getButtonHistoryLabel" />
      <toggleButton id="buttonToggleHistory" getLabel="getLabelToggleHistory" imageMso="ControlToggleButton" onAction="toggleHistory_Click" getPressed="getEnabledToggleHistory" />
      <checkBox id="buttonTriggerMail" label="Toggle auto-history" onAction="Trigger_Click" getPressed="getInitialTriggerState"/>
    </group>
    <group id="groupAttach" label="Attachments">
      <button id="saveMail2" label="Add mail as .msg attachment" imageMso="AttachItem" onAction="saveMail_Click" getEnabled="getMailAndIDSelected"/>
      <button id="selectAttach" label="Select attachments to add" imageMso="AttachMenu" onAction="selectAttach_Click" getEnabled="getMailAndIDSelectedAndAttach"/>
    </group>
    <group id="groupLinks" label="Hyperlinks">
      <button id="addLinkToMail" label="Add task link to mail body" imageMso="HyperlinkInsert" onAction="addLink_Click" size="large" getEnabled="getMailAndIDSelected"/>
    </group>
      </tab>
    </tabs>
  </ribbon>
  <contextMenus>
    <contextMenu idMso="ContextMenuReadOnlyMailText">
      <menu id="dcp" label="DCP">
    <button id="selectedText" label="Copy selection to task" imageMso="CitationInsert" onAction="selectedText_Click"/>
    <button id="addTask" label="New task" imageMso="GoToNewRecord" onAction="buttonNewTask_Click" />
      </menu>
    </contextMenu>
    <contextMenu idMso="ContextMenuReadOnlyMailTable">
      <menu id="dcp3" label="DCP">
    <button id="selectedText2" label="Copy selection to task" imageMso="CitationInsert" onAction="selectedText_Click"/>
    <button id="addTask3" label="New task" imageMso="GoToNewRecord" onAction="buttonNewTask_Click" />
      </menu>
    </contextMenu>
    <contextMenu idMso="ContextMenuReadOnlyMailTableCell">
      <menu id="dcp4" label="DCP">
    <button id="selectedText3" label="Copy selection to task" imageMso="CitationInsert" onAction="selectedText_Click"/>
    <button id="addTask4" label="New task" imageMso="GoToNewRecord" onAction="buttonNewTask_Click" />
      </menu>
    </contextMenu>
    <contextMenu idMso="ContextMenuReadOnlyMailListTable">
      <menu id="dcp5" label="DCP">
    <button id="selectedText4" label="Copy selection to task" imageMso="CitationInsert" onAction="selectedText_Click"/>
    <button id="addTask5" label="New task" imageMso="GoToNewRecord" onAction="buttonNewTask_Click" />
      </menu>
    </contextMenu>
    <contextMenu idMso="ContextMenuReadOnlyMailPictureTable">
      <menu id="dcp6" label="DCP">
    <button id="selectedText5" label="Copy selection to task" imageMso="CitationInsert" onAction="selectedText_Click" />
    <button id="addTask6" label="New task" imageMso="GoToNewRecord" onAction="buttonNewTask_Click" />
      </menu>
    </contextMenu>
    <contextMenu idMso="ContextMenuReadOnlyMailTextTable">
      <menu id="dcp7" label="DCP">
    <button id="selectedText6" label="Copy selection to task" imageMso="CitationInsert" onAction="selectedText_Click"/>
    <button id="addTask7" label="New task" imageMso="GoToNewRecord" onAction="buttonNewTask_Click" />
      </menu>
    </contextMenu>
    <contextMenu idMso="ContextMenuReadOnlyMailTableWhole">
      <menu id="dcp8" label="DCP">
    <button id="selectedText7" label="Copy selection to task" imageMso="CitationInsert" onAction="selectedText_Click" />
    <button id="addTask8" label="New task" imageMso="GoToNewRecord" onAction="buttonNewTask_Click" />
      </menu>
    </contextMenu>
    <contextMenu idMso="ContextMenuReadOnlyMailList">
      <menu id="dcp9" label="DCP">
    <button id="selectedText8" label="Copy selection to task" imageMso="CitationInsert" onAction="selectedText_Click" />
    <button id="addTask9" label="New task" imageMso="GoToNewRecord" onAction="buttonNewTask_Click" />
      </menu>
    </contextMenu>
    <contextMenu idMso="ContextMenuReadOnlyMailHyperlink">
      <menu id="dcp10" label="DCP">
    <button id="selectedText9" label="Copy selection to task" imageMso="CitationInsert" onAction="selectedText_Click" />
    <button id="addTask10" label="New task" imageMso="GoToNewRecord" onAction="buttonNewTask_Click" />
      </menu>
    </contextMenu>
    <contextMenu idMso="ContextMenuMailItem">
      <menu id="dcp2" label="DCP">
    <button id="buttonTaskHistoryMail" label="View task history" imageMso="SourceControlShowHistory" onAction="taskInfo_Click" />
    <button id="addTask2" label="New task" imageMso="GoToNewRecord" onAction="buttonNewTask_Click" />
    <button id="saveMail" label="Add mail as .msg attachment" imageMso="AttachItem" onAction="saveMail_Click" />
      </menu>
    </contextMenu>
    <contextMenu idMso="ContextMenuAttachments">
    <button id="buttonAddAttachment" label="Add attachment to task" imageMso="AttachMenu" onAction="addAttachment_Click"/>
    </contextMenu>
  </contextMenus>
</customUI>

As you can see I have a couple of actions that require invalidation to enable, toggle... my buttons. My add-in starts up fine but crashes on some occasions. The following are some examples on which the add-in almost always crashes:

Opening a mail item in a new inspector window and closing it again
Multiple windows open, context menu with custom button in it is opened

The occasions in which it occurs make me pretty sure it has everything to do with the automatic invalidation on creation of a new context menu or ribbon, not when I call it myself. The error does not persist when I remove the getEnabled, getPressed... attributes. I can't figure out a way to surpress the error instead of crashing or how to fix it. So if anybody can help or can give me more info on this it would be much appreciated. If you need any more code (like the getEnabled, getPressed... methods), let me know.
My invalidate methods. Note that most just return a boolean. These booleans are kept as a private variable inside the ribbon.cs class
public bool getEnabledToggleHistory(IRibbonControl control)
{
   return toggleHistoryPanelState;
}

public bool getMailSelected(IRibbonControl control)
{
    try
    {
        MailItem mailItem = getMail();
        if (mailItem != null)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    catch (System.Exception ex)
    {
        return false;
    }
}

public bool getMailAndIDSelected(IRibbonControl control)
{
    return mailAndIDSelected;
}

public bool getMailAndIDSelectedAndAttach(IRibbonControl control)
{
    if (hasAttachments && mailAndIDSelected)
    {
        return true;
    }
    return false;
}

If I debug in a new Visual Studio instance I get the following:
Unhandled exception at 0x70B5B2A7 (MSO.DLL) in OUTLOOK.EXE: 0xC0000005: Access violation reading location 0x00000000.
If I debug the code from my solution I can never catch the error, nor does it say it has an unhandled one. It just crashes.
Comment: put up your behind C# - how to tell anything from this :)
Comment: My methods needed for invalidate are really simple and most likely not the problem. However I'll post some if you want
Comment: I edited my question to show you the methods for invalidating
Comment: it's not what I want :) - run it in debug and try to catch to see what's going on - you can pretty much get most of the errors - or log.  Isolate and remove everything else but the 'culprits' that cause issue - that'd narrow it down. It could be many things w/ OL, hard to say, make it more specific - I can help but need something
Comment: yep, that's OL - if you can't catch it or log (don't just catch exceptions, put something to dump - you can dump into temp user folder) - my best suggestion, the good old divide and conquer - remove everything (you already said only 'flags' are causing it), just leave one button with one thing in it - 'return' all methods until you get one causing all the problems - something like that...
Comment: and just saw it - you have the last `ContextMenuAttachments` w/o a `menu` - just a button (I don't recall context menus, how it's done) - might be that? check id-s for duplicate etc.
Comment: "don't just catch exceptions, put something to dump - you can dump into temp user folder" You mean putting streamwriters in my code that log messages to a file?
Comment: or using some logger (google, there're many) - I have my own class using since BC :)
Comment: Context menu's can have both buttons inside as menu's. I use the menu for when I'm adding multiple options, adding buttons straight into the context menu is the most known way. No duplicate ID's either, I receive errors on that when I build my code if I have duplicates.
Comment: ...that OL XML system for ribbons etc. is very error prone - so you need to check everything (be meticulous) - and OL errors aren't very descriptive, most of the time just crashes. Btw what happens if you just remove the whole context-menu?
Comment: Then there are only the standard buttons, no custom ones...
Comment: I think I found my mistake, thanks to you. Narrowed it down to the `getMailSelected` method. called the `getMail` method from outside my invalidate and set a static bool accordingly (just like in the other methods). No crashes so far... Thanks man
Comment: super :) can I post an answer then for you to mark that? Even though it's not much of an answer, if it did help :), cheers
Answer: (posting sort of an 'answer' based on our discussion in the comments)
If you can't catch it or log (don't just catch exceptions, put something into dump - you can dump into temp user folder)...
My best suggestion, the good old divide and conquer - remove everything (you already said only 'flags' are causing it), just leave one button with one thing in it - 'return' all methods until you get one causing all the problems - something like that.
(OL XML system for ribbons etc. is very error prone - so you need to check everything (be meticulous) - and OL errors aren't very descriptive, most of the time just crashes. Btw what happens if you just remove the whole context-menu?)


How can I edit the code from url and save to .html file on desktop

Question: Teacher ask me to write java to read html file from school web and cut all unneeded parts (everything that don't need in that web page), left only the announcement part at the center of the website and save as another html file.
I now can read html file into java now but can't write code to edit (to cut unneeded) and save as html file.
code that has been done so far is:
<code>import java.io.*;
import java.net.*;

public class Html {

    public static void main(String[] args) throws IOException {

            URL chula = new URL("http://www.ise.eng.chula.ac.th");
            URLConnection yc = chula.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc
                    .getInputStream()));

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
            in.close();
        }
    }
}
</code>
Comment: What do you mean by "Cut unneeded path" ?
Comment: can you paste the console output? so we can know how your page html is .
Answer: change System.out.println(inputLine); to:
<code>    PrintWriter output = new PrintWriter("newFile.html");
    output.println(inputLine);
</code>
This will create a new file with all the contents of the inputLine typed into the new file.
I have edited the code you put, and think i found the answer you needed
What you have to do, is use a scanner, with the InputStreamReader. The scanner will read the file, or in this case, the URL that you are using. You then must create a new File using the PrintWriter class, and change the while loop to this:
<code>    while(in.hasNext()) {}
</code>
This will read URL that you want, and it will go through each line of the file(URL) and will not stop until it reaches the end. Then you must create a String holding the information from the URl within the while loop. The last thing to do is just write the contents into the file, and ALWAYS make sure to close BOTH the scanner, and the file that you are writing to.
Here is the code:
<code>    import java.io.*;
    import java.net.*;
    import java.util.*;

public class Html {
    public static void main(String[] args) throws IOException {

        URL chula = new URL("http://www.ise.eng.chula.ac.th");
        URLConnection yc = chula.openConnection();
        //BufferedReader in = new BufferedReader(new InputStreamReader(yc
          //      .getInputStream()));
        Scanner in = new Scanner(new InputStreamReader(yc.getInputStream()));

        PrintWriter output = new PrintWriter("newFile.html");
        while (in.hasNext()) {
            String inputLine = in.nextLine();
            output.println(inputLine);
        }
        in.close();
        output.close();
    }
}
</code>
Hope this helps!
Comment: System.out.println is within while loop- did u noticed that?
Comment: Tried, but no data in that file. It just create an empty file.
Comment: did you put the output.println(inputLine) in the while loop?
Comment: both inside and outside the while loop


Is there a analytical formula for Super- and Sub-Poissonian distributions?

Question: I'm currently wrtiting my Bachelors thesis on photon statistics. The way different sources of light can be classified is by Poissonian (coherent light), Super-Poissonian (thermal light) and Sub-Poissonian (n-Photon-states). However, both books that I'm using as primary sources (Rodney Loudon, The Quantum theory of light and Mark Fox, Quantum Optics - An introduction) don't mention explicitly a formula for Sub and Super-Poisson distribution, just that for Sub-Poissonian light the variance $\Delta n$ falls below the expectation $\langle n \rangle$ (that is, $\Delta n < \langle n \rangle$), and for Super-Poissonian $\Delta n > \langle n \rangle$.
For my work, I want to plot three plots with varying $\Delta n$, but same $\langle n  \rangle$. However, I can't do this with the standard Poisson distribution
$$
P(n)=\frac{\mu^n e^{-n}}{n!}
$$
However, I've read that for large expectation values $\mu$, I can approximate the Poisson distribution with a normal distribution. Given that my expectation values usually don't exceed 10, this doesn't seem to be an option.
So I'm here, looking for help from mathematicians and hope that someone can help me.
Answer: Unlike Poisson distribution, sub-Poissonian and super-Poissonian are not distributions, but rather properties of distributions (properties to have larger or smaller variance than the Poisson distribution with the same mean). An example of super-Poissonian distribution is negative binomial distribution, which has two parameters, $r \in \mathbb{Z}_{+}$ and $p \in (0, 1)$, for which $P(n) = \begin{pmatrix}n + r - 1\\ n\end{pmatrix} (1 - p)^r p^n$, the mean $\langle n \rangle = \frac{p r}{1-p}$ and variance $\langle (\Delta n)^2 \rangle = \frac{p r}{(1 - p)^2}$.
Another option is to multiply the parameter of Poisson distribution and the resulting random variable by a factor $\alpha$. For this distribution, $P(x) = \frac{(\alpha \mu)^{\alpha x}}{(\alpha x)!} e^{-\mu \alpha}$ if $\alpha x$ is integer and $0$ otherwise, the mean is $\langle x \rangle = \mu$ and variance is $\langle (\Delta x)^2 \rangle = \frac{\mu}{\alpha}$, so for $\alpha > 1$ the distribution will be sub-Poissonian and for $\alpha < 1$ super-Poissonian.
Edit: correction of the distribution, thanks to @Alex


Plivo SMS is not being sent and getting error in Java

Question: I am integrating Plivo SMS API with my java web application. I want to send messages through my application. I am referring to https://www.plivo.com/docs/getting-started/send-a-single-sms/ link.
Below is the code snippet:
<code>String authId = "{my Auth_id}"; //Your Authentication ID
String authToken = "{my auth Token}"; //Your authentication code
RestAPI api = new RestAPI(authId, authToken, "v1");

LinkedHashMap<String, String> parameters = new LinkedHashMap<String, String>();
parameters.put("src", "+44*******"); // Sender's phone number with country code
parameters.put("dst", "+91*******"); // Receiver's phone number with country code
parameters.put("text", "Hi, text from Plivo"); // Your SMS text message

try {
  // Send the message
  MessageResponse msgResponse = api.sendMessage(parameters);
  // Print the response
  System.out.println(msgResponse);
  // Print the Api ID
  System.out.println("Api ID : " + msgResponse.apiId);
  // Print the Response Message
  System.out.println("Message : " + msgResponse.message);

  if (msgResponse.serverCode == 202) {
  // Print the Message UUID
  System.out.println("Message UUID : " +   msgResponse.messageUuids.get(0).toString());
  } else {
     System.out.println(msgResponse.error);
         }
        } catch (PlivoException e) {
            System.out.println(e.getLocalizedMessage());
     }
</code>
I tried to run this code using console application as well as web application.I am getting exception "com.plivo.helper.exception.PlivoException: Connection to https://api.plivo.com refused". What is wrong with my code? Am I missing anything here?
Comment: Please check your firewall settings to ensure that it's not blocking any traffic. Also, are you using a web proxy? If yes, make sure that your application is using this proxy to handle connections.
Comment: Yes,there was a problem of proxy settings and somehow that was blocking the connection to API. I changed my proxy settings and it started working. Thank you for your help!
Comment: Great! Please mark the questions as answered.
Answer: Plivo Sales Engineer here.
Please check your firewall settings to ensure that it's not blocking any traffic. Also, are you using a web proxy? If yes, make sure that your application is using this proxy to handle connections.


Render Widget as HTML in Code Behind

Question: I have come across a situation where I'm needing to retrieve the rich text content of a page type column, and return that data/HTML as it would appear on a rendered page. A custom web part then serves aggregated data as nodes of XML or JSON.
For the most part this was easy enough in the code behind using DocumentQuery, however the problem is with widgets that have been inserted into the content.
My question is: How do I "render" a widget purely in code? Or even, what process is Kentico doing to render a widget that I might be able to reproduce?
I am somewhat familiar with the widget/web part/user control relationship, so I'm thinking a web part would need to be instantiated (somewhere, somehow) using the properties on the widget, and then accessing the RenderedHTML property of the web part.
Due to the format that widgets are stored in the data, I was hoping that they could just be Resolved with the MacroResolver, but that doesn't seem to be the case.
For reference, here is an example of how the out-of-the-box DateTime widget shows up:
{^widget|(jsuseservertime)False|(name)DateTime|(widget_displayname)Date+%26+time|(width)|(height)^}
Any input is greatly appreciated!
Comment: Why you need to do this via a widget? If it's a content of some page type field (even rich text) you can simply get the treenode in the code and get the value of such a field.
Comment: I believe he is saying it's part of the DocumentContent column in the CMS_Document database, IE the text used in an "Editable Text" webpart.
Comment: Clarification: We are utilizing custom page type fields, with a data type of Long Text / Rich Text, that allow someone to enter rich content and custom widgets via the Form view.

So for a simplistic example, if the rich text field has the content:
"Hello, welcome to the site. The current time is "

The output when retrieving the corresponding database column would be:
"Hello, welcome to the site. The current time is 12:00"

The widgets in use are obviously more complex, and the pages don't necessarily have a template due to the "Container" type pages.
Comment: I meant the "Content only" page type flag, not the container flag :) The content editor may see only the "Content" tab and not the usual "Page", "Design" and "Form" tabs.
Answer: Have you checked this article http://devnet.kentico.com/articles/how-to-resolving-the-inline-controls? It is pretty old. But CMS.ExtendedControls.ControlsHelper.ResolveDynamicControls is available in newer Kentico versions. I think it might resolve you issue.

Render Widget as HTML in Code Behind


ApacheSolr integration

Question: I have a Drupal multisite website, with Apache Solr Search Integration, which is up and running very well in the live server. I am trying to replicate the same website, on another server to use it as a development environment. I have copied all the code and replicated the DB and changed the settings.php file accordingly, but I am getting the following errors.

Memeber profile is not completed.
Apache solr is not integrated on to the server.

Can anyone help me with the steps which I have to follow during the process?
Answer: Solr is a server and you must set up the parameters to this server correctly in your site at this address: admin/settings/apachesolr/settings.
Is there any errors in the status report ?
Answer: When cloning your live site, you inherited the Solr settings from its database. It's likely that the Solr server for live site is either running on the same server or on some host un-reachable from the development environment.
You need to setup a Solr server for your development environment and configure your development site to use this server. You can use the same server to host your live and development Solr, but you need to use different indexes for each site.

ApacheSolr integration


Exclusão de registro em tabelas em cascata

Question: Tenho uma tabela "Termos" que seu ID é FK de "TermosExpressao".
Conforme mostrado na figura abaixo.
Quando vou executar o comando "delete Termos where IDTermo = 4" o sql me gera
o seguinte erro.

The DELETE statement conflicted with the REFERENCE constraint
  "FK_TermoExpressao_Termos1". The conflict occurred in database
  "SprintJuncao", table "dbo.TermoExpressao", column 'IDTermoExpressao'.
  The statement has been terminated.

Pelo que li me parece que isso é uma exclusão em cascata, quando eu excluir os registro de  "Termos" automaticamente devo excluir os registros relacionados á "TermosExpressao",
No caso todos os registro em TermosExpressao com IDTermo = 4
Alguém pode me ajudar como devo proceder nesse caso?
Comment: terás que excluir primeiro os dados da tabela `TermoExpressao`, podes fazer assim `delete dbo.TermoExpressao where IDTermo = 4`
Comment: Outra coisa que poderias fazer, seria alterar a tua FK para ser `delete cascade`
Comment: @PabloVargas Eu acho que o correto no meu caso seria esse delete cascade, como procedo para fazer isso?
Answer: A melhor solução então é alterar sua FK para que ela seja delete cascade
ALTER TABLE [dbo].[TermoExpressao] DROP CONSTRAINT [FK_TermoExpressao_Termos1]
GO
ALTER TABLE [dbo].[TermoExpressao]  WITH CHECK ADD  CONSTRAINT [FK_TermoExpressao_Termos1] FOREIGN KEY([IDTermo])
REFERENCES [dbo].[Termo] ([IDTermo])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[TermoExpressao] CHECK CONSTRAINT [FK_TermoExpressao_Termos1]
GO

outra opção, para resolver isso seria modificar a sua FK conforme as imagens.
Comment: a FK_TermosExpressao_Termos já está dessa forma. Tem outra FK_TermosExpressao_Termos1 que referencia IDTermosExpressao ao IDTermos. Sem isto, será que o erro está sendo gerado ai?
Comment: Provavelmente, terás que por em ambas suas FK o `delete cascade`


Flask Callback when Application Context is Available

Question: I have a function that I want to call that generates a set of urls. However, to fully generate the urls (using url_for()) I need to have an application context that's available with SERVER_NAME set.
I'm looking for a solution that doesn't involve setting SERVER_NAME explicitly, but instead a solution that would involve running my function as soon as a full application context is available, that is, after a app.run() provides a full application context. I'm running this application on uWSGI, so I'm looking for a solution that works with the uWSGI initialization.
Answer: You could use the before_first_request hook to run the code once, inside the application context, and after the server is fully initialised.
Comment: I'm assuming there isn't an equivalent callback for after server startup is there?

before_first_request normally should work, but this code contains some performance intensive sections. I wouldn't really want to run it during any regular request traffic.
Comment: Not that I'm aware of, but in general performance intensive code shouldn't depend on the web server, so you might want to rethink your design and consider background queues or scheduled jobs.


A question about integration by parts in $\mathbb{R}^n$

Question: Let $h \in L^2(\mu)$ and $\mu = \rho(x)dx$, where $dx$ is Lebesgue measure and $\rho(x)$ is $C^1$. Also, $b(x) = (b_1(x), \cdots, b_n(x))$ is also a $C^1$ function on $\mathbb{R}^n$. Then, does the following integration by parts hold?
$$\int_{\mathbb{R}^n} b \cdot \nabla(h^2)\rho \,dx = - \int_{\mathbb{R}^n} h^2 \nabla \cdot (b\rho)\,dx$$
The issue for me is, of course, the boundary term. Is there any reason to say the boundary term is $0$? If not, could it hold if we impose some restrictions on $b(x)$ or $h$, such as $h$ is a Schwartz function? Any help would be really appreciated!
Comment: You have to write your integral as a limit of integrals on the ball $\{\lvert x\rvert \le R\}$. Apply the integration by parts there, then let $R\to \infty$. Maybe the boundary terms vanish (it should be the case with suitable decay assumptions).
Comment: @GiuseppeNegro Thanks for your answer. Yes, of course, I assumed we should do the limit process. So, I am wondering if the boundary terms vanish as $R \to \infty$. Is $h\in L^2(\mu)$ enough to show it or at least does it have to belong to $\mathcal{S}(\mathbb{R}^n)$?
Answer: If $h$ is Schwartz then the answer is affirmative, but you seem to want $h\in L^2$ only. That's not enough. Having $k:=h^2$ in $L^1$ does not guarantee anything about $\nabla k$. It could be a tiny but highly oscillating function, say
$$
k(x)=\frac{\sin(e^{|x|})}{(1+|x|^2)^{100}}.$$
With this function, your right-hand side does make sense, but the left-hand side does not.
The right assumption is $h^2\in W^{1,1}$. With this one, your formula is true. Proof: establish the formula for a Schwartz $h$, then extend by density, using the fact that both sides are continuous with respect to the $W^{1,1}$ norm.

EDIT. How to prove that the boundary term vanishes, provided $h$ decays sufficiently rapidly?

Here's a way. Integration by parts on the ball $\{|x|\le R\}$ yields
$$
\int_{\{|x|\le R\}} \boldsymbol b \cdot \nabla(h^2)\rho \,dx = \int_{\{|x|=R\}} \boldsymbol{b}\cdot\boldsymbol{n}\, h^2 \rho\, dS - \int_{\{|x|\le R\}} h^2 \nabla \cdot (\boldsymbol b\rho)\,dx,$$
where $\boldsymbol{n}$ denotes the unit normal vector. We then have the estimate
$$\left\lvert \int_{\{|x|=R\}} \boldsymbol{b}\cdot\boldsymbol{n}\, h^2 \rho\, dS \right\rvert\le C_{\boldsymbol b, \rho}\sup_{|x|=R} (h^2(x))\left\lvert \int_{|x|=R}\, dS\right\rvert=C_{\boldsymbol b, \rho}\sup_{|x|=R} (h^2(x))R^{n-1}.$$
Thus, if $h^2(x)=o(|x|^{-(n-1)})$, the boundary term vanishes. This is certainly the case if $h$ is compactly supported, or Schwartz.
Comment: Oh, yes, I assumed $b$ and $\rho$ were bounded. If they are not, then $h$ must decay sufficiently fast to compensate. A compactly supported $h$ will be OK for all $b$s and $\rho$s.
Comment: Yes. ${}{}{}{}{}$
Comment: Yes, but that is easy. Since $h\in L^2$, assuming that $\nabla h\in L^2$ we have that $$\nabla(h^2)=2h\nabla h \in L^1, $$ hence if $h\in H^1$ the formula holds.
Comment: You have such boundedness; it is encoded precisely in the condition $h\in H^1$. Use that $\phi\in L^\infty$ and that $h_n\to h$ and $\partial_i h_n\to \partial_i h$ in $L^2$, thus their product converges in $L^1$.
Comment: Yes, I meant using the Cauchy-Schwarz inequality, which looks like what you did. You should specify what the norms are, though; $\lVert h_n^2-h^2\rVert$ is $L^1$, while $\|\partial_i \phi\rVert$ is $L^\infty$.
Comment: Oh yeah, it's Holder, not Cauchy Schwarz. Anyway.
Comment: Thank you very much for your help. Actually, this is from one of Cedric Villani's books. In this book, many things assumed to be trivial, but as a novice, I am trying to understand it one by one.

Here, he just assumes $h \in H = L^2(\mu)$ and $\rho$ is an equilibrium measure (which I forgot to mention.) Also, $Bh = b(x) \cdot \nabla h$, an unbounded operator.

I have two further questions/favors. First, could you show in detail how the equality  holds when $h$ is a Schwarts function when $b$ is just a $C^1$ function? Second, if it holds when $h \in W^{1,1}$ by desity, that means
Comment: it holds for the weak derivative of $(\nabla h^2)$, right? I'd really appreciate it if you'd help me. Thanks so much :)
Comment: I've also added a photo of the statement in case I missed some information. It'd very helpful if you'd answer me. Thanks!
Comment: Thank you very much for your answer! I understand most of it, except for one thing. If $h$ is compactly supported, then $C_{\textbf{b}, \rho} \sup\limits_{\vert x \vert =R } (h^2(x)) R^{n-1} \to 0$. However, if it's just Schwarts and $C_{\textbf{b}, \rho}$ is not bounded, then $C_{\textbf{b}, \rho} \sup\limits_{\vert x \vert =R } (h^2(x)) R^{n-1}$ might not go to $0$, since  $C_{\textbf{b}, \rho}$ depends on $x$ too. Do we have to impose more restrictions on $\textbf{b}$ and $\rho$, too?
Comment: I see. Also, if that equality holds for Schwartz functions, then it holds for $h\in W^{1,1}$ by density. However, in this case, it is in the sense of weak derivatives, since $\nabla (h^2)$ only makes sense weakly..?
Comment: Thank you so much!
Comment: Hi, can I ask you one more question about this? If $h \in H^1$ instead of $h^2 \in W^{1,1}$, can we still use the density argument? In other words, even if $h \in H^1$, we cannot guarantee that $h^2 \in W^{1,1}$?
Comment: Thank you very much for getting back to me first! Actually, the tricky part for me is to show $\nabla(h^2) = 2h \nabla h$. We have a sequence $\{h_n\} \in C_c^{\infty}(\mathbb{R}^N)$ such that $h_n \to h$ and $\partial_{x_i} h_n \to \partial_{x_i} h$. Accordinly, we have $\int (h_n)^2 \partial_{x_i}\phi' = \int 2h_n \partial_{x_i}h_n \phi$. If we want to show each side passes to the limit using dominated convergence Theorem to show $\nabla(h^2) = 2h\nabla h$, I think we need some kind of $L^\infty$ boundedness for $h_n$ and $\partial_{x_i} h_n$. Does that make sense? I try to think rigorously.
Comment: (LHS):  $\vert \int h_n^2 \partial_{x_i} \phi -  \int h^2 \partial_{x_i} \phi \vert \le \int \vert h_n^2 \partial_{x_i} \phi -  h^2 \partial_{x_i} \phi \vert  \le \Vert h_n^2 - h^2 \Vert \Vert \partial_{x_i}\phi \Vert \to 0$ since $h_n$, $h \in L^1$. (RHS): $\vert \int h_n\partial_{x_i}h_n \phi - \int h\partial_{x_i}h \phi \vert \le \int \vert h_n\partial_{x_i}h_n \phi - h\partial_{x_i}h \phi \vert \le \Vert h_n \partial_{x_i}h_n - h \partial_{x_i}h\Vert_1 \Vert \phi\Vert_1 \to 0$, since $h_n\partial_{x_i}h_n$, $h \partial_{x_i}h \in L^1$. Is that what you meant? :)
Comment: Actually, since I only know that if $u$, $v\in W^{1,p} \cap L^\infty$, then $uv  \in W^{1,p} \cap L^\infty$, I thought we might need the $L^\infty$ boundedness. However, $H^2$ is a little different. I really thank you for your help. I really appreciate it!
Comment: Oh, I made several major typos. $\int \vert h_n^2 \partial_{x_i} \phi - h^2 \partial_{x_i} \phi \vert \le \Vert h_n^2 - h^2 \Vert_1 \Vert \partial_{x_i} \phi \Vert_\infty$. Also, $\int \vert h_n \partial_{x_i} h_n\phi - h \partial_{x_i} h \phi \vert \le \Vert h_n \partial_{x_i}h_n - h\partial_{x_i} h\Vert_1 \Vert \phi\Vert_{\infty}$. Actually this is more like Holder's inequality rather than Cauchy-Schwarz you meant... However, is it still okay? :)


Conditional Reading in react working but shouldn't?

Question: So the question is, this code works perfectly but why when I remove the return(Header /) it doesn't work but it returns the correct Header type when return(Header /) is there depending on what the props.weather is?
Surely it should return  and not any others if its depending on it?
also if anyone can re-format this any better feel free, relatively new to it.
import Header from './header'
import HeaderCloudy from './headercloudy'
import HeaderSunny from './headerSunny'
import HeaderRaining from './headerRain'

function HeaderLoadOut(props){
//log weather from api by city
console.log(props.weather);
//convert
  let types = {
    weather: props.weather
  }
//check weather load weather

if (types.weather == 'Clouds'){
  return <HeaderCloudy />
} else if (types.weather == 'Sunny'){
  return <HeaderSunny />
} else if (types.weather == 'Clear'){
  return <HeaderSunny />
} else if (types.weather == 'Rain'){
  return <HeaderRaining />
} else if (types.weather == 'Snow'){
  return <HeaderRaining />
}

console.log(types.weather)
return (

)

}
export default HeaderLoadOut;

Answer: Try using an object to map your weather type, also, in functional component you must render a react element, therefore you must supply a node like Header or any value as specified in docs.
const WEATHER_TYPE = {
  Clouds: <HeaderCloudy />,
  Sunny: <HeaderSunny />,
  Clear: <HeaderSunny />,
  Rain: <HeaderRaining />,
  Snow: <HeaderRaining />
};

function HeaderLoadOut({ weather }) {
  return weather ? WEATHER_TYPE[weather] : ;
}

export default HeaderLoadOut;

As stated in docs, undefined is also a valid react element:
function HeaderLoadOut({ weather }) {
  return WEATHER_TYPE[weather];
}

Comment: That's Awesome thanks, never would have thought of doing it like that, my next step was a switch statement.


Notation for selecting $n$ maximum entries of an array?

Question: I have a vector $A=\left[\begin{array}{ccccc}1&2&5&4&3\end{array}\right]$ and I get vector $B=\left[\begin{array}{cc}4&5\end{array}\right]$, i.e., the maximum two elements of $A$.
What could be the proper notation for representing $B$? For example if I want to represent only the maximum value, I can write $B=\max(A)$
Comment: I don't know where you are trying to use this, but could you not introduce your own notation, such as $B=\max_n(A)$ to mean the $n$ biggest elements of $A$?
Comment: Thank you :).  I think i can use this. I am using it in a pseudo code.
Answer: Introducing a notation as lioness99a suggests is best, to suggest an array I think keeping the $[\cdot]$ notation is fine, so something like $\max[n](A)$.
Also if order has importance, for instance if you need $B=[4,5]$ rather than $B=[5,4]$ you have to define it explicitely.
Here is a possibility by induction:
$\begin{cases}
\max[0](A)=[\ ] \\
\max[n+1](A)=[\max(A\setminus\max[n](A))]\oplus\max[n](A)
\end{cases}$
Or something more direct:
$\max[n](A)=[m_n,m_{n-1},...,m_1]$ where $m_i=\max(A\setminus[m_{i+1},...,m_1])]$
Or even something python-like:
$\max[n](A)=\operatorname{IncreasingSort}(A)[-n:]$


determining server config

Question: I have recently set up a Linux server for my college which also hosts the college website and other downloadables. This server is linked to outside world using a leased line connection of 1mbps capacity.
My problem is that the users complain that the downloads from the server are very slow, how can I imporve this?
What things should I be looking at.
My current server config:
Dell vostro260s with 4Gb of ram and i3 processor.
Answer:
This server is linked to outside world using a leased line connection of 1mbps capacity.
  My problem is that the users complain that the downloads from the server are very slow, how can I imporve this?

I've bolded the relevant words from your question. 1Mbps is slow, therefor downloads from your server will be slow. Get a faster uplink. While you're at it, get a real server.
Answer: Try to connect to the server yourself as an outside user and do a wget . See the speed that you are getting.
Do a ping and traceroute from server to other system and other system to server. Take a note of the TTL and round trip value.
Do an iperf to find out the network performance.
Some quick tests that I would rather do.
Answer: You've got more than one issue here:

"Dell vostro260s" is not a server-grade computer. I don't expect much from it.
"leased line of 1Mbps capacity" and most of us have more bandwidth than that on our phones.

This must be a very small college, if it's still only using a T1/E1 for public Internet connectivity.
Anyway, doing anything about either of these two issues is going to require money, and I'm guessing that's probably the one thing they won't give you.
Comment: Agreed - I thought I was an alumni of a small college (~3000 undergrad students), but they're running a 1Gbps circuit now. :)
Answer: Adi,
This is really a hard question, since there could be thousands of factors:
Here is a list of stuff to look at ...

What kind of Webservices you run?
How to users download the software?
Does it have a lot of Disk I/O ? Does it swap?
Did you set up raid?

Try using iotop and powertop to find out what processes cause load on your server...

determining server config


Reloading a kernel "live" in CentOS / RHEL 6

Question: When upgrading the kernel package on CentOS or RHEL 6, is it possible to load the new kernel without rebooting?
My gut tells me it's not, but if it were, it'd be handy - especially when compiling applications that require kernel modules (like VirtualBox, for example) that complain when the "wrong" kernel source is available (eg the running kernel is 2.6.2-100 but the upgraded one is 2.6.2-152).
Answer: No.
kexec will allow you to skip the firmware (BIOS/EFI) and bootloader steps of a standard restart, but this is not the same thing (though useful if you have a slow loading RAID card).
The closest you can get is loading and unloading kernel modules.
Comment: that's a shame :| .. thanks, though :)
Comment: "loading and unloading kernel modules" - can you actually load kernel-modules of a newer kernel? Sounds tricky to me.
Comment: Didn't mean to imply the loading of modules from newer kernel, just modules that may not have been built on the same version.
Answer: Oracle Enterprise Linux can do that with KSplice, but you have to have an oracle ULN (support) contract for it.  I believe they are about $120.  http://www.ksplice.com/pricing
Answer: Yes for RHEL. (Since Feb 22, 2012)
Oracle Offers Free Trial of Innovative Ksplice Zero-Downtime Updates to Red Hat Customers
To continue after the 30 day trial, you need to purchase the
Oracle Linux Premier Support package.
Pricing starts at $1,400 for systems with two physical CPUs and $2,300 for systems with more than two physical CPUs. You can configure your systems to automatically install updates as they become available.
It had been offered for both RHEL and CentOS (as well as other operating systems) prior to July, 2011 when Oracle acquired Ksplice. Prior customers are still supported.
Oracle buys Ksplice
The Ksplice code was created and distributed under the GPL v2 and other open source licenses. After Oracle acquired Ksplice and limited availability to Oracle Linux, Ubuntu Desktop, and Fedora, there was discussion about maintaining a CentOS fork of Ksplice:
Ksplice and CentOS
It was also argued that Ksplice was violating the GPL:
Ksplice currently violates the GPL
Answer: Nobody pointed to kpatch. It not live kernel reload, but targeted same problem.
kpatch Red Hat technology to apply patches to live kernel.

With respect to granularity, kpatch works at the function level; put simply, old functions are replaced with new ones.  It has four main components:

kpatch-build: a collection of tools which convert a source diff patch to a hot patch module. They work by compiling the kernel both with and without the source patch, comparing the binaries, and generating a hot patch module which includes new binary versions of the functions to be replaced.
hot patch module: a kernel module (.ko file) which includes the replacement functions and metadata about the original functions.
kpatch core module: a kernel module (.ko file) which provides an interface for the hot patch modules to register new functions for replacement.  It uses the kernel ftrace subsystem to hook into the original function's mcount call instruction, so that a call to the original function is redirected to the replacement function.
kpatch utility: a command-line tool which allows a user to manage a collection of hot patch modules.  One or more hot patch modules may be configured to load at boot time, so that a system can remain patched even after a reboot into the same version of the kernel.

Supported from RHEL 7
Comment: But the OP is asking about loading an entire new kernel, not replacing modules or functions.
Comment: Yes. But other question marked as duplicate (http://serverfault.com/questions/366974/kernel-update-without-reboot) ask about kernel update. I expect, kernel reloaded in live not just for fun, but to be updated and keep uptime.
Comment: I'm sure no one else mentioned it because the OP is from 2012 .. and this is only supported in RHEL7 :)
Comment: but in RHEL7 it is not a complete reloading of the kernel. It is only patching certain parts of it. So the answer to the original question still remains: "No".
Answer: KExec claims that you can do exactly that.
Comment: I would say this most certainly does not satisfy the OP's requirement of "not rebooting." In fact it only shifts the burden of reboot to the user instead of the init/systemd scripts ... And more importantly, it should be noted this does not replace the entire kernel, it's only for applying patches to pieces of the kernel.
Comment: kexec was mostly aimed at industrial linux systems and got prominent via carrier gracde linux project. those are specialized / hardened distros for professionals and half-ass desktop/server distros like RHEL (for years) didn't make full use of kexec. OpenSUSE started like 3 years ago to skip the reboot after installing the OS. now in RHEL7 you can actually do it, too. I hope this kind of explains why kexec might have been there for 10 years but you couldn't just "use" it to do the 'fast reboot' it was intended for.
Comment: how does kexec work, and can it be automated to fire *as soon as* a kernel is upgraded?
Comment: From the link @monksy gave: "Essentially, kexec is a fast reboot feature that lets you reboot to a new Linux kernel -- without having to go through a bootloader." No mention of it being automated, it seems unlikely based on this statement: "Unlike the normal reboot process, kexec does not perform a clean shutdown of the system before rebooting. It is left to you to kill all applications and unmount file systems before attempting a kexec reboot."
Answer: Actually, I just re-read this Oracle Blog post:
https://blogs.oracle.com/wim/entry/fast_reboots_for_oracle_linux
So, as long as you use the UEK kernel, you can do the kexec fast reboot on OEL5 and OEL6. This is not related to ksplice (which is about not rebooting in the first place!) and not needed a license or anything to use.
Comment: Fast reboot is not the same as no reboot.
Comment: The Oracle Blog pointed to by this answer explains how to setup kexec and how it works.
Comment: "No reboot" is a different thing and has been available i.e. with ksplice for like 5 years. I used it on desktops @ work to make sure I don't have to reboot when I don't want to.


Set transparency of face by index in THREE.js

Question: I've managed to set the colour of a mesh face using:
geometry.faces[i].color.setHex('0xff00ff');

Is there a function to set the transparency to true and opacity to say 0.5?
I'm sure there is one, just have no idea of the syntax.
Answer: Actually, you cannot achieve that by changing your geometry. Because transparency controlled by materials.
But there's way to do this.
First, each face has materialIndex (Face manual).
Next, Each mesh, drawn within three.js scene has material. And there's special material of type THREE.MeshFaceMaterial (MeshFaceMaterial manual), which takes array of materials as argument.
When faces are drawn, three.js renderer takes face's materialIndex and uses corresponding material from this material array or, if mesh contains single material type.
So you could do something like:
var opacMaterial = new THREE.MeshLambertMaterial({
  transparent:true,
  opacity:0.7
});
var solidMaterial = new THREE.MeshLambertMaterial({
  transparent:false,
  color:new THREE.Color(1,0,0)
});

var mesh = new THREE.Mesh(
  geometry,
  new THREE.MultiMaterial([solidMaterial, opacMaterial])
 );

By default, if your geometry have materialIndex == 0 for each faces, you will see solidMaterial drawn.
If you want to make it transparent do something like this;
geometry.faces[i].materialIndex = 1;

Don't forget to update geometry in mesh: (How to update geometry in mesh question.)
Also, aware, if you have materialIndex in your faces greater than length of material array, you will get awkward error inside of deep of THREE.js
Comment: Frankly saying,  I made a typo in this answer. I just fixed it.


wsdl.exe/svcutil.exe - is there a way not to generate the classes for types in the xsds during a Web service or client generation

Question: We have a centrally managed object model for types in the schema in C#.
We want every one across the enterprise use that object model instead of using the one generated each time from wsdl/svcutil during a webservice client or service implementation.
is there a parameter(any other way) to wsdl/svcutil not to generate classes for the schema types during theie execution?
Answer: I don't know of any specific setting or command line switch to enforce this - what you can do, but that's mostly a matter of training and enforcing by checking, is to share the class library (the assembly, in a DLL) with the developers, and make sure that everyone references that common class library and leaves the default settings in the "Add Service Reference" dialog (on the "Advanced" page) alone:

Here, you define that WCF will reuse any types it can find in any of the referenced assemblies - so if your developers add a regular reference to the common data contracts library, then WCF will use those types instead of re-creating them over and over again.
But again - that's only a "management by example and checking" kind of approach - I don't know of any technical way to enforce this.
Answer: I believe what you are looking for is: svcutil.exe /r your-dtos.dll

/reference:             -
  Reference types in the specified
  assembly. When generating clients, use
  this option to specify assemblies that
  might contain types representing the
  metadata being imported.  (Short:
  /r)

In my opinion the tight coupling of the WCF proxy, endpoint channel, service operations and dto payloads into the same generated client proxy is a major design flaw.
This is what spurred me to solve in my open web services framework where I decouple the end point and payload which allows:

The same web service client (i.e. Soap11, Soap12, XML, JSON) to be able to call any web service.
It lets me also use the same DataContract dto instance in any of the web service clients
This has many benefits including being able to expose the same web service on a number of different end points without any extra configuration. Thus providing optimized web service endpoints for each consumer of my service. E.g.

XML for interoperability and strongly-type clients,
JSON for Ajax clients,
WSDL's for environments that prefer generated code (i.e. Flex Builder, VS.NET 'Add Service Reference' etc)

At my company we have developed hundreds of web services called by a number of different clients i.e. Ajax, Flash/ActionScript, C++, Silverlight, ASP.NET and being able to call the same web service through different endpoints has saved us countless hours.
Answer: If you remove the mex endpoint from the service config file, the client app will not be able to discover and generate the proxy objects.
A way to handle this situation if I understand your question correctly is to do the following:

Create a common set of DLLs that has the service, and datacontracts / shared object model.
Create a service using the contracts in the common dll instead of the contracts visual studio creates when you create a new service.
Remove the MEX endpoint from the server config file (this will essentially break proxy generation).
Have your client use the the common dll and manually create the channels on the client side (via channel factory etc...).

In this approach you do not use wsdl.exe/svcutil.exe at all since you are essentially bypassing the wsdl. You do not add service references either since you are manually managing the connections.
EDIT: Following this approach, the client can still try to generate proxy objects via wsdl.exe/svcutil.exe, but they won't get the correct information from the wsdl. They'll essentially generate a non-functioning / incomplete proxy.
Comment: is there a way to control this during wsdl/svcutil.exe execution?

I have a wsdl that imports some xsds and I want to generate a service interface using wsdl.exe or svcutil.exe from a command prompt.

during the execution of wsdl.exe/svcutil.exe, can I control not to generate classes for types in the xsds?
Comment: Part of the reason WSDLs exist is to define the object schema necessary to communicate with them. The wsdl.exe and svcutil.exe are designed to generate classes for these objects, I don't think there's a way to prevent it.
Comment: Jeremy, that is true if the client doesn't know how to communicate with the service. If the developers have access the actual contract dlls, they don't need the WSDL at all. They agree on the contract by using the same dlls.


How do I change a core error message?

Question: I would like to change the default error message from Drupal core.
The error message is "Please Select the Valid File Format".
My problem is in brief below.

I have created a CCK called 'Assignment'.
There I have given the users an option to upload files.
In such case if the user uploads invalid file format drupal will throw the error message as mentioned above.
I need to change the error message in to "The file upload field cannot upload the speicified filed".

How can I achieve this?
(Should not use string overrides module)
Thanks in advance..
Comment: For Drupal 7, check: [How do you alter a form error?](http://drupal.stackexchange.com/q/68006/1908) or [Change form validation error messages in Drupal 7](http://drupal.stackexchange.com/q/75455/1908)
Answer: If that string is run through the t() function (which is probably is) and you don't want to use  String Overrides, then you can update your settings file.
For Drupal 6, putting this in your "settings.php" file should work.
$conf["locale_custom_strings_en"] = array(
  "Please Select the Valid File Format" => "The file upload field cannot upload the speicified filed",
);

In Drupal 7, you would change it to
$conf["locale_custom_strings_en"][""] = array(
  "Please Select the Valid File Format" => "The file upload field cannot upload the speicified filed",
);

However, I am not seeing the string "Please Select the Valid File Format" in any of my D6 installs, and that is not the message I get when try to upload to a CCK filefield with the wrong file type or the MIME type doesn't match the file extension.
Answer:
Get the messages using drupal_get_messages(). Make sure to leave the $clear_queue parameter at the default true.
Search the resulting array for the relevant messages and replace them. The resulting array is indexed by message type and the values are arrays of messages for that type (even if you only retrieve messages of a particular type).
Inject the messages back into the message queue using drupal_set_message().

Drupal retrieves the message queue in function theme_status_messages() which is called from template_preprocess_page(), so one place to achieve this would be an override of that theme function. Depending on the exact circumstances of the message, you might find some hook that is closer to the point when the message is generated.
Because the messages are rendered in template_preprocess_page(), an implementation of hook_exit() is not an option, because this hook is invoked when the page is already rendered.
BTW: I often wished for a hook_message_alter().
Answer: I placed the following code in  template_preprocess_page() and it worked perfectly. I'm not totally convinced this is the best way to do it but it was faster than building a module to generate the custom errors.
To get this done I looked at all the error messages generated by drupal_get_messages() and cycled through them. If they matched the string I was looking for I would then use drupal_set_message() to generate the error with new text. The final step was to pass the remaining errors through drupal_set_message() otherwise they wouldn't be called.
Again I'm not certain this is the best way of pulling it off, if anyone has any suggestions on how to do this in the theme layer I'd love to hear them.
$getmsg = drupal_get_messages('error');
    if ($getmsg){
      foreach($getmsg['error'] as $err) {

          switch($err) {
          case 'SUBSCRIBE TO THE NEWSLETTER field is required.':
            drupal_set_message('Sorry, you must sign up to the newsletter to enter', 'error');
          break;
          case 'I AGREE WITH THE CONTEST RULES & REGULATIONS field is required.':
            drupal_set_message('Sorry, you must agree to the rules and regulations', 'error');
          break;
          default:
            drupal_set_message(t($err), 'error', FALSE);
          break;
        }

      }
    }

Answer: The easiest way is to use the String Overrides module.
Install the module and you can replace the string with your own string. The string overrides module also allows you to replace any string wrapped in the t() function.
Comment: The OP specifically stated, _not_ using the String Overrides module
Answer: Drupal 7
You can customize error messages by using Field validation per entity field.
To do that, edit field settings, go to Validation and add a new validation rule (Required field rule). There, you should have textfield to set-up Custom error message for that field.

How do I change a core error message?


URL path settings not supporting more than one level

Question: I'm trying to edit and create content on my inherited Drupal site and when I enter an address into the "URL Path Settings' URL Alias" field, it will not save the first part of the desired URL.
For example if I enter "firstpart/contentname"
it just saves "contentname" instead of the full hierarchy.
Comment: And are you sure your firstpart token is correct, and that the (Entity) Token module is enabled?
Answer: That's strange. If you edit the URL alias manually, it shouldn't be automatically changed unless you bulk delete and update your URL aliases in Pathauto.
Have you checked your Pathauto pattern settings (/admin/config/search/path/patterns) to see if there is something overriding your changes?
You said that you inherited the site. Are there any URL/path-related modules that your predecessor has enabled?


How to dynamically calculate interval designations of data?

Question: I am looking for an equation to calculate appropriate intervals to designate values as very low, low, medium, high, very high for dynamic data.
for example if my dataset ranges from 0 to 100 very low= <=20, low=21-40, medium=41-60, high=61-80, very high= >81
However, if the range is small there should be fewer intervals. For example, if the range is 20 then there should be a low and high interval designation only.
the intervals need to be logical intervals so they can be used for a graphical display. logical intervals would include intervals of 5, 10, 25, 50, 100 etc depending on the dataset. Is there an equation that can determine appropriate intervals for each unique dataset?
Comment: It sounds like your definition of "logical" may be specific to your application. You have hinted at some properties that you want in your cut point algorithm, but you may wish to edit your question to make these more specific.
Comment: @Jeromy Anglim I would like to create a heatmap given dynamic data that should indicate lower and higher levels of a property. The intervals of lower and higher should be determined dynamically based on the dataset. The heatmap will have a legend indicating the interval that each color represents and the intervals should be "logical" to the person using the heatmap in analysis of information
Answer: A few quick thoughts:

Your example makes it sound like you have a specific application in mind, such that you could program the cut points as a set of if-then rules. E.g., if max = 20, then cutpoint is 10; if max = 50 then cutpoints are 15, 30, 45; etc...
You could have a look at the cut function in R to get additional ideas.
The literature on histograms, bin size, etc (e.g., see wikipedia) may also be relevant.

You probably want to think about what properties are most desirable:

Importance of rounding to 5s, 10s, 100s on interval borders
Equality of intervals versus equality of proportion of sample in each interval
The functional relationship between range and number of intervals that you want to use
Answer: Dividing any range into intervals is subjective. What makes '20' a small range and '100' a big range? What about a range of 1? Or 1000000?
However, if you can think of a few more hypothetical scenarios such as the two you provided (20 range->2 intervals, 100 range->5 intervals), you can fit a function to them that will tell you how many intervals to keep. For instance, if you graph 20,2 and 100,5 and fit a linear function you'll get:
$y=0.375x+1.25$
or a logarithmic function would give you:
$y=1.864ln(x)-3.5841$
where x is your range and y is the number of intervals you should keep. Of course, these functions would be a lot more meaningful if you had more than 2 a priori examples. In that case, you would choose the function that fits best (the highest $R^2$).
After determining the number of intervals you should keep, you can simply space the intervals evenly throughout your data, or round to the nearest "logical interval".
As Jeromy suggests, there are several other factors you may want to keep in mind besides this functional relationship, so YMMV-- but it's a start.


kettle transformation escape commas input CSV file

Question: I get a CSV file, each field in this file are separated by commas, taking into consideration the header of 2 lines of the file.
Sample the beginning of a file:
Title of the file
Time,User,Pages,Copies,Printer,Document Name,Client,Paper Size,Language,Height,Width,Duplex,Grayscale,Size
2014-05-16 00:06:24,userb,7,1,DLP-SAI-KY4500-BAC3 LDVI,"Crystal Reports",SVXENAPP1,A4,EMF,,,NOT DUPLEX,NOT GRAYSCALE,824kb,
2014-05-16 00:06:35,userb,1,2,DLP-SAI-KY4500,"Crystal Reports",SVXENAPP1,A4,EMF,,,NOT DUPLEX,NOT GRAYSCALE,727kb,

Some fields between quote " have commas Example.:
2014-05-16 10:25:32,userb,8,1,2LP-GEN-KY1135,"RDV 2014-06-12_ SOCIETE, ABCDEF, TESTK, AABB Normandie, SOCAA Grands Ri.pdf",PC-DLP-50,A4,PCL6,,,NOT DUPLEX,GRAYSCALE,4689kb,

In this example,
"RDV 2014-06-12_ SOCIETE, ABCDEF, TESTK, AABB Normandie, SOCAA Grands Ri.pdf"
is the Document name and contains commas.
How to escape these commas?
That's my transformation :

But Option ' Escape : " ' doesn't works
(In my transormation, "Replace char" just allow to delete quote for the DocumentName field)
Answer: Your component is missing the enclosure configuration. Your sample works for me if I set the enclosure character to ".
Comment: Yes it works but when there are several commas that follow (without information between two commas), instead of putting the field to NULL, it skips the field. Example of line : 2014-05-05 17:03:19,Userp,1,1,DLP-SAV-KY300,"Crystal Report",PC-DLP-85,A4,PCL6,,,NOT DUPLEX,GRAYSCALE,279kb,
Comment: I also tried this line. It works for me. Could you pipe your text input into a text output and include the presumably wrong output into your question?


Is there a way to rehearse being in a stressful performance situation?

Question: I'm a brass player in a UK brass band. We spend lots of time practising things:

we practise our technique so that we can perform fast or slow phrases without stumbling;
we practise ensemble playing so we are in tune with the other players and our articulation is in accord the others, so we all play notes the same length and the same shape;
we practise dynamic variations so we can get louder/quieter smoothly and at the same rate as the other players;
we practise playing at extreme ranges so we can perform high/low notes securely;

We rehearse these things (and lots of other stuff besides), individually and in ensemble, over and over again and they improve.
However - during performance, nerves kick in and these have an unwanted adverse effect.
Here's the question: is there any way, during a rehearsal, to reproduce the physiological changes that normally only occur during the performance, in order that we can rehearse strategies for dealing with those unwanted side-effects?
Comment: Note that nerves and stage fright are commonly experienced even by experienced musicians.  A psychological trick I've read about (YMMV) is to reframe that feeling as excitement.  In other words, make a conscious effort to interpret your physiological response to a stressful situation in a positive way rather than a negative way.
Comment: Some of this suggestions in [What are good tips for remaining composed during one's first public performance?](https://music.stackexchange.com/q/106/70803) will also be useful here.
Comment: Do you have spectators when you practise? I noticed I have trouble knowing I'm being observed by a relative/colleague/recording camera which I put there myself.
Comment: Busk :) While I was in school I was lucky enough to find a music store that put a piano out on the street. I played it on lunch breaks and the gathering audience behind my back did wonders for my confidence. Soon I was offering to play at events (more trepidation, more pushing through it).
Answer: You've hit on a very important point. I give this speech often to my students, that we "practice practicing," but rarely "practice performing." Especially for a non-professional, a student might spend dozens of hours in lessons per term, and hundreds of hours practicing, and to every single hour performing in a term-end recital.
My best advice is not precisely what you asked for, but simply to "practice performing" more often. If an important concert is coming up, schedule a handful of less-formal, lower-stakes performances beforehand. Call an open rehearsal, invite your friends; busk on the street; play in a coffeehouse. Every time you "survive" such an experience, you teach your psyche not to fear it. Every time you have a successful performance, you train yourself like Pavlov's dogs to welcome another.
But you asked what elements you can incorporate into a rehearsal. There are a few things you can do:

If you're not already, practice playing pieces all the way through, in the same way you will in the performance. Some ensembles (or conductors?) are terrible about disciplining themselves to do this; even in the dress rehearsal they'll stop often to fix things. Similarly, it can be helpful sometimes to rehearse without the full volume, or without all the expression or rubato that might be present in the final version. But you do want to also rehearse at least a few times with these. The performance shouldn't be the first time you play the piece "that way."
A bit of physical exercise can to some degree replicate some of the physical effects of nerves. Jog around a bit, do a few pushups, and then play: you'll have a bit of muscle shakiness, an elevated pulse and heightened circulation, like the effects of adrenaline.
One can do a lot just with the imagination. Envision—or act out—every step of the performance experience. Imagine waiting backstage, filing out onto the stage—imagine the lights, the audience, the applause—getting settled in, waiting for the downbeat. Imagine yourself in your concert attire, or even wear it! If possible, have a rehearsal in the performance space, so you don't add to performance nerves by also being in a strange place.
One performance challenge is simply thinking straight and staying level-headed while so many neurons are firing excitedly. You can try adding distractions to a rehearsal. Keep going all the way through the piece while someone shouts random things at you—trash talk, maths questions, anything to try to steal your focus. Walk a line while playing (welcome to marching band!). Try to play while someone plays a different piece.
Maybe the simplest and most effective is as mentioned above: turn a rehearsal into a performance by inviting a small audience. Friends, family, strangers off the street.
Comment: Some great advice there. In particular, I found _visualising_ the performance really helpful. As you say, it's worth visiting the venue in advance if possible, so you can picture yourself there and have an idea of what you'll see, where you'll be looking, etc. (That's especially important if your performance may involve moving around, e.g. singing solo.) — And one advantage of having a small audience for practice is that they can give helpful feedback, especially on non-technical aspects you may have overlooked.
Comment: Only thing I'd add is that I personally find it very helpful to do as you describe *at the venue* if at all possible. You'll often find something's quite quite different about the acoustics of the venue at the place in it you are performing (vs. where you typically practice), and you have to adjust in real-time. I don't want to be doing that in the middle of the actual public performance.
Comment: Visualization is popular and has even helped me, despite my rampant cynicism. Also I've found other performances help with comfort in performing. Public karaoke is one way I've gotten practice with stage fright, since I'm not much of a singer and I do it sober.
Answer: Make a perfect recording of your part.  That can be surprisingly tricky even when you are sure you've got everything.
Comment: I came here to write this answer.  In addition, it can be beneficial to alternate between performing mode (I'm not stopping for anything!) and practice mode (let's work on where I heard rough spots when I ran through it in performing mode).  Just decide which mode you are in before each play through.
Comment: I tried that once — and saw a greater improvement in a few days than I had in the previous month! It forces you to be aware of all the little fluffs and insecurities that you tend to overlook in rehearsal.
Answer: Don't forget to get used to playing the pieces all the way through!  I remember one brass band I played with for a bit which practiced every section of the 'contest' piece meticulously, not realising they'd never actually played it top-to-bottom. And I'm not sure we even rehearsed the separate sections at the same tempo!  Too much detail, no over-view.  The performance was... interesting.
The nearest I can think of to concert stress might be 'red light stress'.   Get someone to bring in some recording gear.  Make it as obtrusive as possible, a microphone up as many people's nose as possible! No hiding place!  An actual red light would be good too!
Or invite someone - preferably with some musical credentials - to assess a run-through.  Or end each rehearsal with half-an-hour of 'friends and family welcome' and play through the pieces you've been rehearsing.
Answer: This actually applies to all players, not just horn players!
A lot of good points from Andy - particularly his 1st - when everyone has had their part dissected and perfected, that's the time to play through top to bottom, with repeats, dynamics, just as it would (should?) be at a concert.
Making a recording at the rehearsal will put pressure on all players to get it right 1st time - peer pressure comes in here.
Having said that, there needs to be some 'concern', brought on partly by adrenalin flow, that makes a performer have that 'edge' that's needed to play their best, so it's not surprising that it occurs in performances. As you say, getting it to flow in rehearsals is the thing!
Some pieces may need a click track, or metronome, which in itself can be stressful to keep to, others with rubato need the conductor to make timings, so he could exaggerate things, keeping the band on its toes. Same with dynamics, to a degree. Something sadly neglected until the end of a rehearsal for some, but making the difference between a loose and a tight band.
Comment: "Dynamics? I'm already playing as loud as I can!"
Comment: @arne - don't remind me of so many auditions I went to...
Answer: You have to find a setting, where you can practice and it matters. I.e. like saying, you'll play the whole concert program which takes two hours and you're not allowed to take breaks or start over again after a wrong note. You will feel a certain pressure even if it's just a practice.
Answer: When I had to audition for my university placement in the music program as an 18 year old, my hands and mouth shook so much I could barely get out a note on the flute. It was awful.  The main thing I learned was to expect to be nervous--it's okay, everyone is!  Even professionals.  Practically, I forced myself to perform as much as possible, and one learns coping strategies and it gets easier.  And if you REALLY want to feel secure, memorize your music.


Specific estimates about fuel consumption - Simple linear regression?

Question: I am working on a story problem for a project.
"You work for a small environmental foundation that wants to analyze fuel consumption. Your boss (in the year 2002) has asked you to help her analyze the 2001 data on highway fuel consumption to find out what a change in the tax rate does to fuel consumption. She has provided a datafile (labelled Fuel2001) that has data on the following variables:
Drivers Number of Licensed drivers in the state
FuelC Gasoline sold for road use (1000s of gal.)
Income Per capita personal income (year 2000)
Miles Miles of Federal-aid highway miles in the state
MPC Estimated miles driven per capita
Pop Population age 16 and over
Tax Gasoline state tax rate, cents per gallon
She wants you to produce an analysis that does the best job of helping her argue that higher tax rates lead to lower fuel consumption. But her initial analysis of the data (simply including all of these variables in a naive regression model) did not find that tax rates had a statistically significant effect. Is there anything that can be done to find out if there is a relationship? Write her a short memo on that subject including your analysis, including specific estimates of the relationship."
I'm supposed to present her with the best case possible to support her cause (raising gas tax to reduce fuel consumption), but I should also include the best model, for her information. I have transformed all the skewed variables by taking their natural log. I ran a bunch of different regressions in Stata until I found one in which tax was statistically significant. When I ran the same regression robust tax was no longer statistically significant.
What would you do and show (graphically, including tables or graphs)? What does it mean that the robust regression makes tax insignificant?
I know it would be helpful to have the data, but I can't figure out how to upload it.
Thanks in advance for any input.
Answer: So many people, myself included, learned statistics because someone handed them data problems that they didn't know how to handle.
First comment:  you've got a lot to learn, and running regressions without knowing what they mean is dangerous -- you may get caught with your you-know-what hanging out.
Second comment:  read Mostly Harmless Econometrics, by Angrist and Pishke.  It seems like what you need is a fixed effects model, or maybe a regression discontinuity, or anyway some econometrics-style identification strategy that will let you argue about causation rather than just correlation.
Third comment:  in stata, reg y x, robust means that the variance-covariance matrix is calculated as $\left(X'X\right)^{-1}X'\epsilon \epsilon' X \left(X'X\right)^{-1}$.  Do you know what that means?  If you don't, beware, and read up.  A good overview is given in section 20.20 of the Users Guide that comes with Stata and the references therein.  If you move onto a panel-data style analysis, you'll want to go further, and cluster your standard errors to account for intra-class correlation (look it up).
Last comment:  typically this kind of thing is presented in regression tables.  The stata "package" estout is helpful.
Last last comment:  you say "best" model.  That can mean a lot of things.  It can mean the model in which you can argue that your regression coefficients represent unbiased causal effects.  It could also mean that youv'e got the best-predicting model, according to Akaike's Information criterion or something similar.  What do you mean?
Comment: Much good advice here, but also some presumptions about the OP's background. Angrist and Pischke [NB] could be a useful book if you really are an economist and this is about your second time round with regression. http://www.amazon.com/Mostly-Harmless-Econometrics-Empiricists-Companion/dp/0691120358 gives more details. Andrew Gelman's review at http://www.stata-journal.com/sjpdf.html?articlenum=gn0046 gives a good perspective of their book from a modest distance.
Answer: I don't really see a way to estimate it very well from the variation in cross-section data. Everything I know about this literature uses panel data (which may still be bad, but at least you can include fixed effects to control for unobserved time-varying consumption factors) or an instrumental variables with panel data (which is better, but may not identify the parameter you care about here because responses to unexpected oil shocks are different from tax increases or they may be weak or not exogenous).
The problem is that price and quantity demanded are jointly determined, which induces a correlation between price and the error terms that will bias estimates towards zero in a naive regression of quantity on price. I guess you can say that any coefficient you estimate with OLS will be biased downward. This may be the problem you run into. Or you might be able to do something simple, find that it agrees with more sophisticated results, and dismiss the objections on those grounds.
Another strategy would be to take some elasticity estimates from the literature, and use those to see what happens. In the short-run, the demand is going to be very inelastic, so you can assume the full burden of the tax will fall on the consumer. Then you can use your data to show how consumption would change.
There's a nice blog summary of the literature and the econometric issues here. In particular, there are links to two accessible papers. Hughes, Knittel, and Sperling  find short-run gas price elasticities of -0.034 to -0.077 in the first five years of this century, which means that a price increase of 1% will lower quantity demanded by between 0.034% and 0.077%. You can also try replicating their specification with your cross-section (using logged price and quantity). The Killian and Davis paper points out some issues with the first approach and find somewhat larger effects with the HKS method (-0.19% with state panel data) and much larger estimates using IV (-0.46% with stata panel data). You might use all of them in your simulations, and compare with your own estimates.