Initial Value, First Order Differential Equation: Weird natural log separation

Question: Solve the initial value first order differential equation problem:
$y' = \displaystyle\frac{y^5}{x(1+y^4)},\ y(1) = 1$
\begin{align}
\frac{1+y^4}{y^5}dy &= \frac 1x dx\\
\left(\frac 1{y^5} + \frac 1y\right)dy &= \frac 1x dx\\
-\frac 1 {4y^4} + \text{ln}|y| &= \text{ln}|x| + C_1
\end{align}
This is where I get stuck. How do I solve for $y$ at this point?
Wolfram Alpha gave has this following step, which I do not understand at all:

I tried the raising everything as exponents of $e$, but that seems to be a dead end:
\begin{align}
-\frac 1 {4y^4} + \text{ln}|y| &= \text{ln}|x| + C_1\\
e^{\left(\text{ln} y - \frac 1 {4y^4}\right)} &= e^{\text{ln} x + C_1}\\
y\cdot e^{\left(- \frac 1 {4y^4}\right)} &= x\cdot C_2,\ \text{where $C_2 = e^{C_1}$}
\end{align}

P.S. Natural logarithms don't seem to be working: \ln |y| produces $\ln |y|$. I used \text{ln}|y| for $\text{ln}|y|$ instead. Is this a bug?
Comment: Basic answer is that you don't solve for $y$. The solution to the DE will have to be left in implicit form. Happens a lot.
Comment: They are making use of the Lambert W function I believe. Just solve for $C_1$ from your general solution. I do not think an elementary solution exists to your ODE.
Comment: @AndréNicolas and Cameron Williams Thank you very much.
Answer: You got nearly the conclusion. Let's elevate to power $-4$ after your equation :
\begin{align}
e^{\ln y - \frac 1 {4y^4}} &= e^{\text{ln} x + C_1}\\
e^{-4\ln y + \frac 1 {y^4}} &= e^{-4\,\text{ln} x - 4\;C_1}\\
\frac 1{y^4}\;e^{\frac 1 {y^4}} &= \frac {C_2}{x^4}\\
\end{align}
So that from the definition of the LambertW function $\displaystyle W(z)\;e^{W(z)}=z\,$ we get for $\,z:=\dfrac {C_2}{x^4}$ :
$$W\left(\dfrac {C_2}{x^4}\right)=\frac 1{y^4}$$
or
$$y^4=\frac 1{W\left(\dfrac {C_2}{x^4}\right)}$$
and the four solutions proposed by Alpha :
\begin{align}
y&=\frac 1{\sqrt[4]{\left(W\left(\dfrac {C_2}{x^4}\right)\right)}}\\
y&=\frac {-1}{\sqrt[4]{\left(W\left(\dfrac {C_2}{x^4}\right)\right)}}\\
y&=\frac i{\sqrt[4]{\left(W\left(\dfrac {C_2}{x^4}\right)\right)}}\\
y&=\frac {-i}{\sqrt[4]{\left(W\left(\dfrac {C_2}{x^4}\right)\right)}}\\
\end{align}
Comment: @JDG: The Lambert $W$ function is one of these special functions that you shouldn't hope to rewrite in another way. Of course you may expand it in series, rewrite it as iterations and get approximations as detailed in Corless & all 's paper ['On the Lambert W Function'](http://www.apmaths.uwo.ca/~djeffrey/Offprints/W-adv-cm.pdf) but technically it is defined as the (multivalued) inverse of the function $\;w\mapsto w\;e^w$ so that when you were able to rewrite an equation as $\;y\;e^y=z$ (with $y$ and $z$ any expression) then 'by definition of the $W$ function' this is equivalent to $z=W(y)$.
Comment: Thank you. I don't understand the Lambert Function. What does the W represent? Is it another constant that I would need to solve for? After reading the Wikipedia entry, I still don't understand how the equations goes from: \begin{align}Y = X e ^ X \; \Longleftrightarrow \; X = W(Y)\end{align}
Comment: Could not edit after five minutes: After rereading the Wikipedia, I understand that the W represents *any* complex number. However, I still do not understand why $Y = X e ^ X \; \Longleftrightarrow \; X = W(Y)$.
Comment: Okay, I see. Thank you!
Comment: Correction : if $\,z\ge -1/e\,$ then $\;y\;e^y=z\,$ becomes $\,y=W(z)$.


In general, do top orchestral musicians play multiple instruments as very young children or do they specialize right away?

Question: In general, is it more common for a top orchestral musicians (say, in the top 500 players in the world for a given instrument) to have played multiple instruments as a very young child (3-6 years old) or is it more common for such players to have specialized right away?
Wayne Gretzky has regularly emphasized the importance of early generalization in sports. However, the accomplished orchestral musicians I know started exclusively playing the instrument they specialize in at very early age.
What do the stats (so to speak) say? Is it more common to see early generalization or specialization?
Comment: This question is highly speculative. Unless someone is aware of an in-depth survey of professional musicians on this subject it cannot be answered accurately,
Comment: Where do you get the "top 500" list and what is it based on? Most money earned, or most favorable reviews, or what? Why should it matter? Is this what music and life are about?
Comment: More loosely, I meant elite players. Those playing in notable orchestras.
Comment: The answer to this seems different the moment you switch the topic to rock or metal musicians. There are several one-man metal bands on YouTube who record their own guitar, bass, and (for some of them) drums.
Comment: Can you name one such elite player as an example of what you mean?
Answer: As a child, you normally begin with just one instrument.
Still, almost any professional classical orchestra musician (and most skilled musicians in general) learned basic elements of another instrument at some point in their career, possibly a few years after beginning to play their instrument - assuming they didn't change their preference.
This is not a rule, though.
String, percussion and wind players probably studied piano for a short period of time (statistically, between 2 and 5 years), because that's the convention for professional music courses in those families. But this normally happens at least 3-4 years after beginning their path as musicians.
The reason behind it is that those instrument families lack some important aspects of music learning: most importantly, better knowledge, understanding and self-awareness about polyphony. Knowing more about these aspects normally improves their capabilities in their own instrument(s).
Piano players sometimes learn to play another instrument, but it's not the norm: it is mostly up to their choice, the suggestions of their teachers, or the possible requirement of their courses.
This is often the case for harp, organ and guitar too.
Be aware, though: learning another instrument is not a guarantee of becoming a better musician. I know some musicians that have studied other instruments, and are no better than other fellow musicians that only studied their own instrument, or just another "extra" one.
I've also met a few that even took degrees for many other instruments, but that clearly didn't make them better in any way.
Learning to play another instrument, especially in young age, is certainly an important added aspect to the knowledge and experience of what could become an highly skilled musician.
But it doesn't automatically make them better musicians, and not even make them in the "top 500" (whatever that may mean).
Comment: One thing is that graduates with music degrees from accredited American universities probably had to take brief surveys of all sections of the orchestra (winds, brass, strings, and percussion) plus basic keyboard and vocal skills classes in order to get their bachelor's degrees.
Comment: @ToddWilcox Yes, that is quite common in most accredited music institutes all over the world - and for good reasons. For example, in italian conservatories (at least, following the "old regulation", before it became compared to university), piano was a course inconsistently mandatory: all strings (except double-bass), sax, singing, percussion and harp (!!!) but, weirdly, not for classical wind instruments (weeds and brass). In state music high schools, a second instrument is obligatory (normally a polyphonic instrument when choosing a main instrument that is monophonic, and vice versa).
Comment: This answer seems to concentrate on much older players - the question is about much younger ones.
Answer: In general very young children start on one instrument only. A child might change instruments after a couple of years when they decide that the new instrument is the one they really want to play. After a couple of years they might add a second instrument (particularly piano if it's not already their first instrument). Playing multiple instruments (i.e. more than two) would be very unusual.
Comment: I support your answer, although I know many who have started rightaway with two instruments, one being an instrument typically seen in orchestras plus the piano.
Comment: @hschmauder There are exceptions of course.
Answer: Not had chance to ask many (any!) of those 500, logic says that a very young child (which is what the question points to) will usually come from a musical family, and will fancy a particular instrument, having seen a parent or sibling playing the same.
Up to puberty, they will most likely stick to that one instrument, until another may appeal as well or instead of. But by then, said child will have become rather good on the original, and that will be the 'chosen' one for performances.
Later, at college/uni, another instrument is expected to be studied - usually a polyphonic one, i.e. piano. For various reasons, harmony and theory being just two.
It's common for players of, say, reed instruments to able to perform well on sax, clarinet and flute, and often brass instruments will be doubled. But not at 3-5 yrs old! So basic guess ('cos that's all it will ever be) is that at a young and tender age, one instrument will be pursued for at least a fair time, long enough for the child to become 'good' enough to consider another. At that point, of course, half of te job has already been achieved - i.e. knowing music; the only thing to do is to familiarise with the new instrument...
Answer: Children, whether destined for musical greatness or not, generally settle pretty quickly on just one instrument, or one plus piano, i think.


I cant extract instagram hashtags of a post with bs4

Question: I wanted to extract hashtags from a specific post(given url) using BeautifoulSoup4. First I fetch the page using requests and I've tried find_all() to get every hashtag but it seems there is a hidden problem.
here is the code:
import requests
from bs4 import BeautifulSoup as bs

URL = 'https://www.instagram.com/p/CBz7-X6AOqK/?utm_source=ig_web_copy_link'

r = requests.get(URL)
soup = bs(r.content,'html.parser')
items = soup.find_all('a',attrs={'class':' xil3i'})

print(items)

the result of this code is just an empty list. Can someone please help me with the problem?
Answer: It looks like the page you are trying to scrape requires javascript. This means that some elements of the webpage are not there when you send a GET requests.
One way you can figure out if the webpage you are scraping requires javascript to populate the info you need is to simply save the html into a file:
URL = 'https://www.instagram.com/p/CBz7-X6AOqK/?utm_source=ig_web_copy_link'

r = requests.get(URL)

with open('dump.html', 'w+') as file:
    file.write(r.text)

and then open that file into a web browser
If the file you open does not have the information you want to scrape then it is likely that it is automatically populated using javascript.
To get around this you can render the javascript using

A web driver (like selenium) that simulates a user going to those pages in a web browser
requests-HTML, which is a slightly new package that allows you to render javascript on a page, and has so many other awesome features that are useful for web scraping

There is a larger group of people who work with selenium which makes debugging easier than with requests-HTML, but if you do not want to learn about a new module like selenium, requests-HTML is very similar to requests and picking it up should not be very difficult


How do I properly render a private file URI with l()?

Question: If given a private file with a uri of private://Screenshot from 2015-12-07 15-52-42_0.png. How might I use l() to properly render the link?

When rendered as follows I see https://server/drupal-private-file-system/Screenshot%20from%202015-12-07%2015-52-42_0.png instead of system/.... in the URL.
Answer: The function file_create_url() is what I was after. I'm able to find what I was after with that.
dpm(file_create_url($file_obj['uri']));


python - Imprimir os elementos da lista que terminam com a letra 'a'

Question:
Considerando a seguinte lista:
lista_nomes =['Manuel', 'Laura', 'Antonio', 'Jasmim', 'Maria', 'Silvia', 'Lu', 'Pancrácio', 'Diogo', 'Ricardo', 'Miguel', 'Andre',]*
O que pretendo é imprimir os elementos da lista que terminam com a letra 'a'.
Bem, para uma lista de inteiros, poderia fazer assim:
>>> L = [1, 1, 2, 3, 5, 8, 13, 21]
>>> L[-1]
21

Sei que poderia fazer assim:
    lista_nomes =['Manuel', 'Laura', 'Antonio', 'Jasmim', 'Maria', 'Silvia', 'Lu', 'Pancrácio', 'Diogo', 'Ricardo', 'Miguel', 'Andre',]

print(lista_nomes[1:2])
print(lista_nomes[5:6])
print(lista_nomes[4:5])

Mas não acho que esteja bem!
Alguma ideia, por favor?!
Obrigado,
Answer: A lógica para 'agarrar' o ultimo elemento de cada nome (ultima letra) é a mesma (nome[-1]). Visto que uma string em muitas linguagens é também um iterável, e python não foge à regra:
Para imprimires todos os nomes cujo ultimo caracter é "a":
lista_nomes = ['Manuel', 'Laura', 'Antonio', 'Jasmim', 'Maria', 'Silvia', 'Lu', 'Pancrácio', 'Diogo', 'Ricardo', 'Miguel', 'Andre',]
for nome in lista_nomes:
  if(nome[-1] == 'a'): # verificar se ultimo caracter e um 'a'
    print(nome)
# Laura, Maria, Silvia

DEMONSTRAÇÃO
Caso queiras uma lista só com os nomes que terminam 'a' (usando compreensão de lista):
lista_nomes = ['Manuel', 'Laura', 'Antonio', 'Jasmim', 'Maria', 'Silvia', 'Lu', 'Pancrácio', 'Diogo', 'Ricardo', 'Miguel', 'Andre']
nomes_a = [nome for nome in lista_nomes if nome[-1] == 'a'] # ['Laura', 'Maria', 'Silvia']

Comment: É isso mesmo que queria!!! Muito obrigado!!! Excelente!
Comment: @JoaoPeixotoFernandes, podes fazer o mesmo do meu ultimo exemplo num `for`: https://repl.it/repls/PrimeMilkyBot
Comment: Sim, eu sei. Era mesmo isso!! :)
Comment: Como disseste "O que pretendo é imprimir...", daí ter feito o primeiro exemplo com `print`. Para a próxima diz que pretendes uma lista (;
Comment: o que pretendia era mesmo com o for ! Obrigado.

python - Imprimir os elementos da lista que terminam com a letra ‘a’


Why do I need a specific port 80 rule inspite of having :INPUT ACCEPT [0:0] in /etc/sysconfig/iptables?

Question: On my RHEL 6.2 server, in my /etc/sysconfig/iptables, I have :INPUT ACCEPT [0:0] but I cannot access files through web server on port 80 unless I add a rule like this:
-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT

Please clarify why. Thanks. According to this post, I shouldn't need that additional entry.
Comment: What rules are defined in the output table?
Answer: We can only guess as you don't show us the rest of your INPUT rules. My guess is that you have a line like this
-A INPUT -j REJECT --reject-with icmp-host-prohibited

at the end of your input rules. This will reject any packet that arrives there and so your policy (:INPUT ACCEPT)isn't consulted.
Comment: Yup! That's exactly what it is. I didn't know what that line meant. Here's the full content of iptables file.
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
Comment: Sorry, I don't know how to paste the iptables content so that it shows on different lines.


How does a Webform able to differentiate among radio buttons, check boxes and Lists

Question: I am using webform module to build forms. Initially i created a simple form with few components like text-field, text-area, radios, check boxes , Drop down list and submitted it.
When i checked the database,  I found that the module is storing type "select" for the components radio, check boxes and lists in table name "webform_component". I want to know how can we differentiate them.
Please check the screenshot,

While creating the form i choose the following parameters
Gender ----> Radio
Range  ----> List
Hobbies----> Checkbox
But in the table it was shown as "select" for all the fields
Can anyone suggest the way to find out ?
Answer: the webform_component table also has an extra column you've cropped out.
It's SQL column help description is:

Additional information unique to the display or processing of this
  component.

A select can simply be rendered many ways -- I believe the display settings for the "selectable options" used in rendering a radio, list or checkbox are in that column.
Comment: Sorry i dint mentioned in my post, I have examined extras column, the only differentiation i observed is for a      radio it stores b:0 and b:o                                 for checkbox b:1 and b:0                                                   for list b:0 and b:1, But  i am expecting something which is easier to be differed. Hope you understand my point Thanks for your valuable reply
Comment: hehe ... why would you "expect" something easy !? a Webform is not a core drupal form built with the core  FAPI. The webform maintainers long ago built their own form storage, and description "api". This is the result of that. Please read http://drupal.org/node/325766 and you will see that radio,list and checkbox in webform components all come from `select` in their API. It does look like that DB column and data derives how it is shown. You may have a better time differenietating them in a hook_form_alter after webform has done some initial processing to load them up ...


Using an Interface for Collection<> generic type

Question: I have these types in c#
public class A : IA
{

}

public interface IA
{

}

public class B
{
    public B()
    {
        A = new List(); //Where I have problem
    }

    public ICollection<IA> A { get; set; }
}

I've got this cast error:

Cannot implicitly convert type 'System.Collections.Generic.List' to
  'System.Collections.Generic.ICollection'. An explicit conversion
  exists (are you missing a cast?)

How can I do such things!
Comment: Look at @Daniel answer to [this](http://stackoverflow.com/questions/2640738/c-sharp-cannot-implicitly-convert-type-listproduct-to-listiproduct) question.
Comment: [C# variance problem: Assigning List as List](http://stackoverflow.com/q/2033912/284240)
Comment: And also here is a suggested workaround: http://stackoverflow.com/questions/5832094/covariance-and-ilist/5832173#5832173
Answer: You can't implicitly convert a List to List. If you want to do that, you need to decide whether the collection should contains A or IA.
Here is a fix:
public class B
{
    public B()
    {
        A = new List<IA>();
    }

    public ICollection<IA> A { get; set; }
}


Organizar labels verticalmente

Question: Eu queria colocar painéis em posições especificas, então tentei combinar alguns gerenciadores de layout, mas ainda não consegui o resultado que eu preciso.
Eu tentei usar o gridLayout, para que os componentes não fossem esticados, mas não tenho certeza se estou fazendo um mal uso dele.
eu tentei fazer isso:

onde os quadros pretos são componentes, nesse caso labels.
E o resultado que eu obtive foi:

Alguém consegue me demostrar ou indicar um forma de fazer isso?
Segue um exemplo do codigo:
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE;

public class PainelPosicao {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new PainelPosicao());
    }

    public PainelPosicao() {
        JFrame jFrame = new JFrame();
        jFrame.setUndecorated(true);
        jFrame.setContentPane(new Pane());
        jFrame.setSize(500, 300);
        jFrame.setVisible(true);
        jFrame.setLocationRelativeTo(null);
        jFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    class Pane extends JPanel {

        public Pane() {
            setLayout(new GridLayout(2, 1));
            JPanel gridPainel = new JPanel();
            gridPainel.setLayout(new GridLayout(2, 1));
            gridPainel.setBackground(Color.GREEN);

            JPanel painel = new JPanel();
            painel.add(new JLabel("Label 01"));

            JPanel painelProgress = new JPanel();
            painelProgress.setLayout(new GridLayout(2, 1));
            painelProgress.add(new JLabel("Label 01"));
            painelProgress.add(new JLabel(".......Label 02 ......"));

            gridPainel.add(painel);
            gridPainel.add(painelProgress);
            add(gridPainel);
            setBackground(Color.BLACK);
        }
    }
}

Comment: @Articuno As duas ficaram excelentes, era exatamente o que eu precisava ! Obrigado
Comment: Nao entendi o que quer fazer. Quer botar os dois labels de baixo no quadro preto?
Comment: Na verdade, era pro quandro cinza estar dentro do quadro petro, não sei por que ele não ficou. Os labels eu queria centralizar em baixo do quandro cinza
Comment: Precisa dessa classe de painel ai? Eu consigo fazer sem ela, ela ta bastante inutil no codigo
Comment: Da pra fazer isso tudo ai com apenas um painel. Usando GridBagLayout.
Comment: Pode sim, eu vou combinar com a outra pergunta que fiz, ai so fazer o que vc me explicou la
Comment: fiz uma abordagem mais simplista usando apenas um jpanel, conforme havia comentado. Veja na resposta, fica como alternativa.
Answer: Se o objetivo é alinhar no centro e na posição inferior os dois labels de baixo, consegui fazer assim:
import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class PainelPosicao {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new PainelPosicao());
    }

    public PainelPosicao() {
        JFrame jFrame = new JFrame();
        jFrame.setUndecorated(true);
        jFrame.setContentPane(new Pane());
        jFrame.setPreferredSize(new Dimension(500, 300));
        jFrame.pack();
        jFrame.setVisible(true);
        jFrame.setLocationRelativeTo(null);
        jFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    class Pane extends JPanel {

        public Pane() {

            setLayout(new BorderLayout());

            JPanel painel = new JPanel();
            painel.add(new JLabel("Label 01"));

            JPanel painelProgress = new JPanel();
            painelProgress.setLayout(new BoxLayout(painelProgress, BoxLayout.PAGE_AXIS));

            JLabel label1 = new JLabel("Label 01");
            label1.setAlignmentX(Component.CENTER_ALIGNMENT);
            painelProgress.add(label1);

            JLabel label2 = new JLabel(".......Label 02 ......");
            label2.setAlignmentX(Component.CENTER_ALIGNMENT);
            painelProgress.add(label2);

            add(painel, BorderLayout.NORTH);
            add(painelProgress, BorderLayout.SOUTH);
        }
    }
}

Resultado:

Para organizar o painel onde você adiciona os dois labels, eu utilizei o gerenciador de layout BoxLayout, que me permite adicionar componentes na orientação vertical. Depois, utilizei o método setAlignmentX() pra orientar o BoxLayout a alinhar o componente horizontalmente no centro.

Tem essa outra abordagem mais simplista, sem utilizar esse tanto de paineis:
class Pane2 extends JPanel {

    public Pane2() {

        setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));

        JLabel label1 = new JLabel("Label 01");
        label1.setAlignmentX(Component.CENTER_ALIGNMENT);
        add(label1);

        add(Box.createVerticalGlue());

        JLabel label2 = new JLabel("Label 02");
        label2.setAlignmentX(Component.CENTER_ALIGNMENT);
        add(label2);

        JLabel label3 = new JLabel(".......Label 03 ......");
        label3.setAlignmentX(Component.CENTER_ALIGNMENT);
        add(label3);

    }
}

Ainda se utilizando da flexibilidade de uso do BoxLayout, nessa abordagem eu organizo os 3 labels no mesmo JPanel, e utilizo um recurso de preenchimento, através do método createVerticalGlue(), que preenche o espaço a partir do label do topo, empurrando os dois labels de baixo até o limite inferior da tela.

Organizar labels verticalmente


How to display a GIF in a Service?

Question: I'm building an app similar to Facebook Messenger on Android and I would like to display a GIF as the chat head/bubble. I know the chat head operates as a service and found a way to display GIFs on activities (http://android-er.blogspot.ca/2014/03/play-animated-gif-with.html), but can't get it to work for a service.
Separate, but likely related issue: I'd also like to display GIFs in the popup window (after the chat head is opened).
Answer: Android actually can decode and display animated GIFs, using android.graphics.Movie class.
This is not too much documented, but is in SDK Reference. Moreover, it is used in Samples in ApiDemos in BitmapDecode example with some animated flag.
Find here:
https://stackoverflow.com/a/7772170/3626214
Comment: but with this solution you have to turn of hardware acceleration which makes the app laggy when using something like view pager.

How to display a GIF in a Service?


Django test runner failing with "relation does not exist" error

Question: I'm seeing an error when running my tests, i.e. $ ./manage.py test --settings=my.test.settings
django.db.utils.ProgrammingError: relation "<relation name>" does not exist
This is after running ./manage.py makemigrations && migrate.
Answer: This error turns out (usually) to be caused, ultimately, by failing to create the initial migration for a new app. the error was resolved by running $ ./manage.py makemigrations <my new app module name> && migrate
NOTE: makemigrations DOES NOT AUTOMATICALLY CREATE THE INITIAL MIGRATION FOR NEW APPS
Comment: `makemigrations` should create the initial migration for new apps, especifically if the new app is listed in `INSTALLED_APPS`
Answer: This error happened to me because I was trying to run a piece of code that accessed the database when Django starts.
# file name: blog/apps.py

from django.apps import AppConfig

class BlogConfig(AppConfig):
    name = 'blog'

    def ready(self):
        from .business import markdown_to_html
        markdown_to_html.refresh_posts() # This method access the database.

Then, when I executed the tests: python manage.py test, this code fragment was executed and I got the error you mentioned.
Why? It is explained here: https://docs.djangoproject.com/en/3.0/ref/applications/#django.apps.AppConfig.ready
As I needed to execute this method only once, I decided to create a management command.
Here is the code:
# file name: md_to_html.py

from django.core.management.base import BaseCommand
from blog.business import markdown_to_html

class Command(BaseCommand):
    help = 'Convert posts written in markdown to html'

    def handle(self, *args, **options):
        markdown_to_html.refresh_posts()
        self.stdout.write(self.style.SUCCESS('HTML files created'))

Before starting the Django project, I executed the command using the following line: python manage.py md_to_html. In this way I ensured this code is executed only once in a safely.
Now when I run the tests I don't get the error anymore.
Here you can find more information about how to create a custom management command in Django: https://docs.djangoproject.com/en/3.0/howto/custom-management-commands/
This link describes how to test a custom management command: https://docs.djangoproject.com/en/3.0/topics/testing/tools/#topics-testing-management-commands
Answer: In case you faced this issue while using pytest-django package, check that your haven't created new migrations with --reuse-db option in your pytest.ini
Answer: I had a similar case, table wasn't created just for one model and i figured out that the model is placed in models directory and is not added to models/__init__.py. Just added it to __init__.py and magic happened.
models tree looks like:
models/
    __init__.py
    model.py

model.py
class ModelName(models.Model):
    pass

__init__.py
from .model import ModelName

__all__ = [
    'ModelName',
]


Meaning of "closed under composition"

Question: I have been reading this paper and it is mentioned there that the Applicative class is closed under composition.
What does that actually mean ?
Answer: In general, "X is closed under Y" means that if you take some Xs and Y them, the result is an X. For example, "the set of integers is closed under addition" means that if you take two integers and add them, the result is an integer.
Therefore, saying that the class Applicative is closed under composition means that if you take two applicative functors and compose them, the result is also an applicative functor.
Answer: The composition of Applicatives f and g is
newtype Compose f g a = Compose { getCompose :: f (g a) }

and "Applicative is closed under composition" means that this newtype itself has an Applicative instance.
http://hackage.haskell.org/package/transformers-0.3.0.0/docs/Data-Functor-Compose.html

Meaning of "closed under composition"


Como fazer números aleatorios

Question: Olá alguém saberia me dizer qual o nome desse efeito que tem nesse site :
http://www.popupdesign.com.br/
assim que rolar a pagina acima do fale conosco existe 4 imagem e embaixo dela gera um numero gostaria de saber qual o nome deste efeito e onde posso encontra-lo.
Comment: O número não é gerado aleatoriamente, ele foi colocado lá. O nome do efeito é `FLIP` http://tableless.com.br/introducao-ao-css-3d-flip-card/.
Comment: sim amigo mais vc percebeu como ele faz eleconta alguens números antes de inserir eles eu vi ele no jquery plugin porém não achei que um dia fosse precisar e assim não me lembro qual o nome disso porem sei que tem no site da jquery plugin
Comment: isso lhe ajuda? http://rendro.github.io/easy-pie-chart/ Repare que a contagem começa do 0 e vai até o número pretendido.
Comment: Também tem esse plugin: http://www.jqueryscript.net/animation/Animating-Numbers-Counting-Up-with-jQuery-Counter-Up-Plugin.html
Comment: opa era isso mesmo amigo "vlw" porem o link com resposta para eu aceitar se quiser
Comment: Uma dica, sempre que responder a um comentário de alguém na sua pergunta, pressione o "@" (arroba) que irá aparecer o nome do utilizador e selecione, assim ele irá receber uma notificação e saberá que você respondeu ao comentário. Por exemplo, o @natan agora irá receber uma notificação porque o mencionei no meu comentário. Fica a dica!
Comment: Opa obrigado @FilipeMoraes
Answer: Veja esse plugin: http://www.jqueryscript.net/animation/Animating-Numbers-Counting-Up-with-jQuery-Counter-Up-Plugin.html
Implementação:
Inserir as bibliotecas abaixo no seu código. Fazer o donwload dos arquivos no site acima. Não esquecer de incluir o Jquery também:

Definir o tipo de conteúdo dentro da tag span:
12345
123.45
12,345.00

Executar o plugin, no exemplo abaixo foi aplicado diretamente a qualquer tag "span":

Comment: @Kirito conheço esse plugin: http://bxslider.com/ o exemplo que aparece na página principal pode ser editado para ter o mesmo efeito que você pretende.
Comment: cara uma outra duvida mais acho que terei que abrir outro tópico mais se "vc" entrar novamente no site acima do efeito que falei existe um texto em rosa que fica passando se sabe "tbm" se tem um puglin para isso

Como fazer números aleatorios


% Change for value that didn't exist before

Question: I want to record the percentage change of a value from one week to another.
For example: I deal with a client who brings in 10€ is week 1. In week 2, he brings in 30€. The percentage change is a 300% increase.
Say there's another client I hadn't yet dealt with in week 1, but am now working with him in week 2 and he brings 1000€.
What would be the best way to represent this new client's change coming in? I could say it is 100%, but that somehow does not seem reflective of the true value of this client. Indeed, had he brought in 10€ in week 1, like client 1, the % increase would have been 10,000%, and thus should be much more valuable than client 1.
Can I simply replace the 0 in week 1 with a 1? Or should I do the actual amount as the percentage increase or 100 times the new amount (1000, or 10,000). What is the best course of action?
Thanks
Answer: Whatever value you choose, it would be equally arbitrary. If you don't know the previous value, you cannot say anything about the change.
Answer: Best course of action for what purpose? Purely mathematically, the client brought in either 0 (and 0 to 1000 is not a 100% increase but rather an infinite increase) or the income was missing (was perhaps not even a client).
If you are interested in predicting future income, then perhaps trying different approaches (e.g. also average income from other - in some sense similar - clients could be something to try) and seeing the prediction performance in cross-validation could be an approach.
Answer:
[...] that somehow does not seem reflective of the true value of this client.

... because percentages are to reflect changes or relative values and not absolute values.
If you want to highlight that this client has a higher absolute value than the one bringing in 10 or 30 € you can:

use the absolute values
use other indicators better suited for this purpose (eg. percentage of the total money brought in)

If you want to stick with percentages you won't have information regarding the relative worth of the clients between each other. Nevertheless, I would then recommend having no value in the first week and the relative value (as for other clients) in the following ones.


Attenuation - Formulating and solving an integral

Question: Suppose I have a sphere with radius $R$, and a point $A$ outside it.
For an arbitrary point in the sphere, denote $B$ the line connecting said point and $A$.
I wish to calculate the following integral: $\int dV e^{-\mu d}$, where the integral is done over the sphere, and $d$ is the length of $B$ that's contained inside the sphere.
I have been able to write this down and solve it for a point that's on the sphere itself, but I have been unable to do so for a general point.
On the sphere, I've written: (Assuming WLOG the point is $(0,0,R)$)
$\int dV e^{-\mu (x^2+y^2+(z-R)^2)^{\frac{1}{2}}}$
How would this look for a general point, and how can it be solved? (This particular case I believe I've solved with differentiation under the integral after moving to cylindrical coordinates)
(The physics behind this question concerns calculating attenuation of an isotropically radiating sphere, but since this is essentially a math question, I'll leave that as a note)
Answer: We establish a coordinate system so that the point $A$ is on the $z$ axis.  The spherical symmetry allows us to do this without loss of generality.
Let the point $A$ be denoted $\vec r_0=\hat zz_0$ and a point on the sphere denoted by $\vec r=r\hat r$.  Then,
$$d=|\vec r-\vec r_0|=\sqrt{r^2+z_0^2-2rz_0\cos(\theta)}\tag 1$$
Using $(1)$, we can write
$$\begin{align}
\int_V e^{-\mu d}\,dV&=-\frac{d}{d\mu}\int_V \frac{e^{-\mu d}}{d}\,dV\\\\
&=-2\pi \frac{d}{d\mu}\int_0^\pi\int_0^R \frac{e^{-\mu \sqrt{r^2+z_0^2-2rz_0\cos(\theta)}}}{\sqrt{r^2+z_0^2-2rz_0\cos(\theta)}}\,r^2\,\sin(\theta)\,dr\,d\theta\\\\
&=-2\pi \frac{d}{d\mu}\int_0^R r\left.\left(\frac{e^{-\mu\sqrt{r^2+z_0^2-2rz_0\cos(\theta)}}}{-\mu z_0}\right)\right|_0^\pi\,dr\\\\
&=\frac{2\pi}{z_0} \frac{d}{d\mu}\left(\frac1\mu \int_0^R r \left(e^{-\mu (r+z_0)}-e^{-\mu(z_0-r)}\right)\,dr\right)
\end{align}$$
Can you finish now?
Comment: Most certainly can, thanks. (Can't believe it was this easy, especially since I've seen (And used) similar tricks used before...)
Comment: @Omry Pleased to hear and you're welcome!  My pleasure.  -Mark
Answer: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

With $\ds{\mu > 0}$ and $\ds{a > R > 0,\quad}$ lets
  $\ds{\quad\vec{\alpha} \equiv \mu\vec{a}\qquad}$ and
  $\ds{\quad\tilde{R} \equiv \mu R}$.

$$
\mbox{Note that}\
\iiint_{\large\mathbb{R}^{3}}\expo{-\mu\verts{\vec{r} - \vec{a}}}\bracks{r < R}
\,\dd^{3}\vec{r} =
{1 \over \mu^{3}}\iiint_{\large\mathbb{R}^{3}}\expo{-\verts{\vec{r} - \vec{\alpha}}}\bracks{r < \tilde{R}}
\,\dd^{3}\vec{r}
$$

\begin{align}
&\iiint_{\large\mathbb{R}^{3}}\expo{-\verts{\vec{r} - \vec{\alpha}}}
\bracks{r < \tilde{R}}\,\dd^{3}\vec{r} =
\int_{0}^{\tilde{R}}
\pars{\int_{\large\Omega_{\vec{r}}}\expo{-\verts{\vec{r} - \vec{\alpha}}}\,{\dd\Omega_{\vec{r}} \over 4\pi}}4\pi r^{2}\,\dd r
\\[5mm] = &\
4\pi\int_{0}^{\tilde{R}}
\bracks{{1 \over 2}\int_{0}^{\pi}
\exp\pars{-\root{r^{2} -2r\alpha\cos\pars{\theta} + \alpha^{2}}}
\sin\pars{\theta}\,\dd\theta}r^{2}\,\dd r
\\[5mm] = &\
2\pi\int_{0}^{\tilde{R}}
\bracks{{1 \over 2r\alpha}\int_{\pars{\alpha - r}^{2}}^{\pars{r + \alpha}^{2}}\exp\pars{-\root{\xi}}\,\dd\xi}r^{2}\,\dd r =
{\pi \over \alpha}\int_{0}^{\tilde{R}}
\bracks{2\int_{\alpha - r}^{\alpha + r}\exp\pars{-\xi}\xi\,\dd\xi}r\,\dd r
\\[5mm] = &\
{2\pi \over \alpha}\int_{0}^{\tilde{R}}
\braces{2\expo{-\alpha}\bracks{-r\cosh\pars{r} + \pars{1 + \alpha}\sinh\pars{r}}}r\,\dd r
\\[5mm] = &\
-4\pi\,{\expo{-\alpha} \over \alpha}\int_{0}^{\tilde{R}}\cosh\pars{r}r^{2}
\,\dd r +
4\pi\,{\pars{1 + \alpha}\expo{-\alpha} \over \alpha}
\int_{0}^{\tilde{R}}\sinh\pars{r}r\,\dd r
\end{align}

The remaining integrals can be straightforward evaluated.


Existance of a measure on $\mathcal{B}_{\mathbb{Q}}$

Question: The full question I have is the following: Does there exists a measure $\mu$ on $\mathcal{B}_{\mathbb{Q}}$ (Borel $\sigma$-algebra on $\mathbb{Q}$) that satisfies the following:
$$
\mu((a, b]\cap\mathbb{Q}) = b-a
$$
for all $a\leq b \in \mathbb{R}$. And if it exists, is it unique?
Comment: $\Bbb{Q}$ is countable, so any $\sigma$-additive measure on it is a sum of point masses.
Answer: The Borel σ-Algebra on $\mathbb{Q}$ is generated by open sets in $\mathbb{Q}$, which have the form $(a;b)\cap\mathbb{Q}$ for $a,b\in\mathbb{R}$. Equivalently, it is generated by its closed sets, which are of the form $(a;b)^c\cap\mathbb{Q}$. In particular, singletons; for $x\in\mathbb{Q}$, we have
$$\{x\} = \{x\}\cap\mathbb{Q} = \left[(-\infty;x)\cup(x;+\infty)\right]^c\cap\mathbb{Q}$$
hence $\{x\}\in\mathcal{B}_\mathbb{Q}$.
Now suppose you wanted a measure $μ$ on $\mathcal{B}_\mathbb{Q}$ such that $μ((a;b]\cap\mathbb{Q}) = b-a$.
Taking $b=x\in\mathbb{Q}$ and $a = x-1/n$, we have $μ((x-1/n;x]) = 1/n$. The sets $(x-1/n;x]$ decrease to $\{x\}$, while the RHS $1/n\to 0$. Thus $μ(\{x\}) = 0$, for any $x\in\mathbb{Q}$.
But since a measure is countably additive and $\mathbb{Q}$ is countable, we have
$$μ(\mathbb{Q}) = μ\left(\bigcup_{x\in\mathbb{Q}} \{x\}\right) = \sum_{x\in\mathbb{Q}} μ(\{x\}) = 0$$
so your measure $μ\equiv 0$, which is a contradiction.
Comment: I edited the post, sorry for this, but I think your argument still holds.
Comment: Yep it holds, you assumed correctly that the set $(a, b]$ is obviously not in $\mathcal{B}_{\mathbb{Q}}$.


$\lim_{{n \to \infty}} \sum_{{k=1}}^{n} \arctan\left(\frac{1}{k}\right) - \ln n$

Question: $\arctan(x) = \sum_{m=0}^{\infty} \frac{(-1)^m}{2m+1}x^{2m+1}$
\begin{align*}
\arctan\left(\frac{1}{k}\right) &= \sum_{m=0}^{\infty} \frac{(-1)^m}{2m+1}\left(\frac{1}{k^{2m+1}}\right)
&= \frac{1}{k} + \sum_{m=1}^{\infty} \frac{(-1)^m}{2m+1}\left(\frac{1}{k^{2m+1}}\right)
\end{align*}
We have that
\begin{align*}
\sum_{k=1}^{\infty} \frac{1}{k^{2m+1}} &= \zeta(2m+1)\\
\end{align*}
converges, provided that  $m>0$ and
$\lim_{{n \to \infty}} \left( \sum_{{k=1}}^{n}  \frac{1}{k} - \ln(n)  \right) = \gamma$
where  $\gamma$ is the Euler-Mascheroni constant.
Need help in further
Comment: Your sum clearly diverges, you should get rid of parenthesis. Also try using the Harmonic sequence?
Comment: Note that the alternating series at the right does converge, since its terms tend to  0 , so the swap of the limit and the series (and the swap of the sums) is allowed. Whether this can be rewritten in closed form, that I don't know, you might want to search for zeta values at the odd positive integers, but I don't think alternative expressions allow for an easier attack.
Comment: @Martin As it stands, your logarithm term is inside the summand. So then the summands should tend to $0-\infty$. I think you may need to edit your parentheses :)
Comment: If you read my answer please delete it from your mind, I was not really awake
Answer: have
$\arctan(x)=\sum_{m=0}^{\infty} \dfrac{(-1)^m}{2m+1} x^{2m+1}$
And as such we find
$\arctan\left(\frac{1}{k}\right)=\sum_{m=0}^{\infty} \frac{(-1)^m}{2m+1} \frac{1}{k^{2m+1}}=\frac{1}{k} + \sum_{m=1}^{\infty} \frac{(-1)^m}{2m+1} \frac{1}{k^{2m+1}}$
We have that
$\displaystyle \sum_{k=1}^{\infty} \dfrac{1}{k^{2m+1}}=\zeta(2m+1)$
converges, provided that $m>0$, and
$\lim_{n \to \infty} \sum_{k=1}^n \dfrac{1}{k}-\ln(n)=\gamma$
where $\gamma$ is the Euler-Mascheroni constant.
We find
$\lim_{n\to \infty} \left(\sum_{k=1}^n \arctan\left(\frac{1}{k}\right)-\ln(n)\right)=\gamma+\sum_{m=1}^{\infty} \dfrac{(-1)^m}{2m+1}\zeta(2m+1)$
Note that the alternating series at the right does converge, since its terms tend to $0$, so the swap of the limit and the series (and the swap of the sums) is allowed. Whether this can be rewritten in closed form, that I don't know, you might want to search for zeta values at the odd positive integers, but I don't think alternative expressions allow for an easier attack.
Addendum
A more concise answer can be obtained by taking a detour to the complex numbers. Lets rewrite the arctangent to its complex form, by using the following sketch
If we associate the point $(k,1)$ with the complex number $k+i$and the point $(k,-1)$ with the complex number $k-i$ we obtain
$\ln(k+i)=a+i \text{Arg}(k+i)=a+i \arctan(1/k)\tag*{}$
[math]\ln(k-i)=a-i\text{Arg}(k-i)=a- i \arctan(1/k)\tag*{}$
where the real part of both expressions $a$ is equal to the logarithm of the distance of these points to the origin. Subtract both equations and the real parts drop out
$2i \arctan(1/k)=\ln(k+i)-\ln(k-i)\tag*{}$
or
$\arctan(1/k)=\dfrac{1}{2i} (\ln(k+i)-\ln(k-i))\tag*{}$
We may thus replace the given sum as follows
$\dfrac{1}{2i} \sum_{k=1}^n \ln(k+i)-\ln(k-i)\tag*{}$
which can be rewritten to
$\dfrac{1}{2i} \ln\left(\dfrac{\prod_{k=1}^n k+i}{\prod_{k=1}^n k-i}\right)=\dfrac{1}{2i}$ $\ln\left(\dfrac{(1+i)^{\underline{n}}}{(1-i)^{\underline{n}}}\right)\tag*{}$
where the last notation indicates the rising factorial (defined through the correspondig terms at the left).
We still have to incorporate the term $-\ln(n)$, which we may achieve by including
$-\dfrac{1}{2i}\ln(n)=-\dfrac{1}{2i} (2i \ln(n))=\dfrac{1}{2i} \ln\left(n^{-2i}\right)\tag*{}$
A slight warning is in order here. The logarithm is to measure the angle of $n^{2i}$ with respect to the real axis, including all extra rotations! For instance if you ask Wolfram Alpha to compute $\ln(1000^{-2i})$ it will respond with the principal branch of the logarithm and reduce the argument modulo $2\pi$. That's not what is written above!
All in all we find that the expression reduces to
$\dfrac{1}{2i} \ln\left(n^{-2i}\dfrac{\prod_{k=1}^n k+i}{\prod_{k=1}^n k-i}\right)\tag*{}$
and we are to compute
$\lim_{n \to \infty} \dfrac{1}{2i} \ln\left(n^{-2i}\dfrac{(1+i)^{\underline{n}}}{(1-i)^{\underline{n}}}\right)\tag{1}$
Time to let Gauss enter the stage, who started his investigation of $\Gamma(z)$ by defining
$\Gamma(z)$=$\lim_{n\to \infty} \dfrac{n^z n!}{(z)^{\underline{n+1}}}\tag*{}$
From which we obtain
$\dfrac{\Gamma(z_1)}{\Gamma(z_2)}=\lim_{n \to \infty} \dfrac{n^{z_1}}{n^{z_2}} \dfrac{(z_2)^{\underline{n+1}}}{(z_1)^{\underline{n+1}}}=\lim_{n \to \infty} \dfrac{(n-1)^{z_1}}{(n-1)^{z_2}} \dfrac{(z_2)^{\underline{n}}}{(z_1)^{\underline{n}}}\tag*{}$
We also have
$\dfrac{(n-1)^{z_1}}{(n-1)^{z_2}}=e^{(z_1-z_2)\ln(n-1)}=(n-1)^{z_1-z_2}\tag*{}$
With the same annotation as previously. Compare with $(1)$ and pick $z_1=1-i, z_2=1+i$
$\dfrac{\Gamma(1-i)}{\Gamma(1+i)}=\lim_{n \to \infty} \dfrac{(n-1)^{-2i}(1+i)^{\underline{n}}}{(1-i)^{\underline{n}}}\tag{2}$
Finally observe that
$\lim_{n \to \infty} \dfrac{(n-1)^{-2i}}{n^{-2i}}=1\tag*{}$
which is a consequence of
$\lim_{n \to \infty} \ln(n-1)-\ln(n)=\lim_{n\to \infty} \ln(1–1/n)=0\tag*{}$
and we find
$\lim_{n\to \infty} \left(\sum_{k=1}^n \arctan\left(\frac{1}{k}\right)-\ln(n)\right)=\dfrac{1}{2i} \ln\left(\dfrac{\Gamma(1-i)}{\Gamma(1+i)}\right)=\dfrac{i}{2}\ln\left(\dfrac{\Gamma(1+i)}{\Gamma(1-i)}\right)\tag*{}$
Answer: I wouldn't recommend solving double series with rearrangements from a power series to a zeta function (i.e., $\displaystyle \sum_k\sum_i k^i=\sum_i\sum_k k^i$), since it's usually the former that is easier to solve (e.g., by a geometric series) while the latter makes things even more difficult.
Instead, since you have a summand that has convenient differential properties, where the trouble is caused by the summation over discrete integers, you can ameliorate that by smoothing out the sum, converting it to an integral. Hence, try the Euler-Maclaurin formula. This gives you $$\sum_{k=1}^{x}\arctan\frac{1}{k}
=\int_{1}^{x}\arctan\frac{1}{t}dt+\frac{\arctan1+\arctan\frac{1}{x}}{2}+\sum \frac{B_{2k}}{(2k)!}\ldots
\\=\frac{1}{2}\left(-\frac{\pi}{4}-\ln2\right)+\frac{\ln\left(x^{2}+1\right)}{2}+\left(x+\frac{1}{2}\right)\arctan\frac{1}{x}+\sum\ldots$$
The middle terms dependent on $x$ tend to $\ln x +1$, so in the limiting difference they become $+1$. The  remainder Bernoulli number terms do annoyingly retain some constant order parts, but from a brief numerical evaluation, those seem to vanish after the 4th term. We could evaluate that more thoroughly with the expression for the derivatives of arctan given here that would give us a power series since the arctan derivatives become rational functions, but I'll leave that to you. Ultimately, numerical evidence suggests the constant term should be $0.302$, which is a little more than the $0.207$ extracted in the initial terms.
Comment: https://math.stackexchange.com/a/4770222/1218598


Dispose writer after memoryStream

Question: This is a piece of my code:
private static MemoryStream outputStream;

public static void ConvertMp3ToWavStream(string inputPath)
        {
            outputStream = new MemoryStream();
            using (Mp3FileReader reader = new Mp3FileReader(inputPath))
            {
                using (WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(reader))
                {
                    WaveFileWriter waveFileWriter = new WaveFileWriter(outputStream, waveStream.WaveFormat);

                    byte[] bytes = new byte[waveStream.Length];
                    waveStream.Position = 0;
                    waveStream.Read(bytes, 0, (int)waveStream.Length);
                    waveFileWriter.Write(bytes, 0, bytes.Length);
                    waveFileWriter.Flush();
                }
            }
        }

This is my CloseAndDispose method, which I invoke after some manipulations:
private static void CloseAndDispose()
        {
            if (outputStream != null)
            {
                outputStream.Close();
                outputStream.Dispose();
            }
        }

The problem: after all actions I've got some memory in memory stack, which wasn't disposed. As I understand, It's my writer. When I try to dispose writer, I get an exception. (can't read MemoryStream). When I try to close and dispose writer after CloseAndDispose() method, I get an exception. Where should I close waveFileWriter?
Comment: If it's this [WaveFileWriter](https://daisy-trac.cvsdude.com/urakawa-sdk/browser/trunk/csharp/audio/NAudio/Wave/WaveOutputs/WaveFileWriter.cs?rev=1346) you're a little stuck. *Some* `Stream` based classes allow you to construct them with a parameter which indicates whether the passed in stream should be `Disposed`, but this one doesn't appear to give you that option. Of course, if you're working with this source, you're free to change it to implement that option.
Answer: NAudio has a helper class called IgnoreDisposeStream in the NAudio.Utils namespace. Wrap your memory stream in one of those before passing it into the WaveFileWriter
using (var writer = new WaveFileWriter(new IgnoreDisposeStream(outputStream),
                                       waveStream.WaveFormat))
{
    ...
}

Answer: You could pass a local MemoryStream to WaveFileWriter and copy it to the global one before it's disposed:
public static void ConvertMp3ToWavStream(string inputPath)
{
    outputStream = new MemoryStream();
    var outputStreamLocal = new MemoryStream();
    using (...
    {
            using (var waveFileWriter = new WaveFileWriter(outputStreamLocal, ...
            {
                ...
                outputStreamLocal.CopyTo(outputStream);
            }
    }
}

Dispose writer after memoryStream


What makes a floating point number finite?

Question: We started studying about the binary floating point system, and talked mainly about the limitations when trying to represent fractions on computer systems, and how mostly what we get when manipulating floating point in a computer, is approximations to the "real" decimal number.
That popped some question into my mind, about something that obviously I noticed before, but never occurred to me to ask.
Irrational numbers, in their decimal (or any other base for that matter) floating point representation, are infinite, or in other words, every number that cannot be expressed as a ratio of two integers, has infinitely many digits after the point in its decimal floating point representation.
But some numbers, such like the number $\frac{1}{6}$, or $\frac{1}{3}$, can be expressed as a ratio of two integers, but still have infinite decimal floating point representations. What makes them different from, e.g., $\frac{1}{2}$, which, in a binary system, can be finitely represented as $0.1$, but $\frac{1}{3}$ or $\frac{1}{6}$ cannot?
What so special about $\frac{1}{3}$ or $\frac{1}{6}$ (or any other number that isn't irrational) but that would require infinitely many digits after the point to be represented in binary?
Answer: To answer you bottom-line question metaphorically:
The reason why $\frac13$ and $\frac16$ require infinitely many digits after the point to be represented in binary, is the same reason for which you cannot be $\frac13$ Spanish or $\frac16$ German - you have exactly $2$ parents (and each one of them has exactly $2$ parents, and so on).
No matter how you choose your family tree, you will never be able to reach full accuracy...
Comment: I know I asked this question over two years ago, but this is just a beautiful analogy.
Comment: @so.very.tired: Haha, thanks. I noticed that it was an old question only after I had answered it. I guess that someone has answered it, and then it popped up in the question list as a result...
Answer: As you pointed out, irrationals never have a terminating representation. So let's restrict our attention to rationals.
I believe that a rational number $p/q$ (in lowest terms) is representable as a terminating floating point expression in base $b$ if and only if each prime factor of $q$ is a divisor of $b$.
This is because if you write the fractional part of a number as $x=0.a_1a_2a_3\ldots$, then it terminates if there is integral $n$ with $x=0.a_1a_2a_3\ldots a_n$ in base $b$. That's the same as saying $b^n x=m\in \mathbb{Z}$, so you can write
$$x=\frac{m}{b^n}$$
Supposing for simplicity that the original number is between $0$ and $1$ (so you only have to deal with the fractional part--that's okay because adding integers doesn't affect the part past the radix point), this means you can write the number as a fraction whose denominator is a power of $b$ (this form will probably not be in lowest terms).
That's another way to say it--there is a terminating base $b$ floating point representation of $x$ if and only if $x=m/b^n$ for some integers $m$ and $n$.
Answer: Only rational numbers having integer powers of 2 and 5, and their products in the denominator give finite floating point. So I believe 2, 5 are the special numbers.
Actually only 2 is special. Since reciprocals of powers of 5 give powers of 0.2 which is 2/ base of number system
.


Loading a complete HTML Page in Modal Box

Question: Ok so now it has been a day almost in searching about Modal box to display a complete .HTML file in Modal box rather opening it in new window or tab.
More precisely:
example

This ajax.html file should open in "modal box" in the same window.
How can I acheive it through anchor tag?
I have searched thoroughly but found no good solution except this one(Example#4). This works on site but doesn't work when I download it.
.
P.S: I do not want to use iframe.
Answer: There are a few different ways to do this, but the best way is to use an AJAX request to the page using jQuery:
$.post("ajax.html", function(data){

    $("#myModalDiv").html(data).fadeIn();

});

Then to bind this to your anchor, assign it an ID and do this in your $(document).ready():
$(document).ready(function(){

    $("a#someId").on("click", function(){

        //Put the code from above here.

    });

});

Note that this will only work for files on the same domain.
If you want to use files on a different domain, you will have to use an iframe, therefore I cannot put this into a fiddle because there are no local files to pull on a fiddle.
Comment: `data` is what is returned by the `$.post()` request. It doesn't have to be called data, but that is what I use. You could do `$.post("ajax.html", function(sugar){});` and it would still work. So data essentially contains the contents of "ajax.html" since it is an HTML file. If you were to post to a PHP page, it would be whatever is echoed by the PHP page, including `echo` calls, `var_dumps`, errors, and HTML.
Comment: Whatever you want them to be. It could be empty.
Answer: You can use bootstrap for the thing you want to do.
http://getbootstrap.com/javascript/
Check out the modal section.
Comment: If you mean Bootstrap's remote option for modals, they clearly state on the page you link to: "This option is deprecated since v3.3.0 and will be removed in v4. We recommend instead using client-side templating or a data binding framework, or calling jQuery.load yourself."


First-order linear differential equation for matrix valued functions of size $3\times 3$

Question: I have two matries given    by (M' means derivative w.r.t x)
$
M=\left( \begin{array}{ccc}
   f_1(x) & f_2(x) & f_3(x) \\
   f_4(x) & f_5(x)& f_6(x) \\
  f_7(x) & f_8(x) & f_9(x) \\
   \end{array} \right) \tag 1$
$
M'=\left( \begin{array}{ccc}
   f_1'(x) & f_2'(x) & f_3'(x) \\
   f_4'(x) & f_5'(x)& f_6'(x) \\
  f_7'(x) & f_8'(x) & f_9'(x) \\
   \end{array} \right) \tag 2$ . These $f_i(x)$ can be any type of functions. They can be equal ($f_i=f_j$)or different or equal some of them and different others ,they can be constant functions. There is no limit or condition at all. Only one exception is that total matrix M cant be a zero matrix with full entries as zeros.
Question
Can you provide all $f_i$( any function you can select) such that it just satisfies following condition(all $a_0,b_0,c_0,a_1,b_1,c_1$ are constants cant be altered,but x is a   variable) . or is it not possible to have such one M? please clarify
$ M'=\{\left( \begin{array}{ccc}
   0 & -c_0 & b_0 \\
   c_0 & 0 & -a_0 \\
  -b_0 & a_0 & 0 \\
   \end{array} \right)+\left( \begin{array}{ccc}
   0 & -(c_1-c_0) & (b_1-b_0) \\
   (c_1-c_0) & 0 & -(a_1-a_0) \\
   -(b_1-b_0) & (a_1-a_0) & 0 \\
   \end{array} \right)x\}M \tag 3$
a,b,c are constants. You can select any arbitrar function. I tried a lot. Since there is no standard methods. I couldnt get a proper one.Thanks a lot
Answer: Not a solution but maybe a step in the right direction. First you can formulate your problem as a matrix differential equation. With the matrix vectorization operator, which stacks the columns of the matrix , we write:
$$m(x) = \text{vec}(M(x))$$
whereas $m(x)$ is just the vector of your unknown functions $f_i(x)$.
Your original problem is
$$M'(x) = (A + Bx)M(x)$$
which transforms to the matrix differential equation, after applying matrix vectorization on both sides
$$m'(x) = ((I \otimes A)  + (I \otimes Bx))m(x)$$
with the Kronecker matrix product $\otimes$. So we have an matrix differential equation of the form
$$m'(x) = (\widetilde A  + \widetilde Bx)m(x)$$
with some constant matrices $\widetilde A$ and $\widetilde B$ that essentially just contain the numbers $a_0, b_0$ etc.
This is solvable, when the matrices $\widetilde A$ and $\widetilde B$ are commuting, i.e. $\widetilde A \widetilde B = \widetilde B \widetilde A$ using the matrix exponential:
$$m(x) = \exp (\widetilde A x + 1/2\widetilde Bx^2)$$
However, I dont know whether the matrices commute (which is simple to check, but tedious) and unfortunately I have no solution when the do not commute.
This Math24 page gives some background information, on how to solve matrix differential equations with variable coefficients (as in this case).
Comment: I slightly changed the formatting, using display math syntax `$$ $$` and the link syntax [text](url). Hope you like it.
Comment: The issue is how do you evaluate $m(x) = \exp (\widetilde A x + 1/2\widetilde Bx^2)$ to check whether it satisfies  the condition. Issue is when you put these exponential power especially with $Bx^2$ it is complicated
Comment: To check the commuting condition you don't need to evaluate the matrix exponential. But I agree evaluating the matrix exponential of a 9x9 matrix is complicated. Personally I would only try it with a computer algebra package. But in case the commuting condition is met, then the solution maybe just be complicated because your problem is. Of course it also might be, that the matrix exponential simplifies significantly from the special structure of the $\widetilde{A}$ and $\widetilde{B}$ matrices. That I do not know.
Comment: @Rejo_Slash See the above comment ^^^ (since I inserted mine at the same time, I'm not sure you were notified).
Comment: Just checked now thanks
Comment: $9\times 9$ matrices?
Comment: I think, I am bit confused..you said  ($m(x) = \exp (\widetilde A x + 1/2\widetilde Bx^2)$.. shall we write $m'(x)$ from it? Shall we get a expression form as we did for derivative of $\exp(Ax)$,which is $A\exp(Ax)$. Here the power of 2 in x associated with B will make a mess..I was bit confused there..Thanks
Comment: Is it possible to write empirically by trail and error..Because any   $f_i(x)$  is ok for me..But I couldnt make one..So I am confused,whether it is not possible at all
Comment: m(x) is the vector of your 9 unknown functions: $m(x) = (f_1(x), ..., f_9(x))$ and $exp(A˜x+1/2B˜x2)$ is an explicit expression for the $f_i$ which solve your above matrix equation. This is as explicit as I could make it.
Comment: Hmm, if you want to do try and error. You could try to guess which form the components of the matrix exponential will have. I would try $f_i(x) = \sum_{j=1}^9 c_{ij} exp(-l_j x - p_j x^2)$. Plug this in and try to solve for the $c_{ij}$ and $l_j$ and $p_j$.
Comment: You can do this by equating coefficients on both sides of your matrix equation. I think the key is that you have to assume a superposition of different Gaussian functions. And the maximum you need is 9, which is the number of equations/unknown functions. If you try to evaluate the matrix exponential by the diagonalization method one just arrives at such a form. Hence I think it is worth a try in a try and error approach.


How can I extract text using regex on a string that containts both English and Hebrew?

Question: I have strings in the following format and am trying to extract in python the word(s) before the file extension but before the word שנה. In the first example I want the word בראשית and in the second חיי שרה
1. בראשית שנה ה_ - שפת התורה.pdf
5. חיי שרה שנה ה_ - כתיבת כתובה.pdf
I've tried a few regexs, including
regex = '\d\..+שנה (. +)\.pdf but can't seem to figure it out
Answer: You can use the following regex:
r'\d.\s(.*)\sשנה.*.pdf'

Please see the full code snippet below:
import re

match_object = re.match(r'\d.\s(.*)\sשנה.*.pdf', '1. בראשית שנה ה_ - שפת התורה.pdf')
print(match_object.groups()[0])
# prints בראשית
match_object = re.match(r'\d.\s(.*)\sשנה.*.pdf', '5. חיי שרה שנה ה_ - כתיבת כתובה.pdf')
print(match_object.groups()[0])
# prints חיי שרה


Theory of Automata : Context Free Grammar

Question: Please help me in making a CFG for this language.
a^i b^j c^k where i<j+k
I am fed up of trying this but not able to complete it.
Comment: I'm voting to close this question as off-topic because it is best suited for CS Stack Exchange.
Comment: This question might be better suited for the [Computer Science StackExchange](https://cs.stackexchange.com/) as it seems to be about programming theory. Remember to read [their question requirements](https://cs.stackexchange.com/help/on-topic) as they are more strict than this site.
Comment: Can you add one (or more!) attempts you've made? It'll help folks know where you're struggling and how to help you.
Comment: I have done this   S-> 0S1/0S2/1S/S2/1/2 but thing is that I am not getting how to force order in this cfg so that a comes before b and b comes before c
Answer: S -> Ac | Bb
A -> Ac | aAc | B
B -> Bb | aBb | ε

You "force order" by first generating as many cs as you need before moving on to bs.


Set limit for IN condition element that evaluate true

Question: table: t
+--------------+-----------+-----------+
| Id           | price     | Date      |
+--------------+-----------+-----------+
|  1           | 30        | 2021-05-09|
|  1           | 24        | 2021-04-26|
|  1           | 33        | 2021-04-13|
|  2           | 36        | 2021-04-18|
|  3           | 15        | 2021-04-04|
|  3           | 33        | 2021-05-06|
|  4           | 46        | 2021-02-16|
+--------------+-----------+-----------+

I want to select rows where id is 1,2,4 and get maximum 2 row for each id by date descending order.
+--------------+-----------+-----------+
| Id           | price     | Date      |
+--------------+-----------+-----------+
|  1           | 30        | 2021-05-09|
|  1           | 24        | 2021-04-26|
|  2           | 36        | 2021-04-18|
|  4           | 46        | 2021-02-16|
+--------------+-----------+-----------+

Something like:
Select * from t where Id IN ('1','2','4') limit 2 order by Date desc;

this will limit the overall result fetched.
Answer: Use row_number():
select id, price, date
from (select t.*,
             row_number() over (partition by id order by date desc) as seqnum
      from t
      where id in (1, 2, 4)
     ) t
where seqnum <= 2;

Probably the most efficient method is a correlated subquery:
select t.*
from t
where t.id in (1, 2, 4) and
      t.date >= coalesce( (select t2.date
                           from t t2
                           where t2.id = t.id
                           order by t2.date desc
                           limit 1,1
                           ), t.date
                        );

For performance, you want an index on (id, date).  Also, this can return duplicates if there are multiple rows for a given id on the same date.
Here is a db<>fiddle.
Comment: assuming that there will be thousands of records for each id..then if I m not wrong the inner subquery will going to fetch all those thousands rows, lets say for Id "1" and then assign row numbers to all those records. (wouldn't that cause a performance issue to fetch all the records and select only 2 or 3 latest records by date?)
Comment: @user2248435 Get the execution plan and see. It'll probably depend on the available indexes.
Comment: @user2248435 . . . A correlated subquery (with the right index) can be more efficient than `row_number()`.  Usually the difference is not particularly significant, though.
Comment: @GordonLinoff Thanks, the 2nd approach will work good. Anyway to define  limit by date?. Right now it will only fetch latest row (one row) by Date for each id.
Comment: @user2248435 . . . Yes, of course.  I fixed the answer so it is appropriate to your question.
Comment: @GordonLinoff I tried your answer. it does look perfectly good. but idk why it return ok Message on workbench with NO result grid. this is the actual query that i m making:

`select * from Price04 A WHERE A.CUSIP IN ('594918104', '482170107', '471718205')
AND (A.PrimaryExchgCD = A.ExchgCD or A.ExchgCD = 'USOTCB')
and A.MktCloseDate >= coalesce( (select B.MktCloseDate FROM  Price04 B WHERE B.CUSIP=A.CUSIP order by B.MktCloseDate desc limit 1,3),A.MktCloseDate) order by CUSIP desc, A.MktCloseDate desc;`
Comment: @user2248435 . . . I added a db<>fiddle.  It returns exactly what the question specifies.


MAC address for DHCP when using bridge with 2 NICs?

Question: I have a Ubuntu system with 2 NICs where I want to create a bridge br0 and bind both NICs to that bridge using the bridge_ports eth0 eth1 option.
I also want to configure the bridge to get an IP address from the local DHCP server.
I think I know how to do this, but I wonder which MAC address(es) will the bridge send out when requesting IP settings from the DHCP server? The MAC address of eht0, eth1, both?
Thanks,
Carsten
Comment: I'd suspect its the first in the order you name them when creating the bridge, or there is a command to designate/override.
Answer: The brctl command used to set up the bridge creates a virtual interface that shows up in ifconfig. The default address is the interface with the lowest MAC address. Thus, a NIC with a mac starting with 00:50 will be picked over one starting with 00:6f. It may be possible to change the MAC address by way of ifconfig, but you may need to turn off Spanning Tree first.


Program will not run because of error code * Program does not contain a static 'Main' method suitable for an entry point

Question: class CollegeStudent
{
    // fields
    private string studentName;
    private int midTerm1;
    private int midTerm2;
    private int finalExam;
    // properties
    public string StudentId
    {
        get { return studentName; }
        set { studentName = value; }
    }
    public int MidTerm1
    {
        get { return midTerm1; }
        set { midTerm1 = value; }

I don't know where to enter the entry point and Im pretty much stuck.  I have read another post, but it is not very clear on how they solved it and when I try to apply what they did to my own it does not work.  If anyone can help with this it be great.  The code itself reads * program does not contain a static 'Main' method suitable for an entry point
Comment: Well what do you want to happen when you run your program? You've got to tell the code where to start - at least if you're writing an *application* rather than a *library*. (As a side-note, I suggest you look into *automatically implemented properties* which will make your code a lot simpler.)
Comment: thats the question to debug code even though your snippet is cut - please consider using visual studio along with auto generated project ( you can start with console app)
Comment: Please provide a code sample of how your running the code along with your expected behavior. Following this guideline will help the community be able to your answer your question better https://stackoverflow.com/help/how-to-ask
Answer: Your project type is console that required main static method it is called (driver method) it is mandatory to run console application .
static void Main(string[] args)
{
//...
}

If you want to make DLL , you should use Class Library Project type add class library in visual studio 2017.


Strange Firewall Issue

Question: We have put a web server in place on a network, it was recently moved from a testing environment in another subnet to a different office. Now that we have the server in place, we can access it via its internal IP but cannot reach it on the assigned external IP. I am not sure what to do as normally, once you allow port 80 and 443 through and map the external IP to the internal you are typically up and running.
I even went so far as to disable the Firewall on the IIS server running server 2008. I can access the site on its internal ip on both HTTP and SSL. The Admin guy tells me the firewall has the proper settings in place but I do not have enough access to confirm. My usual logic tells me that if I can access it inside, as long as the firewall/router is configured correctly I should be able to get access outside the network as well.
This is server 2008 and not R2. I know that Windows 2008 can differentiate traffic from local and external nets in the firewall, but I figured that would have been bypassed by disabling windows firewall. My eyes keep going to the firewall  but I want to make sure that I am not missing anything.
Is there anything other than what I mentioned that I should be checking? I am at a loss
Answer: "cannot reach it on the assigned external IP"
Where on the network is this being attempted from? Internally or externally? If internally, have you tried from an external point as well?
If its external IP is reachable from an external point, but not internally, then it may be the router's configuration/ability to "loop-back" traffic which crosses/transitions between internal-external-internal.
Comment: You can load sites on port 80 on the internal 192.168 addy but cannot reach them from outside the network on the public IP
Answer: So your problem appears to be that you are having difficulty determining where the problem is, that is, whether the problem is on the new web server that has moved from a testing environment to another subnet.
Part of the confusion is with terminology. You need to clarify, if only for your own sanity between the network firewall (which may be using Checkpoint software based on your tags, but otherwise not mentioned), and the web server system's Windows Firewall on the web server.
For "external IP" I take it you mean a routable IP address that can be reached via the Internet, or in other words, not an RFC 1918 private IP address.
Without knowing the network topology, as alluded to by user48838 in his good answer, it is hard to say.
With the Windows Firewall enabled and logged rejected or denied connections, if you cannot see  denied / rejected connections for web connection, or the failing network connection attempts in Event Viewer logs, then I would expect there to most likely be a problem with regards to the destination network address translation (D-NAT or DNAT) to forward the external requests to web server on your ineternal network with its internal IP. Other approaches to forward external IP addresses may be possible, but DNAT is the most common.
Being a Unix geek I would normally use tcpdump to verify this. So enable any host based TCP monitoring on the server (WinDump, Ethereal, or Wireshark) to see if there if it is receiving any TCP connection attempts for port 80 (HTTP) or 443. tcpdump "tcp port 80 or port 443"
Of course as @user48838 said, it may be a matter of your network is not set up to re-forward internal requests to your external IP addresses correctly, which can be a problem if you are trying to access the web server from the internal network. If this isn't a normal problem, you need to modify your testing procedures, such as using an external proxy for testing.
You didn't mention any proxy servers, do I assume there are not involved in this network setup.
Comment: Thanks for the replies! I realize that my question from ysterday was very poorly worded. Chalk that up to frustration after a very long day. Anyway, the problem turned out to be that I was given incorrect network settings for the servers. They have some proxy gateways in place that I was unaware of that I discovered this morning. After getting the correct gateway settings in place on the NIC of the web server, we were able to access it from the outside.
Comment: Sounds like all is now well...

Strange Firewall Issue


Sequential characterization of closedness of the set

Question:
Let $(X, d)$ be a metric space. A set $F\subset X$ is closed if and only if for every sequence $\left\{x_n\right\}\subset F$, if $x\in X$ and $x_n\rightarrow x$ then $x\in F$.

Definition of closed set: Set is closed if and only if its complement is open. A Set $U$ is open if and only if $\forall_{x\in U}\exists_{r>0}B(x,r)\subset U$, where $B(x,r)$ is a ball with middle in $x$ and with radius $r$.
It's rather a well-known fact that I used many times while solving problems, but just now I realized that I don't know how to prove it.
Comment: This seems to be more or less the same as [this question](http://math.stackexchange.com/questions/125287/what-are-the-minimal-conditions-on-a-topological-space-for-its-closure-to-equal).
The property you wrote is not true for all topological spaces, spaces with this property are called Fréchet–Urysohn spaces. A related property: [sequential spaces](http://en.wikipedia.org/wiki/Sequential_space). See also [this blog](http://dantopology.wordpress.com/tag/sequential-space/) and perhaps
[this question](http://math.stackexchange.com/questions/132352/).
Comment: @Martin: I don't think it's the same question.  xan: Will you please provide context in your question?  You seem to be assuming that $X$ is a metric space without having mentioned it.
Comment: @MartinSleziak: The information and links in your comment are much appreciated.
Comment: See also: [Closure of Subset of Metric Space by Convergent Sequence](http://www.proofwiki.org/wiki/Closure_of_Subset_of_Metric_Space_by_Convergent_Sequence) at ProofWiki.
Answer: $\Rightarrow$: Suppose that $F$ is closed and let $\{x_{n}\}\subset F$ so that $x_{n}\to x$ for some $x\in X$. We show that $x\in F$. Let $U$ be any nhood of $x$. Since $x_{n}\to x$ there exists $k\in\mathbb{N}$ so that $x_{n}\in U$ for all $n\geq k$. In particular, $U\cap F\neq \emptyset$ (since e.g. $x_{k}\in U\cap F$). Since $U$ was an arbitrary nhood of $x$, this shows that $x$ is in the closure of $F$, which is equal to $F$ since $F$ is a closed set. Hence $x\in F$.
$\Leftarrow$: We show that $F$ is closed provided the latter property. Let $x$ be any element in the closure of $F$: we show that $x\in F$. Choose $x_{n}\in B(x,\frac{1}{n})\cap F$ for all $n\in\mathbb{N}$ (such $x_{n}$ exists since $x$ is in the closure of $F$, whence every nhood of $x$ intersects $F$). Now $x_{n}\to x$ and by assumption of this direction we have $x\in F$. Hence the closure of $F$ is a subset of $F$, whence they are in fact equal since a set is always subset of its closure. But this means that $F$ is a closed set.
Comment: now I see it, thank you very much!
Comment: @xan: Sure; you're welcome. I'm glad I was able to help you figure this out.


Uploading youtube videos to the site

Question: I would like to be able to upload youtube videos to the new site I am currently building. I would like to have a page which will list ALL the youtube videos uploaded, and then on the homepage, I would like to have a single video selected from the list of already uploaded youtube videos (changeable).
I would like it to be as simple as possible. I was thinking of a YouTube Field module. Is this simple enough?
I was thinking of possibly using Views to list all the Youtube Videos... but how would I embed the one on the homepage?
Any feedback and advice would be appreciated.
Answer: I am not sure what you are trying to do, but I recently tried a module that allows you to upload your videos via your website to Youtube. Check it out:
http://drupal.org/project/video_upload
On the other hand, if you simply want to integrate existing Youtube videos to your website (as fields), simply use the Media modules:
First of all, you need Embedded Media Field module:
http://drupal.org/project/emfield
Then install Media: Youtube to integrate your videos:
_http://drupal.org/project/media_youtube
You can list, sort, filter all your nodes (that contain your video field) very easily with views.
I hope this help, feel free to ask some more details.
Comment: http://drupal.org/project/youtube did the trick. Thank you.

Uploading youtube videos to the site


How to submit without closing the rich popup panel?

Question: <rich:popupPanel modal="true">
    <h:form
        id="myModal"
        onkeypress="if (event.keyCode == 13) {
                alert('ok10');
                $( "[name$='modalConfirmButton']").click();
                if (typeof evt.stopPropagation != 'undefined') {
                    evt.stopPropagation();
                } else {
                    evt.cancelBubble = true;
                }
                return true;
            }"

                <a4j:commandButton
                    value="Cancel"
                    immediate="true"
                    onclick="#{rich:component(cc.attrs.idModal)}.hide(); return false;" />

                <a4j:commandButton
                    id="modalConfirmButton"
                    value="Confirm"
                    action="#{mb.confirm}" />

If I click the 'confirm' button using the mouse, it will validate the form, and will not close if there are errors.
But, if I press enter, it will not validate, and will close it.
If I put the 'cancel' button after the 'confirm' button, it will validade, show the errors, but still close.
Any idea how to make the 'enter' key to work just like the mouse click for 'confirm'?
Answer: you should validate against submit form event, so it is not dependant on mouse-click or Enter key-press. Basically the behaviour you want, is associated with the button only. if you move that to onsubmit for your form, it should work.
Comment: same result here, unfortunately


Trying to make simple calculator

Question: val = float(input("Division(1) eller multiplikation(2)"))
if val == 1:

div1 = float(input('Ange din täljare: '))
div2 = float(input('Ange din nämnare: '))
print(div1 / div2)

elif val == 2:

mult1 = float(input('Ange din faktor: '))
mult2 = float(input('Ange din andra faktor: '))
print(mult1 * mult2)

input()

im trying to make a calculator and it works until i put in the if code. It says expected an indented block.
Comment: Format your code. Especially in a language like Python, and when you're getting indentation errors, unformatted code is nearly useless. I'd fix it, but I don't want to make any assumptions about your indentation.
Comment: Welcome to StackOverflow. Please check out this article to help you ask better questions https://stackoverflow.com/help/how-to-ask
Answer: Some languages (C,Java,C#) use brackets for form code blocks. Python uses indentation. Try this:
val = float(input("Division(1) eller multiplikation(2)"))
if val == 1:
    div1 = float(input('Ange din täljare: '))
    div2 = float(input('Ange din nämnare: '))
    print(div1 / div2)

elif val == 2:
    mult1 = float(input('Ange din faktor: '))
    mult2 = float(input('Ange din andra faktor: '))
    print(mult1 * mult2)

input()

Make sure you do not mix tabs and spaces for indentation as python might not be able to understand that 4 spaces equals one tab-character and gives you errors.

Trying to make simple calculator


How to use some code only in the template of selected content types?

Question: I have some code (calling JS and CSS) in the head section that I only want to appear if the HTML template is used for the content type 'home page'.
I did it like this in the html template:
<?php if ($variables['node']->type = 'home_page'){ ?>
Code....
<?php } ?>

But if I check the source code of my pages, the code is showing up in all off my pages, not only on the pages that use the 'home page' template.
Any tips, code, links?
PS: I'm not good at PHP (I normally cut and paste)
Answer: Typo:
if ($variables['node']->type = 'home_page'){
change it into:
if ($variables['node']->type == 'home_page'){
Comment: Thanks for quick response! But if i do it like this, the code is not showing up on the homepages ( there are 5 pages that use the homepage template). :-s But it shows up on all the other pages...
Comment: is `home_page` your custom content type?
Comment: I don't think so. www.hotelcapitole.be is the website... In source code you see comment where i want to show up my extra code... but space is empty. But if i look at other pages, the code is showing up... Gonna try some things now..
Comment: how about `home-page`? try to `var_dump($variables['node']->type)` and then you will have the right content type for your condition. Clear cache after changes.
Answer: You can do it by using hook_init
<?php
/**
 * Implementation of hook_init()
 */
function Hook_init() {

     // Check for front page
    if(drupal_is_front_page()){
        // Add css/js files
       drupal_add_css($module_path . '/css.css');
       drupal_add_js($module_path . '/js.js');
    }
}
?>

If you add in template file look this code :
function yourtheme_preprocess_node(&$vars) {
  // Add JS & CSS by node type
  if( $vars['type'] == 'your-node-type') {
    drupal_add_js( /* parameters */ );
    drupal_add_css( /* parameters */ );
  }

  // Add JS & CSS to the front page
  if ($vars['is_front']) {
    drupal_add_js( /* parameters */ );
    drupal_add_css( /* parameters */ );
  }

  // Add JS & CSS by node ID
  if (drupal_get_path_alias("node/{$vars['#node']->nid}") == 'your-node-id') {
    drupal_add_js( /* parameters */ );
    drupal_add_css( /* parameters */ );
  }
}

Answer: IF you are trying to include the code only on the front page of your site, I'd suggest you override its template by creating page--front.tpl.php inside the template directory of your theme. See this explanation.
EDIT: If you want to use the logic you had in your posting, I would be sure to check the syntax of your if statement. I may be wrong about this, but I've mostly seen this as:
<?php if ($variables['node']->type == 'home_page'): ?>
Html, css or Javascript code here.
<?php endif; ?>.

Notice, no curly braces.  Also, as another answer pointed, it's ==
Comment: In this case your suggested solution is not optimal. Normaly I use the page--front.tpl.php . But i built the website using a normal node tpl for the home-pages... 5 times.. one for dutch .. one for english... all use the called 'home_page' tpl...
Answer: If you are putting condition for your sites home page its better to use :
 if(drupal_is_front_page()){
CODE...
 }
Alternative is:
If you print all your $variables array you will find $variables['is_front'] set to either true or false which you can use.
Just remember to set site's front page.


How to recover from RAID 5

Question: there are 5 disk-array. i've lost the data of one of them. How can i recover? I don't know where to start?
Comment: Start by finding out the make and model of the disks and raid controller.
Comment: Find the doc for your hardware, ultimately, mark the disk as failed, add a new disk as a hotspare to the array, rebuild the array and remove the failing drive.
Answer: You need to consult the manual/helpfile for any specifics to the particular RAID controller you have, but essentially you remove the bad disk and replace it with a good one, and that's it.
Or are you saying that you've lost the actual data on the RAID array? In which case the answer is "You restore from your last backup".
Without wanting to sound rude, it's difficult to give a better answer than this until you ask a better question.
Answer: Remove broken HDD, install new, add it in RAID managing software.
It will automatically populate it with recovered data, it might take up to 10 hours.
Comment: "it might take up to 10 hours" - I've just had a conversation with an HP tech who lives across the road from me. He's been monitoring a RAID rebuild that's expected to run for at least two weeks.

How to recover from RAID 5