VScode debugger with docker-compose

Question: Recently i have started using docker for my project running with the following

Django
Nginx
Gunicorn
Celery
Postgres
Redis

Earlier it was easy to setup debugger but after using docker-compose i am not able to do that. As soon as i start the debugger it loads for sometime and then automatically stops with no logs or error anywhere.
Here are the relevant code.
launch.json
{
"configurations": [
    {
        "name": "Python: Remote Attach",
        "type": "python",
        "request": "attach",
        "connect": {
            "host": "localhost",
            "port": 443
        },
        "pathMappings": [
            {
                "localRoot": "${workspaceFolder}",
                "remoteRoot": "."
            }
        ]
    }
]
}

docker-compose.yml
version: '3'

services:
 db:
     image: postgres:12
     env_file: .env
     environment:
        - POSTGRES_DB=${DB_NAME}
        - POSTGRES_USER=${DB_USER}
        - POSTGRES_PASSWORD=${DB_PASSWORD}
    ports:
        - "5431:5432"
    volumes:
        - dbdata:/var/lib/postgresql/data
nginx:
    image: nginx:1.14
    ports:
        - "443:443"
        - "80:80"
    volumes:
        - ./config/nginx/:/etc/nginx/conf.d
        - ./myapp/static:/var/www/myapp.me/static/
web:
    restart: always
    build: ./myapp
    command:  bash -c "
                python manage.py collectstatic --noinput
                && python manage.py makemigrations
                && python manage.py migrate
                && gunicorn --certfile=/etc/certs/localhost.crt --keyfile=/etc/certs/localhost.key myapp.wsgi:application --bind 0.0.0.0:443 --reload"
    expose:
        - "443"
    depends_on:
        - db
        - nginx
    env_file:
        - .env
    volumes:
        - ./myapp:/opt/myapp
        - ./config/nginx/certs/:/etc/certs
        - ./myapp/static:/var/www/myapp.me/static/

broker:
    image: redis:alpine
    expose:
        - "6379"

celery:
    build: ./myapp
    command: celery -A myapp worker -l info
    env_file:
        - .env
    volumes:
        - ./myapp:/opt/myapp
    depends_on:
        - broker
        - db

celery-beat:
    build: ./myapp
    command: celery -A myapp beat -l info
    env_file:
        - .env
    volumes:
        - ./myapp:/opt/myapp
    depends_on:
        - broker
        - db

volumes:
    dbdata:

Answer: Finally i managed to solve it myself.
Few takeaways from the problem.
You need to use debugpy and place that in your manage.py file to start listening to a port.
I did something like this
import debugpy

debugpy.listen(('0.0.0.0', 5678))
debugpy.wait_for_client()
debugpy.breakpoint()

Along with this we need to map this port to a port inside the host machine. For that we need to change and add a single line in web service of docker-compose
ports:
    - "5678:5678"

And my launch.json looks like this
{
"configurations": [
    {
        "name": "Python: Remote Attach",
        "type": "python",
        "request": "attach",
        "connect": {
            "host": "0.0.0.0",
            "port": 5678
        },
        "pathMappings": [
            {
                "localRoot": "${workspaceFolder}/myapp",
                "remoteRoot": "."
            }
        ]
    }
]
}

NOTE: make sure you have debugpy in your requirements file or install it manually.
Comment: Seems like you have to attach the debugger to the process somehow. This only attaches it to the application running on the specific port. Can't help you more without going through the code
Comment: @ricoms in that case you can import it in your main application file.
Comment: Thank you for this great help, you gave me here! I was trying for hours to get some working configuration and yours just works like a charm!
Comment: You just saved my s
Comment: @targhs were you able to debug celery tasks as well?
Comment: @ReemaParakh i don't think i checked debugging celery tasks. Did you face any issue?
Comment: @targhs debugger is not working in case of celery task.
Comment: is that `manage.py` file is specific for Django project?
Comment: @ricoms its been a long time but yes i suppose so.
Comment: Thanks @targhs. I learnt that I need to include that debugpy import and call anywhere in my application code. I'm using fastapi and I didn't have a manage.py file  I was confused about that
Answer: If you make your debugger a module you can turn it on and off with an environment variable.  I just used this article as the basis for a fastapi/gunicorn debugging solution.
# debugger.py
from os import getenv

def initialize_flask_server_debugger_if_needed():
    if getenv("DEBUGGER") == "True":
        import multiprocessing

        if multiprocessing.current_process().pid > 1:
            import debugpy

            debugpy.listen(("0.0.0.0", 10001))
            print("⏳ VS Code debugger can now be attached, press F5 in VS Code ⏳", flush=True)
            debugpy.wait_for_client()
            print("� VS Code debugger attached, enjoy debugging �", flush=True)

See this article by Adrian:  Flask Debugging in VS Code
Comment: Thanks. It seems helpful. Will try to get this in my project.
Comment: @MrYutz, I'm using your solution now as well, which is kind of nice. There are just two things:
1) Why are you checking for `pid > 1`?
2) If I call this function in the main() of my manage.py, it will run multiple times, resetting the debug server and waiting for a new connection.
Comment: @LarsSchellhas - "In debug mode Flask uses a first process (with pid==1) to start child processes that handle connections. If the code below this line is executed by the main process, the debugging port is taken and subsequent child processes can't use the same port and are attributed a random port which prevents connections."
Comment: Ah fair enough. I'm not using flask but Django, so I guess, adapting it in my way is ok :)

VScode debugger with docker-compose


Encapsular valores retornados por JSON dentro de um único objeto

Question: Estou com uma dúvida, tenho este código abaixo no controller:
[Authorize]
    public JsonResult Teste()
    {

        var licencas = new List<Object>();
        licencas.Add(new {
                            Responsavel = "José",
                            Ticket = 79007,
                            Descricao = "RC - 01 Desktop padrão - José",
                            Status = "Pendente Gestão",
                            SLA = "10/10/2013"
                        });
        licencas.Add(new {
                            Responsavel = "Maria",
                            Ticket = 79037,
                            Descricao = "RC - 01 Notebook padrão - Maria",
                            Status = "Pendente Pedido",
                            SLA = "10/11/2013"
                        });

        return this.Json(licencas, JsonRequestBehavior.AllowGet);

    }

Que retorna o seguinte JSON:
[
   {
    "Responsavel":"José",
    "Ticket":79007,"Descricao":"RC - 01 Desktop padrão - José",
    "Status":"Pendente Gestão",
    "SLA":"10/10/2013"
    },
    {"Responsavel":"Maria",
     "Ticket":79037,
     "Descricao":"RC - 01 Notebook padrão - Maria",
     "Status":"Pendente Pedido",
     "SLA":"10/11/2013"
   }
 ]

Mas eu preciso que retorne assim:
licencas = [
   {
    "Responsavel":"José",
    "Ticket":79007,"Descricao":"RC - 01 Desktop padrão - José",
    "Status":"Pendente Gestão",
    "SLA":"10/10/2013"
    },
    {"Responsavel":"Maria",
     "Ticket":79037,
     "Descricao":"RC - 01 Notebook padrão - Maria",
     "Status":"Pendente Pedido",
     "SLA":"10/11/2013"
   }
 ]

O que faço para retornar o JSON desta maneira?
Comment: Porque precisa que retorne daquela maneira?
Comment: Exatamente por que necessita desse retorno? Não seria melhor criar essa variável do lado do cliente e atribuir o valor a ela?
Comment: `return this.Json(new { licencas = licencas }, JsonRequestBehavior.AllowGet);` não? Ou `return this.Json(new { licencas = licencas.ToArray()}, JsonRequestBehavior.AllowGet);`
Comment: É estranho, já deve haver algo fora de padrão no teu código. Então uma tentativa seria retornar do jeito que o @MiguelAngelo demonstrou e fazer um pós processamento antes de utilizar, certifique-se que o JSON está em formato string e utilize um replace maroto de '"licencas":' para 'licencas = '
Answer: Resposta da sua pergunta "Como faço para retornar o JSON desta maneira?
Simplesmente não faz. Você não pode retornar um JSON desta forma pois a sintaxe do JSON não permite, o formato mais adequado ao seu objeto com certeza é:
{

    "licencas":[
        {
            "Responsavel":"José",
            "Ticket":79007,
            "Descricao":"RC - 01 Desktop padrão - José",
            "Status":"Pendente Gestão",
            "SLA":"10/10/2013"
        },
        {
            "Responsavel":"Maria",
            "Ticket":79037,
            "Descricao":"RC - 01 Notebook padrão - Maria",
            "Status":"Pendente Pedido",
            "SLA":"10/11/2013"
        }
    ]

}

O código c# pra retornar este JSON é o informado pelo @MiguelAngelo:
return this.Json(new { licencas }, JsonRequestBehavior.AllowGet);

Você pode entender melhor o JSON utilizando sites como este de uma olhada, no seu JSON por exemplo:

Posteriormente você poderá acessa-lo usando:
seuJSON.licensas[0].Responsavel; // José
seuJSON.licensas[0].Ticket;      // 79007
seuJSON.licensas[0].Descricao;   // RC - 01 Desktop padrão - José
seuJSON.licensas[0].Status;      // Pendente Gestão
seuJSON.licensas[0].SLA;         // 10/10/2013

seuJSON.licensas[1].Responsavel; // Maria
seuJSON.licensas[1].Ticket;      // 79037
seuJSON.licensas[1].Descricao;   // RC - 01 Notebook padrão - Maria
seuJSON.licensas[1].Status;      // Pendente Pedido
seuJSON.licensas[1].SLA;         // 10/11/2013

Answer: Faça assim para retornar o json que vai sair do jeito que você quer:
return this.Json(new { licencas }, JsonRequestBehavior.AllowGet);

Comment: Você deve saber que o valor exatamente da forma que quer, não é um JSON válido. Nenhum json inclui um sinal de igual.
Comment: Miguel, o códogo acima retorna:
{"licencas":[{"Responsavel":"José","Ticket":79007,"Descricao":"RC - 01 Desktop padrão - José","Status":"Pendente Gestão","SLA":"10/10/2013"},{"Responsavel":"Maria","Ticket":79037,"Descricao":"RC - 01 Notebook padrão - Maria","Status":"Pendente Pedido","SLA":"10/11/2013"}]}

com { iniciando e "licencas" como string e :

para dar certo precisa ser idêntico ao que postei

obrigado mesmo assim
Comment: Por isso que perguntei porque precisava ser daquela maneira, pois se você pegar o resultado JSON e atribuir a uma variável `licencas` vai ser o mais próximo da maneira que @Jhonatan quer...(Ex: `success: function(data) { var licencas = data; // ... o q quiser }` )
Answer: Você vai precisar criar um novo ActionResultpara fazer isso. Já fiz no passado um JsonVariableResult que fazia o que você queria, mas com a webapi e novidades no Framework acabei deletando o código.
Para não te frustrar, baixe o ILSPY, e dê uma olhada no fonte das ActionResults, elas são muito simples, crie a sua e seja feliz!


Show that two groups that are isomorphic to a third group are isomorphic to each other

Question: Prove that if G is isomorphic to K and H is isomorphic to K then G and H are isomorphic to each other.
My strategy thus far has been to show that we can use composition of the respective isomorphisms to map from G to K then K to H. Would it be conclusive to show that this process can be inverted thus proving G and H are isomorphic?
Comment: Yes. Since the homorphisms from $G\to K$ and $H \to K$ are isomorphisms, they are invertible and hence so is their composition.
Answer: Isomorphism is transitive, since the composition of two isomorphisms is an isomorphism.  This is utterly straight forward.  In fact, it's not hard to see that isomorphism defines an equivalence relation.


What is the safest/proper way to implement a thread-safe singleton pattern?

Question: How do I implement the singleton pattern in C# and ensure that it is thread safe?
Answer: Jon Skeet has an article on this that covers most of your options.


buscar dados em tabela MySQL e php

Question: Tenho a tabela A com os campos id e usuario
e tabela B com id, dados e id_A;
Na página PHP eu quero q apareça o conteudo da tabela B, e com o id_A buscar o nome na tabela A.
O pricipal para mim seria a busca de uma tabela em outra mesmo, pois o conteudo ja consigo mandar para a página.
Answer: Você tem que relacionar as tabelas no select, tenta assim:
<code>SELECT b.id, b.dados FROM tablela a, tabelab b WHERE a.id = b.id
</code>

buscar dados em tabela MySQL e php


Error in DynamicDatabaseFactory.CreateDatabase connection string parsing

Question: I'm not very familiar with DynamicDatabaseFactory and there isn't a lot of information out there.  I'm making changes to a site and I'm just trying to get it to run on my development machine and I've run into this problem, the line: DynamicDatabaseFactory.CreateDatabase(MyConnectionString, DBProviderType.SqlServer) generates this error: [ArgumentOutOfRangeException: Index and length must refer to a location within the string..  I know the connection string is good because it is used in other areas of the application and connects to the database with no problem. In the debugger I can see that the string is being provided properly.  So what am I missing?
Comment: What is `DynamicDatabaseFactory` in this context? Is it one of your custom classes or a library from somewhere?
Comment: It's a library, EnterpriseLibrary.Extensions.Data.DynamicDatabaseFactory.
Answer: I was able to get it to work by using one of the overloads to the CreateDatabase method:
Static db As Database = DynamicDatabaseFactory.CreateDatabase("localhost\SQLEXPRESS", "MYDB", "username", "password", DBProviderType.SqlServer)

This overload allows you to pass the server, database, username and password to the method instead of passing just the connection string.  I suspect, but cannot confirm, that the call coded earlier was having a problem parsing the server portion of the connection string, I use Sql Express in my development environment and the database is located at "localhost/SQLEXPRESS", production uses the full version of Sql Server which is located at "localhost".  In any event, I was able to get things working with the line of code above.


Pagefactory dynamic webelement with wildcard

Question: I have dynamically generated locators depends on which element is gonna be chosen from a list.
For instance, this is my generated id:
Function:TableName:0:submenuAction

0 is the counter, meaning first element is chosen from the list. All strings before and after the counter won't change, so start with, contains xpath method does not work.
Can I use some wildcard like
   Function:TableName:{X}:submenuAction {x} is integer.
I can store the chosen number of element, but how can I use this variable inside the pagefactory element? driver.findelement can fail with staleElementException,thats why I wanna use PageFactory.
Comment: usually stale element error occurs when you try to access any element after changing the DOM state of the page. so if you want to use any element, you should get the reference instantly and then you can perform any action. for your better understanding of the scenario im writing some pseudo for triggering the stale element error.
1. get the reference of any element on the page (driver.findelement(....))
2. refresh page (driver.manage.navigate.refresh())
3. try to click on that element now (element.click())--> you will encounter stale element error.
Answer: Whatever you're passing in would probably have to be a constant (e.g. final static in Java) to be used in a PageFactory annotation.
private final static int ITEM_INDEX = 2;

...

@FindBy(xpath="Function:TableName:"+ ITEM_INDEX + ":submenuAction")
private WebElement targetListItem;

In addition to some of the stale checking strategies mentioned in the comment, you may also want to try binding all of those dynamically-identified elements to a collection (e.g. List<WebElement>), then indexing in:
@FindBy(xpath="...")
private List<WebElement> allListEntries;

...

private WebElement getTargetListEntry(int index) {
    return allListEntries.get(index);
}

Comment: The problem is that, it have to be a constant. I do not know the index value just after a for loop. As far as I know, constant cannot be modified or initialized in such way. Any idea?
Comment: Ah, yeah. If you calculate the desired index dynamically, then the second example (grabbing all the items in that dynamic list and indexing in) is probably what you'll need to do.


Como configurar o timezone no REPL Clojure?

Question: Como configurar o REPL com o timezone correto?
Ao executar uma query num banco postgres através de um REPL os campos data estão com fuso horário UTC quero configurá-lo para America/Sao_Paulo.
No REPL do Intellij eu tentei o seguinte:

Configurar o arquivo idea.vmoptions (do intellij) com o parâmetro -Duser.timezone=America/Sao_Paulo
Adicionar :jvm-opts ["-Duser.timezone=America/Sao_Paulo"] no project.clj
Adicionar -Duser.timezone=America/Sao_Paulo na configuração do REPL pelo intellij
export JAVA_OPTS="-Duser.timezone=America/Sao_Paulo:$JAVA_OPTS" no arquivo ~/.zshrc

e no REPL Leiningen:

Adicionar :jvm-opts ["-Duser.timezone=America/Sao_Paulo"] no project.clj
export JAVA_OPTS="-Duser.timezone=America/Sao_Paulo:$JAVA_OPTS" no arquivo ~/.zshrc
Nada surtiu efeito!

Exemplo
(ns experiments
  (:require [next.jdbc :as jdbc]))

(def db
  {:dbtype   "postgres"
   :dbname   "<dbname>"
   :host     "<host>"
   :port     5432
   :user     "<user>"
   :password "<pass>"})

(def ds (jdbc/get-datasource db))

(jdbc/execute! ds ["select current_timestamp"])

Comment: Pelo que eu entendi, o timestamp que você está pegando não tem relação com o REPL, Clojure ou IntelliJ. O `current_timestamp` é um retorno do Postgres que, por padrão, retorna UTC. Você provavelmente teria que fazer alguma coisa parecida com isso: `SELECT current_timestamp::timestamp at time zone 'UTC';`
Answer: Por padrão a JVM pega o timezone da variável de ambiente TZ
export TZ="America/Sao_Paulo"

Caso não queira declarar a variável de ambiente por algum motivo você pode passar via opts da JVM, como você comentou na pergunta:
-Duser.timezone=America/Sao_Paulo

No seu exemplo você executa a consulta (jdbc/execute! ds ["select current_timestamp"]), a função current_timestamp do PostgreSQL pega a data/hora local do servidor que esta rodando o banco de dados, não do servidor de aplicação, ou seja, provavelmente o problema de "timezone" não é na JVM e sim no servidor de banco de dados.


Nuxt how to access the exception error on the server error page?

Question: In Nuxt.js, is there a way to globally handle any server-side errors?
I'd like to conditionally redirect to my own Vue error page. For example:
if (process.env.NODE_ENV === 'production') {
   redirect("/error?message=the-error-message-here");
} else {
   // render the default server error page with the stack trace
}

Is this possible?
I've read about creating an app/views/error.html but that doesn't change anything.
Comment: I think that this can answer your question : https://nuxtjs.org/docs/configuration-glossary/configuration-dev/
Answer: you should put error.vue in here
layouts/error.vue
    <template>

Page not found

An error occurred

        <NuxtLink to="/">Home page</NuxtLink>

    </template>

You must see this layout as a component displayed when an error occurs (404, 500, etc.). Similar to other page components, you can set a custom layout for the error page as well in the usual way.
here is the documentation :
https://nuxtjs.org/docs/concepts/views#error-page


Area enclosed by the curve $x^2+y^2=|x|+|y|$.

Question:
Find the area enclosed by the curve $x^2+y^2=|x|+|y|$ on the coordinate plane.

I have no idea how this curve looks like, therefore can't find the area. Please help. Thank you.
Answer: To get an idea of what the curve looks like, try different cases. For example, when $x\ge 0$ and $y\le 0$, you get
$$x^2+y^2=x-y\iff x^2-x+y^2+y=0\\\iff\left(x-\frac 12\right)^2-\frac 14+\left(y+\frac 12\right)^2-\frac 14=0\\ \iff \left(x-\frac 12\right)^2+\left(y+\frac 12\right)^2=\left(\frac 1{\sqrt 2}\right)^2$$
So here the curve is part of a circle centered at $(1/2,-1/2)$ with radius $1/\sqrt 2$.
Answer: In the first place $S:=\{(x,y)\ |\ x^2+y^2=|x|+|y|\}$ is just a set. As $S$ is symmetric with respect to the axes we begin by determining  the points of $S$ lying in the (closed) first quadrant $Q$. In $Q$ we have $|x|=x$ and $|y|=y$. Therefore
$$S\cap Q=\{(x,y)\in Q|x^2+y^2=x+y\}\ .$$
Now the equation $x^2+y^2=x+y$ is equivalent with $(x-{1\over2})^2+(y-{1\over2})^2={1\over2}$ and describes a circle $C$ with center $({1\over2},{1\over2})$ and radius ${1\over\sqrt{2}}$.
It follows that $S\cap Q=C\cap Q$, and $S$ becomes the set you get by reflecting this intersection on the two axes. Now it should not be too difficult to compute the area enclosed by $S$.
Answer: Wolfram|Alpha shows you how the curve looks like. To obtain the area, first note that by symmetry we can concentrate on the first quadrant. There the equation is equivalent to $x^2 + y^2 = x+y\iff y^2 - y + (x^2-x) = 0$, so
\[
  y_{1,2} = \frac 12 \pm \sqrt{\frac 14 - (x^2-x)}
\]
The randicand is nonnegative for $x^2 - x \le \frac 14$, that is $0 \le x \le \frac 12(1 + \sqrt 2)$ (note that we are in the first quadrant, hence $x \ge 0$). $y_2$ is positive if moreover $x^2-x \ge 0$, that is $x \ge 1$. So the area is
\begin{align*}
  A &= 4 \left(\int_0^1 \left(\frac 12 + \sqrt{\frac 14 - (x^2-x)}\right)\,dx
       + \int_1^{\frac 12(1 +\sqrt 2)} 2\sqrt{\frac 14 - (x^2 - x)}\, dx\right)
\end{align*}
Comment: You can also use polar coordinates for $r(t)=\cos t + \sin t$, which is a circle. See a [plot](http://www.wolframalpha.com/input/?i=plot+r+%3D%5Ccos+t+%2B+%5Csin+t).
Answer: If you have a Mac, it came with wonderful free software called Grapher which can graph things like this easily.
Anyway, I think this one is best tackled in polar. We can work in the first quadrant to get rid of the absolute value signs and then multiply our answer by 4. We have
$$
x^2 + y^2 = x + y
$$
so
$$
r^2 = r(\cos(\theta) + \sin(\theta))
$$
i.e.
$$
r = \cos(\theta) + \sin(\theta).
$$
The area is therefore
$$
4\int_0^{\frac{\pi}{2}}\frac{1}{2}(\cos(\theta) + \sin(\theta))^2 d\theta.
$$


Interpretation for diffeomorphism

Question: Let $f: M \to N$ be a diffeomorphism between two differentiable manifolds.  Every book mentions that if $M$ and $N$ are diffeomorphic then they are basically the same from the differentiable point of view, ie, they are indistinguishable as differentiable manifolds.   Of course I agree about this but what I do not understand is how $f$ show this fact.   Let me explain this a bit more.  When we are dealing with a isomorphism $T: V \to W$ between two vector spaces $V$ and $W$ (I am out of the manifold context for a minute), this map tells that you can "rename" the objects from $V$, i.e., if $v \in V$ then rename it as $T(v)$ and the operations in $V$ rename it as $v_1 + v_2 = T(v_1) +' T(v_2)$, where $+'$ is the operation in $W$, thus, via the bijection you are seeing $V$ just as $W$.   That information is obtained directly from $T$ and its linear property from its definition as linear transformation.  In other words, $T$ transforms $V$ into $W$ preserving the linear structure. Now, back to the diffeomorphism $f: M \to N$ , how $f$ tells me that $V$ is basically the same as $W$?   How can I see $f$ as transforming $M$ into $N$ in such a way that $M$ and N$ are esentially the same as differeantible manifolds.   I hope I am clear otherwise let me know so I can explain it again in a better way.
Answer: A manifold is a topological space $M$ (with certain properties) together with an open cover $(U_\lambda)_{\lambda\in\Lambda}$ such that, for each $\lambda\in\Lambda$ there is a homeomorphism $\varphi_\lambda\colon U_\lambda\longrightarrow\mathbb R$ (which satisfy certain conditions). Now, the map $f\colon M\longrightarrow N$ transports this  open cover to $N$: for each $\lambda\in \Lambda$, consider $f(U_\lambda)$ a the map $\varphi_\lambda\circ f^{-1}\colon\varphi(U_\lambda)\longrightarrow\mathbb R$. This new atlas induces in $N$ a differentiable manifold structure, which is identical to its original one.
Comment: I see! that is a very nice way to construct an atlas in $N$ from $f$ (and $M$).  Now I see that the compatibility from this new atlas and the one in $N$ is strongly based from $f$ and $f^{-1}$ being differentiable.  Thank you!
Comment: @ValinK If my answer was useful, perhaps that you could mark it as the accepted one.
Answer: A differentiable manifold is a topological manifold with the extra structure (differentiable). I will split this two structures to make it more clear and continue with your analogy of "renaming stuff":

A topological space is a structrue which is just a set together with a set of subsets called open sets. A diffeomorphism is to begin with a homeomorphism, and this means precisely that you are transforming one space into the other preserving the topological structure, you "rename" the objects as you said (which in this case are open sets). So you are still seeing the second space as the first one in this sense, if you want.
A differential structure on your manifold consists on defining what maps from your manifold to $\mathbb{R}$ are what you will call smooth (just as before we defined what subsets we would call open). As with open sets there are some conditions that you want this structure to verify of course, but I won't get into that because I think it is not important for the point we are discussing. In this context, the map between two differentiable manifolds being a diffeomorphism means precisely that you are transforming one space into the other preserving the differential structure. In this case instead of "renaming" subsets we rename maps. So the diffeomorphism tells you that you can call a map from the manifold to $\mathbb{R}$ smooth if and only if the composition with the diffeomorphism is what you were calling smooth before.

Summarizing: a diffeomorphism allows you to do exactly the same as the vector space isomorphism, but only in a more complicated way if you want (because the structure is now more complicated). And you can see this by layers of structure as I suggested above (and there is even a third more basic layer which is the set theoretical, that tells you that you can rename points in $N$ by the corresponding points in $M$, which amounts to say that $f$ is a bijection).

Interpretation for diffeomorphism


Data Structures within Databases

Question: I have an idea for an application, and it requires a graph data structure.  I will have nodes that contain text, numbers, and pointers to other nodes. The edges will have a certain weight and I want to be able to traverse my graph efficiently.  This graph will be HUGE, so naturally I want to use a database.  I understand how to store the text and numbers in a database object, but I don't understand how I can store the pointers to other nodes.
It seems to me that most data structures use this idea of a node connected to other nodes, so there must be an easy way to do it with a database, I just can't find it for the life of me.
How can I have a database entry that has a field that points to another database entry?
How can I create a data structure within a database?
Thanks in advance
Comment: Maybe you should explore using a graph database like [Neo4J](http://neo4j.com/) instead of a relational database?
Comment: @jpw Wow! I never know things like that existed! Thank you, I think I will actually use Neo4J, it seems perfect for my project
Comment: Welcome to SO! For starters what database are you using? You need to show us more of what you have tried and researched. See the [how to ask page](http://stackoverflow.com/help/how-to-ask) for help in improving your question.
Comment: @Madness  I actually am just in the beginning stages of my project, still just ironing out the plan so I haven't nailed down any specifics like that, it's just an idea.  I will keep that in mind for my next questions though, thanks! :D
Comment: There's a lot to be said for going with what you know.  I would consider Neo4J for any project that faced the problem of persisting objects that were not predictable or whose form down the road might not be known.  If your data model is pretty well known at design time and you had confidence in its stability (which is a pretty common scenario), I would probably stay with tried and true RDBMSs.
Comment: @scottb  To be completely honest, I have never done serious work with databases (only with very simple data models), so I will have to work out what my exact needs are.  However, I do think it'll be a constant data model, so I will probably end up going with RDBMs.  I do want to explore my options with other models though (so I can gain knowledge for future projects).  Thanks again for all your advice, I didn't know databases were such a wide field.
Answer: Your question gets at the impedance mismatch between relational databases and object-oriented development environments like Java.

Database tables map relationships between each other using keys; tables have no notion or concept of object-oriented principles like inheritance.
Memory resident objects have references to map relationships and use composition and inheritance to build hierarchies and graphs of objects.  Hierarchies and composition are not native concepts in relational databases.

A straightforward way to get at your problem is to use an ORM framework to take these impedance mismatch issues out of your problem domain.

Develop your domain object model as you would for any object-oriented  application (i.e., using composition and inheritance)
When complete, map your objects with a JPA framework such as Hibernate, which will do the ORM for you
As long as your domain object model is well-formed and the JPA mapping is correct, then JPA will take care of the problem of mapping your objects into a database and vice-versa.

ORM isn't magic.  It won't take a poorly conceived or suboptimally conceived domain object model and fix its problems in the database layer.  It really does pay off to spend time getting the domain object model right, tight, concise, and efficient before you begin the work of using it with JPA.
Comment: Thank you very much! I am a little new to databases, so I have a lot of work to do, but your answer has gotten me on the right track :D.  I up-voted your answer but it said I didn't have enough rep...

Data Structures within Databases


Extensão do Visual Studio Code: "Code Runner" não compila C

Question: Estou tentando rodar um código em C no Visual Studio Code com a extensão Code Runner mas não estou conseguindo. Já instalei o MinGW corretamente, consigo verificar ele no cmd via
g++ --version

Mas continuo sem conseguir fazer rodar C no VSCode. Eu sei que o VS não é o mais indicado mas queria centralizar meus trabalhos em um único editor.
A mensagem que aparece quando tento rodar é a seguinte:
[Running] cd "c:\Users\henrique\Documents\_minhas-coisas\_Faculdade\TesteVSCode\C\" &&
             gcc first.c -o first &&
             "c:\Users\henrique\Documents\_minhas-coisas\_Faculdade\TesteVSCode\C\"first
             'gcc' n�o � reconhecido como um comando interno
             ou externo, um programa oper�vel ou um arquivo em lotes.

[Done] exited with code=1 in 0.188 seconds

O First é o nome do arquivo.c
Comment: Tente com a extensão c/c++  esse plugin ... na documentação é indicado ele em vez do core runner. tentei no linux com gcc e funcionou de boas.
Answer: Crie uma variável de ambiente no PATH com o caminho para o gcc. O PATH é uma variável do sistema usada pelo sistema operacional para localizar executáveis que serão utilizados por linha de comando.
Seguem as instruções:
Sistema  → Config. Avançadas do Sistema  → Variaveis de Ambiente → Adicionar no path a variável em questão
Comment: Alterei e só mudou o erro... Agora ele aponta que não pode abrir o arquivo por falta de permissão.

[Running] cd "c:\Users\henrique\Documents\_minhas-coisas\_Faculdade\TesteVSCode\C\" && gcc first.c -o first && "c:\Users\henrique\Documents\_minhas-coisas\_Faculdade\TesteVSCode\C\"first
C:/mingw-w64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot open output file first.exe: Permission denied
collect2.exe: error: ld returned 1 exit status

[Done] exited with code=1 in 0.193 seconds
Comment: já tentou executar como administrador?
Comment: Não tinha tentado, mas tentei agora e o arquivo só da que parou de funcionar. Até criei um novo arquivo pra ver se era com aqueles o problema mas continua o mesmo aviso, sem permissão.


CSS Footer with an overflow scrollbar

Question: I suppose the easiest way to show this would simply be to give a link to the website where it needs to be added.
I NEED a simple footer that is always stuck at the bottom of the page, no matter how much content is placed within the main CONTENT and SIDEBAR divs.
I've tried using the sticky footer, and a few other methods. Such as putting it at the bottom of the page with bottom 0, etc.. But, with my setup it never seems to work. If you need anymore information feel free to ask.
Comment: Hi. I am a bit unsure what you are trying to accomplish here. As I understand, you want a bottom bar kind of thing that is scrollable ?
Comment: kindly give the information clearly wat u want to be fixed.
Comment: I need a footer, a simple footer for the copyright and referral links of the site. Like any other site has, but the problem is.. It never sticks at the bottom of the page no matter what I do.
Answer: change the css of your site to this one...this may help you...
#Wrapper {
    color: #FFFFFF;
    min-height: 100%;
    overflow: auto;
    width: 100%;
    z-index: 6;
}
#Banner {
    height: 169px;
    position: relative;
    top: 0;
    width: 100%;
}
#Navbar {
    background-color: #666666;
    color: #FFFFFF;
    float: left;
    height: 35px;
    position: relative;
    width: 100%;
}
#Outer {
    float: left;
    height: auto;
    margin-top: 35px;
    width: 100%;
    z-index: 2;
}
#Sidebar {
    background-color: #00FF00;
    float: left;
    margin-left: 10px;
    min-height: 600px;
    width: 12.5%;
}
#Content {
    background-color: #00FF00;
    float: right;
    margin-right: 10px;
    min-height: 65%;
    width: 85%;
}
#Copyright {
    background-color: #FF3333;
    float: left;
    height: 35px;
    width: 100%;
    z-index: 20;
}

Comment: That is the same problem as the one above, it is a fixed footer. I also uploaded an example of what that would come out as on my website. I need something that is on most major websites, the footer that is always at the bottom of the page no matter how much content is added. But it is at the bottom of the page, not stuck to the bottom of the view port, if that makes sense.
Comment: mostly dont use position:absolute; the problem is becos of float and absolute only...
Answer: Ok what you want is a css class that looks more or less like this.
EDIT
.MyBottomBasicClass {
     position: relative;
     bottom 0;
     margin: 0 auto;
     padding: 0;
     Width: 100%;
     height : 300px // or whatever...
     overflow-x: hidden;
     overflow: scroll;
 }

EDIT
You also need to wrap your other content.
.wrapper{
    min-height: 100%;
 }

and...
html, body {height: 100%;}

now in your html...

         //       your site content

         // here you enter all the information you may need to include copyright  information

Comment: Well, if I placed a 'fixed' position it would always be there no matter where I scrolled. Which isn't what I am looking for. The big trick is getting it to ONLY show up when you've scrolled to the bottom of the page. Using a FIXED position causes it to always be at the bottom of the view port, which isn't really a footer per say.

Also, I uploaded the example of a basic 'FIXED' position footer to the website.
Comment: what happens With the new changes ?
Comment: I uploaded the new changes, and you can see them on the site. Basically the same problem, only it is stuck to the top of the page now.
Comment: Thank you for the assistance, and the attempts. ^^
Comment: its a pleasure, I had to try. remember to upvote the answer! I'll upvote you to get rid of that negative vote
Comment: Thanks, and yeah.. I'd give you a useful answer if I could. Either way, thanks. ^^

CSS Footer with an overflow scrollbar


How to iterate through a mysql array and append corresponding text from an PHP array

Question: I am making a pricing table to upgrade membership.
In mySQL I have a table with limits on what each membership can allow see picture
I grab the info from the table and try to iterate through it and append some text to it from another array. I have tried thoroughly looking online for an answer but I'm probably not even searching for the right terms. For the purpose of this question i'm using 2 fields but in reality i will be iterating and appending many columns.
Here's my code:
$sql = "SELECT maxProducts,maxImages FROM memproducts_membership_settings WHERE useThis='1'";

$rs = mysql_query($sql);

while($row = mysql_fetch_array($rs,MYSQL_ASSOC))
{
    foreach($row as $field)
    {
        $append = array('Product Slots','Images per product');
        print $field.' '.$append.'
';
    }
}

All i get is:
5 Array
2 Array
and not what i need which would be:
5 Product Slots
2 Images per product
I'm sure there is a way to do this but i just cannot figure it out, please anyone give me some pointers? Many regards :)
Comment: There is no any "mysql array". Every array in php - is a php array.
Answer: To append values to the end of an array use array_push()
http://php.net/manual/en/function.array-push.php
Answer: This is pretty basic stuff...
while($row = mysql_fetch_array($rs,MYSQL_ASSOC))
{
    echo $row['maxProducts'] . ' Product Slots
';
    echo $row['maxImages'] . ' Images per product
';
}

Or if you are needing to do this with dynamic fields in whatever order you return from database like your question suggests, perhaps you might consider providing a mapping of database column names to the appropriate label content like this:
$labels = array(
    'maxProducts' => 'Product Slots',
    'maxImages' => 'Images per product',
    ...
);

...

while($row = mysql_fetch_array($rs,MYSQL_ASSOC)) {
    foreach ($row as $key => $value) {
        echo $value . ' ' . $labels[$key] . '
';
    }
}

Note if you are just learning PHP, you REALLY should NOT learn mysql_* functions.  They are deprecated and need to die.  Please learn to use PDO or mysqli.
Comment: I work 60 hrs a week as a taxi driver and have for the last 5 months neglected my little cms that i'm writing so i dont have to pick up idiots for a living. This answer worked for me and i truly appreciate the pointers and advice. i'll be looking into replacing the deprecated code for the newer stuff. sanitation is one subject i have considered in depth and feel i have covered but will look into it further. many many thanks
Answer: There's plenty about your code and your approach that I don't like at all, but the most immediate solution to your current problem would be to iterate the array of strings from within the foreach loop, using each():
$strings = array('Product Slots','Images per product');
while($row = mysql_fetch_array($rs,MYSQL_ASSOC))
{
    reset($strings);
    foreach($row as $field)
    {
        $append = each($strings);
        print $field.' '.$append[1].'
';
    }
}

You should at very least make yourself aware of:

the deprecation of ext/mysql (use either mysqli or PDO); and
the risk of XSS attacks (escape any HTML in values from your database before returning them to the browser).
Answer: It's doing what it should... You have created an array and asked it to print its name. As print can't automatically iterate an array it just tells you what the variable type is.


O que realmente significa "from modulox import *"

Question: Até onde eu sei isso importa todas as classes e funções de um certo arquivo sem precisar referenciá-lo no código, certo? Porém estou começando achar que from modulo import * não significa isso.
Eu estava estudando a biblioteca tkinter e me deparei com a seguinte situação:
from tkinter import *
from tkinter import colorchooser

Se no primeiro import já usou o *, por que precisaria importar o colorchooser de novo? Na verdade aparentemente o colorchooser nem foi importado.
Se eu tentar usar o colorchooser sem usar a segunda linha ele simplesmente diz que não está definido. Por que precisa importar duas vezes o colorchooser?
Answer: Você não importa duas vezes. O uso do asterisco não significa necessariamente que você irá importar todas as classes, funções ou variáveis disponíveis dentro de um módulo. Aí temos dois casos...

Não foi definida a variável __all__ em arquivo __init__.py, daí o Python carregará tudo o que estiver definido lá dentro (o que não pode ser o melhor dos comportamentos), ou
Importar tudo aquilo que é considerado necessário e que foi definido dentro de __all__, o que te dá muito mais controle sobre o que está sendo carregado.

Por exemplo você tem um módulo chamado modulo e no diretório dele há dois arquivos, um contendo as classes, o somas.py:
class Media:
    ...

class Soma:
    ...

E o outro o __init__.py que, inclusive, assinala que este diretório é um módulo:
__all__ = ("Media",)

from .somas import Media, Soma

Neste cenário se você fizer:
>>> from modulo import *
>>> a = Media()
>>> b = Soma()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Soma' is not defined

Você não consegue usar a classe Soma pois apenas Media foi carregada automaticamente.
Sendo necessário fazer a carga dela manualmente (neste caso somente da classe Soma):
>>> from teste import Soma
>>> b = Soma()

Ou, dependendo do caso, acrescentando-a dentro de __all__.
Comment: Não sei se entendi direito, então quando se faz um import de uma biblioteca, ao usar o *, ele importa tudo que estiver no arquivo __init__.py dessa pasta? então o tkinter não seria um arquivo "tkinter.py" mas uma pasta?
Comment: O asterisco no caso que estamos falando, vai importar o `__init__.py` do pacote (pasta) `tkinter` **se ele existir**. Mas o asterisco por si só, importa os dados apenas do módulo especificado, como eu disse na minha resposta https://pt.stackoverflow.com/a/440593/157404
Answer: Utilizar o asterisco (*) irá sim importar todos os dados (variáveis, funções e classes) do módulo que você especificou no from, não tendo outra finalidade.
O que acontece, é que ao fazer from tkinter import *, você está importando do pacote tkinter o arquivo __init__.py. E diferentemente do que você pensa, o colorchooser não está dentro do arquivo que você importa, pois ele é um outro módulo dentro do pacote.
Logo, se você apenas realizar a primeira importação, você não poderá acessar o colorchooser e consequentemente será gerado um NameError.
from tkinter import *             # Aqui você importa tudo do __init__.py
from tkinter import colorchooser  # Aqui você importa o módulo colorchooser.py do pacote

Você pode comprovar que o colorchooser é um módulo utilizando a função help.
>>> help(colorchooser)
Help on module tkinter.colorchooser in tkinter:

NAME
    tkinter.colorchooser
...

Veja aqui o conteúdo do pacote. Você também pode ver o conteúdo indo para o diretório <python_path>/lib/tkinter ou executando help(tkinter) para olhar a documentação.
Comment: Seria legala crescentar na resposta que a recomendação é __nunca__ usar `from x import *`: isso dificulta a manutençao (você não sabe de onde uma variável u função se originou), e atrapalalha inclusive as funcionalidades de auto-complete das IDEs - além de ter uma chance grande de conflito de nomes.
O ideal é ou importar todos os nomes explicitamente, ou importar o módulo, possivelmente com um nome encurtado - e usar sempre o prefixo. Por exemplo: `import tkinter as tk; button=tk.Button(...)`
Comment: Neste caso, se o __init__.py n existisse. ele importaria tudo da pasta tkinter?
Comment: Não, apenas importaria o pacote com suas informações. Você mesmo pode fazer esse teste criando seu próprio pacote e colocando ou não o arquivo `__init__` para ver no que resulta.
Comment: So mais uma duvida, se tiver um pacote e dentro desse pacote tiver uma pasta. Ao importar ele usando asteristo essa pasta seria importada tbm?
Comment: Não. Vamos dizer que há a pasta `modulo2` dentro de `modulo1`. Nesse caso a importação para obter **somente** os dados do `modulo2` seria `from modulo1.modulo2 import *`. A não ser é claro que você já fizesse um importação com o `__all__` dentro do `modulo1`.
Comment: Muito obrigado, aparentemente tenho muita coisa ainda a aprender haha


Como receber dados do Angular em um arquivo (de rota) PHP

Question: 0
votar contra
accept
Amigo, agora deu certo, mas fiquei com uma dúvida... Com relação à acentuação, ele não está aceitando acentuação.
Já tentei das formas abaixo, mas não teve jeito:
var config = {
        headers : {
            'Content-Type': 'application/json;charset=iso-8859-1'
        }
    };
var config = {
        headers : {
            'Content-Type': 'application/json;charset=utf-8'
        }
    };
Comment: Começa estudando [xmlhttprequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest), ajax, e o modulo [$http](https://docs.angularjs.org/api/ng/service/$http) do angular. No seu caso vai precisar usar o modulo $http para enviar os dados para a URL/rota do php que vai processar ela.
Comment: O meu envia com acentuação e tudo. Se puder enviar o PHP para eu ver como você ta recebendo ele. Mas provavelmente deve ser algum ajuste que deve ser feito no PHP.
Answer: O angularjs é um framework client-side, e como você deve saber o PHP é server-side, então isso daqui nao existe: $titulo = '{{livro.titulo}}'.  Você tem que passar via $http esse valor para o PHP -> https://docs.angularjs.org/api/ng/service/$http.
Segue um exemplo que fiz em um aplicativo:
<code>$scope.salvar = function(lista)
{
    var config = {
        headers : {
            'Content-Type': 'application/json'
        }
    };

    var data = lista;

    $http.post( Url.link + 'adicionar', data, config).success(function(res){
        alert('Cadastrado com sucesso');
    });

    $scope.lista = { lis_nome: '', lis_cpf: '', lis_animal: '', lis_descricao: '' };
};
</code>
eu pego informações de um submit de um formulario e envio via $http.post.


Should I use the optional context parameter if I don't use `this` keyword in the callback?

Question: when using the multitude of utility functions that can accept it.  For example:
<code>function foo () {
    _.each ([0,1,2,3], function(val) {
        // I don't use this in the body
    }, this);
}
</code>
It seems like one way is more concise and the other is there in case you add code later.
Comment: No, you shouldn't use it if you don't need it.
Answer: The optional parameter adds the context, in other words what 'this' refers to within the callback.
You only need to add it if you want it that way. If you're using a library like backbone, it can come in very handy (eg. when the function is called from within a view object, and you want 'this' to refer to the view).
Answer:
It seems like one way is more concise

Then use that.

in case you add code later.

You ain't gonna need it. Not until later, at least.
Comment: that's the way I'm leaning, plus it keeps some other dev from going hey ... you don't need that there and then have to explain why it is there.


CentOs vhost shows default apache page

Question: I'm using CentOs 6.2. On this server I want to host 1 website. I created a vhost in httpd.conf. You can see the setup below.
The problem is that when I go to the domain I get the apache default page. I have restarted the httpd deamon. Does anyone know what I might be doing wrong?
NameVirtualHost *:80

<VirtualHost *:80>
    ServerAdmin helpdesk@***.nl
    DocumentRoot /var/website
    ServerName ***.nl
    #ServerAlias www.***.nl
    ErrorLog logs/***.nl-error_log
    CustomLog logs/***.nl-access_log common
</VirtualHost>

EDIT:
I checked the logs:
Access log:
220.127.116.11 - - [27/Nov/2012:20:37:10 +0100] "GET / HTTP/1.1" 403 5039
184.108.40.206 - - [27/Nov/2012:20:37:11 +0100] "GET /favicon.ico HTTP/1.1" 403 295

Error log:
[Mon Nov 26 22:37:46 2012] [error] [client 184.108.40.206] (13)Permission denied: access to /index.php denied
[Mon Nov 26 22:37:46 2012] [error] [client 126.96.36.199] (13)Permission denied: access to /index.html denied
[Mon Nov 26 22:37:46 2012] [error] [client 184.108.40.206] (13)Permission denied: access to /index.html.var denied
[Mon Nov 26 22:37:46 2012] [error] [client 18.104.22.168] (13)Permission denied: access to /favicon.ico denied

Permissions:
[root@srv2 website]# ls -la
total 17536
drwx------ 10 kvdp kvdp     4096 Nov 26 23:01 .
drwxr-xr-x 20 root root     4096 Nov 26 22:30 ..
-rw-r--r--  1 kvdp kvdp       37 Nov 26 22:31 35a12fb7ab5a.html
-rw-r--r--  1 kvdp kvdp      515 Nov 26 22:31 400.shtml
-rw-r--r--  1 kvdp kvdp      515 Nov 26 22:31 401.shtml
-rw-r--r--  1 kvdp kvdp      515 Nov 26 22:31 403.shtml
-rw-r--r--  1 kvdp kvdp      515 Nov 26 22:31 404.shtml
-rw-r--r--  1 kvdp kvdp      515 Nov 26 22:31 500.shtml
-rw-r--r--  1 kvdp kvdp 17816103 Nov 26 22:41 admin_kvdp.sql
drw-r--r--  2 kvdp kvdp     4096 Nov 26 22:31 _api
drw-r--r-- 13 kvdp kvdp     4096 Nov 26 22:33 beheer
drw-r--r--  2 kvdp kvdp     4096 Nov 26 22:33 cgi-bin
drw-r--r--  2 kvdp kvdp     4096 Nov 26 22:31 _config
-rw-r--r--  1 kvdp kvdp      728 Nov 26 22:31 controller.inc.php
-rw-r--r--  1 kvdp kvdp      813 Nov 26 22:31 controller.view.inc.php
-rw-r--r--  1 kvdp kvdp       53 Nov 26 22:31 google3f6160378ab03426.html
-rw-r--r--  1 kvdp kvdp      611 Nov 26 22:31 .htaccess
-rw-r--r--  1 kvdp kvdp     1978 Nov 26 22:31 index.php
drw-r--r--  3 kvdp kvdp     4096 Nov 26 22:31 _libs
drw-r--r--  6 kvdp kvdp     4096 Nov 26 22:31 _models
-rw-r--r--  1 kvdp kvdp      232 Nov 26 22:31 robots.txt
-rw-r--r--  1 kvdp kvdp       11 Nov 26 22:31 test.php
drw-r--r--  4 kvdp kvdp     4096 Nov 26 22:35 upload
drw-r--r--  5 kvdp kvdp     4096 Nov 26 22:31 _views

Comment: Have you put an index.html at /var/website yet?
Comment: @AdamBatkin That shouldn't be needed. I would have a look at the web server logs to see which virtual host the request is routed to.
Comment: personally, you are making this harder then it needs to be. no need for a vhost. simply dump your "web site" into your docu root directory.
Comment: Apache (at least with CentOS) comes with a module which displays the default page whenever there is no index.html. Also, you can try requesting a specific filename (like http://whatever/somefile.html) and see if that works
Comment: I already disabled SELinux. SO SELinux can't be the problem. I updated my post and added the logs and permissions
Answer: First check that the user account that Apache is running as has access to your website folder (it will also need traverse access to all folders above it in the path):
ps aux | grep httpd

You should see lines like:
apache    1336  0.0  1.1 282772  6008 ?        S    03:24   0:00 /usr/sbin/httpd
apache    1338  0.0  1.1 282772  6008 ?        S    03:24   0:00 /usr/sbin/httpd

The first column is the user account that needs to have access to your folders.
If that all looks good, check if you're running SELinux. If so, your /var/website directory is probably still under the default_t security context. Check it with:
ls -Z /var/website

You will probably see something like this:
drwxr-xr-x  root root user_u:object_r:default_t        website

If so, you can change the security context with the chcon command:
chcon -Rv --type=httpd_sys_content_t /var/website

Alternatively, you can disable SELinux for Apache (as root):

Edit /etc/selinux/targeted/booleans and set httpd_disable_trans equal to 1.
Run setsebool httpd_disable_trans 1 to ensure the boolean is set for your current session.
Restart apache with service httpd restart.

Or, if this is a development server and you don't care to run SELinux, you can effectively disable it by setting it to "permissive" mode (as root):

Edit /etc/selinux/config and set SELINUX equal to permissive.
Reboot.
Run getenforce to verify SELinux is in permissive mode.

In your case, the problem is this line:
[root@srv2 website]# ls -la
total 17536
drwx------ 10 kvdp kvdp     4096 Nov 26 23:01 .

This means that only your user account (kvdp) has access to the folder. Run the following command within your /var/website folder to rectify the situation:
chmod go+rx .

Comment: Please don't disable SELinux. Set it to 'permissive', but leave it enabled. If you disable it and later want to enable it, even in permissive mode, you'll have a bad time.
Comment: @John: Answer edited, though I have to play devil's advocate here and ask: Why would anyone *want* to re-enable SELinux? :)
Comment: Granted, I haven't put SELinux back into enforcing mode -ever-, but it's not beyond imagination that some poor depraved soul would want to. For example, the people maintaining it...
Comment: I already disabled SELinux. SO SELinux can't be the problem. I updated my post and added the logs and permissions
Comment: @Bernhard: See my edit. You have a permissions problem, run the command at the end of my answer to fix it.
Comment: @Justinᚅᚔᚈᚄᚒᚔ I ran the command you mentioned but I'm still getting the default page
Answer: There are a couple potential issues here. Like Adam said, you may just need an index.html file in /var/website. Since that isn't a default directory, you may also need to check permissions on that directory (you'll get the error page if the httpd process can't read files therein). The last thing I can think of that you've got SELinux in enforcing mode and that directory isn't labeled with the correct context.
Comment: I already disabled SELinux. SO SELinux can't be the problem. I updated my post and added the logs and permissions
Answer: You've got php5 installed, right? If you don't apache can't serve PHP pages and you'll bounce back to a default "Welcome to Apache!" page.
I haven't used CentOS anything in a bit, so I'm a bit rusty. Aren't the web files supposed to be owned by the webserver user, or at least readable by the apache user? If the webserver can't read the file it might also explain the behaviour you're seeing. Looks like that from your logs. Web server is getting access denied to your web directory.
Comment: Yes, I've got PHP5 installed so that's not the problem. And if I'm not mistaken, the files are readable for apache

CentOs vhost shows default apache page


Help me determine if ℂ= is a vector space over ℂ

Question: I need help determining if for b∈ℂ, b≠0, ℂ= is a vector space over the field of complex numbers
Thanks
Comment: Is your question whether $\mathbb{C}$ is a vector space over itself or not?
Comment: I think the question is if any non-zero complex number can produce the vector space ℂ over the field of complex numbers.Sorry for not being clear, the way the question was given confused me as well
Answer: For any $b\in \mathbb{C}, b\neq 0$, $b$ is indeed a basis of the $\mathbb{C}$-vector space $\mathbb{C}$ since this vector space has dimension one and $\{ b\}$ is linearly independent (i.e., $b\neq 0$). To make sure that $b$ produces all of $\mathbb{C}$ note that $\forall c \in \mathbb{C}, \exists ! \alpha \in \mathbb{C}, c=\alpha b \left( \alpha =\frac{c}{b} \right)$.
Note that this is no longer true if you look at $\mathbb{C}$ as an $\mathbb{R}$-vector space (because it has dimension $2$ so you would need two linearly independent vectors at least).


Coefficients of $(x-1)(x-2)\cdots(x-k)$

Question: I'm interested in the coefficients of $x$ in the expansion of,
$$ (x-1)(x-2)\cdots(x-k) = x^k + P_1(k) x^{k-1} + P_2(k)x^{k-2} + \cdots + P_k(k),$$
Where $k$ is an integer. In particular I am interested in thinking of these coefficients as polynomials in $k$.
Its not to hard to show that,
$$ P_1(k) = -\sum_{i=1}^k i =-k(k-1)/2 $$
 $$ P_2(k) = \sum_{i=2}^k i \sum_{j=1}^{i-1} j = k^4/8 + k^3/12-k^2/8-k/12$$
And I am pretty sure that $$ P_n(k) = (-1)^k\sum_{i_1=n}^k i_1 \sum_{i_2=1}^{i_1-1}i_2 \sum_{i_3=1}^{i_2-1}i_3\cdots i_{n-1}\sum_{i_n=1}^{i_{n-1}-1}i_n$$
I haven't gotten around to proving it but it works for $P_1$, $P_2$ and $P_3$ which gives me some confidence in the formula. For the purpose of this question assume that the formula works in general.
The last polynomial is a bit awkward because $P_k(k) = (-1)^kk!$ meaning that the coefficients are heavily dependent upon $k$ and somewhat ill defined. However I am primarily interested in $P_n$ when $n<k$.
My questions are the following,

Is there a simple formula for the coefficients of $P_n(k)$.
Is there a tight upper bound $M_k \geq P_n(x)$ for $x=1,2,\ldots,k$ which holds for all $n$.
I would also be interested in an upper bound on the coefficients if their explicit form is unavailable.
Answer: It is the Stirling  numbers of the first kind.

By definition they are the coefficients in the expansion
$(x)_n = \sum_{k=0}^n s(n,k) x^k,$
where $(x)_n$ is the falling factorial
$(x)_n = x(x-1)(x-2)\cdots(x-n+1).$

So  $P_n(k)=s(n+1,k).$
Answer: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\down}{\downarrow}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\fermi}{\,{\rm f}}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\half}{{1 \over 2}}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\ol}[1]{\overline{#1}}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
$$
\sum_{k = 0}^{n}a_{k}x^{k} = \sum_{k = 0}^{n}\left[k!\,a_{k}\right]\,{x^{k} \over k!}
$$
Then,
$$
a_{k}
=
\left.{1 \over k!}\totald[k]{\pars{\sum_{k = 0}^{n}a_{k}x^{k}}}{x}
\right\vert_{x\ =\ 0}
$$
In your case, the 'simple formula' you are looking for is given by:
$$
P_{i}
=
\left.
{1 \over \pars{k - i}!}\totald[k - i]{\bracks{\pars{x - 1}\ldots\pars{x - k}}}{x}
\right\vert_{x\ =\ 0}
$$

Coefficients of $(x-1)(x-2)\cdots(x-k)$


Log de Banco SQL em Restoring Pending

Question: Tenho um banco SQL que foi acessado por alguma outra pessoa e ele entrou em "Restoring Pending" assim que acessaram. Existe alguma forma de extrair algum log ou qualquer outra maneira mais detalhada de saber como, quem e quando foi feito?
Answer: O SQL Server tem um log dessas ações, no caso do restore, na tablea restorehistory.
Aqui uma query que vai mostrar o último restore para cada database, deve te ajudar:
WITH LastRestores AS
(
SELECT
    DatabaseName = [d].[name] ,
    [d].[create_date] ,
    [d].[compatibility_level] ,
    [d].[collation_name] ,
    r.*,
    RowNum = ROW_NUMBER() OVER (PARTITION BY d.Name ORDER BY r.[restore_date] DESC)
FROM master.sys.databases d
LEFT OUTER JOIN msdb.dbo.[restorehistory] r ON r.[destination_database_name] = d.Name
)
SELECT *
FROM [LastRestores]
WHERE [RowNum] = 1

Créditos: how-to-query-last-restore-date-in-sql-server

Log de Banco SQL em Restoring Pending


Why doesn't this definition of natural numbers hold up in axiomatic set theory?

Question: I was reading about older definitions of the natural numbers on Wikipedia here (in retrospect, not the best place to learn mathematics) and came across the following definition for the natural numbers: (paraphrased)

Let $\sigma$ be a function such that for every set $A$, $\sigma(A) := \{ x \cup \{ y \} \mid x \in A \wedge y \notin x \} $. Then $\sigma(A)$ is the set obtained by adding any new element to all elements of $A$. Then define $0 := \{ \emptyset \}$, $1 := \sigma(0)$, $2 := \sigma(1)$ et cetera.

The way I understood this definition is that the natural number $n$ is "defined" as the set of all sets with exactly $n$ elements. This sounded straightforward to me, until I read the next paragraph:

This definition works in naive set theory, type theory, and in set theories that grew out of type theory, such as New Foundations and related systems. But it does not work in the axiomatic set theory ZFC and related systems, because in such systems the equivalence classes under equinumerosity are "too large" to be sets. For that matter, there is no universal set V in ZFC, under pain of the Russell paradox.

Why exactly doesn't this definition work in ZFC? I don't fully understand how the sets in this definition are "too large". Is part of the problem just that there is no "universal set" to pick the element $y$ from?
I tried to do some more reading to find my answer, but the material was way out of my depth. (I am only familiar with the basics of set theory, Russell Paradox, Cantor diagonal argument, and not much more. ) So I apologize in advance if this is a really simple question...
Comment: Wikipedia is a great place to learn mathematics.
Comment: @MartinArgerami I've personally seen very few issues with the *mathematical* articles on Wikipedia (other topics notwithstanding). You'll find mistakes and typos in any reference. I've seen mathematics textbooks that are full of typos (and unlike Wikipedia it's impossible for them to be fixed once the book is printed).
Comment: @asmeurer: The trouble with learning from Wikipedia is not that it claims wrong things, but that its information is often not structured in a way that makes learning easy. Many articles are written on the level of highest possible abstraction and generalization, which is not really what a newcomer to the topic needs. (E.g., I'll challenge you to find anyone who after reading the [scheme (mathematics)](https://en.wikipedia.org/wiki/Scheme_%28mathematics%29) article has any better understanding of _what a scheme is_ and what one can do with one than he had before he started reading).
Comment: Just to pre-emptively forestall a common misunderstanding: "type theory" in this quote means Russell's original type theory, *not* the later systems coming from the work Church that are the main things known as "type theory" studied today.
Comment: @asmeurer: most often, but there are also many articles that have expository flaws and/or mistakes.
Comment: Wikipedia is much like a traditional technical encyclopedia in this respect. It's not a textbook, and learning a complex topic *just* from Wikipedia would generally be very difficult; but it's an excellent source to use *alongside* a good textbook.  The textbook gives a good ground-level path through a subject; Wikipedia gives an atlas showing how ideas connect to each other and to different topics outside the scope of the textbook.
Answer: "Too large" is an informal description of what goes wrong, and is not entirely on point for understanding how ZFC doesn't allow you to do this.
It would be more honest to describe the problem as

There is simply no axiom in ZFC that will let you conclude that the notation $\{ x \cup \{y\} \mid x\in a, y\notin x\}$ describes any set that exists.

Remember that ZFC doesn't support free-wheeling use of the set builder noation which assumes that $\{y\mid \phi(y) \}$ (where $\phi$ is some logical formula) always describes a set. Instead you have only separation which tells you that expressions of the form $\{y\in A\mid \phi(y)\}$ describe sets, and replacement which tells you that expressions of the form $\{F(y)\mid y\in A\}$ -- where $F$ is some function that you can define by a logical formula -- are sets.
However, $\{ x \cup \{y\} \mid x\in a, y\notin x\}$ doesn't have this form -- instead it would fit the scheme $\{ F(y) \mid \phi(y) \}$, and neither Separation nor Replacement promises to work for that situation.
(If you haven't seen the axioms of ZFC written down, it would probably help your understanding to seek out an explanation of them. In particular, what I describe as, for example, "$\{y\in A\mid \phi(y)\}$ exists" is formally described by saying that for any formula $\phi(y)$ that doesn't contain $x$, the formula
$$ \exists x.\forall y.(y\in x \iff y\in A \land \phi(y)) $$
is an axiom).

The "too large to be a set" is at most a hint at an answer to a different question, namely

Why can't we just have some more axioms that say we can do this?

The answer to this is that we can actually prove that $\{x\cup \{y\}\mid  x\in A, y\notin x\}$ does not exist (which is different from not being able to prove that it does) -- so if we had an axiom that claimed that it did exist, the system would become inconsistent.
In more detail, the proof might go: Suppose that for some set $A$,
$$\sigma(A) = \{x\cup \{y\}\mid x\in A, y\notin x\}$$
exists. Then $\bigcup A \cup \bigcup\sigma(A)$ -- which must exist due to ZFCs explicit Axiom of Unions -- would be a set that contains all elements of $A$, as well as all elements of elements of $A$, as well as every set that is in neither of these groups. In other words, this would be a set of all sets, and then Russell's paradox would lead us to a contradiction.
Presenting only this second argument, without explaining (or stressing) the first one, is a common failing of semi-popular descriptions of set theory. It can easily give a reader the impression that something must be allowed unless we can see it leads to a paradox, which is most definitely not how axiomatic set theory works. Axiomatic set theory works by saying from the beginning, "these are the things that are allowed" and then hoping no combination of those things lead to a paradox.
The only real value of the "if you could do this, it would lead to a paradox" argument is that once you see it you can stop trying to figure out a way that it is allowed.
Answer: Notice that, under that definition, we have
$$
\begin{split}
1 = \sigma(0) &= \sigma(\{\emptyset\}) = \{x \cup \{y\} : x \in \{\emptyset\} \land y \not \in x\} \\
&= \{ \emptyset \cup \{y\} : \text{y is a set}\}\\
& = \{ \{y\} : y \text{ is a set}\}\\
&= \{ z : |z| = 1\}.
\end{split}
$$
In ZFC, the collection of all sets ("$V$") does not form a set, so the definition breaks down already at stage $1$. If $\sigma(0)$ was a set then $V = \{y : \{y\} \in \sigma(0)\}$ would also be a set. So that is really the technical difficulty. Frege and Russell proposed that the number $1$ could be defined to consist of all $1$-element sets, but that collection of sets is not itself a set in ZFC.
The usual way of describing why $V$ is not a set is that it is "too large"; this sense of "largeness" is one of the more common ways of motivating the ZFC axioms, so the Wikipedia author alluded to it.
The idea of "largeness" is really an allusion to the "cumulative hierarchy" vision of set theory.  Unfortunately, the cumulative hierarchy is hard to describe in one sentence, because it depends already on the notion of ordinal. But the idea is that we can form a collection of sets stage by stage, so that the powerset of each set is formed at the next stage after the set is formed, and so that all the members of each set are formed at stages strictly before the set itself is formed.
One way to understand the ZFC axioms is that they are only trying to describe the sets that are formed via this process. But $V$ cannot be formed at any stage, because it would have to already contain its powerset, but the powerset ought to be formed at the next stage.  So the claim that $V$ is too "large" really means that $V$ could not be formed at any stage of the process.
Back to defining the numbers. We can imagine that two sets have the same cardinality if there is a bijection between them. This is an equivalence relation, so it ought to have equivalence classes. And the equivalence class of $\{\emptyset\}$ will consist of every set that has exactly one element. That is the idea behind the definition above. But these equivalences classes are not sets in the cumulative hierarchy, so ZFC has trouble with them.
The way that we usually circumvent this kind of problem in ZFC is to select a "particular" representative from each equivalence class. Then, instead of referring to the entire equivalence class, we refer just to that representative. The most commonly use set of representatives in ZFC are the von Neumann ordinals. So we have
$$
\begin{split}
0 &= \emptyset\\
1 &= \{\emptyset\} = \{0\}\\
2 &= \{\emptyset, \{\emptyset\}\} = \{0,1\}\\
3 &= \{0,1,2\}
\end{split}
$$
and so on. This is not really much different than the definition due to Frege and Russell, as you can see.


How do I find what content is supplying my current page?

Question: I have a webpage on my site that doesn't have edit tabs, so I am not sure where this website is retrieving content. How can I find out what content represents this webpage? I am using Drupal 7.
Comment: Inspecting CSS classes on the body and content wrappers often help to identify what module produced it (unless it's custom, then it's up to whoever developed it to add those classes)
Comment: Check page path in views and panels, may be the page is coming from there.
Comment: grep the site files for the page's path.
Answer: Take a look if you can see the contextual "settings wheel" in the top right corner.
This can provide you with a direct link to edit the "page"/"view" or Panel that you are on


How to call a C# static method from jQuery

Question: I've seen some articles showing how to call a C# method from JavaScript using Microsoft's [WebMethod] for a Web Forms application. I'd like to do the same with an ASP.NET MVC application. I have a C# static method that returns translated data:
public static string Translate(string word)
{
  return langRepo.Translate(word);
}

The above function works fine inside server-side code. However, I'd like to extend the same code to the client side. Ideally I would like to create a jQuery function like this:
function Translate(word) {
  //call C# translate method and return result
}

And use it like this:
"

" + Translate(heading) + "
";

How would I do this?
Comment: The you did not try correctly :)
Comment: Please add code, errors and data as **text** ([using code formatting](//stackoverflow.com/editing-help#code)), not images. Images: A) don't allow us to copy-&-paste the code/errors/data for testing; B) don't permit searching based on the code/error/data contents; and [many more reasons](https://meta.stackoverflow.com/a/285557). In general, code/errors/data in text format >>>> code/errors/data as an image >> nothing.  Images should only be used, *in addition to text in code format*, if having the image adds something significant that is not conveyed by just the text code/error/data.
Comment: You need to use ajax to call a server method
Comment: I already tried that. It doesn't work
Comment: add your ajax code and we would be able to correct that.
Comment: **AJAX is asynchronous**. `return t;` will immediately be executed after starting the AJAX call, but regardless of whether the call has completed or not (which means the success method has never had the chance to put anything into `t`). You need to look into using callback methods (this is a rather broad topic)
Comment: And here I thought this question was easy...
Comment: First of all, what do you see when you paste the url ".../api/translate/anyword" on to a web browser? You should get a json with translated word. In debug mode it should hit the api controller action.
Comment: When I type .../api/translate/word I get the translated word back "translated" (with quotes). The api gets hit when the ajax called is made. The problem is that I'm unable to "capture" this result and it has something to do with the nature of Asynchronous calls. My problem is that I'm treating it as a "synchronous" call which obviously it isn't.
Answer: Do the following:

Add  [WebMethod] on top of your function in server side.
Call from client side should be looking like the following snippet:

Hint: The type should be of type "POST". check this for complete example.
function Translate(word){
  // Type of data passed should match the function's parameters
  var data = {word: word};
  $.ajax({
    type: "POST",
    url: "pageName.aspx/Translate",
    data: data,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    },
    success: function (response) {
      // Here you can assign response to tags.
      // If response was empty, try response.d.
      $("#id").html(response);

    }
  });
}

If you are using an ASP.NET MVC application, you can use [HttpGet] instead and return the result from your function (Action) as in JSON format since we specified in our Ajax request we are expecting dataType: "json".
Below is an example:
[HttpGet]
public ActionResult Translate(String word)
{
  var resultWord = ModelInit.repo.TranslateItem(word);
  return Json(new {result = resultWord}, JsonRequestBehavior.AllowGet);
}

In the success handler in your Ajax call, get the value by accessing the result property:
success: function (response) {
  // Here you can assign response to tags
  $("#id").html(response.result);
}

Comment: Unfortunately this will not work. You're assuming my function is inside a ".aspx" page. I'm using MVC (No .aspx pages here). I created a Web API that "mimics" the function call but even this didn't work for me.
Comment: My function is inside another assembly I call "App.Services.Helpers":
Comment: namespace App.Services.Helpers
{
    public static class Utility
    {
        public static string CapitalizeFirst(string word)
        {
            // Check for empty string.
            if (string.IsNullOrEmpty(word))
            {
                return string.Empty;
            }
            // Return char and concat substring.
            return char.ToUpper(word[0]) + word.Substring(1);
        }

        [WebMethod]
        public static string Translate(string word)
        {
            return ModelInit.repo.TranslateItem(word);
        }
    }
}
Comment: Maybe I could go about this another way...  Let's say I create a Web API where I can pass the word and it will translate it for me like this: /api/translate/title and this API returns a string: "título". How can I grab this result and use it like this: heading = "" + translatedWord + "";?
Comment: your question was not clear enough as you mentioned "web forms" applications that is why I wrote this answer. if it is MVC application no need to decorate with [WebMethod] .. instead decorate with [HttpGet] and inside your function - return Json(new {id = 10, title="test"});
Comment: That still comes back as "undefined"
Comment: Whether I use "post" or "get", the function response on success is "undefined"
Comment: can you plz update your question by adding your complete server code
Comment: regarding your first question, use "get". no screenshots added, please make sure to update it again
Answer: Try the following. First a C# controller action that will return a json and then call controller action from a jQuery method.
public class LanguageController : Controller
{
    [HttpGet]
    public JsonResult Translate(string word)
    {
        var translatedWord = langRepo.Translate(word);
        return Json(translatedWord, JsonRequestBehavior.AllowGet);
    }
}

jQuery method:
function Translate(word){
    $.ajax({
        type: "GET",
        url: "/Language/Translate",
        data: {word: word},
        dataType: "json",
        cache: false,
        success: function (data) {
            if(data.length == 0) {
                alert("Cannot translate.");
            }
            else {
                // Get the translated word
                var translatedWord = data.translatedWord;

                // Update the DOM element (label) with translated word
                $("#translatedWord").text(translatedWord);
            }
        }
    });
}

Answer: For the first time in my years of programming, I've had to change an AJAX call to synchronous for it to work the way I wanted it. All that was needed was to add the "async: false" attribute to the AJAX call. This way the AJAX call is treated like any other synchronous function:
function Translate(word) {
    var Url = "/api/translate/" + word;
    var translated;

    $.ajax({
        type: "GET",
        url: Url,
        dataType: "json",
        cache: false,
        async: false,
        success: function (response, status, xhr) {
            translated = response.translatedWord;
        },
        error: function (jqXhr, textStatus, errorThrown) {
            var error = CapitalizeFirst(textStatus) + ": " + errorThrown + " - " + jqXhr.responseText;
            bootbox.alert(error);
        }
    });

    return translated;
}

For those of you thinking of implementing this as a solution for your project, THINK AGAIN!  Making an AJAX call synchronous is no trivial matter. Doing so will force your users into waiting for a response back from the server before the program is responsive again. Unless you're sure the data set is small and its access is not very frequent, you should look for other ways.
Comment: This is absolutely not the solution you should pursue. I can't see your screenshots, but it's clear you're doing something wrong somewhere, as you're hardly the first person to call a method asynchronously using jQuery (I literally did this earlier today). Secondly, this is probably not the approach you should pursue anyway if you're looking to translate webpages.
Comment: If you have a better solution, by all means, please post it!
Comment: It has to be!! There is an Ajax call inside another Ajax call. They will all get mixed up when executed asynchronously. The inner one needs to be synchronous.
Answer: I can't see your screenshots (imgur domain blocked for me) and you didn't post much of your code, so I will show you an example of how I did it, and I can update the answer to better answer your question later.
I called a stored procedure and used AJAX to insert the resulting data into my page.
First, I had an object in C# that held a start and end date. My model:
public class DateRange
{
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }
}

My data access layer (DateRepository), which calls my stored procedure (anonymized it a bit since it's not relevant to this question):
public static List<DateRange> GetDates(int number)
{
    // execute stored procedure, ORM converts the rows to a list of objects
    ...
    return dateRanges;
}

My service layer, which calls the data access layer:
[Route("Dates/{number}")]
public IHttpActionResult Get_DateRanges(int number)
{
    var response = DateRepository.GetDates(number);
    return Json(response);
}

The Json(result) is from System.Web.Http > ApiController > JsonResult<T> Json<T>(T content).
Now, my UI layer controller calling this service method:
public async Task<JsonResult> Get_DateRanges(int number)
{
    var response = await ServiceClient.HttpGetList<DateRange>([url here calling /Dates/{number} ]);
    return new JsonResult { Data = response, MaxJsonLength = Convert.ToInt32(WebConfigurationManager.AppSettings["MaxJsonLength"]), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

And that ServiceClient method (simplified, omitting authorization etc details):
public static class ServiceClient
{
    public static async Task<List<T>> HttpGetList<T>(string url)
    {
        using (var client = SetupHttpClient())
        {
            HttpResponseMessage response = await client.GetAsync(url);
            CheckResponse(response);

            var tList = await response.Content.ReadAsAsync<List<T>>();
            return tList;
        }

    }
}

Remember, this JSONResult is of List<DateRange>. This is what will be in the data field of the JSON.
Finally, the javascript code calling the UI controller method:
function updateDateRanges() {
    var nNumber = $("input#Number").val();
    var params = { number: nNumber };

    // note the JSON call is to the UI layer
    $.getJSON(ROOT + "UIController/Get_DateRanges", params, function (data) { })
    .done(function (data) {
        // change model values from server
        $("input#StartDate").val(data[0].StartDate);
        $("input#EndDate").val(data[0].EndDate);
    })
    .fail(function () {
        errorAlert("Error retrieving dates.");
    })

}

Note that the way I retrieve my dates (e.g. data[0].StartDate) is because I have a list of date range objects. Since you can call your function that returns the JSON separately (just as if I had typed in the URL for my service layer into my browser), it should be easy to see what that JSON data looks like.
From looking at your comments, it seems your problem is not at all what is stated in the original post, but a basic understanding of javascript's asynchronous nature. Consider the following example:

$("#output").click(function() {
    var inputText = $("#output").text();
    translateWord(inputText);
});

function translateWord(word){
    getTranslationFromServer(word);
}

function getTranslationFromServer(word) {
    // using setTimeout to simulate slow response (2 seconds) instead of AJAX request
    setTimeout(function(){
        $("#output").text("texto en español");
    }, 2000);

    $("#output").css('background-color', 'yellow');

}

English text

Notice that even though the setTimeout function is called first, what happens immediately is that the background changes to yellow, and 2 seconds later, the text is translated. That is due to the asynchronous nature of Javascript. While it's waiting on your AJAX call, it has moved on to the next line. So in your particular example, you set var t = "";, you make your AJAX call, and the next line is to return t;. So while you're waiting on your AJAX call, the program has moved to the next line, which says to return: exit this function and return this value to the caller. So you are exiting your function before it ever has a chance to finish.
Okay, so what you're real question is: "How do I wait for this javascript function to complete before returning to the other function?" Well, I originally suggested callbacks, but the better solution these days is to use promises. Since you seem to be using jQuery, I will use their promise library:

$("#output").click(function() {
    var inputText = $("#output").text();
    translateWord(inputText);
});

function translateWord(word){
    $("#output").text("waiting...");
    $.when(getTranslationFromServer(word))
 .then(
     function(word) {
      $("#output").text(word);
                $("#output").css('background-color', 'orange');
     }

    );
}

function getTranslationFromServer(input) {
$("#output").css('background-color', 'yellow');
    var deferred = new $.Deferred();
    var output = "";
    // using setTimeout to simulate slow response (2 seconds) instead of AJAX request
    setTimeout(function(){
        // mock translate function
        if (input === "English text") {
            output = "texto en español";
        }
        else if (input === "texto en español") {
            output = "English text";
        }
        else {
            output = "No translation for this text found."
        }
        deferred.resolve(output);
        }, 2000);

    return deferred.promise();
}

English text

I changed the background colors to hopefully help you follow along where in the code the javascript is. I believe this finally answers your XY question regarding javascript.
Comment: OK. Your solution is what I call "conventional" and is the way many of us developers do it every day. Your $.getJSON is writing out the values DIRECTLY to the DOM. BUT as you can see from the question (if you could see it) I want to know how to get the result of an AJAX call as a return value from a function that you can call in Javascript. This way, the function can be made generic (like Capitalizing the first letter) and used anywhere as needed and not just for a SPECIFIC USE CASE. Why do I need it this way? Because in this case I am calling it from INSIDE another AJAX function!
Comment: @KeithHarris My approach is beyond generic-- the data is inserted into the DOM because I'm displaying that data. That doesn't make anything any less general. If you need to call an async function from inside another one, it sounds like you need to read about how callbacks work in Javascript.
Comment: Your solution won't work for me because I don't know ahead of time what the DOM will be at run time. In fact, the DOM is built dynamically depending on what the user is allowed to access. I realize that this is an unusual case (as I've never had to do resort to this before) so I wondered if other developers out there have had a similar issue and how they solved it.
Comment: I tried using a callback function (also shown in the screenshot that you can't see) but it didn't work either.
Comment: @KeithHarris I have answered your questions with snippets demonstrating the proper way to wait on your AJAX call that should hopefully help your understanding of javascript. If you could do me a giant favor, it would be to edit your actual code into your original question, because it's a lot easier for you to copy/paste it than it is for me to re-type it from a screenshot on my phone. If you want me to actually use your code as an example, you need to post it for me.
Comment: @KeithHarris Also, please read about promises-- they will be helpful for you when you need to chain AJAX calls together, as you said in your original comment on my answer.
Comment: @KeithHarris Just pinging you again to see if you ever looked into using javascript/jQuery promises?


Editar banco de dados MySQL com php

Question: Estou fazendo um sistema de cadastro em php, e utilizando o mysql como db, já consegui fazer a pagina de cadastro e ela está funcionando normalmente. O problema é que agora preciso de que quando o cadastro seja criado seja gerado um link para editar e que ao clicar nele seja possível editar os dados no banco de dados.
O código que executa o cadastro:
 <?php
 /**
  * Created by PhpStorm.
  * User: Arnaud
  * Date: 22/05/2017
  * Time: 16:38
  */

 $nome = $_POST["txtnome"];
 $email = $_POST["txtemail"];
 $telefone = $_POST["txttelefone"];
 $senha = $_POST["txtpass"];
 $data = $_POST["txtdata"];
 $id = $_POST["id"];

 $con = mysqli_connect("localhost", "root", "");
 mysqli_select_db($con,"testeconstrusite");
 if (mysqli_connect_errno())
 {
     echo "Falha ao conectar ao servidor MySQL: " . mysqli_connect_error();
 }

 if(!empty($nome) && !empty($email) && !empty($telefone) && !empty($senha) && !empty($data) && !empty($id) && empty($id)) {
     mysqli_query($con, "insert into clientes (nome_cliente, email_cliente, telefone_cliente, senha_cliente, data_nasc_cliente) VALUE('$nome', '$email', '$telefone', '$senha', STR_TO_DATE('$data','%d/%m/%Y'))");
     $id_inserido = mysqli_insert_id($con);
     echo "Cliente inserido com id de número: $id_inserido
";
     echo "Para editar o usuário cadastrado clique aqui";
 }

 elseif(!empty($nome) && !empty($email) && !empty($telefone) && !empty($senha) && !empty($data) && !empty($id) && !empty($id)){
     mysqli_query($con, "update clientes set nome_cliente ='$nome', email_cliente='$email', telefone_cliente='$telefone', senha_cliente='$senha', data_nasc_cliente=STR_TO_DATE('$data','%d/%m/%Y') where id_cliente = '$id'");
 }

 else{
     echo "Preencha todos os campos!";
 }

A pagina do formulário:
      <!DOCTYPE html>

     <meta charset="UTF-8">
     <link type="text/css" rel="stylesheet" media="all"  href="estilos/estilo.css" />

     <title>Cadastro</title>

 <form action="cadastrar.php" method="post">

     <input type='text' name="id" class='campo' id="id" value="<?php if(!empty($_GET["id"])){echo $_GET["id"];}; ?>">

     Nome *

     <input type='text' name="txtnome" class='campo' id="txtnome" required>

     E-mail *

     <input type="email" class='campo' required="required" name="txtemail" id="txtemail" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$">

     Telefone *

     <input type="tel" class="campo" name="txttelefone" id="txttelefone" required="required" pattern="\([0-9]{2}\)[\s][0-9]{4}-[0-9]{4,5}" />

     Senha *

     <input type="password" name="txtpass" class='campo' required="required" id="txtpass">

     Data de Nascimento *

     <input type='data' name="txtdata" id="txtdata" class='campo' required="required">

     <input type='submit' name='BTEnvia' value='Cadastrar' class = botao>

 </form>

Comment: utilize a mesma página, e use um campo hidden para guardar a chave primária. Se a chave for vazia, você insere, caso contrário, update
Comment: Mas como crio um link pra pessoa clicar e a chave primária já ir preenchida? Eu tenho uma pagina html e uma php.
Comment: @RovannLinhalis
Comment: você deve ter uma página inserir cliente correto? Ex. você tem um botão inserir cliente, que abre essa página, faça um editar cliente que também irá abrir essa página, porém passando um valor no POST com a chave que você precisa editar. A partir daí, basta testar se esse valor não é vazio e dar o select no banco, e preencher os campos
Comment: @RovannLinhalis tentei, mas não consigo entender
Comment: tente editar sua pergunta e postar o código das páginas que você tem
Comment: @RovannLinhalis editado
Answer: Utilize a mesma página para inserir e editar os registros.
Nesta página coloque um campo para guardar a chave primária do registro selecionado.
No botão salvar, se o campo estiver vazio, realiza o INSERT, se estiver preenchido, UPDATE.
Na hora de abrir a página a partir de um botão INSERIR CLIENTE abra-a normalmente, Na hora de abrir a partir de um botão EDITAR CLIENTE abra-a informando um parâmetro, seja por GET ou POST, que tenha o valor da chave primária do registro que queria editar.
Ao carregar a página, verifique se esse parâmetro é vazio, se sim, abre a tela limpa para o usuário cadastrar um novo cliente, se não, executa a select no banco de dados e preenche os campos com os dados do cliente selecionado.
Segue um exemplo:
PHP
<?php

$nome = $_POST["txtnome"];
 $email = $_POST["txtemail"];
 $telefone = $_POST["txttelefone"];
 $senha = $_POST["txtpass"];
 $data = $_POST["txtdata"];

 $con = mysqli_connect("localhost", "root", "");
 mysqli_select_db($con,"testeconstrusite");
 if (mysqli_connect_errno())
 {
     echo "Falha ao conectar ao servidor MySQL: " . mysqli_connect_error();
 }

 if (isset($_POST["nid"]))
{
    $nid = $_POST["nid"];
    mysqli_query($con, "update clientes set nome_cliente ='$nome', email_cliente='$email', telefone_cliente='$telefone', senha_cliente='$senha', data_nasc_cliente=STR_TO_DATE('$data','%d/%m/%Y') where nid = '$nid'");
    //executa a query
}
else
{
    mysqli_query($con, "insert into clientes (nome_cliente, email_cliente, telefone_cliente, senha_cliente, data_nasc_cliente) VALUE('$nome', '$email', '$telefone', '$senha', STR_TO_DATE('$data','%d/%m/%Y'))");
    $id_inserido = mysqli_insert_id($con);
}

 ?>

HTML -> Deve renomear para PHP
<?php

 $con = mysqli_connect("localhost", "root", "");
 mysqli_select_db($con,"testeconstrusite");
 if (mysqli_connect_errno())
 {
     echo "Falha ao conectar ao servidor MySQL: " . mysqli_connect_error();
 }

if (isset($_GET['nid']))
{
    $nid = $_GET['nid'];
    $clienteAtual = mysql_fetch_assoc(mysql_query("
    SELECT *,
    FROM clientes
    where nid = $nid")) or die(mysql_error());
}

?>

<!DOCTYPE html>

     <meta charset="UTF-8">
     <link type="text/css" rel="stylesheet" media="all"  href="estilos/estilo.css" />

     <title>Cadastro</title>

 <form action="cadastrar.php" method="post">

     <input type='number' name="txtid" class='campo' id="nid" hidden="hidden" value="<?php echo($nid); ?>">

     Nome *

     <input type='text' name="txtnome" class='campo' id="txtnome"  <?php  echo('value="'.$clienteAtual['nome_cliente'].'"');  ?> required>

     E-mail *

     <input type="email" class='campo' required="required" name="txtemail" id="txtemail" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$">

     Telefone *

     <input type="tel" class="campo" name="txttelefone" id="txttelefone" required="required" pattern="\([0-9]{2}\)[\s][0-9]{4}-[0-9]{4,5}" />

     Senha *

     <input type="password" name="txtpass" class='campo' required="required" id="txtpass">

     Data de Nascimento *

     <input type='data' name="txtdata" id="txtdata" class='campo' required="required">

     <input type='submit' name='BTEnvia' value='Cadastrar' class = botao>

 </form>

Comment: Já consegui adicionar na primeira pagina o campo id escondido puxando o id quando a pessoa clica no link pra editar @RovannLinhalis agora falta fazer a alteração no cadastro com a condição.
Comment: @ArnaudLanna editei minha resposta com seu código, veja se ajuda
Comment: quando abro o index o seguinte erro é retornado: `( ! ) Notice: Undefined variable: nid in C:\wamp64\www\testeb\index.php on line 42 Call Stack #TimeMemoryFunctionLocation 10.0003241144{main}( )...\index.php:0 "> Nome *`
Comment: Consegui modificar meu código, tá funcionando perfeitamente, só não preenche os campos, como faço isso?
Comment: no código que alterei, os campos de id e nome deveriam ser preenchidos
Answer: Você pode criar outra pagina de alteração para isso.
pagina_alteracao.php
Só que você passa como parâmetro o id que foi guardado na tabela.
Assim o link para alteração ficaria da seguinte forma.
<a href="pagina_alteracao.php?id=id_cliente" Editar

Com esse id você pode pegar através da query:
SELECT * FROM cliente where id=id_cliente
Ai so precisa fazer a query para alterar os dados.

Editar banco de dados MySQL com php


EigenVector I don't understand

Question: I know how to calculate the eigenvalues and get eigenvectors but there are some Matrix I don't understand?

When Eigenvalue is $1$ we have two eigenvectors i understand and have don gauss-eleminationsand only get $(1,0,1)$ when I have done Gauss-Eleminations  but where does $(0,1,0)$ comes from?

And here is the Matrix above picture:
You can divide the middle row with $1/3$ so you get $(1,0,1)$
and remove the upper and bottom row but where does the eigenvector $(0,1,0)$ comes from
and how two vectors span this eigenspace I don't understand??
Answer: I think the best way to understand eigenvectors is to look at the definition of eigenvectors:
$M\underline{v}=\lambda\underline{v}$ where $M$ is the matrix and $\underline{v}$ the eigenvector and $\lambda$ the associated eigenvalue.
So what I am guessing you are doing is that you rearranged the equation a bit and got the following $(M-\lambda I)\underline{v}=\underline{0}$. So looking at the matrix you got at the end you need to find vectors that gives you the zero vector and looking at it if you have the matrix operating on $(0,1,0)$ you get $(0,0,0)$ so everything is in order. And thus $(0,1,0)$ is an eigenvector.
Comment: Can you explain more @DragonFire0310 i don't understand but i know where the equations?
Comment: So you understand $Mv = \lambda v$ correct and that you can rearrange that into $Mv-\lambda v=0$ and then to "factor" out to get $(M-\lambda I)v = 0$. You already did $M -\lambda I$ so what you need to do now is to "guess" with intuition a vector $v$ which gives you the zero vector when you do the operation $Mv$, this works for me with 2x2 and 3x3 matrices, for higher dim matrices you have to do row operations to find the null space. Is it now clearer ? @Jonte YH
Comment: Okay i have done the calculations on that but how can you know when there is a vector that is missing then? @DragonFire0310
Comment: So you want to know how many eigenvectors there are for each eigenvalue?
Comment: Yes @DragonFire0310 ?
Comment: Alright, the easiest way I know of is that you do $M-\lambda I$ and then you look at the rank of the new matrix and then with the rank-nullity theorem you know the nullity of the new matrix. The nullity = number of linear independent eigenvectors which you should get for the eigenvalue.
Comment: Yes Thanks @DragonFire0310 but how do you apply this formula (M−λI)v=0 i know I is the Identity Matrix but i'dont get 0 when i multiply with the other vector (1,0,1)?
Comment: When i take M x eigenvector then i get 0 in both cases with both eigenvectors?
Comment: $0$ is the origin or the zero vector with all entries being zero, so in a sense what you want to find is the null space of the matrix $M-\lambda I$
Comment: No, when $M$ is operating on $v$ you should get $\lambda v$
Comment: What is M in this case @DragonFire0310?
Comment: Your matrix where you want to find the eigenvalues for.
Comment: But in this case if we take lamda*v where v is the eigenvector we have 1*1+ 0*1+1*1=2
But M*v = 0 is zero?
-6*1 + 0*0 +6*!
etc? @@DragonFire0310
Comment: I think you confuse the matrices $M$ is the first matrix and $M-\lambda I$ is the second matrix which you gave. $M$ operating on $v$ should give $\lambda v$ and if you operate $M-\lambda I$ on $v$ you should get $0$.
Comment: Okay hahaha Thanks
Answer: The row reduced form is
$$\begin{pmatrix}
1 & 0 & -1 \\
0 & 0 & 0 \\
0 & 0 & 0 \\
\end{pmatrix}.$$
The null space of this matrix is
$$\{(x_3, x_2, x_3) : x_2, x_3 \in \mathbb{R}\} = \{x_2(0, 1, 0) + x_3(1, 0, 1) : x_2, x_3 \in \mathbb{R}\} = \text{span}\{(0, 1, 0), (1, 0, 1)\}.$$
Since row operations don't change the null space of a matrix, this is the null space of the original matrix.

EigenVector I don't understand