How to prove that $\int_0^{\infty} \log^2(x) e^{-kx}dx = \dfrac{\pi^2}{6k} + \dfrac{(\gamma+ \ln(k))^2}{k}$?

Question: I was answering this question: $\int_0^\infty(\log x)^2(\mathrm{sech}\,x)^2\mathrm dx$ and in my answer, I encountered the integral
$$\int_0^{\infty} \log^2(x) e^{-kx}dx$$
which according to WolframAlpha for $k=1,2,3$ and thereby generalizing gives us

$$\int_0^{\infty} \log^2(x) e^{-kx}dx = \dfrac{\pi^2}{6k} + \dfrac{(\gamma+ \ln(k))^2}{k} \tag{$\star$}$$

Also, in general, is there a nice form for

$$\int_0^{\infty} \log^m(x) e^{-kx} dx \tag{$\perp$}$$

EDIT
For $(\star)$, if we let $kx = t$, we then get
$$I = \int_0^{\infty} \log^2(t/k) e^{-t} \dfrac{dt}k = \dfrac1k\int_0^{\infty}\log^2(t) e^{-t}dt-\dfrac{2\log(k)}{k}\int_0^{\infty}\log(t) e^{-t} dt + \dfrac{\log^2(k)}k$$
Considering the above, $(\star)$ and $(\perp)$ boil down to evaluating the integral

$$\color{red}{I(m) = \int_0^{\infty} \log^m(x) e^{-x} dx} \tag{$\spadesuit$}$$

Some values of $I(m)$.
\begin{align}
I(1) & = -\gamma\\
I(2) & = \zeta(2) + \gamma^2\\
I(3) & = -2\zeta(3) - 3 \gamma \zeta(2) - \gamma^3\\
I(4) & = \dfrac{27}2 \zeta(4) +8 \gamma \zeta(3) + 6 \gamma^2 \zeta(2) + \gamma^4\\
I(5) & = -24 \zeta(5) - \dfrac{135}2 \gamma \zeta(4) - 20 \gamma^2 \zeta(3) - 20\zeta(2) \zeta(3) - 10 \gamma^3 \zeta(2) -\gamma^5
\end{align}
Comment: $$\int_0^{\infty} \log(x)^m e^{-x} dx = \left.\frac{\partial^m}{\partial\alpha^m} \int_0^{\infty} x^{\alpha} e^{-x} dx \right|_{\alpha=0} = \Gamma^{(m)}(1)$$
Comment: A [related problem](http://math.stackexchange.com/questions/332375/calculating-int-0-infty-log-tn-e-t-dt/332385#332385).
Comment: A [related problem](http://math.stackexchange.com/questions/181153/define-integral-for-gamma-zetai-i-in-mathbbn-and-stirling-numbers-of-the).
Comment: These numbers seem very closely related to the Laurent expansion of the Gamma function about $0$, but I don't know why this is the case or how to use this.
Comment: Start with Weierstrass infinite product definition of [Gamma function](http://en.wikipedia.org/wiki/Gamma_function):$$\frac{1}{\Gamma(z)} = e^{\gamma z}z\prod_{n=1}^{\infty}(1+\frac{z}{n})e^{-\frac{z}{n}}$$ It is not hard to derive following expansion of $\log \Gamma(z+1)$: $$\log\Gamma(z+1) = -\gamma z + \sum_{k=2}^{\infty} \frac{\zeta(k)}{k} (-z)^k$$ in terms of zeta functions. Taking exp and Taylor expand it allow you to express your integrals in terms of $\gamma$ and the zeta functions.
Comment: @GitGud I do not quite follow your second comment. Feel free to edit to change if something is unclear.
Comment: @GitGud Oh ok. Understood. Thanks.
Comment: @user17762 No problem.
Comment: For the second, your integral is simply $ \Gamma'(1) $ which is well known to be $ -\gamma $. The first one can be expressed using the double derivative of the Gamma function, which might help find resources on it.
Comment: @achillehui Very nice. That qualifies to be answer! Could you also outline the method to obtain the $m^{th}$ derivatives of $\Gamma(1)$ in terms of $\gamma$ and the $\zeta$ function evaluated at the first $m$ values?
Comment: @achillehui: that series for $\log(\Gamma(z+1))$ can also be easily derived from $(\ast)$ in my answer.
Answer: As mentioned in this answer
$$
\int_0^\infty\log(t)\,e^{-t}\,\mathrm{d}t=\Gamma'(1)=-\gamma
$$
Using the definition
$$
\Gamma(x)=\int_0^\infty t^{x-1}\,e^{-t}\,\mathrm{d}t
$$
and taking the derivative $n$ times, we get
$$
\Gamma^{(n)}(1)=\int_0^\infty\log(t)^n\,e^{-t}\,\mathrm{d}t
$$
In the aforementioned answer, we also have
$$
\Gamma'(x+1)=\Gamma(x+1)\left(-\gamma+\sum_{k=1}^\infty\left(\frac1k-\frac1{k+x}\right)\right)\tag{$\ast$}
$$
Taking the derivative of $(\ast)$ at $x=0$ yields
$$
\begin{align}
\Gamma''(1)
&=\Gamma'(1)\left(-\gamma\right)+\Gamma(1)\zeta(2)\\
&=\gamma^2+\zeta(2)
\end{align}
$$
Taking the second derivative of $(\ast)$ at $x=0$ yields
$$
\begin{align}
\Gamma'''(1)
&=\Gamma''(1)(-\gamma)+2\Gamma'(1)\zeta(2)+\Gamma(1)(-2\zeta(3))\\
&=-\gamma^3-3\gamma\zeta(2)-2\zeta(3)
\end{align}
$$
We can use Leibniz rule and
$$
\frac{\mathrm{d}^n}{\mathrm{d}x^n}\left(-\gamma+\sum_{k=1}^\infty\left(\frac1k-\frac1{k+x}\right)\right)=(-1)^{n+1}n!\,\zeta(n+1)\quad\text{ for }n\ge1
$$
applied to $(\ast)$, to get the recursion
$$
\Gamma^{(n)}(1)=-\gamma\,\Gamma^{(n-1)}(1)+(n-1)!\sum_{k=2}^n(-1)^k\zeta(k)\frac{\Gamma^{(n-k)}(1)}{(n-k)!}
$$
Comment: I shall go through them, but I assume (?) in general $$\int_0^{\infty} \log^m(x) e^{-x} dx = \Gamma^{(m)}(1)$$ Could you also outline the method to obtain the $m^{th}$ derivatives of $\Gamma(1)$ in terms of $\gamma$ and the $\zeta$ function evaluated at the first $m$ values?
Comment: @user17762: yes. I should have added that to my answer (as I have now :-)
Comment: Very nice. Thanks.
Answer: Another method involving Mellin Transforms.
[This is my first time using this tactic so please correct me if I make a mistake, I am answering this question in part as practice]
Consider $F(s)$ as the Mellin Transform of $f(x)$
$$F(s)=\int_0^\infty x^{s-1} f(x)\text{ d}x$$
And thus
$$F''(s)=\int_0^\infty x^{s-1}\ln^2 x \space f(x) \text{ d}x$$
We assume that $f(x)=e^{-kx}$ and we are left with a nice known identity:
$$F(s)=\int_0^\infty x^{s-1}e^{-kx}=\frac{\Gamma(s)}{k^{s+1}}$$
Thus the answer to our integral is truly:
$$\lim_{s\to 3} \left(\left[\frac{\Gamma(s)}{k^{s-1}}\right]''\right)$$
Unfortunately, I am unable to calculate this limit, but to me, if you wanted to take a route similar to this, it seems much cleaner in the long run.
Comment: Please let me know if the limit evaluates to the result, but in theory it does.


Recuperar o valor de um JTextField através de um ActionListener

Question: Sou um pouco novo em java e estava tentando entender os listeners. Por isso desculpem-me se o erro for simples.
Tenho um programa que cria uma interface gráfica simples e eu quero pegar o valor de um JTextField através de um ActionListener. Segue o código:
public abstract class Teste {

    public static void main(String[] args) {

        JFrame tela = new JFrame("Teste");
        JPanel panel = new JPanel();
        JLabel texto = new JLabel("Nome: ");
        JTextField nomeField = new JTextField(60);

        panel.add(texto);
        panel.add(nomeField);

        Clique text = new Clique();
        nomeField.addActionListener(text);

        panel.setLayout(new FlowLayout());
        tela.setContentPane(panel);
        tela.pack();
        tela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        tela.setVisible(true);
   }

}

class Clique implements ActionListener{

    public void actionPerformed(ActionEvent e){

        System.out.println(); //Quero imprimir o texto do campo aqui

    }
}

A questão é que eu não sei como referenciar o objeto do campo de texto para pegar o valor através de um getText().
Answer: Você pode passar o campo necessário no construtor:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public abstract class Teste {

    public static void main(String[] args) {

        JFrame tela = new JFrame("Teste");
        JPanel panel = new JPanel();
        JLabel texto = new JLabel("Nome: ");
        JTextField nomeField = new JTextField(60);

        panel.add(texto);
        panel.add(nomeField);

        Clique text = new Clique(nomeField);
        nomeField.addActionListener(text);

        panel.setLayout(new FlowLayout());
        tela.setContentPane(panel);
        tela.pack();
        tela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        tela.setVisible(true);
   }

}

class Clique implements ActionListener {

    private final JTextField field;

    public Clique(JTextField field) {
        this.field = field;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(field.getText());
    }
}

Uma outra alternativa é usar um lambda (Java 8 ou superior):
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public abstract class Teste {

    public static void main(String[] args) {

        JFrame tela = new JFrame("Teste");
        JPanel panel = new JPanel();
        JLabel texto = new JLabel("Nome: ");
        JTextField nomeField = new JTextField(60);

        panel.add(texto);
        panel.add(nomeField);

        nomeField.addActionListener(event -> System.out.println(nomeField.getText()));

        panel.setLayout(new FlowLayout());
        tela.setContentPane(panel);
        tela.pack();
        tela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        tela.setVisible(true);
   }

}

Uma terceira forma, caso você esteja no Java 7 ou inferior, é usar uma classe anônima:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public abstract class Teste {

    public static void main(String[] args) {

        JFrame tela = new JFrame("Teste");
        JPanel panel = new JPanel();
        JLabel texto = new JLabel("Nome: ");
        JTextField nomeField = new JTextField(60);

        panel.add(texto);
        panel.add(nomeField);

        nomeField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                System.out.println(nomeField.getText());
            }
        });

        panel.setLayout(new FlowLayout());
        tela.setContentPane(panel);
        tela.pack();
        tela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        tela.setVisible(true);
   }

}

Comment: @leandro17br Vê se este link te ajuda: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html - Se não ajudar, é só procurar no Google por "java lambda-expressions" que você deve achar bastante coisas.
Comment: muito boa resposta, sobre o segundo método tem algum link que possa indicar com alguma explicação a mais?


Enumerator::Lazy and Garbage Collection

Question: I am using Ruby's built in CSV parser against large files.
My approach is to separate the parsing with the rest of the logic. To achieve this I am creating an array of hashes. I also want to take advantage of Ruby's Enumerator:: Lazy to prevent loading the entire file in memory.
My question is, when I'm actually iterating through the array of hashes, does the Garbage collector actually clean things up as I go or will it only clean up when the entire array can be cleaned up, essentially still allowing the entire value in memory still?
I'm not asking if it will clean each element as I finish with it, only if it will clean it before the entire enum is actually evaluated.
Answer: When you iterate over a plain old array, the garbage collector has no chance to do anything.
You can help the garbage collector by writing nil into the array position after you no longer need the element, so that the object in this position may now be free for collection.
When you correctly use lazy enumerator, you are not iterate over an array of hashes. Instead you enumerate over the hashes, handling one after the other, and each one is read on demand.
So you have the chance to use much less memory (depending on your further processing, and that it does not hold the objects in memory anyway)
the structure may look like this:
enum = Enumerator.new do |yielder|
  csv.read(...) do
     ...
     yielder.yield hash
  end
end

enum.lazy.map{|hash| do_something(hash); nil}.count

You also need to make sure that you are not generate the array again in the last step of the chain.

Enumerator::Lazy and Garbage Collection


Sql with mysql reserved word

Question: I have this following sql code:
$sql = "INSERT INTO data (Artist, Name) VALUES ('TF2', 'you're right behind me')";

The code itself looks normal but for some reason mysql doesn't want to allow me to save it. I get the following error:
"#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 're right behind me')' at line 1"

What I know the problem is because of the word "right" being reserved in mysql but I need to save it so how should my code look like. All help is appreciated
Comment: I believe that is because of extra single qoute `'you're right behind me'` in `you're`. Maybe you can escape it by using backslash?
Comment: this is a good argument for parameterized queries
Comment: You need to escape your commas. Use `You\'re` for instance. There's a function for that, called `addslashes`. Consult the PHP manual on the matter http://php.net/manual/en/function.addslashes.php
Comment: @Fred addaslashes is **NOT** the function that should be used to escape sql parameters. Each db library has it's own function that will take into account things such as the encoding of the connection to properly escape the string (mysql_escape_string, mysqli_real_escape_string, etc). Even better, would be using bound parameters so you don't have to escape them manually.
Comment: @jcsanyi You're right. I was 50% right, apostrophes need to be escaped, if manually inserted. ;-)
Comment: I meant `mysql_real_escape_string` http://www.php.net/manual/en/function.mysql-real-escape-string.php - I looked up the wrong function.
Comment: Okay, have used mysql_real_escape_string like two years ago, forgot about if that was the one. Thanks Fred and @jcsanyi
Comment: @AmandaWood You're welcome, hope this solved your problem Amanda.
Comment: @AmandaWood You haven't mentioned what libraries you are using to actually connect to mysql. If you're using mysql_connect, mysql_query, etc, then yes - mysql_escape_string() is what you want. If you're using mysqli or PDO, there's corresponding functions that you should use with them instead.
Comment: @AmandaWood If you **are** using the mysql_* functions, **[please reconsider](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php).**  They are no longer maintained and are officially deprecated. See the **[red box](http://php.net/manual/en/function.mysql-connect.php)**? You can use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) instead - [this page](http://php.net/manual/en/mysqlinfo.api.choosing.php) can help you decide which to use.
Comment: @Dukeling: Not really, it isn't.
Answer: Your problem is because you have an ' in the work you're. So your string is terminating to early in your sentence.  Use you\'re instead to escape the character '
$sql = "INSERT INTO data ('Artist', 'Name') VALUES ('TF2', 'you\'re right behind me')";

Answer: As @Fred and @JunM have already commented, you have two issues. The first is that Name is a reserved word. The second is that you have a single quote inside your single quoted string. Change your SQL to this:
$sql = "INSERT INTO data (`Artist`, `Name`) VALUES ('TF2', 'you\'re right behind me')";

Comment: This works for this particular exempel, but the thing is the name is submitted by user, and are different from time to time, is there any permament solution?
Comment: @AmandaWood http://php.net/manual/en/function.addslashes.php
Comment: @AmandaWood `addslashes()` is **not** what you should be using. See my comment above
Comment: @AmandaWood He's right. I looked up the wrong function. See `jcsanyi's` comment above.
Comment: @jcsanyi I stand corrected.
Comment: @Fred Okay, should I be using mysql_escape_string?
Comment: @AmandaWood I would say yes, however I'm not an MySQL expert. Views on this anyone? There are examples on the PHP.net link I gave you.
Answer: My experience with MySQL is limited, but I use SQL Server extensively. To me it seems that the problem is in the apostrophy used in the "you're right behind me". In SQL server, I'd have to use a double apostrophy, so the sql instruction would be something like this (notice the double apostrophy in the you''re):
$sql = "INSERT INTO data (Artist, Name) VALUES ('TF2', 'you''re right behind me')";

Hope this helps.
Regards
Comment: yet another argument for parameterized queries... escaping is done in a database specific way.
Comment: This is wrong, you have to escape ' with \'
Comment: Thanks for the clarification @ObieMD5. I use the double quotes in SQL Server. Regards

Sql with mysql reserved word


Preventing line breaks - ENTER keypresses. Instead - fire custom event

Question: I'd like to use Aloha to WYSIWYG-edit single-line headlines.
For that I need to intercept ENTER keypress (to prevent line-break) and fire custom save event.
Is there a way to do that?
Thanks!
Answer: Here's what worked for me on "hotfix" branch:
<code>Aloha.bind('aloha-smart-content-changed', function(e, data) {
    value = data.editable.getContents();
    // save it to database.
});
Aloha.bind('aloha-command-will-execute', function(e, data) {
    if (data.commandId == 'insertlinebreak') {
        data.preventDefault = true;
    }
});
</code>
More info here:
https://github.com/alohaeditor/Aloha-Editor/issues/1502


Horizontal scrolling Marquee, My text insists on bunching together when function is acxtivated

Question: So Im creating a vertically scrolling marquee, which uses javascript to alter the the top position of the text. A function runs at timed intervals creating the illusion of several groups of text moving vertically within the marquee from bottom to top and back again.
Everything is working fine Except the groups of text insist of been bunched together at the top of the marquee.
Can anybody offer advice ???

window.onload = defineMarquee;

var timeID;
var marqueeTxt = new Array();
var marqueeOff = true;
var topPos= 20;

/* defineMarquee()
      Initializes the contents of the marquee, determines the
      top style positions of each marquee item, and sets the
      onclick event handlers for the document
*/
   function defineMarquee() {

   var topValue;

   var allElems = document.getElementsByTagName("*");

   for(var i = 0; i < allElems.length; i++){
      if (allElems[i].className == "marqueeTxt") marqueeTxt.push(allElems[i]);
   }

//Extract the "top" CSS class from marqueeTxt

   for(var i = 0; i < marqueeTxt.length; i++){
      if(marqueeTxt[i].getComputedStyle) {
         topValue = marqueeTxt[i].getPropertyValue("top")
         marqueeTxt[i].style.top = topValue +"px";
       }
      else if (marqueeTxt[i].currentStyle) {
          topValue = marqueeTxt[i].currentStyle("top");
          marqueeTxt[i].style.top = topValue +"px";
      }

   }

   document.getElementById("startMarquee").onclick = startMarquee;
   document.getElementById("stopMarquee").onclick = stopMarquee;

}

/* startMarquee()
      Starts the marquee in motion
*/

   function startMarquee() {
      if(marqueeOff ==  true) {
         timeID = setInterval("moveText()", 50);
         marqueeOff = false;
      }
   }

/* stopMarquee()
   Stops the Marquee
*/

   function stopMarquee() {
      clearInterval(timeID);
      marqueeOff = true;
   }

/* moveText ()
   move the text within the marquee in a vertical direction
*/

   function moveText() {

   for(var i = 0; i < marqueeTxt.length; i++) {
      if(marqueeTxt[i].getComputedStyle) {
      topPos = parseInt(marqueeTxt.getPropertyValue("top"));
   }
   else if(marqueeTxt[i].currentStyle) {
      topPos = parseInt(marqueeTxt.currentStyle("top"));
   }

   if(topPos < -110) {
      topPos = 700;
   } else { topPos -= 1;
   }

   marqueeTxt[i].style.top = topPos + "px";

}

}
*                    {margin: 0px; padding: 0px}
body                 {font-size: 15px; font-family: Arial, Helvetica, sans-serif}

#pageContent         {position: absolute; top: 0px; left: 30px; width: 800px}

#links               {display: block; width: 100%; margin-bottom: 20px;
                      border-bottom: 1px solid rgb(0,153, 102); float: left}
#links               {list-style-type: none}
#links li            {display: block; float: left; text-align: center; width: 19%}
#links li a          {display: block; width: 100%; text-decoration: none; color: black;
                      background-color: white}
#links li a:hover    {color: white; background-color: rgb(0,153,102)}

#leftCol             {clear: left; float: left}
h1                   {font-size: 24px; letter-spacing: 5px; color: rgb(0, 153,102)}

#main                {float: left; width: 450px; margin-left: 10px;
                      padding-left: 10px; border-left: 1px solid rgb(0,153,102);
                      padding-bottom: 15px}
#main img            {float: right; margin: 0px 0px 10px 10px}

#main p              {margin-bottom: 10px}

address              {width: 100%; clear: left; font-style: normal; font-size: 12px;
                      border-top: 1px solid black; text-align: center;
                      padding-bottom: 15px}

.marquee             {position: absolute; top: 0px; left: 0px;
                      width: 280px; height: 300px;
                      background-color: rgb(0, 153, 102); color:white;
                      border: 5px inset white;
                      padding:0px; overflow:hidden; position:relative}

#marqueeTxt1         {font-size: 1.4em; letter-spacing: 0.15em; border-bottom: 1px solid white}
input                {width: 120px; margin: 5px; font-size: 0.9em}
#marqueeButtons      {width: 280px; text-align: center}

#marqueeTxt1         {position: absolute; top: 40px; left: 20px}
#marqueeTxt2         {position: absolute; top: 90px; left: 20px}
#marqueeTxt3         {position: absolute; top: 170px; left: 20px}
#marqueeTxt4         {position: absolute; top: 250px; left: 20px}
#marqueeTxt5         {position: absolute; top: 330px; left: 20px}
#marqueeTxt6         {position: absolute; top: 410px; left: 20px}
#marqueeTxt7         {position: absolute; top: 490px; left: 20px}
#marqueeTxt8         {position: absolute; top: 570px; left: 20px}
#marqueeTxt9         {position: absolute; top: 640px; left: 20px}
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

   <title>Boise Youth Symphony Orchestra</title>
   <link href="bstyles.css" rel="stylesheet" type="text/css" />

   <form id="marqueeForm" action="">

Home Page

About BYSO

Our Director

Join BYSO

Contact Us

            Schedule of Events

            Holiday Concert

            December 14, 7:30 PM

            Boise Civic Center

            Christmas Concert

            Dec. 16, 7 PM

            Our Savior Episcopal Church

            Spring Concert

            Feb. 27, 7 PM

            Boise Civic Center

            Easter Fanfare

            March 14, 9 PM

            Our Savior Episcopal Church

            High School MusicFest

            May 2, 3 PM

            Boise Central High School

            Summer Concert

            June 15, 7:30 PM

            Frontier Concert Hall

            Fourth Fest

            July 4, 4 PM

            Canyon View Park

            Frontier Days

            August 9, 1 PM

            Boise Concert Hall

         <input type="button" id="startMarquee" value="Start Marquee" />
         <input type="button" id="stopMarquee" value="Pause Marquee" />

Boise Youth Symphony Orchestra

The Boise Youth Symphony Orchestra has delighted audiences worldwide with
            beautiful music while offering the highest quality musical training to over
            1,000 teens throughout Idaho for the past 30 years. BYSO
            has established an outstanding reputation for its high quality sound, its
            series of commissioned works, and collaborations with prominent musical groups
            such as the Idaho and Boise Symphony Orchestras, the Montana Chamber
            Orchestra, the Boise Adult Choir and the Western Symphony Orchestra.
            Last year the group was invited to serve as the U.S. representative to
            the 7th Annual World Festival of youth orchestras in Poznan, Poland.

Leading this success for the past decade has been Boise Symphony artistic
            director Denise Young. In a concert review by John Aehl, music critic for
            the Boise Times, Roger Adler writes, "It is a pleasure to report that
            the orchestra is playing better than ever."

    <address>
    BYSO · 300 Mountain Lane · Boise, Idaho  83702 · (208) 555 - 9114
    </address>

</form>

Comment: Look at how you are setting the top value on your marqueeText objects, they are only 1 pixel apart.  Try spacing them out more.
Comment: ugh, the snippet is misbehaving, but you are using the topPos var as a global, so it is being set to the same for all of the different items, you need to use a closure
Comment: I think you could be onto to something Ray ...But when I declare the topPos variable inside  the movetext(), the text doesn't move
Comment: I'd like to manipulate the text without changing any of the properties in the CSS file...
Comment: We're do you think I should add a closure..?
Answer: My recommendation would be to use relative positioning for #marqueeTxt:
#marqueeTxt1         {position: relative; padding: 4px 0 4px 0;}
...

Also setting a longer interval time and additional length onto the positioning might work better:
Interval:
timeID = setInterval("moveText()", 100);

Position:
if(topPos < -600) {
   topPos = 300;

window.onload = defineMarquee;

var timeID;
var marqueeTxt = new Array();
var marqueeOff = true;
var topPos= 20;

/* defineMarquee()
      Initializes the contents of the marquee, determines the
      top style positions of each marquee item, and sets the
      onclick event handlers for the document
*/
   function defineMarquee() {

   var topValue;

   var allElems = document.getElementsByTagName("*");

   for(var i = 0; i < allElems.length; i++){
      if (allElems[i].className == "marqueeTxt") marqueeTxt.push(allElems[i]);
   }

//Extract the "top" CSS class from marqueeTxt

   for(var i = 0; i < marqueeTxt.length; i++){
      if(marqueeTxt[i].getComputedStyle) {
         topValue = marqueeTxt[i].getPropertyValue("top")
         marqueeTxt[i].style.top = topValue +"px";
       }
      else if (marqueeTxt[i].currentStyle) {
          topValue = marqueeTxt[i].currentStyle("top");
          marqueeTxt[i].style.top = topValue +"px";
      }

   }

   document.getElementById("startMarquee").onclick = startMarquee;
   document.getElementById("stopMarquee").onclick = stopMarquee;

}

/* startMarquee()
      Starts the marquee in motion
*/

   function startMarquee() {
      if(marqueeOff ==  true) {
         timeID = setInterval("moveText()", 100);
         marqueeOff = false;
      }
   }

/* stopMarquee()
   Stops the Marquee
*/

   function stopMarquee() {
      clearInterval(timeID);
      marqueeOff = true;
   }

/* moveText ()
   move the text within the marquee in a vertical direction
*/

   function moveText() {

   for(var i = 0; i < marqueeTxt.length; i++) {
      if(marqueeTxt[i].getComputedStyle) {
      topPos = parseInt(marqueeTxt.getPropertyValue("top"));
   }
   else if(marqueeTxt[i].currentStyle) {
      topPos = parseInt(marqueeTxt.currentStyle("top"));
   }

   if(topPos < -600) {
      topPos = 300;
   } else { topPos -= 1;
   }

   marqueeTxt[i].style.top = topPos + "px";

}

}
*                    {margin: 0px; padding: 0px}
body                 {font-size: 15px; font-family: Arial, Helvetica, sans-serif}

#pageContent         {position: absolute; top: 0px; left: 30px; width: 800px}

#links               {display: block; width: 100%; margin-bottom: 20px;
                      border-bottom: 1px solid rgb(0,153, 102); float: left}
#links               {list-style-type: none}
#links li            {display: block; float: left; text-align: center; width: 19%}
#links li a          {display: block; width: 100%; text-decoration: none; color: black;
                      background-color: white}
#links li a:hover    {color: white; background-color: rgb(0,153,102)}

#leftCol             {clear: left; float: left}
h1                   {font-size: 24px; letter-spacing: 5px; color: rgb(0, 153,102)}

#main                {float: left; width: 450px; margin-left: 10px;
                      padding-left: 10px; border-left: 1px solid rgb(0,153,102);
                      padding-bottom: 15px}
#main img            {float: right; margin: 0px 0px 10px 10px}

#main p              {margin-bottom: 10px}

address              {width: 100%; clear: left; font-style: normal; font-size: 12px;
                      border-top: 1px solid black; text-align: center;
                      padding-bottom: 15px}

.marquee             {position: absolute; top: 0px; left: 0px;
                      width: 280px; height: 300px;
                      background-color: rgb(0, 153, 102); color:white;
                      border: 5px inset white;
                      padding:0px; overflow:hidden; position:relative}

#marqueeTxt1         {font-size: 1.4em; letter-spacing: 0.15em; border-bottom: 1px solid white}
input                {width: 120px; margin: 5px; font-size: 0.9em}
#marqueeButtons      {width: 280px; text-align: center}

#marqueeTxt1         {position: relative; padding: 4px 0 4px 0;}
#marqueeTxt2         {position: relative; padding: 4px 0 4px 0;}
#marqueeTxt3         {position: relative; padding: 4px 0 4px 0;}
#marqueeTxt4         {position: relative; padding: 4px 0 4px 0;}
#marqueeTxt5         {position: relative; padding: 4px 0 4px 0;}
#marqueeTxt6         {position: relative; padding: 4px 0 4px 0;}
#marqueeTxt7         {position: relative; padding: 4px 0 4px 0;}
#marqueeTxt8         {position: relative; padding: 4px 0 4px 0;}
#marqueeTxt9         {position: relative; padding: 4px 0 4px 0;}
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

   <title>Boise Youth Symphony Orchestra</title>
   <link href="bstyles.css" rel="stylesheet" type="text/css" />

   <form id="marqueeForm" action="">

Home Page

About BYSO

Our Director

Join BYSO

Contact Us

            Schedule of Events

            Holiday Concert

            December 14, 7:30 PM

            Boise Civic Center

            Christmas Concert

            Dec. 16, 7 PM

            Our Savior Episcopal Church

            Spring Concert

            Feb. 27, 7 PM

            Boise Civic Center

            Easter Fanfare

            March 14, 9 PM

            Our Savior Episcopal Church

            High School MusicFest

            May 2, 3 PM

            Boise Central High School

            Summer Concert

            June 15, 7:30 PM

            Frontier Concert Hall

            Fourth Fest

            July 4, 4 PM

            Canyon View Park

            Frontier Days

            August 9, 1 PM

            Boise Concert Hall

         <input type="button" id="startMarquee" value="Start Marquee" />
         <input type="button" id="stopMarquee" value="Pause Marquee" />

Boise Youth Symphony Orchestra

The Boise Youth Symphony Orchestra has delighted audiences worldwide with
            beautiful music while offering the highest quality musical training to over
            1,000 teens throughout Idaho for the past 30 years. BYSO
            has established an outstanding reputation for its high quality sound, its
            series of commissioned works, and collaborations with prominent musical groups
            such as the Idaho and Boise Symphony Orchestras, the Montana Chamber
            Orchestra, the Boise Adult Choir and the Western Symphony Orchestra.
            Last year the group was invited to serve as the U.S. representative to
            the 7th Annual World Festival of youth orchestras in Poznan, Poland.

Leading this success for the past decade has been Boise Symphony artistic
            director Denise Young. In a concert review by John Aehl, music critic for
            the Boise Times, Roger Adler writes, "It is a pleasure to report that
            the orchestra is playing better than ever."

    <address>
    BYSO · 300 Mountain Lane · Boise, Idaho  83702 · (208) 555 - 9114
    </address>

</form>

Comment: Thanks for the tip...but if possible I'd like to fix this problem without changing any off the properties in the css file..
Comment: The main issue is a direct result of the `CSS`, so unless you make some changes there you'll have to add `CSS` into your html, which essentially overrides the `.css` file. Why would not want to change any of the properties in the `CSS`? That makes absolutely no sense.
Comment: Cool...Well what you did works well, Thank you !!! Im going to keep playing with it as I know that I will be able to change the top position, by setting the initial style in Javascript.
Answer: So I managed to solve this problem.
Thanks to the .getComputedStyle method.
Thanks for the help everyone

window.onload = defineMarquee;

var timeID;
var marqueeTxt = new Array();
var marqueeOff = true;

/* defineMarquee()
      Initializes the contents of the marquee, determines the
      top style positions of each marquee item, and sets the
      onclick event handlers for the document
*/
   function defineMarquee() {

   var topValue = 0;

   var allElems = document.getElementsByTagName("*");

   for(var i = 0; i < allElems.length; i++){
      if (allElems[i].className == "marqueeTxt") marqueeTxt.push(allElems[i]);
   }

//Extract the "top" CSS class from marqueeTxt

   for(var i = 0; i < marqueeTxt.length; i++){
      if (window.getComputedStyle) {
       topValue = document.defaultView.getComputedStyle(marqueeTxt[i]).getPropertyValue("top");}
       else if (marqueeTxt[i].currentStyle) {
         topValue = document.defaultView.marqueeTxt[i].currentStyle["top"];
       }
         marqueeTxt[i].style.top = topValue;
   }

   document.getElementById("startMarquee").onclick = startMarquee;
   document.getElementById("stopMarquee").onclick = stopMarquee;

}

/* startMarquee()
      Starts the marquee in motion
*/

   function startMarquee() {
      if(marqueeOff ==  true) {
         timeID = setInterval("moveText()", 50);
         marqueeOff = false;
      }
   }

/* stopMarquee()
   Stops the Marquee
*/

   function stopMarquee() {
      clearInterval(timeID);
      marqueeOff = true;
   }

/* moveText ()
   move the text within the marquee in a vertical direction
*/

function moveText (){

for(var i = 0; i < marqueeTxt.length; i++) {

   topPos = parseInt(marqueeTxt[i].style.top);

   if(topPos < -110) {
      topPos = 700;
   } else { topPos -= 1;
   }

   marqueeTxt[i].style.top = topPos + "px";

}

}
*                    {margin: 0px; padding: 0px}
body                 {font-size: 15px; font-family: Arial, Helvetica, sans-serif}

#pageContent         {position: absolute; top: 0px; left: 30px; width: 800px}

#links               {display: block; width: 100%; margin-bottom: 20px;
                      border-bottom: 1px solid rgb(0,153, 102); float: left}
#links               {list-style-type: none}
#links li            {display: block; float: left; text-align: center; width: 19%}
#links li a          {display: block; width: 100%; text-decoration: none; color: black;
                      background-color: white}
#links li a:hover    {color: white; background-color: rgb(0,153,102)}

#leftCol             {clear: left; float: left}
h1                   {font-size: 24px; letter-spacing: 5px; color: rgb(0, 153,102)}

#main                {float: left; width: 450px; margin-left: 10px;
                      padding-left: 10px; border-left: 1px solid rgb(0,153,102);
                      padding-bottom: 15px}
#main img            {float: right; margin: 0px 0px 10px 10px}

#main p              {margin-bottom: 10px}

address              {width: 100%; clear: left; font-style: normal; font-size: 12px;
                      border-top: 1px solid black; text-align: center;
                      padding-bottom: 15px}

.marquee             {position: absolute; top: 0px; left: 0px;
                      width: 280px; height: 300px;
                      background-color: rgb(0, 153, 102); color:white;
                      border: 5px inset white;
                      padding:0px; overflow:hidden; position:relative}

#marqueeTxt1         {font-size: 1.4em; letter-spacing: 0.15em; border-bottom: 1px solid white}
input                {width: 120px; margin: 5px; font-size: 0.9em}
#marqueeButtons      {width: 280px; text-align: center}

#marqueeTxt1         {position: absolute; top: 40px; left: 20px}
#marqueeTxt2         {position: absolute; top: 90px; left: 20px}
#marqueeTxt3         {position: absolute; top: 170px; left: 20px}
#marqueeTxt4         {position: absolute; top: 250px; left: 20px}
#marqueeTxt5         {position: absolute; top: 330px; left: 20px}
#marqueeTxt6         {position: absolute; top: 410px; left: 20px}
#marqueeTxt7         {position: absolute; top: 490px; left: 20px}
#marqueeTxt8         {position: absolute; top: 570px; left: 20px}
#marqueeTxt9         {position: absolute; top: 640px; left: 20px}
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

   <title>Boise Youth Symphony Orchestra</title>
   <link href="bstyles.css" rel="stylesheet" type="text/css" />

   <form id="marqueeForm" action="">

Home Page

About BYSO

Our Director

Join BYSO

Contact Us

            Schedule of Events

            Holiday Concert

            December 14, 7:30 PM

            Boise Civic Center

            Christmas Concert

            Dec. 16, 7 PM

            Our Savior Episcopal Church

            Spring Concert

            Feb. 27, 7 PM

            Boise Civic Center

            Easter Fanfare

            March 14, 9 PM

            Our Savior Episcopal Church

            High School MusicFest

            May 2, 3 PM

            Boise Central High School

            Summer Concert

            June 15, 7:30 PM

            Frontier Concert Hall

            Fourth Fest

            July 4, 4 PM

            Canyon View Park

            Frontier Days

            August 9, 1 PM

            Boise Concert Hall

         <input type="button" id="startMarquee" value="Start Marquee" />
         <input type="button" id="stopMarquee" value="Pause Marquee" />

Boise Youth Symphony Orchestra

The Boise Youth Symphony Orchestra has delighted audiences worldwide with
            beautiful music while offering the highest quality musical training to over
            1,000 teens throughout Idaho for the past 30 years. BYSO
            has established an outstanding reputation for its high quality sound, its
            series of commissioned works, and collaborations with prominent musical groups
            such as the Idaho and Boise Symphony Orchestras, the Montana Chamber
            Orchestra, the Boise Adult Choir and the Western Symphony Orchestra.
            Last year the group was invited to serve as the U.S. representative to
            the 7th Annual World Festival of youth orchestras in Poznan, Poland.

Leading this success for the past decade has been Boise Symphony artistic
            director Denise Young. In a concert review by John Aehl, music critic for
            the Boise Times, Roger Adler writes, "It is a pleasure to report that
            the orchestra is playing better than ever."

    <address>
    BYSO · 300 Mountain Lane · Boise, Idaho  83702 · (208) 555 - 9114
    </address>

</form>


Type-safe configuration read/write library for Java?

Question: Is there a good configuration library for Java which will allow me to read settings in a type-safe way? For example by taking my crafted IConfiguration interface with getters and setters declared and allowing me to read/write configuration via it.
It's a bit boring to read settings using properties.getProperty("group.setting") and then cast it to needed type. Apache commons configuration allows to use something like config.getDouble("number"), but "number" here is a string again and I would like to be able to do something like double value = config.GetNumber().
Answer: OWNER library does what you want.
Answer: I think typesafe's config library is what you might need. Here is the link
It is a type-safe library. Here is an example on how to use this library:
import com.typesafe.config.ConfigFactory

Config conf = ConfigFactory.load();
int bar1 = conf.getInt("foo.bar");
Config foo = conf.getConfig("foo");
int bar2 = foo.getInt("bar");

The main reason why I recommend this library is that it can read HOCON files. It stands for "Human-Optimized Config Object Notation" and is a superset of JSON:
{
    "foo" : {
        "bar" : 10,
        "baz" : 12
    }
}

It has many features to make it more readable. Like omitting special characters (,,:,{}). And the coolest things is inheritance:
standard-timeout = 10ms
foo.timeout = ${standard-timeout}
bar.timeout = ${standard-timeout}

And if you duplicate a field with an object value, then the objects are merged with last-one-wins. So:
foo = { a : 42, c : 5 }
foo = { b : 43, c : 6 }

means the same as:
foo = { a : 42, b : 43, c : 6 }

Please look at the project's readme file to find more about this great configuration library https://github.com/typesafehub/config
Answer: You can define an XML configuration file with XSD and then generate JAXB source code with XJC. Every XSD type is mapped to a Java class, which you can easily marshal/unmarshal
An example. XSD:
<xsd:simpleType name="GroupType">
  <xsd:restriction base="xsd:int">
    <xsd:minInclusive value="1"/>
    <xsd:maxInclusive value="255"/>
  </xsd:restriction>
</xsd:simpleType>

Resulting Java code:
public class ElementType {
    @XmlAttribute(name = "Group", required = true)
    protected int group;

    public int getGroup() {
        return group;
    }
    public void setGroup(int value) {
        this.group = value;
    }
}

Taken from the tutorial:
http://jaxb.java.net/tutorial/
Answer: If you have a configuration interface such as:
public interface IConfig {
  int getNumber();
  void setNumber(int number);

  String getSomeProperty();
  void setSomeProperty(String someProperty);
}

then you could use a Proxy to map the methods to properties:
public class ConfigWrapper implements InvocationHandler {
  @SuppressWarnings(value="unchecked")
  public static <T> T wrap(Class c, Properties p) {
    return (T)Proxy.newProxyInstance(c.getClassLoader(), new Class[] {c},
        new ConfigWrapper(p));
  }

  private final Properties properties;

  private ConfigWrapper(Properties p) {
    this.properties = p;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) {
    if(method.getName().startsWith("get")) {
      if(method.getReturnType().equals(int.class)) {
        return Integer.parseInt(
            this.properties.getProperty(method.getName().substring(3)));
      } else if(method.getReturnType().equals(String.class)) {
        return this.properties.getProperty(method.getName().substring(3));
      } else {
        // obviously in a real application you'd want to handle more than just
        // String and int
        throw new RuntimeException(method.getName() + " returns unsupported type: "
            + method.getReturnType());
      }
    } else if(method.getName().startsWith("set")) {
      this.properties.setProperty(method.getName().substring(3),
          args[0].toString());
      return null;
    } else {
      throw new RuntimeException("Unknown method: " + method.getName());
    }
  }
}

To use:
Properties p = new Properties();

IConfig config = wrap(IConfig.class, p);

config.setNumber(50);
config.setSomeProperty("some value");
System.out.println(config.getNumber());
System.out.println(config.getSomeProperty());
System.out.println(p);

Calling one of the interface methods results in a call to ConfigWrapper.invoke(), which updates or retrieves from the Properties object (depending on whether you called a getter or setter).
Note that this implementation is distinctly unsafe since:

values already in the Properties object aren't validated until the getter is called
setter and getter don't have to accept/return the same type

I'm not aware of an existing library to do this, maybe because Properties objects are fairly limited in terms of the configuration they can describe.
Answer: My Config4J library (which is mature and well-documented but not widely known) provides most of what you want.
In particular, Config4J provides type-safe "lookup" (that is, "get") operations for built-in types such as string, boolean, int, float, and durations (such as "500 milliseconds" or "2.5 days"). A duration string is automatically converted to an integer value denoting (your choice of) milliseconds or seconds.
The library also provides building blocks so you can perform type-safe lookups on strings of the form "<float> <units>" (for example, "2 cm" and "10.5 meters" for distances) or "<units> <float>" (for example, "$0.99" or "£10.00" for money).
The library also provides a trivial-to-use schema validator (in case that is of interest to you).
The way Config4J fails to meet your stated requirements is that the "insert" (that is, "put") functionality of the library works only in terms of strings. So you would have to convert an int/boolean/float/int-denoting-duration/whatever value into a string and then "insert" that into the Config4J object. However, that -to-string conversion is not usually a burdensome task.
After inserting some name=value pairs into the Config4J object, you can then call dump() to serialise the entire object into a string that you can then write back to a configuration file.
Reading Chapters 2 and 3 of the "Getting Started Guide" (PDF, HTML) should give you an a good-enough overview of Config4J to decide if it fits your needs. You might also want to look at the "simple-encapsulation" demo, which is supplied in the source-code download (compressed tar, zip).
Comment: Thanks, I will look. BTW, where is chapter 1 on the site? :) I see only 2-4
Comment: @FractalizeR: On the www.config4star.org website, scroll down to the "Download the Manuals" section, and you will be able to access all the manuals.
Answer: I don't think so, because java is not a dynamic language. The only way this is achievable is if you had a code generator that would get your properties file and generate the configuration class. Or if you manually add a getter for each property.
commons-configuration is the best way to go, I think.
Answer: You should be able to get some traction by using XStream to serialize the configuration class.  But the downsides are:

The config file won't be in one of the standard properties file formats.  It will be arbitrary XML instead.
The serialization format will be fragile.  Minor changes to the configuration class could render old config files unreadable.

On the upside, a format based on arbitrary XML can represent configuration items that have structure much better than the standard properties file formats can.


How do I parse in the arguments to my Python training file when running the Sagemaker pipeline's TrainingStep?

Question: I am trying to parse in arguments from my previous ProcessingStep into a custom python script in SageMaker pipelines, as shown below.
xgb_estimator = XGBoost(
        entry_point=os.path.join(BASE_DIR, "xgboost_train.py"),
        output_path=model_path,
        code_location=model_path,
        hyperparameters=hyperparams,
        role=role,
        # Fetch instance type and count from pipeline parameters
        instance_count=1,
        instance_type=training_instance_type,
        framework_version="1.3-1",
    )

    # Access the location where the preceding processing step saved train and validation datasets
    # Pipeline step properties can give access to outputs which can be used in succeeding steps
    s3_input_train = TrainingInput(
        s3_data=step_process.properties.ProcessingOutputConfig.Outputs[
            "train"
        ].S3Output.S3Uri,
        content_type="text/csv",
        # s3_data_type="S3Prefix",
    )
    s3_input_validation = TrainingInput(
        s3_data=step_process.properties.ProcessingOutputConfig.Outputs[
            "validation"
        ].S3Output.S3Uri,
        content_type="text/csv",
        # s3_data_type="S3Prefix",
    )

    # Set pipeline training step
    step_train = TrainingStep(
        name="TrainHDBResaleXGBModel",
        estimator=xgb_estimator,
        inputs={
            "train": s3_input_train,  # Train channel
            "validation": s3_input_validation,  # Validation channel
        },
    )

In my xgboost_train.py, I tried to access the inputs train and validation using:
# Set location of input training data
parser.add_argument("--train", type=str)
# Set location of input validation data
parser.add_argument("--validation", type=str)

data_train = pd.read_csv(f"{args.train}/train.csv")
data_validation = pd.read_csv(f"{args.validation}/validation.csv")

But args.train and args.validation keeps defaulting to None. How do I actually get the train and validation channel inputs I passed into TrainingStep inputs?
Answer: Looking in the documentation under "Prepare a Training script":

you can access useful properties about the training environment through various environment variables

Therefore, when you input a data channel as in your case, you will refer to specially created environment variables.
Your code becomes:
parser = argparse.ArgumentParser()

# Set location of input training data
parser.add_argument("--train", type=str, default=os.environ["SM_CHANNEL_TRAIN"])

# Set location of input validation data
parser.add_argument("--validation", type=str, default=os.environ["SM_CHANNEL_VALIDATION"])

args, _ = parser.parse_known_args()

data_train = pd.read_csv(f"{args.train}/train.csv")
data_validation = pd.read_csv(f"{args.validation}/validation.csv")

If you want to choose a different name for your input channel, the environment variable will change accordingly.
For example:
# in your TrainingStep
inputs = {
            "myexample": TrainingInput(
                s3_data=step_process.properties.ProcessingOutputConfig.Outputs[
                    "myexample"
                ].S3Output.S3Uri
            )
        }

# in your training script
parser.add_argument("--myexample", type=str, default=os.environ["SM_CHANNEL_MYEXAMPLE"])


Have two functions and have to find out parameter A in which functions intersect

Question: I have two functions and want to find out in which points they intersect
$f(x)=-3x^3-3x^2+Ax$
$g(x)=x^3+x^2-6x$
I know that parameter should be A=18, but it was just my guess. What I want to as you for is the process how to find it.
I know that I must start by $f(x)=g(x)$ and then $f(x)-g(x)=0$ and so on, but I am stuck with quadratic equation with parameter.
Will you help me? :) thx a lot
Comment: You "know that parameter should be A=18" in order that **what** be true?
Comment: Why do you think you are stuck? You have a quadratic equation. What is the discriminat equal to?
Comment: I just guessed that A should be 18, but if it was some other number and I wanted to calculate that. Lets say that 18 is result and you must prove it, not guess it.
Answer: y= f(x) and y= g(x) intersect where f(x)= g(x).  Here that is $-3x^3-3x^2+Ax= x^3+x^2-6x$.  The first thing I see is that $x(-3x^2- 3x+ A)= x(x^2+ x- 6)$ so x= 0 is one solution.  If $x\ne 0$ then we can divide both sides by x to get $-3x^2- 3x+ A= x^2+ x- 6$.  We can write that as $4x^2+ 4x- (A+ 6)= 0$.  That is a quadratic equation which has roots $x= \frac{-4\pm \sqrt{16- 4(4)(A+ 6)}}{2(4)}= \frac{-4\pm 4\sqrt{1- A- 6}}{8}$.
Now the question of the number of real roots depends upon the value of $-A- 5$.  If $A= -5$ then $-A- 5= 0$ so the quadratic equation has one real solution and the graphs cross twice.  If $A< -5$ so $-A- 5> 0$ the quadratic equation has two real solutions and the graphs cross three times.  If $A> -5$ so $-A- 5< 0$ so the quadratic equation has no real solutions and the graphs cross only once.


Python default module lookup folder

Question: I have written a number of modules I use in my Python3 programs in Spyder and every time I want to use one of these modules I put them in the same directory as my program. But I want to know if its possible to set up these modules in a single folder so that every time I want to use them in a program I just import them and this becomes a default folder Spyder checks. That way if I want to change any of these modules I don't have to go through everywhere I have copied it and replace it and can just update the module in this one folder.
This seems to me like a basic practice many people would have and I have tried searching for it but maybe I am just using the wrong terms, so if this questions has been asked before I apologize.
Thanks
Answer: This is a general Python question, not specific to Spyder.
Python searches for modules to import in the locations specified by the PYTHONPATH environment variable:

PYTHONPATH
Augment the default search path for module files. The format is the same as the shell's PATH: one or more directory pathnames
  separated by os.pathsep (e.g. colons on Unix or semicolons on
  Windows). Non-existent directories are silently ignored.

Or you can add the module location to sys.path in your script, before you import the module(s), using sys.path.append.
Comment: Thanks Nekomatic I was able to add the path using sys.path.append()

Python default module lookup folder


Django admin - make all fields readonly

Question: I'm trying to make all fields readonly without listing them explicitly.
Something like:
class CustomAdmin(admin.ModelAdmin):
    def get_readonly_fields(self, request, obj=None):
        if request.user.is_superuser:
            return self.readonly_fields

        return self.fields

The problem is CustomAdmin.fields is not set at this point.
Any ideas?
Comment: Hope this one helps http://stackoverflow.com/questions/7920371/whole-model-as-read-only
Comment: Please check out this link http://stackoverflow.com/questions/4343535/django-admin-make-a-field-read-only-when-modifying-obj-but-required-when-adding
Comment: None of the answers there answer my question - "... without listing them explicitly"
Comment: @Prateek Thanks for reminding me to update that answer ;-)
Comment: @DannyW.Adair: Mention not coz I will be using the updated answer very soon. But thanks for the useful post.
Answer: Since django 2.1, you can prevent editing, while allowing viewing, by returning False from the ModelAdmin's has_change_permission method, like this:
class CustomAdmin(admin.ModelAdmin):
    def has_change_permission(self, request, obj=None):
        return False

(This will not work before django 2.1, as it will also deny permission to any user trying only to view.)
Comment: Great answer! For some applications, you might want to add `has_delete_permission` and `has_add_permission` methods too
Comment: Such a beautiful and nice solution. Why not more up-votes?
Comment: @ErikKalkoken: this works [only since version 2.1 of django](https://docs.djangoproject.com/en/2.1/releases/2.1/#model-view-permission) where the [view permission](https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.has_view_permission) was added.  Before then (so up to and including django 2.0), the solution suggested by this answer will make the admin site deny permission to all users trying to view the relevant model in the admin.  Agree that it's the neatest solution for recent django.
Comment: Not that inlines can't be added
Answer: Careful, self.model._meta.fields are not necessarily the same fields that CustomAdmin has!
"All fields of the Admin" would look more like this:
from django.contrib import admin
from django.contrib.admin.utils import flatten_fieldsets

class CustomAdmin(admin.ModelAdmin):
    def get_readonly_fields(self, request, obj=None):
        if request.user.is_superuser:
            return self.readonly_fields

        if self.declared_fieldsets:
            return flatten_fieldsets(self.declared_fieldsets)
        else:
            return list(set(
                [field.name for field in self.opts.local_fields] +
                [field.name for field in self.opts.local_many_to_many]
            ))

Comment: `declared_fieldsets` is deprecated since django 1.7 and will be removed in django 1.9; replacing it with `get_fieldsets(req,obj)` reaches recursion limit. also, `admin.util` is renamed to `admin.utils`
Comment: This worked for me with Django 1.10

`    def get_readonly_fields(self, request, obj=None):
        if request.user.is_superuser:
            return self.readonly_fields

        return list(set(
            [field.name for field in self.opts.local_fields] +
            [field.name for field in self.opts.local_many_to_many]
        ))`
Comment: No worries. Careful if you ever have an m2m that's not an inline. Though it should make itself known :-)
Comment: Thanks this works great. Just had to remove the many_to_many because it makes it look weird (they're registered as inlines anyway and have their own permissions.
This feels much safer then getting `model._meta`.
Comment: Thank you. This is the most reasonable answer I found.
Comment: Note, this won't work with a mix of readonly fields and custom fieldsets.
Comment: What do you mean by custom fieldsets? If you declared fieldsets then all of the fields should be returned as readonly.
Comment: Seeing as `declared_fieldsets` is deprecated and not available anymore in Django 1.7, what's a good approach to it nowadays?
Answer: Ok, now there's this:
class CustomAdmin(admin.ModelAdmin):
    def get_readonly_fields(self, request, obj=None):
        # ...

        return [f.name for f in self.model._meta.fields]

Still looking for a less ugly way.
Comment: True. It's just cleaner. Also, it doesn't do this: `AttributeError: type object 'NoneType' has no attribute '_meta'` when creating objects.
Comment: Actually I found this elsewhere. And after upvoting your answer and adjusting it a bit to the version I used and tested in my code posted my own.
Comment: the if clause doesn't add anything to your question
Comment: This does not include any extra fields (eg: with a custom form).
Answer: You could iterate through the model meta fields:
def get_readonly_fields(self, request, obj=None):
    if obj:
        self.readonly_fields = [field.name for field in obj.__class__._meta.fields]
    return self.readonly_fields

Comment: @hedde you aren't entitled to the answer just because you wrote it first, and just because someone has the same approach doesn't mean they are copying you or deserve a downvote
Comment: When user try to create new object you have exception here: obj.__class__._meta.fields
Comment: Ok, i delete my answer, you really was first :)
Comment: Really appreciated. Nice answer !!
Comment: This does not include any extra fields (eg: with a custom form).
Answer: For Inlines (Tab or Stack)
def get_readonly_fields(self, request, obj=None):
    fields = []
    for field in self.model._meta.get_all_field_names():
        if field != 'id':
            fields.append(field)
    return fields

def has_add_permission(self, request):
    return False

Comment: The `self.model._meta.get_all_field_names()` methodology has been deprecated in Django 1.10+: https://docs.djangoproject.com/en/2.1/ref/models/meta/#migrating-from-the-old-api
Comment: return [field for field in self.model._meta.get_all_field_names() if field != 'id']
### thanks YPREZ
Answer: This worked for me with Django 1.10
def get_readonly_fields(self, request, obj=None):
    if request.user.is_superuser:
        return self.readonly_fields

    return list(set(
        [field.name for field in self.opts.local_fields] +
        [field.name for field in self.opts.local_many_to_many]
    ))

Answer: If someone still lookign for better way, you can use it like this:
@admin.register(ClassName)
class ClassNameAdmin(admin.ModelAdmin):
    readonly_fields = [field.name for field in ClassName._meta.fields]

ClassName is your Model class.
Comment: Thank you for coming back and posting this!
Answer: My requirement was similar . I needed only one field to be shown as read-only . And this worked fine:
class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 1
    fields = ['choice_text', 'votes']
    readonly_fields = ['votes']

class QuestionAdmin(admin.ModelAdmin):
    #fields = ['pub_date', 'question_text']
    fieldsets = [
        (None, {'fields': ['question_text']}),
        ('Date Information', {'fields': ['pub_date']}),
    ]
    search_fields = ['question_text']

    inlines = [ChoiceInline]

Refer: C:\Python27\Lib\site-packages\django\contrib\admin\options.py
Answer: Say you have defined user_mode as;
Admin, Customers and Staff

If you'd like to deny a staff (and of course, customers) the privilege of deleting a customer, product, order etc...
Your code goes;
def get_readonly_fields(self, request: HttpRequest, obj=None):
    if request.user.user_mode != "Admin":
        return self.readonly_fields + ['user_mode']
    return super().get_readonly_fields(request, obj)

where user_mode = a model field holding the type of user.
N.B: my code uses "Pylance" (like typescript in JS)
Answer: With get_fieldsets you get all fields from the form
def get_readonly_fields(self, request, obj=None):
    readonly = []
    for fs in self.get_fieldsets(request, obj):
        if len(fs) > 1:
            readonly += fs[1].get('fields', [])
    return readonly

Comment: calling `get_fieldsets()` inside `get_readonly_fields()` reaches recursion limit :(
Answer: @admin.register(Hero)
class HeroAdmin(admin.ModelAdmin, ExportCsvMixin):
    ...
    readonly_fields = ["father", "mother", "spouse"]

reference :
https://books.agiliq.com/projects/django-admin-cookbook/en/latest/changeview_readonly.html
Comment: Question was to get `all fields readonly without listing them explicitly`. Your answer suggest listing them explicitly.

Django admin - make all fields readonly


Using SharePoint to access and modify data in database

Question: I have a situation where I currently have a huge spreadsheet that is used for tracking 40+ deliverables for projects. The spreadsheet solution is past cumbersome.
I have been thinking about how I can use our SharePoint instance to handle some of these tasks. One option that I have been thinking about was to create a relational database (MSSQL) and then use SharePoint to access and modify the data. I would like to be able to grant users access to specific data elements to allow users to modify the data rather on depending on an administrative resource. This will require some development.
I am relatively new to working with SharePoint so there must be some better ways to implement this functionality rather than the typical list functionality. Right now I am looking for some ideas and this is the best place to find them.
Thank you in advance. Ray
Answer: I am not fond of sharepoint, what I am fond of is developing external applications and framing that application within sharepoint.  That is my recommendations.  Write the application in vb.net / C# as a web application and use the page viewer web part to embed that application into the portal.
This avoids having to understand the sharepoint model, it keeps your concentration on more important things like databases, c# code, object oriented programming, etc.
No offense to the sharepoint developers of course.
Comment: None taken! :) This is how we develop most of our modules which require more .net development. Another advantage is we were able to use experienced .net developers(less SP knowledge) to work with SharePoint and get the job done.
Comment: JonH - not a bad idea at all. I think that I will approach this project using this strategy. Thank you.


SQLITE: Getting difference from two different column values

Question: I have 2 tables naming..InvoiceGarmentService and Payment..
InvoiceGarmentService Table Data
----------------------------------
IGSID     InvoiceID   Price

0           1001      50

1           1001      100

2           1002      500

3           1002      600

------------------------------------
Payment Data
------------------------------------
PaymentID InvoiceID Amount

0          1001      20

1          1002      300

2          1003      900

------------------------------------

I want to get the due amount ie. (Sum of Price From IGS)-(Sum of Amount from Payment)
I have used a query like this
SELECT sum(Price) FROM InvoiceGarmentService - sum(Amount)FROM Payment
WHERE InvoiceGarmentService.InvoiceID='1001'

But I am Unable to find result..saying here is a syntax error but I dn knw about that..
Anyone can help me
Comment: Seeing your query, i would advise you to read the 'sql-basics' first...
Answer: SELECT igs.InvoiceID, (val1 - val2)
  FROM (SELECT InvoiceID, sum(Price) AS val1
          FROM InvoiceGarmentService
         GROUP BY InvoiceID) igs
  JOIN (SELECT InvoiceID, sum(Amount) AS val2
          FROM Payment
         GROUP BY InvoiceID) p
    ON (igs.InvoiceID = p.InvoiceID)
 WHERE igs.InvoiceID = '1001'


Saddle point and stationary point approximation of the Airy equation

Question: Happy New Year to you all.
Let $$\tag 1 J(N)=\int_a^b e^{Nf(x)}dx$$ where $N\in\mathbb R$ and $N>>1$ and $f(x)$ has a global maximum at $x=x_0$ with  Taylor expansion $$f(x) \approx f(x_0)-|f''(x_0)|\frac{(x-x_0)^2}{2}.$$ Then by the saddle point approximation, we get
$$ \tag 2 J(N)\approx \frac{e^{Nf(x_0)}}{\sqrt{N}}\sqrt{\frac{2\pi}{|f''(x_0)|}}\left(1+O\left(\frac{1}{N}\right)\right).$$
Let $$\tag 3  Ai(x)= \int_\gamma \exp{\left(tx-\frac{t^3}{3}\right)}dt$$ where $\gamma$ is a contour in $\mathbb{C}$ chosen such that the integral converges and the integrand vanishes as $t\to\infty$.
First question: For $x>0$, I want to find an approximation to (3). So, by letting $t=u \sqrt{x}$ , I get $$ Ai(x) = \sqrt{x} \int_{\mathbb{R}_+}\exp{\left(\left(u -\frac{u^3}{3}\right)x^{3/2}\right)}$$ Doing so allows me to identify the following:$$ N= x^{3/2}~~~f(u)=u-u^3/3~~~$$ from which I get $$ Ai(x>0) = \sqrt{2\pi}e^{{2/3}z^{3/2}}x^{-1/4}\left(1+O\left(z^{-3/2}\right)\right).$$ However, the solution is given as $$ Ai(x>0) = \sqrt{2\pi}e^{{-2/3}z^{3/2}}x^{-1/4}\left(1+\left(x^{-3/2}\right)\right).$$ Obviously, the my trouble stems from the fact that using  (2), I keep getting 2/3 and not -2/3. I'd be very happy if someone could point me in the right direction.
Second question: For $x<0$, can I get help in using the stationary phase approximation to approximate (2)?
Please, if what I've done above is complete hokum, let me know as well. Thanks.
Comment: I think it should be $N=x^{3/2}$ and in the integral before this formula as well (and $x^{3/2}$ should be part of the exponent, too).
Comment: You found the asymptotic expansion of the Bi-function. The Ai-function is dominated by the saddle point at $u_0=-1$. The Ai-function should be defined such that it vanishes for $x\to \infty $ (I guess there is another typo in the post) which your solution does not do.
Comment: @Fabian: I've fixed the  typo.
Comment: @Fabian: Can you please point out the typo. did I define The Ai-function incorrectly?
Comment: I guess Ai is defined such that it vanishes for $x\to\infty$ (and not fur $t\to\infty$ as you state in your post).
Answer: I) Judging from OP's eq. (2), it seems OP is conflating Laplace's method in real analysis, and the method of steepest descent in complex analysis. The latter has extra complex phase factors, which undoubtedly resolves OP's sign problem.
II) In more detail, the Airy function of first kind is defined as
$$ Ai(z)~:=~\int_{i\mathbb{R}+0^{+}} \! \frac{du}{2\pi i} \exp\left(\frac{u^3}{3}-uz \right)~\stackrel{u=\sqrt{r} t}{=}~\frac{\sqrt{r}}{2\pi i} \int_{i\mathbb{R}+0^{+}} \! dt~\exp\left(r^{\frac{3}{2}} S(t,\theta) \right) , \qquad z~=~re^{i\theta},$$
$$ S(t,\theta)~:=~\frac{t^3}{3}-te^{i\theta}, \qquad S^{\prime}(t,\theta)~:=~t^2-e^{i\theta},\qquad S^{\prime\prime}(t,\theta)~:=~2t. \tag{1}$$
Here $r\gg 1$. There are two critical points:
$$ t_{\sigma} ~=~\sigma e^{\frac{i\theta}{2}}, \qquad S_{\sigma}~=~ - \frac{2\sigma}{3}e^{\frac{3i\theta}{2}} , \qquad S^{\prime\prime}_{\sigma}~=~  2\sigma e^{\frac{i\theta}{2}}, \qquad \sigma ~\in~\{\pm 1\} .\tag{2}$$
The steepest decent contribution from each critical point comes from a Gaussian integral:
$$ I_{\sigma}~=~\frac{\sqrt{r}}{2\pi i}\sqrt{\frac{2\pi}{-r^{\frac{3}{2}} S^{\prime\prime}_{\sigma}} } \exp\left(r^{\frac{3}{2}} S_{\sigma} \right)$$
$$ ~=~\frac{1}{2\sqrt{\pi}i \sqrt[4]{r}}  \exp\left(-\frac{2\sigma}{3}r^{\frac{3}{2}} e^{\frac{3i\theta}{2}} -\frac{i\theta}{4}\right)\left\{\begin{array}{rcl}  \pm i & \text{for}& \sigma~=~+1 \cr\cr 1 & \text{for}& \sigma~=~-1\end{array}  \right\} .\tag{3}$$
Case $z<0 ~\Leftrightarrow ~\theta=\pi$: Critical points: $t_{\sigma}=\sigma i$. The $Ai$-contour along the imaginary axis is reproduced by a combination of both the two steepest decent contours:
$$ Ai(-r)~\sim~\pm I_{+1}-I_{-1}~=~\frac{1}{\sqrt{\pi} \sqrt[4]{r}}\sin\left( \frac{2}{3}r^{\frac{3}{2}}+\frac{\pi}{4}\right)$$
$$~=~\frac{1}{\sqrt{\pi} \sqrt[4]{r}}\cos\left( \frac{2}{3}r^{\frac{3}{2}}-\frac{\pi}{4}\right)\quad \text{for} \quad r\to \infty.  \tag{4}$$
Case $z>0 ~\Leftrightarrow~ \theta=0$: Critical points: $t_{\sigma}=\sigma$. The $Ai$-contour  along the imaginary axis is reproduced by the steepest decent contour corresponding to the critical point $t_{+1}$:
$$ Ai(r)~\sim~\pm I_{+1}~=~\frac{1}{2\sqrt{\pi} \sqrt[4]{r}}\exp\left(- \frac{2}{3}r^{\frac{3}{2}}\right)\quad \text{for} \quad r\to \infty. \tag{5}$$
The $\pm$ in eqs. (3), (4) & (5) are correlated. See also the Wikipedia page for the Stokes phenomenon.


Is rsyslog redundant on when using journald?

Question: I have noticed log messages are duplicated in journald and /var/log/messages on my CentOS 7 system. At first I thought it was the journald option ForwardToSyslog (which defaults to 'yes' in the installed version) which caused this behavior, but setting it to 'no' did not make a difference.
Obviously if I stop the rsyslog service the logging to /var/log/messages (and probably some other logs stop, but what I worry about when I do this if rsyslog is logging things that journald are not.
Is rsyslog only logging whatever it reads from journald or is it logging other things as well?
Extract from /etc/rsyslog.conf:
<code># The imjournal module bellow is now used as a message source instead of imuxsock.
$ModLoad imuxsock # provides support for local system logging (e.g. via logger command)
$ModLoad imjournal # provides access to the systemd journal

...

# Turn off message reception via local log socket;
# local messages are retrieved through imjournal now.
$OmitLocalLogging on
</code>
Answer: From Red hat documentation, using the journal

The Journal is a component of systemd that is responsible for viewing and management of log files. It can be used in parallel, or in place of a traditional syslog daemon, such as rsyslogd.

From Red had documentation, rsyslog journal interaction

By default, rsyslogd uses the imjournal module as a default input mode for journal files.

From Red hat documentation, journal storage

With persistent logging enabled, journal files are stored in /var/log/journal which means they persist after reboot. Journal can then replace rsyslog for some users (but see the chapter introduction).

Based on this I would say that rsyslog is redundant if journald persistent storage is enabled and there are no applications that depend on the specific files and format produced by rsyslog, the content is the same.
Comment: Those links are all dead.
Comment: @stolenmoment Anybody could just edit the post and fix them. Even you.
Comment: I thought half the point of rsyslog was not just ingestion but transformation and output/forwarding of logs to other places. Does journald do that stuff?
Answer: We solved this by not creating /var/log/journal (so that journalctl stuff is ephemeral) and setting up rsyslog to store everything from journald in a new logfile.  We often have to debug our deployments post-mortem, and grepping through logfiles is (for us old-timers) much easier than learning a new obscure command language.

:syslogtag, startswith, "systemd" /var/log/systemd.log

We also learned that the "/etc/rsyslog.d/listen.conf" that systemd installs is an essential part of the glue; one of our components inadvertently wiped out the

$IncludeConfig /etc/rsyslog.d/*.conf

and we got nothing from journald.
Answer: Late response, but for those who prefer classic syslog, journald can be configured in this way:
<code>[Journal]
Storage=none
ForwardToSyslog=yes
</code>
and then configure rsyslog as you like. In this way, you preserve logging for journald-only apps, while have the single logs processing engine - rsyslog.


Add repeating events to all weekday that starts with the current day

Question:
I want my calendar to have the repeating events on weekdays that start on the current day. I already added the events on weekdays but it also adds the events on past dates. events must only be added on current date onwards(weekdays)
<code><script>
    var today = new Date(new Date().getFullYear(),new Date().getMonth() , new Date().getDate());
    var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();

    document.addEventListener('DOMContentLoaded', function() {
        var calendarEl = document.getElementById('calendar');
        var calendar = new FullCalendar.Calendar(calendarEl, {
            plugins: [  'dayGrid', 'rrule','googleCalendar' ],
            header: {
                left: 'title',
                right: 'today prev,next',
        },

      defaultDate: today,
      businessHours: true,
      editable: true,
        events:
        [
            {
            title: 'AM 500 Slots',
            start: today,
            daysOfWeek: [ 1, 2, 3, 4 ,5]
            },

            {
            title: 'PM 500 Slots',
            start: today,
            daysOfWeek: [ 1, 2, 3, 4 ,5]
            }
        ],
    });

    calendar.render();
  });

</script>
</code>
Comment: https://fullcalendar.io/docs/recurring-events, https://fullcalendar.io/docs/rrule-plugin
Answer: I used this link  here  to generate my desired output.


Setting pointer to arbitrary dimension array?

Question: When I want to initiate a multidimensional array, I usually just use pointers. For example, for two dimensions I use:
double **array

and for three I use:
double ***array

However, I'd like to set a multidimensional array based on a command line argument indicating the dimension. Is there are way to set an array of arbitrary size once you have a variable with the number of dimensions you'd like?
Comment: Have you looked into using a third-party library? To me, it sounds like you're looking for a matrix class; [Eigen](http://eigen.tuxfamily.org/index.php?title=Main_Page) is a good option.
Comment: `When I want to initiate a multidimensional array, I usually just use pointers.` <-- That is a sign you are doing something wrong ...
Comment: @MichaelLeVine The most basic method is a vector of vectors.  The rest of your question (dealing with an arbitrary number of dimensions) is a design issue:  array dimensions *mean* something in the context of an application.  An arbitrary number of dimensions indicates you are trying to change the meaning to an *instance* of the application.  It is possible, but very messy, and as a practical application is an indication that you did not properly think about your design.
Comment: You can try use void*
Comment: Unless you specifically need arbitrary row-length-allocation size *within* the matrix, there is absolutely no reason whatsoever to do this in a modern C++ program (and even *that* isn't a valid reason with a decent amount of engineering forethought).
Comment: Also, I would _strenuously_ avoid `void*` in C++.
Comment: I think we're going to need a little more detail on the problem you are trying to solve. I have to say though, both the solutions presented (`void*` and `double **...*`) make me die a little on the inside.
Comment: If it is not jagged, write a multi dimensional array class that stores the data in a single vector. It it is jagged, then vector of vector.
Comment: @anjruu Sorry, I don't want an arbitrary dimension matrix, I want an arbitrary dimension array object. For example, I want array[0][1][2]...[n].
Comment: @LeeNeverGup Are you suggesting to loop and keep pointing void* to another void*?
Comment: Is there a reasonable bound on the number of dimensions? Is this bound greater than, say, five?
Comment: [Three star programmers](http://c2.com/cgi/wiki?ThreeStarProgrammer) are "cool".
Comment: @anjruu Not exactly - it's a combinatorial problem and I'm going to see how far I can reasonably push it.
Comment: @ZacHowland how do you suggest when I need a multidimensional array of arbitrary dimensions? Such as a x b x c ... x z?
Comment: @ZacHowland I don't see why an array of arrays is any better or worse than a vector of vectors.
Comment: @MichaelLeVine First off, we are talking about a *dynamic* array of *dynamic* arrays vs a vector of vectors.  Performance-wise, there is no difference.  The real difference comes in that vector already has memory management well tested ... whereas your dynamic array of dynamic arrays would be untested (and therefore, potentially flawed).  When possible, always prefer code reuse.
Comment: You may be interested in http://stackoverflow.com/questions/20846684/c11-dynamic-multidimensional-array-of-any-type-using-vector-initilizer-list/20848053#20848053
Comment: Questions for you that you should probably clarify in your question description: 1) If your dimensionality is selectable at runtime, how do you even expect to write code like `array[0][1][2]...[n].`? or is that describing CLI syntax you want to expose? 2) Are the bounds on the number of entries in each dimension static or dynamic (ie. known at compile-time? or variable at runtime?)? 3) In what ways can the collection be mutated? Can individual dimensions be resized at runtime? Entry insertion / removal?
Answer: you may be interested in the following code which allow you to use any "dynamic" dimension:
#include <cassert>
#include <cstddef>

#include <vector>

template<typename T>
class MultiArray
{
public:
    explicit MultiArray(const std::vector<size_t>& dimensions) :
        dimensions(dimensions),
        values(computeTotalSize(dimensions))
    {
        assert(!dimensions.empty());
        assert(!values.empty());
    }

    const T& get(const std::vector<size_t>& indexes) const
    {
        return values[computeIndex(indexes)];
    }
    T& get(const std::vector<size_t>& indexes)
    {
        return values[computeIndex(indexes)];
    }

    size_t computeIndex(const std::vector<size_t>& indexes) const
    {
        assert(indexes.size() == dimensions.size());

        size_t index = 0;
        size_t mul = 1;

        for (size_t i = 0; i != dimensions.size(); ++i) {
            assert(indexes[i] < dimensions[i]);
            index += indexes[i] * mul;
            mul *= dimensions[i];
        }
        assert(index < values.size());
        return index;
    }

    std::vector<size_t> computeIndexes(size_t index) const
    {
        assert(index < values.size());

        std::vector<size_t> res(dimensions.size());

        size_t mul = values.size();
        for (size_t i = dimensions.size(); i != 0; --i) {
            mul /= dimensions[i - 1];
            res[i - 1] = index / mul;
            assert(res[i - 1] < dimensions[i - 1]);
            index -= res[i - 1] * mul;
        }
        return res;
    }

private:
    size_t computeTotalSize(const std::vector<size_t>& dimensions) const
    {
        size_t totalSize = 1;

        for (auto i : dimensions) {
            totalSize *= i;
        }
        return totalSize;
    }

private:
    std::vector<size_t> dimensions;
    std::vector<T> values;
};

int main()
{
    MultiArray<int> m({3, 2, 4});

    m.get({0, 0, 3}) = 42;
    m.get({2, 1, 3}) = 42;

    for (size_t i = 0; i != 24; ++i) {
        assert(m.computeIndex(m.computeIndexes(i)) == i);
    }
    return 0;
}

Answer: Even though this whole question is an indication of a design flaw, you can (sort of) accomplish this:
template<typename T>
class MultiArray
{
public:
    MultiArray(std::size_t dimen, std::size_t dimen_size) : _dimensions(dimen)
    {
        _data = new T[dimen * dimen_size];
    }

    // implment copy constructor, copy-assignment operator, destructor, and move constructors as well

    T* operator[](int i)
    {
        assert(0 <= i && i < _dimensions); // bounds check for your dimension
        return &_data[i];
    }
private:
    T* _data;
    std::size_t _dimensions;
};

int main()
{
    MultiArray<int> a(5, 2);
    a[4][1] = 3;
    std::cout << a[4][1] << std::endl;
    return 0;
}

If you want it jagged, you would have to do more math and maintenance regarding the bounds for each "dimension".
The problem you run into has making the dimensions mean something for your application.  Typically, a multi-dimensional array represents something (e.g. a 2D vector can represent Cartesian space, a  3D or 4D vector can be used for manipulating data for 3D graphics).  Beyond the 4th dimension, finding a valid meaning for the array becomes murky and maintaining the logic behind it becomes increasingly complex with each new dimension.
Comment: What would you suggest as a smart way to design a structure to solve this problem:
I have n terms in a function, each with m possible forms. I need to calculate all values for any combination of the n terms with all the possible m forms of the terms.
Comment: @MichaelLeVine What you just described is a 2 dimensional array (one dimension for your forms, the other for the elements on each form).  It is basically a permutations calculation.
Comment: No, but I also need to store the function output of arbitrary combinations of the terms with arbitrary forms of the terms. I'm solving a combinatorial problems that requires a recursive algorithm, so I need to be able to look up previous outputs (because looking them up is several times faster than recalculating).


What does this shorthand mean?

Question: I was reading an article on the Internet and saw this notation:

3*3*3*3* – 4331 – tmp+3 – hp – cel/pno – cds (14/12/10/8/6)

Then, searching on Google, I could see that this is a shorthand for orchestra instrumentation. But even reading this Wikipedia article, I could not understand all the parts of this statement.
What do all of these things mean? Mainly the final parts...
Answer: I would recommend consulting the source where you found this. If it was a publishing company, they may have their own system of shorthand that will clarify this.
Otherwise, this all seems relatively standard:

3*3*3*3* indicates the wind grouping with three performers each: three flutes, three oboes, three clarinets, three bassoons. The asterisks indicate that one of the players is playing another instrument of that family; one flute is also playing piccolo, one bassoon is also playing contrabassoon, etc. Contrast this with 3d, where the third player is doubling on that instrument.
4331 indicates a standard brass grouping of four horns, three trumpets, three trombones, and a tuba.
tmp+3 indicates a timpanist and three other percussionists.
hp indicates harp.
cel/pno indicates a score for celesta/piano.
(14/12/10/8/6) indicates the number of strings: 14 first violins, 12 second violins, 10 violas, 8 celli, and 6 double basses.

My only confusion is with the designation cds before the last entry. My guess is that this indication is in another language—perhaps French?—and this tells us that the following numbers pertain to "strings" (cordes in French).
Comment: I think specifically "cel/pno" means "celesta **or** piano".  It would be a little unusual to have both, though I imagine it's not unheard-of.
Comment: I don't agree about cel/pno.  I think it would normally be celesta **and** piano, but with one player taking both instruments (perfectly feasible if the instruments are never playing together and there is a little time to change seats).

What does this shorthand mean?


trying to update a UILabel on a parent view controller when dismissing the modal view

Question: I am trying to update a UILabel in a parent View after someone makes a change in a modal view.  So, after they click "save" ... the newly entered value would change what text is displayed on the parent view controller.
But, I can't seem to get that UILabel to refresh the newly entered value.
Any ideas on what I can try?  I've tried a few things, but being the view is already loaded, nothing is getting "refreshed".
Thanks!
Comment: I would make a delegation method. When the "Save" button is pressed, the modal is dismissed and the delegation method is called. The parent view has this delegation method implemented and when it is called, the label is refreshed.
Answer: There are many ways to do this. One way is to use NSNotificationCenter to be able to do calls between different classes. So in the parent view you will have a function responsible for the update (lets call it updateLabel) and you will do the following:
- (void) updateLabel
{
    yourLabel.text = @"what you need";
}

- (void)viewDidLoad
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateLabel) name:@"DoUpdateLabel" object:nil];
}

Now in other view simply post a notification in the save button:
[[NSNotificationCenter defaultCenter] postNotificationName:@"DoUpdateLabel" object:nil userInfo:nil];

EDIT:
I have to mention 2 things here:

In this scenario it is always preferable to have Shared Data Modal where you save your data in so you can access this data in any view in your program. In other words it is a good practice to separate the data from classes.
Remember to resomve the NSNotificationCenter that you used in the main view by adding [[NSNotificationCenter defaultCenter] removeObserver:self];
Comment: Worked perfectly and is very straight forward.  Thanks!
Answer: To elaborate on my comment. This is how I would implement a delegation method to update the label.
In the header of the parent view controller:
#import "ModalViewController.h"

@interface ViewController : UIViewController <ModalViewControllerDelegate>

/* This presents the modal view controller */
- (IBAction)buttonModalPressed:(id)sender;

@end

And in the implementation:
/* Modal view controller did save */
- (void)modalViewControllerDidSave:(ModalViewController *)viewController withText:(NSString *)text
{
    NSLog(@"Update label: %@", text);
}

/* Prepare for segue */
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"modalSegue"])
    {
        ModalViewController *mvc = (ModalViewController *) segue.destinationViewController;
        mvc.delegate = self;
    }
}

/* Present modal view */
- (IBAction)buttonModalPressed:(id)sender
{
    [self performSegueWithIdentifier:@"modalSegue" sender:self];
}

Here you see the delegation method in the top.
The header of the modal view controller would contain the delegation protocol like this:
@protocol ModalViewControllerDelegate;

@interface ModalViewController : UIViewController

@property (nonatomic, weak) id <ModalViewControllerDelegate> delegate;

- (IBAction)buttonSavePressed:(id)sender;

@end

@protocol ModalViewControllerDelegate <NSObject>
- (void)modalViewControllerDidSave:(ModalViewController *)viewController withText:(NSString *)text;
@end

The implementation of the modal view controller would contain a method similar to this one:
/* Save button was pressed */
- (IBAction)buttonSavePressed:(id)sender
{
    if ([self.delegate respondsToSelector:@selector(modalViewControllerDidSave:withText:)])
        [self.delegate modalViewControllerDidSave:self withText:@"Some text"];

    [self dismissModalViewControllerAnimated:YES];
}

When the save button is pressed, the delegate is notified and the text in your text view is sent through the delegation method.
Comment: This seems very solid.  Thank you very much.  About to test this out now.
Comment: Thanks. Might want to check out [this answer](http://stackoverflow.com/a/6169104/426839) for a fuller explanation with some strong suggestions such as always making delegate properties weak references.
Comment: True, the delegate should definitely be weak. That was a mistake. I have updated the answer. Thanks.
Answer: in SWIFT:
ParentViewController :
    func updateLabel() {
        yourLabel.text! = "what you need"
    }

override func viewDidLoad() {
        super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.updateLabel), name: "DoUpdateLabel", object: nil)
}

In OtherView:
@IBAction func closePopUp(sender: AnyObject) {

       NSNotificationCenter.defaultCenter().postNotificationName("DoUpdateLabel", object: nil, userInfo: nil)
    }


github push access denied to someone

Question: I'm trying to push several files into my own repository on GitHub but my access was denied. Here's the message:
remote: Permission to lily0225/TravellingSalesmanProblem.git denied to ls3311.

fatal: unable to access
'https://github.com/lily0225/TravellingSalesmanProblem.git/':
The requested URL returned error: 403

ls3311 is a friend whom I worked with on a previous project but we ended up not using GitHub.
I don't understand why my access was denied to her.
Answer:
Github seems only supports ssh way to read&write the repo, although https way also displayed 'Read&Write'.

No: the write aspect is only dependent on your GitHub right: owner of or collaborator on a GitHub project.
And that for https or ssh.
See "Permission levels for a user account repository".
So make sure your own GitHub account has been declared collaborator on your friend's repo.

remote: Permission to lily0225/TravellingSalesmanProblem.git denied to ls3311.

That means you are pushing to your own repo lily0225 with ls3311's credentials.
That happens when a credential helper has cached ls3311's credentials in association with lily0225/TravellingSalesmanProblem.git.
Check for a credential helper on your Git config:
git config -l | grep credential

On Windows, for instance, open your Windows Credential Manager and look for a github.com entry.
Comment: Thanks Vonc. But could you explain a little more why my access is denied to her? I hesitate adding her as a collaborator because she is not a collaborator for the project that I want to push. And what if in the future, I want to push other projects that she is not a collaborator of?
Comment: @lily0225 Sure, I have edited my answer. Are you on Windows? What git version are you using?
Comment: I'm using terminal on a macbook pro
Answer: I also got the same problem and figured out what's cause.
Github seems only supports ssh way to read&write the repo, although https way also displayed 'Read&Write'.
So you need to change your repo config on your PC to ssh way:
edit .git/config file under your repo directory
find url=entry under section [remote "origin"]
change it from url=https://email@example.com/pakistan/lunch_call.git to url=ssh://firstname.lastname@example.com/pakistan/lunch_call.git. that is, change all the texts before @ symbol to ssh://git
Save config file and quit. now you could use git push origin master to sync your repo on GitHub

github push access denied to someone


Minsets of diagonalizable elements in the symmetric space $SL(n,\mathbb{R})/SO(n)$

Question: Let $X = \text{SL}(n,\mathbb{R})/\text{SO}(n)$ be the symmetric space associated to $G = \text{SL}(n,\mathbb{R})$.
Every element $\phi \in \text{SL}(n,\mathbb{R})$ acts as an isometry on $X$ and hence we can consider its displacement function
$$
d_\phi \colon X \to \mathbb{R},
\quad
x \mapsto d(\phi \cdot x,x)
$$
and the possibly empty subspace $\text{Min}(\phi)$ of $X$ where the minimum of $d_\phi$ is attained. This is a symmetric subspaces of $X$ via the inclusion
$$
G(\phi)\Big/\Bigl(G(\phi) \cap \text{SO}(n)\Bigr) \to \text{SL}(n,\mathbb{R})\big/\text{SO}(n),
$$
where $G(\phi) = \{ g \in \text{SL}(n,\mathbb{R}) : g \text{Min}(\phi) = \text{Min}(\phi) \}$.
Question: I'm trying to understand $G(\phi)$ in the case that $\phi$ has $n$ distinct real eigenvalues. It is clear to me that the centralizer $Z(\phi)$ of $\phi$ in $\text{SL}(n,\mathbb{R})$ is contained in $G(\phi)$. I read that
$$
G(\phi) \cong Z(\phi) \rtimes \text{Sym}(n),
$$
where the symmetric group permutes the eigenspaces of $\phi$. However, I do not understand what the isomorphism should be and how an element of $G(\phi)$ is related to (coming from) an element of $Z(\phi)$.
Comment: An element of $Z(\phi)$ is already literally an element of $G(\phi)$. This $G(\phi)$ injects into an isometry group of Euclidean space, with the centralizer acting by translation and the permutation group sitting in an orthogonal subgroup.
Answer: The first thing to prove is that the min-set of such $\phi$ is a maximal flat in $X$. (A proof takes some effort, the key fact is that if a geodesic in $X$ is parallel to a regular geodesic in a maximal flat, then it is contained in this flat.) If you think of $X$ as the space of positive definite matrices with unit determinant and $\phi$ a diagonal matrix, then the minset of $\phi$ is the intersection of $X$ with the set  of diagonal matrices. Can you finish given this information?
I suggest you take a look in Eberlein's book "Manifolds of nonpositive curvature", Chicago University Press, 1996.
Comment: Hi Moishe, thank you for the hint. I now found the statement that in general, if $F$ is a maximal flat in a symmetric space $X$, then the group of isometries of $X$ stabilizing $F$ is $\mathbb{R}^r \rtimes W$, where $W$ is the Weyl group, see [p. 15 here](https://www.mathematik.uni-muenchen.de/~leeb/pub/manicures.pdf). However, I have not yet been able to find  a proof of this statement. In this case $W$ is the symmetric group on $n$ letters.


How to set processing timeouts in apache beam / Dataflow python batch jobs?

Question: I am currently using the stopit library https://github.com/glenfant/stopit to set per element processing timeouts in batch jobs. These jobs work on the direct runner and I am able to timeout functions that take too long.
What is the beam way of setting a per element process timeout for a batch job?
Is there a way I could set a processing timeout with a trigger for a dataflow batch job?
My use case is extracting named entities from a text. The NER process sometimes takes too long if the document being processed is too long.
It would be nice to get rid of this dependency and move to a beam native solution.
Comment: According to the Apache Beam documentation you can use  the *waituntilfinish()* method with [direct runner](https://beam.apache.org/releases/javadoc/2.5.0/org/apache/beam/runners/direct/DirectRunner.DirectPipelineResult.html#waitUntilFinish-org.joda.time.Duration-) or [data flow runner](https://cloud.google.com/dataflow/docs/guides/specifying-exec-params#blocking-execution). Using this method you can define the amount of time that the pipeline will time out. Is that what you are looking for?
Comment: Can you please exemplify what you are doing and why you are setting a time out for each element? So I can understand better and help you.
Comment: I am looking for a per element process timeout not a whole pipeline timeout. I have updated the question as well to clarify this. Thanks for the helpful suggestion though!
Comment: Running an NLP extraction pipeline on each piece of text, the execution time of the code depends on the text. For particular texts the NLP library I am using can run very slowly and I would like to terminate the slow running extractions and reprocess them on a different machine.
Answer: As per my understanding the answer to the question is timely processing which also maintain state.
Lets say you have a function f and get the output for  any batch that will use the function.
So basically we have to mark the batch(update a state) after we receive a batch and we will set timers that will update the output as per the watermark/expiry timing which can be set, if there is any output we will receive it and if we don't any output from the function as per your query, we can surely re-route that batch.
This is not an exact solution, but can be worked out
For better understanding you can read it here:  apache beam documentation
Comment: Interesting, thanks for sharing last time I checked I thought timely processing is only supported for streaming jobs. Looks like it is available for streaming. I will look into it later.