Com puxar uma variável fora da função PHP

Question: Estou montando um código para fazer comentários porém a conexão com o banco de dados fica fora da função, sendo assim, é necessário recolocar o código dentro da função, como eu puxo o código que está fora?
include 'sis-config.php';
    include 'sis-checar.php';
    $conn = mysqli_connect($host, $usuario, $senha, $db);
    if (!$conn) {
    echo "Não foi possível conectar-se ao MySql." . PHP_EOL;
    exit;
    }
    function comentar()
    {
        include 'sis-config.php';
        $conn = mysqli_connect($host, $usuario, $senha, $db);
        if (!$conn) {
        echo "Não foi possível conectar-se ao MySql." . PHP_EOL;
        exit;
        }
        if (isset($_POST['comentar']))
        {
            $nome=$_POST['nome'];
            $msg=$_POST['mensagem'];
            $vrc1=checar($nome);
            $vrc2=checar($msg);
            $ip=$_SERVER['REMOTE_ADDR'];
            $p = "INSERT INTO `chat` (`nome`, `ip`, `mensagem`, `vip`) VALUES ('$vrc1', '$ip', '$vrc2', '0');";
            if ($conn->query($p) === TRUE) {
                echo 'Postado com sucesso';
            } else {
             echo "Erro: " . $p . "
" . $conn->error;
            }

        }
    }

Quando eu removo o
include 'sis-config.php';
    $conn = mysqli_connect($host, $usuario, $senha, $db);
    if (!$conn) {
    echo "Não foi possível conectar-se ao MySql." . PHP_EOL;
    exit;

da função, a query não funciona, quero que funcione sem ter que recolocar o código dentro da função
Answer: Passe por parâmetro:
function comentar($conn) {
  ...
}

E quando for chamar a função, faça comentar($conn). É para isso que existem os parâmetros da função, gerenciar os escopos.
Comment: Muito obrigao consegu
Comment: @VictorStanford Recomendo que leia também sobre o princípio de responsabilidade única, pois te ajudará a escrever funções mais consistentes.


Atualizar ficheiro .csv quando editado em Java

Question: Tenho um ficheiro .csv que contem informação, mas quando removo informação (neste caso contatos) a partir da saída da consola o ficheiro .csv não está a ser atualizado. Como resolver?
<code>    private void insertContact(String contactName) {
        contactsListModel.addElement(new Contact(contactName));
    }

    private void setContactsList() {
        contactsListModel = new DefaultListModel<Contact>();
        contactsList = new JList<Contact>(contactsListModel);
contactsList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        contactsList.setLayoutOrientation(JList.VERTICAL);
        contactsList.setVisibleRowCount(-1);
        contactsList.setBackground(Color.LIGHT_GRAY);
        loadContacts();

        add(contactsList, BorderLayout.CENTER);
    }

    private void setContactsLabel() {
        contactsLabel = new JLabel("Contacts:");
        contactsLabel.setOpaque(true);
        contactsLabel.setBackground(Color.WHITE);

        add(contactsLabel, BorderLayout.NORTH);
    }

        public void loadContacts(){

        BufferedReader br = null;
        String line = "";
        String separator = ";";

        try {

            br = new BufferedReader(new FileReader("diretorio"));
            while ((line = br.readLine()) != null) {
                String[] contactName = line.split(separator);

                contactsListModel.addElement(new Contact(contactName[0]));

                System.out.println( );

            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
      }
}
</code>
Comment: O que é contactsListModel? Seu código parece estar incompleto.
Comment: private DefaultListModel contactsListModel;
Comment: Mas de onde veio?
Comment: percebe agora??
Comment: Boa tarde, note que você postou apenas parte do código, tanto que a classe ButtonListener não esta inteira, falta fechar o `}`. Siga estas dicas  de http://pt.stackoverflow.com/help/mcve - Tenho certeza que vai levar meu comentário como uma critica construtiva.
Comment: essa classe buttonlistenner esta inteira sim, agora se esta correta não sei. obrigado! consegue me ajudar com a pergunta?
Answer: Você criou um método que lê o arquivo e o transforma em uma lista de contatos. Quando você remove algo dessa lista, você está removendo apenas da lista. Isso é simplesmente esperado. Agora você precisa fazer um método análogo ao que carrega os contatos para salvar os contatos da lista num arquivo e chamá-lo quando alterar a lista. O jeito mais fácil é fazer um que recria o arquivo (apagando o que já existe) e imprimindo lá no arquivo um por um dos contatos. É importante manter o mesmo formato que você usa para leitura.
Comment: Como é o formato do seu arquivo?
Comment: o formato é numa coluna o nome na outra coluna da frente o numero (ficheiro .csv)
Comment: como faço isso em código? pode me dar uma ajuda?
Comment: Blz. Então basicamente você cria um BufferedWriter passando o endereço do seu arquivo como parâmetro e escreve nele uma string contendo o nome do contato, a vírgula e o número para cada elemento da lista usando um for. O BufferedWriter é quase idêntico ao BufferedReader, então não tem erro.
Comment: Eu atualizo quando chegar em casa.
Comment: muito obrigado pela ajuda vou ficar à espera, ate ja
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/31121/discussion-between-java-and-pablo).
Comment: Consegue me ajudar?
Comment: Cheguei. Entre no chat, por favor.


Additional fields for my entity from another table in views

Question: I have table of my entity with structure:
<code>=====================================
eid | myfield1 | myfield2 | myfield3
=====================================
</code>
And also an additional table with primary key being foreign key to my entity id:
<code>==========================
eid | myfield4 | myfield5
==========================
</code>
I would like to expose values in my second table to view of fields, of my entity, but I don't want to join second table with first, every time, but only if I will use one of its fields.
I believe it should be doable with views_join class modifying a query at handler level, but is it possible on hook_views_data_alter() level?
Is it possible to do this transparently - so I wouldn't need to add any relationship to view (just like the field values are pulled from fields tables - yes, you can think a bit about it as about creating fields alternative ;) ) ?
Answer: Technically it's possible, using hook_views_query_alter(), you can adapt the view query to add or change conditions. So you could add a join with something like this:
<code>function modulename_views_query_alter(&$view, &$query) {
  $join = new views_join();
  $join->table = 'mytable';
  $join->field = 'eid';
  $join->left_table = 'entity_table';
  $join->left_field = 'eid';
  $join->type = 'left';
  $query->add_relationship('relationship_name', $join, 'entity_table');
}
</code>
But a better approach would be to use hook_views_data() to expose your table to views, and then add the relevant fields when needed (with a relationship though), but in practical terms is no different than altering the query.


how to remove line in UITabBar?

Question: Help remove the line in tab bar!

`[[UITabBar appearance] setBackgroundImage:[[UIImage alloc] init]];`  - NOT WORK

CODE:
[[UITabBar appearance] setBarTintColor:[UIColor colorWithRed:54.0f/255.0f green:62.0f/255.0f blue:69.0f/255.0f alpha:1.0f]];
    [[UITabBar appearance] setTintColor:[UIColor whiteColor]];
    [[UITabBar appearance] setBackgroundImage:[[UIImage alloc] init]];

    [[self.tabBar.items objectAtIndex:0] setFinishedSelectedImage:[UIImage imageNamed:@"barMap.png"] withFinishedUnselectedImage:[UIImage imageNamed:@"barMapNo.png"]];

    [[self.tabBar.items objectAtIndex:2] setFinishedSelectedImage:[UIImage imageNamed:@"barNews.png"] withFinishedUnselectedImage:[UIImage imageNamed:@"barNewsNo.png"]];

    [[self.tabBar.items objectAtIndex:1] setFinishedSelectedImage:[UIImage imageNamed:@"barNew.png"] withFinishedUnselectedImage:[UIImage imageNamed:@"barNewNo.png"]];

Answer: It looks likes you're setting an image to a tab bar item (with default frame) when the image is larger than the button's frame. You need to replace the entire button!
UIImage *image = [UIImage imageNamed:@"image"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 0, image.size.width, image.size.height);
[button setImage:image forState:UIControlStateNormal];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];
[tabBar setItems:@[ barButton, /* etc */ ]];

Answer: If you're trying to remove the shadowImage then just do the same thing you're doing, but assign it to shadowImage instead of backgroundImage.
Comment: This, but I've found that (as of iOS 7) using `[[UIImage alloc] init]` isn't sufficient. I draw a 1px transparent image using CG and convert that to a UIImage to use.
Comment: @axiixc have you ever tried setting it to `nil`?  It's been a while since I've messed with this and I remember that I got a one liner to work at one point.
Comment: can't say, but my gut would have me believe that would just use the default appearance.
Answer: Try this,
//Remove shadow image by assigning nil value.
[[UITabBar appearance] setShadowImage: nil];

// or

// Assing UIImage instance without image reference
[[UITabBar appearance] setShadowImage: [[UIImage alloc] init]];

Here is apple guideline for shadow image.

Default is nil. When non-nil, a custom shadow image to show instead of
  the default shadow image. For a custom shadow to be shown, a custom
  background image must also be set with -setBackgroundImage: (if the
  default background image is used, the default shadow image will be
  used).

how to remove line in UITabBar?


Why does dd make the host unresponsive?

Question: As root I yesterday did
dd if=/dev/zero of=/var/lib/libvirt/images/dat.img bs=1G count=1000

and for many hours it made the server completely unresponsive.
The raid controller is an HP P410 with 4 disks in raid 1+0.
Is the problem that I used bs=1G or perhaps that CentOS needs a kernel parameter, so heavy I/O can't grind the host to a halt?
Question
Can anyone explain why this happens?
Ps. next time I will create a sparse file, but right now I would like to understand how to prevent I/O from maxing out the host.
Comment: Writing one Tb of data can take some time. Is the /var filesystem the only one using the raid controller?
Comment: Oops.  Can you have a look at the first answer here: https://unix.stackexchange.com/questions/48138/how-to-throttle-per-process-i-o-to-a-max-limit,   I'm under the impression it would allow you to target a specific filesystem via major:minor device number.
Comment: It looks that way. Now I have zero experience with that, always needed to get things as fast as possible on disk. I've seen your problem now and then when creating datafiles for Oracle databases.  You can compare that to your dd: a large amount of nothing useful is being written.  Do you really need this?
Comment: No, all 4 disks are in one raid 1+0, and then split in two partitions. `/var/lib/libvirt/images` is its own partition.
Comment: What's the other partition on the raid?
Comment: That is `/`.....
Comment: `ionice` seams like a really good solution for running processes. And I suppose if I want it by default for all processes, then I have to look into cgroups?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/83677/discussion-between-sandra-and-gerard-h-pille).
Answer: Short answer: the server become unresponsive because you filled almost all memory with dirty pages (ie: data to be flushed out).
Long answer: generally, writes do not push data to the backing device immediately. Rather, they are cached in the pagecache. This is done for performance reasons: storage (especially HDDs) is quite slow compared to CPU/memory, so caching as much possible significantly increse I/O speed. However, if you write to much at all, the pagecache will frenetically (and with high priority) flush to disks as much data as possible. This cause the calling process to go into "deep sleep" - meaning that you can not interrupt it because, well, it is not really running, rather itself is waiting for be woken by the kernel. Moreover, as dirty data flushing is a costly and high priority operation, the entire server become very slow.
That said, how can you create large image files without reducing the server to a crawl? You had different options:

launch your dd command appending the oflag=direct option: this will cause dd to bypass the pagecache, directly writing to disks. I also suggest to use a smaller buffer, ie: 1 MB, using something similar to that dd if=/dev/zero of=/var/lib/libvirt/images/dat.img bs=1M count=1000000. Please note that this command above will somewhat slow down the server during execution (after all, you are writing to disks), but nowhere near you first try;
a better approach to create a fully-allocated file is to use the fallocate command, ie: fallocate /var/lib/libvirt/images/dat.img -l 1G. By allocating via metadata handling, and not writing any real data, this command will return almost immediately, causing no slow down at all. Many modern filesystems support it, with the notable exception of ZFS;
finally, you can use a sparse file - a file with a nominal size but no real allocation. You can create it by issuing truncate --size=1G /var/lib/libvirt/images/dat.img. This command will return immediately, causing basically almost no I/O at all.
Answer: dd allocates a buffer of size bs - if this is a fair chunk of your memory it'll displace other memory and cause swapping.
Worse, the bs buffer is written out in a single operation. This may bind your storage system for a while. In combination with the swapping from above this may tie up the system seriously.
So, it's reasonable to use for instance bs=16M for your task. It's a decent enough buffer size to get efficient I/O while being granular enough to not tie up anything too much.

Why does dd make the host unresponsive?


diagonalize general quadratic form

Question: I want to diagonalize an arbitrary quadratic form $$\sum_{i\leq j \leq n} a_{i,j}x_ix_j$$ over an algebraically closed field of characteristic not equal to $2$.  If $x_n^2$ appears in the form with nonzero coefficient, we can "complete the square" to get the square of a linear form plus a quadratic form of dimension $n-1$. If all $x_i^2$'s appear with nonzero coefficient, doing this successively will diagonalize the form and we'll end up with a total of $n$ squares of linear forms.  However if $x_i^2$ does not appear, it seems we have to write $$x_i \sum_{k<i}a_{k,i}x_{k} = \bigg(\frac{1}{2}(x_i +\sum_{k<i}a_{k,i}x_{k})\bigg)^2 + \bigg(\frac{i}{2}(x_i -\sum_{k<i}a_{k,i}x_{k})\bigg)^2. $$
which is fine except that it requires two linear forms instead of one.   This seems to throw the dimension off so that we end up with more than $n$ squares of linear forms at the end.  How do you fix this?
Context:  This is exercise 5.4.J in Ravi Vakil's Fundamentals of Algebraic Geometry
Comment: It looks like the "contradiction" arises because we're being imprecise about what we mean by "diagonalization." For example, in the answer you linked, there is no invertible matrix $A$ such that $A^{-1} \begin{pmatrix} 1 & i \\ i & -1\end{pmatrix} A$ is diagonal. But there is an invertible matrix $A = \begin{pmatrix}1 & -i \\ 1 & i \end{pmatrix}$ such that $A^T \begin{pmatrix} 1 & i \\ i & -1 \end{pmatrix} A$ is diagonal. You can check that for the purposes of diagonalizing a quadratic form, it is the second notion of diagonalizability of a matrix that we need.
Comment: @CharlesHudgins see algorithm at http://math.stackexchange.com/questions/1388421/reference-for-linear-algebra-books-that-teach-reverse-hermite-method-for-symmetr
Comment: Isn't this problem equivalent to showing that any symmetric matrix is orthogonally diagonalizable? Every proof of the latter fact involves eigenvalues, so I don't see how we're going to show the desired result just by completing the square. The good news is that if you get stuck showing this result by completing the square, you can just imitate a proof of the orthogonal diagonalizability of symmetric matrices.
Comment: @CharlesHudgins  I don't think "orthogonally diagonalizable" has a meaning here since i'm working over an arbitrary algebraically closed field (char $\neq 2$).
Comment: notice that in case the field is $\mathbb{C}$, this is therefore a weaker claim than the one you allude to (that hermitian matrices are unitarily diagonalizable)
Comment: That's a good point, which sent me googling to see if the more general statement is also true. Look at this stack exchange post https://math.stackexchange.com/questions/1142250/diagonalization-of-a-symmetric-matrix-over-algebraically-closed-field .
Comment: @CharlesHudgins  Huh, this is strange: https://mathoverflow.net/questions/23629/non-diagonalizable-complex-symmetric-matrix

am I missing something or are these contradictory?
Comment: I don't think there's a contradiction, but I'm not sure how the two results are consistent either. Sorry if my comments have only confused things. It's been a while since I've looked at this stuff. I'm reading around right now. I'll let you know if I figure it out.
Comment: @CharlesHudgins not at all -- i appreciate your help
Comment: Continued: It is this second notion of diagonalizability that is used in the answer I linked.
Comment: @CharlesHudgins Forgetting about the issue of "orthonormality" in the answer you linked, the claim there is that there is a basis of eigenvectors for any symmetric matrix $M$ over $\mathbb{C}$.  Wouldn't that imply there exists $A$ with $A^{-1}MA$ diagonal?
Comment: or did the answer in that post prove a different claim from what was asked by the OP?
Comment: In the answer I linked, it looks like the post proved that, given a quadratic form with matrix $Q$, we can find an invertible matrix $A$ such that $A^T D A = Q$ where $D$ is diagonal (apologies: I wrote this condition backward in the previous comment). Note that we do not require that $A^T = A^{-1}$. In the original basis, say $e_1, \ldots e_n$, the quadratic form is $q(x) = x^T Q x$. Define a new basis $v_i = A e_i$. Then $q(x) = x^T Q x = x^T A^T D A x = (Ax)^T D (Ax)$, where the $Ax$ are linear combinations of the $x_i$ that make the quadratic form diagonal.
Comment: I found a good reference that brings together everything we've been talking about if you just want an explanation of the whole problem: http://www2.math.ou.edu/~kmartin/ntii/chap7.pdf
Comment: @CharlesHudgins  great, thanks so much.
Comment: @WillJagy  Thanks Will, your step 2 case III was the answer to my question.
Answer: Following @WillJagy 's link in the comments, if no squared terms appear we take some nonzero term, $cxy~~(c\in K)$, say, and replace all $y$ with $x+y$. Then $x^2$ appears in the new expression and we complete the square and continue.

diagonalize general quadratic form


mysql allow invalid dates on select

Question: For some reason, I can't even select invalid dates in my table. How do I force select? I just receive:
select * from table
>> Mysql2::Error: Invalid date: 1900-00-00

I'm not trying to insert, just select. Can I set allow invalid dates in select query?
mysql --version
mysql  Ver 14.14 Distrib 5.1.61, for debian-linux-gnu (i686) using readline 6.1

mysql> select @@global.sql_mode;
+-------------------+
| @@global.sql_mode |
+-------------------+
|                   |

Comment: Can you add your sample query?
Comment: What library are you using? Strict mode turned on?
Comment: I don't know. How do I find out or disable strict mode? I'm using ruby mysql2 library.
Comment: I don't think I have strict mode enabled.
Comment: see related question on how to convert invalid dates: http://stackoverflow.com/questions/12933042/mysql-fix-invalid-dates
Answer: This is what I do to ignore invalid dates:
SET SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

Comment: @njoshsn in /etc/my.cnf you can configure mysql, comment by [Martin Eisenführer](http://stackoverflow.com/users/7308580/martin-eisenf%c3%bchrer) posted incorrectly in [answer](http://stackoverflow.com/a/41192800/5292302)
Comment: where do you set this?
Answer:
Log into mysql in the command line mysql -u root -p
Enter your password
View the current sql-modes using SELECT @@GLOBAL.sql_mode;
Copy the current modes (add or delete modes as needed) and paste in next step.
Set the sql-modes using SET GLOBAL sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,ALLOW_INVALID_DATES';
This adds ALLOW_INVALID_DATES and removes both NO_ZERO_DATE, NO_ZERO_IN_DATE
Restart the MySQL server /etc/init.d/mysql start
Comment: all good but the sql-modes went back to the default when i restarted the mysql service. It worked for me without restarting the service.
Comment: If you have a default configuration for the MySQL server, it will reset when the computer reboots.
Comment: still the issue persist ! my innodb_version is 5.5.53 on  alter table statements !
Answer: SQL Server Modes [Reset configuration file]
Solution Link
- From the command line which mysqld
- Should get something like /usr/sbin/mysqld which is the location of the binary file
- Sort out the path for the configuration files /usr/sbin/mysqld --verbose --help | grep -A 1 "Default options"
- Your bash response should look like this: Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf ~/.my.cnf
- Look at the files in successive order to see where to make changes (if a file does not exist it is not being referenced).
- Look up your current mode. Open a terminal and log into the mysql database mysql -u database_user -p -e "select @@sql_mode"
- Modify the SQL modes you want to change by adding the following code to the configuration file.

[mysqld]
sql-mode = "STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,ALLOW_INVALID_DATES"

- Save the configuration file and restart the mysql service
Comment: still the issue persist ! my innodb_version is 5.5.53
Comment: Walk me through the problem?
Can you login to your mysql database?
Can you ```use myDataBaseName;``` the correct database?
Can you ```show tables;``` and see the table you want to reference?
Can you ```describe myTableName``` of the table you want to utilize?
What is the data type of the column that contains the zero date?
What is your current SQL-mode?
Answer: This one solve my problem. I tested in local MySQL 5.7 ubuntu 18.04.
set global sql_mode="NO_ENGINE_SUBSTITUTION";

Before running this query globally I added a cnf file in  /etc/mysql/conf.d directory. The cnf file name is mysql.cnf and codes
[mysqld]
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ALLOW_INVALID_DATES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

Then I restart mysql
sudo service mysql restart

Hope this can help someone.

mysql allow invalid dates on select


How to Insert following beautiful soup scraped data in excel?

Question: from bs4 import BeautifulSoup
import pandas as pd
import requests
import time
from datetime import datetime

def extract_source(url):
     agent = {"User-Agent":"Mozilla/5.0"}
     source=requests.get(url, headers=agent).text
     return source

html_text = extract_source('https://www.mpbio.com/us/life-sciences/biochemicals/amino-acids')
soup = BeautifulSoup(html_text, 'lxml')

for a in soup.find_all('a', class_ = 'button button--link button--fluid catalog-list-item__actions-primary-button', href=True):
    # print ("Found the URL:", a['href'])
    urlof = a['href']
    html_text = extract_source(urlof)
    soup = BeautifulSoup(html_text, 'lxml')

    table_rows = soup.find_all('tr')

    first_columns = []
    third_columns = []
    for row in table_rows:
#         for row in table_rows[1:]:
        first_columns.append(row.findAll('td')[0])
        third_columns.append(row.findAll('td')[1])

    for first, third in zip(first_columns, third_columns):
        print(first.text, third.text)

Basically I am trying to scrape data from tables from multiple links of Website. And I want to insert that data in one excel csv file in following table format
SKU                           07DE9922
Analyte / Target           Corticosterone
Base Catalog Number        DE9922
Diagnostic Platforms       EIA/ELISA
Diagnostic Solutions       Endocrinology
Disease Screened           Corticosterone
Evaluation                 Quantitative
Pack Size                  96 Wells
Sample Type                Plasma, Serum
Sample Volume              10 uL
Species Reactivity         Mouse, Rat
Usage Statement            For Research Use Only, not for use in diagnostic procedures.

To below format in excel file

SKU  Analyte/Target  Base Catalog Number Pack Size Sample Type
data   data           data                 data      data

I am facing difficulties while converting data in proper format
Answer: I made small modification to your code. Instead of printing the data, I created a dictionary and added it to list. Then I used this list to create a DataFrame:
import pandas as pd
import requests
import time
from datetime import datetime

def extract_source(url):
    agent = {"User-Agent": "Mozilla/5.0"}
    source = requests.get(url, headers=agent).text
    return source

html_text = extract_source(
    "https://www.mpbio.com/us/life-sciences/biochemicals/amino-acids"
)
soup = BeautifulSoup(html_text, "lxml")

data = []
for a in soup.find_all(
    "a",
    class_="button button--link button--fluid catalog-list-item__actions-primary-button",
    href=True,
):
    urlof = a["href"]
    html_text = extract_source(urlof)
    soup = BeautifulSoup(html_text, "lxml")

    table_rows = soup.find_all("tr")

    first_columns = []
    third_columns = []
    for row in table_rows:
        first_columns.append(row.findAll("td")[0])
        third_columns.append(row.findAll("td")[1])

    # create dictionary with values and add to the list
    d = {}
    for first, third in zip(first_columns, third_columns):
        d[first.get_text(strip=True)] = third.get_text(strip=True)
    data.append(d)

df = pd.DataFrame(data)
print(df)
df.to_csv("data.csv", index=False)

Prints:
           SKU                                    Alternate Names Base Catalog Number        CAS #  EC Number  Format  Molecular Formula Molecular Weight           Personal Protective Equipment                                    Usage Statement                                  Application Notes Beilstein Registry Number                 Optical Rotation Purity     UV Visible Absorbance Hazard Statements RTECS Number Safety Symbol         Auto Ignition                  Biochemical Physiological Actions                    Density                            Melting Point                                          pH                              pKa                                         Solubility                      Vapor Pressure      Grade                                      Boiling Point Isoelectric Point
0  02100078-CF                2-Acetamido-5-Guanidinovaleric acid              100078  210545-23-6  205-846-6  Powder    C8H16N4O3· 2H2O    216.241 g/mol   Eyeshields, Gloves, respirator filter  Unless specified otherwise, MP Biomedical's pr...                                                NaN                       NaN                              NaN    NaN                       NaN               NaN          NaN           NaN                   NaN                                                NaN                        NaN                                      NaN                                         NaN                              NaN                                                NaN                                 NaN        NaN                                                NaN               NaN
1  02100142-CF  Acetyltryptophan; DL-α-Acetylamino-3-indolepro...              100142      87-32-1  201-739-3  Powder         C13H14N2O3    246.266 g/mol   Eyeshields, Gloves, respirator filter  Unless specified otherwise, MP Biomedical's pr...  N-acetyl-DL-tryptophan, is used as stabilizer ...                     89478  0° ± 2° (c=1, 1N NaOH, 24 hrs.)   ~99%  λ max (water)=280 ± 2 nm               NaN          NaN           NaN                   NaN                                                NaN                        NaN                                      NaN                                         NaN                              NaN                                                NaN                                 NaN        NaN                                                NaN               NaN
2  02100421-CF  L-2,5-Diaminopentanoic acid; 2,5-Diaminopentan...              100421    3184-13-2  221-678-6  Powder    C5H12N2O2 • HCl    168.621 g/mol   Eyeshields, Gloves, respirator filter  Unless specified otherwise, MP Biomedical's pr...                                                NaN                   3625847                              NaN   ~99%                       NaN              H319    RM2985000         GHS07                   NaN                                                NaN                        NaN                                      NaN                                         NaN                              NaN                                                NaN                                 NaN        NaN                                                NaN               NaN
3  02100520-CF  Phosphocreatine Disodium Salt Tetrahydrate; So...              100520     922-32-7  213-074-6  Powder  C4H8N3Na2O5P·4H2O    255.077 g/mol   Eyeshields, Gloves, respirator filter  Unless specified otherwise, MP Biomedical's pr...                                                NaN                       NaN                              NaN   ≥98%                       NaN               NaN          NaN           NaN                   NaN                                                NaN                        NaN                                      NaN                                         NaN                              NaN                                                NaN                                 NaN        NaN                                                NaN               NaN
4  02100769-CF  Vitamin C; Ascorbate; Sodium ascorbate; L-Xylo...              100769      50-81-7  200-066-2     NaN             C6H8O6    176.124 g/mol   Eyeshields, Gloves, respirator filter  Unless specified otherwise, MP Biomedical's pr...  L-Ascorbic Acid is used as an Antimicrobial an...                     84272        +18° to +32° (c=1, water)   ≥98%                       NaN               NaN    CI7650000           NaN  1220° F (NTP, 1992)  Ascorbic Acid, also known as Vitamin C, is a s...           1.65 (NTP, 1992)  374 to 378° F (decomposes) (NTP, 1992)  Between 2,4 and 2,8 (2 % aqueous solution)            pK1: 4.17; pK2: 11.57  greater than or equal to 100 mg/mL at 73° F (...  9.28X10-11 mm Hg at 25 deg C (est)        NaN                                                NaN               NaN
5  02101003-CF  Lycine; Oxyneurine; (Carboxymethyl)trimethylam...              101003     107-43-7  203-490-6  Powder           C5H11NO2    117.148 g/mol   Eyeshields, Gloves, respirator filter  Unless specified otherwise, MP Biomedical's pr...  Betaine is a reagent that is used in soldering...                   3537113                              NaN    NaN                       NaN               NaN    DS5900000           NaN                   NaN  End-product of oxidative metabolism of choline...                        NaN              Decomposes around 293 deg C                                         NaN                      1.83 (Lit.)  Solubility (g/100 g solvent): <a class="pubche...   1.36X10-8 mm Hg at 25 deg C (est)  Anhydrous                                                NaN               NaN
6  02101806-CF  (S)-2,5-Diamino-5-oxopentanoic acid; L-Glutami...              101806      56-85-9  200-292-1     NaN          C5H10N2O3    146.146 g/mol  Eyeshields, Gloves,  respirator filter  Unless specified otherwise, MP Biomedical's pr...  L-glutamine is an essential amino acid, which ...                   1723797       +30 ± 5° (c = 3.5, 1N HCl)   ≥99%                       NaN               NaN    MA2275100           NaN                   NaN  L-Glutamine is an essential amino acid that is...              1.364 g/cu cm                             185.5 dec °C            pH = 5-6 at 14.6 g/L at 25 deg C                              NaN              Water Solubility41300 mg/L (at 25 °C)    1.9X10-8 mm Hg at 25 deg C (est)        NaN                                                NaN               NaN
7  02102158-CF  L-2-Amino-4-methylpentanoic acid; Leu; L; α-am...              102158      61-90-5  200-522-0  Powder           C6H13NO2    131.175 g/mol   Eyeshields, Gloves, respirator filter  Unless specified otherwise, MP Biomedical's pr...  Leucine has been used as a molecular marker in...                   1721722        +14.5 ° to +16.5 ° (Lit.)    NaN                       NaN               NaN    OH2850000           NaN                   NaN                                                NaN  1.293 g/cu cm at 18 deg C                                   293 °C                                         NaN  2.33 (-COOH), 9.74 (-NH2)(Lit.)              Water Solubility21500 mg/L (at 25 °C)   5.52X10-9 mm Hg at 25 deg C (est)        NaN  Sublimes at 145-148 deg C. Decomposes at 293-2...        6.04(Lit.)
8  02102576-CF  4-Hydroxycinnamic acid; 3-(4-Hydroxphenyl)-2-p...              102576    7400-08-0  231-000-0  Powder             C9H8O3     164.16 g/mol           Dust mask, Eyeshields, Gloves  Unless specified otherwise, MP Biomedical's pr...  p-Coumaric acid was used as a substrate to stu...                       NaN                              NaN   ≥98%                       NaN               NaN    GD9094000           NaN                   NaN                                                NaN                        NaN                                 211.5 °C                                         NaN                              NaN                                                NaN                                 NaN        NaN                                                NaN               NaN
9  02102868-CF  DL-2-Amino-3-hydroxypropionic acid; (±)-2-Amin...              102868     302-84-1  206-130-6  Powder            C3H7NO3    105.093 g/mol   Eyeshields, Gloves, respirator filter  Unless specified otherwise, MP Biomedical's pr...                                                NaN                   1721405      -1° to + 1° (c = 5, 1N HCl)   ≥98%                       NaN               NaN          NaN           NaN                   NaN  NMDA agonist acting at the glycine site; precu...     1.6 g/cu cm @ 22 deg C                   228 deg C (decomposes)                                         NaN                              NaN  SOL IN <a class="pubchem-internal-link CID-962...                                 NaN        NaN                                                NaN               NaN

...and so on.

And saves data.csv (screenshot from LibreOffice):
Answer: Try this -
import pandas as pd
import requests
import time
from datetime import datetime
from bs4 import BeautifulSoup

def extract_source(url):
    agent = {"User-Agent": "Mozilla/5.0"}
    return requests.get(url, headers=agent).text

html_text = extract_source(
    'https://www.mpbio.com/us/life-sciences/biochemicals/amino-acids')
soup = BeautifulSoup(html_text, 'lxml')

result = []
for index, a in enumerate(soup.find_all('a', class_='button button--link button--fluid catalog-list-item__actions-primary-button', href=True)):
    #  if index >= 10:
    #       break
    # print ("Found the URL:", a['href'])
    urlof = a['href']
    html_text = extract_source(urlof)
    soup = BeautifulSoup(html_text, 'lxml')

    table_rows = soup.find_all('tr')

    first_columns = []
    third_columns = []
    for row in table_rows:
        #         for row in table_rows[1:]:
        first_columns.append(row.findAll('td')[0])
        third_columns.append(row.findAll('td')[1])

    temp = {}
    for first, third in zip(first_columns, third_columns):
        third = str(third.text).strip('\n')
        first = str(first.text).strip('\n')
        temp[first] = third

    result.append(temp)
df = pd.DataFrame(result)
# please drop useless column before saving the output to csv.
df.to_csv('out.csv', index=False)

This will give output -

SKU
Alternate Names
Base Catalog Number
CAS #
EC Number
Format
Molecular Formula
Molecular Weight
Personal Protective Equipment
Usage Statement
Application Notes
Beilstein Registry Number
Optical Rotation
Purity
UV Visible Absorbance
Hazard Statements
RTECS Number
Safety Symbol

02100078-CF
2-Acetamido-5-Guanidinovaleric acid
100078
210545-23-6
205-846-6
Powder
C8H16N4O3· 2H2O
216.241 g/mol
Eyeshields, Gloves, respirator filter
Unless specified otherwise, MP Biomedical's products are for research or further manufacturing use only, not for direct human use. For more information, please contact our customer service department.

02100142-CF
Acetyltryptophan; DL-α-Acetylamino-3-indolepropionic acid
100142
87-32-1
201-739-3
Powder
C13H14N2O3
246.266 g/mol
Eyeshields, Gloves, respirator filter
Unless specified otherwise, MP Biomedical's products are for research or further manufacturing use only, not for direct human use. For more information, please contact our customer service department.
N-acetyl-DL-tryptophan, is used as stabilizer in the human blood-derived therapeutic products normal serum albumin and plasma protein fraction.
89478
0° ± 2° (c=1, 1N NaOH, 24 hrs.)
~99%
λ max (water)=280 ± 2 nm

02100421-CF
L-2,5-Diaminopentanoic acid; 2,5-Diaminopentanoic acid monohydrochloride
100421
3184-13-2
221-678-6
Powder
C5H12N2O2 • HCl
168.621 g/mol
Eyeshields, Gloves, respirator filter
Unless specified otherwise, MP Biomedical's products are for research or further manufacturing use only, not for direct human use. For more information, please contact our customer service department.

3625847

~99%

H319
RM2985000
GHS07
Comment: Glad it helped have a look at - https://stackoverflow.com/help/someone-answers @sumitshelar


Conexão php a banco de dados PostgreSQL

Question: Problema ao realizar conexão com banco de dados PostgreSQL utilizando PHP.
Quando executo a função pg_conect(), ocorre o seguinte erro
Fatal error: Call to undefined function pg_connect()

já adicionei o caminho da dll do postgreSQL para o httpd
LoadFile "C:/Program Files/PostgreSQL/9.4/bin/libpq.dll"

e também ativei as extensões do php, no php.ini removendo o ; extension=php_pgsql.dll
Sempre que executo o código para verificar se a extensão está ativa ele me retona erro
echo extension_loaded('pgsql') ? 'Ok':'Erro';

Atualmente utilizo o wampserv com apache2.4.9 e php5.5.12. Como posso resolver esse erro? é possivel resolver a alterando a versão, já que fazendo essas alterações não consigo?
Como consigo fazer com que o php tenha acesso ao pgsql? já que minha aplicação não é capaz de encontrá-la ?
Comment: Possível duplicata de [Não estou conseguindo me conectar com o postgreSQL no php](https://pt.stackoverflow.com/questions/100445/n%c3%a3o-estou-conseguindo-me-conectar-com-o-postgresql-no-php)
Comment: Olá, a pergunta de certa forma é semelhante mas a resposta desse link não é capaz de resolver meu erro, vou editar a pergunta para ficar mais clara
Answer: O problema consistia na versão referente ao wamp e suas ferramentas, desinstalei a versão que estava usando 2.* e instalei a versão mais atual. realizei os procedimento novamente de habilitar o pgsql, removendo o ; do php.ini, e agora ele conseguiu encontrar a extensão e se conectar ao PostgreSQL

Conexão php a banco de dados PostgreSQL


Proving $A \cap (B - C) = (A \cap B) - (A \cap C)$

Question: I am trying to prove that $A \cap (B - C) = (A \cap B) - (A \cap C)$ using biconditionals, but I cannot seem to get the proof to work out.
\begin{align*}
x \in A \cap (B - C) & \iff x \in A \text{ and } x \in B - C \\
& \iff x \in A \text{ and } (x \in B \text{ and } x \not \in C) \\
& \iff (x \in A \text{ and } x \in B) \text{ and } (x \in A \text{ and } x \not \in C) \\
& \iff x \in A \cap B \text{ and } x \in A - C \\
& \iff x \in (A \cap B) \cap (A-C).
\end{align*}
I cannot figure out how to get from $(A \cap B) \cap (A - C)$ to $(A \cap B) - (A \cap C)$.
Answer: HINT:
$(x \in A \text{ and } x \in B) \text{ and } (x \in A \text{ and } x \not \in C)\\
\iff (x \in A \text{ and } x \in B) \text{ and } (x\in A \text{ and }x \not\in A \cap C)$
Comment: The forward implication makes sense, but why is it the case that $x \not \in A \cap C$ implies $x \in A$ and $x \not \in C$? We could instead have, for example, $x \in C$ and $x \not \in A$.
Comment: Hmmm, but we already have $x \in A$ from the first parenthesis, so we must have $x \not \in C$ if $x \not \in A \cap C$. Got it -- thank you!
Comment: I have edited my answer to avoid confusion!
Comment: This is a helpful intermediary step. I appreciate it! (It won't let me accept an answer yet, but I will in just a moment.)
Answer: A small observation is that: if $x \notin C \implies x \notin A\cap C$ because $A\cap C \subseteq C$. Using this you can justify the step above.


Redirecionamento após login laravel 5.5

Question: Bom dia, estou utilizando o scafold de autenticação padrão do Laravel, e reaproveitando a estrutura sobrescrevendo os métodos que preciso pra que se comporte da maneira que eu quero.
Personalizei a model default, consegui fazer autenticar e registrar, tudo ok. No entanto após o registro, eu queria redirecionar o usuário para uma rota minha, de pós cadastro. O laravel me fornece alguns pra isso como o protected function registered( $user ), no entanto, tudo que eu faço dentro dele parece que é ignorado. Por conta do middleware RedirectIfAuthenticated (guest).
Já tentei diversas outras formas e meio que a estrutura do laravel me fornece.
Já tentei alterar as variáveis $redirectTo do RegisterController e do LoginController, e criar os métodos redirectTo em ambos.
Nada parece funcionar. A controller em questão é essa:
/**
     * @Middleware("auth")
     * @Get("Painel", as="painel")
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function painel()
    {
        dump('chegou na home controller');
//      $usuario = auth()->user();
//      if ( $usuario->tipo == 'aluno' ) {
//          $aluno = AlunoModel::where('usuario_id',$usuario->id)->first();
//          return view('home.painel-aluno', compact( 'aluno') );
//      }
    }

Estou usando o pacote laravelcollective/annotations, mas acho que não tem influência alguma.
Minha model de user:
<?php

namespace ContrateUmAluno\Models\Cadastros;

use ContrateUmAluno\Traits\Uuids;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class UsuarioModel extends Authenticatable
{
    use Notifiable, Uuids, SoftDeletes;

    protected $table = 'usuarios';
    public $incrementing = false;
    protected $fillable = [
        'nome', 'email', 'senha', 'tipo'
    ];
    protected $hidden = [
        'senha', 'remember_token',
    ];

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword()
    {
        return $this->senha;
    }
}

RegisterController:
<?php

namespace ContrateUmAluno\Http\Controllers\Auth;

use ContrateUmAluno\Models\Cadastros\AlunoModel;
use ContrateUmAluno\Models\Cadastros\EmpresaModel;
use ContrateUmAluno\Models\Cadastros\UsuarioModel;
use ContrateUmAluno\Http\Controllers\Controller;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */
    use RegistersUsers;

    protected $redirectTo = 'painel';
    /**
     * Handle a registration request for the application.
     */
    public function redirectTo() {
        return route($this->redirectTo);
    }

    public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create([
            'nome'          => $request['name'],
            'email'         => $request['email'],
            'senha'         => $request['password'],
            'tipo_usuario'  => $request['tipo_usuario'],
        ])));

        $this->guard()->login($user);

        return $this->registered($request, $user)
            ?: redirect($this->redirectPath());
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name'          => 'required|string|max:255',
            'email'         => 'required|string|email|max:255|unique:usuarios',
            'password'      => 'required|string|min:6|confirmed',
            'tipo_usuario'  => 'required',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return UsuarioModel
     */
    protected function create(array $data)
    {
        $usuario = UsuarioModel::create([
            'nome'  => $data['nome'],
            'email' => $data['email'],
            'tipo'  => $data['tipo_usuario'],
            'senha' => bcrypt($data['senha']),
        ]);

        $this->criar_tipo($data['tipo_usuario'], $data, $usuario);
        return $usuario;
    }

    /**
     * @param string       $tipo_usuario
     * @param array        $dados
     * @param UsuarioModel $usuario
     *
     * @return void
     */
    private function criar_tipo(string $tipo_usuario, array $dados, UsuarioModel $usuario)
    {
        $usuario_id = $usuario->id;
        if ( $tipo_usuario == 'aluno' ) {
            AlunoModel::create([ 'nome' => $dados['nome'], 'usuario_id' => $usuario_id ]);
        } else {
            EmpresaModel::create([ 'nome' => $dados['nome'], 'usuario_id' => $usuario_id ]);
        }
    }
}

Após algumas tentativas de alterar manualmente todos os lugares que está escrito /home (o que não me parece correto, já que temos a herança pra não precisarmos fazer isso) eu consigo com que ele jogue a rota /Painel, no entanto o navegador acusa redirecionamento incorreto.

PS: na print está /login, mas é porque eu tinha removido o middleware pra fazer alguns outros testes.
Eu já não sei mais o que testar e como tentar. Pelo que já procurei nas issues no github, já tem reports desse mesmo padrão, no entanto todas as soluções que foram dadas, não funciona, eu consigo jogar pra rota em questão, mas me acusa esse erro. E alguns casos das issues, era apenas uma questão de estar invertendo o uso da variavel $redirectTo e dos métodos autenticated e registered.
Desde já, obrigado!
Answer: Se você está usando rotas por annotation, verifique se o controller do painel está usando o middleware "web", pois sem ele o Laravel não inicia, nem lê a sessão do usuário nessa rota.
Comment: Realmente, era isso mesmo.
Obrigado!

Redirecionamento após login laravel 5.5


How to show scrollbar inside ui-select dropdownlist

Question: I am using ui-select for showing list of states. My state list is greater than ui-select dropdown height. How can I show the scrollbar inside ui-select drop down list so that user knows there are more items in the list?
Comment: set a css property `overflow:scroll`.
Comment: use overflow:scroll, If it is for touch device use -webkit-overflow-scrolling: touch. still your facing the problem. Please post the code to rectify
Comment: @HP's411: What element should receive the `overflow:scroll` property?
Comment: @jkndrkn :  The Container which has large amount of Data to Show on it. For Example you have a `` which will holds your Data, than this `` should receive this Property.
Answer: Add below css code
<code>.ui-select-choices-content{
 overflow-y:scroll !important;
 &::-webkit-scrollbar
 {
 width: 8px !important;
 }
 &::-webkit-scrollbar-thumb
 {
 border-radius: 7px;
 -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
 background-color: red;
 }
}
</code>


Why is the constructor method being called before setup

Question: Here is my class under test:
KafkaProcessorApplication
@EnableBinding(Processor.class)
@EnableConfigurationProperties(KafkaProperties.class)
public class KafkaProcessorApplication {

    @Autowired
    private Processor processor;

    @Autowired
    private KafkaProperties kafkaProperties;

    private KafkaTemplate<String, String> kafkaTemplate;

    @Autowired
    KafkaProcessorApplication(SenderConfig senderConfig) {
        this.kafkaTemplate = senderConfig.kafkaTemplate();
    }

Here, SenderConfig is a just a simple config class with the method kafkaTemplate() creating a new instance of KafkaTemplate.
SenderConfig
@Configuration
public class SenderConfig {
@Autowired
KafkaProperties kafkaProperties;

public ProducerFactory<String, String> producerFactory() {
    return new DefaultKafkaProducerFactory<>(new HashMap());
}

public KafkaTemplate<String, String> kafkaTemplate() {
    return new KafkaTemplate<>(ProducerFactory()));
}

}
Here is the test class:
KafkaTestClass
@SpringBootTest
@ActiveProfiles("test")
@ContextConfiguration(classes = {SenderConfig.class, KafkaProcessorApplication.class})
@TestPropertySource(locations = "classpath:test-resources.properties")
@RunWith(SpringRunner.class)
public class KafkaProcessorApplicationTest {

    @Autowired
    private Processor processor;
    @Mock
    private SenderConfig senderConfig;

    @Mock
    private KafkaProperties kafkaProperties = new KafkaProperties();
    @Mock private KafkaTemplate mockKafka;

    @Autowired
    @InjectMocks
    private KafkaProcessorApplication app;

    @Before
    public void setup() throws Exception {
        MockitoAnnotations.initMocks(this);
        doReturn("ServerConfig").when(kafkaProperties).getServersConfig();
        when(senderConfig.kafkaTemplate()).thenReturn(kafkaTemplate);
    }

I want to mock kafkaTemplate. But, its instantiation is in constructor which is being executed even before the @Before is executed, where the logic of mocking the method is written.
Just curious why is the constructor being executed first, and also, how can I mock the method if this is the case?
What could be the approaches of mocking the kafkaTemplate, without using Powermock and without modifying  the class under test as I can not change it?
Answer: When you use @SpringBootTest, the Spring dependency tree is resolved before the @Before method has a chance to execute. This includes constructing the KafkaProcessorApplication bean and its dependencies. This is why the constructor runs before @Before.
What you want is Spring's @MockBean to create and inject a mock bean in the application context.
This question has a great write-up of how you can use this: Difference between @Mock, @MockBean and Mockito.mock()
update
Now I see. The problem is that the KafkaProcessorApplication accesses the mock in its constructor before you can configure it.
This can be solved with a separate test Spring configuration that will return a configured SenderConfig mock bean as described here: Testing spring bean with post construct
Comment: Ok, I have used many options to mock the bahaviour of the method being called, but it always remains null, or in the case of using MockBean, creates new instance, So, how do I define its behaviour?
Comment: Which bean do you want to mock exactly? It's a bit hard to tell with your current test code. That mock must have @MockBean applied. The example in the first answer to the question I linked to seems pretty good.
Comment: I want to mock KafkaTemplate which is being created in the constructor call. I want a clear way to do it, without changing the source code
Comment: Are you sure? It looks like SenderConfig is the **bean** you want to mock. I don't see any KafkaTemplate **bean**.
Comment: I can mock SenderConfig already, it is just that, it is instantiating the KafkaTemplate before it can mock the method call on this mocked senderConfig.
Comment: Thanks, it worked after I updated it to use the configuration class, it will load the beans and define their behavior before beans can be created.
Comment: @KumarAnkit No problem. Please remember to accept my answer! I see you don't usually accept answers to your questions. See here for more info https://stackoverflow.com/help/someone-answers and here https://stackoverflow.com/help/accepted-answer


Endlessly looping the same function after inputting action once

Question: I've been making a little game, but when i choose and action such as "attack", it keeps looping the same function over and over.
I can never choose another action like "inventory":
def attack():
    # this has way more code but not important to demo the problem
    # see the actual output below for what happes when this is called
    print("Attacking.")

def flee():
    print("Fled to safety.")

def inventory():
    print("Backpack is empty.")

def shop():
    print("No shop near-ish. Got no money")

action = input('Which action would you like to choose? ')

while action != "Exit Game":
    if action == "attack":
        attack()
    elif action == "flee":
        flee()
    elif action == "inventory":
        inventory()
    elif action == "shop":
        shop()
    else:
        break

Example of the simulated (attack) outcome - I only get to choose the action onces and then it repeats endlessly:
Which action would you like to choose? attack
Attacking.
Attacking.
Attacking.
Attacking.
Attacking.
Attacking.
Attacking.
# etc

Example of the real (attack) code outcome:
Comment: Please fix the indentation in the question to match your actual code.
Comment: Of course, because you only ask for input once.  If you want new input each time through the loop, then you had better move the `input` call inside the loop.
Comment: Converted the code to a [mre] that replicates your problem without having all the missing bits and pieces your original code had ... revert if you do not like it.
Answer: You need to update the user's desired action for every iteration of the loop. Right now you only ask once and never again. Instead, try this
while True:
    action = input('Which action would you like to choose?')
    if ...

Answer: You have to read action at the beginning of your decision tree
And - this code worked for me only after several changes (identation, global vars, missing var
import random

def attack():

   global HP
   global EnemyHP
   global Coins
   coin_multiplyer=2

   print('You try to strike the enemy')
   if random.randint(0, 10) >= 4:
       print('You missed the enemy')
       print('The enemy attacks you')
       HP = HP - 4
       print('You have ' + str(HP) + 'HP left')

   else:
       if random.randint(0, 10) >= 3:
           print('Critical Hit!')
           EnemyHP = EnemyHP - 7
       else:
           print('You hit the enemy')
           EnemyHP = EnemyHP - 4
       print('The enemy has ' + str(EnemyHP) + 'HP left')
       print('You have ' + str(HP) + 'HP left')

   if EnemyHP <= 0:
       print('You killed the goblin!')
       print('Oh, the goblin left some golden coins!')
       print('You recived 12 golden coins!')
       Coins = Coins + 12 * coin_multiplyer
       print('You have ' + str(Coins) + 'gold coins')
       print('Oh no! Another goblin appeared!')
       EnemyHP = 10

#Below here is the code that summons the function depending on what action you choose

HP=0
EnemyHP=0
Coins=0

while action != "Exit Game":
   action = input('Which action would you like to choose?')
   if action == "attack":
       attack()
   elif action == "flee":
       flee()
   elif action == "inventory":
       inventory()
   elif action == "shop":
       shop()
   else:
       break

Answer: You need to have your input call inside the loop:
while True:
    action = input('Which action would you like to choose?')
    if action == "attack":
    ...
    else:
        break

Also, an approach I usually take for a code like yours is to implement a switch dictionary, so that you don't end up with a lot of if ... else:
actions = {
    "attack": attack,
    "flee": flee,
    "inventory": inventory,
    "shop": shop,
    "Exit Game": lambda: True,
}

while True:
    try:
        if actions[input('Which action would you like to choose?')]():
            break
    except KeyError:
        pass

Comment: Note that using a dictionary like this can result in an exception being thrown.
Comment: @BTables Thank you, I edited my answer and added exception handling


My list items are not collapsing in navbar

Question: i am a little new to bootsrap, and I have tried everything for the UL class to collapse but its not collapsing when re sizing the view port. Below is the code that I have wrote.
Any help would be really appreciated. Thank you!

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
            Toggle navigation

        </button>

Projects

Freelancer

Inbox

My Account

Answer: Never mind guys I just found out why. I needed to wrap the following div element around the UL

The code looks like this ..

Projects

Freelancer

Inbox

My Account


getting error while showing a user online or offline

Question: While setting a user online or offline status with the Views module, I get this error message:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')) < 30, 1, 0) AS users_node_is_online, 1 AS expression FROM node node LEFT JOI' at line 1

How do I fix it?
Comment: It's not clear to me when you get that error. The Views module should not allow you to set the status of a user's account. May you explain with more details what you were doing?
Comment: well, i just wanna show users online status. Is a website is online or offline. To do so i add this status field in views and then this error appear. What to do to fix it?
Answer: I believe the field meh is referring to is provided by the user_stats module. Indeed, once installed it is possible to add that field in a views. There is also a patch for this error on the user_stats issue queue.
Comment: Thanks for your response :) but i am not using Drupal anymore :)


get value of a specific column in Telerik Multi column combobox

Question: <telerik:RadComboBox ID="drpEmployeeItemID" runat="server" DropDownWidth="825px" EnableLoadOnDemand="true" Height="190px">
                    <HeaderTemplate>

ItemName

ColorName

StyleName

BrandName

ModelName

LotNo

BatchNo

CountryName

                    </HeaderTemplate>
                    <ItemTemplate>

                                <%# DataBinder.Eval(Container.DataItem, "ItemName")%>

                                <%# DataBinder.Eval(Container.DataItem, "ColorName")%>

                                <%# DataBinder.Eval(Container.DataItem, "StyleName")%>

                                <%# DataBinder.Eval(Container.DataItem, "BrandName")%>

                                <%# DataBinder.Eval(Container.DataItem, "ModelName")%>

                                <%# DataBinder.Eval(Container.DataItem, "LotNo")%>

                                <%# DataBinder.Eval(Container.DataItem, "BatchNo")%>

                                <%# DataBinder.Eval(Container.DataItem, "CountryName")%>

                    </ItemTemplate>
                </telerik:RadComboBox>

I have to get the LotNo of the selected Item. I have tried GetSelectedItem / getselected value. but no selection of the specific column.
Answer: Set OnDataBound event
telerik:RadComboBox ID="drpEmployeeItemID" OnDataBound="drpEmployeeItemID_DataBound"

Define handler
protected void drpEmployeeItemID_DataBound(object sender, RadComboBoxItemEventArgs e)
{
   e.Item.Text = ((DataRowView)e.Item.DataItem)["ItemName"].ToString() ;
   e.Item.Value = ((DataRowView)e.Item.DataItem)["LotNo"].ToString();

   // set attributes
   e.Item.Attributes["ColorName"] = dataItem["ColorName"];
   e.Item.Attributes["StyleName"] = dataItem["StyleName"];
   ...
}

Use the text and value in the butto
var itemName = drpEmployeeItemID.Text;
var value = drpEmployeeItemID.SelectedValue;

// get item
var item = drpEmployeeItemID.FindItemByValue(value);
var colorName = item.Attributes["ColorName"];

Edited
There is now way to get original DataItem after data bound. If you want to add more properties to an item, you can use Attributes collection to store them.
Another way is to save your original datasource in the session and find data item by selected value.
Comment: 1) I have to select the value while i click the save button. 2) I need to have all the column value of the radcombobox. Atleast id as value, name as text, and lotid as ............


Learn guitarpro

Question: Can anyone suggest a good source from where I can learn guitarpro software? Books, youtube videos, etc. I have looked through youtube and google but there are a lot of bits and pieces but nothing well put together.
Thanks in advance and Cheers!!
Comment: Why does no-one think to start with the [product manual](https://support.guitar-pro.com/hc/en-us/articles/115002399509-GP7-5-Guitar-Pro-7-5-User-s-guide-) any more?
Comment: @Tetsujin - if all else fails - read the instructions...
Answer: Here's how you do it… this applies to any new software
You get the product manual - which is an authoritative information source, unlike YouTube, which is just some random guesser who's already tried to make sense of it, thinks he's an expert & is passing on second hand information with pretty pictures, because he's heard that this is the modern way to gain fame & make money. This is not the way to learn anything.
Once you have the manual, you read it, cover to cover.
Most of it won't make any sense at all as it's far too complicated & you haven't even used the software yet.
Then you start to use the software.
If you struggle you try to find reference in the manual - which you may or may not find yet because of lack of familiarity with the whole setup.
Then, after two weeks of this… you read the manual again.
This time you'll already have a grounding in what the software does, so you will reinforce existing knowledge & pick up new useful information.
You then go back to using the software again.
Guess what?
After another month or two of this… you read the manual again.
This is how you gain a deep understanding of complex software.
Answer: Here you go! GP7 Manual and Enjoy
Comment: The manual is already great. The UI is easy if you even know basics of guitar tablatures. I recommend try experimenting with what you make and suppose you have problem simply search online and don't waste time in understanding every features after all it isn't any software for bombing planet Earth.XD
Comment: Is there any other source apart from user manual?

Learn guitarpro


Call this (public) function inside private function

Question: I have the following javascript: (JSFiddle)
$(function () {
    function Cat()
    {
        this.Meow = function (sound) {
            alert("Meow: " + sound);
        }

        this.Kick = function () {
            MakeNoise();
        }

        var MakeNoise = function () {
            Meow("noise");
            //Cat.Meow("noise");
            //self.Meow("noise");
            //this.Meow("noise");
        }
    }

    var c = new Cat();
    c.Kick();
});

When I call the Kick function, I get the error "Meow is not defined" (with any of the four things I tried in the MakeNoise function).
I also tried prototyping like so but that gave me the same error:
Cat.prototype.Meow = function (sound) {
    return this.Meow(sound);
}

I've sure this has a terribly straightforward solution, but I can't figure out how to successfully call the Meow function of the "Cat" class. How can I do this?
As an aside, does this architecture make any sense at all? My intention was to have Kick and Meow as public functions, and MakeNoise as private.
Comment: Musa's answer below will do the trick, but I'd encourage you to take a look at the following article for more explanation about 'this' and scoping. https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this
Comment: @gerges Thanks for the link. I assumed (incorrectly it seems) that this would refer to the current object.
Answer: Save a reference object so you can use it in the MakeNoise function.
$(function () {
    function Cat()
    {
        var self = this;
        this.Meow = function (sound) {
            alert("Meow: " + sound);
        }

        this.Kick = function () {
            MakeNoise();
        }

        var MakeNoise = function () {
            //Meow("noise");
            //Cat.Meow("noise");
            self.Meow("noise");
            //this.Meow("noise");
        }
    }

    var c = new Cat();
    c.Kick();
});

http://jsfiddle.net/mowglisanu/7XEYD/3/


Searching through nested data

Question: I cant figure out what is wrong with this search function/s? I want to be able to search for the word bird or snake. Also it would be nice to ignor any object that dont have that text in them. I am confused as this person never uses her "animals" object array and I never see getEachItem actually called?
example tutorial
const SlideData = [
  {
    id: 1,
    title: "Slide 0",
    layout: "standard",
    content: [
      {
        id: 1,
        type: "paragraph",
        text: "this has the word cat."
      },
      {
        id: 2,
        type: "space",
        height: "1em"
      },
      {
        id: 3,
        type: "paragraph",
        text: "this has the word snake."
      }
    ],
  },
  {
    id: 2,
    title: "Slide 1",
    layout: "standard",
    content: [
      {
        id: 1,
        type: "paragraph",
        text: "This has the word bird."
      },
      {
        id: 2,
        type: "space",
        height: "1em"
      },
      {
        id: 3,
        type: "paragraph",
        text: "This has the word bear."
      }
    ],
  }
];
export default SlideData;

import SlideData from "./SlideData";

const SearchResults = () => {
  const searchTerm = "bird";
  let result = [];

  function getEachItem(object) {
    object.forEach((item) => {
      searchItem(item);
    });
    let uniqueResults = [...new Set(result)];
    return uniqueResults.length;
  }
  function searchItem(item) {
    SlideData.forEach((key) => {
      if (typeof item[key] === "object") {
        searchItem(item[key]);
      }
      if (typeof item[key] === "string") {
        let searchAsRegEx = new RegExp(searchTerm, "gi");
        if (item[key].match(searchAsRegEx)) {
          result.push(item.id);
        }
      }
    });
  }

  return (

Results

{result}

      <button type="submit" onClick={searchItem}>
        Search
      </button>

  );
};
export default SearchResults;

Answer: It looks like you're doing a recursive call to searchItem, but you never specify a return condition to pop the call stack and return the flow of control back to the original caller
function searchItem(item) {
    SlideData.forEach((key) => {
      if (typeof item[key] === "object") {
        /** return result of recursive call **/
        return searchItem(item[key]);
      }
      if (typeof item[key] === "string") {
        let searchAsRegEx = new RegExp(searchTerm, "gi");
        if (item[key].match(searchAsRegEx)) {
          result.push(item.id);
        }
      }
      /** return and pop call stack
       * since you pushed an item to the result array
       **/
      return;
    });
  }

It would be better to have the searchItem function do all of the iterating and return an array result instead of recursively trying to push items onto a global array. You're mixing scopes with the way you're doing it now
Answer: Tutorials are often low effort affairs. The author of this one seems to be sharing a partial implementation of something they wrote for a different project, and is posting it to try to get feedback. They aren't writing an app with a complete search implementation.
In your case, to make the search work for terms other than "bird", you'll have to make searchTerm an argument that is passed into the function. You'll also have to set up the form and display areas to put the results in.
To reiterate, the tutorial is only giving you part of a complete app. You'll have to set up the rest yourself.

Searching through nested data


Dunn.test in R: are adjusted p-values corrected for number of comparisons?

Question: I've performed a post-hoc Dunn's test with Sidak adjustment using the dunn.test code for R.  There are three groups in my comparison and I understand from the R help files that the lower number in the output is the adjusted p-value which I use to compare to alpha (0.05).
My question is: do I divide alpha by three (since I've three comparisons), or does the adjusted p-value generated by R factor in that I have three comparisons and I simply compare the value with alpha?
Thanks for any help (including pointing me to another discussion).  Have googled in vain.

EDIT: I first performed a Kruskal-Wallis test and a signficanct difference in the groupings was identified.  Also I am very new to R and have read to the best of my ability before posting (am not a statistician).  I do understand from the dunn.test manual that the output from holm adjustment and others mark rejection with a asterisk.  It is interpretation of the Sidak output I'm confused about
Answer: Author of dunn.test here. As per the help file for dunn.test under the sidak option for the method argument:

the FWER is controlled using Šidák's (1967) adjustment, and adjusted p-values = max(1, 1 - (1 - p)^m).

So, Yes. dunn.test corrects p-values for multiple comparisons given the argument to method. For the Šidák option, you would reject each null hypothesis if $p\le \alpha/2$ (i.e. dunn.test report one-sided p-values).
Also from the help file:

method adjusts the p-value for multiple comparisons using the Bonferroni, Šidák, Holm, Holm-Šidák, Hochberg, Benjamini-Hochberg, or Benjamini-Yekutieli adjustment (see Details). The default is no adjustment for multiple comparisons.

For the stepwise multiple comparisons adjustment methods, because rejection depends both on adjusted p-values (sometimes called q-values) and the ordering of unadjusted p-values, rejection decisions for a specified level of $\alpha$ are starred in the output.
The advantage of not starring output for the static results is that adjusted p-values can be interpreted by the reader according to their own preference for $\alpha$.
Comment: thank you sincerley for your answer.  As I non-stats person I had tried to understand the method argument but was unable to interpret.  Your expertise is much appreciated.


Testing mean difference between multiple (small) samples and their populations

Question: Consider, for example, that I demand that every farmer gives me 10 of their best apples from each of the tens of apple orchards that I own. I detest worms in my apples, but know that some will worm their way into some of them in any case.
The farmers know exactly how many of their apples contained worms and they give me a proportion relating the number of spoilt fruit to the number of all apples produced in their orchard. The orchards are of different sizes and are known.
Despite warnings, I find some worms in my treats. How can I know whether the farmers tried to cheat me or this was a sincere mistake on their part?
In other words, how can I know the proportions of worm-eaten apples in my small samples are indeed smaller than the general proportions in their orchards? Note, that I would like a general assessment of fairness of my farmers. That is, I am not looking to single out a farmer and its fruit garden, but instead have a general sense of whether (most of) the farmers are trying to cheat me or not.
My thoughts and questions:

Is a paired t-test (or a non-parametric alternative) an appropriate analysis here given that one of the samples is actually the whole population (all of the apples produced in an orchard)?
What can the correlation between the proportion of wormy fruit in my sample and the proportion in the corresponding orchard tell me? Should I expect this correlation to be zero if the farmers are fair?
Are the sizes of orchards of importance here? Given that my sample is always of fixed size, should I take the sizes of the populations into account somehow?
Should I drop the idea of proportions altogether and do something with raw number of apples?

I was trying to find related questions and this one tried to compare proportions. My example is different (or doesn't it matter?), however, because I have population estimate on one hand.
Comment: You are at risk of getting answers that may be invalid for your actual problem because they rely (perhaps only implicitly) on assumptions true for the made-up problem but not true for the real problem.  It's almost always better to describe the problem you face rather than attempting to present it abstractly.  Another risk is that as answers emerge you may discover some of these inadequacies of the abstraction, compelling you to change the details of the question, which leaves the entire thread in a terrible mess.
Comment: If I had a nickel for every question on Cross Validated that was phrased as a hypothetical or metaphorical scenario that turned out to be a poor representation of the real problem, I'd be a wealthy man. Why people are so reluctant to describe their real problem, I'll never know. Are they afraid we'll steal their ideas? Or are they so embarrassed about asking a question here that they don't want their real-life colleagues to recognize the scenario?
Comment: @whuber and Kodiologist, you both raised good points. I realize now that this question is more difficult to answer, given that it is a hypothetical.

The reason I chose to rephrase the question as a simpler one is that the original problem is well out of my field of expertise. So, by trying to simplify it, I was trying both to communicate it better and grasp the core of it myself.
I am aware that this might make the answers less relevant. Thank you for trying to help me despite this!
Comment: It does not seem possible to answer your questions with such data: the apples offered you are not random samples; there may be differences among the farms; and you have no controls to compare what you receive to what is typical of those farms.  Suppose some test were to declare there is a "significant" difference in the data: what then?  It would not be valid to draw any conclusions about cheating, fairness, or even apple quality generally.
Comment: 1) You could simply compare the ratio of normal to worm-infested apples with a $\chi^2$-test for given probabilities, where the given probabilities are the numbers the farmers claim. 2) The proportions are single numbers, what do you mean by correlation between them?
Comment: @whuber I might have got carried away with my made-up story. Say that the farmers have poor/no control over what apples they give away, so that the samples are random. I simply wanted to stress that I don't want to simply test whether a sample comes from a population, but that I want to check this for multiple samples and, possibly, have a single measure to decide.
Comment: @FransRodenburg thanks. I think this is also what Sid proposed. Re correlation: I meant the correlation over all of the samples/orchards.
Answer: You have a contingency table comprising 10 rows (1 for each orchard), and 2 columns (contains worms and not contains worms). You know the null probabilities for bad apple in each of the 10 farms, and you are trying to find if the deviation is very large. The answer will be a chi-square test which tests for large deviations.
Comment: Thank you, Sid, for this answer. Would you mind elaborating on why this would be preferable to doing a paired *t*-test as I suggested? Also, am I right in thinking that a larger table (i.e. a larger number of orchards) would result in a chi-square test with more power?
Comment: Hi Fato39, please see https://biology.stackexchange.com/questions/13486/deciding-between-chi-square-and-t-test
Comment: Sid, thank you for providing the link to a helpful answer! I accepted your answer as I tend to think it's correct, but if you cared to elaborate on any other subquestions I posed, please edit it.


WooCommerce AJAX update and delete buttons (outside of cart page)

Question: I have a cart list in my header, so it's outside of the actual cart page. In it, I have buttons to update and delete each cart item. It works fine, but my issue is that I'm trying to use AJAX to get rid of the page refresh.
So far I have the following

$('.cart-list form').on('submit', function() {

    var $theForm = $(this);

    // send xhr request
    $.post({
      type: $theForm.attr('method'),
      url: $theForm.attr('action'),
      data: $theForm.serialize(),
      success: function(data) {
        // This works
        console.log("success!")
        });
      }
    });

    // prevent submitting again
    return false;

  });

I got that snippet from another stack overflow post. That user was doing a similar thing, but for adding a new product. To get it to work, he needed to add a hidden input inside of his form.

<input type="hidden" name="add-to-cart" value="<?php echo absint( $id ); ?>" />

Of course, that won't work for me, since I'm not just adding to cart. I'm updating the quantity or deleting the product altogether.
Are there any other hidden inputs I should try adding to my form to get this to work, or anything else I can try?
Answer: I figured it out! Place this input by the update button
<input type="hidden" name="update_cart" value="<?php echo $product_id; ?>">

To do delete, use the following

$('YOURDELETEBUTTON').on('click', function() {

    var href = $(this).prop('href');

    // send xhr request
    $.post({
      type: 'post',
      url: href,
      success: function(data) {
        // Maybe add a document trigger here
      }
    });

    return false;
  });


How to display MDN reference in JavaScript file

Question: I have a strange problem in my vocode

My editor has disabled the refences and the definition that is shown from MDN not in HTML nor CSS  but it is only in my JavaScript file

I have made many things like :
write two following lines in settings.JSON and no thing happens
"editor.hover.enabled": true,
"editor.hover.delay": 300,
I has installed intellisense and the same result no thing changed

I need to show it when hovering
Comment: Only MDN links or all site links are disabled?
And could u paste related codes.
Comment: No, it disabled in all javaScript files
Answer: See this ref.
There is no official support for  MDN reference for javascript until now.
This extension may help to some extent.
Comment: But sometimes I see a box that show when hover on function object , var and for and it displays definition for how to use the code


Why are consecutive P4s okay to use while P1s, P5s, P8s are not?

Question: Consecutive P1s, P5s, and P8s are not okay to be used while P4s are allowed.  What's the reason?
Comment: Wait, consecutive P1's (perfect unisons) weren't allowed? I never heard that from my theory classes.
Answer: There are no such rules unless you are choosing to write within a particular style.
For example parallel fifths and parallel octaves are frowned upon if you are writing in an 18th century style (imitating Bach for example) but that is a very specific instance.
If you are composing something of your own you are free to do whatever you want.  If it sounds how you want it to then that's ok.
Answer: It's important to know the reasons behind the recommendation to avoid consecutive unisons, fifths, and octaves. If one wishes to have two (or more) independent voices, such repetition weakens the independence. If one is just doubling a single voice, there is no problem. Consecutive fourths generally do not weaken the feeling of independence between voices; such fourths generally appear in successions of first inversion chords (6-3 chords). Some older theorists also suggest no more than 3 or 4 (or some other number) of consecutive thirds or sixths should be avoided so as to keep the music sounding like several simultaneous melodies rather than just a succession of chords.
In most popular (country, rock, jazz, light classical, etc.) the only parts that usually need to be independent are the bass and the melody.


Aren't constructive math proofs more "sound"?

Question: Since constructive mathematics allows us to avoid things like Russell's Paradox, then why don't they replace traditional proofs?  How do we know the "regular" kind of mathematics are free of paradox without a proof construction?
Comment: @Noah: There is, at least historically - Weyl (1921) "On the New foundational Crisis of Mathematics" talks of paradoxes threateneing the chorence of mathematics as an enterprise, and recommending intuitionistic or predicative mathematics as the solution.
Comment: I'm voting down as I don't think this question makes sense.  As far as I know there's no relationship between Russell's paradox and constructive mathematics, so I don't understand what the question is asking.
Comment: @Noah, they are related in a strong sense. I suggest you read about the history of constructivism. Intuitionists were trying to find a safer foundations that would avoid paradoxes arising in classical mathematics and set theory like Russell's paradox.
Comment: In fact the Russell paradox is perfectly constructive. It shows that naïve set theory is inconsistent, and does so in an entirely constructive way. No excluded middle is used, because even intuitionistically an equivalence $P\iff\lnot P$ is a contradiction (where $P$ is $R\in R$ for the set $R=\{x\mid x\notin x\}$): one has $(P\to\lnot P)\implies\lnot P$ and  $(\lnot P\to P)\implies\lnot\lnot P$, and of course $\lnot P\land\lnot\lnot P\implies\bot$). The problem is with the axioms of naïve set theory, not with the logic used.
Comment: Does this answer your question? [Why are direct proofs often considered better than indirect proofs?](https://math.stackexchange.com/questions/3341323/why-are-direct-proofs-often-considered-better-than-indirect-proofs)
Answer: Proof theorists have obtained several "relative consistency" proofs between classical and constructive theories. These show that if certain theories of classical mathematics are inconsistent, then corresponding theories of constructive mathematics are also inconsistent. These relative consistency results are proved constructively. They show that the consistency problem does not simply disappear if we switch to constructive mathematics.
One of the more famous relative consistency techniques uses a "double negation translation". This method assigns each formula $\phi$ of a system a corresponding formula $\phi^N$ (the "translation" of $\phi$). The exact definition of the translation varies from author to author, depending on the system at hand. But the name is somewhat accurate: the definition of $\phi^N$ involves adding additional negation symbols to $\phi$ in the right places.
In 1933, Gödel proved there is a translation $N$ of formulas of Peano arithmetic so that whenever a formula $\phi$ is provable in Peano arithmetic, the corresponding formula $\phi^N$ is provable in the constructive system of Heyting arithmetic. Moreover, if $\phi$ is of the form $A \land \lnot A$ then Gödel's translation assigns it the formula $\phi^N = A^N \land \lnot A^N$, which is still contradictory. This means that if Peano arithmetic is inconsistent, so is its constructive counterpart Heyting arithmetic. Gödel's proof is constructive, like you would hope.
So if we were only worried about consistency, there would be no advantage to working in Heyting arithmetic instead of Peano arithmetic. But people who work in constructive mathematics do not do it only for the sake of consistency. Constructive proofs carry more information than classical proofs, so constructive provability is interesting even to classical mathematicians.
You can read a little more about Gödel's result at this wikipedia article.
Answer: A whole bunch of things in mathematics are inherently nonconstructive. For instance, invariant theory--recall the famous quote by Gordan that Hilbert's mathematics was "theology." (A quote which, I believe, was in jest.)
The Hahn-Banach theorem, a fundamental tool in functional analysis (and a great tool for proving all sorts of results, like approximation results--Runge's theorem, the Stone-Weierstrass theorem, and more) relies on the axiom of choice, and is consequently nonconstructive.  The fact that any proper ideal in a ring is contained in a maximal ideal is frequently used in algebra, and yet it needs the axiom of choice.  The use of ultraproducts in logic (or the construction of hyperreal numbers) is inherently nonconstructive: you can't just exhibit a nonprincipal ultrafilter on the natural numbers.
Basically, a lot of mathematics just doesn't work without Zorn's lemma, and this is equivalent to the axiom of choice.
Comment: While Hilbert's arguments regarding invariant theory were non-constructive, there are nowadays constructive proofs, I think.
Comment: Another perhaps less famous equivalence of AC is Tychonoff's_theorem (see http://en.wikipedia.org/wiki/Tychonoff's_theorem - also I recommend Kelly's paper to any interested student reading topology).
Answer: "Taking the principle of excluded middle from the mathematician would be the same, say, as proscribing the telescope to the astronomer or to the boxer the use of his fists. To prohibit existence statements and the principle of excluded middle is tantamount to relinquishing the science of mathematics altogether."
-David Hilbert
Answer: The distinction between constructive mathematics and traditional mathematics has nothing to do with Russell's Paradox.
Constructive mathematics simply requires working with one less basic postulate that many mathematicians have believed to be sensible and on which some proofs are based, namely the Axiom of Choice
Comment: Although you're right that constructive mathematics has nothing to do with Russell's paradox, my understanding is that the key point that constructivists deny is the law of the excluded middle (not the Axiom of Choice, though most constructivists don't use that either).
Comment: @Noah: I've browsed the ultimate authority on everything (wikipedia) and it seems you're right on this.  Grad school was a long time ago!  I just remember one faculty member walking out on my thesis defense when I admitted to using the axiom of choice.
Comment: @Noah: There isn't really such a thing as "the" axiom of choice constructively.  Higher-order intuitionistic logic has the existence of Skolem functions for all Pi-0-2 sentences, which over ZF is equivalent to the axiom of choice, and this choice principle is generally known as the axiom of choice in intuitionistic type theory, and is much used.
Comment: if we deal only with finite sets, there is no real difference between constructive and non-constructive proofs.
Answer: when dealing with infinite sets, many propositions cannot be proved mithout using non-constructive proofs. Axiom of Choice (AC, in brief) or an equivalent proposition is required. Russell's paradox is not a problem per se, you just rule out certain collections of things as sets; Banach-Tarski paradox (you may take a ball, "divide" it in a finite number of parts, translate and rotate them and obtain two balls equal to the first) may be worse indeed. But few mathematicians would prefer not to do a lot of maths because AC is not allowed!
Answer: Here is one elementary result you can't prove without the Axiom of Choice (that I used to think was not part of constructive mathematics): let $\left\{X_i\right\}_{i\in I}$ be an arbitrary family of non-empty sets. Then its product $\prod_{i\in I} X_i$ is a non-empty set.
Everybody knows how to prove that for a family of two sets. If two sets $X$ and $Y$ are non-empty, then their cartesian product $X \times Y$ is non-empty too: since $X$ is non-empty, you can choose one element from it: $x \in X$. For the same reason, you can choose also one $y \in Y$. So you have an element $(x,y) \in X\times Y$ and therefore it is non-empty. Right?
For a finite family of non-empty sets $X_1, \dots , X_n$ this procedure still works: you choose one element in each set starting from the first: $x_1 \in X_1$. And then keep on doing the same for the rest: choose $x_2$ in the second set $X_2$, $x_3$ in the third one $X_3$,... And so on, till you reach $x_n \in X_n$. You have thus produced an element of the cartesian product: $(x_1, \dots , x_n) \in X_1 \times \dots \times X_n$.
Even if you had an infinite countable family of non-empty sets $X_1, X_2, \dots , X_n, \dots$, you could produce an element of their product $\prod_{n=1}^{\infty} X_n$ this way: choose successively elements $x_1 \in X_1$, $x_2 \in X_2$,..., $x_n \in X_n$... And you would obtain your element $(x_n)$ of your infinite cartesian product. Hence $\prod_{n=1}^{\infty} X_n$ is non-empty too if all the $X_n$, $n=1, 2, \dots $ are non-empty.
Now, try to do the same with an arbitrary family of sets $X_i$, with the indexes $i$ belonging to an arbitrary indexing set $I$. That is, set $I$ can be infinite and not  countable. This kind of cartesian products do exist in "nature". For instance: $I$ could be the set of real numbers $\mathbb{R}$. Take $X_i = \mathbb{R}$ for all $i \in \mathbb{R}$ too. This cartesian product $\prod_{i\in \mathbb{R}} X_i = \mathbb{R}^\mathbb{R}$ is the same as the set of all (not necessarily continuous) functions from $\mathbb{R}$ to $\mathbb{R}$.
Of course, you can prove that $\mathbb{R}^\mathbb{R}$ is non-empty by showing an element of it (for instance, $f(x) = x$ for all $x\in \mathbb{R}$), but how can you prove, in general, that the product of an arbitrary family of non-empty sets $\prod_{i\in I}X_i$ is non-empty too?
If you try to imitate what you have just done in the finite or countable cases, you'll find asking yourself: where do I start? Which is the first  $\ i \in I$? Assuming there is a first $i$, which is the next one?
The answer is that, for an infinite, non-countable, set of indexes $I$ there is in general no such a thing as a first index $i$, nor a next one. So you can't use the previous algorithm in order to produce an element of the product $\prod_{i\in I} X_i$...
Except you have something that allows you to choose, one particular element of each set $x_i \in X_i$ -no matter how, even with no precise constructive algorithm as in the finite or countable cases.
If you were able to do that for no matter which set of indexes $I$, then you would have your element $(x_i)_{i\in I}$ and you would have proved that, if every $X_i \neq \emptyset$, so is their cartesian product $\prod_{i\in I} X_i$.
What do allow you for an infinite, non-countable, set of indexes $I$ to choose those $x_i \in X_i$ for every $i\in I$? Well, this is exactly what the Axiom of Choice says.
Comment: People often say that the axiom of choice is "nonconstructive", but many systems of constructive math include the axiom of choice. One example is Martin-Lof type theory, which has very strong intuitionist bona fides. Errett Bishop famously wrote that the axiom of choice "is unique in its ability to trouble the conscience of the classical mathematician, but in fact it is not a real source of nonconstructivity in classical mathematics. A choice function exists in constructive mathematics, because a choice is implied by the very meaning of existence." The classical "or" is much more problematic.
Comment: @DavidW: Thanks. As for your question: I'm afraid not. Think about the case of the product of two sets X x Y. There is no map X ---> X x Y. For products you only have maps in the opposite direction X x Y ---> X. In fact, if you look at the proof of an arbitrary product being non-empty it is just the Axiom of Choice. I mean: the fact that an arbitrary product is non-empty, if all its components are non-empty, is equivalent to the Axiom of Choice since elements of the product are, by definition, choice functions!   :-)
Comment: @Carl. Ok. I've changed the first sentence.
Comment: A very interesting and detailed exposition for how a "constructive" proof seems to require AOC. But surely you don't need AOC simply to prove that an uncountable product of nonempty sets is non-empty. Once you prove it for finite or countably infinite products, an injective mapping of any of those into the uncountable product should suffice, no?
Comment: @DavidW: Partial correction to my previous statement. When I said "there is no map X ---> X x Y", I actually meant "no *canonical* map". Of course there are plenty of them: *choose* one element of Y, y_0, and you have one:  x \mapsto (x, y_0). But focus on what I needed to do: I had to *choose* an element of Y ! In the uncontable case you would need to do this... an infinite (uncontable) number of times. So you are using what?   :-)
Comment: Constructively, there is a distinction between an inhabited set $A$ (that is, $\exists x.x \in A$) and a non-empty set A (that is, $\neg \forall x. x \notin A$).
Proving that $A \times B$ is inhabited if both $A$ and $B$ are seems easy. You can just take the witnesses $a \in A$ and $b \in B$ and construct $(a,b) \in A \times B$. Does this require AC?
Comment: @fishlips. The problem is not with finite, or countable products: these do not require AC.
Comment: I believe countable products still require AC. See http://en.wikipedia.org/wiki/Axiom_of_countable_choice
Comment: @BenBlum-Smith. I must agree with you: I made that common misconception, I'm afraid.


Update com variavel PHP

Question: Estou tomando uma surra com um update com variavel. Por favor alguem pode me ajudar?
<code>$servidorBanco = "localhost";
$usuarioBanco = "root";
$senhaBanco = "";
$dadosBanco = "db";

$conexao = new mysqli($servidorBanco, $usuarioBanco, $senhaBanco, $dadosBanco);

date_default_timezone_set('America/Sao_Paulo');
$hora = date('H:i:s');

$idHost = 1;

$consulta2 = $conexao->escape_string("UPDATE host SET uptimeHost='".$hora."', avisoHost=0 WHERE idHost='".$idHost);
$resultado4 = $conexao->query($consulta2);
</code>
Não esta atualizando no banco de dados MySQL.
Comment: Faz o que o `iPramesPortas` sugeriu, mas antes verifique se a sua consulta SQL está correta. Faz um `echo` na SQL e teste-a no seu banco.
Comment: Ja resolvi o problema, obrigado.
Answer: <code>$hora = date('H:i:s'); $idHost = 1;

$conexao = mysqli_connect("localhost","root","","banco");

$sql = "update host set uptimeHost='$hora',avisoHost='0' where idHost='$idHost'";

$query = mysqli_query($conexao, $sql);
</code>
Comment: esse conexão já tem. Vou atualizar a pergunta.
Answer: Esqueceu de fechas as aspas
seu código:
<code>$consulta2 = $conexao->escape_string("UPDATE host SET uptimeHost='".$hora."', avisoHost=0 WHERE idHost='".$idHost);
</code>
como deveria ser:
<code>$consulta2 = $conexao->escape_string("UPDATE host SET uptimeHost='$hora',avisoHost='0' WHERE idHost='$idHost');
</code>
Comment: da erro de pagina
Answer: Pronto resolvi a resolução é essa
<code>$servidorBanco = "localhost";
$usuarioBanco = "root";
$senhaBanco = "";
$dadosBanco = "db";

$conexao = new mysqli($servidorBanco, $usuarioBanco, $senhaBanco, $dadosBanco);

date_default_timezone_set('America/Sao_Paulo');
$hora = date('H:i:s');

$idHost = 1;

$sql = "UPDATE host SET uptimeHost='$hora', avisoHost=0 WHERE idHost='$idHost'";
if($conexao->query($sql) === true){
    echo "Atualizado com sucesso";
}else{
    echo "Não atualizado";
}
</code>
Obrigado a todos.

Update com variavel PHP